From 07c325430e9eafe35e09cd7d6261f26250d47f09 Mon Sep 17 00:00:00 2001 From: Matthias Glauch Date: Thu, 27 May 2021 23:08:03 +0200 Subject: [PATCH 01/79] fixed SemVer regex (major number was optional) and added test for the issue caused by the wrong regex --- .../VersionCalculation/SemanticVersionTests.cs | 5 +++-- .../VersionCalculation/SemanticVersioning/SemanticVersion.cs | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/GitVersion.Core.Tests/VersionCalculation/SemanticVersionTests.cs b/src/GitVersion.Core.Tests/VersionCalculation/SemanticVersionTests.cs index 1637227ffd..ef8a8f79c8 100644 --- a/src/GitVersion.Core.Tests/VersionCalculation/SemanticVersionTests.cs +++ b/src/GitVersion.Core.Tests/VersionCalculation/SemanticVersionTests.cs @@ -57,9 +57,10 @@ public void ValidateVersionParsing( [TestCase("someText")] [TestCase("some-T-ext")] - public void ValidateInvalidVersionParsing(string versionString) + [TestCase("v.1.2.3", "v")] + public void ValidateInvalidVersionParsing(string versionString, string tagPrefixRegex = null) { - Assert.IsFalse(SemanticVersion.TryParse(versionString, null, out _), "TryParse Result"); + Assert.IsFalse(SemanticVersion.TryParse(versionString, tagPrefixRegex, out _), "TryParse Result"); } [Test] diff --git a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs index 3975a634f8..6b96d966d9 100644 --- a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs +++ b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs @@ -8,7 +8,7 @@ public class SemanticVersion : IFormattable, IComparable private static SemanticVersion Empty = new SemanticVersion(); private static readonly Regex ParseSemVer = new Regex( - @"^(?(?\d+)?(\.(?\d+))?(\.(?\d+))?)(\.(?\d+))?(-(?[^\+]*))?(\+(?.*))?$", + @"^(?(?\d+)(\.(?\d+))?(\.(?\d+))?)(\.(?\d+))?(-(?[^\+]*))?(\+(?.*))?$", RegexOptions.Compiled); public int Major; From 52e6f0b753cb05d23cbdc0f8a547710e4dc9be73 Mon Sep 17 00:00:00 2001 From: James May Date: Fri, 4 Jun 2021 14:31:39 +1000 Subject: [PATCH 02/79] msbuild.md: update for rename to GitVersion.MsBuild from GitVersionTask --- docs/input/docs/usage/msbuild.md | 32 ++++++++++++++++++-------------- 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/docs/input/docs/usage/msbuild.md b/docs/input/docs/usage/msbuild.md index 7055d6f482..21d80d8715 100644 --- a/docs/input/docs/usage/msbuild.md +++ b/docs/input/docs/usage/msbuild.md @@ -7,7 +7,7 @@ Description: | CardIcon: collect.svg --- -The MSBuild Task for GitVersion — **GitVersionTask** — is a simple solution if +The MSBuild Task for GitVersion — **GitVersion.MsBuild** — is a simple solution if you want to version your assemblies without writing any command line scripts or modifying your build process. @@ -17,17 +17,21 @@ version information that is compiled into the resulting artifact. It currently works with desktop `MSBuild`. Support for CoreCLR with `dotnet build` is coming soon. +> **Note** + The nuget package was "*[GitVersionTask](https://www.nuget.org/packages/GitVersionTask/)*" up until version 5.5.1. + From version 5.6.0 it has been called "*[GitVersion.MsBuild](https://www.nuget.org/packages/GitVersionTask/)*" + ## TL;DR ### Install the MSTask targets -Add the [GitVersionTask](https://www.nuget.org/packages/GitVersionTask/) NuGet +Add the [GitVersion.MsBuild](https://www.nuget.org/packages/GitVersionTask/) NuGet Package into the project you want to be versioned by GitVersion. From the Package Manager Console: ```shell -Install-Package GitVersionTask +Install-Package GitVersion.MsBuild ``` If you're using `PackageReference` style NuGet dependencies (VS 2017+), add @@ -35,7 +39,7 @@ If you're using `PackageReference` style NuGet dependencies (VS 2017+), add dependency of your package: ``` xml - + All ``` @@ -43,12 +47,12 @@ dependency of your package: ### Remove AssemblyInfo attributes The next thing you need to do is to remove the `Assembly*Version` attributes from -your `Properties\AssemblyInfo.cs` files. This puts GitVersionTask in charge of +your `Properties\AssemblyInfo.cs` files. This puts GitVersion.MsBuild in charge of versioning your assemblies. ### Done! -The setup process is now complete and GitVersionTask should be working its magic, +The setup process is now complete and GitVersion.MsBuild should be working its magic, versioning your assemblies like a champ. However, more can be done to further customize the build process. Keep reading to find out how the version variables are set and how you can use them in MSBuild tasks. @@ -61,10 +65,10 @@ described below. ### Inject version metadata into the assembly -The sub-task named `GitVersionTask.UpdateAssemblyInfo` will inject version -metadata into the assembly where GitVersionTask has been added to. For each assembly +The sub-task named `GitVersion.MsBuild.UpdateAssemblyInfo` will inject version +metadata into the assembly where GitVersion.MsBuild has been added to. For each assembly you want GitVersion to handle versioning, you will need to install -[GitVersionTask](https://www.nuget.org/packages/GitVersionTask/) into the corresponding +[GitVersion.MsBuild](https://www.nuget.org/packages/GitVersion.MsBuild/) into the corresponding project via NuGet. #### AssemblyInfo Attributes @@ -152,11 +156,11 @@ else ### Populate some MSBuild properties with version metadata -The sub-task `GitVersionTask.GetVersion` will write all the derived +The sub-task `GitVersion.MsBuild.GetVersion` will write all the derived [variables](/docs/reference/variables) to MSBuild properties so the information can be used by other tooling in the build pipeline. -The class for `GitVersionTask.GetVersion` has a property for each variable. +The class for `GitVersion.MsBuild.GetVersion` has a property for each variable. However at MSBuild time these properties are mapped to MSBuild properties that are prefixed with `GitVersion_`. This prevents conflicts with other properties in the pipeline. @@ -182,7 +186,7 @@ package versions but older NuGet clients and nuget.org do not. #### Accessing variables in MSBuild -Once `GitVersionTask.GetVersion` has been executed, the MSBuild properties can be +Once `GitVersion.MsBuild.GetVersion` has been executed, the MSBuild properties can be used in the standard way. For example: ```xml @@ -191,7 +195,7 @@ used in the standard way. For example: ### Communicate variables to current Build Server -The sub-task `GitVersionTask.WriteVersionInfoToBuildLog` will attempt to write +The sub-task `GitVersion.MsBuild.WriteVersionInfoToBuildLog` will attempt to write the version information to the current Build Server log. If, at build time, it is detected that the build is occurring inside a Build @@ -205,7 +209,7 @@ Properties `WriteVersionInfoToBuildLog`, `UpdateAssemblyInfo`, `UseFullSemVerForNuGet`, `UpdateVersionProperties` and `GetVersion` are checked before running these tasks. -You can disable `GitVersionTask.UpdateAssemblyInfo` by setting +You can disable `GitVersion.MsBuild.UpdateAssemblyInfo` by setting `UpdateAssemblyInfo` to `false` in your MSBuild script, like this: From 840ede8fb5d92367c96c455203814714a656d6b3 Mon Sep 17 00:00:00 2001 From: James May Date: Fri, 4 Jun 2021 18:26:33 +1000 Subject: [PATCH 03/79] Update docs/input/docs/usage/msbuild.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Asbjørn Ulsberg --- docs/input/docs/usage/msbuild.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/input/docs/usage/msbuild.md b/docs/input/docs/usage/msbuild.md index 21d80d8715..7eb5a613cb 100644 --- a/docs/input/docs/usage/msbuild.md +++ b/docs/input/docs/usage/msbuild.md @@ -25,7 +25,7 @@ is coming soon. ### Install the MSTask targets -Add the [GitVersion.MsBuild](https://www.nuget.org/packages/GitVersionTask/) NuGet +Add the [GitVersion.MsBuild](https://www.nuget.org/packages/GitVersion.MsBuild/) NuGet Package into the project you want to be versioned by GitVersion. From the Package Manager Console: From a74d44da231334307df7de0d47267bdd7ca62a7c Mon Sep 17 00:00:00 2001 From: James May Date: Mon, 7 Jun 2021 15:39:40 +1000 Subject: [PATCH 04/79] add note to README --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6b609c564e..e69c1762f8 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ works out the [Semantic Version][semver] of the commit being built. | **GitVersion.Portable** | [![Chocolatey][choco-badge]][choco] | | **GitVersion.Tool** | [![NuGet][gvgt-badge]][gvgt] | | **GitVersion.CommandLine** | [![NuGet][gvcl-badge]][gvcl] | -| **GitVersion.MsBuild** | [![NuGet][gvt-badge]][gvt] | +| **GitVersion.MsBuild** | [![NuGet][gvt-badge]][gvt] | Known as *[GitVersionTask](https://www.nuget.org/packages/GitVersionTask/)* before v5.6.0 | | **Homebrew** | [![homebrew][brew-badge]][brew] | | **Azure Pipeline Task** | [![Azure Pipeline Task][az-pipeline-task-badge]][az-pipeline-task] | | **Github Action** | [![Github Action][gh-actions-badge]][gh-actions] | From 69a9726dca45173cc29ab6356eaad4fd2d70875f Mon Sep 17 00:00:00 2001 From: James May Date: Tue, 8 Jun 2021 17:41:12 +1000 Subject: [PATCH 05/79] README.md: note GitVersionTask name change follow up to #2716. Somehow it worked in the preview but not once it was committed. --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e69c1762f8..d46af2b514 100644 --- a/README.md +++ b/README.md @@ -8,8 +8,8 @@ works out the [Semantic Version][semver] of the commit being built. [![codecov][codecov-badge]][codecov] [![Gitter][gitter-badge]][gitter] -| Artifact | Stable | -| :------------------------- | :----------------------------------------------------------------- | +| Artifact | Stable | | +| :------------------------- | :----------------------------------------------------------------- | - | | **GitHub Release** | [![GitHub release][gh-rel-badge]][gh-rel] | | **GitVersion.Portable** | [![Chocolatey][choco-badge]][choco] | | **GitVersion.Tool** | [![NuGet][gvgt-badge]][gvgt] | From da1ff04caee08dd43c38f57f709f57592b2a8a15 Mon Sep 17 00:00:00 2001 From: James May Date: Wed, 9 Jun 2021 12:46:46 +1000 Subject: [PATCH 06/79] code review changes --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index d46af2b514..45f4b214d7 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ works out the [Semantic Version][semver] of the commit being built. | **GitVersion.Portable** | [![Chocolatey][choco-badge]][choco] | | **GitVersion.Tool** | [![NuGet][gvgt-badge]][gvgt] | | **GitVersion.CommandLine** | [![NuGet][gvcl-badge]][gvcl] | -| **GitVersion.MsBuild** | [![NuGet][gvt-badge]][gvt] | Known as *[GitVersionTask](https://www.nuget.org/packages/GitVersionTask/)* before v5.6.0 | +| **GitVersion.MsBuild** | [![NuGet][gvt-badge]][gvt] | Known as *[GitVersionTask][GitVersionTask]* before v5.6.0 | | **Homebrew** | [![homebrew][brew-badge]][brew] | | **Azure Pipeline Task** | [![Azure Pipeline Task][az-pipeline-task-badge]][az-pipeline-task] | | **Github Action** | [![Github Action][gh-actions-badge]][gh-actions] | @@ -69,6 +69,7 @@ from The Noun Project. [choco-badge]: https://img.shields.io/chocolatey/v/gitversion.portable.svg?logo=nuget [gvt]: https://www.nuget.org/packages/GitVersion.MsBuild [gvt-badge]: https://img.shields.io/nuget/v/GitVersion.MsBuild.svg?logo=nuget +[gitversiontask]: https://www.nuget.org/packages/GitVersionTask/ [gvcl]: https://www.nuget.org/packages/GitVersion.CommandLine [gvcl-badge]: https://img.shields.io/nuget/v/GitVersion.CommandLine.svg?logo=nuget [gvgt]: https://www.nuget.org/packages/GitVersion.Tool From 33a5305b6263c71bfbbda7fded769fe459e9e52b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 9 Jun 2021 05:45:04 +0000 Subject: [PATCH 07/79] Bump NUnit3TestAdapter from 3.17.0 to 4.0.0 Bumps [NUnit3TestAdapter](https://github.com/nunit/nunit3-vs-adapter) from 3.17.0 to 4.0.0. - [Release notes](https://github.com/nunit/nunit3-vs-adapter/releases) - [Commits](https://github.com/nunit/nunit3-vs-adapter/compare/V3.17...V4.0.0) --- updated-dependencies: - dependency-name: NUnit3TestAdapter dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- src/Directory.Build.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 1cf7f50bef..b44b848204 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -35,7 +35,7 @@ 4.2.2 3.0.3 3.13.2 - 3.17.0 + 4.0.0 3.0.107 4.0.3 From 73a5938f98cd597c27677ce4f519686f64cc71ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Asbj=C3=B8rn=20Ulsberg?= Date: Fri, 11 Jun 2021 11:47:56 +0200 Subject: [PATCH 08/79] Explicit mention of how GitVersion exposes environment variables --- .../docs/reference/build-servers/index.cshtml | 34 +++++++++++++------ docs/input/docs/reference/variables.md | 7 ++++ 2 files changed, 31 insertions(+), 10 deletions(-) diff --git a/docs/input/docs/reference/build-servers/index.cshtml b/docs/input/docs/reference/build-servers/index.cshtml index 836e9269fe..e65f96af73 100644 --- a/docs/input/docs/reference/build-servers/index.cshtml +++ b/docs/input/docs/reference/build-servers/index.cshtml @@ -19,27 +19,41 @@ Description: Details on GitVersion's Build Server support @Html.Partial("_ChildPages") -

- When the gitVersion executable is run with the - /output buildserver flag instead of outputting JSON it will - export variables to the current build server. -

+

Build Server Variables

- For instance if you are running in TeamCity after you run + When the gitVersion executable is run with the + /output buildserver flag instead of outputting JSON, it will + export its version variables to the + current build server as build-server native variables. For instance if you + are running in TeamCity after you run gitversion /output buildserver you will have the %system.GitVersion.SemVer% variable available for you to use in the rest of the build configuration.

+

MSBuild Properties

+

When running in MSBuild either from the - MSBuild Task or - by using the /proj myproject.sln parameter, GitVersion will - make the MSBuild variables available in the format - $(GitVersion_SemVer)` + MSBuild Task or by using + /proj myproject.sln parameter, GitVersion will make its + version variables available as + MSBuild properties in the format $(GitVersion_SemVer).

+

Environment Variables

+ +

+ When executed within one of the supported build servers mentioned above, + GitVersion will also expose the version + variables as environment variables, in the format + GitVersion_SemVer (and in some circumstances, as + GitVersion.SemVer). +

+ +

Normalization

+

The standard gitversion executable normalize the branches if there is a build server detected. This behavior can be disabled with the diff --git a/docs/input/docs/reference/variables.md b/docs/input/docs/reference/variables.md index 7c75e5998e..ce81073c36 100644 --- a/docs/input/docs/reference/variables.md +++ b/docs/input/docs/reference/variables.md @@ -83,3 +83,10 @@ Each property of the above JSON document is described in the below table. | `CommitsSinceVersionSourcePadded` | The `CommitsSinceVersionSource` padded with `0` up to 4 digits. | | `CommitDate` | The ISO-8601 formatted date of the commit identified by `Sha`. | | `UncommittedChanges` | The number of uncommitted changes present in the repository. | + +Depending on how and in which context GitVersion is executed (for instance +within a [supported build server][build-servers]), the above version variables +may be exposed automatically as **environment variables** in the format +`GitVersion_FullSemVer`. + +[build-servers]: ./build-servers/ From 1e51971c9741214b659e8fe076209a7273244971 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 14 Jun 2021 07:11:33 +0000 Subject: [PATCH 09/79] Bump YamlDotNet from 11.1.1 to 11.2.0 Bumps [YamlDotNet](https://github.com/aaubry/YamlDotNet) from 11.1.1 to 11.2.0. - [Release notes](https://github.com/aaubry/YamlDotNet/releases) - [Commits](https://github.com/aaubry/YamlDotNet/compare/v11.1.1...v11.2.0) --- updated-dependencies: - dependency-name: YamlDotNet dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- src/Directory.Build.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Directory.Build.props b/src/Directory.Build.props index b44b848204..edf2bf8767 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -25,7 +25,7 @@ 2.0.312 2021.1.0 - 11.1.1 + 11.2.0 5.0.0 5.0.0 5.0.0 From 14297d7fed569352838f4a7906a2ce41afbb339a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Asbj=C3=B8rn=20Ulsberg?= Date: Thu, 17 Jun 2021 13:25:30 +0200 Subject: [PATCH 10/79] Move mergify.yml to the .github directory --- .mergify.yml => .github/.mergify.yml | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .mergify.yml => .github/.mergify.yml (100%) diff --git a/.mergify.yml b/.github/.mergify.yml similarity index 100% rename from .mergify.yml rename to .github/.mergify.yml From 9fd634aa1ef66a2e312afb0292863cf7dd3dc1cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Asbj=C3=B8rn=20Ulsberg?= Date: Thu, 17 Jun 2021 13:29:27 +0200 Subject: [PATCH 11/79] Delete appveyor.yml --- appveyor.yml | 10 ---------- 1 file changed, 10 deletions(-) delete mode 100644 appveyor.yml diff --git a/appveyor.yml b/appveyor.yml deleted file mode 100644 index efa2a4f7fa..0000000000 --- a/appveyor.yml +++ /dev/null @@ -1,10 +0,0 @@ -image: Visual Studio 2019 - -assembly_info: - patch: false - -build_script: - - pwsh: ./build.ps1 -script build.cake -target Default - -test: off -skip_tags: true From 829501615884479b61f4193fdb6be819aecf4bdc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Asbj=C3=B8rn=20Ulsberg?= Date: Thu, 17 Jun 2021 13:31:11 +0200 Subject: [PATCH 12/79] Move codecov.yml to the .github directory --- codecov.yml => .github/codecov.yml | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename codecov.yml => .github/codecov.yml (100%) diff --git a/codecov.yml b/.github/codecov.yml similarity index 100% rename from codecov.yml rename to .github/codecov.yml From bda6d1774a5e20f36b10772a8f71a6cf4692648d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Asbj=C3=B8rn=20Ulsberg?= Date: Thu, 17 Jun 2021 13:31:50 +0200 Subject: [PATCH 13/79] Update license --- LICENSE | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/LICENSE b/LICENSE index 7e5992d6cf..8cb034708b 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2013 NServiceBus Ltd +Copyright (c) 2021 NServiceBus Ltd, GitTools and contributors. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in @@ -17,4 +17,4 @@ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. From 77c6aa02ab6004158636216a71122c5b408e6260 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Asbj=C3=B8rn=20Ulsberg?= Date: Thu, 17 Jun 2021 13:33:57 +0200 Subject: [PATCH 14/79] Remove everything but Home from the ReadTheDocs navigation menu --- mkdocs.yml | 52 ---------------------------------------------------- 1 file changed, 52 deletions(-) diff --git a/mkdocs.yml b/mkdocs.yml index 845317b0ae..6215b58620 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -4,55 +4,3 @@ repo_url: https://github.com/GitTools/GitVersion pages: - Home: index.md -- Usage: - - Usage: usage/usage.md - - Command Line: usage/command-line.md - - MSBuild Task: usage/msbuild-task.md - - NuGet Library: usage/nuget-library.md -- Configuration: configuration.md -- Build Server Support: - - Introduction: reference/build-servers-support.md - - Build Servers: - - AppVeyor: reference/build-servers/appveyor.md - - Bamboo: reference/build-servers/bamboo.md - - GitLab CI: reference/build-servers/gitlab.md - - Continua CI: reference/build-servers/continua.md - - Jenkins: reference/build-servers/jenkins.md - - MyGet: reference/build-servers/myget.md - - Octopus Deploy: reference/build-servers/octopus-deploy.md - - TeamCity: reference/build-servers/teamcity.md - - Team Build (TFS): reference/build-servers/teambuild.md - - TFS Build vNext: reference/build-servers/azure-devops.md -- Examples: examples.md -- FAQ: faq.md -- Why?: why.md -- Who is using GitVersion: who.md - -- More Info: - - How it works: more-info/how-it-works.md - - Dynamic Repositories: more-info/dynamic-repositories.md - - Variables: more-info/variables.md - - Version incrementing: more-info/version-increments.md - - Version sources: more-info/version-sources.md - - Incrementing per commit: more-info/incrementing-per-commit.md - -- Git branching strategies: - - Home: git-branching-strategies/index.md - - GitFlow: git-branching-strategies/gitflow.md - - GitHubFlow: git-branching-strategies/githubflow.md - - GitFlow Examples: git-branching-strategies/gitflow-examples.md - - GitHubFlow Examples: git-branching-strategies/githubflow-examples.md - - Converting to GitFlow: git-branching-strategies/converting-to-gitflow.md - - Creating/Updating examples: git-branching-strategies/creating-updating-examples.md - - Complete: git-branching-strategies/gitflow-examples_complete.md - -- Reference: - - Intro to SemVer: reference/intro-to-semver.md - - Git setup: reference/git-setup.md - - Feature branches: reference/feature-branches.md - - Pull requests: reference/pull-requests.md - - Versioning modes: - - Versioning modes: reference/versioning-mode.md - - Mainline development: reference/mainline-development.md - - Continuous delivery: reference/continuous-delivery.md - - Continuous deployment: reference/continuous-deployment.md From 8230368d3c31aa3b394a1e49efd4501cacb49be1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Asbj=C3=B8rn=20Ulsberg?= Date: Thu, 17 Jun 2021 13:39:44 +0200 Subject: [PATCH 15/79] Move build.config into the build directory --- .azurepipelines/common-steps.yml | 2 +- .github/workflows/build.yml | 18 +++++++++--------- build.ps1 | 2 +- build.config => build/build.config | 0 4 files changed, 11 insertions(+), 11 deletions(-) rename build.config => build/build.config (100%) diff --git a/.azurepipelines/common-steps.yml b/.azurepipelines/common-steps.yml index 7d3c9925fc..7734b3f14e 100644 --- a/.azurepipelines/common-steps.yml +++ b/.azurepipelines/common-steps.yml @@ -11,7 +11,7 @@ steps: displayName: Cache Cake tools - task: Cache@2 inputs: - key: 'v1-dotnet | "$(Agent.OS)" | build.config' + key: 'v1-dotnet | "$(Agent.OS)" | build/build.config' path: .dotnet displayName: Cache dotnet locally - ${{ if eq(parameters.includeArtifacts, true) }}: diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 75a263c2c9..0912185120 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -55,7 +55,7 @@ jobs: uses: actions/cache@v2.1.5 with: path: .dotnet - key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build.config') }} + key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build/build.config') }} - name: '[Cake build & pack]' shell: pwsh run: ./build.ps1 -target Pack @@ -97,7 +97,7 @@ jobs: uses: actions/cache@v2.1.5 with: path: .dotnet - key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build.config') }} + key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build/build.config') }} - name: '[Run Test]' shell: pwsh run: ./build.ps1 -target Test @@ -129,7 +129,7 @@ jobs: uses: actions/cache@v2.1.5 with: path: .dotnet - key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build.config') }} + key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build/build.config') }} - uses: actions/download-artifact@v2.0.9 name: Download artifacts folder with: @@ -159,7 +159,7 @@ jobs: uses: actions/cache@v2.1.5 with: path: .dotnet - key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build.config') }} + key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build/build.config') }} - uses: actions/download-artifact@v2.0.9 name: Download artifacts folder with: @@ -189,7 +189,7 @@ jobs: uses: actions/cache@v2.1.5 with: path: .dotnet - key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build.config') }} + key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build/build.config') }} - uses: actions/download-artifact@v2.0.9 name: Download artifacts folder with: @@ -219,7 +219,7 @@ jobs: uses: actions/cache@v2.1.5 with: path: .dotnet - key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build.config') }} + key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build/build.config') }} - uses: actions/download-artifact@v2.0.9 name: Download artifacts folder with: @@ -259,7 +259,7 @@ jobs: uses: actions/cache@v2.1.5 with: path: .dotnet - key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build.config') }} + key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build/build.config') }} - uses: actions/download-artifact@v2.0.9 name: Download artifacts folder with: @@ -300,7 +300,7 @@ jobs: uses: actions/cache@v2.1.5 with: path: .dotnet - key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build.config') }} + key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build/build.config') }} - uses: actions/download-artifact@v2.0.9 name: Download artifacts folder with: @@ -332,7 +332,7 @@ jobs: uses: actions/cache@v2.1.5 with: path: .dotnet - key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build.config') }} + key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build/build.config') }} - uses: actions/download-artifact@v2.0.9 name: Download artifacts folder with: diff --git a/build.ps1 b/build.ps1 index d07e283e1f..051ab34163 100644 --- a/build.ps1 +++ b/build.ps1 @@ -62,7 +62,7 @@ $DotNetChannel = 'LTS' $PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent [string[]] $DotNetVersion= '' -foreach($line in Get-Content (Join-Path $PSScriptRoot 'build.config')) +foreach($line in Get-Content (Join-Path $PSScriptRoot 'build' 'build.config')) { if ($line -like 'DOTNET_VERSION=*') { $DotNetVersion = $line.SubString("DOTNET_VERSION=".Length).Split(',') diff --git a/build.config b/build/build.config similarity index 100% rename from build.config rename to build/build.config From 3ae377e76fba1127505c0f44c21cd382a57ceeb7 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 17 Jun 2021 13:36:29 +0000 Subject: [PATCH 16/79] Bump actions/cache from 2.1.5 to 2.1.6 Bumps [actions/cache](https://github.com/actions/cache) from 2.1.5 to 2.1.6. - [Release notes](https://github.com/actions/cache/releases) - [Commits](https://github.com/actions/cache/compare/v2.1.5...v2.1.6) Signed-off-by: dependabot[bot] --- .github/workflows/build.yml | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 0912185120..9063ce570e 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -46,13 +46,13 @@ jobs: git fetch --prune --unshallow - name: Cache tools id: cache-tools - uses: actions/cache@v2.1.5 + uses: actions/cache@v2.1.6 with: path: tools key: v1-${{ runner.os }}-tools-${{ hashFiles('build.cake') }} - name: Cache dotnet id: cache-dotnet - uses: actions/cache@v2.1.5 + uses: actions/cache@v2.1.6 with: path: .dotnet key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build/build.config') }} @@ -88,13 +88,13 @@ jobs: git fetch --prune --unshallow - name: Cache tools id: cache-tools - uses: actions/cache@v2.1.5 + uses: actions/cache@v2.1.6 with: path: tools key: v1-${{ runner.os }}-tools-${{ hashFiles('build.cake') }} - name: Cache dotnet id: cache-dotnet - uses: actions/cache@v2.1.5 + uses: actions/cache@v2.1.6 with: path: .dotnet key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build/build.config') }} @@ -120,13 +120,13 @@ jobs: git fetch --prune --unshallow - name: Cache tools id: cache-tools - uses: actions/cache@v2.1.5 + uses: actions/cache@v2.1.6 with: path: tools key: v1-${{ runner.os }}-tools-${{ hashFiles('build.cake') }} - name: Cache dotnet id: cache-dotnet - uses: actions/cache@v2.1.5 + uses: actions/cache@v2.1.6 with: path: .dotnet key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build/build.config') }} @@ -150,13 +150,13 @@ jobs: git fetch --prune --unshallow - name: Cache tools id: cache-tools - uses: actions/cache@v2.1.5 + uses: actions/cache@v2.1.6 with: path: tools key: v1-${{ runner.os }}-tools-${{ hashFiles('build.cake') }} - name: Cache dotnet id: cache-dotnet - uses: actions/cache@v2.1.5 + uses: actions/cache@v2.1.6 with: path: .dotnet key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build/build.config') }} @@ -180,13 +180,13 @@ jobs: git fetch --prune --unshallow - name: Cache tools id: cache-tools - uses: actions/cache@v2.1.5 + uses: actions/cache@v2.1.6 with: path: tools key: v1-${{ runner.os }}-tools-${{ hashFiles('build.cake') }} - name: Cache dotnet id: cache-dotnet - uses: actions/cache@v2.1.5 + uses: actions/cache@v2.1.6 with: path: .dotnet key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build/build.config') }} @@ -210,13 +210,13 @@ jobs: git fetch --prune --unshallow - name: Cache tools id: cache-tools - uses: actions/cache@v2.1.5 + uses: actions/cache@v2.1.6 with: path: tools key: v1-${{ runner.os }}-tools-${{ hashFiles('build.cake') }} - name: Cache dotnet id: cache-dotnet - uses: actions/cache@v2.1.5 + uses: actions/cache@v2.1.6 with: path: .dotnet key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build/build.config') }} @@ -250,13 +250,13 @@ jobs: git fetch --prune --unshallow - name: Cache tools id: cache-tools - uses: actions/cache@v2.1.5 + uses: actions/cache@v2.1.6 with: path: tools key: v1-${{ runner.os }}-tools-${{ hashFiles('build.cake') }} - name: Cache dotnet id: cache-dotnet - uses: actions/cache@v2.1.5 + uses: actions/cache@v2.1.6 with: path: .dotnet key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build/build.config') }} @@ -291,13 +291,13 @@ jobs: git fetch --prune --unshallow - name: Cache tools id: cache-tools - uses: actions/cache@v2.1.5 + uses: actions/cache@v2.1.6 with: path: tools key: v1-${{ runner.os }}-tools-${{ hashFiles('build.cake') }} - name: Cache dotnet id: cache-dotnet - uses: actions/cache@v2.1.5 + uses: actions/cache@v2.1.6 with: path: .dotnet key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build/build.config') }} @@ -323,13 +323,13 @@ jobs: git fetch --prune --unshallow - name: Cache tools id: cache-tools - uses: actions/cache@v2.1.5 + uses: actions/cache@v2.1.6 with: path: tools key: v1-${{ runner.os }}-tools-${{ hashFiles('build.cake') }} - name: Cache dotnet id: cache-dotnet - uses: actions/cache@v2.1.5 + uses: actions/cache@v2.1.6 with: path: .dotnet key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build/build.config') }} From 6e80a0b695e154ddb4f12a3aff650854700295e1 Mon Sep 17 00:00:00 2001 From: Eberhard Beilharz Date: Thu, 17 Jun 2021 15:59:17 +0200 Subject: [PATCH 17/79] Update link to GitVersion.MsBuild nuget package in `msbuild.md` --- docs/input/docs/usage/msbuild.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/input/docs/usage/msbuild.md b/docs/input/docs/usage/msbuild.md index 7eb5a613cb..efc913761e 100644 --- a/docs/input/docs/usage/msbuild.md +++ b/docs/input/docs/usage/msbuild.md @@ -19,7 +19,7 @@ is coming soon. > **Note** The nuget package was "*[GitVersionTask](https://www.nuget.org/packages/GitVersionTask/)*" up until version 5.5.1. - From version 5.6.0 it has been called "*[GitVersion.MsBuild](https://www.nuget.org/packages/GitVersionTask/)*" + From version 5.6.0 it has been called "*[GitVersion.MsBuild](https://www.nuget.org/packages/GitVersion.MsBuild/)*" ## TL;DR From 94bd1d33c2cc3a81d3e9b784f775e946e90776bc Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 17 Jun 2021 15:08:19 +0000 Subject: [PATCH 18/79] Bump actions/download-artifact from 2.0.9 to 2.0.10 Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 2.0.9 to 2.0.10. - [Release notes](https://github.com/actions/download-artifact/releases) - [Commits](https://github.com/actions/download-artifact/compare/v2.0.9...v2.0.10) --- updated-dependencies: - dependency-name: actions/download-artifact dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .github/workflows/build.yml | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 9063ce570e..e26b736363 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -130,7 +130,7 @@ jobs: with: path: .dotnet key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build/build.config') }} - - uses: actions/download-artifact@v2.0.9 + - uses: actions/download-artifact@v2.0.10 name: Download artifacts folder with: name: storage @@ -160,7 +160,7 @@ jobs: with: path: .dotnet key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build/build.config') }} - - uses: actions/download-artifact@v2.0.9 + - uses: actions/download-artifact@v2.0.10 name: Download artifacts folder with: name: storage @@ -190,7 +190,7 @@ jobs: with: path: .dotnet key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build/build.config') }} - - uses: actions/download-artifact@v2.0.9 + - uses: actions/download-artifact@v2.0.10 name: Download artifacts folder with: name: storage @@ -220,7 +220,7 @@ jobs: with: path: .dotnet key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build/build.config') }} - - uses: actions/download-artifact@v2.0.9 + - uses: actions/download-artifact@v2.0.10 name: Download artifacts folder with: name: storage @@ -260,7 +260,7 @@ jobs: with: path: .dotnet key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build/build.config') }} - - uses: actions/download-artifact@v2.0.9 + - uses: actions/download-artifact@v2.0.10 name: Download artifacts folder with: name: storage @@ -301,7 +301,7 @@ jobs: with: path: .dotnet key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build/build.config') }} - - uses: actions/download-artifact@v2.0.9 + - uses: actions/download-artifact@v2.0.10 name: Download artifacts folder with: name: storage @@ -333,22 +333,22 @@ jobs: with: path: .dotnet key: v1-${{ runner.os }}-dotnet-${{ hashFiles('build/build.config') }} - - uses: actions/download-artifact@v2.0.9 + - uses: actions/download-artifact@v2.0.10 name: Download artifacts folder with: name: storage path: ${{ github.workspace }}/artifacts - - uses: actions/download-artifact@v2.0.9 + - uses: actions/download-artifact@v2.0.10 name: Download windows native folder with: name: storage-windows-latest path: ${{ github.workspace }}/artifacts/native - - uses: actions/download-artifact@v2.0.9 + - uses: actions/download-artifact@v2.0.10 name: Download linux native folder with: name: storage-ubuntu-latest path: ${{ github.workspace }}/artifacts/native - - uses: actions/download-artifact@v2.0.9 + - uses: actions/download-artifact@v2.0.10 name: Download osx native folder with: name: storage-macos-latest From 5460ba460d1bc8e27318eaaa604754b5f0986fa4 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 17 Jun 2021 15:08:24 +0000 Subject: [PATCH 19/79] Bump actions/upload-artifact from 2.2.3 to 2.2.4 Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 2.2.3 to 2.2.4. - [Release notes](https://github.com/actions/upload-artifact/releases) - [Commits](https://github.com/actions/upload-artifact/compare/v2.2.3...v2.2.4) --- updated-dependencies: - dependency-name: actions/upload-artifact dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .github/workflows/build.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 9063ce570e..ca3b1517f9 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -59,13 +59,13 @@ jobs: - name: '[Cake build & pack]' shell: pwsh run: ./build.ps1 -target Pack - - uses: actions/upload-artifact@v2.2.3 + - uses: actions/upload-artifact@v2.2.4 if: matrix.os == 'windows-latest' with: name: storage path: ${{ github.workspace }}/artifacts name: 'Upload artifacts folder' - - uses: actions/upload-artifact@v2.2.3 + - uses: actions/upload-artifact@v2.2.4 with: name: storage-${{ matrix.os }} path: ${{ github.workspace }}/artifacts/native From 06c0f8552bb73d7b72c10774c1df05f86f1cca2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Asbj=C3=B8rn=20Ulsberg?= Date: Thu, 17 Jun 2021 22:38:24 +0200 Subject: [PATCH 20/79] Rename .mergify.yml to mergify.yml --- .github/{.mergify.yml => mergify.yml} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .github/{.mergify.yml => mergify.yml} (100%) diff --git a/.github/.mergify.yml b/.github/mergify.yml similarity index 100% rename from .github/.mergify.yml rename to .github/mergify.yml From fcb7e36744b56403587344d7df57d6f6ffbde07f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Asbj=C3=B8rn=20Ulsberg?= Date: Thu, 17 Jun 2021 12:49:03 +0200 Subject: [PATCH 21/79] Add remark-lint --- .github/workflows/docs.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index c95a25e6d0..b09e4eb34c 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -30,6 +30,12 @@ jobs: directory: ./artifacts/Documentation arguments: --url-ignore /api/ --allow-hash-href --assume-extension --disable-external + - name: '[Remark Lint]' + uses: reviewdog/action-remark-lint@v2 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + reporter: github-pr-check + - name: '[Publish Documentation]' if: ${{ github.event_name == 'push' }} shell: pwsh From dc6a9853fb98bfe1dfe863e1cd56b209ab464f26 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Asbj=C3=B8rn=20Ulsberg?= Date: Thu, 17 Jun 2021 13:07:12 +0200 Subject: [PATCH 22/79] Rewarp a doc file to trigger the docs build --- docs/input/docs/reference/build-servers/appveyor.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/input/docs/reference/build-servers/appveyor.md b/docs/input/docs/reference/build-servers/appveyor.md index 78ad696c5e..6d4728fb92 100644 --- a/docs/input/docs/reference/build-servers/appveyor.md +++ b/docs/input/docs/reference/build-servers/appveyor.md @@ -10,4 +10,5 @@ AppVeyor is the first build server which has a setup helper built into 1. Run `GitVersion init` 2. Choose `Setup build scripts` (currently option 7, but that could change) 3. Choose `AppVeyor` -4. Follow the prompts to generate an AppVeyor.yml file which works nicely with GitVersion +4. Follow the prompts to generate an AppVeyor.yml file which works nicely with + GitVersion From 3bb802126114f81a106fc7923b4d751032472fc4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Asbj=C3=B8rn=20Ulsberg?= Date: Thu, 17 Jun 2021 22:37:29 +0200 Subject: [PATCH 23/79] Add remark config --- .remarkrc.yaml | 71 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 .remarkrc.yaml diff --git a/.remarkrc.yaml b/.remarkrc.yaml new file mode 100644 index 0000000000..4ca9043aea --- /dev/null +++ b/.remarkrc.yaml @@ -0,0 +1,71 @@ +plugins: + - remark-frontmatter + - remark-lint + - remark-lint-no-empty-sections + - remark-lint-code + - remark-lint-blockquote-indentation + - remark-lint-checkbox-character-style + - remark-lint-checkbox-content-indent + - remark-lint-code-block-style: fenced + - remark-lint-definition-case + - remark-lint-definition-spacing + - remark-lint-fenced-code-flag + - remark-lint-fenced-code-marker + - remark-lint-file-extension + - remark-lint-final-definition + - remark-lint-final-newline + - remark-lint-hard-break-spaces + - remark-lint-heading-increment + - remark-lint-heading-style: atx + - remark-lint-link-title-style + - remark-lint-list-item-bullet-indent + - remark-lint-list-item-content-indent + - remark-lint-maximum-heading-length: 120 + - remark-lint-no-auto-link-without-protocol + - remark-lint-no-blockquote-without-marker + - remark-lint-no-consecutive-blank-lines + - remark-lint-no-duplicate-definitions + - remark-lint-no-duplicate-headings + - remark-lint-no-emphasis-as-heading + - remark-lint-no-empty-url + - remark-lint-no-file-name-articles + - remark-lint-no-file-name-consecutive-dashes + - remark-lint-no-file-name-irregular-characters + - remark-lint-no-file-name-mixed-case + - remark-lint-no-file-name-outer-dashes + - remark-lint-no-heading-content-indent + - remark-lint-no-heading-indent + - remark-lint-no-heading-like-paragraph + - remark-lint-no-inline-padding + - remark-lint-no-literal-urls + - remark-lint-no-multiple-toplevel-headings + - remark-lint-no-reference-like-url + - remark-lint-no-shell-dollars + - remark-lint-no-shortcut-reference-image + - remark-lint-no-table-indentation + - remark-lint-no-tabs + - remark-lint-no-unused-definitions + - remark-lint-ordered-list-marker-style + - remark-lint-ordered-list-marker-value + - remark-lint-rule-style + - remark-lint-strong-marker + - remark-lint-table-cell-padding + - remark-lint-table-pipe-alignment + - remark-lint-table-pipes + - remark-lint-unordered-list-marker-style + - remark-lint-list-item-indent: space +settings: + bullet: '*' + emphasis: _ + strong: '*' + fence: '`' + rule: '-' + ruleSpaces: false + ruleRepetition: 3 + gfm: true + footnotes: true + commonmark: false + pedantic: false + entities: false + fences: true + spacedTable: true From 7809b809da2268e1d11ea55bf710d727674ef2d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Asbj=C3=B8rn=20Ulsberg?= Date: Thu, 17 Jun 2021 22:37:06 +0200 Subject: [PATCH 24/79] Fix Markdown issues pointed out by markdown-lint --- BREAKING_CHANGES.md | 54 +++---- CONTRIBUTING.md | 70 +++++----- README.md | 20 +-- .../contribute-examples.md | 8 +- .../branching-strategies/gitflow/examples.md | 24 ++-- .../branching-strategies/gitflow/index.md | 132 ++++++++++-------- .../branching-strategies/githubflow/index.md | 22 +-- .../learn/branching-strategies/overview.md | 32 ++--- docs/input/docs/learn/dynamic-repositories.md | 14 +- docs/input/docs/learn/faq.md | 4 +- docs/input/docs/learn/git-setup.md | 2 +- docs/input/docs/learn/how-it-works.md | 65 ++++----- docs/input/docs/learn/intro-to-semver.md | 16 ++- docs/input/docs/learn/who.md | 24 ++-- docs/input/docs/learn/why.md | 34 ++--- .../docs/reference/build-servers/appveyor.md | 10 +- .../reference/build-servers/azure-devops.md | 92 ++++++------ .../docs/reference/build-servers/bamboo.md | 6 +- .../docs/reference/build-servers/continua.md | 54 +++---- .../docs/reference/build-servers/jenkins.md | 33 +++-- .../docs/reference/build-servers/myget.md | 24 ++-- .../reference/build-servers/octopus-deploy.md | 64 +++++---- .../docs/reference/build-servers/teamcity.md | 63 +++++---- docs/input/docs/reference/configuration.md | 85 ++++++----- .../reference/modes/continuous-delivery.md | 36 ++--- docs/input/docs/reference/modes/mainline.md | 21 +-- .../docs/reference/version-increments.md | 14 +- docs/input/docs/reference/version-sources.md | 20 +-- docs/input/docs/usage/ci.md | 9 +- docs/input/docs/usage/cli/arguments.md | 43 +++--- docs/input/docs/usage/cli/assembly-patch.md | 27 ++-- docs/input/docs/usage/cli/installation.md | 9 +- docs/input/docs/usage/msbuild.md | 17 ++- docs/readme.md | 6 +- src/Docker/Readme.md | 10 +- 35 files changed, 605 insertions(+), 559 deletions(-) diff --git a/BREAKING_CHANGES.md b/BREAKING_CHANGES.md index 19bb07b58b..a78b5d04a8 100644 --- a/BREAKING_CHANGES.md +++ b/BREAKING_CHANGES.md @@ -1,9 +1,9 @@ ## v5.0.0 -- Version numbers in branches other than `release` branches are no longer - considered as a version source by default. Implemented in [#1541][pr-1541]. -- [#1581][pr-1581] folds `GitTools.Core` back into GitVersion to make - maintaining GitVersion easier. +* Version numbers in branches other than `release` branches are no longer + considered as a version source by default. Implemented in [#1541][pr-1541]. +* [#1581][pr-1581] folds `GitTools.Core` back into GitVersion to make + maintaining GitVersion easier. ## v4.0.0 @@ -12,35 +12,35 @@ When using GitFlow, a few things have changed. Hopefully the new settings just work for you -- `develop` has pre-release tag of `alpha` now, not unstable. -- `develop` will bump as soon as a `release` branch is created. -- Look at the [GitFlow examples][gitflow] for details of how it works now. +* `develop` has pre-release tag of `alpha` now, not unstable. +* `develop` will bump as soon as a `release` branch is created. +* Look at the [GitFlow examples][gitflow] for details of how it works now. ### Configuration Changes -- `GitVersionConfig.yaml` is deprecated in favor of `GitVersion.yml`. -- Regular expressions are no longer used as keys in branch config - - We have named branches, and introduced a `regex` config which you can - override. - - The default keys are: `master`, `develop`, `feature`, `release`, `pull-request`, - `hotfix` and `support` - - Just run `GitVersion.exe` in your project directory and it will tell you - what to change your config keys to - - For example, `dev(elop)?(ment)?$` is now just `develop`, we suggest not - overring regular expressions unless you really want to use a different convention. -- `source-branches` added as a configuration option for branches, it helps - GitVersion pick the correct source branch +* `GitVersionConfig.yaml` is deprecated in favor of `GitVersion.yml`. +* Regular expressions are no longer used as keys in branch config + * We have named branches, and introduced a `regex` config which you can + override. + * The default keys are: `master`, `develop`, `feature`, `release`, `pull-request`, + `hotfix` and `support` + * Just run `GitVersion.exe` in your project directory and it will tell you + what to change your config keys to + * For example, `dev(elop)?(ment)?$` is now just `develop`, we suggest not + overring regular expressions unless you really want to use a different convention. +* `source-branches` added as a configuration option for branches, it helps + GitVersion pick the correct source branch ## v3.0.0 -- NextVersion.txt has been deprecated, only `GitVersionConfig.yaml` is supported -- `AssemblyFileSemVer` variable removed, `AssemblyVersioningScheme` configuration - value makes this variable obsolete -- Variables `ClassicVersion` and `ClassicVersionWithTag` removed -- MSBuild task arguments (`AssemblyVersioningScheme`, `DevelopBranchTag`, - `ReleaseBranchTag`, `TagPrefix`, `NextVersion`) have been removed, use - `GitVersionConfig.yaml` instead -- GitVersionTask's `ReleaseDateAttribute` no longer exists +* NextVersion.txt has been deprecated, only `GitVersionConfig.yaml` is supported +* `AssemblyFileSemVer` variable removed, `AssemblyVersioningScheme` configuration + value makes this variable obsolete +* Variables `ClassicVersion` and `ClassicVersionWithTag` removed +* MSBuild task arguments (`AssemblyVersioningScheme`, `DevelopBranchTag`, + `ReleaseBranchTag`, `TagPrefix`, `NextVersion`) have been removed, use + `GitVersionConfig.yaml` instead +* GitVersionTask's `ReleaseDateAttribute` no longer exists [gitflow]: https://gitversion.net/docs/learn/branching-strategies/gitflow-examples_complete [pr-1541]: https://github.com/GitTools/GitVersion/pull/1541 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 618ddcc61a..20248c6335 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,10 +2,10 @@ We love contributions to get started contributing you might need: -- [Get started with git](http://rogerdudler.github.io/git-guide) -- [How to create a pull request](https://help.github.com/articles/using-pull-requests) -- [An issue to work on](https://github.com/GitTools/GitVersion/labels/up-for-grabs) - We are on [Up for grabs](http://up-for-grabs.net/), our up for grabs issues are tagged `up-for-grabs` -- An understanding of our [architecture](http://gitversion.net/docs/learn/how-it-works#architecture) and how [we write tests](#writing-tests) +* [Get started with git](http://rogerdudler.github.io/git-guide) +* [How to create a pull request](https://help.github.com/articles/using-pull-requests) +* [An issue to work on](https://github.com/GitTools/GitVersion/labels/up-for-grabs) - We are on [Up for grabs](http://up-for-grabs.net/), our up for grabs issues are tagged `up-for-grabs` +* An understanding of our [architecture](http://gitversion.net/docs/learn/how-it-works#architecture) and how [we write tests](#writing-tests) Once you know how to create a pull request and have an issue to work on, just post a comment saying you will work on it. If you end up not being able to complete the task, please post another comment so others can pick it up. @@ -14,12 +14,12 @@ Issues are also welcome, [failing tests](#writing-tests) are even more welcome. ## Contribution Guidelines -- Try to use feature branches rather than developing on main. -- Please include tests covering the change. -- The documentation is stored in the repository under the [`docs`](docs) folder. - Have a look at the [documentation readme file](docs/readme.md) for guidance - on how to improve the documentation and please include documentation updates - with your PR. +* Try to use feature branches rather than developing on main. +* Please include tests covering the change. +* The documentation is stored in the repository under the [`docs`](docs) folder. + Have a look at the [documentation readme file](docs/readme.md) for guidance + on how to improve the documentation and please include documentation updates + with your PR. ## How it works @@ -43,13 +43,13 @@ We are currently using NUnit, so just create a descriptive test method and attri We have a few fixtures for different scenarios. -- `EmptyRepositoryFixture` - Gives you an empty git repo to start with -- `RemoteRepositoryFixture` - A local repo tracking a test remote repository. The remote repo is available through the `Repository` property, the local is accessible via `LocalRepository` -- `BaseGitFlowRepositoryFixture` - A repo setup for GitFlow (has a develop branch checked out ready to go) +* `EmptyRepositoryFixture` - Gives you an empty git repo to start with +* `RemoteRepositoryFixture` - A local repo tracking a test remote repository. The remote repo is available through the `Repository` property, the local is accessible via `LocalRepository` +* `BaseGitFlowRepositoryFixture` - A repo setup for GitFlow (has a develop branch checked out ready to go) You can use a fixture by just `using` it. Like this -``` csharp +```csharp using (var fixture = new EmptyRepositoryFixture(new Config())) { } @@ -65,7 +65,7 @@ We have a number of extension method off `IRepository` to make it easy to write An example test looks like this: -``` csharp +```csharp fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("feature-test"); fixture.Repository.Checkout("feature-test"); @@ -85,22 +85,22 @@ Even better include the fix, but a failing test is a great start We use Cake for our build and deployment process. The way the build / release process is setup is: -1) We build releasable artifacts on AppVeyor -1) Login to AppVeyor -1) Deploy the latest main build -![docs/input/docs/img/release-1-deploy.png](docs/input/docs/img/release-1-deploy.png) -1) Choose GitVersion release, when you press deploy it will create a *non-released* GitHub release, this *will not* create a Git tag. This step is so we can validate the release and release notes before pushing the button. -![docs/input/docs/img/release-2-deploy.png](docs/input/docs/img/release-2-deploy.png) -1) All the artifacts should upload nicely -![docs/input/docs/img/release-3-deploy.png](docs/input/docs/img/release-3-deploy.png) -1) Head over to GitHub releases, you should have a draft release, download a copy of the release notes -![docs/input/docs/img/release-4-deploy.png](docs/input/docs/img/release-4-deploy.png) -1) Edit the release and do the following: - 1. Remove the build metadata from the tag and title (the + and everything after it) - 2. Paste the downloaded release notes in, you can clean them up if you want otherwise there may be closed issues which were questions etc. - 3. Tick the pre-release box if it's pre-release - 4. Press Publish -1) Publishing tags (a git tag) the release commit, this will trigger another appveyor build which only builds tags, this build uses deploy.cake. It downloads the artifacts from that GitHub release, then performs the release +1. We build releasable artifacts on AppVeyor +2. Login to AppVeyor +3. Deploy the latest main build + ![docs/input/docs/img/release-1-deploy.png](docs/input/docs/img/release-1-deploy.png) +4. Choose GitVersion release, when you press deploy it will create a _non-released_ GitHub release, this _will not_ create a Git tag. This step is so we can validate the release and release notes before pushing the button. + ![docs/input/docs/img/release-2-deploy.png](docs/input/docs/img/release-2-deploy.png) +5. All the artifacts should upload nicely + ![docs/input/docs/img/release-3-deploy.png](docs/input/docs/img/release-3-deploy.png) +6. Head over to GitHub releases, you should have a draft release, download a copy of the release notes + ![docs/input/docs/img/release-4-deploy.png](docs/input/docs/img/release-4-deploy.png) +7. Edit the release and do the following: + 1. Remove the build metadata from the tag and title (the + and everything after it) + 2. Paste the downloaded release notes in, you can clean them up if you want otherwise there may be closed issues which were questions etc. + 3. Tick the pre-release box if it's pre-release + 4. Press Publish +8. Publishing tags (a git tag) the release commit, this will trigger another appveyor build which only builds tags, this build uses deploy.cake. It downloads the artifacts from that GitHub release, then performs the release ## Docker @@ -109,17 +109,19 @@ It is a manual release step after the release now, first download the appropriat ```bash docker build . --build-arg GitVersionZip=GitVersion_.zip --tag gittools/gitversion ``` + ## Code Style In order to apply the code style defined by by the `.editorconfig` file you can use [`dotnet-format`](https://github.com/dotnet/format). -1. Install [`dotnet-format`](https://github.com/dotnet/format) as a global tool: +1. Install [`dotnet-format`](https://github.com/dotnet/format) as a global tool: ```shell dotnet tool install -g dotnet-format ``` -2. Change to the root folder of the GitVersion repository and use the following command to apply the code style: +2. Change to the root folder of the GitVersion repository and use the following command to apply the code style: + ```shell dotnet format ./ --folder --exclude **/AddFormats/ --fix-codestyle -``` \ No newline at end of file +``` diff --git a/README.md b/README.md index 45f4b214d7..e3cc21ee15 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ works out the [Semantic Version][semver] of the commit being built. | **GitVersion.Portable** | [![Chocolatey][choco-badge]][choco] | | **GitVersion.Tool** | [![NuGet][gvgt-badge]][gvgt] | | **GitVersion.CommandLine** | [![NuGet][gvcl-badge]][gvcl] | -| **GitVersion.MsBuild** | [![NuGet][gvt-badge]][gvt] | Known as *[GitVersionTask][GitVersionTask]* before v5.6.0 | +| **GitVersion.MsBuild** | [![NuGet][gvt-badge]][gvt] | Known as [GitVersionTask] before v5.6.0 | | **Homebrew** | [![homebrew][brew-badge]][brew] | | **Azure Pipeline Task** | [![Azure Pipeline Task][az-pipeline-task-badge]][az-pipeline-task] | | **Github Action** | [![Github Action][gh-actions-badge]][gh-actions] | @@ -26,13 +26,13 @@ GitVersion works on Windows, Linux, and Mac. ## Quick Links -- [Documentation][docs] -- [Contributing][contribute] -- [Why GitVersion][why] -- [Usage][usage] -- [How it works][how] -- [FAQ][faq] -- [Who is using GitVersion][who] +* [Documentation][docs] +* [Contributing][contribute] +* [Why GitVersion][why] +* [Usage][usage] +* [How it works][how] +* [FAQ][faq] +* [Who is using GitVersion][who] ## GitVersion in action! @@ -40,8 +40,8 @@ GitVersion works on Windows, Linux, and Mac. You are seeing: -- Pull requests being built as pre-release builds -- A branch called `release-1.0.0` producing beta v1 packages +* Pull requests being built as pre-release builds +* A branch called `release-1.0.0` producing beta v1 packages ## Icon diff --git a/docs/input/docs/learn/branching-strategies/contribute-examples.md b/docs/input/docs/learn/branching-strategies/contribute-examples.md index 3f1fb2b8ca..f2de039ab6 100644 --- a/docs/input/docs/learn/branching-strategies/contribute-examples.md +++ b/docs/input/docs/learn/branching-strategies/contribute-examples.md @@ -8,10 +8,10 @@ The examples are generated by GitVersion tests, there are a number of services which will then turn the sequence diagram text into an image to use in the docs. Here are some links which could be useful -- [PlantUML Sequence Diagrams](http://www.plantuml.com/sequence.html) -- [CodeUML Online editor](http://www.codeuml.com/) -- [PlantText Online editor](http://www.planttext.com/planttext) -- [PlantUML gist renderer](http://uml.mvnsearch.org) +* [PlantUML Sequence Diagrams](http://www.plantuml.com/sequence.html) +* [CodeUML Online editor](http://www.codeuml.com/) +* [PlantText Online editor](http://www.planttext.com/planttext) +* [PlantUML gist renderer](http://uml.mvnsearch.org) The tests are quite simple. Using the methods on the `fixture` itself will record that action in the sequence diagram. If you do not want the action diff --git a/docs/input/docs/learn/branching-strategies/gitflow/examples.md b/docs/input/docs/learn/branching-strategies/gitflow/examples.md index eba9271040..7e38000182 100644 --- a/docs/input/docs/learn/branching-strategies/gitflow/examples.md +++ b/docs/input/docs/learn/branching-strategies/gitflow/examples.md @@ -3,7 +3,7 @@ Order: 40 Title: GitFlow Examples --- -These examples are using the *default* configuration with GitVersion. Which is +These examples are using the _default_ configuration with GitVersion. Which is [continuous deployment](/docs/reference/modes/continuous-deployment) mode for `develop` and [continuous delivery](/docs/reference/modes/continuous-delivery) mode for all other branches. @@ -17,11 +17,11 @@ then tagged. Read more about this at [version increments](/docs/reference/versio Feature branches will take the feature branch name and use that as the pre-release tag. -![GitFlow](/docs/img/05119d0cd4ecaaefff94_feature-branch.png) +![GitFlow](/docs/img/05119d0cd4ecaaefff94\_feature-branch.png) Notice after the feature branch is merged, the version on `develop` is -`1.3.0-alpha.3`. This is due to `develop` running in *continuous deployment* -mode. If you configured `develop` to use *continuous delivery* the version would +`1.3.0-alpha.3`. This is due to `develop` running in _continuous deployment_ +mode. If you configured `develop` to use _continuous delivery_ the version would still be `1.3.0-alpha.1` and you would have to use release tags to increment the `alpha.1`. @@ -39,10 +39,10 @@ pull request branch name which is created when you submit a pull request ## Hotfix Branches -Hotfix branches are used when you need to do a *patch* release in GitFlow and +Hotfix branches are used when you need to do a _patch_ release in GitFlow and are always created off `main` -![GitFlow](/docs/img/f26ae57adbd9b74f74c4_hotfix.png) +![GitFlow](/docs/img/f26ae57adbd9b74f74c4\_hotfix.png) ## Minor Release Branches @@ -50,14 +50,14 @@ Release branches are used for both major and minor releases for stabilisation before a release. Release branches are taken off `develop` then merged to both `develop` and `main`. Finally `main` is tagged with the released version. -![GitFlow](/docs/img/6d33d35a70a777608fa1_minor-release.png) +![GitFlow](/docs/img/6d33d35a70a777608fa1\_minor-release.png) ## Major Release Branches Major releases are just like minor releases, the difference is you bump the major in the release branch name. -![GitFlow](/docs/img/39f9d8b8b007c82f1f80_major-release.png) +![GitFlow](/docs/img/39f9d8b8b007c82f1f80\_major-release.png) ## Support Branches @@ -73,12 +73,12 @@ support minors use `support/..x` or `support/..0`. Depending on what you name your support branch, you may or may not need a hotfix branch. Naming it `support/1.x` will automatically bump the patch, if you name it `support/1.3.0` then the version in branch name rule will kick in and the -patch *will not* automatically bump, meaning you have to use hotfix branches. -![GitFlow](/docs/img/b035b8ca99bd34239518_support-hotfix.png) +patch _will not_ automatically bump, meaning you have to use hotfix branches. +![GitFlow](/docs/img/b035b8ca99bd34239518\_support-hotfix.png) ### Minor Release -![GitFlow](/docs/img/2167fb1c4a5cf84edfd8_support-minor.png) +![GitFlow](/docs/img/2167fb1c4a5cf84edfd8\_support-minor.png) ## To Contribute @@ -91,4 +91,4 @@ See [contributing examples](/docs/learn/branching-strategies/contribute-examples ### Source See `DocumentationSamples.GitFlowExample`. To update, modify then run test. -Update [https://gist.github.com/JakeGinnivan/cf053d7f5d336ae9f7bb](https://gist.github.com/JakeGinnivan/cf053d7f5d336ae9f7bb) +Update diff --git a/docs/input/docs/learn/branching-strategies/gitflow/index.md b/docs/input/docs/learn/branching-strategies/gitflow/index.md index 21b211b3e9..c4a989ff62 100644 --- a/docs/input/docs/learn/branching-strategies/gitflow/index.md +++ b/docs/input/docs/learn/branching-strategies/gitflow/index.md @@ -11,20 +11,20 @@ SemVer compatible versions from this structure. ## Assumptions: -* Using [GitFlow branching model](http://nvie.com/git-model/) which always has a -main and a develop branch -* Following [Semantic Versioning](http://semver.org/) -* Planned releases (bumps in major or minor) are done on release branches -prefixed with release-. Eg: release-4.1 (or release-4.1.0) -* Hotfixes are prefixed with hotfix- Eg. hotfix-4.0.4 -* The original [GitFlow model](http://nvie.com/posts/a-successful-git-branching-model/) -specifies branches with a "-" separator while the [git flow extensions](https://github.com/nvie/gitflow) -default to a "/" separator. Either work with GitVersion. -* Tags are used on the main branch and reflects the SemVer of each stable -release eg 3.3.8 , 4.0.0, etc -* Tags can also be used to override versions while we transition repositories -over to GitVersion -* Using a build server with multi-branch building enabled eg TeamCity 8 +* Using [GitFlow branching model](http://nvie.com/git-model/) which always has a + main and a develop branch +* Following [Semantic Versioning](http://semver.org/) +* Planned releases (bumps in major or minor) are done on release branches + prefixed with release-. Eg: release-4.1 (or release-4.1.0) +* Hotfixes are prefixed with hotfix- Eg. hotfix-4.0.4 +* The original [GitFlow model](http://nvie.com/posts/a-successful-git-branching-model/) + specifies branches with a "-" separator while the [git flow extensions](https://github.com/nvie/gitflow) + default to a "/" separator. Either work with GitVersion. +* Tags are used on the main branch and reflects the SemVer of each stable + release eg 3.3.8 , 4.0.0, etc +* Tags can also be used to override versions while we transition repositories + over to GitVersion +* Using a build server with multi-branch building enabled eg TeamCity 8 ## How Branches are handled @@ -32,8 +32,8 @@ The descriptions of how commits and branches are versioned can be considered a type of pseudopod. With that in mind there are a few common "variables" that we will refer to: -* `targetBranch` => the branch we are targeting -* `targetCommit` => the commit we are targeting on `targetbranch` +* `targetBranch` => the branch we are targeting +* `targetCommit` => the commit we are targeting on `targetbranch` ### Main branch @@ -45,20 +45,22 @@ If we try to build from a commit that is no merge and no tag then assume `0.1.0` `mergeVersion` => the SemVer extracted from `targetCommit.Message` -* major: `mergeVersion.Major` -* minor: `mergeVersion.Minor` -* patch: `mergeVersion.Patch` -* pre-release: 0 (perhaps count ahead commits later) -* stability: final +* major: `mergeVersion.Major` +* minor: `mergeVersion.Minor` +* patch: `mergeVersion.Patch` +* pre-release: 0 (perhaps count ahead commits later) +* stability: final Optional Tags (only when transitioning existing repository): -* TagOnHeadCommit.Name={semver} => overrides the version to be {semver} +* TagOnHeadCommit.Name={semver} => overrides the version to be {semver} Long version: - {major}.{minor}.{patch} Sha:'{sha}' - 1.2.3 Sha:'a682956dccae752aa24597a0f5cd939f93614509' +``` +{major}.{minor}.{patch} Sha:'{sha}' +1.2.3 Sha:'a682956dccae752aa24597a0f5cd939f93614509' +``` ### Develop branch @@ -67,16 +69,18 @@ Long version: `main` that is older than the `targetCommitDate` `mainMergeVersion` => the SemVer extracted from `mainVersionCommit.Message` -* major: `mainMergeVersion.Major` -* minor: `mainMergeVersion.Minor + 1` (0 if the override above is used) -* patch: 0 -* pre-release: `alpha.{n}` where n = how many commits `develop` is in front of -`mainVersionCommit.Date` ('0' padded to 4 characters) +* major: `mainMergeVersion.Major` +* minor: `mainMergeVersion.Minor + 1` (0 if the override above is used) +* patch: 0 +* pre-release: `alpha.{n}` where n = how many commits `develop` is in front of + `mainVersionCommit.Date` ('0' padded to 4 characters) Long version: - {major}.{minor}.{patch}-{pre-release} Branch:'{branchName}' Sha:'{sha}' - 1.2.3-alpha.645 Branch:'develop' Sha:'a682956dccae752aa24597a0f5cd939f93614509' +``` +{major}.{minor}.{patch}-{pre-release} Branch:'{branchName}' Sha:'{sha}' +1.2.3-alpha.645 Branch:'develop' Sha:'a682956dccae752aa24597a0f5cd939f93614509' +``` ### Hotfix branches @@ -84,22 +88,24 @@ Named: `hotfix-{versionNumber}` eg `hotfix-1.2` `branchVersion` => the SemVer extracted from `targetBranch.Name` -* major: `mergeVersion.Major` -* minor: `mergeVersion.Minor` -* patch: `mergeVersion.Patch` -* pre-release: `beta{n}` where n = number of commits on branch ('0' padded to -4 characters) +* major: `mergeVersion.Major` +* minor: `mergeVersion.Minor` +* patch: `mergeVersion.Patch` +* pre-release: `beta{n}` where n = number of commits on branch ('0' padded to + 4 characters) Long version: - {major}.{minor}.{patch}-{pre-release} Branch:'{branchName}' Sha:'{sha}' - 1.2.3-beta645 Branch:'hotfix-foo' Sha:'a682956dccae752aa24597a0f5cd939f93614509' +``` +{major}.{minor}.{patch}-{pre-release} Branch:'{branchName}' Sha:'{sha}' +1.2.3-beta645 Branch:'hotfix-foo' Sha:'a682956dccae752aa24597a0f5cd939f93614509' +``` ### Release branches - * May branch off from: develop - * Must merge back into: develop and main - * Branch naming convention: `release-{n}` eg `release-1.2` +* May branch off from: develop +* Must merge back into: develop and main +* Branch naming convention: `release-{n}` eg `release-1.2` `releaseVersion` => the SemVer extracted from `targetBranch.Name` `releaseTag` => the first version tag placed on the branch. Note that at least @@ -107,20 +113,22 @@ one version tag is required on the branch. The recommended initial tag is `{releaseVersion}.0-alpha1`. So for a branch named `release-1.2` the recommended tag would be `1.2.0-alpha1` -* major: `mergeVersion.Major` -* minor: `mergeVersion.Minor` -* patch: 0 -* pre-release: `{releaseTag.preRelease}.{n}` where n = 1 + the number of commits -since `releaseTag`. +* major: `mergeVersion.Major` +* minor: `mergeVersion.Minor` +* patch: 0 +* pre-release: `{releaseTag.preRelease}.{n}` where n = 1 + the number of commits + since `releaseTag`. So on a branch named `release-1.2` with a tag `1.2.0-alpha1` and 4 commits after that tag the version would be `1.2.0-alpha1.4` Long version: - {major}.{minor}.{patch}-{pre-release} Branch:'{branchName}' Sha:'{sha}' - 1.2.3-alpha2.4 Branch:'release-1.2' Sha:'a682956dccae752aa24597a0f5cd939f93614509' - 1.2.3-rc2 Branch:'release-1.2' Sha:'a682956dccae752aa24597a0f5cd939f93614509' +``` +{major}.{minor}.{patch}-{pre-release} Branch:'{branchName}' Sha:'{sha}' +1.2.3-alpha2.4 Branch:'release-1.2' Sha:'a682956dccae752aa24597a0f5cd939f93614509' +1.2.3-rc2 Branch:'release-1.2' Sha:'a682956dccae752aa24597a0f5cd939f93614509' +``` ### Feature branches @@ -132,16 +140,18 @@ Branch naming convention: anything except `main`, `develop`, `release-{n}`, or TODO: feature branches cannot start with a SemVer. to stop people from create branches named like "4.0.3" -* major: `mainMergeVersion.Major` -* minor: `mainMergeVersion.Minor + 1` (0 if the override above is used) -* patch: 0 -* pre-release: `alpha.feature-{n}` where n = First 8 characters of the commit -SHA of the first commit +* major: `mainMergeVersion.Major` +* minor: `mainMergeVersion.Minor + 1` (0 if the override above is used) +* patch: 0 +* pre-release: `alpha.feature-{n}` where n = First 8 characters of the commit + SHA of the first commit Long version: - {major}.{minor}.{patch}-{pre-release} Branch:'{branchName}' Sha:'{sha}' - 1.2.3-alpha.feature-a682956d Branch:'feature1' Sha:'a682956dccae752aa24597a0f5cd939f93614509' +``` +{major}.{minor}.{patch}-{pre-release} Branch:'{branchName}' Sha:'{sha}' +1.2.3-alpha.feature-a682956d Branch:'feature1' Sha:'a682956dccae752aa24597a0f5cd939f93614509' +``` ### Pull-request branches @@ -150,11 +160,11 @@ Must merge back into: `develop` Branch naming convention: anything except `main`, `develop`, `release-{n}`, or `hotfix-{n}`. Canonical branch name contains `/pull/`. -* major: `mainMergeVersion.Major` -* minor: `mainMergeVersion.Minor + 1` (0 if the override above is used) -* patch: 0 -* pre-release: `alpha.pull{n}` where n = the pull request number ('0' padded to -4 characters) +* major: `mainMergeVersion.Major` +* minor: `mainMergeVersion.Minor + 1` (0 if the override above is used) +* patch: 0 +* pre-release: `alpha.pull{n}` where n = the pull request number ('0' padded to + 4 characters) ## Nightly Builds diff --git a/docs/input/docs/learn/branching-strategies/githubflow/index.md b/docs/input/docs/learn/branching-strategies/githubflow/index.md index b6c5c73d7a..b0007f062c 100644 --- a/docs/input/docs/learn/branching-strategies/githubflow/index.md +++ b/docs/input/docs/learn/branching-strategies/githubflow/index.md @@ -10,19 +10,19 @@ are much better off with a simpler workflow. GitHubFlow is in a nutshell: -1. Update main to latest [upstream](/docs/learn/git-setup#upstream) code -1. Create a feature branch `git checkout -b myFeatureBranch` -1. Do the feature/work -1. Push feature branch to [origin](/docs/learn/git-setup#origin) -1. Create pull request from origin/ -> upstream/main -1. Review, fix raised comments, merge your PR or even better, get someone else to. +1. Update main to latest [upstream](/docs/learn/git-setup#upstream) code +2. Create a feature branch `git checkout -b myFeatureBranch` +3. Do the feature/work +4. Push feature branch to [origin](/docs/learn/git-setup#origin) +5. Create pull request from origin/ -> upstream/main +6. Review, fix raised comments, merge your PR or even better, get someone else to. -The main rule of GitHub Flow is that main should *always* be deployable. +The main rule of GitHub Flow is that main should _always_ be deployable. GitHub Flow allows and encourages [continuous delivery](/docs/reference/modes/continuous-delivery). ## Resources -- [GitHubFlow guide by GitHub](https://guides.github.com/introduction/flow/index.html) -- [GitHubFlow original blog post](http://scottchacon.com/2011/08/31/github-flow.html) -- [Phil Haack's (haacked) GitHubFlow aliases](http://haacked.com/archive/2014/07/28/github-flow-aliases/) -- [GitHubFlow vs GitFlow](http://lucamezzalira.com/2014/03/10/git-flow-vs-github-flow/) +* [GitHubFlow guide by GitHub](https://guides.github.com/introduction/flow/index.html) +* [GitHubFlow original blog post](http://scottchacon.com/2011/08/31/github-flow.html) +* [Phil Haack's (haacked) GitHubFlow aliases](http://haacked.com/archive/2014/07/28/github-flow-aliases/) +* [GitHubFlow vs GitFlow](http://lucamezzalira.com/2014/03/10/git-flow-vs-github-flow/) diff --git a/docs/input/docs/learn/branching-strategies/overview.md b/docs/input/docs/learn/branching-strategies/overview.md index aaaaee056d..aae1372e90 100644 --- a/docs/input/docs/learn/branching-strategies/overview.md +++ b/docs/input/docs/learn/branching-strategies/overview.md @@ -26,33 +26,33 @@ As mentioned above the GitVersion docs cover [GitHubFlow][githubflow] and GitHubFlow is a simple and powerful branching strategy. It is what GitHub uses and the branching strategy most open source projects use. - - [Mainline development][mainline] on `main` - - Work on [feature branches][feature-branches], merge into `main` via [pull - requests][pull-requests] - - Works well for [continuous delivery][continuous-delivery] - - Does not have a way to manage/maintain old releases - - Only allows working on a single release at a time +* [Mainline development][mainline] on `main`. +* Work on [feature branches][feature-branches], merge into `main` via a [pull + request][pull-request]. +* Works well for [continuous delivery][continuous-delivery]. +* Does not have a way to manage/maintain old releases. +* Only allows working on a single release at a time. ### Git Flow GitFlow is a more complex and complete branching strategy. It also gives much more control over when features and code is released. -- Development on `develop` branch -- `main` only contains *released* code -- Supports maintaining old releases (like nServiceBus, they support the last 3 -major versions with bug fixes and security updates) -- Supports development on multiple releases at one time +* Development on `develop` branch. +* `main` only contains _released_ code. +* Supports maintaining old releases (like nServiceBus, they support the last 3 + major versions with bug fixes and security updates). +* Supports development on multiple releases at one time. ## Choosing a branching strategy There are a few reasons you would pick GitFlow over GitHubFlow, they are: -1. You need to support multiple major versions at the same time -1. You need to work on multiple releases at the same time +1. You need to support multiple major versions at the same time. +2. You need to work on multiple releases at the same time. -- For example a new feature which will go in the next major version, while bug -fixes/smaller features are still going into the current release +* For example a new feature which will go in the next major version, while bug + fixes/smaller features are still going into the current release But if you do not have a good reason to go with GitFlow, then start with GitHubFlow. It is a far simpler model and if you end up needing GitFlow later, @@ -64,4 +64,4 @@ it is [easy to convert][converting-to-gitflow]. [gitflow]: /docs/learn/branching-strategies/gitflow [githubflow]: /docs/learn/branching-strategies/githubflow [mainline]: /docs/reference/modes/mainline -[pull-request]: /docs/learn/branching-strategies/gitflow/examples#pull-requests +[pull-request]: /docs/learn/branching-strategies/gitflow/examples#pull-request diff --git a/docs/input/docs/learn/dynamic-repositories.md b/docs/input/docs/learn/dynamic-repositories.md index 76dcbcf130..30497536e7 100644 --- a/docs/input/docs/learn/dynamic-repositories.md +++ b/docs/input/docs/learn/dynamic-repositories.md @@ -13,7 +13,7 @@ is built, the build process isn't aware of the Git repository at all - i.e _there is no Git Repository available locally to the build!_ For an example of one such circumstance, you can have a read about -[Team City's checkout mode: Automatically on Server](https://confluence.jetbrains.com/display/TCD7/VCS+Checkout+Mode) +[Team City's checkout mode: Automatically on Server][tc-checkout]. So `how is GitVersion meant to work in that scenario?` - well it needs to be able to obtain a copy of the Git repo on the fly and not rely on the build @@ -30,11 +30,11 @@ will assume there is already a ".git" folder present, and it will use it. To tell GitVersion.exe to obtain the repository on the fly, you need to call `GitVersion.exe` with the following arguments: -* /url [the url of your git repo] -* /u [authentication username] -* /p [authentication password] -* /b [branch name] -* /c [commit id] +* `/url [the url of your git repo]` +* `/u [authentication username]` +* `/p [authentication password]` +* `/b [branch name]` +* `/c [commit id]` Please note that these arguments are described when calling `GitVersion.exe /?`. @@ -56,3 +56,5 @@ Where `` is the `VCS root ID` as described on the Configuring GitVersion will checkout the dynamic repository into the %tmp% directory and just keep that dynamic repository up to date, this saves recloning the repository every build. + +[tc-checkout]: https://confluence.jetbrains.com/display/TCD7/VCS+Checkout+Mode diff --git a/docs/input/docs/learn/faq.md b/docs/input/docs/learn/faq.md index 0c678e6088..e09e74db40 100644 --- a/docs/input/docs/learn/faq.md +++ b/docs/input/docs/learn/faq.md @@ -6,7 +6,7 @@ Title: FAQ ## Why is my version not incrementing? GitVersion calculates the semantic version, this will only change once per -*release*. Read more at [version increments](/docs/reference/version-increments) +_release_. Read more at [version increments](/docs/reference/version-increments) ## I'm using Octopus deploy @@ -32,7 +32,7 @@ Read more at [intro to semver](/docs/learn/intro-to-semver) ## I can't use the build number for NuGet If you have used NuGet you would notice the versions above are not compatible -with NuGet. GitVersion solves this by providing *variables*. +with NuGet. GitVersion solves this by providing _variables_. What you have seen above is the **SemVer** variable. You can use the **NuGetVersion** variable to have the version formatted in a NuGet compatible diff --git a/docs/input/docs/learn/git-setup.md b/docs/input/docs/learn/git-setup.md index bb9cc81d73..4559a5bc0c 100644 --- a/docs/input/docs/learn/git-setup.md +++ b/docs/input/docs/learn/git-setup.md @@ -13,4 +13,4 @@ newly created feature branch ### origin -`origin` should point to your *fork*. +`origin` should point to your _fork_. diff --git a/docs/input/docs/learn/how-it-works.md b/docs/input/docs/learn/how-it-works.md index a06f80c6ae..02f00efc1d 100644 --- a/docs/input/docs/learn/how-it-works.md +++ b/docs/input/docs/learn/how-it-works.md @@ -9,24 +9,25 @@ class which calculated the version for that branch type. v3 is driven by [configuration](/docs/reference/configuration), meaning most of the behaviors in GitVersion can be tweaked to work the way you want. This also makes -it *much* more predictable and easier to diagnose when odd things are happening. +it _much_ more predictable and easier to diagnose when odd things are happening. ## Architecture + GitVersion has three distinct steps for calculating versions in v3. -1. If the current commit is tagged, the tag is used and build metadata -(excluding commit count) is added. The other two steps will not execute. -2. A set of strategies are evaluated to decide on the base version and some -metadata about that version. These strategies include HighestReachableTag, -NextVersionInConfig, MergedBranchWithVersion, VersionInBranchName etc. -3. The highest base version is selected, using that base version as the new -version is calculated. +1. If the current commit is tagged, the tag is used and build metadata + (excluding commit count) is added. The other two steps will not execute. +2. A set of strategies are evaluated to decide on the base version and some + metadata about that version. These strategies include HighestReachableTag, + NextVersionInConfig, MergedBranchWithVersion, VersionInBranchName etc. +3. The highest base version is selected, using that base version as the new + version is calculated. Visually it looks something like this: -![Version Calculation](http://www.plantuml.com:80/plantuml/png/fLCxJyCm4DxzAsuib4P914i69De1CS38Vd6kYIN7ZcodK8aVp-KX6Y2fKCbY9NV-7lVb2WoOeoVOMRDNfH0lz1vUoNbbpGwrR3K6ws1p3rlk-bN8u972f2AC3GHEbLN8m1D1Jjg-mPuXAZvx9kL1ZW1KY5dOZczMI0Pf54VnHtf7jpaAWJg0sW-uXw4PK3Eb1sMaevfCW6i1_0m6po1l7HfPJUxvu5XYUOHLWq5MLptCudmMK9--u5glJ0dIEaVo1Dw3JgVM6Km4cM9mzyrQXHuQHnj7chhl0JcnIrHjno1wiWtgfi8eWVK_7OQAmBHrJWvORFVM2PmrE7AcWZGh-Lj0FvptVvLiUPnCdG_XhNhOov9wQ1fzv7nw5S5EwSvw6CDQNfnMwUAP0XQyQpj70nkx3Nn3p5NFY9IshbNWepKi8ublWFiSPkC0ee8El75Dv5aOxqZQBScbWpWn0Pe2wb6aM1p4Eea_0G00) +![Version Calculation](http://www.plantuml.com:80/plantuml/png/fLCxJyCm4DxzAsuib4P914i69De1CS38Vd6kYIN7ZcodK8aVp-KX6Y2fKCbY9NV-7lVb2WoOeoVOMRDNfH0lz1vUoNbbpGwrR3K6ws1p3rlk-bN8u972f2AC3GHEbLN8m1D1Jjg-mPuXAZvx9kL1ZW1KY5dOZczMI0Pf54VnHtf7jpaAWJg0sW-uXw4PK3Eb1sMaevfCW6i1\_0m6po1l7HfPJUxvu5XYUOHLWq5MLptCudmMK9--u5glJ0dIEaVo1Dw3JgVM6Km4cM9mzyrQXHuQHnj7chhl0JcnIrHjno1wiWtgfi8eWVK\_7OQAmBHrJWvORFVM2PmrE7AcWZGh-Lj0FvptVvLiUPnCdG_XhNhOov9wQ1fzv7nw5S5EwSvw6CDQNfnMwUAP0XQyQpj70nkx3Nn3p5NFY9IshbNWepKi8ublWFiSPkC0ee8El75Dv5aOxqZQBScbWpWn0Pe2wb6aM1p4Eea\_0G00) -[Edit Diagram](http://www.plantuml.com/plantuml/form?url=http://www.plantuml.com/plantuml/png/fLCxJyCm4DxzAsuib4P914i69De1CS38Vd6kYIN7ZcodK8aVp-KX6Y2fKCbY9NV-7lVb2WoOeoVOMRDNfH0lz1vUoNbbpGwrR3K6ws1p3rlk-bN8u972f2AC3GHEbLN8m1D1Jjg-mPuXAZvx9kL1ZW1KY5dOZczMI0Pf54VnHtf7jpaAWJg0sW-uXw4PK3Eb1sMaevfCW6i1_0m6po1l7HfPJUxvu5XYUOHLWq5MLptCudmMK9--u5glJ0dIEaVo1Dw3JgVM6Km4cM9mzyrQXHuQHnj7chhl0JcnIrHjno1wiWtgfi8eWVK_7OQAmBHrJWvORFVM2PmrE7AcWZGh-Lj0FvptVvLiUPnCdG_XhNhOov9wQ1fzv7nw5S5EwSvw6CDQNfnMwUAP0XQyQpj70nkx3Nn3p5NFY9IshbNWepKi8ublWFiSPkC0ee8El75Dv5aOxqZQBScbWpWn0Pe2wb6aM1p4Eea_0G00) +[Edit Diagram](http://www.plantuml.com/plantuml/form?url=http://www.plantuml.com/plantuml/png/fLCxJyCm4DxzAsuib4P914i69De1CS38Vd6kYIN7ZcodK8aVp-KX6Y2fKCbY9NV-7lVb2WoOeoVOMRDNfH0lz1vUoNbbpGwrR3K6ws1p3rlk-bN8u972f2AC3GHEbLN8m1D1Jjg-mPuXAZvx9kL1ZW1KY5dOZczMI0Pf54VnHtf7jpaAWJg0sW-uXw4PK3Eb1sMaevfCW6i1\_0m6po1l7HfPJUxvu5XYUOHLWq5MLptCudmMK9--u5glJ0dIEaVo1Dw3JgVM6Km4cM9mzyrQXHuQHnj7chhl0JcnIrHjno1wiWtgfi8eWVK\_7OQAmBHrJWvORFVM2PmrE7AcWZGh-Lj0FvptVvLiUPnCdG_XhNhOov9wQ1fzv7nw5S5EwSvw6CDQNfnMwUAP0XQyQpj70nkx3Nn3p5NFY9IshbNWepKi8ublWFiSPkC0ee8El75Dv5aOxqZQBScbWpWn0Pe2wb6aM1p4Eea\_0G00) **\*** Some strategies allow the version to be incremented, others don't. More info below. @@ -37,29 +38,29 @@ simply to show what happens if the check is true. Currently we have the following strategies: -- `HighestTagBaseVersionStrategy` - Finds the highest reachable tag from the -current branch -- `VersionInBranchBaseVersionStrategy` - Extracts version information from the -branch name (e.g., `release/3.0.0` will find `3.0.0`) -- `ConfigNextVersionBaseVersionStrategy` - Returns the version from the -GitVersion.yaml file -- `MergeMessageBaseVersionStrategy` - Finds version numbers from merge messages -(e.g., `Merge 'release/3.0.0' into 'main'` will return `3.0.0`) -- `FallbackBaseVersionStrategy` - Always returns 0.1.0 for new repositories +* `HighestTagBaseVersionStrategy` - Finds the highest reachable tag from the + current branch +* `VersionInBranchBaseVersionStrategy` - Extracts version information from the + branch name (e.g., `release/3.0.0` will find `3.0.0`) +* `ConfigNextVersionBaseVersionStrategy` - Returns the version from the + GitVersion.yaml file +* `MergeMessageBaseVersionStrategy` - Finds version numbers from merge messages + (e.g., `Merge 'release/3.0.0' into 'main'` will return `3.0.0`) +* `FallbackBaseVersionStrategy` - Always returns 0.1.0 for new repositories Each strategy needs to return an instance of `BaseVersion` which has the following properties: -- `Source` - Description of the source (e.g., `Merge message 'Merge 'release/3.0.0' into 'main'`) -- `ShouldIncrement` - Some strategies should have the version incremented, -others do not (e.g., `ConfigNextVersionBaseVersionStrategy` returns false, -`HighestTagBaseVersionStrategy` returns true) -- `SemanticVersion` - SemVer of the base version strategy -- `BaseVersionSource` - SHA hash of the source. Commits will be counted from -this hash. Can be null (e.g., `ConfigNextVersionBaseVersionStrategy` returns -null). -- `BranchNameOverride` - When `useBranchName` or `{BranchName}` is used in the -tag configuration, this allows the branch name to be changed by a base version. -`VersionInBranchBaseVersionStrategy` uses this to strip out anything before the -first `-` or `/.` so `foo` ends up being evaluated as `foo`. If in doubt, just -use null. +* `Source` - Description of the source (e.g., `Merge message 'Merge 'release/3.0.0' into 'main'`) +* `ShouldIncrement` - Some strategies should have the version incremented, + others do not (e.g., `ConfigNextVersionBaseVersionStrategy` returns false, + `HighestTagBaseVersionStrategy` returns true) +* `SemanticVersion` - SemVer of the base version strategy +* `BaseVersionSource` - SHA hash of the source. Commits will be counted from + this hash. Can be null (e.g., `ConfigNextVersionBaseVersionStrategy` returns + null). +* `BranchNameOverride` - When `useBranchName` or `{BranchName}` is used in the + tag configuration, this allows the branch name to be changed by a base version. + `VersionInBranchBaseVersionStrategy` uses this to strip out anything before the + first `-` or `/.` so `foo` ends up being evaluated as `foo`. If in doubt, just + use null. diff --git a/docs/input/docs/learn/intro-to-semver.md b/docs/input/docs/learn/intro-to-semver.md index f3fc720178..68f6679bb9 100644 --- a/docs/input/docs/learn/intro-to-semver.md +++ b/docs/input/docs/learn/intro-to-semver.md @@ -6,6 +6,7 @@ Title: Intro to SemVer For the official Semantic Version docs head to [semver.org](http://semver.org). This is just a quick guide for people getting started and how SemVer is used in GitVersion. ## Why SemVer? + The quick reason is to solve two problems: Version Lock and Version promiscuity. To explain these things, let's imagine the scenario where I am building an app which authenticates with Facebook (v1.0.0) and Twitter (v1.0.0). Both the Facebook and Twitter libraries use a JSON library (v1.0.0). Version lock is when we rely on absolute versions, both **FacebookApi** and **TwitterApi** rely on _v1.0.0_ of **JsonLibrary**. **JsonLibrary** _v1.1.0_ comes out and **FacebookApi** decides to upgrade. If our dependency management relies on exact versions we cannot upgrade our application to use **FacebookApi** because **TwitterApi** references _v1.0.0_. The only way we can upgrade is if **TwitterApi** also upgrades to _v1.1.0_ of **JsonLibrary**. @@ -14,18 +15,19 @@ Version Promiscuity is the opposite problem, **JsonLibrary** releases _v1.1.0_ w SemVer introduces conventions about breaking changes into our version numbers so we can safely upgrade dependencies without fear of unexpected, breaking changes while still allowing us to upgrade downstream libraries to get new features and bug fixes. The convention is quite simple: -* `{major}.{minor}.{patch}-{tag}+{buildmetadata}` -* `{major}` is only incremented if the release has breaking changes (includes bug fixes which have breaking behavioural changes -* `{minor}` is incremented if the release has new non-breaking features -* `{patch}` is incremented if the release only contains non-breaking bug fixes -* `{tag}` is optional and denotes a pre-release of the version preceding -* `{buildmetadata}` is optional and contains additional information about the version, but **does not affect** the semantic version preceding it. +* `{major}.{minor}.{patch}-{tag}+{buildmetadata}` +* `{major}` is only incremented if the release has breaking changes (includes bug fixes which have breaking behavioural changes +* `{minor}` is incremented if the release has new non-breaking features +* `{patch}` is incremented if the release only contains non-breaking bug fixes +* `{tag}` is optional and denotes a pre-release of the version preceding +* `{buildmetadata}` is optional and contains additional information about the version, but **does not affect** the semantic version preceding it. Only one number should be incremented per release, and all lower parts should be reset to 0 (if `{major}` is incremented, then `{minor}` and `{patch}` should become 0). For a more complete explanation check out [semver.org](http://semver.org) which is the official spec. Remember this is a brief introduction and does not cover all parts of semantic versioning, just the important parts to get started. ## SemVer in GitVersion -GitVersion makes it easy to follow semantic versioning in your library by automatically calculating the next semantic version which your library/application is likely to use. In [GitFlow](https://www.atlassian.com/git/tutorials/comparing-workflows/gitflow-workflow/) the develop branch will bump the *minor* when main is tagged, while [GitHubFlow](https://guides.github.com/introduction/flow/) will bump the *patch*. + +GitVersion makes it easy to follow semantic versioning in your library by automatically calculating the next semantic version which your library/application is likely to use. In [GitFlow](https://www.atlassian.com/git/tutorials/comparing-workflows/gitflow-workflow/) the develop branch will bump the _minor_ when main is tagged, while [GitHubFlow](https://guides.github.com/introduction/flow/) will bump the _patch_. Because one size does not always fit all, GitVersion provides many [Variables](/docs/reference/variables) for you to use which contain different variations of the version. For example SemVer will be in the format `{major}.{minor}.{patch}-{tag}`, but `FullSemVer` will also include build metadata: `{major}.{minor}.{patch}-{tag}+{buildmetadata}` diff --git a/docs/input/docs/learn/who.md b/docs/input/docs/learn/who.md index 4a93c82eaf..6431650b8a 100644 --- a/docs/input/docs/learn/who.md +++ b/docs/input/docs/learn/who.md @@ -7,18 +7,18 @@ Various people are actively using GitVersion, and taking advantage of the automatic generation of their version numbers. Here is a list of applications that we know about today. -* [Catel](https://github.com/catel/catel) -* [ChocolateyGUI](https://github.com/chocolatey/ChocolateyGUI) -* [GitLink](https://github.com/GitTools/GitLink) -* [OctopusDeploy](https://github.com/OctopusDeploy) -* [Orc.* packages](https://github.com/wildgums?query=orc) -* [Orchestra](https://github.com/wildgums/orchestra) -* [Pomona](http://pomona.io/) -* [Shouldly](https://github.com/shouldly/shouldly) -* [Akavache](https://github.com/akavache/akavache) -* [Splat](https://github.com/paulcbetts/splat) -* [ReactiveUI](https://github.com/reactiveui/reactiveui) -* [Uno Platform](https://platform.uno/) +* [Catel](https://github.com/catel/catel) +* [ChocolateyGUI](https://github.com/chocolatey/ChocolateyGUI) +* [GitLink](https://github.com/GitTools/GitLink) +* [OctopusDeploy](https://github.com/OctopusDeploy) +* [Orc.\* packages](https://github.com/wildgums?query=orc) +* [Orchestra](https://github.com/wildgums/orchestra) +* [Pomona](http://pomona.io/) +* [Shouldly](https://github.com/shouldly/shouldly) +* [Akavache](https://github.com/akavache/akavache) +* [Splat](https://github.com/paulcbetts/splat) +* [ReactiveUI](https://github.com/reactiveui/reactiveui) +* [Uno Platform](https://platform.uno/) If you are using GitVersion in your projects, and you are not listed above, please feel free to add a link to your project. diff --git a/docs/input/docs/learn/why.md b/docs/input/docs/learn/why.md index 188ab2431c..8d09611a5b 100644 --- a/docs/input/docs/learn/why.md +++ b/docs/input/docs/learn/why.md @@ -10,28 +10,28 @@ transportable between projects. It solves: -- Rebuilding tags always produces the same version -- Not having to rebuild to increment versions -- Not duplicating version information in multiple places (branch release/2.0.0 - already has the version in it, why do I need to change something else) -- Each branch calculates its SemVer and versions flow between branches when - they are merged -- Pull requests produce unique pre-release version numbers -- NuGet semver issues -- Build server integration -- Updating assembly info -- And a whole lot of edge cases you don't want to think about +* Rebuilding tags always produces the same version +* Not having to rebuild to increment versions +* Not duplicating version information in multiple places (branch release/2.0.0 + already has the version in it, why do I need to change something else) +* Each branch calculates its SemVer and versions flow between branches when + they are merged +* Pull requests produce unique pre-release version numbers +* NuGet semver issues +* Build server integration +* Updating assembly info +* And a whole lot of edge cases you don't want to think about ## Advantages vs other approaches ### Version.txt/Version in build script -- With version.txt/build script, after the release you need to do an additional commit to bump the version -- After tagging a release, the next build will still be the same version +* With version.txt/build script, after the release you need to do an additional commit to bump the version +* After tagging a release, the next build will still be the same version ### Build Server versioning -- Cannot have different version numbers on different branches -- Rebuilding will result in a different build number (if using an auto incrementing number in the version) -- Need to login to the build server to change version number -- Only build administrators can change the version number +* Cannot have different version numbers on different branches +* Rebuilding will result in a different build number (if using an auto incrementing number in the version) +* Need to login to the build server to change version number +* Only build administrators can change the version number diff --git a/docs/input/docs/reference/build-servers/appveyor.md b/docs/input/docs/reference/build-servers/appveyor.md index 6d4728fb92..15904e70e1 100644 --- a/docs/input/docs/reference/build-servers/appveyor.md +++ b/docs/input/docs/reference/build-servers/appveyor.md @@ -7,8 +7,8 @@ Description: Details on the AppVeyor support in GitVersion AppVeyor is the first build server which has a setup helper built into `GitVersion init`. -1. Run `GitVersion init` -2. Choose `Setup build scripts` (currently option 7, but that could change) -3. Choose `AppVeyor` -4. Follow the prompts to generate an AppVeyor.yml file which works nicely with - GitVersion +1. Run `GitVersion init` +2. Choose `Setup build scripts` (currently option 7, but that could change) +3. Choose `AppVeyor` +4. Follow the prompts to generate an AppVeyor.yml file which works nicely with + GitVersion diff --git a/docs/input/docs/reference/build-servers/azure-devops.md b/docs/input/docs/reference/build-servers/azure-devops.md index 659a4dc0f9..de649d9308 100644 --- a/docs/input/docs/reference/build-servers/azure-devops.md +++ b/docs/input/docs/reference/build-servers/azure-devops.md @@ -17,27 +17,27 @@ task into your TFS or Azure DevOps Pipeline instance. ### Using GitVersion with the MSBuild Task NuGet Package -1. Add the [GitVersionTask](https://www.nuget.org/packages/GitVersionTask/) -NuGet package to your projects. +1. Add the [GitVersionTask](https://www.nuget.org/packages/GitVersionTask/) + NuGet package to your projects. See [MSBuild Task](/docs/usage/msbuild) for further instructions how to use the MS Build Task. ### Using GitVersion with the Command Line build step -1. Make sure to have GitVersion.exe under version control. There exists also a -[Chocolatey package](https://chocolatey.org/packages/GitVersion.Portable) for -installing GitVersion.exe on build agents. -2. Add a Command Line build step to your build definition. You'll probably want -to drag the task to be at or near the top to ensure it executes before your -other build steps. -3. Set the Tool parameter to `\GitVersion.exe`. -4. Set the Arguments parameter to `/output buildserver /nofetch`. -5. If you want the GitVersionTask to update AssemblyInfo files add -`updateAssemblyInfo true` to the Arguments parameter. -6. If you want to update the build number you need to send a -[logging command](https://github.com/Microsoft/azure-pipelines-tasks/blob/main/docs/authoring/commands.md) -to TFS. +1. Make sure to have GitVersion.exe under version control. There exists also a + [Chocolatey package](https://chocolatey.org/packages/GitVersion.Portable) for + installing GitVersion.exe on build agents. +2. Add a Command Line build step to your build definition. You'll probably want + to drag the task to be at or near the top to ensure it executes before your + other build steps. +3. Set the Tool parameter to `\GitVersion.exe`. +4. Set the Arguments parameter to `/output buildserver /nofetch`. +5. If you want the GitVersionTask to update AssemblyInfo files add + `updateAssemblyInfo true` to the Arguments parameter. +6. If you want to update the build number you need to send a + [logging command](https://github.com/Microsoft/azure-pipelines-tasks/blob/main/docs/authoring/commands.md) + to TFS. ### Using the custom GitVersion build step @@ -48,24 +48,24 @@ to TFS. For Visual Studio Team Service or TFS 2015 Update 2 or higher it is recommended to install the GitVersion extension: -1. Install the -[GitVersion Extension](https://marketplace.visualstudio.com/items?itemName=gittools.usegitversion). +1. Install the + [GitVersion Extension](https://marketplace.visualstudio.com/items?itemName=gittools.usegitversion). ##### Manually installing/updating the custom build step If you run TFS 2015 RTM or Update 1 or don't want to install the GitVersion extension you can install the build task manually: -1. Install the `tfx` command line tool as shown [here](https://github.com/Microsoft/tfs-cli/blob/main/README.md#install). -2. For TFS 2015 On-Prem configure Basic Authentication in TFS as shown [here](https://github.com/Microsoft/tfs-cli/blob/main/docs/configureBasicAuth.md). -3. Download the GitVersion TFS build task from the latest release on the -[GitVersion releases page](https://github.com/GitTools/GitVersion/releases) and -unzip. -4. Run `tfx login` as shown [here](https://github.com/Microsoft/tfs-cli/blob/main/README.md#login). -5. From the directory outside of where you unzipped the task, run -`tfx build tasks upload --task-path .\GitVersionVsixTask --overwrite` where -GitVersionVsixTask is the directory containing the files. -6. It should successfully install. +1. Install the `tfx` command line tool as shown [here](https://github.com/Microsoft/tfs-cli/blob/main/README.md#install). +2. For TFS 2015 On-Prem configure Basic Authentication in TFS as shown [here](https://github.com/Microsoft/tfs-cli/blob/main/docs/configureBasicAuth.md). +3. Download the GitVersion TFS build task from the latest release on the + [GitVersion releases page](https://github.com/GitTools/GitVersion/releases) and + unzip. +4. Run `tfx login` as shown [here](https://github.com/Microsoft/tfs-cli/blob/main/README.md#login). +5. From the directory outside of where you unzipped the task, run + `tfx build tasks upload --task-path .\GitVersionVsixTask --overwrite` where + GitVersionVsixTask is the directory containing the files. +6. It should successfully install. #### Using the GitVersion custom build step @@ -151,22 +151,22 @@ variables. #### Known limitations -* If you are using on premises TFS, make sure you are using at least -**TFS 2015 Update 1**, otherwise a few things will not work. -* Installing the extension on an on premise TFS requires at least TFS 2015 -Update 2. -* You need to make sure that all tags are fetched for the Git repository, -otherwise you may end with wrong versions (e.g. `FullSemVer` like `1.2.0+5` -instead of `1.2.0` for tagged releases) Just checking the `Clean Repository` -check box in the build definition settings might not be enough since this will -run a `git clean -fdx/reset --hard` without fetching all tags later. You can -force deletion of the whole folder and a re-clone containing all tags by -settings the variable `Build.Clean` to `all`. This will take more time during -build but makes sure that all tags are fetched. In the future it is planned to -allow using `git.exe` instead of current `libgit2sharp` for syncing the repos -which might allow other possibilities to solve this issue. For details see this -[GitHub issue](https://github.com/Microsoft/azure-pipelines-tasks/issues/1218). -* If running a build for a certain commit (through passing the commit SHA while -queueing the build) all tags from the repository will be fetched, even the ones -newer than the commit. This can lead to different version numbers while -re-running historical builds. +* If you are using on premises TFS, make sure you are using at least + **TFS 2015 Update 1**, otherwise a few things will not work. +* Installing the extension on an on premise TFS requires at least TFS 2015 + Update 2. +* You need to make sure that all tags are fetched for the Git repository, + otherwise you may end with wrong versions (e.g. `FullSemVer` like `1.2.0+5` + instead of `1.2.0` for tagged releases) Just checking the `Clean Repository` + check box in the build definition settings might not be enough since this will + run a `git clean -fdx/reset --hard` without fetching all tags later. You can + force deletion of the whole folder and a re-clone containing all tags by + settings the variable `Build.Clean` to `all`. This will take more time during + build but makes sure that all tags are fetched. In the future it is planned to + allow using `git.exe` instead of current `libgit2sharp` for syncing the repos + which might allow other possibilities to solve this issue. For details see this + [GitHub issue](https://github.com/Microsoft/azure-pipelines-tasks/issues/1218). +* If running a build for a certain commit (through passing the commit SHA while + queueing the build) all tags from the repository will be fetched, even the ones + newer than the commit. This can lead to different version numbers while + re-running historical builds. diff --git a/docs/input/docs/reference/build-servers/bamboo.md b/docs/input/docs/reference/build-servers/bamboo.md index 7de009a762..b693c5e5bf 100644 --- a/docs/input/docs/reference/build-servers/bamboo.md +++ b/docs/input/docs/reference/build-servers/bamboo.md @@ -35,6 +35,6 @@ sed -i '1d;$ d;s/ //;s/"//g;s/,//;s/:/=/' gitversion.txt **Required Properties** -- __Path to properties file__: gitversion.txt -- __Namespace__: GitVersion -- __Scope of the Variables__: Result +* **Path to properties file**: gitversion.txt +* **Namespace**: GitVersion +* **Scope of the Variables**: Result diff --git a/docs/input/docs/reference/build-servers/continua.md b/docs/input/docs/reference/build-servers/continua.md index a1c1affd29..0c53f9ae79 100644 --- a/docs/input/docs/reference/build-servers/continua.md +++ b/docs/input/docs/reference/build-servers/continua.md @@ -12,47 +12,47 @@ This guide assumes a few variables are present in the configuration. Note that this example uses `Catel` as repository name, but it should be replaced by the name of the repository where GitVersion is running against. -* RepositoryBranchName => \$Source.Catel.BranchName\$ -* RepositoryCommitId => \$Source.Catel.LatestChangeset.Id\$ -* RepositoryName => Catel -* RepositoryName => \$Source.Catel.Path\$ -* RepositoryUrl => \$Source.Catel.Url\$ +* RepositoryBranchName => $Source.Catel.BranchName$ +* RepositoryCommitId => $Source.Catel.LatestChangeset.Id$ +* RepositoryName => Catel +* RepositoryName => $Source.Catel.Path$ +* RepositoryUrl => $Source.Catel.Url$ It also requires a few variables which will automatically be filled by GitVersion. The example below are just a few, any of the GitVersion variables written to the output can be used. -* GitVersion_FullSemVer -* GitVersion_MajorMinorPatch -* GitVersion_NuGetVersion +* GitVersion_FullSemVer +* GitVersion_MajorMinorPatch +* GitVersion_NuGetVersion You also need to add a property collector for the agents to detect the GitVersion tool on the agents: -* Namespace => GitVersion -* Run On => Agent -* Type => Path Finder Plugin -* Property Name => Path -* Executable => GitVersion.exe -* Search paths => your installation folder (e.g. `C:\Tools\GitVersion` or if you -are using Chocolatey `C:\ProgramData\chocolatey\lib\GitVersion.Portable\tools`) +* Namespace => GitVersion +* Run On => Agent +* Type => Path Finder Plugin +* Property Name => Path +* Executable => GitVersion.exe +* Search paths => your installation folder (e.g. `C:\Tools\GitVersion` or if you + are using Chocolatey `C:\ProgramData\chocolatey\lib\GitVersion.Portable\tools`) ## Basic Usage To run GitLink inside [Continua CI](https://www.finalbuilder.com/continua-ci), follow the steps below: -* Add a new `Execute Program` step to a stage -* In the `Execute Program` tab, set the following values: - * Executable path: $Agent.GitVersion.Path$ - * Working directory: %RepositoryPath% -* In the `Arguments` tab, set the following values: - * Arguments: /url %RepositoryUrl% /b %RepositoryBranchName% /c %RepositoryCommitId% /output buildserver -* In the `Options` tab, set the following values: - * Wait for completion: checked - * Log output: checked - * Check program exit code: checked - * Exit code must be: equal to - * Exit code: 0 +* Add a new `Execute Program` step to a stage +* In the `Execute Program` tab, set the following values: + * Executable path: $Agent.GitVersion.Path$ + * Working directory: %RepositoryPath% +* In the `Arguments` tab, set the following values: + * Arguments: /url %RepositoryUrl% /b %RepositoryBranchName% /c %RepositoryCommitId% /output buildserver +* In the `Options` tab, set the following values: + * Wait for completion: checked + * Log output: checked + * Check program exit code: checked + * Exit code must be: equal to + * Exit code: 0 Now GitVersion will automatically run and fill the `GitVersion_` variables. diff --git a/docs/input/docs/reference/build-servers/jenkins.md b/docs/input/docs/reference/build-servers/jenkins.md index 1ec139c29e..d1decd9bb3 100644 --- a/docs/input/docs/reference/build-servers/jenkins.md +++ b/docs/input/docs/reference/build-servers/jenkins.md @@ -6,15 +6,15 @@ Description: Details on the Jenkins support in GitVersion ## SCM Settings -When setting up a Jenkins project for GitVersion, it is necessary to add a few *Behaviors* to the SCM settings to ensure that GitVersion has enough information: +When setting up a Jenkins project for GitVersion, it is necessary to add a few _Behaviors_ to the SCM settings to ensure that GitVersion has enough information: -* Advanced clone behaviors - * Enable `Fetch tags` - * Enable `Honor refspec on intial clone` -* Check out to matching local branch -* Prune stale remote-tracking branches -* Specify ref specs - * Ref Spec: `+refs/heads/*:refs/remotes/@{remote}/*` +* Advanced clone behaviors + * Enable `Fetch tags` + * Enable `Honor refspec on intial clone` +* Check out to matching local branch +* Prune stale remote-tracking branches +* Specify ref specs + * Ref Spec: `+refs/heads/*:refs/remotes/@{remote}/*` ## Usage @@ -29,15 +29,15 @@ Jenkins plugins exist that provide this functionality. Of these plugins To inject the GitVersion variables as environment variables for a build job using [EnvInject], do the following: -1. Add an **Execute Windows batch command** build step with *Command*: +1. Add an **Execute Windows batch command** build step with _Command_: `gitversion /output buildserver` -1. Add an **Inject environment variables** build step and use value -'gitversion.properties' for the *Properties File Path* parameter +2. Add an **Inject environment variables** build step and use value + 'gitversion.properties' for the _Properties File Path_ parameter This assumes GitVersion.exe is available on the command line. You can verify correct injection of environment variables by adding another -"Execute Windows batch command" build step with the following *Command*: +"Execute Windows batch command" build step with the following _Command_: ```shell @echo Retrieving some GitVersion environment variables: @@ -54,15 +54,18 @@ For pipeline projects, GitVersion variables can be accessed by reading the `gitv In a pipeline stage: -1. Run GitVersion with the flag for *buildserver* output (this only works when run from Jenkins, specifically when the `JENKINS_URL` environment variable is defined): +1. Run GitVersion with the flag for _buildserver_ output (this only works when run from Jenkins, specifically when the `JENKINS_URL` environment variable is defined): + ```groovy sh 'gitversion /output buildserver'` ``` -2. Add a script block to read the properties file, assign environment variables as needed: + +2. Add a script block to read the properties file, assign environment variables as needed: + ```groovy script { def props = readProperties file: 'gitversion.properties' - + env.GitVersion_SemVer = props.GitVersion_SemVer env.GitVersion_BranchName = props.GitVersion_BranchName env.GitVersion_AssemblySemVer = props.GitVersion_AssemblySemVer diff --git a/docs/input/docs/reference/build-servers/myget.md b/docs/input/docs/reference/build-servers/myget.md index be7f98313d..f339a4aad6 100644 --- a/docs/input/docs/reference/build-servers/myget.md +++ b/docs/input/docs/reference/build-servers/myget.md @@ -7,18 +7,18 @@ Description: Details on the MyGet support in GitVersion MyGet Build Services has built-in support for GitVersion and is encouraging you to leverage GitVersion + GitFlow to produce Semantically Versioned packages. -* Create a [custom build script](http://docs.myget.org/docs/reference/custom-build-scripts): -we advise to run a tool like GitVersion in a *pre-build* script, so that it can -set additional environment variables for the actual build script. MyGet -[by convention](http://docs.myget.org/docs/reference/build-services#Pre-_and_post-build_steps) -automatically picks up any of the following file names as pre-build script: - * `pre-build.(bat|cmd|ps1)` - * `pre-myget.(bat|cmd|ps1)` -* Run `GitVersion /output buildserver`: this will cause MyGet Build Services to -set the current `%PackageVersion%` value to the NuGet-compatible SemVer -generated by GitVersion and apply this [MyGet Environment Variable](http://docs.myget.org/docs/reference/build-services#Available_Environment_Variables) -wherever it is used during the build process. -* Ensure the build script has been pushed to your source repository root. Done :) +* Create a [custom build script](http://docs.myget.org/docs/reference/custom-build-scripts): + we advise to run a tool like GitVersion in a _pre-build_ script, so that it can + set additional environment variables for the actual build script. MyGet + [by convention](http://docs.myget.org/docs/reference/build-services#Pre-\_and_post-build_steps) + automatically picks up any of the following file names as pre-build script: + * `pre-build.(bat|cmd|ps1)` + * `pre-myget.(bat|cmd|ps1)` +* Run `GitVersion /output buildserver`: this will cause MyGet Build Services to + set the current `%PackageVersion%` value to the NuGet-compatible SemVer + generated by GitVersion and apply this [MyGet Environment Variable](http://docs.myget.org/docs/reference/build-services#Available_Environment_Variables) + wherever it is used during the build process. +* Ensure the build script has been pushed to your source repository root. Done :) :::{.alert .alert-info} **Note** diff --git a/docs/input/docs/reference/build-servers/octopus-deploy.md b/docs/input/docs/reference/build-servers/octopus-deploy.md index 160cc349a7..f47472492d 100644 --- a/docs/input/docs/reference/build-servers/octopus-deploy.md +++ b/docs/input/docs/reference/build-servers/octopus-deploy.md @@ -7,17 +7,17 @@ Description: Details on the Octopus Deploy support in GitVersion While not a build server, there are a few things to consider when using Octopus Deploy with GitVersion. - GitVersion follows [continuous delivery][continuous-delivery] versioning by - default. This means builds will keep producing *the same version* with just - metadata differing. For example, when you start a new release (say `1.0.0`) - with git flow, the branch will start with a semver like `1.0.0-beta.1+0`, and - the Octopus NuGet package will have a version of `1.0.0-beta0001`. As you - commit changes to this release branch the *metadata* of the semver will - increase like so: `1.0.0-beta.1+1`, `1.0.0-beta.1+2`, etc. However, the version - of the corresponding Octopus NuGet package will retain the *same* - `1.0.0-beta0001` version you started with. The problem is Octopus Deploy will - prevent you from deploying these revisions because it sees the same NuGet - package version and thinks nothing has changed. +GitVersion follows [continuous delivery][continuous-delivery] versioning by +default. This means builds will keep producing _the same version_ with just +metadata differing. For example, when you start a new release (say `1.0.0`) +with git flow, the branch will start with a semver like `1.0.0-beta.1+0`, and +the Octopus NuGet package will have a version of `1.0.0-beta0001`. As you +commit changes to this release branch the _metadata_ of the semver will +increase like so: `1.0.0-beta.1+1`, `1.0.0-beta.1+2`, etc. However, the version +of the corresponding Octopus NuGet package will retain the _same_ +`1.0.0-beta0001` version you started with. The problem is Octopus Deploy will +prevent you from deploying these revisions because it sees the same NuGet +package version and thinks nothing has changed. Because Octopus Deploy uses NuGet like this you cannot continue to push revisions in this manner without some intervention (or changes to GitVersion's @@ -34,30 +34,32 @@ depending on which build server you have this approach may or may not work for you. For instance in TFS Build vNext you cannot chain builds to publish artifacts built in one build in another. -1. Your CI build creates the stable NuGet package - - Do *not* publish this package into the Octopus nuget feed -2. When you want to push a package into the Octopus deployment pipeline you trigger the second build - - it will either take the package built from the first build in the chain (your CI build?) or rebuild - - It will publish that package into the Octopus deploy feed - - The build then is *tagged* with the version, this will cause GitVersion to increment the version +1. Your CI build creates the stable NuGet package -This means that CI builds are *not* available to Octopus deploy, there will be a -manual build in your *build server* which pushes the package to Octopus deploy. +* Do _not_ publish this package into the Octopus nuget feed + +2. When you want to push a package into the Octopus deployment pipeline you trigger the second build + +* it will either take the package built from the first build in the chain (your CI build?) or rebuild +* It will publish that package into the Octopus deploy feed +* The build then is _tagged_ with the version, this will cause GitVersion to increment the version + +This means that CI builds are _not_ available to Octopus deploy, there will be a +manual build in your _build server_ which pushes the package to Octopus deploy. ### Tag to release Another simple option is to tag a stable version to release, the basic idea is: -1. GitVersion is set to continuous deployment mode, so main will create `-ci.x` -pre-release builds -1. CI Builds only create NuGet packages for stable builds -1. You tag main with a stable version of the next version then push it -1. The CI build triggers, GitVersion will always respect tags so you will get a -stable version -1. The stable package will be pushed to Octopus -1. Because of the tag, then next build will be incremented and will be producing -pre-release packages of the next build - +1. GitVersion is set to continuous deployment mode, so main will create `-ci.x` + pre-release builds +2. CI Builds only create NuGet packages for stable builds +3. You tag main with a stable version of the next version then push it +4. The CI build triggers, GitVersion will always respect tags so you will get a + stable version +5. The stable package will be pushed to Octopus +6. Because of the tag, then next build will be incremented and will be producing + pre-release packages of the next build #### Script to create the release @@ -65,7 +67,7 @@ Here is an example script which could be used to tag the stable version, it uses GitVersion to calculate the version so you just run `./CreateRelease.ps1` and it will tag and push the tag. -``` powershell +```powershell [CmdletBinding()] param() @@ -126,7 +128,7 @@ Pop-Location #### Sample build script (build.ps1) -``` powershell +```powershell [CmdletBinding()] param() $ErrorActionPreference = "Stop" diff --git a/docs/input/docs/reference/build-servers/teamcity.md b/docs/input/docs/reference/build-servers/teamcity.md index 3f45760673..989fb36383 100644 --- a/docs/input/docs/reference/build-servers/teamcity.md +++ b/docs/input/docs/reference/build-servers/teamcity.md @@ -6,13 +6,12 @@ Description: Details on the TeamCity support in GitVersion ## Basic Usage -In [TeamCity](https://www.jetbrains.com/teamcity/) you can create a build step -as follows: +In [TeamCity] you can create a build step as follows: -* **Runner type:** Command Line -* **Run:** Executable with parameters -* **Command executable:** `GitVersion.exe` -* **Command parameters:** `/output buildserver /updateassemblyinfo true` +* **Runner type:** Command Line +* **Run:** Executable with parameters +* **Command executable:** `GitVersion.exe` +* **Command parameters:** `/output buildserver /updateassemblyinfo true` Then in your build parameters simply [add a placeholder](#nuget-in-teamcity) of the GitVersion variables you would like to use. @@ -23,9 +22,9 @@ passed to your build scripts to use. ## GitVersion meta runner for TeamCity TeamCity has support for meta-runners which allow custom tasks. There is a -GitVersion meta-runner available which makes it easy to use GitVersion. +[GitVersion meta-runner][meta-runner] available which makes it easy to use +GitVersion. - - [Project Link](https://github.com/JetBrains/meta-runner-power-pack/tree/master/gitversion) ## Running inside TeamCity @@ -44,11 +43,11 @@ Just go to your build configuration, Parameters, click Add, Name should be For GitVersion to work with any mode requiring other than the currently built branch to calculate the version number, you need to set the configuration -parameter [`teamcity.git.fetchAllHeads = true` in TeamCity](https://www.jetbrains.com/help/teamcity/git.html#Git-GeneralSettings), +parameter [`teamcity.git.fetchAllHeads = true` in TeamCity][general-settings], because TeamCity by default fetches only the current branch for building. To add this configuration parameter to your build configuration, go to -*Parameters*, click *Add*, *Name* should be `teamcity.git.fetchAllHeads` and the +_Parameters_, click _Add_, _Name_ should be `teamcity.git.fetchAllHeads` and the value should be `true`. ### Dynamic repositories @@ -58,27 +57,28 @@ GitVersion. Server side checkout sends just the files to the agent and not the actual .git folder. Dynamic repositories will clone your repo into a temp folder and use it to calculate version information. -See [dynamic repositories](/docs/learn/dynamic-repositories) for more info. +See [dynamic repositories][dynamic-repo] for more info. ### Output -* We update the TC build number to the GitVersion number automatically -* We output the individual values of the GitVersion version variables as build -parameters with format `GitVersion.*` (Eg: `GitVersion.Major`) if you need -access to them in your build script. Being system variables they will be passed -as msbuild/environmental variables to other build steps +* We update the TC build number to the GitVersion number automatically +* We output the individual values of the GitVersion version variables as build + parameters with format `GitVersion.*` (Eg: `GitVersion.Major`) if you need + access to them in your build script. Being system variables they will be passed + as msbuild/environmental variables to other build steps ### NuGet in TeamCity -* Add dummy [parameter](http://confluence.jetbrains.com/display/TCD8/Configuring+Build+Parameters) -to the project called `GitVersion.NuGetVersion`. If many of your projects uses -git-flow and SemVer you can add the parameter to the "root-project" -(TeamCity 8.x+). You need a dummy param because GitVersion creates the variables -at runtime, and you cannot reference a parameter which is not available -statically. GitVersion will overwrite the dummy value -* Then setup you nuget pack build set the "version" to `%GitVersion.NuGetVersion%` -* If you do your pack in a build script then you can just use environmental -variables because teamcity will pass them through automatically. +* Add a dummy [parameter] to the project called `GitVersion.NuGetVersion`. If + many of your projects uses git-flow and SemVer you can add the parameter to + the "root-project" (TeamCity 8.x+). You need a dummy param because + GitVersion creates the variables at runtime, and you cannot reference a + parameter which is not available statically. GitVersion will overwrite the + dummy value. +* Then setup you nuget pack build set the "version" to + `%GitVersion.NuGetVersion%`. +* If you do your pack in a build script then you can just use environmental + variables because teamcity will pass them through automatically. ### When TeamCity -> GitHub can't use https @@ -89,14 +89,23 @@ pull down main branch for you during the build. If however your TeamCity uses SSH to clone git repos and https is unavailable then GitVersion will error with a message like -> [GitVersionTask.UpdateAssemblyInfo] Error occurred: GitVersion.MissingBranchException: +```cs +[GitVersionTask.UpdateAssemblyInfo] Error occurred: GitVersion.MissingBranchException: Could not fetch from 'git@github.dev.xero.com:Xero/Bus.git' since LibGit2 does not support the transport. You have most likely cloned using SSH. If there is a remote branch named 'main' then fetch it manually, otherwise please create a local branch named 'main'. ---> LibGit2Sharp.LibGit2SharpException: An error was raised by libgit2. Category = Net (Error). This transport isn't implemented. Sorry +``` ## Guides - - [Continuous Delivery Setup in TeamCity](http://jake.ginnivan.net/blog/2014/07/09/my-typical-teamcity-build-setup) +* [Continuous Delivery Setup in TeamCity][cd] + +[cd]: http://jake.ginnivan.net/blog/2014/07/09/my-typical-teamcity-build-setup +[dynamic-repo]: /docs/learn/dynamic-repositories +[general-settings]: https://www.jetbrains.com/help/teamcity/git.html#Git-GeneralSettings +[parameter]: http://confluence.jetbrains.com/display/TCD8/Configuring+Build+Parameters +[teamcity]: https://www.jetbrains.com/teamcity/ +[meta-runner]: https://github.com/JetBrains/meta-runner-power-pack/tree/master/gitversion diff --git a/docs/input/docs/reference/configuration.md b/docs/input/docs/reference/configuration.md index 1b85ef6901..d7c6af93e0 100644 --- a/docs/input/docs/reference/configuration.md +++ b/docs/input/docs/reference/configuration.md @@ -24,7 +24,7 @@ GitVersion ships with internal default configuration which works with GitHubFlow and GitFlow, probably with others too. ::: -The *develop* branch is set to `ContinuousDeployment` mode by default as we have +The `develop` branch is set to `ContinuousDeployment` mode by default as we have found that is generally what is needed when using GitFlow. You can run `GitVersion /showConfig` to see the effective configuration @@ -91,7 +91,7 @@ skip updating the `AssemblyFileVersion` while still updating the Specifies the format of `AssemblyFileVersion` and overwrites the value of `assembly-file-versioning-scheme`. -Expressions in curly braces reference one of the [variables](/docs/reference/variables) +Expressions in curly braces reference one of the [variables] or a process-scoped environment variable (when prefixed with `env:`). For example, ```yaml @@ -120,7 +120,7 @@ The default value is `{InformationalVersion}`. ### mode Sets the `mode` of how GitVersion should create a new version. Read more at -[versioning modes](/docs/reference/modes). +[versioning modes][modes]. ### increment @@ -184,25 +184,29 @@ none` and `+semver: skip` ### legacy-semver-padding The number of characters to pad `LegacySemVer` to in the `LegacySemVerPadded` -[variable](/docs/reference/variables). Is default set to `4`, which will pad the +[variable][variables]. Is default set to `4`, which will pad the `LegacySemVer` value of `3.0.0-beta1` to `3.0.0-beta0001`. ### build-metadata-padding The number of characters to pad `BuildMetaData` to in the `BuildMetaDataPadded` -[variable](/docs/reference/variables). Is default set to `4`, which will pad the +[variable][variables]. Is default set to `4`, which will pad the `BuildMetaData` value of `1` to `0001`. ### commits-since-version-source-padding The number of characters to pad `CommitsSinceVersionSource` to in the -`CommitsSinceVersionSourcePadded` [variable](/docs/reference/variables). Is default -set to `4`, which will pad the `CommitsSinceVersionSource` value of `1` to -`0001`. +`CommitsSinceVersionSourcePadded` [variable][variables]. Is default set to `4`, +which will pad the `CommitsSinceVersionSource` value of `1` to `0001`. ### tag-pre-release-weight -The pre-release weight in case of tagged commits. If the value is not set in the configuration, a default weight of 60000 is used instead. If the `WeightedPreReleaseNumber` [variable](/docs/reference/variables) is 0 and this parameter is set, its value is used. This helps if your branching model is GitFlow and the last release build, which is often tagged, can utilise this parameter to produce a monotonically increasing build number. +The pre-release weight in case of tagged commits. If the value is not set in the +configuration, a default weight of 60000 is used instead. If the +`WeightedPreReleaseNumber` [variable][variables] is 0 and this +parameter is set, its value is used. This helps if your branching model is +GitFlow and the last release build, which is often tagged, can utilise this +parameter to produce a monotonically increasing build number. ### commit-message-incrementing @@ -268,9 +272,9 @@ merge-message-formats: The regular expression should contain the following capture groups: -+ SourceBranch - Identifies the source branch of the merge -+ TargetBranch - Identifies the target of the merge -+ PullRequestNumber - Captures the pull-request number +* SourceBranch - Identifies the source branch of the merge +* TargetBranch - Identifies the target of the merge +* PullRequestNumber - Captures the pull-request number Custom merge message formats are evaluated _before_ any built in formats. @@ -385,16 +389,16 @@ Take this commit graph By looking at this graph, you cannot tell which of these scenarios happened: -+ feature/foo branches off release/1.0.0 - + Branch release/1.0.0 from main - + Branch feature/foo from release/1.0.0 - + Add a commit to both release/1.0.0 and feature/foo - + release/1.0.0 is the base for feature/foo -+ release/1.0.0 branches off feature/foo - + Branch feature/foo from main - + Branch release/1.0.0 from feature/foo - + Add a commit to both release/1.0.0 and feature/foo - + feature/foo is the base for release/1.0.0 +* feature/foo branches off release/1.0.0 + * Branch release/1.0.0 from main + * Branch feature/foo from release/1.0.0 + * Add a commit to both release/1.0.0 and feature/foo + * release/1.0.0 is the base for feature/foo +* release/1.0.0 branches off feature/foo + * Branch feature/foo from main + * Branch release/1.0.0 from feature/foo + * Add a commit to both release/1.0.0 and feature/foo + * feature/foo is the base for release/1.0.0 Or put more simply, you cannot tell which branch was created first, `release/1.0.0` or `feature/foo`. @@ -471,8 +475,10 @@ When `release-2.0.0` is merged into main, we want main to build `2.0.0`. If `release-2.0.0` is merged into develop we want it to build `2.1.0`, this option prevents incrementing after a versioned branch is merged. -In a GitFlow-based repository, setting this option can have implications on the `CommitsSinceVersionSource` output variable. It can rule -out a potentially better version source proposed by the `MergeMessageBaseVersionStrategy`. For more details and an in-depth analysis, please see the discussion [here](https://github.com/GitTools/GitVersion/pull/2506#issuecomment-754754037). +In a GitFlow-based repository, setting this option can have implications on the +`CommitsSinceVersionSource` output variable. It can rule out a potentially +better version source proposed by the `MergeMessageBaseVersionStrategy`. For +more details and an in-depth analysis, please see [the discussion][2506]. ### tag-number-pattern @@ -502,7 +508,7 @@ branches: Strategy which will look for tagged merge commits directly off the current branch. For example `develop` → `release/1.0.0` → merge into `main` and tag -`1.0.0`. The tag is *not* on develop, but develop should be version `1.0.0` now. +`1.0.0`. The tag is _not_ on develop, but develop should be version `1.0.0` now. ### tracks-release-branches @@ -519,16 +525,21 @@ default support/ and main are mainlines. ### pre-release-weight -Provides a way to translate the `PreReleaseLabel` -([variables](/docs/reference/variables)) to a numeric value in order to avoid version -collisions across different branches. For example, a release branch created -after "1.2.3-alpha.55" results in "1.2.3-beta.1" and thus e.g. "1.2.3-alpha.4" -and "1.2.3-beta.4" would have the same file version: "1.2.3.4". One of the ways -to use this value is to set -`assembly-file-versioning-format: {Major}.{Minor}.{Patch}.{WeightedPreReleaseNumber}`. -If the `pre-release-weight` is set, it would be added to the `PreReleaseNumber` -to get a final `AssemblySemFileVer`, otherwise a branch specific default for -`pre-release-weight` will be used in the calculation. Related Issues -[1145](https://github.com/GitTools/GitVersion/issues/1145), [1366](https://github.com/GitTools/GitVersion/issues/1366) - +Provides a way to translate the `PreReleaseLabel` ([variables]) to a numeric +value in order to avoid version collisions across different branches. For +example, a release branch created after "1.2.3-alpha.55" results in +"1.2.3-beta.1" and thus e.g. "1.2.3-alpha.4" and "1.2.3-beta.4" would have the +same file version: "1.2.3.4". One of the ways to use this value is to set +`assembly-file-versioning-format: +{Major}.{Minor}.{Patch}.{WeightedPreReleaseNumber}`. If the `pre-release-weight` +is set, it would be added to the `PreReleaseNumber` to get a final +`AssemblySemFileVer`, otherwise a branch specific default for +`pre-release-weight` will be used in the calculation. Related Issues [1145], +[1366] + +[1145]: https://github.com/GitTools/GitVersion/issues/1145 +[1366]: https://github.com/GitTools/GitVersion/issues/1366 +[2506]: https://github.com/GitTools/GitVersion/pull/2506#issuecomment-754754037 +[modes]: /docs/reference/modes +[variables]: /docs/reference/variables [version-sources]: /docs/reference/version-sources diff --git a/docs/input/docs/reference/modes/continuous-delivery.md b/docs/input/docs/reference/modes/continuous-delivery.md index 3eb4d401fa..5025232ffa 100644 --- a/docs/input/docs/reference/modes/continuous-delivery.md +++ b/docs/input/docs/reference/modes/continuous-delivery.md @@ -12,28 +12,28 @@ default mode in GitVersion. Each stage of the pipeline gets the code going through the pipeline closer to production. The topic itself is rather large, here we will just focus on the building and -creation of *releasable* artifacts. This is only a part of continuous delivery +creation of _releasable_ artifacts. This is only a part of continuous delivery as a whole, with the hard part being the ability to measure the impacts of what you have deployed into production. In essence continuous delivery means: -- Your code is automatically built and tested -- If any of the automated tests fail, the team's #1 priority is to fix the - build -- If the build is green, the application can be deployed at any time - - Ideally the business should make that decision - - The same artifacts which were built and tested should be deployed - - That means no rebuilding everything when you are deploying +* Your code is automatically built and tested +* If any of the automated tests fail, the team's #1 priority is to fix the + build +* If the build is green, the application can be deployed at any time + * Ideally the business should make that decision + * The same artifacts which were built and tested should be deployed + * That means no rebuilding everything when you are deploying Continuous delivery does not work well with GitFlow. The reason is that you are -required to *merge* to main to do a release, triggering a rebuild and a new +required to _merge_ to main to do a release, triggering a rebuild and a new set of artifacts to go through your pipeline. Depending on how long your pipeline is, this could be a while. GitHubFlow is a better fit for Continuous delivery, the [mainline development][mainline] model means that every merged feature branch will be -built as a *stable* version and if the build/builds go green then you are free +built as a _stable_ version and if the build/builds go green then you are free to deploy to production at any time. ## Usage @@ -49,24 +49,24 @@ mode: ContinuousDelivery ## How Continuous Delivery affects GitVersion -The thing about continuous delivery is that there will be *multiple* candidates +The thing about continuous delivery is that there will be _multiple_ candidates to deploy to production and it is a human choice to deploy. This means that GitVersion will build **the same semantic version** until that version is deployed. For instance: -- 1.1.0+5 -- 1.1.0+6 -- 1.1.0+7 <-- This is the artifact we release, tag the commit which created -this version -- 1.1.1+0 +* 1.1.0+5 +* 1.1.0+6 +* 1.1.0+7 <-- This is the artifact we release, tag the commit which created + this version +* 1.1.1+0 Tags are required in this mode to communicate when the release is done as it's an external manual process. ## Resources -- [Continuous Delivery on Wikipedia][wikipedia] -- [Continuous Delivery, the book][book] +* [Continuous Delivery on Wikipedia][wikipedia] +* [Continuous Delivery, the book][book] [book]: http://www.amazon.com/Continuous-Delivery-Deployment-Automation-Addison-Wesley/dp/0321601912 [configuration]: /docs/reference/configuration diff --git a/docs/input/docs/reference/modes/mainline.md b/docs/input/docs/reference/modes/mainline.md index d4b4e11625..bce2481731 100644 --- a/docs/input/docs/reference/modes/mainline.md +++ b/docs/input/docs/reference/modes/mainline.md @@ -21,7 +21,7 @@ fix the issue, then do a release with the fix. Like all things, it is an approach and will work for some people and not for others. GitVersion is unique in the fact that it works very well with mainline -development and the version numbers it generates are *predictive* and indicate +development and the version numbers it generates are _predictive_ and indicate what the next version to be released is. Most other approaches require bumping the version number before the release which means that the version being built and the version number which will be deployed are often different. @@ -29,16 +29,16 @@ and the version number which will be deployed are often different. This mode is great if you do not want to tag each release because you simply deploy every commit to main. The behaviour of this mode is as follows: -1. Calculate a base version (likely a tag in this mode) -2. Walk all commits from the base version commit -3. When a merge commit is found: - - Calculate increments for each direct commit on main - - Calculate the increment for the branch -4. Calculate increments for each remaining direct commit -5. For feature branches then calculate increment for the commits so far on your - feature branch. +1. Calculate a base version (likely a tag in this mode) +2. Walk all commits from the base version commit +3. When a merge commit is found: + * Calculate increments for each direct commit on main + * Calculate the increment for the branch +4. Calculate increments for each remaining direct commit +5. For feature branches then calculate increment for the commits so far on your + feature branch. -If you *do not want* GitVersion to treat a commit or a pull request as a release +If you _do not want_ GitVersion to treat a commit or a pull request as a release and increment the version you can use `+semver: none` or `+semver: skip` in a commit message to skip incrementing for that commit. @@ -57,6 +57,7 @@ slowing down. ::: ## Usage + By default GitVersion is set up to do [Continuous Delivery][continuous-delivery] versioning on all branches but `develop` (which does [Continuous Deployment][continuous-deployment] by default). To change the [versioning diff --git a/docs/input/docs/reference/version-increments.md b/docs/input/docs/reference/version-increments.md index 6ac763752f..147c96b646 100644 --- a/docs/input/docs/reference/version-increments.md +++ b/docs/input/docs/reference/version-increments.md @@ -12,7 +12,7 @@ version. ## Approach -Semantic Versioning is all about *releases*, not builds. This means that the +Semantic Versioning is all about _releases_, not builds. This means that the version only increases after you release, this directly conflicts with the concept of published CI builds. When you release the next version of your library/app/website/whatever you should only increment major/minor or patch then @@ -22,10 +22,10 @@ either `2.0.0`, `1.1.0` or `1.0.1`. Because of this, GitVersion works out what the next SemVer of your app is on each commit. When you are ready to release you simply deploy the latest built version and tag the release it was from. This practice is called -**continuous delivery**. GitVersion will increment the *metadata* for each build +**continuous delivery**. GitVersion will increment the _metadata_ for each build so you can tell builds apart. For example `1.0.0+5` followed by `1.0.0+6`. It is -important to note that build metadata *is not part of the semantic version, it -is just metadata!*. +important to note that build metadata _is not part of the semantic version, it +is just metadata!_. All this effectively means that GitVersion will produce the same version NuGet package each commit until you tag a release. @@ -38,8 +38,8 @@ are: ### 1. GitFlow If you are using GitFlow then builds off the `develop` branch will actually -*increment on every commit*. This is known in GitVersion as *continuous -deployment mode*. By default `develop` builds are tagged with the `alpha` +_increment on every commit_. This is known in GitVersion as _continuous +deployment mode_. By default `develop` builds are tagged with the `alpha` pre-release tag. This is so they are sorted higher than release branches. If you need to consume packages built from develop, we recommend publishing @@ -119,7 +119,7 @@ rules for that branch (some branches bump patch, some minor). ### Incrementing per commit When using the continuous deployment mode (which will increment the SemVer every -commit) all builds *must* have a pre-release tag, except for builds which are +commit) all builds _must_ have a pre-release tag, except for builds which are explicitly tagged as stable. Then the build metadata (which is the commit count) is promoted to the diff --git a/docs/input/docs/reference/version-sources.md b/docs/input/docs/reference/version-sources.md index 5c1df06467..9a475f7992 100644 --- a/docs/input/docs/reference/version-sources.md +++ b/docs/input/docs/reference/version-sources.md @@ -10,13 +10,13 @@ version should be. The logic of GitVersion is something like this: -- Is the current commit tagged - - Yes: Use the tag as the version - - No: continue -- Calculate the base version (highest version from all the sources) -- Increment version if needed based on branch config -- Calculate the build metadata (everything after the +) and append to the -calculated version +* Is the current commit tagged + * Yes: Use the tag as the version + * No: continue +* Calculate the base version (highest version from all the sources) +* Increment version if needed based on branch config +* Calculate the build metadata (everything after the +) and append to the + calculated version ## Version Sources @@ -49,9 +49,9 @@ Will increment: false For the develop branch, i.e. marked with `is-develop: true` -- Returns the version number extracted from any child release-branches, i.e. -those marked with `is-release-branch: true` -- Returns the version number of any tags on the main branch +* Returns the version number extracted from any child release-branches, i.e. + those marked with `is-release-branch: true` +* Returns the version number of any tags on the main branch Will increment: true diff --git a/docs/input/docs/usage/ci.md b/docs/input/docs/usage/ci.md index 31963f82e0..3861b24540 100644 --- a/docs/input/docs/usage/ci.md +++ b/docs/input/docs/usage/ci.md @@ -18,13 +18,14 @@ supported continuous integration servers below. GitVersion's GitTools Actions allows for simple integration into a GitHub Actions build pipeline. -GitTools Actions +[GitTools Actions][gittools-actions]{.btn .btn-primary} ## Azure DevOps GitVersion's GitTools Azure DevOps Task allows for simple integration of GitVersion into an Azure DevOps build pipeline. -GitTools Task +[GitTools Task][gittools-task]{.btn .btn-primary} + +[gittools-actions]: https://github.com/marketplace/actions/gittools +[gittools-task]: https://marketplace.visualstudio.com/items?itemName=gittools.gittools diff --git a/docs/input/docs/usage/cli/arguments.md b/docs/input/docs/usage/cli/arguments.md index f0ac0a8ad1..abc684bd33 100644 --- a/docs/input/docs/usage/cli/arguments.md +++ b/docs/input/docs/usage/cli/arguments.md @@ -109,27 +109,28 @@ To have **space characters** as a part of `value`, `value` has be enclosed with Double quote character inside of the double quoted `value` has to be be escaped with a backslash '\\' - `key="My \"escaped-quotes\""`. Following options are supported: -1. `assembly-file-versioning-format` -1. `assembly-file-versioning-scheme` -1. `assembly-informational-format` -1. `assembly-versioning-format` -1. `assembly-versioning-scheme` -1. `build-metadata-padding` -1. `commit-date-format` -1. `commit-message-incrementing` -1. `commits-since-version-source-padding` -1. `continuous-delivery-fallback-tag` -1. `increment` -1. `legacy-semver-padding` -1. `major-version-bump-message` -1. `minor-version-bump-message` -1. `mode` -1. `next-version` -1. `no-bump-message` -1. `patch-version-bump-message` -1. `tag-prefix` -1. `tag-pre-release-weight` -1. `update-build-number` + +1. `assembly-file-versioning-format` +2. `assembly-file-versioning-scheme` +3. `assembly-informational-format` +4. `assembly-versioning-format` +5. `assembly-versioning-scheme` +6. `build-metadata-padding` +7. `commit-date-format` +8. `commit-message-incrementing` +9. `commits-since-version-source-padding` +10. `continuous-delivery-fallback-tag` +11. `increment` +12. `legacy-semver-padding` +13. `major-version-bump-message` +14. `minor-version-bump-message` +15. `mode` +16. `next-version` +17. `no-bump-message` +18. `patch-version-bump-message` +19. `tag-prefix` +20. `tag-pre-release-weight` +21. `update-build-number` Read more about [Configuration](/docs/reference/configuration). diff --git a/docs/input/docs/usage/cli/assembly-patch.md b/docs/input/docs/usage/cli/assembly-patch.md index bc405cc523..704044e0fd 100644 --- a/docs/input/docs/usage/cli/assembly-patch.md +++ b/docs/input/docs/usage/cli/assembly-patch.md @@ -10,11 +10,11 @@ Description: | `AssemblyInfo.cs` or `AssemblyInfo.vb` files in the git repo and update them. It will update the following assembly attributes: -* `AssemblyVersion` will be set to the `AssemblySemVer` variable. -* `AssemblyFileVersion` will be set to the `MajorMinorPatch` variable with an -appended `.0`. -* `AssemblyInformationalVersion` will be set to the `InformationalVersion` -variable. +* `AssemblyVersion` will be set to the `AssemblySemVer` variable. +* `AssemblyFileVersion` will be set to the `MajorMinorPatch` variable with an + appended `.0`. +* `AssemblyInformationalVersion` will be set to the `InformationalVersion` + variable. Note that contrary to when using the [MSBuild Task][msbuild-task] the attributes must already exist in the `AssemblyInfo.cs` or `AssemblyInfo.vb` @@ -29,13 +29,13 @@ already exist. Use the `/ensureassemblyinfo` switch alongside `/updateassemblyinfo `, if the filename specified does not exist it will be generated based on a known template that adds: -* `AssemblyVersion` will be set to the `AssemblySemVer` variable. -* `AssemblyFileVersion` will be set to the `MajorMinorPatch` variable with an -appended `.0`. -* `AssemblyInformationalVersion` will be set to the `InformationalVersion` -variable. +* `AssemblyVersion` will be set to the `AssemblySemVer` variable. +* `AssemblyFileVersion` will be set to the `MajorMinorPatch` variable with an + appended `.0`. +* `AssemblyInformationalVersion` will be set to the `InformationalVersion` + variable. -This can be done for *.cs, *.vb and *.fs files. +This can be done for \*.cs, \*.vb and \*.fs files. When requesting that GitVersion generate an assembly info file you are limited to only specifying a single `` within the `/updateassemblyinfo` @@ -80,10 +80,5 @@ To support integration with WiX projects, use `GitVersion.exe `GitVersion_WixVersion.wxi` under the current working directory and can be referenced in the WiX project files. -[brew]: https://formulae.brew.sh/formula-linux/gitversion -[choco]: http://chocolatey.org/packages/GitVersion.Portable -[docker]: https://hub.docker.com/r/gittools/gitversion -[dotnet-tool]: https://docs.microsoft.com/en-us/dotnet/core/tools/global-tools#install-a-global-tool [msbuild-task]: /docs/usage/msbuild -[tool]: https://www.nuget.org/packages/GitVersion.Tool/ [variables]: /docs/reference/variables diff --git a/docs/input/docs/usage/cli/installation.md b/docs/input/docs/usage/cli/installation.md index 69f83fc4e4..d1f6c9219a 100644 --- a/docs/input/docs/usage/cli/installation.md +++ b/docs/input/docs/usage/cli/installation.md @@ -26,7 +26,7 @@ dotnet-gitversion ### Homebrew -To install the [`gitversion`][brew] formula with [Homebrew](https://brew.sh/), +To install the [`gitversion`][brew] formula with [Homebrew][homebrew], enter the following into a terminal: ```shell @@ -78,3 +78,10 @@ be exposed to the host OS. This should work on all operating systems supported by Docker (at the time of writing: Linux, macOS, Windows). + +[dotnet-tool]: https://docs.microsoft.com/en-us/dotnet/core/tools/global-tools#install-a-global-tool +[tool]: https://www.nuget.org/packages/GitVersion.Tool/ +[brew]: https://formulae.brew.sh/formula-linux/gitversion +[homebrew]: https://brew.sh/ +[docker]: https://hub.docker.com/r/gittools/gitversion +[choco]: http://chocolatey.org/packages/GitVersion.Portable diff --git a/docs/input/docs/usage/msbuild.md b/docs/input/docs/usage/msbuild.md index efc913761e..29dd1e7614 100644 --- a/docs/input/docs/usage/msbuild.md +++ b/docs/input/docs/usage/msbuild.md @@ -17,9 +17,9 @@ version information that is compiled into the resulting artifact. It currently works with desktop `MSBuild`. Support for CoreCLR with `dotnet build` is coming soon. -> **Note** - The nuget package was "*[GitVersionTask](https://www.nuget.org/packages/GitVersionTask/)*" up until version 5.5.1. - From version 5.6.0 it has been called "*[GitVersion.MsBuild](https://www.nuget.org/packages/GitVersion.MsBuild/)*" +> **Note**\ +> The nuget package was "_[GitVersionTask](https://www.nuget.org/packages/GitVersionTask/)_" up until version 5.5.1.\ +> From version 5.6.0 it has been called "_[GitVersion.MsBuild](https://www.nuget.org/packages/GitVersion.MsBuild/)_" ## TL;DR @@ -38,7 +38,7 @@ If you're using `PackageReference` style NuGet dependencies (VS 2017+), add `all` to prevent the task from becoming a dependency of your package: -``` xml +```xml All @@ -87,10 +87,10 @@ Default sample: Now, when you build: -* `AssemblyVersion` will be set to the `AssemblySemVer` variable. -* `AssemblyFileVersion` will be set to the `MajorMinorPatch` variable with `.0` -appended to it. -* `AssemblyInformationalVersion` will be set to the `InformationalVersion` variable. +* `AssemblyVersion` will be set to the `AssemblySemVer` variable. +* `AssemblyFileVersion` will be set to the `MajorMinorPatch` variable with `.0` + appended to it. +* `AssemblyInformationalVersion` will be set to the `InformationalVersion` variable. #### Other injected Variables @@ -183,7 +183,6 @@ versions by setting `UseFullSemVerForNuGet` to true in your project (this is off by default for compatibility). Some hosts, like MyGet, support SemVer 2.0 package versions but older NuGet clients and nuget.org do not. - #### Accessing variables in MSBuild Once `GitVersion.MsBuild.GetVersion` has been executed, the MSBuild properties can be diff --git a/docs/readme.md b/docs/readme.md index 8fb8b589d6..a35ed62c43 100644 --- a/docs/readme.md +++ b/docs/readme.md @@ -43,6 +43,6 @@ a local web server. Information about the URL that can be used to view the docs will be shown in the output. Copy/paste this URL into a browser window. [gitversion.net]: https://gitversion.net/ -[forking]: https://guides.github.com/activities/forking/ -[ps-mac]: https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell-core-on-macos?view=powershell-7.1 -[ps-linux]: https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell-core-on-linux?view=powershell-7.1 +[forking]: https://guides.github.com/activities/forking/ +[ps-mac]: https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell-core-on-macos?view=powershell-7.1 +[ps-linux]: https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell-core-on-linux?view=powershell-7.1 diff --git a/src/Docker/Readme.md b/src/Docker/Readme.md index 56d40b2691..c89ad73690 100644 --- a/src/Docker/Readme.md +++ b/src/Docker/Readme.md @@ -1,10 +1,10 @@ # There are 4 variants of docker image -- based on **microsoft/dotnet-framework:4.8-runtime** - Windows Full FX -- based on **microsoft/dotnet:2.1-runtime** - Windows dotnet core -- based on **mono:5.18** - Linux Full FX - on mono -- based on **microsoft/dotnet:2.1-runtime** - Linux dotnet core -- based on **centos:7** - linux dotnet core +* based on **microsoft/dotnet-framework:4.8-runtime** - Windows Full FX +* based on **microsoft/dotnet:2.1-runtime** - Windows dotnet core +* based on **mono:5.18** - Linux Full FX - on mono +* based on **microsoft/dotnet:2.1-runtime** - Linux dotnet core +* based on **centos:7** - linux dotnet core To run on windows container run this `docker run --rm -v "$(pwd):c:/repo" gittools/gitversion:latest-windows-net48 c:/repo` From cd5979484b6a423c9e0b4a77d4b86ce57e04e029 Mon Sep 17 00:00:00 2001 From: Michael Blake Date: Mon, 21 Jun 2021 20:54:18 +0100 Subject: [PATCH 25/79] Update variables.md Make example more obvious --- docs/input/docs/reference/variables.md | 54 +++++++++++++------------- 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/docs/input/docs/reference/variables.md b/docs/input/docs/reference/variables.md index ce81073c36..d347bd54af 100644 --- a/docs/input/docs/reference/variables.md +++ b/docs/input/docs/reference/variables.md @@ -11,37 +11,37 @@ what is available. For the `release/3.0.0` branch of GitVersion it shows: ```json { "Major": 3, - "Minor": 0, - "Patch": 0, - "PreReleaseTag": "beta.1", - "PreReleaseTagWithDash": "-beta.1", + "Minor": 22, + "Patch": 11, + "PreReleaseTag": "beta.99", + "PreReleaseTagWithDash": "-beta.99", "PreReleaseLabel": "beta", "PreReleaseLabelWithDash": "-beta", - "PreReleaseNumber": 1, - "WeightedPreReleaseNumber": 1001, - "BuildMetaData": 1, - "BuildMetaDataPadded": "0001", - "FullBuildMetaData": "1.Branch.release/3.0.0.Sha.28c853159a46b5a87e6cc9c4f6e940c59d6bc68a", - "MajorMinorPatch": "3.0.0", - "SemVer": "3.0.0-beta.1", - "LegacySemVer": "3.0.0-beta1", - "LegacySemVerPadded": "3.0.0-beta0001", - "AssemblySemVer": "3.0.0.0", - "AssemblySemFileVer": "3.0.0.0", - "InformationalVersion": "3.0.0-beta.1+1.Branch.release/3.0.0.Sha.28c853159a46b5a87e6cc9c4f6e940c59d6bc68a", - "FullSemVer": "3.0.0-beta.1+1", - "BranchName": "release/3.0.0", - "EscapedBranchName": "release-3.0.0", + "PreReleaseNumber": 99, + "WeightedPreReleaseNumber": 1099, + "BuildMetaData": 88, + "BuildMetaDataPadded": "0088", + "FullBuildMetaData": "99.Branch.release/3.22.11.Sha.28c853159a46b5a87e6cc9c4f6e940c59d6bc68a", + "MajorMinorPatch": "3.22.11", + "SemVer": "3.22.11-beta.99", + "LegacySemVer": "3.22.11-beta99", + "LegacySemVerPadded": "3.22.11-beta0099", + "AssemblySemVer": "3.22.11.0", + "AssemblySemFileVer": "3.22.11.0", + "InformationalVersion": "3.22.11-beta.99+88.Branch.release/3.022.011.Sha.28c853159a46b5a87e6cc9c4f6e940c59d6bc68a", + "FullSemVer": "3.22.11-beta.99+88", + "BranchName": "release/3.022.011", + "EscapedBranchName": "release-3.022.011", "Sha": "28c853159a46b5a87e6cc9c4f6e940c59d6bc68a", "ShortSha": "28c8531", - "NuGetVersionV2": "3.0.0-beta0001", - "NuGetVersion": "3.0.0-beta0001", - "NuGetPreReleaseTagV2": "beta0001", - "NuGetPreReleaseTag": "beta0001", - "VersionSourceSha": "950d2f830f5a2af12a6779a48d20dcbb02351f25", - "CommitsSinceVersionSource": 1, - "CommitsSinceVersionSourcePadded": "0001", - "CommitDate": "2014-03-06", + "NuGetVersionV2": "3.22.11-beta0099", + "NuGetVersion": "3.22.11-beta0099", + "NuGetPreReleaseTagV2": "beta0099", + "NuGetPreReleaseTag": "beta0099", + "VersionSourceSha": "28c853159a46b5a87e6cc9c4f6e940c59d6bc68a", + "CommitsSinceVersionSource": 7, + "CommitsSinceVersionSourcePadded": "0007", + "CommitDate": "2021-12-31", "UncommittedChanges": 0 } ``` From 1faf5834b1529e1012ba72d2d50e6564f05cecd1 Mon Sep 17 00:00:00 2001 From: Darwin Date: Fri, 25 Jun 2021 14:27:22 -0400 Subject: [PATCH 26/79] Update misleading error and give resolution hints Previous message sounded like literal branches rather than Gitversion branch "types". Also gave hints on checking local repo meets Gitversion requirements or to use dynamic repositories. --- .../Configuration/BranchConfigurationCalculator.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/GitVersion.Core/Configuration/BranchConfigurationCalculator.cs b/src/GitVersion.Core/Configuration/BranchConfigurationCalculator.cs index 5af7e4c8a8..11d51c628f 100644 --- a/src/GitVersion.Core/Configuration/BranchConfigurationCalculator.cs +++ b/src/GitVersion.Core/Configuration/BranchConfigurationCalculator.cs @@ -132,7 +132,7 @@ private BranchConfig InheritBranchConfiguration(IBranch targetBranch, BranchConf { // TODO We should call the build server to generate this exception, each build server works differently // for fetch issues and we could give better warnings. - throw new InvalidOperationException("Could not find a 'develop' or 'main' branch, neither locally nor remotely."); + throw new InvalidOperationException("Gitversion could not determine which branch to treat as the development branch (default = develop) nor release branch (default = main or master), neither locally nor remotely. Ensure the local clone and checkout match the requirements or considering using 'Gitversion Dynamic Repositories'"); } log.Warning($"{errorMessage}{System.Environment.NewLine}Falling back to {chosenBranch} branch config"); From 837ab61894c62cd32952d3040830b9693b2b4b50 Mon Sep 17 00:00:00 2001 From: Darwin Date: Mon, 28 Jun 2021 09:24:44 -0400 Subject: [PATCH 27/79] Update BranchConfigurationCalculator.cs --- .../Configuration/BranchConfigurationCalculator.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/GitVersion.Core/Configuration/BranchConfigurationCalculator.cs b/src/GitVersion.Core/Configuration/BranchConfigurationCalculator.cs index 11d51c628f..dcc8e077a1 100644 --- a/src/GitVersion.Core/Configuration/BranchConfigurationCalculator.cs +++ b/src/GitVersion.Core/Configuration/BranchConfigurationCalculator.cs @@ -132,7 +132,7 @@ private BranchConfig InheritBranchConfiguration(IBranch targetBranch, BranchConf { // TODO We should call the build server to generate this exception, each build server works differently // for fetch issues and we could give better warnings. - throw new InvalidOperationException("Gitversion could not determine which branch to treat as the development branch (default = develop) nor release branch (default = main or master), neither locally nor remotely. Ensure the local clone and checkout match the requirements or considering using 'Gitversion Dynamic Repositories'"); + throw new InvalidOperationException("Gitversion could not determine which branch to treat as the development branch (default is 'develop') nor releaseable branch (default is 'main' or 'master'), either locally or remotely. Ensure the local clone and checkout match the requirements or considering using 'GitVersion Dynamic Repositories'"); } log.Warning($"{errorMessage}{System.Environment.NewLine}Falling back to {chosenBranch} branch config"); From 17cf0dff4210ff3622a3bbc461e9bb367e9db74a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 29 Jun 2021 15:03:24 +0000 Subject: [PATCH 28/79] Bump YamlDotNet from 11.2.0 to 11.2.1 Bumps [YamlDotNet](https://github.com/aaubry/YamlDotNet) from 11.2.0 to 11.2.1. - [Release notes](https://github.com/aaubry/YamlDotNet/releases) - [Commits](https://github.com/aaubry/YamlDotNet/compare/v11.2.0...v11.2.1) --- updated-dependencies: - dependency-name: YamlDotNet dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- src/Directory.Build.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Directory.Build.props b/src/Directory.Build.props index edf2bf8767..4a4a70510c 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -25,7 +25,7 @@ 2.0.312 2021.1.0 - 11.2.0 + 11.2.1 5.0.0 5.0.0 5.0.0 From d79ca2280b389374371adc97e33f97801575bde8 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 2 Jul 2021 15:04:16 +0000 Subject: [PATCH 29/79] Bump Mono.Cecil from 0.11.3 to 0.11.4 Bumps [Mono.Cecil](https://github.com/jbevain/cecil) from 0.11.3 to 0.11.4. - [Release notes](https://github.com/jbevain/cecil/releases) - [Commits](https://github.com/jbevain/cecil/compare/0.11.3...0.11.4) --- updated-dependencies: - dependency-name: Mono.Cecil dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- src/GitVersion.App.Tests/GitVersion.App.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/GitVersion.App.Tests/GitVersion.App.Tests.csproj b/src/GitVersion.App.Tests/GitVersion.App.Tests.csproj index 0bf680f272..0b81e83d89 100644 --- a/src/GitVersion.App.Tests/GitVersion.App.Tests.csproj +++ b/src/GitVersion.App.Tests/GitVersion.App.Tests.csproj @@ -6,7 +6,7 @@ - + From bfa6149fe2a214a1416ac9034b7d010f63c3fba4 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 5 Jul 2021 15:04:22 +0000 Subject: [PATCH 30/79] Bump LibGit2Sharp from 0.27.0-preview-0096 to 0.27.0-preview-0102 Bumps [LibGit2Sharp](https://github.com/libgit2/libgit2sharp) from 0.27.0-preview-0096 to 0.27.0-preview-0102. - [Release notes](https://github.com/libgit2/libgit2sharp/releases) - [Changelog](https://github.com/libgit2/libgit2sharp/blob/master/CHANGES.md) - [Commits](https://github.com/libgit2/libgit2sharp/commits) --- updated-dependencies: - dependency-name: LibGit2Sharp dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- src/Directory.Build.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 4a4a70510c..d9bd225cdc 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -21,7 +21,7 @@ - 0.27.0-preview-0096 + 0.27.0-preview-0102 2.0.312 2021.1.0 From 2748f1495924a1cf074fec7e74167743dbb5030e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Asbj=C3=B8rn=20Ulsberg?= Date: Mon, 12 Jul 2021 14:51:17 +0200 Subject: [PATCH 31/79] Change from inline to reference links --- docs/input/docs/learn/faq.md | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/docs/input/docs/learn/faq.md b/docs/input/docs/learn/faq.md index e09e74db40..decd5f770b 100644 --- a/docs/input/docs/learn/faq.md +++ b/docs/input/docs/learn/faq.md @@ -6,28 +6,25 @@ Title: FAQ ## Why is my version not incrementing? GitVersion calculates the semantic version, this will only change once per -_release_. Read more at [version increments](/docs/reference/version-increments) +_release_. Read more about [version increments][increments]. ## I'm using Octopus deploy Because Octopus deploy cannot have the same version of a package to a NuGet feed. There is no magic solution to this, but you can read more about your -options at [octopus deploy](/docs/reference/build-servers/octopus-deploy). +options at [octopus deploy][octopus]. ## How can GitVersion run for a shallow clone or checkout on server working directories GitVersion needs a proper git repository to run, some build servers do not do a -proper clone which can cause issues. GitVersion has a feature called -[dynamic repositories](/docs/learn/dynamic-repositories) which solves this by -cloning the repository and working against that clone instead of the working -directory. +proper clone which can cause issues. GitVersion has a feature called [dynamic +repositories][dynamic-repos] which solves this by cloning the repository and +working against that clone instead of the working directory. ## I don't understand what SemVer is all about -Not a problem, we have a quick introduction to SemVer which can be a good primer -to read before reading [SemVer.org](https://semver.org) - -Read more at [intro to semver](/docs/learn/intro-to-semver) +Not a problem, we have a quick [introduction to SemVer][semver-intro] which can +be a good primer to read before reading [SemVer.org][semver]. ## I can't use the build number for NuGet @@ -58,3 +55,9 @@ If you run `gitversion init` then choose `Getting started wizard` then choose `Unsure, tell me more`, GitVersion will run through a series of questions which will try and help point you towards a branching strategy and why you would use it. + +[dynamic-repos]: /docs/learn/dynamic-repositories +[increments]: /docs/reference/version-increments +[octopus]: /docs/reference/build-servers/octopus-deploy +[semver-intro]: /docs/learn/intro-to-semver +[semver]: https://semver.org From e5a3bb0b854e806d85acc99b462f98bdf6a1458a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Asbj=C3=B8rn=20Ulsberg?= Date: Mon, 12 Jul 2021 14:57:48 +0200 Subject: [PATCH 32/79] Improve formatting and add link to variables --- docs/input/docs/learn/faq.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/input/docs/learn/faq.md b/docs/input/docs/learn/faq.md index decd5f770b..98601bcd01 100644 --- a/docs/input/docs/learn/faq.md +++ b/docs/input/docs/learn/faq.md @@ -29,11 +29,10 @@ be a good primer to read before reading [SemVer.org][semver]. ## I can't use the build number for NuGet If you have used NuGet you would notice the versions above are not compatible -with NuGet. GitVersion solves this by providing _variables_. +with NuGet. GitVersion solves this by providing [variables]. -What you have seen above is the **SemVer** variable. You can use the -**NuGetVersion** variable to have the version formatted in a NuGet compatible -way. +What you have seen above is the `SemVer` variable. You can use the +`NuGetVersion` variable to have the version formatted in a NuGet compatible way. So `1.0.1-rc.1+5` would become `1.0.1-rc0001`, this takes into account characters which are not allowed and NuGets crap sorting. @@ -61,3 +60,4 @@ it. [octopus]: /docs/reference/build-servers/octopus-deploy [semver-intro]: /docs/learn/intro-to-semver [semver]: https://semver.org +[variables]: /docs/reference/variables From ee56d1722612450fdeaaa56b6edca00835a94fdc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Asbj=C3=B8rn=20Ulsberg?= Date: Mon, 12 Jul 2021 15:21:47 +0200 Subject: [PATCH 33/79] Add FAQ section for merged branch names --- docs/input/docs/learn/faq.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/docs/input/docs/learn/faq.md b/docs/input/docs/learn/faq.md index 98601bcd01..42cbd7a9ef 100644 --- a/docs/input/docs/learn/faq.md +++ b/docs/input/docs/learn/faq.md @@ -55,6 +55,25 @@ If you run `gitversion init` then choose `Getting started wizard` then choose will try and help point you towards a branching strategy and why you would use it. +## Merged branch names as version source + +When GitVersion considers previous commits to calculate a version number, it's +important that the metadata to be considered is _stable_. Since branches are +usually deleted after they are merged, the name of a branch can't be considered +as a stable version source. _Branch names are not stable_, they are ephemeral. + +The only place a branch name can be considered for version calculation is for +the branch itself. This is typically used for `release/*` branches, which +usually have a version number in their name. For the release branch +`release/1.2.3`, the verison number `1.2.3` will be used to calculate the final +version number _for the release branch_. + +However, when the `release/1.2.3` branch is merged into `main`, the fact that +the merged commits came from a branch named `release/1.2.3` vanishes with the +branch which will be deleted. The name of the merged release branch can +therefore not be considered for version calculation in the target branch of the +merge. + [dynamic-repos]: /docs/learn/dynamic-repositories [increments]: /docs/reference/version-increments [octopus]: /docs/reference/build-servers/octopus-deploy From c2373faf78cb342f9cb83fd38494acb41e0e4749 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Asbj=C3=B8rn=20Ulsberg?= Date: Mon, 12 Jul 2021 15:23:12 +0200 Subject: [PATCH 34/79] Add link from Version Increments to FAQ Also clean up Version Incremnets a bit. --- .../docs/reference/version-increments.md | 85 ++++++++++--------- 1 file changed, 46 insertions(+), 39 deletions(-) diff --git a/docs/input/docs/reference/version-increments.md b/docs/input/docs/reference/version-increments.md index 147c96b646..d8cf337ca8 100644 --- a/docs/input/docs/reference/version-increments.md +++ b/docs/input/docs/reference/version-increments.md @@ -4,7 +4,7 @@ Title: Version Incrementing Description: Details on how GitVersion performs version increments --- -Because GitVersion works with a number of workflows the way it does its version +Because GitVersion works with several workflows, the way it does its version incrementing may work perfectly for you, or it may cause you issues. This page is split up into two sections, first is all about understanding the approach GitVersion uses by default, and the second is how you can manually increment the @@ -16,16 +16,16 @@ Semantic Versioning is all about _releases_, not builds. This means that the version only increases after you release, this directly conflicts with the concept of published CI builds. When you release the next version of your library/app/website/whatever you should only increment major/minor or patch then -reset all lower parts to 0, for instance given 1.0.0, the next release should be -either `2.0.0`, `1.1.0` or `1.0.1`. +reset all lower parts to 0, for instance given `1.0.0`, the next release should +be either `2.0.0`, `1.1.0` or `1.0.1`. Because of this, GitVersion works out what the next SemVer of your app is on -each commit. When you are ready to release you simply deploy the latest built -version and tag the release it was from. This practice is called -**continuous delivery**. GitVersion will increment the _metadata_ for each build -so you can tell builds apart. For example `1.0.0+5` followed by `1.0.0+6`. It is -important to note that build metadata _is not part of the semantic version, it -is just metadata!_. +each commit. When you are ready to release, you simply deploy the latest built +version and tag the commit it was created from. This practice is called +[continuous delivery][continuous-delivery]. GitVersion will increment the +_metadata_ for each build so you can tell builds apart. For example `1.0.0+5` +followed by `1.0.0+6`. It is important to note that build metadata _is not part +of the semantic version; it is just metadata!_. All this effectively means that GitVersion will produce the same version NuGet package each commit until you tag a release. @@ -42,7 +42,7 @@ _increment on every commit_. This is known in GitVersion as _continuous deployment mode_. By default `develop` builds are tagged with the `alpha` pre-release tag. This is so they are sorted higher than release branches. -If you need to consume packages built from develop, we recommend publishing +If you need to consume packages built from `develop`, we recommend publishing these packages to a separate NuGet feed as an alpha channel. That way you can publish beta/release candidate builds and only people who opt into the alpha feed will see the alpha packages. @@ -53,7 +53,7 @@ See [Octopus deploy](/docs/reference/build-servers/octopus-deploy) ## Manually incrementing the version -With v3 there are multiple approaches. +With v3 there are multiple approaches. Read about these below. ### Commit messages @@ -76,19 +76,19 @@ commit-message-incrementing: Enabled The options for `commit-message-incrementing` are `Enabled`, `MergeMessageOnly` and `Disabled` -If the incrementing mode is set to `MergeMessageOnly` you can add this -information in when merging a pull request. This prevents commits within a PR -bumping the version. +If the incrementing `mode` is set to `MergeMessageOnly` you can add this +information when merging a pull request. This prevents commits within a PR to +bump the version number. -One thing to be aware of: If the current version is an alpha-version -(i.e. 0.x.y.), attempting to bump the major version will merely bump the minor -(eg from 0.2.0 to 0.3.0 instead of 1.0.0). Once the current version is greater -than 1.0.0, bumping the major version works as expected. +One thing to be aware of: If the current version is an alpha-version (i.e. +`0.x.y`.), attempting to bump the major version will merely bump the minor (eg +from `0.2.0` to `0.3.0` instead of `1.0.0`). Once the current version is greater +than `1.0.0`, bumping the major version works as expected. #### Conventional commit messages -If you want to use the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) -standard, you can leverage this feature as follows: +If you want to use the [Conventional Commits][conventional-commits] standard, +you can leverage this feature as follows: ```yaml mode: MainLine # Only add this if you want every version to be created automatically on your main branch. @@ -97,7 +97,8 @@ minor-version-bump-message: "^(feat)(\\([\\w\\s]*\\))?:" patch-version-bump-message: "^(build|chore|ci|docs|fix|perf|refactor|revert|style|test)(\\([\\w\\s]*\\))?:" ``` -This will ensure that your version gets bumped according to the commits you've created. +This will ensure that your version gets bumped according to the commits you've +created. ### GitVersion.yml @@ -106,9 +107,10 @@ This property only serves as a base version, ### Branch name -If you create a branch with the version number in the branch name such as +If you create a branch with the version number in the branch name, such as `release-1.2.0` or `hotfix/1.0.1` then GitVersion will take the version number -from the branch name as a source +from the branch name as a source. However, GitVersion can't use the [branch +name as a version source for _other branches_][faq-branch-name-source]. ### Tagging commit @@ -118,27 +120,32 @@ rules for that branch (some branches bump patch, some minor). ### Incrementing per commit -When using the continuous deployment mode (which will increment the SemVer every -commit) all builds _must_ have a pre-release tag, except for builds which are +When using the continuous deployment `mode` (which will increment the SemVer every +commit) all builds _must_ have a pre-release tag, except for builds that are explicitly tagged as stable. Then the build metadata (which is the commit count) is promoted to the -pre-release tag. Applying those rules the above commit graph would produce: +pre-release tag. Applying these rules, the above commit-graph would produce: ``` -e137e9 -> 1.0.0+0 -a5f6c5 -> 1.0.1-ci.1 -adb29a -> 1.0.1-feature-foo.1 (PR #5 Version: `1.0.1-PullRequest.5+2`) -7c2438 -> 1.0.1-feature-foo.2 (PR #5 Version: `1.0.1-PullRequest.5+3`) -5f413b -> 1.0.1-ci.4 -d6155b -> 2.0.0-rc.1+4 (Before and after tag) -d53ab6 -> 2.0.0-rc.2 (If there was another commit on the release branch it would be 2.0.0-rc.3) -b5d142 -> 2.0.0-ci.0 (2.0.0 branch was merged, so main is now at 2.0.0) +e137e9 -> 1.0.0+0 +a5f6c5 -> 1.0.1-ci.1 +adb29a -> 1.0.1-feature-foo.1 (PR #5 Version: `1.0.1-PullRequest.5+2`) +7c2438 -> 1.0.1-feature-foo.2 (PR #5 Version: `1.0.1-PullRequest.5+3`) +5f413b -> 1.0.1-ci.4 +d6155b -> 2.0.0-rc.1+4 (Before and after tag) +d53ab6 -> 2.0.0-rc.2 (If there was another commit on the release branch it would be 2.0.0-rc.3) +b5d142 -> 2.0.0-ci.0 (2.0.0 branch was merged, so main is now at 2.0.0) ``` -As you can see the versions now no longer conflict. When you want to create a -stable `2.0.0` release you simply `git tag 2.0.0` then build the tag and it will -produce a stable 2.0.0 package. +As you can see, the versions now no longer conflict. When you want to create a +stable `2.0.0` release you simply `git tag 2.0.0`, then build the tag, and it +will produce a stable `2.0.0` package. -For more information/background on why we have come to this conclusion read -[Xavier Decoster's blog post on the subject](http://www.xavierdecoster.com/semantic-versioning-auto-incremented-nuget-package-versions). +For more information/background on why we have come to this conclusion, read +[Xavier Decoster's blog post on the subject][auto-incremented-nuget-package]. + +[auto-incremented-nuget-package]: http://www.xavierdecoster.com/semantic-versioning-auto-incremented-nuget-package-versions +[continuous-delivery]: /docs/reference/modes/continuous-delivery +[conventional-commits]: https://www.conventionalcommits.org/ +[faq-branch-name-source]: /docs/learn/faq#merged-branch-names-as-version-source From c863cd9d59f8f1364da9f6acbb5500c7a6fbed4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Thu, 15 Jul 2021 16:02:26 +0200 Subject: [PATCH 35/79] Make fields readonly where applicable --- src/GitVersion.App.Tests/Helpers/ProgramFixture.cs | 2 +- src/GitVersion.App/GlobbingResolver.cs | 2 +- src/GitVersion.App/OverrideConfigOptionParser.cs | 2 +- src/GitVersion.Core/Core/GitPreparer.cs | 3 ++- src/GitVersion.Core/Helpers/RetryAction.cs | 2 +- .../VersionInBranchNameVersionStrategy.cs | 2 +- src/GitVersion.LibGit2Sharp/Git/GitRepository.cs | 2 +- src/GitVersion.LibGit2Sharp/Git/GitRepositoryInfo.cs | 8 ++++---- 8 files changed, 12 insertions(+), 11 deletions(-) diff --git a/src/GitVersion.App.Tests/Helpers/ProgramFixture.cs b/src/GitVersion.App.Tests/Helpers/ProgramFixture.cs index 2d41e77795..56f46beccc 100644 --- a/src/GitVersion.App.Tests/Helpers/ProgramFixture.cs +++ b/src/GitVersion.App.Tests/Helpers/ProgramFixture.cs @@ -12,7 +12,7 @@ namespace GitVersion.App.Tests { public sealed class ProgramFixture { - private IEnvironment environment; + private readonly IEnvironment environment; public List> Overrides { get; } = new List>(); private readonly Lazy logger; private readonly Lazy output; diff --git a/src/GitVersion.App/GlobbingResolver.cs b/src/GitVersion.App/GlobbingResolver.cs index 31a4d56eba..4f1754b19f 100644 --- a/src/GitVersion.App/GlobbingResolver.cs +++ b/src/GitVersion.App/GlobbingResolver.cs @@ -9,7 +9,7 @@ namespace GitVersion { public class GlobbingResolver : IGlobbingResolver { - private Matcher matcher = new Matcher(StringComparison.OrdinalIgnoreCase); + private readonly Matcher matcher = new Matcher(StringComparison.OrdinalIgnoreCase); public IEnumerable Resolve(string workingDirectory, string pattern) { diff --git a/src/GitVersion.App/OverrideConfigOptionParser.cs b/src/GitVersion.App/OverrideConfigOptionParser.cs index c0e312a1e4..298fe78b35 100644 --- a/src/GitVersion.App/OverrideConfigOptionParser.cs +++ b/src/GitVersion.App/OverrideConfigOptionParser.cs @@ -10,7 +10,7 @@ internal class OverrideConfigOptionParser private static readonly Lazy> _lazySupportedProperties = new Lazy>(GetSupportedProperties, true); - private Lazy _lazyConfig = new Lazy(); + private readonly Lazy _lazyConfig = new Lazy(); internal ILookup SupportedProperties => _lazySupportedProperties.Value; diff --git a/src/GitVersion.Core/Core/GitPreparer.cs b/src/GitVersion.Core/Core/GitPreparer.cs index c8fad1df76..9cd1fc9685 100644 --- a/src/GitVersion.Core/Core/GitPreparer.cs +++ b/src/GitVersion.Core/Core/GitPreparer.cs @@ -20,7 +20,7 @@ public class GitPreparer : IGitPreparer private readonly IGitRepositoryInfo repositoryInfo; private readonly IRepositoryStore repositoryStore; private readonly ICurrentBuildAgent buildAgent; - private RetryAction retryAction; + private readonly RetryAction retryAction; private const string DefaultRemoteName = "origin"; @@ -39,6 +39,7 @@ public GitPreparer(ILog log, IEnvironment environment, ICurrentBuildAgent buildA public void Prepare() { + System.Diagnostics.Debugger.Launch(); var gitVersionOptions = options.Value; // Normalize if we are running on build server diff --git a/src/GitVersion.Core/Helpers/RetryAction.cs b/src/GitVersion.Core/Helpers/RetryAction.cs index 14b46c01d4..1a8e8127b9 100644 --- a/src/GitVersion.Core/Helpers/RetryAction.cs +++ b/src/GitVersion.Core/Helpers/RetryAction.cs @@ -24,7 +24,7 @@ public void Execute(Action operation) } public class RetryAction where T : Exception { - private RetryPolicy retryPolicy; + private readonly RetryPolicy retryPolicy; public RetryAction(int maxRetries = 5) { diff --git a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/VersionInBranchNameVersionStrategy.cs b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/VersionInBranchNameVersionStrategy.cs index 0195a845df..dacc623e76 100644 --- a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/VersionInBranchNameVersionStrategy.cs +++ b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/VersionInBranchNameVersionStrategy.cs @@ -13,7 +13,7 @@ namespace GitVersion.VersionCalculation /// public class VersionInBranchNameVersionStrategy : VersionStrategyBase { - private IRepositoryStore repositoryStore; + private readonly IRepositoryStore repositoryStore; public VersionInBranchNameVersionStrategy(IRepositoryStore repositoryStore, Lazy versionContext) : base(versionContext) { diff --git a/src/GitVersion.LibGit2Sharp/Git/GitRepository.cs b/src/GitVersion.LibGit2Sharp/Git/GitRepository.cs index 729994d3e3..eacd35e905 100644 --- a/src/GitVersion.LibGit2Sharp/Git/GitRepository.cs +++ b/src/GitVersion.LibGit2Sharp/Git/GitRepository.cs @@ -11,7 +11,7 @@ namespace GitVersion internal sealed class GitRepository : IMutatingGitRepository { private readonly ILog log; - private Lazy repositoryLazy; + private readonly Lazy repositoryLazy; private IRepository repositoryInstance => repositoryLazy.Value; public GitRepository(ILog log, IGitRepositoryInfo repositoryInfo) diff --git a/src/GitVersion.LibGit2Sharp/Git/GitRepositoryInfo.cs b/src/GitVersion.LibGit2Sharp/Git/GitRepositoryInfo.cs index 598ad464dc..e03aefffdf 100644 --- a/src/GitVersion.LibGit2Sharp/Git/GitRepositoryInfo.cs +++ b/src/GitVersion.LibGit2Sharp/Git/GitRepositoryInfo.cs @@ -10,10 +10,10 @@ internal class GitRepositoryInfo : IGitRepositoryInfo private readonly IOptions options; private GitVersionOptions gitVersionOptions => options.Value; - private Lazy dynamicGitRepositoryPath; - private Lazy dotGitDirectory; - private Lazy gitRootPath; - private Lazy projectRootDirectory; + private readonly Lazy dynamicGitRepositoryPath; + private readonly Lazy dotGitDirectory; + private readonly Lazy gitRootPath; + private readonly Lazy projectRootDirectory; public GitRepositoryInfo(IOptions options) { From 119851c114e45106beb225f8a1a7c965dfb63456 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Thu, 15 Jul 2021 17:38:16 +0200 Subject: [PATCH 36/79] Split throw part from the yielding function --- src/GitVersion.Core/Core/RepositoryStore.cs | 68 +++++++++++---------- 1 file changed, 37 insertions(+), 31 deletions(-) diff --git a/src/GitVersion.Core/Core/RepositoryStore.cs b/src/GitVersion.Core/Core/RepositoryStore.cs index feba667620..5be24cdc89 100644 --- a/src/GitVersion.Core/Core/RepositoryStore.cs +++ b/src/GitVersion.Core/Core/RepositoryStore.cs @@ -239,52 +239,58 @@ public IEnumerable ExcludingBranches(IEnumerable branchesToExc // TODO Should we cache this? public IEnumerable GetBranchesContainingCommit(ICommit commit, IEnumerable branches = null, bool onlyTrackedBranches = false) { - branches ??= repository.Branches.ToList(); - static bool IncludeTrackedBranches(IBranch branch, bool includeOnlyTracked) => includeOnlyTracked && branch.IsTracking || !includeOnlyTracked; - if (commit == null) { throw new ArgumentNullException(nameof(commit)); } - using (log.IndentLog($"Getting branches containing the commit '{commit.Id}'.")) + + branches ??= repository.Branches.ToList(); + static bool IncludeTrackedBranches(IBranch branch, bool includeOnlyTracked) => includeOnlyTracked && branch.IsTracking || !includeOnlyTracked; + + return Impl(); + + IEnumerable Impl() { - var directBranchHasBeenFound = false; - log.Info("Trying to find direct branches."); - // TODO: It looks wasteful looping through the branches twice. Can't these loops be merged somehow? @asbjornu - var branchList = branches.ToList(); - foreach (var branch in branchList) + using (log.IndentLog($"Getting branches containing the commit '{commit.Id}'.")) { - if (branch.Tip != null && branch.Tip.Sha != commit.Sha || IncludeTrackedBranches(branch, onlyTrackedBranches)) + var directBranchHasBeenFound = false; + log.Info("Trying to find direct branches."); + // TODO: It looks wasteful looping through the branches twice. Can't these loops be merged somehow? @asbjornu + var branchList = branches.ToList(); + foreach (var branch in branchList) { - continue; + if (branch.Tip != null && branch.Tip.Sha != commit.Sha || IncludeTrackedBranches(branch, onlyTrackedBranches)) + { + continue; + } + + directBranchHasBeenFound = true; + log.Info($"Direct branch found: '{branch}'."); + yield return branch; } - directBranchHasBeenFound = true; - log.Info($"Direct branch found: '{branch}'."); - yield return branch; - } + if (directBranchHasBeenFound) + { + yield break; + } - if (directBranchHasBeenFound) - { - yield break; - } + log.Info($"No direct branches found, searching through {(onlyTrackedBranches ? "tracked" : "all")} branches."); + foreach (var branch in branchList.Where(b => IncludeTrackedBranches(b, onlyTrackedBranches))) + { + log.Info($"Searching for commits reachable from '{branch}'."); - log.Info($"No direct branches found, searching through {(onlyTrackedBranches ? "tracked" : "all")} branches."); - foreach (var branch in branchList.Where(b => IncludeTrackedBranches(b, onlyTrackedBranches))) - { - log.Info($"Searching for commits reachable from '{branch}'."); + var commits = GetCommitsReacheableFrom(commit, branch); - var commits = GetCommitsReacheableFrom(commit, branch); + if (!commits.Any()) + { + log.Info($"The branch '{branch}' has no matching commits."); + continue; + } - if (!commits.Any()) - { - log.Info($"The branch '{branch}' has no matching commits."); - continue; + log.Info($"The branch '{branch}' has a matching commit."); + yield return branch; } - - log.Info($"The branch '{branch}' has a matching commit."); - yield return branch; } } } From 15a66bf3945a12a7b1b2c967ffa6e7d79de4ad06 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Fri, 16 Jul 2021 14:01:31 +0200 Subject: [PATCH 37/79] Address review comments --- .../Core/RepositoryStoreTests.cs | 11 +++++++++++ src/GitVersion.Core/Core/RepositoryStore.cs | 10 ++++++---- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/GitVersion.Core.Tests/Core/RepositoryStoreTests.cs b/src/GitVersion.Core.Tests/Core/RepositoryStoreTests.cs index bcd187409c..7614db60f3 100644 --- a/src/GitVersion.Core.Tests/Core/RepositoryStoreTests.cs +++ b/src/GitVersion.Core.Tests/Core/RepositoryStoreTests.cs @@ -6,6 +6,7 @@ using Microsoft.Extensions.DependencyInjection; using NUnit.Framework; using Shouldly; +using NSubstitute.ExceptionExtensions; namespace GitVersion.Core.Tests { @@ -204,5 +205,15 @@ public void FindsCorrectMergeBaseForMultipleForwardMerges() releaseBranchMergeBase.ShouldBe(expectedReleaseMergeBase); developMergeBase.ShouldBe(expectedDevelopMergeBase); } + + [Test] + public void GetBranchesContainingCommitThrowsDirectlyOnNullCommit() + { + using var fixture = new EmptyRepositoryFixture(); + var fixtureRepository = fixture.Repository.ToGitRepository(); + var gitRepoMetadataProvider = new RepositoryStore(log, fixtureRepository); + + Assert.Throws(() => gitRepoMetadataProvider.GetBranchesContainingCommit(null)); + } } } diff --git a/src/GitVersion.Core/Core/RepositoryStore.cs b/src/GitVersion.Core/Core/RepositoryStore.cs index 5be24cdc89..9aa06f81be 100644 --- a/src/GitVersion.Core/Core/RepositoryStore.cs +++ b/src/GitVersion.Core/Core/RepositoryStore.cs @@ -244,14 +244,16 @@ public IEnumerable GetBranchesContainingCommit(ICommit commit, IEnumera throw new ArgumentNullException(nameof(commit)); } + return InnerGetBranchesContainingCommit(); - branches ??= repository.Branches.ToList(); static bool IncludeTrackedBranches(IBranch branch, bool includeOnlyTracked) => includeOnlyTracked && branch.IsTracking || !includeOnlyTracked; - return Impl(); - - IEnumerable Impl() + // Yielding part is split from the main part of the method to avoid having the exception check performed lazily. + // Details at https://github.com/GitTools/GitVersion/issues/2755 + IEnumerable InnerGetBranchesContainingCommit() { + branches ??= repository.Branches.ToList(); + using (log.IndentLog($"Getting branches containing the commit '{commit.Id}'.")) { var directBranchHasBeenFound = false; From 22a434370012c900c4fe8408d416523e4d227604 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Fri, 16 Jul 2021 14:06:23 +0200 Subject: [PATCH 38/79] Refactor versionVariables as local variable. In GitVersionTaskExecutor, the field versionVariables was always assigned before being used so there is no point in keeping it as a field. --- src/GitVersion.MsBuild/GitVersionTaskExecutor.cs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/GitVersion.MsBuild/GitVersionTaskExecutor.cs b/src/GitVersion.MsBuild/GitVersionTaskExecutor.cs index 13472af54c..490d41ced6 100644 --- a/src/GitVersion.MsBuild/GitVersionTaskExecutor.cs +++ b/src/GitVersion.MsBuild/GitVersionTaskExecutor.cs @@ -13,7 +13,6 @@ public class GitVersionTaskExecutor : IGitVersionTaskExecutor private readonly ILog log; private readonly IGitVersionOutputTool gitVersionOutputTool; private readonly IOptions options; - private VersionVariables versionVariables; public GitVersionTaskExecutor(IFileSystem fileSystem, IGitVersionOutputTool gitVersionOutputTool, IOptions options, ILog log) { @@ -25,7 +24,7 @@ public GitVersionTaskExecutor(IFileSystem fileSystem, IGitVersionOutputTool gitV public void GetVersion(GetVersion task) { - versionVariables = VersionVariables.FromFile(task.VersionFile, fileSystem, log); + var versionVariables = VersionVariables.FromFile(task.VersionFile, fileSystem, log); var outputType = typeof(GetVersion); foreach (var variable in versionVariables) { @@ -35,7 +34,7 @@ public void GetVersion(GetVersion task) public void UpdateAssemblyInfo(UpdateAssemblyInfo task) { - versionVariables = VersionVariables.FromFile(task.VersionFile, fileSystem, log); + var versionVariables = VersionVariables.FromFile(task.VersionFile, fileSystem, log); FileHelper.DeleteTempFiles(); if (task.CompileFiles != null) FileHelper.CheckForInvalidFiles(task.CompileFiles, task.ProjectFile); @@ -53,7 +52,7 @@ public void UpdateAssemblyInfo(UpdateAssemblyInfo task) public void GenerateGitVersionInformation(GenerateGitVersionInformation task) { - versionVariables = VersionVariables.FromFile(task.VersionFile, fileSystem, log); + var versionVariables = VersionVariables.FromFile(task.VersionFile, fileSystem, log); var fileWriteInfo = task.IntermediateOutputPath.GetFileWriteInfo(task.Language, task.ProjectFile, "GitVersionInformation"); task.GitVersionInformationFilePath = Path.Combine(fileWriteInfo.WorkingDirectory, fileWriteInfo.FileName); @@ -65,7 +64,7 @@ public void GenerateGitVersionInformation(GenerateGitVersionInformation task) public void WriteVersionInfoToBuildLog(WriteVersionInfoToBuildLog task) { - versionVariables = VersionVariables.FromFile(task.VersionFile, fileSystem, log); + var versionVariables = VersionVariables.FromFile(task.VersionFile, fileSystem, log); gitVersionOutputTool.OutputVariables(versionVariables, false); } } From e91d69a7629cae071103e43aaeb9c7b5045a5c77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Fri, 16 Jul 2021 14:12:35 +0200 Subject: [PATCH 39/79] Make local function static --- src/GitVersion.Core/Core/RepositoryStore.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/GitVersion.Core/Core/RepositoryStore.cs b/src/GitVersion.Core/Core/RepositoryStore.cs index 9aa06f81be..14567160ed 100644 --- a/src/GitVersion.Core/Core/RepositoryStore.cs +++ b/src/GitVersion.Core/Core/RepositoryStore.cs @@ -244,13 +244,13 @@ public IEnumerable GetBranchesContainingCommit(ICommit commit, IEnumera throw new ArgumentNullException(nameof(commit)); } - return InnerGetBranchesContainingCommit(); + return InnerGetBranchesContainingCommit(commit, branches, onlyTrackedBranches, repository, log); static bool IncludeTrackedBranches(IBranch branch, bool includeOnlyTracked) => includeOnlyTracked && branch.IsTracking || !includeOnlyTracked; // Yielding part is split from the main part of the method to avoid having the exception check performed lazily. // Details at https://github.com/GitTools/GitVersion/issues/2755 - IEnumerable InnerGetBranchesContainingCommit() + static IEnumerable InnerGetBranchesContainingCommit(ICommit commit, IEnumerable branches, bool onlyTrackedBranches, IGitRepository repository, ILog log) { branches ??= repository.Branches.ToList(); @@ -282,7 +282,7 @@ IEnumerable InnerGetBranchesContainingCommit() { log.Info($"Searching for commits reachable from '{branch}'."); - var commits = GetCommitsReacheableFrom(commit, branch); + var commits = GetCommitsReacheableFrom(repository, commit, branch); if (!commits.Any()) { @@ -482,7 +482,7 @@ private IEnumerable GetMergeCommitsForBranch(IBranch branch, Confi return branchMergeBases; } - private IEnumerable GetCommitsReacheableFrom(ICommit commit, IBranch branch) + private static IEnumerable GetCommitsReacheableFrom(IGitRepository repository, ICommit commit, IBranch branch) { var filter = new CommitFilter { From 011b0723216ad68198811520f088bbcdcc2c8722 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Sun, 18 Jul 2021 11:20:21 +0200 Subject: [PATCH 40/79] Remove Debugger.Launch --- src/GitVersion.Core/Core/GitPreparer.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/GitVersion.Core/Core/GitPreparer.cs b/src/GitVersion.Core/Core/GitPreparer.cs index 9cd1fc9685..8ef3da6326 100644 --- a/src/GitVersion.Core/Core/GitPreparer.cs +++ b/src/GitVersion.Core/Core/GitPreparer.cs @@ -39,7 +39,6 @@ public GitPreparer(ILog log, IEnvironment environment, ICurrentBuildAgent buildA public void Prepare() { - System.Diagnostics.Debugger.Launch(); var gitVersionOptions = options.Value; // Normalize if we are running on build server From 14cfd0c21e9b5cbb7be5d9bd9dc406262b8bc954 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 21 Jul 2021 15:04:32 +0000 Subject: [PATCH 41/79] Bump JetBrains.Annotations from 2021.1.0 to 2021.2.0 Bumps JetBrains.Annotations from 2021.1.0 to 2021.2.0. --- updated-dependencies: - dependency-name: JetBrains.Annotations dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- src/Directory.Build.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Directory.Build.props b/src/Directory.Build.props index d9bd225cdc..1528d94ebc 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -24,7 +24,7 @@ 0.27.0-preview-0102 2.0.312 - 2021.1.0 + 2021.2.0 11.2.1 5.0.0 5.0.0 From 80d8a9c9a7ddd92ee1904951db1004d6c07032f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Mon, 19 Jul 2021 18:38:47 +0200 Subject: [PATCH 42/79] Enable nullable feature on GitVersion.Core --- .../Helpers/ArgumentBuilder.cs | 11 +- .../Helpers/GitVersionHelper.cs | 3 +- .../Helpers/ProgramFixture.cs | 5 +- src/GitVersion.App/ArgumentParser.cs | 8 +- src/GitVersion.App/QuotedStringHelpers.cs | 3 +- .../DefaultConfigFileLocatorTests.cs | 5 +- .../BuildAgents/Abstractions/IBuildAgent.cs | 4 +- .../Abstractions/IBuildAgentResolver.cs | 2 +- src/GitVersion.Core/BuildAgents/AppVeyor.cs | 3 +- .../BuildAgents/AzurePipelines.cs | 2 +- .../BuildAgents/BuildAgentBase.cs | 9 +- .../BuildAgents/BuildAgentResolver.cs | 4 +- .../BuildAgents/BuildServerModule.cs | 2 + src/GitVersion.Core/BuildAgents/CodeBuild.cs | 9 +- src/GitVersion.Core/BuildAgents/Drone.cs | 7 +- src/GitVersion.Core/BuildAgents/EnvRun.cs | 3 +- .../BuildAgents/GitHubActions.cs | 5 +- src/GitVersion.Core/BuildAgents/GitLabCi.cs | 4 +- src/GitVersion.Core/BuildAgents/Jenkins.cs | 7 +- src/GitVersion.Core/BuildAgents/MyGet.cs | 5 +- src/GitVersion.Core/BuildAgents/TeamCity.cs | 7 +- .../IBranchConfigurationCalculator.cs | 2 +- .../Abstractions/IConfigFileLocator.cs | 4 +- .../Abstractions/IConfigProvider.cs | 4 +- .../BranchConfigurationCalculator.cs | 30 ++-- .../Configuration/ConfigExtensions.cs | 22 +-- .../Configuration/ConfigFileLocator.cs | 17 +- .../Configuration/ConfigProvider.cs | 4 +- .../Configuration/ConfigurationBuilder.cs | 16 +- .../Init/BuildServer/AppVeyorSetup.cs | 4 +- .../Init/BuildServer/AppveyorPublicPrivate.cs | 8 +- .../Init/BuildServer/SetupBuildScripts.cs | 6 +- .../Configuration/Init/EditConfigStep.cs | 16 +- .../AssemblyVersioningSchemeSetting.cs | 4 +- .../Init/SetConfig/ConfigureBranch.cs | 16 +- .../Init/SetConfig/ConfigureBranches.cs | 10 +- .../Init/SetConfig/GlobalModeSetting.cs | 13 +- .../Init/SetConfig/SetBranchIncrementMode.cs | 13 +- .../Init/SetConfig/SetBranchTag.cs | 17 +- .../Configuration/Init/SetNextVersion.cs | 9 +- .../Init/Wizard/ConfigInitStepFactory.cs | 4 +- .../Init/Wizard/ConfigInitWizard.cs | 4 +- .../Init/Wizard/ConfigInitWizardStep.cs | 7 +- .../Init/Wizard/IConfigInitStepFactory.cs | 2 +- .../Init/Wizard/IConfigInitWizard.cs | 2 +- .../Init/Wizard/PickBranchingStrategy1Step.cs | 10 +- .../Init/Wizard/PickBranchingStrategy2Step.cs | 10 +- .../Init/Wizard/PickBranchingStrategy3Step.cs | 8 +- .../Init/Wizard/PickBranchingStrategyStep.cs | 10 +- .../Core/Abstractions/IFileSystem.cs | 8 +- .../Abstractions/IGitVersionContextFactory.cs | 2 +- .../Core/Abstractions/IRepositoryStore.cs | 30 ++-- src/GitVersion.Core/Core/FileSystem.cs | 8 +- src/GitVersion.Core/Core/GitPreparer.cs | 48 +++--- .../Core/GitVersionCalculateTool.cs | 2 +- .../Core/GitVersionContextFactory.cs | 8 +- .../Core/GitVersionOutputTool.cs | 2 +- src/GitVersion.Core/Core/RepositoryStore.cs | 72 ++++----- .../AssemblyVersionsGeneratorExtensions.cs | 8 +- .../Extensions/EnumerableExtensions.cs | 2 +- .../Extensions/GitExtensions.cs | 2 +- .../Extensions/NullableAttributes.cs | 149 ++++++++++++++++++ .../Extensions/ServiceCollectionExtensions.cs | 2 +- .../Extensions/StringExtensions.cs | 9 +- src/GitVersion.Core/Git/CommitFilter.cs | 4 +- src/GitVersion.Core/Git/IBranch.cs | 4 +- src/GitVersion.Core/Git/IBranchCollection.cs | 2 +- src/GitVersion.Core/Git/IGitRepository.cs | 2 +- src/GitVersion.Core/Git/IGitRepositoryInfo.cs | 8 +- .../Git/IMutatingGitRepository.cs | 4 +- src/GitVersion.Core/Git/IReference.cs | 2 +- .../Git/IReferenceCollection.cs | 4 +- src/GitVersion.Core/Git/IRemoteCollection.cs | 2 +- src/GitVersion.Core/Git/ITag.cs | 2 +- src/GitVersion.Core/Git/ReferenceName.cs | 4 +- src/GitVersion.Core/GitVersion.Core.csproj | 1 + src/GitVersion.Core/GitVersionCoreModule.cs | 2 +- src/GitVersion.Core/Helpers/EncodingHelper.cs | 6 +- .../Helpers/LambdaEqualityHelper.cs | 6 +- .../Helpers/LambdaKeyComparer.cs | 2 +- src/GitVersion.Core/Helpers/ProcessHelper.cs | 14 +- .../Helpers/ServiceMessageEscapeHelper.cs | 2 +- .../Helpers/StringFormatWith.cs | 10 +- .../Logging/Abstractions/IConsole.cs | 2 +- src/GitVersion.Core/Logging/ConsoleAdapter.cs | 2 +- src/GitVersion.Core/Logging/Disposable.cs | 2 +- src/GitVersion.Core/Logging/NullLog.cs | 2 +- .../Model/AuthenticationInfo.cs | 6 +- src/GitVersion.Core/Model/ConfigInfo.cs | 4 +- .../Model/Configuration/BranchConfig.cs | 12 +- .../Model/Configuration/Config.cs | 28 ++-- .../Configuration/EffectiveConfiguration.cs | 54 +++---- .../Model/GitVersionCacheKey.cs | 3 +- .../Model/GitVersionContext.cs | 12 +- .../Model/GitVersionOptions.cs | 8 +- src/GitVersion.Core/Model/MergeMessage.cs | 17 +- src/GitVersion.Core/Model/RepositoryInfo.cs | 8 +- src/GitVersion.Core/Model/VersionVariables.cs | 97 ++++++------ .../Model/VersionVariablesJsonModel.cs | 66 ++++---- .../VersionVariablesJsonNumberConverter.cs | 3 +- .../IMainlineVersionCalculator.cs | 2 +- .../Abstractions/IVersionFilter.cs | 4 +- .../BaseVersionCalculator.cs | 36 +++-- .../BaseVersionCalculators/BaseVersion.cs | 6 +- .../ConfigNextVersionVersionStrategy.cs | 5 +- .../FallbackVersionStrategy.cs | 2 +- .../MergeMessageVersionStrategy.cs | 12 +- .../TaggedCommitVersionStrategy.cs | 21 +-- .../TrackReleaseBranchesVersionStrategy.cs | 6 +- .../VersionInBranchNameVersionStrategy.cs | 9 +- .../Cache/GitVersionCache.cs | 2 +- .../Cache/GitVersionCacheKeyFactory.cs | 7 +- .../Cache/IGitVersionCache.cs | 2 +- .../Cache/IGitVersionCacheKeyFactory.cs | 2 +- .../IncrementStrategyFinder.cs | 25 +-- .../MainlineVersionCalculator.cs | 48 +++--- .../MinDateVersionFilter.cs | 3 +- .../NextVersionCalculator.cs | 34 ++-- .../SemanticVersioning/SemanticVersion.cs | 66 ++++---- .../SemanticVersionBuildMetaData.cs | 66 ++++---- .../SemanticVersionExtensions.cs | 3 +- .../SemanticVersionFormatValues.cs | 49 +++--- .../SemanticVersionPreReleaseTag.cs | 73 ++++----- .../VersionCalculation/ShaVersionFilter.cs | 3 +- .../VersionCalculation/VariableProvider.cs | 24 +-- .../AssemblyInfo/AssemblyInfoContext.cs | 4 +- .../AssemblyInfo/AssemblyInfoFileUpdater.cs | 21 +-- .../AssemblyInfo/ProjectFileUpdater.cs | 13 +- .../GitVersionInfo/GitVersionInfoContext.cs | 4 +- .../GitVersionInfo/GitVersionInfoGenerator.cs | 2 +- .../VersionConverters/IConverterContext.cs | 2 +- .../OutputGenerator/OutputContext.cs | 6 +- .../VersionConverters/TemplateManager.cs | 8 +- .../WixUpdater/WixVersionContext.cs | 4 +- .../WixUpdater/WixVersionFileUpdater.cs | 2 +- src/GitVersion.LibGit2Sharp/Git/Branch.cs | 2 +- src/GitVersion.LibGit2Sharp/Git/Commit.cs | 2 +- .../Git/CommitCollection.cs | 2 +- src/GitVersion.LibGit2Sharp/Git/GitObject.cs | 2 +- .../Git/GitRepository.cs | 19 ++- .../Git/GitRepositoryInfo.cs | 21 +-- src/GitVersion.LibGit2Sharp/Git/ObjectId.cs | 2 +- src/GitVersion.LibGit2Sharp/Git/RefSpec.cs | 2 +- src/GitVersion.LibGit2Sharp/Git/Reference.cs | 2 +- src/GitVersion.LibGit2Sharp/Git/Remote.cs | 2 +- src/GitVersion.LibGit2Sharp/Git/Tag.cs | 2 +- 146 files changed, 1000 insertions(+), 773 deletions(-) create mode 100644 src/GitVersion.Core/Extensions/NullableAttributes.cs diff --git a/src/GitVersion.App.Tests/Helpers/ArgumentBuilder.cs b/src/GitVersion.App.Tests/Helpers/ArgumentBuilder.cs index 6d3b78ac6d..7bf19bb74b 100644 --- a/src/GitVersion.App.Tests/Helpers/ArgumentBuilder.cs +++ b/src/GitVersion.App.Tests/Helpers/ArgumentBuilder.cs @@ -1,4 +1,5 @@ using System.Text; +using GitVersion.Extensions; namespace GitVersion.App.Tests { @@ -36,27 +37,27 @@ public override string ToString() arguments.AppendFormat(" /targetpath \"{0}\"", workingDirectory); - if (!string.IsNullOrWhiteSpace(exec)) + if (!StringExtensions.IsNullOrWhiteSpace(exec)) { arguments.AppendFormat(" /exec \"{0}\"", exec); } - if (!string.IsNullOrWhiteSpace(execArgs)) + if (!StringExtensions.IsNullOrWhiteSpace(execArgs)) { arguments.AppendFormat(" /execArgs \"{0}\"", execArgs); } - if (!string.IsNullOrWhiteSpace(projectFile)) + if (!StringExtensions.IsNullOrWhiteSpace(projectFile)) { arguments.AppendFormat(" /proj \"{0}\"", projectFile); } - if (!string.IsNullOrWhiteSpace(projectArgs)) + if (!StringExtensions.IsNullOrWhiteSpace(projectArgs)) { arguments.AppendFormat(" /projargs \"{0}\"", projectArgs); } - if (!string.IsNullOrWhiteSpace(logFile)) + if (!StringExtensions.IsNullOrWhiteSpace(logFile)) { arguments.AppendFormat(" /l \"{0}\"", logFile); } diff --git a/src/GitVersion.App.Tests/Helpers/GitVersionHelper.cs b/src/GitVersion.App.Tests/Helpers/GitVersionHelper.cs index fae31184b6..34fc061ae0 100644 --- a/src/GitVersion.App.Tests/Helpers/GitVersionHelper.cs +++ b/src/GitVersion.App.Tests/Helpers/GitVersionHelper.cs @@ -6,6 +6,7 @@ using GitVersion.BuildAgents; using GitVersion.Helpers; using GitVersion.Core.Tests.Helpers; +using GitVersion.Extensions; namespace GitVersion.App.Tests { @@ -100,7 +101,7 @@ params KeyValuePair[] environments Console.WriteLine(); Console.WriteLine("-------------------------------------------------------"); - if (string.IsNullOrWhiteSpace(arguments.LogFile) || !File.Exists(arguments.LogFile)) + if (StringExtensions.IsNullOrWhiteSpace(arguments.LogFile) || !File.Exists(arguments.LogFile)) { return new ExecutionResults(exitCode, output.ToString(), null); } diff --git a/src/GitVersion.App.Tests/Helpers/ProgramFixture.cs b/src/GitVersion.App.Tests/Helpers/ProgramFixture.cs index 56f46beccc..5b721a2c84 100644 --- a/src/GitVersion.App.Tests/Helpers/ProgramFixture.cs +++ b/src/GitVersion.App.Tests/Helpers/ProgramFixture.cs @@ -7,6 +7,7 @@ using GitVersion.OutputVariables; using GitVersion.Core.Tests.Helpers; using Microsoft.Extensions.DependencyInjection; +using GitVersion.Extensions; namespace GitVersion.App.Tests { @@ -61,7 +62,7 @@ public async Task Run(params string[] args) // Create the application and override registrations. var program = new Program(builder => Overrides.ForEach(action => action(builder))); - if (!string.IsNullOrWhiteSpace(workingDirectory)) + if (!StringExtensions.IsNullOrWhiteSpace(workingDirectory)) { args = new[] { "-targetpath", workingDirectory }.Concat(args).ToArray(); } @@ -86,7 +87,7 @@ public VersionVariables OutputVariables { get { - if (string.IsNullOrWhiteSpace(Output)) return null; + if (StringExtensions.IsNullOrWhiteSpace(Output)) return null; var jsonStartIndex = Output.IndexOf("{", StringComparison.Ordinal); var jsonEndIndex = Output.IndexOf("}", StringComparison.Ordinal); diff --git a/src/GitVersion.App/ArgumentParser.cs b/src/GitVersion.App/ArgumentParser.cs index 3b373ca225..684e5ff800 100644 --- a/src/GitVersion.App/ArgumentParser.cs +++ b/src/GitVersion.App/ArgumentParser.cs @@ -128,13 +128,13 @@ private void ParseSwitchArguments(Arguments arguments, NameValueCollection switc private void AddAuthentication(Arguments arguments) { var username = environment.GetEnvironmentVariable("GITVERSION_REMOTE_USERNAME"); - if (!string.IsNullOrWhiteSpace(username)) + if (!StringExtensions.IsNullOrWhiteSpace(username)) { arguments.Authentication.Username = username; } var password = environment.GetEnvironmentVariable("GITVERSION_REMOTE_PASSWORD"); - if (!string.IsNullOrWhiteSpace(password)) + if (!StringExtensions.IsNullOrWhiteSpace(password)) { arguments.Authentication.Password = password; } @@ -362,7 +362,7 @@ private static void ParseShowVariable(Arguments arguments, string value, string { string versionVariable = null; - if (!string.IsNullOrWhiteSpace(value)) + if (!StringExtensions.IsNullOrWhiteSpace(value)) { versionVariable = VersionVariables.AvailableVariables.SingleOrDefault(av => av.Equals(value.Replace("'", ""), StringComparison.CurrentCultureIgnoreCase)); } @@ -563,7 +563,7 @@ private static NameValueCollection CollectSwitchesAndValuesFromArguments(IList !string.IsNullOrEmpty(argument)).ToArray(); + return splitted.Where(argument => !StringExtensions.IsNullOrEmpty(argument)).ToArray(); } ///

diff --git a/src/GitVersion.Core.Tests/Configuration/DefaultConfigFileLocatorTests.cs b/src/GitVersion.Core.Tests/Configuration/DefaultConfigFileLocatorTests.cs index 863e0b15bb..4a8985d67b 100644 --- a/src/GitVersion.Core.Tests/Configuration/DefaultConfigFileLocatorTests.cs +++ b/src/GitVersion.Core.Tests/Configuration/DefaultConfigFileLocatorTests.cs @@ -2,6 +2,7 @@ using System.IO; using GitVersion.Configuration; using GitVersion.Core.Tests.Helpers; +using GitVersion.Extensions; using GitVersion.Logging; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; @@ -219,9 +220,9 @@ public void ThrowsExceptionOnCustomYmlFileDoesNotExist() private string SetupConfigFileContent(string text, string fileName = null, string path = null) { - if (string.IsNullOrEmpty(fileName)) fileName = configFileLocator.FilePath; + if (StringExtensions.IsNullOrEmpty(fileName)) fileName = configFileLocator.FilePath; var filePath = fileName; - if (!string.IsNullOrEmpty(path)) + if (!StringExtensions.IsNullOrEmpty(path)) filePath = Path.Combine(path, filePath); fileSystem.WriteAllText(filePath, text); return filePath; diff --git a/src/GitVersion.Core/BuildAgents/Abstractions/IBuildAgent.cs b/src/GitVersion.Core/BuildAgents/Abstractions/IBuildAgent.cs index ee126bf262..e187972c3e 100644 --- a/src/GitVersion.Core/BuildAgents/Abstractions/IBuildAgent.cs +++ b/src/GitVersion.Core/BuildAgents/Abstractions/IBuildAgent.cs @@ -6,8 +6,8 @@ namespace GitVersion.BuildAgents public interface IBuildAgent { bool CanApplyToCurrentContext(); - void WriteIntegration(Action writer, VersionVariables variables, bool updateBuildNumber = true); - string GetCurrentBranch(bool usingDynamicRepos); + void WriteIntegration(Action writer, VersionVariables variables, bool updateBuildNumber = true); + string? GetCurrentBranch(bool usingDynamicRepos); bool PreventFetch(); bool ShouldCleanUpRemotes(); } diff --git a/src/GitVersion.Core/BuildAgents/Abstractions/IBuildAgentResolver.cs b/src/GitVersion.Core/BuildAgents/Abstractions/IBuildAgentResolver.cs index 3970aed872..3235f9dbba 100644 --- a/src/GitVersion.Core/BuildAgents/Abstractions/IBuildAgentResolver.cs +++ b/src/GitVersion.Core/BuildAgents/Abstractions/IBuildAgentResolver.cs @@ -2,6 +2,6 @@ namespace GitVersion.BuildAgents { public interface IBuildAgentResolver { - ICurrentBuildAgent Resolve(); + ICurrentBuildAgent? Resolve(); } } diff --git a/src/GitVersion.Core/BuildAgents/AppVeyor.cs b/src/GitVersion.Core/BuildAgents/AppVeyor.cs index 340a2e4a4d..0ef56d9c60 100644 --- a/src/GitVersion.Core/BuildAgents/AppVeyor.cs +++ b/src/GitVersion.Core/BuildAgents/AppVeyor.cs @@ -4,6 +4,7 @@ using GitVersion.Logging; using GitVersion.OutputVariables; using System.Text.Json; +using GitVersion.Extensions; namespace GitVersion.BuildAgents { @@ -69,7 +70,7 @@ private HttpClient GetHttpClient() public override string GetCurrentBranch(bool usingDynamicRepos) { var pullRequestBranchName = Environment.GetEnvironmentVariable("APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH"); - if (!string.IsNullOrWhiteSpace(pullRequestBranchName)) + if (!StringExtensions.IsNullOrWhiteSpace(pullRequestBranchName)) { return pullRequestBranchName; } diff --git a/src/GitVersion.Core/BuildAgents/AzurePipelines.cs b/src/GitVersion.Core/BuildAgents/AzurePipelines.cs index bffb7d9957..93939226de 100644 --- a/src/GitVersion.Core/BuildAgents/AzurePipelines.cs +++ b/src/GitVersion.Core/BuildAgents/AzurePipelines.cs @@ -38,7 +38,7 @@ public override string GenerateSetVersionMessage(VersionVariables variables) // For AzurePipelines, we'll get the Build Number and insert GitVersion variables where // specified var buildNumberEnv = Environment.GetEnvironmentVariable("BUILD_BUILDNUMBER"); - if (string.IsNullOrWhiteSpace(buildNumberEnv)) + if (StringExtensions.IsNullOrWhiteSpace(buildNumberEnv)) return variables.FullSemVer; var newBuildNumber = variables.Aggregate(buildNumberEnv, ReplaceVariables); diff --git a/src/GitVersion.Core/BuildAgents/BuildAgentBase.cs b/src/GitVersion.Core/BuildAgents/BuildAgentBase.cs index e54089e080..68dfe61db4 100644 --- a/src/GitVersion.Core/BuildAgents/BuildAgentBase.cs +++ b/src/GitVersion.Core/BuildAgents/BuildAgentBase.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.OutputVariables; @@ -18,17 +19,17 @@ protected BuildAgentBase(IEnvironment environment, ILog log) protected abstract string EnvironmentVariable { get; } - public abstract string GenerateSetVersionMessage(VersionVariables variables); + public abstract string? GenerateSetVersionMessage(VersionVariables variables); public abstract string[] GenerateSetParameterMessage(string name, string value); - public virtual bool CanApplyToCurrentContext() => !string.IsNullOrEmpty(Environment.GetEnvironmentVariable(EnvironmentVariable)); + public virtual bool CanApplyToCurrentContext() => !StringExtensions.IsNullOrEmpty(Environment.GetEnvironmentVariable(EnvironmentVariable)); - public virtual string GetCurrentBranch(bool usingDynamicRepos) => null; + public virtual string? GetCurrentBranch(bool usingDynamicRepos) => null; public virtual bool PreventFetch() => true; public virtual bool ShouldCleanUpRemotes() => false; - public virtual void WriteIntegration(Action writer, VersionVariables variables, bool updateBuildNumber = true) + public virtual void WriteIntegration(Action writer, VersionVariables variables, bool updateBuildNumber = true) { if (writer == null) { diff --git a/src/GitVersion.Core/BuildAgents/BuildAgentResolver.cs b/src/GitVersion.Core/BuildAgents/BuildAgentResolver.cs index ee03abf575..d3480a0062 100644 --- a/src/GitVersion.Core/BuildAgents/BuildAgentResolver.cs +++ b/src/GitVersion.Core/BuildAgents/BuildAgentResolver.cs @@ -14,9 +14,9 @@ public BuildAgentResolver(IEnumerable buildAgents, ILog log) this.buildAgents = buildAgents ?? Array.Empty(); } - public ICurrentBuildAgent Resolve() + public ICurrentBuildAgent? Resolve() { - ICurrentBuildAgent instance = null; + ICurrentBuildAgent? instance = null; foreach (var buildAgent in buildAgents) { var agentName = buildAgent.GetType().Name; diff --git a/src/GitVersion.Core/BuildAgents/BuildServerModule.cs b/src/GitVersion.Core/BuildAgents/BuildServerModule.cs index 3733145321..e5756df823 100644 --- a/src/GitVersion.Core/BuildAgents/BuildServerModule.cs +++ b/src/GitVersion.Core/BuildAgents/BuildServerModule.cs @@ -15,7 +15,9 @@ public override void RegisterTypes(IServiceCollection services) } services.AddSingleton(); +#pragma warning disable CS8634 // The type cannot be used as type parameter in the generic type or method. Nullability of type argument doesn't match 'class' constraint. services.AddSingleton(sp => sp.GetService()?.Resolve()); +#pragma warning restore CS8634 // The type cannot be used as type parameter in the generic type or method. Nullability of type argument doesn't match 'class' constraint. } } } diff --git a/src/GitVersion.Core/BuildAgents/CodeBuild.cs b/src/GitVersion.Core/BuildAgents/CodeBuild.cs index a4ed331a7b..23a2c7d999 100644 --- a/src/GitVersion.Core/BuildAgents/CodeBuild.cs +++ b/src/GitVersion.Core/BuildAgents/CodeBuild.cs @@ -1,5 +1,6 @@ using System; using System.IO; +using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.OutputVariables; @@ -7,7 +8,7 @@ namespace GitVersion.BuildAgents { public sealed class CodeBuild : BuildAgentBase { - private string file; + private string? file; public const string WebHookEnvironmentVariableName = "CODEBUILD_WEBHOOK_HEAD_REF"; public const string SourceVersionEnvironmentVariableName = "CODEBUILD_SOURCE_VERSION"; @@ -41,7 +42,7 @@ public override string GetCurrentBranch(bool usingDynamicRepos) var currentBranch = Environment.GetEnvironmentVariable(WebHookEnvironmentVariableName); - if (string.IsNullOrEmpty(currentBranch)) + if (StringExtensions.IsNullOrEmpty(currentBranch)) { return Environment.GetEnvironmentVariable(SourceVersionEnvironmentVariableName); } @@ -49,7 +50,7 @@ public override string GetCurrentBranch(bool usingDynamicRepos) return currentBranch; } - public override void WriteIntegration(Action writer, VersionVariables variables, bool updateBuildNumber = true) + public override void WriteIntegration(Action writer, VersionVariables variables, bool updateBuildNumber = true) { base.WriteIntegration(writer, variables); writer($"Outputting variables to '{file}' ... "); @@ -59,6 +60,6 @@ public override void WriteIntegration(Action writer, VersionVariables va public override bool PreventFetch() => true; public override bool CanApplyToCurrentContext() - => !string.IsNullOrEmpty(Environment.GetEnvironmentVariable(WebHookEnvironmentVariableName)) || !string.IsNullOrEmpty(Environment.GetEnvironmentVariable(SourceVersionEnvironmentVariableName)); + => !StringExtensions.IsNullOrEmpty(Environment.GetEnvironmentVariable(WebHookEnvironmentVariableName)) || !StringExtensions.IsNullOrEmpty(Environment.GetEnvironmentVariable(SourceVersionEnvironmentVariableName)); } } diff --git a/src/GitVersion.Core/BuildAgents/Drone.cs b/src/GitVersion.Core/BuildAgents/Drone.cs index 9e1129ef09..7ddaffc87b 100644 --- a/src/GitVersion.Core/BuildAgents/Drone.cs +++ b/src/GitVersion.Core/BuildAgents/Drone.cs @@ -1,4 +1,5 @@ using System; +using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.OutputVariables; @@ -36,18 +37,18 @@ public override string GetCurrentBranch(bool usingDynamicRepos) // https://discourse.drone.io/t/getting-the-branch-a-pull-request-is-created-from/670 // Unfortunately, DRONE_REFSPEC isn't populated, however CI_COMMIT_REFSPEC can be used instead of. var pullRequestNumber = Environment.GetEnvironmentVariable("DRONE_PULL_REQUEST"); - if (!string.IsNullOrWhiteSpace(pullRequestNumber)) + if (!StringExtensions.IsNullOrWhiteSpace(pullRequestNumber)) { // DRONE_SOURCE_BRANCH is available in Drone 1.x.x version var sourceBranch = Environment.GetEnvironmentVariable("DRONE_SOURCE_BRANCH"); - if (!string.IsNullOrWhiteSpace(sourceBranch)) + if (!StringExtensions.IsNullOrWhiteSpace(sourceBranch)) return sourceBranch; // In drone lower than 1.x.x source branch can be parsed from CI_COMMIT_REFSPEC // CI_COMMIT_REFSPEC - {sourceBranch}:{destinationBranch} // https://github.com/drone/drone/issues/2222 var ciCommitRefSpec = Environment.GetEnvironmentVariable("CI_COMMIT_REFSPEC"); - if (!string.IsNullOrWhiteSpace(ciCommitRefSpec)) + if (!StringExtensions.IsNullOrWhiteSpace(ciCommitRefSpec)) { var colonIndex = ciCommitRefSpec.IndexOf(':'); if (colonIndex > 0) diff --git a/src/GitVersion.Core/BuildAgents/EnvRun.cs b/src/GitVersion.Core/BuildAgents/EnvRun.cs index d7fcc69a12..f3caf490f1 100644 --- a/src/GitVersion.Core/BuildAgents/EnvRun.cs +++ b/src/GitVersion.Core/BuildAgents/EnvRun.cs @@ -1,4 +1,5 @@ using System.IO; +using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.OutputVariables; @@ -15,7 +16,7 @@ public EnvRun(IEnvironment environment, ILog log) : base(environment, log) public override bool CanApplyToCurrentContext() { var envRunDatabasePath = Environment.GetEnvironmentVariable(EnvironmentVariableName); - if (!string.IsNullOrEmpty(envRunDatabasePath)) + if (!StringExtensions.IsNullOrEmpty(envRunDatabasePath)) { if (!File.Exists(envRunDatabasePath)) { diff --git a/src/GitVersion.Core/BuildAgents/GitHubActions.cs b/src/GitVersion.Core/BuildAgents/GitHubActions.cs index f929776a75..12357c7ca2 100644 --- a/src/GitVersion.Core/BuildAgents/GitHubActions.cs +++ b/src/GitVersion.Core/BuildAgents/GitHubActions.cs @@ -1,3 +1,4 @@ +using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.OutputVariables; using System.IO; @@ -31,7 +32,7 @@ public override string[] GenerateSetParameterMessage(string name, string value) return new string[0]; } - public override void WriteIntegration(System.Action writer, VersionVariables variables, bool updateBuildNumber = true) + public override void WriteIntegration(System.Action writer, VersionVariables variables, bool updateBuildNumber = true) { base.WriteIntegration(writer, variables, updateBuildNumber); @@ -52,7 +53,7 @@ public override void WriteIntegration(System.Action writer, VersionVaria using var streamWriter = File.AppendText(gitHubSetEnvFilePath); foreach (var variable in variables) { - if (!string.IsNullOrEmpty(variable.Value)) + if (!StringExtensions.IsNullOrEmpty(variable.Value)) { streamWriter.WriteLine($"GitVersion_{variable.Key}={variable.Value}"); } diff --git a/src/GitVersion.Core/BuildAgents/GitLabCi.cs b/src/GitVersion.Core/BuildAgents/GitLabCi.cs index e33ed5deb0..b8163dec7b 100644 --- a/src/GitVersion.Core/BuildAgents/GitLabCi.cs +++ b/src/GitVersion.Core/BuildAgents/GitLabCi.cs @@ -8,7 +8,7 @@ namespace GitVersion.BuildAgents public class GitLabCi : BuildAgentBase { public const string EnvironmentVariableName = "GITLAB_CI"; - private string file; + private string? file; public GitLabCi(IEnvironment environment, ILog log) : base(environment, log) { @@ -43,7 +43,7 @@ public override string GetCurrentBranch(bool usingDynamicRepos) public override bool PreventFetch() => true; - public override void WriteIntegration(Action writer, VersionVariables variables, bool updateBuildNumber = true) + public override void WriteIntegration(Action writer, VersionVariables variables, bool updateBuildNumber = true) { base.WriteIntegration(writer, variables); writer($"Outputting variables to '{file}' ... "); diff --git a/src/GitVersion.Core/BuildAgents/Jenkins.cs b/src/GitVersion.Core/BuildAgents/Jenkins.cs index 76fcd8c9ed..5dbd1e2d44 100644 --- a/src/GitVersion.Core/BuildAgents/Jenkins.cs +++ b/src/GitVersion.Core/BuildAgents/Jenkins.cs @@ -1,5 +1,6 @@ using System; using System.IO; +using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.OutputVariables; @@ -8,7 +9,7 @@ namespace GitVersion.BuildAgents public class Jenkins : BuildAgentBase { public const string EnvironmentVariableName = "JENKINS_URL"; - private string file; + private string? file; protected override string EnvironmentVariable { get; } = EnvironmentVariableName; public Jenkins(IEnvironment environment, ILog log) : base(environment, log) @@ -43,7 +44,7 @@ public override string GetCurrentBranch(bool usingDynamicRepos) private bool IsPipelineAsCode() { - return !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("BRANCH_NAME")); + return !StringExtensions.IsNullOrEmpty(Environment.GetEnvironmentVariable("BRANCH_NAME")); } public override bool PreventFetch() => true; @@ -58,7 +59,7 @@ public override bool ShouldCleanUpRemotes() return IsPipelineAsCode(); } - public override void WriteIntegration(Action writer, VersionVariables variables, bool updateBuildNumber = true) + public override void WriteIntegration(Action writer, VersionVariables variables, bool updateBuildNumber = true) { base.WriteIntegration(writer, variables); writer($"Outputting variables to '{file}' ... "); diff --git a/src/GitVersion.Core/BuildAgents/MyGet.cs b/src/GitVersion.Core/BuildAgents/MyGet.cs index a80f4c9d54..1ef9653f21 100644 --- a/src/GitVersion.Core/BuildAgents/MyGet.cs +++ b/src/GitVersion.Core/BuildAgents/MyGet.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using GitVersion.Extensions; using GitVersion.Helpers; using GitVersion.Logging; using GitVersion.OutputVariables; @@ -18,7 +19,7 @@ public override bool CanApplyToCurrentContext() { var buildRunner = Environment.GetEnvironmentVariable(EnvironmentVariable); - return !string.IsNullOrEmpty(buildRunner) + return !StringExtensions.IsNullOrEmpty(buildRunner) && buildRunner.Equals("MyGet", StringComparison.InvariantCultureIgnoreCase); } @@ -37,7 +38,7 @@ public override string[] GenerateSetParameterMessage(string name, string value) return messages.ToArray(); } - public override string GenerateSetVersionMessage(VersionVariables variables) + public override string? GenerateSetVersionMessage(VersionVariables variables) { return null; } diff --git a/src/GitVersion.Core/BuildAgents/TeamCity.cs b/src/GitVersion.Core/BuildAgents/TeamCity.cs index 82f3795f5e..b163f337fb 100644 --- a/src/GitVersion.Core/BuildAgents/TeamCity.cs +++ b/src/GitVersion.Core/BuildAgents/TeamCity.cs @@ -1,3 +1,4 @@ +using GitVersion.Extensions; using GitVersion.Helpers; using GitVersion.Logging; using GitVersion.OutputVariables; @@ -14,11 +15,11 @@ public TeamCity(IEnvironment environment, ILog log) : base(environment, log) protected override string EnvironmentVariable { get; } = EnvironmentVariableName; - public override string GetCurrentBranch(bool usingDynamicRepos) + public override string? GetCurrentBranch(bool usingDynamicRepos) { var branchName = Environment.GetEnvironmentVariable("Git_Branch"); - if (string.IsNullOrEmpty(branchName)) + if (StringExtensions.IsNullOrEmpty(branchName)) { if (!usingDynamicRepos) { @@ -41,7 +42,7 @@ private void WriteBranchEnvVariableWarning() public override bool PreventFetch() { - return !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("Git_Branch")); + return !StringExtensions.IsNullOrEmpty(Environment.GetEnvironmentVariable("Git_Branch")); } public override string[] GenerateSetParameterMessage(string name, string value) diff --git a/src/GitVersion.Core/Configuration/Abstractions/IBranchConfigurationCalculator.cs b/src/GitVersion.Core/Configuration/Abstractions/IBranchConfigurationCalculator.cs index 6215a64ad9..96c17b3489 100644 --- a/src/GitVersion.Core/Configuration/Abstractions/IBranchConfigurationCalculator.cs +++ b/src/GitVersion.Core/Configuration/Abstractions/IBranchConfigurationCalculator.cs @@ -8,6 +8,6 @@ public interface IBranchConfigurationCalculator /// /// Gets the for the current commit. /// - BranchConfig GetBranchConfiguration(IBranch targetBranch, ICommit currentCommit, Config configuration, IList excludedInheritBranches = null); + BranchConfig GetBranchConfiguration(IBranch targetBranch, ICommit? currentCommit, Config configuration, IList? excludedInheritBranches = null); } } diff --git a/src/GitVersion.Core/Configuration/Abstractions/IConfigFileLocator.cs b/src/GitVersion.Core/Configuration/Abstractions/IConfigFileLocator.cs index 21b5ac1cbf..d245fe2853 100644 --- a/src/GitVersion.Core/Configuration/Abstractions/IConfigFileLocator.cs +++ b/src/GitVersion.Core/Configuration/Abstractions/IConfigFileLocator.cs @@ -5,11 +5,11 @@ namespace GitVersion.Configuration public interface IConfigFileLocator { string FilePath { get; } - bool HasConfigFileAt(string workingDirectory); + bool HasConfigFileAt(string? workingDirectory); string GetConfigFilePath(string workingDirectory); void Verify(GitVersionOptions gitVersionOptions, IGitRepositoryInfo repositoryInfo); void Verify(string workingDirectory, string projectRootDirectory); string SelectConfigFilePath(GitVersionOptions gitVersionOptions, IGitRepositoryInfo repositoryInfo); - Config ReadConfig(string workingDirectory); + Config ReadConfig(string? workingDirectory); } } diff --git a/src/GitVersion.Core/Configuration/Abstractions/IConfigProvider.cs b/src/GitVersion.Core/Configuration/Abstractions/IConfigProvider.cs index 406eb043db..a11743f814 100644 --- a/src/GitVersion.Core/Configuration/Abstractions/IConfigProvider.cs +++ b/src/GitVersion.Core/Configuration/Abstractions/IConfigProvider.cs @@ -4,8 +4,8 @@ namespace GitVersion.Configuration { public interface IConfigProvider { - Config Provide(Config overrideConfig = null); - Config Provide(string workingDirectory, Config overrideConfig = null); + Config Provide(Config? overrideConfig = null); + Config Provide(string workingDirectory, Config? overrideConfig = null); void Init(string workingDirectory); } } diff --git a/src/GitVersion.Core/Configuration/BranchConfigurationCalculator.cs b/src/GitVersion.Core/Configuration/BranchConfigurationCalculator.cs index dcc8e077a1..81ddd0aa04 100644 --- a/src/GitVersion.Core/Configuration/BranchConfigurationCalculator.cs +++ b/src/GitVersion.Core/Configuration/BranchConfigurationCalculator.cs @@ -25,7 +25,7 @@ public BranchConfigurationCalculator(ILog log, IRepositoryStore repositoryStore) /// /// Gets the for the current commit. /// - public BranchConfig GetBranchConfiguration(IBranch targetBranch, ICommit currentCommit, Config configuration, IList excludedInheritBranches = null) + public BranchConfig GetBranchConfiguration(IBranch targetBranch, ICommit? currentCommit, Config configuration, IList? excludedInheritBranches = null) { var matchingBranches = configuration.GetConfigForBranch(targetBranch.Name.WithoutRemote); @@ -45,7 +45,7 @@ public BranchConfig GetBranchConfiguration(IBranch targetBranch, ICommit current if (matchingBranches.Increment == IncrementStrategy.Inherit) { matchingBranches = InheritBranchConfiguration(targetBranch, matchingBranches, currentCommit, configuration, excludedInheritBranches); - if (matchingBranches.Name.IsEquivalentTo(FallbackConfigName) && matchingBranches.Increment == IncrementStrategy.Inherit) + if (matchingBranches.Name!.IsEquivalentTo(FallbackConfigName) && matchingBranches.Increment == IncrementStrategy.Inherit) { // We tried, and failed to inherit, just fall back to patch matchingBranches.Increment = IncrementStrategy.Patch; @@ -56,16 +56,16 @@ public BranchConfig GetBranchConfiguration(IBranch targetBranch, ICommit current } // TODO I think we need to take a fresh approach to this.. it's getting really complex with heaps of edge cases - private BranchConfig InheritBranchConfiguration(IBranch targetBranch, BranchConfig branchConfiguration, ICommit currentCommit, Config configuration, IList excludedInheritBranches) + private BranchConfig InheritBranchConfiguration(IBranch targetBranch, BranchConfig branchConfiguration, ICommit? currentCommit, Config configuration, IList? excludedInheritBranches) { using (log.IndentLog("Attempting to inherit branch configuration from parent branch")) { var excludedBranches = new[] { targetBranch }; // Check if we are a merge commit. If so likely we are a pull request - var parentCount = currentCommit.Parents.Count(); + var parentCount = currentCommit?.Parents.Count(); if (parentCount == 2) { - excludedBranches = CalculateWhenMultipleParents(currentCommit, ref targetBranch, excludedBranches); + excludedBranches = CalculateWhenMultipleParents(currentCommit!, ref targetBranch, excludedBranches); } excludedInheritBranches ??= repositoryStore.GetExcludedInheritBranches(configuration).ToList(); @@ -155,9 +155,9 @@ private BranchConfig InheritBranchConfiguration(IBranch targetBranch, BranchConf }; } - var inheritingBranchConfig = GetBranchConfiguration(chosenBranch, currentCommit, configuration, excludedInheritBranches); + var inheritingBranchConfig = GetBranchConfiguration(chosenBranch, currentCommit, configuration, excludedInheritBranches)!; var configIncrement = inheritingBranchConfig.Increment; - if (inheritingBranchConfig.Name.IsEquivalentTo(FallbackConfigName) && configIncrement == IncrementStrategy.Inherit) + if (inheritingBranchConfig.Name!.IsEquivalentTo(FallbackConfigName) && configIncrement == IncrementStrategy.Inherit) { log.Warning("Fallback config inherits by default, dropping to patch increment"); configIncrement = IncrementStrategy.Patch; @@ -210,32 +210,32 @@ private IBranch[] CalculateWhenMultipleParents(ICommit currentCommit, ref IBranc - private static BranchConfig ChooseMainOrDevelopIncrementStrategyIfTheChosenBranchIsOneOfThem(IBranch chosenBranch, BranchConfig branchConfiguration, Config config) + private static BranchConfig? ChooseMainOrDevelopIncrementStrategyIfTheChosenBranchIsOneOfThem(IBranch chosenBranch, BranchConfig branchConfiguration, Config config) { - BranchConfig mainOrDevelopConfig = null; - var developBranchRegex = config.Branches[Config.DevelopBranchKey].Regex; - var mainBranchRegex = config.Branches[Config.MainBranchKey].Regex; + BranchConfig? mainOrDevelopConfig = null; + var developBranchRegex = config.Branches[Config.DevelopBranchKey]?.Regex; + var mainBranchRegex = config.Branches[Config.MainBranchKey]?.Regex; if (Regex.IsMatch(chosenBranch.Name.Friendly, developBranchRegex, RegexOptions.IgnoreCase)) { // Normally we would not expect this to happen but for safety we add a check - if (config.Branches[Config.DevelopBranchKey].Increment != + if (config.Branches[Config.DevelopBranchKey]?.Increment != IncrementStrategy.Inherit) { mainOrDevelopConfig = new BranchConfig(branchConfiguration) { - Increment = config.Branches[Config.DevelopBranchKey].Increment + Increment = config.Branches[Config.DevelopBranchKey]?.Increment }; } } else if (Regex.IsMatch(chosenBranch.Name.Friendly, mainBranchRegex, RegexOptions.IgnoreCase)) { // Normally we would not expect this to happen but for safety we add a check - if (config.Branches[Config.MainBranchKey].Increment != + if (config.Branches[Config.MainBranchKey]?.Increment != IncrementStrategy.Inherit) { mainOrDevelopConfig = new BranchConfig(branchConfiguration) { - Increment = config.Branches[Config.DevelopBranchKey].Increment + Increment = config.Branches[Config.DevelopBranchKey]?.Increment }; } } diff --git a/src/GitVersion.Core/Configuration/ConfigExtensions.cs b/src/GitVersion.Core/Configuration/ConfigExtensions.cs index 828ef97237..aeec67bba5 100644 --- a/src/GitVersion.Core/Configuration/ConfigExtensions.cs +++ b/src/GitVersion.Core/Configuration/ConfigExtensions.cs @@ -10,11 +10,11 @@ namespace GitVersion.Configuration { public static class ConfigExtensions { - public static BranchConfig GetConfigForBranch(this Config config, string branchName) + public static BranchConfig? GetConfigForBranch(this Config config, string? branchName) { if (branchName == null) throw new ArgumentNullException(nameof(branchName)); var matches = config.Branches - .Where(b => Regex.IsMatch(branchName, b.Value.Regex, RegexOptions.IgnoreCase)) + .Where(b => Regex.IsMatch(branchName, b.Value?.Regex, RegexOptions.IgnoreCase)) .ToArray(); try @@ -33,7 +33,7 @@ public static BranchConfig GetConfigForBranch(this Config config, string branchN // TODO check how to log this Console.WriteLine( $"Multiple branch configurations match the current branch branchName of '{branchName}'. " + - $"Using the first matching configuration, '{picked.Name}'. Matching configurations include:'{matchingConfigs}'"); + $"Using the first matching configuration, '{picked?.Name}'. Matching configurations include:'{matchingConfigs}'"); return picked; } @@ -117,9 +117,9 @@ public static EffectiveConfiguration CalculateEffectiveConfiguration(this Config tagPreReleaseWeight); } - public static string GetBranchSpecificTag(this EffectiveConfiguration configuration, ILog log, string branchFriendlyName, string branchNameOverride) + public static string GetBranchSpecificTag(this EffectiveConfiguration configuration, ILog log, string? branchFriendlyName, string? branchNameOverride) { - var tagToUse = configuration.Tag; + var tagToUse = configuration.Tag!; if (tagToUse == "useBranchName") { tagToUse = "{BranchName}"; @@ -129,22 +129,22 @@ public static string GetBranchSpecificTag(this EffectiveConfiguration configurat log.Info("Using branch name to calculate version tag"); var branchName = branchNameOverride ?? branchFriendlyName; - if (!string.IsNullOrWhiteSpace(configuration.BranchPrefixToTrim)) + if (!StringExtensions.IsNullOrWhiteSpace(configuration.BranchPrefixToTrim)) { - var branchNameTrimmed = branchName.RegexReplace(configuration.BranchPrefixToTrim, string.Empty, RegexOptions.IgnoreCase); - branchName = string.IsNullOrEmpty(branchNameTrimmed) ? branchName : branchNameTrimmed; + var branchNameTrimmed = branchName?.RegexReplace(configuration.BranchPrefixToTrim, string.Empty, RegexOptions.IgnoreCase); + branchName = StringExtensions.IsNullOrEmpty(branchNameTrimmed) ? branchName : branchNameTrimmed; } - branchName = branchName.RegexReplace("[^a-zA-Z0-9-]", "-"); + branchName = branchName?.RegexReplace("[^a-zA-Z0-9-]", "-"); tagToUse = tagToUse.Replace("{BranchName}", branchName); } return tagToUse; } - public static List> GetReleaseBranchConfig(this Config configuration) + public static List> GetReleaseBranchConfig(this Config configuration) { return configuration.Branches - .Where(b => b.Value.IsReleaseBranch == true) + .Where(b => b.Value?.IsReleaseBranch == true) .ToList(); } } diff --git a/src/GitVersion.Core/Configuration/ConfigFileLocator.cs b/src/GitVersion.Core/Configuration/ConfigFileLocator.cs index 980a8ce1c0..899cd88f57 100644 --- a/src/GitVersion.Core/Configuration/ConfigFileLocator.cs +++ b/src/GitVersion.Core/Configuration/ConfigFileLocator.cs @@ -1,5 +1,6 @@ using System.IO; using System.Linq; +using GitVersion.Extensions; using GitVersion.Model.Configuration; using GitVersion.VersionCalculation; using Microsoft.Extensions.Options; @@ -14,16 +15,16 @@ public ConfigFileLocator(IFileSystem fileSystem, IOptions opt { this.fileSystem = fileSystem; var configFile = options?.Value.ConfigInfo.ConfigFile; - FilePath = !string.IsNullOrWhiteSpace(configFile) ? configFile : DefaultFileName; + FilePath = !StringExtensions.IsNullOrWhiteSpace(configFile) ? configFile : DefaultFileName; } public string FilePath { get; } - public bool HasConfigFileAt(string workingDirectory) => fileSystem.Exists(Path.Combine(workingDirectory, FilePath)); + public bool HasConfigFileAt(string? workingDirectory) => fileSystem.Exists(Path.Combine(workingDirectory, FilePath)); - public string GetConfigFilePath(string workingDirectory) => Path.Combine(workingDirectory, FilePath); + public string GetConfigFilePath(string? workingDirectory) => Path.Combine(workingDirectory, FilePath); - public void Verify(string workingDirectory, string projectRootDirectory) + public void Verify(string? workingDirectory, string? projectRootDirectory) { if (!Path.IsPathRooted(FilePath) && !fileSystem.PathsEqual(workingDirectory, projectRootDirectory)) { @@ -39,7 +40,7 @@ public string SelectConfigFilePath(GitVersionOptions gitVersionOptions, IGitRepo return GetConfigFilePath(HasConfigFileAt(workingDirectory) ? workingDirectory : projectRootDirectory); } - public Config ReadConfig(string workingDirectory) + public Config ReadConfig(string? workingDirectory) { var configFilePath = GetConfigFilePath(workingDirectory); @@ -58,7 +59,7 @@ public Config ReadConfig(string workingDirectory) public void Verify(GitVersionOptions gitVersionOptions, IGitRepositoryInfo repositoryInfo) { - if (!string.IsNullOrWhiteSpace(gitVersionOptions.RepositoryInfo.TargetUrl)) + if (!StringExtensions.IsNullOrWhiteSpace(gitVersionOptions.RepositoryInfo.TargetUrl)) { // Assuming this is a dynamic repository. At this stage it's unsure whether we have // any .git info so we need to skip verification @@ -74,7 +75,7 @@ public void Verify(GitVersionOptions gitVersionOptions, IGitRepositoryInfo repos private static void VerifyReadConfig(Config config) { // Verify no branches are set to mainline mode - if (config.Branches.Any(b => b.Value.VersioningMode == VersioningMode.Mainline)) + if (config.Branches.Any(b => b.Value?.VersioningMode == VersioningMode.Mainline)) { throw new ConfigurationException(@"Mainline mode only works at the repository level, a single branch cannot be put into mainline mode @@ -84,7 +85,7 @@ This is because mainline mode treats your entire git repository as an event sour } } - private void WarnAboutAmbiguousConfigFileSelection(string workingDirectory, string projectRootDirectory) + private void WarnAboutAmbiguousConfigFileSelection(string? workingDirectory, string? projectRootDirectory) { var workingConfigFile = GetConfigFilePath(workingDirectory); var projectRootConfigFile = GetConfigFilePath(projectRootDirectory); diff --git a/src/GitVersion.Core/Configuration/ConfigProvider.cs b/src/GitVersion.Core/Configuration/ConfigProvider.cs index 9d669c9370..4f5bfb57f2 100644 --- a/src/GitVersion.Core/Configuration/ConfigProvider.cs +++ b/src/GitVersion.Core/Configuration/ConfigProvider.cs @@ -27,7 +27,7 @@ public ConfigProvider(IFileSystem fileSystem, ILog log, IConfigFileLocator confi this.repositoryInfo = repositoryInfo ?? throw new ArgumentNullException(nameof(this.repositoryInfo)); } - public Config Provide(Config overrideConfig = null) + public Config Provide(Config? overrideConfig = null) { var gitVersionOptions = options.Value; var workingDirectory = gitVersionOptions.WorkingDirectory; @@ -37,7 +37,7 @@ public Config Provide(Config overrideConfig = null) return Provide(rootDirectory, overrideConfig); } - public Config Provide(string workingDirectory, Config overrideConfig = null) + public Config Provide(string? workingDirectory, Config? overrideConfig = null) { return new ConfigurationBuilder() .Add(configFileLocator.ReadConfig(workingDirectory)) diff --git a/src/GitVersion.Core/Configuration/ConfigurationBuilder.cs b/src/GitVersion.Core/Configuration/ConfigurationBuilder.cs index 959835df98..aa9e5f7289 100644 --- a/src/GitVersion.Core/Configuration/ConfigurationBuilder.cs +++ b/src/GitVersion.Core/Configuration/ConfigurationBuilder.cs @@ -83,7 +83,7 @@ private static void ApplyBranchOverrides(Config targetConfig, Config overrideCon // In case when several branch configurations match the current branch (by regex), we choose the first one. // So we have to add new branches to the beginning of a dictionary to preserve 5.3.x behavior. - var newBranches = new Dictionary(); + var newBranches = new Dictionary(); var targetConfigBranches = targetConfig.Branches; @@ -96,8 +96,8 @@ private static void ApplyBranchOverrides(Config targetConfig, Config overrideCon target = BranchConfig.CreateDefaultBranchConfig(branchName); } - branchConfig.MergeTo(target); - if (target.SourceBranches != null && target.SourceBranches.Contains(Config.MasterBranchKey)) + branchConfig!.MergeTo(target!); + if (target!.SourceBranches != null && target.SourceBranches.Contains(Config.MasterBranchKey)) { target.SourceBranches.Remove(Config.MasterBranchKey); target.SourceBranches.Add(Config.MainBranchKey); @@ -127,9 +127,9 @@ private static void FinalizeConfiguration(Config config) } } - private static void FinalizeBranchConfiguration(Config config, string name, BranchConfig branchConfig) + private static void FinalizeBranchConfiguration(Config config, string name, BranchConfig? branchConfig) { - branchConfig.Name = name; + branchConfig!.Name = name; branchConfig.Increment ??= config.Increment ?? IncrementStrategy.Inherit; if (branchConfig.VersioningMode == null) @@ -148,7 +148,7 @@ private static void FinalizeBranchConfiguration(Config config, string name, Bran { foreach (var targetBranchName in branchConfig.IsSourceBranchFor) { - var targetBranchConfig = config.Branches[targetBranchName]; + var targetBranchConfig = config.Branches[targetBranchName]!; targetBranchConfig.SourceBranches ??= new HashSet(); targetBranchConfig.SourceBranches.Add(name); } @@ -159,7 +159,7 @@ private static void ValidateConfiguration(Config config) { foreach (var (name, branchConfig) in config.Branches) { - var regex = branchConfig.Regex; + var regex = branchConfig?.Regex; var helpUrl = $"{System.Environment.NewLine}See https://gitversion.net/docs/reference/configuration for more info"; if (regex == null) @@ -167,7 +167,7 @@ private static void ValidateConfiguration(Config config) throw new ConfigurationException($"Branch configuration '{name}' is missing required configuration 'regex'{helpUrl}"); } - var sourceBranches = branchConfig.SourceBranches; + var sourceBranches = branchConfig?.SourceBranches; if (sourceBranches == null) { throw new ConfigurationException($"Branch configuration '{name}' is missing required configuration 'source-branches'{helpUrl}"); diff --git a/src/GitVersion.Core/Configuration/Init/BuildServer/AppVeyorSetup.cs b/src/GitVersion.Core/Configuration/Init/BuildServer/AppVeyorSetup.cs index 75b1b76901..d3d8b80bf2 100644 --- a/src/GitVersion.Core/Configuration/Init/BuildServer/AppVeyorSetup.cs +++ b/src/GitVersion.Core/Configuration/Init/BuildServer/AppVeyorSetup.cs @@ -28,9 +28,9 @@ public AppVeyorSetup WithData(ProjectVisibility visibility) return this; } - protected override StepResult HandleResult(string result, Queue steps, Config config, string workingDirectory) + protected override StepResult HandleResult(string? result, Queue steps, Config config, string workingDirectory) { - var editConfigStep = StepFactory.CreateStep(); + var editConfigStep = StepFactory.CreateStep()!; switch (result) { case "0": diff --git a/src/GitVersion.Core/Configuration/Init/BuildServer/AppveyorPublicPrivate.cs b/src/GitVersion.Core/Configuration/Init/BuildServer/AppveyorPublicPrivate.cs index 4a9444bdc1..2b91db921d 100644 --- a/src/GitVersion.Core/Configuration/Init/BuildServer/AppveyorPublicPrivate.cs +++ b/src/GitVersion.Core/Configuration/Init/BuildServer/AppveyorPublicPrivate.cs @@ -11,18 +11,18 @@ public AppveyorPublicPrivate(IConsole console, IFileSystem fileSystem, ILog log, { } - protected override StepResult HandleResult(string result, Queue steps, Config config, string workingDirectory) + protected override StepResult HandleResult(string? result, Queue steps, Config config, string workingDirectory) { switch (result) { case "0": - steps.Enqueue(StepFactory.CreateStep()); + steps.Enqueue(StepFactory.CreateStep()!); return StepResult.Ok(); case "1": - steps.Enqueue(StepFactory.CreateStep().WithData(ProjectVisibility.Public)); + steps.Enqueue(StepFactory.CreateStep()!.WithData(ProjectVisibility.Public)); return StepResult.Ok(); case "2": - steps.Enqueue(StepFactory.CreateStep().WithData(ProjectVisibility.Private)); + steps.Enqueue(StepFactory.CreateStep()!.WithData(ProjectVisibility.Private)); return StepResult.Ok(); } return StepResult.Ok(); diff --git a/src/GitVersion.Core/Configuration/Init/BuildServer/SetupBuildScripts.cs b/src/GitVersion.Core/Configuration/Init/BuildServer/SetupBuildScripts.cs index a2c9434de9..a75e317100 100644 --- a/src/GitVersion.Core/Configuration/Init/BuildServer/SetupBuildScripts.cs +++ b/src/GitVersion.Core/Configuration/Init/BuildServer/SetupBuildScripts.cs @@ -11,15 +11,15 @@ public SetupBuildScripts(IConsole console, IFileSystem fileSystem, ILog log, ICo { } - protected override StepResult HandleResult(string result, Queue steps, Config config, string workingDirectory) + protected override StepResult HandleResult(string? result, Queue steps, Config config, string workingDirectory) { switch (result) { case "0": - steps.Enqueue(StepFactory.CreateStep()); + steps.Enqueue(StepFactory.CreateStep()!); return StepResult.Ok(); case "1": - steps.Enqueue(StepFactory.CreateStep()); + steps.Enqueue(StepFactory.CreateStep()!); return StepResult.Ok(); } return StepResult.Ok(); diff --git a/src/GitVersion.Core/Configuration/Init/EditConfigStep.cs b/src/GitVersion.Core/Configuration/Init/EditConfigStep.cs index cfc679a81a..438c1d94f3 100644 --- a/src/GitVersion.Core/Configuration/Init/EditConfigStep.cs +++ b/src/GitVersion.Core/Configuration/Init/EditConfigStep.cs @@ -13,7 +13,7 @@ public EditConfigStep(IConsole console, IFileSystem fileSystem, ILog log, IConfi { } - protected override StepResult HandleResult(string result, Queue steps, Config config, string workingDirectory) + protected override StepResult HandleResult(string? result, Queue steps, Config config, string workingDirectory) { switch (result) { @@ -23,25 +23,25 @@ protected override StepResult HandleResult(string result, Queue()); + steps.Enqueue(StepFactory.CreateStep()!); return StepResult.Ok(); case "3": - steps.Enqueue(StepFactory.CreateStep()); + steps.Enqueue(StepFactory.CreateStep()!); return StepResult.Ok(); case "4": - steps.Enqueue(StepFactory.CreateStep()); + steps.Enqueue(StepFactory.CreateStep()!); return StepResult.Ok(); case "5": var editConfigStep = StepFactory.CreateStep(); - steps.Enqueue(StepFactory.CreateStep().WithData(editConfigStep, false)); + steps.Enqueue(StepFactory.CreateStep()!.WithData(editConfigStep!, false)); return StepResult.Ok(); case "6": - steps.Enqueue(StepFactory.CreateStep()); + steps.Enqueue(StepFactory.CreateStep()!); return StepResult.Ok(); case "7": - steps.Enqueue(StepFactory.CreateStep()); + steps.Enqueue(StepFactory.CreateStep()!); return StepResult.Ok(); } return StepResult.InvalidResponseSelected(); @@ -63,6 +63,6 @@ protected override string GetPrompt(Config config, string workingDirectory) 7) Setup build scripts"; } - protected override string DefaultResult => null; + protected override string? DefaultResult => null; } } diff --git a/src/GitVersion.Core/Configuration/Init/SetConfig/AssemblyVersioningSchemeSetting.cs b/src/GitVersion.Core/Configuration/Init/SetConfig/AssemblyVersioningSchemeSetting.cs index 4be3929d19..e313356241 100644 --- a/src/GitVersion.Core/Configuration/Init/SetConfig/AssemblyVersioningSchemeSetting.cs +++ b/src/GitVersion.Core/Configuration/Init/SetConfig/AssemblyVersioningSchemeSetting.cs @@ -12,9 +12,9 @@ public AssemblyVersioningSchemeSetting(IConsole console, IFileSystem fileSystem, { } - protected override StepResult HandleResult(string result, Queue steps, Config config, string workingDirectory) + protected override StepResult HandleResult(string? result, Queue steps, Config config, string workingDirectory) { - var editConfigStep = StepFactory.CreateStep(); + var editConfigStep = StepFactory.CreateStep()!; switch (result) { case "0": diff --git a/src/GitVersion.Core/Configuration/Init/SetConfig/ConfigureBranch.cs b/src/GitVersion.Core/Configuration/Init/SetConfig/ConfigureBranch.cs index 259767db4d..d909232458 100644 --- a/src/GitVersion.Core/Configuration/Init/SetConfig/ConfigureBranch.cs +++ b/src/GitVersion.Core/Configuration/Init/SetConfig/ConfigureBranch.cs @@ -7,32 +7,32 @@ namespace GitVersion.Configuration.Init.SetConfig { public class ConfigureBranch : ConfigInitWizardStep { - private string name; - private BranchConfig branchConfig; + private string? name; + private BranchConfig? branchConfig; public ConfigureBranch(IConsole console, IFileSystem fileSystem, ILog log, IConfigInitStepFactory stepFactory) : base(console, fileSystem, log, stepFactory) { } - public ConfigureBranch WithData(string name, BranchConfig branchConfig) + public ConfigureBranch WithData(string? name, BranchConfig? branchConfig) { this.branchConfig = branchConfig; this.name = name; return this; } - protected override StepResult HandleResult(string result, Queue steps, Config config, string workingDirectory) + protected override StepResult HandleResult(string? result, Queue steps, Config config, string workingDirectory) { switch (result) { case "0": - steps.Enqueue(StepFactory.CreateStep()); + steps.Enqueue(StepFactory.CreateStep()!); return StepResult.Ok(); case "1": - steps.Enqueue(StepFactory.CreateStep().WithData(name, branchConfig)); + steps.Enqueue(StepFactory.CreateStep()!.WithData(name, branchConfig)); return StepResult.Ok(); case "2": - steps.Enqueue(StepFactory.CreateStep().WithData(name, branchConfig)); + steps.Enqueue(StepFactory.CreateStep()!.WithData(name!, branchConfig!)); return StepResult.Ok(); } @@ -44,7 +44,7 @@ protected override string GetPrompt(Config config, string workingDirectory) return $@"What would you like to change for '{name}': 0) Go Back -1) Branch Pre-release tag (Current: {branchConfig.Tag}) +1) Branch Pre-release tag (Current: {branchConfig!.Tag}) 2) Branch Increment mode (per commit/after tag) (Current: {branchConfig.VersioningMode})"; } diff --git a/src/GitVersion.Core/Configuration/Init/SetConfig/ConfigureBranches.cs b/src/GitVersion.Core/Configuration/Init/SetConfig/ConfigureBranches.cs index e0c20bebdf..99dd6f2044 100644 --- a/src/GitVersion.Core/Configuration/Init/SetConfig/ConfigureBranches.cs +++ b/src/GitVersion.Core/Configuration/Init/SetConfig/ConfigureBranches.cs @@ -13,13 +13,13 @@ public ConfigureBranches(IConsole console, IFileSystem fileSystem, ILog log, ICo { } - protected override StepResult HandleResult(string result, Queue steps, Config config, string workingDirectory) + protected override StepResult HandleResult(string? result, Queue steps, Config config, string workingDirectory) { if (int.TryParse(result, out var parsed)) { if (parsed == 0) { - steps.Enqueue(StepFactory.CreateStep()); + steps.Enqueue(StepFactory.CreateStep()!); return StepResult.Ok(); } @@ -32,7 +32,7 @@ protected override StepResult HandleResult(string result, Queue().WithData(foundBranch.Key, branchConfig)); + steps.Enqueue(StepFactory.CreateStep()!.WithData(foundBranch.Key, branchConfig)); return StepResult.Ok(); } catch (ArgumentOutOfRangeException) @@ -50,14 +50,14 @@ protected override string GetPrompt(Config config, string workingDirectory) " + string.Join(System.Environment.NewLine, OrderedBranches(config).Select((c, i) => $"{i + 1}) {c.Key}")); } - private static IOrderedEnumerable> OrderedBranches(Config config) + private static IOrderedEnumerable> OrderedBranches(Config config) { var defaultConfig = new ConfigurationBuilder().Build(); var defaultConfigurationBranches = defaultConfig.Branches .Where(k => !config.Branches.ContainsKey(k.Key)) // Return an empty branch config - .Select(v => new KeyValuePair(v.Key, null)); + .Select(v => new KeyValuePair(v.Key, null)); return config.Branches.Union(defaultConfigurationBranches).OrderBy(b => b.Key); } diff --git a/src/GitVersion.Core/Configuration/Init/SetConfig/GlobalModeSetting.cs b/src/GitVersion.Core/Configuration/Init/SetConfig/GlobalModeSetting.cs index 451d8d8d70..31fd78dd59 100644 --- a/src/GitVersion.Core/Configuration/Init/SetConfig/GlobalModeSetting.cs +++ b/src/GitVersion.Core/Configuration/Init/SetConfig/GlobalModeSetting.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using GitVersion.Configuration.Init.Wizard; +using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.Model.Configuration; using GitVersion.VersionCalculation; @@ -8,7 +9,7 @@ namespace GitVersion.Configuration.Init.SetConfig { public class GlobalModeSetting : ConfigInitWizardStep { - private ConfigInitWizardStep returnToStep; + private ConfigInitWizardStep? returnToStep; private bool isPartOfWizard; public GlobalModeSetting(IConsole console, IFileSystem fileSystem, ILog log, IConfigInitStepFactory stepFactory) : base(console, fileSystem, log, stepFactory) @@ -22,25 +23,25 @@ public GlobalModeSetting WithData(ConfigInitWizardStep returnToStep, bool isPart return this; } - protected override StepResult HandleResult(string result, Queue steps, Config config, string workingDirectory) + protected override StepResult HandleResult(string? result, Queue steps, Config config, string workingDirectory) { switch (result) { case "1": config.VersioningMode = VersioningMode.ContinuousDelivery; - steps.Enqueue(returnToStep); + steps.Enqueue(returnToStep!); return StepResult.Ok(); case "2": config.VersioningMode = VersioningMode.ContinuousDeployment; - steps.Enqueue(returnToStep); + steps.Enqueue(returnToStep!); return StepResult.Ok(); case "3": config.VersioningMode = VersioningMode.Mainline; - steps.Enqueue(returnToStep); + steps.Enqueue(returnToStep!); return StepResult.Ok(); case "0": case "4": - steps.Enqueue(returnToStep); + steps.Enqueue(returnToStep!); return StepResult.Ok(); } diff --git a/src/GitVersion.Core/Configuration/Init/SetConfig/SetBranchIncrementMode.cs b/src/GitVersion.Core/Configuration/Init/SetConfig/SetBranchIncrementMode.cs index 6a7d69a283..2e30bef08f 100644 --- a/src/GitVersion.Core/Configuration/Init/SetConfig/SetBranchIncrementMode.cs +++ b/src/GitVersion.Core/Configuration/Init/SetConfig/SetBranchIncrementMode.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using GitVersion.Configuration.Init.Wizard; +using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.Model.Configuration; using GitVersion.VersionCalculation; @@ -8,8 +9,8 @@ namespace GitVersion.Configuration.Init.SetConfig { public class SetBranchIncrementMode : ConfigInitWizardStep { - private string name; - private BranchConfig branchConfig; + private string? name; + private BranchConfig? branchConfig; public SetBranchIncrementMode(IConsole console, IFileSystem fileSystem, ILog log, IConfigInitStepFactory stepFactory) : base(console, fileSystem, log, stepFactory) { @@ -22,20 +23,20 @@ public SetBranchIncrementMode WithData(string name, BranchConfig branchConfig) return this; } - protected override StepResult HandleResult(string result, Queue steps, Config config, string workingDirectory) + protected override StepResult HandleResult(string? result, Queue steps, Config config, string workingDirectory) { - var configureBranchStep = StepFactory.CreateStep(); + var configureBranchStep = StepFactory.CreateStep()!; switch (result) { case "0": steps.Enqueue(configureBranchStep.WithData(name, branchConfig)); return StepResult.Ok(); case "1": - branchConfig.VersioningMode = VersioningMode.ContinuousDelivery; + branchConfig!.VersioningMode = VersioningMode.ContinuousDelivery; steps.Enqueue(configureBranchStep.WithData(name, branchConfig)); return StepResult.Ok(); case "2": - branchConfig.VersioningMode = VersioningMode.ContinuousDeployment; + branchConfig!.VersioningMode = VersioningMode.ContinuousDeployment; steps.Enqueue(configureBranchStep.WithData(name, branchConfig)); return StepResult.Ok(); } diff --git a/src/GitVersion.Core/Configuration/Init/SetConfig/SetBranchTag.cs b/src/GitVersion.Core/Configuration/Init/SetConfig/SetBranchTag.cs index 9dbc4cb8a0..b7089cb8d9 100644 --- a/src/GitVersion.Core/Configuration/Init/SetConfig/SetBranchTag.cs +++ b/src/GitVersion.Core/Configuration/Init/SetConfig/SetBranchTag.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using GitVersion.Configuration.Init.Wizard; +using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.Model.Configuration; @@ -7,39 +8,39 @@ namespace GitVersion.Configuration.Init.SetConfig { public class SetBranchTag : ConfigInitWizardStep { - private string name; - private BranchConfig branchConfig; + private string? name; + private BranchConfig? branchConfig; public SetBranchTag(IConsole console, IFileSystem fileSystem, ILog log, IConfigInitStepFactory stepFactory) : base(console, fileSystem, log, stepFactory) { } - public SetBranchTag WithData(string name, BranchConfig branchConfig) + public SetBranchTag WithData(string? name, BranchConfig? branchConfig) { this.branchConfig = branchConfig; this.name = name; return this; } - protected override StepResult HandleResult(string result, Queue steps, Config config, string workingDirectory) + protected override StepResult HandleResult(string? result, Queue steps, Config config, string workingDirectory) { - if (string.IsNullOrWhiteSpace(result)) + if (StringExtensions.IsNullOrWhiteSpace(result)) { return StepResult.InvalidResponseSelected(); } - var configureBranchStep = StepFactory.CreateStep(); + var configureBranchStep = StepFactory.CreateStep()!; switch (result) { case "0": steps.Enqueue(configureBranchStep.WithData(name, branchConfig)); return StepResult.Ok(); case "1": - branchConfig.Tag = string.Empty; + branchConfig!.Tag = string.Empty; steps.Enqueue(configureBranchStep.WithData(name, branchConfig)); return StepResult.Ok(); default: - branchConfig.Tag = result; + branchConfig!.Tag = result; steps.Enqueue(configureBranchStep.WithData(name, branchConfig)); return StepResult.Ok(); } diff --git a/src/GitVersion.Core/Configuration/Init/SetNextVersion.cs b/src/GitVersion.Core/Configuration/Init/SetNextVersion.cs index 7155e3c239..1c1e10971a 100644 --- a/src/GitVersion.Core/Configuration/Init/SetNextVersion.cs +++ b/src/GitVersion.Core/Configuration/Init/SetNextVersion.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using GitVersion.Configuration.Init.Wizard; +using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.Model.Configuration; @@ -11,10 +12,10 @@ public SetNextVersion(IConsole console, IFileSystem fileSystem, ILog log, IConfi { } - protected override StepResult HandleResult(string result, Queue steps, Config config, string workingDirectory) + protected override StepResult HandleResult(string? result, Queue steps, Config config, string workingDirectory) { - var editConfigStep = StepFactory.CreateStep(); - if (string.IsNullOrEmpty(result)) + var editConfigStep = StepFactory.CreateStep()!; + if (StringExtensions.IsNullOrEmpty(result)) { steps.Enqueue(editConfigStep); return StepResult.Ok(); @@ -33,6 +34,6 @@ protected override string GetPrompt(Config config, string workingDirectory) return @"What would you like to set the next version to (enter nothing to cancel)?"; } - protected override string DefaultResult => null; + protected override string? DefaultResult => null; } } diff --git a/src/GitVersion.Core/Configuration/Init/Wizard/ConfigInitStepFactory.cs b/src/GitVersion.Core/Configuration/Init/Wizard/ConfigInitStepFactory.cs index b6c218f53a..a9142f433d 100644 --- a/src/GitVersion.Core/Configuration/Init/Wizard/ConfigInitStepFactory.cs +++ b/src/GitVersion.Core/Configuration/Init/Wizard/ConfigInitStepFactory.cs @@ -5,7 +5,7 @@ namespace GitVersion.Configuration.Init.Wizard { public class ConfigInitStepFactory : IConfigInitStepFactory { - private readonly IServiceProvider sp; + private readonly IServiceProvider? sp; public ConfigInitStepFactory() { @@ -16,6 +16,6 @@ public ConfigInitStepFactory(IServiceProvider sp) this.sp = sp ?? throw new ArgumentNullException(nameof(sp)); } - public T CreateStep() => sp.GetService(); + public T? CreateStep() => sp!.GetService(); } } diff --git a/src/GitVersion.Core/Configuration/Init/Wizard/ConfigInitWizard.cs b/src/GitVersion.Core/Configuration/Init/Wizard/ConfigInitWizard.cs index 0eda425f3e..f2e0753d3b 100644 --- a/src/GitVersion.Core/Configuration/Init/Wizard/ConfigInitWizard.cs +++ b/src/GitVersion.Core/Configuration/Init/Wizard/ConfigInitWizard.cs @@ -16,11 +16,11 @@ public ConfigInitWizard(IConsole console, IConfigInitStepFactory stepFactory) this.stepFactory = stepFactory ?? throw new ArgumentNullException(nameof(stepFactory)); } - public Config Run(Config config, string workingDirectory) + public Config? Run(Config config, string workingDirectory) { console.WriteLine("GitVersion init will guide you through setting GitVersion up to work for you"); var steps = new Queue(); - steps.Enqueue(stepFactory.CreateStep()); + steps.Enqueue(stepFactory.CreateStep()!); while (steps.Count > 0) { diff --git a/src/GitVersion.Core/Configuration/Init/Wizard/ConfigInitWizardStep.cs b/src/GitVersion.Core/Configuration/Init/Wizard/ConfigInitWizardStep.cs index b7d8fc8f4a..232725ead9 100644 --- a/src/GitVersion.Core/Configuration/Init/Wizard/ConfigInitWizardStep.cs +++ b/src/GitVersion.Core/Configuration/Init/Wizard/ConfigInitWizardStep.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.Model.Configuration; @@ -41,7 +42,7 @@ public bool Apply(Queue steps, Config config, string worki InvalidResponse(steps); return true; } - var resultWithDefaultApplied = string.IsNullOrEmpty(input) ? DefaultResult : input; + var resultWithDefaultApplied = StringExtensions.IsNullOrEmpty(input) ? DefaultResult : input; var stepResult = HandleResult(resultWithDefaultApplied, steps, config, workingDirectory); if (stepResult.InvalidResponse) { @@ -65,8 +66,8 @@ private void InvalidResponse(Queue steps) steps.Enqueue(this); } - protected abstract StepResult HandleResult(string result, Queue steps, Config config, string workingDirectory); + protected abstract StepResult HandleResult(string? result, Queue steps, Config config, string workingDirectory); protected abstract string GetPrompt(Config config, string workingDirectory); - protected abstract string DefaultResult { get; } + protected abstract string? DefaultResult { get; } } } diff --git a/src/GitVersion.Core/Configuration/Init/Wizard/IConfigInitStepFactory.cs b/src/GitVersion.Core/Configuration/Init/Wizard/IConfigInitStepFactory.cs index 3fdfb52c77..e24225f1b6 100644 --- a/src/GitVersion.Core/Configuration/Init/Wizard/IConfigInitStepFactory.cs +++ b/src/GitVersion.Core/Configuration/Init/Wizard/IConfigInitStepFactory.cs @@ -2,6 +2,6 @@ namespace GitVersion.Configuration.Init.Wizard { public interface IConfigInitStepFactory { - T CreateStep(); + T? CreateStep(); } } diff --git a/src/GitVersion.Core/Configuration/Init/Wizard/IConfigInitWizard.cs b/src/GitVersion.Core/Configuration/Init/Wizard/IConfigInitWizard.cs index be2765e99a..7eccd24aad 100644 --- a/src/GitVersion.Core/Configuration/Init/Wizard/IConfigInitWizard.cs +++ b/src/GitVersion.Core/Configuration/Init/Wizard/IConfigInitWizard.cs @@ -4,6 +4,6 @@ namespace GitVersion.Configuration.Init.Wizard { public interface IConfigInitWizard { - Config Run(Config config, string workingDirectory); + Config? Run(Config config, string workingDirectory); } } diff --git a/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy1Step.cs b/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy1Step.cs index 97a6b22d53..2e36175871 100644 --- a/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy1Step.cs +++ b/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy1Step.cs @@ -10,18 +10,18 @@ public PickBranchingStrategy1Step(IConsole console, IFileSystem fileSystem, ILog { } - protected override StepResult HandleResult(string result, Queue steps, Config config, string workingDirectory) + protected override StepResult HandleResult(string? result, Queue steps, Config config, string workingDirectory) { - switch (result.ToLower()) + switch (result?.ToLower()) { case "y": Console.Write(@"Because you need to maintain multiple versions of your product in production at the same time, GitFlow is likely a good fit. GitFlow allows you to have new development happening on the 'develop' branch, patch issues in old minor versions with 'hotfix/' branches and support old major versions with 'support/' branches"); - steps.Enqueue(StepFactory.CreateStep()); + steps.Enqueue(StepFactory.CreateStep()!); return StepResult.Ok(); case "n": - steps.Enqueue(StepFactory.CreateStep()); + steps.Enqueue(StepFactory.CreateStep()!); return StepResult.Ok(); } @@ -35,6 +35,6 @@ protected override string GetPrompt(Config config, string workingDirectory) Do you need to maintain multiple versions of your application simultaneously in production? (y/n)"; } - protected override string DefaultResult => null; + protected override string? DefaultResult => null; } } diff --git a/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy2Step.cs b/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy2Step.cs index ec706ee14d..c0849d69be 100644 --- a/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy2Step.cs +++ b/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy2Step.cs @@ -10,9 +10,9 @@ public PickBranchingStrategy2Step(IConsole console, IFileSystem fileSystem, ILog { } - protected override StepResult HandleResult(string result, Queue steps, Config config, string workingDirectory) + protected override StepResult HandleResult(string? result, Queue steps, Config config, string workingDirectory) { - switch (result.ToLower()) + switch (result?.ToLower()) { case "y": Console.WriteLine("GitFlow is likely a good fit, the 'develop' branch can be used " + @@ -21,10 +21,10 @@ protected override StepResult HandleResult(string result, Queue()); + steps.Enqueue(StepFactory.CreateStep()!); return StepResult.Ok(); case "n": - steps.Enqueue(StepFactory.CreateStep()); + steps.Enqueue(StepFactory.CreateStep()!); return StepResult.Ok(); } @@ -36,6 +36,6 @@ protected override string GetPrompt(Config config, string workingDirectory) return "Do you stabilise releases while continuing work on the next version? (y/n)"; } - protected override string DefaultResult => null; + protected override string? DefaultResult => null; } } diff --git a/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy3Step.cs b/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy3Step.cs index 4791f33ffa..8b88dd5ad6 100644 --- a/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy3Step.cs +++ b/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy3Step.cs @@ -10,9 +10,9 @@ public PickBranchingStrategy3Step(IConsole console, IFileSystem fileSystem, ILog { } - protected override StepResult HandleResult(string result, Queue steps, Config config, string workingDirectory) + protected override StepResult HandleResult(string? result, Queue steps, Config config, string workingDirectory) { - switch (result.ToLower()) + switch (result?.ToLower()) { case "y": Console.WriteLine("GitFlow could be a better fit than GitHubFlow for you."); @@ -28,7 +28,7 @@ protected override StepResult HandleResult(string result, Queue()); + steps.Enqueue(StepFactory.CreateStep()!); return StepResult.Ok(); } @@ -37,6 +37,6 @@ protected override string GetPrompt(Config config, string workingDirectory) return "Do you need to build nightlies or consume packages the CI build creates without releasing those versions? (y/n)"; } - protected override string DefaultResult => null; + protected override string? DefaultResult => null; } } diff --git a/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategyStep.cs b/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategyStep.cs index 783b8aa2cb..7e8f24963b 100644 --- a/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategyStep.cs +++ b/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategyStep.cs @@ -10,19 +10,19 @@ public PickBranchingStrategyStep(IConsole console, IFileSystem fileSystem, ILog { } - protected override StepResult HandleResult(string result, Queue steps, Config config, string workingDirectory) + protected override StepResult HandleResult(string? result, Queue steps, Config config, string workingDirectory) { var returnToStep = StepFactory.CreateStep(); switch (result) { case "1": - steps.Enqueue(StepFactory.CreateStep().WithData(returnToStep, true)); + steps.Enqueue(StepFactory.CreateStep()!.WithData(returnToStep!, true)); break; case "2": - steps.Enqueue(StepFactory.CreateStep().WithData(returnToStep, true)); + steps.Enqueue(StepFactory.CreateStep()!.WithData(returnToStep!, true)); break; case "3": - steps.Enqueue(StepFactory.CreateStep()); + steps.Enqueue(StepFactory.CreateStep()!); break; default: return StepResult.InvalidResponseSelected(); @@ -40,6 +40,6 @@ protected override string GetPrompt(Config config, string workingDirectory) 3) Unsure, tell me more"; } - protected override string DefaultResult => null; + protected override string? DefaultResult => null; } } diff --git a/src/GitVersion.Core/Core/Abstractions/IFileSystem.cs b/src/GitVersion.Core/Core/Abstractions/IFileSystem.cs index bfd32bcbd5..fd03c3558c 100644 --- a/src/GitVersion.Core/Core/Abstractions/IFileSystem.cs +++ b/src/GitVersion.Core/Core/Abstractions/IFileSystem.cs @@ -11,15 +11,15 @@ public interface IFileSystem bool Exists(string file); void Delete(string path); string ReadAllText(string path); - void WriteAllText(string file, string fileContents); - void WriteAllText(string file, string fileContents, Encoding encoding); - IEnumerable DirectoryEnumerateFiles(string directory, string searchPattern, SearchOption searchOption); + void WriteAllText(string? file, string fileContents); + void WriteAllText(string? file, string fileContents, Encoding encoding); + IEnumerable DirectoryEnumerateFiles(string? directory, string searchPattern, SearchOption searchOption); Stream OpenWrite(string path); Stream OpenRead(string path); void CreateDirectory(string path); bool DirectoryExists(string path); long GetLastDirectoryWrite(string path); - bool PathsEqual(string path, string otherPath); + bool PathsEqual(string? path, string? otherPath); } } diff --git a/src/GitVersion.Core/Core/Abstractions/IGitVersionContextFactory.cs b/src/GitVersion.Core/Core/Abstractions/IGitVersionContextFactory.cs index 310c1b4251..a3746cbf07 100644 --- a/src/GitVersion.Core/Core/Abstractions/IGitVersionContextFactory.cs +++ b/src/GitVersion.Core/Core/Abstractions/IGitVersionContextFactory.cs @@ -2,6 +2,6 @@ namespace GitVersion { public interface IGitVersionContextFactory { - GitVersionContext Create(GitVersionOptions gitVersionOptions); + GitVersionContext Create(GitVersionOptions? gitVersionOptions); } } diff --git a/src/GitVersion.Core/Core/Abstractions/IRepositoryStore.cs b/src/GitVersion.Core/Core/Abstractions/IRepositoryStore.cs index 0a8f3a8d0a..8ac1273a39 100644 --- a/src/GitVersion.Core/Core/Abstractions/IRepositoryStore.cs +++ b/src/GitVersion.Core/Core/Abstractions/IRepositoryStore.cs @@ -10,23 +10,23 @@ public interface IRepositoryStore /// /// Find the merge base of the two branches, i.e. the best common ancestor of the two branches' tips. /// - ICommit FindMergeBase(IBranch branch, IBranch otherBranch); - ICommit FindMergeBase(ICommit commit, ICommit mainlineTip); - ICommit GetCurrentCommit(IBranch currentBranch, string commitId); + ICommit? FindMergeBase(IBranch branch, IBranch? otherBranch); + ICommit FindMergeBase(ICommit? commit, ICommit? mainlineTip); + ICommit? GetCurrentCommit(IBranch currentBranch, string? commitId); ICommit GetBaseVersionSource(ICommit currentBranchTip); - IEnumerable GetMainlineCommitLog(ICommit baseVersionSource, ICommit mainlineTip); - IEnumerable GetMergeBaseCommits(ICommit mergeCommit, ICommit mergedHead, ICommit findMergeBase); - IEnumerable GetCommitLog(ICommit baseVersionSource, ICommit currentCommit); + IEnumerable GetMainlineCommitLog(ICommit? baseVersionSource, ICommit? mainlineTip); + IEnumerable GetMergeBaseCommits(ICommit? mergeCommit, ICommit? mergedHead, ICommit? findMergeBase); + IEnumerable GetCommitLog(ICommit? baseVersionSource, ICommit? currentCommit); - IBranch GetTargetBranch(string targetBranchName); - IBranch FindBranch(string branchName); + IBranch GetTargetBranch(string? targetBranchName); + IBranch FindBranch(string? branchName); IBranch GetChosenBranch(Config configuration); IEnumerable GetBranchesForCommit(ICommit commit); IEnumerable GetExcludedInheritBranches(Config configuration); - IEnumerable GetReleaseBranches(IEnumerable> releaseBranchConfig); + IEnumerable GetReleaseBranches(IEnumerable>? releaseBranchConfig); IEnumerable ExcludingBranches(IEnumerable branchesToExclude); - IEnumerable GetBranchesContainingCommit(ICommit commit, IEnumerable branches = null, bool onlyTrackedBranches = false); - Dictionary> GetMainlineBranches(ICommit commit, IEnumerable> mainlineBranchConfigs); + IEnumerable GetBranchesContainingCommit(ICommit? commit, IEnumerable? branches = null, bool onlyTrackedBranches = false); + Dictionary> GetMainlineBranches(ICommit? commit, IEnumerable>? mainlineBranchConfigs); /// /// Find the commit where the given branch was branched from another branch. @@ -34,12 +34,12 @@ public interface IRepositoryStore /// BranchCommit FindCommitBranchWasBranchedFrom(IBranch branch, Config configuration, params IBranch[] excludedBranches); - SemanticVersion GetCurrentCommitTaggedVersion(ICommit commit, EffectiveConfiguration config); + SemanticVersion GetCurrentCommitTaggedVersion(ICommit? commit, EffectiveConfiguration config); SemanticVersion MaybeIncrement(BaseVersion baseVersion, GitVersionContext context); - IEnumerable GetVersionTagsOnBranch(IBranch branch, string tagPrefixRegex); - IEnumerable> GetValidVersionTags(string tagPrefixRegex, DateTimeOffset? olderThan = null); + IEnumerable GetVersionTagsOnBranch(IBranch branch, string? tagPrefixRegex); + IEnumerable> GetValidVersionTags(string? tagPrefixRegex, DateTimeOffset? olderThan = null); - bool IsCommitOnBranch(ICommit baseVersionSource, IBranch branch, ICommit firstMatchingCommit); + bool IsCommitOnBranch(ICommit? baseVersionSource, IBranch branch, ICommit firstMatchingCommit); VersionField? DetermineIncrementedField(BaseVersion baseVersion, GitVersionContext context); int GetNumberOfUncommittedChanges(); diff --git a/src/GitVersion.Core/Core/FileSystem.cs b/src/GitVersion.Core/Core/FileSystem.cs index cb64fee773..5b0a092992 100644 --- a/src/GitVersion.Core/Core/FileSystem.cs +++ b/src/GitVersion.Core/Core/FileSystem.cs @@ -33,7 +33,7 @@ public string ReadAllText(string path) return File.ReadAllText(path); } - public void WriteAllText(string file, string fileContents) + public void WriteAllText(string? file, string fileContents) { // Opinionated decision to use UTF8 with BOM when creating new files or when the existing // encoding was not easily detected due to the file not having an encoding preamble. @@ -41,12 +41,12 @@ public void WriteAllText(string file, string fileContents) WriteAllText(file, fileContents, encoding); } - public void WriteAllText(string file, string fileContents, Encoding encoding) + public void WriteAllText(string? file, string fileContents, Encoding encoding) { File.WriteAllText(file, fileContents, encoding); } - public IEnumerable DirectoryEnumerateFiles(string directory, string searchPattern, SearchOption searchOption) + public IEnumerable DirectoryEnumerateFiles(string? directory, string searchPattern, SearchOption searchOption) { return Directory.EnumerateFiles(directory, searchPattern, searchOption); } @@ -81,7 +81,7 @@ public long GetLastDirectoryWrite(string path) .Ticks; } - public bool PathsEqual(string path, string otherPath) + public bool PathsEqual(string? path, string? otherPath) { return string.Equals( Path.GetFullPath(path).TrimEnd('\\').TrimEnd('/'), diff --git a/src/GitVersion.Core/Core/GitPreparer.cs b/src/GitVersion.Core/Core/GitPreparer.cs index 8ef3da6326..c88b769daf 100644 --- a/src/GitVersion.Core/Core/GitPreparer.cs +++ b/src/GitVersion.Core/Core/GitPreparer.cs @@ -51,7 +51,7 @@ public void Prepare() log.Info($"Project root is: {projectRoot}"); log.Info($"DotGit directory is: {dotGitDirectory}"); - if (string.IsNullOrEmpty(dotGitDirectory) || string.IsNullOrEmpty(projectRoot)) + if (StringExtensions.IsNullOrEmpty(dotGitDirectory) || StringExtensions.IsNullOrEmpty(projectRoot)) { throw new Exception($"Failed to prepare or find the .git directory in path '{gitVersionOptions.WorkingDirectory}'."); } @@ -59,10 +59,10 @@ public void Prepare() PrepareInternal(normalizeGitDirectory, currentBranch, shouldCleanUpRemotes); } - private void PrepareInternal(bool normalizeGitDirectory, string currentBranch, bool shouldCleanUpRemotes = false) + private void PrepareInternal(bool normalizeGitDirectory, string? currentBranch, bool shouldCleanUpRemotes = false) { var gitVersionOptions = options.Value; - if (!string.IsNullOrWhiteSpace(gitVersionOptions.RepositoryInfo.TargetUrl)) + if (!StringExtensions.IsNullOrWhiteSpace(gitVersionOptions.RepositoryInfo.TargetUrl)) { CreateDynamicRepository(currentBranch); } @@ -78,7 +78,7 @@ private void PrepareInternal(bool normalizeGitDirectory, string currentBranch, b } } - private string ResolveCurrentBranch() + private string? ResolveCurrentBranch() { var gitVersionOptions = options.Value; var targetBranch = gitVersionOptions.RepositoryInfo.TargetBranch; @@ -87,7 +87,7 @@ private string ResolveCurrentBranch() return targetBranch; } - var isDynamicRepository = !string.IsNullOrWhiteSpace(gitVersionOptions.RepositoryInfo.DynamicRepositoryClonePath); + var isDynamicRepository = !StringExtensions.IsNullOrWhiteSpace(gitVersionOptions.RepositoryInfo.DynamicRepositoryClonePath); var currentBranch = buildAgent.GetCurrentBranch(isDynamicRepository) ?? targetBranch; log.Info("Branch from build environment: " + currentBranch); @@ -114,10 +114,10 @@ private void CleanupDuplicateOrigin() } } - private void CreateDynamicRepository(string targetBranch) + private void CreateDynamicRepository(string? targetBranch) { var gitVersionOptions = options.Value; - if (string.IsNullOrWhiteSpace(targetBranch)) + if (StringExtensions.IsNullOrWhiteSpace(targetBranch)) { throw new Exception("Dynamic Git repositories must have a target branch (/b)"); } @@ -139,7 +139,7 @@ private void CreateDynamicRepository(string targetBranch) } } - private void NormalizeGitDirectory(string targetBranch, bool isDynamicRepository) + private void NormalizeGitDirectory(string? targetBranch, bool isDynamicRepository) { using (log.IndentLog($"Normalizing git directory for branch '{targetBranch}'")) { @@ -148,7 +148,7 @@ private void NormalizeGitDirectory(string targetBranch, bool isDynamicRepository } } - private void CloneRepository(string repositoryUrl, string gitDirectory, AuthenticationInfo auth) + private void CloneRepository(string? repositoryUrl, string? gitDirectory, AuthenticationInfo auth) { using (log.IndentLog($"Cloning repository from url '{repositoryUrl}'")) { @@ -162,11 +162,11 @@ private void CloneRepository(string repositoryUrl, string gitDirectory, Authenti /// This is designed to be run *only on the build server* which checks out repositories in different ways. /// It is not recommended to run normalization against a local repository /// - private void NormalizeGitDirectory(bool noFetch, string currentBranchName, bool isDynamicRepository) + private void NormalizeGitDirectory(bool noFetch, string? currentBranchName, bool isDynamicRepository) { var authentication = options.Value.Authentication; // Need to ensure the HEAD does not move, this is essentially a BugCheck - var expectedSha = repository.Head.Tip.Sha; + var expectedSha = repository.Head.Tip?.Sha; var expectedBranchName = repository.Head.Name.Canonical; try @@ -191,10 +191,10 @@ private void NormalizeGitDirectory(bool noFetch, string currentBranchName, bool var currentBranch = repositoryStore.FindBranch(currentBranchName); // Bug fix for https://github.com/GitTools/GitVersion/issues/1754, head maybe have been changed // if this is a dynamic repository. But only allow this in case the branches are different (branch switch) - if (expectedSha != repository.Head.Tip.Sha && + if (expectedSha != repository.Head.Tip?.Sha && (isDynamicRepository || currentBranch is null || !repository.Head.Equals(currentBranch))) { - var newExpectedSha = repository.Head.Tip.Sha; + var newExpectedSha = repository.Head.Tip?.Sha; var newExpectedBranchName = repository.Head.Name.Canonical; log.Info($"Head has moved from '{expectedBranchName} | {expectedSha}' => '{newExpectedBranchName} | {newExpectedSha}', allowed since this is a dynamic repository"); @@ -202,7 +202,7 @@ private void NormalizeGitDirectory(bool noFetch, string currentBranchName, bool expectedSha = newExpectedSha; } - var headSha = repository.Refs.Head.TargetIdentifier; + var headSha = repository.Refs.Head?.TargetIdentifier; if (!repository.IsHeadDetached) { @@ -216,9 +216,9 @@ private void NormalizeGitDirectory(bool noFetch, string currentBranchName, bool // In order to decide whether a fake branch is required or not, first check to see if any local branches have the same commit SHA of the head SHA. // If they do, go ahead and checkout that branch // If no, go ahead and check out a new branch, using the known commit SHA as the pointer - var localBranchesWhereCommitShaIsHead = repository.Branches.Where(b => !b.IsRemote && b.Tip.Sha == headSha).ToList(); + var localBranchesWhereCommitShaIsHead = repository.Branches.Where(b => !b.IsRemote && b.Tip?.Sha == headSha).ToList(); - var matchingCurrentBranch = !string.IsNullOrEmpty(currentBranchName) + var matchingCurrentBranch = !StringExtensions.IsNullOrEmpty(currentBranchName) ? localBranchesWhereCommitShaIsHead.SingleOrDefault(b => b.Name.Canonical.Replace("/heads/", "/") == currentBranchName.Replace("/heads/", "/")) : null; if (matchingCurrentBranch != null) @@ -267,7 +267,7 @@ private void NormalizeGitDirectory(bool noFetch, string currentBranchName, bool } finally { - if (repository.Head.Tip.Sha != expectedSha) + if (repository.Head.Tip?.Sha != expectedSha) { if (environment.GetEnvironmentVariable("IGNORE_NORMALISATION_GIT_HEAD_MOVE") != "1") { @@ -325,13 +325,13 @@ private void CreateOrUpdateLocalBranchesFromRemoteTrackingOnes(string remoteName if (repository.Refs.Any(x => x.Name.Equals(referenceName))) { - var localRef = repository.Refs[localCanonicalName]; + var localRef = repository.Refs[localCanonicalName]!; if (localRef.TargetIdentifier == remoteTrackingReference.TargetIdentifier) { log.Info($"Skipping update of '{remoteTrackingReference.Name.Canonical}' as it already matches the remote ref."); continue; } - var remoteRefTipId = remoteTrackingReference.ReferenceTargetId; + var remoteRefTipId = remoteTrackingReference.ReferenceTargetId!; log.Info($"Updating local ref '{localRef.Name.Canonical}' to point at {remoteRefTipId}."); retryAction.Execute(() => repository.Refs.UpdateTarget(localRef, remoteRefTipId)); continue; @@ -340,19 +340,19 @@ private void CreateOrUpdateLocalBranchesFromRemoteTrackingOnes(string remoteName log.Info($"Creating local branch from remote tracking '{remoteTrackingReference.Name.Canonical}'."); repository.Refs.Add(localCanonicalName, remoteTrackingReference.TargetIdentifier, true); - var branch = repository.Branches[branchName]; + var branch = repository.Branches[branchName]!; repository.Branches.UpdateTrackedBranch(branch, remoteTrackingReferenceName); } } - public void EnsureLocalBranchExistsForCurrentBranch(IRemote remote, string currentBranch) + public void EnsureLocalBranchExistsForCurrentBranch(IRemote? remote, string? currentBranch) { if (remote is null) { throw new ArgumentNullException(nameof(remote)); } - if (string.IsNullOrEmpty(currentBranch)) return; + if (StringExtensions.IsNullOrEmpty(currentBranch)) return; var isRef = currentBranch.Contains("refs"); var isBranch = currentBranch.Contains("refs/heads"); @@ -372,7 +372,7 @@ public void EnsureLocalBranchExistsForCurrentBranch(IRemote remote, string curre repoTip = originBranch.Tip; } - var repoTipId = repoTip.Id; + var repoTipId = repoTip!.Id; var referenceName = ReferenceName.Parse(localCanonicalName); if (repository.Branches.All(b => !b.Name.Equals(referenceName))) @@ -385,7 +385,7 @@ public void EnsureLocalBranchExistsForCurrentBranch(IRemote remote, string curre { log.Info(isBranch ? $"Updating local branch {referenceName} to point at {repoTip}" : $"Updating local branch {referenceName} to match ref {currentBranch}"); - var localRef = repository.Refs[localCanonicalName]; + var localRef = repository.Refs[localCanonicalName]!; retryAction.Execute(() => repository.Refs.UpdateTarget(localRef, repoTipId)); } diff --git a/src/GitVersion.Core/Core/GitVersionCalculateTool.cs b/src/GitVersion.Core/Core/GitVersionCalculateTool.cs index ffe27ffaf8..9994a082fc 100644 --- a/src/GitVersion.Core/Core/GitVersionCalculateTool.cs +++ b/src/GitVersion.Core/Core/GitVersionCalculateTool.cs @@ -50,7 +50,7 @@ public VersionVariables CalculateVersionVariables() if (versionVariables != null) return versionVariables; var semanticVersion = nextVersionCalculator.FindVersion(); - versionVariables = variableProvider.GetVariablesFor(semanticVersion, context.Configuration, context.IsCurrentCommitTagged); + versionVariables = variableProvider.GetVariablesFor(semanticVersion, context.Configuration!, context.IsCurrentCommitTagged); if (gitVersionOptions.Settings.NoCache) return versionVariables; try diff --git a/src/GitVersion.Core/Core/GitVersionContextFactory.cs b/src/GitVersion.Core/Core/GitVersionContextFactory.cs index 234b5411ff..1193599d6e 100644 --- a/src/GitVersion.Core/Core/GitVersionContextFactory.cs +++ b/src/GitVersion.Core/Core/GitVersionContextFactory.cs @@ -21,19 +21,19 @@ public GitVersionContextFactory(IConfigProvider configProvider, IRepositoryStore this.options = options ?? throw new ArgumentNullException(nameof(options)); } - public GitVersionContext Create(GitVersionOptions gitVersionOptions) + public GitVersionContext Create(GitVersionOptions? gitVersionOptions) { - var currentBranch = repositoryStore.GetTargetBranch(gitVersionOptions.RepositoryInfo.TargetBranch); + var currentBranch = repositoryStore.GetTargetBranch(gitVersionOptions?.RepositoryInfo.TargetBranch); if (currentBranch == null) throw new InvalidOperationException("Need a branch to operate on"); var configuration = configProvider.Provide(overrideConfig: options.Value.ConfigInfo.OverrideConfig); - var currentCommit = repositoryStore.GetCurrentCommit(currentBranch, gitVersionOptions.RepositoryInfo.CommitId); + var currentCommit = repositoryStore.GetCurrentCommit(currentBranch, gitVersionOptions?.RepositoryInfo.CommitId); if (currentBranch.IsDetachedHead) { - var branchForCommit = repositoryStore.GetBranchesContainingCommit(currentCommit, onlyTrackedBranches: gitVersionOptions.Settings.OnlyTrackedBranches).OnlyOrDefault(); + var branchForCommit = repositoryStore.GetBranchesContainingCommit(currentCommit, onlyTrackedBranches: gitVersionOptions?.Settings.OnlyTrackedBranches == true).OnlyOrDefault(); currentBranch = branchForCommit ?? currentBranch; } diff --git a/src/GitVersion.Core/Core/GitVersionOutputTool.cs b/src/GitVersion.Core/Core/GitVersionOutputTool.cs index 2342faf5e8..5cffb73bee 100644 --- a/src/GitVersion.Core/Core/GitVersionOutputTool.cs +++ b/src/GitVersion.Core/Core/GitVersionOutputTool.cs @@ -45,7 +45,7 @@ public void OutputVariables(VersionVariables variables, bool updateBuildNumber) public void UpdateAssemblyInfo(VersionVariables variables) { - var gitVersionOptions = options.Value; + var gitVersionOptions = options.Value!; var assemblyInfoContext = new AssemblyInfoContext(gitVersionOptions.WorkingDirectory, gitVersionOptions.AssemblyInfo.EnsureAssemblyInfo, gitVersionOptions.AssemblyInfo.Files.ToArray()); if (gitVersionOptions.AssemblyInfo.UpdateProjectFiles) diff --git a/src/GitVersion.Core/Core/RepositoryStore.cs b/src/GitVersion.Core/Core/RepositoryStore.cs index 14567160ed..029f17b8ba 100644 --- a/src/GitVersion.Core/Core/RepositoryStore.cs +++ b/src/GitVersion.Core/Core/RepositoryStore.cs @@ -4,6 +4,7 @@ using System.Text.RegularExpressions; using GitVersion.Common; using GitVersion.Configuration; +using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.Model.Configuration; using GitVersion.VersionCalculation; @@ -13,8 +14,8 @@ namespace GitVersion public class RepositoryStore : IRepositoryStore { private readonly Dictionary> mergeBaseCommitsCache = new(); - private readonly Dictionary, ICommit> mergeBaseCache = new(); - private readonly Dictionary> semanticVersionTagsOnBranchCache = new(); + private readonly Dictionary, ICommit?> mergeBaseCache = new(); + private readonly Dictionary> semanticVersionTagsOnBranchCache = new(); private const string MissingTipFormat = "{0} has no tip. Please see http://example.com/docs for information on how to fix this."; private readonly ILog log; @@ -29,7 +30,7 @@ public RepositoryStore(ILog log, IGitRepository repository) /// /// Find the merge base of the two branches, i.e. the best common ancestor of the two branches' tips. /// - public ICommit FindMergeBase(IBranch branch, IBranch otherBranch) + public ICommit? FindMergeBase(IBranch branch, IBranch? otherBranch) { var key = Tuple.Create(branch, otherBranch); @@ -42,11 +43,11 @@ public ICommit FindMergeBase(IBranch branch, IBranch otherBranch) using (log.IndentLog($"Finding merge base between '{branch}' and '{otherBranch}'.")) { // Other branch tip is a forward merge - var commitToFindCommonBase = otherBranch.Tip; + var commitToFindCommonBase = otherBranch?.Tip; var commit = branch.Tip; - if (otherBranch.Tip.Parents.Contains(commit)) + if (commitToFindCommonBase?.Parents.Contains(commit) == true) { - commitToFindCommonBase = otherBranch.Tip.Parents.First(); + commitToFindCommonBase = otherBranch!.Tip!.Parents.First(); } var findMergeBase = FindMergeBase(commit, commitToFindCommonBase); @@ -94,10 +95,10 @@ public ICommit FindMergeBase(IBranch branch, IBranch otherBranch) } } - public ICommit GetCurrentCommit(IBranch currentBranch, string commitId) + public ICommit? GetCurrentCommit(IBranch currentBranch, string? commitId) { - ICommit currentCommit = null; - if (!string.IsNullOrWhiteSpace(commitId)) + ICommit? currentCommit = null; + if (!StringExtensions.IsNullOrWhiteSpace(commitId)) { log.Info($"Searching for specific commit '{commitId}'"); @@ -137,7 +138,7 @@ public ICommit GetBaseVersionSource(ICommit currentBranchTip) throw new GitVersionException($"Cannot find commit {currentBranchTip}. Please ensure that the repository is an unshallow clone with `git fetch --unshallow`.", exception); } } - public IEnumerable GetMainlineCommitLog(ICommit baseVersionSource, ICommit mainlineTip) + public IEnumerable GetMainlineCommitLog(ICommit? baseVersionSource, ICommit? mainlineTip) { var filter = new CommitFilter { @@ -149,7 +150,7 @@ public IEnumerable GetMainlineCommitLog(ICommit baseVersionSource, ICom return repository.Commits.QueryBy(filter); } - public IEnumerable GetMergeBaseCommits(ICommit mergeCommit, ICommit mergedHead, ICommit findMergeBase) + public IEnumerable GetMergeBaseCommits(ICommit? mergeCommit, ICommit? mergedHead, ICommit? findMergeBase) { var filter = new CommitFilter { @@ -167,13 +168,13 @@ public IEnumerable GetMergeBaseCommits(ICommit mergeCommit, ICommit mer return commits; } - public IBranch GetTargetBranch(string targetBranchName) + public IBranch GetTargetBranch(string? targetBranchName) { // By default, we assume HEAD is pointing to the desired branch var desiredBranch = repository.Head; // Make sure the desired branch has been specified - if (!string.IsNullOrEmpty(targetBranchName)) + if (!StringExtensions.IsNullOrEmpty(targetBranchName)) { // There are some edge cases where HEAD is not pointing to the desired branch. // Therefore it's important to verify if 'currentBranch' is indeed the desired branch. @@ -196,12 +197,12 @@ public IBranch GetTargetBranch(string targetBranchName) return desiredBranch; } - public IBranch FindBranch(string branchName) => repository.Branches.FirstOrDefault(x => x.Name.EquivalentTo(branchName)); + public IBranch FindBranch(string? branchName) => repository.Branches.FirstOrDefault(x => x.Name.EquivalentTo(branchName)); public IBranch GetChosenBranch(Config configuration) { - var developBranchRegex = configuration.Branches[Config.DevelopBranchKey].Regex; - var mainBranchRegex = configuration.Branches[Config.MainBranchKey].Regex; + var developBranchRegex = configuration.Branches[Config.DevelopBranchKey]?.Regex; + var mainBranchRegex = configuration.Branches[Config.MainBranchKey]?.Regex; var chosenBranch = repository.Branches.FirstOrDefault(b => Regex.IsMatch(b.Name.Friendly, developBranchRegex, RegexOptions.IgnoreCase) || @@ -225,10 +226,10 @@ public IEnumerable GetExcludedInheritBranches(Config configuration) }).ToList(); } - public IEnumerable GetReleaseBranches(IEnumerable> releaseBranchConfig) + public IEnumerable GetReleaseBranches(IEnumerable>? releaseBranchConfig) { return repository.Branches - .Where(b => releaseBranchConfig.Any(c => Regex.IsMatch(b.Name.Friendly, c.Value.Regex))); + .Where(b => releaseBranchConfig?.Any(c => Regex.IsMatch(b.Name.Friendly, c.Value?.Regex)) == true); } public IEnumerable ExcludingBranches(IEnumerable branchesToExclude) @@ -237,7 +238,7 @@ public IEnumerable ExcludingBranches(IEnumerable branchesToExc } // TODO Should we cache this? - public IEnumerable GetBranchesContainingCommit(ICommit commit, IEnumerable branches = null, bool onlyTrackedBranches = false) + public IEnumerable GetBranchesContainingCommit(ICommit? commit, IEnumerable? branches = null, bool onlyTrackedBranches = false) { if (commit == null) { @@ -250,7 +251,7 @@ public IEnumerable GetBranchesContainingCommit(ICommit commit, IEnumera // Yielding part is split from the main part of the method to avoid having the exception check performed lazily. // Details at https://github.com/GitTools/GitVersion/issues/2755 - static IEnumerable InnerGetBranchesContainingCommit(ICommit commit, IEnumerable branches, bool onlyTrackedBranches, IGitRepository repository, ILog log) + static IEnumerable InnerGetBranchesContainingCommit(ICommit commit, IEnumerable? branches, bool onlyTrackedBranches, IGitRepository repository, ILog log) { branches ??= repository.Branches.ToList(); @@ -297,13 +298,10 @@ static IEnumerable InnerGetBranchesContainingCommit(ICommit commit, IEn } } - public Dictionary> GetMainlineBranches(ICommit commit, IEnumerable> mainlineBranchConfigs) + public Dictionary> GetMainlineBranches(ICommit? commit, IEnumerable>? mainlineBranchConfigs) { return repository.Branches - .Where(b => - { - return mainlineBranchConfigs.Any(c => Regex.IsMatch(b.Name.Friendly, c.Value.Regex)); - }) + .Where(b => mainlineBranchConfigs?.Any(c => Regex.IsMatch(b.Name.Friendly, c.Value?.Regex)) == true) .Select(b => new { MergeBase = FindMergeBase(b.Tip, commit), @@ -350,7 +348,7 @@ public BranchCommit FindCommitBranchWasBranchedFrom(IBranch branch, Config confi } } - public SemanticVersion GetCurrentCommitTaggedVersion(ICommit commit, EffectiveConfiguration config) + public SemanticVersion GetCurrentCommitTaggedVersion(ICommit? commit, EffectiveConfiguration config) { return repository.Tags .SelectMany(t => @@ -372,7 +370,7 @@ public SemanticVersion MaybeIncrement(BaseVersion baseVersion, GitVersionContext return increment != null ? baseVersion.SemanticVersion.IncrementVersion(increment.Value) : baseVersion.SemanticVersion; } - public IEnumerable GetVersionTagsOnBranch(IBranch branch, string tagPrefixRegex) + public IEnumerable GetVersionTagsOnBranch(IBranch branch, string? tagPrefixRegex) { if (semanticVersionTagsOnBranchCache.ContainsKey(branch)) { @@ -384,16 +382,16 @@ public IEnumerable GetVersionTagsOnBranch(IBranch branch, strin { var tags = GetValidVersionTags(tagPrefixRegex); - var versionTags = branch.Commits.SelectMany(c => tags.Where(t => c.Sha == t.Item1.TargetSha).Select(t => t.Item2)).ToList(); + var versionTags = branch.Commits.SelectMany(c => tags.Where(t => c.Sha == t.Item1?.TargetSha).Select(t => t.Item2)).ToList(); semanticVersionTagsOnBranchCache.Add(branch, versionTags); return versionTags; } } - public IEnumerable> GetValidVersionTags(string tagPrefixRegex, DateTimeOffset? olderThan = null) + public IEnumerable> GetValidVersionTags(string? tagPrefixRegex, DateTimeOffset? olderThan = null) { - var tags = new List>(); + var tags = new List>(); foreach (var tag in repository.Tags) { @@ -407,14 +405,16 @@ public IEnumerable> GetValidVersionTags(string tagP if (SemanticVersion.TryParse(tag.Name.Friendly, tagPrefixRegex, out var semver)) { +#pragma warning disable CS8620 // Argument cannot be used for parameter due to differences in the nullability of reference types. tags.Add(Tuple.Create(tag, semver)); +#pragma warning restore CS8620 // Argument cannot be used for parameter due to differences in the nullability of reference types. } } return tags; } - public IEnumerable GetCommitLog(ICommit baseVersionSource, ICommit currentCommit) + public IEnumerable GetCommitLog(ICommit? baseVersionSource, ICommit? currentCommit) { var filter = new CommitFilter { @@ -431,7 +431,7 @@ public IEnumerable GetCommitLog(ICommit baseVersionSource, ICommit curr return IncrementStrategyFinder.DetermineIncrementedField(repository, context, baseVersion); } - public bool IsCommitOnBranch(ICommit baseVersionSource, IBranch branch, ICommit firstMatchingCommit) + public bool IsCommitOnBranch(ICommit? baseVersionSource, IBranch branch, ICommit firstMatchingCommit) { var filter = new CommitFilter { @@ -454,7 +454,7 @@ private IEnumerable GetMergeCommitsForBranch(IBranch branch, Confi var currentBranchConfig = configuration.GetConfigForBranch(branch.Name.WithoutRemote); var regexesToCheck = currentBranchConfig == null ? new[] { ".*" } // Match anything if we can't find a branch config - : currentBranchConfig.SourceBranches.Select(sb => configuration.Branches[sb].Regex); + : currentBranchConfig.SourceBranches.Select(sb => configuration.Branches[sb]?.Regex); var branchMergeBases = ExcludingBranches(excludedBranches) .Where(b => { @@ -472,7 +472,7 @@ private IEnumerable GetMergeCommitsForBranch(IBranch branch, Confi } var findMergeBase = FindMergeBase(branch, otherBranch); - return new BranchCommit(findMergeBase, otherBranch); + return new BranchCommit(findMergeBase!, otherBranch); }) .Where(b => b.Commit != null) .OrderByDescending(b => b.Commit.When) @@ -493,7 +493,7 @@ private static IEnumerable GetCommitsReacheableFrom(IGitRepository repo return commitCollection.Where(c => c.Sha == commit.Sha); } - private ICommit GetForwardMerge(ICommit commitToFindCommonBase, ICommit findMergeBase) + private ICommit GetForwardMerge(ICommit? commitToFindCommonBase, ICommit? findMergeBase) { var filter = new CommitFilter { @@ -505,7 +505,7 @@ private ICommit GetForwardMerge(ICommit commitToFindCommonBase, ICommit findMerg return commitCollection.FirstOrDefault(c => c.Parents.Contains(findMergeBase)); } - public ICommit FindMergeBase(ICommit commit, ICommit mainlineTip) => repository.FindMergeBase(commit, mainlineTip); + public ICommit FindMergeBase(ICommit? commit, ICommit? mainlineTip) => repository.FindMergeBase(commit, mainlineTip); public int GetNumberOfUncommittedChanges() => repository.GetNumberOfUncommittedChanges(); } diff --git a/src/GitVersion.Core/Extensions/AssemblyVersionsGeneratorExtensions.cs b/src/GitVersion.Core/Extensions/AssemblyVersionsGeneratorExtensions.cs index c41bb0a60a..77ab7f9464 100644 --- a/src/GitVersion.Core/Extensions/AssemblyVersionsGeneratorExtensions.cs +++ b/src/GitVersion.Core/Extensions/AssemblyVersionsGeneratorExtensions.cs @@ -22,27 +22,27 @@ public enum AssemblyVersioningScheme public static class AssemblyVersionsGeneratorExtensions { - public static string GetAssemblyVersion(this SemanticVersion sv, AssemblyVersioningScheme scheme) + public static string? GetAssemblyVersion(this SemanticVersion sv, AssemblyVersioningScheme scheme) { return scheme switch { AssemblyVersioningScheme.Major => $"{sv.Major}.0.0.0", AssemblyVersioningScheme.MajorMinor => $"{sv.Major}.{sv.Minor}.0.0", AssemblyVersioningScheme.MajorMinorPatch => $"{sv.Major}.{sv.Minor}.{sv.Patch}.0", - AssemblyVersioningScheme.MajorMinorPatchTag => $"{sv.Major}.{sv.Minor}.{sv.Patch}.{sv.PreReleaseTag.Number ?? 0}", + AssemblyVersioningScheme.MajorMinorPatchTag => $"{sv.Major}.{sv.Minor}.{sv.Patch}.{sv.PreReleaseTag?.Number ?? 0}", AssemblyVersioningScheme.None => null, _ => throw new ArgumentException($"Unexpected value ({scheme}).", nameof(scheme)) }; } - public static string GetAssemblyFileVersion(this SemanticVersion sv, AssemblyFileVersioningScheme scheme) + public static string? GetAssemblyFileVersion(this SemanticVersion sv, AssemblyFileVersioningScheme scheme) { return scheme switch { AssemblyFileVersioningScheme.Major => $"{sv.Major}.0.0.0", AssemblyFileVersioningScheme.MajorMinor => $"{sv.Major}.{sv.Minor}.0.0", AssemblyFileVersioningScheme.MajorMinorPatch => $"{sv.Major}.{sv.Minor}.{sv.Patch}.0", - AssemblyFileVersioningScheme.MajorMinorPatchTag => $"{sv.Major}.{sv.Minor}.{sv.Patch}.{sv.PreReleaseTag.Number ?? 0}", + AssemblyFileVersioningScheme.MajorMinorPatchTag => $"{sv.Major}.{sv.Minor}.{sv.Patch}.{sv.PreReleaseTag?.Number ?? 0}", AssemblyFileVersioningScheme.None => null, _ => throw new ArgumentException($"Unexpected value ({scheme}).", nameof(scheme)) }; diff --git a/src/GitVersion.Core/Extensions/EnumerableExtensions.cs b/src/GitVersion.Core/Extensions/EnumerableExtensions.cs index 1ffc3b69fe..fd5eb751ba 100644 --- a/src/GitVersion.Core/Extensions/EnumerableExtensions.cs +++ b/src/GitVersion.Core/Extensions/EnumerableExtensions.cs @@ -5,7 +5,7 @@ namespace GitVersion.Extensions { public static class EnumerableExtensions { - public static T OnlyOrDefault(this IEnumerable source) + public static T? OnlyOrDefault(this IEnumerable source) { switch (source) { diff --git a/src/GitVersion.Core/Extensions/GitExtensions.cs b/src/GitVersion.Core/Extensions/GitExtensions.cs index e8b0d863a5..a7d59ff9bd 100644 --- a/src/GitVersion.Core/Extensions/GitExtensions.cs +++ b/src/GitVersion.Core/Extensions/GitExtensions.cs @@ -7,7 +7,7 @@ namespace GitVersion.Extensions { public static class GitExtensions { - public static void DumpGraph(string workingDirectory, Action writer = null, int? maxCommits = null) + public static void DumpGraph(string workingDirectory, Action? writer = null, int? maxCommits = null) { var output = new StringBuilder(); try diff --git a/src/GitVersion.Core/Extensions/NullableAttributes.cs b/src/GitVersion.Core/Extensions/NullableAttributes.cs new file mode 100644 index 0000000000..23e364d106 --- /dev/null +++ b/src/GitVersion.Core/Extensions/NullableAttributes.cs @@ -0,0 +1,149 @@ +// This was copied from https://github.com/dotnet/coreclr/blob/60f1e6265bd1039f023a82e0643b524d6aaf7845/src/System.Private.CoreLib/shared/System/Diagnostics/CodeAnalysis/NullableAttributes.cs +// and updated to have the scope of the attributes be internal. + +#pragma warning disable CA1019 // Define accessors for attribute arguments + +namespace System.Diagnostics.CodeAnalysis +{ +#if !NETCOREAPP + + /// Specifies that null is allowed as an input even if the corresponding type disallows it. + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)] + internal sealed class AllowNullAttribute : Attribute { } + + /// Specifies that null is disallowed as an input even if the corresponding type allows it. + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)] + internal sealed class DisallowNullAttribute : Attribute { } + + /// Specifies that an output may be null even if the corresponding type disallows it. + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)] + internal sealed class MaybeNullAttribute : Attribute { } + + /// Specifies that an output will not be null even if the corresponding type allows it. + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)] + internal sealed class NotNullAttribute : Attribute { } + + /// Specifies that when a method returns , the parameter may be null even if the corresponding type disallows it. + [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] + internal sealed class MaybeNullWhenAttribute : Attribute + { + /// Initializes the attribute with the specified return value condition. + /// + /// The return value condition. If the method returns this value, the associated parameter may be null. + /// + public MaybeNullWhenAttribute(bool returnValue) => ReturnValue = returnValue; + + /// Gets the return value condition. + public bool ReturnValue { get; } + } + + /// Specifies that when a method returns , the parameter will not be null even if the corresponding type allows it. + [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] + internal sealed class NotNullWhenAttribute : Attribute + { + /// Initializes the attribute with the specified return value condition. + /// + /// The return value condition. If the method returns this value, the associated parameter will not be null. + /// + public NotNullWhenAttribute(bool returnValue) => ReturnValue = returnValue; + + /// Gets the return value condition. + public bool ReturnValue { get; } + } + + /// Specifies that the output will be non-null if the named parameter is non-null. + [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] + internal sealed class NotNullIfNotNullAttribute : Attribute + { + /// Initializes the attribute with the associated parameter name. + /// + /// The associated parameter name. The output will be non-null if the argument to the parameter specified is non-null. + /// + public NotNullIfNotNullAttribute(string parameterName) => ParameterName = parameterName; + + /// Gets the associated parameter name. + public string ParameterName { get; } + } + + /// Applied to a method that will never return under any circumstance. + [AttributeUsage(AttributeTargets.Method, Inherited = false)] + internal sealed class DoesNotReturnAttribute : Attribute { } + + /// Specifies that the method will not return if the associated Boolean parameter is passed the specified value. + [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] + internal sealed class DoesNotReturnIfAttribute : Attribute + { + /// Initializes the attribute with the specified parameter value. + /// + /// The condition parameter value. Code after the method will be considered unreachable by diagnostics if the argument to + /// the associated parameter matches this value. + /// + public DoesNotReturnIfAttribute(bool parameterValue) => ParameterValue = parameterValue; + + /// Gets the condition parameter value. + public bool ParameterValue { get; } + } + +#endif + +#if !NETCOREAPP || NETCOREAPP3_1 + + /// Specifies that the method or property will ensure that the listed field and property members have not-null values. + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] + internal sealed class MemberNotNullAttribute : Attribute + { + /// Initializes the attribute with a field or property member. + /// + /// The field or property member that is promised to be not-null. + /// + public MemberNotNullAttribute(string member) => Members = new[] { member }; + + /// Initializes the attribute with the list of field and property members. + /// + /// The list of field and property members that are promised to be not-null. + /// + public MemberNotNullAttribute(params string[] members) => Members = members; + + /// Gets field or property member names. + public string[] Members { get; } + } + + /// Specifies that the method or property will ensure that the listed field and property members have not-null values when returning with the specified return value condition. + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] + internal sealed class MemberNotNullWhenAttribute : Attribute + { + /// Initializes the attribute with the specified return value condition and a field or property member. + /// + /// The return value condition. If the method returns this value, the associated parameter will not be null. + /// + /// + /// The field or property member that is promised to be not-null. + /// + public MemberNotNullWhenAttribute(bool returnValue, string member) + { + ReturnValue = returnValue; + Members = new[] { member }; + } + + /// Initializes the attribute with the specified return value condition and list of field and property members. + /// + /// The return value condition. If the method returns this value, the associated parameter will not be null. + /// + /// + /// The list of field and property members that are promised to be not-null. + /// + public MemberNotNullWhenAttribute(bool returnValue, params string[] members) + { + ReturnValue = returnValue; + Members = members; + } + + /// Gets the return value condition. + public bool ReturnValue { get; } + + /// Gets field or property member names. + public string[] Members { get; } + } + +#endif +} diff --git a/src/GitVersion.Core/Extensions/ServiceCollectionExtensions.cs b/src/GitVersion.Core/Extensions/ServiceCollectionExtensions.cs index 7a696a4b41..499dad18a9 100644 --- a/src/GitVersion.Core/Extensions/ServiceCollectionExtensions.cs +++ b/src/GitVersion.Core/Extensions/ServiceCollectionExtensions.cs @@ -14,7 +14,7 @@ public static IServiceCollection AddModule(this IServiceCollection serviceCollec public static TService GetServiceForType(this IServiceProvider serviceProvider) { - return serviceProvider.GetServices().SingleOrDefault(t => t.GetType() == typeof(TType)); + return serviceProvider.GetServices().SingleOrDefault(t => t?.GetType() == typeof(TType)); } } } diff --git a/src/GitVersion.Core/Extensions/StringExtensions.cs b/src/GitVersion.Core/Extensions/StringExtensions.cs index 1d81b8142f..5e4725232c 100644 --- a/src/GitVersion.Core/Extensions/StringExtensions.cs +++ b/src/GitVersion.Core/Extensions/StringExtensions.cs @@ -1,4 +1,5 @@ using System; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Text; @@ -130,9 +131,15 @@ public static string RegexReplace(this string input, string pattern, string repl return Regex.Replace(input, pattern, replace, options); } - public static bool IsEquivalentTo(this string self, string other) + public static bool IsEquivalentTo(this string self, string? other) { return string.Equals(self, other, StringComparison.OrdinalIgnoreCase); } + + /// + public static bool IsNullOrEmpty([NotNullWhen(returnValue: false)] string? value) => string.IsNullOrEmpty(value); + + /// + public static bool IsNullOrWhiteSpace([NotNullWhen(returnValue: false)] string? value) => string.IsNullOrWhiteSpace(value); } } diff --git a/src/GitVersion.Core/Git/CommitFilter.cs b/src/GitVersion.Core/Git/CommitFilter.cs index dbcb395cc1..5b9a2db7be 100644 --- a/src/GitVersion.Core/Git/CommitFilter.cs +++ b/src/GitVersion.Core/Git/CommitFilter.cs @@ -6,8 +6,8 @@ public class CommitFilter { public bool FirstParentOnly { get; set; } - public object IncludeReachableFrom { get; set; } - public object ExcludeReachableFrom { get; set; } + public object? IncludeReachableFrom { get; set; } + public object? ExcludeReachableFrom { get; set; } public CommitSortStrategies SortBy { get; set; } } diff --git a/src/GitVersion.Core/Git/IBranch.cs b/src/GitVersion.Core/Git/IBranch.cs index bc299d58e1..7c89ab4087 100644 --- a/src/GitVersion.Core/Git/IBranch.cs +++ b/src/GitVersion.Core/Git/IBranch.cs @@ -4,11 +4,11 @@ namespace GitVersion { public interface IBranch : IEquatable, IComparable, INamedReference { - ICommit Tip { get; } + ICommit? Tip { get; } bool IsRemote { get; } bool IsTracking { get; } bool IsDetachedHead { get; } - ICommitCollection Commits { get; } + ICommitCollection? Commits { get; } } } diff --git a/src/GitVersion.Core/Git/IBranchCollection.cs b/src/GitVersion.Core/Git/IBranchCollection.cs index 3cf1c2e7b4..a2ffc42b22 100644 --- a/src/GitVersion.Core/Git/IBranchCollection.cs +++ b/src/GitVersion.Core/Git/IBranchCollection.cs @@ -4,7 +4,7 @@ namespace GitVersion { public interface IBranchCollection : IEnumerable { - IBranch this[string name] { get; } + IBranch? this[string name] { get; } IEnumerable ExcludeBranches(IEnumerable branchesToExclude); void UpdateTrackedBranch(IBranch branch, string remoteTrackingReferenceName); } diff --git a/src/GitVersion.Core/Git/IGitRepository.cs b/src/GitVersion.Core/Git/IGitRepository.cs index 376f463e89..d6ec7ab2a4 100644 --- a/src/GitVersion.Core/Git/IGitRepository.cs +++ b/src/GitVersion.Core/Git/IGitRepository.cs @@ -12,7 +12,7 @@ public interface IGitRepository ICommitCollection Commits { get; } IRemoteCollection Remotes { get; } - ICommit FindMergeBase(ICommit commit, ICommit otherCommit); + ICommit FindMergeBase(ICommit? commit, ICommit? otherCommit); int GetNumberOfUncommittedChanges(); } } diff --git a/src/GitVersion.Core/Git/IGitRepositoryInfo.cs b/src/GitVersion.Core/Git/IGitRepositoryInfo.cs index e8ec427860..02ce1fa1c6 100644 --- a/src/GitVersion.Core/Git/IGitRepositoryInfo.cs +++ b/src/GitVersion.Core/Git/IGitRepositoryInfo.cs @@ -2,9 +2,9 @@ namespace GitVersion { public interface IGitRepositoryInfo { - string DotGitDirectory { get; } - string ProjectRootDirectory { get; } - string DynamicGitRepositoryPath { get; } - string GitRootPath { get; } + string? DotGitDirectory { get; } + string? ProjectRootDirectory { get; } + string? DynamicGitRepositoryPath { get; } + string? GitRootPath { get; } } } diff --git a/src/GitVersion.Core/Git/IMutatingGitRepository.cs b/src/GitVersion.Core/Git/IMutatingGitRepository.cs index e3f263b425..72754a35cf 100644 --- a/src/GitVersion.Core/Git/IMutatingGitRepository.cs +++ b/src/GitVersion.Core/Git/IMutatingGitRepository.cs @@ -6,7 +6,7 @@ public interface IMutatingGitRepository : IGitRepository { void CreateBranchForPullRequestBranch(AuthenticationInfo auth); void Checkout(string commitOrBranchSpec); - void Fetch(string remote, IEnumerable refSpecs, AuthenticationInfo auth, string logMessage); - void Clone(string sourceUrl, string workdirPath, AuthenticationInfo auth); + void Fetch(string remote, IEnumerable refSpecs, AuthenticationInfo auth, string? logMessage); + void Clone(string? sourceUrl, string? workdirPath, AuthenticationInfo auth); } } diff --git a/src/GitVersion.Core/Git/IReference.cs b/src/GitVersion.Core/Git/IReference.cs index 8ce5a202e5..4b8e4b1117 100644 --- a/src/GitVersion.Core/Git/IReference.cs +++ b/src/GitVersion.Core/Git/IReference.cs @@ -5,6 +5,6 @@ namespace GitVersion public interface IReference : IEquatable, IComparable, INamedReference { string TargetIdentifier { get; } - IObjectId ReferenceTargetId { get; } + IObjectId? ReferenceTargetId { get; } } } diff --git a/src/GitVersion.Core/Git/IReferenceCollection.cs b/src/GitVersion.Core/Git/IReferenceCollection.cs index 0a0a15a306..b9f84e4ae4 100644 --- a/src/GitVersion.Core/Git/IReferenceCollection.cs +++ b/src/GitVersion.Core/Git/IReferenceCollection.cs @@ -4,8 +4,8 @@ namespace GitVersion { public interface IReferenceCollection : IEnumerable { - IReference Head { get; } - IReference this[string name] { get; } + IReference? Head { get; } + IReference? this[string name] { get; } void Add(string name, string canonicalRefNameOrObjectish, bool allowOverwrite = false); void UpdateTarget(IReference directRef, IObjectId targetId); IEnumerable FromGlob(string prefix); diff --git a/src/GitVersion.Core/Git/IRemoteCollection.cs b/src/GitVersion.Core/Git/IRemoteCollection.cs index 075429f919..e5aff4fef1 100644 --- a/src/GitVersion.Core/Git/IRemoteCollection.cs +++ b/src/GitVersion.Core/Git/IRemoteCollection.cs @@ -4,7 +4,7 @@ namespace GitVersion { public interface IRemoteCollection : IEnumerable { - IRemote this[string name] { get; } + IRemote? this[string name] { get; } void Remove(string remoteName); void Update(string remoteName, string refSpec); } diff --git a/src/GitVersion.Core/Git/ITag.cs b/src/GitVersion.Core/Git/ITag.cs index 3981088372..ab6d3f4bfb 100644 --- a/src/GitVersion.Core/Git/ITag.cs +++ b/src/GitVersion.Core/Git/ITag.cs @@ -5,6 +5,6 @@ namespace GitVersion public interface ITag : IEquatable, IComparable, INamedReference { string TargetSha { get; } - ICommit PeeledTargetCommit(); + ICommit? PeeledTargetCommit(); } } diff --git a/src/GitVersion.Core/Git/ReferenceName.cs b/src/GitVersion.Core/Git/ReferenceName.cs index 54532df11c..24e475b89a 100644 --- a/src/GitVersion.Core/Git/ReferenceName.cs +++ b/src/GitVersion.Core/Git/ReferenceName.cs @@ -5,7 +5,7 @@ namespace GitVersion { public class ReferenceName : IEquatable, IComparable { - private static readonly LambdaEqualityHelper equalityHelper = new(x => x.Canonical); + private static readonly LambdaEqualityHelper equalityHelper = new(x => x?.Canonical); private static readonly LambdaKeyComparer comparerHelper = new(x => x.Canonical); private const string LocalBranchPrefix = "refs/heads/"; @@ -52,7 +52,7 @@ public static ReferenceName Parse(string canonicalName) public override int GetHashCode() => equalityHelper.GetHashCode(this); public override string ToString() => Friendly; - public bool EquivalentTo(string name) + public bool EquivalentTo(string? name) { return Canonical.Equals(name, StringComparison.OrdinalIgnoreCase) || Friendly.Equals(name, StringComparison.OrdinalIgnoreCase) diff --git a/src/GitVersion.Core/GitVersion.Core.csproj b/src/GitVersion.Core/GitVersion.Core.csproj index c5279a78e8..8558d2c327 100644 --- a/src/GitVersion.Core/GitVersion.Core.csproj +++ b/src/GitVersion.Core/GitVersion.Core.csproj @@ -4,6 +4,7 @@ netstandard2.0 GitVersion bin\$(Configuration)\GitVersionCore.xml + enable GitVersion.Core GitVersion diff --git a/src/GitVersion.Core/GitVersionCoreModule.cs b/src/GitVersion.Core/GitVersionCoreModule.cs index 22c3140cca..4ecee1af4a 100644 --- a/src/GitVersion.Core/GitVersionCoreModule.cs +++ b/src/GitVersion.Core/GitVersionCoreModule.cs @@ -35,7 +35,7 @@ public void RegisterTypes(IServiceCollection services) { var options = sp.GetService>(); var contextFactory = sp.GetService(); - return new Lazy(() => contextFactory?.Create(options?.Value)); + return new Lazy(() => contextFactory?.Create(options?.Value)); }); services.AddModule(new BuildServerModule()); diff --git a/src/GitVersion.Core/Helpers/EncodingHelper.cs b/src/GitVersion.Core/Helpers/EncodingHelper.cs index cf2a1f8efd..fbf2b24c3c 100644 --- a/src/GitVersion.Core/Helpers/EncodingHelper.cs +++ b/src/GitVersion.Core/Helpers/EncodingHelper.cs @@ -7,7 +7,7 @@ namespace GitVersion.Helpers { public static class EncodingHelper { - private static IList encodingsWithPreambles; + private static IList? encodingsWithPreambles; private static int maxPreambleLength; @@ -16,7 +16,7 @@ public static class EncodingHelper /// /// The file name to check the encoding of. /// The encoding of the file if it has a preamble otherwise null. - public static Encoding DetectEncoding(string filename) + public static Encoding? DetectEncoding(string? filename) { if (!File.Exists(filename)) { @@ -48,7 +48,7 @@ public static Encoding DetectEncoding(string filename) /// /// The bytes to check for a matching preamble. /// The encoding that has a matching preamble or null if one was not found. - public static Encoding DetectEncoding(IList bytes) + public static Encoding? DetectEncoding(IList bytes) { if (bytes == null || bytes.Count == 0) { diff --git a/src/GitVersion.Core/Helpers/LambdaEqualityHelper.cs b/src/GitVersion.Core/Helpers/LambdaEqualityHelper.cs index 35a2e4cb43..546d61b40b 100644 --- a/src/GitVersion.Core/Helpers/LambdaEqualityHelper.cs +++ b/src/GitVersion.Core/Helpers/LambdaEqualityHelper.cs @@ -7,14 +7,14 @@ namespace GitVersion.Helpers // see https://github.com/libgit2/libgit2sharp/blob/7af5c60f22f9bd6064204f84467cfa62bedd1147/LibGit2Sharp/Core/LambdaEqualityHelper.cs public class LambdaEqualityHelper { - private readonly Func[] equalityContributorAccessors; + private readonly Func[] equalityContributorAccessors; - public LambdaEqualityHelper(params Func[] equalityContributorAccessors) + public LambdaEqualityHelper(params Func[] equalityContributorAccessors) { this.equalityContributorAccessors = equalityContributorAccessors; } - public bool Equals(T instance, T other) + public bool Equals(T? instance, T? other) { if (ReferenceEquals(null, instance) || ReferenceEquals(null, other)) { diff --git a/src/GitVersion.Core/Helpers/LambdaKeyComparer.cs b/src/GitVersion.Core/Helpers/LambdaKeyComparer.cs index b593b5908f..c88a219e8d 100644 --- a/src/GitVersion.Core/Helpers/LambdaKeyComparer.cs +++ b/src/GitVersion.Core/Helpers/LambdaKeyComparer.cs @@ -10,7 +10,7 @@ public class LambdaKeyComparer : Comparer where TSource public LambdaKeyComparer( Func keySelector, - IComparer innerComparer = null) + IComparer? innerComparer = null) { this.keySelector = keySelector; this.innerComparer = innerComparer ?? Comparer.Default; diff --git a/src/GitVersion.Core/Helpers/ProcessHelper.cs b/src/GitVersion.Core/Helpers/ProcessHelper.cs index 531c11344d..2220ac4e0e 100644 --- a/src/GitVersion.Core/Helpers/ProcessHelper.cs +++ b/src/GitVersion.Core/Helpers/ProcessHelper.cs @@ -5,6 +5,7 @@ using System.IO; using System.Runtime.InteropServices; using System.Threading; +using GitVersion.Extensions; namespace GitVersion.Helpers { @@ -13,7 +14,7 @@ public static class ProcessHelper private static readonly object LockObject = new object(); // http://social.msdn.microsoft.com/Forums/en/netfxbcl/thread/f6069441-4ab1-4299-ad6a-b8bb9ed36be3 - private static Process Start(ProcessStartInfo startInfo) + private static Process? Start(ProcessStartInfo startInfo) { Process process; @@ -79,9 +80,9 @@ private static Process Start(ProcessStartInfo startInfo) } // http://csharptest.net/532/using-processstart-to-capture-console-output/ - public static int Run(Action output, Action errorOutput, TextReader input, string exe, string args, string workingDirectory, params KeyValuePair[] environmentalVariables) + public static int Run(Action output, Action errorOutput, TextReader? input, string exe, string args, string workingDirectory, params KeyValuePair[] environmentalVariables) { - if (string.IsNullOrEmpty(exe)) + if (StringExtensions.IsNullOrEmpty(exe)) throw new ArgumentNullException(nameof(exe)); if (output == null) throw new ArgumentNullException(nameof(output)); @@ -118,6 +119,13 @@ public static int Run(Action output, Action errorOutput, TextRea } using var process = Start(psi); + + if (process is null) + { + // FIX ME: What error code do you want to return? + return -1; + } + using var mreOut = new ManualResetEvent(false); using var mreErr = new ManualResetEvent(false); process.EnableRaisingEvents = true; diff --git a/src/GitVersion.Core/Helpers/ServiceMessageEscapeHelper.cs b/src/GitVersion.Core/Helpers/ServiceMessageEscapeHelper.cs index 3c1ba06d3d..b889689f9f 100644 --- a/src/GitVersion.Core/Helpers/ServiceMessageEscapeHelper.cs +++ b/src/GitVersion.Core/Helpers/ServiceMessageEscapeHelper.cs @@ -2,7 +2,7 @@ namespace GitVersion.Helpers { public static class ServiceMessageEscapeHelper { - public static string EscapeValue(string value) + public static string? EscapeValue(string value) { if (value == null) { diff --git a/src/GitVersion.Core/Helpers/StringFormatWith.cs b/src/GitVersion.Core/Helpers/StringFormatWith.cs index 5c0c690e2f..d841d7e7dc 100644 --- a/src/GitVersion.Core/Helpers/StringFormatWith.cs +++ b/src/GitVersion.Core/Helpers/StringFormatWith.cs @@ -35,7 +35,7 @@ internal static class StringFormatWithExtension /// "{env:BUILD_NUMBER}".FormatWith(new { }, env); /// "{env:BUILD_NUMBER ?? \"0\"}".FormatWith(new { }, env); /// - public static string FormatWith(this string template, T source, IEnvironment environment) + public static string FormatWith(this string template, T? source, IEnvironment environment) { if (template == null) { @@ -45,7 +45,7 @@ public static string FormatWith(this string template, T source, IEnvironment foreach (Match match in TokensRegex.Matches(template)) { string propertyValue; - string fallback = match.Groups["fallback"].Success ? match.Groups["fallback"].Value : null; + string? fallback = match.Groups["fallback"].Success ? match.Groups["fallback"].Value : null; if (match.Groups["envvar"].Success) { @@ -55,7 +55,7 @@ public static string FormatWith(this string template, T source, IEnvironment } else { - var objType = source.GetType(); + var objType = source?.GetType(); string memberAccessExpression = match.Groups["member"].Value; var expression = CompileDataBinder(objType, memberAccessExpression); // It would be better to throw if the expression and fallback produce null, but provide an empty string for back compat. @@ -68,13 +68,13 @@ public static string FormatWith(this string template, T source, IEnvironment return template; } - private static Func CompileDataBinder(Type type, string expr) + private static Func CompileDataBinder(Type? type, string expr) { ParameterExpression param = Expression.Parameter(typeof(object)); Expression body = Expression.Convert(param, type); body = expr.Split('.').Aggregate(body, Expression.PropertyOrField); body = Expression.Convert(body, typeof(object)); // Convert result in case the body produces a Nullable value type. - return Expression.Lambda>(body, param).Compile(); + return Expression.Lambda>(body, param).Compile(); } } } diff --git a/src/GitVersion.Core/Logging/Abstractions/IConsole.cs b/src/GitVersion.Core/Logging/Abstractions/IConsole.cs index 01c0ebd981..14638c9456 100644 --- a/src/GitVersion.Core/Logging/Abstractions/IConsole.cs +++ b/src/GitVersion.Core/Logging/Abstractions/IConsole.cs @@ -4,7 +4,7 @@ namespace GitVersion.Logging { public interface IConsole { - void WriteLine(string msg); + void WriteLine(string? msg); void WriteLine(); void Write(string msg); string ReadLine(); diff --git a/src/GitVersion.Core/Logging/ConsoleAdapter.cs b/src/GitVersion.Core/Logging/ConsoleAdapter.cs index 6ab21d1584..ce450df9e4 100644 --- a/src/GitVersion.Core/Logging/ConsoleAdapter.cs +++ b/src/GitVersion.Core/Logging/ConsoleAdapter.cs @@ -4,7 +4,7 @@ namespace GitVersion.Logging { public class ConsoleAdapter : IConsole { - public void WriteLine(string msg) + public void WriteLine(string? msg) { Console.WriteLine(msg); } diff --git a/src/GitVersion.Core/Logging/Disposable.cs b/src/GitVersion.Core/Logging/Disposable.cs index 410c6ce53e..c251fc2ba7 100644 --- a/src/GitVersion.Core/Logging/Disposable.cs +++ b/src/GitVersion.Core/Logging/Disposable.cs @@ -26,7 +26,7 @@ public void Dispose() disposer = null; } - private Action disposer; + private Action? disposer; } } } diff --git a/src/GitVersion.Core/Logging/NullLog.cs b/src/GitVersion.Core/Logging/NullLog.cs index b2aa48365b..e0e28f03af 100644 --- a/src/GitVersion.Core/Logging/NullLog.cs +++ b/src/GitVersion.Core/Logging/NullLog.cs @@ -19,6 +19,6 @@ public void AddLogAppender(ILogAppender logAppender) { } - public string Indent { get; set; } + public string? Indent { get; set; } } } diff --git a/src/GitVersion.Core/Model/AuthenticationInfo.cs b/src/GitVersion.Core/Model/AuthenticationInfo.cs index 1303cd7556..44c912cfde 100644 --- a/src/GitVersion.Core/Model/AuthenticationInfo.cs +++ b/src/GitVersion.Core/Model/AuthenticationInfo.cs @@ -2,8 +2,8 @@ namespace GitVersion { public class AuthenticationInfo { - public string Username { get; set; } - public string Password { get; set; } - public string Token { get; set; } + public string? Username { get; set; } + public string? Password { get; set; } + public string? Token { get; set; } } } diff --git a/src/GitVersion.Core/Model/ConfigInfo.cs b/src/GitVersion.Core/Model/ConfigInfo.cs index 510636dd9f..14b09489f5 100644 --- a/src/GitVersion.Core/Model/ConfigInfo.cs +++ b/src/GitVersion.Core/Model/ConfigInfo.cs @@ -4,8 +4,8 @@ namespace GitVersion { public class ConfigInfo { - public string ConfigFile; - public Config OverrideConfig; + public string? ConfigFile; + public Config? OverrideConfig; public bool ShowConfig; } } diff --git a/src/GitVersion.Core/Model/Configuration/BranchConfig.cs b/src/GitVersion.Core/Model/Configuration/BranchConfig.cs index a14e72ac15..4f1a9e1ce5 100644 --- a/src/GitVersion.Core/Model/Configuration/BranchConfig.cs +++ b/src/GitVersion.Core/Model/Configuration/BranchConfig.cs @@ -41,7 +41,7 @@ public BranchConfig(BranchConfig branchConfiguration) /// Special value 'useBranchName' will extract the tag from the branch name /// [YamlMember(Alias = "tag")] - public string Tag { get; set; } + public string? Tag { get; set; } [YamlMember(Alias = "increment")] public IncrementStrategy? Increment { get; set; } @@ -50,7 +50,7 @@ public BranchConfig(BranchConfig branchConfiguration) public bool? PreventIncrementOfMergedBranchVersion { get; set; } [YamlMember(Alias = "tag-number-pattern")] - public string TagNumberPattern { get; set; } + public string? TagNumberPattern { get; set; } [YamlMember(Alias = "track-merge-target")] public bool? TrackMergeTarget { get; set; } @@ -59,13 +59,13 @@ public BranchConfig(BranchConfig branchConfiguration) public CommitMessageIncrementMode? CommitMessageIncrementing { get; set; } [YamlMember(Alias = "regex")] - public string Regex { get; set; } + public string? Regex { get; set; } [YamlMember(Alias = "source-branches")] - public HashSet SourceBranches { get; set; } + public HashSet? SourceBranches { get; set; } [YamlMember(Alias = "is-source-branch-for")] - public HashSet IsSourceBranchFor { get; set; } + public HashSet? IsSourceBranchFor { get; set; } [YamlMember(Alias = "tracks-release-branches")] public bool? TracksReleaseBranches { get; set; } @@ -83,7 +83,7 @@ public BranchConfig(BranchConfig branchConfiguration) /// The name given to this configuration in the config file. /// [YamlIgnore] - public string Name { get; set; } + public string? Name { get; set; } public void MergeTo([NotNull] BranchConfig targetConfig) { diff --git a/src/GitVersion.Core/Model/Configuration/Config.cs b/src/GitVersion.Core/Model/Configuration/Config.cs index 2165aa8bfa..5e8b9d6cdc 100644 --- a/src/GitVersion.Core/Model/Configuration/Config.cs +++ b/src/GitVersion.Core/Model/Configuration/Config.cs @@ -11,11 +11,11 @@ namespace GitVersion.Model.Configuration { public class Config { - private string nextVersion; + private string? nextVersion; public Config() { - Branches = new Dictionary(); + Branches = new Dictionary(); Ignore = new IgnoreConfig(); } @@ -26,25 +26,25 @@ public Config() public AssemblyFileVersioningScheme? AssemblyFileVersioningScheme { get; set; } [YamlMember(Alias = "assembly-informational-format")] - public string AssemblyInformationalFormat { get; set; } + public string? AssemblyInformationalFormat { get; set; } [YamlMember(Alias = "assembly-versioning-format")] - public string AssemblyVersioningFormat { get; set; } + public string? AssemblyVersioningFormat { get; set; } [YamlMember(Alias = "assembly-file-versioning-format")] - public string AssemblyFileVersioningFormat { get; set; } + public string? AssemblyFileVersioningFormat { get; set; } [YamlMember(Alias = "mode")] public VersioningMode? VersioningMode { get; set; } [YamlMember(Alias = "tag-prefix")] - public string TagPrefix { get; set; } + public string? TagPrefix { get; set; } [YamlMember(Alias = "continuous-delivery-fallback-tag")] - public string ContinuousDeploymentFallbackTag { get; set; } + public string? ContinuousDeploymentFallbackTag { get; set; } [YamlMember(Alias = "next-version")] - public string NextVersion + public string? NextVersion { get => nextVersion; set => @@ -54,16 +54,16 @@ public string NextVersion } [YamlMember(Alias = "major-version-bump-message")] - public string MajorVersionBumpMessage { get; set; } + public string? MajorVersionBumpMessage { get; set; } [YamlMember(Alias = "minor-version-bump-message")] - public string MinorVersionBumpMessage { get; set; } + public string? MinorVersionBumpMessage { get; set; } [YamlMember(Alias = "patch-version-bump-message")] - public string PatchVersionBumpMessage { get; set; } + public string? PatchVersionBumpMessage { get; set; } [YamlMember(Alias = "no-bump-message")] - public string NoBumpMessage { get; set; } + public string? NoBumpMessage { get; set; } [YamlMember(Alias = "legacy-semver-padding")] public int? LegacySemVerPadding { get; set; } @@ -81,7 +81,7 @@ public string NextVersion public CommitMessageIncrementMode? CommitMessageIncrementing { get; set; } [YamlMember(Alias = "branches")] - public Dictionary Branches { get; set; } + public Dictionary Branches { get; set; } [YamlMember(Alias = "ignore")] public IgnoreConfig Ignore { get; set; } @@ -90,7 +90,7 @@ public string NextVersion public IncrementStrategy? Increment { get; set; } [YamlMember(Alias = "commit-date-format")] - public string CommitDateFormat { get; set; } + public string? CommitDateFormat { get; set; } [YamlMember(Alias = "merge-message-formats")] public Dictionary MergeMessageFormats { get; set; } = new Dictionary(); diff --git a/src/GitVersion.Core/Model/Configuration/EffectiveConfiguration.cs b/src/GitVersion.Core/Model/Configuration/EffectiveConfiguration.cs index 9c50c050d9..1c4228ddc2 100644 --- a/src/GitVersion.Core/Model/Configuration/EffectiveConfiguration.cs +++ b/src/GitVersion.Core/Model/Configuration/EffectiveConfiguration.cs @@ -12,20 +12,20 @@ public class EffectiveConfiguration public EffectiveConfiguration( AssemblyVersioningScheme assemblyVersioningScheme, AssemblyFileVersioningScheme assemblyFileVersioningScheme, - string assemblyInformationalFormat, - string assemblyVersioningFormat, - string assemblyFileVersioningFormat, - VersioningMode versioningMode, string gitTagPrefix, - string tag, string nextVersion, IncrementStrategy increment, - string branchPrefixToTrim, + string? assemblyInformationalFormat, + string? assemblyVersioningFormat, + string? assemblyFileVersioningFormat, + VersioningMode versioningMode, string? gitTagPrefix, + string? tag, string? nextVersion, IncrementStrategy increment, + string? branchPrefixToTrim, bool preventIncrementForMergedBranchVersion, - string tagNumberPattern, - string continuousDeploymentFallbackTag, + string? tagNumberPattern, + string? continuousDeploymentFallbackTag, bool trackMergeTarget, - string majorVersionBumpMessage, - string minorVersionBumpMessage, - string patchVersionBumpMessage, - string noBumpMessage, + string? majorVersionBumpMessage, + string? minorVersionBumpMessage, + string? patchVersionBumpMessage, + string? noBumpMessage, CommitMessageIncrementMode commitMessageIncrementing, int legacySemVerPaddding, int buildMetaDataPadding, @@ -33,7 +33,7 @@ public EffectiveConfiguration( IEnumerable versionFilters, bool tracksReleaseBranches, bool isCurrentBranchRelease, - string commitDateFormat, + string? commitDateFormat, bool updateBuildNumber, int preReleaseWeight, int tagPreReleaseWeight) @@ -77,41 +77,41 @@ public EffectiveConfiguration( public AssemblyVersioningScheme AssemblyVersioningScheme { get; private set; } public AssemblyFileVersioningScheme AssemblyFileVersioningScheme { get; private set; } - public string AssemblyInformationalFormat { get; private set; } - public string AssemblyVersioningFormat { get; private set; } - public string AssemblyFileVersioningFormat { get; private set; } + public string? AssemblyInformationalFormat { get; private set; } + public string? AssemblyVersioningFormat { get; private set; } + public string? AssemblyFileVersioningFormat { get; private set; } /// /// Git tag prefix /// - public string GitTagPrefix { get; private set; } + public string? GitTagPrefix { get; private set; } /// /// Tag to use when calculating SemVer /// - public string Tag { get; private set; } + public string? Tag { get; private set; } - public string NextVersion { get; private set; } + public string? NextVersion { get; private set; } public IncrementStrategy Increment { get; private set; } - public string BranchPrefixToTrim { get; private set; } + public string? BranchPrefixToTrim { get; private set; } public bool PreventIncrementForMergedBranchVersion { get; private set; } - public string TagNumberPattern { get; private set; } + public string? TagNumberPattern { get; private set; } - public string ContinuousDeploymentFallbackTag { get; private set; } + public string? ContinuousDeploymentFallbackTag { get; private set; } public bool TrackMergeTarget { get; private set; } - public string MajorVersionBumpMessage { get; private set; } + public string? MajorVersionBumpMessage { get; private set; } - public string MinorVersionBumpMessage { get; private set; } + public string? MinorVersionBumpMessage { get; private set; } - public string PatchVersionBumpMessage { get; private set; } + public string? PatchVersionBumpMessage { get; private set; } - public string NoBumpMessage { get; private set; } + public string? NoBumpMessage { get; private set; } public int LegacySemVerPadding { get; private set; } public int BuildMetaDataPadding { get; private set; } @@ -121,7 +121,7 @@ public EffectiveConfiguration( public IEnumerable VersionFilters { get; private set; } - public string CommitDateFormat { get; private set; } + public string? CommitDateFormat { get; private set; } public bool UpdateBuildNumber { get; private set; } diff --git a/src/GitVersion.Core/Model/GitVersionCacheKey.cs b/src/GitVersion.Core/Model/GitVersionCacheKey.cs index 88461ad3ce..05ec2ad543 100644 --- a/src/GitVersion.Core/Model/GitVersionCacheKey.cs +++ b/src/GitVersion.Core/Model/GitVersionCacheKey.cs @@ -1,4 +1,5 @@ using System; +using GitVersion.Extensions; namespace GitVersion.Cache { @@ -6,7 +7,7 @@ public class GitVersionCacheKey { public GitVersionCacheKey(string value) { - if (string.IsNullOrEmpty(value)) + if (StringExtensions.IsNullOrEmpty(value)) { throw new ArgumentNullException(nameof(value)); } diff --git a/src/GitVersion.Core/Model/GitVersionContext.cs b/src/GitVersion.Core/Model/GitVersionContext.cs index 5e9ba4007b..06d9ea4b2c 100644 --- a/src/GitVersion.Core/Model/GitVersionContext.cs +++ b/src/GitVersion.Core/Model/GitVersionContext.cs @@ -10,12 +10,12 @@ public class GitVersionContext /// /// Contains the raw configuration, use Configuration for specific config based on the current GitVersion context. /// - public Config FullConfiguration { get; } + public Config? FullConfiguration { get; } - public SemanticVersion CurrentCommitTaggedVersion { get; } - public EffectiveConfiguration Configuration { get; } - public IBranch CurrentBranch { get; } - public ICommit CurrentCommit { get; } + public SemanticVersion? CurrentCommitTaggedVersion { get; } + public EffectiveConfiguration? Configuration { get; } + public IBranch? CurrentBranch { get; } + public ICommit? CurrentCommit { get; } public bool IsCurrentCommitTagged => CurrentCommitTaggedVersion != null; public int NumberOfUncommittedChanges { get; } @@ -24,7 +24,7 @@ public GitVersionContext() { } - public GitVersionContext(IBranch currentBranch, ICommit currentCommit, + public GitVersionContext(IBranch currentBranch, ICommit? currentCommit, Config configuration, EffectiveConfiguration effectiveConfiguration, SemanticVersion currentCommitTaggedVersion, int numberOfUncommittedChanges) { CurrentCommit = currentCommit; diff --git a/src/GitVersion.Core/Model/GitVersionOptions.cs b/src/GitVersion.Core/Model/GitVersionOptions.cs index 3ff685392b..1680938e58 100644 --- a/src/GitVersion.Core/Model/GitVersionOptions.cs +++ b/src/GitVersion.Core/Model/GitVersionOptions.cs @@ -6,7 +6,7 @@ namespace GitVersion { public class GitVersionOptions { - public string WorkingDirectory { get; set; } + public string? WorkingDirectory { get; set; } public AssemblyInfoData AssemblyInfo { get; } = new AssemblyInfoData(); public AuthenticationInfo Authentication { get; } = new AuthenticationInfo(); @@ -20,9 +20,9 @@ public class GitVersionOptions public bool IsVersion; public bool IsHelp; - public string LogFilePath; - public string ShowVariable; - public string OutputFile; + public string? LogFilePath; + public string? ShowVariable; + public string? OutputFile; public ISet Output = new HashSet(); public Verbosity Verbosity = Verbosity.Normal; } diff --git a/src/GitVersion.Core/Model/MergeMessage.cs b/src/GitVersion.Core/Model/MergeMessage.cs index d5ebdf787f..d50008346e 100644 --- a/src/GitVersion.Core/Model/MergeMessage.cs +++ b/src/GitVersion.Core/Model/MergeMessage.cs @@ -18,17 +18,20 @@ public class MergeMessage new MergeMessageFormat("RemoteTracking", @"^Merge remote-tracking branch '(?[^\s]*)'(?: into (?[^\s]*))*") }; - public MergeMessage(string mergeMessage, Config config) + public MergeMessage(string mergeMessage, Config? config) { if (mergeMessage == null) throw new NullReferenceException(); // Concat config formats with the defaults. // Ensure configs are processed first. - var allFormats = config.MergeMessageFormats + var allFormats = config?.MergeMessageFormats .Select(x => new MergeMessageFormat(x.Key, x.Value)) .Concat(DefaultFormats); + if (allFormats is null) + return; + foreach (var format in allFormats) { var match = format.Pattern.Match(mergeMessage); @@ -47,21 +50,21 @@ public MergeMessage(string mergeMessage, Config config) PullRequestNumber = pullNumber; } - Version = ParseVersion(config.TagPrefix); + Version = ParseVersion(config!.TagPrefix!); break; } } } - public string FormatName { get; } - public string TargetBranch { get; } + public string? FormatName { get; } + public string? TargetBranch { get; } public string MergedBranch { get; } = ""; public bool IsMergedPullRequest => PullRequestNumber != null; public int? PullRequestNumber { get; } - public SemanticVersion Version { get; } + public SemanticVersion? Version { get; } - private SemanticVersion ParseVersion(string tagPrefix) + private SemanticVersion? ParseVersion(string tagPrefix) { // Remove remotes and branch prefixes like release/ feature/ hotfix/ etc var toMatch = Regex.Replace(MergedBranch, @"^(\w+[-/])*", "", RegexOptions.IgnoreCase); diff --git a/src/GitVersion.Core/Model/RepositoryInfo.cs b/src/GitVersion.Core/Model/RepositoryInfo.cs index 42825c3b7e..03e3b46c25 100644 --- a/src/GitVersion.Core/Model/RepositoryInfo.cs +++ b/src/GitVersion.Core/Model/RepositoryInfo.cs @@ -2,9 +2,9 @@ namespace GitVersion { public class RepositoryInfo { - public string TargetUrl; - public string TargetBranch; - public string CommitId; - public string DynamicRepositoryClonePath; + public string? TargetUrl; + public string? TargetBranch; + public string? CommitId; + public string? DynamicRepositoryClonePath; } } diff --git a/src/GitVersion.Core/Model/VersionVariables.cs b/src/GitVersion.Core/Model/VersionVariables.cs index 1aedbbe465..37a8e8504f 100644 --- a/src/GitVersion.Core/Model/VersionVariables.cs +++ b/src/GitVersion.Core/Model/VersionVariables.cs @@ -17,36 +17,36 @@ public class VersionVariables : IEnumerable> public VersionVariables(string major, string minor, string patch, - string buildMetaData, - string buildMetaDataPadded, - string fullBuildMetaData, - string branchName, - string escapedBranchName, - string sha, - string shortSha, + string? buildMetaData, + string? buildMetaDataPadded, + string? fullBuildMetaData, + string? branchName, + string? escapedBranchName, + string? sha, + string? shortSha, string majorMinorPatch, string semVer, string legacySemVer, string legacySemVerPadded, string fullSemVer, - string assemblySemVer, - string assemblySemFileVer, - string preReleaseTag, - string preReleaseTagWithDash, - string preReleaseLabel, - string preReleaseLabelWithDash, - string preReleaseNumber, + string? assemblySemVer, + string? assemblySemFileVer, + string? preReleaseTag, + string? preReleaseTagWithDash, + string? preReleaseLabel, + string? preReleaseLabelWithDash, + string? preReleaseNumber, string weightedPreReleaseNumber, - string informationalVersion, - string commitDate, + string? informationalVersion, + string? commitDate, string nugetVersion, string nugetVersionV2, - string nugetPreReleaseTag, - string nugetPreReleaseTagV2, - string versionSourceSha, - string commitsSinceVersionSource, - string commitsSinceVersionSourcePadded, - string uncommittedChanges) + string? nugetPreReleaseTag, + string? nugetPreReleaseTagV2, + string? versionSourceSha, + string? commitsSinceVersionSource, + string? commitsSinceVersionSourcePadded, + string? uncommittedChanges) { Major = major; Minor = minor; @@ -86,36 +86,36 @@ public VersionVariables(string major, public string Major { get; } public string Minor { get; } public string Patch { get; } - public string PreReleaseTag { get; } - public string PreReleaseTagWithDash { get; } - public string PreReleaseLabel { get; } - public string PreReleaseLabelWithDash { get; } - public string PreReleaseNumber { get; } + public string? PreReleaseTag { get; } + public string? PreReleaseTagWithDash { get; } + public string? PreReleaseLabel { get; } + public string? PreReleaseLabelWithDash { get; } + public string? PreReleaseNumber { get; } public string WeightedPreReleaseNumber { get; } - public string BuildMetaData { get; } - public string BuildMetaDataPadded { get; } - public string FullBuildMetaData { get; } + public string? BuildMetaData { get; } + public string? BuildMetaDataPadded { get; } + public string? FullBuildMetaData { get; } public string MajorMinorPatch { get; } public string SemVer { get; } public string LegacySemVer { get; } public string LegacySemVerPadded { get; } - public string AssemblySemVer { get; } - public string AssemblySemFileVer { get; } + public string? AssemblySemVer { get; } + public string? AssemblySemFileVer { get; } public string FullSemVer { get; } - public string InformationalVersion { get; } - public string BranchName { get; } - public string EscapedBranchName { get; } - public string Sha { get; } - public string ShortSha { get; } + public string? InformationalVersion { get; } + public string? BranchName { get; } + public string? EscapedBranchName { get; } + public string? Sha { get; } + public string? ShortSha { get; } public string NuGetVersionV2 { get; } public string NuGetVersion { get; } - public string NuGetPreReleaseTagV2 { get; } - public string NuGetPreReleaseTag { get; } - public string VersionSourceSha { get; } - public string CommitsSinceVersionSource { get; } - public string CommitsSinceVersionSourcePadded { get; } - public string UncommittedChanges { get; } - public string CommitDate { get; set; } + public string? NuGetPreReleaseTagV2 { get; } + public string? NuGetPreReleaseTag { get; } + public string? VersionSourceSha { get; } + public string? CommitsSinceVersionSource { get; } + public string? CommitsSinceVersionSourcePadded { get; } + public string? UncommittedChanges { get; } + public string? CommitDate { get; set; } [ReflectionIgnore] public static IEnumerable AvailableVariables @@ -131,10 +131,10 @@ public static IEnumerable AvailableVariables } [ReflectionIgnore] - public string FileName { get; set; } + public string? FileName { get; set; } [ReflectionIgnore] - public string this[string variable] => typeof(VersionVariables).GetProperty(variable)?.GetValue(this, null) as string; + public string? this[string variable] => typeof(VersionVariables).GetProperty(variable)?.GetValue(this, null) as string; public IEnumerator> GetEnumerator() { @@ -146,7 +146,8 @@ IEnumerator IEnumerable.GetEnumerator() return GetEnumerator(); } - public static VersionVariables FromDictionary(IEnumerable> properties) + // FIX ME: Shall we return an instance with no ctorArgs or explicitly fail when properties is null? + public static VersionVariables FromDictionary(IEnumerable>? properties) { var type = typeof(VersionVariables); var constructors = type.GetConstructors(); @@ -197,7 +198,7 @@ private static VersionVariables FromFileInternal(string filePath, IFileSystem fi return versionVariables; } - public bool TryGetValue(string variable, out string variableValue) + public bool TryGetValue(string variable, out string? variableValue) { if (ContainsKey(variable)) { diff --git a/src/GitVersion.Core/Model/VersionVariablesJsonModel.cs b/src/GitVersion.Core/Model/VersionVariablesJsonModel.cs index 22eb1e72d5..2900359981 100644 --- a/src/GitVersion.Core/Model/VersionVariablesJsonModel.cs +++ b/src/GitVersion.Core/Model/VersionVariablesJsonModel.cs @@ -5,70 +5,70 @@ namespace GitVersion.OutputVariables public class VersionVariablesJsonModel { [JsonConverter(typeof(VersionVariablesJsonNumberConverter))] - public string Major { get; set; } + public string? Major { get; set; } [JsonConverter(typeof(VersionVariablesJsonNumberConverter))] - public string Minor { get; set; } + public string? Minor { get; set; } [JsonConverter(typeof(VersionVariablesJsonNumberConverter))] - public string Patch { get; set; } + public string? Patch { get; set; } [JsonConverter(typeof(VersionVariablesJsonStringConverter))] - public string PreReleaseTag { get; set; } + public string? PreReleaseTag { get; set; } [JsonConverter(typeof(VersionVariablesJsonStringConverter))] - public string PreReleaseTagWithDash { get; set; } + public string? PreReleaseTagWithDash { get; set; } [JsonConverter(typeof(VersionVariablesJsonStringConverter))] - public string PreReleaseLabel { get; set; } + public string? PreReleaseLabel { get; set; } [JsonConverter(typeof(VersionVariablesJsonStringConverter))] - public string PreReleaseLabelWithDash { get; set; } + public string? PreReleaseLabelWithDash { get; set; } [JsonConverter(typeof(VersionVariablesJsonNumberConverter))] - public string PreReleaseNumber { get; set; } + public string? PreReleaseNumber { get; set; } [JsonConverter(typeof(VersionVariablesJsonNumberConverter))] - public string WeightedPreReleaseNumber { get; set; } + public string? WeightedPreReleaseNumber { get; set; } [JsonConverter(typeof(VersionVariablesJsonNumberConverter))] - public string BuildMetaData { get; set; } + public string? BuildMetaData { get; set; } [JsonConverter(typeof(VersionVariablesJsonStringConverter))] - public string BuildMetaDataPadded { get; set; } + public string? BuildMetaDataPadded { get; set; } [JsonConverter(typeof(VersionVariablesJsonStringConverter))] - public string FullBuildMetaData { get; set; } + public string? FullBuildMetaData { get; set; } [JsonConverter(typeof(VersionVariablesJsonStringConverter))] - public string MajorMinorPatch { get; set; } + public string? MajorMinorPatch { get; set; } [JsonConverter(typeof(VersionVariablesJsonStringConverter))] - public string SemVer { get; set; } + public string? SemVer { get; set; } [JsonConverter(typeof(VersionVariablesJsonStringConverter))] - public string LegacySemVer { get; set; } + public string? LegacySemVer { get; set; } [JsonConverter(typeof(VersionVariablesJsonStringConverter))] - public string LegacySemVerPadded { get; set; } + public string? LegacySemVerPadded { get; set; } [JsonConverter(typeof(VersionVariablesJsonStringConverter))] - public string AssemblySemVer { get; set; } + public string? AssemblySemVer { get; set; } [JsonConverter(typeof(VersionVariablesJsonStringConverter))] - public string AssemblySemFileVer { get; set; } + public string? AssemblySemFileVer { get; set; } [JsonConverter(typeof(VersionVariablesJsonStringConverter))] - public string FullSemVer { get; set; } + public string? FullSemVer { get; set; } [JsonConverter(typeof(VersionVariablesJsonStringConverter))] - public string InformationalVersion { get; set; } + public string? InformationalVersion { get; set; } [JsonConverter(typeof(VersionVariablesJsonStringConverter))] - public string BranchName { get; set; } + public string? BranchName { get; set; } [JsonConverter(typeof(VersionVariablesJsonStringConverter))] - public string EscapedBranchName { get; set; } + public string? EscapedBranchName { get; set; } [JsonConverter(typeof(VersionVariablesJsonStringConverter))] - public string Sha { get; set; } + public string? Sha { get; set; } [JsonConverter(typeof(VersionVariablesJsonStringConverter))] - public string ShortSha { get; set; } + public string? ShortSha { get; set; } [JsonConverter(typeof(VersionVariablesJsonStringConverter))] - public string NuGetVersionV2 { get; set; } + public string? NuGetVersionV2 { get; set; } [JsonConverter(typeof(VersionVariablesJsonStringConverter))] - public string NuGetVersion { get; set; } + public string? NuGetVersion { get; set; } [JsonConverter(typeof(VersionVariablesJsonStringConverter))] - public string NuGetPreReleaseTagV2 { get; set; } + public string? NuGetPreReleaseTagV2 { get; set; } [JsonConverter(typeof(VersionVariablesJsonStringConverter))] - public string NuGetPreReleaseTag { get; set; } + public string? NuGetPreReleaseTag { get; set; } [JsonConverter(typeof(VersionVariablesJsonStringConverter))] - public string VersionSourceSha { get; set; } + public string? VersionSourceSha { get; set; } [JsonConverter(typeof(VersionVariablesJsonNumberConverter))] - public string CommitsSinceVersionSource { get; set; } + public string? CommitsSinceVersionSource { get; set; } [JsonConverter(typeof(VersionVariablesJsonStringConverter))] - public string CommitsSinceVersionSourcePadded { get; set; } + public string? CommitsSinceVersionSourcePadded { get; set; } [JsonConverter(typeof(VersionVariablesJsonNumberConverter))] - public string UncommittedChanges { get; set; } + public string? UncommittedChanges { get; set; } [JsonConverter(typeof(VersionVariablesJsonStringConverter))] - public string CommitDate { get; set; } + public string? CommitDate { get; set; } } } diff --git a/src/GitVersion.Core/Model/VersionVariablesJsonNumberConverter.cs b/src/GitVersion.Core/Model/VersionVariablesJsonNumberConverter.cs index 92e4f88bf1..c293a62bb8 100644 --- a/src/GitVersion.Core/Model/VersionVariablesJsonNumberConverter.cs +++ b/src/GitVersion.Core/Model/VersionVariablesJsonNumberConverter.cs @@ -3,6 +3,7 @@ using System.Buffers.Text; using System.Text.Json; using System.Text.Json.Serialization; +using GitVersion.Extensions; using JetBrains.Annotations; namespace GitVersion.OutputVariables @@ -31,7 +32,7 @@ public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonS public override void Write(Utf8JsonWriter writer, [CanBeNull] string value, JsonSerializerOptions options) { - if (string.IsNullOrWhiteSpace(value)) + if (StringExtensions.IsNullOrWhiteSpace(value)) { writer.WriteNullValue(); } diff --git a/src/GitVersion.Core/VersionCalculation/Abstractions/IMainlineVersionCalculator.cs b/src/GitVersion.Core/VersionCalculation/Abstractions/IMainlineVersionCalculator.cs index bbbee8eb30..ec2486f2ac 100644 --- a/src/GitVersion.Core/VersionCalculation/Abstractions/IMainlineVersionCalculator.cs +++ b/src/GitVersion.Core/VersionCalculation/Abstractions/IMainlineVersionCalculator.cs @@ -3,6 +3,6 @@ namespace GitVersion.VersionCalculation public interface IMainlineVersionCalculator { SemanticVersion FindMainlineModeVersion(BaseVersion baseVersion); - SemanticVersionBuildMetaData CreateVersionBuildMetaData(ICommit baseVersionSource); + SemanticVersionBuildMetaData CreateVersionBuildMetaData(ICommit? baseVersionSource); } } diff --git a/src/GitVersion.Core/VersionCalculation/Abstractions/IVersionFilter.cs b/src/GitVersion.Core/VersionCalculation/Abstractions/IVersionFilter.cs index 3e58de0856..608d987d89 100644 --- a/src/GitVersion.Core/VersionCalculation/Abstractions/IVersionFilter.cs +++ b/src/GitVersion.Core/VersionCalculation/Abstractions/IVersionFilter.cs @@ -1,7 +1,9 @@ +using System.Diagnostics.CodeAnalysis; + namespace GitVersion.VersionCalculation { public interface IVersionFilter { - bool Exclude(BaseVersion version, out string reason); + bool Exclude(BaseVersion version, [NotNullWhen(true)] out string? reason); } } diff --git a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculator.cs b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculator.cs index a6359662c2..a7e9279d1d 100644 --- a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculator.cs +++ b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculator.cs @@ -44,40 +44,43 @@ public BaseVersion GetBaseVersion() FixTheBaseVersionSourceOfMergeMessageStrategyIfReleaseBranchWasMergedAndDeleted(versions); - if (context.Configuration.VersioningMode == VersioningMode.Mainline) + if (context.Configuration?.VersioningMode == VersioningMode.Mainline) { versions = versions - .Where(b => !b.IncrementedVersion.PreReleaseTag.HasTag()) + .Where(b => b.IncrementedVersion?.PreReleaseTag?.HasTag() != true) .ToList(); } var maxVersion = versions.Aggregate((v1, v2) => v1.IncrementedVersion > v2.IncrementedVersion ? v1 : v2); var matchingVersionsOnceIncremented = versions - .Where(b => b.Version.BaseVersionSource != null && b.IncrementedVersion == maxVersion.IncrementedVersion) + .Where(b => b.Version?.BaseVersionSource != null && b.IncrementedVersion == maxVersion.IncrementedVersion) .ToList(); BaseVersion baseVersionWithOldestSource; if (matchingVersionsOnceIncremented.Any()) { - var oldest = matchingVersionsOnceIncremented.Aggregate((v1, v2) => v1.Version.BaseVersionSource.When < v2.Version.BaseVersionSource.When ? v1 : v2); - baseVersionWithOldestSource = oldest.Version; + var oldest = matchingVersionsOnceIncremented.Aggregate((v1, v2) => + { + return v1.Version!.BaseVersionSource!.When < v2.Version!.BaseVersionSource!.When ? v1 : v2; + }); + baseVersionWithOldestSource = oldest!.Version!; maxVersion = oldest; - log.Info($"Found multiple base versions which will produce the same SemVer ({maxVersion.IncrementedVersion}), taking oldest source for commit counting ({baseVersionWithOldestSource.Source})"); + log.Info($"Found multiple base versions which will produce the same SemVer ({maxVersion.IncrementedVersion}), taking oldest source for commit counting ({baseVersionWithOldestSource!.Source})"); } else { baseVersionWithOldestSource = versions - .Where(v => v.Version.BaseVersionSource != null) + .Where(v => v.Version?.BaseVersionSource != null) .OrderByDescending(v => v.IncrementedVersion) - .ThenByDescending(v => v.Version.BaseVersionSource.When) + .ThenByDescending(v => v.Version!.BaseVersionSource!.When) .First() - .Version; + .Version!; } if (baseVersionWithOldestSource.BaseVersionSource == null) throw new Exception("Base version should not be null"); var calculatedBase = new BaseVersion( - maxVersion.Version.Source, maxVersion.Version.ShouldIncrement, maxVersion.Version.SemanticVersion, + maxVersion.Version!.Source, maxVersion.Version.ShouldIncrement, maxVersion.Version.SemanticVersion, baseVersionWithOldestSource.BaseVersionSource, maxVersion.Version.BranchNameOverride); log.Info($"Base version used: {calculatedBase}"); @@ -100,6 +103,9 @@ private IEnumerable GetBaseVersions(IVersionStrategy strategy) } private bool IncludeVersion(BaseVersion version) { + if (context.Configuration == null) + return false; + foreach (var filter in context.Configuration.VersionFilters) { if (filter.Exclude(version, out var reason)) @@ -116,11 +122,11 @@ private void FixTheBaseVersionSourceOfMergeMessageStrategyIfReleaseBranchWasMerg if (ReleaseBranchExistsInRepo()) return; foreach (var baseVersion in baseVersions) { - if (baseVersion.Version.Source.Contains(MergeMessageVersionStrategy.MergeMessageStrategyPrefix) + if (baseVersion.Version?.Source.Contains(MergeMessageVersionStrategy.MergeMessageStrategyPrefix) == true && baseVersion.Version.Source.Contains("Merge branch") && baseVersion.Version.Source.Contains("release")) { - var parents = baseVersion.Version.BaseVersionSource.Parents.ToList(); + var parents = baseVersion.Version.BaseVersionSource!.Parents.ToList(); baseVersion.Version = new BaseVersion( baseVersion.Version.Source, baseVersion.Version.ShouldIncrement, @@ -133,15 +139,15 @@ private void FixTheBaseVersionSourceOfMergeMessageStrategyIfReleaseBranchWasMerg private bool ReleaseBranchExistsInRepo() { - var releaseBranchConfig = context.FullConfiguration.GetReleaseBranchConfig(); + var releaseBranchConfig = context.FullConfiguration?.GetReleaseBranchConfig(); var releaseBranches = repositoryStore.GetReleaseBranches(releaseBranchConfig); return releaseBranches.Any(); } private class Versions { - public SemanticVersion IncrementedVersion { get; set; } - public BaseVersion Version { get; set; } + public SemanticVersion? IncrementedVersion { get; set; } + public BaseVersion? Version { get; set; } public override string ToString() { diff --git a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/BaseVersion.cs b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/BaseVersion.cs index 23c02b1d75..651a8b2457 100644 --- a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/BaseVersion.cs +++ b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/BaseVersion.cs @@ -2,7 +2,7 @@ namespace GitVersion.VersionCalculation { public class BaseVersion { - public BaseVersion(string source, bool shouldIncrement, SemanticVersion semanticVersion, ICommit baseVersionSource, string branchNameOverride) + public BaseVersion(string source, bool shouldIncrement, SemanticVersion semanticVersion, ICommit? baseVersionSource, string? branchNameOverride) { Source = source; ShouldIncrement = shouldIncrement; @@ -17,9 +17,9 @@ public BaseVersion(string source, bool shouldIncrement, SemanticVersion semantic public SemanticVersion SemanticVersion { get; } - public ICommit BaseVersionSource { get; } + public ICommit? BaseVersionSource { get; } - public string BranchNameOverride { get; } + public string? BranchNameOverride { get; } public override string ToString() { diff --git a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/ConfigNextVersionVersionStrategy.cs b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/ConfigNextVersionVersionStrategy.cs index 49b95c8980..d2e852b962 100644 --- a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/ConfigNextVersionVersionStrategy.cs +++ b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/ConfigNextVersionVersionStrategy.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using GitVersion.Extensions; namespace GitVersion.VersionCalculation { @@ -16,9 +17,9 @@ public ConfigNextVersionVersionStrategy(Lazy versionContext) public override IEnumerable GetVersions() { - if (string.IsNullOrEmpty(Context.Configuration.NextVersion) || Context.IsCurrentCommitTagged) + if (StringExtensions.IsNullOrEmpty(Context.Configuration?.NextVersion) || Context.IsCurrentCommitTagged) yield break; - var semanticVersion = SemanticVersion.Parse(Context.Configuration.NextVersion, Context.Configuration.GitTagPrefix); + var semanticVersion = SemanticVersion.Parse(Context.Configuration.NextVersion, Context.Configuration?.GitTagPrefix); yield return new BaseVersion("NextVersion in GitVersion configuration file", false, semanticVersion, null, null); } } diff --git a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/FallbackVersionStrategy.cs b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/FallbackVersionStrategy.cs index c17a0808fe..21a1932b8c 100644 --- a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/FallbackVersionStrategy.cs +++ b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/FallbackVersionStrategy.cs @@ -19,7 +19,7 @@ public FallbackVersionStrategy(IRepositoryStore repositoryStore, Lazy GetVersions() { - var currentBranchTip = Context.CurrentBranch.Tip; + var currentBranchTip = Context.CurrentBranch?.Tip; if (currentBranchTip == null) { throw new GitVersionException("No commits found on the current branch."); diff --git a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/MergeMessageVersionStrategy.cs b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/MergeMessageVersionStrategy.cs index ea07d17f4e..88c324c1fc 100644 --- a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/MergeMessageVersionStrategy.cs +++ b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/MergeMessageVersionStrategy.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text.RegularExpressions; using GitVersion.Configuration; @@ -24,16 +25,17 @@ public MergeMessageVersionStrategy(ILog log, Lazy versionCont public override IEnumerable GetVersions() { - var commitsPriorToThan = Context.CurrentBranch.Commits.GetCommitsPriorTo(Context.CurrentCommit.When); + // FIX ME: What to do when CurrentCommit is null? + var commitsPriorToThan = Context.CurrentBranch!.Commits!.GetCommitsPriorTo(Context.CurrentCommit!.When); var baseVersions = commitsPriorToThan .SelectMany(c => { if (TryParse(c, Context, out var mergeMessage) && mergeMessage.Version != null && - Context.FullConfiguration.IsReleaseBranch(TrimRemote(mergeMessage.MergedBranch))) + Context.FullConfiguration?.IsReleaseBranch(TrimRemote(mergeMessage.MergedBranch)) == true) { log.Info($"Found commit [{Context.CurrentCommit}] matching merge message format: {mergeMessage.FormatName}"); - var shouldIncrement = !Context.Configuration.PreventIncrementForMergedBranchVersion; + var shouldIncrement = Context.Configuration?.PreventIncrementForMergedBranchVersion != true; return new[] { new BaseVersion($"{MergeMessageStrategyPrefix} '{c.Message.Trim()}'", shouldIncrement, mergeMessage.Version, c, null) @@ -48,13 +50,13 @@ public override IEnumerable GetVersions() public static readonly string MergeMessageStrategyPrefix = "Merge message"; - private static bool TryParse(ICommit mergeCommit, GitVersionContext context, out MergeMessage mergeMessage) + private static bool TryParse(ICommit mergeCommit, GitVersionContext context, [NotNullWhen(true)] out MergeMessage? mergeMessage) { mergeMessage = Inner(mergeCommit, context); return mergeMessage != null; } - private static MergeMessage Inner(ICommit mergeCommit, GitVersionContext context) + private static MergeMessage? Inner(ICommit mergeCommit, GitVersionContext context) { if (mergeCommit.Parents.Count() < 2) { diff --git a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/TaggedCommitVersionStrategy.cs b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/TaggedCommitVersionStrategy.cs index a21655d09b..3bd70af264 100644 --- a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/TaggedCommitVersionStrategy.cs +++ b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/TaggedCommitVersionStrategy.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using GitVersion.Common; +using GitVersion.Extensions; namespace GitVersion.VersionCalculation { @@ -21,25 +22,25 @@ public TaggedCommitVersionStrategy(IRepositoryStore repositoryStore, Lazy GetVersions() { - return GetTaggedVersions(Context.CurrentBranch, Context.CurrentCommit.When); + return GetTaggedVersions(Context.CurrentBranch, Context.CurrentCommit?.When); } - internal IEnumerable GetTaggedVersions(IBranch currentBranch, DateTimeOffset? olderThan) + internal IEnumerable GetTaggedVersions(IBranch? currentBranch, DateTimeOffset? olderThan) { - var allTags = repositoryStore.GetValidVersionTags(Context.Configuration.GitTagPrefix, olderThan); + var allTags = repositoryStore.GetValidVersionTags(Context.Configuration?.GitTagPrefix, olderThan); var taggedCommits = currentBranch - .Commits + ?.Commits .SelectMany(commit => allTags.Where(t => IsValidTag(t.Item1, commit))).ToList(); var taggedVersions = taggedCommits .Select(t => { - var commit = t.Item1.PeeledTargetCommit(); - return commit != null ? new VersionTaggedCommit(commit, t.Item2, t.Item1.Name.Friendly) : null; + var commit = t.Item1?.PeeledTargetCommit(); + return commit != null ? new VersionTaggedCommit(commit, t.Item2!, t.Item1!.Name.Friendly) : null; }) .Where(versionTaggedCommit => versionTaggedCommit != null) - .Select(versionTaggedCommit => CreateBaseVersion(Context, versionTaggedCommit)) + .Select(versionTaggedCommit => CreateBaseVersion(Context, versionTaggedCommit!)) .ToList(); var taggedVersionsOnCurrentCommit = taggedVersions.Where(version => !version.ShouldIncrement).ToList(); @@ -48,7 +49,7 @@ internal IEnumerable GetTaggedVersions(IBranch currentBranch, DateT private BaseVersion CreateBaseVersion(GitVersionContext context, VersionTaggedCommit version) { - var shouldUpdateVersion = version.Commit.Sha != context.CurrentCommit.Sha; + var shouldUpdateVersion = version.Commit.Sha != context.CurrentCommit?.Sha; var baseVersion = new BaseVersion(FormatSource(version), shouldUpdateVersion, version.SemVer, version.Commit, null); return baseVersion; } @@ -58,9 +59,9 @@ protected virtual string FormatSource(VersionTaggedCommit version) return $"Git tag '{version.Tag}'"; } - protected virtual bool IsValidTag(ITag tag, ICommit commit) + protected virtual bool IsValidTag(ITag? tag, ICommit commit) { - var targetCommit = tag.PeeledTargetCommit(); + var targetCommit = tag?.PeeledTargetCommit(); return targetCommit != null && Equals(targetCommit, commit); } diff --git a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/TrackReleaseBranchesVersionStrategy.cs b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/TrackReleaseBranchesVersionStrategy.cs index 227e543eb1..a28ef74ed3 100644 --- a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/TrackReleaseBranchesVersionStrategy.cs +++ b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/TrackReleaseBranchesVersionStrategy.cs @@ -40,7 +40,7 @@ public TrackReleaseBranchesVersionStrategy(IRepositoryStore repositoryStore, Laz public override IEnumerable GetVersions() { - if (Context.Configuration.TracksReleaseBranches) + if (Context.Configuration?.TracksReleaseBranches == true) { return ReleaseBranchBaseVersions().Union(MainTagsVersions()); } @@ -58,7 +58,7 @@ private IEnumerable MainTagsVersions() private IEnumerable ReleaseBranchBaseVersions() { - var releaseBranchConfig = Context.FullConfiguration.GetReleaseBranchConfig(); + var releaseBranchConfig = Context.FullConfiguration?.GetReleaseBranchConfig(); if (releaseBranchConfig.Any()) { var releaseBranches = repositoryStore.GetReleaseBranches(releaseBranchConfig); @@ -83,7 +83,7 @@ private IEnumerable ReleaseBranchBaseVersions() private IEnumerable GetReleaseVersion(GitVersionContext context, IBranch releaseBranch) { - var tagPrefixRegex = context.Configuration.GitTagPrefix; + var tagPrefixRegex = context.Configuration?.GitTagPrefix; // Find the commit where the child branch was created. var baseSource = repositoryStore.FindMergeBase(releaseBranch, context.CurrentBranch); diff --git a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/VersionInBranchNameVersionStrategy.cs b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/VersionInBranchNameVersionStrategy.cs index dacc623e76..df82657312 100644 --- a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/VersionInBranchNameVersionStrategy.cs +++ b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/VersionInBranchNameVersionStrategy.cs @@ -23,13 +23,14 @@ public VersionInBranchNameVersionStrategy(IRepositoryStore repositoryStore, Lazy public override IEnumerable GetVersions() { var currentBranch = Context.CurrentBranch; - var tagPrefixRegex = Context.Configuration.GitTagPrefix; + var tagPrefixRegex = Context.Configuration?.GitTagPrefix; return GetVersions(tagPrefixRegex, currentBranch); } - internal IEnumerable GetVersions(string tagPrefixRegex, IBranch currentBranch) + internal IEnumerable GetVersions(string? tagPrefixRegex, IBranch? currentBranch) { - if (!Context.FullConfiguration.IsReleaseBranch(NameWithoutOrigin(currentBranch))) + if (currentBranch == null || + Context.FullConfiguration?.IsReleaseBranch(NameWithoutOrigin(currentBranch)) != true) { yield break; } @@ -44,7 +45,7 @@ internal IEnumerable GetVersions(string tagPrefixRegex, IBranch cur } } - private static Tuple GetVersionInBranch(string branchName, string tagPrefixRegex) + private static Tuple? GetVersionInBranch(string branchName, string? tagPrefixRegex) { var branchParts = branchName.Split('/', '-'); foreach (var part in branchParts) diff --git a/src/GitVersion.Core/VersionCalculation/Cache/GitVersionCache.cs b/src/GitVersion.Core/VersionCalculation/Cache/GitVersionCache.cs index 7d4643c9b0..e339e50180 100644 --- a/src/GitVersion.Core/VersionCalculation/Cache/GitVersionCache.cs +++ b/src/GitVersion.Core/VersionCalculation/Cache/GitVersionCache.cs @@ -57,7 +57,7 @@ public string GetCacheDirectory() return Path.Combine(gitDir, "gitversion_cache"); } - public VersionVariables LoadVersionVariablesFromDiskCache(GitVersionCacheKey key) + public VersionVariables? LoadVersionVariablesFromDiskCache(GitVersionCacheKey key) { using (log.IndentLog("Loading version variables from disk cache")) { diff --git a/src/GitVersion.Core/VersionCalculation/Cache/GitVersionCacheKeyFactory.cs b/src/GitVersion.Core/VersionCalculation/Cache/GitVersionCacheKeyFactory.cs index 6ae5f527b5..463f9df073 100644 --- a/src/GitVersion.Core/VersionCalculation/Cache/GitVersionCacheKeyFactory.cs +++ b/src/GitVersion.Core/VersionCalculation/Cache/GitVersionCacheKeyFactory.cs @@ -6,6 +6,7 @@ using System.Text; using GitVersion.Cache; using GitVersion.Configuration; +using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.Model.Configuration; using Microsoft.Extensions.Options; @@ -33,7 +34,7 @@ public GitVersionCacheKeyFactory(IFileSystem fileSystem, ILog log, this.repositoryInfo = repositoryInfo ?? throw new ArgumentNullException(nameof(repositoryInfo)); } - public GitVersionCacheKey Create(Config overrideConfig) + public GitVersionCacheKey Create(Config? overrideConfig) { var gitSystemHash = GetGitSystemHash(); var configFileHash = GetConfigFileHash(); @@ -155,7 +156,7 @@ private string GetRepositorySnapshotHash() return GetHash(hash); } - private static string GetOverrideConfigHash(Config overrideConfig) + private static string GetOverrideConfigHash(Config? overrideConfig) { if (overrideConfig == null) { @@ -197,7 +198,7 @@ private static string GetHash(params string[] textsToHash) private static string GetHash(string textToHash) { - if (string.IsNullOrEmpty(textToHash)) + if (StringExtensions.IsNullOrEmpty(textToHash)) { return string.Empty; } diff --git a/src/GitVersion.Core/VersionCalculation/Cache/IGitVersionCache.cs b/src/GitVersion.Core/VersionCalculation/Cache/IGitVersionCache.cs index 00e49577f4..8905dc412b 100644 --- a/src/GitVersion.Core/VersionCalculation/Cache/IGitVersionCache.cs +++ b/src/GitVersion.Core/VersionCalculation/Cache/IGitVersionCache.cs @@ -7,6 +7,6 @@ public interface IGitVersionCache { void WriteVariablesToDiskCache(GitVersionCacheKey cacheKey, VersionVariables variablesFromCache); string GetCacheDirectory(); - VersionVariables LoadVersionVariablesFromDiskCache(GitVersionCacheKey key); + VersionVariables? LoadVersionVariablesFromDiskCache(GitVersionCacheKey key); } } diff --git a/src/GitVersion.Core/VersionCalculation/Cache/IGitVersionCacheKeyFactory.cs b/src/GitVersion.Core/VersionCalculation/Cache/IGitVersionCacheKeyFactory.cs index d8eede9c39..bfaffef02a 100644 --- a/src/GitVersion.Core/VersionCalculation/Cache/IGitVersionCacheKeyFactory.cs +++ b/src/GitVersion.Core/VersionCalculation/Cache/IGitVersionCacheKeyFactory.cs @@ -5,6 +5,6 @@ namespace GitVersion.VersionCalculation.Cache { public interface IGitVersionCacheKeyFactory { - GitVersionCacheKey Create(Config overrideConfig); + GitVersionCacheKey Create(Config? overrideConfig); } } diff --git a/src/GitVersion.Core/VersionCalculation/IncrementStrategyFinder.cs b/src/GitVersion.Core/VersionCalculation/IncrementStrategyFinder.cs index b6077924b6..4165f21950 100644 --- a/src/GitVersion.Core/VersionCalculation/IncrementStrategyFinder.cs +++ b/src/GitVersion.Core/VersionCalculation/IncrementStrategyFinder.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; +using GitVersion.Extensions; using GitVersion.VersionCalculation; namespace GitVersion @@ -15,7 +16,7 @@ public enum CommitMessageIncrementMode public static class IncrementStrategyFinder { - private static IEnumerable intermediateCommitCache; + private static IEnumerable? intermediateCommitCache; public const string DefaultMajorPattern = @"\+semver:\s?(breaking|major)"; public const string DefaultMinorPattern = @"\+semver:\s?(feature|minor)"; public const string DefaultPatchPattern = @"\+semver:\s?(fix|patch)"; @@ -31,7 +32,7 @@ public static class IncrementStrategyFinder public static VersionField? DetermineIncrementedField(IGitRepository repository, GitVersionContext context, BaseVersion baseVersion) { var commitMessageIncrement = FindCommitMessageIncrement(repository, context, baseVersion); - var defaultIncrement = context.Configuration.Increment.ToVersionField(); + var defaultIncrement = context.Configuration?.Increment.ToVersionField(); // use the default branch config increment strategy if there are no commit message overrides if (commitMessageIncrement == null) @@ -57,15 +58,15 @@ public static class IncrementStrategyFinder public static VersionField? GetIncrementForCommits(GitVersionContext context, IEnumerable commits) { - var majorRegex = TryGetRegexOrDefault(context.Configuration.MajorVersionBumpMessage, DefaultMajorPatternRegex); - var minorRegex = TryGetRegexOrDefault(context.Configuration.MinorVersionBumpMessage, DefaultMinorPatternRegex); - var patchRegex = TryGetRegexOrDefault(context.Configuration.PatchVersionBumpMessage, DefaultPatchPatternRegex); - var none = TryGetRegexOrDefault(context.Configuration.NoBumpMessage, DefaultNoBumpPatternRegex); + var majorRegex = TryGetRegexOrDefault(context.Configuration?.MajorVersionBumpMessage, DefaultMajorPatternRegex); + var minorRegex = TryGetRegexOrDefault(context.Configuration?.MinorVersionBumpMessage, DefaultMinorPatternRegex); + var patchRegex = TryGetRegexOrDefault(context.Configuration?.PatchVersionBumpMessage, DefaultPatchPatternRegex); + var none = TryGetRegexOrDefault(context.Configuration?.NoBumpMessage, DefaultNoBumpPatternRegex); var increments = commits .Select(c => GetIncrementFromMessage(c.Message, majorRegex, minorRegex, patchRegex, none)) .Where(v => v != null) - .Select(v => v.Value) + .Select(v => v!.Value) .ToList(); if (increments.Any()) @@ -78,21 +79,21 @@ public static class IncrementStrategyFinder private static VersionField? FindCommitMessageIncrement(IGitRepository repository, GitVersionContext context, BaseVersion baseVersion) { - if (context.Configuration.CommitMessageIncrementing == CommitMessageIncrementMode.Disabled) + if (context.Configuration?.CommitMessageIncrementing == CommitMessageIncrementMode.Disabled) { return null; } var commits = GetIntermediateCommits(repository, baseVersion.BaseVersionSource, context.CurrentCommit); - if (context.Configuration.CommitMessageIncrementing == CommitMessageIncrementMode.MergeMessageOnly) + if (context.Configuration?.CommitMessageIncrementing == CommitMessageIncrementMode.MergeMessageOnly) { commits = commits.Where(c => c.Parents.Count() > 1); } return GetIncrementForCommits(context, commits); } - private static Regex TryGetRegexOrDefault(string messageRegex, Regex defaultRegex) + private static Regex TryGetRegexOrDefault(string? messageRegex, Regex defaultRegex) { if (messageRegex == null) { @@ -101,7 +102,7 @@ private static Regex TryGetRegexOrDefault(string messageRegex, Regex defaultRege return CompiledRegexCache.GetOrAdd(messageRegex, pattern => new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase)); } - private static IEnumerable GetIntermediateCommits(IGitRepository repo, ICommit baseCommit, ICommit headCommit) + private static IEnumerable GetIntermediateCommits(IGitRepository repo, ICommit? baseCommit, ICommit? headCommit) { if (baseCommit == null) yield break; @@ -132,7 +133,7 @@ private static IEnumerable GetIntermediateCommits(IGitRepository repo, return null; } - private static IEnumerable GetCommitsReacheableFromHead(IGitRepository repo, ICommit headCommit) + private static IEnumerable GetCommitsReacheableFromHead(IGitRepository repo, ICommit? headCommit) { var filter = new CommitFilter { diff --git a/src/GitVersion.Core/VersionCalculation/MainlineVersionCalculator.cs b/src/GitVersion.Core/VersionCalculation/MainlineVersionCalculator.cs index 5b0d819676..934a0235d2 100644 --- a/src/GitVersion.Core/VersionCalculation/MainlineVersionCalculator.cs +++ b/src/GitVersion.Core/VersionCalculation/MainlineVersionCalculator.cs @@ -1,8 +1,10 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using GitVersion.Common; using GitVersion.Configuration; +using GitVersion.Extensions; using GitVersion.Logging; namespace GitVersion.VersionCalculation @@ -23,7 +25,7 @@ public MainlineVersionCalculator(ILog log, IRepositoryStore repositoryStore, Laz public SemanticVersion FindMainlineModeVersion(BaseVersion baseVersion) { - if (baseVersion.SemanticVersion.PreReleaseTag.HasTag()) + if (baseVersion.SemanticVersion.PreReleaseTag?.HasTag() == true) { throw new NotSupportedException("Mainline development mode doesn't yet support pre-release tags on main"); } @@ -43,7 +45,7 @@ public SemanticVersion FindMainlineModeVersion(BaseVersion baseVersion) var mainlineTip = mainline.Tip; // when the current branch is not mainline, find the effective mainline tip for versioning the branch - if (!context.CurrentBranch.Equals(mainline)) + if (!context.CurrentBranch!.Equals(mainline)) { mergeBase = FindMergeBaseBeforeForwardMerge(baseVersion.BaseVersionSource, mainline, out mainlineTip); log.Info($"Current branch ({context.CurrentBranch}) was branch from {mergeBase}"); @@ -52,7 +54,7 @@ public SemanticVersion FindMainlineModeVersion(BaseVersion baseVersion) var mainlineCommitLog = repositoryStore.GetMainlineCommitLog(baseVersion.BaseVersionSource, mainlineTip).ToList(); var directCommits = new List(mainlineCommitLog.Count); - if (string.IsNullOrEmpty(context.Configuration.NextVersion)) + if (StringExtensions.IsNullOrEmpty(context.Configuration?.NextVersion)) { // Scans commit log in reverse, aggregating merge commits foreach (var commit in mainlineCommitLog) @@ -71,7 +73,7 @@ public SemanticVersion FindMainlineModeVersion(BaseVersion baseVersion) mainlineVersion.BuildMetaData = CreateVersionBuildMetaData(mergeBase); // branches other than main always get a bump for the act of branching - if ((!context.CurrentBranch.Equals(mainline)) && (string.IsNullOrEmpty(context.Configuration.NextVersion))) + if ((!context.CurrentBranch.Equals(mainline)) && (StringExtensions.IsNullOrEmpty(context.Configuration?.NextVersion))) { var branchIncrement = FindMessageIncrement(null, context.CurrentCommit, mergeBase, mainlineCommitLog); log.Info($"Performing {branchIncrement} increment for current branch "); @@ -83,20 +85,20 @@ public SemanticVersion FindMainlineModeVersion(BaseVersion baseVersion) } } - public SemanticVersionBuildMetaData CreateVersionBuildMetaData(ICommit baseVersionSource) + public SemanticVersionBuildMetaData CreateVersionBuildMetaData(ICommit? baseVersionSource) { var commitLog = repositoryStore.GetCommitLog(baseVersionSource, context.CurrentCommit); var commitsSinceTag = commitLog.Count(); log.Info($"{commitsSinceTag} commits found between {baseVersionSource} and {context.CurrentCommit}"); - var shortSha = context.CurrentCommit.Id.ToString(7); + var shortSha = context.CurrentCommit?.Id.ToString(7); return new SemanticVersionBuildMetaData( - baseVersionSource.Sha, + baseVersionSource?.Sha, commitsSinceTag, - context.CurrentBranch.Name.Friendly, - context.CurrentCommit.Sha, + context.CurrentBranch?.Name.Friendly, + context.CurrentCommit?.Sha, shortSha, - context.CurrentCommit.When, + context.CurrentCommit?.When, context.NumberOfUncommittedChanges); } @@ -120,17 +122,17 @@ private SemanticVersion AggregateMergeCommitIncrement(ICommit commit, List b.Value.IsMainline == true).ToList(); + var mainlineBranchConfigs = context.FullConfiguration?.Branches.Where(b => b.Value?.IsMainline == true).ToList(); var mainlineBranches = repositoryStore.GetMainlineBranches(context.CurrentCommit, mainlineBranchConfigs); var allMainlines = mainlineBranches.Values.SelectMany(branches => branches.Select(b => b.Name.Friendly)); log.Info("Found possible mainline branches: " + string.Join(", ", allMainlines)); // Find closest mainline branch - var firstMatchingCommit = context.CurrentBranch.Commits.First(c => mainlineBranches.ContainsKey(c.Sha)); - var possibleMainlineBranches = mainlineBranches[firstMatchingCommit.Sha]; + var firstMatchingCommit = context.CurrentBranch?.Commits.First(c => mainlineBranches.ContainsKey(c.Sha)); + var possibleMainlineBranches = mainlineBranches[firstMatchingCommit!.Sha]; if (possibleMainlineBranches.Count == 1) { @@ -140,7 +142,7 @@ private IBranch GetMainline(ICommit baseVersionSource) } // prefer current branch, if it is a mainline branch - if (possibleMainlineBranches.Any(context.CurrentBranch.Equals)) + if (possibleMainlineBranches.Any(context.CurrentBranch!.Equals)) { log.Info($"Choosing {context.CurrentBranch} as mainline because it is the current branch"); return context.CurrentBranch; @@ -175,7 +177,7 @@ private IBranch GetMainline(ICommit baseVersionSource) /// /// This method gets the most recent commit on mainline that should be considered for versioning the current branch. /// - private ICommit GetEffectiveMainlineTip(IEnumerable mainlineCommitLog, ICommit mergeBase, ICommit mainlineTip) + private ICommit? GetEffectiveMainlineTip(IEnumerable mainlineCommitLog, ICommit mergeBase, ICommit? mainlineTip) { // find the commit that merged mergeBase into mainline foreach (var commit in mainlineCommitLog) @@ -197,7 +199,7 @@ private ICommit GetEffectiveMainlineTip(IEnumerable mainlineCommitLog, /// The mainline branch. /// The commit on mainline at which the returned merge base was fully integrated. /// The best possible merge base between the current commit and that is not the child of a forward merge. - private ICommit FindMergeBaseBeforeForwardMerge(ICommit baseVersionSource, IBranch mainline, out ICommit mainlineTip) + private ICommit FindMergeBaseBeforeForwardMerge(ICommit? baseVersionSource, IBranch mainline, [NotNullWhen(true)] out ICommit? mainlineTip) { var mergeBase = repositoryStore.FindMergeBase(context.CurrentCommit, mainline.Tip); var mainlineCommitLog = repositoryStore.GetMainlineCommitLog(baseVersionSource, mainline.Tip).ToList(); @@ -208,7 +210,7 @@ private ICommit FindMergeBaseBeforeForwardMerge(ICommit baseVersionSource, IBran // detect forward merge and rewind mainlineTip to before it if (Equals(mergeBase, context.CurrentCommit) && !mainlineCommitLog.Contains(mergeBase)) { - var mainlineTipPrevious = mainlineTip.Parents.FirstOrDefault(); + var mainlineTipPrevious = mainlineTip?.Parents.FirstOrDefault(); if (mainlineTipPrevious != null) { var message = $"Detected forward merge at {mainlineTip}; rewinding mainline to previous commit {mainlineTipPrevious}"; @@ -237,7 +239,7 @@ private SemanticVersion IncrementForEachCommit(IEnumerable directCommit return mainlineVersion; } - private VersionField FindMessageIncrement(ICommit mergeCommit, ICommit mergedHead, ICommit findMergeBase, List commitLog) + private VersionField FindMessageIncrement(ICommit? mergeCommit, ICommit? mergedHead, ICommit? findMergeBase, List commitLog) { var commits = repositoryStore.GetMergeBaseCommits(mergeCommit, mergedHead, findMergeBase); commitLog.RemoveAll(c => commits.Any(c1 => c1.Sha == c.Sha)); @@ -245,14 +247,14 @@ private VersionField FindMessageIncrement(ICommit mergeCommit, ICommit mergedHea ?? TryFindIncrementFromMergeMessage(mergeCommit); } - private VersionField TryFindIncrementFromMergeMessage(ICommit mergeCommit) + private VersionField TryFindIncrementFromMergeMessage(ICommit? mergeCommit) { if (mergeCommit != null) { var mergeMessage = new MergeMessage(mergeCommit.Message, context.FullConfiguration); if (mergeMessage.MergedBranch != null) { - var config = context.FullConfiguration.GetConfigForBranch(mergeMessage.MergedBranch); + var config = context.FullConfiguration?.GetConfigForBranch(mergeMessage.MergedBranch); if (config?.Increment != null && config.Increment != IncrementStrategy.Inherit) { return config.Increment.Value.ToVersionField(); @@ -264,9 +266,9 @@ private VersionField TryFindIncrementFromMergeMessage(ICommit mergeCommit) return FindDefaultIncrementForBranch(context); } - private static VersionField FindDefaultIncrementForBranch(GitVersionContext context, string branch = null) + private static VersionField FindDefaultIncrementForBranch(GitVersionContext context, string? branch = null) { - var config = context.FullConfiguration.GetConfigForBranch(branch ?? context.CurrentBranch.Name.WithoutRemote); + var config = context.FullConfiguration?.GetConfigForBranch(branch ?? context.CurrentBranch?.Name.WithoutRemote); if (config?.Increment != null && config.Increment != IncrementStrategy.Inherit) { return config.Increment.Value.ToVersionField(); diff --git a/src/GitVersion.Core/VersionCalculation/MinDateVersionFilter.cs b/src/GitVersion.Core/VersionCalculation/MinDateVersionFilter.cs index 7fb2e26538..a5d3610abb 100644 --- a/src/GitVersion.Core/VersionCalculation/MinDateVersionFilter.cs +++ b/src/GitVersion.Core/VersionCalculation/MinDateVersionFilter.cs @@ -1,4 +1,5 @@ using System; +using System.Diagnostics.CodeAnalysis; namespace GitVersion.VersionCalculation { @@ -11,7 +12,7 @@ public MinDateVersionFilter(DateTimeOffset minimum) this.minimum = minimum; } - public bool Exclude(BaseVersion version, out string reason) + public bool Exclude(BaseVersion version, [NotNullWhen(true)] out string? reason) { if (version == null) throw new ArgumentNullException(nameof(version)); diff --git a/src/GitVersion.Core/VersionCalculation/NextVersionCalculator.cs b/src/GitVersion.Core/VersionCalculation/NextVersionCalculator.cs index 7589b16c53..152ab8e9a2 100644 --- a/src/GitVersion.Core/VersionCalculation/NextVersionCalculator.cs +++ b/src/GitVersion.Core/VersionCalculation/NextVersionCalculator.cs @@ -40,7 +40,7 @@ public SemanticVersion FindVersion() EnsureHeadIsNotDetached(context); } - SemanticVersion taggedSemanticVersion = null; + SemanticVersion? taggedSemanticVersion = null; if (context.IsCurrentCommitTagged) { @@ -58,7 +58,7 @@ public SemanticVersion FindVersion() var baseVersion = baseVersionCalculator.GetBaseVersion(); baseVersion.SemanticVersion.BuildMetaData = mainlineVersionCalculator.CreateVersionBuildMetaData(baseVersion.BaseVersionSource); SemanticVersion semver; - if (context.Configuration.VersioningMode == VersioningMode.Mainline) + if (context.Configuration?.VersioningMode == VersioningMode.Mainline) { semver = mainlineVersionCalculator.FindMainlineModeVersion(baseVersion); } @@ -75,12 +75,14 @@ public SemanticVersion FindVersion() } } - var hasPreReleaseTag = semver.PreReleaseTag.HasTag(); - var branchConfigHasPreReleaseTagConfigured = !string.IsNullOrEmpty(context.Configuration.Tag); - var preReleaseTagDoesNotMatchConfiguration = hasPreReleaseTag && branchConfigHasPreReleaseTagConfigured && semver.PreReleaseTag.Name != context.Configuration.Tag; - if (!semver.PreReleaseTag.HasTag() && branchConfigHasPreReleaseTagConfigured || preReleaseTagDoesNotMatchConfiguration) + var hasPreReleaseTag = semver.PreReleaseTag?.HasTag() == true; + var branchConfigHasPreReleaseTagConfigured = !StringExtensions.IsNullOrEmpty(context.Configuration?.Tag); +#pragma warning disable CS8602 // Dereference of a possibly null reference. // context.Configuration.Tag not null when branchConfigHasPreReleaseTagConfigured is true + var preReleaseTagDoesNotMatchConfiguration = hasPreReleaseTag && branchConfigHasPreReleaseTagConfigured && semver.PreReleaseTag?.Name != context.Configuration.Tag; +#pragma warning restore CS8602 // Dereference of a possibly null reference. + if (semver.PreReleaseTag?.HasTag() != true && branchConfigHasPreReleaseTagConfigured || preReleaseTagDoesNotMatchConfiguration) { - UpdatePreReleaseTag(semver, baseVersion.BranchNameOverride); + UpdatePreReleaseTag(semver, baseVersion?.BranchNameOverride); } if (taggedSemanticVersion != null) @@ -90,10 +92,10 @@ public SemanticVersion FindVersion() { taggedSemanticVersion = null; } - else + else if (taggedSemanticVersion.BuildMetaData != null) { // set the commit count on the tagged ver - taggedSemanticVersion.BuildMetaData.CommitsSinceVersionSource = semver.BuildMetaData.CommitsSinceVersionSource; + taggedSemanticVersion.BuildMetaData.CommitsSinceVersionSource = semver.BuildMetaData?.CommitsSinceVersionSource; } } @@ -112,19 +114,19 @@ private SemanticVersion PerformIncrement(BaseVersion baseVersion) return semver; } - private void UpdatePreReleaseTag(SemanticVersion semanticVersion, string branchNameOverride) + private void UpdatePreReleaseTag(SemanticVersion semanticVersion, string? branchNameOverride) { - var tagToUse = context.Configuration.GetBranchSpecificTag(log, context.CurrentBranch.Name.Friendly, branchNameOverride); + var tagToUse = context.Configuration?.GetBranchSpecificTag(log, context.CurrentBranch?.Name.Friendly, branchNameOverride); int? number = null; var lastTag = repositoryStore - .GetVersionTagsOnBranch(context.CurrentBranch, context.Configuration.GitTagPrefix) - .FirstOrDefault(v => v.PreReleaseTag.Name.IsEquivalentTo(tagToUse)); + .GetVersionTagsOnBranch(context.CurrentBranch!, context.Configuration?.GitTagPrefix) + .FirstOrDefault(v => v?.PreReleaseTag?.Name?.IsEquivalentTo(tagToUse) == true); if (lastTag != null && MajorMinorPatchEqual(lastTag, semanticVersion) && - lastTag.PreReleaseTag.HasTag()) + lastTag.PreReleaseTag?.HasTag() == true) { number = lastTag.PreReleaseTag.Number + 1; } @@ -136,7 +138,7 @@ private void UpdatePreReleaseTag(SemanticVersion semanticVersion, string branchN private static void EnsureHeadIsNotDetached(GitVersionContext context) { - if (!context.CurrentBranch.IsDetachedHead) + if (context.CurrentBranch?.IsDetachedHead != true) { return; } @@ -144,7 +146,7 @@ private static void EnsureHeadIsNotDetached(GitVersionContext context) var message = string.Format( "It looks like the branch being examined is a detached Head pointing to commit '{0}'. " + "Without a proper branch name GitVersion cannot determine the build version.", - context.CurrentCommit.Id.ToString(7)); + context.CurrentCommit?.Id.ToString(7)); throw new WarningException(message); } diff --git a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs index 6b96d966d9..8eb08032a3 100644 --- a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs +++ b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs @@ -1,5 +1,7 @@ using System; +using System.Diagnostics.CodeAnalysis; using System.Text.RegularExpressions; +using GitVersion.Extensions; namespace GitVersion { @@ -14,8 +16,8 @@ public class SemanticVersion : IFormattable, IComparable public int Major; public int Minor; public int Patch; - public SemanticVersionPreReleaseTag PreReleaseTag; - public SemanticVersionBuildMetaData BuildMetaData; + public SemanticVersionPreReleaseTag? PreReleaseTag; + public SemanticVersionBuildMetaData? BuildMetaData; public SemanticVersion(int major = 0, int minor = 0, int patch = 0) { @@ -26,17 +28,17 @@ public SemanticVersion(int major = 0, int minor = 0, int patch = 0) BuildMetaData = new SemanticVersionBuildMetaData(); } - public SemanticVersion(SemanticVersion semanticVersion) + public SemanticVersion(SemanticVersion? semanticVersion) { - Major = semanticVersion.Major; - Minor = semanticVersion.Minor; - Patch = semanticVersion.Patch; + Major = semanticVersion?.Major ?? 0; + Minor = semanticVersion?.Minor ?? 0; + Patch = semanticVersion?.Patch ?? 0; - PreReleaseTag = new SemanticVersionPreReleaseTag(semanticVersion.PreReleaseTag); - BuildMetaData = new SemanticVersionBuildMetaData(semanticVersion.BuildMetaData); + PreReleaseTag = new SemanticVersionPreReleaseTag(semanticVersion?.PreReleaseTag); + BuildMetaData = new SemanticVersionBuildMetaData(semanticVersion?.BuildMetaData); } - public bool Equals(SemanticVersion obj) + public bool Equals(SemanticVersion? obj) { if (obj == null) { @@ -54,7 +56,7 @@ public bool IsEmpty() return Equals(Empty); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (ReferenceEquals(null, obj)) { @@ -84,7 +86,7 @@ public override int GetHashCode() } } - public static bool operator ==(SemanticVersion v1, SemanticVersion v2) + public static bool operator ==(SemanticVersion? v1, SemanticVersion? v2) { if (ReferenceEquals(v1, null)) { @@ -93,12 +95,12 @@ public override int GetHashCode() return v1.Equals(v2); } - public static bool operator !=(SemanticVersion v1, SemanticVersion v2) + public static bool operator !=(SemanticVersion? v1, SemanticVersion? v2) { return !(v1 == v2); } - public static bool operator >(SemanticVersion v1, SemanticVersion v2) + public static bool operator >(SemanticVersion? v1, SemanticVersion? v2) { if (v1 == null) throw new ArgumentNullException(nameof(v1)); @@ -107,7 +109,7 @@ public override int GetHashCode() return v1.CompareTo(v2) > 0; } - public static bool operator >=(SemanticVersion v1, SemanticVersion v2) + public static bool operator >=(SemanticVersion? v1, SemanticVersion? v2) { if (v1 == null) throw new ArgumentNullException(nameof(v1)); @@ -116,7 +118,7 @@ public override int GetHashCode() return v1.CompareTo(v2) >= 0; } - public static bool operator <=(SemanticVersion v1, SemanticVersion v2) + public static bool operator <=(SemanticVersion? v1, SemanticVersion? v2) { if (v1 == null) throw new ArgumentNullException(nameof(v1)); @@ -126,7 +128,7 @@ public override int GetHashCode() return v1.CompareTo(v2) <= 0; } - public static bool operator <(SemanticVersion v1, SemanticVersion v2) + public static bool operator <(SemanticVersion? v1, SemanticVersion? v2) { if (v1 == null) throw new ArgumentNullException(nameof(v1)); @@ -136,7 +138,7 @@ public override int GetHashCode() return v1.CompareTo(v2) < 0; } - public static SemanticVersion Parse(string version, string tagPrefixRegex) + public static SemanticVersion Parse(string version, string? tagPrefixRegex) { if (!TryParse(version, tagPrefixRegex, out var semanticVersion)) throw new WarningException($"Failed to parse {version} into a Semantic Version"); @@ -144,7 +146,7 @@ public static SemanticVersion Parse(string version, string tagPrefixRegex) return semanticVersion; } - public static bool TryParse(string version, string tagPrefixRegex, out SemanticVersion semanticVersion) + public static bool TryParse(string version, string? tagPrefixRegex, [NotNullWhen(true)] out SemanticVersion? semanticVersion) { var match = Regex.Match(version, $"^({tagPrefixRegex})?(?.*)$"); @@ -187,7 +189,7 @@ public int CompareTo(SemanticVersion value) return CompareTo(value, true); } - public int CompareTo(SemanticVersion value, bool includePrerelease) + public int CompareTo(SemanticVersion? value, bool includePrerelease) { if (value == null) { @@ -217,9 +219,9 @@ public int CompareTo(SemanticVersion value, bool includePrerelease) } return -1; } - if (includePrerelease && PreReleaseTag != value.PreReleaseTag) + if (includePrerelease && PreReleaseTag != value?.PreReleaseTag) { - if (PreReleaseTag > value.PreReleaseTag) + if (PreReleaseTag > value?.PreReleaseTag) { return 1; } @@ -243,9 +245,9 @@ public override string ToString() /// l - Legacy SemVer tag for systems which do not support SemVer 2.0 properly [1.2.3-beta4] /// lp - Legacy SemVer tag for systems which do not support SemVer 2.0 properly (padded) [1.2.3-beta0004] /// - public string ToString(string format, IFormatProvider formatProvider = null) + public string ToString(string? format, IFormatProvider? formatProvider = null) { - if (string.IsNullOrEmpty(format)) + if (StringExtensions.IsNullOrEmpty(format)) format = "s"; if (formatProvider?.GetFormat(GetType()) is ICustomFormatter formatter) @@ -256,7 +258,7 @@ public string ToString(string format, IFormatProvider formatProvider = null) if (format.StartsWith("lp", StringComparison.Ordinal)) { // handle the padding - return PreReleaseTag.HasTag() ? $"{ToString("j")}-{PreReleaseTag.ToString(format)}" : ToString("j"); + return PreReleaseTag?.HasTag() == true ? $"{ToString("j")}-{PreReleaseTag.ToString(format)}" : ToString("j"); } switch (format) @@ -264,22 +266,22 @@ public string ToString(string format, IFormatProvider formatProvider = null) case "j": return $"{Major}.{Minor}.{Patch}"; case "s": - return PreReleaseTag.HasTag() ? $"{ToString("j")}-{PreReleaseTag}" : ToString("j"); + return PreReleaseTag?.HasTag() == true ? $"{ToString("j")}-{PreReleaseTag}" : ToString("j"); case "t": - return PreReleaseTag.HasTag() ? $"{ToString("j")}-{PreReleaseTag.ToString("t")}" : ToString("j"); + return PreReleaseTag?.HasTag() == true ? $"{ToString("j")}-{PreReleaseTag.ToString("t")}" : ToString("j"); case "l": - return PreReleaseTag.HasTag() ? $"{ToString("j")}-{PreReleaseTag.ToString("l")}" : ToString("j"); + return PreReleaseTag?.HasTag() == true ? $"{ToString("j")}-{PreReleaseTag.ToString("l")}" : ToString("j"); case "f": { - var buildMetadata = BuildMetaData.ToString(); + var buildMetadata = BuildMetaData?.ToString(); - return !string.IsNullOrEmpty(buildMetadata) ? $"{ToString("s")}+{buildMetadata}" : ToString("s"); + return !StringExtensions.IsNullOrEmpty(buildMetadata) ? $"{ToString("s")}+{buildMetadata}" : ToString("s"); } case "i": { - var buildMetadata = BuildMetaData.ToString("f"); + var buildMetadata = BuildMetaData?.ToString("f"); - return !string.IsNullOrEmpty(buildMetadata) ? $"{ToString("s")}+{buildMetadata}" : ToString("s"); + return !StringExtensions.IsNullOrEmpty(buildMetadata) ? $"{ToString("s")}+{buildMetadata}" : ToString("s"); } default: throw new ArgumentException($"Unrecognised format '{format}'", nameof(format)); @@ -289,7 +291,7 @@ public string ToString(string format, IFormatProvider formatProvider = null) public SemanticVersion IncrementVersion(VersionField incrementStrategy) { var incremented = new SemanticVersion(this); - if (!incremented.PreReleaseTag.HasTag()) + if (incremented.PreReleaseTag?.HasTag() != true) { switch (incrementStrategy) { diff --git a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionBuildMetaData.cs b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionBuildMetaData.cs index 12cd22a3d0..8631ee7a80 100644 --- a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionBuildMetaData.cs +++ b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionBuildMetaData.cs @@ -1,5 +1,6 @@ using System; using System.Text.RegularExpressions; +using GitVersion.Extensions; using GitVersion.Helpers; namespace GitVersion @@ -11,23 +12,23 @@ public class SemanticVersionBuildMetaData : IFormattable, IEquatable EqualityHelper = - new LambdaEqualityHelper(x => x.CommitsSinceTag, x => x.Branch, x => x.Sha); + new LambdaEqualityHelper(x => x?.CommitsSinceTag, x => x?.Branch, x => x?.Sha); public int? CommitsSinceTag; - public string Branch; - public string Sha; - public string ShortSha; - public string OtherMetaData; - public DateTimeOffset CommitDate; - public string VersionSourceSha; - public int CommitsSinceVersionSource; + public string? Branch; + public string? Sha; + public string? ShortSha; + public string? OtherMetaData; + public DateTimeOffset? CommitDate; + public string? VersionSourceSha; + public int? CommitsSinceVersionSource; public int UncommittedChanges; public SemanticVersionBuildMetaData() { } - public SemanticVersionBuildMetaData(string versionSourceSha, int? commitsSinceTag, string branch, string commitSha, string commitShortSha, DateTimeOffset commitDate, int numbeerOfUncommitedChanges, string otherMetadata = null) + public SemanticVersionBuildMetaData(string? versionSourceSha, int? commitsSinceTag, string? branch, string? commitSha, string? commitShortSha, DateTimeOffset? commitDate, int numbeerOfUncommitedChanges, string? otherMetadata = null) { Sha = commitSha; ShortSha = commitShortSha; @@ -40,17 +41,17 @@ public SemanticVersionBuildMetaData(string versionSourceSha, int? commitsSinceTa UncommittedChanges = numbeerOfUncommitedChanges; } - public SemanticVersionBuildMetaData(SemanticVersionBuildMetaData buildMetaData) + public SemanticVersionBuildMetaData(SemanticVersionBuildMetaData? buildMetaData) { - Sha = buildMetaData.Sha; - ShortSha = buildMetaData.ShortSha; - CommitsSinceTag = buildMetaData.CommitsSinceTag; - Branch = buildMetaData.Branch; - CommitDate = buildMetaData.CommitDate; - OtherMetaData = buildMetaData.OtherMetaData; - VersionSourceSha = buildMetaData.VersionSourceSha; - CommitsSinceVersionSource = buildMetaData.CommitsSinceVersionSource; - UncommittedChanges = buildMetaData.UncommittedChanges; + Sha = buildMetaData?.Sha; + ShortSha = buildMetaData?.ShortSha; + CommitsSinceTag = buildMetaData?.CommitsSinceTag; + Branch = buildMetaData?.Branch; + CommitDate = buildMetaData?.CommitDate; + OtherMetaData = buildMetaData?.OtherMetaData; + VersionSourceSha = buildMetaData?.VersionSourceSha; + CommitsSinceVersionSource = buildMetaData?.CommitsSinceVersionSource; + UncommittedChanges = buildMetaData?.UncommittedChanges ?? 0; } public override bool Equals(object obj) @@ -58,7 +59,7 @@ public override bool Equals(object obj) return Equals(obj as SemanticVersionBuildMetaData); } - public bool Equals(SemanticVersionBuildMetaData other) + public bool Equals(SemanticVersionBuildMetaData? other) { return EqualityHelper.Equals(this, other); } @@ -79,7 +80,7 @@ public override string ToString() /// f - Formats the full build metadata /// p - Formats the padded build number. Can specify an integer for padding, default is 4. (i.e., p5) /// - public string ToString(string format, IFormatProvider formatProvider = null) + public string ToString(string? format, IFormatProvider? formatProvider = null) { if (formatProvider != null) { @@ -87,10 +88,9 @@ public string ToString(string format, IFormatProvider formatProvider = null) return formatter.Format(format, this, formatProvider); } - if (string.IsNullOrEmpty(format)) + if (StringExtensions.IsNullOrEmpty(format)) format = "b"; - format = format.ToLower(); if (format.StartsWith("p", StringComparison.Ordinal)) { @@ -111,25 +111,25 @@ public string ToString(string format, IFormatProvider formatProvider = null) return format.ToLower() switch { "b" => CommitsSinceTag.ToString(), - "s" => $"{CommitsSinceTag}{(string.IsNullOrEmpty(Sha) ? null : ".Sha." + Sha)}".TrimStart('.'), - "f" => $"{CommitsSinceTag}{(string.IsNullOrEmpty(Branch) ? null : ".Branch." + FormatMetaDataPart(Branch))}{(string.IsNullOrEmpty(Sha) ? null : ".Sha." + Sha)}{(string.IsNullOrEmpty(OtherMetaData) ? null : "." + FormatMetaDataPart(OtherMetaData))}".TrimStart('.'), + "s" => $"{CommitsSinceTag}{(StringExtensions.IsNullOrEmpty(Sha) ? null : ".Sha." + Sha)}".TrimStart('.'), + "f" => $"{CommitsSinceTag}{(StringExtensions.IsNullOrEmpty(Branch) ? null : ".Branch." + FormatMetaDataPart(Branch))}{(StringExtensions.IsNullOrEmpty(Sha) ? null : ".Sha." + Sha)}{(StringExtensions.IsNullOrEmpty(OtherMetaData) ? null : "." + FormatMetaDataPart(OtherMetaData))}".TrimStart('.'), _ => throw new ArgumentException("Unrecognised format", nameof(format)) }; } - public static bool operator ==(SemanticVersionBuildMetaData left, SemanticVersionBuildMetaData right) + public static bool operator ==(SemanticVersionBuildMetaData? left, SemanticVersionBuildMetaData? right) { return Equals(left, right); } - public static bool operator !=(SemanticVersionBuildMetaData left, SemanticVersionBuildMetaData right) + public static bool operator !=(SemanticVersionBuildMetaData? left, SemanticVersionBuildMetaData? right) { return !Equals(left, right); } - public static implicit operator string(SemanticVersionBuildMetaData preReleaseTag) + public static implicit operator string?(SemanticVersionBuildMetaData? preReleaseTag) { - return preReleaseTag.ToString(); + return preReleaseTag?.ToString(); } public static implicit operator SemanticVersionBuildMetaData(string preReleaseTag) @@ -137,10 +137,10 @@ public static implicit operator SemanticVersionBuildMetaData(string preReleaseTa return Parse(preReleaseTag); } - public static SemanticVersionBuildMetaData Parse(string buildMetaData) + public static SemanticVersionBuildMetaData Parse(string? buildMetaData) { var semanticVersionBuildMetaData = new SemanticVersionBuildMetaData(); - if (string.IsNullOrEmpty(buildMetaData)) + if (StringExtensions.IsNullOrEmpty(buildMetaData)) return semanticVersionBuildMetaData; var parsed = ParseRegex.Match(buildMetaData); @@ -157,7 +157,7 @@ public static SemanticVersionBuildMetaData Parse(string buildMetaData) if (parsed.Groups["Sha"].Success) semanticVersionBuildMetaData.Sha = parsed.Groups["Sha"].Value; - if (parsed.Groups["Other"].Success && !string.IsNullOrEmpty(parsed.Groups["Other"].Value)) + if (parsed.Groups["Other"].Success && !StringExtensions.IsNullOrEmpty(parsed.Groups["Other"].Value)) semanticVersionBuildMetaData.OtherMetaData = parsed.Groups["Other"].Value.TrimStart('.'); return semanticVersionBuildMetaData; @@ -165,7 +165,7 @@ public static SemanticVersionBuildMetaData Parse(string buildMetaData) private string FormatMetaDataPart(string value) { - if (!string.IsNullOrEmpty(value)) + if (!StringExtensions.IsNullOrEmpty(value)) value = Regex.Replace(value, "[^0-9A-Za-z-.]", "-"); return value; } diff --git a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionExtensions.cs b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionExtensions.cs index 36248df663..960407f1ff 100644 --- a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionExtensions.cs +++ b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionExtensions.cs @@ -1,3 +1,4 @@ +using GitVersion.Extensions; using GitVersion.Model.Configuration; namespace GitVersion @@ -6,7 +7,7 @@ public static class SemanticVersionExtensions { public static void OverrideVersionManuallyIfNeeded(this SemanticVersion version, EffectiveConfiguration configuration) { - if (!string.IsNullOrEmpty(configuration.NextVersion) && SemanticVersion.TryParse(configuration.NextVersion, configuration.GitTagPrefix, out var manualNextVersion)) + if (!StringExtensions.IsNullOrEmpty(configuration.NextVersion) && SemanticVersion.TryParse(configuration.NextVersion, configuration.GitTagPrefix, out var manualNextVersion)) { if (manualNextVersion > version) { diff --git a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionFormatValues.cs b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionFormatValues.cs index eae5bb911a..2e5e7770b9 100644 --- a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionFormatValues.cs +++ b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionFormatValues.cs @@ -22,23 +22,23 @@ public SemanticVersionFormatValues(SemanticVersion semver, EffectiveConfiguratio public string Patch => semver.Patch.ToString(); - public string PreReleaseTag => semver.PreReleaseTag; + public string? PreReleaseTag => semver.PreReleaseTag; - public string PreReleaseTagWithDash => semver.PreReleaseTag.HasTag() ? "-" + semver.PreReleaseTag : null; + public string? PreReleaseTagWithDash => semver.PreReleaseTag?.HasTag() == true ? "-" + semver.PreReleaseTag : null; - public string PreReleaseLabel => semver.PreReleaseTag.HasTag() ? semver.PreReleaseTag.Name : null; + public string? PreReleaseLabel => semver.PreReleaseTag?.HasTag() == true ? semver.PreReleaseTag.Name : null; - public string PreReleaseLabelWithDash => semver.PreReleaseTag.HasTag() ? "-" + semver.PreReleaseTag.Name : null; + public string? PreReleaseLabelWithDash => semver.PreReleaseTag?.HasTag() == true ? "-" + semver.PreReleaseTag.Name : null; - public string PreReleaseNumber => semver.PreReleaseTag.HasTag() ? semver.PreReleaseTag.Number.ToString() : null; + public string? PreReleaseNumber => semver.PreReleaseTag?.HasTag() == true ? semver.PreReleaseTag.Number.ToString() : null; public string WeightedPreReleaseNumber => GetWeightedPreReleaseNumber(); - public string BuildMetaData => semver.BuildMetaData; + public string? BuildMetaData => semver.BuildMetaData; - public string BuildMetaDataPadded => semver.BuildMetaData.ToString("p" + config.BuildMetaDataPadding); + public string? BuildMetaDataPadded => semver.BuildMetaData?.ToString("p" + config.BuildMetaDataPadding); - public string FullBuildMetaData => semver.BuildMetaData.ToString("f"); + public string? FullBuildMetaData => semver.BuildMetaData?.ToString("f"); public string MajorMinorPatch => $"{semver.Major}.{semver.Minor}.{semver.Patch}"; @@ -48,21 +48,21 @@ public SemanticVersionFormatValues(SemanticVersion semver, EffectiveConfiguratio public string LegacySemVerPadded => semver.ToString("lp" + config.LegacySemVerPadding); - public string AssemblySemVer => semver.GetAssemblyVersion(config.AssemblyVersioningScheme); + public string? AssemblySemVer => semver.GetAssemblyVersion(config.AssemblyVersioningScheme); - public string AssemblyFileSemVer => semver.GetAssemblyFileVersion(config.AssemblyFileVersioningScheme); + public string? AssemblyFileSemVer => semver.GetAssemblyFileVersion(config.AssemblyFileVersioningScheme); public string FullSemVer => semver.ToString("f"); - public string BranchName => semver.BuildMetaData.Branch; + public string? BranchName => semver.BuildMetaData?.Branch; - public string EscapedBranchName => semver.BuildMetaData.Branch?.RegexReplace("[^a-zA-Z0-9-]", "-"); + public string? EscapedBranchName => semver.BuildMetaData?.Branch?.RegexReplace("[^a-zA-Z0-9-]", "-"); - public string Sha => semver.BuildMetaData.Sha; + public string? Sha => semver.BuildMetaData?.Sha; - public string ShortSha => semver.BuildMetaData.ShortSha; + public string? ShortSha => semver.BuildMetaData?.ShortSha; - public string CommitDate => semver.BuildMetaData.CommitDate.UtcDateTime.ToString(config.CommitDateFormat, CultureInfo.InvariantCulture); + public string? CommitDate => semver.BuildMetaData?.CommitDate?.UtcDateTime.ToString(config.CommitDateFormat, CultureInfo.InvariantCulture); // TODO When NuGet 3 is released: public string NuGetVersionV3 { get { return ??; } } @@ -70,30 +70,31 @@ public SemanticVersionFormatValues(SemanticVersion semver, EffectiveConfiguratio public string NuGetVersion => NuGetVersionV2; - public string NuGetPreReleaseTagV2 => semver.PreReleaseTag.HasTag() ? semver.PreReleaseTag.ToString("lp").ToLower() : null; + public string? NuGetPreReleaseTagV2 => semver.PreReleaseTag?.HasTag() == true ? semver.PreReleaseTag?.ToString("lp")?.ToLower() : null; - public string NuGetPreReleaseTag => NuGetPreReleaseTagV2; + public string? NuGetPreReleaseTag => NuGetPreReleaseTagV2; public string InformationalVersion => semver.ToString("i"); [Obsolete("Use InformationalVersion instead")] public string DefaultInformationalVersion => InformationalVersion; - public string VersionSourceSha => semver.BuildMetaData.VersionSourceSha; + public string? VersionSourceSha => semver.BuildMetaData?.VersionSourceSha; - public string CommitsSinceVersionSource => semver.BuildMetaData.CommitsSinceVersionSource.ToString(CultureInfo.InvariantCulture); + public string? CommitsSinceVersionSource => semver.BuildMetaData?.CommitsSinceVersionSource?.ToString(CultureInfo.InvariantCulture); - public string CommitsSinceVersionSourcePadded => semver.BuildMetaData.CommitsSinceVersionSource.ToString(CultureInfo.InvariantCulture).PadLeft(config.CommitsSinceVersionSourcePadding, '0'); + public string? CommitsSinceVersionSourcePadded => semver.BuildMetaData?.CommitsSinceVersionSource?.ToString(CultureInfo.InvariantCulture).PadLeft(config.CommitsSinceVersionSourcePadding, '0'); - public string UncommittedChanges => semver.BuildMetaData.UncommittedChanges.ToString(CultureInfo.InvariantCulture); + public string? UncommittedChanges => semver.BuildMetaData?.UncommittedChanges.ToString(CultureInfo.InvariantCulture); private string GetWeightedPreReleaseNumber() { var weightedPreReleaseNumber = - semver.PreReleaseTag.HasTag() ? (semver.PreReleaseTag.Number + config.PreReleaseWeight).ToString() : null; - if (string.IsNullOrEmpty(weightedPreReleaseNumber)) + semver.PreReleaseTag?.HasTag() == true ? (semver.PreReleaseTag.Number + config.PreReleaseWeight).ToString() : null; + + if (StringExtensions.IsNullOrEmpty(weightedPreReleaseNumber)) { - weightedPreReleaseNumber = $"{config.TagPreReleaseWeight}"; + return $"{config.TagPreReleaseWeight}"; } return weightedPreReleaseNumber; diff --git a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionPreReleaseTag.cs b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionPreReleaseTag.cs index 9bfd838b38..f36bee347a 100644 --- a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionPreReleaseTag.cs +++ b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionPreReleaseTag.cs @@ -1,6 +1,7 @@ using System; using System.Linq; using System.Text.RegularExpressions; +using GitVersion.Extensions; using GitVersion.Helpers; namespace GitVersion @@ -9,35 +10,35 @@ public class SemanticVersionPreReleaseTag : IFormattable, IComparable, IEquatable { private static readonly LambdaEqualityHelper EqualityHelper = - new LambdaEqualityHelper(x => x.Name, x => x.Number); + new LambdaEqualityHelper(x => x?.Name, x => x?.Number); public SemanticVersionPreReleaseTag() { } - public SemanticVersionPreReleaseTag(string name, int? number) + public SemanticVersionPreReleaseTag(string? name, int? number) { Name = name; Number = number; } - public SemanticVersionPreReleaseTag(SemanticVersionPreReleaseTag preReleaseTag) + public SemanticVersionPreReleaseTag(SemanticVersionPreReleaseTag? preReleaseTag) { - Name = preReleaseTag.Name; - Number = preReleaseTag.Number; - PromotedFromCommits = preReleaseTag.PromotedFromCommits; + Name = preReleaseTag?.Name; + Number = preReleaseTag?.Number; + PromotedFromCommits = preReleaseTag?.PromotedFromCommits; } - public string Name { get; set; } + public string? Name { get; set; } public int? Number { get; set; } - public bool PromotedFromCommits { get; set; } + public bool? PromotedFromCommits { get; set; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { return Equals(obj as SemanticVersionPreReleaseTag); } - public bool Equals(SemanticVersionPreReleaseTag other) + public bool Equals(SemanticVersionPreReleaseTag? other) { return EqualityHelper.Equals(this, other); } @@ -47,49 +48,49 @@ public override int GetHashCode() return EqualityHelper.GetHashCode(this); } - public static bool operator ==(SemanticVersionPreReleaseTag left, SemanticVersionPreReleaseTag right) + public static bool operator ==(SemanticVersionPreReleaseTag? left, SemanticVersionPreReleaseTag? right) { return Equals(left, right); } - public static bool operator !=(SemanticVersionPreReleaseTag left, SemanticVersionPreReleaseTag right) + public static bool operator !=(SemanticVersionPreReleaseTag? left, SemanticVersionPreReleaseTag? right) { return !Equals(left, right); } - public static bool operator >(SemanticVersionPreReleaseTag left, SemanticVersionPreReleaseTag right) + public static bool operator >(SemanticVersionPreReleaseTag? left, SemanticVersionPreReleaseTag? right) { - return left.CompareTo(right) > 0; + return left?.CompareTo(right) > 0; } - public static bool operator <(SemanticVersionPreReleaseTag left, SemanticVersionPreReleaseTag right) + public static bool operator <(SemanticVersionPreReleaseTag? left, SemanticVersionPreReleaseTag? right) { - return left.CompareTo(right) < 0; + return left?.CompareTo(right) < 0; } - public static bool operator >=(SemanticVersionPreReleaseTag left, SemanticVersionPreReleaseTag right) + public static bool operator >=(SemanticVersionPreReleaseTag? left, SemanticVersionPreReleaseTag? right) { - return left.CompareTo(right) >= 0; + return left?.CompareTo(right) >= 0; } - public static bool operator <=(SemanticVersionPreReleaseTag left, SemanticVersionPreReleaseTag right) + public static bool operator <=(SemanticVersionPreReleaseTag? left, SemanticVersionPreReleaseTag? right) { - return StringComparerUtils.IgnoreCaseComparer.Compare(left.Name, right.Name) != 1; + return StringComparerUtils.IgnoreCaseComparer.Compare(left?.Name, right?.Name) != 1; } - public static implicit operator string(SemanticVersionPreReleaseTag preReleaseTag) + public static implicit operator string?(SemanticVersionPreReleaseTag? preReleaseTag) { - return preReleaseTag.ToString(); + return preReleaseTag?.ToString()!; } - public static implicit operator SemanticVersionPreReleaseTag(string preReleaseTag) + public static implicit operator SemanticVersionPreReleaseTag(string? preReleaseTag) { return Parse(preReleaseTag); } - public static SemanticVersionPreReleaseTag Parse(string preReleaseTag) + public static SemanticVersionPreReleaseTag Parse(string? preReleaseTag) { - if (string.IsNullOrEmpty(preReleaseTag)) + if (StringExtensions.IsNullOrEmpty(preReleaseTag)) { return new SemanticVersionPreReleaseTag(); } @@ -110,26 +111,26 @@ public static SemanticVersionPreReleaseTag Parse(string preReleaseTag) return new SemanticVersionPreReleaseTag(value, number); } - public int CompareTo(SemanticVersionPreReleaseTag other) + public int CompareTo(SemanticVersionPreReleaseTag? other) { - if (!HasTag() && other.HasTag()) + if (!HasTag() && other?.HasTag() == true) { return 1; } - if (HasTag() && !other.HasTag()) + if (HasTag() && other?.HasTag() != true) { return -1; } - var nameComparison = StringComparerUtils.IgnoreCaseComparer.Compare(Name, other.Name); + var nameComparison = StringComparerUtils.IgnoreCaseComparer.Compare(Name, other?.Name); if (nameComparison != 0) return nameComparison; - return Nullable.Compare(Number, other.Number); + return Nullable.Compare(Number, other?.Number); } - public override string ToString() + public override string? ToString() { return ToString(null); } @@ -140,7 +141,7 @@ public override string ToString() /// l - Legacy SemVer tag with the tag number padded. [beta1] /// lp - Legacy SemVer tag with the tag number padded. [beta0001]. Can specify an integer to control padding (i.e., lp5) /// - public string ToString(string format, IFormatProvider formatProvider = null) + public string? ToString(string? format, IFormatProvider? formatProvider = null) { if (formatProvider != null) { @@ -148,7 +149,7 @@ public string ToString(string format, IFormatProvider formatProvider = null) return formatter.Format(format, this, formatProvider); } - if (string.IsNullOrEmpty(format)) + if (StringExtensions.IsNullOrEmpty(format)) format = "t"; format = format.ToLower(); @@ -170,7 +171,7 @@ public string ToString(string format, IFormatProvider formatProvider = null) return format switch { - "t" => (Number.HasValue ? string.IsNullOrEmpty(Name) ? $"{Number}" : $"{Name}.{Number}" : Name), + "t" => (Number.HasValue ? StringExtensions.IsNullOrEmpty(Name) ? $"{Number}" : $"{Name}.{Number}" : Name), "l" => (Number.HasValue ? FormatLegacy(GetLegacyName(), Number.Value.ToString()) : FormatLegacy(GetLegacyName())), _ => throw new ArgumentException("Unknown format", nameof(format)) }; @@ -190,7 +191,7 @@ private string FormatLegacy(string tag, string number = "") private string GetLegacyName() { - if (string.IsNullOrEmpty(Name)) + if (StringExtensions.IsNullOrEmpty(Name)) { return string.Empty; } @@ -200,7 +201,7 @@ private string GetLegacyName() public bool HasTag() { - return !string.IsNullOrEmpty(Name) || (Number.HasValue && !PromotedFromCommits); + return !StringExtensions.IsNullOrEmpty(Name) || (Number.HasValue && PromotedFromCommits != true); } } } diff --git a/src/GitVersion.Core/VersionCalculation/ShaVersionFilter.cs b/src/GitVersion.Core/VersionCalculation/ShaVersionFilter.cs index 56cd4d93c1..43f149cd55 100644 --- a/src/GitVersion.Core/VersionCalculation/ShaVersionFilter.cs +++ b/src/GitVersion.Core/VersionCalculation/ShaVersionFilter.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; namespace GitVersion.VersionCalculation @@ -13,7 +14,7 @@ public ShaVersionFilter(IEnumerable shas) this.shas = shas ?? throw new ArgumentNullException(nameof(shas)); } - public bool Exclude(BaseVersion version, out string reason) + public bool Exclude(BaseVersion version, [NotNullWhen(true)] out string? reason) { if (version == null) throw new ArgumentNullException(nameof(version)); diff --git a/src/GitVersion.Core/VersionCalculation/VariableProvider.cs b/src/GitVersion.Core/VersionCalculation/VariableProvider.cs index 0a1fce7d53..670a053cf6 100644 --- a/src/GitVersion.Core/VersionCalculation/VariableProvider.cs +++ b/src/GitVersion.Core/VersionCalculation/VariableProvider.cs @@ -27,10 +27,10 @@ public VersionVariables GetVariablesFor(SemanticVersion semanticVersion, Effecti { semanticVersion = new SemanticVersion(semanticVersion); // Continuous Deployment always requires a pre-release tag unless the commit is tagged - if (!semanticVersion.PreReleaseTag.HasTag()) + if (semanticVersion.PreReleaseTag?.HasTag() != true) { - semanticVersion.PreReleaseTag.Name = config.GetBranchSpecificTag(log, semanticVersion.BuildMetaData.Branch, null); - if (string.IsNullOrEmpty(semanticVersion.PreReleaseTag.Name)) + semanticVersion.PreReleaseTag!.Name = config.GetBranchSpecificTag(log, semanticVersion.BuildMetaData?.Branch, null); + if (StringExtensions.IsNullOrEmpty(semanticVersion.PreReleaseTag.Name)) { semanticVersion.PreReleaseTag.Name = config.ContinuousDeploymentFallbackTag; } @@ -38,14 +38,14 @@ public VersionVariables GetVariablesFor(SemanticVersion semanticVersion, Effecti } // Evaluate tag number pattern and append to prerelease tag, preserving build metadata - var appendTagNumberPattern = !string.IsNullOrEmpty(config.TagNumberPattern) && semanticVersion.PreReleaseTag.HasTag(); + var appendTagNumberPattern = !StringExtensions.IsNullOrEmpty(config.TagNumberPattern) && semanticVersion.PreReleaseTag?.HasTag() == true; if (appendTagNumberPattern) { - var match = Regex.Match(semanticVersion.BuildMetaData.Branch, config.TagNumberPattern); + var match = Regex.Match(semanticVersion.BuildMetaData!.Branch, config.TagNumberPattern); var numberGroup = match.Groups["number"]; if (numberGroup.Success) { - semanticVersion.PreReleaseTag.Name += numberGroup.Value.PadLeft(config.BuildMetaDataPadding, '0'); + semanticVersion.PreReleaseTag!.Name += numberGroup.Value.PadLeft(config.BuildMetaDataPadding, '0'); } } @@ -103,15 +103,15 @@ public VersionVariables GetVariablesFor(SemanticVersion semanticVersion, Effecti private static void PromoteNumberOfCommitsToTagNumber(SemanticVersion semanticVersion) { // For continuous deployment the commits since tag gets promoted to the pre-release number - if (!semanticVersion.BuildMetaData.CommitsSinceTag.HasValue) + if (!semanticVersion.BuildMetaData!.CommitsSinceTag.HasValue) { - semanticVersion.PreReleaseTag.Number = null; + semanticVersion.PreReleaseTag!.Number = null; semanticVersion.BuildMetaData.CommitsSinceVersionSource = 0; } else { // Number of commits since last tag should be added to PreRelease number if given. Remember to deduct automatic version bump. - if (semanticVersion.PreReleaseTag.Number.HasValue) + if (semanticVersion.PreReleaseTag!.Number.HasValue) { semanticVersion.PreReleaseTag.Number += semanticVersion.BuildMetaData.CommitsSinceTag - 1; } @@ -125,11 +125,11 @@ private static void PromoteNumberOfCommitsToTagNumber(SemanticVersion semanticVe } } - private string CheckAndFormatString(string formatString, T source, string defaultValue, string formatVarName) + private string? CheckAndFormatString(string? formatString, T source, string? defaultValue, string formatVarName) { - string formattedString; + string? formattedString; - if (string.IsNullOrEmpty(formatString)) + if (StringExtensions.IsNullOrEmpty(formatString)) { formattedString = defaultValue; } diff --git a/src/GitVersion.Core/VersionConverters/AssemblyInfo/AssemblyInfoContext.cs b/src/GitVersion.Core/VersionConverters/AssemblyInfo/AssemblyInfoContext.cs index a5b62d8b5a..33e49e14ef 100644 --- a/src/GitVersion.Core/VersionConverters/AssemblyInfo/AssemblyInfoContext.cs +++ b/src/GitVersion.Core/VersionConverters/AssemblyInfo/AssemblyInfoContext.cs @@ -2,14 +2,14 @@ namespace GitVersion.VersionConverters.AssemblyInfo { public readonly struct AssemblyInfoContext : IConverterContext { - public AssemblyInfoContext(string workingDirectory, bool ensureAssemblyInfo, params string[] assemblyInfoFiles) + public AssemblyInfoContext(string? workingDirectory, bool ensureAssemblyInfo, params string[] assemblyInfoFiles) { AssemblyInfoFiles = assemblyInfoFiles; EnsureAssemblyInfo = ensureAssemblyInfo; WorkingDirectory = workingDirectory; } - public string WorkingDirectory { get; } + public string? WorkingDirectory { get; } public bool EnsureAssemblyInfo { get; } public string[] AssemblyInfoFiles { get; } } diff --git a/src/GitVersion.Core/VersionConverters/AssemblyInfo/AssemblyInfoFileUpdater.cs b/src/GitVersion.Core/VersionConverters/AssemblyInfo/AssemblyInfoFileUpdater.cs index dbf5a9ee92..0eccd9f0ed 100644 --- a/src/GitVersion.Core/VersionConverters/AssemblyInfo/AssemblyInfoFileUpdater.cs +++ b/src/GitVersion.Core/VersionConverters/AssemblyInfo/AssemblyInfoFileUpdater.cs @@ -3,6 +3,7 @@ using System.IO; using System.Linq; using System.Text.RegularExpressions; +using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.OutputVariables; @@ -48,13 +49,13 @@ public void Execute(VersionVariables variables, AssemblyInfoContext context) log.Info($"Found {assemblyInfoFiles.Count} files"); var assemblyVersion = variables.AssemblySemVer; - var assemblyVersionString = !string.IsNullOrWhiteSpace(assemblyVersion) ? $"AssemblyVersion(\"{assemblyVersion}\")" : null; + var assemblyVersionString = !StringExtensions.IsNullOrWhiteSpace(assemblyVersion) ? $"AssemblyVersion(\"{assemblyVersion}\")" : null; var assemblyInfoVersion = variables.InformationalVersion; - var assemblyInfoVersionString = !string.IsNullOrWhiteSpace(assemblyInfoVersion) ? $"AssemblyInformationalVersion(\"{assemblyInfoVersion}\")" : null; + var assemblyInfoVersionString = !StringExtensions.IsNullOrWhiteSpace(assemblyInfoVersion) ? $"AssemblyInformationalVersion(\"{assemblyInfoVersion}\")" : null; var assemblyFileVersion = variables.AssemblySemFileVer; - var assemblyFileVersionString = !string.IsNullOrWhiteSpace(assemblyFileVersion) ? $"AssemblyFileVersion(\"{assemblyFileVersion}\")" : null; + var assemblyFileVersionString = !StringExtensions.IsNullOrWhiteSpace(assemblyFileVersion) ? $"AssemblyFileVersion(\"{assemblyFileVersion}\")" : null; foreach (var assemblyInfoFile in assemblyInfoFiles) { @@ -78,17 +79,17 @@ public void Execute(VersionVariables variables, AssemblyInfoContext context) var fileContents = originalFileContents; var appendedAttributes = false; - if (!string.IsNullOrWhiteSpace(assemblyVersion)) + if (!StringExtensions.IsNullOrWhiteSpace(assemblyVersion)) { fileContents = ReplaceOrInsertAfterLastAssemblyAttributeOrAppend(assemblyVersionRegex, fileContents, assemblyVersionString, assemblyInfoFile.Extension, ref appendedAttributes); } - if (!string.IsNullOrWhiteSpace(assemblyFileVersion)) + if (!StringExtensions.IsNullOrWhiteSpace(assemblyFileVersion)) { fileContents = ReplaceOrInsertAfterLastAssemblyAttributeOrAppend(assemblyFileVersionRegex, fileContents, assemblyFileVersionString, assemblyInfoFile.Extension, ref appendedAttributes); } - if (!string.IsNullOrWhiteSpace(assemblyInfoVersion)) + if (!StringExtensions.IsNullOrWhiteSpace(assemblyInfoVersion)) { fileContents = ReplaceOrInsertAfterLastAssemblyAttributeOrAppend(assemblyInfoVersionRegex, fileContents, assemblyInfoVersionString, assemblyInfoFile.Extension, ref appendedAttributes); } @@ -129,7 +130,7 @@ private void CommitChanges() restoreBackupTasks.Clear(); } - private string ReplaceOrInsertAfterLastAssemblyAttributeOrAppend(Regex replaceRegex, string inputString, string replaceString, string fileExtension, ref bool appendedAttributes) + private string ReplaceOrInsertAfterLastAssemblyAttributeOrAppend(Regex replaceRegex, string inputString, string? replaceString, string fileExtension, ref bool appendedAttributes) { var assemblyAddFormat = templateManager.GetAddFormatFor(fileExtension); @@ -159,11 +160,11 @@ private string ReplaceOrInsertAfterLastAssemblyAttributeOrAppend(Regex replaceRe private IEnumerable GetAssemblyInfoFiles(AssemblyInfoContext context) { - var workingDirectory = context.WorkingDirectory; + var workingDirectory = context.WorkingDirectory!; var ensureAssemblyInfo = context.EnsureAssemblyInfo; var assemblyInfoFileNames = new HashSet(context.AssemblyInfoFiles); - if (assemblyInfoFileNames.Any(x => !string.IsNullOrWhiteSpace(x))) + if (assemblyInfoFileNames.Any(x => !StringExtensions.IsNullOrWhiteSpace(x))) { foreach (var item in assemblyInfoFileNames) { @@ -204,7 +205,7 @@ private bool EnsureVersionAssemblyInfoFile(string fullPath, bool ensureAssemblyI var assemblyInfoSource = templateManager.GetTemplateFor(Path.GetExtension(fullPath)); - if (!string.IsNullOrWhiteSpace(assemblyInfoSource)) + if (!StringExtensions.IsNullOrWhiteSpace(assemblyInfoSource)) { var fileInfo = new FileInfo(fullPath); diff --git a/src/GitVersion.Core/VersionConverters/AssemblyInfo/ProjectFileUpdater.cs b/src/GitVersion.Core/VersionConverters/AssemblyInfo/ProjectFileUpdater.cs index d4b6155141..d35016f6d2 100644 --- a/src/GitVersion.Core/VersionConverters/AssemblyInfo/ProjectFileUpdater.cs +++ b/src/GitVersion.Core/VersionConverters/AssemblyInfo/ProjectFileUpdater.cs @@ -1,3 +1,4 @@ +using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.OutputVariables; using System; @@ -73,22 +74,22 @@ public void Execute(VersionVariables variables, AssemblyInfoContext context) cleanupBackupTasks.Add(() => fileSystem.Delete(backupProjectFile)); - if (!string.IsNullOrWhiteSpace(assemblyVersion)) + if (!StringExtensions.IsNullOrWhiteSpace(assemblyVersion)) { UpdateProjectVersionElement(fileXml, AssemblyVersionElement, assemblyVersion); } - if (!string.IsNullOrWhiteSpace(assemblyFileVersion)) + if (!StringExtensions.IsNullOrWhiteSpace(assemblyFileVersion)) { UpdateProjectVersionElement(fileXml, FileVersionElement, assemblyFileVersion); } - if (!string.IsNullOrWhiteSpace(assemblyInfoVersion)) + if (!StringExtensions.IsNullOrWhiteSpace(assemblyInfoVersion)) { UpdateProjectVersionElement(fileXml, InformationalVersionElement, assemblyInfoVersion); } - if (!string.IsNullOrWhiteSpace(packageVersion)) + if (!StringExtensions.IsNullOrWhiteSpace(packageVersion)) { UpdateProjectVersionElement(fileXml, VersionElement, packageVersion); } @@ -182,7 +183,7 @@ private IEnumerable GetProjectFiles(AssemblyInfoContext context) var workingDirectory = context.WorkingDirectory; var assemblyInfoFileNames = new HashSet(context.AssemblyInfoFiles); - if (assemblyInfoFileNames.Any(x => !string.IsNullOrWhiteSpace(x))) + if (assemblyInfoFileNames.Any(x => !StringExtensions.IsNullOrWhiteSpace(x))) { foreach (var item in assemblyInfoFileNames) { @@ -211,7 +212,7 @@ private IEnumerable GetProjectFiles(AssemblyInfoContext context) private bool IsSupportedProjectFile(string fileName) { - if (string.IsNullOrEmpty(fileName)) + if (StringExtensions.IsNullOrEmpty(fileName)) { return false; } diff --git a/src/GitVersion.Core/VersionConverters/GitVersionInfo/GitVersionInfoContext.cs b/src/GitVersion.Core/VersionConverters/GitVersionInfo/GitVersionInfoContext.cs index e18f1c0f7c..8682d6100c 100644 --- a/src/GitVersion.Core/VersionConverters/GitVersionInfo/GitVersionInfoContext.cs +++ b/src/GitVersion.Core/VersionConverters/GitVersionInfo/GitVersionInfoContext.cs @@ -2,14 +2,14 @@ namespace GitVersion.VersionConverters.GitVersionInfo { public readonly struct GitVersionInfoContext : IConverterContext { - public GitVersionInfoContext(string workingDirectory, string fileName, string fileExtension) + public GitVersionInfoContext(string? workingDirectory, string fileName, string fileExtension) { WorkingDirectory = workingDirectory; FileName = fileName; FileExtension = fileExtension; } - public string WorkingDirectory { get; } + public string? WorkingDirectory { get; } public string FileName { get; } public string FileExtension { get; } } diff --git a/src/GitVersion.Core/VersionConverters/GitVersionInfo/GitVersionInfoGenerator.cs b/src/GitVersion.Core/VersionConverters/GitVersionInfo/GitVersionInfoGenerator.cs index a5cb0e3278..46ab3484fc 100644 --- a/src/GitVersion.Core/VersionConverters/GitVersionInfo/GitVersionInfoGenerator.cs +++ b/src/GitVersion.Core/VersionConverters/GitVersionInfo/GitVersionInfoGenerator.cs @@ -26,7 +26,7 @@ public void Execute(VersionVariables variables, GitVersionInfoContext context) var directory = context.WorkingDirectory; var filePath = Path.Combine(directory, fileName); - string originalFileContents = null; + string? originalFileContents = null; if (File.Exists(filePath)) { diff --git a/src/GitVersion.Core/VersionConverters/IConverterContext.cs b/src/GitVersion.Core/VersionConverters/IConverterContext.cs index 8fe1579693..5b0d077f2a 100644 --- a/src/GitVersion.Core/VersionConverters/IConverterContext.cs +++ b/src/GitVersion.Core/VersionConverters/IConverterContext.cs @@ -2,6 +2,6 @@ namespace GitVersion.VersionConverters { public interface IConverterContext { - public string WorkingDirectory { get; } + public string? WorkingDirectory { get; } } } diff --git a/src/GitVersion.Core/VersionConverters/OutputGenerator/OutputContext.cs b/src/GitVersion.Core/VersionConverters/OutputGenerator/OutputContext.cs index 16598a7822..9663ac3138 100644 --- a/src/GitVersion.Core/VersionConverters/OutputGenerator/OutputContext.cs +++ b/src/GitVersion.Core/VersionConverters/OutputGenerator/OutputContext.cs @@ -2,15 +2,15 @@ namespace GitVersion.VersionConverters.OutputGenerator { public readonly struct OutputContext : IConverterContext { - public OutputContext(string workingDirectory, string outputFile, bool? updateBuildNumber) + public OutputContext(string? workingDirectory, string? outputFile, bool? updateBuildNumber) { WorkingDirectory = workingDirectory; OutputFile = outputFile; UpdateBuildNumber = updateBuildNumber; } - public string WorkingDirectory { get; } - public string OutputFile { get; } + public string? WorkingDirectory { get; } + public string? OutputFile { get; } public bool? UpdateBuildNumber { get; } } } diff --git a/src/GitVersion.Core/VersionConverters/TemplateManager.cs b/src/GitVersion.Core/VersionConverters/TemplateManager.cs index 26900f5d03..c7c70f3c50 100644 --- a/src/GitVersion.Core/VersionConverters/TemplateManager.cs +++ b/src/GitVersion.Core/VersionConverters/TemplateManager.cs @@ -23,14 +23,14 @@ public TemplateManager(TemplateType templateType) addFormats = GetEmbeddedTemplates(templateType, "AddFormats").ToDictionary(Path.GetExtension, v => v, StringComparer.OrdinalIgnoreCase); } - public string GetTemplateFor(string fileExtension) + public string? GetTemplateFor(string fileExtension) { if (fileExtension == null) { throw new ArgumentNullException(nameof(fileExtension)); } - string result = null; + string? result = null; if (templates.TryGetValue(fileExtension, out var template) && template != null) { @@ -40,14 +40,14 @@ public string GetTemplateFor(string fileExtension) return result; } - public string GetAddFormatFor(string fileExtension) + public string? GetAddFormatFor(string fileExtension) { if (fileExtension == null) { throw new ArgumentNullException(nameof(fileExtension)); } - string result = null; + string? result = null; if (addFormats.TryGetValue(fileExtension, out var addFormat) && addFormat != null) { diff --git a/src/GitVersion.Core/VersionConverters/WixUpdater/WixVersionContext.cs b/src/GitVersion.Core/VersionConverters/WixUpdater/WixVersionContext.cs index adb793f3bc..8ef599a727 100644 --- a/src/GitVersion.Core/VersionConverters/WixUpdater/WixVersionContext.cs +++ b/src/GitVersion.Core/VersionConverters/WixUpdater/WixVersionContext.cs @@ -2,11 +2,11 @@ namespace GitVersion.VersionConverters.WixUpdater { public readonly struct WixVersionContext : IConverterContext { - public WixVersionContext(string workingDirectory) + public WixVersionContext(string? workingDirectory) { WorkingDirectory = workingDirectory; } - public string WorkingDirectory { get; } + public string? WorkingDirectory { get; } } } diff --git a/src/GitVersion.Core/VersionConverters/WixUpdater/WixVersionFileUpdater.cs b/src/GitVersion.Core/VersionConverters/WixUpdater/WixVersionFileUpdater.cs index 238779f084..4b97e76167 100644 --- a/src/GitVersion.Core/VersionConverters/WixUpdater/WixVersionFileUpdater.cs +++ b/src/GitVersion.Core/VersionConverters/WixUpdater/WixVersionFileUpdater.cs @@ -14,7 +14,7 @@ public class WixVersionFileUpdater : IWixVersionFileUpdater { private readonly IFileSystem fileSystem; private readonly ILog log; - private string wixVersionFile; + private string? wixVersionFile; public const string WixVersionFileName = "GitVersion_WixVersion.wxi"; public WixVersionFileUpdater(IFileSystem fileSystem, ILog log) diff --git a/src/GitVersion.LibGit2Sharp/Git/Branch.cs b/src/GitVersion.LibGit2Sharp/Git/Branch.cs index 20caa4d58c..2d7971ee54 100644 --- a/src/GitVersion.LibGit2Sharp/Git/Branch.cs +++ b/src/GitVersion.LibGit2Sharp/Git/Branch.cs @@ -5,7 +5,7 @@ namespace GitVersion { internal sealed class Branch : IBranch { - private static readonly LambdaEqualityHelper equalityHelper = new(x => x.Name.Canonical); + private static readonly LambdaEqualityHelper equalityHelper = new(x => x?.Name.Canonical); private static readonly LambdaKeyComparer comparerHelper = new(x => x.Name.Canonical); private readonly LibGit2Sharp.Branch innerBranch; diff --git a/src/GitVersion.LibGit2Sharp/Git/Commit.cs b/src/GitVersion.LibGit2Sharp/Git/Commit.cs index 1f12029e3d..2c7a82a803 100644 --- a/src/GitVersion.LibGit2Sharp/Git/Commit.cs +++ b/src/GitVersion.LibGit2Sharp/Git/Commit.cs @@ -7,7 +7,7 @@ namespace GitVersion { internal sealed class Commit : GitObject, ICommit { - private static readonly LambdaEqualityHelper equalityHelper = new(x => x.Id); + private static readonly LambdaEqualityHelper equalityHelper = new(x => x?.Id); private static readonly LambdaKeyComparer comparerHelper = new(x => x.Sha); private readonly LibGit2Sharp.Commit innerCommit; diff --git a/src/GitVersion.LibGit2Sharp/Git/CommitCollection.cs b/src/GitVersion.LibGit2Sharp/Git/CommitCollection.cs index 159d130064..989fe18c8b 100644 --- a/src/GitVersion.LibGit2Sharp/Git/CommitCollection.cs +++ b/src/GitVersion.LibGit2Sharp/Git/CommitCollection.cs @@ -21,7 +21,7 @@ public IEnumerator GetEnumerator() public IEnumerable GetCommitsPriorTo(DateTimeOffset olderThan) => this.SkipWhile(c => c.When > olderThan); public IEnumerable QueryBy(CommitFilter commitFilter) { - static object? GetReacheableFrom(object item) + static object? GetReacheableFrom(object? item) { return item switch { diff --git a/src/GitVersion.LibGit2Sharp/Git/GitObject.cs b/src/GitVersion.LibGit2Sharp/Git/GitObject.cs index 3f37234b00..30ca754e51 100644 --- a/src/GitVersion.LibGit2Sharp/Git/GitObject.cs +++ b/src/GitVersion.LibGit2Sharp/Git/GitObject.cs @@ -4,7 +4,7 @@ namespace GitVersion { internal class GitObject : IGitObject { - private static readonly LambdaEqualityHelper equalityHelper = new(x => x.Id); + private static readonly LambdaEqualityHelper equalityHelper = new(x => x?.Id); private static readonly LambdaKeyComparer comparerHelper = new(x => x.Sha); internal GitObject(LibGit2Sharp.GitObject innerGitObject) diff --git a/src/GitVersion.LibGit2Sharp/Git/GitRepository.cs b/src/GitVersion.LibGit2Sharp/Git/GitRepository.cs index eacd35e905..27c852e514 100644 --- a/src/GitVersion.LibGit2Sharp/Git/GitRepository.cs +++ b/src/GitVersion.LibGit2Sharp/Git/GitRepository.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using GitVersion.Extensions; using GitVersion.Helpers; using GitVersion.Logging; using LibGit2Sharp; @@ -30,7 +31,7 @@ internal GitRepository(IRepository repository) repositoryLazy = new Lazy(() => repository); } - private GitRepository(ILog log, Func getGitRootDirectory) + private GitRepository(ILog log, Func getGitRootDirectory) { this.log = log ?? throw new ArgumentNullException(nameof(log)); repositoryLazy = new Lazy(() => new Repository(getGitRootDirectory())); @@ -52,8 +53,11 @@ public void Dispose() public ICommitCollection Commits => new CommitCollection(repositoryInstance.Commits); public IRemoteCollection Remotes => new RemoteCollection(repositoryInstance.Network.Remotes); - public ICommit FindMergeBase(ICommit commit, ICommit otherCommit) + public ICommit FindMergeBase(ICommit? commit, ICommit? otherCommit) { + _ = commit ?? throw new ArgumentNullException(nameof(commit)); + _ = otherCommit ?? throw new ArgumentNullException(nameof(otherCommit)); + var retryAction = new RetryAction(); return retryAction.Execute(() => { @@ -111,7 +115,8 @@ public void CreateBranchForPullRequestBranch(AuthenticationInfo auth) log.Info($"Remote Refs:{System.Environment.NewLine}" + string.Join(System.Environment.NewLine, remoteTips.Select(r => r.CanonicalName))); - var headTipSha = Head.Tip?.Sha; + // FIX ME: What to do when Tip is null? + var headTipSha = Head.Tip!.Sha; var refs = remoteTips.Where(r => r.TargetIdentifier == headTipSha).ToList(); @@ -155,7 +160,7 @@ public void CreateBranchForPullRequestBranch(AuthenticationInfo auth) } }); } - public void Clone(string sourceUrl, string workdirPath, AuthenticationInfo auth) + public void Clone(string? sourceUrl, string? workdirPath, AuthenticationInfo auth) { try { @@ -192,14 +197,14 @@ public void Checkout(string commitOrBranchSpec) Commands.Checkout(repositoryInstance, commitOrBranchSpec); }); } - public void Fetch(string remote, IEnumerable refSpecs, AuthenticationInfo auth, string logMessage) + public void Fetch(string remote, IEnumerable refSpecs, AuthenticationInfo auth, string? logMessage) { RepositoryExtensions.RunSafe(() => { Commands.Fetch((Repository)repositoryInstance, remote, refSpecs, GetFetchOptions(auth), logMessage); }); } - internal static string Discover(string path) => Repository.Discover(path); + internal static string Discover(string? path) => Repository.Discover(path); private static FetchOptions GetFetchOptions(AuthenticationInfo auth) { @@ -218,7 +223,7 @@ private static CloneOptions GetCloneOptions(AuthenticationInfo auth) } private static CredentialsHandler? GetCredentialsProvider(AuthenticationInfo auth) { - if (!string.IsNullOrWhiteSpace(auth.Username)) + if (!StringExtensions.IsNullOrWhiteSpace(auth.Username)) { return (_, _, _) => new UsernamePasswordCredentials { diff --git a/src/GitVersion.LibGit2Sharp/Git/GitRepositoryInfo.cs b/src/GitVersion.LibGit2Sharp/Git/GitRepositoryInfo.cs index e03aefffdf..83f0def818 100644 --- a/src/GitVersion.LibGit2Sharp/Git/GitRepositoryInfo.cs +++ b/src/GitVersion.LibGit2Sharp/Git/GitRepositoryInfo.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Linq; +using GitVersion.Extensions; using Microsoft.Extensions.Options; namespace GitVersion @@ -13,7 +14,7 @@ internal class GitRepositoryInfo : IGitRepositoryInfo private readonly Lazy dynamicGitRepositoryPath; private readonly Lazy dotGitDirectory; private readonly Lazy gitRootPath; - private readonly Lazy projectRootDirectory; + private readonly Lazy projectRootDirectory; public GitRepositoryInfo(IOptions options) { @@ -22,18 +23,18 @@ public GitRepositoryInfo(IOptions options) dynamicGitRepositoryPath = new Lazy(GetDynamicGitRepositoryPath); dotGitDirectory = new Lazy(GetDotGitDirectory); gitRootPath = new Lazy(GetGitRootPath); - projectRootDirectory = new Lazy(GetProjectRootDirectory); + projectRootDirectory = new Lazy(GetProjectRootDirectory); } public string? DynamicGitRepositoryPath => dynamicGitRepositoryPath.Value; public string? DotGitDirectory => dotGitDirectory.Value; public string? GitRootPath => gitRootPath.Value; - public string ProjectRootDirectory => projectRootDirectory.Value; + public string? ProjectRootDirectory => projectRootDirectory.Value; private string? GetDynamicGitRepositoryPath() { var repositoryInfo = gitVersionOptions.RepositoryInfo; - if (string.IsNullOrWhiteSpace(repositoryInfo.TargetUrl)) return null; + if (StringExtensions.IsNullOrWhiteSpace(repositoryInfo.TargetUrl)) return null; var targetUrl = repositoryInfo.TargetUrl; var dynamicRepositoryClonePath = repositoryInfo.DynamicRepositoryClonePath; @@ -61,12 +62,12 @@ public GitRepositoryInfo(IOptions options) private string? GetDotGitDirectory() { - var gitDirectory = !string.IsNullOrWhiteSpace(DynamicGitRepositoryPath) + var gitDirectory = !StringExtensions.IsNullOrWhiteSpace(DynamicGitRepositoryPath) ? DynamicGitRepositoryPath : GitRepository.Discover(gitVersionOptions.WorkingDirectory); gitDirectory = gitDirectory?.TrimEnd('/', '\\'); - if (string.IsNullOrEmpty(gitDirectory)) + if (StringExtensions.IsNullOrEmpty(gitDirectory)) throw new DirectoryNotFoundException("Cannot find the .git directory"); return gitDirectory is null ? null : gitDirectory.Contains(Path.Combine(".git", "worktrees")) @@ -74,16 +75,16 @@ public GitRepositoryInfo(IOptions options) : gitDirectory; } - private string GetProjectRootDirectory() + private string? GetProjectRootDirectory() { - if (!string.IsNullOrWhiteSpace(DynamicGitRepositoryPath)) + if (!StringExtensions.IsNullOrWhiteSpace(DynamicGitRepositoryPath)) { return gitVersionOptions.WorkingDirectory; } var gitDirectory = GitRepository.Discover(gitVersionOptions.WorkingDirectory); - if (string.IsNullOrEmpty(gitDirectory)) + if (StringExtensions.IsNullOrEmpty(gitDirectory)) throw new DirectoryNotFoundException("Cannot find the .git directory"); return new GitRepository(gitDirectory).WorkingDirectory; @@ -91,7 +92,7 @@ private string GetProjectRootDirectory() private string? GetGitRootPath() { - var isDynamicRepo = !string.IsNullOrWhiteSpace(DynamicGitRepositoryPath); + var isDynamicRepo = !StringExtensions.IsNullOrWhiteSpace(DynamicGitRepositoryPath); var rootDirectory = isDynamicRepo ? DotGitDirectory : ProjectRootDirectory; return rootDirectory; diff --git a/src/GitVersion.LibGit2Sharp/Git/ObjectId.cs b/src/GitVersion.LibGit2Sharp/Git/ObjectId.cs index e323545a3f..3bc9286547 100644 --- a/src/GitVersion.LibGit2Sharp/Git/ObjectId.cs +++ b/src/GitVersion.LibGit2Sharp/Git/ObjectId.cs @@ -4,7 +4,7 @@ namespace GitVersion { internal sealed class ObjectId : IObjectId { - private static readonly LambdaEqualityHelper equalityHelper = new(x => x.Sha); + private static readonly LambdaEqualityHelper equalityHelper = new(x => x?.Sha); private static readonly LambdaKeyComparer comparerHelper = new(x => x.Sha); private readonly LibGit2Sharp.ObjectId innerObjectId; diff --git a/src/GitVersion.LibGit2Sharp/Git/RefSpec.cs b/src/GitVersion.LibGit2Sharp/Git/RefSpec.cs index 0c6bd1af17..726e125214 100644 --- a/src/GitVersion.LibGit2Sharp/Git/RefSpec.cs +++ b/src/GitVersion.LibGit2Sharp/Git/RefSpec.cs @@ -4,7 +4,7 @@ namespace GitVersion { public class RefSpec : IRefSpec { - private static readonly LambdaEqualityHelper equalityHelper = new(x => x.Specification); + private static readonly LambdaEqualityHelper equalityHelper = new(x => x?.Specification); private static readonly LambdaKeyComparer comparerHelper = new(x => x.Specification); private readonly LibGit2Sharp.RefSpec innerRefSpec; diff --git a/src/GitVersion.LibGit2Sharp/Git/Reference.cs b/src/GitVersion.LibGit2Sharp/Git/Reference.cs index d4077d8732..589838e225 100644 --- a/src/GitVersion.LibGit2Sharp/Git/Reference.cs +++ b/src/GitVersion.LibGit2Sharp/Git/Reference.cs @@ -5,7 +5,7 @@ namespace GitVersion { internal sealed class Reference : IReference { - private static readonly LambdaEqualityHelper equalityHelper = new(x => x.Name.Canonical); + private static readonly LambdaEqualityHelper equalityHelper = new(x => x?.Name.Canonical); private static readonly LambdaKeyComparer comparerHelper = new(x => x.Name.Canonical); internal readonly LibGit2Sharp.Reference innerReference; diff --git a/src/GitVersion.LibGit2Sharp/Git/Remote.cs b/src/GitVersion.LibGit2Sharp/Git/Remote.cs index 8a2d9876c8..caec49b348 100644 --- a/src/GitVersion.LibGit2Sharp/Git/Remote.cs +++ b/src/GitVersion.LibGit2Sharp/Git/Remote.cs @@ -6,7 +6,7 @@ namespace GitVersion { internal sealed class Remote : IRemote { - private static readonly LambdaEqualityHelper equalityHelper = new(x => x.Name); + private static readonly LambdaEqualityHelper equalityHelper = new(x => x?.Name); private static readonly LambdaKeyComparer comparerHelper = new(x => x.Name); private readonly LibGit2Sharp.Remote innerRemote; diff --git a/src/GitVersion.LibGit2Sharp/Git/Tag.cs b/src/GitVersion.LibGit2Sharp/Git/Tag.cs index b280dba879..f385fac5e7 100644 --- a/src/GitVersion.LibGit2Sharp/Git/Tag.cs +++ b/src/GitVersion.LibGit2Sharp/Git/Tag.cs @@ -5,7 +5,7 @@ namespace GitVersion { internal sealed class Tag : ITag { - private static readonly LambdaEqualityHelper equalityHelper = new(x => x.Name.Canonical); + private static readonly LambdaEqualityHelper equalityHelper = new(x => x?.Name.Canonical); private static readonly LambdaKeyComparer comparerHelper = new(x => x.Name.Canonical); private readonly LibGit2Sharp.Tag innerTag; From c0eef653bb4062aff3e614e10e6878a95960eedf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Thu, 22 Jul 2021 09:13:58 +0200 Subject: [PATCH 43/79] Use new string extension as extension methods --- .../Helpers/ArgumentBuilder.cs | 10 +++++----- .../Helpers/GitVersionHelper.cs | 2 +- .../Helpers/ProgramFixture.cs | 4 ++-- src/GitVersion.App/ArgumentParser.cs | 8 ++++---- src/GitVersion.App/QuotedStringHelpers.cs | 2 +- .../DefaultConfigFileLocatorTests.cs | 4 ++-- src/GitVersion.Core/BuildAgents/AppVeyor.cs | 2 +- .../BuildAgents/AzurePipelines.cs | 2 +- .../BuildAgents/BuildAgentBase.cs | 2 +- src/GitVersion.Core/BuildAgents/CodeBuild.cs | 4 ++-- src/GitVersion.Core/BuildAgents/Drone.cs | 6 +++--- src/GitVersion.Core/BuildAgents/EnvRun.cs | 2 +- src/GitVersion.Core/BuildAgents/GitHubActions.cs | 2 +- src/GitVersion.Core/BuildAgents/Jenkins.cs | 2 +- src/GitVersion.Core/BuildAgents/MyGet.cs | 2 +- src/GitVersion.Core/BuildAgents/TeamCity.cs | 4 ++-- .../Configuration/ConfigExtensions.cs | 4 ++-- .../Configuration/ConfigFileLocator.cs | 4 ++-- .../Configuration/Init/SetConfig/SetBranchTag.cs | 2 +- .../Configuration/Init/SetNextVersion.cs | 2 +- .../Init/Wizard/ConfigInitWizardStep.cs | 2 +- src/GitVersion.Core/Core/GitPreparer.cs | 12 ++++++------ src/GitVersion.Core/Core/RepositoryStore.cs | 4 ++-- .../Extensions/StringExtensions.cs | 8 ++++---- src/GitVersion.Core/Helpers/ProcessHelper.cs | 2 +- src/GitVersion.Core/Model/GitVersionCacheKey.cs | 2 +- .../Model/VersionVariablesJsonNumberConverter.cs | 2 +- .../ConfigNextVersionVersionStrategy.cs | 5 +++-- .../Cache/GitVersionCacheKeyFactory.cs | 2 +- .../MainlineVersionCalculator.cs | 5 +++-- .../VersionCalculation/NextVersionCalculator.cs | 5 +++-- .../SemanticVersioning/SemanticVersion.cs | 6 +++--- .../SemanticVersionBuildMetaData.cs | 12 ++++++------ .../SemanticVersionExtensions.cs | 2 +- .../SemanticVersionFormatValues.cs | 2 +- .../SemanticVersionPreReleaseTag.cs | 10 +++++----- .../VersionCalculation/VariableProvider.cs | 6 +++--- .../AssemblyInfo/AssemblyInfoFileUpdater.cs | 16 ++++++++-------- .../AssemblyInfo/ProjectFileUpdater.cs | 12 ++++++------ src/GitVersion.LibGit2Sharp/Git/GitRepository.cs | 2 +- .../Git/GitRepositoryInfo.cs | 12 ++++++------ 41 files changed, 101 insertions(+), 98 deletions(-) diff --git a/src/GitVersion.App.Tests/Helpers/ArgumentBuilder.cs b/src/GitVersion.App.Tests/Helpers/ArgumentBuilder.cs index 7bf19bb74b..5fb69e3823 100644 --- a/src/GitVersion.App.Tests/Helpers/ArgumentBuilder.cs +++ b/src/GitVersion.App.Tests/Helpers/ArgumentBuilder.cs @@ -37,27 +37,27 @@ public override string ToString() arguments.AppendFormat(" /targetpath \"{0}\"", workingDirectory); - if (!StringExtensions.IsNullOrWhiteSpace(exec)) + if (!exec.IsNullOrWhiteSpace()) { arguments.AppendFormat(" /exec \"{0}\"", exec); } - if (!StringExtensions.IsNullOrWhiteSpace(execArgs)) + if (!execArgs.IsNullOrWhiteSpace()) { arguments.AppendFormat(" /execArgs \"{0}\"", execArgs); } - if (!StringExtensions.IsNullOrWhiteSpace(projectFile)) + if (!projectFile.IsNullOrWhiteSpace()) { arguments.AppendFormat(" /proj \"{0}\"", projectFile); } - if (!StringExtensions.IsNullOrWhiteSpace(projectArgs)) + if (!projectArgs.IsNullOrWhiteSpace()) { arguments.AppendFormat(" /projargs \"{0}\"", projectArgs); } - if (!StringExtensions.IsNullOrWhiteSpace(logFile)) + if (!logFile.IsNullOrWhiteSpace()) { arguments.AppendFormat(" /l \"{0}\"", logFile); } diff --git a/src/GitVersion.App.Tests/Helpers/GitVersionHelper.cs b/src/GitVersion.App.Tests/Helpers/GitVersionHelper.cs index 34fc061ae0..9a9182e83a 100644 --- a/src/GitVersion.App.Tests/Helpers/GitVersionHelper.cs +++ b/src/GitVersion.App.Tests/Helpers/GitVersionHelper.cs @@ -101,7 +101,7 @@ params KeyValuePair[] environments Console.WriteLine(); Console.WriteLine("-------------------------------------------------------"); - if (StringExtensions.IsNullOrWhiteSpace(arguments.LogFile) || !File.Exists(arguments.LogFile)) + if (arguments.LogFile.IsNullOrWhiteSpace() || !File.Exists(arguments.LogFile)) { return new ExecutionResults(exitCode, output.ToString(), null); } diff --git a/src/GitVersion.App.Tests/Helpers/ProgramFixture.cs b/src/GitVersion.App.Tests/Helpers/ProgramFixture.cs index 5b721a2c84..f6e89953f9 100644 --- a/src/GitVersion.App.Tests/Helpers/ProgramFixture.cs +++ b/src/GitVersion.App.Tests/Helpers/ProgramFixture.cs @@ -62,7 +62,7 @@ public async Task Run(params string[] args) // Create the application and override registrations. var program = new Program(builder => Overrides.ForEach(action => action(builder))); - if (!StringExtensions.IsNullOrWhiteSpace(workingDirectory)) + if (!workingDirectory.IsNullOrWhiteSpace()) { args = new[] { "-targetpath", workingDirectory }.Concat(args).ToArray(); } @@ -87,7 +87,7 @@ public VersionVariables OutputVariables { get { - if (StringExtensions.IsNullOrWhiteSpace(Output)) return null; + if (Output.IsNullOrWhiteSpace()) return null; var jsonStartIndex = Output.IndexOf("{", StringComparison.Ordinal); var jsonEndIndex = Output.IndexOf("}", StringComparison.Ordinal); diff --git a/src/GitVersion.App/ArgumentParser.cs b/src/GitVersion.App/ArgumentParser.cs index 684e5ff800..de992ef9f8 100644 --- a/src/GitVersion.App/ArgumentParser.cs +++ b/src/GitVersion.App/ArgumentParser.cs @@ -128,13 +128,13 @@ private void ParseSwitchArguments(Arguments arguments, NameValueCollection switc private void AddAuthentication(Arguments arguments) { var username = environment.GetEnvironmentVariable("GITVERSION_REMOTE_USERNAME"); - if (!StringExtensions.IsNullOrWhiteSpace(username)) + if (!username.IsNullOrWhiteSpace()) { arguments.Authentication.Username = username; } var password = environment.GetEnvironmentVariable("GITVERSION_REMOTE_PASSWORD"); - if (!StringExtensions.IsNullOrWhiteSpace(password)) + if (!password.IsNullOrWhiteSpace()) { arguments.Authentication.Password = password; } @@ -362,7 +362,7 @@ private static void ParseShowVariable(Arguments arguments, string value, string { string versionVariable = null; - if (!StringExtensions.IsNullOrWhiteSpace(value)) + if (!value.IsNullOrWhiteSpace()) { versionVariable = VersionVariables.AvailableVariables.SingleOrDefault(av => av.Equals(value.Replace("'", ""), StringComparison.CurrentCultureIgnoreCase)); } @@ -563,7 +563,7 @@ private static NameValueCollection CollectSwitchesAndValuesFromArguments(IList !StringExtensions.IsNullOrEmpty(argument)).ToArray(); + return splitted.Where(argument => !argument.IsNullOrEmpty()).ToArray(); } /// diff --git a/src/GitVersion.Core.Tests/Configuration/DefaultConfigFileLocatorTests.cs b/src/GitVersion.Core.Tests/Configuration/DefaultConfigFileLocatorTests.cs index 4a8985d67b..5f8a4b419e 100644 --- a/src/GitVersion.Core.Tests/Configuration/DefaultConfigFileLocatorTests.cs +++ b/src/GitVersion.Core.Tests/Configuration/DefaultConfigFileLocatorTests.cs @@ -220,9 +220,9 @@ public void ThrowsExceptionOnCustomYmlFileDoesNotExist() private string SetupConfigFileContent(string text, string fileName = null, string path = null) { - if (StringExtensions.IsNullOrEmpty(fileName)) fileName = configFileLocator.FilePath; + if (fileName.IsNullOrEmpty()) fileName = configFileLocator.FilePath; var filePath = fileName; - if (!StringExtensions.IsNullOrEmpty(path)) + if (!path.IsNullOrEmpty()) filePath = Path.Combine(path, filePath); fileSystem.WriteAllText(filePath, text); return filePath; diff --git a/src/GitVersion.Core/BuildAgents/AppVeyor.cs b/src/GitVersion.Core/BuildAgents/AppVeyor.cs index 0ef56d9c60..9b96e4b39e 100644 --- a/src/GitVersion.Core/BuildAgents/AppVeyor.cs +++ b/src/GitVersion.Core/BuildAgents/AppVeyor.cs @@ -70,7 +70,7 @@ private HttpClient GetHttpClient() public override string GetCurrentBranch(bool usingDynamicRepos) { var pullRequestBranchName = Environment.GetEnvironmentVariable("APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH"); - if (!StringExtensions.IsNullOrWhiteSpace(pullRequestBranchName)) + if (!pullRequestBranchName.IsNullOrWhiteSpace()) { return pullRequestBranchName; } diff --git a/src/GitVersion.Core/BuildAgents/AzurePipelines.cs b/src/GitVersion.Core/BuildAgents/AzurePipelines.cs index 93939226de..6b698b5e4e 100644 --- a/src/GitVersion.Core/BuildAgents/AzurePipelines.cs +++ b/src/GitVersion.Core/BuildAgents/AzurePipelines.cs @@ -38,7 +38,7 @@ public override string GenerateSetVersionMessage(VersionVariables variables) // For AzurePipelines, we'll get the Build Number and insert GitVersion variables where // specified var buildNumberEnv = Environment.GetEnvironmentVariable("BUILD_BUILDNUMBER"); - if (StringExtensions.IsNullOrWhiteSpace(buildNumberEnv)) + if (buildNumberEnv.IsNullOrWhiteSpace()) return variables.FullSemVer; var newBuildNumber = variables.Aggregate(buildNumberEnv, ReplaceVariables); diff --git a/src/GitVersion.Core/BuildAgents/BuildAgentBase.cs b/src/GitVersion.Core/BuildAgents/BuildAgentBase.cs index 68dfe61db4..21b84b4357 100644 --- a/src/GitVersion.Core/BuildAgents/BuildAgentBase.cs +++ b/src/GitVersion.Core/BuildAgents/BuildAgentBase.cs @@ -22,7 +22,7 @@ protected BuildAgentBase(IEnvironment environment, ILog log) public abstract string? GenerateSetVersionMessage(VersionVariables variables); public abstract string[] GenerateSetParameterMessage(string name, string value); - public virtual bool CanApplyToCurrentContext() => !StringExtensions.IsNullOrEmpty(Environment.GetEnvironmentVariable(EnvironmentVariable)); + public virtual bool CanApplyToCurrentContext() => !Environment.GetEnvironmentVariable(EnvironmentVariable).IsNullOrEmpty(); public virtual string? GetCurrentBranch(bool usingDynamicRepos) => null; diff --git a/src/GitVersion.Core/BuildAgents/CodeBuild.cs b/src/GitVersion.Core/BuildAgents/CodeBuild.cs index 23a2c7d999..35e0a71b89 100644 --- a/src/GitVersion.Core/BuildAgents/CodeBuild.cs +++ b/src/GitVersion.Core/BuildAgents/CodeBuild.cs @@ -42,7 +42,7 @@ public override string GetCurrentBranch(bool usingDynamicRepos) var currentBranch = Environment.GetEnvironmentVariable(WebHookEnvironmentVariableName); - if (StringExtensions.IsNullOrEmpty(currentBranch)) + if (currentBranch.IsNullOrEmpty()) { return Environment.GetEnvironmentVariable(SourceVersionEnvironmentVariableName); } @@ -60,6 +60,6 @@ public override void WriteIntegration(Action writer, VersionVariables v public override bool PreventFetch() => true; public override bool CanApplyToCurrentContext() - => !StringExtensions.IsNullOrEmpty(Environment.GetEnvironmentVariable(WebHookEnvironmentVariableName)) || !StringExtensions.IsNullOrEmpty(Environment.GetEnvironmentVariable(SourceVersionEnvironmentVariableName)); + => !Environment.GetEnvironmentVariable(WebHookEnvironmentVariableName).IsNullOrEmpty() || !Environment.GetEnvironmentVariable(SourceVersionEnvironmentVariableName).IsNullOrEmpty(); } } diff --git a/src/GitVersion.Core/BuildAgents/Drone.cs b/src/GitVersion.Core/BuildAgents/Drone.cs index 7ddaffc87b..155eb4374e 100644 --- a/src/GitVersion.Core/BuildAgents/Drone.cs +++ b/src/GitVersion.Core/BuildAgents/Drone.cs @@ -37,18 +37,18 @@ public override string GetCurrentBranch(bool usingDynamicRepos) // https://discourse.drone.io/t/getting-the-branch-a-pull-request-is-created-from/670 // Unfortunately, DRONE_REFSPEC isn't populated, however CI_COMMIT_REFSPEC can be used instead of. var pullRequestNumber = Environment.GetEnvironmentVariable("DRONE_PULL_REQUEST"); - if (!StringExtensions.IsNullOrWhiteSpace(pullRequestNumber)) + if (!pullRequestNumber.IsNullOrWhiteSpace()) { // DRONE_SOURCE_BRANCH is available in Drone 1.x.x version var sourceBranch = Environment.GetEnvironmentVariable("DRONE_SOURCE_BRANCH"); - if (!StringExtensions.IsNullOrWhiteSpace(sourceBranch)) + if (!sourceBranch.IsNullOrWhiteSpace()) return sourceBranch; // In drone lower than 1.x.x source branch can be parsed from CI_COMMIT_REFSPEC // CI_COMMIT_REFSPEC - {sourceBranch}:{destinationBranch} // https://github.com/drone/drone/issues/2222 var ciCommitRefSpec = Environment.GetEnvironmentVariable("CI_COMMIT_REFSPEC"); - if (!StringExtensions.IsNullOrWhiteSpace(ciCommitRefSpec)) + if (!ciCommitRefSpec.IsNullOrWhiteSpace()) { var colonIndex = ciCommitRefSpec.IndexOf(':'); if (colonIndex > 0) diff --git a/src/GitVersion.Core/BuildAgents/EnvRun.cs b/src/GitVersion.Core/BuildAgents/EnvRun.cs index f3caf490f1..069d5dba29 100644 --- a/src/GitVersion.Core/BuildAgents/EnvRun.cs +++ b/src/GitVersion.Core/BuildAgents/EnvRun.cs @@ -16,7 +16,7 @@ public EnvRun(IEnvironment environment, ILog log) : base(environment, log) public override bool CanApplyToCurrentContext() { var envRunDatabasePath = Environment.GetEnvironmentVariable(EnvironmentVariableName); - if (!StringExtensions.IsNullOrEmpty(envRunDatabasePath)) + if (!envRunDatabasePath.IsNullOrEmpty()) { if (!File.Exists(envRunDatabasePath)) { diff --git a/src/GitVersion.Core/BuildAgents/GitHubActions.cs b/src/GitVersion.Core/BuildAgents/GitHubActions.cs index 12357c7ca2..67c7b977f7 100644 --- a/src/GitVersion.Core/BuildAgents/GitHubActions.cs +++ b/src/GitVersion.Core/BuildAgents/GitHubActions.cs @@ -53,7 +53,7 @@ public override void WriteIntegration(System.Action writer, VersionVari using var streamWriter = File.AppendText(gitHubSetEnvFilePath); foreach (var variable in variables) { - if (!StringExtensions.IsNullOrEmpty(variable.Value)) + if (!variable.Value.IsNullOrEmpty()) { streamWriter.WriteLine($"GitVersion_{variable.Key}={variable.Value}"); } diff --git a/src/GitVersion.Core/BuildAgents/Jenkins.cs b/src/GitVersion.Core/BuildAgents/Jenkins.cs index 5dbd1e2d44..c442733fc0 100644 --- a/src/GitVersion.Core/BuildAgents/Jenkins.cs +++ b/src/GitVersion.Core/BuildAgents/Jenkins.cs @@ -44,7 +44,7 @@ public override string GetCurrentBranch(bool usingDynamicRepos) private bool IsPipelineAsCode() { - return !StringExtensions.IsNullOrEmpty(Environment.GetEnvironmentVariable("BRANCH_NAME")); + return !Environment.GetEnvironmentVariable("BRANCH_NAME").IsNullOrEmpty(); } public override bool PreventFetch() => true; diff --git a/src/GitVersion.Core/BuildAgents/MyGet.cs b/src/GitVersion.Core/BuildAgents/MyGet.cs index 1ef9653f21..5dd9646f30 100644 --- a/src/GitVersion.Core/BuildAgents/MyGet.cs +++ b/src/GitVersion.Core/BuildAgents/MyGet.cs @@ -19,7 +19,7 @@ public override bool CanApplyToCurrentContext() { var buildRunner = Environment.GetEnvironmentVariable(EnvironmentVariable); - return !StringExtensions.IsNullOrEmpty(buildRunner) + return !buildRunner.IsNullOrEmpty() && buildRunner.Equals("MyGet", StringComparison.InvariantCultureIgnoreCase); } diff --git a/src/GitVersion.Core/BuildAgents/TeamCity.cs b/src/GitVersion.Core/BuildAgents/TeamCity.cs index b163f337fb..9fab3ad0f9 100644 --- a/src/GitVersion.Core/BuildAgents/TeamCity.cs +++ b/src/GitVersion.Core/BuildAgents/TeamCity.cs @@ -19,7 +19,7 @@ public TeamCity(IEnvironment environment, ILog log) : base(environment, log) { var branchName = Environment.GetEnvironmentVariable("Git_Branch"); - if (StringExtensions.IsNullOrEmpty(branchName)) + if (branchName.IsNullOrEmpty()) { if (!usingDynamicRepos) { @@ -42,7 +42,7 @@ private void WriteBranchEnvVariableWarning() public override bool PreventFetch() { - return !StringExtensions.IsNullOrEmpty(Environment.GetEnvironmentVariable("Git_Branch")); + return !Environment.GetEnvironmentVariable("Git_Branch").IsNullOrEmpty(); } public override string[] GenerateSetParameterMessage(string name, string value) diff --git a/src/GitVersion.Core/Configuration/ConfigExtensions.cs b/src/GitVersion.Core/Configuration/ConfigExtensions.cs index aeec67bba5..1bb10b73bd 100644 --- a/src/GitVersion.Core/Configuration/ConfigExtensions.cs +++ b/src/GitVersion.Core/Configuration/ConfigExtensions.cs @@ -129,10 +129,10 @@ public static string GetBranchSpecificTag(this EffectiveConfiguration configurat log.Info("Using branch name to calculate version tag"); var branchName = branchNameOverride ?? branchFriendlyName; - if (!StringExtensions.IsNullOrWhiteSpace(configuration.BranchPrefixToTrim)) + if (!configuration.BranchPrefixToTrim.IsNullOrWhiteSpace()) { var branchNameTrimmed = branchName?.RegexReplace(configuration.BranchPrefixToTrim, string.Empty, RegexOptions.IgnoreCase); - branchName = StringExtensions.IsNullOrEmpty(branchNameTrimmed) ? branchName : branchNameTrimmed; + branchName = branchNameTrimmed.IsNullOrEmpty() ? branchName : branchNameTrimmed; } branchName = branchName?.RegexReplace("[^a-zA-Z0-9-]", "-"); diff --git a/src/GitVersion.Core/Configuration/ConfigFileLocator.cs b/src/GitVersion.Core/Configuration/ConfigFileLocator.cs index 899cd88f57..0fd59e89f2 100644 --- a/src/GitVersion.Core/Configuration/ConfigFileLocator.cs +++ b/src/GitVersion.Core/Configuration/ConfigFileLocator.cs @@ -15,7 +15,7 @@ public ConfigFileLocator(IFileSystem fileSystem, IOptions opt { this.fileSystem = fileSystem; var configFile = options?.Value.ConfigInfo.ConfigFile; - FilePath = !StringExtensions.IsNullOrWhiteSpace(configFile) ? configFile : DefaultFileName; + FilePath = !configFile.IsNullOrWhiteSpace() ? configFile : DefaultFileName; } public string FilePath { get; } @@ -59,7 +59,7 @@ public Config ReadConfig(string? workingDirectory) public void Verify(GitVersionOptions gitVersionOptions, IGitRepositoryInfo repositoryInfo) { - if (!StringExtensions.IsNullOrWhiteSpace(gitVersionOptions.RepositoryInfo.TargetUrl)) + if (!gitVersionOptions.RepositoryInfo.TargetUrl.IsNullOrWhiteSpace()) { // Assuming this is a dynamic repository. At this stage it's unsure whether we have // any .git info so we need to skip verification diff --git a/src/GitVersion.Core/Configuration/Init/SetConfig/SetBranchTag.cs b/src/GitVersion.Core/Configuration/Init/SetConfig/SetBranchTag.cs index b7089cb8d9..8e40b9121e 100644 --- a/src/GitVersion.Core/Configuration/Init/SetConfig/SetBranchTag.cs +++ b/src/GitVersion.Core/Configuration/Init/SetConfig/SetBranchTag.cs @@ -24,7 +24,7 @@ public SetBranchTag WithData(string? name, BranchConfig? branchConfig) protected override StepResult HandleResult(string? result, Queue steps, Config config, string workingDirectory) { - if (StringExtensions.IsNullOrWhiteSpace(result)) + if (result.IsNullOrWhiteSpace()) { return StepResult.InvalidResponseSelected(); } diff --git a/src/GitVersion.Core/Configuration/Init/SetNextVersion.cs b/src/GitVersion.Core/Configuration/Init/SetNextVersion.cs index 1c1e10971a..64f9c0d653 100644 --- a/src/GitVersion.Core/Configuration/Init/SetNextVersion.cs +++ b/src/GitVersion.Core/Configuration/Init/SetNextVersion.cs @@ -15,7 +15,7 @@ public SetNextVersion(IConsole console, IFileSystem fileSystem, ILog log, IConfi protected override StepResult HandleResult(string? result, Queue steps, Config config, string workingDirectory) { var editConfigStep = StepFactory.CreateStep()!; - if (StringExtensions.IsNullOrEmpty(result)) + if (result.IsNullOrEmpty()) { steps.Enqueue(editConfigStep); return StepResult.Ok(); diff --git a/src/GitVersion.Core/Configuration/Init/Wizard/ConfigInitWizardStep.cs b/src/GitVersion.Core/Configuration/Init/Wizard/ConfigInitWizardStep.cs index 232725ead9..e0e787feae 100644 --- a/src/GitVersion.Core/Configuration/Init/Wizard/ConfigInitWizardStep.cs +++ b/src/GitVersion.Core/Configuration/Init/Wizard/ConfigInitWizardStep.cs @@ -42,7 +42,7 @@ public bool Apply(Queue steps, Config config, string worki InvalidResponse(steps); return true; } - var resultWithDefaultApplied = StringExtensions.IsNullOrEmpty(input) ? DefaultResult : input; + var resultWithDefaultApplied = input.IsNullOrEmpty() ? DefaultResult : input; var stepResult = HandleResult(resultWithDefaultApplied, steps, config, workingDirectory); if (stepResult.InvalidResponse) { diff --git a/src/GitVersion.Core/Core/GitPreparer.cs b/src/GitVersion.Core/Core/GitPreparer.cs index c88b769daf..3a49316ccc 100644 --- a/src/GitVersion.Core/Core/GitPreparer.cs +++ b/src/GitVersion.Core/Core/GitPreparer.cs @@ -51,7 +51,7 @@ public void Prepare() log.Info($"Project root is: {projectRoot}"); log.Info($"DotGit directory is: {dotGitDirectory}"); - if (StringExtensions.IsNullOrEmpty(dotGitDirectory) || StringExtensions.IsNullOrEmpty(projectRoot)) + if (dotGitDirectory.IsNullOrEmpty() || projectRoot.IsNullOrEmpty()) { throw new Exception($"Failed to prepare or find the .git directory in path '{gitVersionOptions.WorkingDirectory}'."); } @@ -62,7 +62,7 @@ public void Prepare() private void PrepareInternal(bool normalizeGitDirectory, string? currentBranch, bool shouldCleanUpRemotes = false) { var gitVersionOptions = options.Value; - if (!StringExtensions.IsNullOrWhiteSpace(gitVersionOptions.RepositoryInfo.TargetUrl)) + if (!gitVersionOptions.RepositoryInfo.TargetUrl.IsNullOrWhiteSpace()) { CreateDynamicRepository(currentBranch); } @@ -87,7 +87,7 @@ private void PrepareInternal(bool normalizeGitDirectory, string? currentBranch, return targetBranch; } - var isDynamicRepository = !StringExtensions.IsNullOrWhiteSpace(gitVersionOptions.RepositoryInfo.DynamicRepositoryClonePath); + var isDynamicRepository = !gitVersionOptions.RepositoryInfo.DynamicRepositoryClonePath.IsNullOrWhiteSpace(); var currentBranch = buildAgent.GetCurrentBranch(isDynamicRepository) ?? targetBranch; log.Info("Branch from build environment: " + currentBranch); @@ -117,7 +117,7 @@ private void CleanupDuplicateOrigin() private void CreateDynamicRepository(string? targetBranch) { var gitVersionOptions = options.Value; - if (StringExtensions.IsNullOrWhiteSpace(targetBranch)) + if (targetBranch.IsNullOrWhiteSpace()) { throw new Exception("Dynamic Git repositories must have a target branch (/b)"); } @@ -218,7 +218,7 @@ private void NormalizeGitDirectory(bool noFetch, string? currentBranchName, bool // If no, go ahead and check out a new branch, using the known commit SHA as the pointer var localBranchesWhereCommitShaIsHead = repository.Branches.Where(b => !b.IsRemote && b.Tip?.Sha == headSha).ToList(); - var matchingCurrentBranch = !StringExtensions.IsNullOrEmpty(currentBranchName) + var matchingCurrentBranch = !currentBranchName.IsNullOrEmpty() ? localBranchesWhereCommitShaIsHead.SingleOrDefault(b => b.Name.Canonical.Replace("/heads/", "/") == currentBranchName.Replace("/heads/", "/")) : null; if (matchingCurrentBranch != null) @@ -352,7 +352,7 @@ public void EnsureLocalBranchExistsForCurrentBranch(IRemote? remote, string? cur throw new ArgumentNullException(nameof(remote)); } - if (StringExtensions.IsNullOrEmpty(currentBranch)) return; + if (currentBranch.IsNullOrEmpty()) return; var isRef = currentBranch.Contains("refs"); var isBranch = currentBranch.Contains("refs/heads"); diff --git a/src/GitVersion.Core/Core/RepositoryStore.cs b/src/GitVersion.Core/Core/RepositoryStore.cs index 029f17b8ba..e3d6bc02f0 100644 --- a/src/GitVersion.Core/Core/RepositoryStore.cs +++ b/src/GitVersion.Core/Core/RepositoryStore.cs @@ -98,7 +98,7 @@ public RepositoryStore(ILog log, IGitRepository repository) public ICommit? GetCurrentCommit(IBranch currentBranch, string? commitId) { ICommit? currentCommit = null; - if (!StringExtensions.IsNullOrWhiteSpace(commitId)) + if (!commitId.IsNullOrWhiteSpace()) { log.Info($"Searching for specific commit '{commitId}'"); @@ -174,7 +174,7 @@ public IBranch GetTargetBranch(string? targetBranchName) var desiredBranch = repository.Head; // Make sure the desired branch has been specified - if (!StringExtensions.IsNullOrEmpty(targetBranchName)) + if (!targetBranchName.IsNullOrEmpty()) { // There are some edge cases where HEAD is not pointing to the desired branch. // Therefore it's important to verify if 'currentBranch' is indeed the desired branch. diff --git a/src/GitVersion.Core/Extensions/StringExtensions.cs b/src/GitVersion.Core/Extensions/StringExtensions.cs index 5e4725232c..ab691c68b8 100644 --- a/src/GitVersion.Core/Extensions/StringExtensions.cs +++ b/src/GitVersion.Core/Extensions/StringExtensions.cs @@ -136,10 +136,10 @@ public static bool IsEquivalentTo(this string self, string? other) return string.Equals(self, other, StringComparison.OrdinalIgnoreCase); } - /// - public static bool IsNullOrEmpty([NotNullWhen(returnValue: false)] string? value) => string.IsNullOrEmpty(value); + /// + public static bool IsNullOrEmpty([NotNullWhen(returnValue: false)] this string? value) => string.IsNullOrEmpty(value); - /// - public static bool IsNullOrWhiteSpace([NotNullWhen(returnValue: false)] string? value) => string.IsNullOrWhiteSpace(value); + /// + public static bool IsNullOrWhiteSpace([NotNullWhen(returnValue: false)] this string? value) => string.IsNullOrWhiteSpace(value); } } diff --git a/src/GitVersion.Core/Helpers/ProcessHelper.cs b/src/GitVersion.Core/Helpers/ProcessHelper.cs index 2220ac4e0e..8b8f786129 100644 --- a/src/GitVersion.Core/Helpers/ProcessHelper.cs +++ b/src/GitVersion.Core/Helpers/ProcessHelper.cs @@ -82,7 +82,7 @@ public static class ProcessHelper // http://csharptest.net/532/using-processstart-to-capture-console-output/ public static int Run(Action output, Action errorOutput, TextReader? input, string exe, string args, string workingDirectory, params KeyValuePair[] environmentalVariables) { - if (StringExtensions.IsNullOrEmpty(exe)) + if (exe.IsNullOrEmpty()) throw new ArgumentNullException(nameof(exe)); if (output == null) throw new ArgumentNullException(nameof(output)); diff --git a/src/GitVersion.Core/Model/GitVersionCacheKey.cs b/src/GitVersion.Core/Model/GitVersionCacheKey.cs index 05ec2ad543..0315f266db 100644 --- a/src/GitVersion.Core/Model/GitVersionCacheKey.cs +++ b/src/GitVersion.Core/Model/GitVersionCacheKey.cs @@ -7,7 +7,7 @@ public class GitVersionCacheKey { public GitVersionCacheKey(string value) { - if (StringExtensions.IsNullOrEmpty(value)) + if (value.IsNullOrEmpty()) { throw new ArgumentNullException(nameof(value)); } diff --git a/src/GitVersion.Core/Model/VersionVariablesJsonNumberConverter.cs b/src/GitVersion.Core/Model/VersionVariablesJsonNumberConverter.cs index c293a62bb8..608e010c39 100644 --- a/src/GitVersion.Core/Model/VersionVariablesJsonNumberConverter.cs +++ b/src/GitVersion.Core/Model/VersionVariablesJsonNumberConverter.cs @@ -32,7 +32,7 @@ public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonS public override void Write(Utf8JsonWriter writer, [CanBeNull] string value, JsonSerializerOptions options) { - if (StringExtensions.IsNullOrWhiteSpace(value)) + if (value.IsNullOrWhiteSpace()) { writer.WriteNullValue(); } diff --git a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/ConfigNextVersionVersionStrategy.cs b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/ConfigNextVersionVersionStrategy.cs index d2e852b962..3b29998c61 100644 --- a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/ConfigNextVersionVersionStrategy.cs +++ b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/ConfigNextVersionVersionStrategy.cs @@ -17,9 +17,10 @@ public ConfigNextVersionVersionStrategy(Lazy versionContext) public override IEnumerable GetVersions() { - if (StringExtensions.IsNullOrEmpty(Context.Configuration?.NextVersion) || Context.IsCurrentCommitTagged) + var nextVersion = Context.Configuration?.NextVersion; + if (nextVersion.IsNullOrEmpty() || Context.IsCurrentCommitTagged) yield break; - var semanticVersion = SemanticVersion.Parse(Context.Configuration.NextVersion, Context.Configuration?.GitTagPrefix); + var semanticVersion = SemanticVersion.Parse(nextVersion, Context.Configuration?.GitTagPrefix); yield return new BaseVersion("NextVersion in GitVersion configuration file", false, semanticVersion, null, null); } } diff --git a/src/GitVersion.Core/VersionCalculation/Cache/GitVersionCacheKeyFactory.cs b/src/GitVersion.Core/VersionCalculation/Cache/GitVersionCacheKeyFactory.cs index 463f9df073..d4e2a813f9 100644 --- a/src/GitVersion.Core/VersionCalculation/Cache/GitVersionCacheKeyFactory.cs +++ b/src/GitVersion.Core/VersionCalculation/Cache/GitVersionCacheKeyFactory.cs @@ -198,7 +198,7 @@ private static string GetHash(params string[] textsToHash) private static string GetHash(string textToHash) { - if (StringExtensions.IsNullOrEmpty(textToHash)) + if (textToHash.IsNullOrEmpty()) { return string.Empty; } diff --git a/src/GitVersion.Core/VersionCalculation/MainlineVersionCalculator.cs b/src/GitVersion.Core/VersionCalculation/MainlineVersionCalculator.cs index 934a0235d2..eba07bfa8d 100644 --- a/src/GitVersion.Core/VersionCalculation/MainlineVersionCalculator.cs +++ b/src/GitVersion.Core/VersionCalculation/MainlineVersionCalculator.cs @@ -54,7 +54,8 @@ public SemanticVersion FindMainlineModeVersion(BaseVersion baseVersion) var mainlineCommitLog = repositoryStore.GetMainlineCommitLog(baseVersion.BaseVersionSource, mainlineTip).ToList(); var directCommits = new List(mainlineCommitLog.Count); - if (StringExtensions.IsNullOrEmpty(context.Configuration?.NextVersion)) + var nextVersion = context.Configuration?.NextVersion; + if (nextVersion.IsNullOrEmpty()) { // Scans commit log in reverse, aggregating merge commits foreach (var commit in mainlineCommitLog) @@ -73,7 +74,7 @@ public SemanticVersion FindMainlineModeVersion(BaseVersion baseVersion) mainlineVersion.BuildMetaData = CreateVersionBuildMetaData(mergeBase); // branches other than main always get a bump for the act of branching - if ((!context.CurrentBranch.Equals(mainline)) && (StringExtensions.IsNullOrEmpty(context.Configuration?.NextVersion))) + if (!context.CurrentBranch.Equals(mainline) && nextVersion.IsNullOrEmpty()) { var branchIncrement = FindMessageIncrement(null, context.CurrentCommit, mergeBase, mainlineCommitLog); log.Info($"Performing {branchIncrement} increment for current branch "); diff --git a/src/GitVersion.Core/VersionCalculation/NextVersionCalculator.cs b/src/GitVersion.Core/VersionCalculation/NextVersionCalculator.cs index 152ab8e9a2..3d7a780c47 100644 --- a/src/GitVersion.Core/VersionCalculation/NextVersionCalculator.cs +++ b/src/GitVersion.Core/VersionCalculation/NextVersionCalculator.cs @@ -76,9 +76,10 @@ public SemanticVersion FindVersion() } var hasPreReleaseTag = semver.PreReleaseTag?.HasTag() == true; - var branchConfigHasPreReleaseTagConfigured = !StringExtensions.IsNullOrEmpty(context.Configuration?.Tag); + var tag = context.Configuration?.Tag; + var branchConfigHasPreReleaseTagConfigured = !tag.IsNullOrEmpty(); #pragma warning disable CS8602 // Dereference of a possibly null reference. // context.Configuration.Tag not null when branchConfigHasPreReleaseTagConfigured is true - var preReleaseTagDoesNotMatchConfiguration = hasPreReleaseTag && branchConfigHasPreReleaseTagConfigured && semver.PreReleaseTag?.Name != context.Configuration.Tag; + var preReleaseTagDoesNotMatchConfiguration = hasPreReleaseTag && branchConfigHasPreReleaseTagConfigured && semver.PreReleaseTag?.Name != tag; #pragma warning restore CS8602 // Dereference of a possibly null reference. if (semver.PreReleaseTag?.HasTag() != true && branchConfigHasPreReleaseTagConfigured || preReleaseTagDoesNotMatchConfiguration) { diff --git a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs index 8eb08032a3..bf364b0a81 100644 --- a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs +++ b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs @@ -247,7 +247,7 @@ public override string ToString() /// public string ToString(string? format, IFormatProvider? formatProvider = null) { - if (StringExtensions.IsNullOrEmpty(format)) + if (format.IsNullOrEmpty()) format = "s"; if (formatProvider?.GetFormat(GetType()) is ICustomFormatter formatter) @@ -275,13 +275,13 @@ public string ToString(string? format, IFormatProvider? formatProvider = null) { var buildMetadata = BuildMetaData?.ToString(); - return !StringExtensions.IsNullOrEmpty(buildMetadata) ? $"{ToString("s")}+{buildMetadata}" : ToString("s"); + return !buildMetadata.IsNullOrEmpty() ? $"{ToString("s")}+{buildMetadata}" : ToString("s"); } case "i": { var buildMetadata = BuildMetaData?.ToString("f"); - return !StringExtensions.IsNullOrEmpty(buildMetadata) ? $"{ToString("s")}+{buildMetadata}" : ToString("s"); + return !buildMetadata.IsNullOrEmpty() ? $"{ToString("s")}+{buildMetadata}" : ToString("s"); } default: throw new ArgumentException($"Unrecognised format '{format}'", nameof(format)); diff --git a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionBuildMetaData.cs b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionBuildMetaData.cs index 8631ee7a80..8d259405e9 100644 --- a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionBuildMetaData.cs +++ b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionBuildMetaData.cs @@ -88,7 +88,7 @@ public string ToString(string? format, IFormatProvider? formatProvider = null) return formatter.Format(format, this, formatProvider); } - if (StringExtensions.IsNullOrEmpty(format)) + if (format.IsNullOrEmpty()) format = "b"; format = format.ToLower(); @@ -111,8 +111,8 @@ public string ToString(string? format, IFormatProvider? formatProvider = null) return format.ToLower() switch { "b" => CommitsSinceTag.ToString(), - "s" => $"{CommitsSinceTag}{(StringExtensions.IsNullOrEmpty(Sha) ? null : ".Sha." + Sha)}".TrimStart('.'), - "f" => $"{CommitsSinceTag}{(StringExtensions.IsNullOrEmpty(Branch) ? null : ".Branch." + FormatMetaDataPart(Branch))}{(StringExtensions.IsNullOrEmpty(Sha) ? null : ".Sha." + Sha)}{(StringExtensions.IsNullOrEmpty(OtherMetaData) ? null : "." + FormatMetaDataPart(OtherMetaData))}".TrimStart('.'), + "s" => $"{CommitsSinceTag}{(Sha.IsNullOrEmpty() ? null : ".Sha." + Sha)}".TrimStart('.'), + "f" => $"{CommitsSinceTag}{(Branch.IsNullOrEmpty() ? null : ".Branch." + FormatMetaDataPart(Branch))}{(Sha.IsNullOrEmpty() ? null : ".Sha." + Sha)}{(OtherMetaData.IsNullOrEmpty() ? null : "." + FormatMetaDataPart(OtherMetaData))}".TrimStart('.'), _ => throw new ArgumentException("Unrecognised format", nameof(format)) }; } @@ -140,7 +140,7 @@ public static implicit operator SemanticVersionBuildMetaData(string preReleaseTa public static SemanticVersionBuildMetaData Parse(string? buildMetaData) { var semanticVersionBuildMetaData = new SemanticVersionBuildMetaData(); - if (StringExtensions.IsNullOrEmpty(buildMetaData)) + if (buildMetaData.IsNullOrEmpty()) return semanticVersionBuildMetaData; var parsed = ParseRegex.Match(buildMetaData); @@ -157,7 +157,7 @@ public static SemanticVersionBuildMetaData Parse(string? buildMetaData) if (parsed.Groups["Sha"].Success) semanticVersionBuildMetaData.Sha = parsed.Groups["Sha"].Value; - if (parsed.Groups["Other"].Success && !StringExtensions.IsNullOrEmpty(parsed.Groups["Other"].Value)) + if (parsed.Groups["Other"].Success && !parsed.Groups["Other"].Value.IsNullOrEmpty()) semanticVersionBuildMetaData.OtherMetaData = parsed.Groups["Other"].Value.TrimStart('.'); return semanticVersionBuildMetaData; @@ -165,7 +165,7 @@ public static SemanticVersionBuildMetaData Parse(string? buildMetaData) private string FormatMetaDataPart(string value) { - if (!StringExtensions.IsNullOrEmpty(value)) + if (!value.IsNullOrEmpty()) value = Regex.Replace(value, "[^0-9A-Za-z-.]", "-"); return value; } diff --git a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionExtensions.cs b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionExtensions.cs index 960407f1ff..2ddb9786b2 100644 --- a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionExtensions.cs +++ b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionExtensions.cs @@ -7,7 +7,7 @@ public static class SemanticVersionExtensions { public static void OverrideVersionManuallyIfNeeded(this SemanticVersion version, EffectiveConfiguration configuration) { - if (!StringExtensions.IsNullOrEmpty(configuration.NextVersion) && SemanticVersion.TryParse(configuration.NextVersion, configuration.GitTagPrefix, out var manualNextVersion)) + if (!configuration.NextVersion.IsNullOrEmpty() && SemanticVersion.TryParse(configuration.NextVersion, configuration.GitTagPrefix, out var manualNextVersion)) { if (manualNextVersion > version) { diff --git a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionFormatValues.cs b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionFormatValues.cs index 2e5e7770b9..4555b6ad23 100644 --- a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionFormatValues.cs +++ b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionFormatValues.cs @@ -92,7 +92,7 @@ private string GetWeightedPreReleaseNumber() var weightedPreReleaseNumber = semver.PreReleaseTag?.HasTag() == true ? (semver.PreReleaseTag.Number + config.PreReleaseWeight).ToString() : null; - if (StringExtensions.IsNullOrEmpty(weightedPreReleaseNumber)) + if (weightedPreReleaseNumber.IsNullOrEmpty()) { return $"{config.TagPreReleaseWeight}"; } diff --git a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionPreReleaseTag.cs b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionPreReleaseTag.cs index f36bee347a..54c8123d9f 100644 --- a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionPreReleaseTag.cs +++ b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionPreReleaseTag.cs @@ -90,7 +90,7 @@ public static implicit operator SemanticVersionPreReleaseTag(string? preReleaseT public static SemanticVersionPreReleaseTag Parse(string? preReleaseTag) { - if (StringExtensions.IsNullOrEmpty(preReleaseTag)) + if (preReleaseTag.IsNullOrEmpty()) { return new SemanticVersionPreReleaseTag(); } @@ -149,7 +149,7 @@ public int CompareTo(SemanticVersionPreReleaseTag? other) return formatter.Format(format, this, formatProvider); } - if (StringExtensions.IsNullOrEmpty(format)) + if (format.IsNullOrEmpty()) format = "t"; format = format.ToLower(); @@ -171,7 +171,7 @@ public int CompareTo(SemanticVersionPreReleaseTag? other) return format switch { - "t" => (Number.HasValue ? StringExtensions.IsNullOrEmpty(Name) ? $"{Number}" : $"{Name}.{Number}" : Name), + "t" => (Number.HasValue ? Name.IsNullOrEmpty() ? $"{Number}" : $"{Name}.{Number}" : Name), "l" => (Number.HasValue ? FormatLegacy(GetLegacyName(), Number.Value.ToString()) : FormatLegacy(GetLegacyName())), _ => throw new ArgumentException("Unknown format", nameof(format)) }; @@ -191,7 +191,7 @@ private string FormatLegacy(string tag, string number = "") private string GetLegacyName() { - if (StringExtensions.IsNullOrEmpty(Name)) + if (Name.IsNullOrEmpty()) { return string.Empty; } @@ -201,7 +201,7 @@ private string GetLegacyName() public bool HasTag() { - return !StringExtensions.IsNullOrEmpty(Name) || (Number.HasValue && PromotedFromCommits != true); + return !Name.IsNullOrEmpty() || (Number.HasValue && PromotedFromCommits != true); } } } diff --git a/src/GitVersion.Core/VersionCalculation/VariableProvider.cs b/src/GitVersion.Core/VersionCalculation/VariableProvider.cs index 670a053cf6..797a7d3154 100644 --- a/src/GitVersion.Core/VersionCalculation/VariableProvider.cs +++ b/src/GitVersion.Core/VersionCalculation/VariableProvider.cs @@ -30,7 +30,7 @@ public VersionVariables GetVariablesFor(SemanticVersion semanticVersion, Effecti if (semanticVersion.PreReleaseTag?.HasTag() != true) { semanticVersion.PreReleaseTag!.Name = config.GetBranchSpecificTag(log, semanticVersion.BuildMetaData?.Branch, null); - if (StringExtensions.IsNullOrEmpty(semanticVersion.PreReleaseTag.Name)) + if (semanticVersion.PreReleaseTag.Name.IsNullOrEmpty()) { semanticVersion.PreReleaseTag.Name = config.ContinuousDeploymentFallbackTag; } @@ -38,7 +38,7 @@ public VersionVariables GetVariablesFor(SemanticVersion semanticVersion, Effecti } // Evaluate tag number pattern and append to prerelease tag, preserving build metadata - var appendTagNumberPattern = !StringExtensions.IsNullOrEmpty(config.TagNumberPattern) && semanticVersion.PreReleaseTag?.HasTag() == true; + var appendTagNumberPattern = !config.TagNumberPattern.IsNullOrEmpty() && semanticVersion.PreReleaseTag?.HasTag() == true; if (appendTagNumberPattern) { var match = Regex.Match(semanticVersion.BuildMetaData!.Branch, config.TagNumberPattern); @@ -129,7 +129,7 @@ private static void PromoteNumberOfCommitsToTagNumber(SemanticVersion semanticVe { string? formattedString; - if (StringExtensions.IsNullOrEmpty(formatString)) + if (formatString.IsNullOrEmpty()) { formattedString = defaultValue; } diff --git a/src/GitVersion.Core/VersionConverters/AssemblyInfo/AssemblyInfoFileUpdater.cs b/src/GitVersion.Core/VersionConverters/AssemblyInfo/AssemblyInfoFileUpdater.cs index 0eccd9f0ed..1d1f71ce10 100644 --- a/src/GitVersion.Core/VersionConverters/AssemblyInfo/AssemblyInfoFileUpdater.cs +++ b/src/GitVersion.Core/VersionConverters/AssemblyInfo/AssemblyInfoFileUpdater.cs @@ -49,13 +49,13 @@ public void Execute(VersionVariables variables, AssemblyInfoContext context) log.Info($"Found {assemblyInfoFiles.Count} files"); var assemblyVersion = variables.AssemblySemVer; - var assemblyVersionString = !StringExtensions.IsNullOrWhiteSpace(assemblyVersion) ? $"AssemblyVersion(\"{assemblyVersion}\")" : null; + var assemblyVersionString = !assemblyVersion.IsNullOrWhiteSpace() ? $"AssemblyVersion(\"{assemblyVersion}\")" : null; var assemblyInfoVersion = variables.InformationalVersion; - var assemblyInfoVersionString = !StringExtensions.IsNullOrWhiteSpace(assemblyInfoVersion) ? $"AssemblyInformationalVersion(\"{assemblyInfoVersion}\")" : null; + var assemblyInfoVersionString = !assemblyInfoVersion.IsNullOrWhiteSpace() ? $"AssemblyInformationalVersion(\"{assemblyInfoVersion}\")" : null; var assemblyFileVersion = variables.AssemblySemFileVer; - var assemblyFileVersionString = !StringExtensions.IsNullOrWhiteSpace(assemblyFileVersion) ? $"AssemblyFileVersion(\"{assemblyFileVersion}\")" : null; + var assemblyFileVersionString = !assemblyFileVersion.IsNullOrWhiteSpace() ? $"AssemblyFileVersion(\"{assemblyFileVersion}\")" : null; foreach (var assemblyInfoFile in assemblyInfoFiles) { @@ -79,17 +79,17 @@ public void Execute(VersionVariables variables, AssemblyInfoContext context) var fileContents = originalFileContents; var appendedAttributes = false; - if (!StringExtensions.IsNullOrWhiteSpace(assemblyVersion)) + if (!assemblyVersion.IsNullOrWhiteSpace()) { fileContents = ReplaceOrInsertAfterLastAssemblyAttributeOrAppend(assemblyVersionRegex, fileContents, assemblyVersionString, assemblyInfoFile.Extension, ref appendedAttributes); } - if (!StringExtensions.IsNullOrWhiteSpace(assemblyFileVersion)) + if (!assemblyFileVersion.IsNullOrWhiteSpace()) { fileContents = ReplaceOrInsertAfterLastAssemblyAttributeOrAppend(assemblyFileVersionRegex, fileContents, assemblyFileVersionString, assemblyInfoFile.Extension, ref appendedAttributes); } - if (!StringExtensions.IsNullOrWhiteSpace(assemblyInfoVersion)) + if (!assemblyInfoVersion.IsNullOrWhiteSpace()) { fileContents = ReplaceOrInsertAfterLastAssemblyAttributeOrAppend(assemblyInfoVersionRegex, fileContents, assemblyInfoVersionString, assemblyInfoFile.Extension, ref appendedAttributes); } @@ -164,7 +164,7 @@ private IEnumerable GetAssemblyInfoFiles(AssemblyInfoContext context) var ensureAssemblyInfo = context.EnsureAssemblyInfo; var assemblyInfoFileNames = new HashSet(context.AssemblyInfoFiles); - if (assemblyInfoFileNames.Any(x => !StringExtensions.IsNullOrWhiteSpace(x))) + if (assemblyInfoFileNames.Any(x => !x.IsNullOrWhiteSpace())) { foreach (var item in assemblyInfoFileNames) { @@ -205,7 +205,7 @@ private bool EnsureVersionAssemblyInfoFile(string fullPath, bool ensureAssemblyI var assemblyInfoSource = templateManager.GetTemplateFor(Path.GetExtension(fullPath)); - if (!StringExtensions.IsNullOrWhiteSpace(assemblyInfoSource)) + if (!assemblyInfoSource.IsNullOrWhiteSpace()) { var fileInfo = new FileInfo(fullPath); diff --git a/src/GitVersion.Core/VersionConverters/AssemblyInfo/ProjectFileUpdater.cs b/src/GitVersion.Core/VersionConverters/AssemblyInfo/ProjectFileUpdater.cs index d35016f6d2..d87d03ea77 100644 --- a/src/GitVersion.Core/VersionConverters/AssemblyInfo/ProjectFileUpdater.cs +++ b/src/GitVersion.Core/VersionConverters/AssemblyInfo/ProjectFileUpdater.cs @@ -74,22 +74,22 @@ public void Execute(VersionVariables variables, AssemblyInfoContext context) cleanupBackupTasks.Add(() => fileSystem.Delete(backupProjectFile)); - if (!StringExtensions.IsNullOrWhiteSpace(assemblyVersion)) + if (!assemblyVersion.IsNullOrWhiteSpace()) { UpdateProjectVersionElement(fileXml, AssemblyVersionElement, assemblyVersion); } - if (!StringExtensions.IsNullOrWhiteSpace(assemblyFileVersion)) + if (!assemblyFileVersion.IsNullOrWhiteSpace()) { UpdateProjectVersionElement(fileXml, FileVersionElement, assemblyFileVersion); } - if (!StringExtensions.IsNullOrWhiteSpace(assemblyInfoVersion)) + if (!assemblyInfoVersion.IsNullOrWhiteSpace()) { UpdateProjectVersionElement(fileXml, InformationalVersionElement, assemblyInfoVersion); } - if (!StringExtensions.IsNullOrWhiteSpace(packageVersion)) + if (!packageVersion.IsNullOrWhiteSpace()) { UpdateProjectVersionElement(fileXml, VersionElement, packageVersion); } @@ -183,7 +183,7 @@ private IEnumerable GetProjectFiles(AssemblyInfoContext context) var workingDirectory = context.WorkingDirectory; var assemblyInfoFileNames = new HashSet(context.AssemblyInfoFiles); - if (assemblyInfoFileNames.Any(x => !StringExtensions.IsNullOrWhiteSpace(x))) + if (assemblyInfoFileNames.Any(x => !x.IsNullOrWhiteSpace())) { foreach (var item in assemblyInfoFileNames) { @@ -212,7 +212,7 @@ private IEnumerable GetProjectFiles(AssemblyInfoContext context) private bool IsSupportedProjectFile(string fileName) { - if (StringExtensions.IsNullOrEmpty(fileName)) + if (fileName.IsNullOrEmpty()) { return false; } diff --git a/src/GitVersion.LibGit2Sharp/Git/GitRepository.cs b/src/GitVersion.LibGit2Sharp/Git/GitRepository.cs index 27c852e514..c0283ee8a7 100644 --- a/src/GitVersion.LibGit2Sharp/Git/GitRepository.cs +++ b/src/GitVersion.LibGit2Sharp/Git/GitRepository.cs @@ -223,7 +223,7 @@ private static CloneOptions GetCloneOptions(AuthenticationInfo auth) } private static CredentialsHandler? GetCredentialsProvider(AuthenticationInfo auth) { - if (!StringExtensions.IsNullOrWhiteSpace(auth.Username)) + if (!auth.Username.IsNullOrWhiteSpace()) { return (_, _, _) => new UsernamePasswordCredentials { diff --git a/src/GitVersion.LibGit2Sharp/Git/GitRepositoryInfo.cs b/src/GitVersion.LibGit2Sharp/Git/GitRepositoryInfo.cs index 83f0def818..611a77c6c8 100644 --- a/src/GitVersion.LibGit2Sharp/Git/GitRepositoryInfo.cs +++ b/src/GitVersion.LibGit2Sharp/Git/GitRepositoryInfo.cs @@ -34,7 +34,7 @@ public GitRepositoryInfo(IOptions options) private string? GetDynamicGitRepositoryPath() { var repositoryInfo = gitVersionOptions.RepositoryInfo; - if (StringExtensions.IsNullOrWhiteSpace(repositoryInfo.TargetUrl)) return null; + if (repositoryInfo.TargetUrl.IsNullOrWhiteSpace()) return null; var targetUrl = repositoryInfo.TargetUrl; var dynamicRepositoryClonePath = repositoryInfo.DynamicRepositoryClonePath; @@ -62,12 +62,12 @@ public GitRepositoryInfo(IOptions options) private string? GetDotGitDirectory() { - var gitDirectory = !StringExtensions.IsNullOrWhiteSpace(DynamicGitRepositoryPath) + var gitDirectory = !DynamicGitRepositoryPath.IsNullOrWhiteSpace() ? DynamicGitRepositoryPath : GitRepository.Discover(gitVersionOptions.WorkingDirectory); gitDirectory = gitDirectory?.TrimEnd('/', '\\'); - if (StringExtensions.IsNullOrEmpty(gitDirectory)) + if (gitDirectory.IsNullOrEmpty()) throw new DirectoryNotFoundException("Cannot find the .git directory"); return gitDirectory is null ? null : gitDirectory.Contains(Path.Combine(".git", "worktrees")) @@ -77,14 +77,14 @@ public GitRepositoryInfo(IOptions options) private string? GetProjectRootDirectory() { - if (!StringExtensions.IsNullOrWhiteSpace(DynamicGitRepositoryPath)) + if (!DynamicGitRepositoryPath.IsNullOrWhiteSpace()) { return gitVersionOptions.WorkingDirectory; } var gitDirectory = GitRepository.Discover(gitVersionOptions.WorkingDirectory); - if (StringExtensions.IsNullOrEmpty(gitDirectory)) + if (gitDirectory.IsNullOrEmpty()) throw new DirectoryNotFoundException("Cannot find the .git directory"); return new GitRepository(gitDirectory).WorkingDirectory; @@ -92,7 +92,7 @@ public GitRepositoryInfo(IOptions options) private string? GetGitRootPath() { - var isDynamicRepo = !StringExtensions.IsNullOrWhiteSpace(DynamicGitRepositoryPath); + var isDynamicRepo = !DynamicGitRepositoryPath.IsNullOrWhiteSpace(); var rootDirectory = isDynamicRepo ? DotGitDirectory : ProjectRootDirectory; return rootDirectory; From ff0df665d53e38b7a4f1cf200bb233e2d1c81f16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Thu, 22 Jul 2021 09:39:58 +0200 Subject: [PATCH 44/79] Ensure parameter is not nullable when function throws argument null --- .../Core/Abstractions/IRepositoryStore.cs | 4 ++-- src/GitVersion.Core/Core/RepositoryStore.cs | 10 +++++----- src/GitVersion.Core/Git/IGitRepository.cs | 2 +- .../VersionCalculation/BaseVersionCalculator.cs | 2 +- .../VersionCalculation/MainlineVersionCalculator.cs | 4 ++-- .../SemanticVersioning/SemanticVersion.cs | 8 ++++---- src/GitVersion.LibGit2Sharp/Git/GitRepository.cs | 2 +- 7 files changed, 16 insertions(+), 16 deletions(-) diff --git a/src/GitVersion.Core/Core/Abstractions/IRepositoryStore.cs b/src/GitVersion.Core/Core/Abstractions/IRepositoryStore.cs index 8ac1273a39..026311a06c 100644 --- a/src/GitVersion.Core/Core/Abstractions/IRepositoryStore.cs +++ b/src/GitVersion.Core/Core/Abstractions/IRepositoryStore.cs @@ -11,7 +11,7 @@ public interface IRepositoryStore /// Find the merge base of the two branches, i.e. the best common ancestor of the two branches' tips. /// ICommit? FindMergeBase(IBranch branch, IBranch? otherBranch); - ICommit FindMergeBase(ICommit? commit, ICommit? mainlineTip); + ICommit FindMergeBase(ICommit commit, ICommit mainlineTip); ICommit? GetCurrentCommit(IBranch currentBranch, string? commitId); ICommit GetBaseVersionSource(ICommit currentBranchTip); IEnumerable GetMainlineCommitLog(ICommit? baseVersionSource, ICommit? mainlineTip); @@ -26,7 +26,7 @@ public interface IRepositoryStore IEnumerable GetReleaseBranches(IEnumerable>? releaseBranchConfig); IEnumerable ExcludingBranches(IEnumerable branchesToExclude); IEnumerable GetBranchesContainingCommit(ICommit? commit, IEnumerable? branches = null, bool onlyTrackedBranches = false); - Dictionary> GetMainlineBranches(ICommit? commit, IEnumerable>? mainlineBranchConfigs); + Dictionary> GetMainlineBranches(ICommit commit, IEnumerable>? mainlineBranchConfigs); /// /// Find the commit where the given branch was branched from another branch. diff --git a/src/GitVersion.Core/Core/RepositoryStore.cs b/src/GitVersion.Core/Core/RepositoryStore.cs index e3d6bc02f0..d250d1c7d2 100644 --- a/src/GitVersion.Core/Core/RepositoryStore.cs +++ b/src/GitVersion.Core/Core/RepositoryStore.cs @@ -44,13 +44,13 @@ public RepositoryStore(ILog log, IGitRepository repository) { // Other branch tip is a forward merge var commitToFindCommonBase = otherBranch?.Tip; - var commit = branch.Tip; + var commit = branch.Tip!; if (commitToFindCommonBase?.Parents.Contains(commit) == true) { commitToFindCommonBase = otherBranch!.Tip!.Parents.First(); } - var findMergeBase = FindMergeBase(commit, commitToFindCommonBase); + var findMergeBase = FindMergeBase(commit, commitToFindCommonBase!); if (findMergeBase != null) { log.Info($"Found merge base of {findMergeBase}"); @@ -298,13 +298,13 @@ static IEnumerable InnerGetBranchesContainingCommit(ICommit commit, IEn } } - public Dictionary> GetMainlineBranches(ICommit? commit, IEnumerable>? mainlineBranchConfigs) + public Dictionary> GetMainlineBranches(ICommit commit, IEnumerable>? mainlineBranchConfigs) { return repository.Branches .Where(b => mainlineBranchConfigs?.Any(c => Regex.IsMatch(b.Name.Friendly, c.Value?.Regex)) == true) .Select(b => new { - MergeBase = FindMergeBase(b.Tip, commit), + MergeBase = FindMergeBase(b.Tip!, commit), Branch = b }) .Where(a => a.MergeBase != null) @@ -505,7 +505,7 @@ private ICommit GetForwardMerge(ICommit? commitToFindCommonBase, ICommit? findMe return commitCollection.FirstOrDefault(c => c.Parents.Contains(findMergeBase)); } - public ICommit FindMergeBase(ICommit? commit, ICommit? mainlineTip) => repository.FindMergeBase(commit, mainlineTip); + public ICommit FindMergeBase(ICommit commit, ICommit mainlineTip) => repository.FindMergeBase(commit, mainlineTip); public int GetNumberOfUncommittedChanges() => repository.GetNumberOfUncommittedChanges(); } diff --git a/src/GitVersion.Core/Git/IGitRepository.cs b/src/GitVersion.Core/Git/IGitRepository.cs index d6ec7ab2a4..376f463e89 100644 --- a/src/GitVersion.Core/Git/IGitRepository.cs +++ b/src/GitVersion.Core/Git/IGitRepository.cs @@ -12,7 +12,7 @@ public interface IGitRepository ICommitCollection Commits { get; } IRemoteCollection Remotes { get; } - ICommit FindMergeBase(ICommit? commit, ICommit? otherCommit); + ICommit FindMergeBase(ICommit commit, ICommit otherCommit); int GetNumberOfUncommittedChanges(); } } diff --git a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculator.cs b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculator.cs index a7e9279d1d..99ea0b601b 100644 --- a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculator.cs +++ b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculator.cs @@ -51,7 +51,7 @@ public BaseVersion GetBaseVersion() .ToList(); } - var maxVersion = versions.Aggregate((v1, v2) => v1.IncrementedVersion > v2.IncrementedVersion ? v1 : v2); + var maxVersion = versions.Aggregate((v1, v2) => v1.IncrementedVersion! > v2.IncrementedVersion! ? v1 : v2); var matchingVersionsOnceIncremented = versions .Where(b => b.Version?.BaseVersionSource != null && b.IncrementedVersion == maxVersion.IncrementedVersion) .ToList(); diff --git a/src/GitVersion.Core/VersionCalculation/MainlineVersionCalculator.cs b/src/GitVersion.Core/VersionCalculation/MainlineVersionCalculator.cs index eba07bfa8d..01266f52cd 100644 --- a/src/GitVersion.Core/VersionCalculation/MainlineVersionCalculator.cs +++ b/src/GitVersion.Core/VersionCalculation/MainlineVersionCalculator.cs @@ -126,7 +126,7 @@ private SemanticVersion AggregateMergeCommitIncrement(ICommit commit, List b.Value?.IsMainline == true).ToList(); - var mainlineBranches = repositoryStore.GetMainlineBranches(context.CurrentCommit, mainlineBranchConfigs); + var mainlineBranches = repositoryStore.GetMainlineBranches(context.CurrentCommit!, mainlineBranchConfigs); var allMainlines = mainlineBranches.Values.SelectMany(branches => branches.Select(b => b.Name.Friendly)); log.Info("Found possible mainline branches: " + string.Join(", ", allMainlines)); @@ -202,7 +202,7 @@ private IBranch GetMainline(ICommit? baseVersionSource) /// The best possible merge base between the current commit and that is not the child of a forward merge. private ICommit FindMergeBaseBeforeForwardMerge(ICommit? baseVersionSource, IBranch mainline, [NotNullWhen(true)] out ICommit? mainlineTip) { - var mergeBase = repositoryStore.FindMergeBase(context.CurrentCommit, mainline.Tip); + var mergeBase = repositoryStore.FindMergeBase(context.CurrentCommit!, mainline.Tip!); var mainlineCommitLog = repositoryStore.GetMainlineCommitLog(baseVersionSource, mainline.Tip).ToList(); // find the mainline commit effective for versioning the current branch diff --git a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs index bf364b0a81..b996957534 100644 --- a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs +++ b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs @@ -100,7 +100,7 @@ public override int GetHashCode() return !(v1 == v2); } - public static bool operator >(SemanticVersion? v1, SemanticVersion? v2) + public static bool operator >(SemanticVersion v1, SemanticVersion v2) { if (v1 == null) throw new ArgumentNullException(nameof(v1)); @@ -109,7 +109,7 @@ public override int GetHashCode() return v1.CompareTo(v2) > 0; } - public static bool operator >=(SemanticVersion? v1, SemanticVersion? v2) + public static bool operator >=(SemanticVersion v1, SemanticVersion v2) { if (v1 == null) throw new ArgumentNullException(nameof(v1)); @@ -118,7 +118,7 @@ public override int GetHashCode() return v1.CompareTo(v2) >= 0; } - public static bool operator <=(SemanticVersion? v1, SemanticVersion? v2) + public static bool operator <=(SemanticVersion v1, SemanticVersion v2) { if (v1 == null) throw new ArgumentNullException(nameof(v1)); @@ -128,7 +128,7 @@ public override int GetHashCode() return v1.CompareTo(v2) <= 0; } - public static bool operator <(SemanticVersion? v1, SemanticVersion? v2) + public static bool operator <(SemanticVersion v1, SemanticVersion v2) { if (v1 == null) throw new ArgumentNullException(nameof(v1)); diff --git a/src/GitVersion.LibGit2Sharp/Git/GitRepository.cs b/src/GitVersion.LibGit2Sharp/Git/GitRepository.cs index c0283ee8a7..f0653481d0 100644 --- a/src/GitVersion.LibGit2Sharp/Git/GitRepository.cs +++ b/src/GitVersion.LibGit2Sharp/Git/GitRepository.cs @@ -53,7 +53,7 @@ public void Dispose() public ICommitCollection Commits => new CommitCollection(repositoryInstance.Commits); public IRemoteCollection Remotes => new RemoteCollection(repositoryInstance.Network.Remotes); - public ICommit FindMergeBase(ICommit? commit, ICommit? otherCommit) + public ICommit FindMergeBase(ICommit commit, ICommit otherCommit) { _ = commit ?? throw new ArgumentNullException(nameof(commit)); _ = otherCommit ?? throw new ArgumentNullException(nameof(otherCommit)); From 8b69f778a691b7f147918bd1ccc07c5431419a9b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Thu, 22 Jul 2021 09:42:58 +0200 Subject: [PATCH 45/79] Fix expected-actual order in test assert --- .../IntegrationTests/ReleaseBranchScenarios.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/GitVersion.Core.Tests/IntegrationTests/ReleaseBranchScenarios.cs b/src/GitVersion.Core.Tests/IntegrationTests/ReleaseBranchScenarios.cs index 710fa0ebc9..245033d053 100644 --- a/src/GitVersion.Core.Tests/IntegrationTests/ReleaseBranchScenarios.cs +++ b/src/GitVersion.Core.Tests/IntegrationTests/ReleaseBranchScenarios.cs @@ -580,7 +580,7 @@ public void AssemblySemFileVerShouldBeWeightedByPreReleaseWeight() fixture.Checkout("release-2.0.0"); var variables = fixture.GetVersion(config); - Assert.AreEqual(variables.AssemblySemFileVer, "2.0.0.1001"); + Assert.AreEqual("2.0.0.1001", variables.AssemblySemFileVer); } [Test] @@ -599,7 +599,7 @@ public void AssemblySemFileVerShouldBeWeightedByDefaultPreReleaseWeight() fixture.Repository.CreateBranch("release-2.0.0"); fixture.Checkout("release-2.0.0"); var variables = fixture.GetVersion(config); - Assert.AreEqual(variables.AssemblySemFileVer, "2.0.0.30001"); + Assert.AreEqual("2.0.0.30001", variables.AssemblySemFileVer); } /// From 37e36131a631b9aa0ffa43869932de8f92a08b88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Thu, 22 Jul 2021 09:50:09 +0200 Subject: [PATCH 46/79] Simplify return condition --- src/GitVersion.LibGit2Sharp/Git/GitRepositoryInfo.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/GitVersion.LibGit2Sharp/Git/GitRepositoryInfo.cs b/src/GitVersion.LibGit2Sharp/Git/GitRepositoryInfo.cs index e03aefffdf..bf9084e2ec 100644 --- a/src/GitVersion.LibGit2Sharp/Git/GitRepositoryInfo.cs +++ b/src/GitVersion.LibGit2Sharp/Git/GitRepositoryInfo.cs @@ -69,7 +69,7 @@ public GitRepositoryInfo(IOptions options) if (string.IsNullOrEmpty(gitDirectory)) throw new DirectoryNotFoundException("Cannot find the .git directory"); - return gitDirectory is null ? null : gitDirectory.Contains(Path.Combine(".git", "worktrees")) + return gitDirectory?.Contains(Path.Combine(".git", "worktrees")) == true ? Directory.GetParent(Directory.GetParent(gitDirectory).FullName).FullName : gitDirectory; } From f73118db5d047526999ad83abeed4bcb90e07b69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Thu, 22 Jul 2021 14:20:32 +0200 Subject: [PATCH 47/79] GetEnvironmentVariable can return null --- src/GitVersion.Core/BuildAgents/AppVeyor.cs | 2 +- src/GitVersion.Core/BuildAgents/AzurePipelines.cs | 2 +- src/GitVersion.Core/BuildAgents/CodeBuild.cs | 2 +- src/GitVersion.Core/BuildAgents/Drone.cs | 2 +- src/GitVersion.Core/BuildAgents/GitHubActions.cs | 2 +- src/GitVersion.Core/BuildAgents/GitLabCi.cs | 2 +- src/GitVersion.Core/BuildAgents/Jenkins.cs | 2 +- src/GitVersion.Core/BuildAgents/SpaceAutomation.cs | 2 +- src/GitVersion.Core/Core/Abstractions/IEnvironment.cs | 2 +- src/GitVersion.Core/Core/Environment.cs | 2 +- 10 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/GitVersion.Core/BuildAgents/AppVeyor.cs b/src/GitVersion.Core/BuildAgents/AppVeyor.cs index 9b96e4b39e..a71b0efa3e 100644 --- a/src/GitVersion.Core/BuildAgents/AppVeyor.cs +++ b/src/GitVersion.Core/BuildAgents/AppVeyor.cs @@ -67,7 +67,7 @@ private HttpClient GetHttpClient() } - public override string GetCurrentBranch(bool usingDynamicRepos) + public override string? GetCurrentBranch(bool usingDynamicRepos) { var pullRequestBranchName = Environment.GetEnvironmentVariable("APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH"); if (!pullRequestBranchName.IsNullOrWhiteSpace()) diff --git a/src/GitVersion.Core/BuildAgents/AzurePipelines.cs b/src/GitVersion.Core/BuildAgents/AzurePipelines.cs index 6b698b5e4e..5bf8915558 100644 --- a/src/GitVersion.Core/BuildAgents/AzurePipelines.cs +++ b/src/GitVersion.Core/BuildAgents/AzurePipelines.cs @@ -26,7 +26,7 @@ public override string[] GenerateSetParameterMessage(string name, string value) }; } - public override string GetCurrentBranch(bool usingDynamicRepos) + public override string? GetCurrentBranch(bool usingDynamicRepos) { return Environment.GetEnvironmentVariable("BUILD_SOURCEBRANCH"); } diff --git a/src/GitVersion.Core/BuildAgents/CodeBuild.cs b/src/GitVersion.Core/BuildAgents/CodeBuild.cs index 35e0a71b89..aecacf1d99 100644 --- a/src/GitVersion.Core/BuildAgents/CodeBuild.cs +++ b/src/GitVersion.Core/BuildAgents/CodeBuild.cs @@ -37,7 +37,7 @@ public override string[] GenerateSetParameterMessage(string name, string value) }; } - public override string GetCurrentBranch(bool usingDynamicRepos) + public override string? GetCurrentBranch(bool usingDynamicRepos) { var currentBranch = Environment.GetEnvironmentVariable(WebHookEnvironmentVariableName); diff --git a/src/GitVersion.Core/BuildAgents/Drone.cs b/src/GitVersion.Core/BuildAgents/Drone.cs index 155eb4374e..b1291d8fa8 100644 --- a/src/GitVersion.Core/BuildAgents/Drone.cs +++ b/src/GitVersion.Core/BuildAgents/Drone.cs @@ -31,7 +31,7 @@ public override string[] GenerateSetParameterMessage(string name, string value) }; } - public override string GetCurrentBranch(bool usingDynamicRepos) + public override string? GetCurrentBranch(bool usingDynamicRepos) { // In Drone DRONE_BRANCH variable is equal to destination branch in case of pull request // https://discourse.drone.io/t/getting-the-branch-a-pull-request-is-created-from/670 diff --git a/src/GitVersion.Core/BuildAgents/GitHubActions.cs b/src/GitVersion.Core/BuildAgents/GitHubActions.cs index 67c7b977f7..1e5e4790d5 100644 --- a/src/GitVersion.Core/BuildAgents/GitHubActions.cs +++ b/src/GitVersion.Core/BuildAgents/GitHubActions.cs @@ -65,7 +65,7 @@ public override void WriteIntegration(System.Action writer, VersionVari } } - public override string GetCurrentBranch(bool usingDynamicRepos) + public override string? GetCurrentBranch(bool usingDynamicRepos) { return Environment.GetEnvironmentVariable("GITHUB_REF"); } diff --git a/src/GitVersion.Core/BuildAgents/GitLabCi.cs b/src/GitVersion.Core/BuildAgents/GitLabCi.cs index b8163dec7b..75fb7d98d8 100644 --- a/src/GitVersion.Core/BuildAgents/GitLabCi.cs +++ b/src/GitVersion.Core/BuildAgents/GitLabCi.cs @@ -36,7 +36,7 @@ public override string[] GenerateSetParameterMessage(string name, string value) }; } - public override string GetCurrentBranch(bool usingDynamicRepos) + public override string? GetCurrentBranch(bool usingDynamicRepos) { return Environment.GetEnvironmentVariable("CI_COMMIT_REF_NAME"); } diff --git a/src/GitVersion.Core/BuildAgents/Jenkins.cs b/src/GitVersion.Core/BuildAgents/Jenkins.cs index c442733fc0..7cdf30bbc0 100644 --- a/src/GitVersion.Core/BuildAgents/Jenkins.cs +++ b/src/GitVersion.Core/BuildAgents/Jenkins.cs @@ -35,7 +35,7 @@ public override string[] GenerateSetParameterMessage(string name, string value) }; } - public override string GetCurrentBranch(bool usingDynamicRepos) + public override string? GetCurrentBranch(bool usingDynamicRepos) { return IsPipelineAsCode() ? Environment.GetEnvironmentVariable("BRANCH_NAME") diff --git a/src/GitVersion.Core/BuildAgents/SpaceAutomation.cs b/src/GitVersion.Core/BuildAgents/SpaceAutomation.cs index 2e7ae6ae78..b5f3fedf1b 100644 --- a/src/GitVersion.Core/BuildAgents/SpaceAutomation.cs +++ b/src/GitVersion.Core/BuildAgents/SpaceAutomation.cs @@ -13,7 +13,7 @@ public SpaceAutomation(IEnvironment environment, ILog log) : base(environment, l protected override string EnvironmentVariable { get; } = EnvironmentVariableName; - public override string GetCurrentBranch(bool usingDynamicRepos) + public override string? GetCurrentBranch(bool usingDynamicRepos) { return Environment.GetEnvironmentVariable("JB_SPACE_GIT_BRANCH"); } diff --git a/src/GitVersion.Core/Core/Abstractions/IEnvironment.cs b/src/GitVersion.Core/Core/Abstractions/IEnvironment.cs index efa0114a8b..c3e0557a36 100644 --- a/src/GitVersion.Core/Core/Abstractions/IEnvironment.cs +++ b/src/GitVersion.Core/Core/Abstractions/IEnvironment.cs @@ -2,7 +2,7 @@ namespace GitVersion { public interface IEnvironment { - string GetEnvironmentVariable(string variableName); + string? GetEnvironmentVariable(string variableName); void SetEnvironmentVariable(string variableName, string value); } } diff --git a/src/GitVersion.Core/Core/Environment.cs b/src/GitVersion.Core/Core/Environment.cs index 0eb30eccc0..5e91f2be91 100644 --- a/src/GitVersion.Core/Core/Environment.cs +++ b/src/GitVersion.Core/Core/Environment.cs @@ -2,7 +2,7 @@ namespace GitVersion { public class Environment : IEnvironment { - public string GetEnvironmentVariable(string variableName) + public string? GetEnvironmentVariable(string variableName) { return System.Environment.GetEnvironmentVariable(variableName); } From d080958b872cb643c04dd4eabde7f626b84cd7dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Fri, 16 Jul 2021 18:40:53 +0200 Subject: [PATCH 48/79] Add Microsoft.CodeAnalysis.CSharp.CodeStyle --- src/GitTools.Testing/GitTools.Testing.csproj | 8 ++++++-- .../GitVersion.App.Tests.csproj | 6 +++++- src/GitVersion.App/GitVersion.App.csproj | 4 ++++ .../GitVersion.Core.Tests.csproj | 4 ++++ src/GitVersion.Core/GitVersion.Core.csproj | 4 ++++ .../GitVersion.LibGit2Sharp.csproj | 4 ++++ .../GitVersion.MsBuild.Tests.csproj | 4 ++++ src/GitVersion.MsBuild/GitVersion.MsBuild.csproj | 14 +++++++++----- 8 files changed, 40 insertions(+), 8 deletions(-) diff --git a/src/GitTools.Testing/GitTools.Testing.csproj b/src/GitTools.Testing/GitTools.Testing.csproj index 67ea6f149c..569a353c27 100644 --- a/src/GitTools.Testing/GitTools.Testing.csproj +++ b/src/GitTools.Testing/GitTools.Testing.csproj @@ -4,7 +4,11 @@ false - - + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/src/GitVersion.App.Tests/GitVersion.App.Tests.csproj b/src/GitVersion.App.Tests/GitVersion.App.Tests.csproj index 0b81e83d89..bf6100c6a3 100644 --- a/src/GitVersion.App.Tests/GitVersion.App.Tests.csproj +++ b/src/GitVersion.App.Tests/GitVersion.App.Tests.csproj @@ -6,7 +6,11 @@ - + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + diff --git a/src/GitVersion.App/GitVersion.App.csproj b/src/GitVersion.App/GitVersion.App.csproj index c98673eb24..544744355b 100644 --- a/src/GitVersion.App/GitVersion.App.csproj +++ b/src/GitVersion.App/GitVersion.App.csproj @@ -26,6 +26,10 @@ + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/src/GitVersion.Core.Tests/GitVersion.Core.Tests.csproj b/src/GitVersion.Core.Tests/GitVersion.Core.Tests.csproj index 5e6ed30613..7cf3f3778f 100644 --- a/src/GitVersion.Core.Tests/GitVersion.Core.Tests.csproj +++ b/src/GitVersion.Core.Tests/GitVersion.Core.Tests.csproj @@ -13,6 +13,10 @@ + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/src/GitVersion.Core/GitVersion.Core.csproj b/src/GitVersion.Core/GitVersion.Core.csproj index 8558d2c327..d39025a07d 100644 --- a/src/GitVersion.Core/GitVersion.Core.csproj +++ b/src/GitVersion.Core/GitVersion.Core.csproj @@ -14,6 +14,10 @@ + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/src/GitVersion.LibGit2Sharp/GitVersion.LibGit2Sharp.csproj b/src/GitVersion.LibGit2Sharp/GitVersion.LibGit2Sharp.csproj index 0fe8d0c06c..a04c027bd1 100644 --- a/src/GitVersion.LibGit2Sharp/GitVersion.LibGit2Sharp.csproj +++ b/src/GitVersion.LibGit2Sharp/GitVersion.LibGit2Sharp.csproj @@ -7,6 +7,10 @@ + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/src/GitVersion.MsBuild.Tests/GitVersion.MsBuild.Tests.csproj b/src/GitVersion.MsBuild.Tests/GitVersion.MsBuild.Tests.csproj index ce2aee7142..33f9923b58 100644 --- a/src/GitVersion.MsBuild.Tests/GitVersion.MsBuild.Tests.csproj +++ b/src/GitVersion.MsBuild.Tests/GitVersion.MsBuild.Tests.csproj @@ -10,6 +10,10 @@ + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/src/GitVersion.MsBuild/GitVersion.MsBuild.csproj b/src/GitVersion.MsBuild/GitVersion.MsBuild.csproj index ae207e1686..f31898deca 100644 --- a/src/GitVersion.MsBuild/GitVersion.MsBuild.csproj +++ b/src/GitVersion.MsBuild/GitVersion.MsBuild.csproj @@ -13,11 +13,15 @@ - - - - - + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + From a55feb4a31c64a0396cefebc03ba5230bd193bb1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Fri, 16 Jul 2021 18:53:18 +0200 Subject: [PATCH 49/79] Add default .editorconfig options for C# code style --- .editorconfig | 140 ++++++++++++++++++++++++++++++++++++++ src/Directory.Build.props | 8 +++ src/GitVersion.sln | 5 +- 3 files changed, 151 insertions(+), 2 deletions(-) diff --git a/.editorconfig b/.editorconfig index afcf2694ec..7a65df1482 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,4 +1,6 @@ # http://editorconfig.org + +# top-most EditorConfig file root = true [*] @@ -11,3 +13,141 @@ insert_final_newline = true [*.yml] indent_size = 2 + +### CSharp code style settings ### +[*.cs] +# Organize usings +dotnet_separate_import_directive_groups = false +dotnet_sort_system_directives_first = true + +# Avoid "this." and "Me." if not necessary +dotnet_style_qualification_for_field = false:silent +dotnet_style_qualification_for_property = false:silent +dotnet_style_qualification_for_method = false:silent +dotnet_style_qualification_for_event = false:silent + +# Use language keywords instead of framework type names for type references +dotnet_style_predefined_type_for_locals_parameters_members = true:warning +dotnet_style_predefined_type_for_member_access = true:warning + +# Parentheses preferences +dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent +dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent +dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent +dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent + +# Modifier preferences +dotnet_style_require_accessibility_modifiers = for_non_interface_members:warning + +# Field preferences +dotnet_style_readonly_field = true:warning + +# Parameter preferences +dotnet_code_quality_unused_parameters = all:warning + +# Expression-level preferences +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_explicit_tuple_names = true:suggestion +dotnet_style_null_propagation = true:suggestion +dotnet_style_object_initializer = true:suggestion +dotnet_style_prefer_auto_properties = true:silent +dotnet_style_prefer_compound_assignment = true:warning +dotnet_style_prefer_conditional_expression_over_assignment = true:silent +dotnet_style_prefer_conditional_expression_over_return = true:silent +dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion +dotnet_style_prefer_inferred_tuple_names = true:suggestion +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion +dotnet_style_prefer_simplified_interpolation = true:suggestion + +# Dispose rules (CA2000 and CA2213) ported to IDE analyzers. We already execute the CA rules on the repo, so disable the IDE ones. +dotnet_diagnostic.IDE0067.severity = none +dotnet_diagnostic.IDE0068.severity = none +dotnet_diagnostic.IDE0069.severity = none + +#### C# Coding Conventions #### + +# Prefer "var" everywhere +csharp_style_var_for_built_in_types = true:silent +csharp_style_var_when_type_is_apparent = true:silent +csharp_style_var_elsewhere = true:silent + +# Prefer method-like constructs to have a block body, except for lambdas +csharp_style_expression_bodied_methods = false:none +csharp_style_expression_bodied_constructors = false:none +csharp_style_expression_bodied_operators = false:none +csharp_style_expression_bodied_local_functions = false:none +csharp_style_expression_bodied_lambdas = true:none + +# Pattern matching preferences +csharp_style_pattern_matching_over_as_with_null_check = true:warning +csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion +csharp_style_prefer_switch_expression = true:suggestion + +# Null-checking preferences +csharp_style_conditional_delegate_call = true:warning + +# Modifier preferences +csharp_prefer_static_local_function = true:warning +csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:silent + +# Code-block preferences +csharp_prefer_braces = when_multiline:warning +csharp_prefer_simple_using_statement = true:warning + +# Expression-level preferences +csharp_style_unused_value_assignment_preference = discard_variable:warning +csharp_prefer_simple_default_expression = true:suggestion +csharp_style_deconstructed_variable_declaration = true:suggestion +csharp_style_inlined_variable_declaration = true:suggestion +csharp_style_pattern_local_over_anonymous_function = true:suggestion +csharp_style_prefer_index_operator = true:suggestion +csharp_style_prefer_range_operator = true:suggestion +csharp_style_throw_expression = true:suggestion +csharp_style_unused_value_expression_statement_preference = discard_variable:silent + +# 'using' directive preferences +csharp_using_directive_placement = outside_namespace:silent + +#### C# Formatting Rules #### + +# New line preferences +csharp_new_line_before_open_brace = all +csharp_new_line_before_else = true +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 +csharp_new_line_between_query_expression_clauses = true + +# Indentation preferences +csharp_indent_block_contents = true +csharp_indent_braces = false +csharp_indent_case_contents = true +csharp_indent_case_contents_when_block = true +csharp_indent_labels = no_change +csharp_indent_switch_labels = true + +# Space preferences +csharp_space_after_cast = false +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_after_comma = true +csharp_space_after_dot = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_after_semicolon_in_for_statement = true +csharp_space_around_binary_operators = before_and_after +csharp_space_around_declaration_statements = false +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_before_comma = false +csharp_space_before_dot = false +csharp_space_before_open_square_brackets = false +csharp_space_before_semicolon_in_for_statement = false +csharp_space_between_empty_square_brackets = false +csharp_space_between_method_call_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_declaration_name_and_open_parenthesis = false +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_parentheses = false +csharp_space_between_square_brackets = false diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 1528d94ebc..4a52b34715 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -74,4 +74,12 @@ + + + + true + + + + diff --git a/src/GitVersion.sln b/src/GitVersion.sln index 6121dc1f1f..2483132e4b 100644 --- a/src/GitVersion.sln +++ b/src/GitVersion.sln @@ -8,6 +8,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GitVersion.Core.Tests", "Gi EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{3EFFC5D6-88D0-49D9-BB53-E1B7EB49DD45}" ProjectSection(SolutionItems) = preProject + ..\.editorconfig = ..\.editorconfig ..\.gitattributes = ..\.gitattributes ..\.gitignore = ..\.gitignore ..\appveyor.yml = ..\appveyor.yml @@ -30,9 +31,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GitVersion.MsBuild", "GitVe EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GitVersion.MsBuild.Tests", "GitVersion.MsBuild.Tests\GitVersion.MsBuild.Tests.csproj", "{B35EF742-95D4-4E6A-B782-BE1C3E5CF9AE}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GitTools.Testing", "GitTools.Testing\GitTools.Testing.csproj", "{6138640B-5C05-4070-BE32-6B17BEFDF63C}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GitTools.Testing", "GitTools.Testing\GitTools.Testing.csproj", "{6138640B-5C05-4070-BE32-6B17BEFDF63C}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GitVersion.LibGit2Sharp", "GitVersion.LibGit2Sharp\GitVersion.LibGit2Sharp.csproj", "{093AFCF2-68F4-49B1-8173-7CB88467E783}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GitVersion.LibGit2Sharp", "GitVersion.LibGit2Sharp\GitVersion.LibGit2Sharp.csproj", "{093AFCF2-68F4-49B1-8173-7CB88467E783}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution From f72716727ade3f9fb94a029898408994edd7dfa9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Fri, 16 Jul 2021 18:54:24 +0200 Subject: [PATCH 50/79] Enforce `this.` qualifier for fields --- .editorconfig | 2 +- .../Fixtures/RepositoryFixtureBase.cs | 18 +-- .../Fixtures/SequenceDiagram.cs | 44 ++--- .../Internal/ProcessHelper.cs | 6 +- .../ArgumentParserOnBuildServerTests.cs | 4 +- .../ArgumentParserTests.cs | 124 +++++++-------- src/GitVersion.App.Tests/HelpWriterTests.cs | 4 +- .../Helpers/ArgumentBuilder.cs | 28 ++-- .../Helpers/ProgramFixture.cs | 18 +-- .../Helpers/TestConsoleAdapter.cs | 8 +- .../UpdateWixVersionFileTests.cs | 8 +- .../VersionWriterTests.cs | 6 +- src/GitVersion.App/ArgumentParser.cs | 12 +- src/GitVersion.App/Arguments.cs | 8 +- src/GitVersion.App/GitVersionApp.cs | 8 +- src/GitVersion.App/GitVersionExecutor.cs | 50 +++--- src/GitVersion.App/GlobbingResolver.cs | 4 +- src/GitVersion.App/HelpWriter.cs | 4 +- .../OverrideConfigOptionParser.cs | 10 +- src/GitVersion.App/Program.cs | 2 +- src/GitVersion.App/VersionWriter.cs | 2 +- .../BuildAgents/AzurePipelinesTests.cs | 24 +-- .../BuildAgents/BuildServerBaseTests.cs | 6 +- .../BuildAgents/CodeBuildTests.cs | 28 ++-- .../BuildAgents/ContinuaCiTests.cs | 4 +- .../BuildAgents/DroneTests.cs | 56 +++---- .../BuildAgents/EnvRunTests.cs | 24 +-- .../BuildAgents/GitHubActionsTests.cs | 56 +++---- .../BuildAgents/GitLabCiTests.cs | 14 +- .../BuildAgents/JenkinsTests.cs | 60 +++---- .../BuildAgents/MyGetTests.cs | 8 +- .../BuildAgents/SpaceAutomationTests.cs | 28 ++-- .../BuildAgents/TeamCityTests.cs | 6 +- .../Configuration/ConfigProviderTests.cs | 74 ++++----- .../DefaultConfigFileLocatorTests.cs | 110 ++++++------- .../Core/DynamicRepositoryTests.cs | 12 +- .../Core/GitVersionExecutorTests.cs | 70 ++++---- .../Core/GitVersionToolDirectoryTests.cs | 10 +- .../Core/RepositoryStoreTests.cs | 8 +- .../DocumentationTests.cs | 4 +- .../StringFormatWithExtensionTests.cs | 66 ++++---- .../Helpers/GitVersionContextBuilder.cs | 22 +-- .../Helpers/TestConsole.cs | 10 +- .../Helpers/TestEnvironment.cs | 6 +- .../Helpers/TestFileSystem.cs | 34 ++-- .../Helpers/TestLogAppender.cs | 2 +- .../Helpers/TestStream.cs | 26 +-- .../MainlineDevelopmentMode.cs | 120 +++++++------- .../Model/MergeMessageTests.cs | 34 ++-- .../BaseVersionCalculatorTests.cs | 8 +- .../TestBaseVersionCalculator.cs | 2 +- .../TestMainlineVersionCalculator.cs | 2 +- .../VariableProviderTests.cs | 30 ++-- .../AssemblyInfoFileUpdaterTests.cs | 88 +++++----- .../ProjectFileUpdaterTests.cs | 56 +++---- .../BuildAgents/BuildAgentBase.cs | 2 +- .../BuildAgents/BuildAgentResolver.cs | 6 +- src/GitVersion.Core/BuildAgents/CodeBuild.cs | 6 +- src/GitVersion.Core/BuildAgents/EnvRun.cs | 2 +- src/GitVersion.Core/BuildAgents/GitLabCi.cs | 6 +- src/GitVersion.Core/BuildAgents/Jenkins.cs | 6 +- src/GitVersion.Core/BuildAgents/TeamCity.cs | 2 +- .../BranchConfigurationCalculator.cs | 32 ++-- .../Configuration/ConfigFileLocator.cs | 12 +- .../Configuration/ConfigProvider.cs | 18 +-- .../Configuration/ConfigurationBuilder.cs | 4 +- .../Init/BuildServer/AppVeyorSetup.cs | 16 +- .../Init/BuildServer/AppveyorPublicPrivate.cs | 6 +- .../Init/BuildServer/SetupBuildScripts.cs | 4 +- .../Configuration/Init/EditConfigStep.cs | 14 +- .../AssemblyVersioningSchemeSetting.cs | 2 +- .../Init/SetConfig/ConfigureBranch.cs | 12 +- .../Init/SetConfig/ConfigureBranches.cs | 4 +- .../Init/SetConfig/GlobalModeSetting.cs | 12 +- .../Init/SetConfig/SetBranchIncrementMode.cs | 14 +- .../Init/SetConfig/SetBranchTag.cs | 12 +- .../Configuration/Init/SetNextVersion.cs | 2 +- .../Init/Wizard/ConfigInitStepFactory.cs | 2 +- .../Init/Wizard/ConfigInitWizard.cs | 4 +- .../Init/Wizard/ConfigInitWizardStep.cs | 28 ++-- .../Init/Wizard/PickBranchingStrategy1Step.cs | 6 +- .../Init/Wizard/PickBranchingStrategy2Step.cs | 10 +- .../Init/Wizard/PickBranchingStrategy3Step.cs | 10 +- .../Init/Wizard/PickBranchingStrategyStep.cs | 8 +- src/GitVersion.Core/Core/GitPreparer.cs | 150 +++++++++--------- .../Core/GitVersionCalculateTool.cs | 18 +-- .../Core/GitVersionContextFactory.cs | 14 +- .../Core/GitVersionOutputTool.cs | 28 ++-- src/GitVersion.Core/Core/RepositoryStore.cs | 104 ++++++------ .../Helpers/LambdaEqualityHelper.cs | 4 +- .../Helpers/LambdaKeyComparer.cs | 6 +- src/GitVersion.Core/Helpers/ProcessHelper.cs | 6 +- src/GitVersion.Core/Helpers/RetryAction.cs | 4 +- .../Logging/ConsoleAppender.cs | 8 +- src/GitVersion.Core/Logging/Disposable.cs | 4 +- src/GitVersion.Core/Logging/FileAppender.cs | 2 +- src/GitVersion.Core/Logging/Log.cs | 20 +-- .../Model/Configuration/Config.cs | 4 +- .../BaseVersionCalculator.cs | 20 +-- .../FallbackVersionStrategy.cs | 2 +- .../MergeMessageVersionStrategy.cs | 2 +- .../TaggedCommitVersionStrategy.cs | 10 +- .../TrackReleaseBranchesVersionStrategy.cs | 14 +- .../VersionInBranchNameVersionStrategy.cs | 2 +- .../VersionStrategyBase.cs | 2 +- .../Cache/GitVersionCache.cs | 28 ++-- .../Cache/GitVersionCacheKeyFactory.cs | 20 +-- .../MainlineVersionCalculator.cs | 46 +++--- .../MinDateVersionFilter.cs | 2 +- .../NextVersionCalculator.cs | 24 +-- .../SemanticVersioning/SemanticVersion.cs | 70 ++++---- .../SemanticVersionBuildMetaData.cs | 44 ++--- .../SemanticVersionFormatValues.cs | 62 ++++---- .../VersionCalculation/ShaVersionFilter.cs | 2 +- .../VersionCalculation/VariableProvider.cs | 6 +- .../AssemblyInfo/AssemblyInfoFileUpdater.cs | 60 +++---- .../AssemblyInfo/ProjectFileUpdater.cs | 46 +++--- .../GitVersionInfo/GitVersionInfoGenerator.cs | 10 +- .../OutputGenerator/OutputGenerator.cs | 10 +- .../VersionConverters/TemplateManager.cs | 10 +- .../WixUpdater/WixVersionFileUpdater.cs | 10 +- src/GitVersion.LibGit2Sharp/Git/Branch.cs | 10 +- .../Git/BranchCollection.cs | 8 +- src/GitVersion.LibGit2Sharp/Git/Commit.cs | 4 +- .../Git/CommitCollection.cs | 6 +- .../Git/GitRepository.cs | 24 +-- .../Git/GitRepositoryInfo.cs | 18 +-- src/GitVersion.LibGit2Sharp/Git/ObjectId.cs | 6 +- src/GitVersion.LibGit2Sharp/Git/RefSpec.cs | 10 +- .../Git/RefSpecCollection.cs | 4 +- src/GitVersion.LibGit2Sharp/Git/Reference.cs | 4 +- .../Git/ReferenceCollection.cs | 12 +- src/GitVersion.LibGit2Sharp/Git/Remote.cs | 8 +- .../Git/RemoteCollection.cs | 10 +- src/GitVersion.LibGit2Sharp/Git/Tag.cs | 8 +- .../Git/TagCollection.cs | 4 +- .../Helpers/MsBuildExeFixture.cs | 16 +- .../Helpers/MsBuildExeFixtureResult.cs | 2 +- .../Helpers/MsBuildTaskFixture.cs | 8 +- .../Helpers/MsBuildTaskFixtureResult.cs | 2 +- .../InvalidFileCheckerTests.cs | 62 ++++---- .../Mocks/MockEngine.cs | 18 +-- .../GitVersionTaskExecutor.cs | 4 +- .../Helpers/MsBuildAdapter.cs | 4 +- .../Helpers/MsBuildAppender.cs | 6 +- 145 files changed, 1436 insertions(+), 1436 deletions(-) diff --git a/.editorconfig b/.editorconfig index 7a65df1482..afeec6253f 100644 --- a/.editorconfig +++ b/.editorconfig @@ -21,7 +21,7 @@ dotnet_separate_import_directive_groups = false dotnet_sort_system_directives_first = true # Avoid "this." and "Me." if not necessary -dotnet_style_qualification_for_field = false:silent +dotnet_style_qualification_for_field = true:warning dotnet_style_qualification_for_property = false:silent dotnet_style_qualification_for_method = false:silent dotnet_style_qualification_for_event = false:silent diff --git a/src/GitTools.Testing/Fixtures/RepositoryFixtureBase.cs b/src/GitTools.Testing/Fixtures/RepositoryFixtureBase.cs index 5036680b74..3695789872 100644 --- a/src/GitTools.Testing/Fixtures/RepositoryFixtureBase.cs +++ b/src/GitTools.Testing/Fixtures/RepositoryFixtureBase.cs @@ -18,7 +18,7 @@ protected RepositoryFixtureBase(Func repoBuilder) protected RepositoryFixtureBase(IRepository repository) { - _sequenceDiagram = new SequenceDiagram(); + this._sequenceDiagram = new SequenceDiagram(); Repository = repository; Repository.Config.Set("user.name", "Test"); Repository.Config.Set("user.email", "test@email.com"); @@ -33,7 +33,7 @@ public string RepositoryPath public SequenceDiagram SequenceDiagram { - get { return _sequenceDiagram; } + get { return this._sequenceDiagram; } } /// @@ -53,10 +53,10 @@ public virtual void Dispose() e.Message); } - _sequenceDiagram.End(); + this._sequenceDiagram.End(); Console.WriteLine("**Visualisation of test:**"); Console.WriteLine(string.Empty); - Console.WriteLine(_sequenceDiagram.GetDiagram()); + Console.WriteLine(this._sequenceDiagram.GetDiagram()); } public void Checkout(string branch) @@ -77,20 +77,20 @@ public void MakeATaggedCommit(string tag) public void ApplyTag(string tag) { - _sequenceDiagram.ApplyTag(tag, Repository.Head.FriendlyName); + this._sequenceDiagram.ApplyTag(tag, Repository.Head.FriendlyName); Repository.ApplyTag(tag); } public void BranchTo(string branchName, string @as = null) { - _sequenceDiagram.BranchTo(branchName, Repository.Head.FriendlyName, @as); + this._sequenceDiagram.BranchTo(branchName, Repository.Head.FriendlyName, @as); var branch = Repository.CreateBranch(branchName); Commands.Checkout(Repository, branch); } public void BranchToFromTag(string branchName, string fromTag, string onBranch, string @as = null) { - _sequenceDiagram.BranchToFromTag(branchName, fromTag, onBranch, @as); + this._sequenceDiagram.BranchToFromTag(branchName, fromTag, onBranch, @as); var branch = Repository.CreateBranch(branchName); Commands.Checkout(Repository, branch); } @@ -98,7 +98,7 @@ public void BranchToFromTag(string branchName, string fromTag, string onBranch, public void MakeACommit() { var to = Repository.Head.FriendlyName; - _sequenceDiagram.MakeACommit(to); + this._sequenceDiagram.MakeACommit(to); Repository.MakeACommit(); } @@ -107,7 +107,7 @@ public void MakeACommit() /// public void MergeNoFF(string mergeSource) { - _sequenceDiagram.Merge(mergeSource, Repository.Head.FriendlyName); + this._sequenceDiagram.Merge(mergeSource, Repository.Head.FriendlyName); Repository.MergeNoFF(mergeSource, Generate.SignatureNow()); } diff --git a/src/GitTools.Testing/Fixtures/SequenceDiagram.cs b/src/GitTools.Testing/Fixtures/SequenceDiagram.cs index 85582ba210..911062f874 100644 --- a/src/GitTools.Testing/Fixtures/SequenceDiagram.cs +++ b/src/GitTools.Testing/Fixtures/SequenceDiagram.cs @@ -17,8 +17,8 @@ public class SequenceDiagram /// public SequenceDiagram() { - _diagramBuilder = new StringBuilder(); - _diagramBuilder.AppendLine("@startuml"); + this._diagramBuilder = new StringBuilder(); + this._diagramBuilder.AppendLine("@startuml"); } /// @@ -26,7 +26,7 @@ public SequenceDiagram() /// public void Activate(string branch) { - _diagramBuilder.AppendLineFormat("activate {0}", GetParticipant(branch)); + this._diagramBuilder.AppendLineFormat("activate {0}", GetParticipant(branch)); } /// @@ -34,7 +34,7 @@ public void Activate(string branch) /// public void Destroy(string branch) { - _diagramBuilder.AppendLineFormat("destroy {0}", GetParticipant(branch)); + this._diagramBuilder.AppendLineFormat("destroy {0}", GetParticipant(branch)); } /// @@ -42,11 +42,11 @@ public void Destroy(string branch) /// public void Participant(string participant, string @as = null) { - _participants.Add(participant, @as ?? participant); + this._participants.Add(participant, @as ?? participant); if (@as == null) - _diagramBuilder.AppendLineFormat("participant {0}", participant); + this._diagramBuilder.AppendLineFormat("participant {0}", participant); else - _diagramBuilder.AppendLineFormat("participant \"{0}\" as {1}", participant, @as); + this._diagramBuilder.AppendLineFormat("participant \"{0}\" as {1}", participant, @as); } /// @@ -54,7 +54,7 @@ public void Participant(string participant, string @as = null) /// public void Divider(string text) { - _diagramBuilder.AppendLineFormat("== {0} ==", text); + this._diagramBuilder.AppendLineFormat("== {0} ==", text); } /// @@ -62,7 +62,7 @@ public void Divider(string text) /// public void NoteOver(string noteText, string startParticipant, string endParticipant = null, string prefix = null, string color = null) { - _diagramBuilder.AppendLineFormat( + this._diagramBuilder.AppendLineFormat( prefix + @"note over {0}{1}{2} {3} end note", @@ -77,7 +77,7 @@ public void NoteOver(string noteText, string startParticipant, string endPartici /// public void ApplyTag(string tag, string toBranch) { - _diagramBuilder.AppendLineFormat("{0} -> {0}: tag {1}", GetParticipant(toBranch), tag); + this._diagramBuilder.AppendLineFormat("{0} -> {0}: tag {1}", GetParticipant(toBranch), tag); } /// @@ -85,13 +85,13 @@ public void ApplyTag(string tag, string toBranch) /// public void BranchTo(string branchName, string currentName, string @as) { - if (!_participants.ContainsKey(branchName)) + if (!this._participants.ContainsKey(branchName)) { - _diagramBuilder.Append("create "); + this._diagramBuilder.Append("create "); Participant(branchName, @as); } - _diagramBuilder.AppendLineFormat( + this._diagramBuilder.AppendLineFormat( "{0} -> {1}: branch from {2}", GetParticipant(currentName), GetParticipant(branchName), currentName); @@ -102,13 +102,13 @@ public void BranchTo(string branchName, string currentName, string @as) /// public void BranchToFromTag(string branchName, string fromTag, string onBranch, string @as) { - if (!_participants.ContainsKey(branchName)) + if (!this._participants.ContainsKey(branchName)) { - _diagramBuilder.Append("create "); + this._diagramBuilder.Append("create "); Participant(branchName, @as); } - _diagramBuilder.AppendLineFormat("{0} -> {1}: branch from tag ({2})", GetParticipant(onBranch), GetParticipant(branchName), fromTag); + this._diagramBuilder.AppendLineFormat("{0} -> {1}: branch from tag ({2})", GetParticipant(onBranch), GetParticipant(branchName), fromTag); } /// @@ -116,7 +116,7 @@ public void BranchToFromTag(string branchName, string fromTag, string onBranch, /// public void MakeACommit(string toParticipant) { - _diagramBuilder.AppendLineFormat("{0} -> {0}: commit", GetParticipant(toParticipant)); + this._diagramBuilder.AppendLineFormat("{0} -> {0}: commit", GetParticipant(toParticipant)); } /// @@ -124,13 +124,13 @@ public void MakeACommit(string toParticipant) /// public void Merge(string @from, string to) { - _diagramBuilder.AppendLineFormat("{0} -> {1}: merge", GetParticipant(@from), GetParticipant(to)); + this._diagramBuilder.AppendLineFormat("{0} -> {1}: merge", GetParticipant(@from), GetParticipant(to)); } string GetParticipant(string branch) { - if (_participants.ContainsKey(branch)) - return _participants[branch]; + if (this._participants.ContainsKey(branch)) + return this._participants[branch]; return branch; } @@ -140,7 +140,7 @@ string GetParticipant(string branch) /// public void End() { - _diagramBuilder.AppendLine("@enduml"); + this._diagramBuilder.AppendLine("@enduml"); } /// @@ -148,7 +148,7 @@ public void End() /// public string GetDiagram() { - return _diagramBuilder.ToString(); + return this._diagramBuilder.ToString(); } } } diff --git a/src/GitTools.Testing/Internal/ProcessHelper.cs b/src/GitTools.Testing/Internal/ProcessHelper.cs index 6d3650a863..71117c654f 100644 --- a/src/GitTools.Testing/Internal/ProcessHelper.cs +++ b/src/GitTools.Testing/Internal/ProcessHelper.cs @@ -182,11 +182,11 @@ public ChangeErrorMode(ErrorModes mode) { try { - oldMode = SetErrorMode((int)mode); + this.oldMode = SetErrorMode((int)mode); } catch (Exception ex) when (ex is EntryPointNotFoundException || ex is DllNotFoundException) { - oldMode = (int)mode; + this.oldMode = (int)mode; } } @@ -195,7 +195,7 @@ void IDisposable.Dispose() { try { - SetErrorMode(oldMode); + SetErrorMode(this.oldMode); } catch (Exception ex) when (ex is EntryPointNotFoundException || ex is DllNotFoundException) { diff --git a/src/GitVersion.App.Tests/ArgumentParserOnBuildServerTests.cs b/src/GitVersion.App.Tests/ArgumentParserOnBuildServerTests.cs index 64f65a61b8..f17ca02ab4 100644 --- a/src/GitVersion.App.Tests/ArgumentParserOnBuildServerTests.cs +++ b/src/GitVersion.App.Tests/ArgumentParserOnBuildServerTests.cs @@ -22,13 +22,13 @@ public void SetUp() services.AddSingleton(); services.AddSingleton(); }); - argumentParser = sp.GetService(); + this.argumentParser = sp.GetService(); } [Test] public void EmptyOnFetchDisabledBuildServerMeansNoFetchIsTrue() { - var arguments = argumentParser.ParseArguments(""); + var arguments = this.argumentParser.ParseArguments(""); arguments.NoFetch.ShouldBe(true); } diff --git a/src/GitVersion.App.Tests/ArgumentParserTests.cs b/src/GitVersion.App.Tests/ArgumentParserTests.cs index 4208d4c013..a9758c5513 100644 --- a/src/GitVersion.App.Tests/ArgumentParserTests.cs +++ b/src/GitVersion.App.Tests/ArgumentParserTests.cs @@ -26,14 +26,14 @@ public void SetUp() services.AddSingleton(); services.AddSingleton(); }); - environment = sp.GetService(); - argumentParser = sp.GetService(); + this.environment = sp.GetService(); + this.argumentParser = sp.GetService(); } [Test] public void EmptyMeansUseCurrentDirectory() { - var arguments = argumentParser.ParseArguments(""); + var arguments = this.argumentParser.ParseArguments(""); arguments.TargetPath.ShouldBe(System.Environment.CurrentDirectory); arguments.LogFilePath.ShouldBe(null); arguments.IsHelp.ShouldBe(false); @@ -42,7 +42,7 @@ public void EmptyMeansUseCurrentDirectory() [Test] public void SingleMeansUseAsTargetDirectory() { - var arguments = argumentParser.ParseArguments("path"); + var arguments = this.argumentParser.ParseArguments("path"); arguments.TargetPath.ShouldBe("path"); arguments.LogFilePath.ShouldBe(null); arguments.IsHelp.ShouldBe(false); @@ -51,7 +51,7 @@ public void SingleMeansUseAsTargetDirectory() [Test] public void NoPathAndLogfileShouldUseCurrentDirectoryTargetDirectory() { - var arguments = argumentParser.ParseArguments("-l logFilePath"); + var arguments = this.argumentParser.ParseArguments("-l logFilePath"); arguments.TargetPath.ShouldBe(System.Environment.CurrentDirectory); arguments.LogFilePath.ShouldBe("logFilePath"); arguments.IsHelp.ShouldBe(false); @@ -60,7 +60,7 @@ public void NoPathAndLogfileShouldUseCurrentDirectoryTargetDirectory() [Test] public void HelpSwitchTest() { - var arguments = argumentParser.ParseArguments("-h"); + var arguments = this.argumentParser.ParseArguments("-h"); Assert.IsNull(arguments.TargetPath); Assert.IsNull(arguments.LogFilePath); arguments.IsHelp.ShouldBe(true); @@ -69,7 +69,7 @@ public void HelpSwitchTest() [Test] public void VersionSwitchTest() { - var arguments = argumentParser.ParseArguments("-version"); + var arguments = this.argumentParser.ParseArguments("-version"); Assert.IsNull(arguments.TargetPath); Assert.IsNull(arguments.LogFilePath); arguments.IsVersion.ShouldBe(true); @@ -78,7 +78,7 @@ public void VersionSwitchTest() [Test] public void TargetDirectoryAndLogFilePathCanBeParsed() { - var arguments = argumentParser.ParseArguments("targetDirectoryPath -l logFilePath"); + var arguments = this.argumentParser.ParseArguments("targetDirectoryPath -l logFilePath"); arguments.TargetPath.ShouldBe("targetDirectoryPath"); arguments.LogFilePath.ShouldBe("logFilePath"); arguments.IsHelp.ShouldBe(false); @@ -87,7 +87,7 @@ public void TargetDirectoryAndLogFilePathCanBeParsed() [Test] public void UsernameAndPasswordCanBeParsed() { - var arguments = argumentParser.ParseArguments("targetDirectoryPath -u [username] -p [password]"); + var arguments = this.argumentParser.ParseArguments("targetDirectoryPath -u [username] -p [password]"); arguments.TargetPath.ShouldBe("targetDirectoryPath"); arguments.Authentication.Username.ShouldBe("[username]"); arguments.Authentication.Password.ShouldBe("[password]"); @@ -97,14 +97,14 @@ public void UsernameAndPasswordCanBeParsed() [Test] public void UnknownOutputShouldThrow() { - var exception = Assert.Throws(() => argumentParser.ParseArguments("targetDirectoryPath -output invalid_value")); + var exception = Assert.Throws(() => this.argumentParser.ParseArguments("targetDirectoryPath -output invalid_value")); exception.Message.ShouldBe("Value 'invalid_value' cannot be parsed as output type, please use 'json', 'file' or 'buildserver'"); } [Test] public void OutputDefaultsToJson() { - var arguments = argumentParser.ParseArguments("targetDirectoryPath"); + var arguments = this.argumentParser.ParseArguments("targetDirectoryPath"); arguments.Output.ShouldContain(OutputType.Json); arguments.Output.ShouldNotContain(OutputType.BuildServer); arguments.Output.ShouldNotContain(OutputType.File); @@ -113,7 +113,7 @@ public void OutputDefaultsToJson() [Test] public void OutputJsonCanBeParsed() { - var arguments = argumentParser.ParseArguments("targetDirectoryPath -output json"); + var arguments = this.argumentParser.ParseArguments("targetDirectoryPath -output json"); arguments.Output.ShouldContain(OutputType.Json); arguments.Output.ShouldNotContain(OutputType.BuildServer); arguments.Output.ShouldNotContain(OutputType.File); @@ -122,7 +122,7 @@ public void OutputJsonCanBeParsed() [Test] public void MultipleOutputJsonCanBeParsed() { - var arguments = argumentParser.ParseArguments("targetDirectoryPath -output json -output json"); + var arguments = this.argumentParser.ParseArguments("targetDirectoryPath -output json -output json"); arguments.Output.ShouldContain(OutputType.Json); arguments.Output.ShouldNotContain(OutputType.BuildServer); arguments.Output.ShouldNotContain(OutputType.File); @@ -131,7 +131,7 @@ public void MultipleOutputJsonCanBeParsed() [Test] public void OutputBuildserverCanBeParsed() { - var arguments = argumentParser.ParseArguments("targetDirectoryPath -output buildserver"); + var arguments = this.argumentParser.ParseArguments("targetDirectoryPath -output buildserver"); arguments.Output.ShouldContain(OutputType.BuildServer); arguments.Output.ShouldNotContain(OutputType.Json); arguments.Output.ShouldNotContain(OutputType.File); @@ -140,7 +140,7 @@ public void OutputBuildserverCanBeParsed() [Test] public void MultipleOutputBuildserverCanBeParsed() { - var arguments = argumentParser.ParseArguments("targetDirectoryPath -output buildserver -output buildserver"); + var arguments = this.argumentParser.ParseArguments("targetDirectoryPath -output buildserver -output buildserver"); arguments.Output.ShouldContain(OutputType.BuildServer); arguments.Output.ShouldNotContain(OutputType.Json); arguments.Output.ShouldNotContain(OutputType.File); @@ -149,7 +149,7 @@ public void MultipleOutputBuildserverCanBeParsed() [Test] public void OutputFileCanBeParsed() { - var arguments = argumentParser.ParseArguments("targetDirectoryPath -output file"); + var arguments = this.argumentParser.ParseArguments("targetDirectoryPath -output file"); arguments.Output.ShouldContain(OutputType.File); arguments.Output.ShouldNotContain(OutputType.BuildServer); arguments.Output.ShouldNotContain(OutputType.Json); @@ -158,7 +158,7 @@ public void OutputFileCanBeParsed() [Test] public void MultipleOutputFileCanBeParsed() { - var arguments = argumentParser.ParseArguments("targetDirectoryPath -output file -output file"); + var arguments = this.argumentParser.ParseArguments("targetDirectoryPath -output file -output file"); arguments.Output.ShouldContain(OutputType.File); arguments.Output.ShouldNotContain(OutputType.BuildServer); arguments.Output.ShouldNotContain(OutputType.Json); @@ -167,7 +167,7 @@ public void MultipleOutputFileCanBeParsed() [Test] public void OutputBuildserverAndJsonCanBeParsed() { - var arguments = argumentParser.ParseArguments("targetDirectoryPath -output buildserver -output json"); + var arguments = this.argumentParser.ParseArguments("targetDirectoryPath -output buildserver -output json"); arguments.Output.ShouldContain(OutputType.BuildServer); arguments.Output.ShouldContain(OutputType.Json); arguments.Output.ShouldNotContain(OutputType.File); @@ -176,7 +176,7 @@ public void OutputBuildserverAndJsonCanBeParsed() [Test] public void OutputBuildserverAndJsonAndFileCanBeParsed() { - var arguments = argumentParser.ParseArguments("targetDirectoryPath -output buildserver -output json -output file"); + var arguments = this.argumentParser.ParseArguments("targetDirectoryPath -output buildserver -output json -output file"); arguments.Output.ShouldContain(OutputType.BuildServer); arguments.Output.ShouldContain(OutputType.Json); arguments.Output.ShouldContain(OutputType.File); @@ -185,7 +185,7 @@ public void OutputBuildserverAndJsonAndFileCanBeParsed() [Test] public void MultipleArgsAndFlag() { - var arguments = argumentParser.ParseArguments("targetDirectoryPath -output buildserver -updateAssemblyInfo"); + var arguments = this.argumentParser.ParseArguments("targetDirectoryPath -output buildserver -updateAssemblyInfo"); arguments.Output.ShouldContain(OutputType.BuildServer); } @@ -193,7 +193,7 @@ public void MultipleArgsAndFlag() [TestCase("-output file -outputfile version.json", "version.json")] public void OutputFileArgumentCanBeParsed(string args, string outputFile) { - var arguments = argumentParser.ParseArguments(args); + var arguments = this.argumentParser.ParseArguments(args); arguments.Output.ShouldContain(OutputType.File); arguments.OutputFile.ShouldBe(outputFile); @@ -202,7 +202,7 @@ public void OutputFileArgumentCanBeParsed(string args, string outputFile) [Test] public void UrlAndBranchNameCanBeParsed() { - var arguments = argumentParser.ParseArguments("targetDirectoryPath -url http://github.com/Particular/GitVersion.git -b somebranch"); + var arguments = this.argumentParser.ParseArguments("targetDirectoryPath -url http://github.com/Particular/GitVersion.git -b somebranch"); arguments.TargetPath.ShouldBe("targetDirectoryPath"); arguments.TargetUrl.ShouldBe("http://github.com/Particular/GitVersion.git"); arguments.TargetBranch.ShouldBe("somebranch"); @@ -212,7 +212,7 @@ public void UrlAndBranchNameCanBeParsed() [Test] public void WrongNumberOfArgumentsShouldThrow() { - var exception = Assert.Throws(() => argumentParser.ParseArguments("targetDirectoryPath -l logFilePath extraArg")); + var exception = Assert.Throws(() => this.argumentParser.ParseArguments("targetDirectoryPath -l logFilePath extraArg")); exception.Message.ShouldBe("Could not parse command line parameter 'extraArg'."); } @@ -220,7 +220,7 @@ public void WrongNumberOfArgumentsShouldThrow() [TestCase("/invalid-argument")] public void UnknownArgumentsShouldThrow(string arguments) { - var exception = Assert.Throws(() => argumentParser.ParseArguments(arguments)); + var exception = Assert.Throws(() => this.argumentParser.ParseArguments(arguments)); exception.Message.ShouldStartWith("Could not parse command line parameter"); } @@ -233,7 +233,7 @@ public void UnknownArgumentsShouldThrow(string arguments) [TestCase("-updateAssemblyInfo Assembly.cs Assembly.cs -ensureassemblyinfo")] public void UpdateAssemblyInfoTrue(string command) { - var arguments = argumentParser.ParseArguments(command); + var arguments = this.argumentParser.ParseArguments(command); arguments.UpdateAssemblyInfo.ShouldBe(true); } @@ -243,7 +243,7 @@ public void UpdateAssemblyInfoTrue(string command) [TestCase("-updateProjectFiles")] public void UpdateProjectTrue(string command) { - var arguments = argumentParser.ParseArguments(command); + var arguments = this.argumentParser.ParseArguments(command); arguments.UpdateProjectFiles.ShouldBe(true); } @@ -251,21 +251,21 @@ public void UpdateProjectTrue(string command) [TestCase("-updateAssemblyInfo 0")] public void UpdateAssemblyInfoFalse(string command) { - var arguments = argumentParser.ParseArguments(command); + var arguments = this.argumentParser.ParseArguments(command); arguments.UpdateAssemblyInfo.ShouldBe(false); } [TestCase("-updateAssemblyInfo Assembly.cs Assembly1.cs -ensureassemblyinfo")] public void CreateMulitpleAssemblyInfoProtected(string command) { - var exception = Assert.Throws(() => argumentParser.ParseArguments(command)); + var exception = Assert.Throws(() => this.argumentParser.ParseArguments(command)); exception.Message.ShouldBe("Can't specify multiple assembly info files when using /ensureassemblyinfo switch, either use a single assembly info file or do not specify /ensureassemblyinfo and create assembly info files manually"); } [TestCase("-updateProjectFiles Assembly.csproj -ensureassemblyinfo")] public void UpdateProjectInfoWithEnsureAssemblyInfoProtected(string command) { - var exception = Assert.Throws(() => argumentParser.ParseArguments(command)); + var exception = Assert.Throws(() => this.argumentParser.ParseArguments(command)); exception.Message.ShouldBe("Cannot specify -ensureassemblyinfo with updateprojectfiles: please ensure your project file exists before attempting to update it"); } @@ -277,7 +277,7 @@ public void UpdateAssemblyInfoWithFilename() var assemblyFile = Path.Combine(repo.RepositoryPath, "CommonAssemblyInfo.cs"); using var file = File.Create(assemblyFile); - var arguments = argumentParser.ParseArguments($"-targetpath {repo.RepositoryPath} -updateAssemblyInfo CommonAssemblyInfo.cs"); + var arguments = this.argumentParser.ParseArguments($"-targetpath {repo.RepositoryPath} -updateAssemblyInfo CommonAssemblyInfo.cs"); arguments.UpdateAssemblyInfo.ShouldBe(true); arguments.UpdateAssemblyInfoFileName.Count.ShouldBe(1); arguments.UpdateAssemblyInfoFileName.ShouldContain(x => Path.GetFileName(x).Equals("CommonAssemblyInfo.cs")); @@ -294,7 +294,7 @@ public void UpdateAssemblyInfoWithMultipleFilenames() var assemblyFile2 = Path.Combine(repo.RepositoryPath, "VersionAssemblyInfo.cs"); using var file2 = File.Create(assemblyFile2); - var arguments = argumentParser.ParseArguments($"-targetpath {repo.RepositoryPath} -updateAssemblyInfo CommonAssemblyInfo.cs VersionAssemblyInfo.cs"); + var arguments = this.argumentParser.ParseArguments($"-targetpath {repo.RepositoryPath} -updateAssemblyInfo CommonAssemblyInfo.cs VersionAssemblyInfo.cs"); arguments.UpdateAssemblyInfo.ShouldBe(true); arguments.UpdateAssemblyInfoFileName.Count.ShouldBe(2); arguments.UpdateAssemblyInfoFileName.ShouldContain(x => Path.GetFileName(x).Equals("CommonAssemblyInfo.cs")); @@ -312,7 +312,7 @@ public void UpdateProjectFilesWithMultipleFilenames() var assemblyFile2 = Path.Combine(repo.RepositoryPath, "VersionAssemblyInfo.csproj"); using var file2 = File.Create(assemblyFile2); - var arguments = argumentParser.ParseArguments($"-targetpath {repo.RepositoryPath} -updateProjectFiles CommonAssemblyInfo.csproj VersionAssemblyInfo.csproj"); + var arguments = this.argumentParser.ParseArguments($"-targetpath {repo.RepositoryPath} -updateProjectFiles CommonAssemblyInfo.csproj VersionAssemblyInfo.csproj"); arguments.UpdateProjectFiles.ShouldBe(true); arguments.UpdateAssemblyInfoFileName.Count.ShouldBe(2); arguments.UpdateAssemblyInfoFileName.ShouldContain(x => Path.GetFileName(x).Equals("CommonAssemblyInfo.csproj")); @@ -335,7 +335,7 @@ public void UpdateAssemblyInfoWithMultipleFilenamesMatchingGlobbing() var assemblyFile3 = Path.Combine(subdir, "LocalAssemblyInfo.cs"); using var file3 = File.Create(assemblyFile3); - var arguments = argumentParser.ParseArguments($"-targetpath {repo.RepositoryPath} -updateAssemblyInfo **/*AssemblyInfo.cs"); + var arguments = this.argumentParser.ParseArguments($"-targetpath {repo.RepositoryPath} -updateAssemblyInfo **/*AssemblyInfo.cs"); arguments.UpdateAssemblyInfo.ShouldBe(true); arguments.UpdateAssemblyInfoFileName.Count.ShouldBe(3); arguments.UpdateAssemblyInfoFileName.ShouldContain(x => Path.GetFileName(x).Equals("CommonAssemblyInfo.cs")); @@ -354,7 +354,7 @@ public void UpdateAssemblyInfoWithRelativeFilename() var targetPath = Path.Combine(repo.RepositoryPath, "subdir1", "subdir2"); Directory.CreateDirectory(targetPath); - var arguments = argumentParser.ParseArguments($"-targetpath {targetPath} -updateAssemblyInfo ..\\..\\CommonAssemblyInfo.cs"); + var arguments = this.argumentParser.ParseArguments($"-targetpath {targetPath} -updateAssemblyInfo ..\\..\\CommonAssemblyInfo.cs"); arguments.UpdateAssemblyInfo.ShouldBe(true); arguments.UpdateAssemblyInfoFileName.Count.ShouldBe(1); arguments.UpdateAssemblyInfoFileName.ShouldContain(x => Path.GetFileName(x).Equals("CommonAssemblyInfo.cs")); @@ -363,14 +363,14 @@ public void UpdateAssemblyInfoWithRelativeFilename() [Test] public void OverrideconfigWithNoOptions() { - var arguments = argumentParser.ParseArguments("/overrideconfig"); + var arguments = this.argumentParser.ParseArguments("/overrideconfig"); arguments.OverrideConfig.ShouldBeNull(); } [TestCaseSource(nameof(OverrideconfigWithInvalidOptionTestData))] public string OverrideconfigWithInvalidOption(string options) { - var exception = Assert.Throws(() => argumentParser.ParseArguments($"/overrideconfig {options}")); + var exception = Assert.Throws(() => this.argumentParser.ParseArguments($"/overrideconfig {options}")); return exception.Message; } @@ -406,7 +406,7 @@ private static IEnumerable OverrideconfigWithInvalidOptionTestData [TestCaseSource(nameof(OverrideconfigWithSingleOptionTestData))] public void OverrideconfigWithSingleOptions(string options, Config expected) { - var arguments = argumentParser.ParseArguments($"/overrideconfig {options}"); + var arguments = this.argumentParser.ParseArguments($"/overrideconfig {options}"); arguments.OverrideConfig.ShouldBeEquivalentTo(expected); } @@ -564,7 +564,7 @@ private static IEnumerable OverrideconfigWithSingleOptionTestData( [TestCaseSource(nameof(OverrideconfigWithMultipleOptionsTestData))] public void OverrideconfigWithMultipleOptions(string options, Config expected) { - var arguments = argumentParser.ParseArguments(options); + var arguments = this.argumentParser.ParseArguments(options); arguments.OverrideConfig.ShouldBeEquivalentTo(expected); } @@ -603,56 +603,56 @@ private static IEnumerable OverrideconfigWithMultipleOptionsTestDa [Test] public void EnsureAssemblyInfoTrueWhenFound() { - var arguments = argumentParser.ParseArguments("-ensureAssemblyInfo"); + var arguments = this.argumentParser.ParseArguments("-ensureAssemblyInfo"); arguments.EnsureAssemblyInfo.ShouldBe(true); } [Test] public void EnsureAssemblyInfoTrue() { - var arguments = argumentParser.ParseArguments("-ensureAssemblyInfo true"); + var arguments = this.argumentParser.ParseArguments("-ensureAssemblyInfo true"); arguments.EnsureAssemblyInfo.ShouldBe(true); } [Test] public void EnsureAssemblyInfoFalse() { - var arguments = argumentParser.ParseArguments("-ensureAssemblyInfo false"); + var arguments = this.argumentParser.ParseArguments("-ensureAssemblyInfo false"); arguments.EnsureAssemblyInfo.ShouldBe(false); } [Test] public void DynamicRepoLocation() { - var arguments = argumentParser.ParseArguments("-dynamicRepoLocation c:\\foo\\"); + var arguments = this.argumentParser.ParseArguments("-dynamicRepoLocation c:\\foo\\"); arguments.DynamicRepositoryClonePath.ShouldBe("c:\\foo\\"); } [Test] public void CanLogToConsole() { - var arguments = argumentParser.ParseArguments("-l console"); + var arguments = this.argumentParser.ParseArguments("-l console"); arguments.LogFilePath.ShouldBe("console"); } [Test] public void NofetchTrueWhenDefined() { - var arguments = argumentParser.ParseArguments("-nofetch"); + var arguments = this.argumentParser.ParseArguments("-nofetch"); arguments.NoFetch.ShouldBe(true); } [Test] public void NonormilizeTrueWhenDefined() { - var arguments = argumentParser.ParseArguments("-nonormalize"); + var arguments = this.argumentParser.ParseArguments("-nonormalize"); arguments.NoNormalize.ShouldBe(true); } [Test] public void OtherArgumentsCanBeParsedBeforeNofetch() { - var arguments = argumentParser.ParseArguments("targetpath -nofetch "); + var arguments = this.argumentParser.ParseArguments("targetpath -nofetch "); arguments.TargetPath.ShouldBe("targetpath"); arguments.NoFetch.ShouldBe(true); } @@ -660,7 +660,7 @@ public void OtherArgumentsCanBeParsedBeforeNofetch() [Test] public void OtherArgumentsCanBeParsedBeforeNonormalize() { - var arguments = argumentParser.ParseArguments("targetpath -nonormalize"); + var arguments = this.argumentParser.ParseArguments("targetpath -nonormalize"); arguments.TargetPath.ShouldBe("targetpath"); arguments.NoNormalize.ShouldBe(true); } @@ -668,7 +668,7 @@ public void OtherArgumentsCanBeParsedBeforeNonormalize() [Test] public void OtherArgumentsCanBeParsedBeforeNocache() { - var arguments = argumentParser.ParseArguments("targetpath -nocache"); + var arguments = this.argumentParser.ParseArguments("targetpath -nocache"); arguments.TargetPath.ShouldBe("targetpath"); arguments.NoCache.ShouldBe(true); } @@ -681,7 +681,7 @@ public void OtherArgumentsCanBeParsedBeforeNocache() [TestCase("-nonormalize -nofetch -nocache")] public void SeveralSwitchesCanBeParsed(string commandLineArgs) { - var arguments = argumentParser.ParseArguments(commandLineArgs); + var arguments = this.argumentParser.ParseArguments(commandLineArgs); arguments.NoCache.ShouldBe(true); arguments.NoNormalize.ShouldBe(true); arguments.NoFetch.ShouldBe(true); @@ -690,14 +690,14 @@ public void SeveralSwitchesCanBeParsed(string commandLineArgs) [Test] public void LogPathCanContainForwardSlash() { - var arguments = argumentParser.ParseArguments("-l /some/path"); + var arguments = this.argumentParser.ParseArguments("-l /some/path"); arguments.LogFilePath.ShouldBe("/some/path"); } [Test] public void BooleanArgumentHandling() { - var arguments = argumentParser.ParseArguments("/nofetch /updateassemblyinfo true"); + var arguments = this.argumentParser.ParseArguments("/nofetch /updateassemblyinfo true"); arguments.NoFetch.ShouldBe(true); arguments.UpdateAssemblyInfo.ShouldBe(true); } @@ -705,7 +705,7 @@ public void BooleanArgumentHandling() [Test] public void NocacheTrueWhenDefined() { - var arguments = argumentParser.ParseArguments("-nocache"); + var arguments = this.argumentParser.ParseArguments("-nocache"); arguments.NoCache.ShouldBe(true); } @@ -719,11 +719,11 @@ public void CheckVerbosityParsing(string command, bool shouldThrow, Verbosity ex { if (shouldThrow) { - Assert.Throws(() => argumentParser.ParseArguments(command)); + Assert.Throws(() => this.argumentParser.ParseArguments(command)); } else { - var arguments = argumentParser.ParseArguments(command); + var arguments = this.argumentParser.ParseArguments(command); arguments.Verbosity.ShouldBe(expectedVerbosity); } } @@ -731,32 +731,32 @@ public void CheckVerbosityParsing(string command, bool shouldThrow, Verbosity ex [Test] public void EmptyArgumentsRemoteUsernameDefinedSetsUsername() { - environment.SetEnvironmentVariable("GITVERSION_REMOTE_USERNAME", "value"); - var arguments = argumentParser.ParseArguments(string.Empty); + this.environment.SetEnvironmentVariable("GITVERSION_REMOTE_USERNAME", "value"); + var arguments = this.argumentParser.ParseArguments(string.Empty); arguments.Authentication.Username.ShouldBe("value"); } [Test] public void EmptyArgumentsRemotePasswordDefinedSetsPassword() { - environment.SetEnvironmentVariable("GITVERSION_REMOTE_PASSWORD", "value"); - var arguments = argumentParser.ParseArguments(string.Empty); + this.environment.SetEnvironmentVariable("GITVERSION_REMOTE_PASSWORD", "value"); + var arguments = this.argumentParser.ParseArguments(string.Empty); arguments.Authentication.Password.ShouldBe("value"); } [Test] public void ArbitraryArgumentsRemoteUsernameDefinedSetsUsername() { - environment.SetEnvironmentVariable("GITVERSION_REMOTE_USERNAME", "value"); - var arguments = argumentParser.ParseArguments("-nocache"); + this.environment.SetEnvironmentVariable("GITVERSION_REMOTE_USERNAME", "value"); + var arguments = this.argumentParser.ParseArguments("-nocache"); arguments.Authentication.Username.ShouldBe("value"); } [Test] public void ArbitraryArgumentsRemotePasswordDefinedSetsPassword() { - environment.SetEnvironmentVariable("GITVERSION_REMOTE_PASSWORD", "value"); - var arguments = argumentParser.ParseArguments("-nocache"); + this.environment.SetEnvironmentVariable("GITVERSION_REMOTE_PASSWORD", "value"); + var arguments = this.argumentParser.ParseArguments("-nocache"); arguments.Authentication.Password.ShouldBe("value"); } } diff --git a/src/GitVersion.App.Tests/HelpWriterTests.cs b/src/GitVersion.App.Tests/HelpWriterTests.cs index 58dc0acc4b..3b60606e13 100644 --- a/src/GitVersion.App.Tests/HelpWriterTests.cs +++ b/src/GitVersion.App.Tests/HelpWriterTests.cs @@ -18,7 +18,7 @@ public HelpWriterTests() { services.AddModule(new GitVersionAppModule()); }); - helpWriter = sp.GetService(); + this.helpWriter = sp.GetService(); } [Test] @@ -41,7 +41,7 @@ public void AllArgsAreInHelp() }; string helpText = null; - helpWriter.WriteTo(s => helpText = s); + this.helpWriter.WriteTo(s => helpText = s); var ignored = new[] { diff --git a/src/GitVersion.App.Tests/Helpers/ArgumentBuilder.cs b/src/GitVersion.App.Tests/Helpers/ArgumentBuilder.cs index 5fb69e3823..4652f630ea 100644 --- a/src/GitVersion.App.Tests/Helpers/ArgumentBuilder.cs +++ b/src/GitVersion.App.Tests/Helpers/ArgumentBuilder.cs @@ -27,42 +27,42 @@ public ArgumentBuilder(string workingDirectory, string additionalArguments, stri this.logFile = logFile; } - public string WorkingDirectory => workingDirectory; + public string WorkingDirectory => this.workingDirectory; - public string LogFile => logFile; + public string LogFile => this.logFile; public override string ToString() { var arguments = new StringBuilder(); - arguments.AppendFormat(" /targetpath \"{0}\"", workingDirectory); + arguments.AppendFormat(" /targetpath \"{0}\"", this.workingDirectory); - if (!exec.IsNullOrWhiteSpace()) + if (!this.exec.IsNullOrWhiteSpace()) { - arguments.AppendFormat(" /exec \"{0}\"", exec); + arguments.AppendFormat(" /exec \"{0}\"", this.exec); } - if (!execArgs.IsNullOrWhiteSpace()) + if (!this.execArgs.IsNullOrWhiteSpace()) { - arguments.AppendFormat(" /execArgs \"{0}\"", execArgs); + arguments.AppendFormat(" /execArgs \"{0}\"", this.execArgs); } - if (!projectFile.IsNullOrWhiteSpace()) + if (!this.projectFile.IsNullOrWhiteSpace()) { - arguments.AppendFormat(" /proj \"{0}\"", projectFile); + arguments.AppendFormat(" /proj \"{0}\"", this.projectFile); } - if (!projectArgs.IsNullOrWhiteSpace()) + if (!this.projectArgs.IsNullOrWhiteSpace()) { - arguments.AppendFormat(" /projargs \"{0}\"", projectArgs); + arguments.AppendFormat(" /projargs \"{0}\"", this.projectArgs); } - if (!logFile.IsNullOrWhiteSpace()) + if (!this.logFile.IsNullOrWhiteSpace()) { - arguments.AppendFormat(" /l \"{0}\"", logFile); + arguments.AppendFormat(" /l \"{0}\"", this.logFile); } - arguments.Append(additionalArguments); + arguments.Append(this.additionalArguments); return arguments.ToString(); } diff --git a/src/GitVersion.App.Tests/Helpers/ProgramFixture.cs b/src/GitVersion.App.Tests/Helpers/ProgramFixture.cs index f6e89953f9..cc4d455494 100644 --- a/src/GitVersion.App.Tests/Helpers/ProgramFixture.cs +++ b/src/GitVersion.App.Tests/Helpers/ProgramFixture.cs @@ -30,24 +30,24 @@ public ProgramFixture(string workingDirectory = "") var consoleBuilder = new StringBuilder(); IConsole consoleAdapter = new TestConsoleAdapter(consoleBuilder); - environment = new TestEnvironment(); + this.environment = new TestEnvironment(); Overrides.Add(services => { services.AddSingleton(log); services.AddSingleton(consoleAdapter); - services.AddSingleton(environment); + services.AddSingleton(this.environment); }); - logger = new Lazy(() => logBuilder.ToString()); - output = new Lazy(() => consoleAdapter.ToString()); + this.logger = new Lazy(() => logBuilder.ToString()); + this.output = new Lazy(() => consoleAdapter.ToString()); } public void WithEnv(params KeyValuePair[] envs) { foreach (var env in envs) { - environment.SetEnvironmentVariable(env.Key, env.Value); + this.environment.SetEnvironmentVariable(env.Key, env.Value); } } @@ -62,17 +62,17 @@ public async Task Run(params string[] args) // Create the application and override registrations. var program = new Program(builder => Overrides.ForEach(action => action(builder))); - if (!workingDirectory.IsNullOrWhiteSpace()) + if (!this.workingDirectory.IsNullOrWhiteSpace()) { - args = new[] { "-targetpath", workingDirectory }.Concat(args).ToArray(); + args = new[] { "-targetpath", this.workingDirectory }.Concat(args).ToArray(); } await program.RunAsync(args); return new ProgramFixtureResult { ExitCode = System.Environment.ExitCode, - Output = output.Value, - Log = logger.Value + Output = this.output.Value, + Log = this.logger.Value }; } } diff --git a/src/GitVersion.App.Tests/Helpers/TestConsoleAdapter.cs b/src/GitVersion.App.Tests/Helpers/TestConsoleAdapter.cs index 2687817654..315f50c2d8 100644 --- a/src/GitVersion.App.Tests/Helpers/TestConsoleAdapter.cs +++ b/src/GitVersion.App.Tests/Helpers/TestConsoleAdapter.cs @@ -13,22 +13,22 @@ public TestConsoleAdapter(StringBuilder sb) } public void WriteLine(string msg) { - sb.AppendLine(msg); + this.sb.AppendLine(msg); } public void WriteLine() { - sb.AppendLine(); + this.sb.AppendLine(); } public void Write(string msg) { - sb.Append(msg); + this.sb.Append(msg); } public override string ToString() { - return sb.ToString(); + return this.sb.ToString(); } public string ReadLine() diff --git a/src/GitVersion.App.Tests/UpdateWixVersionFileTests.cs b/src/GitVersion.App.Tests/UpdateWixVersionFileTests.cs index 3779644b3d..b8cd526acb 100644 --- a/src/GitVersion.App.Tests/UpdateWixVersionFileTests.cs +++ b/src/GitVersion.App.Tests/UpdateWixVersionFileTests.cs @@ -18,7 +18,7 @@ internal class UpdateWixVersionFileTests [SetUp] public void Setup() { - wixVersionFileName = WixVersionFileUpdater.WixVersionFileName; + this.wixVersionFileName = WixVersionFileUpdater.WixVersionFileName; } [Test] @@ -29,7 +29,7 @@ public void WixVersionFileCreationTest() fixture.MakeACommit(); GitVersionHelper.ExecuteIn(fixture.RepositoryPath, arguments: " /updatewixversionfile"); - Assert.IsTrue(File.Exists(Path.Combine(fixture.RepositoryPath, wixVersionFileName))); + Assert.IsTrue(File.Exists(Path.Combine(fixture.RepositoryPath, this.wixVersionFileName))); } [Test] @@ -44,7 +44,7 @@ public void WixVersionFileVarCountTest() GitVersionHelper.ExecuteIn(fixture.RepositoryPath, arguments: " /updatewixversionfile"); - var gitVersionVarsInWix = GetGitVersionVarsInWixFile(Path.Combine(fixture.RepositoryPath, wixVersionFileName)); + var gitVersionVarsInWix = GetGitVersionVarsInWixFile(Path.Combine(fixture.RepositoryPath, this.wixVersionFileName)); var gitVersionVars = VersionVariables.AvailableVariables; Assert.AreEqual(gitVersionVars.Count(), gitVersionVarsInWix.Count); @@ -62,7 +62,7 @@ public void WixVersionFileContentTest() GitVersionHelper.ExecuteIn(fixture.RepositoryPath, arguments: " /updatewixversionfile"); - var gitVersionVarsInWix = GetGitVersionVarsInWixFile(Path.Combine(fixture.RepositoryPath, wixVersionFileName)); + var gitVersionVarsInWix = GetGitVersionVarsInWixFile(Path.Combine(fixture.RepositoryPath, this.wixVersionFileName)); var gitVersionVars = VersionVariables.AvailableVariables; foreach (var variable in gitVersionVars) diff --git a/src/GitVersion.App.Tests/VersionWriterTests.cs b/src/GitVersion.App.Tests/VersionWriterTests.cs index 0c3525e763..58c071f0ad 100644 --- a/src/GitVersion.App.Tests/VersionWriterTests.cs +++ b/src/GitVersion.App.Tests/VersionWriterTests.cs @@ -21,7 +21,7 @@ public VersionWriterTests() services.AddModule(new GitVersionAppModule()); }); - versionWriter = sp.GetService(); + this.versionWriter = sp.GetService(); } [Test] public void WriteVersionShouldWriteFileVersionWithNoPrereleaseTag() @@ -29,7 +29,7 @@ public void WriteVersionShouldWriteFileVersionWithNoPrereleaseTag() var asm = GenerateAssembly(new Version(1, 0, 0), ""); string version = null; - versionWriter.WriteTo(asm, v => version = v); + this.versionWriter.WriteTo(asm, v => version = v); Assert.IsNotNull(asm); Assert.AreEqual("1.0.0", version); @@ -41,7 +41,7 @@ public void WriteVersionShouldWriteFileVersionWithPrereleaseTag() var asm = GenerateAssembly(new Version(1, 0, 0), "-beta0004"); string version = null; - versionWriter.WriteTo(asm, v => version = v); + this.versionWriter.WriteTo(asm, v => version = v); Assert.IsNotNull(asm); Assert.AreEqual("1.0.0-beta0004", version); diff --git a/src/GitVersion.App/ArgumentParser.cs b/src/GitVersion.App/ArgumentParser.cs index de992ef9f8..a8191543b5 100644 --- a/src/GitVersion.App/ArgumentParser.cs +++ b/src/GitVersion.App/ArgumentParser.cs @@ -47,7 +47,7 @@ public Arguments ParseArguments(string[] commandLineArguments) AddAuthentication(args); - args.NoFetch = buildAgent != null && buildAgent.PreventFetch(); + args.NoFetch = this.buildAgent != null && this.buildAgent.PreventFetch(); return args; } @@ -109,7 +109,7 @@ public Arguments ParseArguments(string[] commandLineArguments) arguments.TargetPath = arguments.TargetPath.TrimEnd('/', '\\'); if (!arguments.EnsureAssemblyInfo) arguments.UpdateAssemblyInfoFileName = ResolveFiles(arguments.TargetPath, arguments.UpdateAssemblyInfoFileName).ToHashSet(); - arguments.NoFetch = arguments.NoFetch || buildAgent != null && buildAgent.PreventFetch(); + arguments.NoFetch = arguments.NoFetch || this.buildAgent != null && this.buildAgent.PreventFetch(); return arguments; } @@ -127,13 +127,13 @@ private void ParseSwitchArguments(Arguments arguments, NameValueCollection switc private void AddAuthentication(Arguments arguments) { - var username = environment.GetEnvironmentVariable("GITVERSION_REMOTE_USERNAME"); + var username = this.environment.GetEnvironmentVariable("GITVERSION_REMOTE_USERNAME"); if (!username.IsNullOrWhiteSpace()) { arguments.Authentication.Username = username; } - var password = environment.GetEnvironmentVariable("GITVERSION_REMOTE_PASSWORD"); + var password = this.environment.GetEnvironmentVariable("GITVERSION_REMOTE_PASSWORD"); if (!password.IsNullOrWhiteSpace()) { arguments.Authentication.Password = password; @@ -146,7 +146,7 @@ private IEnumerable ResolveFiles(string workingDirectory, ISet a foreach (var file in assemblyInfoFiles) { - var paths = globbingResolver.Resolve(workingDirectory, file); + var paths = this.globbingResolver.Resolve(workingDirectory, file); foreach (var path in paths) { @@ -163,7 +163,7 @@ private void ParseTargetPath(Arguments arguments, string name, string[] values, arguments.TargetPath = value; if (!Directory.Exists(value)) { - console.WriteLine($"The working directory '{value}' does not exist."); + this.console.WriteLine($"The working directory '{value}' does not exist."); } return; diff --git a/src/GitVersion.App/Arguments.cs b/src/GitVersion.App/Arguments.cs index bde9b7fce7..1b97531b90 100644 --- a/src/GitVersion.App/Arguments.cs +++ b/src/GitVersion.App/Arguments.cs @@ -44,7 +44,7 @@ public class Arguments public GitVersionOptions ToOptions() { - var workingDirectory = TargetPath?.TrimEnd('/', '\\'); + var workingDirectory = this.TargetPath?.TrimEnd('/', '\\'); return new GitVersionOptions { @@ -60,9 +60,9 @@ public GitVersionOptions ToOptions() Authentication = { - Username = Authentication.Username, - Password = Authentication.Password, - Token = Authentication.Token, + Username = this.Authentication.Username, + Password = this.Authentication.Password, + Token = this.Authentication.Token, }, ConfigInfo = diff --git a/src/GitVersion.App/GitVersionApp.cs b/src/GitVersion.App/GitVersionApp.cs index 1652c71966..35b8868433 100644 --- a/src/GitVersion.App/GitVersionApp.cs +++ b/src/GitVersion.App/GitVersionApp.cs @@ -25,9 +25,9 @@ public Task StartAsync(CancellationToken cancellationToken) { try { - var gitVersionOptions = options.Value; - log.Verbosity = gitVersionOptions.Verbosity; - System.Environment.ExitCode = gitVersionExecutor.Execute(gitVersionOptions); + var gitVersionOptions = this.options.Value; + this.log.Verbosity = gitVersionOptions.Verbosity; + System.Environment.ExitCode = this.gitVersionExecutor.Execute(gitVersionOptions); } catch (Exception exception) { @@ -35,7 +35,7 @@ public Task StartAsync(CancellationToken cancellationToken) System.Environment.ExitCode = 1; } - applicationLifetime.StopApplication(); + this.applicationLifetime.StopApplication(); return Task.CompletedTask; } diff --git a/src/GitVersion.App/GitVersionExecutor.cs b/src/GitVersion.App/GitVersionExecutor.cs index 2ae0f84cd4..d9e5071a81 100644 --- a/src/GitVersion.App/GitVersionExecutor.cs +++ b/src/GitVersion.App/GitVersionExecutor.cs @@ -49,7 +49,7 @@ public int Execute(GitVersionOptions gitVersionOptions) if (exitCode != 0) { // Dump log to console if we fail to complete successfully - console.Write(log.ToString()); + this.console.Write(this.log.ToString()); } return exitCode; @@ -57,7 +57,7 @@ public int Execute(GitVersionOptions gitVersionOptions) private int RunGitVersionTool(GitVersionOptions gitVersionOptions) { - var mutexName = repositoryInfo.DotGitDirectory.Replace(Path.DirectorySeparatorChar.ToString(), ""); + var mutexName = this.repositoryInfo.DotGitDirectory.Replace(Path.DirectorySeparatorChar.ToString(), ""); using var mutex = new Mutex(true, $@"Global\gitversion{mutexName}", out var acquired); try @@ -67,37 +67,37 @@ private int RunGitVersionTool(GitVersionOptions gitVersionOptions) mutex.WaitOne(); } - var variables = gitVersionCalculateTool.CalculateVersionVariables(); + var variables = this.gitVersionCalculateTool.CalculateVersionVariables(); - var configuration = configProvider.Provide(overrideConfig: gitVersionOptions.ConfigInfo.OverrideConfig); + var configuration = this.configProvider.Provide(overrideConfig: gitVersionOptions.ConfigInfo.OverrideConfig); - gitVersionOutputTool.OutputVariables(variables, configuration.UpdateBuildNumber ?? true); - gitVersionOutputTool.UpdateAssemblyInfo(variables); - gitVersionOutputTool.UpdateWixVersionFile(variables); + this.gitVersionOutputTool.OutputVariables(variables, configuration.UpdateBuildNumber ?? true); + this.gitVersionOutputTool.UpdateAssemblyInfo(variables); + this.gitVersionOutputTool.UpdateWixVersionFile(variables); } catch (WarningException exception) { var error = $"An error occurred:{System.Environment.NewLine}{exception.Message}"; - log.Warning(error); + this.log.Warning(error); return 1; } catch (Exception exception) { var error = $"An unexpected error occurred:{System.Environment.NewLine}{exception}"; - log.Error(error); + this.log.Error(error); if (gitVersionOptions == null) return 1; - log.Info("Attempting to show the current git graph (please include in issue): "); - log.Info("Showing max of 100 commits"); + this.log.Info("Attempting to show the current git graph (please include in issue): "); + this.log.Info("Showing max of 100 commits"); try { - GitExtensions.DumpGraph(gitVersionOptions.WorkingDirectory, mess => log.Info(mess), 100); + GitExtensions.DumpGraph(gitVersionOptions.WorkingDirectory, mess => this.log.Info(mess), 100); } catch (Exception dumpGraphException) { - log.Error("Couldn't dump the git graph due to the following error: " + dumpGraphException); + this.log.Error("Couldn't dump the git graph due to the following error: " + dumpGraphException); } return 1; } @@ -113,7 +113,7 @@ private bool HandleNonMainCommand(GitVersionOptions gitVersionOptions, out int e { if (gitVersionOptions == null) { - helpWriter.Write(); + this.helpWriter.Write(); exitCode = 1; return true; } @@ -122,14 +122,14 @@ private bool HandleNonMainCommand(GitVersionOptions gitVersionOptions, out int e if (gitVersionOptions.IsVersion) { var assembly = Assembly.GetExecutingAssembly(); - versionWriter.Write(assembly); + this.versionWriter.Write(assembly); exitCode = 0; return true; } if (gitVersionOptions.IsHelp) { - helpWriter.Write(); + this.helpWriter.Write(); exitCode = 0; return true; } @@ -140,37 +140,37 @@ private bool HandleNonMainCommand(GitVersionOptions gitVersionOptions, out int e gitVersionOptions.Output.Add(OutputType.BuildServer); } - ConfigureLogging(gitVersionOptions, log); + ConfigureLogging(gitVersionOptions, this.log); var workingDirectory = gitVersionOptions.WorkingDirectory; if (gitVersionOptions.Diag) { - log.Info("Dumping commit graph: "); - GitExtensions.DumpGraph(workingDirectory, mess => log.Info(mess), 100); + this.log.Info("Dumping commit graph: "); + GitExtensions.DumpGraph(workingDirectory, mess => this.log.Info(mess), 100); } if (!Directory.Exists(workingDirectory)) { - log.Warning($"The working directory '{workingDirectory}' does not exist."); + this.log.Warning($"The working directory '{workingDirectory}' does not exist."); } else { - log.Info("Working directory: " + workingDirectory); + this.log.Info("Working directory: " + workingDirectory); } - configFileLocator.Verify(gitVersionOptions, repositoryInfo); + this.configFileLocator.Verify(gitVersionOptions, this.repositoryInfo); if (gitVersionOptions.Init) { - configProvider.Init(workingDirectory); + this.configProvider.Init(workingDirectory); exitCode = 0; return true; } if (gitVersionOptions.ConfigInfo.ShowConfig) { - var config = configProvider.Provide(workingDirectory); - console.WriteLine(config.ToString()); + var config = this.configProvider.Provide(workingDirectory); + this.console.WriteLine(config.ToString()); exitCode = 0; return true; } diff --git a/src/GitVersion.App/GlobbingResolver.cs b/src/GitVersion.App/GlobbingResolver.cs index 4f1754b19f..513e53f26b 100644 --- a/src/GitVersion.App/GlobbingResolver.cs +++ b/src/GitVersion.App/GlobbingResolver.cs @@ -13,8 +13,8 @@ public class GlobbingResolver : IGlobbingResolver public IEnumerable Resolve(string workingDirectory, string pattern) { - matcher.AddInclude(pattern); - return matcher.Execute(GetDirectoryInfoWrapper(workingDirectory)).Files.Select(file => file.Path); + this.matcher.AddInclude(pattern); + return this.matcher.Execute(GetDirectoryInfoWrapper(workingDirectory)).Files.Select(file => file.Path); } protected virtual DirectoryInfoBase GetDirectoryInfoWrapper(string workingDirectory) => new DirectoryInfoWrapper(new DirectoryInfo(workingDirectory)); diff --git a/src/GitVersion.App/HelpWriter.cs b/src/GitVersion.App/HelpWriter.cs index c93a309b71..f17439fa3d 100644 --- a/src/GitVersion.App/HelpWriter.cs +++ b/src/GitVersion.App/HelpWriter.cs @@ -18,14 +18,14 @@ public HelpWriter(IVersionWriter versionWriter, IConsole console) public void Write() { - WriteTo(console.WriteLine); + WriteTo(this.console.WriteLine); } public void WriteTo(Action writeAction) { var version = string.Empty; var assembly = Assembly.GetExecutingAssembly(); - versionWriter.WriteTo(assembly, v => version = v); + this.versionWriter.WriteTo(assembly, v => version = v); var args = ArgumentList(); var nl = System.Environment.NewLine; diff --git a/src/GitVersion.App/OverrideConfigOptionParser.cs b/src/GitVersion.App/OverrideConfigOptionParser.cs index 298fe78b35..e307569c5b 100644 --- a/src/GitVersion.App/OverrideConfigOptionParser.cs +++ b/src/GitVersion.App/OverrideConfigOptionParser.cs @@ -69,13 +69,13 @@ internal void SetValue(string key, string value) unwrapped = pi.PropertyType; if (unwrapped == typeof(string)) - pi.SetValue(_lazyConfig.Value, unwrappedText); + pi.SetValue(this._lazyConfig.Value, unwrappedText); else if (unwrapped.IsEnum) { try { var parsedEnum = Enum.Parse(unwrapped, unwrappedText); - pi.SetValue(_lazyConfig.Value, parsedEnum); + pi.SetValue(this._lazyConfig.Value, parsedEnum); } catch (ArgumentException) { @@ -92,14 +92,14 @@ internal void SetValue(string key, string value) else if (unwrapped == typeof(int)) { if (int.TryParse(unwrappedText, out int parsedInt)) - pi.SetValue(_lazyConfig.Value, parsedInt); + pi.SetValue(this._lazyConfig.Value, parsedInt); else throw new WarningException($"Could not parse /overrideconfig option: {key}={value}. Ensure that 'value' is valid integer number."); } else if (unwrapped == typeof(bool)) { if (bool.TryParse(unwrappedText, out bool parsedBool)) - pi.SetValue(_lazyConfig.Value, parsedBool); + pi.SetValue(this._lazyConfig.Value, parsedBool); else throw new WarningException($"Could not parse /overrideconfig option: {key}={value}. Ensure that 'value' is 'true' or 'false'."); } @@ -108,7 +108,7 @@ internal void SetValue(string key, string value) internal Config GetConfig() { - return _lazyConfig.IsValueCreated ? _lazyConfig.Value : null; + return this._lazyConfig.IsValueCreated ? this._lazyConfig.Value : null; } } } diff --git a/src/GitVersion.App/Program.cs b/src/GitVersion.App/Program.cs index af6b8d01de..0999caca05 100644 --- a/src/GitVersion.App/Program.cs +++ b/src/GitVersion.App/Program.cs @@ -46,7 +46,7 @@ private IHostBuilder CreateHostBuilder(string[] args) => return Options.Create(gitVersionOptions); }); - overrides?.Invoke(services); + this.overrides?.Invoke(services); services.AddHostedService(); }) .UseConsoleLifetime(); diff --git a/src/GitVersion.App/VersionWriter.cs b/src/GitVersion.App/VersionWriter.cs index d8975567a8..41061f12e5 100644 --- a/src/GitVersion.App/VersionWriter.cs +++ b/src/GitVersion.App/VersionWriter.cs @@ -15,7 +15,7 @@ public VersionWriter(IConsole console) } public void Write(Assembly assembly) { - WriteTo(assembly, console.WriteLine); + WriteTo(assembly, this.console.WriteLine); } public void WriteTo(Assembly assembly, Action writeAction) diff --git a/src/GitVersion.Core.Tests/BuildAgents/AzurePipelinesTests.cs b/src/GitVersion.Core.Tests/BuildAgents/AzurePipelinesTests.cs index 0c46282ee4..37d2006b0c 100644 --- a/src/GitVersion.Core.Tests/BuildAgents/AzurePipelinesTests.cs +++ b/src/GitVersion.Core.Tests/BuildAgents/AzurePipelinesTests.cs @@ -22,23 +22,23 @@ public void SetEnvironmentVariableForTest() { services.AddSingleton(); }); - environment = sp.GetService(); - buildServer = sp.GetService(); + this.environment = sp.GetService(); + this.buildServer = sp.GetService(); - environment.SetEnvironmentVariable(key, "Some Build_Value $(GitVersion_FullSemVer) 20151310.3 $(UnknownVar) Release"); + this.environment.SetEnvironmentVariable(key, "Some Build_Value $(GitVersion_FullSemVer) 20151310.3 $(UnknownVar) Release"); } [TearDown] public void ClearEnvironmentVariableForTest() { - environment.SetEnvironmentVariable(key, null); + this.environment.SetEnvironmentVariable(key, null); } [Test] public void DevelopBranch() { var vars = new TestableVersionVariables(fullSemVer: "0.0.0-Unstable4"); - var vsVersion = buildServer.GenerateSetVersionMessage(vars); + var vsVersion = this.buildServer.GenerateSetVersionMessage(vars); vsVersion.ShouldBe("##vso[build.updatebuildnumber]Some Build_Value 0.0.0-Unstable4 20151310.3 $(UnknownVar) Release"); } @@ -46,7 +46,7 @@ public void DevelopBranch() [Test] public void EscapeValues() { - var vsVersion = buildServer.GenerateSetParameterMessage("Foo", "0.8.0-unstable568 Branch:'develop' Sha:'ee69bff1087ebc95c6b43aa2124bd58f5722e0cb'"); + var vsVersion = this.buildServer.GenerateSetParameterMessage("Foo", "0.8.0-unstable568 Branch:'develop' Sha:'ee69bff1087ebc95c6b43aa2124bd58f5722e0cb'"); vsVersion.ShouldContain("##vso[task.setvariable variable=GitVersion.Foo]0.8.0-unstable568 Branch:'develop' Sha:'ee69bff1087ebc95c6b43aa2124bd58f5722e0cb'"); vsVersion.ShouldContain("##vso[task.setvariable variable=GitVersion.Foo;isOutput=true]0.8.0-unstable568 Branch:'develop' Sha:'ee69bff1087ebc95c6b43aa2124bd58f5722e0cb'"); @@ -55,11 +55,11 @@ public void EscapeValues() [Test] public void MissingEnvShouldNotBlowUp() { - environment.SetEnvironmentVariable(key, null); + this.environment.SetEnvironmentVariable(key, null); var semver = "0.0.0-Unstable4"; var vars = new TestableVersionVariables(fullSemVer: semver); - var vsVersion = buildServer.GenerateSetVersionMessage(vars); + var vsVersion = this.buildServer.GenerateSetVersionMessage(vars); vsVersion.ShouldBe(semver); } @@ -69,9 +69,9 @@ public void MissingEnvShouldNotBlowUp() [TestCase("$(GITVERSION_FULLSEMVER)-Build.1234", "1.0.0", "1.0.0-Build.1234")] public void AzurePipelinesBuildNumberWithFullSemVer(string buildNumberFormat, string myFullSemVer, string expectedBuildNumber) { - environment.SetEnvironmentVariable(key, buildNumberFormat); + this.environment.SetEnvironmentVariable(key, buildNumberFormat); var vars = new TestableVersionVariables(fullSemVer: myFullSemVer); - var logMessage = buildServer.GenerateSetVersionMessage(vars); + var logMessage = this.buildServer.GenerateSetVersionMessage(vars); logMessage.ShouldBe(logPrefix + expectedBuildNumber); } @@ -81,9 +81,9 @@ public void AzurePipelinesBuildNumberWithFullSemVer(string buildNumberFormat, st [TestCase("$(GITVERSION_SEMVER)-Build.1234", "1.0.0", "1.0.0-Build.1234")] public void AzurePipelinesBuildNumberWithSemVer(string buildNumberFormat, string mySemVer, string expectedBuildNumber) { - environment.SetEnvironmentVariable(key, buildNumberFormat); + this.environment.SetEnvironmentVariable(key, buildNumberFormat); var vars = new TestableVersionVariables(semVer: mySemVer); - var logMessage = buildServer.GenerateSetVersionMessage(vars); + var logMessage = this.buildServer.GenerateSetVersionMessage(vars); logMessage.ShouldBe(logPrefix + expectedBuildNumber); } } diff --git a/src/GitVersion.Core.Tests/BuildAgents/BuildServerBaseTests.cs b/src/GitVersion.Core.Tests/BuildAgents/BuildServerBaseTests.cs index 82cb823a2d..8ab20e1e95 100644 --- a/src/GitVersion.Core.Tests/BuildAgents/BuildServerBaseTests.cs +++ b/src/GitVersion.Core.Tests/BuildAgents/BuildServerBaseTests.cs @@ -20,11 +20,11 @@ public class BuildServerBaseTests : TestBase [SetUp] public void SetUp() { - sp = ConfigureServices(services => + this.sp = ConfigureServices(services => { services.AddSingleton(); }); - buildServer = sp.GetService(); + this.buildServer = this.sp.GetService(); } [Test] @@ -46,7 +46,7 @@ public void BuildNumberIsFullSemVer() var config = new TestEffectiveConfiguration(); var variables = this.buildServer.GetVariablesFor(semanticVersion, config, false); - var buildServer = sp.GetService(); + var buildServer = this.sp.GetService(); buildServer.WriteIntegration(writes.Add, variables); writes[1].ShouldBe("1.2.3-beta.1+5"); diff --git a/src/GitVersion.Core.Tests/BuildAgents/CodeBuildTests.cs b/src/GitVersion.Core.Tests/BuildAgents/CodeBuildTests.cs index 823a18fa00..cdf2a7a6ce 100644 --- a/src/GitVersion.Core.Tests/BuildAgents/CodeBuildTests.cs +++ b/src/GitVersion.Core.Tests/BuildAgents/CodeBuildTests.cs @@ -21,40 +21,40 @@ public sealed class CodeBuildTests : TestBase [SetUp] public void SetUp() { - sp = ConfigureServices(services => + this.sp = ConfigureServices(services => { services.AddSingleton(); }); - environment = sp.GetService(); - buildServer = sp.GetService(); + this.environment = this.sp.GetService(); + this.buildServer = this.sp.GetService(); } [Test] public void CorrectlyIdentifiesCodeBuildPresenceFromSourceVersion() { - environment.SetEnvironmentVariable(CodeBuild.SourceVersionEnvironmentVariableName, "a value"); - buildServer.CanApplyToCurrentContext().ShouldBe(true); + this.environment.SetEnvironmentVariable(CodeBuild.SourceVersionEnvironmentVariableName, "a value"); + this.buildServer.CanApplyToCurrentContext().ShouldBe(true); } [Test] public void PicksUpBranchNameFromEnvironmentFromSourceVersion() { - environment.SetEnvironmentVariable(CodeBuild.SourceVersionEnvironmentVariableName, $"refs/heads/{MainBranch}"); - buildServer.GetCurrentBranch(false).ShouldBe($"refs/heads/{MainBranch}"); + this.environment.SetEnvironmentVariable(CodeBuild.SourceVersionEnvironmentVariableName, $"refs/heads/{MainBranch}"); + this.buildServer.GetCurrentBranch(false).ShouldBe($"refs/heads/{MainBranch}"); } [Test] public void CorrectlyIdentifiesCodeBuildPresenceFromWebHook() { - environment.SetEnvironmentVariable(CodeBuild.WebHookEnvironmentVariableName, "a value"); - buildServer.CanApplyToCurrentContext().ShouldBe(true); + this.environment.SetEnvironmentVariable(CodeBuild.WebHookEnvironmentVariableName, "a value"); + this.buildServer.CanApplyToCurrentContext().ShouldBe(true); } [Test] public void PicksUpBranchNameFromEnvironmentFromWebHook() { - environment.SetEnvironmentVariable(CodeBuild.WebHookEnvironmentVariableName, $"refs/heads/{MainBranch}"); - buildServer.GetCurrentBranch(false).ShouldBe($"refs/heads/{MainBranch}"); + this.environment.SetEnvironmentVariable(CodeBuild.WebHookEnvironmentVariableName, $"refs/heads/{MainBranch}"); + this.buildServer.GetCurrentBranch(false).ShouldBe($"refs/heads/{MainBranch}"); } [Test] @@ -90,13 +90,13 @@ private void AssertVariablesAreWrittenToFile(string file) var config = new TestEffectiveConfiguration(); - var variableProvider = sp.GetService(); + var variableProvider = this.sp.GetService(); var variables = variableProvider.GetVariablesFor(semanticVersion, config, false); - buildServer.WithPropertyFile(file); + this.buildServer.WithPropertyFile(file); - buildServer.WriteIntegration(writes.Add, variables); + this.buildServer.WriteIntegration(writes.Add, variables); writes[1].ShouldBe("1.2.3-beta.1+5"); diff --git a/src/GitVersion.Core.Tests/BuildAgents/ContinuaCiTests.cs b/src/GitVersion.Core.Tests/BuildAgents/ContinuaCiTests.cs index eecbd7a7a3..c7c78e8a28 100644 --- a/src/GitVersion.Core.Tests/BuildAgents/ContinuaCiTests.cs +++ b/src/GitVersion.Core.Tests/BuildAgents/ContinuaCiTests.cs @@ -14,7 +14,7 @@ public class ContinuaCiTests : TestBase [SetUp] public void SetUp() { - sp = ConfigureServices(services => + this.sp = ConfigureServices(services => { services.AddSingleton(); }); @@ -23,7 +23,7 @@ public void SetUp() [Test] public void GenerateBuildVersion() { - var buildServer = sp.GetService(); + var buildServer = this.sp.GetService(); var vars = new TestableVersionVariables(fullSemVer: "0.0.0-Beta4.7"); var continuaCiVersion = buildServer.GenerateSetVersionMessage(vars); Assert.AreEqual("@@continua[setBuildVersion value='0.0.0-Beta4.7']", continuaCiVersion); diff --git a/src/GitVersion.Core.Tests/BuildAgents/DroneTests.cs b/src/GitVersion.Core.Tests/BuildAgents/DroneTests.cs index f4115624b5..010cb73d33 100644 --- a/src/GitVersion.Core.Tests/BuildAgents/DroneTests.cs +++ b/src/GitVersion.Core.Tests/BuildAgents/DroneTests.cs @@ -17,26 +17,26 @@ public class DroneTests : TestBase [SetUp] public void SetUp() { - sp = ConfigureServices(services => + this.sp = ConfigureServices(services => { services.AddSingleton(); }); - environment = sp.GetService(); - buildServer = sp.GetService(); - environment.SetEnvironmentVariable("DRONE", "true"); + this.environment = this.sp.GetService(); + this.buildServer = this.sp.GetService(); + this.environment.SetEnvironmentVariable("DRONE", "true"); } [TearDown] public void TearDown() { - environment.SetEnvironmentVariable("DRONE", null); + this.environment.SetEnvironmentVariable("DRONE", null); } [Test] public void CanApplyToCurrentContextShouldBeTrueWhenEnvironmentVariableIsSet() { // Act - var result = buildServer.CanApplyToCurrentContext(); + var result = this.buildServer.CanApplyToCurrentContext(); // Assert result.ShouldBeTrue(); @@ -46,10 +46,10 @@ public void CanApplyToCurrentContextShouldBeTrueWhenEnvironmentVariableIsSet() public void CanApplyToCurrentContextShouldBeFalseWhenEnvironmentVariableIsNotSet() { // Arrange - environment.SetEnvironmentVariable("DRONE", ""); + this.environment.SetEnvironmentVariable("DRONE", ""); // Act - var result = buildServer.CanApplyToCurrentContext(); + var result = this.buildServer.CanApplyToCurrentContext(); // Assert result.ShouldBeFalse(); @@ -61,11 +61,11 @@ public void GetCurrentBranchShouldDroneBranchInCaseOfPush() // Arrange const string droneBranch = "droneBranch"; - environment.SetEnvironmentVariable("DRONE_PULL_REQUEST", ""); - environment.SetEnvironmentVariable("DRONE_BRANCH", droneBranch); + this.environment.SetEnvironmentVariable("DRONE_PULL_REQUEST", ""); + this.environment.SetEnvironmentVariable("DRONE_BRANCH", droneBranch); // Act - var result = buildServer.GetCurrentBranch(false); + var result = this.buildServer.GetCurrentBranch(false); // Assert result.ShouldBe(droneBranch); @@ -76,11 +76,11 @@ public void GetCurrentBranchShouldUseDroneSourceBranchInCaseOfPullRequestAndNonE { // Arrange const string droneSourceBranch = "droneSourceBranch"; - environment.SetEnvironmentVariable("DRONE_PULL_REQUEST", "1"); - environment.SetEnvironmentVariable("DRONE_SOURCE_BRANCH", droneSourceBranch); + this.environment.SetEnvironmentVariable("DRONE_PULL_REQUEST", "1"); + this.environment.SetEnvironmentVariable("DRONE_SOURCE_BRANCH", droneSourceBranch); // Act - var result = buildServer.GetCurrentBranch(false); + var result = this.buildServer.GetCurrentBranch(false); // Assert result.ShouldBe(droneSourceBranch); @@ -95,12 +95,12 @@ public void GetCurrentBranchShouldUseSourceBranchFromCiCommitRefSpecInCaseOfPull var ciCommitRefSpec = $"{droneSourceBranch}:{droneDestinationBranch}"; - environment.SetEnvironmentVariable("DRONE_PULL_REQUEST", "1"); - environment.SetEnvironmentVariable("DRONE_SOURCE_BRANCH", ""); - environment.SetEnvironmentVariable("CI_COMMIT_REFSPEC", ciCommitRefSpec); + this.environment.SetEnvironmentVariable("DRONE_PULL_REQUEST", "1"); + this.environment.SetEnvironmentVariable("DRONE_SOURCE_BRANCH", ""); + this.environment.SetEnvironmentVariable("CI_COMMIT_REFSPEC", ciCommitRefSpec); // Act - var result = buildServer.GetCurrentBranch(false); + var result = this.buildServer.GetCurrentBranch(false); // Assert result.ShouldBe(droneSourceBranch); @@ -112,13 +112,13 @@ public void GetCurrentBranchShouldUseDroneBranchInCaseOfPullRequestAndEmptyDrone // Arrange const string droneBranch = "droneBranch"; - environment.SetEnvironmentVariable("DRONE_PULL_REQUEST", "1"); - environment.SetEnvironmentVariable("DRONE_SOURCE_BRANCH", ""); - environment.SetEnvironmentVariable("CI_COMMIT_REFSPEC", ""); - environment.SetEnvironmentVariable("DRONE_BRANCH", droneBranch); + this.environment.SetEnvironmentVariable("DRONE_PULL_REQUEST", "1"); + this.environment.SetEnvironmentVariable("DRONE_SOURCE_BRANCH", ""); + this.environment.SetEnvironmentVariable("CI_COMMIT_REFSPEC", ""); + this.environment.SetEnvironmentVariable("DRONE_BRANCH", droneBranch); // Act - var result = buildServer.GetCurrentBranch(false); + var result = this.buildServer.GetCurrentBranch(false); // Assert result.ShouldBe(droneBranch); @@ -134,13 +134,13 @@ public void GetCurrentBranchShouldUseDroneBranchInCaseOfPullRequestAndEmptyDrone var ciCommitRefSpec = $"{droneSourceBranch};{droneDestinationBranch}"; - environment.SetEnvironmentVariable("DRONE_PULL_REQUEST", "1"); - environment.SetEnvironmentVariable("DRONE_SOURCE_BRANCH", ""); - environment.SetEnvironmentVariable("CI_COMMIT_REFSPEC", ciCommitRefSpec); - environment.SetEnvironmentVariable("DRONE_BRANCH", droneBranch); + this.environment.SetEnvironmentVariable("DRONE_PULL_REQUEST", "1"); + this.environment.SetEnvironmentVariable("DRONE_SOURCE_BRANCH", ""); + this.environment.SetEnvironmentVariable("CI_COMMIT_REFSPEC", ciCommitRefSpec); + this.environment.SetEnvironmentVariable("DRONE_BRANCH", droneBranch); // Act - var result = buildServer.GetCurrentBranch(false); + var result = this.buildServer.GetCurrentBranch(false); // Assert result.ShouldBe(droneBranch); diff --git a/src/GitVersion.Core.Tests/BuildAgents/EnvRunTests.cs b/src/GitVersion.Core.Tests/BuildAgents/EnvRunTests.cs index 413bf3b4c0..67de91c32b 100644 --- a/src/GitVersion.Core.Tests/BuildAgents/EnvRunTests.cs +++ b/src/GitVersion.Core.Tests/BuildAgents/EnvRunTests.cs @@ -22,34 +22,34 @@ public void SetEnvironmentVariableForTest() { services.AddSingleton(); }); - environment = sp.GetService(); - buildServer = sp.GetService(); + this.environment = sp.GetService(); + this.buildServer = sp.GetService(); // set environment variable and create an empty envrun file to indicate that EnvRun is running... - mFilePath = Path.Combine(Path.GetTempPath(), "envrun.db"); - environment.SetEnvironmentVariable(EnvVarName, mFilePath); - File.OpenWrite(mFilePath).Dispose(); + this.mFilePath = Path.Combine(Path.GetTempPath(), "envrun.db"); + this.environment.SetEnvironmentVariable(EnvVarName, this.mFilePath); + File.OpenWrite(this.mFilePath).Dispose(); } [TearDown] public void ClearEnvironmentVariableForTest() { - environment.SetEnvironmentVariable(EnvVarName, null); - File.Delete(mFilePath); + this.environment.SetEnvironmentVariable(EnvVarName, null); + File.Delete(this.mFilePath); } [Test] public void CanApplyToCurrentContext() { - var applys = buildServer.CanApplyToCurrentContext(); + var applys = this.buildServer.CanApplyToCurrentContext(); applys.ShouldBeTrue(); } [Test] public void CanApplyToCurrentContextEnvironmentVariableNotSet() { - environment.SetEnvironmentVariable(EnvVarName, null); - var applys = buildServer.CanApplyToCurrentContext(); + this.environment.SetEnvironmentVariable(EnvVarName, null); + var applys = this.buildServer.CanApplyToCurrentContext(); applys.ShouldBeFalse(); } @@ -58,7 +58,7 @@ public void CanApplyToCurrentContextEnvironmentVariableNotSet() public void GenerateSetVersionMessage(string fullSemVer) { var vars = new TestableVersionVariables(fullSemVer: fullSemVer); - var version = buildServer.GenerateSetVersionMessage(vars); + var version = this.buildServer.GenerateSetVersionMessage(vars); version.ShouldBe(fullSemVer); } @@ -66,7 +66,7 @@ public void GenerateSetVersionMessage(string fullSemVer) [TestCase("Version", "1.2.3-rc4", "@@envrun[set name='GitVersion_Version' value='1.2.3-rc4']")] public void GenerateSetParameterMessage(string name, string value, string expected) { - var output = buildServer.GenerateSetParameterMessage(name, value); + var output = this.buildServer.GenerateSetParameterMessage(name, value); output.ShouldHaveSingleItem(); output[0].ShouldBe(expected); } diff --git a/src/GitVersion.Core.Tests/BuildAgents/GitHubActionsTests.cs b/src/GitVersion.Core.Tests/BuildAgents/GitHubActionsTests.cs index 878bb3913c..89effffe38 100644 --- a/src/GitVersion.Core.Tests/BuildAgents/GitHubActionsTests.cs +++ b/src/GitVersion.Core.Tests/BuildAgents/GitHubActionsTests.cs @@ -23,23 +23,23 @@ public void SetUp() { services.AddSingleton(); }); - environment = sp.GetService(); - buildServer = sp.GetService(); - environment.SetEnvironmentVariable(GitHubActions.EnvironmentVariableName, "true"); + this.environment = sp.GetService(); + this.buildServer = sp.GetService(); + this.environment.SetEnvironmentVariable(GitHubActions.EnvironmentVariableName, "true"); - githubSetEnvironmentTempFilePath = Path.GetTempFileName(); - environment.SetEnvironmentVariable(GitHubActions.GitHubSetEnvTempFileEnvironmentVariableName, githubSetEnvironmentTempFilePath); + this.githubSetEnvironmentTempFilePath = Path.GetTempFileName(); + this.environment.SetEnvironmentVariable(GitHubActions.GitHubSetEnvTempFileEnvironmentVariableName, this.githubSetEnvironmentTempFilePath); } [TearDown] public void TearDown() { - environment.SetEnvironmentVariable(GitHubActions.EnvironmentVariableName, null); - environment.SetEnvironmentVariable(GitHubActions.GitHubSetEnvTempFileEnvironmentVariableName, null); - if (githubSetEnvironmentTempFilePath != null && File.Exists(githubSetEnvironmentTempFilePath)) + this.environment.SetEnvironmentVariable(GitHubActions.EnvironmentVariableName, null); + this.environment.SetEnvironmentVariable(GitHubActions.GitHubSetEnvTempFileEnvironmentVariableName, null); + if (this.githubSetEnvironmentTempFilePath != null && File.Exists(this.githubSetEnvironmentTempFilePath)) { - File.Delete(githubSetEnvironmentTempFilePath); - githubSetEnvironmentTempFilePath = null; + File.Delete(this.githubSetEnvironmentTempFilePath); + this.githubSetEnvironmentTempFilePath = null; } } @@ -47,7 +47,7 @@ public void TearDown() public void CanApplyToCurrentContextShouldBeTrueWhenEnvironmentVariableIsSet() { // Act - var result = buildServer.CanApplyToCurrentContext(); + var result = this.buildServer.CanApplyToCurrentContext(); // Assert result.ShouldBeTrue(); @@ -57,10 +57,10 @@ public void CanApplyToCurrentContextShouldBeTrueWhenEnvironmentVariableIsSet() public void CanApplyToCurrentContextShouldBeFalseWhenEnvironmentVariableIsNotSet() { // Arrange - environment.SetEnvironmentVariable(GitHubActions.EnvironmentVariableName, ""); + this.environment.SetEnvironmentVariable(GitHubActions.EnvironmentVariableName, ""); // Act - var result = buildServer.CanApplyToCurrentContext(); + var result = this.buildServer.CanApplyToCurrentContext(); // Assert result.ShouldBeFalse(); @@ -70,10 +70,10 @@ public void CanApplyToCurrentContextShouldBeFalseWhenEnvironmentVariableIsNotSet public void GetCurrentBranchShouldHandleBranches() { // Arrange - environment.SetEnvironmentVariable("GITHUB_REF", $"refs/heads/{MainBranch}"); + this.environment.SetEnvironmentVariable("GITHUB_REF", $"refs/heads/{MainBranch}"); // Act - var result = buildServer.GetCurrentBranch(false); + var result = this.buildServer.GetCurrentBranch(false); // Assert result.ShouldBe($"refs/heads/{MainBranch}"); @@ -83,10 +83,10 @@ public void GetCurrentBranchShouldHandleBranches() public void GetCurrentBranchShouldHandleTags() { // Arrange - environment.SetEnvironmentVariable("GITHUB_REF", "refs/tags/1.0.0"); + this.environment.SetEnvironmentVariable("GITHUB_REF", "refs/tags/1.0.0"); // Act - var result = buildServer.GetCurrentBranch(false); + var result = this.buildServer.GetCurrentBranch(false); // Assert result.ShouldBe("refs/tags/1.0.0"); @@ -96,10 +96,10 @@ public void GetCurrentBranchShouldHandleTags() public void GetCurrentBranchShouldHandlePullRequests() { // Arrange - environment.SetEnvironmentVariable("GITHUB_REF", "refs/pull/1/merge"); + this.environment.SetEnvironmentVariable("GITHUB_REF", "refs/pull/1/merge"); // Act - var result = buildServer.GetCurrentBranch(false); + var result = this.buildServer.GetCurrentBranch(false); // Assert result.ShouldBe("refs/pull/1/merge"); @@ -109,10 +109,10 @@ public void GetCurrentBranchShouldHandlePullRequests() public void GetSetParameterMessage() { // Assert - environment.GetEnvironmentVariable("GitVersion_Something").ShouldBeNullOrWhiteSpace(); + this.environment.GetEnvironmentVariable("GitVersion_Something").ShouldBeNullOrWhiteSpace(); // Act - var result = buildServer.GenerateSetParameterMessage("GitVersion_Something", "1.0.0"); + var result = this.buildServer.GenerateSetParameterMessage("GitVersion_Something", "1.0.0"); // Assert result.ShouldContain(s => true, 0); @@ -122,7 +122,7 @@ public void GetSetParameterMessage() public void SkipEmptySetParameterMessage() { // Act - var result = buildServer.GenerateSetParameterMessage("Hello", string.Empty); + var result = this.buildServer.GenerateSetParameterMessage("Hello", string.Empty); // Assert result.ShouldBeEquivalentTo(new string[0]); @@ -137,10 +137,10 @@ public void ShouldWriteIntegration() var list = new List(); // Assert - environment.GetEnvironmentVariable("GitVersion_Major").ShouldBeNullOrWhiteSpace(); + this.environment.GetEnvironmentVariable("GitVersion_Major").ShouldBeNullOrWhiteSpace(); // Act - buildServer.WriteIntegration(s => { list.Add(s); }, vars); + this.buildServer.WriteIntegration(s => { list.Add(s); }, vars); // Assert var expected = new List @@ -159,7 +159,7 @@ public void ShouldWriteIntegration() "GitVersion_Major=1.0.0" }; - var actualFileContents = File.ReadAllLines(githubSetEnvironmentTempFilePath); + var actualFileContents = File.ReadAllLines(this.githubSetEnvironmentTempFilePath); actualFileContents.ShouldBe(expectedFileContents); } @@ -173,10 +173,10 @@ public void ShouldNotWriteIntegration() var list = new List(); // Assert - environment.GetEnvironmentVariable("GitVersion_Major").ShouldBeNullOrWhiteSpace(); + this.environment.GetEnvironmentVariable("GitVersion_Major").ShouldBeNullOrWhiteSpace(); // Act - buildServer.WriteIntegration(s => { list.Add(s); }, vars, false); + this.buildServer.WriteIntegration(s => { list.Add(s); }, vars, false); list.ShouldNotContain(x => x.StartsWith("Executing GenerateSetVersionMessage for ")); } @@ -188,7 +188,7 @@ public void GetEmptyGenerateSetVersionMessage() var vars = new TestableVersionVariables("1.0.0"); // Act - var message = buildServer.GenerateSetVersionMessage(vars); + var message = this.buildServer.GenerateSetVersionMessage(vars); // Assert message.ShouldBeEmpty(); diff --git a/src/GitVersion.Core.Tests/BuildAgents/GitLabCiTests.cs b/src/GitVersion.Core.Tests/BuildAgents/GitLabCiTests.cs index 4539b480a8..04a6490afb 100644 --- a/src/GitVersion.Core.Tests/BuildAgents/GitLabCiTests.cs +++ b/src/GitVersion.Core.Tests/BuildAgents/GitLabCiTests.cs @@ -20,24 +20,24 @@ public class GitLabCiTests : TestBase [SetUp] public void SetUp() { - sp = ConfigureServices(services => + this.sp = ConfigureServices(services => { services.AddSingleton(); }); - buildServer = sp.GetService(); + this.buildServer = this.sp.GetService(); } [Test] public void GenerateSetVersionMessageReturnsVersionAsIsAlthoughThisIsNotUsedByJenkins() { var vars = new TestableVersionVariables(fullSemVer: "0.0.0-Beta4.7"); - buildServer.GenerateSetVersionMessage(vars).ShouldBe("0.0.0-Beta4.7"); + this.buildServer.GenerateSetVersionMessage(vars).ShouldBe("0.0.0-Beta4.7"); } [Test] public void GenerateMessageTest() { - var generatedParameterMessages = buildServer.GenerateSetParameterMessage("name", "value"); + var generatedParameterMessages = this.buildServer.GenerateSetParameterMessage("name", "value"); generatedParameterMessages.Length.ShouldBe(1); generatedParameterMessages[0].ShouldBe("GitVersion_name=value"); } @@ -74,13 +74,13 @@ private void AssertVariablesAreWrittenToFile(string file) semanticVersion.BuildMetaData.Sha = "commitSha"; var config = new TestEffectiveConfiguration(); - var variableProvider = sp.GetService(); + var variableProvider = this.sp.GetService(); var variables = variableProvider.GetVariablesFor(semanticVersion, config, false); - buildServer.WithPropertyFile(file); + this.buildServer.WithPropertyFile(file); - buildServer.WriteIntegration(writes.Add, variables); + this.buildServer.WriteIntegration(writes.Add, variables); writes[1].ShouldBe("1.2.3-beta.1+5"); diff --git a/src/GitVersion.Core.Tests/BuildAgents/JenkinsTests.cs b/src/GitVersion.Core.Tests/BuildAgents/JenkinsTests.cs index fc92ecf015..4f6bfbf4f7 100644 --- a/src/GitVersion.Core.Tests/BuildAgents/JenkinsTests.cs +++ b/src/GitVersion.Core.Tests/BuildAgents/JenkinsTests.cs @@ -25,96 +25,96 @@ public class JenkinsTests : TestBase [SetUp] public void SetUp() { - sp = ConfigureServices(services => + this.sp = ConfigureServices(services => { services.AddSingleton(); }); - environment = sp.GetService(); - buildServer = sp.GetService(); + this.environment = this.sp.GetService(); + this.buildServer = this.sp.GetService(); } private void SetEnvironmentVariableForDetection() { - environment.SetEnvironmentVariable(key, "a value"); + this.environment.SetEnvironmentVariable(key, "a value"); } private void ClearenvironmentVariableForDetection() { - environment.SetEnvironmentVariable(key, null); + this.environment.SetEnvironmentVariable(key, null); } [Test] public void CanApplyCurrentContextWhenenvironmentVariableIsSet() { SetEnvironmentVariableForDetection(); - buildServer.CanApplyToCurrentContext().ShouldBe(true); + this.buildServer.CanApplyToCurrentContext().ShouldBe(true); } [Test] public void CanNotApplyCurrentContextWhenenvironmentVariableIsNotSet() { ClearenvironmentVariableForDetection(); - buildServer.CanApplyToCurrentContext().ShouldBe(false); + this.buildServer.CanApplyToCurrentContext().ShouldBe(false); } [Test] public void JenkinsTakesLocalBranchNameNotRemoteName() { // Save original values so they can be restored - var branchOrig = environment.GetEnvironmentVariable(branch); - var localBranchOrig = environment.GetEnvironmentVariable(localBranch); + var branchOrig = this.environment.GetEnvironmentVariable(branch); + var localBranchOrig = this.environment.GetEnvironmentVariable(localBranch); // Set GIT_BRANCH for testing - environment.SetEnvironmentVariable(branch, $"origin/{MainBranch}"); + this.environment.SetEnvironmentVariable(branch, $"origin/{MainBranch}"); // Test Jenkins that GetCurrentBranch falls back to GIT_BRANCH if GIT_LOCAL_BRANCH undefined - buildServer.GetCurrentBranch(true).ShouldBe($"origin/{MainBranch}"); + this.buildServer.GetCurrentBranch(true).ShouldBe($"origin/{MainBranch}"); // Set GIT_LOCAL_BRANCH - environment.SetEnvironmentVariable(localBranch, MainBranch); + this.environment.SetEnvironmentVariable(localBranch, MainBranch); // Test Jenkins GetCurrentBranch method now returns GIT_LOCAL_BRANCH - buildServer.GetCurrentBranch(true).ShouldBe(MainBranch); + this.buildServer.GetCurrentBranch(true).ShouldBe(MainBranch); // Restore environment variables - environment.SetEnvironmentVariable(branch, branchOrig); - environment.SetEnvironmentVariable(localBranch, localBranchOrig); + this.environment.SetEnvironmentVariable(branch, branchOrig); + this.environment.SetEnvironmentVariable(localBranch, localBranchOrig); } [Test] public void JenkinsTakesBranchNameInPipelineAsCode() { // Save original values so they can be restored - var branchOrig = environment.GetEnvironmentVariable(branch); - var localBranchOrig = environment.GetEnvironmentVariable(localBranch); - var pipelineBranchOrig = environment.GetEnvironmentVariable(pipelineBranch); + var branchOrig = this.environment.GetEnvironmentVariable(branch); + var localBranchOrig = this.environment.GetEnvironmentVariable(localBranch); + var pipelineBranchOrig = this.environment.GetEnvironmentVariable(pipelineBranch); // Set BRANCH_NAME in pipeline mode - environment.SetEnvironmentVariable(pipelineBranch, MainBranch); + this.environment.SetEnvironmentVariable(pipelineBranch, MainBranch); // When Jenkins uses a Pipeline, GIT_BRANCH and GIT_LOCAL_BRANCH are not set: - environment.SetEnvironmentVariable(branch, null); - environment.SetEnvironmentVariable(localBranch, null); + this.environment.SetEnvironmentVariable(branch, null); + this.environment.SetEnvironmentVariable(localBranch, null); // Test Jenkins GetCurrentBranch method now returns BRANCH_NAME - buildServer.GetCurrentBranch(true).ShouldBe(MainBranch); + this.buildServer.GetCurrentBranch(true).ShouldBe(MainBranch); // Restore environment variables - environment.SetEnvironmentVariable(branch, branchOrig); - environment.SetEnvironmentVariable(localBranch, localBranchOrig); - environment.SetEnvironmentVariable(pipelineBranch, pipelineBranchOrig); + this.environment.SetEnvironmentVariable(branch, branchOrig); + this.environment.SetEnvironmentVariable(localBranch, localBranchOrig); + this.environment.SetEnvironmentVariable(pipelineBranch, pipelineBranchOrig); } [Test] public void GenerateSetVersionMessageReturnsVersionAsIsAlthoughThisIsNotUsedByJenkins() { var vars = new TestableVersionVariables(fullSemVer: "0.0.0-Beta4.7"); - buildServer.GenerateSetVersionMessage(vars).ShouldBe("0.0.0-Beta4.7"); + this.buildServer.GenerateSetVersionMessage(vars).ShouldBe("0.0.0-Beta4.7"); } [Test] public void GenerateMessageTest() { - var generatedParameterMessages = buildServer.GenerateSetParameterMessage("name", "value"); + var generatedParameterMessages = this.buildServer.GenerateSetParameterMessage("name", "value"); generatedParameterMessages.Length.ShouldBe(1); generatedParameterMessages[0].ShouldBe("GitVersion_name=value"); } @@ -152,13 +152,13 @@ private void AssertVariablesAreWrittenToFile(string file) var config = new TestEffectiveConfiguration(); - var variableProvider = sp.GetService(); + var variableProvider = this.sp.GetService(); var variables = variableProvider.GetVariablesFor(semanticVersion, config, false); - buildServer.WithPropertyFile(file); + this.buildServer.WithPropertyFile(file); - buildServer.WriteIntegration(writes.Add, variables); + this.buildServer.WriteIntegration(writes.Add, variables); writes[1].ShouldBe("1.2.3-beta.1+5"); diff --git a/src/GitVersion.Core.Tests/BuildAgents/MyGetTests.cs b/src/GitVersion.Core.Tests/BuildAgents/MyGetTests.cs index 82b8579ce0..0bfff09006 100644 --- a/src/GitVersion.Core.Tests/BuildAgents/MyGetTests.cs +++ b/src/GitVersion.Core.Tests/BuildAgents/MyGetTests.cs @@ -17,28 +17,28 @@ public void SetUp() { services.AddSingleton(); }); - buildServer = sp.GetService(); + this.buildServer = sp.GetService(); } [Test] public void DevelopBranch() { var vars = new TestableVersionVariables(fullSemVer: "0.0.0-Unstable4"); - var message = buildServer.GenerateSetVersionMessage(vars); + var message = this.buildServer.GenerateSetVersionMessage(vars); Assert.AreEqual(null, message); } [Test] public void EscapeValues() { - var message = buildServer.GenerateSetParameterMessage("Foo", "0.8.0-unstable568 Branch:'develop' Sha:'ee69bff1087ebc95c6b43aa2124bd58f5722e0cb'"); + var message = this.buildServer.GenerateSetParameterMessage("Foo", "0.8.0-unstable568 Branch:'develop' Sha:'ee69bff1087ebc95c6b43aa2124bd58f5722e0cb'"); Assert.AreEqual("##myget[setParameter name='GitVersion.Foo' value='0.8.0-unstable568 Branch:|'develop|' Sha:|'ee69bff1087ebc95c6b43aa2124bd58f5722e0cb|'']", message[0]); } [Test] public void BuildNumber() { - var message = buildServer.GenerateSetParameterMessage("LegacySemVerPadded", "0.8.0-unstable568"); + var message = this.buildServer.GenerateSetParameterMessage("LegacySemVerPadded", "0.8.0-unstable568"); Assert.AreEqual("##myget[buildNumber '0.8.0-unstable568']", message[1]); } } diff --git a/src/GitVersion.Core.Tests/BuildAgents/SpaceAutomationTests.cs b/src/GitVersion.Core.Tests/BuildAgents/SpaceAutomationTests.cs index 9764fbcacc..610208be48 100644 --- a/src/GitVersion.Core.Tests/BuildAgents/SpaceAutomationTests.cs +++ b/src/GitVersion.Core.Tests/BuildAgents/SpaceAutomationTests.cs @@ -21,22 +21,22 @@ public void SetUp() { services.AddSingleton(); }); - environment = sp.GetService(); - buildServer = sp.GetService(); - environment.SetEnvironmentVariable(SpaceAutomation.EnvironmentVariableName, "true"); + this.environment = sp.GetService(); + this.buildServer = sp.GetService(); + this.environment.SetEnvironmentVariable(SpaceAutomation.EnvironmentVariableName, "true"); } [TearDown] public void TearDown() { - environment.SetEnvironmentVariable(SpaceAutomation.EnvironmentVariableName, null); + this.environment.SetEnvironmentVariable(SpaceAutomation.EnvironmentVariableName, null); } [Test] public void CanApplyToCurrentContextShouldBeTrueWhenEnvironmentVariableIsSet() { // Act - var result = buildServer.CanApplyToCurrentContext(); + var result = this.buildServer.CanApplyToCurrentContext(); // Assert result.ShouldBeTrue(); @@ -46,10 +46,10 @@ public void CanApplyToCurrentContextShouldBeTrueWhenEnvironmentVariableIsSet() public void CanApplyToCurrentContextShouldBeFalseWhenEnvironmentVariableIsNotSet() { // Arrange - environment.SetEnvironmentVariable(SpaceAutomation.EnvironmentVariableName, ""); + this.environment.SetEnvironmentVariable(SpaceAutomation.EnvironmentVariableName, ""); // Act - var result = buildServer.CanApplyToCurrentContext(); + var result = this.buildServer.CanApplyToCurrentContext(); // Assert result.ShouldBeFalse(); @@ -59,10 +59,10 @@ public void CanApplyToCurrentContextShouldBeFalseWhenEnvironmentVariableIsNotSet public void GetCurrentBranchShouldHandleBranches() { // Arrange - environment.SetEnvironmentVariable("JB_SPACE_GIT_BRANCH", "refs/heads/master"); + this.environment.SetEnvironmentVariable("JB_SPACE_GIT_BRANCH", "refs/heads/master"); // Act - var result = buildServer.GetCurrentBranch(false); + var result = this.buildServer.GetCurrentBranch(false); // Assert result.ShouldBe("refs/heads/master"); @@ -72,10 +72,10 @@ public void GetCurrentBranchShouldHandleBranches() public void GetCurrentBranchShouldHandleTags() { // Arrange - environment.SetEnvironmentVariable("JB_SPACE_GIT_BRANCH", "refs/tags/1.0.0"); + this.environment.SetEnvironmentVariable("JB_SPACE_GIT_BRANCH", "refs/tags/1.0.0"); // Act - var result = buildServer.GetCurrentBranch(false); + var result = this.buildServer.GetCurrentBranch(false); // Assert result.ShouldBe("refs/tags/1.0.0"); @@ -85,10 +85,10 @@ public void GetCurrentBranchShouldHandleTags() public void GetCurrentBranchShouldHandlePullRequests() { // Arrange - environment.SetEnvironmentVariable("JB_SPACE_GIT_BRANCH", "refs/pull/1/merge"); + this.environment.SetEnvironmentVariable("JB_SPACE_GIT_BRANCH", "refs/pull/1/merge"); // Act - var result = buildServer.GetCurrentBranch(false); + var result = this.buildServer.GetCurrentBranch(false); // Assert result.ShouldBe("refs/pull/1/merge"); @@ -101,7 +101,7 @@ public void GetEmptyGenerateSetVersionMessage() var vars = new TestableVersionVariables("1.0.0"); // Act - var message = buildServer.GenerateSetVersionMessage(vars); + var message = this.buildServer.GenerateSetVersionMessage(vars); // Assert message.ShouldBeEmpty(); diff --git a/src/GitVersion.Core.Tests/BuildAgents/TeamCityTests.cs b/src/GitVersion.Core.Tests/BuildAgents/TeamCityTests.cs index 2bb7812f28..ac0ccbe4b8 100644 --- a/src/GitVersion.Core.Tests/BuildAgents/TeamCityTests.cs +++ b/src/GitVersion.Core.Tests/BuildAgents/TeamCityTests.cs @@ -17,21 +17,21 @@ public void SetUp() { services.AddSingleton(); }); - buildServer = sp.GetService(); + this.buildServer = sp.GetService(); } [Test] public void DevelopBranch() { var vars = new TestableVersionVariables(fullSemVer: "0.0.0-Unstable4"); - var tcVersion = buildServer.GenerateSetVersionMessage(vars); + var tcVersion = this.buildServer.GenerateSetVersionMessage(vars); Assert.AreEqual("##teamcity[buildNumber '0.0.0-Unstable4']", tcVersion); } [Test] public void EscapeValues() { - var tcVersion = buildServer.GenerateSetParameterMessage("Foo", "0.8.0-unstable568 Branch:'develop' Sha:'ee69bff1087ebc95c6b43aa2124bd58f5722e0cb'"); + var tcVersion = this.buildServer.GenerateSetParameterMessage("Foo", "0.8.0-unstable568 Branch:'develop' Sha:'ee69bff1087ebc95c6b43aa2124bd58f5722e0cb'"); Assert.AreEqual("##teamcity[setParameter name='GitVersion.Foo' value='0.8.0-unstable568 Branch:|'develop|' Sha:|'ee69bff1087ebc95c6b43aa2124bd58f5722e0cb|'']", tcVersion[0]); Assert.AreEqual("##teamcity[setParameter name='system.GitVersion.Foo' value='0.8.0-unstable568 Branch:|'develop|' Sha:|'ee69bff1087ebc95c6b43aa2124bd58f5722e0cb|'']", tcVersion[1]); } diff --git a/src/GitVersion.Core.Tests/Configuration/ConfigProviderTests.cs b/src/GitVersion.Core.Tests/Configuration/ConfigProviderTests.cs index 2ce25a30e0..4abb715418 100644 --- a/src/GitVersion.Core.Tests/Configuration/ConfigProviderTests.cs +++ b/src/GitVersion.Core.Tests/Configuration/ConfigProviderTests.cs @@ -30,14 +30,14 @@ public class ConfigProviderTests : TestBase [SetUp] public void Setup() { - repoPath = DefaultRepoPath; + this.repoPath = DefaultRepoPath; var options = Options.Create(new GitVersionOptions { WorkingDirectory = repoPath }); var sp = ConfigureServices(services => { services.AddSingleton(options); }); - configProvider = sp.GetService(); - fileSystem = sp.GetService(); + this.configProvider = sp.GetService(); + this.fileSystem = sp.GetService(); ShouldlyConfiguration.ShouldMatchApprovedDefaults.LocateTestMethodUsingAttribute(); } @@ -45,7 +45,7 @@ public void Setup() [Test] public void OverwritesDefaultsWithProvidedConfig() { - var defaultConfig = configProvider.Provide(repoPath); + var defaultConfig = this.configProvider.Provide(this.repoPath); const string text = @" next-version: 2.0.0 branches: @@ -53,7 +53,7 @@ public void OverwritesDefaultsWithProvidedConfig() mode: ContinuousDeployment tag: dev"; SetupConfigFileContent(text); - var config = configProvider.Provide(repoPath); + var config = this.configProvider.Provide(this.repoPath); config.NextVersion.ShouldBe("2.0.0"); config.Branches["develop"].Increment.ShouldBe(defaultConfig.Branches["develop"].Increment); @@ -66,7 +66,7 @@ public void AllBranchesModeWhenUsingMainline() { const string text = @"mode: Mainline"; SetupConfigFileContent(text); - var config = configProvider.Provide(repoPath); + var config = this.configProvider.Provide(this.repoPath); var branches = config.Branches.Select(x => x.Value); branches.All(branch => branch.VersioningMode == VersioningMode.Mainline).ShouldBe(true); } @@ -80,7 +80,7 @@ public void CanRemoveTag() release: tag: """""; SetupConfigFileContent(text); - var config = configProvider.Provide(repoPath); + var config = this.configProvider.Provide(this.repoPath); config.NextVersion.ShouldBe("2.0.0"); config.Branches["release"].Tag.ShouldBe(string.Empty); @@ -95,7 +95,7 @@ public void RegexIsRequired() bug: tag: bugfix"; SetupConfigFileContent(text); - var ex = Should.Throw(() => configProvider.Provide(repoPath)); + var ex = Should.Throw(() => this.configProvider.Provide(this.repoPath)); ex.Message.ShouldBe($"Branch configuration 'bug' is missing required configuration 'regex'{System.Environment.NewLine}" + "See https://gitversion.net/docs/reference/configuration for more info"); } @@ -110,7 +110,7 @@ public void SourceBranchIsRequired() regex: 'bug[/-]' tag: bugfix"; SetupConfigFileContent(text); - var ex = Should.Throw(() => configProvider.Provide(repoPath)); + var ex = Should.Throw(() => this.configProvider.Provide(this.repoPath)); ex.Message.ShouldBe($"Branch configuration 'bug' is missing required configuration 'source-branches'{System.Environment.NewLine}" + "See https://gitversion.net/docs/reference/configuration for more info"); } @@ -125,7 +125,7 @@ public void SourceBranchesValidationShouldFailWhenMatchingBranchConfigurationIsM tag: bugfix source-branches: [notconfigured]"; SetupConfigFileContent(text); - var ex = Should.Throw(() => configProvider.Provide(repoPath)); + var ex = Should.Throw(() => this.configProvider.Provide(this.repoPath)); ex.Message.ShouldBe($"Branch configuration 'bug' defines these 'source-branches' that are not configured: '[notconfigured]'{System.Environment.NewLine}" + "See https://gitversion.net/docs/reference/configuration for more info"); } @@ -142,7 +142,7 @@ public void SourceBranchesValidationShouldSucceedForWellKnownBranches(string wel tag: bugfix source-branches: [{wellKnownBranchKey}]"; SetupConfigFileContent(text); - var config = configProvider.Provide(repoPath); + var config = this.configProvider.Provide(this.repoPath); config.Branches["bug"].SourceBranches.ShouldBe(new List { wellKnownBranchKey }); } @@ -158,7 +158,7 @@ public void CanProvideConfigForNewBranch() tag: bugfix source-branches: []"; SetupConfigFileContent(text); - var config = configProvider.Provide(repoPath); + var config = this.configProvider.Provide(this.repoPath); config.Branches["bug"].Regex.ShouldBe("bug[/-]"); config.Branches["bug"].Tag.ShouldBe("bugfix"); @@ -175,7 +175,7 @@ public void MasterConfigReplacedWithMain() tag: beta"; SetupConfigFileContent(text); - var config = configProvider.Provide(repoPath); + var config = this.configProvider.Provide(this.repoPath); config.Branches[MainBranch].Regex.ShouldBe("^master$|^main$"); config.Branches[MainBranch].Tag.ShouldBe("beta"); @@ -195,7 +195,7 @@ public void MasterConfigReplacedWithMainInSourceBranches() is-release-branch: false"; SetupConfigFileContent(text); - var config = configProvider.Provide(repoPath); + var config = this.configProvider.Provide(this.repoPath); config.Branches["breaking"].Regex.ShouldBe("breaking[/]"); config.Branches["breaking"].SourceBranches.ShouldHaveSingleItem(); @@ -207,7 +207,7 @@ public void NextVersionCanBeInteger() { const string text = "next-version: 2"; SetupConfigFileContent(text); - var config = configProvider.Provide(repoPath); + var config = this.configProvider.Provide(this.repoPath); config.NextVersion.ShouldBe("2.0"); } @@ -217,7 +217,7 @@ public void NextVersionCanHaveEnormousMinorVersion() { const string text = "next-version: 2.118998723"; SetupConfigFileContent(text); - var config = configProvider.Provide(repoPath); + var config = this.configProvider.Provide(this.repoPath); config.NextVersion.ShouldBe("2.118998723"); } @@ -227,7 +227,7 @@ public void NextVersionCanHavePatch() { const string text = "next-version: 2.12.654651698"; SetupConfigFileContent(text); - var config = configProvider.Provide(repoPath); + var config = this.configProvider.Provide(this.repoPath); config.NextVersion.ShouldBe("2.12.654651698"); } @@ -238,7 +238,7 @@ public void NextVersionCanHavePatch() [Description(NoMonoDescription)] public void CanWriteOutEffectiveConfiguration() { - var config = configProvider.Provide(repoPath); + var config = this.configProvider.Provide(this.repoPath); config.ToString().ShouldMatchApproved(); } @@ -253,7 +253,7 @@ public void CanUpdateAssemblyInformationalVersioningScheme() SetupConfigFileContent(text); - var config = configProvider.Provide(repoPath); + var config = this.configProvider.Provide(this.repoPath); config.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinor); config.AssemblyFileVersioningScheme.ShouldBe(AssemblyFileVersioningScheme.MajorMinorPatch); config.AssemblyInformationalFormat.ShouldBe("{NugetVersion}"); @@ -269,7 +269,7 @@ public void CanUpdateAssemblyInformationalVersioningSchemeWithMultipleVariables( SetupConfigFileContent(text); - var config = configProvider.Provide(repoPath); + var config = this.configProvider.Provide(this.repoPath); config.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinor); config.AssemblyFileVersioningScheme.ShouldBe(AssemblyFileVersioningScheme.MajorMinorPatch); config.AssemblyInformationalFormat.ShouldBe("{Major}.{Minor}.{Patch}"); @@ -288,7 +288,7 @@ public void CanUpdateAssemblyInformationalVersioningSchemeWithFullSemVer() SetupConfigFileContent(text); - var config = configProvider.Provide(repoPath); + var config = this.configProvider.Provide(this.repoPath); config.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinorPatch); config.AssemblyFileVersioningScheme.ShouldBe(AssemblyFileVersioningScheme.MajorMinorPatch); config.AssemblyInformationalFormat.ShouldBe("{FullSemVer}"); @@ -299,7 +299,7 @@ public void CanReadDefaultDocument() { const string text = ""; SetupConfigFileContent(text); - var config = configProvider.Provide(repoPath); + var config = this.configProvider.Provide(this.repoPath); config.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinorPatch); config.AssemblyFileVersioningScheme.ShouldBe(AssemblyFileVersioningScheme.MajorMinorPatch); config.AssemblyInformationalFormat.ShouldBe(null); @@ -338,22 +338,22 @@ public void NoWarnOnGitVersionYmlFile() services.AddSingleton(options); services.AddSingleton(log); }); - configProvider = sp.GetService(); + this.configProvider = sp.GetService(); - configProvider.Provide(repoPath); + this.configProvider.Provide(this.repoPath); stringLogger.Length.ShouldBe(0); } private string SetupConfigFileContent(string text, string fileName = ConfigFileLocator.DefaultFileName) { - return SetupConfigFileContent(text, fileName, repoPath); + return SetupConfigFileContent(text, fileName, this.repoPath); } private string SetupConfigFileContent(string text, string fileName, string path) { var fullPath = Path.Combine(path, fileName); - fileSystem.WriteAllText(fullPath, text); + this.fileSystem.WriteAllText(fullPath, text); return fullPath; } @@ -369,7 +369,7 @@ public void ShouldUseSpecifiedSourceBranchesForDevelop() source-branches: ['develop'] tag: dev"; SetupConfigFileContent(text); - var config = configProvider.Provide(repoPath); + var config = this.configProvider.Provide(this.repoPath); config.Branches["develop"].SourceBranches.ShouldBe(new List { "develop" }); } @@ -384,7 +384,7 @@ public void ShouldUseDefaultSourceBranchesWhenNotSpecifiedForDevelop() mode: ContinuousDeployment tag: dev"; SetupConfigFileContent(text); - var config = configProvider.Provide(repoPath); + var config = this.configProvider.Provide(this.repoPath); config.Branches["develop"].SourceBranches.ShouldBe(new List()); } @@ -400,7 +400,7 @@ public void ShouldUseSpecifiedSourceBranchesForFeature() source-branches: ['develop', 'release'] tag: dev"; SetupConfigFileContent(text); - var config = configProvider.Provide(repoPath); + var config = this.configProvider.Provide(this.repoPath); config.Branches["feature"].SourceBranches.ShouldBe(new List { "develop", "release" }); } @@ -415,7 +415,7 @@ public void ShouldUseDefaultSourceBranchesWhenNotSpecifiedForFeature() mode: ContinuousDeployment tag: dev"; SetupConfigFileContent(text); - var config = configProvider.Provide(repoPath); + var config = this.configProvider.Provide(this.repoPath); config.Branches["feature"].SourceBranches.ShouldBe( new List { "develop", MainBranch, "release", "feature", "support", "hotfix" }); @@ -429,8 +429,8 @@ public void ShouldNotOverrideAnythingWhenOverrideConfigIsEmpty() tag-prefix: custom-tag-prefix-from-yml"; SetupConfigFileContent(text); - var expectedConfig = configProvider.Provide(repoPath, overrideConfig: null); - var overridenConfig = configProvider.Provide(repoPath, overrideConfig: new Config()); + var expectedConfig = this.configProvider.Provide(this.repoPath, overrideConfig: null); + var overridenConfig = this.configProvider.Provide(this.repoPath, overrideConfig: new Config()); overridenConfig.AssemblyVersioningScheme.ShouldBe(expectedConfig.AssemblyVersioningScheme); overridenConfig.AssemblyFileVersioningScheme.ShouldBe(expectedConfig.AssemblyFileVersioningScheme); @@ -470,7 +470,7 @@ public void ShouldUseDefaultTagPrefixWhenNotSetInConfigFile() { const string text = ""; SetupConfigFileContent(text); - var config = configProvider.Provide(repoPath); + var config = this.configProvider.Provide(this.repoPath); config.TagPrefix.ShouldBe("[vV]"); } @@ -480,7 +480,7 @@ public void ShouldUseTagPrefixFromConfigFileWhenProvided() { const string text = "tag-prefix: custom-tag-prefix-from-yml"; SetupConfigFileContent(text); - var config = configProvider.Provide(repoPath); + var config = this.configProvider.Provide(this.repoPath); config.TagPrefix.ShouldBe("custom-tag-prefix-from-yml"); } @@ -490,7 +490,7 @@ public void ShouldOverrideTagPrefixWithOverrideConfigValue([Values] bool tagPref { var text = tagPrefixSetAtYmlFile ? "tag-prefix: custom-tag-prefix-from-yml" : ""; SetupConfigFileContent(text); - var config = configProvider.Provide(repoPath, overrideConfig: new Config { TagPrefix = "tag-prefix-from-override-config" }); + var config = this.configProvider.Provide(this.repoPath, overrideConfig: new Config { TagPrefix = "tag-prefix-from-override-config" }); config.TagPrefix.ShouldBe("tag-prefix-from-override-config"); } @@ -500,7 +500,7 @@ public void ShouldNotOverrideDefaultTagPrefixWhenNotSetInOverrideConfig() { const string text = ""; SetupConfigFileContent(text); - var config = configProvider.Provide(repoPath, overrideConfig: new Config { TagPrefix = null }); + var config = this.configProvider.Provide(this.repoPath, overrideConfig: new Config { TagPrefix = null }); config.TagPrefix.ShouldBe("[vV]"); } @@ -510,7 +510,7 @@ public void ShouldNotOverrideTagPrefixFromConfigFileWhenNotSetInOverrideConfig() { const string text = "tag-prefix: custom-tag-prefix-from-yml"; SetupConfigFileContent(text); - var config = configProvider.Provide(repoPath, overrideConfig: new Config { TagPrefix = null }); + var config = this.configProvider.Provide(this.repoPath, overrideConfig: new Config { TagPrefix = null }); config.TagPrefix.ShouldBe("custom-tag-prefix-from-yml"); } diff --git a/src/GitVersion.Core.Tests/Configuration/DefaultConfigFileLocatorTests.cs b/src/GitVersion.Core.Tests/Configuration/DefaultConfigFileLocatorTests.cs index 5f8a4b419e..f88ec0df79 100644 --- a/src/GitVersion.Core.Tests/Configuration/DefaultConfigFileLocatorTests.cs +++ b/src/GitVersion.Core.Tests/Configuration/DefaultConfigFileLocatorTests.cs @@ -28,8 +28,8 @@ public class DefaultConfigFileLocatorTests : TestBase [SetUp] public void Setup() { - repoPath = DefaultRepoPath; - workingPath = DefaultWorkingPath; + this.repoPath = DefaultRepoPath; + this.workingPath = DefaultWorkingPath; var options = Options.Create(new GitVersionOptions { WorkingDirectory = repoPath }); var sp = ConfigureServices(services => @@ -37,9 +37,9 @@ public void Setup() services.AddSingleton(options); }); - fileSystem = sp.GetService(); - configurationProvider = sp.GetService(); - configFileLocator = sp.GetService(); + this.fileSystem = sp.GetService(); + this.configurationProvider = sp.GetService(); + this.configFileLocator = sp.GetService(); ShouldlyConfiguration.ShouldMatchApprovedDefaults.LocateTestMethodUsingAttribute(); } @@ -47,12 +47,12 @@ public void Setup() [TestCase(ConfigFileLocator.DefaultFileName, ConfigFileLocator.DefaultFileName)] public void ThrowsExceptionOnAmbiguousConfigFileLocation(string repoConfigFile, string workingConfigFile) { - var repositoryConfigFilePath = SetupConfigFileContent(string.Empty, repoConfigFile, repoPath); - var workingDirectoryConfigFilePath = SetupConfigFileContent(string.Empty, workingConfigFile, workingPath); + var repositoryConfigFilePath = SetupConfigFileContent(string.Empty, repoConfigFile, this.repoPath); + var workingDirectoryConfigFilePath = SetupConfigFileContent(string.Empty, workingConfigFile, this.workingPath); var exception = Should.Throw(() => { - configFileLocator.Verify(workingPath, repoPath); + this.configFileLocator.Verify(this.workingPath, this.repoPath); }); var expecedMessage = $"Ambiguous config file selection from '{workingDirectoryConfigFilePath}' and '{repositoryConfigFilePath}'"; @@ -62,21 +62,21 @@ public void ThrowsExceptionOnAmbiguousConfigFileLocation(string repoConfigFile, [Test] public void NoWarnOnGitVersionYmlFile() { - SetupConfigFileContent(string.Empty, ConfigFileLocator.DefaultFileName, repoPath); + SetupConfigFileContent(string.Empty, ConfigFileLocator.DefaultFileName, this.repoPath); - Should.NotThrow(() => { configurationProvider.Provide(repoPath); }); + Should.NotThrow(() => { this.configurationProvider.Provide(this.repoPath); }); } [Test] public void NoWarnOnNoGitVersionYmlFile() { - Should.NotThrow(() => { configurationProvider.Provide(repoPath); }); + Should.NotThrow(() => { this.configurationProvider.Provide(this.repoPath); }); } private string SetupConfigFileContent(string text, string fileName, string path) { var fullPath = Path.Combine(path, fileName); - fileSystem.WriteAllText(fullPath, text); + this.fileSystem.WriteAllText(fullPath, text); return fullPath; } @@ -96,9 +96,9 @@ public class NamedConfigFileLocatorTests : TestBase [SetUp] public void Setup() { - gitVersionOptions = new GitVersionOptions { ConfigInfo = { ConfigFile = "my-config.yaml" } }; - repoPath = DefaultRepoPath; - workingPath = DefaultWorkingPath; + this.gitVersionOptions = new GitVersionOptions { ConfigInfo = { ConfigFile = "my-config.yaml" } }; + this.repoPath = DefaultRepoPath; + this.workingPath = DefaultWorkingPath; ShouldlyConfiguration.ShouldMatchApprovedDefaults.LocateTestMethodUsingAttribute(); } @@ -106,14 +106,14 @@ public void Setup() [Test] public void ThrowsExceptionOnAmbiguousConfigFileLocation() { - var sp = GetServiceProvider(gitVersionOptions); - configFileLocator = sp.GetService(); - fileSystem = sp.GetService(); + var sp = GetServiceProvider(this.gitVersionOptions); + this.configFileLocator = sp.GetService(); + this.fileSystem = sp.GetService(); - var repositoryConfigFilePath = SetupConfigFileContent(string.Empty, path: repoPath); - var workingDirectoryConfigFilePath = SetupConfigFileContent(string.Empty, path: workingPath); + var repositoryConfigFilePath = SetupConfigFileContent(string.Empty, path: this.repoPath); + var workingDirectoryConfigFilePath = SetupConfigFileContent(string.Empty, path: this.workingPath); - var exception = Should.Throw(() => { configFileLocator.Verify(workingPath, repoPath); }); + var exception = Should.Throw(() => { this.configFileLocator.Verify(this.workingPath, this.repoPath); }); var expectedMessage = $"Ambiguous config file selection from '{workingDirectoryConfigFilePath}' and '{repositoryConfigFilePath}'"; exception.Message.ShouldBe(expectedMessage); @@ -122,44 +122,44 @@ public void ThrowsExceptionOnAmbiguousConfigFileLocation() [Test] public void DoNotThrowWhenWorkingAndRepoPathsAreSame() { - workingPath = DefaultRepoPath; + this.workingPath = DefaultRepoPath; - var sp = GetServiceProvider(gitVersionOptions); - configFileLocator = sp.GetService(); - fileSystem = sp.GetService(); + var sp = GetServiceProvider(this.gitVersionOptions); + this.configFileLocator = sp.GetService(); + this.fileSystem = sp.GetService(); - SetupConfigFileContent(string.Empty, path: workingPath); + SetupConfigFileContent(string.Empty, path: this.workingPath); - Should.NotThrow(() => { configFileLocator.Verify(workingPath, repoPath); }); + Should.NotThrow(() => { this.configFileLocator.Verify(this.workingPath, this.repoPath); }); } [Test] public void DoNotThrowWhenWorkingAndRepoPathsAreSame_WithDifferentCasing() { - workingPath = DefaultRepoPath.ToLower(); + this.workingPath = DefaultRepoPath.ToLower(); - var sp = GetServiceProvider(gitVersionOptions); - configFileLocator = sp.GetService(); - fileSystem = sp.GetService(); + var sp = GetServiceProvider(this.gitVersionOptions); + this.configFileLocator = sp.GetService(); + this.fileSystem = sp.GetService(); - SetupConfigFileContent(string.Empty, path: workingPath); + SetupConfigFileContent(string.Empty, path: this.workingPath); - Should.NotThrow(() => { configFileLocator.Verify(workingPath, repoPath); }); + Should.NotThrow(() => { this.configFileLocator.Verify(this.workingPath, this.repoPath); }); } [Test] public void DoNotThrowWhenConfigFileIsInSubDirectoryOfRepoPath() { - workingPath = DefaultRepoPath; + this.workingPath = DefaultRepoPath; - gitVersionOptions = new GitVersionOptions { ConfigInfo = { ConfigFile = "./src/my-config.yaml" } }; - var sp = GetServiceProvider(gitVersionOptions); - configFileLocator = sp.GetService(); - fileSystem = sp.GetService(); + this.gitVersionOptions = new GitVersionOptions { ConfigInfo = { ConfigFile = "./src/my-config.yaml" } }; + var sp = GetServiceProvider(this.gitVersionOptions); + this.configFileLocator = sp.GetService(); + this.fileSystem = sp.GetService(); - SetupConfigFileContent(string.Empty, path: workingPath); + SetupConfigFileContent(string.Empty, path: this.workingPath); - Should.NotThrow(() => { configFileLocator.Verify(workingPath, repoPath); }); + Should.NotThrow(() => { this.configFileLocator.Verify(this.workingPath, this.repoPath); }); } [Test] @@ -171,15 +171,15 @@ public void NoWarnOnCustomYmlFile() var logAppender = new TestLogAppender(Action); var log = new Log(logAppender); - var sp = GetServiceProvider(gitVersionOptions, log); - configFileLocator = sp.GetService(); - fileSystem = sp.GetService(); + var sp = GetServiceProvider(this.gitVersionOptions, log); + this.configFileLocator = sp.GetService(); + this.fileSystem = sp.GetService(); SetupConfigFileContent(string.Empty); var configurationProvider = sp.GetService(); - configurationProvider.Provide(repoPath); + configurationProvider.Provide(this.repoPath); stringLogger.Length.ShouldBe(0); } @@ -192,39 +192,39 @@ public void NoWarnOnCustomYmlFileOutsideRepoPath() var logAppender = new TestLogAppender(Action); var log = new Log(logAppender); - var sp = GetServiceProvider(gitVersionOptions, log); - configFileLocator = sp.GetService(); - fileSystem = sp.GetService(); + var sp = GetServiceProvider(this.gitVersionOptions, log); + this.configFileLocator = sp.GetService(); + this.fileSystem = sp.GetService(); SetupConfigFileContent(string.Empty, path: @"c:\\Unrelated\\path"); var configurationProvider = sp.GetService(); - configurationProvider.Provide(repoPath); + configurationProvider.Provide(this.repoPath); stringLogger.Length.ShouldBe(0); } [Test] public void ThrowsExceptionOnCustomYmlFileDoesNotExist() { - var sp = GetServiceProvider(gitVersionOptions); - configFileLocator = sp.GetService(); + var sp = GetServiceProvider(this.gitVersionOptions); + this.configFileLocator = sp.GetService(); - var exception = Should.Throw(() => { configFileLocator.Verify(workingPath, repoPath); }); + var exception = Should.Throw(() => { this.configFileLocator.Verify(this.workingPath, this.repoPath); }); - var workingPathFileConfig = Path.Combine(workingPath, gitVersionOptions.ConfigInfo.ConfigFile); - var repoPathFileConfig = Path.Combine(repoPath, gitVersionOptions.ConfigInfo.ConfigFile); + var workingPathFileConfig = Path.Combine(this.workingPath, this.gitVersionOptions.ConfigInfo.ConfigFile); + var repoPathFileConfig = Path.Combine(this.repoPath, this.gitVersionOptions.ConfigInfo.ConfigFile); var expectedMessage = $"The configuration file was not found at '{workingPathFileConfig}' or '{repoPathFileConfig}'"; exception.Message.ShouldBe(expectedMessage); } private string SetupConfigFileContent(string text, string fileName = null, string path = null) { - if (fileName.IsNullOrEmpty()) fileName = configFileLocator.FilePath; + if (fileName.IsNullOrEmpty()) fileName = this.configFileLocator.FilePath; var filePath = fileName; if (!path.IsNullOrEmpty()) filePath = Path.Combine(path, filePath); - fileSystem.WriteAllText(filePath, text); + this.fileSystem.WriteAllText(filePath, text); return filePath; } diff --git a/src/GitVersion.Core.Tests/Core/DynamicRepositoryTests.cs b/src/GitVersion.Core.Tests/Core/DynamicRepositoryTests.cs index 739f9b0fc7..7d59c725cc 100644 --- a/src/GitVersion.Core.Tests/Core/DynamicRepositoryTests.cs +++ b/src/GitVersion.Core.Tests/Core/DynamicRepositoryTests.cs @@ -29,18 +29,18 @@ private static void ClearReadOnly(DirectoryInfo parentDirectory) public void CreateTemporaryRepository() { // Note: we can't use guid because paths will be too long - workDirectory = Path.Combine(Path.GetTempPath(), "GV"); + this.workDirectory = Path.Combine(Path.GetTempPath(), "GV"); // Clean directory upfront, some build agents are having troubles - if (Directory.Exists(workDirectory)) + if (Directory.Exists(this.workDirectory)) { - var di = new DirectoryInfo(workDirectory); + var di = new DirectoryInfo(this.workDirectory); ClearReadOnly(di); - Directory.Delete(workDirectory, true); + Directory.Delete(this.workDirectory, true); } - Directory.CreateDirectory(workDirectory); + Directory.CreateDirectory(this.workDirectory); } @@ -56,7 +56,7 @@ public void Cleanup() [TestCase("GV_main", "https://github.com/GitTools/GitVersion", MainBranch, "3bdcd899530b4e9b37d13639f317da04a749e728", "4.0.0+1092")] public void FindsVersionInDynamicRepo(string name, string url, string targetBranch, string commitId, string expectedFullSemVer) { - var root = Path.Combine(workDirectory, name); + var root = Path.Combine(this.workDirectory, name); var dynamicDirectory = Path.Combine(root, "D"); // dynamic, keeping directory as short as possible var workingDirectory = Path.Combine(root, "W"); // working, keeping directory as short as possible var gitVersionOptions = new GitVersionOptions diff --git a/src/GitVersion.Core.Tests/Core/GitVersionExecutorTests.cs b/src/GitVersion.Core.Tests/Core/GitVersionExecutorTests.cs index 91186ffe8c..ab1575e506 100644 --- a/src/GitVersion.Core.Tests/Core/GitVersionExecutorTests.cs +++ b/src/GitVersion.Core.Tests/Core/GitVersionExecutorTests.cs @@ -43,12 +43,12 @@ public void CacheKeySameAfterReNormalizing() var environment = new TestEnvironment(); environment.SetEnvironmentVariable(AzurePipelines.EnvironmentVariableName, "true"); - sp = GetServiceProvider(gitVersionOptions, environment: environment); + this.sp = GetServiceProvider(gitVersionOptions, environment: environment); - var preparer = sp.GetService(); + var preparer = this.sp.GetService(); preparer.Prepare(); - var cacheKeyFactory = sp.GetService(); + var cacheKeyFactory = this.sp.GetService(); var cacheKey1 = cacheKeyFactory.Create(null); preparer.Prepare(); @@ -69,9 +69,9 @@ public void GitPreparerShouldNotFailWhenTargetPathNotInitialized() }; Should.NotThrow(() => { - sp = GetServiceProvider(gitVersionOptions); + this.sp = GetServiceProvider(gitVersionOptions); - sp.GetService(); + this.sp.GetService(); }); } @@ -97,11 +97,11 @@ public void CacheKeyForWorktree() WorkingDirectory = worktreePath }; - sp = GetServiceProvider(gitVersionOptions); + this.sp = GetServiceProvider(gitVersionOptions); - var preparer = sp.GetService(); + var preparer = this.sp.GetService(); preparer.Prepare(); - var cacheKey = sp.GetService().Create(null); + var cacheKey = this.sp.GetService().Create(null); cacheKey.Value.ShouldNotBeEmpty(); } finally @@ -153,19 +153,19 @@ public void CacheFileExistsOnDisk() void Action(string s) => stringBuilder.AppendLine(s); var logAppender = new TestLogAppender(Action); - log = new Log(logAppender); + this.log = new Log(logAppender); using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeACommit(); var gitVersionOptions = new GitVersionOptions { WorkingDirectory = fixture.RepositoryPath }; - var gitVersionCalculator = GetGitVersionCalculator(gitVersionOptions, log); + var gitVersionCalculator = GetGitVersionCalculator(gitVersionOptions, this.log); var versionVariables = gitVersionCalculator.CalculateVersionVariables(); versionVariables.AssemblySemVer.ShouldBe("0.1.0.0"); - fileSystem.WriteAllText(versionVariables.FileName, versionCacheFileContent); + this.fileSystem.WriteAllText(versionVariables.FileName, versionCacheFileContent); versionVariables = gitVersionCalculator.CalculateVersionVariables(); versionVariables.AssemblySemVer.ShouldBe("4.10.3.0"); @@ -215,16 +215,16 @@ public void CacheFileExistsOnDiskWhenOverrideConfigIsSpecifiedVersionShouldBeDyn fixture.Repository.MakeACommit(); var gitVersionOptions = new GitVersionOptions { WorkingDirectory = fixture.RepositoryPath }; - var gitVersionCalculator = GetGitVersionCalculator(gitVersionOptions, log); + var gitVersionCalculator = GetGitVersionCalculator(gitVersionOptions, this.log); var versionVariables = gitVersionCalculator.CalculateVersionVariables(); versionVariables.AssemblySemVer.ShouldBe("0.1.0.0"); - fileSystem.WriteAllText(versionVariables.FileName, versionCacheFileContent); + this.fileSystem.WriteAllText(versionVariables.FileName, versionCacheFileContent); - var cacheDirectory = gitVersionCache.GetCacheDirectory(); + var cacheDirectory = this.gitVersionCache.GetCacheDirectory(); - var cacheDirectoryTimestamp = fileSystem.GetLastDirectoryWrite(cacheDirectory); + var cacheDirectoryTimestamp = this.fileSystem.GetLastDirectoryWrite(cacheDirectory); var config = new ConfigurationBuilder().Add(new Config { TagPrefix = "prefix" }).Build(); gitVersionOptions = new GitVersionOptions { WorkingDirectory = fixture.RepositoryPath, ConfigInfo = { OverrideConfig = config } }; @@ -234,7 +234,7 @@ public void CacheFileExistsOnDiskWhenOverrideConfigIsSpecifiedVersionShouldBeDyn versionVariables.AssemblySemVer.ShouldBe("0.1.0.0"); - var cachedDirectoryTimestampAfter = fileSystem.GetLastDirectoryWrite(cacheDirectory); + var cachedDirectoryTimestampAfter = this.fileSystem.GetLastDirectoryWrite(cacheDirectory); cachedDirectoryTimestampAfter.ShouldBe(cacheDirectoryTimestamp, "Cache was updated when override config was set"); } @@ -245,14 +245,14 @@ public void CacheFileIsMissing() void Action(string s) => stringBuilder.AppendLine(s); var logAppender = new TestLogAppender(Action); - log = new Log(logAppender); + this.log = new Log(logAppender); using var fixture = new EmptyRepositoryFixture(); var gitVersionOptions = new GitVersionOptions { WorkingDirectory = fixture.RepositoryPath }; fixture.Repository.MakeACommit(); - var gitVersionCalculator = GetGitVersionCalculator(gitVersionOptions, log, fixture.Repository.ToGitRepository()); + var gitVersionCalculator = GetGitVersionCalculator(gitVersionOptions, this.log, fixture.Repository.ToGitRepository()); gitVersionCalculator.CalculateVersionVariables(); @@ -311,15 +311,15 @@ public void ConfigChangeInvalidatesCache() versionVariables.AssemblySemVer.ShouldBe("0.1.0.0"); versionVariables.FileName.ShouldNotBeNullOrEmpty(); - fileSystem.WriteAllText(versionVariables.FileName, versionCacheFileContent); + this.fileSystem.WriteAllText(versionVariables.FileName, versionCacheFileContent); versionVariables = gitVersionCalculator.CalculateVersionVariables(); versionVariables.AssemblySemVer.ShouldBe("4.10.3.0"); var configPath = Path.Combine(fixture.RepositoryPath, ConfigFileLocator.DefaultFileName); - fileSystem.WriteAllText(configPath, "next-version: 5.0"); + this.fileSystem.WriteAllText(configPath, "next-version: 5.0"); - gitVersionCalculator = GetGitVersionCalculator(gitVersionOptions, fs: fileSystem); + gitVersionCalculator = GetGitVersionCalculator(gitVersionOptions, fs: this.fileSystem); versionVariables = gitVersionCalculator.CalculateVersionVariables(); versionVariables.AssemblySemVer.ShouldBe("5.0.0.0"); @@ -376,7 +376,7 @@ public void NoCacheBypassesCache() versionVariables.AssemblySemVer.ShouldBe("0.1.0.0"); versionVariables.FileName.ShouldNotBeNullOrEmpty(); - fileSystem.WriteAllText(versionVariables.FileName, versionCacheFileContent); + this.fileSystem.WriteAllText(versionVariables.FileName, versionCacheFileContent); versionVariables = gitVersionCalculator.CalculateVersionVariables(); versionVariables.AssemblySemVer.ShouldBe("4.10.3.0"); @@ -436,8 +436,8 @@ public void GetProjectRootDirectoryWorkingDirectoryWithWorktree() WorkingDirectory = worktreePath }; - sp = GetServiceProvider(gitVersionOptions); - var repositoryInfo = sp.GetService(); + this.sp = GetServiceProvider(gitVersionOptions); + var repositoryInfo = this.sp.GetService(); repositoryInfo?.ProjectRootDirectory.TrimEnd('/', '\\').ShouldBe(worktreePath); } finally @@ -458,8 +458,8 @@ public void GetProjectRootDirectoryNoWorktree() WorkingDirectory = fixture.RepositoryPath }; - sp = GetServiceProvider(gitVersionOptions); - var repositoryInfo = sp.GetService(); + this.sp = GetServiceProvider(gitVersionOptions); + var repositoryInfo = this.sp.GetService(); var expectedPath = fixture.RepositoryPath.TrimEnd('/', '\\'); repositoryInfo?.ProjectRootDirectory.TrimEnd('/', '\\').ShouldBe(expectedPath); @@ -475,8 +475,8 @@ public void GetDotGitDirectoryNoWorktree() WorkingDirectory = fixture.RepositoryPath }; - sp = GetServiceProvider(gitVersionOptions); - var repositoryInfo = sp.GetService(); + this.sp = GetServiceProvider(gitVersionOptions); + var repositoryInfo = this.sp.GetService(); var expectedPath = Path.Combine(fixture.RepositoryPath, ".git"); repositoryInfo?.DotGitDirectory.ShouldBe(expectedPath); @@ -502,8 +502,8 @@ public void GetDotGitDirectoryWorktree() WorkingDirectory = worktreePath }; - sp = GetServiceProvider(gitVersionOptions); - var repositoryInfo = sp.GetService(); + this.sp = GetServiceProvider(gitVersionOptions); + var repositoryInfo = this.sp.GetService(); var expectedPath = Path.Combine(fixture.RepositoryPath, ".git"); repositoryInfo?.DotGitDirectory.ShouldBe(expectedPath); @@ -547,13 +547,13 @@ public void CalculateVersionFromWorktreeHead() private IGitVersionCalculateTool GetGitVersionCalculator(GitVersionOptions gitVersionOptions, ILog logger = null, IGitRepository repository = null, IFileSystem fs = null) { - sp = GetServiceProvider(gitVersionOptions, logger, repository, fs); + this.sp = GetServiceProvider(gitVersionOptions, logger, repository, fs); - fileSystem = sp.GetService(); - log = sp.GetService(); - gitVersionCache = sp.GetService(); + this.fileSystem = this.sp.GetService(); + this.log = this.sp.GetService(); + this.gitVersionCache = this.sp.GetService(); - return sp.GetService(); + return this.sp.GetService(); } private static IServiceProvider GetServiceProvider(GitVersionOptions gitVersionOptions, ILog log = null, IGitRepository repository = null, IFileSystem fileSystem = null, IEnvironment environment = null) diff --git a/src/GitVersion.Core.Tests/Core/GitVersionToolDirectoryTests.cs b/src/GitVersion.Core.Tests/Core/GitVersionToolDirectoryTests.cs index 1ed08dd0bb..ae79c3824e 100644 --- a/src/GitVersion.Core.Tests/Core/GitVersionToolDirectoryTests.cs +++ b/src/GitVersion.Core.Tests/Core/GitVersionToolDirectoryTests.cs @@ -18,15 +18,15 @@ public class GitVersionTaskDirectoryTests : TestBase [SetUp] public void SetUp() { - workDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); - gitDirectory = Repository.Init(workDirectory).TrimEnd(Path.DirectorySeparatorChar); - Assert.NotNull(gitDirectory); + this.workDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + this.gitDirectory = Repository.Init(this.workDirectory).TrimEnd(Path.DirectorySeparatorChar); + Assert.NotNull(this.gitDirectory); } [TearDown] public void Cleanup() { - Directory.Delete(workDirectory, true); + Directory.Delete(this.workDirectory, true); } [Test] @@ -57,7 +57,7 @@ public void FindsGitDirectory() [Test] public void FindsGitDirectoryInParent() { - var childDir = Path.Combine(workDirectory, "child"); + var childDir = Path.Combine(this.workDirectory, "child"); Directory.CreateDirectory(childDir); try diff --git a/src/GitVersion.Core.Tests/Core/RepositoryStoreTests.cs b/src/GitVersion.Core.Tests/Core/RepositoryStoreTests.cs index 7614db60f3..4943728446 100644 --- a/src/GitVersion.Core.Tests/Core/RepositoryStoreTests.cs +++ b/src/GitVersion.Core.Tests/Core/RepositoryStoreTests.cs @@ -18,7 +18,7 @@ public class RepositoryStoreTests : TestBase public RepositoryStoreTests() { var sp = ConfigureServices(); - log = sp.GetService(); + this.log = sp.GetService(); } [Test] @@ -63,7 +63,7 @@ public void FindsCorrectMergeBaseForForwardMerge() var develop = fixtureRepository.FindBranch("develop"); var release = fixtureRepository.FindBranch("release-2.0.0"); - var gitRepoMetadataProvider = new RepositoryStore(log, fixtureRepository); + var gitRepoMetadataProvider = new RepositoryStore(this.log, fixtureRepository); var releaseBranchMergeBase = gitRepoMetadataProvider.FindMergeBase(release, develop); @@ -119,7 +119,7 @@ public void FindsCorrectMergeBaseForForwardMergeMovesOn() var develop = fixtureRepository.FindBranch("develop"); var release = fixtureRepository.FindBranch("release-2.0.0"); - var gitRepoMetadataProvider = new RepositoryStore(log, fixtureRepository); + var gitRepoMetadataProvider = new RepositoryStore(this.log, fixtureRepository); var releaseBranchMergeBase = gitRepoMetadataProvider.FindMergeBase(release, develop); @@ -194,7 +194,7 @@ public void FindsCorrectMergeBaseForMultipleForwardMerges() var develop = fixtureRepository.FindBranch("develop"); var release = fixtureRepository.FindBranch("release-2.0.0"); - var gitRepoMetadataProvider = new RepositoryStore(log, fixtureRepository); + var gitRepoMetadataProvider = new RepositoryStore(this.log, fixtureRepository); var releaseBranchMergeBase = gitRepoMetadataProvider.FindMergeBase(release, develop); diff --git a/src/GitVersion.Core.Tests/DocumentationTests.cs b/src/GitVersion.Core.Tests/DocumentationTests.cs index bfc0a78f19..695f7970ce 100644 --- a/src/GitVersion.Core.Tests/DocumentationTests.cs +++ b/src/GitVersion.Core.Tests/DocumentationTests.cs @@ -19,7 +19,7 @@ public class DocumentationTests : TestBase [OneTimeSetUp] public void OneTimeSetUp() { - docsDirectory = GetDocsDirectory(); + this.docsDirectory = GetDocsDirectory(); } [Test] @@ -64,7 +64,7 @@ public void VariableDocumentationIsUpToDate() private string ReadDocumentationFile(string relativeDocumentationFilePath) { - var documentationFilePath = Path.Combine(docsDirectory.FullName, relativeDocumentationFilePath); + var documentationFilePath = Path.Combine(this.docsDirectory.FullName, relativeDocumentationFilePath); // Normalize path separators and such. documentationFilePath = new FileInfo(documentationFilePath).FullName; diff --git a/src/GitVersion.Core.Tests/Extensions/StringFormatWithExtensionTests.cs b/src/GitVersion.Core.Tests/Extensions/StringFormatWithExtensionTests.cs index ed7d2ec612..aca1708b4c 100644 --- a/src/GitVersion.Core.Tests/Extensions/StringFormatWithExtensionTests.cs +++ b/src/GitVersion.Core.Tests/Extensions/StringFormatWithExtensionTests.cs @@ -13,7 +13,7 @@ public class StringFormatWithExtensionTests [SetUp] public void Setup() { - environment = new TestEnvironment(); + this.environment = new TestEnvironment(); } [Test] @@ -22,7 +22,7 @@ public void FormatWithNoTokens() var propertyObject = new { }; var target = "Some String without tokens"; var expected = target; - var actual = target.FormatWith(propertyObject, environment); + var actual = target.FormatWith(propertyObject, this.environment); Assert.AreEqual(expected, actual); } @@ -32,7 +32,7 @@ public void FormatWithSingleSimpleToken() var propertyObject = new { SomeProperty = "SomeValue" }; var target = "{SomeProperty}"; var expected = "SomeValue"; - var actual = target.FormatWith(propertyObject, environment); + var actual = target.FormatWith(propertyObject, this.environment); Assert.AreEqual(expected, actual); } @@ -42,61 +42,61 @@ public void FormatWithMultipleTokensAndVerbatimText() var propertyObject = new { SomeProperty = "SomeValue", AnotherProperty = "Other Value" }; var target = "{SomeProperty} some text {AnotherProperty}"; var expected = "SomeValue some text Other Value"; - var actual = target.FormatWith(propertyObject, environment); + var actual = target.FormatWith(propertyObject, this.environment); Assert.AreEqual(expected, actual); } [Test] public void FormatWithEnvVarToken() { - environment.SetEnvironmentVariable("GIT_VERSION_TEST_VAR", "Env Var Value"); + this.environment.SetEnvironmentVariable("GIT_VERSION_TEST_VAR", "Env Var Value"); var propertyObject = new { }; var target = "{env:GIT_VERSION_TEST_VAR}"; var expected = "Env Var Value"; - var actual = target.FormatWith(propertyObject, environment); + var actual = target.FormatWith(propertyObject, this.environment); Assert.AreEqual(expected, actual); } [Test] public void FormatWithEnvVarTokenWithFallback() { - environment.SetEnvironmentVariable("GIT_VERSION_TEST_VAR", "Env Var Value"); + this.environment.SetEnvironmentVariable("GIT_VERSION_TEST_VAR", "Env Var Value"); var propertyObject = new { }; var target = "{env:GIT_VERSION_TEST_VAR ?? fallback}"; var expected = "Env Var Value"; - var actual = target.FormatWith(propertyObject, environment); + var actual = target.FormatWith(propertyObject, this.environment); Assert.AreEqual(expected, actual); } [Test] public void FormatWithUnsetEnvVarToken_WithFallback() { - environment.SetEnvironmentVariable("GIT_VERSION_UNSET_TEST_VAR", null); + this.environment.SetEnvironmentVariable("GIT_VERSION_UNSET_TEST_VAR", null); var propertyObject = new { }; var target = "{env:GIT_VERSION_UNSET_TEST_VAR ?? fallback}"; var expected = "fallback"; - var actual = target.FormatWith(propertyObject, environment); + var actual = target.FormatWith(propertyObject, this.environment); Assert.AreEqual(expected, actual); } [Test] public void FormatWithUnsetEnvVarToken_WithoutFallback() { - environment.SetEnvironmentVariable("GIT_VERSION_UNSET_TEST_VAR", null); + this.environment.SetEnvironmentVariable("GIT_VERSION_UNSET_TEST_VAR", null); var propertyObject = new { }; var target = "{env:GIT_VERSION_UNSET_TEST_VAR}"; - Assert.Throws(() => target.FormatWith(propertyObject, environment)); + Assert.Throws(() => target.FormatWith(propertyObject, this.environment)); } [Test] public void FormatWithMultipleEnvVars() { - environment.SetEnvironmentVariable("GIT_VERSION_TEST_VAR_1", "Val-1"); - environment.SetEnvironmentVariable("GIT_VERSION_TEST_VAR_2", "Val-2"); + this.environment.SetEnvironmentVariable("GIT_VERSION_TEST_VAR_1", "Val-1"); + this.environment.SetEnvironmentVariable("GIT_VERSION_TEST_VAR_2", "Val-2"); var propertyObject = new { }; var target = "{env:GIT_VERSION_TEST_VAR_1} and {env:GIT_VERSION_TEST_VAR_2}"; var expected = "Val-1 and Val-2"; - var actual = target.FormatWith(propertyObject, environment); + var actual = target.FormatWith(propertyObject, this.environment); Assert.AreEqual(expected, actual); } @@ -107,7 +107,7 @@ public void FormatWithMultipleEnvChars() //Test the greediness of the regex in matching env: char var target = "{env:env:GIT_VERSION_TEST_VAR_1} and {env:DUMMY_VAR ?? fallback}"; var expected = "{env:env:GIT_VERSION_TEST_VAR_1} and fallback"; - var actual = target.FormatWith(propertyObject, environment); + var actual = target.FormatWith(propertyObject, this.environment); Assert.AreEqual(expected, actual); } @@ -117,18 +117,18 @@ public void FormatWithMultipleFallbackChars() var propertyObject = new { }; //Test the greediness of the regex in matching env: and ?? chars var target = "{env:env:GIT_VERSION_TEST_VAR_1} and {env:DUMMY_VAR ??? fallback}"; - var actual = target.FormatWith(propertyObject, environment); + var actual = target.FormatWith(propertyObject, this.environment); Assert.AreEqual(target, actual); } [Test] public void FormatWithSingleFallbackChar() { - environment.SetEnvironmentVariable("DUMMY_ENV_VAR", "Dummy-Val"); + this.environment.SetEnvironmentVariable("DUMMY_ENV_VAR", "Dummy-Val"); var propertyObject = new { }; //Test the sanity of the regex when there is a grammar mismatch var target = "{en:DUMMY_ENV_VAR} and {env:DUMMY_ENV_VAR??fallback}"; - var actual = target.FormatWith(propertyObject, environment); + var actual = target.FormatWith(propertyObject, this.environment); Assert.AreEqual(target, actual); } @@ -138,17 +138,17 @@ public void FormatWIthNullPropagationWithMultipleSpaces() var propertyObject = new { SomeProperty = "Some Value" }; var target = "{SomeProperty} and {env:DUMMY_ENV_VAR ?? fallback}"; var expected = "Some Value and fallback"; - var actual = target.FormatWith(propertyObject, environment); + var actual = target.FormatWith(propertyObject, this.environment); Assert.AreEqual(expected, actual); } [Test] public void FormatEnvVar_WithFallback_QuotedAndEmpty() { - environment.SetEnvironmentVariable("ENV_VAR", null); + this.environment.SetEnvironmentVariable("ENV_VAR", null); var propertyObject = new { }; var target = "{env:ENV_VAR ?? \"\"}"; - var actual = target.FormatWith(propertyObject, environment); + var actual = target.FormatWith(propertyObject, this.environment); Assert.That(actual, Is.EqualTo("")); } @@ -157,7 +157,7 @@ public void FormatProperty_String() { var propertyObject = new { Property = "Value" }; var target = "{Property}"; - var actual = target.FormatWith(propertyObject, environment); + var actual = target.FormatWith(propertyObject, this.environment); Assert.That(actual, Is.EqualTo("Value")); } @@ -166,7 +166,7 @@ public void FormatProperty_Integer() { var propertyObject = new { Property = 42 }; var target = "{Property}"; - var actual = target.FormatWith(propertyObject, environment); + var actual = target.FormatWith(propertyObject, this.environment); Assert.That(actual, Is.EqualTo("42")); } @@ -175,7 +175,7 @@ public void FormatProperty_NullObject() { var propertyObject = new { Property = (object)null }; var target = "{Property}"; - var actual = target.FormatWith(propertyObject, environment); + var actual = target.FormatWith(propertyObject, this.environment); Assert.That(actual, Is.EqualTo("")); } @@ -184,7 +184,7 @@ public void FormatProperty_NullInteger() { var propertyObject = new { Property = (int?)null }; var target = "{Property}"; - var actual = target.FormatWith(propertyObject, environment); + var actual = target.FormatWith(propertyObject, this.environment); Assert.That(actual, Is.EqualTo("")); } @@ -193,7 +193,7 @@ public void FormatProperty_String_WithFallback() { var propertyObject = new { Property = "Value" }; var target = "{Property ?? fallback}"; - var actual = target.FormatWith(propertyObject, environment); + var actual = target.FormatWith(propertyObject, this.environment); Assert.That(actual, Is.EqualTo("Value")); } @@ -202,7 +202,7 @@ public void FormatProperty_Integer_WithFallback() { var propertyObject = new { Property = 42 }; var target = "{Property ?? fallback}"; - var actual = target.FormatWith(propertyObject, environment); + var actual = target.FormatWith(propertyObject, this.environment); Assert.That(actual, Is.EqualTo("42")); } @@ -211,7 +211,7 @@ public void FormatProperty_NullObject_WithFallback() { var propertyObject = new { Property = (object)null }; var target = "{Property ?? fallback}"; - var actual = target.FormatWith(propertyObject, environment); + var actual = target.FormatWith(propertyObject, this.environment); Assert.That(actual, Is.EqualTo("fallback")); } @@ -220,7 +220,7 @@ public void FormatProperty_NullInteger_WithFallback() { var propertyObject = new { Property = (int?)null }; var target = "{Property ?? fallback}"; - var actual = target.FormatWith(propertyObject, environment); + var actual = target.FormatWith(propertyObject, this.environment); Assert.That(actual, Is.EqualTo("fallback")); } @@ -229,7 +229,7 @@ public void FormatProperty_NullObject_WithFallback_Quoted() { var propertyObject = new { Property = (object)null }; var target = "{Property ?? \"fallback\"}"; - var actual = target.FormatWith(propertyObject, environment); + var actual = target.FormatWith(propertyObject, this.environment); Assert.That(actual, Is.EqualTo("fallback")); } @@ -238,7 +238,7 @@ public void FormatProperty_NullObject_WithFallback_QuotedAndPadded() { var propertyObject = new { Property = (object)null }; var target = "{Property ?? \" fallback \"}"; - var actual = target.FormatWith(propertyObject, environment); + var actual = target.FormatWith(propertyObject, this.environment); Assert.That(actual, Is.EqualTo(" fallback ")); } @@ -247,7 +247,7 @@ public void FormatProperty_NullObject_WithFallback_QuotedAndEmpty() { var propertyObject = new { Property = (object)null }; var target = "{Property ?? \"\"}"; - var actual = target.FormatWith(propertyObject, environment); + var actual = target.FormatWith(propertyObject, this.environment); Assert.That(actual, Is.EqualTo("")); } } diff --git a/src/GitVersion.Core.Tests/Helpers/GitVersionContextBuilder.cs b/src/GitVersion.Core.Tests/Helpers/GitVersionContextBuilder.cs index abe9265f1a..39b0416fc1 100644 --- a/src/GitVersion.Core.Tests/Helpers/GitVersionContextBuilder.cs +++ b/src/GitVersion.Core.Tests/Helpers/GitVersionContextBuilder.cs @@ -21,19 +21,19 @@ public class GitVersionContextBuilder public GitVersionContextBuilder WithRepository(IGitRepository gitRepository) { - repository = gitRepository; + this.repository = gitRepository; return this; } public GitVersionContextBuilder WithConfig(Config config) { - configuration = config; + this.configuration = config; return this; } public GitVersionContextBuilder OverrideServices(Action overrides = null) { - overrideServices = overrides; + this.overrideServices = overrides; return this; } @@ -44,7 +44,7 @@ public GitVersionContextBuilder WithDevelopBranch() private GitVersionContextBuilder WithBranch(string branchName) { - repository = CreateRepository(); + this.repository = CreateRepository(); return AddBranch(branchName); } @@ -53,19 +53,19 @@ private GitVersionContextBuilder AddBranch(string branchName) var mockCommit = GitToolsTestingExtensions.CreateMockCommit(); var mockBranch = GitToolsTestingExtensions.CreateMockBranch(branchName, mockCommit); - var branches = repository.Branches.ToList(); + var branches = this.repository.Branches.ToList(); branches.Add(mockBranch); - repository.Branches.GetEnumerator().Returns(_ => ((IEnumerable)branches).GetEnumerator()); - repository.Head.Returns(mockBranch); + this.repository.Branches.GetEnumerator().Returns(_ => ((IEnumerable)branches).GetEnumerator()); + this.repository.Head.Returns(mockBranch); return this; } public void Build() { - var repo = repository ?? CreateRepository(); + var repo = this.repository ?? CreateRepository(); var config = new ConfigurationBuilder() - .Add(configuration ?? new Config()) + .Add(this.configuration ?? new Config()) .Build(); var options = Options.Create(new GitVersionOptions @@ -74,11 +74,11 @@ public void Build() ConfigInfo = { OverrideConfig = config } }); - ServicesProvider = ConfigureServices(services => + this.ServicesProvider = ConfigureServices(services => { services.AddSingleton(options); services.AddSingleton(repo); - overrideServices?.Invoke(services); + this.overrideServices?.Invoke(services); }); } diff --git a/src/GitVersion.Core.Tests/Helpers/TestConsole.cs b/src/GitVersion.Core.Tests/Helpers/TestConsole.cs index d1421f91ba..760f87dca1 100644 --- a/src/GitVersion.Core.Tests/Helpers/TestConsole.cs +++ b/src/GitVersion.Core.Tests/Helpers/TestConsole.cs @@ -11,28 +11,28 @@ public class TestConsole : IConsole public TestConsole(params string[] responses) { - log = new NullLog(); + this.log = new NullLog(); this.responses = new Queue(responses); } public void WriteLine(string msg) { - log.Info(msg + System.Environment.NewLine); + this.log.Info(msg + System.Environment.NewLine); } public void WriteLine() { - log.Info(System.Environment.NewLine); + this.log.Info(System.Environment.NewLine); } public void Write(string msg) { - log.Info(msg); + this.log.Info(msg); } public string ReadLine() { - return responses.Dequeue(); + return this.responses.Dequeue(); } public IDisposable UseColor(ConsoleColor consoleColor) diff --git a/src/GitVersion.Core.Tests/Helpers/TestEnvironment.cs b/src/GitVersion.Core.Tests/Helpers/TestEnvironment.cs index 4521a0d88c..fbe71657b2 100644 --- a/src/GitVersion.Core.Tests/Helpers/TestEnvironment.cs +++ b/src/GitVersion.Core.Tests/Helpers/TestEnvironment.cs @@ -8,17 +8,17 @@ public class TestEnvironment : IEnvironment public TestEnvironment() { - map = new Dictionary(); + this.map = new Dictionary(); } public string GetEnvironmentVariable(string variableName) { - return map.TryGetValue(variableName, out var val) ? val : null; + return this.map.TryGetValue(variableName, out var val) ? val : null; } public void SetEnvironmentVariable(string variableName, string value) { - map[variableName] = value; + this.map[variableName] = value; } } } diff --git a/src/GitVersion.Core.Tests/Helpers/TestFileSystem.cs b/src/GitVersion.Core.Tests/Helpers/TestFileSystem.cs index c57de453bb..2ce1b2a739 100644 --- a/src/GitVersion.Core.Tests/Helpers/TestFileSystem.cs +++ b/src/GitVersion.Core.Tests/Helpers/TestFileSystem.cs @@ -14,43 +14,43 @@ public void Copy(string from, string to, bool overwrite) { var fromPath = Path.GetFullPath(from); var toPath = Path.GetFullPath(to); - if (fileSystem.ContainsKey(toPath)) + if (this.fileSystem.ContainsKey(toPath)) { if (overwrite) - fileSystem.Remove(toPath); + this.fileSystem.Remove(toPath); else throw new IOException("File already exists"); } - if (!fileSystem.TryGetValue(fromPath, out var source)) + if (!this.fileSystem.TryGetValue(fromPath, out var source)) throw new FileNotFoundException($"The source file '{fromPath}' was not found", from); - fileSystem.Add(toPath, source); + this.fileSystem.Add(toPath, source); } public void Move(string from, string to) { var fromPath = Path.GetFullPath(from); Copy(from, to, false); - fileSystem.Remove(fromPath); + this.fileSystem.Remove(fromPath); } public bool Exists(string file) { var path = Path.GetFullPath(file); - return fileSystem.ContainsKey(path); + return this.fileSystem.ContainsKey(path); } public void Delete(string path) { var fullPath = Path.GetFullPath(path); - fileSystem.Remove(fullPath); + this.fileSystem.Remove(fullPath); } public string ReadAllText(string file) { var path = Path.GetFullPath(file); - if (!fileSystem.TryGetValue(path, out var content)) + if (!this.fileSystem.TryGetValue(path, out var content)) throw new FileNotFoundException($"The file '{path}' was not found", path); var encoding = EncodingHelper.DetectEncoding(content) ?? Encoding.UTF8; @@ -60,8 +60,8 @@ public string ReadAllText(string file) public void WriteAllText(string file, string fileContents) { var path = Path.GetFullPath(file); - var encoding = fileSystem.ContainsKey(path) - ? EncodingHelper.DetectEncoding(fileSystem[path]) ?? Encoding.UTF8 + var encoding = this.fileSystem.ContainsKey(path) + ? EncodingHelper.DetectEncoding(this.fileSystem[path]) ?? Encoding.UTF8 : Encoding.UTF8; WriteAllText(path, fileContents, encoding); } @@ -69,7 +69,7 @@ public void WriteAllText(string file, string fileContents) public void WriteAllText(string file, string fileContents, Encoding encoding) { var path = Path.GetFullPath(file); - fileSystem[path] = encoding.GetBytes(fileContents); + this.fileSystem[path] = encoding.GetBytes(fileContents); } public IEnumerable DirectoryEnumerateFiles(string directory, string searchPattern, SearchOption searchOption) @@ -85,9 +85,9 @@ public Stream OpenWrite(string path) public Stream OpenRead(string file) { var path = Path.GetFullPath(file); - if (fileSystem.ContainsKey(path)) + if (this.fileSystem.ContainsKey(path)) { - var content = fileSystem[path]; + var content = this.fileSystem[path]; return new MemoryStream(content); } @@ -97,20 +97,20 @@ public Stream OpenRead(string file) public void CreateDirectory(string directory) { var path = Path.GetFullPath(directory); - if (fileSystem.ContainsKey(path)) + if (this.fileSystem.ContainsKey(path)) { - fileSystem[path] = new byte[0]; + this.fileSystem[path] = new byte[0]; } else { - fileSystem.Add(path, new byte[0]); + this.fileSystem.Add(path, new byte[0]); } } public bool DirectoryExists(string directory) { var path = Path.GetFullPath(directory); - return fileSystem.ContainsKey(path); + return this.fileSystem.ContainsKey(path); } public long GetLastDirectoryWrite(string path) diff --git a/src/GitVersion.Core.Tests/Helpers/TestLogAppender.cs b/src/GitVersion.Core.Tests/Helpers/TestLogAppender.cs index 1f5b728164..f5e38a9120 100644 --- a/src/GitVersion.Core.Tests/Helpers/TestLogAppender.cs +++ b/src/GitVersion.Core.Tests/Helpers/TestLogAppender.cs @@ -13,7 +13,7 @@ public TestLogAppender(Action logAction) } public void WriteTo(LogLevel level, string message) { - logAction(message); + this.logAction(message); } } } diff --git a/src/GitVersion.Core.Tests/Helpers/TestStream.cs b/src/GitVersion.Core.Tests/Helpers/TestStream.cs index b732d4e22d..c92bfd750a 100644 --- a/src/GitVersion.Core.Tests/Helpers/TestStream.cs +++ b/src/GitVersion.Core.Tests/Helpers/TestStream.cs @@ -22,40 +22,40 @@ protected override void Dispose(bool disposing) public override void Flush() { - underlying.Position = 0; - var readToEnd = new StreamReader(underlying).ReadToEnd(); - testFileSystem.WriteAllText(path, readToEnd); + this.underlying.Position = 0; + var readToEnd = new StreamReader(this.underlying).ReadToEnd(); + this.testFileSystem.WriteAllText(this.path, readToEnd); } public override long Seek(long offset, SeekOrigin origin) { - return underlying.Seek(offset, origin); + return this.underlying.Seek(offset, origin); } public override void SetLength(long value) { - underlying.SetLength(value); + this.underlying.SetLength(value); } public override int Read(byte[] buffer, int offset, int count) { - return underlying.Read(buffer, offset, count); + return this.underlying.Read(buffer, offset, count); } public override void Write(byte[] buffer, int offset, int count) { - underlying.Write(buffer, offset, count); + this.underlying.Write(buffer, offset, count); } - public override bool CanRead => underlying.CanRead; - public override bool CanSeek => underlying.CanSeek; - public override bool CanWrite => underlying.CanWrite; - public override long Length => underlying.Length; + public override bool CanRead => this.underlying.CanRead; + public override bool CanSeek => this.underlying.CanSeek; + public override bool CanWrite => this.underlying.CanWrite; + public override long Length => this.underlying.Length; public override long Position { - get => underlying.Position; - set => underlying.Position = value; + get => this.underlying.Position; + set => this.underlying.Position = value; } } } diff --git a/src/GitVersion.Core.Tests/IntegrationTests/MainlineDevelopmentMode.cs b/src/GitVersion.Core.Tests/IntegrationTests/MainlineDevelopmentMode.cs index dbc5e627d6..637003090c 100644 --- a/src/GitVersion.Core.Tests/IntegrationTests/MainlineDevelopmentMode.cs +++ b/src/GitVersion.Core.Tests/IntegrationTests/MainlineDevelopmentMode.cs @@ -30,11 +30,11 @@ public void VerifyNonMainMainlineVersionIdenticalAsMain() fixture.Checkout(MainBranch); fixture.MergeNoFF("feature/foo"); - fixture.AssertFullSemver("1.0.0", config); + fixture.AssertFullSemver("1.0.0", this.config); fixture.BranchTo("support/1.0", "support"); - fixture.AssertFullSemver("1.0.0", config); + fixture.AssertFullSemver("1.0.0", this.config); } [Test] @@ -46,20 +46,20 @@ public void MergedFeatureBranchesToMainImpliesRelease() fixture.BranchTo("feature/foo", "foo"); fixture.MakeACommit("2"); - fixture.AssertFullSemver("1.0.1-foo.1", config); + fixture.AssertFullSemver("1.0.1-foo.1", this.config); fixture.MakeACommit("2.1"); - fixture.AssertFullSemver("1.0.1-foo.2", config); + fixture.AssertFullSemver("1.0.1-foo.2", this.config); fixture.Checkout(MainBranch); fixture.MergeNoFF("feature/foo"); - fixture.AssertFullSemver("1.0.1", config); + fixture.AssertFullSemver("1.0.1", this.config); fixture.BranchTo("feature/foo2", "foo2"); fixture.MakeACommit("3 +semver: minor"); - fixture.AssertFullSemver("1.1.0-foo2.1", config); + fixture.AssertFullSemver("1.1.0-foo2.1", this.config); fixture.Checkout(MainBranch); fixture.MergeNoFF("feature/foo2"); - fixture.AssertFullSemver("1.1.0", config); + fixture.AssertFullSemver("1.1.0", this.config); fixture.BranchTo("feature/foo3", "foo3"); fixture.MakeACommit("4"); @@ -72,37 +72,37 @@ public void MergedFeatureBranchesToMainImpliesRelease() { AmendPreviousCommit = true }); - fixture.AssertFullSemver("1.2.0", config); + fixture.AssertFullSemver("1.2.0", this.config); fixture.BranchTo("feature/foo4", "foo4"); fixture.MakeACommit("5 +semver: major"); - fixture.AssertFullSemver("2.0.0-foo4.1", config); + fixture.AssertFullSemver("2.0.0-foo4.1", this.config); fixture.Checkout(MainBranch); fixture.MergeNoFF("feature/foo4"); - fixture.AssertFullSemver("2.0.0", config); + fixture.AssertFullSemver("2.0.0", this.config); // We should evaluate any commits not included in merge commit calculations for direct commit/push or squash to merge commits fixture.MakeACommit("6 +semver: major"); - fixture.AssertFullSemver("3.0.0", config); + fixture.AssertFullSemver("3.0.0", this.config); fixture.MakeACommit("7 +semver: minor"); - fixture.AssertFullSemver("3.1.0", config); + fixture.AssertFullSemver("3.1.0", this.config); fixture.MakeACommit("8"); - fixture.AssertFullSemver("3.1.1", config); + fixture.AssertFullSemver("3.1.1", this.config); // Finally verify that the merge commits still function properly fixture.BranchTo("feature/foo5", "foo5"); fixture.MakeACommit("9 +semver: minor"); - fixture.AssertFullSemver("3.2.0-foo5.1", config); + fixture.AssertFullSemver("3.2.0-foo5.1", this.config); fixture.Checkout(MainBranch); fixture.MergeNoFF("feature/foo5"); - fixture.AssertFullSemver("3.2.0", config); + fixture.AssertFullSemver("3.2.0", this.config); // One more direct commit for good measure fixture.MakeACommit("10 +semver: minor"); - fixture.AssertFullSemver("3.3.0", config); + fixture.AssertFullSemver("3.3.0", this.config); // And we can commit without bumping semver fixture.MakeACommit("11 +semver: none"); - fixture.AssertFullSemver("3.3.0", config); + fixture.AssertFullSemver("3.3.0", this.config); Console.WriteLine(fixture.SequenceDiagram.GetDiagram()); } @@ -113,14 +113,14 @@ public void VerifyPullRequestsActLikeContinuousDelivery() fixture.Repository.MakeACommit("1"); fixture.MakeATaggedCommit("1.0.0"); fixture.MakeACommit(); - fixture.AssertFullSemver("1.0.1", config); + fixture.AssertFullSemver("1.0.1", this.config); fixture.BranchTo("feature/foo", "foo"); - fixture.AssertFullSemver("1.0.2-foo.0", config); + fixture.AssertFullSemver("1.0.2-foo.0", this.config); fixture.MakeACommit(); fixture.MakeACommit(); fixture.Repository.CreatePullRequestRef("feature/foo", MainBranch, normalise: true, prNumber: 8); - fixture.AssertFullSemver("1.0.2-PullRequest0008.3", config); + fixture.AssertFullSemver("1.0.2-PullRequest0008.3", this.config); } [Test] @@ -131,29 +131,29 @@ public void SupportBranches() fixture.MakeATaggedCommit("1.0.0"); fixture.MakeACommit(); // 1.0.1 fixture.MakeACommit(); // 1.0.2 - fixture.AssertFullSemver("1.0.2", config); + fixture.AssertFullSemver("1.0.2", this.config); fixture.BranchTo("support/1.0", "support10"); - fixture.AssertFullSemver("1.0.2", config); + fixture.AssertFullSemver("1.0.2", this.config); // Move main on fixture.Checkout(MainBranch); fixture.MakeACommit("+semver: major"); // 2.0.0 (on main) - fixture.AssertFullSemver("2.0.0", config); + fixture.AssertFullSemver("2.0.0", this.config); // Continue on support/1.0 fixture.Checkout("support/1.0"); fixture.MakeACommit(); // 1.0.3 fixture.MakeACommit(); // 1.0.4 - fixture.AssertFullSemver("1.0.4", config); + fixture.AssertFullSemver("1.0.4", this.config); fixture.BranchTo("feature/foo", "foo"); - fixture.AssertFullSemver("1.0.5-foo.0", config); + fixture.AssertFullSemver("1.0.5-foo.0", this.config); fixture.MakeACommit(); - fixture.AssertFullSemver("1.0.5-foo.1", config); + fixture.AssertFullSemver("1.0.5-foo.1", this.config); fixture.MakeACommit(); - fixture.AssertFullSemver("1.0.5-foo.2", config); + fixture.AssertFullSemver("1.0.5-foo.2", this.config); fixture.Repository.CreatePullRequestRef("feature/foo", "support/1.0", normalise: true, prNumber: 7); - fixture.AssertFullSemver("1.0.5-PullRequest0007.3", config); + fixture.AssertFullSemver("1.0.5-PullRequest0007.3", this.config); } [Test] @@ -166,20 +166,20 @@ public void VerifyForwardMerge() fixture.BranchTo("feature/foo", "foo"); fixture.MakeACommit(); - fixture.AssertFullSemver("1.0.2-foo.1", config); + fixture.AssertFullSemver("1.0.2-foo.1", this.config); fixture.MakeACommit(); - fixture.AssertFullSemver("1.0.2-foo.2", config); + fixture.AssertFullSemver("1.0.2-foo.2", this.config); fixture.Checkout(MainBranch); fixture.MakeACommit(); - fixture.AssertFullSemver("1.0.2", config); + fixture.AssertFullSemver("1.0.2", this.config); fixture.Checkout("feature/foo"); // This may seem surprising, but this happens because we branched off mainline // and incremented. Mainline has then moved on. We do not follow mainline // in feature branches, you need to merge mainline in to get the mainline version - fixture.AssertFullSemver("1.0.2-foo.2", config); + fixture.AssertFullSemver("1.0.2-foo.2", this.config); fixture.MergeNoFF(MainBranch); - fixture.AssertFullSemver("1.0.3-foo.3", config); + fixture.AssertFullSemver("1.0.3-foo.3", this.config); } [Test] @@ -196,18 +196,18 @@ public void VerifySupportForwardMerge() fixture.Checkout(MainBranch); fixture.MakeACommit("+semver: minor"); - fixture.AssertFullSemver("1.1.0", config); + fixture.AssertFullSemver("1.1.0", this.config); fixture.MergeNoFF("support/1.0"); - fixture.AssertFullSemver("1.1.1", config); + fixture.AssertFullSemver("1.1.1", this.config); fixture.MakeACommit(); - fixture.AssertFullSemver("1.1.2", config); + fixture.AssertFullSemver("1.1.2", this.config); fixture.Checkout("support/1.0"); - fixture.AssertFullSemver("1.0.3", config); + fixture.AssertFullSemver("1.0.3", this.config); fixture.BranchTo("feature/foo", "foo"); fixture.MakeACommit(); fixture.MakeACommit(); - fixture.AssertFullSemver("1.0.4-foo.2", config); // TODO This probably should be 1.0.5 + fixture.AssertFullSemver("1.0.4-foo.2", this.config); // TODO This probably should be 1.0.5 } [Test] @@ -220,31 +220,31 @@ public void VerifyDevelopTracksMainVersion() // branching increments the version fixture.BranchTo("develop"); - fixture.AssertFullSemver("1.1.0-alpha.0", config); + fixture.AssertFullSemver("1.1.0-alpha.0", this.config); fixture.MakeACommit(); - fixture.AssertFullSemver("1.1.0-alpha.1", config); + fixture.AssertFullSemver("1.1.0-alpha.1", this.config); // merging develop into main increments minor version on main fixture.Checkout(MainBranch); fixture.MergeNoFF("develop"); - fixture.AssertFullSemver("1.1.0", config); + fixture.AssertFullSemver("1.1.0", this.config); // a commit on develop before the merge still has the same version number fixture.Checkout("develop"); - fixture.AssertFullSemver("1.1.0-alpha.1", config); + fixture.AssertFullSemver("1.1.0-alpha.1", this.config); // moving on to further work on develop tracks main's version from the merge fixture.MakeACommit(); - fixture.AssertFullSemver("1.2.0-alpha.1", config); + fixture.AssertFullSemver("1.2.0-alpha.1", this.config); // adding a commit to main increments patch fixture.Checkout(MainBranch); fixture.MakeACommit(); - fixture.AssertFullSemver("1.1.1", config); + fixture.AssertFullSemver("1.1.1", this.config); // adding a commit to main doesn't change develop's version fixture.Checkout("develop"); - fixture.AssertFullSemver("1.2.0-alpha.1", config); + fixture.AssertFullSemver("1.2.0-alpha.1", this.config); } [Test] @@ -257,41 +257,41 @@ public void VerifyDevelopFeatureTracksMainVersion() // branching increments the version fixture.BranchTo("develop"); - fixture.AssertFullSemver("1.1.0-alpha.0", config); + fixture.AssertFullSemver("1.1.0-alpha.0", this.config); fixture.MakeACommit(); - fixture.AssertFullSemver("1.1.0-alpha.1", config); + fixture.AssertFullSemver("1.1.0-alpha.1", this.config); // merging develop into main increments minor version on main fixture.Checkout(MainBranch); fixture.MergeNoFF("develop"); - fixture.AssertFullSemver("1.1.0", config); + fixture.AssertFullSemver("1.1.0", this.config); // a commit on develop before the merge still has the same version number fixture.Checkout("develop"); - fixture.AssertFullSemver("1.1.0-alpha.1", config); + fixture.AssertFullSemver("1.1.0-alpha.1", this.config); // a branch from develop before the merge tracks the pre-merge version from main // (note: the commit on develop looks like a commit to this branch, thus the .1) fixture.BranchTo("feature/foo"); - fixture.AssertFullSemver("1.0.2-foo.1", config); + fixture.AssertFullSemver("1.0.2-foo.1", this.config); // further work on the branch tracks the merged version from main fixture.MakeACommit(); - fixture.AssertFullSemver("1.1.1-foo.1", config); + fixture.AssertFullSemver("1.1.1-foo.1", this.config); // adding a commit to main increments patch fixture.Checkout(MainBranch); fixture.MakeACommit(); - fixture.AssertFullSemver("1.1.1", config); + fixture.AssertFullSemver("1.1.1", this.config); // adding a commit to main doesn't change the feature's version fixture.Checkout("feature/foo"); - fixture.AssertFullSemver("1.1.1-foo.1", config); + fixture.AssertFullSemver("1.1.1-foo.1", this.config); // merging the feature to develop increments develop fixture.Checkout("develop"); fixture.MergeNoFF("feature/foo"); - fixture.AssertFullSemver("1.2.0-alpha.2", config); + fixture.AssertFullSemver("1.2.0-alpha.2", this.config); } [Test] @@ -314,7 +314,7 @@ public void VerifyMergingMainToFeatureDoesNotCauseBranchCommitsToIncrementVersio fixture.MakeATaggedCommit("1.0.0"); fixture.MergeNoFF("feature/foo"); - fixture.AssertFullSemver("1.0.1", config); + fixture.AssertFullSemver("1.0.1", this.config); } [Test] @@ -336,7 +336,7 @@ public void VerifyMergingMainToFeatureDoesNotStopMainCommitsIncrementingVersion( fixture.Checkout(MainBranch); fixture.MergeNoFF("feature/foo"); - fixture.AssertFullSemver("1.0.2", config); + fixture.AssertFullSemver("1.0.2", this.config); } [Test] @@ -351,7 +351,7 @@ public void VerifyIssue1154CanForwardMergeMainToFeatureBranch() fixture.Checkout(MainBranch); fixture.MergeNoFF("feature/branch1"); - fixture.AssertFullSemver("0.1.1", config); + fixture.AssertFullSemver("0.1.1", this.config); fixture.Checkout("feature/branch2"); fixture.MakeACommit(); @@ -359,7 +359,7 @@ public void VerifyIssue1154CanForwardMergeMainToFeatureBranch() fixture.MakeACommit(); fixture.MergeNoFF(MainBranch); - fixture.AssertFullSemver("0.1.2-branch2.4", config); + fixture.AssertFullSemver("0.1.2-branch2.4", this.config); } [Test] @@ -390,7 +390,7 @@ public void VerifyMergingMainIntoAFeatureBranchWorksWithMultipleBranches() fixture.MergeNoFF("feature/foo"); fixture.MergeNoFF("feature/bar"); - fixture.AssertFullSemver("1.0.2", config); + fixture.AssertFullSemver("1.0.2", this.config); } [Test] @@ -495,7 +495,7 @@ public void VerifyIncrementConfigIsHonoured() fixture.AssertFullSemver("2.0.0-foo4.1", minorIncrementConfig); fixture.Checkout(MainBranch); fixture.MergeNoFF("feature/foo4"); - fixture.AssertFullSemver("2.0.0", config); + fixture.AssertFullSemver("2.0.0", this.config); // We should evaluate any commits not included in merge commit calculations for direct commit/push or squash to merge commits fixture.MakeACommit("6 +semver: major"); diff --git a/src/GitVersion.Core.Tests/Model/MergeMessageTests.cs b/src/GitVersion.Core.Tests/Model/MergeMessageTests.cs index 12c81a28de..45e1d0a3dd 100644 --- a/src/GitVersion.Core.Tests/Model/MergeMessageTests.cs +++ b/src/GitVersion.Core.Tests/Model/MergeMessageTests.cs @@ -16,7 +16,7 @@ public class MergeMessageTests : TestBase public void NullMessageStringThrows() { // Act / Assert - Should.Throw(() => new MergeMessage(null, config)); + Should.Throw(() => new MergeMessage(null, this.config)); } [TestCase("")] @@ -24,7 +24,7 @@ public void NullMessageStringThrows() public void EmptyMessageString(string message) { // Act - var sut = new MergeMessage(message, config); + var sut = new MergeMessage(message, this.config); // Assert sut.TargetBranch.ShouldBeNull(); @@ -73,7 +73,7 @@ public void ParsesMergeMessage( SemanticVersion expectedVersion) { // Act - var sut = new MergeMessage(message, config); + var sut = new MergeMessage(message, this.config); // Assert sut.FormatName.ShouldBe("Default"); @@ -104,7 +104,7 @@ public void ParsesGitHubPullMergeMessage( int? expectedPullRequestNumber) { // Act - var sut = new MergeMessage(message, config); + var sut = new MergeMessage(message, this.config); // Assert sut.FormatName.ShouldBe("GitHubPull"); @@ -138,7 +138,7 @@ public void ParsesBitBucketPullMergeMessage( int? expectedPullRequestNumber) { // Act - var sut = new MergeMessage(message, config); + var sut = new MergeMessage(message, this.config); // Assert sut.FormatName.ShouldBe("BitBucketPull"); @@ -167,7 +167,7 @@ public void ParsesBitBucketPullMergeMessagev7( int? expectedPullRequestNumber) { // Act - var sut = new MergeMessage(message, config); + var sut = new MergeMessage(message, this.config); // Assert sut.FormatName.ShouldBe("BitBucketPullv7"); @@ -197,7 +197,7 @@ public void ParsesSmartGitMergeMessage( SemanticVersion expectedVersion) { // Act - var sut = new MergeMessage(message, config); + var sut = new MergeMessage(message, this.config); // Assert sut.FormatName.ShouldBe("SmartGit"); @@ -227,7 +227,7 @@ public void ParsesRemoteTrackingMergeMessage( SemanticVersion expectedVersion) { // Act - var sut = new MergeMessage(message, config); + var sut = new MergeMessage(message, this.config); // Assert sut.FormatName.ShouldBe("RemoteTracking"); @@ -254,7 +254,7 @@ public void ParsesInvalidMergeMessage( int? expectedPullRequestNumber) { // Act - var sut = new MergeMessage(message, config); + var sut = new MergeMessage(message, this.config); // Assert sut.FormatName.ShouldBeNull(); @@ -271,13 +271,13 @@ public void MatchesSingleCustomMessage() // Arrange var message = "My custom message"; var definition = "Mycustom"; - config.MergeMessageFormats = new Dictionary + this.config.MergeMessageFormats = new Dictionary { [definition] = message }; // Act - var sut = new MergeMessage(message, config); + var sut = new MergeMessage(message, this.config); // Assert sut.FormatName.ShouldBe(definition); @@ -294,7 +294,7 @@ public void MatchesMultipleCustomMessages() // Arrange var format = "My custom message"; var definition = "Mycustom"; - config.MergeMessageFormats = new Dictionary + this.config.MergeMessageFormats = new Dictionary { ["Default2"] = "some example", ["Default3"] = "another example", @@ -302,7 +302,7 @@ public void MatchesMultipleCustomMessages() }; // Act - var sut = new MergeMessage(format, config); + var sut = new MergeMessage(format, this.config); // Assert sut.FormatName.ShouldBe(definition); @@ -319,7 +319,7 @@ public void MatchesCaptureGroupsFromCustomMessages() // Arrange var format = @"^Merged PR #(?\d+) into (?[^\s]*) from (?:(?[^\s]*))"; var definition = "Mycustom"; - config.MergeMessageFormats = new Dictionary + this.config.MergeMessageFormats = new Dictionary { [definition] = format }; @@ -329,7 +329,7 @@ public void MatchesCaptureGroupsFromCustomMessages() // Act - var sut = new MergeMessage($"Merged PR #{pr} into {target} from {source}", config); + var sut = new MergeMessage($"Merged PR #{pr} into {target} from {source}", this.config); // Assert sut.FormatName.ShouldBe(definition); @@ -346,7 +346,7 @@ public void ReturnsAfterFirstMatchingPattern() // Arrange var format = @"^Merge (branch|tag) '(?[^']*)'(?: into (?[^\s]*))*"; var definition = "Mycustom"; - config.MergeMessageFormats = new Dictionary + this.config.MergeMessageFormats = new Dictionary { [definition] = format, ["Default2"] = format, @@ -354,7 +354,7 @@ public void ReturnsAfterFirstMatchingPattern() }; // Act - var sut = new MergeMessage("Merge branch 'this'", config); + var sut = new MergeMessage("Merge branch 'this'", this.config); // Assert sut.FormatName.ShouldBe(definition); diff --git a/src/GitVersion.Core.Tests/VersionCalculation/BaseVersionCalculatorTests.cs b/src/GitVersion.Core.Tests/VersionCalculation/BaseVersionCalculatorTests.cs index 876656b065..b40cf31769 100644 --- a/src/GitVersion.Core.Tests/VersionCalculation/BaseVersionCalculatorTests.cs +++ b/src/GitVersion.Core.Tests/VersionCalculation/BaseVersionCalculatorTests.cs @@ -191,7 +191,7 @@ public TestIgnoreConfig(IVersionFilter filter) public override IEnumerable ToFilters() { - yield return filter; + yield return this.filter; } } @@ -229,7 +229,7 @@ public V1Strategy(DateTimeOffset? when) public IEnumerable GetVersions() { - yield return new BaseVersion("Source 1", false, new SemanticVersion(1), when, null); + yield return new BaseVersion("Source 1", false, new SemanticVersion(1), this.when, null); } } @@ -252,7 +252,7 @@ public V2Strategy(DateTimeOffset? when) public IEnumerable GetVersions() { - yield return new BaseVersion("Source 2", true, new SemanticVersion(2), when, null); + yield return new BaseVersion("Source 2", true, new SemanticVersion(2), this.when, null); } } @@ -267,7 +267,7 @@ public TestVersionStrategy(params BaseVersion[] versions) public IEnumerable GetVersions() { - return versions; + return this.versions; } } } diff --git a/src/GitVersion.Core.Tests/VersionCalculation/TestBaseVersionCalculator.cs b/src/GitVersion.Core.Tests/VersionCalculation/TestBaseVersionCalculator.cs index d6814aef32..f91ea1c58e 100644 --- a/src/GitVersion.Core.Tests/VersionCalculation/TestBaseVersionCalculator.cs +++ b/src/GitVersion.Core.Tests/VersionCalculation/TestBaseVersionCalculator.cs @@ -17,7 +17,7 @@ public TestBaseVersionCalculator(bool shouldIncrement, SemanticVersion semanticV public BaseVersion GetBaseVersion() { - return new BaseVersion("Test source", shouldIncrement, semanticVersion, source, null); + return new BaseVersion("Test source", this.shouldIncrement, this.semanticVersion, this.source, null); } } } diff --git a/src/GitVersion.Core.Tests/VersionCalculation/TestMainlineVersionCalculator.cs b/src/GitVersion.Core.Tests/VersionCalculation/TestMainlineVersionCalculator.cs index 1cc5a1168c..69e0af9ad9 100644 --- a/src/GitVersion.Core.Tests/VersionCalculation/TestMainlineVersionCalculator.cs +++ b/src/GitVersion.Core.Tests/VersionCalculation/TestMainlineVersionCalculator.cs @@ -18,7 +18,7 @@ public SemanticVersion FindMainlineModeVersion(BaseVersion baseVersion) public SemanticVersionBuildMetaData CreateVersionBuildMetaData(ICommit baseVersionSource) { - return metaData; + return this.metaData; } } } diff --git a/src/GitVersion.Core.Tests/VersionCalculation/VariableProviderTests.cs b/src/GitVersion.Core.Tests/VersionCalculation/VariableProviderTests.cs index 699e134ca7..32ce031268 100644 --- a/src/GitVersion.Core.Tests/VersionCalculation/VariableProviderTests.cs +++ b/src/GitVersion.Core.Tests/VersionCalculation/VariableProviderTests.cs @@ -20,15 +20,15 @@ public void Setup() { ShouldlyConfiguration.ShouldMatchApprovedDefaults.LocateTestMethodUsingAttribute(); - logMessages = new List(); + this.logMessages = new List(); var sp = ConfigureServices(services => { - var log = new Log(new TestLogAppender(logMessages.Add)); + var log = new Log(new TestLogAppender(this.logMessages.Add)); services.AddSingleton(log); }); - variableProvider = sp.GetService(); + this.variableProvider = sp.GetService(); } [Test] @@ -45,8 +45,8 @@ public void ShouldLogWarningWhenUsingDefaultInformationalVersionInCustomFormat() var propertyName = nameof(SemanticVersionFormatValues.DefaultInformationalVersion); #pragma warning restore CS0618 // Type or member is obsolete var config = new TestEffectiveConfiguration(assemblyInformationalFormat: $"{{{propertyName}}}"); - variableProvider.GetVariablesFor(semVer, config, false); - logMessages.ShouldContain(message => message.Trim().StartsWith("WARN") && message.Contains(propertyName), 1, $"Expected a warning to be logged when using the variable {propertyName} in a configuration format template"); + this.variableProvider.GetVariablesFor(semVer, config, false); + this.logMessages.ShouldContain(message => message.Trim().StartsWith("WARN") && message.Contains(propertyName), 1, $"Expected a warning to be logged when using the variable {propertyName} in a configuration format template"); } [Test] @@ -71,7 +71,7 @@ public void ProvidesVariablesInContinuousDeliveryModeForPreRelease() var config = new TestEffectiveConfiguration(); - var vars = variableProvider.GetVariablesFor(semVer, config, false); + var vars = this.variableProvider.GetVariablesFor(semVer, config, false); vars.ToString().ShouldMatchApproved(c => c.SubFolder("Approved")); } @@ -98,7 +98,7 @@ public void ProvidesVariablesInContinuousDeliveryModeForPreReleaseWithPadding() var config = new TestEffectiveConfiguration(buildMetaDataPadding: 2, legacySemVerPadding: 5); - var vars = variableProvider.GetVariablesFor(semVer, config, false); + var vars = this.variableProvider.GetVariablesFor(semVer, config, false); vars.ToString().ShouldMatchApproved(c => c.SubFolder("Approved")); } @@ -124,7 +124,7 @@ public void ProvidesVariablesInContinuousDeploymentModeForPreRelease() var config = new TestEffectiveConfiguration(versioningMode: VersioningMode.ContinuousDeployment); - var vars = variableProvider.GetVariablesFor(semVer, config, false); + var vars = this.variableProvider.GetVariablesFor(semVer, config, false); vars.ToString().ShouldMatchApproved(c => c.SubFolder("Approved")); } @@ -149,7 +149,7 @@ public void ProvidesVariablesInContinuousDeliveryModeForStable() var config = new TestEffectiveConfiguration(); - var vars = variableProvider.GetVariablesFor(semVer, config, false); + var vars = this.variableProvider.GetVariablesFor(semVer, config, false); vars.ToString().ShouldMatchApproved(c => c.SubFolder("Approved")); } @@ -174,7 +174,7 @@ public void ProvidesVariablesInContinuousDeploymentModeForStable() var config = new TestEffectiveConfiguration(versioningMode: VersioningMode.ContinuousDeployment); - var vars = variableProvider.GetVariablesFor(semVer, config, false); + var vars = this.variableProvider.GetVariablesFor(semVer, config, false); vars.ToString().ShouldMatchApproved(c => c.SubFolder("Approved")); } @@ -202,7 +202,7 @@ public void ProvidesVariablesInContinuousDeploymentModeForStableWhenCurrentCommi var config = new TestEffectiveConfiguration(versioningMode: VersioningMode.ContinuousDeployment); - var vars = variableProvider.GetVariablesFor(semVer, config, true); + var vars = this.variableProvider.GetVariablesFor(semVer, config, true); vars.ToString().ShouldMatchApproved(c => c.SubFolder("Approved")); } @@ -225,7 +225,7 @@ public void ProvidesVariablesInContinuousDeploymentModeWithTagNamePattern() semVer.BuildMetaData.CommitDate = DateTimeOffset.Parse("2014-03-06 23:59:59Z"); var config = new TestEffectiveConfiguration(versioningMode: VersioningMode.ContinuousDeployment, tagNumberPattern: @"[/-](?\d+)[-/]"); - var vars = variableProvider.GetVariablesFor(semVer, config, false); + var vars = this.variableProvider.GetVariablesFor(semVer, config, false); vars.FullSemVer.ShouldBe("1.2.3-PullRequest0002.5"); } @@ -247,7 +247,7 @@ public void ProvidesVariablesInContinuousDeploymentModeWithTagSetToUseBranchName semVer.BuildMetaData.CommitDate = DateTimeOffset.Parse("2014-03-06 23:59:59Z"); var config = new TestEffectiveConfiguration(versioningMode: VersioningMode.ContinuousDeployment, tag: "useBranchName"); - var vars = variableProvider.GetVariablesFor(semVer, config, false); + var vars = this.variableProvider.GetVariablesFor(semVer, config, false); vars.FullSemVer.ShouldBe("1.2.3-feature.5"); } @@ -274,7 +274,7 @@ public void ProvidesVariablesInContinuousDeliveryModeForFeatureBranch() var config = new TestEffectiveConfiguration(); - var vars = variableProvider.GetVariablesFor(semVer, config, false); + var vars = this.variableProvider.GetVariablesFor(semVer, config, false); vars.ToString().ShouldMatchApproved(c => c.SubFolder("Approved")); } @@ -301,7 +301,7 @@ public void ProvidesVariablesInContinuousDeliveryModeForFeatureBranchWithCustomA var config = new TestEffectiveConfiguration(assemblyInformationalFormat: "{Major}.{Minor}.{Patch}+{CommitsSinceVersionSource}.Branch.{BranchName}.Sha.{ShortSha}"); - var vars = variableProvider.GetVariablesFor(semVer, config, false); + var vars = this.variableProvider.GetVariablesFor(semVer, config, false); vars.ToString().ShouldMatchApproved(c => c.SubFolder("Approved")); } diff --git a/src/GitVersion.Core.Tests/VersionConverters/AssemblyInfoFileUpdaterTests.cs b/src/GitVersion.Core.Tests/VersionConverters/AssemblyInfoFileUpdaterTests.cs index ed26972692..1973820668 100644 --- a/src/GitVersion.Core.Tests/VersionConverters/AssemblyInfoFileUpdaterTests.cs +++ b/src/GitVersion.Core.Tests/VersionConverters/AssemblyInfoFileUpdaterTests.cs @@ -30,9 +30,9 @@ public void Setup() var sp = ConfigureServices(); - log = sp.GetService(); - fileSystem = sp.GetService(); - variableProvider = sp.GetService(); + this.log = sp.GetService(); + this.fileSystem = sp.GetService(); + this.variableProvider = sp.GetService(); } [TestCase("cs")] @@ -45,12 +45,12 @@ public void ShouldCreateAssemblyInfoFileWhenNotExistsAndEnsureAssemblyInfo(strin var workingDir = Path.GetTempPath(); var assemblyInfoFile = "VersionAssemblyInfo." + fileExtension; var fullPath = Path.Combine(workingDir, assemblyInfoFile); - var variables = variableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", "v"), new TestEffectiveConfiguration(), false); + var variables = this.variableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", "v"), new TestEffectiveConfiguration(), false); - using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fileSystem); + using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, this.fileSystem); assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, true, assemblyInfoFile)); - fileSystem.ReadAllText(fullPath).ShouldMatchApproved(c => c.SubFolder(Path.Combine("Approved", fileExtension))); + this.fileSystem.ReadAllText(fullPath).ShouldMatchApproved(c => c.SubFolder(Path.Combine("Approved", fileExtension))); } [TestCase("cs")] @@ -63,12 +63,12 @@ public void ShouldCreateAssemblyInfoFileAtPathWhenNotExistsAndEnsureAssemblyInfo var workingDir = Path.GetTempPath(); var assemblyInfoFile = Path.Combine("src", "Project", "Properties", "VersionAssemblyInfo." + fileExtension); var fullPath = Path.Combine(workingDir, assemblyInfoFile); - var variables = variableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", "v"), new TestEffectiveConfiguration(), false); + var variables = this.variableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", "v"), new TestEffectiveConfiguration(), false); - using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fileSystem); + using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, this.fileSystem); assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, true, assemblyInfoFile)); - fileSystem.ReadAllText(fullPath).ShouldMatchApproved(c => c.SubFolder(Path.Combine("Approved", fileExtension))); + this.fileSystem.ReadAllText(fullPath).ShouldMatchApproved(c => c.SubFolder(Path.Combine("Approved", fileExtension))); } [TestCase("cs")] @@ -84,15 +84,15 @@ public void ShouldCreateAssemblyInfoFilesAtPathWhenNotExistsAndEnsureAssemblyInf "AssemblyInfo." + fileExtension, Path.Combine("src", "Project", "Properties", "VersionAssemblyInfo." + fileExtension) }; - var variables = variableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", "v"), new TestEffectiveConfiguration(), false); + var variables = this.variableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", "v"), new TestEffectiveConfiguration(), false); - using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fileSystem); + using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, this.fileSystem); assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, true, assemblyInfoFiles.ToArray())); foreach (var item in assemblyInfoFiles) { var fullPath = Path.Combine(workingDir, item); - fileSystem.ReadAllText(fullPath).ShouldMatchApproved(c => c.SubFolder(Path.Combine("Approved", fileExtension))); + this.fileSystem.ReadAllText(fullPath).ShouldMatchApproved(c => c.SubFolder(Path.Combine("Approved", fileExtension))); } } @@ -104,41 +104,41 @@ public void ShouldNotCreateAssemblyInfoFileWhenNotExistsAndNotEnsureAssemblyInfo var workingDir = Path.GetTempPath(); var assemblyInfoFile = "VersionAssemblyInfo." + fileExtension; var fullPath = Path.Combine(workingDir, assemblyInfoFile); - var variables = variableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", "v"), new TestEffectiveConfiguration(), false); + var variables = this.variableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", "v"), new TestEffectiveConfiguration(), false); - using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fileSystem); + using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, this.fileSystem); assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, false, assemblyInfoFile)); - fileSystem.Exists(fullPath).ShouldBeFalse(); + this.fileSystem.Exists(fullPath).ShouldBeFalse(); } [Test] public void ShouldNotCreateAssemblyInfoFileForUnknownSourceCodeAndEnsureAssemblyInfo() { - fileSystem = Substitute.For(); + this.fileSystem = Substitute.For(); var workingDir = Path.GetTempPath(); var assemblyInfoFile = "VersionAssemblyInfo.js"; var fullPath = Path.Combine(workingDir, assemblyInfoFile); - var variables = variableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", "v"), new TestEffectiveConfiguration(), false); + var variables = this.variableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", "v"), new TestEffectiveConfiguration(), false); - using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fileSystem); + using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, this.fileSystem); assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, true, assemblyInfoFile)); - fileSystem.Received(0).WriteAllText(fullPath, Arg.Any()); + this.fileSystem.Received(0).WriteAllText(fullPath, Arg.Any()); } [Test] public void ShouldStartSearchFromWorkingDirectory() { - fileSystem = Substitute.For(); + this.fileSystem = Substitute.For(); var workingDir = Path.GetTempPath(); var assemblyInfoFiles = Array.Empty(); - var variables = variableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", "v"), new TestEffectiveConfiguration(), false); + var variables = this.variableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", "v"), new TestEffectiveConfiguration(), false); - using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fileSystem); + using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, this.fileSystem); assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, false, assemblyInfoFiles.ToArray())); - fileSystem.Received().DirectoryEnumerateFiles(Arg.Is(workingDir), Arg.Any(), Arg.Any()); + this.fileSystem.Received().DirectoryEnumerateFiles(Arg.Is(workingDir), Arg.Any(), Arg.Any()); } [TestCase("cs", "[assembly: AssemblyVersion(\"1.0.0.0\")]\r\n[assembly: AssemblyInformationalVersion(\"1.0.0.0\")]\r\n[assembly: AssemblyFileVersion(\"1.0.0.0\")]")] @@ -152,7 +152,7 @@ public void ShouldReplaceAssemblyVersion(string fileExtension, string assemblyFi VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.MajorMinor, (fs, variables) => { - using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fs); + using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, fs); assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, false, assemblyInfoFile)); fs.Received().WriteAllText(fileName, Arg.Is(s => @@ -175,7 +175,7 @@ public void ShouldNotReplaceAssemblyVersionWhenVersionSchemeIsNone(string fileEx VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.None, verify: (fs, variables) => { - using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fs); + using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, fs); assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, false, assemblyInfoFile)); assemblyFileContent = fs.ReadAllText(fileName); @@ -194,7 +194,7 @@ public void ShouldReplaceAssemblyVersionInRelativePath(string fileExtension, str VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.MajorMinor, (fs, variables) => { - using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fs); + using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, fs); assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, false, assemblyInfoFile)); fs.Received().WriteAllText(fileName, Arg.Is(s => @@ -215,7 +215,7 @@ public void ShouldReplaceAssemblyVersionInRelativePathWithWhiteSpace(string file VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.MajorMinor, (fs, variables) => { - using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fs); + using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, fs); assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, false, assemblyInfoFile)); fs.Received().WriteAllText(fileName, Arg.Is(s => @@ -236,7 +236,7 @@ public void ShouldReplaceAssemblyVersionWithStar(string fileExtension, string as VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.MajorMinor, (fs, variables) => { - using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fs); + using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, fs); assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, false, assemblyInfoFile)); fs.Received().WriteAllText(fileName, Arg.Is(s => @@ -257,7 +257,7 @@ public void ShouldReplaceAssemblyVersionWithAtttributeSuffix(string fileExtensio VerifyAssemblyInfoFile(assemblyFileContent, fileName, verify: (fs, variables) => { - using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fs); + using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, fs); assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, false, assemblyInfoFile)); fs.Received().WriteAllText(fileName, Arg.Is(s => @@ -281,7 +281,7 @@ public void ShouldAddAssemblyVersionIfMissingFromInfoFile(string fileExtension) VerifyAssemblyInfoFile("", fileName, AssemblyVersioningScheme.MajorMinor, (fs, variables) => { - using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fs); + using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, fs); assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, false, assemblyInfoFile)); fs.Received().WriteAllText(fileName, Arg.Is(s => @@ -302,7 +302,7 @@ public void ShouldReplaceAlreadySubstitutedValues(string fileExtension, string a VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.MajorMinor, (fs, variables) => { - using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fs); + using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, fs); assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, false, assemblyInfoFile)); fs.Received().WriteAllText(fileName, Arg.Is(s => @@ -323,7 +323,7 @@ public void ShouldReplaceAssemblyVersionWhenCreatingAssemblyVersionFileAndEnsure VerifyAssemblyInfoFile(assemblyFileContent, fileName, verify: (fs, variables) => { - using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fs); + using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, fs); assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, false, assemblyInfoFile)); fs.Received().WriteAllText(fileName, Arg.Is(s => @@ -344,7 +344,7 @@ public void ShouldReplaceAssemblyVersionInRelativePathWithVariables(string fileE VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.MajorMinor, (fs, variables) => { - using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fs); + using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, fs); assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, false, assemblyInfoFile)); fs.Received().WriteAllText(fileName, Arg.Is(s => @@ -365,7 +365,7 @@ public void ShouldReplaceAssemblyVersionInRelativePathWithVariablesAndWhiteSpace VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.MajorMinor, (fs, variables) => { - using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fs); + using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, fs); assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, false, assemblyInfoFile)); fs.Received().WriteAllText(fileName, Arg.Is(s => @@ -388,7 +388,7 @@ public void ShouldAddAssemblyInformationalVersionWhenUpdatingAssemblyVersionFile VerifyAssemblyInfoFile(assemblyFileContent, fileName, verify: (fs, variables) => { - using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fs); + using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, fs); assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, false, assemblyInfoFile)); assemblyFileContent = fs.ReadAllText(fileName); @@ -409,7 +409,7 @@ public void Issue1183ShouldAddFSharpAssemblyInformationalVersionBesideOtherAttri VerifyAssemblyInfoFile(assemblyFileContent, fileName, verify: (fs, variables) => { - using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fs); + using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, fs); assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, false, assemblyInfoFile)); assemblyFileContent = fs.ReadAllText(fileName); @@ -430,7 +430,7 @@ public void ShouldNotAddAssemblyInformationalVersionWhenVersionSchemeIsNone(stri VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.None, verify: (fs, variables) => { - using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fs); + using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(this.log, fs); assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, false, assemblyInfoFile)); assemblyFileContent = fs.ReadAllText(fileName); @@ -444,7 +444,7 @@ private void VerifyAssemblyInfoFile( AssemblyVersioningScheme versioningScheme = AssemblyVersioningScheme.MajorMinorPatch, Action verify = null) { - fileSystem = Substitute.For(); + this.fileSystem = Substitute.For(); var version = new SemanticVersion { BuildMetaData = new SemanticVersionBuildMetaData("versionSourceHash", 3, "foo", "hash", "shortHash", DateTimeOffset.Now, 0), @@ -453,18 +453,18 @@ private void VerifyAssemblyInfoFile( Patch = 1 }; - fileSystem.Exists(fileName).Returns(true); - fileSystem.ReadAllText(fileName).Returns(assemblyFileContent); - fileSystem.When(f => f.WriteAllText(fileName, Arg.Any())).Do(c => + this.fileSystem.Exists(fileName).Returns(true); + this.fileSystem.ReadAllText(fileName).Returns(assemblyFileContent); + this.fileSystem.When(f => f.WriteAllText(fileName, Arg.Any())).Do(c => { assemblyFileContent = c.ArgAt(1); - fileSystem.ReadAllText(fileName).Returns(assemblyFileContent); + this.fileSystem.ReadAllText(fileName).Returns(assemblyFileContent); }); var config = new TestEffectiveConfiguration(assemblyVersioningScheme: versioningScheme); - var variables = variableProvider.GetVariablesFor(version, config, false); + var variables = this.variableProvider.GetVariablesFor(version, config, false); - verify?.Invoke(fileSystem, variables); + verify?.Invoke(this.fileSystem, variables); } } } diff --git a/src/GitVersion.Core.Tests/VersionConverters/ProjectFileUpdaterTests.cs b/src/GitVersion.Core.Tests/VersionConverters/ProjectFileUpdaterTests.cs index 91dca553f4..224cbb1038 100644 --- a/src/GitVersion.Core.Tests/VersionConverters/ProjectFileUpdaterTests.cs +++ b/src/GitVersion.Core.Tests/VersionConverters/ProjectFileUpdaterTests.cs @@ -27,9 +27,9 @@ public void Setup() { ShouldlyConfiguration.ShouldMatchApprovedDefaults.LocateTestMethodUsingAttribute(); var sp = ConfigureServices(); - log = Substitute.For(); - fileSystem = sp.GetService(); - variableProvider = sp.GetService(); + this.log = Substitute.For(); + this.fileSystem = sp.GetService(); + this.variableProvider = sp.GetService(); } [TestCase(@" @@ -44,7 +44,7 @@ public void Setup() [Description(NoMonoDescription)] public void CanUpdateProjectFileWithStandardProjectFileXml(string xml) { - using var projectFileUpdater = new ProjectFileUpdater(log, fileSystem); + using var projectFileUpdater = new ProjectFileUpdater(this.log, this.fileSystem); var canUpdate = projectFileUpdater.CanUpdateProjectFile(XElement.Parse(xml)); @@ -63,7 +63,7 @@ public void CanUpdateProjectFileWithStandardProjectFileXml(string xml) [Description(NoMonoDescription)] public void CanUpdateProjectFileWithStandardWorkerProjectFileXml(string xml) { - using var projectFileUpdater = new ProjectFileUpdater(log, fileSystem); + using var projectFileUpdater = new ProjectFileUpdater(this.log, this.fileSystem); var canUpdate = projectFileUpdater.CanUpdateProjectFile(XElement.Parse(xml)); @@ -82,7 +82,7 @@ public void CanUpdateProjectFileWithStandardWorkerProjectFileXml(string xml) [Description(NoMonoDescription)] public void CanUpdateProjectFileWithStandardWebProjectFileXml(string xml) { - using var projectFileUpdater = new ProjectFileUpdater(log, fileSystem); + using var projectFileUpdater = new ProjectFileUpdater(this.log, this.fileSystem); var canUpdate = projectFileUpdater.CanUpdateProjectFile(XElement.Parse(xml)); @@ -101,7 +101,7 @@ public void CanUpdateProjectFileWithStandardWebProjectFileXml(string xml) [Description(NoMonoDescription)] public void CanUpdateProjectFileWithStandardDesktopProjectFileXml(string xml) { - using var projectFileUpdater = new ProjectFileUpdater(log, fileSystem); + using var projectFileUpdater = new ProjectFileUpdater(this.log, this.fileSystem); var canUpdate = projectFileUpdater.CanUpdateProjectFile(XElement.Parse(xml)); @@ -119,7 +119,7 @@ public void CanUpdateProjectFileWithStandardDesktopProjectFileXml(string xml) [Description(NoMonoDescription)] public void CanUpdateProjectFileWithRazorClassLibraryProjectFileXml(string xml) { - using var projectFileUpdater = new ProjectFileUpdater(log, fileSystem); + using var projectFileUpdater = new ProjectFileUpdater(this.log, this.fileSystem); var canUpdate = projectFileUpdater.CanUpdateProjectFile(XElement.Parse(xml)); @@ -138,7 +138,7 @@ public void CanUpdateProjectFileWithRazorClassLibraryProjectFileXml(string xml) [Description(NoMonoDescription)] public void CannotUpdateProjectFileWithIncorrectProjectSdk(string xml) { - using var projectFileUpdater = new ProjectFileUpdater(log, fileSystem); + using var projectFileUpdater = new ProjectFileUpdater(this.log, this.fileSystem); var canUpdate = projectFileUpdater.CanUpdateProjectFile(XElement.Parse(xml)); @@ -157,7 +157,7 @@ public void CannotUpdateProjectFileWithIncorrectProjectSdk(string xml) [Description(NoMonoDescription)] public void CannotUpdateProjectFileWithMissingProjectSdk(string xml) { - using var projectFileUpdater = new ProjectFileUpdater(log, fileSystem); + using var projectFileUpdater = new ProjectFileUpdater(this.log, this.fileSystem); var canUpdate = projectFileUpdater.CanUpdateProjectFile(XElement.Parse(xml)); @@ -177,7 +177,7 @@ public void CannotUpdateProjectFileWithMissingProjectSdk(string xml) [Description(NoMonoDescription)] public void CannotUpdateProjectFileWithoutAssemblyInfoGeneration(string xml) { - using var projectFileUpdater = new ProjectFileUpdater(log, fileSystem); + using var projectFileUpdater = new ProjectFileUpdater(this.log, this.fileSystem); var canUpdate = projectFileUpdater.CanUpdateProjectFile(XElement.Parse(xml)); @@ -192,7 +192,7 @@ public void CannotUpdateProjectFileWithoutAssemblyInfoGeneration(string xml) [Description(NoMonoDescription)] public void CannotUpdateProjectFileWithoutAPropertyGroup(string xml) { - using var projectFileUpdater = new ProjectFileUpdater(log, fileSystem); + using var projectFileUpdater = new ProjectFileUpdater(this.log, this.fileSystem); var canUpdate = projectFileUpdater.CanUpdateProjectFile(XElement.Parse(xml)); @@ -211,9 +211,9 @@ public void CannotUpdateProjectFileWithoutAPropertyGroup(string xml) [Description(NoMonoDescription)] public void UpdateProjectXmlVersionElementWithStandardXmlInsertsElement(string xml) { - using var projectFileUpdater = new ProjectFileUpdater(log, fileSystem); + using var projectFileUpdater = new ProjectFileUpdater(this.log, this.fileSystem); - var variables = variableProvider.GetVariablesFor(SemanticVersion.Parse("2.0.0", "v"), new TestEffectiveConfiguration(), false); + var variables = this.variableProvider.GetVariablesFor(SemanticVersion.Parse("2.0.0", "v"), new TestEffectiveConfiguration(), false); var xmlRoot = XElement.Parse(xml); projectFileUpdater.UpdateProjectVersionElement(xmlRoot, ProjectFileUpdater.AssemblyVersionElement, variables.AssemblySemVer); @@ -241,9 +241,9 @@ public void UpdateProjectXmlVersionElementWithStandardXmlInsertsElement(string x [Description(NoMonoDescription)] public void UpdateProjectXmlVersionElementWithStandardXmlModifiesElement(string xml) { - using var projectFileUpdater = new ProjectFileUpdater(log, fileSystem); + using var projectFileUpdater = new ProjectFileUpdater(this.log, this.fileSystem); - var variables = variableProvider.GetVariablesFor(SemanticVersion.Parse("2.0.0", "v"), new TestEffectiveConfiguration(), false); + var variables = this.variableProvider.GetVariablesFor(SemanticVersion.Parse("2.0.0", "v"), new TestEffectiveConfiguration(), false); var xmlRoot = XElement.Parse(xml); projectFileUpdater.UpdateProjectVersionElement(xmlRoot, ProjectFileUpdater.AssemblyVersionElement, variables.AssemblySemVer); @@ -274,9 +274,9 @@ public void UpdateProjectXmlVersionElementWithStandardXmlModifiesElement(string [Description(NoMonoDescription)] public void UpdateProjectXmlVersionElementWithDuplicatePropertyGroupsModifiesLastElement(string xml) { - using var projectFileUpdater = new ProjectFileUpdater(log, fileSystem); + using var projectFileUpdater = new ProjectFileUpdater(this.log, this.fileSystem); - var variables = variableProvider.GetVariablesFor(SemanticVersion.Parse("2.0.0", "v"), new TestEffectiveConfiguration(), false); + var variables = this.variableProvider.GetVariablesFor(SemanticVersion.Parse("2.0.0", "v"), new TestEffectiveConfiguration(), false); var xmlRoot = XElement.Parse(xml); projectFileUpdater.UpdateProjectVersionElement(xmlRoot, ProjectFileUpdater.AssemblyVersionElement, variables.AssemblySemVer); @@ -308,9 +308,9 @@ public void UpdateProjectXmlVersionElementWithDuplicatePropertyGroupsModifiesLas [Description(NoMonoDescription)] public void UpdateProjectXmlVersionElementWithMultipleVersionElementsLastOneIsModified(string xml) { - using var projectFileUpdater = new ProjectFileUpdater(log, fileSystem); + using var projectFileUpdater = new ProjectFileUpdater(this.log, this.fileSystem); - var variables = variableProvider.GetVariablesFor(SemanticVersion.Parse("2.0.0", "v"), new TestEffectiveConfiguration(), false); + var variables = this.variableProvider.GetVariablesFor(SemanticVersion.Parse("2.0.0", "v"), new TestEffectiveConfiguration(), false); var xmlRoot = XElement.Parse(xml); projectFileUpdater.UpdateProjectVersionElement(xmlRoot, ProjectFileUpdater.AssemblyVersionElement, variables.AssemblySemVer); @@ -341,7 +341,7 @@ public void UpdateProjectFileAddsVersionToFile(string xml) VerifyAssemblyInfoFile(xml, fileName, AssemblyVersioningScheme.MajorMinorPatch, verify: (fs, variables) => { - using var projectFileUpdater = new ProjectFileUpdater(log, fs); + using var projectFileUpdater = new ProjectFileUpdater(this.log, fs); projectFileUpdater.Execute(variables, new AssemblyInfoContext(Path.GetTempPath(), false, fileName)); var expectedXml = @" @@ -366,7 +366,7 @@ private void VerifyAssemblyInfoFile( AssemblyVersioningScheme versioningScheme = AssemblyVersioningScheme.MajorMinorPatch, Action verify = null) { - fileSystem = Substitute.For(); + this.fileSystem = Substitute.For(); var version = new SemanticVersion { BuildMetaData = new SemanticVersionBuildMetaData("versionSourceHash", 3, "foo", "hash", "shortHash", DateTimeOffset.Now, 0), @@ -375,18 +375,18 @@ private void VerifyAssemblyInfoFile( Patch = 1 }; - fileSystem.Exists(fileName).Returns(true); - fileSystem.ReadAllText(fileName).Returns(projectFileContent); - fileSystem.When(f => f.WriteAllText(fileName, Arg.Any())).Do(c => + this.fileSystem.Exists(fileName).Returns(true); + this.fileSystem.ReadAllText(fileName).Returns(projectFileContent); + this.fileSystem.When(f => f.WriteAllText(fileName, Arg.Any())).Do(c => { projectFileContent = c.ArgAt(1); - fileSystem.ReadAllText(fileName).Returns(projectFileContent); + this.fileSystem.ReadAllText(fileName).Returns(projectFileContent); }); var config = new TestEffectiveConfiguration(assemblyVersioningScheme: versioningScheme); - var variables = variableProvider.GetVariablesFor(version, config, false); + var variables = this.variableProvider.GetVariablesFor(version, config, false); - verify?.Invoke(fileSystem, variables); + verify?.Invoke(this.fileSystem, variables); } } } diff --git a/src/GitVersion.Core/BuildAgents/BuildAgentBase.cs b/src/GitVersion.Core/BuildAgents/BuildAgentBase.cs index 21b84b4357..489ae54af8 100644 --- a/src/GitVersion.Core/BuildAgents/BuildAgentBase.cs +++ b/src/GitVersion.Core/BuildAgents/BuildAgentBase.cs @@ -13,7 +13,7 @@ public abstract class BuildAgentBase : ICurrentBuildAgent protected BuildAgentBase(IEnvironment environment, ILog log) { - Log = log; + this.Log = log; Environment = environment; } diff --git a/src/GitVersion.Core/BuildAgents/BuildAgentResolver.cs b/src/GitVersion.Core/BuildAgents/BuildAgentResolver.cs index d3480a0062..4f19d2e86b 100644 --- a/src/GitVersion.Core/BuildAgents/BuildAgentResolver.cs +++ b/src/GitVersion.Core/BuildAgents/BuildAgentResolver.cs @@ -17,19 +17,19 @@ public BuildAgentResolver(IEnumerable buildAgents, ILog log) public ICurrentBuildAgent? Resolve() { ICurrentBuildAgent? instance = null; - foreach (var buildAgent in buildAgents) + foreach (var buildAgent in this.buildAgents) { var agentName = buildAgent.GetType().Name; try { if (!buildAgent.CanApplyToCurrentContext()) continue; - log.Info($"Applicable build agent found: '{agentName}'."); + this.log.Info($"Applicable build agent found: '{agentName}'."); instance = (ICurrentBuildAgent)buildAgent; } catch (Exception ex) { - log.Warning($"Failed to check build agent '{agentName}': {ex.Message}"); + this.log.Warning($"Failed to check build agent '{agentName}': {ex.Message}"); } } diff --git a/src/GitVersion.Core/BuildAgents/CodeBuild.cs b/src/GitVersion.Core/BuildAgents/CodeBuild.cs index aecacf1d99..0ed1249e9e 100644 --- a/src/GitVersion.Core/BuildAgents/CodeBuild.cs +++ b/src/GitVersion.Core/BuildAgents/CodeBuild.cs @@ -19,7 +19,7 @@ public CodeBuild(IEnvironment environment, ILog log) : base(environment, log) public void WithPropertyFile(string propertiesFileName) { - file = propertiesFileName; + this.file = propertiesFileName; } protected override string EnvironmentVariable => throw new NotSupportedException($"Accessing {nameof(EnvironmentVariable)} is not supported as {nameof(CodeBuild)} supports two environment variables for branch names."); @@ -53,8 +53,8 @@ public override string[] GenerateSetParameterMessage(string name, string value) public override void WriteIntegration(Action writer, VersionVariables variables, bool updateBuildNumber = true) { base.WriteIntegration(writer, variables); - writer($"Outputting variables to '{file}' ... "); - File.WriteAllLines(file, GenerateBuildLogOutput(variables)); + writer($"Outputting variables to '{this.file}' ... "); + File.WriteAllLines(this.file, GenerateBuildLogOutput(variables)); } public override bool PreventFetch() => true; diff --git a/src/GitVersion.Core/BuildAgents/EnvRun.cs b/src/GitVersion.Core/BuildAgents/EnvRun.cs index 069d5dba29..31ded8e5a6 100644 --- a/src/GitVersion.Core/BuildAgents/EnvRun.cs +++ b/src/GitVersion.Core/BuildAgents/EnvRun.cs @@ -20,7 +20,7 @@ public override bool CanApplyToCurrentContext() { if (!File.Exists(envRunDatabasePath)) { - Log.Error($"The database file of EnvRun.exe was not found at {envRunDatabasePath}."); + this.Log.Error($"The database file of EnvRun.exe was not found at {envRunDatabasePath}."); return false; } diff --git a/src/GitVersion.Core/BuildAgents/GitLabCi.cs b/src/GitVersion.Core/BuildAgents/GitLabCi.cs index 75fb7d98d8..dbe474b7ca 100644 --- a/src/GitVersion.Core/BuildAgents/GitLabCi.cs +++ b/src/GitVersion.Core/BuildAgents/GitLabCi.cs @@ -17,7 +17,7 @@ public GitLabCi(IEnvironment environment, ILog log) : base(environment, log) public void WithPropertyFile(string propertiesFileName) { - file = propertiesFileName; + this.file = propertiesFileName; } protected override string EnvironmentVariable { get; } = EnvironmentVariableName; @@ -46,13 +46,13 @@ public override string[] GenerateSetParameterMessage(string name, string value) public override void WriteIntegration(Action writer, VersionVariables variables, bool updateBuildNumber = true) { base.WriteIntegration(writer, variables); - writer($"Outputting variables to '{file}' ... "); + writer($"Outputting variables to '{this.file}' ... "); WriteVariablesFile(variables); } private void WriteVariablesFile(VersionVariables variables) { - File.WriteAllLines(file, GenerateBuildLogOutput(variables)); + File.WriteAllLines(this.file, GenerateBuildLogOutput(variables)); } } } diff --git a/src/GitVersion.Core/BuildAgents/Jenkins.cs b/src/GitVersion.Core/BuildAgents/Jenkins.cs index 7cdf30bbc0..00803c7676 100644 --- a/src/GitVersion.Core/BuildAgents/Jenkins.cs +++ b/src/GitVersion.Core/BuildAgents/Jenkins.cs @@ -19,7 +19,7 @@ public Jenkins(IEnvironment environment, ILog log) : base(environment, log) public void WithPropertyFile(string propertiesFileName) { - file = propertiesFileName; + this.file = propertiesFileName; } public override string GenerateSetVersionMessage(VersionVariables variables) @@ -62,13 +62,13 @@ public override bool ShouldCleanUpRemotes() public override void WriteIntegration(Action writer, VersionVariables variables, bool updateBuildNumber = true) { base.WriteIntegration(writer, variables); - writer($"Outputting variables to '{file}' ... "); + writer($"Outputting variables to '{this.file}' ... "); WriteVariablesFile(variables); } private void WriteVariablesFile(VersionVariables variables) { - File.WriteAllLines(file, GenerateBuildLogOutput(variables)); + File.WriteAllLines(this.file, GenerateBuildLogOutput(variables)); } } } diff --git a/src/GitVersion.Core/BuildAgents/TeamCity.cs b/src/GitVersion.Core/BuildAgents/TeamCity.cs index 9fab3ad0f9..0852bb9fa3 100644 --- a/src/GitVersion.Core/BuildAgents/TeamCity.cs +++ b/src/GitVersion.Core/BuildAgents/TeamCity.cs @@ -34,7 +34,7 @@ public TeamCity(IEnvironment environment, ILog log) : base(environment, log) private void WriteBranchEnvVariableWarning() { - Log.Warning(@"TeamCity doesn't make the current branch available through environmental variables. + this.Log.Warning(@"TeamCity doesn't make the current branch available through environmental variables. Depending on your authentication and transport setup of your git VCS root things may work. In that case, ignore this warning. In your TeamCity build configuration, add a parameter called `env.Git_Branch` with value %teamcity.build.vcs.branch.% See https://gitversion.net/docs/reference/build-servers/teamcity for more info"); diff --git a/src/GitVersion.Core/Configuration/BranchConfigurationCalculator.cs b/src/GitVersion.Core/Configuration/BranchConfigurationCalculator.cs index 81ddd0aa04..3434dcf2cd 100644 --- a/src/GitVersion.Core/Configuration/BranchConfigurationCalculator.cs +++ b/src/GitVersion.Core/Configuration/BranchConfigurationCalculator.cs @@ -31,7 +31,7 @@ public BranchConfig GetBranchConfiguration(IBranch targetBranch, ICommit? curren if (matchingBranches == null) { - log.Info($"No branch configuration found for branch {targetBranch}, falling back to default configuration"); + this.log.Info($"No branch configuration found for branch {targetBranch}, falling back to default configuration"); matchingBranches = BranchConfig.CreateDefaultBranchConfig(FallbackConfigName) .Apply(new BranchConfig @@ -58,7 +58,7 @@ public BranchConfig GetBranchConfiguration(IBranch targetBranch, ICommit? curren // TODO I think we need to take a fresh approach to this.. it's getting really complex with heaps of edge cases private BranchConfig InheritBranchConfiguration(IBranch targetBranch, BranchConfig branchConfiguration, ICommit? currentCommit, Config configuration, IList? excludedInheritBranches) { - using (log.IndentLog("Attempting to inherit branch configuration from parent branch")) + using (this.log.IndentLog("Attempting to inherit branch configuration from parent branch")) { var excludedBranches = new[] { targetBranch }; // Check if we are a merge commit. If so likely we are a pull request @@ -68,7 +68,7 @@ private BranchConfig InheritBranchConfiguration(IBranch targetBranch, BranchConf excludedBranches = CalculateWhenMultipleParents(currentCommit!, ref targetBranch, excludedBranches); } - excludedInheritBranches ??= repositoryStore.GetExcludedInheritBranches(configuration).ToList(); + excludedInheritBranches ??= this.repositoryStore.GetExcludedInheritBranches(configuration).ToList(); excludedBranches = excludedBranches.Where(b => excludedInheritBranches.All(bte => !b.Equals(bte))).ToArray(); // Add new excluded branches. @@ -76,14 +76,14 @@ private BranchConfig InheritBranchConfiguration(IBranch targetBranch, BranchConf { excludedInheritBranches.Add(excludedBranch); } - var branchesToEvaluate = repositoryStore.ExcludingBranches(excludedInheritBranches).ToList(); + var branchesToEvaluate = this.repositoryStore.ExcludingBranches(excludedInheritBranches).ToList(); - var branchPoint = repositoryStore + var branchPoint = this.repositoryStore .FindCommitBranchWasBranchedFrom(targetBranch, configuration, excludedInheritBranches.ToArray()); List possibleParents; if (branchPoint == BranchCommit.Empty) { - possibleParents = repositoryStore.GetBranchesContainingCommit(targetBranch.Tip, branchesToEvaluate) + possibleParents = this.repositoryStore.GetBranchesContainingCommit(targetBranch.Tip, branchesToEvaluate) // It fails to inherit Increment branch configuration if more than 1 parent; // therefore no point to get more than 2 parents .Take(2) @@ -91,10 +91,10 @@ private BranchConfig InheritBranchConfiguration(IBranch targetBranch, BranchConf } else { - var branches = repositoryStore.GetBranchesContainingCommit(branchPoint.Commit, branchesToEvaluate).ToList(); + var branches = this.repositoryStore.GetBranchesContainingCommit(branchPoint.Commit, branchesToEvaluate).ToList(); if (branches.Count > 1) { - var currentTipBranches = repositoryStore.GetBranchesContainingCommit(currentCommit, branchesToEvaluate).ToList(); + var currentTipBranches = this.repositoryStore.GetBranchesContainingCommit(currentCommit, branchesToEvaluate).ToList(); possibleParents = branches.Except(currentTipBranches).ToList(); } else @@ -103,7 +103,7 @@ private BranchConfig InheritBranchConfiguration(IBranch targetBranch, BranchConf } } - log.Info("Found possible parent branches: " + string.Join(", ", possibleParents.Select(p => p.ToString()))); + this.log.Info("Found possible parent branches: " + string.Join(", ", possibleParents.Select(p => p.ToString()))); if (possibleParents.Count == 1) { @@ -127,7 +127,7 @@ private BranchConfig InheritBranchConfiguration(IBranch targetBranch, BranchConf ? "Failed to inherit Increment branch configuration, no branches found." : "Failed to inherit Increment branch configuration, ended up with: " + string.Join(", ", possibleParents.Select(p => p.ToString())); - var chosenBranch = repositoryStore.GetChosenBranch(configuration); + var chosenBranch = this.repositoryStore.GetChosenBranch(configuration); if (chosenBranch == null) { // TODO We should call the build server to generate this exception, each build server works differently @@ -135,7 +135,7 @@ private BranchConfig InheritBranchConfiguration(IBranch targetBranch, BranchConf throw new InvalidOperationException("Gitversion could not determine which branch to treat as the development branch (default is 'develop') nor releaseable branch (default is 'main' or 'master'), either locally or remotely. Ensure the local clone and checkout match the requirements or considering using 'GitVersion Dynamic Repositories'"); } - log.Warning($"{errorMessage}{System.Environment.NewLine}Falling back to {chosenBranch} branch config"); + this.log.Warning($"{errorMessage}{System.Environment.NewLine}Falling back to {chosenBranch} branch config"); // To prevent infinite loops, make sure that a new branch was chosen. if (targetBranch.Equals(chosenBranch)) @@ -148,7 +148,7 @@ private BranchConfig InheritBranchConfiguration(IBranch targetBranch, BranchConf return developOrMainConfig; } - log.Warning("Fallback branch wants to inherit Increment branch configuration from itself. Using patch increment instead."); + this.log.Warning("Fallback branch wants to inherit Increment branch configuration from itself. Using patch increment instead."); return new BranchConfig(branchConfiguration) { Increment = IncrementStrategy.Patch @@ -159,7 +159,7 @@ private BranchConfig InheritBranchConfiguration(IBranch targetBranch, BranchConf var configIncrement = inheritingBranchConfig.Increment; if (inheritingBranchConfig.Name!.IsEquivalentTo(FallbackConfigName) && configIncrement == IncrementStrategy.Inherit) { - log.Warning("Fallback config inherits by default, dropping to patch increment"); + this.log.Warning("Fallback config inherits by default, dropping to patch increment"); configIncrement = IncrementStrategy.Patch; } return new BranchConfig(branchConfiguration) @@ -175,7 +175,7 @@ private BranchConfig InheritBranchConfiguration(IBranch targetBranch, BranchConf private IBranch[] CalculateWhenMultipleParents(ICommit currentCommit, ref IBranch currentBranch, IBranch[] excludedBranches) { var parents = currentCommit.Parents.ToArray(); - var branches = repositoryStore.GetBranchesForCommit(parents[1]).ToList(); + var branches = this.repositoryStore.GetBranchesForCommit(parents[1]).ToList(); if (branches.Count == 1) { var branch = branches[0]; @@ -192,7 +192,7 @@ private IBranch[] CalculateWhenMultipleParents(ICommit currentCommit, ref IBranc } else { - var possibleTargetBranches = repositoryStore.GetBranchesForCommit(parents[0]).ToList(); + var possibleTargetBranches = this.repositoryStore.GetBranchesForCommit(parents[0]).ToList(); if (possibleTargetBranches.Count > 1) { currentBranch = possibleTargetBranches.FirstOrDefault(b => b.Name.WithoutRemote == Config.MainBranchKey) ?? possibleTargetBranches.First(); @@ -203,7 +203,7 @@ private IBranch[] CalculateWhenMultipleParents(ICommit currentCommit, ref IBranc } } - log.Info($"HEAD is merge commit, this is likely a pull request using {currentBranch} as base"); + this.log.Info($"HEAD is merge commit, this is likely a pull request using {currentBranch} as base"); return excludedBranches; } diff --git a/src/GitVersion.Core/Configuration/ConfigFileLocator.cs b/src/GitVersion.Core/Configuration/ConfigFileLocator.cs index 0fd59e89f2..243060f243 100644 --- a/src/GitVersion.Core/Configuration/ConfigFileLocator.cs +++ b/src/GitVersion.Core/Configuration/ConfigFileLocator.cs @@ -20,13 +20,13 @@ public ConfigFileLocator(IFileSystem fileSystem, IOptions opt public string FilePath { get; } - public bool HasConfigFileAt(string? workingDirectory) => fileSystem.Exists(Path.Combine(workingDirectory, FilePath)); + public bool HasConfigFileAt(string? workingDirectory) => this.fileSystem.Exists(Path.Combine(workingDirectory, FilePath)); public string GetConfigFilePath(string? workingDirectory) => Path.Combine(workingDirectory, FilePath); public void Verify(string? workingDirectory, string? projectRootDirectory) { - if (!Path.IsPathRooted(FilePath) && !fileSystem.PathsEqual(workingDirectory, projectRootDirectory)) + if (!Path.IsPathRooted(FilePath) && !this.fileSystem.PathsEqual(workingDirectory, projectRootDirectory)) { WarnAboutAmbiguousConfigFileSelection(workingDirectory, projectRootDirectory); } @@ -44,9 +44,9 @@ public Config ReadConfig(string? workingDirectory) { var configFilePath = GetConfigFilePath(workingDirectory); - if (fileSystem.Exists(configFilePath)) + if (this.fileSystem.Exists(configFilePath)) { - var readAllText = fileSystem.ReadAllText(configFilePath); + var readAllText = this.fileSystem.ReadAllText(configFilePath); var readConfig = ConfigSerializer.Read(new StringReader(readAllText)); VerifyReadConfig(readConfig); @@ -90,8 +90,8 @@ private void WarnAboutAmbiguousConfigFileSelection(string? workingDirectory, str var workingConfigFile = GetConfigFilePath(workingDirectory); var projectRootConfigFile = GetConfigFilePath(projectRootDirectory); - var hasConfigInWorkingDirectory = fileSystem.Exists(workingConfigFile); - var hasConfigInProjectRootDirectory = fileSystem.Exists(projectRootConfigFile); + var hasConfigInWorkingDirectory = this.fileSystem.Exists(workingConfigFile); + var hasConfigInProjectRootDirectory = this.fileSystem.Exists(projectRootConfigFile); if (hasConfigInProjectRootDirectory && hasConfigInWorkingDirectory) { throw new WarningException($"Ambiguous config file selection from '{workingConfigFile}' and '{projectRootConfigFile}'"); diff --git a/src/GitVersion.Core/Configuration/ConfigProvider.cs b/src/GitVersion.Core/Configuration/ConfigProvider.cs index 4f5bfb57f2..6a1c72ecaa 100644 --- a/src/GitVersion.Core/Configuration/ConfigProvider.cs +++ b/src/GitVersion.Core/Configuration/ConfigProvider.cs @@ -29,33 +29,33 @@ public ConfigProvider(IFileSystem fileSystem, ILog log, IConfigFileLocator confi public Config Provide(Config? overrideConfig = null) { - var gitVersionOptions = options.Value; + var gitVersionOptions = this.options.Value; var workingDirectory = gitVersionOptions.WorkingDirectory; - var projectRootDirectory = repositoryInfo.ProjectRootDirectory; + var projectRootDirectory = this.repositoryInfo.ProjectRootDirectory; - var rootDirectory = configFileLocator.HasConfigFileAt(workingDirectory) ? workingDirectory : projectRootDirectory; + var rootDirectory = this.configFileLocator.HasConfigFileAt(workingDirectory) ? workingDirectory : projectRootDirectory; return Provide(rootDirectory, overrideConfig); } public Config Provide(string? workingDirectory, Config? overrideConfig = null) { return new ConfigurationBuilder() - .Add(configFileLocator.ReadConfig(workingDirectory)) + .Add(this.configFileLocator.ReadConfig(workingDirectory)) .Add(overrideConfig ?? new Config()) .Build(); } public void Init(string workingDirectory) { - var configFilePath = configFileLocator.GetConfigFilePath(workingDirectory); - var currentConfiguration = configFileLocator.ReadConfig(workingDirectory); + var configFilePath = this.configFileLocator.GetConfigFilePath(workingDirectory); + var currentConfiguration = this.configFileLocator.ReadConfig(workingDirectory); - var config = configInitWizard.Run(currentConfiguration, workingDirectory); + var config = this.configInitWizard.Run(currentConfiguration, workingDirectory); if (config == null) return; - using var stream = fileSystem.OpenWrite(configFilePath); + using var stream = this.fileSystem.OpenWrite(configFilePath); using var writer = new StreamWriter(stream); - log.Info("Saving config file"); + this.log.Info("Saving config file"); ConfigSerializer.Write(config, writer); stream.Flush(); } diff --git a/src/GitVersion.Core/Configuration/ConfigurationBuilder.cs b/src/GitVersion.Core/Configuration/ConfigurationBuilder.cs index aa9e5f7289..859a47041b 100644 --- a/src/GitVersion.Core/Configuration/ConfigurationBuilder.cs +++ b/src/GitVersion.Core/Configuration/ConfigurationBuilder.cs @@ -18,7 +18,7 @@ public ConfigurationBuilder Add([NotNull] Config config) { if (config == null) throw new ArgumentNullException(nameof(config)); - _overrides.Add(config); + this._overrides.Add(config); return this; } @@ -27,7 +27,7 @@ public Config Build() { var config = CreateDefaultConfiguration(); - foreach (var overrideConfig in _overrides) + foreach (var overrideConfig in this._overrides) { ApplyOverrides(config, overrideConfig); } diff --git a/src/GitVersion.Core/Configuration/Init/BuildServer/AppVeyorSetup.cs b/src/GitVersion.Core/Configuration/Init/BuildServer/AppVeyorSetup.cs index d3d8b80bf2..8fa540058a 100644 --- a/src/GitVersion.Core/Configuration/Init/BuildServer/AppVeyorSetup.cs +++ b/src/GitVersion.Core/Configuration/Init/BuildServer/AppVeyorSetup.cs @@ -24,13 +24,13 @@ public AppVeyorSetup(IConsole console, IFileSystem fileSystem, ILog log, IConfig public AppVeyorSetup WithData(ProjectVisibility visibility) { - projectVisibility = visibility; + this.projectVisibility = visibility; return this; } protected override StepResult HandleResult(string? result, Queue steps, Config config, string workingDirectory) { - var editConfigStep = StepFactory.CreateStep()!; + var editConfigStep = this.StepFactory.CreateStep()!; switch (result) { case "0": @@ -60,12 +60,12 @@ private static string GetGvCommand(ProjectVisibility visibility) private void GenerateBasicConfig(string workingDirectory) { - WriteConfig(workingDirectory, FileSystem, $@"install: + WriteConfig(workingDirectory, this.FileSystem, $@"install: - choco install gitversion.portable -pre -y before_build: - nuget restore -{GetGvCommand(projectVisibility)} +{GetGvCommand(this.projectVisibility)} build: project: "); @@ -73,7 +73,7 @@ private void GenerateBasicConfig(string workingDirectory) private void GenerateNuGetConfig(string workingDirectory) { - WriteConfig(workingDirectory, FileSystem, $@"install: + WriteConfig(workingDirectory, this.FileSystem, $@"install: - choco install gitversion.portable -pre -y assembly_info: @@ -81,7 +81,7 @@ private void GenerateNuGetConfig(string workingDirectory) before_build: - nuget restore -{GetGvCommand(projectVisibility)} +{GetGvCommand(this.projectVisibility)} build: project: @@ -96,13 +96,13 @@ private void WriteConfig(string workingDirectory, IFileSystem fileSystem, string { var outputFilename = GetOutputFilename(workingDirectory, fileSystem); fileSystem.WriteAllText(outputFilename, configContents); - Log.Info($"AppVeyor sample config file written to {outputFilename}"); + this.Log.Info($"AppVeyor sample config file written to {outputFilename}"); } protected override string GetPrompt(Config config, string workingDirectory) { var prompt = new StringBuilder(); - if (AppVeyorConfigExists(workingDirectory, FileSystem)) + if (AppVeyorConfigExists(workingDirectory, this.FileSystem)) { prompt.AppendLine("GitVersion doesn't support modifying existing appveyor config files. We will generate appveyor.gitversion.yml instead"); prompt.AppendLine(); diff --git a/src/GitVersion.Core/Configuration/Init/BuildServer/AppveyorPublicPrivate.cs b/src/GitVersion.Core/Configuration/Init/BuildServer/AppveyorPublicPrivate.cs index 2b91db921d..3faa30e09f 100644 --- a/src/GitVersion.Core/Configuration/Init/BuildServer/AppveyorPublicPrivate.cs +++ b/src/GitVersion.Core/Configuration/Init/BuildServer/AppveyorPublicPrivate.cs @@ -16,13 +16,13 @@ protected override StepResult HandleResult(string? result, Queue()!); + steps.Enqueue(this.StepFactory.CreateStep()!); return StepResult.Ok(); case "1": - steps.Enqueue(StepFactory.CreateStep()!.WithData(ProjectVisibility.Public)); + steps.Enqueue(this.StepFactory.CreateStep()!.WithData(ProjectVisibility.Public)); return StepResult.Ok(); case "2": - steps.Enqueue(StepFactory.CreateStep()!.WithData(ProjectVisibility.Private)); + steps.Enqueue(this.StepFactory.CreateStep()!.WithData(ProjectVisibility.Private)); return StepResult.Ok(); } return StepResult.Ok(); diff --git a/src/GitVersion.Core/Configuration/Init/BuildServer/SetupBuildScripts.cs b/src/GitVersion.Core/Configuration/Init/BuildServer/SetupBuildScripts.cs index a75e317100..3746466cad 100644 --- a/src/GitVersion.Core/Configuration/Init/BuildServer/SetupBuildScripts.cs +++ b/src/GitVersion.Core/Configuration/Init/BuildServer/SetupBuildScripts.cs @@ -16,10 +16,10 @@ protected override StepResult HandleResult(string? result, Queue()!); + steps.Enqueue(this.StepFactory.CreateStep()!); return StepResult.Ok(); case "1": - steps.Enqueue(StepFactory.CreateStep()!); + steps.Enqueue(this.StepFactory.CreateStep()!); return StepResult.Ok(); } return StepResult.Ok(); diff --git a/src/GitVersion.Core/Configuration/Init/EditConfigStep.cs b/src/GitVersion.Core/Configuration/Init/EditConfigStep.cs index 438c1d94f3..6083df91c2 100644 --- a/src/GitVersion.Core/Configuration/Init/EditConfigStep.cs +++ b/src/GitVersion.Core/Configuration/Init/EditConfigStep.cs @@ -23,25 +23,25 @@ protected override StepResult HandleResult(string? result, Queue()!); + steps.Enqueue(this.StepFactory.CreateStep()!); return StepResult.Ok(); case "3": - steps.Enqueue(StepFactory.CreateStep()!); + steps.Enqueue(this.StepFactory.CreateStep()!); return StepResult.Ok(); case "4": - steps.Enqueue(StepFactory.CreateStep()!); + steps.Enqueue(this.StepFactory.CreateStep()!); return StepResult.Ok(); case "5": - var editConfigStep = StepFactory.CreateStep(); - steps.Enqueue(StepFactory.CreateStep()!.WithData(editConfigStep!, false)); + var editConfigStep = this.StepFactory.CreateStep(); + steps.Enqueue(this.StepFactory.CreateStep()!.WithData(editConfigStep!, false)); return StepResult.Ok(); case "6": - steps.Enqueue(StepFactory.CreateStep()!); + steps.Enqueue(this.StepFactory.CreateStep()!); return StepResult.Ok(); case "7": - steps.Enqueue(StepFactory.CreateStep()!); + steps.Enqueue(this.StepFactory.CreateStep()!); return StepResult.Ok(); } return StepResult.InvalidResponseSelected(); diff --git a/src/GitVersion.Core/Configuration/Init/SetConfig/AssemblyVersioningSchemeSetting.cs b/src/GitVersion.Core/Configuration/Init/SetConfig/AssemblyVersioningSchemeSetting.cs index e313356241..92cb619f6d 100644 --- a/src/GitVersion.Core/Configuration/Init/SetConfig/AssemblyVersioningSchemeSetting.cs +++ b/src/GitVersion.Core/Configuration/Init/SetConfig/AssemblyVersioningSchemeSetting.cs @@ -14,7 +14,7 @@ public AssemblyVersioningSchemeSetting(IConsole console, IFileSystem fileSystem, protected override StepResult HandleResult(string? result, Queue steps, Config config, string workingDirectory) { - var editConfigStep = StepFactory.CreateStep()!; + var editConfigStep = this.StepFactory.CreateStep()!; switch (result) { case "0": diff --git a/src/GitVersion.Core/Configuration/Init/SetConfig/ConfigureBranch.cs b/src/GitVersion.Core/Configuration/Init/SetConfig/ConfigureBranch.cs index d909232458..7041760740 100644 --- a/src/GitVersion.Core/Configuration/Init/SetConfig/ConfigureBranch.cs +++ b/src/GitVersion.Core/Configuration/Init/SetConfig/ConfigureBranch.cs @@ -26,13 +26,13 @@ protected override StepResult HandleResult(string? result, Queue()!); + steps.Enqueue(this.StepFactory.CreateStep()!); return StepResult.Ok(); case "1": - steps.Enqueue(StepFactory.CreateStep()!.WithData(name, branchConfig)); + steps.Enqueue(this.StepFactory.CreateStep()!.WithData(name, branchConfig)); return StepResult.Ok(); case "2": - steps.Enqueue(StepFactory.CreateStep()!.WithData(name!, branchConfig!)); + steps.Enqueue(this.StepFactory.CreateStep()!.WithData(name!, branchConfig!)); return StepResult.Ok(); } @@ -41,11 +41,11 @@ protected override StepResult HandleResult(string? result, Queue "0"; diff --git a/src/GitVersion.Core/Configuration/Init/SetConfig/ConfigureBranches.cs b/src/GitVersion.Core/Configuration/Init/SetConfig/ConfigureBranches.cs index 99dd6f2044..3e2801b72b 100644 --- a/src/GitVersion.Core/Configuration/Init/SetConfig/ConfigureBranches.cs +++ b/src/GitVersion.Core/Configuration/Init/SetConfig/ConfigureBranches.cs @@ -19,7 +19,7 @@ protected override StepResult HandleResult(string? result, Queue()!); + steps.Enqueue(this.StepFactory.CreateStep()!); return StepResult.Ok(); } @@ -32,7 +32,7 @@ protected override StepResult HandleResult(string? result, Queue()!.WithData(foundBranch.Key, branchConfig)); + steps.Enqueue(this.StepFactory.CreateStep()!.WithData(foundBranch.Key, branchConfig)); return StepResult.Ok(); } catch (ArgumentOutOfRangeException) diff --git a/src/GitVersion.Core/Configuration/Init/SetConfig/GlobalModeSetting.cs b/src/GitVersion.Core/Configuration/Init/SetConfig/GlobalModeSetting.cs index 31fd78dd59..72773d55a9 100644 --- a/src/GitVersion.Core/Configuration/Init/SetConfig/GlobalModeSetting.cs +++ b/src/GitVersion.Core/Configuration/Init/SetConfig/GlobalModeSetting.cs @@ -29,19 +29,19 @@ protected override StepResult HandleResult(string? result, Queue "4"; diff --git a/src/GitVersion.Core/Configuration/Init/SetConfig/SetBranchIncrementMode.cs b/src/GitVersion.Core/Configuration/Init/SetConfig/SetBranchIncrementMode.cs index 2e30bef08f..e84fea2618 100644 --- a/src/GitVersion.Core/Configuration/Init/SetConfig/SetBranchIncrementMode.cs +++ b/src/GitVersion.Core/Configuration/Init/SetConfig/SetBranchIncrementMode.cs @@ -25,19 +25,19 @@ public SetBranchIncrementMode WithData(string name, BranchConfig branchConfig) protected override StepResult HandleResult(string? result, Queue steps, Config config, string workingDirectory) { - var configureBranchStep = StepFactory.CreateStep()!; + var configureBranchStep = this.StepFactory.CreateStep()!; switch (result) { case "0": - steps.Enqueue(configureBranchStep.WithData(name, branchConfig)); + steps.Enqueue(configureBranchStep.WithData(this.name, this.branchConfig)); return StepResult.Ok(); case "1": - branchConfig!.VersioningMode = VersioningMode.ContinuousDelivery; - steps.Enqueue(configureBranchStep.WithData(name, branchConfig)); + this.branchConfig!.VersioningMode = VersioningMode.ContinuousDelivery; + steps.Enqueue(configureBranchStep.WithData(name, this.branchConfig)); return StepResult.Ok(); case "2": - branchConfig!.VersioningMode = VersioningMode.ContinuousDeployment; - steps.Enqueue(configureBranchStep.WithData(name, branchConfig)); + this.branchConfig!.VersioningMode = VersioningMode.ContinuousDeployment; + steps.Enqueue(configureBranchStep.WithData(name, this.branchConfig)); return StepResult.Ok(); } @@ -46,7 +46,7 @@ protected override StepResult HandleResult(string? result, Queue()!; + var configureBranchStep = this.StepFactory.CreateStep()!; switch (result) { case "0": - steps.Enqueue(configureBranchStep.WithData(name, branchConfig)); + steps.Enqueue(configureBranchStep.WithData(this.name, this.branchConfig)); return StepResult.Ok(); case "1": - branchConfig!.Tag = string.Empty; - steps.Enqueue(configureBranchStep.WithData(name, branchConfig)); + this.branchConfig!.Tag = string.Empty; + steps.Enqueue(configureBranchStep.WithData(name, this.branchConfig)); return StepResult.Ok(); default: - branchConfig!.Tag = result; - steps.Enqueue(configureBranchStep.WithData(name, branchConfig)); + this.branchConfig!.Tag = result; + steps.Enqueue(configureBranchStep.WithData(name, this.branchConfig)); return StepResult.Ok(); } } diff --git a/src/GitVersion.Core/Configuration/Init/SetNextVersion.cs b/src/GitVersion.Core/Configuration/Init/SetNextVersion.cs index 64f9c0d653..a9274fbd59 100644 --- a/src/GitVersion.Core/Configuration/Init/SetNextVersion.cs +++ b/src/GitVersion.Core/Configuration/Init/SetNextVersion.cs @@ -14,7 +14,7 @@ public SetNextVersion(IConsole console, IFileSystem fileSystem, ILog log, IConfi protected override StepResult HandleResult(string? result, Queue steps, Config config, string workingDirectory) { - var editConfigStep = StepFactory.CreateStep()!; + var editConfigStep = this.StepFactory.CreateStep()!; if (result.IsNullOrEmpty()) { steps.Enqueue(editConfigStep); diff --git a/src/GitVersion.Core/Configuration/Init/Wizard/ConfigInitStepFactory.cs b/src/GitVersion.Core/Configuration/Init/Wizard/ConfigInitStepFactory.cs index a9142f433d..b43dd87b20 100644 --- a/src/GitVersion.Core/Configuration/Init/Wizard/ConfigInitStepFactory.cs +++ b/src/GitVersion.Core/Configuration/Init/Wizard/ConfigInitStepFactory.cs @@ -16,6 +16,6 @@ public ConfigInitStepFactory(IServiceProvider sp) this.sp = sp ?? throw new ArgumentNullException(nameof(sp)); } - public T? CreateStep() => sp!.GetService(); + public T? CreateStep() => this.sp!.GetService(); } } diff --git a/src/GitVersion.Core/Configuration/Init/Wizard/ConfigInitWizard.cs b/src/GitVersion.Core/Configuration/Init/Wizard/ConfigInitWizard.cs index f2e0753d3b..b25b0397d0 100644 --- a/src/GitVersion.Core/Configuration/Init/Wizard/ConfigInitWizard.cs +++ b/src/GitVersion.Core/Configuration/Init/Wizard/ConfigInitWizard.cs @@ -18,9 +18,9 @@ public ConfigInitWizard(IConsole console, IConfigInitStepFactory stepFactory) public Config? Run(Config config, string workingDirectory) { - console.WriteLine("GitVersion init will guide you through setting GitVersion up to work for you"); + this.console.WriteLine("GitVersion init will guide you through setting GitVersion up to work for you"); var steps = new Queue(); - steps.Enqueue(stepFactory.CreateStep()!); + steps.Enqueue(this.stepFactory.CreateStep()!); while (steps.Count > 0) { diff --git a/src/GitVersion.Core/Configuration/Init/Wizard/ConfigInitWizardStep.cs b/src/GitVersion.Core/Configuration/Init/Wizard/ConfigInitWizardStep.cs index e0e787feae..83e3a69998 100644 --- a/src/GitVersion.Core/Configuration/Init/Wizard/ConfigInitWizardStep.cs +++ b/src/GitVersion.Core/Configuration/Init/Wizard/ConfigInitWizardStep.cs @@ -15,23 +15,23 @@ public abstract class ConfigInitWizardStep protected ConfigInitWizardStep(IConsole console, IFileSystem fileSystem, ILog log, IConfigInitStepFactory stepFactory) { - Console = console ?? throw new ArgumentNullException(nameof(console)); - FileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem)); - Log = log ?? throw new ArgumentNullException(nameof(log)); - StepFactory = stepFactory ?? throw new ArgumentNullException(nameof(stepFactory)); + this.Console = console ?? throw new ArgumentNullException(nameof(console)); + this.FileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem)); + this.Log = log ?? throw new ArgumentNullException(nameof(log)); + this.StepFactory = stepFactory ?? throw new ArgumentNullException(nameof(stepFactory)); } public bool Apply(Queue steps, Config config, string workingDirectory) { - Console.WriteLine(); - Console.WriteLine(GetPrompt(config, workingDirectory)); - Console.WriteLine(); - Console.Write("> "); - var input = Console.ReadLine(); + this.Console.WriteLine(); + this.Console.WriteLine(GetPrompt(config, workingDirectory)); + this.Console.WriteLine(); + this.Console.Write("> "); + var input = this.Console.ReadLine(); if (input == null) { - Console.WriteLine("Would you like to save changes? (y/n)"); - input = Console.ReadLine(); + this.Console.WriteLine("Would you like to save changes? (y/n)"); + input = this.Console.ReadLine(); if (input == null || input.ToLower() == "n") return false; if (input.ToLower() == "y") { @@ -58,10 +58,10 @@ public bool Apply(Queue steps, Config config, string worki private void InvalidResponse(Queue steps) { - Console.WriteLine(); - using (Console.UseColor(ConsoleColor.Red)) + this.Console.WriteLine(); + using (this.Console.UseColor(ConsoleColor.Red)) { - Console.WriteLine("Invalid response!"); + this.Console.WriteLine("Invalid response!"); } steps.Enqueue(this); } diff --git a/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy1Step.cs b/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy1Step.cs index 2e36175871..1414c193ee 100644 --- a/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy1Step.cs +++ b/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy1Step.cs @@ -15,13 +15,13 @@ protected override StepResult HandleResult(string? result, Queue()!); + steps.Enqueue(this.StepFactory.CreateStep()!); return StepResult.Ok(); case "n": - steps.Enqueue(StepFactory.CreateStep()!); + steps.Enqueue(this.StepFactory.CreateStep()!); return StepResult.Ok(); } diff --git a/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy2Step.cs b/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy2Step.cs index c0849d69be..05115e3f87 100644 --- a/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy2Step.cs +++ b/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy2Step.cs @@ -15,16 +15,16 @@ protected override StepResult HandleResult(string? result, Queue()!); + steps.Enqueue(this.StepFactory.CreateStep()!); return StepResult.Ok(); case "n": - steps.Enqueue(StepFactory.CreateStep()!); + steps.Enqueue(this.StepFactory.CreateStep()!); return StepResult.Ok(); } diff --git a/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy3Step.cs b/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy3Step.cs index 8b88dd5ad6..4bd0388044 100644 --- a/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy3Step.cs +++ b/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy3Step.cs @@ -15,20 +15,20 @@ protected override StepResult HandleResult(string? result, Queue()!); + steps.Enqueue(this.StepFactory.CreateStep()!); return StepResult.Ok(); } diff --git a/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategyStep.cs b/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategyStep.cs index 7e8f24963b..93393c95d3 100644 --- a/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategyStep.cs +++ b/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategyStep.cs @@ -12,17 +12,17 @@ public PickBranchingStrategyStep(IConsole console, IFileSystem fileSystem, ILog protected override StepResult HandleResult(string? result, Queue steps, Config config, string workingDirectory) { - var returnToStep = StepFactory.CreateStep(); + var returnToStep = this.StepFactory.CreateStep(); switch (result) { case "1": - steps.Enqueue(StepFactory.CreateStep()!.WithData(returnToStep!, true)); + steps.Enqueue(this.StepFactory.CreateStep()!.WithData(returnToStep!, true)); break; case "2": - steps.Enqueue(StepFactory.CreateStep()!.WithData(returnToStep!, true)); + steps.Enqueue(this.StepFactory.CreateStep()!.WithData(returnToStep!, true)); break; case "3": - steps.Enqueue(StepFactory.CreateStep()!); + steps.Enqueue(this.StepFactory.CreateStep()!); break; default: return StepResult.InvalidResponseSelected(); diff --git a/src/GitVersion.Core/Core/GitPreparer.cs b/src/GitVersion.Core/Core/GitPreparer.cs index 3a49316ccc..cebd646909 100644 --- a/src/GitVersion.Core/Core/GitPreparer.cs +++ b/src/GitVersion.Core/Core/GitPreparer.cs @@ -34,23 +34,23 @@ public GitPreparer(ILog log, IEnvironment environment, ICurrentBuildAgent buildA this.repositoryInfo = repositoryInfo ?? throw new ArgumentNullException(nameof(repositoryInfo)); this.repositoryStore = repositoryStore ?? throw new ArgumentNullException(nameof(repositoryStore)); this.buildAgent = buildAgent; - retryAction = new RetryAction(); + this.retryAction = new RetryAction(); } public void Prepare() { - var gitVersionOptions = options.Value; + var gitVersionOptions = this.options.Value; // Normalize if we are running on build server - var normalizeGitDirectory = !gitVersionOptions.Settings.NoNormalize && buildAgent != null; - var shouldCleanUpRemotes = buildAgent != null && buildAgent.ShouldCleanUpRemotes(); + var normalizeGitDirectory = !gitVersionOptions.Settings.NoNormalize && this.buildAgent != null; + var shouldCleanUpRemotes = this.buildAgent != null && this.buildAgent.ShouldCleanUpRemotes(); var currentBranch = ResolveCurrentBranch(); - var dotGitDirectory = repositoryInfo.DotGitDirectory; - var projectRoot = repositoryInfo.ProjectRootDirectory; + var dotGitDirectory = this.repositoryInfo.DotGitDirectory; + var projectRoot = this.repositoryInfo.ProjectRootDirectory; - log.Info($"Project root is: {projectRoot}"); - log.Info($"DotGit directory is: {dotGitDirectory}"); + this.log.Info($"Project root is: {projectRoot}"); + this.log.Info($"DotGit directory is: {dotGitDirectory}"); if (dotGitDirectory.IsNullOrEmpty() || projectRoot.IsNullOrEmpty()) { throw new Exception($"Failed to prepare or find the .git directory in path '{gitVersionOptions.WorkingDirectory}'."); @@ -61,7 +61,7 @@ public void Prepare() private void PrepareInternal(bool normalizeGitDirectory, string? currentBranch, bool shouldCleanUpRemotes = false) { - var gitVersionOptions = options.Value; + var gitVersionOptions = this.options.Value; if (!gitVersionOptions.RepositoryInfo.TargetUrl.IsNullOrWhiteSpace()) { CreateDynamicRepository(currentBranch); @@ -80,16 +80,16 @@ private void PrepareInternal(bool normalizeGitDirectory, string? currentBranch, private string? ResolveCurrentBranch() { - var gitVersionOptions = options.Value; + var gitVersionOptions = this.options.Value; var targetBranch = gitVersionOptions.RepositoryInfo.TargetBranch; - if (buildAgent == null) + if (this.buildAgent == null) { return targetBranch; } var isDynamicRepository = !gitVersionOptions.RepositoryInfo.DynamicRepositoryClonePath.IsNullOrWhiteSpace(); - var currentBranch = buildAgent.GetCurrentBranch(isDynamicRepository) ?? targetBranch; - log.Info("Branch from build environment: " + currentBranch); + var currentBranch = this.buildAgent.GetCurrentBranch(isDynamicRepository) ?? targetBranch; + this.log.Info("Branch from build environment: " + currentBranch); return currentBranch; } @@ -98,33 +98,33 @@ private void CleanupDuplicateOrigin() { var remoteToKeep = DefaultRemoteName; // check that we have a remote that matches defaultRemoteName if not take the first remote - if (!repository.Remotes.Any(remote => remote.Name.Equals(DefaultRemoteName, StringComparison.InvariantCultureIgnoreCase))) + if (!this.repository.Remotes.Any(remote => remote.Name.Equals(DefaultRemoteName, StringComparison.InvariantCultureIgnoreCase))) { - remoteToKeep = repository.Remotes.First().Name; + remoteToKeep = this.repository.Remotes.First().Name; } - var duplicateRemotes = repository.Remotes + var duplicateRemotes = this.repository.Remotes .Where(remote => !remote.Name.Equals(remoteToKeep, StringComparison.InvariantCultureIgnoreCase)) .Select(remote => remote.Name); // remove all remotes that are considered duplicates foreach (var remoteName in duplicateRemotes) { - repository.Remotes.Remove(remoteName); + this.repository.Remotes.Remove(remoteName); } } private void CreateDynamicRepository(string? targetBranch) { - var gitVersionOptions = options.Value; + var gitVersionOptions = this.options.Value; if (targetBranch.IsNullOrWhiteSpace()) { throw new Exception("Dynamic Git repositories must have a target branch (/b)"); } - var gitDirectory = repositoryInfo.DynamicGitRepositoryPath; + var gitDirectory = this.repositoryInfo.DynamicGitRepositoryPath; - using (log.IndentLog($"Creating dynamic repository at '{gitDirectory}'")) + using (this.log.IndentLog($"Creating dynamic repository at '{gitDirectory}'")) { var authentication = gitVersionOptions.Authentication; if (!Directory.Exists(gitDirectory)) @@ -133,7 +133,7 @@ private void CreateDynamicRepository(string? targetBranch) } else { - log.Info("Git repository already exists"); + this.log.Info("Git repository already exists"); } NormalizeGitDirectory(targetBranch, true); } @@ -141,18 +141,18 @@ private void CreateDynamicRepository(string? targetBranch) private void NormalizeGitDirectory(string? targetBranch, bool isDynamicRepository) { - using (log.IndentLog($"Normalizing git directory for branch '{targetBranch}'")) + using (this.log.IndentLog($"Normalizing git directory for branch '{targetBranch}'")) { // Normalize (download branches) before using the branch - NormalizeGitDirectory(options.Value.Settings.NoFetch, targetBranch, isDynamicRepository); + NormalizeGitDirectory(this.options.Value.Settings.NoFetch, targetBranch, isDynamicRepository); } } private void CloneRepository(string? repositoryUrl, string? gitDirectory, AuthenticationInfo auth) { - using (log.IndentLog($"Cloning repository from url '{repositoryUrl}'")) + using (this.log.IndentLog($"Cloning repository from url '{repositoryUrl}'")) { - retryAction.Execute(() => repository.Clone(repositoryUrl, gitDirectory, auth)); + this.retryAction.Execute(() => this.repository.Clone(repositoryUrl, gitDirectory, auth)); } } @@ -164,10 +164,10 @@ private void CloneRepository(string? repositoryUrl, string? gitDirectory, Authen /// private void NormalizeGitDirectory(bool noFetch, string? currentBranchName, bool isDynamicRepository) { - var authentication = options.Value.Authentication; + var authentication = this.options.Value.Authentication; // Need to ensure the HEAD does not move, this is essentially a BugCheck - var expectedSha = repository.Head.Tip?.Sha; - var expectedBranchName = repository.Head.Name.Canonical; + var expectedSha = this.repository.Head.Tip?.Sha; + var expectedBranchName = this.repository.Head.Name.Canonical; try { @@ -176,54 +176,54 @@ private void NormalizeGitDirectory(bool noFetch, string? currentBranchName, bool //If noFetch is enabled, then GitVersion will assume that the git repository is normalized before execution, so that fetching from remotes is not required. if (noFetch) { - log.Info("Skipping fetching, if GitVersion does not calculate your version as expected you might need to allow fetching or use dynamic repositories"); + this.log.Info("Skipping fetching, if GitVersion does not calculate your version as expected you might need to allow fetching or use dynamic repositories"); } else { var refSpecs = string.Join(", ", remote.FetchRefSpecs.Select(r => r.Specification)); - log.Info($"Fetching from remote '{remote.Name}' using the following refspecs: {refSpecs}."); - retryAction.Execute(() => repository.Fetch(remote.Name, Enumerable.Empty(), authentication, null)); + this.log.Info($"Fetching from remote '{remote.Name}' using the following refspecs: {refSpecs}."); + this.retryAction.Execute(() => this.repository.Fetch(remote.Name, Enumerable.Empty(), authentication, null)); } EnsureLocalBranchExistsForCurrentBranch(remote, currentBranchName); CreateOrUpdateLocalBranchesFromRemoteTrackingOnes(remote.Name); - var currentBranch = repositoryStore.FindBranch(currentBranchName); + var currentBranch = this.repositoryStore.FindBranch(currentBranchName); // Bug fix for https://github.com/GitTools/GitVersion/issues/1754, head maybe have been changed // if this is a dynamic repository. But only allow this in case the branches are different (branch switch) - if (expectedSha != repository.Head.Tip?.Sha && - (isDynamicRepository || currentBranch is null || !repository.Head.Equals(currentBranch))) + if (expectedSha != this.repository.Head.Tip?.Sha && + (isDynamicRepository || currentBranch is null || !this.repository.Head.Equals(currentBranch))) { - var newExpectedSha = repository.Head.Tip?.Sha; - var newExpectedBranchName = repository.Head.Name.Canonical; + var newExpectedSha = this.repository.Head.Tip?.Sha; + var newExpectedBranchName = this.repository.Head.Name.Canonical; - log.Info($"Head has moved from '{expectedBranchName} | {expectedSha}' => '{newExpectedBranchName} | {newExpectedSha}', allowed since this is a dynamic repository"); + this.log.Info($"Head has moved from '{expectedBranchName} | {expectedSha}' => '{newExpectedBranchName} | {newExpectedSha}', allowed since this is a dynamic repository"); expectedSha = newExpectedSha; } - var headSha = repository.Refs.Head?.TargetIdentifier; + var headSha = this.repository.Refs.Head?.TargetIdentifier; - if (!repository.IsHeadDetached) + if (!this.repository.IsHeadDetached) { - log.Info($"HEAD points at branch '{headSha}'."); + this.log.Info($"HEAD points at branch '{headSha}'."); return; } - log.Info($"HEAD is detached and points at commit '{headSha}'."); - log.Info($"Local Refs:{System.Environment.NewLine}" + string.Join(System.Environment.NewLine, repository.Refs.FromGlob("*").Select(r => $"{r.Name.Canonical} ({r.TargetIdentifier})"))); + this.log.Info($"HEAD is detached and points at commit '{headSha}'."); + this.log.Info($"Local Refs:{System.Environment.NewLine}" + string.Join(System.Environment.NewLine, this.repository.Refs.FromGlob("*").Select(r => $"{r.Name.Canonical} ({r.TargetIdentifier})"))); // In order to decide whether a fake branch is required or not, first check to see if any local branches have the same commit SHA of the head SHA. // If they do, go ahead and checkout that branch // If no, go ahead and check out a new branch, using the known commit SHA as the pointer - var localBranchesWhereCommitShaIsHead = repository.Branches.Where(b => !b.IsRemote && b.Tip?.Sha == headSha).ToList(); + var localBranchesWhereCommitShaIsHead = this.repository.Branches.Where(b => !b.IsRemote && b.Tip?.Sha == headSha).ToList(); var matchingCurrentBranch = !currentBranchName.IsNullOrEmpty() ? localBranchesWhereCommitShaIsHead.SingleOrDefault(b => b.Name.Canonical.Replace("/heads/", "/") == currentBranchName.Replace("/heads/", "/")) : null; if (matchingCurrentBranch != null) { - log.Info($"Checking out local branch '{currentBranchName}'."); + this.log.Info($"Checking out local branch '{currentBranchName}'."); Checkout(matchingCurrentBranch.Name.Canonical); } else if (localBranchesWhereCommitShaIsHead.Count > 1) @@ -232,11 +232,11 @@ private void NormalizeGitDirectory(bool noFetch, string? currentBranchName, bool var csvNames = string.Join(", ", branchNames); const string moveBranchMsg = "Move one of the branches along a commit to remove warning"; - log.Warning($"Found more than one local branch pointing at the commit '{headSha}' ({csvNames})."); + this.log.Warning($"Found more than one local branch pointing at the commit '{headSha}' ({csvNames})."); var main = localBranchesWhereCommitShaIsHead.SingleOrDefault(n => n.Name.EquivalentTo(Config.MainBranchKey)); if (main != null) { - log.Warning("Because one of the branches is 'main', will build main." + moveBranchMsg); + this.log.Warning("Because one of the branches is 'main', will build main." + moveBranchMsg); Checkout(Config.MainBranchKey); } else @@ -245,7 +245,7 @@ private void NormalizeGitDirectory(bool noFetch, string? currentBranchName, bool if (branchesWithoutSeparators.Count == 1) { var branchWithoutSeparator = branchesWithoutSeparators[0]; - log.Warning($"Choosing {branchWithoutSeparator.Name.Canonical} as it is the only branch without / or - in it. " + moveBranchMsg); + this.log.Warning($"Choosing {branchWithoutSeparator.Name.Canonical} as it is the only branch without / or - in it. " + moveBranchMsg); Checkout(branchWithoutSeparator.Name.Canonical); } else @@ -256,20 +256,20 @@ private void NormalizeGitDirectory(bool noFetch, string? currentBranchName, bool } else if (localBranchesWhereCommitShaIsHead.Count == 0) { - log.Info($"No local branch pointing at the commit '{headSha}'. Fake branch needs to be created."); - retryAction.Execute(() => repository.CreateBranchForPullRequestBranch(authentication)); + this.log.Info($"No local branch pointing at the commit '{headSha}'. Fake branch needs to be created."); + this.retryAction.Execute(() => this.repository.CreateBranchForPullRequestBranch(authentication)); } else { - log.Info($"Checking out local branch 'refs/heads/{localBranchesWhereCommitShaIsHead[0]}'."); + this.log.Info($"Checking out local branch 'refs/heads/{localBranchesWhereCommitShaIsHead[0]}'."); Checkout(localBranchesWhereCommitShaIsHead[0].Name.Friendly); } } finally { - if (repository.Head.Tip?.Sha != expectedSha) + if (this.repository.Head.Tip?.Sha != expectedSha) { - if (environment.GetEnvironmentVariable("IGNORE_NORMALISATION_GIT_HEAD_MOVE") != "1") + if (this.environment.GetEnvironmentVariable("IGNORE_NORMALISATION_GIT_HEAD_MOVE") != "1") { // Whoa, HEAD has moved, it shouldn't have. We need to blow up because there is a bug in normalisation throw new BugException($@"GitVersion has a bug, your HEAD has moved after repo normalisation. @@ -284,18 +284,18 @@ To disable this error set an environmental variable called IGNORE_NORMALISATION_ private IRemote EnsureOnlyOneRemoteIsDefined() { - var remotes = repository.Remotes; + var remotes = this.repository.Remotes; var howMany = remotes.Count(); if (howMany == 1) { var remote = remotes.Single(); - log.Info($"One remote found ({remote.Name} -> '{remote.Url}')."); + this.log.Info($"One remote found ({remote.Name} -> '{remote.Url}')."); if (remote.FetchRefSpecs.Any(r => r.Source == "refs/heads/*")) return remote; var allBranchesFetchRefSpec = $"+refs/heads/*:refs/remotes/{remote.Name}/*"; - log.Info($"Adding refspec: {allBranchesFetchRefSpec}"); + this.log.Info($"Adding refspec: {allBranchesFetchRefSpec}"); remotes.Update(remote.Name, allBranchesFetchRefSpec); return remote; } @@ -309,7 +309,7 @@ private void CreateOrUpdateLocalBranchesFromRemoteTrackingOnes(string remoteName var prefix = $"refs/remotes/{remoteName}/"; var remoteHeadCanonicalName = $"{prefix}HEAD"; var headReferenceName = ReferenceName.Parse(remoteHeadCanonicalName); - var remoteTrackingReferences = repository.Refs + var remoteTrackingReferences = this.repository.Refs .FromGlob(prefix + "*") .Where(r => !r.Name.Equals(headReferenceName)); @@ -321,27 +321,27 @@ private void CreateOrUpdateLocalBranchesFromRemoteTrackingOnes(string remoteName var referenceName = ReferenceName.Parse(localCanonicalName); // We do not want to touch our current branch - if (repository.Head.Name.EquivalentTo(branchName)) continue; + if (this.repository.Head.Name.EquivalentTo(branchName)) continue; - if (repository.Refs.Any(x => x.Name.Equals(referenceName))) + if (this.repository.Refs.Any(x => x.Name.Equals(referenceName))) { - var localRef = repository.Refs[localCanonicalName]!; + var localRef = this.repository.Refs[localCanonicalName]!; if (localRef.TargetIdentifier == remoteTrackingReference.TargetIdentifier) { - log.Info($"Skipping update of '{remoteTrackingReference.Name.Canonical}' as it already matches the remote ref."); + this.log.Info($"Skipping update of '{remoteTrackingReference.Name.Canonical}' as it already matches the remote ref."); continue; } var remoteRefTipId = remoteTrackingReference.ReferenceTargetId!; - log.Info($"Updating local ref '{localRef.Name.Canonical}' to point at {remoteRefTipId}."); - retryAction.Execute(() => repository.Refs.UpdateTarget(localRef, remoteRefTipId)); + this.log.Info($"Updating local ref '{localRef.Name.Canonical}' to point at {remoteRefTipId}."); + this.retryAction.Execute(() => this.repository.Refs.UpdateTarget(localRef, remoteRefTipId)); continue; } - log.Info($"Creating local branch from remote tracking '{remoteTrackingReference.Name.Canonical}'."); - repository.Refs.Add(localCanonicalName, remoteTrackingReference.TargetIdentifier, true); + this.log.Info($"Creating local branch from remote tracking '{remoteTrackingReference.Name.Canonical}'."); + this.repository.Refs.Add(localCanonicalName, remoteTrackingReference.TargetIdentifier, true); - var branch = repository.Branches[branchName]!; - repository.Branches.UpdateTrackedBranch(branch, remoteTrackingReferenceName); + var branch = this.repository.Branches[branchName]!; + this.repository.Branches.UpdateTrackedBranch(branch, remoteTrackingReferenceName); } } @@ -362,11 +362,11 @@ public void EnsureLocalBranchExistsForCurrentBranch(IRemote? remote, string? cur ? currentBranch : currentBranch.Replace("refs/", "refs/heads/"); - var repoTip = repository.Head.Tip; + var repoTip = this.repository.Head.Tip; // We currently have the rep.Head of the *default* branch, now we need to look up the right one var originCanonicalName = $"{remote.Name}/{currentBranch}"; - var originBranch = repository.Branches[originCanonicalName]; + var originBranch = this.repository.Branches[originCanonicalName]; if (originBranch != null) { repoTip = originBranch.Tip; @@ -375,18 +375,18 @@ public void EnsureLocalBranchExistsForCurrentBranch(IRemote? remote, string? cur var repoTipId = repoTip!.Id; var referenceName = ReferenceName.Parse(localCanonicalName); - if (repository.Branches.All(b => !b.Name.Equals(referenceName))) + if (this.repository.Branches.All(b => !b.Name.Equals(referenceName))) { - log.Info(isBranch ? $"Creating local branch {referenceName}" + this.log.Info(isBranch ? $"Creating local branch {referenceName}" : $"Creating local branch {referenceName} pointing at {repoTipId}"); - repository.Refs.Add(localCanonicalName, repoTipId.Sha); + this.repository.Refs.Add(localCanonicalName, repoTipId.Sha); } else { - log.Info(isBranch ? $"Updating local branch {referenceName} to point at {repoTip}" + this.log.Info(isBranch ? $"Updating local branch {referenceName} to point at {repoTip}" : $"Updating local branch {referenceName} to match ref {currentBranch}"); - var localRef = repository.Refs[localCanonicalName]!; - retryAction.Execute(() => repository.Refs.UpdateTarget(localRef, repoTipId)); + var localRef = this.repository.Refs[localCanonicalName]!; + this.retryAction.Execute(() => this.repository.Refs.UpdateTarget(localRef, repoTipId)); } Checkout(localCanonicalName); @@ -394,7 +394,7 @@ public void EnsureLocalBranchExistsForCurrentBranch(IRemote? remote, string? cur private void Checkout(string commitOrBranchSpec) { - retryAction.Execute(() => repository.Checkout(commitOrBranchSpec)); + this.retryAction.Execute(() => this.repository.Checkout(commitOrBranchSpec)); } } } diff --git a/src/GitVersion.Core/Core/GitVersionCalculateTool.cs b/src/GitVersion.Core/Core/GitVersionCalculateTool.cs index 9994a082fc..5c20e546c6 100644 --- a/src/GitVersion.Core/Core/GitVersionCalculateTool.cs +++ b/src/GitVersion.Core/Core/GitVersionCalculateTool.cs @@ -18,7 +18,7 @@ public class GitVersionCalculateTool : IGitVersionCalculateTool private readonly IOptions options; private readonly Lazy versionContext; - private GitVersionContext context => versionContext.Value; + private GitVersionContext context => this.versionContext.Value; public GitVersionCalculateTool(ILog log, INextVersionCalculator nextVersionCalculator, IVariableProvider variableProvider, IGitPreparer gitPreparer, @@ -40,26 +40,26 @@ public GitVersionCalculateTool(ILog log, INextVersionCalculator nextVersionCalcu public VersionVariables CalculateVersionVariables() { - gitPreparer.Prepare(); //we need to prepare the repository before using it for version calculation + this.gitPreparer.Prepare(); //we need to prepare the repository before using it for version calculation - var gitVersionOptions = options.Value; + var gitVersionOptions = this.options.Value; - var cacheKey = cacheKeyFactory.Create(gitVersionOptions.ConfigInfo.OverrideConfig); - var versionVariables = gitVersionOptions.Settings.NoCache ? default : gitVersionCache.LoadVersionVariablesFromDiskCache(cacheKey); + var cacheKey = this.cacheKeyFactory.Create(gitVersionOptions.ConfigInfo.OverrideConfig); + var versionVariables = gitVersionOptions.Settings.NoCache ? default : this.gitVersionCache.LoadVersionVariablesFromDiskCache(cacheKey); if (versionVariables != null) return versionVariables; - var semanticVersion = nextVersionCalculator.FindVersion(); - versionVariables = variableProvider.GetVariablesFor(semanticVersion, context.Configuration!, context.IsCurrentCommitTagged); + var semanticVersion = this.nextVersionCalculator.FindVersion(); + versionVariables = this.variableProvider.GetVariablesFor(semanticVersion, context.Configuration!, context.IsCurrentCommitTagged); if (gitVersionOptions.Settings.NoCache) return versionVariables; try { - gitVersionCache.WriteVariablesToDiskCache(cacheKey, versionVariables); + this.gitVersionCache.WriteVariablesToDiskCache(cacheKey, versionVariables); } catch (AggregateException e) { - log.Warning($"One or more exceptions during cache write:{System.Environment.NewLine}{e}"); + this.log.Warning($"One or more exceptions during cache write:{System.Environment.NewLine}{e}"); } return versionVariables; diff --git a/src/GitVersion.Core/Core/GitVersionContextFactory.cs b/src/GitVersion.Core/Core/GitVersionContextFactory.cs index 1193599d6e..d6af78eb92 100644 --- a/src/GitVersion.Core/Core/GitVersionContextFactory.cs +++ b/src/GitVersion.Core/Core/GitVersionContextFactory.cs @@ -23,24 +23,24 @@ public GitVersionContextFactory(IConfigProvider configProvider, IRepositoryStore public GitVersionContext Create(GitVersionOptions? gitVersionOptions) { - var currentBranch = repositoryStore.GetTargetBranch(gitVersionOptions?.RepositoryInfo.TargetBranch); + var currentBranch = this.repositoryStore.GetTargetBranch(gitVersionOptions?.RepositoryInfo.TargetBranch); if (currentBranch == null) throw new InvalidOperationException("Need a branch to operate on"); - var configuration = configProvider.Provide(overrideConfig: options.Value.ConfigInfo.OverrideConfig); + var configuration = this.configProvider.Provide(overrideConfig: this.options.Value.ConfigInfo.OverrideConfig); - var currentCommit = repositoryStore.GetCurrentCommit(currentBranch, gitVersionOptions?.RepositoryInfo.CommitId); + var currentCommit = this.repositoryStore.GetCurrentCommit(currentBranch, gitVersionOptions?.RepositoryInfo.CommitId); if (currentBranch.IsDetachedHead) { - var branchForCommit = repositoryStore.GetBranchesContainingCommit(currentCommit, onlyTrackedBranches: gitVersionOptions?.Settings.OnlyTrackedBranches == true).OnlyOrDefault(); + var branchForCommit = this.repositoryStore.GetBranchesContainingCommit(currentCommit, onlyTrackedBranches: gitVersionOptions?.Settings.OnlyTrackedBranches == true).OnlyOrDefault(); currentBranch = branchForCommit ?? currentBranch; } - var currentBranchConfig = branchConfigurationCalculator.GetBranchConfiguration(currentBranch, currentCommit, configuration); + var currentBranchConfig = this.branchConfigurationCalculator.GetBranchConfiguration(currentBranch, currentCommit, configuration); var effectiveConfiguration = configuration.CalculateEffectiveConfiguration(currentBranchConfig); - var currentCommitTaggedVersion = repositoryStore.GetCurrentCommitTaggedVersion(currentCommit, effectiveConfiguration); - var numberOfUncommittedChanges = repositoryStore.GetNumberOfUncommittedChanges(); + var currentCommitTaggedVersion = this.repositoryStore.GetCurrentCommitTaggedVersion(currentCommit, effectiveConfiguration); + var numberOfUncommittedChanges = this.repositoryStore.GetNumberOfUncommittedChanges(); return new GitVersionContext(currentBranch, currentCommit, configuration, effectiveConfiguration, currentCommitTaggedVersion, numberOfUncommittedChanges); } diff --git a/src/GitVersion.Core/Core/GitVersionOutputTool.cs b/src/GitVersion.Core/Core/GitVersionOutputTool.cs index 5cffb73bee..337cef8c26 100644 --- a/src/GitVersion.Core/Core/GitVersionOutputTool.cs +++ b/src/GitVersion.Core/Core/GitVersionOutputTool.cs @@ -35,55 +35,55 @@ public GitVersionOutputTool(IOptions options, public void OutputVariables(VersionVariables variables, bool updateBuildNumber) { - var gitVersionOptions = options.Value; + var gitVersionOptions = this.options.Value; - using (outputGenerator) + using (this.outputGenerator) { - outputGenerator.Execute(variables, new OutputContext(gitVersionOptions.WorkingDirectory, gitVersionOptions.OutputFile, updateBuildNumber)); + this.outputGenerator.Execute(variables, new OutputContext(gitVersionOptions.WorkingDirectory, gitVersionOptions.OutputFile, updateBuildNumber)); } } public void UpdateAssemblyInfo(VersionVariables variables) { - var gitVersionOptions = options.Value!; + var gitVersionOptions = this.options.Value!; var assemblyInfoContext = new AssemblyInfoContext(gitVersionOptions.WorkingDirectory, gitVersionOptions.AssemblyInfo.EnsureAssemblyInfo, gitVersionOptions.AssemblyInfo.Files.ToArray()); if (gitVersionOptions.AssemblyInfo.UpdateProjectFiles) { - using (projectFileUpdater) + using (this.projectFileUpdater) { - projectFileUpdater.Execute(variables, assemblyInfoContext); + this.projectFileUpdater.Execute(variables, assemblyInfoContext); } } else if (gitVersionOptions.AssemblyInfo.UpdateAssemblyInfo) { - using (assemblyInfoFileUpdater) + using (this.assemblyInfoFileUpdater) { - assemblyInfoFileUpdater.Execute(variables, assemblyInfoContext); + this.assemblyInfoFileUpdater.Execute(variables, assemblyInfoContext); } } } public void UpdateWixVersionFile(VersionVariables variables) { - var gitVersionOptions = options.Value; + var gitVersionOptions = this.options.Value; if (gitVersionOptions.WixInfo.ShouldUpdate) { - using (wixVersionFileUpdater) + using (this.wixVersionFileUpdater) { - wixVersionFileUpdater.Execute(variables, new WixVersionContext(gitVersionOptions.WorkingDirectory)); + this.wixVersionFileUpdater.Execute(variables, new WixVersionContext(gitVersionOptions.WorkingDirectory)); } } } public void GenerateGitVersionInformation(VersionVariables variables, FileWriteInfo fileWriteInfo) { - var gitVersionOptions = options.Value; + var gitVersionOptions = this.options.Value; - using (gitVersionInfoGenerator) + using (this.gitVersionInfoGenerator) { - gitVersionInfoGenerator.Execute(variables, new GitVersionInfoContext(gitVersionOptions.WorkingDirectory, fileWriteInfo.FileName, fileWriteInfo.FileExtension)); + this.gitVersionInfoGenerator.Execute(variables, new GitVersionInfoContext(gitVersionOptions.WorkingDirectory, fileWriteInfo.FileName, fileWriteInfo.FileExtension)); } } } diff --git a/src/GitVersion.Core/Core/RepositoryStore.cs b/src/GitVersion.Core/Core/RepositoryStore.cs index d250d1c7d2..fe4dfb3fba 100644 --- a/src/GitVersion.Core/Core/RepositoryStore.cs +++ b/src/GitVersion.Core/Core/RepositoryStore.cs @@ -34,13 +34,13 @@ public RepositoryStore(ILog log, IGitRepository repository) { var key = Tuple.Create(branch, otherBranch); - if (mergeBaseCache.ContainsKey(key)) + if (this.mergeBaseCache.ContainsKey(key)) { - log.Debug($"Cache hit for merge base between '{branch}' and '{otherBranch}'."); - return mergeBaseCache[key]; + this.log.Debug($"Cache hit for merge base between '{branch}' and '{otherBranch}'."); + return this.mergeBaseCache[key]; } - using (log.IndentLog($"Finding merge base between '{branch}' and '{otherBranch}'.")) + using (this.log.IndentLog($"Finding merge base between '{branch}' and '{otherBranch}'.")) { // Other branch tip is a forward merge var commitToFindCommonBase = otherBranch?.Tip; @@ -53,7 +53,7 @@ public RepositoryStore(ILog log, IGitRepository repository) var findMergeBase = FindMergeBase(commit, commitToFindCommonBase!); if (findMergeBase != null) { - log.Info($"Found merge base of {findMergeBase}"); + this.log.Info($"Found merge base of {findMergeBase}"); // We do not want to include merge base commits which got forward merged into the other branch ICommit forwardMerge; do @@ -65,32 +65,32 @@ public RepositoryStore(ILog log, IGitRepository repository) { // TODO Fix the logging up in this section var second = forwardMerge.Parents.First(); - log.Debug($"Second {second}"); + this.log.Debug($"Second {second}"); var mergeBase = FindMergeBase(commit, second); if (mergeBase == null) { - log.Warning("Could not find mergbase for " + commit); + this.log.Warning("Could not find mergbase for " + commit); } else { - log.Debug($"New Merge base {mergeBase}"); + this.log.Debug($"New Merge base {mergeBase}"); } if (Equals(mergeBase, findMergeBase)) { - log.Debug("Breaking"); + this.log.Debug("Breaking"); break; } findMergeBase = mergeBase; commitToFindCommonBase = second; - log.Info($"Merge base was due to a forward merge, next merge base is {findMergeBase}"); + this.log.Info($"Merge base was due to a forward merge, next merge base is {findMergeBase}"); } } while (forwardMerge != null); } // Store in cache. - mergeBaseCache.Add(key, findMergeBase); + this.mergeBaseCache.Add(key, findMergeBase); - log.Info($"Merge base of {branch}' and '{otherBranch} is {findMergeBase}"); + this.log.Info($"Merge base of {branch}' and '{otherBranch} is {findMergeBase}"); return findMergeBase; } } @@ -100,22 +100,22 @@ public RepositoryStore(ILog log, IGitRepository repository) ICommit? currentCommit = null; if (!commitId.IsNullOrWhiteSpace()) { - log.Info($"Searching for specific commit '{commitId}'"); + this.log.Info($"Searching for specific commit '{commitId}'"); - var commit = repository.Commits.FirstOrDefault(c => string.Equals(c.Sha, commitId, StringComparison.OrdinalIgnoreCase)); + var commit = this.repository.Commits.FirstOrDefault(c => string.Equals(c.Sha, commitId, StringComparison.OrdinalIgnoreCase)); if (commit != null) { currentCommit = commit; } else { - log.Warning($"Commit '{commitId}' specified but not found"); + this.log.Warning($"Commit '{commitId}' specified but not found"); } } if (currentCommit == null) { - log.Info("Using latest commit on specified branch"); + this.log.Info("Using latest commit on specified branch"); currentCommit = currentBranch.Tip; } @@ -129,7 +129,7 @@ public ICommit GetBaseVersionSource(ICommit currentBranchTip) { IncludeReachableFrom = currentBranchTip }; - var commitCollection = repository.Commits.QueryBy(filter); + var commitCollection = this.repository.Commits.QueryBy(filter); return commitCollection.First(c => !c.Parents.Any()); } @@ -148,7 +148,7 @@ public IEnumerable GetMainlineCommitLog(ICommit? baseVersionSource, ICo FirstParentOnly = true }; - return repository.Commits.QueryBy(filter); + return this.repository.Commits.QueryBy(filter); } public IEnumerable GetMergeBaseCommits(ICommit? mergeCommit, ICommit? mergedHead, ICommit? findMergeBase) { @@ -157,7 +157,7 @@ public IEnumerable GetMergeBaseCommits(ICommit? mergeCommit, ICommit? m IncludeReachableFrom = mergedHead, ExcludeReachableFrom = findMergeBase }; - var commitCollection = repository.Commits.QueryBy(filter); + var commitCollection = this.repository.Commits.QueryBy(filter); var commits = mergeCommit != null ? new[] @@ -171,7 +171,7 @@ public IEnumerable GetMergeBaseCommits(ICommit? mergeCommit, ICommit? m public IBranch GetTargetBranch(string? targetBranchName) { // By default, we assume HEAD is pointing to the desired branch - var desiredBranch = repository.Head; + var desiredBranch = this.repository.Head; // Make sure the desired branch has been specified if (!targetBranchName.IsNullOrEmpty()) @@ -184,27 +184,27 @@ public IBranch GetTargetBranch(string? targetBranchName) if (!desiredBranch.Equals(targetBranch)) { // In the case where HEAD is not the desired branch, try to find the branch with matching name - desiredBranch = repository.Branches? + desiredBranch = this.repository.Branches? .Where(b => b.Name.EquivalentTo(targetBranchName)) .OrderBy(b => b.IsRemote) .FirstOrDefault(); // Failsafe in case the specified branch is invalid - desiredBranch ??= repository.Head; + desiredBranch ??= this.repository.Head; } } return desiredBranch; } - public IBranch FindBranch(string? branchName) => repository.Branches.FirstOrDefault(x => x.Name.EquivalentTo(branchName)); + public IBranch FindBranch(string? branchName) => this.repository.Branches.FirstOrDefault(x => x.Name.EquivalentTo(branchName)); public IBranch GetChosenBranch(Config configuration) { var developBranchRegex = configuration.Branches[Config.DevelopBranchKey]?.Regex; var mainBranchRegex = configuration.Branches[Config.MainBranchKey]?.Regex; - var chosenBranch = repository.Branches.FirstOrDefault(b => + var chosenBranch = this.repository.Branches.FirstOrDefault(b => Regex.IsMatch(b.Name.Friendly, developBranchRegex, RegexOptions.IgnoreCase) || Regex.IsMatch(b.Name.Friendly, mainBranchRegex, RegexOptions.IgnoreCase)); @@ -213,12 +213,12 @@ public IBranch GetChosenBranch(Config configuration) public IEnumerable GetBranchesForCommit(ICommit commit) { - return repository.Branches.Where(b => !b.IsRemote && Equals(b.Tip, commit)).ToList(); + return this.repository.Branches.Where(b => !b.IsRemote && Equals(b.Tip, commit)).ToList(); } public IEnumerable GetExcludedInheritBranches(Config configuration) { - return repository.Branches.Where(b => + return this.repository.Branches.Where(b => { var branchConfig = configuration.GetConfigForBranch(b.Name.WithoutRemote); @@ -228,13 +228,13 @@ public IEnumerable GetExcludedInheritBranches(Config configuration) public IEnumerable GetReleaseBranches(IEnumerable>? releaseBranchConfig) { - return repository.Branches + return this.repository.Branches .Where(b => releaseBranchConfig?.Any(c => Regex.IsMatch(b.Name.Friendly, c.Value?.Regex)) == true); } public IEnumerable ExcludingBranches(IEnumerable branchesToExclude) { - return repository.Branches.ExcludeBranches(branchesToExclude); + return this.repository.Branches.ExcludeBranches(branchesToExclude); } // TODO Should we cache this? @@ -245,7 +245,7 @@ public IEnumerable GetBranchesContainingCommit(ICommit? commit, IEnumer throw new ArgumentNullException(nameof(commit)); } - return InnerGetBranchesContainingCommit(commit, branches, onlyTrackedBranches, repository, log); + return InnerGetBranchesContainingCommit(commit, branches, onlyTrackedBranches, this.repository, this.log); static bool IncludeTrackedBranches(IBranch branch, bool includeOnlyTracked) => includeOnlyTracked && branch.IsTracking || !includeOnlyTracked; @@ -300,7 +300,7 @@ static IEnumerable InnerGetBranchesContainingCommit(ICommit commit, IEn public Dictionary> GetMainlineBranches(ICommit commit, IEnumerable>? mainlineBranchConfigs) { - return repository.Branches + return this.repository.Branches .Where(b => mainlineBranchConfigs?.Any(c => Regex.IsMatch(b.Name.Friendly, c.Value?.Regex)) == true) .Select(b => new { @@ -323,11 +323,11 @@ public BranchCommit FindCommitBranchWasBranchedFrom(IBranch branch, Config confi throw new ArgumentNullException(nameof(branch)); } - using (log.IndentLog($"Finding branch source of '{branch}'")) + using (this.log.IndentLog($"Finding branch source of '{branch}'")) { if (branch.Tip == null) { - log.Warning(string.Format(MissingTipFormat, branch)); + this.log.Warning(string.Format(MissingTipFormat, branch)); return BranchCommit.Empty; } @@ -338,7 +338,7 @@ public BranchCommit FindCommitBranchWasBranchedFrom(IBranch branch, Config confi if (possibleBranches.Count > 1) { var first = possibleBranches.First(); - log.Info($"Multiple source branches have been found, picking the first one ({first.Branch}).{System.Environment.NewLine}" + + this.log.Info($"Multiple source branches have been found, picking the first one ({first.Branch}).{System.Environment.NewLine}" + $"This may result in incorrect commit counting.{System.Environment.NewLine}Options were:{System.Environment.NewLine}" + string.Join(", ", possibleBranches.Select(b => b.Branch.ToString()))); return first; @@ -350,7 +350,7 @@ public BranchCommit FindCommitBranchWasBranchedFrom(IBranch branch, Config confi public SemanticVersion GetCurrentCommitTaggedVersion(ICommit? commit, EffectiveConfiguration config) { - return repository.Tags + return this.repository.Tags .SelectMany(t => { var targetCommit = t.PeeledTargetCommit(); @@ -366,25 +366,25 @@ public SemanticVersion GetCurrentCommitTaggedVersion(ICommit? commit, EffectiveC public SemanticVersion MaybeIncrement(BaseVersion baseVersion, GitVersionContext context) { - var increment = IncrementStrategyFinder.DetermineIncrementedField(repository, context, baseVersion); + var increment = IncrementStrategyFinder.DetermineIncrementedField(this.repository, context, baseVersion); return increment != null ? baseVersion.SemanticVersion.IncrementVersion(increment.Value) : baseVersion.SemanticVersion; } public IEnumerable GetVersionTagsOnBranch(IBranch branch, string? tagPrefixRegex) { - if (semanticVersionTagsOnBranchCache.ContainsKey(branch)) + if (this.semanticVersionTagsOnBranchCache.ContainsKey(branch)) { - log.Debug($"Cache hit for version tags on branch '{branch.Name.Canonical}"); - return semanticVersionTagsOnBranchCache[branch]; + this.log.Debug($"Cache hit for version tags on branch '{branch.Name.Canonical}"); + return this.semanticVersionTagsOnBranchCache[branch]; } - using (log.IndentLog($"Getting version tags from branch '{branch.Name.Canonical}'.")) + using (this.log.IndentLog($"Getting version tags from branch '{branch.Name.Canonical}'.")) { var tags = GetValidVersionTags(tagPrefixRegex); var versionTags = branch.Commits.SelectMany(c => tags.Where(t => c.Sha == t.Item1?.TargetSha).Select(t => t.Item2)).ToList(); - semanticVersionTagsOnBranchCache.Add(branch, versionTags); + this.semanticVersionTagsOnBranchCache.Add(branch, versionTags); return versionTags; } } @@ -393,7 +393,7 @@ public SemanticVersion MaybeIncrement(BaseVersion baseVersion, GitVersionContext { var tags = new List>(); - foreach (var tag in repository.Tags) + foreach (var tag in this.repository.Tags) { var commit = tag.PeeledTargetCommit(); @@ -423,12 +423,12 @@ public IEnumerable GetCommitLog(ICommit? baseVersionSource, ICommit? cu SortBy = CommitSortStrategies.Topological | CommitSortStrategies.Time }; - return repository.Commits.QueryBy(filter); + return this.repository.Commits.QueryBy(filter); } public VersionField? DetermineIncrementedField(BaseVersion baseVersion, GitVersionContext context) { - return IncrementStrategyFinder.DetermineIncrementedField(repository, context, baseVersion); + return IncrementStrategyFinder.DetermineIncrementedField(this.repository, context, baseVersion); } public bool IsCommitOnBranch(ICommit? baseVersionSource, IBranch branch, ICommit firstMatchingCommit) @@ -439,16 +439,16 @@ public bool IsCommitOnBranch(ICommit? baseVersionSource, IBranch branch, ICommit ExcludeReachableFrom = baseVersionSource, FirstParentOnly = true, }; - var commitCollection = repository.Commits.QueryBy(filter); + var commitCollection = this.repository.Commits.QueryBy(filter); return commitCollection.Contains(firstMatchingCommit); } private IEnumerable GetMergeCommitsForBranch(IBranch branch, Config configuration, IEnumerable excludedBranches) { - if (mergeBaseCommitsCache.ContainsKey(branch)) + if (this.mergeBaseCommitsCache.ContainsKey(branch)) { - log.Debug($"Cache hit for getting merge commits for branch {branch.Name.Canonical}."); - return mergeBaseCommitsCache[branch]; + this.log.Debug($"Cache hit for getting merge commits for branch {branch.Name.Canonical}."); + return this.mergeBaseCommitsCache[branch]; } var currentBranchConfig = configuration.GetConfigForBranch(branch.Name.WithoutRemote); @@ -467,7 +467,7 @@ private IEnumerable GetMergeCommitsForBranch(IBranch branch, Confi { if (otherBranch.Tip == null) { - log.Warning(string.Format(MissingTipFormat, otherBranch)); + this.log.Warning(string.Format(MissingTipFormat, otherBranch)); return BranchCommit.Empty; } @@ -477,7 +477,7 @@ private IEnumerable GetMergeCommitsForBranch(IBranch branch, Confi .Where(b => b.Commit != null) .OrderByDescending(b => b.Commit.When) .ToList(); - mergeBaseCommitsCache.Add(branch, branchMergeBases); + this.mergeBaseCommitsCache.Add(branch, branchMergeBases); return branchMergeBases; } @@ -500,13 +500,13 @@ private ICommit GetForwardMerge(ICommit? commitToFindCommonBase, ICommit? findMe IncludeReachableFrom = commitToFindCommonBase, ExcludeReachableFrom = findMergeBase }; - var commitCollection = repository.Commits.QueryBy(filter); + var commitCollection = this.repository.Commits.QueryBy(filter); return commitCollection.FirstOrDefault(c => c.Parents.Contains(findMergeBase)); } - public ICommit FindMergeBase(ICommit commit, ICommit mainlineTip) => repository.FindMergeBase(commit, mainlineTip); + public ICommit FindMergeBase(ICommit commit, ICommit mainlineTip) => this.repository.FindMergeBase(commit, mainlineTip); - public int GetNumberOfUncommittedChanges() => repository.GetNumberOfUncommittedChanges(); + public int GetNumberOfUncommittedChanges() => this.repository.GetNumberOfUncommittedChanges(); } } diff --git a/src/GitVersion.Core/Helpers/LambdaEqualityHelper.cs b/src/GitVersion.Core/Helpers/LambdaEqualityHelper.cs index 546d61b40b..322d6693e9 100644 --- a/src/GitVersion.Core/Helpers/LambdaEqualityHelper.cs +++ b/src/GitVersion.Core/Helpers/LambdaEqualityHelper.cs @@ -31,7 +31,7 @@ public bool Equals(T? instance, T? other) return false; } - foreach (var accessor in equalityContributorAccessors) + foreach (var accessor in this.equalityContributorAccessors) { if (!Equals(accessor(instance), accessor(other))) { @@ -48,7 +48,7 @@ public int GetHashCode(T instance) unchecked { - foreach (var accessor in equalityContributorAccessors) + foreach (var accessor in this.equalityContributorAccessors) { var item = accessor(instance); hashCode = (hashCode * 397) ^ (item != null ? item.GetHashCode() : 0); diff --git a/src/GitVersion.Core/Helpers/LambdaKeyComparer.cs b/src/GitVersion.Core/Helpers/LambdaKeyComparer.cs index c88a219e8d..f83cc9eb1f 100644 --- a/src/GitVersion.Core/Helpers/LambdaKeyComparer.cs +++ b/src/GitVersion.Core/Helpers/LambdaKeyComparer.cs @@ -25,9 +25,9 @@ public override int Compare(TSource x, TSource y) if (y == null) return 1; - var xKey = keySelector(x); - var yKey = keySelector(y); - return innerComparer.Compare(xKey, yKey); + var xKey = this.keySelector(x); + var yKey = this.keySelector(y); + return this.innerComparer.Compare(xKey, yKey); } } } diff --git a/src/GitVersion.Core/Helpers/ProcessHelper.cs b/src/GitVersion.Core/Helpers/ProcessHelper.cs index 8b8f786129..d7497ad275 100644 --- a/src/GitVersion.Core/Helpers/ProcessHelper.cs +++ b/src/GitVersion.Core/Helpers/ProcessHelper.cs @@ -190,11 +190,11 @@ public ChangeErrorMode(ErrorModes mode) { try { - oldMode = SetErrorMode((int)mode); + this.oldMode = SetErrorMode((int)mode); } catch (Exception ex) when (ex is EntryPointNotFoundException || ex is DllNotFoundException) { - oldMode = (int)mode; + this.oldMode = (int)mode; } } @@ -203,7 +203,7 @@ void IDisposable.Dispose() { try { - SetErrorMode(oldMode); + SetErrorMode(this.oldMode); } catch (Exception ex) when (ex is EntryPointNotFoundException || ex is DllNotFoundException) { diff --git a/src/GitVersion.Core/Helpers/RetryAction.cs b/src/GitVersion.Core/Helpers/RetryAction.cs index 1a8e8127b9..1a16cf7874 100644 --- a/src/GitVersion.Core/Helpers/RetryAction.cs +++ b/src/GitVersion.Core/Helpers/RetryAction.cs @@ -32,14 +32,14 @@ public RetryAction(int maxRetries = 5) throw new ArgumentOutOfRangeException(nameof(maxRetries)); var linearBackoff = LinearBackoff(TimeSpan.FromMilliseconds(100), maxRetries); - retryPolicy = Policy + this.retryPolicy = Policy .Handle() .WaitAndRetry(linearBackoff); } public Result Execute(Func operation) { - return retryPolicy.Execute(operation); + return this.retryPolicy.Execute(operation); } private static IEnumerable LinearBackoff(TimeSpan initialDelay, int retryCount, double factor = 1.0, bool fastFirst = false) diff --git a/src/GitVersion.Core/Logging/ConsoleAppender.cs b/src/GitVersion.Core/Logging/ConsoleAppender.cs index 618d230a3d..038e3e9464 100644 --- a/src/GitVersion.Core/Logging/ConsoleAppender.cs +++ b/src/GitVersion.Core/Logging/ConsoleAppender.cs @@ -9,16 +9,16 @@ public class ConsoleAppender : ILogAppender private readonly IDictionary palettes; public ConsoleAppender() { - locker = new object(); - palettes = CreatePalette(); + this.locker = new object(); + this.palettes = CreatePalette(); } public void WriteTo(LogLevel level, string message) { - lock (locker) + lock (this.locker) { try { - var (backgroundColor, foregroundColor) = palettes[level]; + var (backgroundColor, foregroundColor) = this.palettes[level]; Console.BackgroundColor = backgroundColor; Console.ForegroundColor = foregroundColor; diff --git a/src/GitVersion.Core/Logging/Disposable.cs b/src/GitVersion.Core/Logging/Disposable.cs index c251fc2ba7..dbd6e5d2b1 100644 --- a/src/GitVersion.Core/Logging/Disposable.cs +++ b/src/GitVersion.Core/Logging/Disposable.cs @@ -22,8 +22,8 @@ public AnonymousDisposable(Action disposer) public void Dispose() { - disposer?.Invoke(); - disposer = null; + this.disposer?.Invoke(); + this.disposer = null; } private Action? disposer; diff --git a/src/GitVersion.Core/Logging/FileAppender.cs b/src/GitVersion.Core/Logging/FileAppender.cs index c3eb970a2c..5594793c1b 100644 --- a/src/GitVersion.Core/Logging/FileAppender.cs +++ b/src/GitVersion.Core/Logging/FileAppender.cs @@ -24,7 +24,7 @@ public void WriteTo(LogLevel level, string message) { try { - WriteLogEntry(filePath, message); + WriteLogEntry(this.filePath, message); } catch (Exception) { diff --git a/src/GitVersion.Core/Logging/Log.cs b/src/GitVersion.Core/Logging/Log.cs index 51021ddab7..e520d383ca 100644 --- a/src/GitVersion.Core/Logging/Log.cs +++ b/src/GitVersion.Core/Logging/Log.cs @@ -21,7 +21,7 @@ public Log() : this(Array.Empty()) public Log(params ILogAppender[] appenders) { this.appenders = appenders ?? Array.Empty(); - sb = new StringBuilder(); + this.sb = new StringBuilder(); Verbosity = Verbosity.Normal; } @@ -36,42 +36,42 @@ public void Write(Verbosity verbosity, LogLevel level, string format, params obj var message = args.Any() ? string.Format(format, args) : format; var formattedString = FormatMessage(message, level.ToString().ToUpperInvariant()); - foreach (var appender in appenders) + foreach (var appender in this.appenders) { appender.WriteTo(level, formattedString); } - sb.AppendLine(formattedString); + this.sb.AppendLine(formattedString); } public IDisposable IndentLog(string operationDescription) { var start = DateTime.Now; Write(Verbosity.Normal, LogLevel.Info, $"Begin: {operationDescription}"); - indent += " "; + this.indent += " "; return Disposable.Create(() => { - var length = indent.Length - 2; - indent = length > 0 ? indent.Substring(0, length) : indent; + var length = this.indent.Length - 2; + this.indent = length > 0 ? this.indent.Substring(0, length) : this.indent; Write(Verbosity.Normal, LogLevel.Info, string.Format(CultureInfo.InvariantCulture, "End: {0} (Took: {1:N}ms)", operationDescription, DateTime.Now.Subtract(start).TotalMilliseconds)); }); } public void AddLogAppender(ILogAppender logAppender) { - appenders = appenders.Concat(new[] { logAppender }); + this.appenders = this.appenders.Concat(new[] { logAppender }); } public override string ToString() { - return sb.ToString(); + return this.sb.ToString(); } private string FormatMessage(string message, string level) { - var obscuredMessage = obscurePasswordRegex.Replace(message, "$1$2:*******@"); - return string.Format(CultureInfo.InvariantCulture, "{0}{1} [{2:MM/dd/yy H:mm:ss:ff}] {3}", indent, level, DateTime.Now, obscuredMessage); + var obscuredMessage = this.obscurePasswordRegex.Replace(message, "$1$2:*******@"); + return string.Format(CultureInfo.InvariantCulture, "{0}{1} [{2:MM/dd/yy H:mm:ss:ff}] {3}", this.indent, level, DateTime.Now, obscuredMessage); } } } diff --git a/src/GitVersion.Core/Model/Configuration/Config.cs b/src/GitVersion.Core/Model/Configuration/Config.cs index 5e8b9d6cdc..fcf6e8ca8e 100644 --- a/src/GitVersion.Core/Model/Configuration/Config.cs +++ b/src/GitVersion.Core/Model/Configuration/Config.cs @@ -46,9 +46,9 @@ public Config() [YamlMember(Alias = "next-version")] public string? NextVersion { - get => nextVersion; + get => this.nextVersion; set => - nextVersion = int.TryParse(value, NumberStyles.Any, NumberFormatInfo.InvariantInfo, out var major) + this.nextVersion = int.TryParse(value, NumberStyles.Any, NumberFormatInfo.InvariantInfo, out var major) ? $"{major}.0" : value; } diff --git a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculator.cs b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculator.cs index 99ea0b601b..581c9b884a 100644 --- a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculator.cs +++ b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculator.cs @@ -13,7 +13,7 @@ public class BaseVersionCalculator : IBaseVersionCalculator private readonly IRepositoryStore repositoryStore; private readonly IVersionStrategy[] strategies; private readonly Lazy versionContext; - private GitVersionContext context => versionContext.Value; + private GitVersionContext context => this.versionContext.Value; public BaseVersionCalculator(ILog log, IRepositoryStore repositoryStore, Lazy versionContext, IEnumerable strategies) { @@ -25,10 +25,10 @@ public BaseVersionCalculator(ILog log, IRepositoryStore repositoryStore, Lazy(); - foreach (var strategy in strategies) + foreach (var strategy in this.strategies) { var baseVersions = GetBaseVersions(strategy).ToList(); allVersions.AddRange(baseVersions); @@ -37,7 +37,7 @@ public BaseVersion GetBaseVersion() var versions = allVersions .Select(baseVersion => new Versions { - IncrementedVersion = repositoryStore.MaybeIncrement(baseVersion, context), + IncrementedVersion = this.repositoryStore.MaybeIncrement(baseVersion, context), Version = baseVersion }) .ToList(); @@ -64,7 +64,7 @@ public BaseVersion GetBaseVersion() }); baseVersionWithOldestSource = oldest!.Version!; maxVersion = oldest; - log.Info($"Found multiple base versions which will produce the same SemVer ({maxVersion.IncrementedVersion}), taking oldest source for commit counting ({baseVersionWithOldestSource!.Source})"); + this.log.Info($"Found multiple base versions which will produce the same SemVer ({maxVersion.IncrementedVersion}), taking oldest source for commit counting ({baseVersionWithOldestSource!.Source})"); } else { @@ -83,7 +83,7 @@ public BaseVersion GetBaseVersion() maxVersion.Version!.Source, maxVersion.Version.ShouldIncrement, maxVersion.Version.SemanticVersion, baseVersionWithOldestSource.BaseVersionSource, maxVersion.Version.BranchNameOverride); - log.Info($"Base version used: {calculatedBase}"); + this.log.Info($"Base version used: {calculatedBase}"); return calculatedBase; } @@ -94,7 +94,7 @@ private IEnumerable GetBaseVersions(IVersionStrategy strategy) { if (version == null) continue; - log.Info(version.ToString()); + this.log.Info(version.ToString()); if (strategy is FallbackVersionStrategy || IncludeVersion(version)) { yield return version; @@ -110,7 +110,7 @@ private bool IncludeVersion(BaseVersion version) { if (filter.Exclude(version, out var reason)) { - log.Info(reason); + this.log.Info(reason); return false; } } @@ -131,7 +131,7 @@ private void FixTheBaseVersionSourceOfMergeMessageStrategyIfReleaseBranchWasMerg baseVersion.Version.Source, baseVersion.Version.ShouldIncrement, baseVersion.Version.SemanticVersion, - repositoryStore.FindMergeBase(parents[0], parents[1]), + this.repositoryStore.FindMergeBase(parents[0], parents[1]), baseVersion.Version.BranchNameOverride); } } @@ -140,7 +140,7 @@ private void FixTheBaseVersionSourceOfMergeMessageStrategyIfReleaseBranchWasMerg private bool ReleaseBranchExistsInRepo() { var releaseBranchConfig = context.FullConfiguration?.GetReleaseBranchConfig(); - var releaseBranches = repositoryStore.GetReleaseBranches(releaseBranchConfig); + var releaseBranches = this.repositoryStore.GetReleaseBranches(releaseBranchConfig); return releaseBranches.Any(); } diff --git a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/FallbackVersionStrategy.cs b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/FallbackVersionStrategy.cs index 21a1932b8c..3cfc66752f 100644 --- a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/FallbackVersionStrategy.cs +++ b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/FallbackVersionStrategy.cs @@ -25,7 +25,7 @@ public override IEnumerable GetVersions() throw new GitVersionException("No commits found on the current branch."); } - var baseVersionSource = repositoryStore.GetBaseVersionSource(currentBranchTip); + var baseVersionSource = this.repositoryStore.GetBaseVersionSource(currentBranchTip); yield return new BaseVersion("Fallback base version", false, new SemanticVersion(minor: 1), baseVersionSource, null); } diff --git a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/MergeMessageVersionStrategy.cs b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/MergeMessageVersionStrategy.cs index 88c324c1fc..14128be42b 100644 --- a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/MergeMessageVersionStrategy.cs +++ b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/MergeMessageVersionStrategy.cs @@ -34,7 +34,7 @@ public override IEnumerable GetVersions() mergeMessage.Version != null && Context.FullConfiguration?.IsReleaseBranch(TrimRemote(mergeMessage.MergedBranch)) == true) { - log.Info($"Found commit [{Context.CurrentCommit}] matching merge message format: {mergeMessage.FormatName}"); + this.log.Info($"Found commit [{Context.CurrentCommit}] matching merge message format: {mergeMessage.FormatName}"); var shouldIncrement = Context.Configuration?.PreventIncrementForMergedBranchVersion != true; return new[] { diff --git a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/TaggedCommitVersionStrategy.cs b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/TaggedCommitVersionStrategy.cs index 3bd70af264..6b813787b4 100644 --- a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/TaggedCommitVersionStrategy.cs +++ b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/TaggedCommitVersionStrategy.cs @@ -27,7 +27,7 @@ public override IEnumerable GetVersions() internal IEnumerable GetTaggedVersions(IBranch? currentBranch, DateTimeOffset? olderThan) { - var allTags = repositoryStore.GetValidVersionTags(Context.Configuration?.GitTagPrefix, olderThan); + var allTags = this.repositoryStore.GetValidVersionTags(Context.Configuration?.GitTagPrefix, olderThan); var taggedCommits = currentBranch ?.Commits @@ -73,14 +73,14 @@ protected class VersionTaggedCommit public VersionTaggedCommit(ICommit commit, SemanticVersion semVer, string tag) { - Tag = tag; - Commit = commit; - SemVer = semVer; + this.Tag = tag; + this.Commit = commit; + this.SemVer = semVer; } public override string ToString() { - return $"{Tag} | {Commit} | {SemVer}"; + return $"{this.Tag} | {this.Commit} | {this.SemVer}"; } } } diff --git a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/TrackReleaseBranchesVersionStrategy.cs b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/TrackReleaseBranchesVersionStrategy.cs index a28ef74ed3..d73e9ce21c 100644 --- a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/TrackReleaseBranchesVersionStrategy.cs +++ b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/TrackReleaseBranchesVersionStrategy.cs @@ -34,8 +34,8 @@ public TrackReleaseBranchesVersionStrategy(IRepositoryStore repositoryStore, Laz { this.repositoryStore = repositoryStore ?? throw new ArgumentNullException(nameof(repositoryStore)); - releaseVersionStrategy = new VersionInBranchNameVersionStrategy(repositoryStore, versionContext); - taggedCommitVersionStrategy = new TaggedCommitVersionStrategy(repositoryStore, versionContext); + this.releaseVersionStrategy = new VersionInBranchNameVersionStrategy(repositoryStore, versionContext); + this.taggedCommitVersionStrategy = new TaggedCommitVersionStrategy(repositoryStore, versionContext); } public override IEnumerable GetVersions() @@ -50,8 +50,8 @@ public override IEnumerable GetVersions() private IEnumerable MainTagsVersions() { - var main = repositoryStore.FindBranch(Config.MainBranchKey); - return main != null ? taggedCommitVersionStrategy.GetTaggedVersions(main, null) : new BaseVersion[0]; + var main = this.repositoryStore.FindBranch(Config.MainBranchKey); + return main != null ? this.taggedCommitVersionStrategy.GetTaggedVersions(main, null) : new BaseVersion[0]; } @@ -61,7 +61,7 @@ private IEnumerable ReleaseBranchBaseVersions() var releaseBranchConfig = Context.FullConfiguration?.GetReleaseBranchConfig(); if (releaseBranchConfig.Any()) { - var releaseBranches = repositoryStore.GetReleaseBranches(releaseBranchConfig); + var releaseBranches = this.repositoryStore.GetReleaseBranches(releaseBranchConfig); return releaseBranches .SelectMany(b => GetReleaseVersion(Context, b)) @@ -86,14 +86,14 @@ private IEnumerable GetReleaseVersion(GitVersionContext context, IB var tagPrefixRegex = context.Configuration?.GitTagPrefix; // Find the commit where the child branch was created. - var baseSource = repositoryStore.FindMergeBase(releaseBranch, context.CurrentBranch); + var baseSource = this.repositoryStore.FindMergeBase(releaseBranch, context.CurrentBranch); if (Equals(baseSource, context.CurrentCommit)) { // Ignore the branch if it has no commits. return new BaseVersion[0]; } - return releaseVersionStrategy + return this.releaseVersionStrategy .GetVersions(tagPrefixRegex, releaseBranch) .Select(b => new BaseVersion(b.Source, true, b.SemanticVersion, baseSource, b.BranchNameOverride)); } diff --git a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/VersionInBranchNameVersionStrategy.cs b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/VersionInBranchNameVersionStrategy.cs index df82657312..f1875fd805 100644 --- a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/VersionInBranchNameVersionStrategy.cs +++ b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/VersionInBranchNameVersionStrategy.cs @@ -39,7 +39,7 @@ internal IEnumerable GetVersions(string? tagPrefixRegex, IBranch? c var versionInBranch = GetVersionInBranch(branchName, tagPrefixRegex); if (versionInBranch != null) { - var commitBranchWasBranchedFrom = repositoryStore.FindCommitBranchWasBranchedFrom(currentBranch, Context.FullConfiguration); + var commitBranchWasBranchedFrom = this.repositoryStore.FindCommitBranchWasBranchedFrom(currentBranch, Context.FullConfiguration); var branchNameOverride = branchName.RegexReplace("[-/]" + versionInBranch.Item1, string.Empty); yield return new BaseVersion("Version in branch name", false, versionInBranch.Item2, commitBranchWasBranchedFrom.Commit, branchNameOverride); } diff --git a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/VersionStrategyBase.cs b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/VersionStrategyBase.cs index c357ba4cd2..b20566381f 100644 --- a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/VersionStrategyBase.cs +++ b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/VersionStrategyBase.cs @@ -6,7 +6,7 @@ namespace GitVersion.VersionCalculation public class VersionStrategyBase : IVersionStrategy { private readonly Lazy versionContext; - protected GitVersionContext Context => versionContext.Value; + protected GitVersionContext Context => this.versionContext.Value; protected VersionStrategyBase(Lazy versionContext) { diff --git a/src/GitVersion.Core/VersionCalculation/Cache/GitVersionCache.cs b/src/GitVersion.Core/VersionCalculation/Cache/GitVersionCache.cs index e339e50180..6049d69279 100644 --- a/src/GitVersion.Core/VersionCalculation/Cache/GitVersionCache.cs +++ b/src/GitVersion.Core/VersionCalculation/Cache/GitVersionCache.cs @@ -31,16 +31,16 @@ public void WriteVariablesToDiskCache(GitVersionCacheKey cacheKey, VersionVariab variablesFromCache.FileName = cacheFileName; Dictionary dictionary; - using (log.IndentLog("Creating dictionary")) + using (this.log.IndentLog("Creating dictionary")) { dictionary = variablesFromCache.ToDictionary(x => x.Key, x => x.Value); } void WriteCacheOperation() { - using var stream = fileSystem.OpenWrite(cacheFileName); + using var stream = this.fileSystem.OpenWrite(cacheFileName); using var sw = new StreamWriter(stream); - using (log.IndentLog("Storing version variables to cache file " + cacheFileName)) + using (this.log.IndentLog("Storing version variables to cache file " + cacheFileName)) { var serializer = new Serializer(); serializer.Serialize(sw, dictionary); @@ -53,41 +53,41 @@ void WriteCacheOperation() public string GetCacheDirectory() { - var gitDir = repositoryInfo.DotGitDirectory; + var gitDir = this.repositoryInfo.DotGitDirectory; return Path.Combine(gitDir, "gitversion_cache"); } public VersionVariables? LoadVersionVariablesFromDiskCache(GitVersionCacheKey key) { - using (log.IndentLog("Loading version variables from disk cache")) + using (this.log.IndentLog("Loading version variables from disk cache")) { var cacheDir = PrepareCacheDirectory(); var cacheFileName = GetCacheFileName(key, cacheDir); - if (!fileSystem.Exists(cacheFileName)) + if (!this.fileSystem.Exists(cacheFileName)) { - log.Info("Cache file " + cacheFileName + " not found."); + this.log.Info("Cache file " + cacheFileName + " not found."); return null; } - using (log.IndentLog("Deserializing version variables from cache file " + cacheFileName)) + using (this.log.IndentLog("Deserializing version variables from cache file " + cacheFileName)) { try { - var loadedVariables = VersionVariables.FromFile(cacheFileName, fileSystem, log); + var loadedVariables = VersionVariables.FromFile(cacheFileName, this.fileSystem, this.log); return loadedVariables; } catch (Exception ex) { - log.Warning("Unable to read cache file " + cacheFileName + ", deleting it."); - log.Info(ex.ToString()); + this.log.Warning("Unable to read cache file " + cacheFileName + ", deleting it."); + this.log.Info(ex.ToString()); try { - fileSystem.Delete(cacheFileName); + this.fileSystem.Delete(cacheFileName); } catch (Exception deleteEx) { - log.Warning($"Unable to delete corrupted version cache file {cacheFileName}. Got {deleteEx.GetType().FullName} exception."); + this.log.Warning($"Unable to delete corrupted version cache file {cacheFileName}. Got {deleteEx.GetType().FullName} exception."); } return null; @@ -101,7 +101,7 @@ private string PrepareCacheDirectory() var cacheDir = GetCacheDirectory(); // If the cacheDir already exists, CreateDirectory just won't do anything (it won't fail). @asbjornu - fileSystem.CreateDirectory(cacheDir); + this.fileSystem.CreateDirectory(cacheDir); return cacheDir; } diff --git a/src/GitVersion.Core/VersionCalculation/Cache/GitVersionCacheKeyFactory.cs b/src/GitVersion.Core/VersionCalculation/Cache/GitVersionCacheKeyFactory.cs index d4e2a813f9..9704765413 100644 --- a/src/GitVersion.Core/VersionCalculation/Cache/GitVersionCacheKeyFactory.cs +++ b/src/GitVersion.Core/VersionCalculation/Cache/GitVersionCacheKeyFactory.cs @@ -47,7 +47,7 @@ public GitVersionCacheKey Create(Config? overrideConfig) private string GetGitSystemHash() { - var dotGitDirectory = repositoryInfo.DotGitDirectory; + var dotGitDirectory = this.repositoryInfo.DotGitDirectory; // traverse the directory and get a list of files, use that for GetHash var contents = CalculateDirectoryContents(Path.Combine(dotGitDirectory, "refs")); @@ -94,12 +94,12 @@ private List CalculateDirectoryContents(string root) // about the systems on which this code will run. catch (UnauthorizedAccessException e) { - log.Error(e.Message); + this.log.Error(e.Message); continue; } catch (DirectoryNotFoundException e) { - log.Error(e.Message); + this.log.Error(e.Message); continue; } @@ -110,12 +110,12 @@ private List CalculateDirectoryContents(string root) } catch (UnauthorizedAccessException e) { - log.Error(e.Message); + this.log.Error(e.Message); continue; } catch (DirectoryNotFoundException e) { - log.Error(e.Message); + this.log.Error(e.Message); continue; } @@ -129,7 +129,7 @@ private List CalculateDirectoryContents(string root) } catch (IOException e) { - log.Error(e.Message); + this.log.Error(e.Message); } } @@ -147,7 +147,7 @@ private List CalculateDirectoryContents(string root) private string GetRepositorySnapshotHash() { - var head = gitRepository.Head; + var head = this.gitRepository.Head; if (head.Tip == null) { return head.Name.Canonical; @@ -180,13 +180,13 @@ private string GetConfigFileHash() { // will return the same hash even when config file will be moved // from workingDirectory to rootProjectDirectory. It's OK. Config essentially is the same. - var configFilePath = configFileLocator.SelectConfigFilePath(options.Value, repositoryInfo); - if (!fileSystem.Exists(configFilePath)) + var configFilePath = this.configFileLocator.SelectConfigFilePath(this.options.Value, this.repositoryInfo); + if (!this.fileSystem.Exists(configFilePath)) { return string.Empty; } - var configFileContent = fileSystem.ReadAllText(configFilePath); + var configFileContent = this.fileSystem.ReadAllText(configFilePath); return GetHash(configFileContent); } diff --git a/src/GitVersion.Core/VersionCalculation/MainlineVersionCalculator.cs b/src/GitVersion.Core/VersionCalculation/MainlineVersionCalculator.cs index 01266f52cd..decbd7dab3 100644 --- a/src/GitVersion.Core/VersionCalculation/MainlineVersionCalculator.cs +++ b/src/GitVersion.Core/VersionCalculation/MainlineVersionCalculator.cs @@ -14,7 +14,7 @@ internal class MainlineVersionCalculator : IMainlineVersionCalculator private readonly ILog log; private readonly IRepositoryStore repositoryStore; private readonly Lazy versionContext; - private GitVersionContext context => versionContext.Value; + private GitVersionContext context => this.versionContext.Value; public MainlineVersionCalculator(ILog log, IRepositoryStore repositoryStore, Lazy versionContext) { @@ -30,7 +30,7 @@ public SemanticVersion FindMainlineModeVersion(BaseVersion baseVersion) throw new NotSupportedException("Mainline development mode doesn't yet support pre-release tags on main"); } - using (log.IndentLog("Using mainline development mode to calculate current version")) + using (this.log.IndentLog("Using mainline development mode to calculate current version")) { var mainlineVersion = baseVersion.SemanticVersion; @@ -48,10 +48,10 @@ public SemanticVersion FindMainlineModeVersion(BaseVersion baseVersion) if (!context.CurrentBranch!.Equals(mainline)) { mergeBase = FindMergeBaseBeforeForwardMerge(baseVersion.BaseVersionSource, mainline, out mainlineTip); - log.Info($"Current branch ({context.CurrentBranch}) was branch from {mergeBase}"); + this.log.Info($"Current branch ({context.CurrentBranch}) was branch from {mergeBase}"); } - var mainlineCommitLog = repositoryStore.GetMainlineCommitLog(baseVersion.BaseVersionSource, mainlineTip).ToList(); + var mainlineCommitLog = this.repositoryStore.GetMainlineCommitLog(baseVersion.BaseVersionSource, mainlineTip).ToList(); var directCommits = new List(mainlineCommitLog.Count); var nextVersion = context.Configuration?.NextVersion; @@ -77,7 +77,7 @@ public SemanticVersion FindMainlineModeVersion(BaseVersion baseVersion) if (!context.CurrentBranch.Equals(mainline) && nextVersion.IsNullOrEmpty()) { var branchIncrement = FindMessageIncrement(null, context.CurrentCommit, mergeBase, mainlineCommitLog); - log.Info($"Performing {branchIncrement} increment for current branch "); + this.log.Info($"Performing {branchIncrement} increment for current branch "); mainlineVersion = mainlineVersion.IncrementVersion(branchIncrement); } @@ -88,9 +88,9 @@ public SemanticVersion FindMainlineModeVersion(BaseVersion baseVersion) public SemanticVersionBuildMetaData CreateVersionBuildMetaData(ICommit? baseVersionSource) { - var commitLog = repositoryStore.GetCommitLog(baseVersionSource, context.CurrentCommit); + var commitLog = this.repositoryStore.GetCommitLog(baseVersionSource, context.CurrentCommit); var commitsSinceTag = commitLog.Count(); - log.Info($"{commitsSinceTag} commits found between {baseVersionSource} and {context.CurrentCommit}"); + this.log.Info($"{commitsSinceTag} commits found between {baseVersionSource} and {context.CurrentCommit}"); var shortSha = context.CurrentCommit?.Id.ToString(7); return new SemanticVersionBuildMetaData( @@ -109,7 +109,7 @@ private SemanticVersion AggregateMergeCommitIncrement(ICommit commit, List b.Value?.IsMainline == true).ToList(); - var mainlineBranches = repositoryStore.GetMainlineBranches(context.CurrentCommit!, mainlineBranchConfigs); + var mainlineBranches = this.repositoryStore.GetMainlineBranches(context.CurrentCommit!, mainlineBranchConfigs); var allMainlines = mainlineBranches.Values.SelectMany(branches => branches.Select(b => b.Name.Friendly)); - log.Info("Found possible mainline branches: " + string.Join(", ", allMainlines)); + this.log.Info("Found possible mainline branches: " + string.Join(", ", allMainlines)); // Find closest mainline branch var firstMatchingCommit = context.CurrentBranch?.Commits.First(c => mainlineBranches.ContainsKey(c.Sha)); @@ -138,32 +138,32 @@ private IBranch GetMainline(ICommit? baseVersionSource) if (possibleMainlineBranches.Count == 1) { var mainlineBranch = possibleMainlineBranches[0]; - log.Info($"Mainline for current branch is {mainlineBranch}"); + this.log.Info($"Mainline for current branch is {mainlineBranch}"); return mainlineBranch; } // prefer current branch, if it is a mainline branch if (possibleMainlineBranches.Any(context.CurrentBranch!.Equals)) { - log.Info($"Choosing {context.CurrentBranch} as mainline because it is the current branch"); + this.log.Info($"Choosing {context.CurrentBranch} as mainline because it is the current branch"); return context.CurrentBranch; } // prefer a branch on which the merge base was a direct commit, if there is such a branch - var firstMatchingCommitBranch = possibleMainlineBranches.FirstOrDefault(b => repositoryStore.IsCommitOnBranch(baseVersionSource, b, firstMatchingCommit)); + var firstMatchingCommitBranch = possibleMainlineBranches.FirstOrDefault(b => this.repositoryStore.IsCommitOnBranch(baseVersionSource, b, firstMatchingCommit)); if (firstMatchingCommitBranch != null) { var message = string.Format( "Choosing {0} as mainline because {1}'s merge base was a direct commit to {0}", firstMatchingCommitBranch, context.CurrentBranch); - log.Info(message); + this.log.Info(message); return firstMatchingCommitBranch; } var chosenMainline = possibleMainlineBranches[0]; - log.Info($"Multiple mainlines ({string.Join(", ", possibleMainlineBranches.Select(b => b))}) have the same merge base for the current branch, choosing {chosenMainline} because we found that branch first..."); + this.log.Info($"Multiple mainlines ({string.Join(", ", possibleMainlineBranches.Select(b => b))}) have the same merge base for the current branch, choosing {chosenMainline} because we found that branch first..."); return chosenMainline; } @@ -185,7 +185,7 @@ private IBranch GetMainline(ICommit? baseVersionSource) { if (Equals(commit, mergeBase) || commit.Parents.Contains(mergeBase)) { - log.Info($"Found branch merge point; choosing {commit} as effective mainline tip"); + this.log.Info($"Found branch merge point; choosing {commit} as effective mainline tip"); return commit; } } @@ -202,8 +202,8 @@ private IBranch GetMainline(ICommit? baseVersionSource) /// The best possible merge base between the current commit and that is not the child of a forward merge. private ICommit FindMergeBaseBeforeForwardMerge(ICommit? baseVersionSource, IBranch mainline, [NotNullWhen(true)] out ICommit? mainlineTip) { - var mergeBase = repositoryStore.FindMergeBase(context.CurrentCommit!, mainline.Tip!); - var mainlineCommitLog = repositoryStore.GetMainlineCommitLog(baseVersionSource, mainline.Tip).ToList(); + var mergeBase = this.repositoryStore.FindMergeBase(context.CurrentCommit!, mainline.Tip!); + var mainlineCommitLog = this.repositoryStore.GetMainlineCommitLog(baseVersionSource, mainline.Tip).ToList(); // find the mainline commit effective for versioning the current branch mainlineTip = GetEffectiveMainlineTip(mainlineCommitLog, mergeBase, mainline.Tip); @@ -216,10 +216,10 @@ private ICommit FindMergeBaseBeforeForwardMerge(ICommit? baseVersionSource, IBra { var message = $"Detected forward merge at {mainlineTip}; rewinding mainline to previous commit {mainlineTipPrevious}"; - log.Info(message); + this.log.Info(message); // re-do mergeBase detection before the forward merge - mergeBase = repositoryStore.FindMergeBase(context.CurrentCommit, mainlineTipPrevious); + mergeBase = this.repositoryStore.FindMergeBase(context.CurrentCommit, mainlineTipPrevious); mainlineTip = GetEffectiveMainlineTip(mainlineCommitLog, mergeBase, mainlineTipPrevious); } } @@ -234,7 +234,7 @@ private SemanticVersion IncrementForEachCommit(IEnumerable directCommit var directCommitIncrement = IncrementStrategyFinder.GetIncrementForCommits(context, new[] { directCommit }) ?? FindDefaultIncrementForBranch(context, mainline.Name.Friendly); mainlineVersion = mainlineVersion.IncrementVersion(directCommitIncrement); - log.Info($"Direct commit on main {directCommit} incremented base versions {directCommitIncrement}, now {mainlineVersion}"); + this.log.Info($"Direct commit on main {directCommit} incremented base versions {directCommitIncrement}, now {mainlineVersion}"); } return mainlineVersion; @@ -242,7 +242,7 @@ private SemanticVersion IncrementForEachCommit(IEnumerable directCommit private VersionField FindMessageIncrement(ICommit? mergeCommit, ICommit? mergedHead, ICommit? findMergeBase, List commitLog) { - var commits = repositoryStore.GetMergeBaseCommits(mergeCommit, mergedHead, findMergeBase); + var commits = this.repositoryStore.GetMergeBaseCommits(mergeCommit, mergedHead, findMergeBase); commitLog.RemoveAll(c => commits.Any(c1 => c1.Sha == c.Sha)); return IncrementStrategyFinder.GetIncrementForCommits(context, commits) ?? TryFindIncrementFromMergeMessage(mergeCommit); diff --git a/src/GitVersion.Core/VersionCalculation/MinDateVersionFilter.cs b/src/GitVersion.Core/VersionCalculation/MinDateVersionFilter.cs index a5d3610abb..4a6bf2df36 100644 --- a/src/GitVersion.Core/VersionCalculation/MinDateVersionFilter.cs +++ b/src/GitVersion.Core/VersionCalculation/MinDateVersionFilter.cs @@ -19,7 +19,7 @@ public bool Exclude(BaseVersion version, [NotNullWhen(true)] out string? reason) reason = null; if (version.BaseVersionSource != null && - version.BaseVersionSource.When < minimum) + version.BaseVersionSource.When < this.minimum) { reason = "Source was ignored due to commit date being outside of configured range"; return true; diff --git a/src/GitVersion.Core/VersionCalculation/NextVersionCalculator.cs b/src/GitVersion.Core/VersionCalculation/NextVersionCalculator.cs index 3d7a780c47..2fe5188351 100644 --- a/src/GitVersion.Core/VersionCalculation/NextVersionCalculator.cs +++ b/src/GitVersion.Core/VersionCalculation/NextVersionCalculator.cs @@ -14,7 +14,7 @@ public class NextVersionCalculator : INextVersionCalculator private readonly IMainlineVersionCalculator mainlineVersionCalculator; private readonly IRepositoryStore repositoryStore; private readonly Lazy versionContext; - private GitVersionContext context => versionContext.Value; + private GitVersionContext context => this.versionContext.Value; public NextVersionCalculator(ILog log, IBaseVersionCalculator baseVersionCalculator, IMainlineVersionCalculator mainlineVersionCalculator, IRepositoryStore repositoryStore, @@ -29,10 +29,10 @@ public NextVersionCalculator(ILog log, IBaseVersionCalculator baseVersionCalcula public SemanticVersion FindVersion() { - log.Info($"Running against branch: {context.CurrentBranch} ({context.CurrentCommit?.ToString() ?? "-"})"); + this.log.Info($"Running against branch: {context.CurrentBranch} ({context.CurrentCommit?.ToString() ?? "-"})"); if (context.IsCurrentCommitTagged) { - log.Info($"Current commit is tagged with version {context.CurrentCommitTaggedVersion}, " + + this.log.Info($"Current commit is tagged with version {context.CurrentCommitTaggedVersion}, " + "version calculation is for metadata only."); } else @@ -45,7 +45,7 @@ public SemanticVersion FindVersion() if (context.IsCurrentCommitTagged) { // Will always be 0, don't bother with the +0 on tags - var semanticVersionBuildMetaData = mainlineVersionCalculator.CreateVersionBuildMetaData(context.CurrentCommit); + var semanticVersionBuildMetaData = this.mainlineVersionCalculator.CreateVersionBuildMetaData(context.CurrentCommit); semanticVersionBuildMetaData.CommitsSinceTag = null; var semanticVersion = new SemanticVersion(context.CurrentCommitTaggedVersion) @@ -55,19 +55,19 @@ public SemanticVersion FindVersion() taggedSemanticVersion = semanticVersion; } - var baseVersion = baseVersionCalculator.GetBaseVersion(); - baseVersion.SemanticVersion.BuildMetaData = mainlineVersionCalculator.CreateVersionBuildMetaData(baseVersion.BaseVersionSource); + var baseVersion = this.baseVersionCalculator.GetBaseVersion(); + baseVersion.SemanticVersion.BuildMetaData = this.mainlineVersionCalculator.CreateVersionBuildMetaData(baseVersion.BaseVersionSource); SemanticVersion semver; if (context.Configuration?.VersioningMode == VersioningMode.Mainline) { - semver = mainlineVersionCalculator.FindMainlineModeVersion(baseVersion); + semver = this.mainlineVersionCalculator.FindMainlineModeVersion(baseVersion); } else { if (taggedSemanticVersion?.BuildMetaData == null || (taggedSemanticVersion.BuildMetaData.Sha != baseVersion.SemanticVersion.BuildMetaData.Sha)) { semver = PerformIncrement(baseVersion); - semver.BuildMetaData = mainlineVersionCalculator.CreateVersionBuildMetaData(baseVersion.BaseVersionSource); + semver.BuildMetaData = this.mainlineVersionCalculator.CreateVersionBuildMetaData(baseVersion.BaseVersionSource); } else { @@ -106,22 +106,22 @@ public SemanticVersion FindVersion() private SemanticVersion PerformIncrement(BaseVersion baseVersion) { var semver = baseVersion.SemanticVersion; - var increment = repositoryStore.DetermineIncrementedField(baseVersion, context); + var increment = this.repositoryStore.DetermineIncrementedField(baseVersion, context); if (increment != null) { semver = semver.IncrementVersion(increment.Value); } - else log.Info("Skipping version increment"); + else this.log.Info("Skipping version increment"); return semver; } private void UpdatePreReleaseTag(SemanticVersion semanticVersion, string? branchNameOverride) { - var tagToUse = context.Configuration?.GetBranchSpecificTag(log, context.CurrentBranch?.Name.Friendly, branchNameOverride); + var tagToUse = context.Configuration?.GetBranchSpecificTag(this.log, context.CurrentBranch?.Name.Friendly, branchNameOverride); int? number = null; - var lastTag = repositoryStore + var lastTag = this.repositoryStore .GetVersionTagsOnBranch(context.CurrentBranch!, context.Configuration?.GitTagPrefix) .FirstOrDefault(v => v?.PreReleaseTag?.Name?.IsEquivalentTo(tagToUse) == true); diff --git a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs index b996957534..e919f14c96 100644 --- a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs +++ b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs @@ -21,21 +21,21 @@ public class SemanticVersion : IFormattable, IComparable public SemanticVersion(int major = 0, int minor = 0, int patch = 0) { - Major = major; - Minor = minor; - Patch = patch; - PreReleaseTag = new SemanticVersionPreReleaseTag(); - BuildMetaData = new SemanticVersionBuildMetaData(); + this.Major = major; + this.Minor = minor; + this.Patch = patch; + this.PreReleaseTag = new SemanticVersionPreReleaseTag(); + this.BuildMetaData = new SemanticVersionBuildMetaData(); } public SemanticVersion(SemanticVersion? semanticVersion) { - Major = semanticVersion?.Major ?? 0; - Minor = semanticVersion?.Minor ?? 0; - Patch = semanticVersion?.Patch ?? 0; + this.Major = semanticVersion?.Major ?? 0; + this.Minor = semanticVersion?.Minor ?? 0; + this.Patch = semanticVersion?.Patch ?? 0; - PreReleaseTag = new SemanticVersionPreReleaseTag(semanticVersion?.PreReleaseTag); - BuildMetaData = new SemanticVersionBuildMetaData(semanticVersion?.BuildMetaData); + this.PreReleaseTag = new SemanticVersionPreReleaseTag(semanticVersion?.PreReleaseTag); + this.BuildMetaData = new SemanticVersionBuildMetaData(semanticVersion?.BuildMetaData); } public bool Equals(SemanticVersion? obj) @@ -44,11 +44,11 @@ public bool Equals(SemanticVersion? obj) { return false; } - return Major == obj.Major && - Minor == obj.Minor && - Patch == obj.Patch && - PreReleaseTag == obj.PreReleaseTag && - BuildMetaData == obj.BuildMetaData; + return this.Major == obj.Major && + this.Minor == obj.Minor && + this.Patch == obj.Patch && + this.PreReleaseTag == obj.PreReleaseTag && + this.BuildMetaData == obj.BuildMetaData; } public bool IsEmpty() @@ -77,11 +77,11 @@ public override int GetHashCode() { unchecked { - var hashCode = Major; - hashCode = (hashCode * 397) ^ Minor; - hashCode = (hashCode * 397) ^ Patch; - hashCode = (hashCode * 397) ^ (PreReleaseTag != null ? PreReleaseTag.GetHashCode() : 0); - hashCode = (hashCode * 397) ^ (BuildMetaData != null ? BuildMetaData.GetHashCode() : 0); + var hashCode = this.Major; + hashCode = (hashCode * 397) ^ this.Minor; + hashCode = (hashCode * 397) ^ this.Patch; + hashCode = (hashCode * 397) ^ (this.PreReleaseTag != null ? this.PreReleaseTag.GetHashCode() : 0); + hashCode = (hashCode * 397) ^ (this.BuildMetaData != null ? this.BuildMetaData.GetHashCode() : 0); return hashCode; } } @@ -195,33 +195,33 @@ public int CompareTo(SemanticVersion? value, bool includePrerelease) { return 1; } - if (Major != value.Major) + if (this.Major != value.Major) { - if (Major > value.Major) + if (this.Major > value.Major) { return 1; } return -1; } - if (Minor != value.Minor) + if (this.Minor != value.Minor) { - if (Minor > value.Minor) + if (this.Minor > value.Minor) { return 1; } return -1; } - if (Patch != value.Patch) + if (this.Patch != value.Patch) { - if (Patch > value.Patch) + if (this.Patch > value.Patch) { return 1; } return -1; } - if (includePrerelease && PreReleaseTag != value?.PreReleaseTag) + if (includePrerelease && this.PreReleaseTag != value?.PreReleaseTag) { - if (PreReleaseTag > value?.PreReleaseTag) + if (this.PreReleaseTag > value?.PreReleaseTag) { return 1; } @@ -258,28 +258,28 @@ public string ToString(string? format, IFormatProvider? formatProvider = null) if (format.StartsWith("lp", StringComparison.Ordinal)) { // handle the padding - return PreReleaseTag?.HasTag() == true ? $"{ToString("j")}-{PreReleaseTag.ToString(format)}" : ToString("j"); + return this.PreReleaseTag?.HasTag() == true ? $"{ToString("j")}-{this.PreReleaseTag.ToString(format)}" : ToString("j"); } switch (format) { case "j": - return $"{Major}.{Minor}.{Patch}"; + return $"{this.Major}.{this.Minor}.{this.Patch}"; case "s": - return PreReleaseTag?.HasTag() == true ? $"{ToString("j")}-{PreReleaseTag}" : ToString("j"); + return this.PreReleaseTag?.HasTag() == true ? $"{ToString("j")}-{this.PreReleaseTag}" : ToString("j"); case "t": - return PreReleaseTag?.HasTag() == true ? $"{ToString("j")}-{PreReleaseTag.ToString("t")}" : ToString("j"); + return this.PreReleaseTag?.HasTag() == true ? $"{ToString("j")}-{this.PreReleaseTag.ToString("t")}" : ToString("j"); case "l": - return PreReleaseTag?.HasTag() == true ? $"{ToString("j")}-{PreReleaseTag.ToString("l")}" : ToString("j"); + return this.PreReleaseTag?.HasTag() == true ? $"{ToString("j")}-{this.PreReleaseTag.ToString("l")}" : ToString("j"); case "f": { - var buildMetadata = BuildMetaData?.ToString(); + var buildMetadata = this.BuildMetaData?.ToString(); return !buildMetadata.IsNullOrEmpty() ? $"{ToString("s")}+{buildMetadata}" : ToString("s"); } case "i": { - var buildMetadata = BuildMetaData?.ToString("f"); + var buildMetadata = this.BuildMetaData?.ToString("f"); return !buildMetadata.IsNullOrEmpty() ? $"{ToString("s")}+{buildMetadata}" : ToString("s"); } diff --git a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionBuildMetaData.cs b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionBuildMetaData.cs index 8d259405e9..fa76df7e3c 100644 --- a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionBuildMetaData.cs +++ b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionBuildMetaData.cs @@ -30,28 +30,28 @@ public SemanticVersionBuildMetaData() public SemanticVersionBuildMetaData(string? versionSourceSha, int? commitsSinceTag, string? branch, string? commitSha, string? commitShortSha, DateTimeOffset? commitDate, int numbeerOfUncommitedChanges, string? otherMetadata = null) { - Sha = commitSha; - ShortSha = commitShortSha; - CommitsSinceTag = commitsSinceTag; - Branch = branch; - CommitDate = commitDate; - OtherMetaData = otherMetadata; - VersionSourceSha = versionSourceSha; - CommitsSinceVersionSource = commitsSinceTag ?? 0; - UncommittedChanges = numbeerOfUncommitedChanges; + this.Sha = commitSha; + this.ShortSha = commitShortSha; + this.CommitsSinceTag = commitsSinceTag; + this.Branch = branch; + this.CommitDate = commitDate; + this.OtherMetaData = otherMetadata; + this.VersionSourceSha = versionSourceSha; + this.CommitsSinceVersionSource = commitsSinceTag ?? 0; + this.UncommittedChanges = numbeerOfUncommitedChanges; } public SemanticVersionBuildMetaData(SemanticVersionBuildMetaData? buildMetaData) { - Sha = buildMetaData?.Sha; - ShortSha = buildMetaData?.ShortSha; - CommitsSinceTag = buildMetaData?.CommitsSinceTag; - Branch = buildMetaData?.Branch; - CommitDate = buildMetaData?.CommitDate; - OtherMetaData = buildMetaData?.OtherMetaData; - VersionSourceSha = buildMetaData?.VersionSourceSha; - CommitsSinceVersionSource = buildMetaData?.CommitsSinceVersionSource; - UncommittedChanges = buildMetaData?.UncommittedChanges ?? 0; + this.Sha = buildMetaData?.Sha; + this.ShortSha = buildMetaData?.ShortSha; + this.CommitsSinceTag = buildMetaData?.CommitsSinceTag; + this.Branch = buildMetaData?.Branch; + this.CommitDate = buildMetaData?.CommitDate; + this.OtherMetaData = buildMetaData?.OtherMetaData; + this.VersionSourceSha = buildMetaData?.VersionSourceSha; + this.CommitsSinceVersionSource = buildMetaData?.CommitsSinceVersionSource; + this.UncommittedChanges = buildMetaData?.UncommittedChanges ?? 0; } public override bool Equals(object obj) @@ -105,14 +105,14 @@ public string ToString(string? format, IFormatProvider? formatProvider = null) } } - return CommitsSinceTag != null ? CommitsSinceTag.Value.ToString("D" + padding) : string.Empty; + return this.CommitsSinceTag != null ? this.CommitsSinceTag.Value.ToString("D" + padding) : string.Empty; } return format.ToLower() switch { - "b" => CommitsSinceTag.ToString(), - "s" => $"{CommitsSinceTag}{(Sha.IsNullOrEmpty() ? null : ".Sha." + Sha)}".TrimStart('.'), - "f" => $"{CommitsSinceTag}{(Branch.IsNullOrEmpty() ? null : ".Branch." + FormatMetaDataPart(Branch))}{(Sha.IsNullOrEmpty() ? null : ".Sha." + Sha)}{(OtherMetaData.IsNullOrEmpty() ? null : "." + FormatMetaDataPart(OtherMetaData))}".TrimStart('.'), + "b" => this.CommitsSinceTag.ToString(), + "s" => $"{this.CommitsSinceTag}{(this.Sha.IsNullOrEmpty() ? null : ".Sha." + this.Sha)}".TrimStart('.'), + "f" => $"{this.CommitsSinceTag}{(this.Branch.IsNullOrEmpty() ? null : ".Branch." + FormatMetaDataPart(this.Branch))}{(this.Sha.IsNullOrEmpty() ? null : ".Sha." + this.Sha)}{(this.OtherMetaData.IsNullOrEmpty() ? null : "." + FormatMetaDataPart(this.OtherMetaData))}".TrimStart('.'), _ => throw new ArgumentException("Unrecognised format", nameof(format)) }; } diff --git a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionFormatValues.cs b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionFormatValues.cs index 4555b6ad23..b6bda809b5 100644 --- a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionFormatValues.cs +++ b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionFormatValues.cs @@ -16,53 +16,53 @@ public SemanticVersionFormatValues(SemanticVersion semver, EffectiveConfiguratio this.config = config; } - public string Major => semver.Major.ToString(); + public string Major => this.semver.Major.ToString(); - public string Minor => semver.Minor.ToString(); + public string Minor => this.semver.Minor.ToString(); - public string Patch => semver.Patch.ToString(); + public string Patch => this.semver.Patch.ToString(); - public string? PreReleaseTag => semver.PreReleaseTag; + public string? PreReleaseTag => this.semver.PreReleaseTag; - public string? PreReleaseTagWithDash => semver.PreReleaseTag?.HasTag() == true ? "-" + semver.PreReleaseTag : null; + public string? PreReleaseTagWithDash => this.semver.PreReleaseTag?.HasTag() == true ? "-" + this.semver.PreReleaseTag : null; - public string? PreReleaseLabel => semver.PreReleaseTag?.HasTag() == true ? semver.PreReleaseTag.Name : null; + public string? PreReleaseLabel => this.semver.PreReleaseTag?.HasTag() == true ? this.semver.PreReleaseTag.Name : null; - public string? PreReleaseLabelWithDash => semver.PreReleaseTag?.HasTag() == true ? "-" + semver.PreReleaseTag.Name : null; + public string? PreReleaseLabelWithDash => this.semver.PreReleaseTag?.HasTag() == true ? "-" + this.semver.PreReleaseTag.Name : null; - public string? PreReleaseNumber => semver.PreReleaseTag?.HasTag() == true ? semver.PreReleaseTag.Number.ToString() : null; + public string? PreReleaseNumber => this.semver.PreReleaseTag?.HasTag() == true ? this.semver.PreReleaseTag.Number.ToString() : null; public string WeightedPreReleaseNumber => GetWeightedPreReleaseNumber(); - public string? BuildMetaData => semver.BuildMetaData; + public string? BuildMetaData => this.semver.BuildMetaData; - public string? BuildMetaDataPadded => semver.BuildMetaData?.ToString("p" + config.BuildMetaDataPadding); + public string? BuildMetaDataPadded => this.semver.BuildMetaData?.ToString("p" + this.config.BuildMetaDataPadding); - public string? FullBuildMetaData => semver.BuildMetaData?.ToString("f"); + public string? FullBuildMetaData => this.semver.BuildMetaData?.ToString("f"); - public string MajorMinorPatch => $"{semver.Major}.{semver.Minor}.{semver.Patch}"; + public string MajorMinorPatch => $"{this.semver.Major}.{this.semver.Minor}.{this.semver.Patch}"; - public string SemVer => semver.ToString(); + public string SemVer => this.semver.ToString(); - public string LegacySemVer => semver.ToString("l"); + public string LegacySemVer => this.semver.ToString("l"); - public string LegacySemVerPadded => semver.ToString("lp" + config.LegacySemVerPadding); + public string LegacySemVerPadded => this.semver.ToString("lp" + this.config.LegacySemVerPadding); - public string? AssemblySemVer => semver.GetAssemblyVersion(config.AssemblyVersioningScheme); + public string? AssemblySemVer => this.semver.GetAssemblyVersion(this.config.AssemblyVersioningScheme); - public string? AssemblyFileSemVer => semver.GetAssemblyFileVersion(config.AssemblyFileVersioningScheme); + public string? AssemblyFileSemVer => this.semver.GetAssemblyFileVersion(this.config.AssemblyFileVersioningScheme); - public string FullSemVer => semver.ToString("f"); + public string FullSemVer => this.semver.ToString("f"); - public string? BranchName => semver.BuildMetaData?.Branch; + public string? BranchName => this.semver.BuildMetaData?.Branch; - public string? EscapedBranchName => semver.BuildMetaData?.Branch?.RegexReplace("[^a-zA-Z0-9-]", "-"); + public string? EscapedBranchName => this.semver.BuildMetaData?.Branch?.RegexReplace("[^a-zA-Z0-9-]", "-"); - public string? Sha => semver.BuildMetaData?.Sha; + public string? Sha => this.semver.BuildMetaData?.Sha; - public string? ShortSha => semver.BuildMetaData?.ShortSha; + public string? ShortSha => this.semver.BuildMetaData?.ShortSha; - public string? CommitDate => semver.BuildMetaData?.CommitDate?.UtcDateTime.ToString(config.CommitDateFormat, CultureInfo.InvariantCulture); + public string? CommitDate => this.semver.BuildMetaData?.CommitDate?.UtcDateTime.ToString(this.config.CommitDateFormat, CultureInfo.InvariantCulture); // TODO When NuGet 3 is released: public string NuGetVersionV3 { get { return ??; } } @@ -70,31 +70,31 @@ public SemanticVersionFormatValues(SemanticVersion semver, EffectiveConfiguratio public string NuGetVersion => NuGetVersionV2; - public string? NuGetPreReleaseTagV2 => semver.PreReleaseTag?.HasTag() == true ? semver.PreReleaseTag?.ToString("lp")?.ToLower() : null; + public string? NuGetPreReleaseTagV2 => this.semver.PreReleaseTag?.HasTag() == true ? this.semver.PreReleaseTag?.ToString("lp")?.ToLower() : null; public string? NuGetPreReleaseTag => NuGetPreReleaseTagV2; - public string InformationalVersion => semver.ToString("i"); + public string InformationalVersion => this.semver.ToString("i"); [Obsolete("Use InformationalVersion instead")] public string DefaultInformationalVersion => InformationalVersion; - public string? VersionSourceSha => semver.BuildMetaData?.VersionSourceSha; + public string? VersionSourceSha => this.semver.BuildMetaData?.VersionSourceSha; - public string? CommitsSinceVersionSource => semver.BuildMetaData?.CommitsSinceVersionSource?.ToString(CultureInfo.InvariantCulture); + public string? CommitsSinceVersionSource => this.semver.BuildMetaData?.CommitsSinceVersionSource?.ToString(CultureInfo.InvariantCulture); - public string? CommitsSinceVersionSourcePadded => semver.BuildMetaData?.CommitsSinceVersionSource?.ToString(CultureInfo.InvariantCulture).PadLeft(config.CommitsSinceVersionSourcePadding, '0'); + public string? CommitsSinceVersionSourcePadded => this.semver.BuildMetaData?.CommitsSinceVersionSource?.ToString(CultureInfo.InvariantCulture).PadLeft(this.config.CommitsSinceVersionSourcePadding, '0'); - public string? UncommittedChanges => semver.BuildMetaData?.UncommittedChanges.ToString(CultureInfo.InvariantCulture); + public string? UncommittedChanges => this.semver.BuildMetaData?.UncommittedChanges.ToString(CultureInfo.InvariantCulture); private string GetWeightedPreReleaseNumber() { var weightedPreReleaseNumber = - semver.PreReleaseTag?.HasTag() == true ? (semver.PreReleaseTag.Number + config.PreReleaseWeight).ToString() : null; + this.semver.PreReleaseTag?.HasTag() == true ? (this.semver.PreReleaseTag.Number + this.config.PreReleaseWeight).ToString() : null; if (weightedPreReleaseNumber.IsNullOrEmpty()) { - return $"{config.TagPreReleaseWeight}"; + return $"{this.config.TagPreReleaseWeight}"; } return weightedPreReleaseNumber; diff --git a/src/GitVersion.Core/VersionCalculation/ShaVersionFilter.cs b/src/GitVersion.Core/VersionCalculation/ShaVersionFilter.cs index 43f149cd55..7068a2cab6 100644 --- a/src/GitVersion.Core/VersionCalculation/ShaVersionFilter.cs +++ b/src/GitVersion.Core/VersionCalculation/ShaVersionFilter.cs @@ -21,7 +21,7 @@ public bool Exclude(BaseVersion version, [NotNullWhen(true)] out string? reason) reason = null; if (version.BaseVersionSource != null && - shas.Any(sha => version.BaseVersionSource.Sha.StartsWith(sha, StringComparison.OrdinalIgnoreCase))) + this.shas.Any(sha => version.BaseVersionSource.Sha.StartsWith(sha, StringComparison.OrdinalIgnoreCase))) { reason = $"Sha {version.BaseVersionSource} was ignored due to commit having been excluded by configuration"; return true; diff --git a/src/GitVersion.Core/VersionCalculation/VariableProvider.cs b/src/GitVersion.Core/VersionCalculation/VariableProvider.cs index 797a7d3154..48896a9265 100644 --- a/src/GitVersion.Core/VersionCalculation/VariableProvider.cs +++ b/src/GitVersion.Core/VersionCalculation/VariableProvider.cs @@ -29,7 +29,7 @@ public VersionVariables GetVariablesFor(SemanticVersion semanticVersion, Effecti // Continuous Deployment always requires a pre-release tag unless the commit is tagged if (semanticVersion.PreReleaseTag?.HasTag() != true) { - semanticVersion.PreReleaseTag!.Name = config.GetBranchSpecificTag(log, semanticVersion.BuildMetaData?.Branch, null); + semanticVersion.PreReleaseTag!.Name = config.GetBranchSpecificTag(this.log, semanticVersion.BuildMetaData?.Branch, null); if (semanticVersion.PreReleaseTag.Name.IsNullOrEmpty()) { semanticVersion.PreReleaseTag.Name = config.ContinuousDeploymentFallbackTag; @@ -139,7 +139,7 @@ private static void PromoteNumberOfCommitsToTagNumber(SemanticVersion semanticVe try { - formattedString = formatString.FormatWith(source, environment).RegexReplace("[^0-9A-Za-z-.+]", "-"); + formattedString = formatString.FormatWith(source, this.environment).RegexReplace("[^0-9A-Za-z-.+]", "-"); } catch (ArgumentException formex) { @@ -157,7 +157,7 @@ private void WarnIfUsingObsoleteFormatValues(string formatString) #pragma warning restore CS0618 // Type or member is obsolete if (formatString.Contains($"{{{obsoletePropertyName}}}")) { - log.Write(LogLevel.Warn, $"Use format variable '{nameof(SemanticVersionFormatValues.InformationalVersion)}' instead of '{obsoletePropertyName}' which is obsolete and will be removed in a future release."); + this.log.Write(LogLevel.Warn, $"Use format variable '{nameof(SemanticVersionFormatValues.InformationalVersion)}' instead of '{obsoletePropertyName}' which is obsolete and will be removed in a future release."); } } } diff --git a/src/GitVersion.Core/VersionConverters/AssemblyInfo/AssemblyInfoFileUpdater.cs b/src/GitVersion.Core/VersionConverters/AssemblyInfo/AssemblyInfoFileUpdater.cs index 1d1f71ce10..92de52eef7 100644 --- a/src/GitVersion.Core/VersionConverters/AssemblyInfo/AssemblyInfoFileUpdater.cs +++ b/src/GitVersion.Core/VersionConverters/AssemblyInfo/AssemblyInfoFileUpdater.cs @@ -39,14 +39,14 @@ public AssemblyInfoFileUpdater(ILog log, IFileSystem fileSystem) { this.fileSystem = fileSystem; this.log = log; - templateManager = new TemplateManager(TemplateType.AssemblyInfo); + this.templateManager = new TemplateManager(TemplateType.AssemblyInfo); } public void Execute(VersionVariables variables, AssemblyInfoContext context) { var assemblyInfoFiles = GetAssemblyInfoFiles(context).ToList(); - log.Info("Updating assembly info files"); - log.Info($"Found {assemblyInfoFiles.Count} files"); + this.log.Info("Updating assembly info files"); + this.log.Info($"Found {assemblyInfoFiles.Count} files"); var assemblyVersion = variables.AssemblySemVer; var assemblyVersionString = !assemblyVersion.IsNullOrWhiteSpace() ? $"AssemblyVersion(\"{assemblyVersion}\")" : null; @@ -61,37 +61,37 @@ public void Execute(VersionVariables variables, AssemblyInfoContext context) { var localAssemblyInfo = assemblyInfoFile.FullName; var backupAssemblyInfo = localAssemblyInfo + ".bak"; - fileSystem.Copy(localAssemblyInfo, backupAssemblyInfo, true); + this.fileSystem.Copy(localAssemblyInfo, backupAssemblyInfo, true); - restoreBackupTasks.Add(() => + this.restoreBackupTasks.Add(() => { - if (fileSystem.Exists(localAssemblyInfo)) + if (this.fileSystem.Exists(localAssemblyInfo)) { - fileSystem.Delete(localAssemblyInfo); + this.fileSystem.Delete(localAssemblyInfo); } - fileSystem.Move(backupAssemblyInfo, localAssemblyInfo); + this.fileSystem.Move(backupAssemblyInfo, localAssemblyInfo); }); - cleanupBackupTasks.Add(() => fileSystem.Delete(backupAssemblyInfo)); + this.cleanupBackupTasks.Add(() => this.fileSystem.Delete(backupAssemblyInfo)); - var originalFileContents = fileSystem.ReadAllText(localAssemblyInfo); + var originalFileContents = this.fileSystem.ReadAllText(localAssemblyInfo); var fileContents = originalFileContents; var appendedAttributes = false; if (!assemblyVersion.IsNullOrWhiteSpace()) { - fileContents = ReplaceOrInsertAfterLastAssemblyAttributeOrAppend(assemblyVersionRegex, fileContents, assemblyVersionString, assemblyInfoFile.Extension, ref appendedAttributes); + fileContents = ReplaceOrInsertAfterLastAssemblyAttributeOrAppend(this.assemblyVersionRegex, fileContents, assemblyVersionString, assemblyInfoFile.Extension, ref appendedAttributes); } if (!assemblyFileVersion.IsNullOrWhiteSpace()) { - fileContents = ReplaceOrInsertAfterLastAssemblyAttributeOrAppend(assemblyFileVersionRegex, fileContents, assemblyFileVersionString, assemblyInfoFile.Extension, ref appendedAttributes); + fileContents = ReplaceOrInsertAfterLastAssemblyAttributeOrAppend(this.assemblyFileVersionRegex, fileContents, assemblyFileVersionString, assemblyInfoFile.Extension, ref appendedAttributes); } if (!assemblyInfoVersion.IsNullOrWhiteSpace()) { - fileContents = ReplaceOrInsertAfterLastAssemblyAttributeOrAppend(assemblyInfoVersionRegex, fileContents, assemblyInfoVersionString, assemblyInfoFile.Extension, ref appendedAttributes); + fileContents = ReplaceOrInsertAfterLastAssemblyAttributeOrAppend(this.assemblyInfoVersionRegex, fileContents, assemblyInfoVersionString, assemblyInfoFile.Extension, ref appendedAttributes); } if (appendedAttributes) @@ -102,7 +102,7 @@ public void Execute(VersionVariables variables, AssemblyInfoContext context) if (originalFileContents != fileContents) { - fileSystem.WriteAllText(localAssemblyInfo, fileContents); + this.fileSystem.WriteAllText(localAssemblyInfo, fileContents); } } CommitChanges(); @@ -110,36 +110,36 @@ public void Execute(VersionVariables variables, AssemblyInfoContext context) public void Dispose() { - foreach (var restoreBackup in restoreBackupTasks) + foreach (var restoreBackup in this.restoreBackupTasks) { restoreBackup(); } - cleanupBackupTasks.Clear(); - restoreBackupTasks.Clear(); + this.cleanupBackupTasks.Clear(); + this.restoreBackupTasks.Clear(); } private void CommitChanges() { - foreach (var cleanupBackupTask in cleanupBackupTasks) + foreach (var cleanupBackupTask in this.cleanupBackupTasks) { cleanupBackupTask(); } - cleanupBackupTasks.Clear(); - restoreBackupTasks.Clear(); + this.cleanupBackupTasks.Clear(); + this.restoreBackupTasks.Clear(); } private string ReplaceOrInsertAfterLastAssemblyAttributeOrAppend(Regex replaceRegex, string inputString, string? replaceString, string fileExtension, ref bool appendedAttributes) { - var assemblyAddFormat = templateManager.GetAddFormatFor(fileExtension); + var assemblyAddFormat = this.templateManager.GetAddFormatFor(fileExtension); if (replaceRegex.IsMatch(inputString)) { return replaceRegex.Replace(inputString, replaceString); } - if (assemblyAttributeRegexes.TryGetValue(fileExtension, out var assemblyRegex)) + if (this.assemblyAttributeRegexes.TryGetValue(fileExtension, out var assemblyRegex)) { var assemblyMatches = assemblyRegex.Matches(inputString); if (assemblyMatches.Count > 0) @@ -178,11 +178,11 @@ private IEnumerable GetAssemblyInfoFiles(AssemblyInfoContext context) } else { - foreach (var item in fileSystem.DirectoryEnumerateFiles(workingDirectory, "AssemblyInfo.*", SearchOption.AllDirectories)) + foreach (var item in this.fileSystem.DirectoryEnumerateFiles(workingDirectory, "AssemblyInfo.*", SearchOption.AllDirectories)) { var assemblyInfoFile = new FileInfo(item); - if (templateManager.IsSupported(assemblyInfoFile.Extension)) + if (this.templateManager.IsSupported(assemblyInfoFile.Extension)) { yield return assemblyInfoFile; } @@ -193,7 +193,7 @@ private IEnumerable GetAssemblyInfoFiles(AssemblyInfoContext context) private bool EnsureVersionAssemblyInfoFile(string fullPath, bool ensureAssemblyInfo) { fullPath = fullPath ?? throw new ArgumentNullException(nameof(fullPath)); - if (fileSystem.Exists(fullPath)) + if (this.fileSystem.Exists(fullPath)) { return true; } @@ -203,22 +203,22 @@ private bool EnsureVersionAssemblyInfoFile(string fullPath, bool ensureAssemblyI return false; } - var assemblyInfoSource = templateManager.GetTemplateFor(Path.GetExtension(fullPath)); + var assemblyInfoSource = this.templateManager.GetTemplateFor(Path.GetExtension(fullPath)); if (!assemblyInfoSource.IsNullOrWhiteSpace()) { var fileInfo = new FileInfo(fullPath); - if (fileInfo.Directory != null && !fileSystem.DirectoryExists(fileInfo.Directory.FullName)) + if (fileInfo.Directory != null && !this.fileSystem.DirectoryExists(fileInfo.Directory.FullName)) { - fileSystem.CreateDirectory(fileInfo.Directory.FullName); + this.fileSystem.CreateDirectory(fileInfo.Directory.FullName); } - fileSystem.WriteAllText(fullPath, assemblyInfoSource); + this.fileSystem.WriteAllText(fullPath, assemblyInfoSource); return true; } - log.Warning($"No version assembly info template available to create source file '{fullPath}'"); + this.log.Warning($"No version assembly info template available to create source file '{fullPath}'"); return false; } } diff --git a/src/GitVersion.Core/VersionConverters/AssemblyInfo/ProjectFileUpdater.cs b/src/GitVersion.Core/VersionConverters/AssemblyInfo/ProjectFileUpdater.cs index d87d03ea77..015607766d 100644 --- a/src/GitVersion.Core/VersionConverters/AssemblyInfo/ProjectFileUpdater.cs +++ b/src/GitVersion.Core/VersionConverters/AssemblyInfo/ProjectFileUpdater.cs @@ -48,31 +48,31 @@ public void Execute(VersionVariables variables, AssemblyInfoContext context) { var localProjectFile = projectFile.FullName; - var originalFileContents = fileSystem.ReadAllText(localProjectFile); + var originalFileContents = this.fileSystem.ReadAllText(localProjectFile); var fileXml = XElement.Parse(originalFileContents); if (!CanUpdateProjectFile(fileXml)) { - log.Warning($"Unable to update file: {localProjectFile}"); + this.log.Warning($"Unable to update file: {localProjectFile}"); continue; } - log.Debug($"Update file: {localProjectFile}"); + this.log.Debug($"Update file: {localProjectFile}"); var backupProjectFile = localProjectFile + ".bak"; - fileSystem.Copy(localProjectFile, backupProjectFile, true); + this.fileSystem.Copy(localProjectFile, backupProjectFile, true); - restoreBackupTasks.Add(() => + this.restoreBackupTasks.Add(() => { - if (fileSystem.Exists(localProjectFile)) + if (this.fileSystem.Exists(localProjectFile)) { - fileSystem.Delete(localProjectFile); + this.fileSystem.Delete(localProjectFile); } - fileSystem.Move(backupProjectFile, localProjectFile); + this.fileSystem.Move(backupProjectFile, localProjectFile); }); - cleanupBackupTasks.Add(() => fileSystem.Delete(backupProjectFile)); + this.cleanupBackupTasks.Add(() => this.fileSystem.Delete(backupProjectFile)); if (!assemblyVersion.IsNullOrWhiteSpace()) { @@ -97,7 +97,7 @@ public void Execute(VersionVariables variables, AssemblyInfoContext context) var outputXmlString = fileXml.ToString(); if (originalFileContents != outputXmlString) { - fileSystem.WriteAllText(localProjectFile, outputXmlString); + this.fileSystem.WriteAllText(localProjectFile, outputXmlString); } } @@ -108,7 +108,7 @@ internal bool CanUpdateProjectFile(XElement xmlRoot) { if (xmlRoot.Name != "Project") { - log.Warning($"Invalid project file specified, root element must be ."); + this.log.Warning($"Invalid project file specified, root element must be ."); return false; } @@ -117,21 +117,21 @@ internal bool CanUpdateProjectFile(XElement xmlRoot) if (sdkAttribute == null || !supportedSdks.Contains(sdkAttribute.Value)) { var supportedSdkString = string.Join("|", supportedSdks); - log.Warning($"Specified project file Sdk ({sdkAttribute?.Value}) is not supported, please ensure the project sdk is of the following: {supportedSdkString}."); + this.log.Warning($"Specified project file Sdk ({sdkAttribute?.Value}) is not supported, please ensure the project sdk is of the following: {supportedSdkString}."); return false; } var propertyGroups = xmlRoot.Descendants("PropertyGroup").ToList(); if (!propertyGroups.Any()) { - log.Warning("Unable to locate any elements in specified project file. Are you sure it is in a correct format?"); + this.log.Warning("Unable to locate any elements in specified project file. Are you sure it is in a correct format?"); return false; } var lastGenerateAssemblyInfoElement = propertyGroups.SelectMany(s => s.Elements("GenerateAssemblyInfo")).LastOrDefault(); if (lastGenerateAssemblyInfoElement != null && (bool)lastGenerateAssemblyInfoElement == false) { - log.Warning($"Project file specifies false: versions set in this project file will not affect the output artifacts."); + this.log.Warning($"Project file specifies false: versions set in this project file will not affect the output artifacts."); return false; } @@ -158,24 +158,24 @@ internal void UpdateProjectVersionElement(XElement xmlRoot, string versionElemen public void Dispose() { - foreach (var restoreBackup in restoreBackupTasks) + foreach (var restoreBackup in this.restoreBackupTasks) { restoreBackup(); } - cleanupBackupTasks.Clear(); - restoreBackupTasks.Clear(); + this.cleanupBackupTasks.Clear(); + this.restoreBackupTasks.Clear(); } private void CommitChanges() { - foreach (var cleanupBackupTask in cleanupBackupTasks) + foreach (var cleanupBackupTask in this.cleanupBackupTasks) { cleanupBackupTask(); } - cleanupBackupTasks.Clear(); - restoreBackupTasks.Clear(); + this.cleanupBackupTasks.Clear(); + this.restoreBackupTasks.Clear(); } private IEnumerable GetProjectFiles(AssemblyInfoContext context) @@ -189,19 +189,19 @@ private IEnumerable GetProjectFiles(AssemblyInfoContext context) { var fullPath = Path.Combine(workingDirectory, item); - if (fileSystem.Exists(fullPath)) + if (this.fileSystem.Exists(fullPath)) { yield return new FileInfo(fullPath); } else { - log.Warning($"Specified file {fullPath} was not found and will not be updated."); + this.log.Warning($"Specified file {fullPath} was not found and will not be updated."); } } } else { - foreach (var item in fileSystem.DirectoryEnumerateFiles(workingDirectory, "*", SearchOption.AllDirectories).Where(IsSupportedProjectFile)) + foreach (var item in this.fileSystem.DirectoryEnumerateFiles(workingDirectory, "*", SearchOption.AllDirectories).Where(IsSupportedProjectFile)) { var assemblyInfoFile = new FileInfo(item); diff --git a/src/GitVersion.Core/VersionConverters/GitVersionInfo/GitVersionInfoGenerator.cs b/src/GitVersion.Core/VersionConverters/GitVersionInfo/GitVersionInfoGenerator.cs index 46ab3484fc..e4acfe84c5 100644 --- a/src/GitVersion.Core/VersionConverters/GitVersionInfo/GitVersionInfoGenerator.cs +++ b/src/GitVersion.Core/VersionConverters/GitVersionInfo/GitVersionInfoGenerator.cs @@ -17,7 +17,7 @@ public class GitVersionInfoGenerator : IGitVersionInfoGenerator public GitVersionInfoGenerator(IFileSystem fileSystem) { this.fileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem)); - templateManager = new TemplateManager(TemplateType.GitVersionInfo); + this.templateManager = new TemplateManager(TemplateType.GitVersionInfo); } public void Execute(VersionVariables variables, GitVersionInfoContext context) @@ -30,12 +30,12 @@ public void Execute(VersionVariables variables, GitVersionInfoContext context) if (File.Exists(filePath)) { - originalFileContents = fileSystem.ReadAllText(filePath); + originalFileContents = this.fileSystem.ReadAllText(filePath); } var fileExtension = Path.GetExtension(filePath); - var template = templateManager.GetTemplateFor(fileExtension); - var addFormat = templateManager.GetAddFormatFor(fileExtension); + var template = this.templateManager.GetTemplateFor(fileExtension); + var addFormat = this.templateManager.GetAddFormatFor(fileExtension); var indentation = GetIndentation(fileExtension); var members = string.Join(System.Environment.NewLine, variables.Select(v => string.Format(indentation + addFormat, v.Key, v.Value))); @@ -44,7 +44,7 @@ public void Execute(VersionVariables variables, GitVersionInfoContext context) if (fileContents != originalFileContents) { - fileSystem.WriteAllText(filePath, fileContents); + this.fileSystem.WriteAllText(filePath, fileContents); } } diff --git a/src/GitVersion.Core/VersionConverters/OutputGenerator/OutputGenerator.cs b/src/GitVersion.Core/VersionConverters/OutputGenerator/OutputGenerator.cs index f1ac549144..9f42a5e0ca 100644 --- a/src/GitVersion.Core/VersionConverters/OutputGenerator/OutputGenerator.cs +++ b/src/GitVersion.Core/VersionConverters/OutputGenerator/OutputGenerator.cs @@ -30,22 +30,22 @@ public OutputGenerator(ICurrentBuildAgent buildAgent, IConsole console, IFileSys public void Execute(VersionVariables variables, OutputContext context) { - var gitVersionOptions = options.Value; + var gitVersionOptions = this.options.Value; if (gitVersionOptions.Output.Contains(OutputType.BuildServer)) { - buildAgent?.WriteIntegration(console.WriteLine, variables, context.UpdateBuildNumber ?? true); + this.buildAgent?.WriteIntegration(this.console.WriteLine, variables, context.UpdateBuildNumber ?? true); } if (gitVersionOptions.Output.Contains(OutputType.File)) { var retryOperation = new RetryAction(); - retryOperation.Execute(() => fileSystem.WriteAllText(context.OutputFile, variables.ToString())); + retryOperation.Execute(() => this.fileSystem.WriteAllText(context.OutputFile, variables.ToString())); } if (gitVersionOptions.Output.Contains(OutputType.Json)) { switch (gitVersionOptions.ShowVariable) { case null: - console.WriteLine(variables.ToString()); + this.console.WriteLine(variables.ToString()); break; default: @@ -54,7 +54,7 @@ public void Execute(VersionVariables variables, OutputContext context) throw new WarningException($"'{gitVersionOptions.ShowVariable}' variable does not exist"); } - console.WriteLine(part); + this.console.WriteLine(part); break; } } diff --git a/src/GitVersion.Core/VersionConverters/TemplateManager.cs b/src/GitVersion.Core/VersionConverters/TemplateManager.cs index c7c70f3c50..20dbb59314 100644 --- a/src/GitVersion.Core/VersionConverters/TemplateManager.cs +++ b/src/GitVersion.Core/VersionConverters/TemplateManager.cs @@ -19,8 +19,8 @@ internal class TemplateManager public TemplateManager(TemplateType templateType) { - templates = GetEmbeddedTemplates(templateType, "Templates").ToDictionary(Path.GetExtension, v => v, StringComparer.OrdinalIgnoreCase); - addFormats = GetEmbeddedTemplates(templateType, "AddFormats").ToDictionary(Path.GetExtension, v => v, StringComparer.OrdinalIgnoreCase); + this.templates = GetEmbeddedTemplates(templateType, "Templates").ToDictionary(Path.GetExtension, v => v, StringComparer.OrdinalIgnoreCase); + this.addFormats = GetEmbeddedTemplates(templateType, "AddFormats").ToDictionary(Path.GetExtension, v => v, StringComparer.OrdinalIgnoreCase); } public string? GetTemplateFor(string fileExtension) @@ -32,7 +32,7 @@ public TemplateManager(TemplateType templateType) string? result = null; - if (templates.TryGetValue(fileExtension, out var template) && template != null) + if (this.templates.TryGetValue(fileExtension, out var template) && template != null) { result = template.ReadAsStringFromEmbeddedResource(); } @@ -49,7 +49,7 @@ public TemplateManager(TemplateType templateType) string? result = null; - if (addFormats.TryGetValue(fileExtension, out var addFormat) && addFormat != null) + if (this.addFormats.TryGetValue(fileExtension, out var addFormat) && addFormat != null) { result = addFormat.ReadAsStringFromEmbeddedResource().TrimEnd('\r', '\n'); } @@ -64,7 +64,7 @@ public bool IsSupported(string fileExtension) throw new ArgumentNullException(nameof(fileExtension)); } - return templates.ContainsKey(fileExtension); + return this.templates.ContainsKey(fileExtension); } private static IEnumerable GetEmbeddedTemplates(TemplateType templateType, string templateCategory) diff --git a/src/GitVersion.Core/VersionConverters/WixUpdater/WixVersionFileUpdater.cs b/src/GitVersion.Core/VersionConverters/WixUpdater/WixVersionFileUpdater.cs index 4b97e76167..c1ae9dea73 100644 --- a/src/GitVersion.Core/VersionConverters/WixUpdater/WixVersionFileUpdater.cs +++ b/src/GitVersion.Core/VersionConverters/WixUpdater/WixVersionFileUpdater.cs @@ -25,8 +25,8 @@ public WixVersionFileUpdater(IFileSystem fileSystem, ILog log) public void Execute(VersionVariables variables, WixVersionContext context) { - wixVersionFile = Path.Combine(context.WorkingDirectory, WixVersionFileName); - log.Info("Updating GitVersion_WixVersion.wxi"); + this.wixVersionFile = Path.Combine(context.WorkingDirectory, WixVersionFileName); + this.log.Info("Updating GitVersion_WixVersion.wxi"); var doc = new XmlDocument(); doc.LoadXml(GetWixFormatFromVersionVariables(variables)); @@ -35,8 +35,8 @@ public void Execute(VersionVariables variables, WixVersionContext context) var root = doc.DocumentElement; doc.InsertBefore(xmlDecl, root); - fileSystem.Delete(wixVersionFile); - using var fs = fileSystem.OpenWrite(wixVersionFile); + this.fileSystem.Delete(this.wixVersionFile); + using var fs = this.fileSystem.OpenWrite(this.wixVersionFile); doc.Save(fs); } @@ -56,7 +56,7 @@ private static string GetWixFormatFromVersionVariables(VersionVariables variable public void Dispose() { - log.Info($"Done writing {wixVersionFile}"); + this.log.Info($"Done writing {this.wixVersionFile}"); } } } diff --git a/src/GitVersion.LibGit2Sharp/Git/Branch.cs b/src/GitVersion.LibGit2Sharp/Git/Branch.cs index 2d7971ee54..cfd747f48a 100644 --- a/src/GitVersion.LibGit2Sharp/Git/Branch.cs +++ b/src/GitVersion.LibGit2Sharp/Git/Branch.cs @@ -12,13 +12,13 @@ internal sealed class Branch : IBranch internal Branch(LibGit2Sharp.Branch branch) { - innerBranch = branch; + this.innerBranch = branch; Name = new ReferenceName(branch.CanonicalName); - var commit = innerBranch.Tip; + var commit = this.innerBranch.Tip; Tip = commit is null ? null : new Commit(commit); - var commits = innerBranch.Commits; + var commits = this.innerBranch.Commits; Commits = commits is null ? null : new CommitCollection(commits); } public ReferenceName Name { get; } @@ -34,7 +34,7 @@ internal Branch(LibGit2Sharp.Branch branch) public bool IsDetachedHead => Name.Canonical.Equals("(no branch)", StringComparison.OrdinalIgnoreCase); - public bool IsRemote => innerBranch.IsRemote; - public bool IsTracking => innerBranch.IsTracking; + public bool IsRemote => this.innerBranch.IsRemote; + public bool IsTracking => this.innerBranch.IsTracking; } } diff --git a/src/GitVersion.LibGit2Sharp/Git/BranchCollection.cs b/src/GitVersion.LibGit2Sharp/Git/BranchCollection.cs index 515f784e08..8ab5b7047c 100644 --- a/src/GitVersion.LibGit2Sharp/Git/BranchCollection.cs +++ b/src/GitVersion.LibGit2Sharp/Git/BranchCollection.cs @@ -7,18 +7,18 @@ namespace GitVersion internal sealed class BranchCollection : IBranchCollection { private readonly LibGit2Sharp.BranchCollection innerCollection; - internal BranchCollection(LibGit2Sharp.BranchCollection collection) => innerCollection = collection; + internal BranchCollection(LibGit2Sharp.BranchCollection collection) => this.innerCollection = collection; public IEnumerator GetEnumerator() { - return innerCollection.Select(branch => new Branch(branch)).GetEnumerator(); + return this.innerCollection.Select(branch => new Branch(branch)).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public IBranch? this[string name] { get { - var branch = innerCollection[name]; + var branch = this.innerCollection[name]; return branch is null ? null : new Branch(branch); } } @@ -26,6 +26,6 @@ public IBranch? this[string name] public IEnumerable ExcludeBranches(IEnumerable branchesToExclude) => this.Where(b => branchesToExclude.All(bte => !b.Equals(bte))); public void UpdateTrackedBranch(IBranch branch, string remoteTrackingReferenceName) => - innerCollection.Update((Branch)branch, b => b.TrackedBranch = remoteTrackingReferenceName); + this.innerCollection.Update((Branch)branch, b => b.TrackedBranch = remoteTrackingReferenceName); } } diff --git a/src/GitVersion.LibGit2Sharp/Git/Commit.cs b/src/GitVersion.LibGit2Sharp/Git/Commit.cs index 2c7a82a803..f499d1f906 100644 --- a/src/GitVersion.LibGit2Sharp/Git/Commit.cs +++ b/src/GitVersion.LibGit2Sharp/Git/Commit.cs @@ -25,13 +25,13 @@ internal Commit(LibGit2Sharp.Commit innerCommit) : base(innerCommit) public override int GetHashCode() => equalityHelper.GetHashCode(this); public override string ToString() { - return $"{Id.ToString(7)} {innerCommit.MessageShort}"; + return $"{Id.ToString(7)} {this.innerCommit.MessageShort}"; } public static implicit operator LibGit2Sharp.Commit(Commit d) => d.innerCommit; public IEnumerable Parents { get; } public DateTimeOffset When { get; } - public string Message => innerCommit.Message; + public string Message => this.innerCommit.Message; } } diff --git a/src/GitVersion.LibGit2Sharp/Git/CommitCollection.cs b/src/GitVersion.LibGit2Sharp/Git/CommitCollection.cs index 989fe18c8b..3359b086b9 100644 --- a/src/GitVersion.LibGit2Sharp/Git/CommitCollection.cs +++ b/src/GitVersion.LibGit2Sharp/Git/CommitCollection.cs @@ -9,11 +9,11 @@ namespace GitVersion internal sealed class CommitCollection : ICommitCollection { private readonly ICommitLog innerCollection; - internal CommitCollection(ICommitLog collection) => innerCollection = collection; + internal CommitCollection(ICommitLog collection) => this.innerCollection = collection; public IEnumerator GetEnumerator() { - return innerCollection.Select(commit => new Commit(commit)).GetEnumerator(); + return this.innerCollection.Select(commit => new Commit(commit)).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); @@ -40,7 +40,7 @@ public IEnumerable QueryBy(CommitFilter commitFilter) FirstParentOnly = commitFilter.FirstParentOnly, SortBy = (LibGit2Sharp.CommitSortStrategies)commitFilter.SortBy, }; - var commitLog = ((IQueryableCommitLog)innerCollection).QueryBy(filter); + var commitLog = ((IQueryableCommitLog)this.innerCollection).QueryBy(filter); return new CommitCollection(commitLog); } } diff --git a/src/GitVersion.LibGit2Sharp/Git/GitRepository.cs b/src/GitVersion.LibGit2Sharp/Git/GitRepository.cs index f0653481d0..1e46cc948f 100644 --- a/src/GitVersion.LibGit2Sharp/Git/GitRepository.cs +++ b/src/GitVersion.LibGit2Sharp/Git/GitRepository.cs @@ -13,7 +13,7 @@ internal sealed class GitRepository : IMutatingGitRepository { private readonly ILog log; private readonly Lazy repositoryLazy; - private IRepository repositoryInstance => repositoryLazy.Value; + private IRepository repositoryInstance => this.repositoryLazy.Value; public GitRepository(ILog log, IGitRepositoryInfo repositoryInfo) : this(log, () => repositoryInfo.GitRootPath) @@ -27,19 +27,19 @@ internal GitRepository(string gitRootDirectory) internal GitRepository(IRepository repository) { - log = new NullLog(); - repositoryLazy = new Lazy(() => repository); + this.log = new NullLog(); + this.repositoryLazy = new Lazy(() => repository); } private GitRepository(ILog log, Func getGitRootDirectory) { this.log = log ?? throw new ArgumentNullException(nameof(log)); - repositoryLazy = new Lazy(() => new Repository(getGitRootDirectory())); + this.repositoryLazy = new Lazy(() => new Repository(getGitRootDirectory())); } public void Dispose() { - if (repositoryLazy.IsValueCreated) repositoryInstance.Dispose(); + if (this.repositoryLazy.IsValueCreated) repositoryInstance.Dispose(); } public string Path => repositoryInstance.Info.Path; @@ -106,14 +106,14 @@ public void CreateBranchForPullRequestBranch(AuthenticationInfo auth) var network = repositoryInstance.Network; var remote = network.Remotes.Single(); - log.Info("Fetching remote refs to see if there is a pull request ref"); + this.log.Info("Fetching remote refs to see if there is a pull request ref"); var credentialsProvider = GetCredentialsProvider(auth); var remoteTips = (credentialsProvider != null ? network.ListReferences(remote, credentialsProvider) : network.ListReferences(remote)) .Select(r => r.ResolveToDirectReference()).ToList(); - log.Info($"Remote Refs:{System.Environment.NewLine}" + string.Join(System.Environment.NewLine, remoteTips.Select(r => r.CanonicalName))); + this.log.Info($"Remote Refs:{System.Environment.NewLine}" + string.Join(System.Environment.NewLine, remoteTips.Select(r => r.CanonicalName))); // FIX ME: What to do when Tip is null? var headTipSha = Head.Tip!.Sha; @@ -136,21 +136,21 @@ public void CreateBranchForPullRequestBranch(AuthenticationInfo auth) var reference = refs.First(); var canonicalName = reference.CanonicalName; var referenceName = ReferenceName.Parse(reference.CanonicalName); - log.Info($"Found remote tip '{canonicalName}' pointing at the commit '{headTipSha}'."); + this.log.Info($"Found remote tip '{canonicalName}' pointing at the commit '{headTipSha}'."); if (referenceName.IsTag) { - log.Info($"Checking out tag '{canonicalName}'"); + this.log.Info($"Checking out tag '{canonicalName}'"); Checkout(reference.Target.Sha); } else if (referenceName.IsPullRequest) { var fakeBranchName = canonicalName.Replace("refs/pull/", "refs/heads/pull/").Replace("refs/pull-requests/", "refs/heads/pull-requests/"); - log.Info($"Creating fake local branch '{fakeBranchName}'."); + this.log.Info($"Creating fake local branch '{fakeBranchName}'."); Refs.Add(fakeBranchName, headTipSha); - log.Info($"Checking local branch '{fakeBranchName}' out."); + this.log.Info($"Checking local branch '{fakeBranchName}' out."); Checkout(fakeBranchName); } else @@ -165,7 +165,7 @@ public void Clone(string? sourceUrl, string? workdirPath, AuthenticationInfo aut try { var path = Repository.Clone(sourceUrl, workdirPath, GetCloneOptions(auth)); - log.Info($"Returned path after repository clone: {path}"); + this.log.Info($"Returned path after repository clone: {path}"); } catch (LibGit2Sharp.LockedFileException ex) { diff --git a/src/GitVersion.LibGit2Sharp/Git/GitRepositoryInfo.cs b/src/GitVersion.LibGit2Sharp/Git/GitRepositoryInfo.cs index 2c5aece6db..078e353a79 100644 --- a/src/GitVersion.LibGit2Sharp/Git/GitRepositoryInfo.cs +++ b/src/GitVersion.LibGit2Sharp/Git/GitRepositoryInfo.cs @@ -9,7 +9,7 @@ namespace GitVersion internal class GitRepositoryInfo : IGitRepositoryInfo { private readonly IOptions options; - private GitVersionOptions gitVersionOptions => options.Value; + private GitVersionOptions gitVersionOptions => this.options.Value; private readonly Lazy dynamicGitRepositoryPath; private readonly Lazy dotGitDirectory; @@ -20,16 +20,16 @@ public GitRepositoryInfo(IOptions options) { this.options = options ?? throw new ArgumentNullException(nameof(options)); - dynamicGitRepositoryPath = new Lazy(GetDynamicGitRepositoryPath); - dotGitDirectory = new Lazy(GetDotGitDirectory); - gitRootPath = new Lazy(GetGitRootPath); - projectRootDirectory = new Lazy(GetProjectRootDirectory); + this.dynamicGitRepositoryPath = new Lazy(GetDynamicGitRepositoryPath); + this.dotGitDirectory = new Lazy(GetDotGitDirectory); + this.gitRootPath = new Lazy(GetGitRootPath); + this.projectRootDirectory = new Lazy(GetProjectRootDirectory); } - public string? DynamicGitRepositoryPath => dynamicGitRepositoryPath.Value; - public string? DotGitDirectory => dotGitDirectory.Value; - public string? GitRootPath => gitRootPath.Value; - public string? ProjectRootDirectory => projectRootDirectory.Value; + public string? DynamicGitRepositoryPath => this.dynamicGitRepositoryPath.Value; + public string? DotGitDirectory => this.dotGitDirectory.Value; + public string? GitRootPath => this.gitRootPath.Value; + public string? ProjectRootDirectory => this.projectRootDirectory.Value; private string? GetDynamicGitRepositoryPath() { diff --git a/src/GitVersion.LibGit2Sharp/Git/ObjectId.cs b/src/GitVersion.LibGit2Sharp/Git/ObjectId.cs index 3bc9286547..e4450c6efd 100644 --- a/src/GitVersion.LibGit2Sharp/Git/ObjectId.cs +++ b/src/GitVersion.LibGit2Sharp/Git/ObjectId.cs @@ -8,7 +8,7 @@ internal sealed class ObjectId : IObjectId private static readonly LambdaKeyComparer comparerHelper = new(x => x.Sha); private readonly LibGit2Sharp.ObjectId innerObjectId; - internal ObjectId(LibGit2Sharp.ObjectId objectId) => innerObjectId = objectId; + internal ObjectId(LibGit2Sharp.ObjectId objectId) => this.innerObjectId = objectId; public ObjectId(string sha) : this(new LibGit2Sharp.ObjectId(sha)) { @@ -20,8 +20,8 @@ public ObjectId(string sha) : this(new LibGit2Sharp.ObjectId(sha)) public override int GetHashCode() => equalityHelper.GetHashCode(this); public override string ToString() => ToString(7); public static implicit operator LibGit2Sharp.ObjectId(ObjectId d) => d.innerObjectId; - public string Sha => innerObjectId.Sha; + public string Sha => this.innerObjectId.Sha; - public string ToString(int prefixLength) => innerObjectId.ToString(prefixLength); + public string ToString(int prefixLength) => this.innerObjectId.ToString(prefixLength); } } diff --git a/src/GitVersion.LibGit2Sharp/Git/RefSpec.cs b/src/GitVersion.LibGit2Sharp/Git/RefSpec.cs index 726e125214..0814f940c9 100644 --- a/src/GitVersion.LibGit2Sharp/Git/RefSpec.cs +++ b/src/GitVersion.LibGit2Sharp/Git/RefSpec.cs @@ -9,15 +9,15 @@ public class RefSpec : IRefSpec private readonly LibGit2Sharp.RefSpec innerRefSpec; - internal RefSpec(LibGit2Sharp.RefSpec refSpec) => innerRefSpec = refSpec; + internal RefSpec(LibGit2Sharp.RefSpec refSpec) => this.innerRefSpec = refSpec; public int CompareTo(IRefSpec other) => comparerHelper.Compare(this, other); public bool Equals(IRefSpec other) => equalityHelper.Equals(this, other); public override bool Equals(object obj) => Equals((obj as IRefSpec)!); public override int GetHashCode() => equalityHelper.GetHashCode(this); public override string ToString() => Specification; - public string Specification => innerRefSpec.Specification; - public RefSpecDirection Direction => (RefSpecDirection)innerRefSpec.Direction; - public string Source => innerRefSpec.Source; - public string Destination => innerRefSpec.Destination; + public string Specification => this.innerRefSpec.Specification; + public RefSpecDirection Direction => (RefSpecDirection)this.innerRefSpec.Direction; + public string Source => this.innerRefSpec.Source; + public string Destination => this.innerRefSpec.Destination; } } diff --git a/src/GitVersion.LibGit2Sharp/Git/RefSpecCollection.cs b/src/GitVersion.LibGit2Sharp/Git/RefSpecCollection.cs index 60a1d04dd0..68329ad37a 100644 --- a/src/GitVersion.LibGit2Sharp/Git/RefSpecCollection.cs +++ b/src/GitVersion.LibGit2Sharp/Git/RefSpecCollection.cs @@ -7,10 +7,10 @@ namespace GitVersion internal sealed class RefSpecCollection : IRefSpecCollection { private readonly LibGit2Sharp.RefSpecCollection innerCollection; - internal RefSpecCollection(LibGit2Sharp.RefSpecCollection collection) => innerCollection = collection; + internal RefSpecCollection(LibGit2Sharp.RefSpecCollection collection) => this.innerCollection = collection; public IEnumerator GetEnumerator() { - return innerCollection.Select(tag => new RefSpec(tag)).GetEnumerator(); + return this.innerCollection.Select(tag => new RefSpec(tag)).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { diff --git a/src/GitVersion.LibGit2Sharp/Git/Reference.cs b/src/GitVersion.LibGit2Sharp/Git/Reference.cs index 589838e225..4eeeec7fa3 100644 --- a/src/GitVersion.LibGit2Sharp/Git/Reference.cs +++ b/src/GitVersion.LibGit2Sharp/Git/Reference.cs @@ -12,7 +12,7 @@ internal sealed class Reference : IReference internal Reference(LibGit2Sharp.Reference reference) { - innerReference = reference; + this.innerReference = reference; Name = new ReferenceName(reference.CanonicalName); if (reference is DirectReference) @@ -25,7 +25,7 @@ internal Reference(LibGit2Sharp.Reference reference) public bool Equals(IReference other) => equalityHelper.Equals(this, other); public override int GetHashCode() => equalityHelper.GetHashCode(this); public override string ToString() => Name.ToString(); - public string TargetIdentifier => innerReference.TargetIdentifier; + public string TargetIdentifier => this.innerReference.TargetIdentifier; public static implicit operator LibGit2Sharp.Reference(Reference d) => d.innerReference; } } diff --git a/src/GitVersion.LibGit2Sharp/Git/ReferenceCollection.cs b/src/GitVersion.LibGit2Sharp/Git/ReferenceCollection.cs index ba03760e91..6b7704d080 100644 --- a/src/GitVersion.LibGit2Sharp/Git/ReferenceCollection.cs +++ b/src/GitVersion.LibGit2Sharp/Git/ReferenceCollection.cs @@ -7,23 +7,23 @@ namespace GitVersion internal sealed class ReferenceCollection : IReferenceCollection { private readonly LibGit2Sharp.ReferenceCollection innerCollection; - internal ReferenceCollection(LibGit2Sharp.ReferenceCollection collection) => innerCollection = collection; + internal ReferenceCollection(LibGit2Sharp.ReferenceCollection collection) => this.innerCollection = collection; public IEnumerator GetEnumerator() { - return innerCollection.Select(reference => new Reference(reference)).GetEnumerator(); + return this.innerCollection.Select(reference => new Reference(reference)).GetEnumerator(); } public void Add(string name, string canonicalRefNameOrObjectish, bool allowOverwrite = false) { - innerCollection.Add(name, canonicalRefNameOrObjectish, allowOverwrite); + this.innerCollection.Add(name, canonicalRefNameOrObjectish, allowOverwrite); } public void UpdateTarget(IReference directRef, IObjectId targetId) { RepositoryExtensions.RunSafe(() => { - innerCollection.UpdateTarget((Reference)directRef, (ObjectId)targetId); + this.innerCollection.UpdateTarget((Reference)directRef, (ObjectId)targetId); }); } @@ -33,7 +33,7 @@ public IReference? this[string name] { get { - var reference = innerCollection[name]; + var reference = this.innerCollection[name]; return reference is null ? null : new Reference(reference); } } @@ -42,7 +42,7 @@ public IReference? this[string name] public IEnumerable FromGlob(string pattern) { - return innerCollection.FromGlob(pattern).Select(reference => new Reference(reference)); + return this.innerCollection.FromGlob(pattern).Select(reference => new Reference(reference)); } } } diff --git a/src/GitVersion.LibGit2Sharp/Git/Remote.cs b/src/GitVersion.LibGit2Sharp/Git/Remote.cs index caec49b348..04721f770c 100644 --- a/src/GitVersion.LibGit2Sharp/Git/Remote.cs +++ b/src/GitVersion.LibGit2Sharp/Git/Remote.cs @@ -11,21 +11,21 @@ internal sealed class Remote : IRemote private readonly LibGit2Sharp.Remote innerRemote; - internal Remote(LibGit2Sharp.Remote remote) => innerRemote = remote; + internal Remote(LibGit2Sharp.Remote remote) => this.innerRemote = remote; public int CompareTo(IRemote other) => comparerHelper.Compare(this, other); public bool Equals(IRemote other) => equalityHelper.Equals(this, other); public override bool Equals(object obj) => Equals((obj as IRemote)!); public override int GetHashCode() => equalityHelper.GetHashCode(this); public override string ToString() => Name; - public string Name => innerRemote.Name; - public string Url => innerRemote.Url; + public string Name => this.innerRemote.Name; + public string Url => this.innerRemote.Url; public IEnumerable RefSpecs { get { - var refSpecs = innerRemote.RefSpecs; + var refSpecs = this.innerRemote.RefSpecs; return refSpecs is null ? Enumerable.Empty() : new RefSpecCollection((LibGit2Sharp.RefSpecCollection)refSpecs); diff --git a/src/GitVersion.LibGit2Sharp/Git/RemoteCollection.cs b/src/GitVersion.LibGit2Sharp/Git/RemoteCollection.cs index 267c7cb248..4d10cb9851 100644 --- a/src/GitVersion.LibGit2Sharp/Git/RemoteCollection.cs +++ b/src/GitVersion.LibGit2Sharp/Git/RemoteCollection.cs @@ -7,11 +7,11 @@ namespace GitVersion internal sealed class RemoteCollection : IRemoteCollection { private readonly LibGit2Sharp.RemoteCollection innerCollection; - internal RemoteCollection(LibGit2Sharp.RemoteCollection collection) => innerCollection = collection; + internal RemoteCollection(LibGit2Sharp.RemoteCollection collection) => this.innerCollection = collection; public IEnumerator GetEnumerator() { - return innerCollection.Select(reference => new Remote(reference)).GetEnumerator(); + return this.innerCollection.Select(reference => new Remote(reference)).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); @@ -19,18 +19,18 @@ public IRemote? this[string name] { get { - var remote = innerCollection[name]; + var remote = this.innerCollection[name]; return remote is null ? null : new Remote(remote); } } public void Remove(string remoteName) { - innerCollection.Remove(remoteName); + this.innerCollection.Remove(remoteName); } public void Update(string remoteName, string refSpec) { - innerCollection.Update(remoteName, r => r.FetchRefSpecs.Add(refSpec)); + this.innerCollection.Update(remoteName, r => r.FetchRefSpecs.Add(refSpec)); } } } diff --git a/src/GitVersion.LibGit2Sharp/Git/Tag.cs b/src/GitVersion.LibGit2Sharp/Git/Tag.cs index f385fac5e7..561037285c 100644 --- a/src/GitVersion.LibGit2Sharp/Git/Tag.cs +++ b/src/GitVersion.LibGit2Sharp/Git/Tag.cs @@ -11,8 +11,8 @@ internal sealed class Tag : ITag private readonly LibGit2Sharp.Tag innerTag; internal Tag(LibGit2Sharp.Tag tag) { - innerTag = tag; - Name = new ReferenceName(innerTag.CanonicalName); + this.innerTag = tag; + Name = new ReferenceName(this.innerTag.CanonicalName); } public ReferenceName Name { get; } @@ -21,11 +21,11 @@ internal Tag(LibGit2Sharp.Tag tag) public override bool Equals(object obj) => Equals((obj as ITag)!); public override int GetHashCode() => equalityHelper.GetHashCode(this); public override string ToString() => Name.ToString(); - public string TargetSha => innerTag.Target.Sha; + public string TargetSha => this.innerTag.Target.Sha; public ICommit? PeeledTargetCommit() { - var target = innerTag.Target; + var target = this.innerTag.Target; while (target is TagAnnotation annotation) { diff --git a/src/GitVersion.LibGit2Sharp/Git/TagCollection.cs b/src/GitVersion.LibGit2Sharp/Git/TagCollection.cs index 172cc50023..ef59662156 100644 --- a/src/GitVersion.LibGit2Sharp/Git/TagCollection.cs +++ b/src/GitVersion.LibGit2Sharp/Git/TagCollection.cs @@ -7,11 +7,11 @@ namespace GitVersion internal sealed class TagCollection : ITagCollection { private readonly LibGit2Sharp.TagCollection innerCollection; - internal TagCollection(LibGit2Sharp.TagCollection collection) => innerCollection = collection; + internal TagCollection(LibGit2Sharp.TagCollection collection) => this.innerCollection = collection; public IEnumerator GetEnumerator() { - return innerCollection.Select(tag => new Tag(tag)).GetEnumerator(); + return this.innerCollection.Select(tag => new Tag(tag)).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); diff --git a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildExeFixture.cs b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildExeFixture.cs index feb178419d..6ab0b2985b 100644 --- a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildExeFixture.cs +++ b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildExeFixture.cs @@ -20,7 +20,7 @@ public class MsBuildExeFixture public void WithEnv(params KeyValuePair[] envs) { - environmentVariables = envs; + this.environmentVariables = envs; } public const string OutputTarget = "GitVersionOutput"; @@ -31,7 +31,7 @@ public void WithEnv(params KeyValuePair[] envs) public MsBuildExeFixture(RepositoryFixtureBase fixture, string workingDirectory = "") { this.fixture = fixture; - ProjectPath = Path.Combine(workingDirectory, "app.csproj"); + this.ProjectPath = Path.Combine(workingDirectory, "app.csproj"); var versionFile = Path.Combine(workingDirectory, "gitversion.json"); @@ -40,7 +40,7 @@ public MsBuildExeFixture(RepositoryFixtureBase fixture, string workingDirectory public MsBuildExeFixtureResult Execute() { - var analyzer = manager.GetProject(ProjectPath); + var analyzer = this.manager.GetProject(this.ProjectPath); var output = new StringWriter(); analyzer.AddBuildLogger(new ConsoleLogger(LoggerVerbosity.Normal, output.Write, null, null)); @@ -49,9 +49,9 @@ public MsBuildExeFixtureResult Execute() environmentOptions.TargetsToBuild.Clear(); environmentOptions.TargetsToBuild.Add(OutputTarget); - if (environmentVariables != null) + if (this.environmentVariables != null) { - foreach (var pair in environmentVariables) + foreach (var pair in this.environmentVariables) { analyzer.SetEnvironmentVariable(pair.Key, pair.Value); } @@ -59,7 +59,7 @@ public MsBuildExeFixtureResult Execute() var results = analyzer.Build(environmentOptions); - return new MsBuildExeFixtureResult(fixture) + return new MsBuildExeFixtureResult(this.fixture) { ProjectPath = ProjectPath, Output = output.ToString(), @@ -70,8 +70,8 @@ public MsBuildExeFixtureResult Execute() public void CreateTestProject(Action extendProject) { var project = RuntimeHelper.IsCoreClr() - ? ProjectCreator.Templates.SdkCsproj(ProjectPath) - : ProjectCreator.Templates.LegacyCsproj(ProjectPath, defaultTargets: null, targetFrameworkVersion: "v4.8", toolsVersion: "15.0"); + ? ProjectCreator.Templates.SdkCsproj(this.ProjectPath) + : ProjectCreator.Templates.LegacyCsproj(this.ProjectPath, defaultTargets: null, targetFrameworkVersion: "v4.8", toolsVersion: "15.0"); if (project == null) return; diff --git a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildExeFixtureResult.cs b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildExeFixtureResult.cs index 144174db49..49197c9d70 100644 --- a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildExeFixtureResult.cs +++ b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildExeFixtureResult.cs @@ -17,7 +17,7 @@ public MsBuildExeFixtureResult(RepositoryFixtureBase fixture) public string ProjectPath { get; set; } public void Dispose() { - fixture.Dispose(); + this.fixture.Dispose(); } } } diff --git a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixture.cs b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixture.cs index ef954cb518..d180c94397 100644 --- a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixture.cs +++ b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixture.cs @@ -21,7 +21,7 @@ public MsBuildTaskFixture(RepositoryFixtureBase fixture) public void WithEnv(params KeyValuePair[] envs) { - environmentVariables = envs; + this.environmentVariables = envs; } public MsBuildTaskFixtureResult Execute(T task) where T : GitVersionTaskBase @@ -33,13 +33,13 @@ public MsBuildTaskFixtureResult Execute(T task) where T : GitVersionTaskBa task.BuildEngine = buildEngine; var versionFile = Path.Combine(task.SolutionDirectory, "gitversion.json"); - fixture.WriteVersionVariables(versionFile); + this.fixture.WriteVersionVariables(versionFile); task.VersionFile = versionFile; var result = task.Execute(); - return new MsBuildTaskFixtureResult(fixture) + return new MsBuildTaskFixtureResult(this.fixture) { Success = result, Task = task, @@ -54,7 +54,7 @@ public MsBuildTaskFixtureResult Execute(T task) where T : GitVersionTaskBa private T UsingEnv(Func func) { ResetEnvironment(); - SetEnvironmentVariables(environmentVariables); + SetEnvironmentVariables(this.environmentVariables); try { diff --git a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixtureResult.cs b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixtureResult.cs index 9c019c9947..af865edff5 100644 --- a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixtureResult.cs +++ b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixtureResult.cs @@ -23,7 +23,7 @@ public MsBuildTaskFixtureResult(RepositoryFixtureBase fixture) public void Dispose() { - fixture.Dispose(); + this.fixture.Dispose(); } } } diff --git a/src/GitVersion.MsBuild.Tests/InvalidFileCheckerTests.cs b/src/GitVersion.MsBuild.Tests/InvalidFileCheckerTests.cs index 9ce1ba5a04..43c7b0c25c 100644 --- a/src/GitVersion.MsBuild.Tests/InvalidFileCheckerTests.cs +++ b/src/GitVersion.MsBuild.Tests/InvalidFileCheckerTests.cs @@ -16,24 +16,24 @@ public class InvalidFileCheckerTests : TestBase [SetUp] public void CreateTemporaryProject() { - projectDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); - projectFile = Path.Combine(projectDirectory, "Fake.csproj"); + this.projectDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + this.projectFile = Path.Combine(this.projectDirectory, "Fake.csproj"); - Directory.CreateDirectory(projectDirectory); + Directory.CreateDirectory(this.projectDirectory); - File.Create(projectFile).Close(); + File.Create(this.projectFile).Close(); } [TearDown] public void Cleanup() { - Directory.Delete(projectDirectory, true); + Directory.Delete(this.projectDirectory, true); } [Test] public void VerifyIgnoreNonAssemblyInfoFile() { - using (var writer = File.CreateText(Path.Combine(projectDirectory, "SomeOtherFile.cs"))) + using (var writer = File.CreateText(Path.Combine(this.projectDirectory, "SomeOtherFile.cs"))) { writer.Write(@" using System; @@ -43,13 +43,13 @@ public void VerifyIgnoreNonAssemblyInfoFile() "); } - FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "SomeOtherFile.cs" } }, projectFile); + FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "SomeOtherFile.cs" } }, this.projectFile); } [Test] public void VerifyAttributeFoundCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion", "System.Reflection.AssemblyVersion")] string attribute) { - using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.cs"))) + using (var writer = File.CreateText(Path.Combine(this.projectDirectory, "AssemblyInfo.cs"))) { writer.Write(@" using System; @@ -59,14 +59,14 @@ public void VerifyAttributeFoundCSharp([Values("AssemblyVersion", "AssemblyFileV ", attribute); } - var ex = Assert.Throws(() => FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.cs" } }, projectFile), attribute); + var ex = Assert.Throws(() => FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.cs" } }, this.projectFile), attribute); Assert.That(ex.Message, Is.EqualTo("File contains assembly version attributes which conflict with the attributes generated by GitVersion AssemblyInfo.cs")); } [Test] public void VerifyUnformattedAttributeFoundCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion", "System . Reflection . AssemblyVersion")] string attribute) { - using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.cs"))) + using (var writer = File.CreateText(Path.Combine(this.projectDirectory, "AssemblyInfo.cs"))) { writer.Write(@" using System; @@ -77,14 +77,14 @@ public void VerifyUnformattedAttributeFoundCSharp([Values("AssemblyVersion", "As ", attribute); } - var ex = Assert.Throws(() => FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.cs" } }, projectFile), attribute); + var ex = Assert.Throws(() => FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.cs" } }, this.projectFile), attribute); Assert.That(ex.Message, Is.EqualTo("File contains assembly version attributes which conflict with the attributes generated by GitVersion AssemblyInfo.cs")); } [Test] public void VerifyCommentWorksCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { - using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.cs"))) + using (var writer = File.CreateText(Path.Combine(this.projectDirectory, "AssemblyInfo.cs"))) { writer.Write(@" using System; @@ -94,13 +94,13 @@ public void VerifyCommentWorksCSharp([Values("AssemblyVersion", "AssemblyFileVer ", attribute); } - FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.cs" } }, projectFile); + FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.cs" } }, this.projectFile); } [Test] public void VerifyCommentWithNoNewLineAtEndWorksCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { - using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.cs"))) + using (var writer = File.CreateText(Path.Combine(this.projectDirectory, "AssemblyInfo.cs"))) { writer.Write(@" using System; @@ -109,13 +109,13 @@ public void VerifyCommentWithNoNewLineAtEndWorksCSharp([Values("AssemblyVersion" //[assembly: {0}(""1.0.0.0"")]", attribute); } - FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.cs" } }, projectFile); + FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.cs" } }, this.projectFile); } [Test] public void VerifyStringWorksCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { - using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.cs"))) + using (var writer = File.CreateText(Path.Combine(this.projectDirectory, "AssemblyInfo.cs"))) { writer.Write(@" using System; @@ -128,13 +128,13 @@ public class Temp ", attribute); } - FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.cs" } }, projectFile); + FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.cs" } }, this.projectFile); } [Test] public void VerifyIdentifierWorksCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { - using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.cs"))) + using (var writer = File.CreateText(Path.Combine(this.projectDirectory, "AssemblyInfo.cs"))) { writer.Write(@" using System; @@ -146,13 +146,13 @@ public class {0} ", attribute); } - FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.cs" } }, projectFile); + FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.cs" } }, this.projectFile); } [Test] public void VerifyAttributeFoundVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion", "System.Reflection.AssemblyVersion")] string attribute) { - using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.vb"))) + using (var writer = File.CreateText(Path.Combine(this.projectDirectory, "AssemblyInfo.vb"))) { writer.Write(@" Imports System @@ -162,14 +162,14 @@ Imports System.Reflection ", attribute); } - var ex = Assert.Throws(() => FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.vb" } }, projectFile), attribute); + var ex = Assert.Throws(() => FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.vb" } }, this.projectFile), attribute); Assert.That(ex.Message, Is.EqualTo("File contains assembly version attributes which conflict with the attributes generated by GitVersion AssemblyInfo.vb")); } [Test] public void VerifyUnformattedAttributeFoundVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion", "System . Reflection . AssemblyVersion")] string attribute) { - using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.vb"))) + using (var writer = File.CreateText(Path.Combine(this.projectDirectory, "AssemblyInfo.vb"))) { writer.Write(@" Imports System @@ -180,14 +180,14 @@ Imports System.Reflection ", attribute); } - var ex = Assert.Throws(() => FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.vb" } }, projectFile), attribute); + var ex = Assert.Throws(() => FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.vb" } }, this.projectFile), attribute); Assert.That(ex.Message, Is.EqualTo("File contains assembly version attributes which conflict with the attributes generated by GitVersion AssemblyInfo.vb")); } [Test] public void VerifyCommentWorksVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { - using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.vb"))) + using (var writer = File.CreateText(Path.Combine(this.projectDirectory, "AssemblyInfo.vb"))) { writer.Write(@" Imports System @@ -197,13 +197,13 @@ Imports System.Reflection ", attribute); } - FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.vb" } }, projectFile); + FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.vb" } }, this.projectFile); } [Test] public void VerifyCommentWithNoNewLineAtEndWorksVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { - using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.vb"))) + using (var writer = File.CreateText(Path.Combine(this.projectDirectory, "AssemblyInfo.vb"))) { writer.Write(@" Imports System @@ -212,13 +212,13 @@ Imports System.Reflection '", attribute); } - FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.vb" } }, projectFile); + FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.vb" } }, this.projectFile); } [Test] public void VerifyStringWorksVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { - using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.vb"))) + using (var writer = File.CreateText(Path.Combine(this.projectDirectory, "AssemblyInfo.vb"))) { writer.Write(@" Imports System @@ -230,13 +230,13 @@ End Class ", attribute); } - FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.vb" } }, projectFile); + FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.vb" } }, this.projectFile); } [Test] public void VerifyIdentifierWorksVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")] string attribute) { - using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.vb"))) + using (var writer = File.CreateText(Path.Combine(this.projectDirectory, "AssemblyInfo.vb"))) { writer.Write(@" Imports System @@ -247,7 +247,7 @@ End Class ", attribute); } - FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.vb" } }, projectFile); + FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.vb" } }, this.projectFile); } } } diff --git a/src/GitVersion.MsBuild.Tests/Mocks/MockEngine.cs b/src/GitVersion.MsBuild.Tests/Mocks/MockEngine.cs index 6f4312eca7..90798acf0a 100644 --- a/src/GitVersion.MsBuild.Tests/Mocks/MockEngine.cs +++ b/src/GitVersion.MsBuild.Tests/Mocks/MockEngine.cs @@ -27,21 +27,21 @@ internal sealed class MockEngine : IBuildEngine4 public void LogErrorEvent(BuildErrorEventArgs eventArgs) { Console.WriteLine(EventArgsFormatting.FormatEventMessage(eventArgs)); - _log.AppendLine(EventArgsFormatting.FormatEventMessage(eventArgs)); + this._log.AppendLine(EventArgsFormatting.FormatEventMessage(eventArgs)); ++Errors; } public void LogWarningEvent(BuildWarningEventArgs eventArgs) { Console.WriteLine(EventArgsFormatting.FormatEventMessage(eventArgs)); - _log.AppendLine(EventArgsFormatting.FormatEventMessage(eventArgs)); + this._log.AppendLine(EventArgsFormatting.FormatEventMessage(eventArgs)); ++Warnings; } public void LogCustomEvent(CustomBuildEventArgs eventArgs) { Console.WriteLine(eventArgs.Message); - _log.AppendLine(eventArgs.Message); + this._log.AppendLine(eventArgs.Message); } public void LogMessageEvent(BuildMessageEventArgs eventArgs) @@ -50,7 +50,7 @@ public void LogMessageEvent(BuildMessageEventArgs eventArgs) if (eventArgs.Importance <= MinimumMessageImportance) { Console.WriteLine(eventArgs.Message); - _log.AppendLine(eventArgs.Message); + this._log.AppendLine(eventArgs.Message); ++Messages; } } @@ -65,8 +65,8 @@ public void LogMessageEvent(BuildMessageEventArgs eventArgs) public string Log { - set => _log = new StringBuilder(value); - get => _log.ToString(); + set => this._log = new StringBuilder(value); + get => this._log.ToString(); } public bool BuildProjectFile(string projectFileName, string[] targetNames, IDictionary globalProperties, IDictionary targetOutputs) => false; @@ -114,18 +114,18 @@ public void Reacquire() public object GetRegisteredTaskObject(object key, RegisteredTaskObjectLifetime lifetime) { - _objectCache.TryGetValue(key, out var obj); + this._objectCache.TryGetValue(key, out var obj); return obj; } public void RegisterTaskObject(object key, object obj, RegisteredTaskObjectLifetime lifetime, bool allowEarlyCollection) { - _objectCache[key] = obj; + this._objectCache[key] = obj; } public object UnregisterTaskObject(object key, RegisteredTaskObjectLifetime lifetime) { - _objectCache.TryRemove(key, out var obj); + this._objectCache.TryRemove(key, out var obj); return obj; } } diff --git a/src/GitVersion.MsBuild/GitVersionTaskExecutor.cs b/src/GitVersion.MsBuild/GitVersionTaskExecutor.cs index 490d41ced6..6ef2f82551 100644 --- a/src/GitVersion.MsBuild/GitVersionTaskExecutor.cs +++ b/src/GitVersion.MsBuild/GitVersionTaskExecutor.cs @@ -41,7 +41,7 @@ public void UpdateAssemblyInfo(UpdateAssemblyInfo task) var fileWriteInfo = task.IntermediateOutputPath.GetFileWriteInfo(task.Language, task.ProjectFile, "AssemblyInfo"); task.AssemblyInfoTempFilePath = Path.Combine(fileWriteInfo.WorkingDirectory, fileWriteInfo.FileName); - var gitVersionOptions = options.Value; + var gitVersionOptions = this.options.Value; gitVersionOptions.AssemblyInfo.UpdateAssemblyInfo = true; gitVersionOptions.AssemblyInfo.EnsureAssemblyInfo = true; gitVersionOptions.WorkingDirectory = fileWriteInfo.WorkingDirectory; @@ -56,7 +56,7 @@ public void GenerateGitVersionInformation(GenerateGitVersionInformation task) var fileWriteInfo = task.IntermediateOutputPath.GetFileWriteInfo(task.Language, task.ProjectFile, "GitVersionInformation"); task.GitVersionInformationFilePath = Path.Combine(fileWriteInfo.WorkingDirectory, fileWriteInfo.FileName); - var gitVersionOptions = options.Value; + var gitVersionOptions = this.options.Value; gitVersionOptions.WorkingDirectory = fileWriteInfo.WorkingDirectory; gitVersionOutputTool.GenerateGitVersionInformation(versionVariables, fileWriteInfo); diff --git a/src/GitVersion.MsBuild/Helpers/MsBuildAdapter.cs b/src/GitVersion.MsBuild/Helpers/MsBuildAdapter.cs index c02dd72d1c..14841620fd 100644 --- a/src/GitVersion.MsBuild/Helpers/MsBuildAdapter.cs +++ b/src/GitVersion.MsBuild/Helpers/MsBuildAdapter.cs @@ -21,12 +21,12 @@ public void WriteLine(string msg) public void WriteLine() { - taskLog.LogMessage("\n"); + this.taskLog.LogMessage("\n"); } public void Write(string msg) { - taskLog.LogMessage(msg); + this.taskLog.LogMessage(msg); } public string ReadLine() diff --git a/src/GitVersion.MsBuild/Helpers/MsBuildAppender.cs b/src/GitVersion.MsBuild/Helpers/MsBuildAppender.cs index 8f3c57ba99..e84ab9458a 100644 --- a/src/GitVersion.MsBuild/Helpers/MsBuildAppender.cs +++ b/src/GitVersion.MsBuild/Helpers/MsBuildAppender.cs @@ -32,15 +32,15 @@ private void WriteLogEntry(LogLevel level, string str) { case LogLevel.Fatal: case LogLevel.Error: - taskLog.LogError(contents); + this.taskLog.LogError(contents); break; case LogLevel.Warn: - taskLog.LogWarning(contents); + this.taskLog.LogWarning(contents); break; case LogLevel.Info: case LogLevel.Verbose: case LogLevel.Debug: - taskLog.LogMessage(contents); + this.taskLog.LogMessage(contents); break; default: throw new ArgumentOutOfRangeException(nameof(level), level, null); From 22d3f185fda799907ef0ce3f2c475e4fc02cad1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Fri, 16 Jul 2021 18:56:19 +0200 Subject: [PATCH 51/79] Prefer expression body Fix error Fix 2 Add resharper config foo --- .editorconfig | 10 +- .../Fixtures/RemoteRepositoryFixture.cs | 5 +- .../Fixtures/RepositoryFixtureBase.cs | 10 +- .../Fixtures/SequenceDiagram.cs | 45 ++----- src/GitTools.Testing/Generate.cs | 5 +- src/GitTools.Testing/GitTestExtensions.cs | 24 +--- .../Internal/DirectoryHelper.cs | 5 +- src/GitTools.Testing/Internal/PathHelper.cs | 5 +- .../ArgumentParserOnBuildServerTests.cs | 25 +--- .../Helpers/TestConsoleAdapter.cs | 30 +---- .../QuotedStringHelpersTests.cs | 15 +-- .../UpdateWixVersionFileTests.cs | 5 +- src/GitVersion.App/GitVersionApp.cs | 5 +- src/GitVersion.App/HelpWriter.cs | 5 +- .../OverrideConfigOptionParser.cs | 10 +- src/GitVersion.App/Program.cs | 10 +- src/GitVersion.App/VersionWriter.cs | 5 +- .../BuildAgents/AzurePipelinesTests.cs | 5 +- .../BuildAgents/BuildServerBaseTests.cs | 15 +-- .../BuildAgents/ContinuaCiTests.cs | 11 +- .../BuildAgents/DroneTests.cs | 5 +- .../BuildAgents/JenkinsTests.cs | 10 +- .../BuildAgents/SpaceAutomationTests.cs | 5 +- .../Configuration/ConfigProviderTests.cs | 5 +- .../DefaultConfigFileLocatorTests.cs | 18 +-- .../Configuration/Init/InitScenarios.cs | 5 +- .../Core/GitVersionExecutorTests.cs | 23 ++-- .../Core/GitVersionToolDirectoryTests.cs | 5 +- .../DocumentationTests.cs | 5 +- .../Extensions/GitToolsTestingExtensions.cs | 15 +-- .../StringFormatWithExtensionTests.cs | 5 +- .../Helpers/DirectoryHelper.cs | 5 +- .../Helpers/GitVersionContextBuilder.cs | 5 +- .../Helpers/PathHelper.cs | 20 +-- .../Helpers/RuntimeHelper.cs | 2 + .../Helpers/TestConsole.cs | 25 +--- .../Helpers/TestEnvironment.cs | 10 +- .../Helpers/TestFileSystem.cs | 20 +-- .../Helpers/TestLogAppender.cs | 5 +- .../Helpers/TestStream.cs | 20 +-- .../IntegrationTests/FileSystemTests.cs | 10 +- .../Model/MergeMessageTests.cs | 4 +- .../BaseVersionCalculatorTests.cs | 5 +- .../JsonVersionBuilderTests.cs | 5 +- .../SemanticVersionTests.cs | 5 +- .../ShaVersionFilterTests.cs | 5 +- .../TestBaseVersionCalculator.cs | 5 +- .../TestMainlineVersionCalculator.cs | 10 +- .../GitVersionInfoGeneratorTests.cs | 5 +- .../VersionConverters/WixFileTests.cs | 5 +- .../BuildAgents/AzurePipelines.cs | 10 +- src/GitVersion.Core/BuildAgents/CodeBuild.cs | 15 +-- src/GitVersion.Core/BuildAgents/ContinuaCi.cs | 10 +- src/GitVersion.Core/BuildAgents/Drone.cs | 15 +-- src/GitVersion.Core/BuildAgents/EnvRun.cs | 10 +- .../BuildAgents/GitHubActions.cs | 17 +-- src/GitVersion.Core/BuildAgents/GitLabCi.cs | 25 +--- src/GitVersion.Core/BuildAgents/Jenkins.cs | 35 +---- src/GitVersion.Core/BuildAgents/MyGet.cs | 5 +- .../BuildAgents/SpaceAutomation.cs | 15 +-- src/GitVersion.Core/BuildAgents/TeamCity.cs | 20 +-- src/GitVersion.Core/BuildAgents/TravisCI.cs | 15 +-- .../Configuration/ConfigExtensions.cs | 6 +- .../Configuration/ConfigProvider.cs | 12 +- .../Init/BuildServer/AppVeyorSetup.cs | 28 ++-- .../Init/BuildServer/AppveyorPublicPrivate.cs | 5 +- .../Init/BuildServer/SetupBuildScripts.cs | 5 +- .../Configuration/Init/EditConfigStep.cs | 5 +- .../AssemblyVersioningSchemeSetting.cs | 6 +- .../Init/SetConfig/ConfigureBranch.cs | 5 +- .../Init/SetConfig/ConfigureBranches.cs | 5 +- .../Init/SetConfig/GlobalModeSetting.cs | 5 +- .../Init/SetConfig/SetBranchIncrementMode.cs | 5 +- .../Init/SetConfig/SetBranchTag.cs | 5 +- .../Configuration/Init/SetNextVersion.cs | 5 +- .../Configuration/Init/StepResult.cs | 36 ++--- .../Init/Wizard/FinishedSetupStep.cs | 5 +- .../Init/Wizard/GitFlowSetupStep.cs | 5 +- .../Init/Wizard/GitHubFlowStep.cs | 5 +- .../Init/Wizard/PickBranchingStrategy1Step.cs | 5 +- .../Init/Wizard/PickBranchingStrategy2Step.cs | 5 +- .../Init/Wizard/PickBranchingStrategy3Step.cs | 5 +- .../Init/Wizard/PickBranchingStrategyStep.cs | 5 +- src/GitVersion.Core/Core/Environment.cs | 10 +- src/GitVersion.Core/Core/FileSystem.cs | 66 +++------ src/GitVersion.Core/Core/GitPreparer.cs | 5 +- src/GitVersion.Core/Core/RepositoryStore.cs | 46 ++----- .../AssemblyVersionsGeneratorExtensions.cs | 14 +- .../Extensions/ServiceCollectionExtensions.cs | 6 +- .../Extensions/StringExtensions.cs | 36 ++--- src/GitVersion.Core/Git/ReferenceName.cs | 10 +- src/GitVersion.Core/Helpers/RetryAction.cs | 18 +-- src/GitVersion.Core/Logging/ConsoleAdapter.cs | 20 +-- src/GitVersion.Core/Logging/Log.cs | 10 +- src/GitVersion.Core/Logging/LogExtensions.cs | 125 ++++-------------- src/GitVersion.Core/Logging/NullLog.cs | 5 +- src/GitVersion.Core/Model/BranchCommit.cs | 5 +- .../Model/Configuration/BranchConfig.cs | 21 ++- src/GitVersion.Core/Model/VersionVariables.cs | 15 +-- .../BaseVersionCalculator.cs | 5 +- .../TaggedCommitVersionStrategy.cs | 16 +-- .../VersionInBranchNameVersionStrategy.cs | 5 +- .../VersionStrategyBase.cs | 5 +- .../Cache/GitVersionCache.cs | 5 +- .../VersionCalculation/IncrementStrategy.cs | 17 +-- .../NextVersionCalculator.cs | 5 +- .../SemanticVersioning/SemanticVersion.cs | 15 +-- .../SemanticVersionBuildMetaData.cs | 20 +-- .../SemanticVersionPreReleaseTag.cs | 26 +--- .../WixUpdater/WixVersionFileUpdater.cs | 5 +- .../Git/BranchCollection.cs | 5 +- src/GitVersion.LibGit2Sharp/Git/Commit.cs | 5 +- .../Git/CommitCollection.cs | 5 +- src/GitVersion.LibGit2Sharp/Git/GitObject.cs | 5 +- .../Git/GitRepository.cs | 38 +++--- .../Git/RefSpecCollection.cs | 10 +- .../Git/ReferenceCollection.cs | 26 +--- .../Git/RemoteCollection.cs | 15 +-- .../Git/TagCollection.cs | 5 +- .../Helpers/EventArgsFormatting.cs | 40 ++---- .../Helpers/MsBuildExeFixture.cs | 5 +- .../Helpers/MsBuildExeFixtureResult.cs | 5 +- .../Helpers/MsBuildTaskFixture.cs | 44 +++--- .../Helpers/MsBuildTaskFixtureResult.cs | 5 +- .../InvalidFileCheckerTests.cs | 5 +- .../Mocks/MockEngine.cs | 5 +- .../Mocks/MockTaskItem.cs | 33 ++--- .../Tasks/WriteVersionInfoTest.cs | 5 +- src/GitVersion.MsBuild/Helpers/FileHelper.cs | 20 +-- .../Helpers/MsBuildAdapter.cs | 15 +-- 130 files changed, 424 insertions(+), 1290 deletions(-) diff --git a/.editorconfig b/.editorconfig index afeec6253f..a9c3d9fccb 100644 --- a/.editorconfig +++ b/.editorconfig @@ -73,11 +73,11 @@ csharp_style_var_when_type_is_apparent = true:silent csharp_style_var_elsewhere = true:silent # Prefer method-like constructs to have a block body, except for lambdas -csharp_style_expression_bodied_methods = false:none -csharp_style_expression_bodied_constructors = false:none -csharp_style_expression_bodied_operators = false:none -csharp_style_expression_bodied_local_functions = false:none -csharp_style_expression_bodied_lambdas = true:none +csharp_style_expression_bodied_methods = true:warning +csharp_style_expression_bodied_constructors = true:warning +csharp_style_expression_bodied_operators = true:warning +csharp_style_expression_bodied_local_functions = true:warning +csharp_style_expression_bodied_lambdas = true:warning # Pattern matching preferences csharp_style_pattern_matching_over_as_with_null_check = true:warning diff --git a/src/GitTools.Testing/Fixtures/RemoteRepositoryFixture.cs b/src/GitTools.Testing/Fixtures/RemoteRepositoryFixture.cs index 158b26cd4c..cbd5a4816d 100644 --- a/src/GitTools.Testing/Fixtures/RemoteRepositoryFixture.cs +++ b/src/GitTools.Testing/Fixtures/RemoteRepositoryFixture.cs @@ -35,10 +35,7 @@ private static IRepository CreateNewRepository(string path) return repo; } - private void CreateLocalRepository() - { - LocalRepositoryFixture = CloneRepository(); - } + private void CreateLocalRepository() => LocalRepositoryFixture = CloneRepository(); /// /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. diff --git a/src/GitTools.Testing/Fixtures/RepositoryFixtureBase.cs b/src/GitTools.Testing/Fixtures/RepositoryFixtureBase.cs index 3695789872..a1112da059 100644 --- a/src/GitTools.Testing/Fixtures/RepositoryFixtureBase.cs +++ b/src/GitTools.Testing/Fixtures/RepositoryFixtureBase.cs @@ -59,15 +59,9 @@ public virtual void Dispose() Console.WriteLine(this._sequenceDiagram.GetDiagram()); } - public void Checkout(string branch) - { - Commands.Checkout(Repository, branch); - } + public void Checkout(string branch) => Commands.Checkout(Repository, branch); - public static void Init(string path) - { - GitTestExtensions.ExecuteGitCmd($"init {path} -b main"); - } + public static void Init(string path) => GitTestExtensions.ExecuteGitCmd($"init {path} -b main"); public void MakeATaggedCommit(string tag) { diff --git a/src/GitTools.Testing/Fixtures/SequenceDiagram.cs b/src/GitTools.Testing/Fixtures/SequenceDiagram.cs index 911062f874..5c83bcd6bd 100644 --- a/src/GitTools.Testing/Fixtures/SequenceDiagram.cs +++ b/src/GitTools.Testing/Fixtures/SequenceDiagram.cs @@ -24,18 +24,12 @@ public SequenceDiagram() /// /// Activates a branch/participant in the sequence diagram /// - public void Activate(string branch) - { - this._diagramBuilder.AppendLineFormat("activate {0}", GetParticipant(branch)); - } + public void Activate(string branch) => this._diagramBuilder.AppendLineFormat("activate {0}", GetParticipant(branch)); /// /// Destroys a branch/participant in the sequence diagram /// - public void Destroy(string branch) - { - this._diagramBuilder.AppendLineFormat("destroy {0}", GetParticipant(branch)); - } + public void Destroy(string branch) => this._diagramBuilder.AppendLineFormat("destroy {0}", GetParticipant(branch)); /// /// Creates a participant in the sequence diagram @@ -52,17 +46,12 @@ public void Participant(string participant, string @as = null) /// /// Appends a divider with specified text to the sequence diagram /// - public void Divider(string text) - { - this._diagramBuilder.AppendLineFormat("== {0} ==", text); - } + public void Divider(string text) => this._diagramBuilder.AppendLineFormat("== {0} ==", text); /// /// Appends a note over one or many participants to the sequence diagram /// - public void NoteOver(string noteText, string startParticipant, string endParticipant = null, string prefix = null, string color = null) - { - this._diagramBuilder.AppendLineFormat( + public void NoteOver(string noteText, string startParticipant, string endParticipant = null, string prefix = null, string color = null) => this._diagramBuilder.AppendLineFormat( prefix + @"note over {0}{1}{2} {3} end note", @@ -70,15 +59,11 @@ public void NoteOver(string noteText, string startParticipant, string endPartici endParticipant == null ? null : ", " + GetParticipant(endParticipant), color == null ? null : " " + color, noteText.Replace("\n", "\n ")); - } /// /// Appends applying a tag to the specified branch/participant to the sequence diagram /// - public void ApplyTag(string tag, string toBranch) - { - this._diagramBuilder.AppendLineFormat("{0} -> {0}: tag {1}", GetParticipant(toBranch), tag); - } + public void ApplyTag(string tag, string toBranch) => this._diagramBuilder.AppendLineFormat("{0} -> {0}: tag {1}", GetParticipant(toBranch), tag); /// /// Appends branching from a branch to another branch, @as can override the participant name @@ -114,18 +99,12 @@ public void BranchToFromTag(string branchName, string fromTag, string onBranch, /// /// Appends a commit on the target participant/branch to the sequence diagram /// - public void MakeACommit(string toParticipant) - { - this._diagramBuilder.AppendLineFormat("{0} -> {0}: commit", GetParticipant(toParticipant)); - } + public void MakeACommit(string toParticipant) => this._diagramBuilder.AppendLineFormat("{0} -> {0}: commit", GetParticipant(toParticipant)); /// /// Append a merge to the sequence diagram /// - public void Merge(string @from, string to) - { - this._diagramBuilder.AppendLineFormat("{0} -> {1}: merge", GetParticipant(@from), GetParticipant(to)); - } + public void Merge(string @from, string to) => this._diagramBuilder.AppendLineFormat("{0} -> {1}: merge", GetParticipant(@from), GetParticipant(to)); string GetParticipant(string branch) { @@ -138,17 +117,11 @@ string GetParticipant(string branch) /// /// Ends the sequence diagram /// - public void End() - { - this._diagramBuilder.AppendLine("@enduml"); - } + public void End() => this._diagramBuilder.AppendLine("@enduml"); /// /// returns the plantUML representation of the Sequence Diagram /// - public string GetDiagram() - { - return this._diagramBuilder.ToString(); - } + public string GetDiagram() => this._diagramBuilder.ToString(); } } diff --git a/src/GitTools.Testing/Generate.cs b/src/GitTools.Testing/Generate.cs index 4d47664a7e..7ed980c3a2 100644 --- a/src/GitTools.Testing/Generate.cs +++ b/src/GitTools.Testing/Generate.cs @@ -20,9 +20,6 @@ public static Signature SignatureNow() /// /// Creates a libgit2sharp signature at the specified time /// - public static Signature Signature(DateTimeOffset dateTimeOffset) - { - return new Signature("A. U. Thor", "thor@valhalla.asgard.com", dateTimeOffset); - } + public static Signature Signature(DateTimeOffset dateTimeOffset) => new Signature("A. U. Thor", "thor@valhalla.asgard.com", dateTimeOffset); } } diff --git a/src/GitTools.Testing/GitTestExtensions.cs b/src/GitTools.Testing/GitTestExtensions.cs index 4b6ee8046e..7b45c369f1 100644 --- a/src/GitTools.Testing/GitTestExtensions.cs +++ b/src/GitTools.Testing/GitTestExtensions.cs @@ -11,30 +11,18 @@ public static class GitTestExtensions { static int _pad = 1; - public static Commit MakeACommit(this IRepository repository, string commitMessage = null) - { - return CreateFileAndCommit(repository, Guid.NewGuid().ToString(), commitMessage); - } + public static Commit MakeACommit(this IRepository repository, string commitMessage = null) => CreateFileAndCommit(repository, Guid.NewGuid().ToString(), commitMessage); - public static void MergeNoFF(this IRepository repository, string branch) - { - MergeNoFF(repository, branch, Generate.SignatureNow()); - } + public static void MergeNoFF(this IRepository repository, string branch) => MergeNoFF(repository, branch, Generate.SignatureNow()); - public static void MergeNoFF(this IRepository repository, string branch, Signature sig) + public static void MergeNoFF(this IRepository repository, string branch, Signature sig) => repository.Merge(repository.Branches[branch], sig, new MergeOptions { - repository.Merge(repository.Branches[branch], sig, new MergeOptions - { - FastForwardStrategy = FastForwardStrategy.NoFastForward - }); - } + FastForwardStrategy = FastForwardStrategy.NoFastForward + }); - public static Commit[] MakeCommits(this IRepository repository, int numCommitsToMake) - { - return Enumerable.Range(1, numCommitsToMake) + public static Commit[] MakeCommits(this IRepository repository, int numCommitsToMake) => Enumerable.Range(1, numCommitsToMake) .Select(_ => repository.MakeACommit()) .ToArray(); - } private static Commit CreateFileAndCommit(this IRepository repository, string relativeFileName, string commitMessage = null) { diff --git a/src/GitTools.Testing/Internal/DirectoryHelper.cs b/src/GitTools.Testing/Internal/DirectoryHelper.cs index d0523f8ac3..e98baab01d 100644 --- a/src/GitTools.Testing/Internal/DirectoryHelper.cs +++ b/src/GitTools.Testing/Internal/DirectoryHelper.cs @@ -28,10 +28,7 @@ public static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo targ } } - static string Rename(string name) - { - return ToRename.ContainsKey(name) ? ToRename[name] : name; - } + static string Rename(string name) => ToRename.ContainsKey(name) ? ToRename[name] : name; public static void DeleteSubDirectories(string parentPath) { diff --git a/src/GitTools.Testing/Internal/PathHelper.cs b/src/GitTools.Testing/Internal/PathHelper.cs index c9e7facaba..ee38b23efd 100644 --- a/src/GitTools.Testing/Internal/PathHelper.cs +++ b/src/GitTools.Testing/Internal/PathHelper.cs @@ -5,9 +5,6 @@ namespace GitTools.Testing.Internal { static class PathHelper { - public static string GetTempPath() - { - return Path.Combine(Path.GetTempPath(), "TestRepositories", Guid.NewGuid().ToString()); - } + public static string GetTempPath() => Path.Combine(Path.GetTempPath(), "TestRepositories", Guid.NewGuid().ToString()); } } diff --git a/src/GitVersion.App.Tests/ArgumentParserOnBuildServerTests.cs b/src/GitVersion.App.Tests/ArgumentParserOnBuildServerTests.cs index f17ca02ab4..58fcae2cd2 100644 --- a/src/GitVersion.App.Tests/ArgumentParserOnBuildServerTests.cs +++ b/src/GitVersion.App.Tests/ArgumentParserOnBuildServerTests.cs @@ -34,30 +34,15 @@ public void EmptyOnFetchDisabledBuildServerMeansNoFetchIsTrue() private class MockBuildAgent : ICurrentBuildAgent { - public bool CanApplyToCurrentContext() - { - throw new NotImplementedException(); - } + public bool CanApplyToCurrentContext() => throw new NotImplementedException(); - public void WriteIntegration(Action writer, VersionVariables variables, bool updateBuildNumber = true) - { - throw new NotImplementedException(); - } + public void WriteIntegration(Action writer, VersionVariables variables, bool updateBuildNumber = true) => throw new NotImplementedException(); - public string GetCurrentBranch(bool usingDynamicRepos) - { - throw new NotImplementedException(); - } + public string GetCurrentBranch(bool usingDynamicRepos) => throw new NotImplementedException(); - public bool PreventFetch() - { - return true; - } + public bool PreventFetch() => true; - public bool ShouldCleanUpRemotes() - { - throw new NotImplementedException(); - } + public bool ShouldCleanUpRemotes() => throw new NotImplementedException(); } } } diff --git a/src/GitVersion.App.Tests/Helpers/TestConsoleAdapter.cs b/src/GitVersion.App.Tests/Helpers/TestConsoleAdapter.cs index 315f50c2d8..d9049f2d06 100644 --- a/src/GitVersion.App.Tests/Helpers/TestConsoleAdapter.cs +++ b/src/GitVersion.App.Tests/Helpers/TestConsoleAdapter.cs @@ -11,34 +11,16 @@ public TestConsoleAdapter(StringBuilder sb) { this.sb = sb; } - public void WriteLine(string msg) - { - this.sb.AppendLine(msg); - } + public void WriteLine(string msg) => this.sb.AppendLine(msg); - public void WriteLine() - { - this.sb.AppendLine(); - } + public void WriteLine() => this.sb.AppendLine(); - public void Write(string msg) - { - this.sb.Append(msg); - } + public void Write(string msg) => this.sb.Append(msg); - public override string ToString() - { - return this.sb.ToString(); - } + public override string ToString() => this.sb.ToString(); - public string ReadLine() - { - throw new NotImplementedException(); - } + public string ReadLine() => throw new NotImplementedException(); - public IDisposable UseColor(ConsoleColor consoleColor) - { - return Disposable.Empty; - } + public IDisposable UseColor(ConsoleColor consoleColor) => Disposable.Empty; } } diff --git a/src/GitVersion.App.Tests/QuotedStringHelpersTests.cs b/src/GitVersion.App.Tests/QuotedStringHelpersTests.cs index 3ee272cd81..0df1721152 100644 --- a/src/GitVersion.App.Tests/QuotedStringHelpersTests.cs +++ b/src/GitVersion.App.Tests/QuotedStringHelpersTests.cs @@ -8,10 +8,7 @@ namespace GitVersionExe.Tests public class QuotedStringHelpersTests { [TestCaseSource(nameof(SplitUnquotedTestData))] - public string[] SplitUnquotedTests(string input, char splitChar) - { - return QuotedStringHelpers.SplitUnquoted(input, splitChar); - } + public string[] SplitUnquotedTests(string input, char splitChar) => QuotedStringHelpers.SplitUnquoted(input, splitChar); private static IEnumerable SplitUnquotedTestData() { @@ -91,10 +88,7 @@ private static IEnumerable SplitUnquotedTestData() } [TestCaseSource(nameof(RemoveEmptyEntriesTestData))] - public string[] SplitUnquotedRemovesEmptyEntries(string input, char splitChar) - { - return QuotedStringHelpers.SplitUnquoted(input, splitChar); - } + public string[] SplitUnquotedRemovesEmptyEntries(string input, char splitChar) => QuotedStringHelpers.SplitUnquoted(input, splitChar); private static IEnumerable RemoveEmptyEntriesTestData() { @@ -110,10 +104,7 @@ private static IEnumerable RemoveEmptyEntriesTestData() } [TestCaseSource(nameof(UnquoteTextTestData))] - public string UnquoteTextTests(string input) - { - return QuotedStringHelpers.UnquoteText(input); - } + public string UnquoteTextTests(string input) => QuotedStringHelpers.UnquoteText(input); private static IEnumerable UnquoteTextTestData() { diff --git a/src/GitVersion.App.Tests/UpdateWixVersionFileTests.cs b/src/GitVersion.App.Tests/UpdateWixVersionFileTests.cs index b8cd526acb..75713ed59a 100644 --- a/src/GitVersion.App.Tests/UpdateWixVersionFileTests.cs +++ b/src/GitVersion.App.Tests/UpdateWixVersionFileTests.cs @@ -16,10 +16,7 @@ internal class UpdateWixVersionFileTests private string wixVersionFileName; [SetUp] - public void Setup() - { - this.wixVersionFileName = WixVersionFileUpdater.WixVersionFileName; - } + public void Setup() => this.wixVersionFileName = WixVersionFileUpdater.WixVersionFileName; [Test] public void WixVersionFileCreationTest() diff --git a/src/GitVersion.App/GitVersionApp.cs b/src/GitVersion.App/GitVersionApp.cs index 35b8868433..53060f5046 100644 --- a/src/GitVersion.App/GitVersionApp.cs +++ b/src/GitVersion.App/GitVersionApp.cs @@ -39,9 +39,6 @@ public Task StartAsync(CancellationToken cancellationToken) return Task.CompletedTask; } - public Task StopAsync(CancellationToken cancellationToken) - { - return Task.CompletedTask; - } + public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; } } diff --git a/src/GitVersion.App/HelpWriter.cs b/src/GitVersion.App/HelpWriter.cs index f17439fa3d..686829b5ae 100644 --- a/src/GitVersion.App/HelpWriter.cs +++ b/src/GitVersion.App/HelpWriter.cs @@ -16,10 +16,7 @@ public HelpWriter(IVersionWriter versionWriter, IConsole console) this.console = console ?? throw new ArgumentNullException(nameof(console)); } - public void Write() - { - WriteTo(this.console.WriteLine); - } + public void Write() => WriteTo(this.console.WriteLine); public void WriteTo(Action writeAction) { diff --git a/src/GitVersion.App/OverrideConfigOptionParser.cs b/src/GitVersion.App/OverrideConfigOptionParser.cs index e307569c5b..eeb25d8b3a 100644 --- a/src/GitVersion.App/OverrideConfigOptionParser.cs +++ b/src/GitVersion.App/OverrideConfigOptionParser.cs @@ -23,9 +23,7 @@ internal class OverrideConfigOptionParser /// Lookup keys are created from to match 'GitVersion.yml' /// options as close as possible. /// - private static ILookup GetSupportedProperties() - { - return typeof(Config).GetProperties(BindingFlags.Public | BindingFlags.Instance) + private static ILookup GetSupportedProperties() => typeof(Config).GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where( pi => IsSupportedPropertyType(pi.PropertyType) && pi.CanWrite @@ -35,7 +33,6 @@ private static ILookup GetSupportedProperties() pi => (pi.GetCustomAttributes(typeof(YamlDotNet.Serialization.YamlMemberAttribute), false)[0] as YamlDotNet.Serialization.YamlMemberAttribute).Alias, pi => pi ); - } /// /// Checks if property of @@ -106,9 +103,6 @@ internal void SetValue(string key, string value) } } - internal Config GetConfig() - { - return this._lazyConfig.IsValueCreated ? this._lazyConfig.Value : null; - } + internal Config GetConfig() => this._lazyConfig.IsValueCreated ? this._lazyConfig.Value : null; } } diff --git a/src/GitVersion.App/Program.cs b/src/GitVersion.App/Program.cs index 0999caca05..ec4a928ad1 100644 --- a/src/GitVersion.App/Program.cs +++ b/src/GitVersion.App/Program.cs @@ -17,15 +17,9 @@ internal Program(Action overrides = null) this.overrides = overrides; } - private static async Task Main(string[] args) - { - await new Program().RunAsync(args); - } + private static async Task Main(string[] args) => await new Program().RunAsync(args); - internal Task RunAsync(string[] args) - { - return CreateHostBuilder(args).Build().RunAsync(); - } + internal Task RunAsync(string[] args) => CreateHostBuilder(args).Build().RunAsync(); private IHostBuilder CreateHostBuilder(string[] args) => new HostBuilder() diff --git a/src/GitVersion.App/VersionWriter.cs b/src/GitVersion.App/VersionWriter.cs index 41061f12e5..c20dcaa593 100644 --- a/src/GitVersion.App/VersionWriter.cs +++ b/src/GitVersion.App/VersionWriter.cs @@ -13,10 +13,7 @@ public VersionWriter(IConsole console) { this.console = console ?? throw new ArgumentNullException(nameof(console)); } - public void Write(Assembly assembly) - { - WriteTo(assembly, this.console.WriteLine); - } + public void Write(Assembly assembly) => WriteTo(assembly, this.console.WriteLine); public void WriteTo(Assembly assembly, Action writeAction) { diff --git a/src/GitVersion.Core.Tests/BuildAgents/AzurePipelinesTests.cs b/src/GitVersion.Core.Tests/BuildAgents/AzurePipelinesTests.cs index 37d2006b0c..7e5ea56f90 100644 --- a/src/GitVersion.Core.Tests/BuildAgents/AzurePipelinesTests.cs +++ b/src/GitVersion.Core.Tests/BuildAgents/AzurePipelinesTests.cs @@ -29,10 +29,7 @@ public void SetEnvironmentVariableForTest() } [TearDown] - public void ClearEnvironmentVariableForTest() - { - this.environment.SetEnvironmentVariable(key, null); - } + public void ClearEnvironmentVariableForTest() => this.environment.SetEnvironmentVariable(key, null); [Test] public void DevelopBranch() diff --git a/src/GitVersion.Core.Tests/BuildAgents/BuildServerBaseTests.cs b/src/GitVersion.Core.Tests/BuildAgents/BuildServerBaseTests.cs index 8ab20e1e95..2f133ef94f 100644 --- a/src/GitVersion.Core.Tests/BuildAgents/BuildServerBaseTests.cs +++ b/src/GitVersion.Core.Tests/BuildAgents/BuildServerBaseTests.cs @@ -64,20 +64,11 @@ public BuildAgent(IEnvironment environment, ILog log) : base(environment, log) { } - public override bool CanApplyToCurrentContext() - { - throw new NotImplementedException(); - } + public override bool CanApplyToCurrentContext() => throw new NotImplementedException(); - public override string GenerateSetVersionMessage(VersionVariables variables) - { - return variables.FullSemVer; - } + public override string GenerateSetVersionMessage(VersionVariables variables) => variables.FullSemVer; - public override string[] GenerateSetParameterMessage(string name, string value) - { - return new string[0]; - } + public override string[] GenerateSetParameterMessage(string name, string value) => new string[0]; } } } diff --git a/src/GitVersion.Core.Tests/BuildAgents/ContinuaCiTests.cs b/src/GitVersion.Core.Tests/BuildAgents/ContinuaCiTests.cs index c7c78e8a28..51f377af8c 100644 --- a/src/GitVersion.Core.Tests/BuildAgents/ContinuaCiTests.cs +++ b/src/GitVersion.Core.Tests/BuildAgents/ContinuaCiTests.cs @@ -12,13 +12,10 @@ public class ContinuaCiTests : TestBase private IServiceProvider sp; [SetUp] - public void SetUp() - { - this.sp = ConfigureServices(services => - { - services.AddSingleton(); - }); - } + public void SetUp() => this.sp = ConfigureServices(services => + { + services.AddSingleton(); + }); [Test] public void GenerateBuildVersion() diff --git a/src/GitVersion.Core.Tests/BuildAgents/DroneTests.cs b/src/GitVersion.Core.Tests/BuildAgents/DroneTests.cs index 010cb73d33..4c40fe73cc 100644 --- a/src/GitVersion.Core.Tests/BuildAgents/DroneTests.cs +++ b/src/GitVersion.Core.Tests/BuildAgents/DroneTests.cs @@ -27,10 +27,7 @@ public void SetUp() } [TearDown] - public void TearDown() - { - this.environment.SetEnvironmentVariable("DRONE", null); - } + public void TearDown() => this.environment.SetEnvironmentVariable("DRONE", null); [Test] public void CanApplyToCurrentContextShouldBeTrueWhenEnvironmentVariableIsSet() diff --git a/src/GitVersion.Core.Tests/BuildAgents/JenkinsTests.cs b/src/GitVersion.Core.Tests/BuildAgents/JenkinsTests.cs index 4f6bfbf4f7..5f16f558c5 100644 --- a/src/GitVersion.Core.Tests/BuildAgents/JenkinsTests.cs +++ b/src/GitVersion.Core.Tests/BuildAgents/JenkinsTests.cs @@ -33,15 +33,9 @@ public void SetUp() this.buildServer = this.sp.GetService(); } - private void SetEnvironmentVariableForDetection() - { - this.environment.SetEnvironmentVariable(key, "a value"); - } + private void SetEnvironmentVariableForDetection() => this.environment.SetEnvironmentVariable(key, "a value"); - private void ClearenvironmentVariableForDetection() - { - this.environment.SetEnvironmentVariable(key, null); - } + private void ClearenvironmentVariableForDetection() => this.environment.SetEnvironmentVariable(key, null); [Test] public void CanApplyCurrentContextWhenenvironmentVariableIsSet() diff --git a/src/GitVersion.Core.Tests/BuildAgents/SpaceAutomationTests.cs b/src/GitVersion.Core.Tests/BuildAgents/SpaceAutomationTests.cs index 610208be48..4db9066847 100644 --- a/src/GitVersion.Core.Tests/BuildAgents/SpaceAutomationTests.cs +++ b/src/GitVersion.Core.Tests/BuildAgents/SpaceAutomationTests.cs @@ -27,10 +27,7 @@ public void SetUp() } [TearDown] - public void TearDown() - { - this.environment.SetEnvironmentVariable(SpaceAutomation.EnvironmentVariableName, null); - } + public void TearDown() => this.environment.SetEnvironmentVariable(SpaceAutomation.EnvironmentVariableName, null); [Test] public void CanApplyToCurrentContextShouldBeTrueWhenEnvironmentVariableIsSet() diff --git a/src/GitVersion.Core.Tests/Configuration/ConfigProviderTests.cs b/src/GitVersion.Core.Tests/Configuration/ConfigProviderTests.cs index 4abb715418..87a2bf87a5 100644 --- a/src/GitVersion.Core.Tests/Configuration/ConfigProviderTests.cs +++ b/src/GitVersion.Core.Tests/Configuration/ConfigProviderTests.cs @@ -345,10 +345,7 @@ public void NoWarnOnGitVersionYmlFile() stringLogger.Length.ShouldBe(0); } - private string SetupConfigFileContent(string text, string fileName = ConfigFileLocator.DefaultFileName) - { - return SetupConfigFileContent(text, fileName, this.repoPath); - } + private string SetupConfigFileContent(string text, string fileName = ConfigFileLocator.DefaultFileName) => SetupConfigFileContent(text, fileName, this.repoPath); private string SetupConfigFileContent(string text, string fileName, string path) { diff --git a/src/GitVersion.Core.Tests/Configuration/DefaultConfigFileLocatorTests.cs b/src/GitVersion.Core.Tests/Configuration/DefaultConfigFileLocatorTests.cs index f88ec0df79..d7ec241ec9 100644 --- a/src/GitVersion.Core.Tests/Configuration/DefaultConfigFileLocatorTests.cs +++ b/src/GitVersion.Core.Tests/Configuration/DefaultConfigFileLocatorTests.cs @@ -68,10 +68,7 @@ public void NoWarnOnGitVersionYmlFile() } [Test] - public void NoWarnOnNoGitVersionYmlFile() - { - Should.NotThrow(() => { this.configurationProvider.Provide(this.repoPath); }); - } + public void NoWarnOnNoGitVersionYmlFile() => Should.NotThrow(() => { this.configurationProvider.Provide(this.repoPath); }); private string SetupConfigFileContent(string text, string fileName, string path) { @@ -228,14 +225,11 @@ private string SetupConfigFileContent(string text, string fileName = null, strin return filePath; } - private static IServiceProvider GetServiceProvider(GitVersionOptions gitVersionOptions, ILog log = null) - { - return ConfigureServices(services => - { - if (log != null) services.AddSingleton(log); - services.AddSingleton(Options.Create(gitVersionOptions)); - }); - } + private static IServiceProvider GetServiceProvider(GitVersionOptions gitVersionOptions, ILog log = null) => ConfigureServices(services => + { + if (log != null) services.AddSingleton(log); + services.AddSingleton(Options.Create(gitVersionOptions)); + }); } } } diff --git a/src/GitVersion.Core.Tests/Configuration/Init/InitScenarios.cs b/src/GitVersion.Core.Tests/Configuration/Init/InitScenarios.cs index 4110704e45..a60ce34483 100644 --- a/src/GitVersion.Core.Tests/Configuration/Init/InitScenarios.cs +++ b/src/GitVersion.Core.Tests/Configuration/Init/InitScenarios.cs @@ -14,10 +14,7 @@ namespace GitVersion.Core.Tests.Init public class InitScenarios : TestBase { [SetUp] - public void Setup() - { - ShouldlyConfiguration.ShouldMatchApprovedDefaults.LocateTestMethodUsingAttribute(); - } + public void Setup() => ShouldlyConfiguration.ShouldMatchApprovedDefaults.LocateTestMethodUsingAttribute(); [Test] [Category(NoMono)] diff --git a/src/GitVersion.Core.Tests/Core/GitVersionExecutorTests.cs b/src/GitVersion.Core.Tests/Core/GitVersionExecutorTests.cs index ab1575e506..8058be4316 100644 --- a/src/GitVersion.Core.Tests/Core/GitVersionExecutorTests.cs +++ b/src/GitVersion.Core.Tests/Core/GitVersionExecutorTests.cs @@ -556,18 +556,15 @@ private IGitVersionCalculateTool GetGitVersionCalculator(GitVersionOptions gitVe return this.sp.GetService(); } - private static IServiceProvider GetServiceProvider(GitVersionOptions gitVersionOptions, ILog log = null, IGitRepository repository = null, IFileSystem fileSystem = null, IEnvironment environment = null) - { - return ConfigureServices(services => - { - if (log != null) services.AddSingleton(log); - if (fileSystem != null) services.AddSingleton(fileSystem); - if (repository != null) services.AddSingleton(repository); - if (environment != null) services.AddSingleton(environment); - var options = Options.Create(gitVersionOptions); - services.AddSingleton(options); - services.AddSingleton(RepositoryExtensions.ToGitRepositoryInfo(options)); - }); - } + private static IServiceProvider GetServiceProvider(GitVersionOptions gitVersionOptions, ILog log = null, IGitRepository repository = null, IFileSystem fileSystem = null, IEnvironment environment = null) => ConfigureServices(services => + { + if (log != null) services.AddSingleton(log); + if (fileSystem != null) services.AddSingleton(fileSystem); + if (repository != null) services.AddSingleton(repository); + if (environment != null) services.AddSingleton(environment); + var options = Options.Create(gitVersionOptions); + services.AddSingleton(options); + services.AddSingleton(RepositoryExtensions.ToGitRepositoryInfo(options)); + }); } } diff --git a/src/GitVersion.Core.Tests/Core/GitVersionToolDirectoryTests.cs b/src/GitVersion.Core.Tests/Core/GitVersionToolDirectoryTests.cs index ae79c3824e..1e38f6363a 100644 --- a/src/GitVersion.Core.Tests/Core/GitVersionToolDirectoryTests.cs +++ b/src/GitVersion.Core.Tests/Core/GitVersionToolDirectoryTests.cs @@ -24,10 +24,7 @@ public void SetUp() } [TearDown] - public void Cleanup() - { - Directory.Delete(this.workDirectory, true); - } + public void Cleanup() => Directory.Delete(this.workDirectory, true); [Test] public void FindsGitDirectory() diff --git a/src/GitVersion.Core.Tests/DocumentationTests.cs b/src/GitVersion.Core.Tests/DocumentationTests.cs index 695f7970ce..fcd79e53dc 100644 --- a/src/GitVersion.Core.Tests/DocumentationTests.cs +++ b/src/GitVersion.Core.Tests/DocumentationTests.cs @@ -17,10 +17,7 @@ public class DocumentationTests : TestBase private DirectoryInfo docsDirectory; [OneTimeSetUp] - public void OneTimeSetUp() - { - this.docsDirectory = GetDocsDirectory(); - } + public void OneTimeSetUp() => this.docsDirectory = GetDocsDirectory(); [Test] public void ConfigurationDocumentationIsUpToDate() diff --git a/src/GitVersion.Core.Tests/Extensions/GitToolsTestingExtensions.cs b/src/GitVersion.Core.Tests/Extensions/GitToolsTestingExtensions.cs index 5f072175ca..969f6d1826 100644 --- a/src/GitVersion.Core.Tests/Extensions/GitToolsTestingExtensions.cs +++ b/src/GitVersion.Core.Tests/Extensions/GitToolsTestingExtensions.cs @@ -52,20 +52,11 @@ public static IBranch CreateMockBranch(string name, params ICommit[] commits) return branch; } - public static IBranch FindBranch(this IGitRepository repository, string branchName) - { - return repository.Branches.FirstOrDefault(x => x.Name.WithoutRemote == branchName); - } + public static IBranch FindBranch(this IGitRepository repository, string branchName) => repository.Branches.FirstOrDefault(x => x.Name.WithoutRemote == branchName); - public static void DumpGraph(this IGitRepository repository, Action writer = null, int? maxCommits = null) - { - GitExtensions.DumpGraph(repository.Path, writer, maxCommits); - } + public static void DumpGraph(this IGitRepository repository, Action writer = null, int? maxCommits = null) => GitExtensions.DumpGraph(repository.Path, writer, maxCommits); - public static void DumpGraph(this IRepository repository, Action writer = null, int? maxCommits = null) - { - GitExtensions.DumpGraph(repository.ToGitRepository().Path, writer, maxCommits); - } + public static void DumpGraph(this IRepository repository, Action writer = null, int? maxCommits = null) => GitExtensions.DumpGraph(repository.ToGitRepository().Path, writer, maxCommits); public static VersionVariables GetVersion(this RepositoryFixtureBase fixture, Config configuration = null, IRepository repository = null, string commitId = null, bool onlyTrackedBranches = true, string branch = null) { diff --git a/src/GitVersion.Core.Tests/Extensions/StringFormatWithExtensionTests.cs b/src/GitVersion.Core.Tests/Extensions/StringFormatWithExtensionTests.cs index aca1708b4c..341ea533c7 100644 --- a/src/GitVersion.Core.Tests/Extensions/StringFormatWithExtensionTests.cs +++ b/src/GitVersion.Core.Tests/Extensions/StringFormatWithExtensionTests.cs @@ -11,10 +11,7 @@ public class StringFormatWithExtensionTests private IEnvironment environment; [SetUp] - public void Setup() - { - this.environment = new TestEnvironment(); - } + public void Setup() => this.environment = new TestEnvironment(); [Test] public void FormatWithNoTokens() diff --git a/src/GitVersion.Core.Tests/Helpers/DirectoryHelper.cs b/src/GitVersion.Core.Tests/Helpers/DirectoryHelper.cs index 61e8b51a2a..0e8656e749 100644 --- a/src/GitVersion.Core.Tests/Helpers/DirectoryHelper.cs +++ b/src/GitVersion.Core.Tests/Helpers/DirectoryHelper.cs @@ -26,10 +26,7 @@ public static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo targ } } - private static string Rename(string name) - { - return ToRename.ContainsKey(name) ? ToRename[name] : name; - } + private static string Rename(string name) => ToRename.ContainsKey(name) ? ToRename[name] : name; public static void DeleteSubDirectories(string parentPath) { diff --git a/src/GitVersion.Core.Tests/Helpers/GitVersionContextBuilder.cs b/src/GitVersion.Core.Tests/Helpers/GitVersionContextBuilder.cs index 39b0416fc1..8b4ad145b0 100644 --- a/src/GitVersion.Core.Tests/Helpers/GitVersionContextBuilder.cs +++ b/src/GitVersion.Core.Tests/Helpers/GitVersionContextBuilder.cs @@ -37,10 +37,7 @@ public GitVersionContextBuilder OverrideServices(Action over return this; } - public GitVersionContextBuilder WithDevelopBranch() - { - return WithBranch("develop"); - } + public GitVersionContextBuilder WithDevelopBranch() => WithBranch("develop"); private GitVersionContextBuilder WithBranch(string branchName) { diff --git a/src/GitVersion.Core.Tests/Helpers/PathHelper.cs b/src/GitVersion.Core.Tests/Helpers/PathHelper.cs index f5653b6e7b..9172d7b497 100644 --- a/src/GitVersion.Core.Tests/Helpers/PathHelper.cs +++ b/src/GitVersion.Core.Tests/Helpers/PathHelper.cs @@ -6,15 +6,9 @@ namespace GitVersion.Core.Tests.Helpers { public static class PathHelper { - public static string GetCurrentDirectory() - { - return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); - } + public static string GetCurrentDirectory() => Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); - public static string GetExecutable() - { - return RuntimeHelper.IsCoreClr() ? "dotnet" : Path.Combine(GetExeDirectory(), "gitversion.exe"); - } + public static string GetExecutable() => RuntimeHelper.IsCoreClr() ? "dotnet" : Path.Combine(GetExeDirectory(), "gitversion.exe"); public static string GetExecutableArgs(string args) { @@ -25,14 +19,8 @@ public static string GetExecutableArgs(string args) return args; } - public static string GetTempPath() - { - return Path.Combine(GetCurrentDirectory(), "TestRepositories", Guid.NewGuid().ToString()); - } + public static string GetTempPath() => Path.Combine(GetCurrentDirectory(), "TestRepositories", Guid.NewGuid().ToString()); - private static string GetExeDirectory() - { - return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)?.Replace("GitVersion.App.Tests", "GitVersion.App"); - } + private static string GetExeDirectory() => Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)?.Replace("GitVersion.App.Tests", "GitVersion.App"); } } diff --git a/src/GitVersion.Core.Tests/Helpers/RuntimeHelper.cs b/src/GitVersion.Core.Tests/Helpers/RuntimeHelper.cs index aa25bb957d..4d5e3d3fe1 100644 --- a/src/GitVersion.Core.Tests/Helpers/RuntimeHelper.cs +++ b/src/GitVersion.Core.Tests/Helpers/RuntimeHelper.cs @@ -13,7 +13,9 @@ public static bool IsCoreClr() || System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription.StartsWith(".NET Core"); return _isCoreClr.Value; #else +#pragma warning disable IDE0022 // Use expression body for methods // Cannot be set because of the pragma section return false; +#pragma warning restore IDE0022 // Use expression body for methods #endif } } diff --git a/src/GitVersion.Core.Tests/Helpers/TestConsole.cs b/src/GitVersion.Core.Tests/Helpers/TestConsole.cs index 760f87dca1..38886c09e8 100644 --- a/src/GitVersion.Core.Tests/Helpers/TestConsole.cs +++ b/src/GitVersion.Core.Tests/Helpers/TestConsole.cs @@ -15,30 +15,15 @@ public TestConsole(params string[] responses) this.responses = new Queue(responses); } - public void WriteLine(string msg) - { - this.log.Info(msg + System.Environment.NewLine); - } + public void WriteLine(string msg) => this.log.Info(msg + System.Environment.NewLine); - public void WriteLine() - { - this.log.Info(System.Environment.NewLine); - } + public void WriteLine() => this.log.Info(System.Environment.NewLine); - public void Write(string msg) - { - this.log.Info(msg); - } + public void Write(string msg) => this.log.Info(msg); - public string ReadLine() - { - return this.responses.Dequeue(); - } + public string ReadLine() => this.responses.Dequeue(); - public IDisposable UseColor(ConsoleColor consoleColor) - { - return new NoOpDisposable(); - } + public IDisposable UseColor(ConsoleColor consoleColor) => new NoOpDisposable(); private class NoOpDisposable : IDisposable { diff --git a/src/GitVersion.Core.Tests/Helpers/TestEnvironment.cs b/src/GitVersion.Core.Tests/Helpers/TestEnvironment.cs index fbe71657b2..37ad5651b2 100644 --- a/src/GitVersion.Core.Tests/Helpers/TestEnvironment.cs +++ b/src/GitVersion.Core.Tests/Helpers/TestEnvironment.cs @@ -11,14 +11,8 @@ public TestEnvironment() this.map = new Dictionary(); } - public string GetEnvironmentVariable(string variableName) - { - return this.map.TryGetValue(variableName, out var val) ? val : null; - } + public string GetEnvironmentVariable(string variableName) => this.map.TryGetValue(variableName, out var val) ? val : null; - public void SetEnvironmentVariable(string variableName, string value) - { - this.map[variableName] = value; - } + public void SetEnvironmentVariable(string variableName, string value) => this.map[variableName] = value; } } diff --git a/src/GitVersion.Core.Tests/Helpers/TestFileSystem.cs b/src/GitVersion.Core.Tests/Helpers/TestFileSystem.cs index 2ce1b2a739..4c487b9954 100644 --- a/src/GitVersion.Core.Tests/Helpers/TestFileSystem.cs +++ b/src/GitVersion.Core.Tests/Helpers/TestFileSystem.cs @@ -72,15 +72,9 @@ public void WriteAllText(string file, string fileContents, Encoding encoding) this.fileSystem[path] = encoding.GetBytes(fileContents); } - public IEnumerable DirectoryEnumerateFiles(string directory, string searchPattern, SearchOption searchOption) - { - throw new NotImplementedException(); - } + public IEnumerable DirectoryEnumerateFiles(string directory, string searchPattern, SearchOption searchOption) => throw new NotImplementedException(); - public Stream OpenWrite(string path) - { - return new TestStream(path, this); - } + public Stream OpenWrite(string path) => new TestStream(path, this); public Stream OpenRead(string file) { @@ -113,17 +107,11 @@ public bool DirectoryExists(string directory) return this.fileSystem.ContainsKey(path); } - public long GetLastDirectoryWrite(string path) - { - return 1; - } + public long GetLastDirectoryWrite(string path) => 1; - public bool PathsEqual(string path, string otherPath) - { - return string.Equals( + public bool PathsEqual(string path, string otherPath) => string.Equals( Path.GetFullPath(path).TrimEnd('\\').TrimEnd('/'), Path.GetFullPath(otherPath).TrimEnd('\\').TrimEnd('/'), StringComparerUtils.OsDependentComparison); - } } } diff --git a/src/GitVersion.Core.Tests/Helpers/TestLogAppender.cs b/src/GitVersion.Core.Tests/Helpers/TestLogAppender.cs index f5e38a9120..fb633abcc0 100644 --- a/src/GitVersion.Core.Tests/Helpers/TestLogAppender.cs +++ b/src/GitVersion.Core.Tests/Helpers/TestLogAppender.cs @@ -11,9 +11,6 @@ public TestLogAppender(Action logAction) { this.logAction = logAction; } - public void WriteTo(LogLevel level, string message) - { - this.logAction(message); - } + public void WriteTo(LogLevel level, string message) => this.logAction(message); } } diff --git a/src/GitVersion.Core.Tests/Helpers/TestStream.cs b/src/GitVersion.Core.Tests/Helpers/TestStream.cs index c92bfd750a..a1a5f550d9 100644 --- a/src/GitVersion.Core.Tests/Helpers/TestStream.cs +++ b/src/GitVersion.Core.Tests/Helpers/TestStream.cs @@ -27,25 +27,13 @@ public override void Flush() this.testFileSystem.WriteAllText(this.path, readToEnd); } - public override long Seek(long offset, SeekOrigin origin) - { - return this.underlying.Seek(offset, origin); - } + public override long Seek(long offset, SeekOrigin origin) => this.underlying.Seek(offset, origin); - public override void SetLength(long value) - { - this.underlying.SetLength(value); - } + public override void SetLength(long value) => this.underlying.SetLength(value); - public override int Read(byte[] buffer, int offset, int count) - { - return this.underlying.Read(buffer, offset, count); - } + public override int Read(byte[] buffer, int offset, int count) => this.underlying.Read(buffer, offset, count); - public override void Write(byte[] buffer, int offset, int count) - { - this.underlying.Write(buffer, offset, count); - } + public override void Write(byte[] buffer, int offset, int count) => this.underlying.Write(buffer, offset, count); public override bool CanRead => this.underlying.CanRead; public override bool CanSeek => this.underlying.CanSeek; diff --git a/src/GitVersion.Core.Tests/IntegrationTests/FileSystemTests.cs b/src/GitVersion.Core.Tests/IntegrationTests/FileSystemTests.cs index d2b3adff8b..34bf031aae 100644 --- a/src/GitVersion.Core.Tests/IntegrationTests/FileSystemTests.cs +++ b/src/GitVersion.Core.Tests/IntegrationTests/FileSystemTests.cs @@ -12,16 +12,10 @@ public class FileSystemTests : TestBase public string TempFilePath { get; set; } [SetUp] - public void CreateTempFile() - { - TempFilePath = Path.GetTempFileName(); - } + public void CreateTempFile() => TempFilePath = Path.GetTempFileName(); [TearDown] - public void Cleanup() - { - File.Delete(TempFilePath); - } + public void Cleanup() => File.Delete(TempFilePath); [TestCase("utf-32")] [TestCase("utf-32BE")] diff --git a/src/GitVersion.Core.Tests/Model/MergeMessageTests.cs b/src/GitVersion.Core.Tests/Model/MergeMessageTests.cs index 45e1d0a3dd..7164a1303b 100644 --- a/src/GitVersion.Core.Tests/Model/MergeMessageTests.cs +++ b/src/GitVersion.Core.Tests/Model/MergeMessageTests.cs @@ -13,11 +13,9 @@ public class MergeMessageTests : TestBase private readonly Config config = new Config { TagPrefix = "[vV]" }; [Test] - public void NullMessageStringThrows() - { + public void NullMessageStringThrows() => // Act / Assert Should.Throw(() => new MergeMessage(null, this.config)); - } [TestCase("")] [TestCase("\t\t ")] diff --git a/src/GitVersion.Core.Tests/VersionCalculation/BaseVersionCalculatorTests.cs b/src/GitVersion.Core.Tests/VersionCalculation/BaseVersionCalculatorTests.cs index b40cf31769..3c15a88b42 100644 --- a/src/GitVersion.Core.Tests/VersionCalculation/BaseVersionCalculatorTests.cs +++ b/src/GitVersion.Core.Tests/VersionCalculation/BaseVersionCalculatorTests.cs @@ -265,10 +265,7 @@ public TestVersionStrategy(params BaseVersion[] versions) this.versions = versions; } - public IEnumerable GetVersions() - { - return this.versions; - } + public IEnumerable GetVersions() => this.versions; } } } diff --git a/src/GitVersion.Core.Tests/VersionCalculation/JsonVersionBuilderTests.cs b/src/GitVersion.Core.Tests/VersionCalculation/JsonVersionBuilderTests.cs index e08f7c8f14..8dcdd65ec7 100644 --- a/src/GitVersion.Core.Tests/VersionCalculation/JsonVersionBuilderTests.cs +++ b/src/GitVersion.Core.Tests/VersionCalculation/JsonVersionBuilderTests.cs @@ -11,10 +11,7 @@ namespace GitVersion.Core.Tests public class JsonVersionBuilderTests : TestBase { [SetUp] - public void Setup() - { - ShouldlyConfiguration.ShouldMatchApprovedDefaults.LocateTestMethodUsingAttribute(); - } + public void Setup() => ShouldlyConfiguration.ShouldMatchApprovedDefaults.LocateTestMethodUsingAttribute(); [Test] [Category(NoMono)] diff --git a/src/GitVersion.Core.Tests/VersionCalculation/SemanticVersionTests.cs b/src/GitVersion.Core.Tests/VersionCalculation/SemanticVersionTests.cs index ef8a8f79c8..458ac9aada 100644 --- a/src/GitVersion.Core.Tests/VersionCalculation/SemanticVersionTests.cs +++ b/src/GitVersion.Core.Tests/VersionCalculation/SemanticVersionTests.cs @@ -58,10 +58,7 @@ public void ValidateVersionParsing( [TestCase("someText")] [TestCase("some-T-ext")] [TestCase("v.1.2.3", "v")] - public void ValidateInvalidVersionParsing(string versionString, string tagPrefixRegex = null) - { - Assert.IsFalse(SemanticVersion.TryParse(versionString, tagPrefixRegex, out _), "TryParse Result"); - } + public void ValidateInvalidVersionParsing(string versionString, string tagPrefixRegex = null) => Assert.IsFalse(SemanticVersion.TryParse(versionString, tagPrefixRegex, out _), "TryParse Result"); [Test] public void LegacySemVerTest() diff --git a/src/GitVersion.Core.Tests/VersionCalculation/ShaVersionFilterTests.cs b/src/GitVersion.Core.Tests/VersionCalculation/ShaVersionFilterTests.cs index bf0e215d86..01f862ce58 100644 --- a/src/GitVersion.Core.Tests/VersionCalculation/ShaVersionFilterTests.cs +++ b/src/GitVersion.Core.Tests/VersionCalculation/ShaVersionFilterTests.cs @@ -10,10 +10,7 @@ namespace GitVersion.Core.Tests public class ShaVersionFilterTests : TestBase { [Test] - public void VerifyNullGuard() - { - Should.Throw(() => new ShaVersionFilter(null)); - } + public void VerifyNullGuard() => Should.Throw(() => new ShaVersionFilter(null)); [Test] public void VerifyNullGuard2() diff --git a/src/GitVersion.Core.Tests/VersionCalculation/TestBaseVersionCalculator.cs b/src/GitVersion.Core.Tests/VersionCalculation/TestBaseVersionCalculator.cs index f91ea1c58e..315743b06e 100644 --- a/src/GitVersion.Core.Tests/VersionCalculation/TestBaseVersionCalculator.cs +++ b/src/GitVersion.Core.Tests/VersionCalculation/TestBaseVersionCalculator.cs @@ -15,9 +15,6 @@ public TestBaseVersionCalculator(bool shouldIncrement, SemanticVersion semanticV this.shouldIncrement = shouldIncrement; } - public BaseVersion GetBaseVersion() - { - return new BaseVersion("Test source", this.shouldIncrement, this.semanticVersion, this.source, null); - } + public BaseVersion GetBaseVersion() => new BaseVersion("Test source", this.shouldIncrement, this.semanticVersion, this.source, null); } } diff --git a/src/GitVersion.Core.Tests/VersionCalculation/TestMainlineVersionCalculator.cs b/src/GitVersion.Core.Tests/VersionCalculation/TestMainlineVersionCalculator.cs index 69e0af9ad9..ba9331a36f 100644 --- a/src/GitVersion.Core.Tests/VersionCalculation/TestMainlineVersionCalculator.cs +++ b/src/GitVersion.Core.Tests/VersionCalculation/TestMainlineVersionCalculator.cs @@ -11,14 +11,8 @@ public TestMainlineVersionCalculator(SemanticVersionBuildMetaData metaData) this.metaData = metaData; } - public SemanticVersion FindMainlineModeVersion(BaseVersion baseVersion) - { - throw new System.NotImplementedException(); - } + public SemanticVersion FindMainlineModeVersion(BaseVersion baseVersion) => throw new System.NotImplementedException(); - public SemanticVersionBuildMetaData CreateVersionBuildMetaData(ICommit baseVersionSource) - { - return this.metaData; - } + public SemanticVersionBuildMetaData CreateVersionBuildMetaData(ICommit baseVersionSource) => this.metaData; } } diff --git a/src/GitVersion.Core.Tests/VersionConverters/GitVersionInfoGeneratorTests.cs b/src/GitVersion.Core.Tests/VersionConverters/GitVersionInfoGeneratorTests.cs index 96163855da..2880a3cd2f 100644 --- a/src/GitVersion.Core.Tests/VersionConverters/GitVersionInfoGeneratorTests.cs +++ b/src/GitVersion.Core.Tests/VersionConverters/GitVersionInfoGeneratorTests.cs @@ -14,10 +14,7 @@ namespace GitVersion.Core.Tests public class GitVersionInfoGeneratorTests : TestBase { [SetUp] - public void Setup() - { - ShouldlyConfiguration.ShouldMatchApprovedDefaults.LocateTestMethodUsingAttribute(); - } + public void Setup() => ShouldlyConfiguration.ShouldMatchApprovedDefaults.LocateTestMethodUsingAttribute(); [TestCase("cs")] [TestCase("fs")] diff --git a/src/GitVersion.Core.Tests/VersionConverters/WixFileTests.cs b/src/GitVersion.Core.Tests/VersionConverters/WixFileTests.cs index c13d50a973..6a4e9d4e27 100644 --- a/src/GitVersion.Core.Tests/VersionConverters/WixFileTests.cs +++ b/src/GitVersion.Core.Tests/VersionConverters/WixFileTests.cs @@ -16,10 +16,7 @@ namespace GitVersion.Core.Tests internal class WixFileTests : TestBase { [SetUp] - public void Setup() - { - ShouldlyConfiguration.ShouldMatchApprovedDefaults.LocateTestMethodUsingAttribute(); - } + public void Setup() => ShouldlyConfiguration.ShouldMatchApprovedDefaults.LocateTestMethodUsingAttribute(); [Test] [Category(NoMono)] diff --git a/src/GitVersion.Core/BuildAgents/AzurePipelines.cs b/src/GitVersion.Core/BuildAgents/AzurePipelines.cs index 5bf8915558..a95066e345 100644 --- a/src/GitVersion.Core/BuildAgents/AzurePipelines.cs +++ b/src/GitVersion.Core/BuildAgents/AzurePipelines.cs @@ -17,19 +17,13 @@ public AzurePipelines(IEnvironment environment, ILog log) : base(environment, lo protected override string EnvironmentVariable { get; } = EnvironmentVariableName; - public override string[] GenerateSetParameterMessage(string name, string value) - { - return new[] + public override string[] GenerateSetParameterMessage(string name, string value) => new[] { $"##vso[task.setvariable variable=GitVersion.{name}]{value}", $"##vso[task.setvariable variable=GitVersion.{name};isOutput=true]{value}" }; - } - public override string? GetCurrentBranch(bool usingDynamicRepos) - { - return Environment.GetEnvironmentVariable("BUILD_SOURCEBRANCH"); - } + public override string? GetCurrentBranch(bool usingDynamicRepos) => Environment.GetEnvironmentVariable("BUILD_SOURCEBRANCH"); public override bool PreventFetch() => true; diff --git a/src/GitVersion.Core/BuildAgents/CodeBuild.cs b/src/GitVersion.Core/BuildAgents/CodeBuild.cs index 0ed1249e9e..aff2b156fd 100644 --- a/src/GitVersion.Core/BuildAgents/CodeBuild.cs +++ b/src/GitVersion.Core/BuildAgents/CodeBuild.cs @@ -17,25 +17,16 @@ public CodeBuild(IEnvironment environment, ILog log) : base(environment, log) WithPropertyFile("gitversion.properties"); } - public void WithPropertyFile(string propertiesFileName) - { - this.file = propertiesFileName; - } + public void WithPropertyFile(string propertiesFileName) => this.file = propertiesFileName; protected override string EnvironmentVariable => throw new NotSupportedException($"Accessing {nameof(EnvironmentVariable)} is not supported as {nameof(CodeBuild)} supports two environment variables for branch names."); - public override string GenerateSetVersionMessage(VersionVariables variables) - { - return variables.FullSemVer; - } + public override string GenerateSetVersionMessage(VersionVariables variables) => variables.FullSemVer; - public override string[] GenerateSetParameterMessage(string name, string value) - { - return new[] + public override string[] GenerateSetParameterMessage(string name, string value) => new[] { $"GitVersion_{name}={value}" }; - } public override string? GetCurrentBranch(bool usingDynamicRepos) { diff --git a/src/GitVersion.Core/BuildAgents/ContinuaCi.cs b/src/GitVersion.Core/BuildAgents/ContinuaCi.cs index 4f5703eacc..4654744ccc 100644 --- a/src/GitVersion.Core/BuildAgents/ContinuaCi.cs +++ b/src/GitVersion.Core/BuildAgents/ContinuaCi.cs @@ -13,18 +13,12 @@ public ContinuaCi(IEnvironment environment, ILog log) : base(environment, log) protected override string EnvironmentVariable { get; } = EnvironmentVariableName; - public override string[] GenerateSetParameterMessage(string name, string value) - { - return new[] + public override string[] GenerateSetParameterMessage(string name, string value) => new[] { $"@@continua[setVariable name='GitVersion_{name}' value='{value}' skipIfNotDefined='true']" }; - } - public override string GenerateSetVersionMessage(VersionVariables variables) - { - return $"@@continua[setBuildVersion value='{variables.FullSemVer}']"; - } + public override string GenerateSetVersionMessage(VersionVariables variables) => $"@@continua[setBuildVersion value='{variables.FullSemVer}']"; public override bool PreventFetch() => false; } diff --git a/src/GitVersion.Core/BuildAgents/Drone.cs b/src/GitVersion.Core/BuildAgents/Drone.cs index b1291d8fa8..b7ba2e8f67 100644 --- a/src/GitVersion.Core/BuildAgents/Drone.cs +++ b/src/GitVersion.Core/BuildAgents/Drone.cs @@ -13,23 +13,14 @@ public Drone(IEnvironment environment, ILog log) : base(environment, log) public const string EnvironmentVariableName = "DRONE"; protected override string EnvironmentVariable { get; } = EnvironmentVariableName; - public override bool CanApplyToCurrentContext() - { - return Environment.GetEnvironmentVariable(EnvironmentVariable)?.Equals("true", StringComparison.OrdinalIgnoreCase) ?? false; - } + public override bool CanApplyToCurrentContext() => Environment.GetEnvironmentVariable(EnvironmentVariable)?.Equals("true", StringComparison.OrdinalIgnoreCase) ?? false; - public override string GenerateSetVersionMessage(VersionVariables variables) - { - return variables.FullSemVer; - } + public override string GenerateSetVersionMessage(VersionVariables variables) => variables.FullSemVer; - public override string[] GenerateSetParameterMessage(string name, string value) - { - return new[] + public override string[] GenerateSetParameterMessage(string name, string value) => new[] { $"GitVersion_{name}={value}" }; - } public override string? GetCurrentBranch(bool usingDynamicRepos) { diff --git a/src/GitVersion.Core/BuildAgents/EnvRun.cs b/src/GitVersion.Core/BuildAgents/EnvRun.cs index 31ded8e5a6..201eabb076 100644 --- a/src/GitVersion.Core/BuildAgents/EnvRun.cs +++ b/src/GitVersion.Core/BuildAgents/EnvRun.cs @@ -30,18 +30,12 @@ public override bool CanApplyToCurrentContext() return false; } - public override string GenerateSetVersionMessage(VersionVariables variables) - { - return variables.FullSemVer; - } + public override string GenerateSetVersionMessage(VersionVariables variables) => variables.FullSemVer; - public override string[] GenerateSetParameterMessage(string name, string value) - { - return new[] + public override string[] GenerateSetParameterMessage(string name, string value) => new[] { $"@@envrun[set name='GitVersion_{name}' value='{value}']" }; - } public override bool PreventFetch() => true; } } diff --git a/src/GitVersion.Core/BuildAgents/GitHubActions.cs b/src/GitVersion.Core/BuildAgents/GitHubActions.cs index 1e5e4790d5..b84f59f24b 100644 --- a/src/GitVersion.Core/BuildAgents/GitHubActions.cs +++ b/src/GitVersion.Core/BuildAgents/GitHubActions.cs @@ -18,19 +18,15 @@ public GitHubActions(IEnvironment environment, ILog log) : base(environment, log protected override string EnvironmentVariable { get; } = EnvironmentVariableName; - public override string GenerateSetVersionMessage(VersionVariables variables) - { + public override string GenerateSetVersionMessage(VersionVariables variables) => // There is no equivalent function in GitHub Actions. - return string.Empty; - } + string.Empty; - public override string[] GenerateSetParameterMessage(string name, string value) - { + public override string[] GenerateSetParameterMessage(string name, string value) => // There is no equivalent function in GitHub Actions. - return new string[0]; - } + new string[0]; public override void WriteIntegration(System.Action writer, VersionVariables variables, bool updateBuildNumber = true) { @@ -65,10 +61,7 @@ public override void WriteIntegration(System.Action writer, VersionVari } } - public override string? GetCurrentBranch(bool usingDynamicRepos) - { - return Environment.GetEnvironmentVariable("GITHUB_REF"); - } + public override string? GetCurrentBranch(bool usingDynamicRepos) => Environment.GetEnvironmentVariable("GITHUB_REF"); public override bool PreventFetch() => true; } diff --git a/src/GitVersion.Core/BuildAgents/GitLabCi.cs b/src/GitVersion.Core/BuildAgents/GitLabCi.cs index dbe474b7ca..c367b4ccde 100644 --- a/src/GitVersion.Core/BuildAgents/GitLabCi.cs +++ b/src/GitVersion.Core/BuildAgents/GitLabCi.cs @@ -15,31 +15,19 @@ public GitLabCi(IEnvironment environment, ILog log) : base(environment, log) WithPropertyFile("gitversion.properties"); } - public void WithPropertyFile(string propertiesFileName) - { - this.file = propertiesFileName; - } + public void WithPropertyFile(string propertiesFileName) => this.file = propertiesFileName; protected override string EnvironmentVariable { get; } = EnvironmentVariableName; - public override string GenerateSetVersionMessage(VersionVariables variables) - { - return variables.FullSemVer; - } + public override string GenerateSetVersionMessage(VersionVariables variables) => variables.FullSemVer; - public override string[] GenerateSetParameterMessage(string name, string value) - { - return new[] + public override string[] GenerateSetParameterMessage(string name, string value) => new[] { $"GitVersion_{name}={value}" }; - } - public override string? GetCurrentBranch(bool usingDynamicRepos) - { - return Environment.GetEnvironmentVariable("CI_COMMIT_REF_NAME"); - } + public override string? GetCurrentBranch(bool usingDynamicRepos) => Environment.GetEnvironmentVariable("CI_COMMIT_REF_NAME"); public override bool PreventFetch() => true; @@ -50,9 +38,6 @@ public override void WriteIntegration(Action writer, VersionVariables v WriteVariablesFile(variables); } - private void WriteVariablesFile(VersionVariables variables) - { - File.WriteAllLines(this.file, GenerateBuildLogOutput(variables)); - } + private void WriteVariablesFile(VersionVariables variables) => File.WriteAllLines(this.file, GenerateBuildLogOutput(variables)); } } diff --git a/src/GitVersion.Core/BuildAgents/Jenkins.cs b/src/GitVersion.Core/BuildAgents/Jenkins.cs index 00803c7676..5e23bc63c9 100644 --- a/src/GitVersion.Core/BuildAgents/Jenkins.cs +++ b/src/GitVersion.Core/BuildAgents/Jenkins.cs @@ -17,35 +17,20 @@ public Jenkins(IEnvironment environment, ILog log) : base(environment, log) WithPropertyFile("gitversion.properties"); } - public void WithPropertyFile(string propertiesFileName) - { - this.file = propertiesFileName; - } + public void WithPropertyFile(string propertiesFileName) => this.file = propertiesFileName; - public override string GenerateSetVersionMessage(VersionVariables variables) - { - return variables.FullSemVer; - } + public override string GenerateSetVersionMessage(VersionVariables variables) => variables.FullSemVer; - public override string[] GenerateSetParameterMessage(string name, string value) - { - return new[] + public override string[] GenerateSetParameterMessage(string name, string value) => new[] { $"GitVersion_{name}={value}" }; - } - public override string? GetCurrentBranch(bool usingDynamicRepos) - { - return IsPipelineAsCode() + public override string? GetCurrentBranch(bool usingDynamicRepos) => IsPipelineAsCode() ? Environment.GetEnvironmentVariable("BRANCH_NAME") : Environment.GetEnvironmentVariable("GIT_LOCAL_BRANCH") ?? Environment.GetEnvironmentVariable("GIT_BRANCH"); - } - private bool IsPipelineAsCode() - { - return !Environment.GetEnvironmentVariable("BRANCH_NAME").IsNullOrEmpty(); - } + private bool IsPipelineAsCode() => !Environment.GetEnvironmentVariable("BRANCH_NAME").IsNullOrEmpty(); public override bool PreventFetch() => true; @@ -54,10 +39,7 @@ private bool IsPipelineAsCode() /// This should be cleaned up, so that normizaling the Git repo will not fail. /// /// - public override bool ShouldCleanUpRemotes() - { - return IsPipelineAsCode(); - } + public override bool ShouldCleanUpRemotes() => IsPipelineAsCode(); public override void WriteIntegration(Action writer, VersionVariables variables, bool updateBuildNumber = true) { @@ -66,9 +48,6 @@ public override void WriteIntegration(Action writer, VersionVariables v WriteVariablesFile(variables); } - private void WriteVariablesFile(VersionVariables variables) - { - File.WriteAllLines(this.file, GenerateBuildLogOutput(variables)); - } + private void WriteVariablesFile(VersionVariables variables) => File.WriteAllLines(this.file, GenerateBuildLogOutput(variables)); } } diff --git a/src/GitVersion.Core/BuildAgents/MyGet.cs b/src/GitVersion.Core/BuildAgents/MyGet.cs index 5dd9646f30..e90539631e 100644 --- a/src/GitVersion.Core/BuildAgents/MyGet.cs +++ b/src/GitVersion.Core/BuildAgents/MyGet.cs @@ -38,10 +38,7 @@ public override string[] GenerateSetParameterMessage(string name, string value) return messages.ToArray(); } - public override string? GenerateSetVersionMessage(VersionVariables variables) - { - return null; - } + public override string? GenerateSetVersionMessage(VersionVariables variables) => null; public override bool PreventFetch() => false; } diff --git a/src/GitVersion.Core/BuildAgents/SpaceAutomation.cs b/src/GitVersion.Core/BuildAgents/SpaceAutomation.cs index b5f3fedf1b..381b641bc9 100644 --- a/src/GitVersion.Core/BuildAgents/SpaceAutomation.cs +++ b/src/GitVersion.Core/BuildAgents/SpaceAutomation.cs @@ -13,19 +13,10 @@ public SpaceAutomation(IEnvironment environment, ILog log) : base(environment, l protected override string EnvironmentVariable { get; } = EnvironmentVariableName; - public override string? GetCurrentBranch(bool usingDynamicRepos) - { - return Environment.GetEnvironmentVariable("JB_SPACE_GIT_BRANCH"); - } + public override string? GetCurrentBranch(bool usingDynamicRepos) => Environment.GetEnvironmentVariable("JB_SPACE_GIT_BRANCH"); - public override string[] GenerateSetParameterMessage(string name, string value) - { - return new string[0]; - } + public override string[] GenerateSetParameterMessage(string name, string value) => new string[0]; - public override string GenerateSetVersionMessage(VersionVariables variables) - { - return string.Empty; - } + public override string GenerateSetVersionMessage(VersionVariables variables) => string.Empty; } } diff --git a/src/GitVersion.Core/BuildAgents/TeamCity.cs b/src/GitVersion.Core/BuildAgents/TeamCity.cs index 0852bb9fa3..e115bd36e8 100644 --- a/src/GitVersion.Core/BuildAgents/TeamCity.cs +++ b/src/GitVersion.Core/BuildAgents/TeamCity.cs @@ -32,31 +32,19 @@ public TeamCity(IEnvironment environment, ILog log) : base(environment, log) return branchName; } - private void WriteBranchEnvVariableWarning() - { - this.Log.Warning(@"TeamCity doesn't make the current branch available through environmental variables. + private void WriteBranchEnvVariableWarning() => this.Log.Warning(@"TeamCity doesn't make the current branch available through environmental variables. Depending on your authentication and transport setup of your git VCS root things may work. In that case, ignore this warning. In your TeamCity build configuration, add a parameter called `env.Git_Branch` with value %teamcity.build.vcs.branch.% See https://gitversion.net/docs/reference/build-servers/teamcity for more info"); - } - public override bool PreventFetch() - { - return !Environment.GetEnvironmentVariable("Git_Branch").IsNullOrEmpty(); - } + public override bool PreventFetch() => !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("Git_Branch")); - public override string[] GenerateSetParameterMessage(string name, string value) - { - return new[] + public override string[] GenerateSetParameterMessage(string name, string value) => new[] { $"##teamcity[setParameter name='GitVersion.{name}' value='{ServiceMessageEscapeHelper.EscapeValue(value)}']", $"##teamcity[setParameter name='system.GitVersion.{name}' value='{ServiceMessageEscapeHelper.EscapeValue(value)}']" }; - } - public override string GenerateSetVersionMessage(VersionVariables variables) - { - return $"##teamcity[buildNumber '{ServiceMessageEscapeHelper.EscapeValue(variables.FullSemVer)}']"; - } + public override string GenerateSetVersionMessage(VersionVariables variables) => $"##teamcity[buildNumber '{ServiceMessageEscapeHelper.EscapeValue(variables.FullSemVer)}']"; } } diff --git a/src/GitVersion.Core/BuildAgents/TravisCI.cs b/src/GitVersion.Core/BuildAgents/TravisCI.cs index 04186565eb..6f3b280e50 100644 --- a/src/GitVersion.Core/BuildAgents/TravisCI.cs +++ b/src/GitVersion.Core/BuildAgents/TravisCI.cs @@ -12,23 +12,14 @@ public TravisCi(IEnvironment environment, ILog log) : base(environment, log) public const string EnvironmentVariableName = "TRAVIS"; protected override string EnvironmentVariable { get; } = EnvironmentVariableName; - public override bool CanApplyToCurrentContext() - { - return "true".Equals(Environment.GetEnvironmentVariable(EnvironmentVariable)) && "true".Equals(Environment.GetEnvironmentVariable("CI")); - } + public override bool CanApplyToCurrentContext() => "true".Equals(Environment.GetEnvironmentVariable(EnvironmentVariable)) && "true".Equals(Environment.GetEnvironmentVariable("CI")); - public override string GenerateSetVersionMessage(VersionVariables variables) - { - return variables.FullSemVer; - } + public override string GenerateSetVersionMessage(VersionVariables variables) => variables.FullSemVer; - public override string[] GenerateSetParameterMessage(string name, string value) - { - return new[] + public override string[] GenerateSetParameterMessage(string name, string value) => new[] { $"GitVersion_{name}={value}" }; - } public override bool PreventFetch() => true; } diff --git a/src/GitVersion.Core/Configuration/ConfigExtensions.cs b/src/GitVersion.Core/Configuration/ConfigExtensions.cs index 1bb10b73bd..b2f6a6b836 100644 --- a/src/GitVersion.Core/Configuration/ConfigExtensions.cs +++ b/src/GitVersion.Core/Configuration/ConfigExtensions.cs @@ -141,11 +141,9 @@ public static string GetBranchSpecificTag(this EffectiveConfiguration configurat return tagToUse; } - public static List> GetReleaseBranchConfig(this Config configuration) - { - return configuration.Branches + public static List> GetReleaseBranchConfig(this Config configuration) => + configuration.Branches .Where(b => b.Value?.IsReleaseBranch == true) .ToList(); - } } } diff --git a/src/GitVersion.Core/Configuration/ConfigProvider.cs b/src/GitVersion.Core/Configuration/ConfigProvider.cs index 6a1c72ecaa..e7f6569a5c 100644 --- a/src/GitVersion.Core/Configuration/ConfigProvider.cs +++ b/src/GitVersion.Core/Configuration/ConfigProvider.cs @@ -37,13 +37,11 @@ public Config Provide(Config? overrideConfig = null) return Provide(rootDirectory, overrideConfig); } - public Config Provide(string? workingDirectory, Config? overrideConfig = null) - { - return new ConfigurationBuilder() - .Add(this.configFileLocator.ReadConfig(workingDirectory)) - .Add(overrideConfig ?? new Config()) - .Build(); - } + public Config Provide(string? workingDirectory, Config? overrideConfig = null) => + new ConfigurationBuilder() + .Add(this.configFileLocator.ReadConfig(workingDirectory)) + .Add(overrideConfig ?? new Config()) + .Build(); public void Init(string workingDirectory) { diff --git a/src/GitVersion.Core/Configuration/Init/BuildServer/AppVeyorSetup.cs b/src/GitVersion.Core/Configuration/Init/BuildServer/AppVeyorSetup.cs index 8fa540058a..28c4bb8531 100644 --- a/src/GitVersion.Core/Configuration/Init/BuildServer/AppVeyorSetup.cs +++ b/src/GitVersion.Core/Configuration/Init/BuildServer/AppVeyorSetup.cs @@ -48,19 +48,14 @@ protected override StepResult HandleResult(string? result, Queue visibility switch { - return visibility switch - { - ProjectVisibility.Public => " - ps: gitversion /l console /output buildserver /updateAssemblyInfo", - ProjectVisibility.Private => " - ps: gitversion $env:APPVEYOR_BUILD_FOLDER /l console /output buildserver /updateAssemblyInfo /nofetch /b $env:APPVEYOR_REPO_BRANCH", - _ => "" - }; - } + ProjectVisibility.Public => " - ps: gitversion /l console /output buildserver /updateAssemblyInfo", + ProjectVisibility.Private => " - ps: gitversion $env:APPVEYOR_BUILD_FOLDER /l console /output buildserver /updateAssemblyInfo /nofetch /b $env:APPVEYOR_REPO_BRANCH", + _ => "" + }; - private void GenerateBasicConfig(string workingDirectory) - { - WriteConfig(workingDirectory, this.FileSystem, $@"install: + private void GenerateBasicConfig(string workingDirectory) => WriteConfig(workingDirectory, this.FileSystem, $@"install: - choco install gitversion.portable -pre -y before_build: @@ -69,11 +64,8 @@ private void GenerateBasicConfig(string workingDirectory) build: project: "); - } - private void GenerateNuGetConfig(string workingDirectory) - { - WriteConfig(workingDirectory, this.FileSystem, $@"install: + private void GenerateNuGetConfig(string workingDirectory) => WriteConfig(workingDirectory, this.FileSystem, $@"install: - choco install gitversion.portable -pre -y assembly_info: @@ -90,7 +82,6 @@ private void GenerateNuGetConfig(string workingDirectory) - cmd: ECHO nuget pack \.nuspec -version ""%GitVersion_NuGetVersion%"" -prop ""target=%CONFIGURATION%"" - cmd: nuget pack \.nuspec -version ""%GitVersion_NuGetVersion%"" -prop ""target=%CONFIGURATION%"" - cmd: appveyor PushArtifact "".%GitVersion_NuGetVersion%.nupkg"""); - } private void WriteConfig(string workingDirectory, IFileSystem fileSystem, string configContents) { @@ -139,10 +130,7 @@ private string GetOutputFilename(string workingDirectory, IFileSystem fileSystem return Path.Combine(workingDirectory, "appveyor.yml"); } - private static bool AppVeyorConfigExists(string workingDirectory, IFileSystem fileSystem) - { - return fileSystem.Exists(Path.Combine(workingDirectory, "appveyor.yml")); - } + private static bool AppVeyorConfigExists(string workingDirectory, IFileSystem fileSystem) => fileSystem.Exists(Path.Combine(workingDirectory, "appveyor.yml")); protected override string DefaultResult => "0"; } diff --git a/src/GitVersion.Core/Configuration/Init/BuildServer/AppveyorPublicPrivate.cs b/src/GitVersion.Core/Configuration/Init/BuildServer/AppveyorPublicPrivate.cs index 3faa30e09f..108bff8641 100644 --- a/src/GitVersion.Core/Configuration/Init/BuildServer/AppveyorPublicPrivate.cs +++ b/src/GitVersion.Core/Configuration/Init/BuildServer/AppveyorPublicPrivate.cs @@ -28,16 +28,13 @@ protected override StepResult HandleResult(string? result, Queue @"Is your project public or private? That is ... does it require authentication to clone/pull? 0) Go Back 1) Public 2) Private"; - } protected override string DefaultResult => "0"; } diff --git a/src/GitVersion.Core/Configuration/Init/BuildServer/SetupBuildScripts.cs b/src/GitVersion.Core/Configuration/Init/BuildServer/SetupBuildScripts.cs index 3746466cad..6f8db2a1f2 100644 --- a/src/GitVersion.Core/Configuration/Init/BuildServer/SetupBuildScripts.cs +++ b/src/GitVersion.Core/Configuration/Init/BuildServer/SetupBuildScripts.cs @@ -25,15 +25,12 @@ protected override StepResult HandleResult(string? result, Queue @"What build server are you using? Want to see more? Contribute a pull request! 0) Go Back 1) AppVeyor"; - } protected override string DefaultResult => "0"; } diff --git a/src/GitVersion.Core/Configuration/Init/EditConfigStep.cs b/src/GitVersion.Core/Configuration/Init/EditConfigStep.cs index 6083df91c2..f7ac50d880 100644 --- a/src/GitVersion.Core/Configuration/Init/EditConfigStep.cs +++ b/src/GitVersion.Core/Configuration/Init/EditConfigStep.cs @@ -47,9 +47,7 @@ protected override StepResult HandleResult(string? result, Queue $@"Which would you like to change? 0) Save changes and exit 1) Exit without saving @@ -61,7 +59,6 @@ protected override string GetPrompt(Config config, string workingDirectory) 5) Branch Increment mode (per commit/after tag) (Current: {config.VersioningMode}) 6) Assembly versioning scheme (Current: {config.AssemblyVersioningScheme}) 7) Setup build scripts"; - } protected override string? DefaultResult => null; } diff --git a/src/GitVersion.Core/Configuration/Init/SetConfig/AssemblyVersioningSchemeSetting.cs b/src/GitVersion.Core/Configuration/Init/SetConfig/AssemblyVersioningSchemeSetting.cs index 92cb619f6d..d9177e15c0 100644 --- a/src/GitVersion.Core/Configuration/Init/SetConfig/AssemblyVersioningSchemeSetting.cs +++ b/src/GitVersion.Core/Configuration/Init/SetConfig/AssemblyVersioningSchemeSetting.cs @@ -45,9 +45,7 @@ protected override StepResult HandleResult(string? result, Queue @"What assembly versioning scheme do you want to use: 0) Go Back 1) Major.0.0.0 @@ -56,8 +54,6 @@ protected override string GetPrompt(Config config, string workingDirectory) 4) Major.Minor.Patch.TagCount (Allows different pre-release tags to cause assembly version to change) 5) None (skip's updating AssemblyVersion)"; - } - protected override string DefaultResult => "0"; } } diff --git a/src/GitVersion.Core/Configuration/Init/SetConfig/ConfigureBranch.cs b/src/GitVersion.Core/Configuration/Init/SetConfig/ConfigureBranch.cs index 7041760740..21231b72c2 100644 --- a/src/GitVersion.Core/Configuration/Init/SetConfig/ConfigureBranch.cs +++ b/src/GitVersion.Core/Configuration/Init/SetConfig/ConfigureBranch.cs @@ -39,14 +39,11 @@ protected override StepResult HandleResult(string? result, Queue $@"What would you like to change for '{this.name}': 0) Go Back 1) Branch Pre-release tag (Current: {this.branchConfig!.Tag}) 2) Branch Increment mode (per commit/after tag) (Current: {this.branchConfig.VersioningMode})"; - } protected override string DefaultResult => "0"; } diff --git a/src/GitVersion.Core/Configuration/Init/SetConfig/ConfigureBranches.cs b/src/GitVersion.Core/Configuration/Init/SetConfig/ConfigureBranches.cs index 3e2801b72b..653fcc02b2 100644 --- a/src/GitVersion.Core/Configuration/Init/SetConfig/ConfigureBranches.cs +++ b/src/GitVersion.Core/Configuration/Init/SetConfig/ConfigureBranches.cs @@ -42,13 +42,10 @@ protected override StepResult HandleResult(string? result, Queue @"Which branch would you like to configure: 0) Go Back " + string.Join(System.Environment.NewLine, OrderedBranches(config).Select((c, i) => $"{i + 1}) {c.Key}")); - } private static IOrderedEnumerable> OrderedBranches(Config config) { diff --git a/src/GitVersion.Core/Configuration/Init/SetConfig/GlobalModeSetting.cs b/src/GitVersion.Core/Configuration/Init/SetConfig/GlobalModeSetting.cs index 72773d55a9..e27f0b652b 100644 --- a/src/GitVersion.Core/Configuration/Init/SetConfig/GlobalModeSetting.cs +++ b/src/GitVersion.Core/Configuration/Init/SetConfig/GlobalModeSetting.cs @@ -48,15 +48,12 @@ protected override StepResult HandleResult(string? result, Queue $@"What do you want the default increment mode to be (can be overriden per branch): {(!this.isPartOfWizard ? "0) Go Back" : string.Empty)} 1) Follow SemVer and only increment when a release has been tagged (continuous delivery mode) 2) Increment based on branch config every commit (continuous deployment mode) 3) Each merged branch against main will increment the version (mainline mode) {(this.isPartOfWizard ? "4) Skip" : string.Empty)}"; - } protected override string DefaultResult => "4"; } diff --git a/src/GitVersion.Core/Configuration/Init/SetConfig/SetBranchIncrementMode.cs b/src/GitVersion.Core/Configuration/Init/SetConfig/SetBranchIncrementMode.cs index e84fea2618..6f88b61c12 100644 --- a/src/GitVersion.Core/Configuration/Init/SetConfig/SetBranchIncrementMode.cs +++ b/src/GitVersion.Core/Configuration/Init/SetConfig/SetBranchIncrementMode.cs @@ -44,14 +44,11 @@ protected override StepResult HandleResult(string? result, Queue $@"What do you want the increment mode for {this.name} to be? 0) Go Back 1) Follow SemVer and only increment when a release has been tagged (continuous delivery mode) 2) Increment based on branch config every commit (continuous deployment mode)"; - } protected override string DefaultResult => "0"; } diff --git a/src/GitVersion.Core/Configuration/Init/SetConfig/SetBranchTag.cs b/src/GitVersion.Core/Configuration/Init/SetConfig/SetBranchTag.cs index 3502114e07..1f6b71fb53 100644 --- a/src/GitVersion.Core/Configuration/Init/SetConfig/SetBranchTag.cs +++ b/src/GitVersion.Core/Configuration/Init/SetConfig/SetBranchTag.cs @@ -46,15 +46,12 @@ protected override StepResult HandleResult(string? result, Queue @"This sets the pre-release tag which will be used for versions on this branch (beta, rc etc) 0) Go Back 1) No tag Anything else will be used as the tag"; - } protected override string DefaultResult => "0"; } diff --git a/src/GitVersion.Core/Configuration/Init/SetNextVersion.cs b/src/GitVersion.Core/Configuration/Init/SetNextVersion.cs index a9274fbd59..f19d5b7db5 100644 --- a/src/GitVersion.Core/Configuration/Init/SetNextVersion.cs +++ b/src/GitVersion.Core/Configuration/Init/SetNextVersion.cs @@ -29,10 +29,7 @@ protected override StepResult HandleResult(string? result, Queue @"What would you like to set the next version to (enter nothing to cancel)?"; protected override string? DefaultResult => null; } diff --git a/src/GitVersion.Core/Configuration/Init/StepResult.cs b/src/GitVersion.Core/Configuration/Init/StepResult.cs index da3c19b3dc..faa3f6c63f 100644 --- a/src/GitVersion.Core/Configuration/Init/StepResult.cs +++ b/src/GitVersion.Core/Configuration/Init/StepResult.cs @@ -4,36 +4,24 @@ public class StepResult { private StepResult() { } - public static StepResult Ok() - { - return new StepResult(); - } + public static StepResult Ok() => new StepResult(); - public static StepResult InvalidResponseSelected() + public static StepResult InvalidResponseSelected() => new StepResult { - return new StepResult - { - InvalidResponse = true - }; - } + InvalidResponse = true + }; - public static StepResult SaveAndExit() + public static StepResult SaveAndExit() => new StepResult { - return new StepResult - { - Save = true, - Exit = true - }; - } + Save = true, + Exit = true + }; - public static StepResult ExitWithoutSaving() + public static StepResult ExitWithoutSaving() => new StepResult { - return new StepResult - { - Save = false, - Exit = true - }; - } + Save = false, + Exit = true + }; public bool Exit { get; private set; } diff --git a/src/GitVersion.Core/Configuration/Init/Wizard/FinishedSetupStep.cs b/src/GitVersion.Core/Configuration/Init/Wizard/FinishedSetupStep.cs index 2fa4a1303a..4ecb14e72e 100644 --- a/src/GitVersion.Core/Configuration/Init/Wizard/FinishedSetupStep.cs +++ b/src/GitVersion.Core/Configuration/Init/Wizard/FinishedSetupStep.cs @@ -9,9 +9,6 @@ public FinishedSetupStep(IConsole console, IFileSystem fileSystem, ILog log, ICo { } - protected override string GetPrompt(Config config, string workingDirectory) - { - return $"Questions are all done, you can now edit GitVersion's configuration further{System.Environment.NewLine}" + base.GetPrompt(config, workingDirectory); - } + protected override string GetPrompt(Config config, string workingDirectory) => $"Questions are all done, you can now edit GitVersion's configuration further{System.Environment.NewLine}" + base.GetPrompt(config, workingDirectory); } } diff --git a/src/GitVersion.Core/Configuration/Init/Wizard/GitFlowSetupStep.cs b/src/GitVersion.Core/Configuration/Init/Wizard/GitFlowSetupStep.cs index c6fcb27f8b..8e3d8f4d62 100644 --- a/src/GitVersion.Core/Configuration/Init/Wizard/GitFlowSetupStep.cs +++ b/src/GitVersion.Core/Configuration/Init/Wizard/GitFlowSetupStep.cs @@ -10,10 +10,7 @@ public GitFlowSetupStep(IConsole console, IFileSystem fileSystem, ILog log, ICon { } - protected override string GetPrompt(Config config, string workingDirectory) - { - return $"By default GitVersion will only increment the version of the 'develop' branch every commit, all other branches will increment when tagged{System.Environment.NewLine}{System.Environment.NewLine}" + + protected override string GetPrompt(Config config, string workingDirectory) => $"By default GitVersion will only increment the version of the 'develop' branch every commit, all other branches will increment when tagged{System.Environment.NewLine}{System.Environment.NewLine}" + base.GetPrompt(config, workingDirectory); - } } } diff --git a/src/GitVersion.Core/Configuration/Init/Wizard/GitHubFlowStep.cs b/src/GitVersion.Core/Configuration/Init/Wizard/GitHubFlowStep.cs index e3e96299ec..405eca826a 100644 --- a/src/GitVersion.Core/Configuration/Init/Wizard/GitHubFlowStep.cs +++ b/src/GitVersion.Core/Configuration/Init/Wizard/GitHubFlowStep.cs @@ -10,9 +10,6 @@ public GitHubFlowStep(IConsole console, IFileSystem fileSystem, ILog log, IConfi { } - protected override string GetPrompt(Config config, string workingDirectory) - { - return $"By default GitVersion will only increment the version when tagged{System.Environment.NewLine}{System.Environment.NewLine}" + base.GetPrompt(config, workingDirectory); - } + protected override string GetPrompt(Config config, string workingDirectory) => $"By default GitVersion will only increment the version when tagged{System.Environment.NewLine}{System.Environment.NewLine}" + base.GetPrompt(config, workingDirectory); } } diff --git a/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy1Step.cs b/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy1Step.cs index 1414c193ee..e6abe30403 100644 --- a/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy1Step.cs +++ b/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy1Step.cs @@ -28,12 +28,9 @@ protected override StepResult HandleResult(string? result, Queue @"GitVersion can try to recommend you a branching strategy based on a few questions. Do you need to maintain multiple versions of your application simultaneously in production? (y/n)"; - } protected override string? DefaultResult => null; } diff --git a/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy2Step.cs b/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy2Step.cs index 05115e3f87..e142fd0f1d 100644 --- a/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy2Step.cs +++ b/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy2Step.cs @@ -31,10 +31,7 @@ protected override StepResult HandleResult(string? result, Queue "Do you stabilise releases while continuing work on the next version? (y/n)"; protected override string? DefaultResult => null; } diff --git a/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy3Step.cs b/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy3Step.cs index 4bd0388044..d9a70d4432 100644 --- a/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy3Step.cs +++ b/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategy3Step.cs @@ -32,10 +32,7 @@ protected override StepResult HandleResult(string? result, Queue "Do you need to build nightlies or consume packages the CI build creates without releasing those versions? (y/n)"; protected override string? DefaultResult => null; } diff --git a/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategyStep.cs b/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategyStep.cs index 93393c95d3..fb2191d882 100644 --- a/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategyStep.cs +++ b/src/GitVersion.Core/Configuration/Init/Wizard/PickBranchingStrategyStep.cs @@ -31,14 +31,11 @@ protected override StepResult HandleResult(string? result, Queue @"The way you will use GitVersion will change a lot based on your branching strategy. What branching strategy will you be using: 1) GitFlow (or similar) 2) GitHubFlow 3) Unsure, tell me more"; - } protected override string? DefaultResult => null; } diff --git a/src/GitVersion.Core/Core/Environment.cs b/src/GitVersion.Core/Core/Environment.cs index 5e91f2be91..520b741338 100644 --- a/src/GitVersion.Core/Core/Environment.cs +++ b/src/GitVersion.Core/Core/Environment.cs @@ -2,14 +2,8 @@ namespace GitVersion { public class Environment : IEnvironment { - public string? GetEnvironmentVariable(string variableName) - { - return System.Environment.GetEnvironmentVariable(variableName); - } + public string? GetEnvironmentVariable(string variableName) => System.Environment.GetEnvironmentVariable(variableName); - public void SetEnvironmentVariable(string variableName, string value) - { - System.Environment.SetEnvironmentVariable(variableName, value); - } + public void SetEnvironmentVariable(string variableName, string value) => System.Environment.SetEnvironmentVariable(variableName, value); } } diff --git a/src/GitVersion.Core/Core/FileSystem.cs b/src/GitVersion.Core/Core/FileSystem.cs index 5b0a092992..0a909f0b57 100644 --- a/src/GitVersion.Core/Core/FileSystem.cs +++ b/src/GitVersion.Core/Core/FileSystem.cs @@ -8,30 +8,15 @@ namespace GitVersion { public class FileSystem : IFileSystem { - public void Copy(string from, string to, bool overwrite) - { - File.Copy(from, to, overwrite); - } + public void Copy(string from, string to, bool overwrite) => File.Copy(from, to, overwrite); - public void Move(string from, string to) - { - File.Move(from, to); - } + public void Move(string from, string to) => File.Move(from, to); - public bool Exists(string file) - { - return File.Exists(file); - } + public bool Exists(string file) => File.Exists(file); - public void Delete(string path) - { - File.Delete(path); - } + public void Delete(string path) => File.Delete(path); - public string ReadAllText(string path) - { - return File.ReadAllText(path); - } + public string ReadAllText(string path) => File.ReadAllText(path); public void WriteAllText(string? file, string fileContents) { @@ -41,52 +26,31 @@ public void WriteAllText(string? file, string fileContents) WriteAllText(file, fileContents, encoding); } - public void WriteAllText(string? file, string fileContents, Encoding encoding) - { + public void WriteAllText(string? file, string fileContents, Encoding encoding) => File.WriteAllText(file, fileContents, encoding); - } - public IEnumerable DirectoryEnumerateFiles(string? directory, string searchPattern, SearchOption searchOption) - { - return Directory.EnumerateFiles(directory, searchPattern, searchOption); - } + public IEnumerable DirectoryEnumerateFiles(string? directory, string searchPattern, SearchOption searchOption) => + Directory.EnumerateFiles(directory, searchPattern, searchOption); - public Stream OpenWrite(string path) - { - return File.OpenWrite(path); - } + public Stream OpenWrite(string path) => File.OpenWrite(path); - public Stream OpenRead(string path) - { - return File.OpenRead(path); - } + public Stream OpenRead(string path) => File.OpenRead(path); - public void CreateDirectory(string path) - { - Directory.CreateDirectory(path); - } + public void CreateDirectory(string path) => Directory.CreateDirectory(path); - public bool DirectoryExists(string path) - { - return Directory.Exists(path); - } + public bool DirectoryExists(string path) => Directory.Exists(path); - public long GetLastDirectoryWrite(string path) - { - return new DirectoryInfo(path) + public long GetLastDirectoryWrite(string path) => new DirectoryInfo(path) .GetDirectories("*.*", SearchOption.AllDirectories) .Select(d => d.LastWriteTimeUtc) .DefaultIfEmpty() .Max() .Ticks; - } - public bool PathsEqual(string? path, string? otherPath) - { - return string.Equals( + public bool PathsEqual(string? path, string? otherPath) => + string.Equals( Path.GetFullPath(path).TrimEnd('\\').TrimEnd('/'), Path.GetFullPath(otherPath).TrimEnd('\\').TrimEnd('/'), StringComparerUtils.OsDependentComparison); - } } } diff --git a/src/GitVersion.Core/Core/GitPreparer.cs b/src/GitVersion.Core/Core/GitPreparer.cs index cebd646909..d6170796c0 100644 --- a/src/GitVersion.Core/Core/GitPreparer.cs +++ b/src/GitVersion.Core/Core/GitPreparer.cs @@ -392,9 +392,6 @@ public void EnsureLocalBranchExistsForCurrentBranch(IRemote? remote, string? cur Checkout(localCanonicalName); } - private void Checkout(string commitOrBranchSpec) - { - this.retryAction.Execute(() => this.repository.Checkout(commitOrBranchSpec)); - } + private void Checkout(string commitOrBranchSpec) => this.retryAction.Execute(() => this.repository.Checkout(commitOrBranchSpec)); } } diff --git a/src/GitVersion.Core/Core/RepositoryStore.cs b/src/GitVersion.Core/Core/RepositoryStore.cs index fe4dfb3fba..3ee8dcf3bf 100644 --- a/src/GitVersion.Core/Core/RepositoryStore.cs +++ b/src/GitVersion.Core/Core/RepositoryStore.cs @@ -211,31 +211,20 @@ public IBranch GetChosenBranch(Config configuration) return chosenBranch; } - public IEnumerable GetBranchesForCommit(ICommit commit) - { - return this.repository.Branches.Where(b => !b.IsRemote && Equals(b.Tip, commit)).ToList(); - } + public IEnumerable GetBranchesForCommit(ICommit commit) => this.repository.Branches.Where(b => !b.IsRemote && Equals(b.Tip, commit)).ToList(); - public IEnumerable GetExcludedInheritBranches(Config configuration) - { - return this.repository.Branches.Where(b => - { - var branchConfig = configuration.GetConfigForBranch(b.Name.WithoutRemote); + public IEnumerable GetExcludedInheritBranches(Config configuration) => this.repository.Branches.Where(b => + { + var branchConfig = configuration.GetConfigForBranch(b.Name.WithoutRemote); - return branchConfig == null || branchConfig.Increment == IncrementStrategy.Inherit; - }).ToList(); - } + return branchConfig == null || branchConfig.Increment == IncrementStrategy.Inherit; + }).ToList(); - public IEnumerable GetReleaseBranches(IEnumerable>? releaseBranchConfig) - { - return this.repository.Branches + public IEnumerable GetReleaseBranches(IEnumerable>? releaseBranchConfig) => + this.repository.Branches .Where(b => releaseBranchConfig?.Any(c => Regex.IsMatch(b.Name.Friendly, c.Value?.Regex)) == true); - } - public IEnumerable ExcludingBranches(IEnumerable branchesToExclude) - { - return this.repository.Branches.ExcludeBranches(branchesToExclude); - } + public IEnumerable ExcludingBranches(IEnumerable branchesToExclude) => this.repository.Branches.ExcludeBranches(branchesToExclude); // TODO Should we cache this? public IEnumerable GetBranchesContainingCommit(ICommit? commit, IEnumerable? branches = null, bool onlyTrackedBranches = false) @@ -298,9 +287,8 @@ static IEnumerable InnerGetBranchesContainingCommit(ICommit commit, IEn } } - public Dictionary> GetMainlineBranches(ICommit commit, IEnumerable>? mainlineBranchConfigs) - { - return this.repository.Branches + public Dictionary> GetMainlineBranches(ICommit commit, IEnumerable>? mainlineBranchConfigs) => + this.repository.Branches .Where(b => mainlineBranchConfigs?.Any(c => Regex.IsMatch(b.Name.Friendly, c.Value?.Regex)) == true) .Select(b => new { @@ -310,7 +298,6 @@ public Dictionary> GetMainlineBranches(ICommit commit, IEn .Where(a => a.MergeBase != null) .GroupBy(b => b.MergeBase.Sha, b => b.Branch) .ToDictionary(b => b.Key, b => b.ToList()); - } /// /// Find the commit where the given branch was branched from another branch. @@ -348,9 +335,8 @@ public BranchCommit FindCommitBranchWasBranchedFrom(IBranch branch, Config confi } } - public SemanticVersion GetCurrentCommitTaggedVersion(ICommit? commit, EffectiveConfiguration config) - { - return this.repository.Tags + public SemanticVersion GetCurrentCommitTaggedVersion(ICommit? commit, EffectiveConfiguration config) => + this.repository.Tags .SelectMany(t => { var targetCommit = t.PeeledTargetCommit(); @@ -362,7 +348,6 @@ public SemanticVersion GetCurrentCommitTaggedVersion(ICommit? commit, EffectiveC return new SemanticVersion[0]; }) .Max(); - } public SemanticVersion MaybeIncrement(BaseVersion baseVersion, GitVersionContext context) { @@ -426,10 +411,7 @@ public IEnumerable GetCommitLog(ICommit? baseVersionSource, ICommit? cu return this.repository.Commits.QueryBy(filter); } - public VersionField? DetermineIncrementedField(BaseVersion baseVersion, GitVersionContext context) - { - return IncrementStrategyFinder.DetermineIncrementedField(this.repository, context, baseVersion); - } + public VersionField? DetermineIncrementedField(BaseVersion baseVersion, GitVersionContext context) => IncrementStrategyFinder.DetermineIncrementedField(this.repository, context, baseVersion); public bool IsCommitOnBranch(ICommit? baseVersionSource, IBranch branch, ICommit firstMatchingCommit) { diff --git a/src/GitVersion.Core/Extensions/AssemblyVersionsGeneratorExtensions.cs b/src/GitVersion.Core/Extensions/AssemblyVersionsGeneratorExtensions.cs index 77ab7f9464..3c00b1a56c 100644 --- a/src/GitVersion.Core/Extensions/AssemblyVersionsGeneratorExtensions.cs +++ b/src/GitVersion.Core/Extensions/AssemblyVersionsGeneratorExtensions.cs @@ -22,22 +22,19 @@ public enum AssemblyVersioningScheme public static class AssemblyVersionsGeneratorExtensions { - public static string? GetAssemblyVersion(this SemanticVersion sv, AssemblyVersioningScheme scheme) - { - return scheme switch + public static string? GetAssemblyVersion(this SemanticVersion sv, AssemblyVersioningScheme scheme) => + scheme switch { AssemblyVersioningScheme.Major => $"{sv.Major}.0.0.0", AssemblyVersioningScheme.MajorMinor => $"{sv.Major}.{sv.Minor}.0.0", AssemblyVersioningScheme.MajorMinorPatch => $"{sv.Major}.{sv.Minor}.{sv.Patch}.0", - AssemblyVersioningScheme.MajorMinorPatchTag => $"{sv.Major}.{sv.Minor}.{sv.Patch}.{sv.PreReleaseTag?.Number ?? 0}", + AssemblyVersioningScheme.MajorMinorPatchTag => $"{sv.Major}.{sv.Minor}.{sv.Patch}.{sv.PreReleaseTag.Number ?? 0}", AssemblyVersioningScheme.None => null, _ => throw new ArgumentException($"Unexpected value ({scheme}).", nameof(scheme)) }; - } - public static string? GetAssemblyFileVersion(this SemanticVersion sv, AssemblyFileVersioningScheme scheme) - { - return scheme switch + public static string? GetAssemblyFileVersion(this SemanticVersion sv, AssemblyFileVersioningScheme scheme) => + scheme switch { AssemblyFileVersioningScheme.Major => $"{sv.Major}.0.0.0", AssemblyFileVersioningScheme.MajorMinor => $"{sv.Major}.{sv.Minor}.0.0", @@ -46,6 +43,5 @@ public static class AssemblyVersionsGeneratorExtensions AssemblyFileVersioningScheme.None => null, _ => throw new ArgumentException($"Unexpected value ({scheme}).", nameof(scheme)) }; - } } } diff --git a/src/GitVersion.Core/Extensions/ServiceCollectionExtensions.cs b/src/GitVersion.Core/Extensions/ServiceCollectionExtensions.cs index 499dad18a9..3d37aebd33 100644 --- a/src/GitVersion.Core/Extensions/ServiceCollectionExtensions.cs +++ b/src/GitVersion.Core/Extensions/ServiceCollectionExtensions.cs @@ -12,9 +12,7 @@ public static IServiceCollection AddModule(this IServiceCollection serviceCollec return serviceCollection; } - public static TService GetServiceForType(this IServiceProvider serviceProvider) - { - return serviceProvider.GetServices().SingleOrDefault(t => t?.GetType() == typeof(TType)); - } + public static TService GetServiceForType(this IServiceProvider serviceProvider) => + serviceProvider.GetServices().SingleOrDefault(t => t?.GetType() == typeof(TType)); } } diff --git a/src/GitVersion.Core/Extensions/StringExtensions.cs b/src/GitVersion.Core/Extensions/StringExtensions.cs index ab691c68b8..749be269d6 100644 --- a/src/GitVersion.Core/Extensions/StringExtensions.cs +++ b/src/GitVersion.Core/Extensions/StringExtensions.cs @@ -28,15 +28,9 @@ static StringExtensions() }; } - public static bool IsTrue(this string value) - { - return Trues.Contains(value, StringComparer.OrdinalIgnoreCase); - } + public static bool IsTrue(this string value) => Trues.Contains(value, StringComparer.OrdinalIgnoreCase); - public static bool IsFalse(this string value) - { - return Falses.Contains(value, StringComparer.OrdinalIgnoreCase); - } + public static bool IsFalse(this string value) => Falses.Contains(value, StringComparer.OrdinalIgnoreCase); public static bool IsValidPath(this string path) { @@ -64,12 +58,9 @@ public static bool IsValidPath(this string path) return Directory.Exists(path); } - public static bool IsSwitchArgument(this string value) - { - return value != null + public static bool IsSwitchArgument(this string value) => value != null && (value.StartsWith("-") || value.StartsWith("/")) && !Regex.Match(value, @"/\w+:").Success; //Exclude msbuild & project parameters in form /blah:, which should be parsed as values, not switch names. - } public static bool IsSwitch(this string value, string switchName) { @@ -89,15 +80,9 @@ public static bool IsSwitch(this string value, string switchName) return string.Equals(switchName, value, StringComparison.OrdinalIgnoreCase); } - public static bool IsInit(this string singleArgument) - { - return singleArgument.Equals("init", StringComparison.OrdinalIgnoreCase); - } + public static bool IsInit(this string singleArgument) => singleArgument.Equals("init", StringComparison.OrdinalIgnoreCase); - public static bool IsHelp(this string singleArgument) - { - return (singleArgument == "?") || singleArgument.IsSwitch("h") || singleArgument.IsSwitch("help") || singleArgument.IsSwitch("?"); - } + public static bool IsHelp(this string singleArgument) => (singleArgument == "?") || singleArgument.IsSwitch("h") || singleArgument.IsSwitch("help") || singleArgument.IsSwitch("?"); public static bool ArgumentRequiresValue(this string argument, int argumentIndex) { @@ -126,15 +111,10 @@ public static void AppendLineFormat(this StringBuilder stringBuilder, string for stringBuilder.AppendLine(); } - public static string RegexReplace(this string input, string pattern, string replace, RegexOptions options = RegexOptions.None) - { - return Regex.Replace(input, pattern, replace, options); - } + public static string RegexReplace(this string input, string pattern, string replace, RegexOptions options = RegexOptions.None) => Regex.Replace(input, pattern, replace, options); - public static bool IsEquivalentTo(this string self, string? other) - { - return string.Equals(self, other, StringComparison.OrdinalIgnoreCase); - } + public static bool IsEquivalentTo(this string self, string? other) => + string.Equals(self, other, StringComparison.OrdinalIgnoreCase); /// public static bool IsNullOrEmpty([NotNullWhen(returnValue: false)] this string? value) => string.IsNullOrEmpty(value); diff --git a/src/GitVersion.Core/Git/ReferenceName.cs b/src/GitVersion.Core/Git/ReferenceName.cs index 24e475b89a..36b806da15 100644 --- a/src/GitVersion.Core/Git/ReferenceName.cs +++ b/src/GitVersion.Core/Git/ReferenceName.cs @@ -52,12 +52,10 @@ public static ReferenceName Parse(string canonicalName) public override int GetHashCode() => equalityHelper.GetHashCode(this); public override string ToString() => Friendly; - public bool EquivalentTo(string? name) - { - return Canonical.Equals(name, StringComparison.OrdinalIgnoreCase) - || Friendly.Equals(name, StringComparison.OrdinalIgnoreCase) - || WithoutRemote.Equals(name, StringComparison.OrdinalIgnoreCase); - } + public bool EquivalentTo(string? name) => + Canonical.Equals(name, StringComparison.OrdinalIgnoreCase) + || Friendly.Equals(name, StringComparison.OrdinalIgnoreCase) + || WithoutRemote.Equals(name, StringComparison.OrdinalIgnoreCase); private string Shorten() { diff --git a/src/GitVersion.Core/Helpers/RetryAction.cs b/src/GitVersion.Core/Helpers/RetryAction.cs index 1a16cf7874..baece22441 100644 --- a/src/GitVersion.Core/Helpers/RetryAction.cs +++ b/src/GitVersion.Core/Helpers/RetryAction.cs @@ -13,14 +13,11 @@ public RetryAction(int maxRetries = 5) { } - public void Execute(Action operation) - { - base.Execute(() => - { - operation(); - return false; - }); - } + public void Execute(Action operation) => base.Execute(() => + { + operation(); + return false; + }); } public class RetryAction where T : Exception { @@ -37,10 +34,7 @@ public RetryAction(int maxRetries = 5) .WaitAndRetry(linearBackoff); } - public Result Execute(Func operation) - { - return this.retryPolicy.Execute(operation); - } + public Result Execute(Func operation) => this.retryPolicy.Execute(operation); private static IEnumerable LinearBackoff(TimeSpan initialDelay, int retryCount, double factor = 1.0, bool fastFirst = false) { diff --git a/src/GitVersion.Core/Logging/ConsoleAdapter.cs b/src/GitVersion.Core/Logging/ConsoleAdapter.cs index ce450df9e4..4e836b29c1 100644 --- a/src/GitVersion.Core/Logging/ConsoleAdapter.cs +++ b/src/GitVersion.Core/Logging/ConsoleAdapter.cs @@ -4,25 +4,13 @@ namespace GitVersion.Logging { public class ConsoleAdapter : IConsole { - public void WriteLine(string? msg) - { - Console.WriteLine(msg); - } + public void WriteLine(string? msg) => Console.WriteLine(msg); - public void WriteLine() - { - Console.WriteLine(); - } + public void WriteLine() => Console.WriteLine(); - public void Write(string msg) - { - Console.Write(msg); - } + public void Write(string msg) => Console.Write(msg); - public string ReadLine() - { - return Console.ReadLine(); - } + public string ReadLine() => Console.ReadLine(); public IDisposable UseColor(ConsoleColor consoleColor) { diff --git a/src/GitVersion.Core/Logging/Log.cs b/src/GitVersion.Core/Logging/Log.cs index e520d383ca..c77953c21a 100644 --- a/src/GitVersion.Core/Logging/Log.cs +++ b/src/GitVersion.Core/Logging/Log.cs @@ -58,15 +58,9 @@ public IDisposable IndentLog(string operationDescription) }); } - public void AddLogAppender(ILogAppender logAppender) - { - this.appenders = this.appenders.Concat(new[] { logAppender }); - } + public void AddLogAppender(ILogAppender logAppender) => this.appenders = this.appenders.Concat(new[] { logAppender }); - public override string ToString() - { - return this.sb.ToString(); - } + public override string ToString() => this.sb.ToString(); private string FormatMessage(string message, string level) { diff --git a/src/GitVersion.Core/Logging/LogExtensions.cs b/src/GitVersion.Core/Logging/LogExtensions.cs index e11fc39aa2..4f5da63996 100644 --- a/src/GitVersion.Core/Logging/LogExtensions.cs +++ b/src/GitVersion.Core/Logging/LogExtensions.cs @@ -5,105 +5,45 @@ namespace GitVersion.Logging { public static class LogExtensions { - public static void Debug(this ILog log, string format, params object[] args) - { - log?.Write(LogLevel.Debug, format, args); - } + public static void Debug(this ILog log, string format, params object[] args) => log?.Write(LogLevel.Debug, format, args); - public static void Debug(this ILog log, Verbosity verbosity, string format, params object[] args) - { - log?.Write(verbosity, LogLevel.Debug, format, args); - } + public static void Debug(this ILog log, Verbosity verbosity, string format, params object[] args) => log?.Write(verbosity, LogLevel.Debug, format, args); - public static void Debug(this ILog log, LogAction logAction) - { - log?.Write(LogLevel.Debug, logAction); - } + public static void Debug(this ILog log, LogAction logAction) => log?.Write(LogLevel.Debug, logAction); - public static void Debug(this ILog log, Verbosity verbosity, LogAction logAction) - { - log?.Write(verbosity, LogLevel.Debug, logAction); - } + public static void Debug(this ILog log, Verbosity verbosity, LogAction logAction) => log?.Write(verbosity, LogLevel.Debug, logAction); - public static void Warning(this ILog log, string format, params object[] args) - { - log?.Write(LogLevel.Warn, format, args); - } + public static void Warning(this ILog log, string format, params object[] args) => log?.Write(LogLevel.Warn, format, args); - public static void Warning(this ILog log, Verbosity verbosity, string format, params object[] args) - { - log?.Write(verbosity, LogLevel.Warn, format, args); - } + public static void Warning(this ILog log, Verbosity verbosity, string format, params object[] args) => log?.Write(verbosity, LogLevel.Warn, format, args); - public static void Warning(this ILog log, LogAction logAction) - { - log?.Write(LogLevel.Warn, logAction); - } + public static void Warning(this ILog log, LogAction logAction) => log?.Write(LogLevel.Warn, logAction); - public static void Warning(this ILog log, Verbosity verbosity, LogAction logAction) - { - log?.Write(verbosity, LogLevel.Warn, logAction); - } + public static void Warning(this ILog log, Verbosity verbosity, LogAction logAction) => log?.Write(verbosity, LogLevel.Warn, logAction); - public static void Info(this ILog log, string format, params object[] args) - { - log?.Write(LogLevel.Info, format, args); - } + public static void Info(this ILog log, string format, params object[] args) => log?.Write(LogLevel.Info, format, args); - public static void Info(this ILog log, Verbosity verbosity, string format, params object[] args) - { - log?.Write(verbosity, LogLevel.Info, format, args); - } + public static void Info(this ILog log, Verbosity verbosity, string format, params object[] args) => log?.Write(verbosity, LogLevel.Info, format, args); - public static void Info(this ILog log, LogAction logAction) - { - log?.Write(LogLevel.Info, logAction); - } + public static void Info(this ILog log, LogAction logAction) => log?.Write(LogLevel.Info, logAction); - public static void Info(this ILog log, Verbosity verbosity, LogAction logAction) - { - log?.Write(verbosity, LogLevel.Info, logAction); - } + public static void Info(this ILog log, Verbosity verbosity, LogAction logAction) => log?.Write(verbosity, LogLevel.Info, logAction); - public static void Verbose(this ILog log, string format, params object[] args) - { - log?.Write(LogLevel.Verbose, format, args); - } + public static void Verbose(this ILog log, string format, params object[] args) => log?.Write(LogLevel.Verbose, format, args); - public static void Verbose(this ILog log, Verbosity verbosity, string format, params object[] args) - { - log?.Write(verbosity, LogLevel.Verbose, format, args); - } + public static void Verbose(this ILog log, Verbosity verbosity, string format, params object[] args) => log?.Write(verbosity, LogLevel.Verbose, format, args); - public static void Verbose(this ILog log, LogAction logAction) - { - log?.Write(LogLevel.Verbose, logAction); - } + public static void Verbose(this ILog log, LogAction logAction) => log?.Write(LogLevel.Verbose, logAction); - public static void Verbose(this ILog log, Verbosity verbosity, LogAction logAction) - { - log?.Write(verbosity, LogLevel.Verbose, logAction); - } + public static void Verbose(this ILog log, Verbosity verbosity, LogAction logAction) => log?.Write(verbosity, LogLevel.Verbose, logAction); - public static void Error(this ILog log, string format, params object[] args) - { - log?.Write(LogLevel.Error, format, args); - } + public static void Error(this ILog log, string format, params object[] args) => log?.Write(LogLevel.Error, format, args); - public static void Error(this ILog log, Verbosity verbosity, string format, params object[] args) - { - log?.Write(verbosity, LogLevel.Error, format, args); - } + public static void Error(this ILog log, Verbosity verbosity, string format, params object[] args) => log?.Write(verbosity, LogLevel.Error, format, args); - public static void Error(this ILog log, LogAction logAction) - { - log?.Write(LogLevel.Error, logAction); - } + public static void Error(this ILog log, LogAction logAction) => log?.Write(LogLevel.Error, logAction); - public static void Error(this ILog log, Verbosity verbosity, LogAction logAction) - { - log?.Write(verbosity, LogLevel.Error, logAction); - } + public static void Error(this ILog log, Verbosity verbosity, LogAction logAction) => log?.Write(verbosity, LogLevel.Error, logAction); public static void Write(this ILog log, LogLevel level, string format, params object[] args) { @@ -148,30 +88,15 @@ public static void Write(this ILog log, LogLevel level, LogAction logAction) logAction(ActionEntry); } - public static IDisposable QuietVerbosity(this ILog log) - { - return log.WithVerbosity(Verbosity.Quiet); - } + public static IDisposable QuietVerbosity(this ILog log) => log.WithVerbosity(Verbosity.Quiet); - public static IDisposable MinimalVerbosity(this ILog log) - { - return log.WithVerbosity(Verbosity.Minimal); - } + public static IDisposable MinimalVerbosity(this ILog log) => log.WithVerbosity(Verbosity.Minimal); - public static IDisposable NormalVerbosity(this ILog log) - { - return log.WithVerbosity(Verbosity.Normal); - } + public static IDisposable NormalVerbosity(this ILog log) => log.WithVerbosity(Verbosity.Normal); - public static IDisposable VerboseVerbosity(this ILog log) - { - return log.WithVerbosity(Verbosity.Verbose); - } + public static IDisposable VerboseVerbosity(this ILog log) => log.WithVerbosity(Verbosity.Verbose); - public static IDisposable DiagnosticVerbosity(this ILog log) - { - return log.WithVerbosity(Verbosity.Diagnostic); - } + public static IDisposable DiagnosticVerbosity(this ILog log) => log.WithVerbosity(Verbosity.Diagnostic); public static IDisposable WithVerbosity(this ILog log, Verbosity verbosity) { diff --git a/src/GitVersion.Core/Logging/NullLog.cs b/src/GitVersion.Core/Logging/NullLog.cs index e0e28f03af..d2eeec8c3d 100644 --- a/src/GitVersion.Core/Logging/NullLog.cs +++ b/src/GitVersion.Core/Logging/NullLog.cs @@ -10,10 +10,7 @@ public void Write(Verbosity verbosity, LogLevel level, string format, params obj { } - public IDisposable IndentLog(string operationDescription) - { - return Disposable.Empty; - } + public IDisposable IndentLog(string operationDescription) => Disposable.Empty; public void AddLogAppender(ILogAppender logAppender) { diff --git a/src/GitVersion.Core/Model/BranchCommit.cs b/src/GitVersion.Core/Model/BranchCommit.cs index 8e321fd0ab..8db9e720ec 100644 --- a/src/GitVersion.Core/Model/BranchCommit.cs +++ b/src/GitVersion.Core/Model/BranchCommit.cs @@ -18,10 +18,7 @@ public BranchCommit(ICommit commit, IBranch branch) : this() public IBranch Branch { get; } public ICommit Commit { get; } - private bool Equals(BranchCommit other) - { - return Equals(Branch, other.Branch) && Equals(Commit, other.Commit); - } + private bool Equals(BranchCommit other) => Equals(Branch, other.Branch) && Equals(Commit, other.Commit); public override bool Equals(object obj) { diff --git a/src/GitVersion.Core/Model/Configuration/BranchConfig.cs b/src/GitVersion.Core/Model/Configuration/BranchConfig.cs index 4f1a9e1ce5..bb18552750 100644 --- a/src/GitVersion.Core/Model/Configuration/BranchConfig.cs +++ b/src/GitVersion.Core/Model/Configuration/BranchConfig.cs @@ -113,18 +113,15 @@ public BranchConfig Apply([NotNull] BranchConfig overrides) return this; } - public static BranchConfig CreateDefaultBranchConfig(string name) + public static BranchConfig CreateDefaultBranchConfig(string name) => new BranchConfig { - return new BranchConfig - { - Name = name, - Tag = "useBranchName", - PreventIncrementOfMergedBranchVersion = false, - TrackMergeTarget = false, - TracksReleaseBranches = false, - IsReleaseBranch = false, - IsMainline = false, - }; - } + Name = name, + Tag = "useBranchName", + PreventIncrementOfMergedBranchVersion = false, + TrackMergeTarget = false, + TracksReleaseBranches = false, + IsReleaseBranch = false, + IsMainline = false, + }; } } diff --git a/src/GitVersion.Core/Model/VersionVariables.cs b/src/GitVersion.Core/Model/VersionVariables.cs index 37a8e8504f..07c0c78add 100644 --- a/src/GitVersion.Core/Model/VersionVariables.cs +++ b/src/GitVersion.Core/Model/VersionVariables.cs @@ -136,15 +136,9 @@ public static IEnumerable AvailableVariables [ReflectionIgnore] public string? this[string variable] => typeof(VersionVariables).GetProperty(variable)?.GetValue(this, null) as string; - public IEnumerator> GetEnumerator() - { - return this.GetProperties().GetEnumerator(); - } + public IEnumerator> GetEnumerator() => this.GetProperties().GetEnumerator(); - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); // FIX ME: Shall we return an instance with no ctorArgs or explicitly fail when properties is null? public static VersionVariables FromDictionary(IEnumerable>? properties) @@ -210,10 +204,7 @@ public bool TryGetValue(string variable, out string? variableValue) return false; } - private static bool ContainsKey(string variable) - { - return typeof(VersionVariables).GetProperty(variable) != null; - } + private static bool ContainsKey(string variable) => typeof(VersionVariables).GetProperty(variable) != null; public override string ToString() { diff --git a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculator.cs b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculator.cs index 581c9b884a..68f5d97eff 100644 --- a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculator.cs +++ b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculator.cs @@ -149,10 +149,7 @@ private class Versions public SemanticVersion? IncrementedVersion { get; set; } public BaseVersion? Version { get; set; } - public override string ToString() - { - return $"{Version} | {IncrementedVersion}"; - } + public override string ToString() => $"{Version} | {IncrementedVersion}"; } } } diff --git a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/TaggedCommitVersionStrategy.cs b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/TaggedCommitVersionStrategy.cs index 6b813787b4..e61feac768 100644 --- a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/TaggedCommitVersionStrategy.cs +++ b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/TaggedCommitVersionStrategy.cs @@ -20,10 +20,8 @@ public TaggedCommitVersionStrategy(IRepositoryStore repositoryStore, Lazy GetVersions() - { - return GetTaggedVersions(Context.CurrentBranch, Context.CurrentCommit?.When); - } + public override IEnumerable GetVersions() => + GetTaggedVersions(Context.CurrentBranch, Context.CurrentCommit?.When); internal IEnumerable GetTaggedVersions(IBranch? currentBranch, DateTimeOffset? olderThan) { @@ -54,10 +52,7 @@ private BaseVersion CreateBaseVersion(GitVersionContext context, VersionTaggedCo return baseVersion; } - protected virtual string FormatSource(VersionTaggedCommit version) - { - return $"Git tag '{version.Tag}'"; - } + protected virtual string FormatSource(VersionTaggedCommit version) => $"Git tag '{version.Tag}'"; protected virtual bool IsValidTag(ITag? tag, ICommit commit) { @@ -78,10 +73,7 @@ public VersionTaggedCommit(ICommit commit, SemanticVersion semVer, string tag) this.SemVer = semVer; } - public override string ToString() - { - return $"{this.Tag} | {this.Commit} | {this.SemVer}"; - } + public override string ToString() => $"{this.Tag} | {this.Commit} | {this.SemVer}"; } } } diff --git a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/VersionInBranchNameVersionStrategy.cs b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/VersionInBranchNameVersionStrategy.cs index f1875fd805..11134a5f15 100644 --- a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/VersionInBranchNameVersionStrategy.cs +++ b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/VersionInBranchNameVersionStrategy.cs @@ -59,11 +59,8 @@ internal IEnumerable GetVersions(string? tagPrefixRegex, IBranch? c return null; } - private static string NameWithoutOrigin(IBranch branch) - { - return branch.IsRemote && branch.Name.Friendly.StartsWith("origin/") + private static string NameWithoutOrigin(IBranch branch) => branch.IsRemote && branch.Name.Friendly.StartsWith("origin/") ? branch.Name.Friendly.Substring("origin/".Length) : branch.Name.Friendly; - } } } diff --git a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/VersionStrategyBase.cs b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/VersionStrategyBase.cs index b20566381f..4aef58c215 100644 --- a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/VersionStrategyBase.cs +++ b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/VersionStrategyBase.cs @@ -12,9 +12,6 @@ protected VersionStrategyBase(Lazy versionContext) { this.versionContext = versionContext ?? throw new ArgumentNullException(nameof(versionContext)); } - public virtual IEnumerable GetVersions() - { - throw new NotImplementedException(); - } + public virtual IEnumerable GetVersions() => throw new NotImplementedException(); } } diff --git a/src/GitVersion.Core/VersionCalculation/Cache/GitVersionCache.cs b/src/GitVersion.Core/VersionCalculation/Cache/GitVersionCache.cs index 6049d69279..f2d58e8939 100644 --- a/src/GitVersion.Core/VersionCalculation/Cache/GitVersionCache.cs +++ b/src/GitVersion.Core/VersionCalculation/Cache/GitVersionCache.cs @@ -106,9 +106,6 @@ private string PrepareCacheDirectory() return cacheDir; } - private static string GetCacheFileName(GitVersionCacheKey key, string cacheDir) - { - return Path.Combine(cacheDir, string.Concat(key.Value, ".yml")); - } + private static string GetCacheFileName(GitVersionCacheKey key, string cacheDir) => Path.Combine(cacheDir, string.Concat(key.Value, ".yml")); } } diff --git a/src/GitVersion.Core/VersionCalculation/IncrementStrategy.cs b/src/GitVersion.Core/VersionCalculation/IncrementStrategy.cs index 1e1610ef76..faca03807c 100644 --- a/src/GitVersion.Core/VersionCalculation/IncrementStrategy.cs +++ b/src/GitVersion.Core/VersionCalculation/IncrementStrategy.cs @@ -18,16 +18,13 @@ public enum IncrementStrategy public static class IncrementStrategyExtensions { - public static VersionField ToVersionField(this IncrementStrategy strategy) + public static VersionField ToVersionField(this IncrementStrategy strategy) => strategy switch { - return strategy switch - { - IncrementStrategy.None => VersionField.None, - IncrementStrategy.Major => VersionField.Major, - IncrementStrategy.Minor => VersionField.Minor, - IncrementStrategy.Patch => VersionField.Patch, - _ => throw new ArgumentOutOfRangeException(nameof(strategy), strategy, null) - }; - } + IncrementStrategy.None => VersionField.None, + IncrementStrategy.Major => VersionField.Major, + IncrementStrategy.Minor => VersionField.Minor, + IncrementStrategy.Patch => VersionField.Patch, + _ => throw new ArgumentOutOfRangeException(nameof(strategy), strategy, null) + }; } } diff --git a/src/GitVersion.Core/VersionCalculation/NextVersionCalculator.cs b/src/GitVersion.Core/VersionCalculation/NextVersionCalculator.cs index 2fe5188351..8db8841841 100644 --- a/src/GitVersion.Core/VersionCalculation/NextVersionCalculator.cs +++ b/src/GitVersion.Core/VersionCalculation/NextVersionCalculator.cs @@ -151,11 +151,8 @@ private static void EnsureHeadIsNotDetached(GitVersionContext context) throw new WarningException(message); } - private static bool MajorMinorPatchEqual(SemanticVersion lastTag, SemanticVersion baseVersion) - { - return lastTag.Major == baseVersion.Major && + private static bool MajorMinorPatchEqual(SemanticVersion lastTag, SemanticVersion baseVersion) => lastTag.Major == baseVersion.Major && lastTag.Minor == baseVersion.Minor && lastTag.Patch == baseVersion.Patch; - } } } diff --git a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs index e919f14c96..b6f3014472 100644 --- a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs +++ b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs @@ -51,10 +51,7 @@ public bool Equals(SemanticVersion? obj) this.BuildMetaData == obj.BuildMetaData; } - public bool IsEmpty() - { - return Equals(Empty); - } + public bool IsEmpty() => Equals(Empty); public override bool Equals(object? obj) { @@ -184,10 +181,7 @@ public static bool TryParse(string version, string? tagPrefixRegex, [NotNullWhen return true; } - public int CompareTo(SemanticVersion value) - { - return CompareTo(value, true); - } + public int CompareTo(SemanticVersion value) => CompareTo(value, true); public int CompareTo(SemanticVersion? value, bool includePrerelease) { @@ -231,10 +225,7 @@ public int CompareTo(SemanticVersion? value, bool includePrerelease) return 0; } - public override string ToString() - { - return ToString(null); - } + public override string ToString() => ToString(null); /// /// s - Default SemVer [1.2.3-beta.4+5] diff --git a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionBuildMetaData.cs b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionBuildMetaData.cs index fa76df7e3c..cb06d85964 100644 --- a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionBuildMetaData.cs +++ b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionBuildMetaData.cs @@ -54,25 +54,13 @@ public SemanticVersionBuildMetaData(SemanticVersionBuildMetaData? buildMetaData) this.UncommittedChanges = buildMetaData?.UncommittedChanges ?? 0; } - public override bool Equals(object obj) - { - return Equals(obj as SemanticVersionBuildMetaData); - } + public override bool Equals(object obj) => Equals(obj as SemanticVersionBuildMetaData); - public bool Equals(SemanticVersionBuildMetaData? other) - { - return EqualityHelper.Equals(this, other); - } + public bool Equals(SemanticVersionBuildMetaData? other) => EqualityHelper.Equals(this, other); - public override int GetHashCode() - { - return EqualityHelper.GetHashCode(this); - } + public override int GetHashCode() => EqualityHelper.GetHashCode(this); - public override string ToString() - { - return ToString(null); - } + public override string ToString() => ToString(null); /// /// b - Formats just the build number diff --git a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionPreReleaseTag.cs b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionPreReleaseTag.cs index 54c8123d9f..bf0a476b07 100644 --- a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionPreReleaseTag.cs +++ b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionPreReleaseTag.cs @@ -33,20 +33,11 @@ public SemanticVersionPreReleaseTag(SemanticVersionPreReleaseTag? preReleaseTag) public int? Number { get; set; } public bool? PromotedFromCommits { get; set; } - public override bool Equals(object? obj) - { - return Equals(obj as SemanticVersionPreReleaseTag); - } + public override bool Equals(object? obj) => Equals(obj as SemanticVersionPreReleaseTag); - public bool Equals(SemanticVersionPreReleaseTag? other) - { - return EqualityHelper.Equals(this, other); - } + public bool Equals(SemanticVersionPreReleaseTag? other) => EqualityHelper.Equals(this, other); - public override int GetHashCode() - { - return EqualityHelper.GetHashCode(this); - } + public override int GetHashCode() => EqualityHelper.GetHashCode(this); public static bool operator ==(SemanticVersionPreReleaseTag? left, SemanticVersionPreReleaseTag? right) { @@ -130,10 +121,7 @@ public int CompareTo(SemanticVersionPreReleaseTag? other) return Nullable.Compare(Number, other?.Number); } - public override string? ToString() - { - return ToString(null); - } + public override string? ToString() => ToString(null); /// /// Default formats: @@ -199,9 +187,7 @@ private string GetLegacyName() return firstPart.Replace(".", string.Empty); } - public bool HasTag() - { - return !Name.IsNullOrEmpty() || (Number.HasValue && PromotedFromCommits != true); - } + public bool HasTag() => + !Name.IsNullOrEmpty() || (Number.HasValue && PromotedFromCommits != true); } } diff --git a/src/GitVersion.Core/VersionConverters/WixUpdater/WixVersionFileUpdater.cs b/src/GitVersion.Core/VersionConverters/WixUpdater/WixVersionFileUpdater.cs index c1ae9dea73..e29227b229 100644 --- a/src/GitVersion.Core/VersionConverters/WixUpdater/WixVersionFileUpdater.cs +++ b/src/GitVersion.Core/VersionConverters/WixUpdater/WixVersionFileUpdater.cs @@ -54,9 +54,6 @@ private static string GetWixFormatFromVersionVariables(VersionVariables variable return builder.ToString(); } - public void Dispose() - { - this.log.Info($"Done writing {this.wixVersionFile}"); - } + public void Dispose() => this.log.Info($"Done writing {this.wixVersionFile}"); } } diff --git a/src/GitVersion.LibGit2Sharp/Git/BranchCollection.cs b/src/GitVersion.LibGit2Sharp/Git/BranchCollection.cs index 8ab5b7047c..87ee3ae186 100644 --- a/src/GitVersion.LibGit2Sharp/Git/BranchCollection.cs +++ b/src/GitVersion.LibGit2Sharp/Git/BranchCollection.cs @@ -9,10 +9,7 @@ internal sealed class BranchCollection : IBranchCollection private readonly LibGit2Sharp.BranchCollection innerCollection; internal BranchCollection(LibGit2Sharp.BranchCollection collection) => this.innerCollection = collection; - public IEnumerator GetEnumerator() - { - return this.innerCollection.Select(branch => new Branch(branch)).GetEnumerator(); - } + public IEnumerator GetEnumerator() => this.innerCollection.Select(branch => new Branch(branch)).GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public IBranch? this[string name] { diff --git a/src/GitVersion.LibGit2Sharp/Git/Commit.cs b/src/GitVersion.LibGit2Sharp/Git/Commit.cs index f499d1f906..bdc8dd87d2 100644 --- a/src/GitVersion.LibGit2Sharp/Git/Commit.cs +++ b/src/GitVersion.LibGit2Sharp/Git/Commit.cs @@ -23,10 +23,7 @@ internal Commit(LibGit2Sharp.Commit innerCommit) : base(innerCommit) public bool Equals(ICommit other) => equalityHelper.Equals(this, other); public override bool Equals(object obj) => Equals((obj as ICommit)!); public override int GetHashCode() => equalityHelper.GetHashCode(this); - public override string ToString() - { - return $"{Id.ToString(7)} {this.innerCommit.MessageShort}"; - } + public override string ToString() => $"{Id.ToString(7)} {this.innerCommit.MessageShort}"; public static implicit operator LibGit2Sharp.Commit(Commit d) => d.innerCommit; public IEnumerable Parents { get; } diff --git a/src/GitVersion.LibGit2Sharp/Git/CommitCollection.cs b/src/GitVersion.LibGit2Sharp/Git/CommitCollection.cs index 3359b086b9..ef9be5212c 100644 --- a/src/GitVersion.LibGit2Sharp/Git/CommitCollection.cs +++ b/src/GitVersion.LibGit2Sharp/Git/CommitCollection.cs @@ -11,10 +11,7 @@ internal sealed class CommitCollection : ICommitCollection private readonly ICommitLog innerCollection; internal CommitCollection(ICommitLog collection) => this.innerCollection = collection; - public IEnumerator GetEnumerator() - { - return this.innerCollection.Select(commit => new Commit(commit)).GetEnumerator(); - } + public IEnumerator GetEnumerator() => this.innerCollection.Select(commit => new Commit(commit)).GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); diff --git a/src/GitVersion.LibGit2Sharp/Git/GitObject.cs b/src/GitVersion.LibGit2Sharp/Git/GitObject.cs index 30ca754e51..45d69193e2 100644 --- a/src/GitVersion.LibGit2Sharp/Git/GitObject.cs +++ b/src/GitVersion.LibGit2Sharp/Git/GitObject.cs @@ -17,10 +17,7 @@ internal GitObject(LibGit2Sharp.GitObject innerGitObject) public bool Equals(IGitObject other) => equalityHelper.Equals(this, other); public override bool Equals(object obj) => Equals((obj as IGitObject)!); public override int GetHashCode() => equalityHelper.GetHashCode(this); - public override string ToString() - { - return Id.ToString(7); - } + public override string ToString() => Id.ToString(7); public IObjectId Id { get; } public string Sha { get; } diff --git a/src/GitVersion.LibGit2Sharp/Git/GitRepository.cs b/src/GitVersion.LibGit2Sharp/Git/GitRepository.cs index 1e46cc948f..b9a6b6e76c 100644 --- a/src/GitVersion.LibGit2Sharp/Git/GitRepository.cs +++ b/src/GitVersion.LibGit2Sharp/Git/GitRepository.cs @@ -99,8 +99,8 @@ private int GetNumberOfUncommittedChangesInternal() return changes.Count; } - public void CreateBranchForPullRequestBranch(AuthenticationInfo auth) - { + + public void CreateBranchForPullRequestBranch(AuthenticationInfo auth) => RepositoryExtensions.RunSafe(() => { var network = repositoryInstance.Network; @@ -159,7 +159,7 @@ public void CreateBranchForPullRequestBranch(AuthenticationInfo auth) throw new WarningException(message); } }); - } + public void Clone(string? sourceUrl, string? workdirPath, AuthenticationInfo auth) { try @@ -190,37 +190,29 @@ public void Clone(string? sourceUrl, string? workdirPath, AuthenticationInfo aut throw new Exception("There was an unknown problem with the Git repository you provided", ex); } } - public void Checkout(string commitOrBranchSpec) - { + public void Checkout(string commitOrBranchSpec) => RepositoryExtensions.RunSafe(() => - { - Commands.Checkout(repositoryInstance, commitOrBranchSpec); - }); - } - public void Fetch(string remote, IEnumerable refSpecs, AuthenticationInfo auth, string? logMessage) - { + Commands.Checkout(repositoryInstance, commitOrBranchSpec)); + + public void Fetch(string remote, IEnumerable refSpecs, AuthenticationInfo auth, string? logMessage) => RepositoryExtensions.RunSafe(() => - { - Commands.Fetch((Repository)repositoryInstance, remote, refSpecs, GetFetchOptions(auth), logMessage); - }); - } + Commands.Fetch((Repository)repositoryInstance, remote, refSpecs, GetFetchOptions(auth), logMessage)); + internal static string Discover(string? path) => Repository.Discover(path); - private static FetchOptions GetFetchOptions(AuthenticationInfo auth) - { - return new() + private static FetchOptions GetFetchOptions(AuthenticationInfo auth) => + new() { CredentialsProvider = GetCredentialsProvider(auth) }; - } - private static CloneOptions GetCloneOptions(AuthenticationInfo auth) - { - return new() + + private static CloneOptions GetCloneOptions(AuthenticationInfo auth) => + new() { Checkout = false, CredentialsProvider = GetCredentialsProvider(auth) }; - } + private static CredentialsHandler? GetCredentialsProvider(AuthenticationInfo auth) { if (!auth.Username.IsNullOrWhiteSpace()) diff --git a/src/GitVersion.LibGit2Sharp/Git/RefSpecCollection.cs b/src/GitVersion.LibGit2Sharp/Git/RefSpecCollection.cs index 68329ad37a..f76210f021 100644 --- a/src/GitVersion.LibGit2Sharp/Git/RefSpecCollection.cs +++ b/src/GitVersion.LibGit2Sharp/Git/RefSpecCollection.cs @@ -8,13 +8,7 @@ internal sealed class RefSpecCollection : IRefSpecCollection { private readonly LibGit2Sharp.RefSpecCollection innerCollection; internal RefSpecCollection(LibGit2Sharp.RefSpecCollection collection) => this.innerCollection = collection; - public IEnumerator GetEnumerator() - { - return this.innerCollection.Select(tag => new RefSpec(tag)).GetEnumerator(); - } - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } + public IEnumerator GetEnumerator() => this.innerCollection.Select(tag => new RefSpec(tag)).GetEnumerator(); + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } } diff --git a/src/GitVersion.LibGit2Sharp/Git/ReferenceCollection.cs b/src/GitVersion.LibGit2Sharp/Git/ReferenceCollection.cs index 6b7704d080..55488ea56b 100644 --- a/src/GitVersion.LibGit2Sharp/Git/ReferenceCollection.cs +++ b/src/GitVersion.LibGit2Sharp/Git/ReferenceCollection.cs @@ -9,23 +9,14 @@ internal sealed class ReferenceCollection : IReferenceCollection private readonly LibGit2Sharp.ReferenceCollection innerCollection; internal ReferenceCollection(LibGit2Sharp.ReferenceCollection collection) => this.innerCollection = collection; - public IEnumerator GetEnumerator() - { - return this.innerCollection.Select(reference => new Reference(reference)).GetEnumerator(); - } + public IEnumerator GetEnumerator() => this.innerCollection.Select(reference => new Reference(reference)).GetEnumerator(); - public void Add(string name, string canonicalRefNameOrObjectish, bool allowOverwrite = false) - { - this.innerCollection.Add(name, canonicalRefNameOrObjectish, allowOverwrite); - } + public void Add(string name, string canonicalRefNameOrObjectish, bool allowOverwrite = false) => this.innerCollection.Add(name, canonicalRefNameOrObjectish, allowOverwrite); - public void UpdateTarget(IReference directRef, IObjectId targetId) - { - RepositoryExtensions.RunSafe(() => - { - this.innerCollection.UpdateTarget((Reference)directRef, (ObjectId)targetId); - }); - } + public void UpdateTarget(IReference directRef, IObjectId targetId) => RepositoryExtensions.RunSafe(() => + { + this.innerCollection.UpdateTarget((Reference)directRef, (ObjectId)targetId); + }); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); @@ -40,9 +31,6 @@ public IReference? this[string name] public IReference? Head => this["HEAD"]; - public IEnumerable FromGlob(string pattern) - { - return this.innerCollection.FromGlob(pattern).Select(reference => new Reference(reference)); - } + public IEnumerable FromGlob(string pattern) => this.innerCollection.FromGlob(pattern).Select(reference => new Reference(reference)); } } diff --git a/src/GitVersion.LibGit2Sharp/Git/RemoteCollection.cs b/src/GitVersion.LibGit2Sharp/Git/RemoteCollection.cs index 4d10cb9851..8436836a7e 100644 --- a/src/GitVersion.LibGit2Sharp/Git/RemoteCollection.cs +++ b/src/GitVersion.LibGit2Sharp/Git/RemoteCollection.cs @@ -9,10 +9,7 @@ internal sealed class RemoteCollection : IRemoteCollection private readonly LibGit2Sharp.RemoteCollection innerCollection; internal RemoteCollection(LibGit2Sharp.RemoteCollection collection) => this.innerCollection = collection; - public IEnumerator GetEnumerator() - { - return this.innerCollection.Select(reference => new Remote(reference)).GetEnumerator(); - } + public IEnumerator GetEnumerator() => this.innerCollection.Select(reference => new Remote(reference)).GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public IRemote? this[string name] @@ -24,13 +21,7 @@ public IRemote? this[string name] } } - public void Remove(string remoteName) - { - this.innerCollection.Remove(remoteName); - } - public void Update(string remoteName, string refSpec) - { - this.innerCollection.Update(remoteName, r => r.FetchRefSpecs.Add(refSpec)); - } + public void Remove(string remoteName) => this.innerCollection.Remove(remoteName); + public void Update(string remoteName, string refSpec) => this.innerCollection.Update(remoteName, r => r.FetchRefSpecs.Add(refSpec)); } } diff --git a/src/GitVersion.LibGit2Sharp/Git/TagCollection.cs b/src/GitVersion.LibGit2Sharp/Git/TagCollection.cs index ef59662156..42b4a91bcc 100644 --- a/src/GitVersion.LibGit2Sharp/Git/TagCollection.cs +++ b/src/GitVersion.LibGit2Sharp/Git/TagCollection.cs @@ -9,10 +9,7 @@ internal sealed class TagCollection : ITagCollection private readonly LibGit2Sharp.TagCollection innerCollection; internal TagCollection(LibGit2Sharp.TagCollection collection) => this.innerCollection = collection; - public IEnumerator GetEnumerator() - { - return this.innerCollection.Select(tag => new Tag(tag)).GetEnumerator(); - } + public IEnumerator GetEnumerator() => this.innerCollection.Select(tag => new Tag(tag)).GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } diff --git a/src/GitVersion.MsBuild.Tests/Helpers/EventArgsFormatting.cs b/src/GitVersion.MsBuild.Tests/Helpers/EventArgsFormatting.cs index 4bbe418f09..644104b514 100644 --- a/src/GitVersion.MsBuild.Tests/Helpers/EventArgsFormatting.cs +++ b/src/GitVersion.MsBuild.Tests/Helpers/EventArgsFormatting.cs @@ -16,13 +16,11 @@ internal static class EventArgsFormatting /// /// Error to format /// The formatted message string. - internal static string FormatEventMessage(BuildErrorEventArgs e) - { + internal static string FormatEventMessage(BuildErrorEventArgs e) => // "error" should not be localized - return FormatEventMessage("error", e.Subcategory, e.Message, + FormatEventMessage("error", e.Subcategory, e.Message, e.Code, e.File, null, e.LineNumber, e.EndLineNumber, e.ColumnNumber, e.EndColumnNumber, e.ThreadId); - } /// /// Format the error event message and all the other event data into @@ -31,13 +29,11 @@ internal static string FormatEventMessage(BuildErrorEventArgs e) /// Error to format /// true to show the project file which issued the event, otherwise false. /// The formatted message string. - internal static string FormatEventMessage(BuildErrorEventArgs e, bool showProjectFile) - { + internal static string FormatEventMessage(BuildErrorEventArgs e, bool showProjectFile) => // "error" should not be localized - return FormatEventMessage("error", e.Subcategory, e.Message, + FormatEventMessage("error", e.Subcategory, e.Message, e.Code, e.File, showProjectFile ? e.ProjectFile : null, e.LineNumber, e.EndLineNumber, e.ColumnNumber, e.EndColumnNumber, e.ThreadId); - } /// /// Format the warning message and all the other event data into a @@ -45,13 +41,11 @@ internal static string FormatEventMessage(BuildErrorEventArgs e, bool showProjec /// /// Warning to format /// The formatted message string. - internal static string FormatEventMessage(BuildWarningEventArgs e) - { + internal static string FormatEventMessage(BuildWarningEventArgs e) => // "warning" should not be localized - return FormatEventMessage("warning", e.Subcategory, e.Message, + FormatEventMessage("warning", e.Subcategory, e.Message, e.Code, e.File, null, e.LineNumber, e.EndLineNumber, e.ColumnNumber, e.EndColumnNumber, e.ThreadId); - } /// /// Format the warning message and all the other event data into a @@ -60,13 +54,11 @@ internal static string FormatEventMessage(BuildWarningEventArgs e) /// Warning to format /// true to show the project file which issued the event, otherwise false. /// The formatted message string. - internal static string FormatEventMessage(BuildWarningEventArgs e, bool showProjectFile) - { + internal static string FormatEventMessage(BuildWarningEventArgs e, bool showProjectFile) => // "warning" should not be localized - return FormatEventMessage("warning", e.Subcategory, e.Message, + FormatEventMessage("warning", e.Subcategory, e.Message, e.Code, e.File, showProjectFile ? e.ProjectFile : null, e.LineNumber, e.EndLineNumber, e.ColumnNumber, e.EndColumnNumber, e.ThreadId); - } /// /// Format the message and all the other event data into a @@ -74,10 +66,7 @@ internal static string FormatEventMessage(BuildWarningEventArgs e, bool showProj /// /// Message to format /// The formatted message string. - internal static string FormatEventMessage(BuildMessageEventArgs e) - { - return FormatEventMessage(e, false); - } + internal static string FormatEventMessage(BuildMessageEventArgs e) => FormatEventMessage(e, false); /// /// Format the message and all the other event data into a @@ -86,12 +75,10 @@ internal static string FormatEventMessage(BuildMessageEventArgs e) /// Message to format /// Show project file or not /// The formatted message string. - internal static string FormatEventMessage(BuildMessageEventArgs e, bool showProjectFile) - { + internal static string FormatEventMessage(BuildMessageEventArgs e, bool showProjectFile) => // "message" should not be localized - return FormatEventMessage("message", e.Subcategory, e.Message, + FormatEventMessage("message", e.Subcategory, e.Message, e.Code, e.File, showProjectFile ? e.ProjectFile : null, e.LineNumber, e.EndLineNumber, e.ColumnNumber, e.EndColumnNumber, e.ThreadId); - } /// /// Format the event message and all the other event data into a @@ -120,10 +107,7 @@ internal static string FormatEventMessage int columnNumber, int endColumnNumber, int threadId - ) - { - return FormatEventMessage(category, subcategory, message, code, file, null, lineNumber, endLineNumber, columnNumber, endColumnNumber, threadId); - } + ) => FormatEventMessage(category, subcategory, message, code, file, null, lineNumber, endLineNumber, columnNumber, endColumnNumber, threadId); /// /// Format the event message and all the other event data into a diff --git a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildExeFixture.cs b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildExeFixture.cs index 6ab0b2985b..1b66f62051 100644 --- a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildExeFixture.cs +++ b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildExeFixture.cs @@ -18,10 +18,7 @@ public class MsBuildExeFixture private readonly RepositoryFixtureBase fixture; private KeyValuePair[] environmentVariables; - public void WithEnv(params KeyValuePair[] envs) - { - this.environmentVariables = envs; - } + public void WithEnv(params KeyValuePair[] envs) => this.environmentVariables = envs; public const string OutputTarget = "GitVersionOutput"; diff --git a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildExeFixtureResult.cs b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildExeFixtureResult.cs index 49197c9d70..1e9d663ebd 100644 --- a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildExeFixtureResult.cs +++ b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildExeFixtureResult.cs @@ -15,9 +15,6 @@ public MsBuildExeFixtureResult(RepositoryFixtureBase fixture) public IAnalyzerResults MsBuild { get; set; } public string Output { get; set; } public string ProjectPath { get; set; } - public void Dispose() - { - this.fixture.Dispose(); - } + public void Dispose() => this.fixture.Dispose(); } } diff --git a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixture.cs b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixture.cs index d180c94397..a0b7c8b51a 100644 --- a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixture.cs +++ b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixture.cs @@ -19,37 +19,31 @@ public MsBuildTaskFixture(RepositoryFixtureBase fixture) this.fixture = fixture; } - public void WithEnv(params KeyValuePair[] envs) - { - this.environmentVariables = envs; - } + public void WithEnv(params KeyValuePair[] envs) => this.environmentVariables = envs; - public MsBuildTaskFixtureResult Execute(T task) where T : GitVersionTaskBase - { - return UsingEnv(() => - { - var buildEngine = new MockEngine(); + public MsBuildTaskFixtureResult Execute(T task) where T : GitVersionTaskBase => UsingEnv(() => + { + var buildEngine = new MockEngine(); - task.BuildEngine = buildEngine; + task.BuildEngine = buildEngine; - var versionFile = Path.Combine(task.SolutionDirectory, "gitversion.json"); - this.fixture.WriteVersionVariables(versionFile); + var versionFile = Path.Combine(task.SolutionDirectory, "gitversion.json"); + this.fixture.WriteVersionVariables(versionFile); - task.VersionFile = versionFile; + task.VersionFile = versionFile; - var result = task.Execute(); + var result = task.Execute(); - return new MsBuildTaskFixtureResult(this.fixture) - { - Success = result, - Task = task, - Errors = buildEngine.Errors, - Warnings = buildEngine.Warnings, - Messages = buildEngine.Messages, - Log = buildEngine.Log, - }; - }); - } + return new MsBuildTaskFixtureResult(this.fixture) + { + Success = result, + Task = task, + Errors = buildEngine.Errors, + Warnings = buildEngine.Warnings, + Messages = buildEngine.Messages, + Log = buildEngine.Log, + }; + }); private T UsingEnv(Func func) { diff --git a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixtureResult.cs b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixtureResult.cs index af865edff5..ac8a82dcc8 100644 --- a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixtureResult.cs +++ b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixtureResult.cs @@ -21,9 +21,6 @@ public MsBuildTaskFixtureResult(RepositoryFixtureBase fixture) public int Messages { get; set; } public string Log { get; set; } - public void Dispose() - { - this.fixture.Dispose(); - } + public void Dispose() => this.fixture.Dispose(); } } diff --git a/src/GitVersion.MsBuild.Tests/InvalidFileCheckerTests.cs b/src/GitVersion.MsBuild.Tests/InvalidFileCheckerTests.cs index 43c7b0c25c..7a30e148b6 100644 --- a/src/GitVersion.MsBuild.Tests/InvalidFileCheckerTests.cs +++ b/src/GitVersion.MsBuild.Tests/InvalidFileCheckerTests.cs @@ -25,10 +25,7 @@ public void CreateTemporaryProject() } [TearDown] - public void Cleanup() - { - Directory.Delete(this.projectDirectory, true); - } + public void Cleanup() => Directory.Delete(this.projectDirectory, true); [Test] public void VerifyIgnoreNonAssemblyInfoFile() diff --git a/src/GitVersion.MsBuild.Tests/Mocks/MockEngine.cs b/src/GitVersion.MsBuild.Tests/Mocks/MockEngine.cs index 90798acf0a..3757dcc7a1 100644 --- a/src/GitVersion.MsBuild.Tests/Mocks/MockEngine.cs +++ b/src/GitVersion.MsBuild.Tests/Mocks/MockEngine.cs @@ -118,10 +118,7 @@ public object GetRegisteredTaskObject(object key, RegisteredTaskObjectLifetime l return obj; } - public void RegisterTaskObject(object key, object obj, RegisteredTaskObjectLifetime lifetime, bool allowEarlyCollection) - { - this._objectCache[key] = obj; - } + public void RegisterTaskObject(object key, object obj, RegisteredTaskObjectLifetime lifetime, bool allowEarlyCollection) => this._objectCache[key] = obj; public object UnregisterTaskObject(object key, RegisteredTaskObjectLifetime lifetime) { diff --git a/src/GitVersion.MsBuild.Tests/Mocks/MockTaskItem.cs b/src/GitVersion.MsBuild.Tests/Mocks/MockTaskItem.cs index 97773c034c..ea1102bbdb 100644 --- a/src/GitVersion.MsBuild.Tests/Mocks/MockTaskItem.cs +++ b/src/GitVersion.MsBuild.Tests/Mocks/MockTaskItem.cs @@ -12,29 +12,14 @@ internal class MockTaskItem : ITaskItem public ICollection MetadataNames { get; private set; } - public IDictionary CloneCustomMetadata() - { - throw new NotImplementedException(); - } - - public void CopyMetadataTo(ITaskItem destinationItem) - { - throw new NotImplementedException(); - } - - public string GetMetadata(string metadataName) - { - throw new NotImplementedException(); - } - - public void RemoveMetadata(string metadataName) - { - throw new NotImplementedException(); - } - - public void SetMetadata(string metadataName, string metadataValue) - { - throw new NotImplementedException(); - } + public IDictionary CloneCustomMetadata() => throw new NotImplementedException(); + + public void CopyMetadataTo(ITaskItem destinationItem) => throw new NotImplementedException(); + + public string GetMetadata(string metadataName) => throw new NotImplementedException(); + + public void RemoveMetadata(string metadataName) => throw new NotImplementedException(); + + public void SetMetadata(string metadataName, string metadataValue) => throw new NotImplementedException(); } } diff --git a/src/GitVersion.MsBuild.Tests/Tasks/WriteVersionInfoTest.cs b/src/GitVersion.MsBuild.Tests/Tasks/WriteVersionInfoTest.cs index a12db3dc26..03f261b3db 100644 --- a/src/GitVersion.MsBuild.Tests/Tasks/WriteVersionInfoTest.cs +++ b/src/GitVersion.MsBuild.Tests/Tasks/WriteVersionInfoTest.cs @@ -13,10 +13,7 @@ public class WriteVersionInfoTest : TestTaskBase protected string GitHubEnvFilePath { get; set; } [OneTimeSetUp] - public void OneTimeSetUp() - { - GitHubEnvFilePath = System.IO.Path.GetTempFileName(); - } + public void OneTimeSetUp() => GitHubEnvFilePath = System.IO.Path.GetTempFileName(); [OneTimeTearDown] public void OneTimeTearDown() diff --git a/src/GitVersion.MsBuild/Helpers/FileHelper.cs b/src/GitVersion.MsBuild/Helpers/FileHelper.cs index 558eda4071..7ddeb971de 100644 --- a/src/GitVersion.MsBuild/Helpers/FileHelper.cs +++ b/src/GitVersion.MsBuild/Helpers/FileHelper.cs @@ -46,16 +46,13 @@ public static void DeleteTempFiles() } } - public static string GetFileExtension(string language) + public static string GetFileExtension(string language) => language switch { - return language switch - { - "C#" => "cs", - "F#" => "fs", - "VB" => "vb", - _ => throw new ArgumentException($"Unknown language detected: '{language}'") - }; - } + "C#" => "cs", + "F#" => "fs", + "VB" => "vb", + _ => throw new ArgumentException($"Unknown language detected: '{language}'") + }; public static void CheckForInvalidFiles(IEnumerable compileFiles, string projectFile) { @@ -131,12 +128,9 @@ private static bool VisualBasicFileContainsVersionAttribute(string compileFile, \s*\(\s*\)\s*\> # End brackets ()>"); } - private static IEnumerable GetInvalidFiles(IEnumerable compileFiles, string projectFile) - { - return compileFiles.Select(x => x.ItemSpec) + private static IEnumerable GetInvalidFiles(IEnumerable compileFiles, string projectFile) => compileFiles.Select(x => x.ItemSpec) .Where(compileFile => compileFile.Contains("AssemblyInfo")) .Where(s => FileContainsVersionAttribute(s, projectFile)); - } public static FileWriteInfo GetFileWriteInfo(this string intermediateOutputPath, string language, string projectFile, string outputFileName) { diff --git a/src/GitVersion.MsBuild/Helpers/MsBuildAdapter.cs b/src/GitVersion.MsBuild/Helpers/MsBuildAdapter.cs index 14841620fd..1a1131441d 100644 --- a/src/GitVersion.MsBuild/Helpers/MsBuildAdapter.cs +++ b/src/GitVersion.MsBuild/Helpers/MsBuildAdapter.cs @@ -19,20 +19,11 @@ public void WriteLine(string msg) WriteLine(); } - public void WriteLine() - { - this.taskLog.LogMessage("\n"); - } + public void WriteLine() => this.taskLog.LogMessage("\n"); - public void Write(string msg) - { - this.taskLog.LogMessage(msg); - } + public void Write(string msg) => this.taskLog.LogMessage(msg); - public string ReadLine() - { - return Console.ReadLine(); - } + public string ReadLine() => Console.ReadLine(); public IDisposable UseColor(ConsoleColor consoleColor) { From 92fb66311eb2363da7ef453a9de27a3ca8106798 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Fri, 16 Jul 2021 19:06:39 +0200 Subject: [PATCH 52/79] Expression body for ctor --- .../Fixtures/BaseGitFlowRepositoryFixture.cs | 5 +---- .../Fixtures/RemoteRepositoryFixture.cs | 5 +---- src/GitVersion.App.Tests/Helpers/ArgumentBuilder.cs | 5 +---- src/GitVersion.App.Tests/Helpers/TestConsoleAdapter.cs | 5 +---- src/GitVersion.App/Program.cs | 5 +---- src/GitVersion.App/VersionWriter.cs | 5 +---- src/GitVersion.Core.Tests/Helpers/TestEnvironment.cs | 5 +---- src/GitVersion.Core.Tests/Helpers/TestLogAppender.cs | 5 +---- .../VersionCalculation/BaseVersionCalculatorTests.cs | 10 ++-------- .../TestMainlineVersionCalculator.cs | 5 +---- src/GitVersion.Core/BuildAgents/CodeBuild.cs | 5 +---- src/GitVersion.Core/BuildAgents/GitLabCi.cs | 5 +---- src/GitVersion.Core/BuildAgents/Jenkins.cs | 5 +---- .../Configuration/Init/Wizard/ConfigInitStepFactory.cs | 5 +---- src/GitVersion.Core/Helpers/LambdaEqualityHelper.cs | 4 +--- src/GitVersion.Core/Logging/Disposable.cs | 10 ++-------- .../Model/Configuration/IgnoreConfig.cs | 5 +---- .../BaseVersionCalculators/FallbackVersionStrategy.cs | 5 +---- .../MergeMessageVersionStrategy.cs | 5 +---- .../TaggedCommitVersionStrategy.cs | 5 +---- .../VersionInBranchNameVersionStrategy.cs | 5 +---- .../BaseVersionCalculators/VersionStrategyBase.cs | 5 +---- .../VersionCalculation/MinDateVersionFilter.cs | 5 +---- .../VersionCalculation/ShaVersionFilter.cs | 5 +---- .../VersionConverters/WixUpdater/WixVersionContext.cs | 4 +--- .../Helpers/MsBuildExeFixtureResult.cs | 5 +---- .../Helpers/MsBuildTaskFixture.cs | 5 +---- .../Helpers/MsBuildTaskFixtureResult.cs | 5 +---- src/GitVersion.MsBuild/GitVersionTaskBase.cs | 5 +---- src/GitVersion.MsBuild/Helpers/MsBuildAdapter.cs | 5 +---- src/GitVersion.MsBuild/Helpers/MsBuildAppender.cs | 5 +---- 31 files changed, 33 insertions(+), 130 deletions(-) diff --git a/src/GitTools.Testing/Fixtures/BaseGitFlowRepositoryFixture.cs b/src/GitTools.Testing/Fixtures/BaseGitFlowRepositoryFixture.cs index 59c90cd28b..1932bf59f9 100644 --- a/src/GitTools.Testing/Fixtures/BaseGitFlowRepositoryFixture.cs +++ b/src/GitTools.Testing/Fixtures/BaseGitFlowRepositoryFixture.cs @@ -24,10 +24,7 @@ public BaseGitFlowRepositoryFixture(string initialVersion) : /// /// The initial setup actions will be performed before branching develop /// - public BaseGitFlowRepositoryFixture(Action initialMainAction) - { - SetupRepo(initialMainAction); - } + public BaseGitFlowRepositoryFixture(Action initialMainAction) => SetupRepo(initialMainAction); void SetupRepo(Action initialMainAction) { diff --git a/src/GitTools.Testing/Fixtures/RemoteRepositoryFixture.cs b/src/GitTools.Testing/Fixtures/RemoteRepositoryFixture.cs index cbd5a4816d..ab53fb3f2a 100644 --- a/src/GitTools.Testing/Fixtures/RemoteRepositoryFixture.cs +++ b/src/GitTools.Testing/Fixtures/RemoteRepositoryFixture.cs @@ -11,10 +11,7 @@ namespace GitTools.Testing public class RemoteRepositoryFixture : RepositoryFixtureBase { public RemoteRepositoryFixture(Func builder) - : base(builder) - { - CreateLocalRepository(); - } + : base(builder) => CreateLocalRepository(); public RemoteRepositoryFixture() : this(CreateNewRepository) { diff --git a/src/GitVersion.App.Tests/Helpers/ArgumentBuilder.cs b/src/GitVersion.App.Tests/Helpers/ArgumentBuilder.cs index 4652f630ea..1bd3ad410f 100644 --- a/src/GitVersion.App.Tests/Helpers/ArgumentBuilder.cs +++ b/src/GitVersion.App.Tests/Helpers/ArgumentBuilder.cs @@ -5,10 +5,7 @@ namespace GitVersion.App.Tests { public class ArgumentBuilder { - public ArgumentBuilder(string workingDirectory) - { - this.workingDirectory = workingDirectory; - } + public ArgumentBuilder(string workingDirectory) => this.workingDirectory = workingDirectory; public ArgumentBuilder(string workingDirectory, string exec, string execArgs, string projectFile, string projectArgs, string logFile) { diff --git a/src/GitVersion.App.Tests/Helpers/TestConsoleAdapter.cs b/src/GitVersion.App.Tests/Helpers/TestConsoleAdapter.cs index d9049f2d06..90748eace8 100644 --- a/src/GitVersion.App.Tests/Helpers/TestConsoleAdapter.cs +++ b/src/GitVersion.App.Tests/Helpers/TestConsoleAdapter.cs @@ -7,10 +7,7 @@ namespace GitVersion.App.Tests public class TestConsoleAdapter : IConsole { private readonly StringBuilder sb; - public TestConsoleAdapter(StringBuilder sb) - { - this.sb = sb; - } + public TestConsoleAdapter(StringBuilder sb) => this.sb = sb; public void WriteLine(string msg) => this.sb.AppendLine(msg); public void WriteLine() => this.sb.AppendLine(); diff --git a/src/GitVersion.App/Program.cs b/src/GitVersion.App/Program.cs index ec4a928ad1..543bc5a0e2 100644 --- a/src/GitVersion.App/Program.cs +++ b/src/GitVersion.App/Program.cs @@ -12,10 +12,7 @@ internal class Program { private readonly Action overrides; - internal Program(Action overrides = null) - { - this.overrides = overrides; - } + internal Program(Action overrides = null) => this.overrides = overrides; private static async Task Main(string[] args) => await new Program().RunAsync(args); diff --git a/src/GitVersion.App/VersionWriter.cs b/src/GitVersion.App/VersionWriter.cs index c20dcaa593..910d961c7f 100644 --- a/src/GitVersion.App/VersionWriter.cs +++ b/src/GitVersion.App/VersionWriter.cs @@ -9,10 +9,7 @@ public class VersionWriter : IVersionWriter { private readonly IConsole console; - public VersionWriter(IConsole console) - { - this.console = console ?? throw new ArgumentNullException(nameof(console)); - } + public VersionWriter(IConsole console) => this.console = console ?? throw new ArgumentNullException(nameof(console)); public void Write(Assembly assembly) => WriteTo(assembly, this.console.WriteLine); public void WriteTo(Assembly assembly, Action writeAction) diff --git a/src/GitVersion.Core.Tests/Helpers/TestEnvironment.cs b/src/GitVersion.Core.Tests/Helpers/TestEnvironment.cs index 37ad5651b2..d351f5fff6 100644 --- a/src/GitVersion.Core.Tests/Helpers/TestEnvironment.cs +++ b/src/GitVersion.Core.Tests/Helpers/TestEnvironment.cs @@ -6,10 +6,7 @@ public class TestEnvironment : IEnvironment { private readonly IDictionary map; - public TestEnvironment() - { - this.map = new Dictionary(); - } + public TestEnvironment() => this.map = new Dictionary(); public string GetEnvironmentVariable(string variableName) => this.map.TryGetValue(variableName, out var val) ? val : null; diff --git a/src/GitVersion.Core.Tests/Helpers/TestLogAppender.cs b/src/GitVersion.Core.Tests/Helpers/TestLogAppender.cs index fb633abcc0..0c11e54db2 100644 --- a/src/GitVersion.Core.Tests/Helpers/TestLogAppender.cs +++ b/src/GitVersion.Core.Tests/Helpers/TestLogAppender.cs @@ -7,10 +7,7 @@ public class TestLogAppender : ILogAppender { private readonly Action logAction; - public TestLogAppender(Action logAction) - { - this.logAction = logAction; - } + public TestLogAppender(Action logAction) => this.logAction = logAction; public void WriteTo(LogLevel level, string message) => this.logAction(message); } } diff --git a/src/GitVersion.Core.Tests/VersionCalculation/BaseVersionCalculatorTests.cs b/src/GitVersion.Core.Tests/VersionCalculation/BaseVersionCalculatorTests.cs index 3c15a88b42..5c279e5322 100644 --- a/src/GitVersion.Core.Tests/VersionCalculation/BaseVersionCalculatorTests.cs +++ b/src/GitVersion.Core.Tests/VersionCalculation/BaseVersionCalculatorTests.cs @@ -184,10 +184,7 @@ private class TestIgnoreConfig : IgnoreConfig public override bool IsEmpty => false; - public TestIgnoreConfig(IVersionFilter filter) - { - this.filter = filter; - } + public TestIgnoreConfig(IVersionFilter filter) => this.filter = filter; public override IEnumerable ToFilters() { @@ -260,10 +257,7 @@ private sealed class TestVersionStrategy : IVersionStrategy { private readonly IEnumerable versions; - public TestVersionStrategy(params BaseVersion[] versions) - { - this.versions = versions; - } + public TestVersionStrategy(params BaseVersion[] versions) => this.versions = versions; public IEnumerable GetVersions() => this.versions; } diff --git a/src/GitVersion.Core.Tests/VersionCalculation/TestMainlineVersionCalculator.cs b/src/GitVersion.Core.Tests/VersionCalculation/TestMainlineVersionCalculator.cs index ba9331a36f..5cc446e8c5 100644 --- a/src/GitVersion.Core.Tests/VersionCalculation/TestMainlineVersionCalculator.cs +++ b/src/GitVersion.Core.Tests/VersionCalculation/TestMainlineVersionCalculator.cs @@ -6,10 +6,7 @@ public class TestMainlineVersionCalculator : IMainlineVersionCalculator { private readonly SemanticVersionBuildMetaData metaData; - public TestMainlineVersionCalculator(SemanticVersionBuildMetaData metaData) - { - this.metaData = metaData; - } + public TestMainlineVersionCalculator(SemanticVersionBuildMetaData metaData) => this.metaData = metaData; public SemanticVersion FindMainlineModeVersion(BaseVersion baseVersion) => throw new System.NotImplementedException(); diff --git a/src/GitVersion.Core/BuildAgents/CodeBuild.cs b/src/GitVersion.Core/BuildAgents/CodeBuild.cs index aff2b156fd..fd6cef1fc0 100644 --- a/src/GitVersion.Core/BuildAgents/CodeBuild.cs +++ b/src/GitVersion.Core/BuildAgents/CodeBuild.cs @@ -12,10 +12,7 @@ public sealed class CodeBuild : BuildAgentBase public const string WebHookEnvironmentVariableName = "CODEBUILD_WEBHOOK_HEAD_REF"; public const string SourceVersionEnvironmentVariableName = "CODEBUILD_SOURCE_VERSION"; - public CodeBuild(IEnvironment environment, ILog log) : base(environment, log) - { - WithPropertyFile("gitversion.properties"); - } + public CodeBuild(IEnvironment environment, ILog log) : base(environment, log) => WithPropertyFile("gitversion.properties"); public void WithPropertyFile(string propertiesFileName) => this.file = propertiesFileName; diff --git a/src/GitVersion.Core/BuildAgents/GitLabCi.cs b/src/GitVersion.Core/BuildAgents/GitLabCi.cs index c367b4ccde..457c787a3e 100644 --- a/src/GitVersion.Core/BuildAgents/GitLabCi.cs +++ b/src/GitVersion.Core/BuildAgents/GitLabCi.cs @@ -10,10 +10,7 @@ public class GitLabCi : BuildAgentBase public const string EnvironmentVariableName = "GITLAB_CI"; private string? file; - public GitLabCi(IEnvironment environment, ILog log) : base(environment, log) - { - WithPropertyFile("gitversion.properties"); - } + public GitLabCi(IEnvironment environment, ILog log) : base(environment, log) => WithPropertyFile("gitversion.properties"); public void WithPropertyFile(string propertiesFileName) => this.file = propertiesFileName; diff --git a/src/GitVersion.Core/BuildAgents/Jenkins.cs b/src/GitVersion.Core/BuildAgents/Jenkins.cs index 5e23bc63c9..43d5e9f627 100644 --- a/src/GitVersion.Core/BuildAgents/Jenkins.cs +++ b/src/GitVersion.Core/BuildAgents/Jenkins.cs @@ -12,10 +12,7 @@ public class Jenkins : BuildAgentBase private string? file; protected override string EnvironmentVariable { get; } = EnvironmentVariableName; - public Jenkins(IEnvironment environment, ILog log) : base(environment, log) - { - WithPropertyFile("gitversion.properties"); - } + public Jenkins(IEnvironment environment, ILog log) : base(environment, log) => WithPropertyFile("gitversion.properties"); public void WithPropertyFile(string propertiesFileName) => this.file = propertiesFileName; diff --git a/src/GitVersion.Core/Configuration/Init/Wizard/ConfigInitStepFactory.cs b/src/GitVersion.Core/Configuration/Init/Wizard/ConfigInitStepFactory.cs index b43dd87b20..16cbaf15b6 100644 --- a/src/GitVersion.Core/Configuration/Init/Wizard/ConfigInitStepFactory.cs +++ b/src/GitVersion.Core/Configuration/Init/Wizard/ConfigInitStepFactory.cs @@ -11,10 +11,7 @@ public ConfigInitStepFactory() { } - public ConfigInitStepFactory(IServiceProvider sp) - { - this.sp = sp ?? throw new ArgumentNullException(nameof(sp)); - } + public ConfigInitStepFactory(IServiceProvider sp) => this.sp = sp ?? throw new ArgumentNullException(nameof(sp)); public T? CreateStep() => this.sp!.GetService(); } diff --git a/src/GitVersion.Core/Helpers/LambdaEqualityHelper.cs b/src/GitVersion.Core/Helpers/LambdaEqualityHelper.cs index 322d6693e9..1c21989d3b 100644 --- a/src/GitVersion.Core/Helpers/LambdaEqualityHelper.cs +++ b/src/GitVersion.Core/Helpers/LambdaEqualityHelper.cs @@ -9,10 +9,8 @@ public class LambdaEqualityHelper { private readonly Func[] equalityContributorAccessors; - public LambdaEqualityHelper(params Func[] equalityContributorAccessors) - { + public LambdaEqualityHelper(params Func[] equalityContributorAccessors) => this.equalityContributorAccessors = equalityContributorAccessors; - } public bool Equals(T? instance, T? other) { diff --git a/src/GitVersion.Core/Logging/Disposable.cs b/src/GitVersion.Core/Logging/Disposable.cs index dbd6e5d2b1..6135bafde7 100644 --- a/src/GitVersion.Core/Logging/Disposable.cs +++ b/src/GitVersion.Core/Logging/Disposable.cs @@ -4,10 +4,7 @@ namespace GitVersion.Logging { public static class Disposable { - static Disposable() - { - Empty = Create(() => { }); - } + static Disposable() => Empty = Create(() => { }); public static IDisposable Create(Action disposer) => new AnonymousDisposable(disposer); @@ -15,10 +12,7 @@ static Disposable() private sealed class AnonymousDisposable : IDisposable { - public AnonymousDisposable(Action disposer) - { - this.disposer = disposer ?? throw new ArgumentNullException(nameof(disposer)); - } + public AnonymousDisposable(Action disposer) => this.disposer = disposer ?? throw new ArgumentNullException(nameof(disposer)); public void Dispose() { diff --git a/src/GitVersion.Core/Model/Configuration/IgnoreConfig.cs b/src/GitVersion.Core/Model/Configuration/IgnoreConfig.cs index d60fc85ed4..3db1b4b2ff 100644 --- a/src/GitVersion.Core/Model/Configuration/IgnoreConfig.cs +++ b/src/GitVersion.Core/Model/Configuration/IgnoreConfig.cs @@ -8,10 +8,7 @@ namespace GitVersion.Model.Configuration { public class IgnoreConfig { - public IgnoreConfig() - { - ShAs = Enumerable.Empty(); - } + public IgnoreConfig() => ShAs = Enumerable.Empty(); [YamlMember(Alias = "commits-before")] public DateTimeOffset? Before { get; set; } diff --git a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/FallbackVersionStrategy.cs b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/FallbackVersionStrategy.cs index 3cfc66752f..b425240a16 100644 --- a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/FallbackVersionStrategy.cs +++ b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/FallbackVersionStrategy.cs @@ -13,10 +13,7 @@ public class FallbackVersionStrategy : VersionStrategyBase { private readonly IRepositoryStore repositoryStore; - public FallbackVersionStrategy(IRepositoryStore repositoryStore, Lazy versionContext) : base(versionContext) - { - this.repositoryStore = repositoryStore; - } + public FallbackVersionStrategy(IRepositoryStore repositoryStore, Lazy versionContext) : base(versionContext) => this.repositoryStore = repositoryStore; public override IEnumerable GetVersions() { var currentBranchTip = Context.CurrentBranch?.Tip; diff --git a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/MergeMessageVersionStrategy.cs b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/MergeMessageVersionStrategy.cs index 14128be42b..05e4453cbf 100644 --- a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/MergeMessageVersionStrategy.cs +++ b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/MergeMessageVersionStrategy.cs @@ -18,10 +18,7 @@ public class MergeMessageVersionStrategy : VersionStrategyBase { private readonly ILog log; - public MergeMessageVersionStrategy(ILog log, Lazy versionContext) : base(versionContext) - { - this.log = log ?? throw new ArgumentNullException(nameof(log)); - } + public MergeMessageVersionStrategy(ILog log, Lazy versionContext) : base(versionContext) => this.log = log ?? throw new ArgumentNullException(nameof(log)); public override IEnumerable GetVersions() { diff --git a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/TaggedCommitVersionStrategy.cs b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/TaggedCommitVersionStrategy.cs index e61feac768..a32d260627 100644 --- a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/TaggedCommitVersionStrategy.cs +++ b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/TaggedCommitVersionStrategy.cs @@ -15,10 +15,7 @@ public class TaggedCommitVersionStrategy : VersionStrategyBase { private readonly IRepositoryStore repositoryStore; - public TaggedCommitVersionStrategy(IRepositoryStore repositoryStore, Lazy versionContext) : base(versionContext) - { - this.repositoryStore = repositoryStore ?? throw new ArgumentNullException(nameof(repositoryStore)); - } + public TaggedCommitVersionStrategy(IRepositoryStore repositoryStore, Lazy versionContext) : base(versionContext) => this.repositoryStore = repositoryStore ?? throw new ArgumentNullException(nameof(repositoryStore)); public override IEnumerable GetVersions() => GetTaggedVersions(Context.CurrentBranch, Context.CurrentCommit?.When); diff --git a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/VersionInBranchNameVersionStrategy.cs b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/VersionInBranchNameVersionStrategy.cs index 11134a5f15..1d2a7a3c0c 100644 --- a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/VersionInBranchNameVersionStrategy.cs +++ b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/VersionInBranchNameVersionStrategy.cs @@ -15,10 +15,7 @@ public class VersionInBranchNameVersionStrategy : VersionStrategyBase { private readonly IRepositoryStore repositoryStore; - public VersionInBranchNameVersionStrategy(IRepositoryStore repositoryStore, Lazy versionContext) : base(versionContext) - { - this.repositoryStore = repositoryStore ?? throw new ArgumentNullException(nameof(repositoryStore)); - } + public VersionInBranchNameVersionStrategy(IRepositoryStore repositoryStore, Lazy versionContext) : base(versionContext) => this.repositoryStore = repositoryStore ?? throw new ArgumentNullException(nameof(repositoryStore)); public override IEnumerable GetVersions() { diff --git a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/VersionStrategyBase.cs b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/VersionStrategyBase.cs index 4aef58c215..c9b452a298 100644 --- a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/VersionStrategyBase.cs +++ b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/VersionStrategyBase.cs @@ -8,10 +8,7 @@ public class VersionStrategyBase : IVersionStrategy private readonly Lazy versionContext; protected GitVersionContext Context => this.versionContext.Value; - protected VersionStrategyBase(Lazy versionContext) - { - this.versionContext = versionContext ?? throw new ArgumentNullException(nameof(versionContext)); - } + protected VersionStrategyBase(Lazy versionContext) => this.versionContext = versionContext ?? throw new ArgumentNullException(nameof(versionContext)); public virtual IEnumerable GetVersions() => throw new NotImplementedException(); } } diff --git a/src/GitVersion.Core/VersionCalculation/MinDateVersionFilter.cs b/src/GitVersion.Core/VersionCalculation/MinDateVersionFilter.cs index 4a6bf2df36..4cfaba156b 100644 --- a/src/GitVersion.Core/VersionCalculation/MinDateVersionFilter.cs +++ b/src/GitVersion.Core/VersionCalculation/MinDateVersionFilter.cs @@ -7,10 +7,7 @@ public class MinDateVersionFilter : IVersionFilter { private readonly DateTimeOffset minimum; - public MinDateVersionFilter(DateTimeOffset minimum) - { - this.minimum = minimum; - } + public MinDateVersionFilter(DateTimeOffset minimum) => this.minimum = minimum; public bool Exclude(BaseVersion version, [NotNullWhen(true)] out string? reason) { diff --git a/src/GitVersion.Core/VersionCalculation/ShaVersionFilter.cs b/src/GitVersion.Core/VersionCalculation/ShaVersionFilter.cs index 7068a2cab6..2fc7dac558 100644 --- a/src/GitVersion.Core/VersionCalculation/ShaVersionFilter.cs +++ b/src/GitVersion.Core/VersionCalculation/ShaVersionFilter.cs @@ -9,10 +9,7 @@ public class ShaVersionFilter : IVersionFilter { private readonly IEnumerable shas; - public ShaVersionFilter(IEnumerable shas) - { - this.shas = shas ?? throw new ArgumentNullException(nameof(shas)); - } + public ShaVersionFilter(IEnumerable shas) => this.shas = shas ?? throw new ArgumentNullException(nameof(shas)); public bool Exclude(BaseVersion version, [NotNullWhen(true)] out string? reason) { diff --git a/src/GitVersion.Core/VersionConverters/WixUpdater/WixVersionContext.cs b/src/GitVersion.Core/VersionConverters/WixUpdater/WixVersionContext.cs index 8ef599a727..89294500a6 100644 --- a/src/GitVersion.Core/VersionConverters/WixUpdater/WixVersionContext.cs +++ b/src/GitVersion.Core/VersionConverters/WixUpdater/WixVersionContext.cs @@ -2,10 +2,8 @@ namespace GitVersion.VersionConverters.WixUpdater { public readonly struct WixVersionContext : IConverterContext { - public WixVersionContext(string? workingDirectory) - { + public WixVersionContext(string? workingDirectory) => WorkingDirectory = workingDirectory; - } public string? WorkingDirectory { get; } } diff --git a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildExeFixtureResult.cs b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildExeFixtureResult.cs index 1e9d663ebd..f40d64a074 100644 --- a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildExeFixtureResult.cs +++ b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildExeFixtureResult.cs @@ -8,10 +8,7 @@ public class MsBuildExeFixtureResult : IDisposable { private readonly RepositoryFixtureBase fixture; - public MsBuildExeFixtureResult(RepositoryFixtureBase fixture) - { - this.fixture = fixture; - } + public MsBuildExeFixtureResult(RepositoryFixtureBase fixture) => this.fixture = fixture; public IAnalyzerResults MsBuild { get; set; } public string Output { get; set; } public string ProjectPath { get; set; } diff --git a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixture.cs b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixture.cs index a0b7c8b51a..55884fcec9 100644 --- a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixture.cs +++ b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixture.cs @@ -14,10 +14,7 @@ public class MsBuildTaskFixture private readonly RepositoryFixtureBase fixture; private KeyValuePair[] environmentVariables; - public MsBuildTaskFixture(RepositoryFixtureBase fixture) - { - this.fixture = fixture; - } + public MsBuildTaskFixture(RepositoryFixtureBase fixture) => this.fixture = fixture; public void WithEnv(params KeyValuePair[] envs) => this.environmentVariables = envs; diff --git a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixtureResult.cs b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixtureResult.cs index ac8a82dcc8..6672b13cd1 100644 --- a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixtureResult.cs +++ b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixtureResult.cs @@ -8,10 +8,7 @@ public class MsBuildTaskFixtureResult : IDisposable where T : ITask { private readonly RepositoryFixtureBase fixture; - public MsBuildTaskFixtureResult(RepositoryFixtureBase fixture) - { - this.fixture = fixture; - } + public MsBuildTaskFixtureResult(RepositoryFixtureBase fixture) => this.fixture = fixture; public bool Success { get; set; } public T Task { get; set; } diff --git a/src/GitVersion.MsBuild/GitVersionTaskBase.cs b/src/GitVersion.MsBuild/GitVersionTaskBase.cs index 873fb904dc..bcd401e61b 100644 --- a/src/GitVersion.MsBuild/GitVersionTaskBase.cs +++ b/src/GitVersion.MsBuild/GitVersionTaskBase.cs @@ -8,10 +8,7 @@ public abstract class GitVersionTaskBase : ITask public IBuildEngine BuildEngine { get; set; } public ITaskHost HostObject { get; set; } - protected GitVersionTaskBase() - { - Log = new TaskLoggingHelper(this); - } + protected GitVersionTaskBase() => Log = new TaskLoggingHelper(this); [Required] public string SolutionDirectory { get; set; } diff --git a/src/GitVersion.MsBuild/Helpers/MsBuildAdapter.cs b/src/GitVersion.MsBuild/Helpers/MsBuildAdapter.cs index 1a1131441d..2eec2cf9ba 100644 --- a/src/GitVersion.MsBuild/Helpers/MsBuildAdapter.cs +++ b/src/GitVersion.MsBuild/Helpers/MsBuildAdapter.cs @@ -8,10 +8,7 @@ internal class MsBuildAdapter : IConsole { private readonly TaskLoggingHelper taskLog; - public MsBuildAdapter(TaskLoggingHelper taskLog) - { - this.taskLog = taskLog; - } + public MsBuildAdapter(TaskLoggingHelper taskLog) => this.taskLog = taskLog; public void WriteLine(string msg) { diff --git a/src/GitVersion.MsBuild/Helpers/MsBuildAppender.cs b/src/GitVersion.MsBuild/Helpers/MsBuildAppender.cs index e84ab9458a..e9495fb51c 100644 --- a/src/GitVersion.MsBuild/Helpers/MsBuildAppender.cs +++ b/src/GitVersion.MsBuild/Helpers/MsBuildAppender.cs @@ -8,10 +8,7 @@ public class MsBuildAppender : ILogAppender { private readonly TaskLoggingHelper taskLog; - public MsBuildAppender(TaskLoggingHelper taskLog) - { - this.taskLog = taskLog; - } + public MsBuildAppender(TaskLoggingHelper taskLog) => this.taskLog = taskLog; public void WriteTo(LogLevel level, string message) { From 9560628817ccdcfe8aa2a490bdc1d8e00eb15bc1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Fri, 16 Jul 2021 19:07:10 +0200 Subject: [PATCH 53/79] Expression body for lambdas --- src/GitVersion.App.Tests/HelpWriterTests.cs | 5 +- .../VersionWriterTests.cs | 5 +- src/GitVersion.App/Program.cs | 5 +- .../BuildAgents/AzurePipelinesTests.cs | 5 +- .../BuildAgents/BuildServerBaseTests.cs | 5 +- .../BuildAgents/CodeBuildTests.cs | 5 +- .../BuildAgents/ContinuaCiTests.cs | 5 +- .../BuildAgents/DroneTests.cs | 5 +- .../BuildAgents/EnvRunTests.cs | 5 +- .../BuildAgents/GitHubActionsTests.cs | 9 +-- .../BuildAgents/GitLabCiTests.cs | 5 +- .../BuildAgents/JenkinsTests.cs | 5 +- .../BuildAgents/MyGetTests.cs | 5 +- .../BuildAgents/SpaceAutomationTests.cs | 5 +- .../BuildAgents/TeamCityTests.cs | 5 +- .../Configuration/ConfigProviderTests.cs | 5 +- .../DefaultConfigFileLocatorTests.cs | 24 +++---- .../Core/DynamicRepositoryTests.cs | 5 +- .../Core/GitVersionToolDirectoryTests.cs | 10 +-- .../Extensions/GitToolsTestingExtensions.cs | 5 +- .../BaseVersionCalculatorTests.cs | 66 +++++++------------ .../VersionConverters/WixFileTests.cs | 10 +-- .../Git/ReferenceCollection.cs | 5 +- .../GenerateGitVersionInformationTest.cs | 10 +-- .../Tasks/GetVersionTaskTests.cs | 10 +-- .../Tasks/UpdateAssemblyInfoTaskTest.cs | 10 +-- .../Tasks/WriteVersionInfoTest.cs | 10 +-- 27 files changed, 66 insertions(+), 183 deletions(-) diff --git a/src/GitVersion.App.Tests/HelpWriterTests.cs b/src/GitVersion.App.Tests/HelpWriterTests.cs index 3b60606e13..17a566c23d 100644 --- a/src/GitVersion.App.Tests/HelpWriterTests.cs +++ b/src/GitVersion.App.Tests/HelpWriterTests.cs @@ -14,10 +14,7 @@ public class HelpWriterTests : TestBase public HelpWriterTests() { - var sp = ConfigureServices(services => - { - services.AddModule(new GitVersionAppModule()); - }); + var sp = ConfigureServices(services => services.AddModule(new GitVersionAppModule())); this.helpWriter = sp.GetService(); } diff --git a/src/GitVersion.App.Tests/VersionWriterTests.cs b/src/GitVersion.App.Tests/VersionWriterTests.cs index 58c071f0ad..ee3b33457c 100644 --- a/src/GitVersion.App.Tests/VersionWriterTests.cs +++ b/src/GitVersion.App.Tests/VersionWriterTests.cs @@ -16,10 +16,7 @@ public class VersionWriterTests : TestBase public VersionWriterTests() { - var sp = ConfigureServices(services => - { - services.AddModule(new GitVersionAppModule()); - }); + var sp = ConfigureServices(services => services.AddModule(new GitVersionAppModule())); this.versionWriter = sp.GetService(); } diff --git a/src/GitVersion.App/Program.cs b/src/GitVersion.App/Program.cs index 543bc5a0e2..305a344386 100644 --- a/src/GitVersion.App/Program.cs +++ b/src/GitVersion.App/Program.cs @@ -20,10 +20,7 @@ internal class Program private IHostBuilder CreateHostBuilder(string[] args) => new HostBuilder() - .ConfigureAppConfiguration((_, configApp) => - { - configApp.AddCommandLine(args); - }) + .ConfigureAppConfiguration((_, configApp) => configApp.AddCommandLine(args)) .ConfigureServices((_, services) => { services.AddModule(new GitVersionCoreModule()); diff --git a/src/GitVersion.Core.Tests/BuildAgents/AzurePipelinesTests.cs b/src/GitVersion.Core.Tests/BuildAgents/AzurePipelinesTests.cs index 7e5ea56f90..e7fd590853 100644 --- a/src/GitVersion.Core.Tests/BuildAgents/AzurePipelinesTests.cs +++ b/src/GitVersion.Core.Tests/BuildAgents/AzurePipelinesTests.cs @@ -18,10 +18,7 @@ public class AzurePipelinesTests : TestBase [SetUp] public void SetEnvironmentVariableForTest() { - var sp = ConfigureServices(services => - { - services.AddSingleton(); - }); + var sp = ConfigureServices(services => services.AddSingleton()); this.environment = sp.GetService(); this.buildServer = sp.GetService(); diff --git a/src/GitVersion.Core.Tests/BuildAgents/BuildServerBaseTests.cs b/src/GitVersion.Core.Tests/BuildAgents/BuildServerBaseTests.cs index 2f133ef94f..3d8dbcd5bb 100644 --- a/src/GitVersion.Core.Tests/BuildAgents/BuildServerBaseTests.cs +++ b/src/GitVersion.Core.Tests/BuildAgents/BuildServerBaseTests.cs @@ -20,10 +20,7 @@ public class BuildServerBaseTests : TestBase [SetUp] public void SetUp() { - this.sp = ConfigureServices(services => - { - services.AddSingleton(); - }); + this.sp = ConfigureServices(services => services.AddSingleton()); this.buildServer = this.sp.GetService(); } diff --git a/src/GitVersion.Core.Tests/BuildAgents/CodeBuildTests.cs b/src/GitVersion.Core.Tests/BuildAgents/CodeBuildTests.cs index cdf2a7a6ce..690663083f 100644 --- a/src/GitVersion.Core.Tests/BuildAgents/CodeBuildTests.cs +++ b/src/GitVersion.Core.Tests/BuildAgents/CodeBuildTests.cs @@ -21,10 +21,7 @@ public sealed class CodeBuildTests : TestBase [SetUp] public void SetUp() { - this.sp = ConfigureServices(services => - { - services.AddSingleton(); - }); + this.sp = ConfigureServices(services => services.AddSingleton()); this.environment = this.sp.GetService(); this.buildServer = this.sp.GetService(); } diff --git a/src/GitVersion.Core.Tests/BuildAgents/ContinuaCiTests.cs b/src/GitVersion.Core.Tests/BuildAgents/ContinuaCiTests.cs index 51f377af8c..53a26a0c97 100644 --- a/src/GitVersion.Core.Tests/BuildAgents/ContinuaCiTests.cs +++ b/src/GitVersion.Core.Tests/BuildAgents/ContinuaCiTests.cs @@ -12,10 +12,7 @@ public class ContinuaCiTests : TestBase private IServiceProvider sp; [SetUp] - public void SetUp() => this.sp = ConfigureServices(services => - { - services.AddSingleton(); - }); + public void SetUp() => this.sp = ConfigureServices(services => services.AddSingleton()); [Test] public void GenerateBuildVersion() diff --git a/src/GitVersion.Core.Tests/BuildAgents/DroneTests.cs b/src/GitVersion.Core.Tests/BuildAgents/DroneTests.cs index 4c40fe73cc..b71bfef4a0 100644 --- a/src/GitVersion.Core.Tests/BuildAgents/DroneTests.cs +++ b/src/GitVersion.Core.Tests/BuildAgents/DroneTests.cs @@ -17,10 +17,7 @@ public class DroneTests : TestBase [SetUp] public void SetUp() { - this.sp = ConfigureServices(services => - { - services.AddSingleton(); - }); + this.sp = ConfigureServices(services => services.AddSingleton()); this.environment = this.sp.GetService(); this.buildServer = this.sp.GetService(); this.environment.SetEnvironmentVariable("DRONE", "true"); diff --git a/src/GitVersion.Core.Tests/BuildAgents/EnvRunTests.cs b/src/GitVersion.Core.Tests/BuildAgents/EnvRunTests.cs index 67de91c32b..8aed5357b9 100644 --- a/src/GitVersion.Core.Tests/BuildAgents/EnvRunTests.cs +++ b/src/GitVersion.Core.Tests/BuildAgents/EnvRunTests.cs @@ -18,10 +18,7 @@ public class EnvRunTests : TestBase [SetUp] public void SetEnvironmentVariableForTest() { - var sp = ConfigureServices(services => - { - services.AddSingleton(); - }); + var sp = ConfigureServices(services => services.AddSingleton()); this.environment = sp.GetService(); this.buildServer = sp.GetService(); diff --git a/src/GitVersion.Core.Tests/BuildAgents/GitHubActionsTests.cs b/src/GitVersion.Core.Tests/BuildAgents/GitHubActionsTests.cs index 89effffe38..148a15d458 100644 --- a/src/GitVersion.Core.Tests/BuildAgents/GitHubActionsTests.cs +++ b/src/GitVersion.Core.Tests/BuildAgents/GitHubActionsTests.cs @@ -19,10 +19,7 @@ public class GitHubActionsTests : TestBase [SetUp] public void SetUp() { - var sp = ConfigureServices(services => - { - services.AddSingleton(); - }); + var sp = ConfigureServices(services => services.AddSingleton()); this.environment = sp.GetService(); this.buildServer = sp.GetService(); this.environment.SetEnvironmentVariable(GitHubActions.EnvironmentVariableName, "true"); @@ -140,7 +137,7 @@ public void ShouldWriteIntegration() this.environment.GetEnvironmentVariable("GitVersion_Major").ShouldBeNullOrWhiteSpace(); // Act - this.buildServer.WriteIntegration(s => { list.Add(s); }, vars); + this.buildServer.WriteIntegration(s => list.Add(s), vars); // Assert var expected = new List @@ -176,7 +173,7 @@ public void ShouldNotWriteIntegration() this.environment.GetEnvironmentVariable("GitVersion_Major").ShouldBeNullOrWhiteSpace(); // Act - this.buildServer.WriteIntegration(s => { list.Add(s); }, vars, false); + this.buildServer.WriteIntegration(s => list.Add(s), vars, false); list.ShouldNotContain(x => x.StartsWith("Executing GenerateSetVersionMessage for ")); } diff --git a/src/GitVersion.Core.Tests/BuildAgents/GitLabCiTests.cs b/src/GitVersion.Core.Tests/BuildAgents/GitLabCiTests.cs index 04a6490afb..7f79d4e92c 100644 --- a/src/GitVersion.Core.Tests/BuildAgents/GitLabCiTests.cs +++ b/src/GitVersion.Core.Tests/BuildAgents/GitLabCiTests.cs @@ -20,10 +20,7 @@ public class GitLabCiTests : TestBase [SetUp] public void SetUp() { - this.sp = ConfigureServices(services => - { - services.AddSingleton(); - }); + this.sp = ConfigureServices(services => services.AddSingleton()); this.buildServer = this.sp.GetService(); } diff --git a/src/GitVersion.Core.Tests/BuildAgents/JenkinsTests.cs b/src/GitVersion.Core.Tests/BuildAgents/JenkinsTests.cs index 5f16f558c5..127ece3db8 100644 --- a/src/GitVersion.Core.Tests/BuildAgents/JenkinsTests.cs +++ b/src/GitVersion.Core.Tests/BuildAgents/JenkinsTests.cs @@ -25,10 +25,7 @@ public class JenkinsTests : TestBase [SetUp] public void SetUp() { - this.sp = ConfigureServices(services => - { - services.AddSingleton(); - }); + this.sp = ConfigureServices(services => services.AddSingleton()); this.environment = this.sp.GetService(); this.buildServer = this.sp.GetService(); } diff --git a/src/GitVersion.Core.Tests/BuildAgents/MyGetTests.cs b/src/GitVersion.Core.Tests/BuildAgents/MyGetTests.cs index 0bfff09006..599ed0c2ca 100644 --- a/src/GitVersion.Core.Tests/BuildAgents/MyGetTests.cs +++ b/src/GitVersion.Core.Tests/BuildAgents/MyGetTests.cs @@ -13,10 +13,7 @@ public class MyGetTests : TestBase [SetUp] public void SetUp() { - var sp = ConfigureServices(services => - { - services.AddSingleton(); - }); + var sp = ConfigureServices(services => services.AddSingleton()); this.buildServer = sp.GetService(); } diff --git a/src/GitVersion.Core.Tests/BuildAgents/SpaceAutomationTests.cs b/src/GitVersion.Core.Tests/BuildAgents/SpaceAutomationTests.cs index 4db9066847..d3f022000c 100644 --- a/src/GitVersion.Core.Tests/BuildAgents/SpaceAutomationTests.cs +++ b/src/GitVersion.Core.Tests/BuildAgents/SpaceAutomationTests.cs @@ -17,10 +17,7 @@ public class SpaceAutomationTests : TestBase [SetUp] public void SetUp() { - var sp = ConfigureServices(services => - { - services.AddSingleton(); - }); + var sp = ConfigureServices(services => services.AddSingleton()); this.environment = sp.GetService(); this.buildServer = sp.GetService(); this.environment.SetEnvironmentVariable(SpaceAutomation.EnvironmentVariableName, "true"); diff --git a/src/GitVersion.Core.Tests/BuildAgents/TeamCityTests.cs b/src/GitVersion.Core.Tests/BuildAgents/TeamCityTests.cs index ac0ccbe4b8..42e7fffe83 100644 --- a/src/GitVersion.Core.Tests/BuildAgents/TeamCityTests.cs +++ b/src/GitVersion.Core.Tests/BuildAgents/TeamCityTests.cs @@ -13,10 +13,7 @@ public class TeamCityTests : TestBase [SetUp] public void SetUp() { - var sp = ConfigureServices(services => - { - services.AddSingleton(); - }); + var sp = ConfigureServices(services => services.AddSingleton()); this.buildServer = sp.GetService(); } diff --git a/src/GitVersion.Core.Tests/Configuration/ConfigProviderTests.cs b/src/GitVersion.Core.Tests/Configuration/ConfigProviderTests.cs index 87a2bf87a5..60d3574a50 100644 --- a/src/GitVersion.Core.Tests/Configuration/ConfigProviderTests.cs +++ b/src/GitVersion.Core.Tests/Configuration/ConfigProviderTests.cs @@ -32,10 +32,7 @@ public void Setup() { this.repoPath = DefaultRepoPath; var options = Options.Create(new GitVersionOptions { WorkingDirectory = repoPath }); - var sp = ConfigureServices(services => - { - services.AddSingleton(options); - }); + var sp = ConfigureServices(services => services.AddSingleton(options)); this.configProvider = sp.GetService(); this.fileSystem = sp.GetService(); diff --git a/src/GitVersion.Core.Tests/Configuration/DefaultConfigFileLocatorTests.cs b/src/GitVersion.Core.Tests/Configuration/DefaultConfigFileLocatorTests.cs index d7ec241ec9..f2c940cb8a 100644 --- a/src/GitVersion.Core.Tests/Configuration/DefaultConfigFileLocatorTests.cs +++ b/src/GitVersion.Core.Tests/Configuration/DefaultConfigFileLocatorTests.cs @@ -32,10 +32,7 @@ public void Setup() this.workingPath = DefaultWorkingPath; var options = Options.Create(new GitVersionOptions { WorkingDirectory = repoPath }); - var sp = ConfigureServices(services => - { - services.AddSingleton(options); - }); + var sp = ConfigureServices(services => services.AddSingleton(options)); this.fileSystem = sp.GetService(); this.configurationProvider = sp.GetService(); @@ -50,10 +47,7 @@ public void ThrowsExceptionOnAmbiguousConfigFileLocation(string repoConfigFile, var repositoryConfigFilePath = SetupConfigFileContent(string.Empty, repoConfigFile, this.repoPath); var workingDirectoryConfigFilePath = SetupConfigFileContent(string.Empty, workingConfigFile, this.workingPath); - var exception = Should.Throw(() => - { - this.configFileLocator.Verify(this.workingPath, this.repoPath); - }); + var exception = Should.Throw(() => this.configFileLocator.Verify(this.workingPath, this.repoPath)); var expecedMessage = $"Ambiguous config file selection from '{workingDirectoryConfigFilePath}' and '{repositoryConfigFilePath}'"; exception.Message.ShouldBe(expecedMessage); @@ -64,11 +58,11 @@ public void NoWarnOnGitVersionYmlFile() { SetupConfigFileContent(string.Empty, ConfigFileLocator.DefaultFileName, this.repoPath); - Should.NotThrow(() => { this.configurationProvider.Provide(this.repoPath); }); + Should.NotThrow(() => this.configurationProvider.Provide(this.repoPath)); } [Test] - public void NoWarnOnNoGitVersionYmlFile() => Should.NotThrow(() => { this.configurationProvider.Provide(this.repoPath); }); + public void NoWarnOnNoGitVersionYmlFile() => Should.NotThrow(() => this.configurationProvider.Provide(this.repoPath)); private string SetupConfigFileContent(string text, string fileName, string path) { @@ -110,7 +104,7 @@ public void ThrowsExceptionOnAmbiguousConfigFileLocation() var repositoryConfigFilePath = SetupConfigFileContent(string.Empty, path: this.repoPath); var workingDirectoryConfigFilePath = SetupConfigFileContent(string.Empty, path: this.workingPath); - var exception = Should.Throw(() => { this.configFileLocator.Verify(this.workingPath, this.repoPath); }); + var exception = Should.Throw(() => this.configFileLocator.Verify(this.workingPath, this.repoPath)); var expectedMessage = $"Ambiguous config file selection from '{workingDirectoryConfigFilePath}' and '{repositoryConfigFilePath}'"; exception.Message.ShouldBe(expectedMessage); @@ -127,7 +121,7 @@ public void DoNotThrowWhenWorkingAndRepoPathsAreSame() SetupConfigFileContent(string.Empty, path: this.workingPath); - Should.NotThrow(() => { this.configFileLocator.Verify(this.workingPath, this.repoPath); }); + Should.NotThrow(() => this.configFileLocator.Verify(this.workingPath, this.repoPath)); } [Test] @@ -141,7 +135,7 @@ public void DoNotThrowWhenWorkingAndRepoPathsAreSame_WithDifferentCasing() SetupConfigFileContent(string.Empty, path: this.workingPath); - Should.NotThrow(() => { this.configFileLocator.Verify(this.workingPath, this.repoPath); }); + Should.NotThrow(() => this.configFileLocator.Verify(this.workingPath, this.repoPath)); } [Test] @@ -156,7 +150,7 @@ public void DoNotThrowWhenConfigFileIsInSubDirectoryOfRepoPath() SetupConfigFileContent(string.Empty, path: this.workingPath); - Should.NotThrow(() => { this.configFileLocator.Verify(this.workingPath, this.repoPath); }); + Should.NotThrow(() => this.configFileLocator.Verify(this.workingPath, this.repoPath)); } [Test] @@ -207,7 +201,7 @@ public void ThrowsExceptionOnCustomYmlFileDoesNotExist() var sp = GetServiceProvider(this.gitVersionOptions); this.configFileLocator = sp.GetService(); - var exception = Should.Throw(() => { this.configFileLocator.Verify(this.workingPath, this.repoPath); }); + var exception = Should.Throw(() => this.configFileLocator.Verify(this.workingPath, this.repoPath)); var workingPathFileConfig = Path.Combine(this.workingPath, this.gitVersionOptions.ConfigInfo.ConfigFile); var repoPathFileConfig = Path.Combine(this.repoPath, this.gitVersionOptions.ConfigInfo.ConfigFile); diff --git a/src/GitVersion.Core.Tests/Core/DynamicRepositoryTests.cs b/src/GitVersion.Core.Tests/Core/DynamicRepositoryTests.cs index 7d59c725cc..f572afe661 100644 --- a/src/GitVersion.Core.Tests/Core/DynamicRepositoryTests.cs +++ b/src/GitVersion.Core.Tests/Core/DynamicRepositoryTests.cs @@ -76,10 +76,7 @@ public void FindsVersionInDynamicRepo(string name, string url, string targetBran Directory.CreateDirectory(dynamicDirectory); Directory.CreateDirectory(workingDirectory); - var sp = ConfigureServices(services => - { - services.AddSingleton(options); - }); + var sp = ConfigureServices(services => services.AddSingleton(options)); var gitPreparer = sp.GetService(); gitPreparer?.Prepare(); diff --git a/src/GitVersion.Core.Tests/Core/GitVersionToolDirectoryTests.cs b/src/GitVersion.Core.Tests/Core/GitVersionToolDirectoryTests.cs index 1e38f6363a..f68e15d581 100644 --- a/src/GitVersion.Core.Tests/Core/GitVersionToolDirectoryTests.cs +++ b/src/GitVersion.Core.Tests/Core/GitVersionToolDirectoryTests.cs @@ -33,10 +33,7 @@ public void FindsGitDirectory() { var options = Options.Create(new GitVersionOptions { WorkingDirectory = workDirectory, Settings = { NoFetch = true } }); - var sp = ConfigureServices(services => - { - services.AddSingleton(options); - }); + var sp = ConfigureServices(services => services.AddSingleton(options)); var gitVersionCalculator = sp.GetService(); @@ -61,10 +58,7 @@ public void FindsGitDirectoryInParent() { var options = Options.Create(new GitVersionOptions { WorkingDirectory = childDir, Settings = { NoFetch = true } }); - var sp = ConfigureServices(services => - { - services.AddSingleton(options); - }); + var sp = ConfigureServices(services => services.AddSingleton(options)); var gitVersionCalculator = sp.GetService(); diff --git a/src/GitVersion.Core.Tests/Extensions/GitToolsTestingExtensions.cs b/src/GitVersion.Core.Tests/Extensions/GitToolsTestingExtensions.cs index 969f6d1826..78216b815b 100644 --- a/src/GitVersion.Core.Tests/Extensions/GitToolsTestingExtensions.cs +++ b/src/GitVersion.Core.Tests/Extensions/GitToolsTestingExtensions.cs @@ -76,10 +76,7 @@ public static VersionVariables GetVersion(this RepositoryFixtureBase fixture, Co Settings = { OnlyTrackedBranches = onlyTrackedBranches } }); - var sp = ConfigureServices(services => - { - services.AddSingleton(options); - }); + var sp = ConfigureServices(services => services.AddSingleton(options)); var variableProvider = sp.GetService(); var nextVersionCalculator = sp.GetService(); diff --git a/src/GitVersion.Core.Tests/VersionCalculation/BaseVersionCalculatorTests.cs b/src/GitVersion.Core.Tests/VersionCalculation/BaseVersionCalculatorTests.cs index 5c279e5322..6dd3f00f50 100644 --- a/src/GitVersion.Core.Tests/VersionCalculation/BaseVersionCalculatorTests.cs +++ b/src/GitVersion.Core.Tests/VersionCalculation/BaseVersionCalculatorTests.cs @@ -18,15 +18,12 @@ public class BaseVersionCalculatorTests : TestBase public void ChoosesHighestVersionReturnedFromStrategies() { var dateTimeOffset = DateTimeOffset.Now; - var versionCalculator = GetBaseVersionCalculator(contextBuilder => - { - contextBuilder.OverrideServices(services => - { - services.RemoveAll(); - services.AddSingleton(new V1Strategy(DateTimeOffset.Now)); - services.AddSingleton(new V2Strategy(dateTimeOffset)); - }); - }); + var versionCalculator = GetBaseVersionCalculator(contextBuilder => contextBuilder.OverrideServices(services => +{ + services.RemoveAll(); + services.AddSingleton(new V1Strategy(DateTimeOffset.Now)); + services.AddSingleton(new V2Strategy(dateTimeOffset)); +})); var baseVersion = versionCalculator.GetBaseVersion(); @@ -40,15 +37,12 @@ public void UsesWhenFromNextBestMatchIfHighestDoesntHaveWhen() { var when = DateTimeOffset.Now; - var versionCalculator = GetBaseVersionCalculator(contextBuilder => - { - contextBuilder.OverrideServices(services => - { - services.RemoveAll(); - services.AddSingleton(new V1Strategy(when)); - services.AddSingleton(new V2Strategy(null)); - }); - }); + var versionCalculator = GetBaseVersionCalculator(contextBuilder => contextBuilder.OverrideServices(services => +{ + services.RemoveAll(); + services.AddSingleton(new V1Strategy(when)); + services.AddSingleton(new V2Strategy(null)); +})); var baseVersion = versionCalculator.GetBaseVersion(); @@ -62,15 +56,12 @@ public void UsesWhenFromNextBestMatchIfHighestDoesntHaveWhenReversedOrder() { var when = DateTimeOffset.Now; - var versionCalculator = GetBaseVersionCalculator(contextBuilder => - { - contextBuilder.OverrideServices(services => - { - services.RemoveAll(); - services.AddSingleton(new V1Strategy(null)); - services.AddSingleton(new V2Strategy(when)); - }); - }); + var versionCalculator = GetBaseVersionCalculator(contextBuilder => contextBuilder.OverrideServices(services => +{ + services.RemoveAll(); + services.AddSingleton(new V1Strategy(null)); + services.AddSingleton(new V2Strategy(when)); +})); var baseVersion = versionCalculator.GetBaseVersion(); @@ -85,16 +76,13 @@ public void ShouldNotFilterVersion() var fakeIgnoreConfig = new TestIgnoreConfig(new ExcludeSourcesContainingExclude()); var version = new BaseVersion("dummy", false, new SemanticVersion(2), GitToolsTestingExtensions.CreateMockCommit(), null); - var versionCalculator = GetBaseVersionCalculator(contextBuilder => - { - contextBuilder + var versionCalculator = GetBaseVersionCalculator(contextBuilder => contextBuilder .WithConfig(new Config { Ignore = fakeIgnoreConfig }) .OverrideServices(services => { services.RemoveAll(); services.AddSingleton(new TestVersionStrategy(version)); - }); - }); + })); var baseVersion = versionCalculator.GetBaseVersion(); @@ -111,16 +99,13 @@ public void ShouldFilterVersion() var higherVersion = new BaseVersion("exclude", false, new SemanticVersion(2), GitToolsTestingExtensions.CreateMockCommit(), null); var lowerVersion = new BaseVersion("dummy", false, new SemanticVersion(1), GitToolsTestingExtensions.CreateMockCommit(), null); - var versionCalculator = GetBaseVersionCalculator(contextBuilder => - { - contextBuilder + var versionCalculator = GetBaseVersionCalculator(contextBuilder => contextBuilder .WithConfig(new Config { Ignore = fakeIgnoreConfig }) .OverrideServices(services => { services.RemoveAll(); services.AddSingleton(new TestVersionStrategy(higherVersion, lowerVersion)); - }); - }); + })); var baseVersion = versionCalculator.GetBaseVersion(); baseVersion.Source.ShouldNotBe(higherVersion.Source); @@ -150,16 +135,13 @@ public void ShouldIgnorePreReleaseVersionInMainlineMode() null ); - var versionCalculator = GetBaseVersionCalculator(contextBuilder => - { - contextBuilder + var versionCalculator = GetBaseVersionCalculator(contextBuilder => contextBuilder .WithConfig(new Config { VersioningMode = VersioningMode.Mainline, Ignore = fakeIgnoreConfig }) .OverrideServices(services => { services.RemoveAll(); services.AddSingleton(new TestVersionStrategy(preReleaseVersion, lowerVersion)); - }); - }); + })); var baseVersion = versionCalculator.GetBaseVersion(); baseVersion.Source.ShouldNotBe(preReleaseVersion.Source); diff --git a/src/GitVersion.Core.Tests/VersionConverters/WixFileTests.cs b/src/GitVersion.Core.Tests/VersionConverters/WixFileTests.cs index 6a4e9d4e27..1791c45497 100644 --- a/src/GitVersion.Core.Tests/VersionConverters/WixFileTests.cs +++ b/src/GitVersion.Core.Tests/VersionConverters/WixFileTests.cs @@ -45,10 +45,7 @@ public void UpdateWixVersionFile() var logAppender = new TestLogAppender(Action); var log = new Log(logAppender); - var sp = ConfigureServices(service => - { - service.AddSingleton(log); - }); + var sp = ConfigureServices(service => service.AddSingleton(log)); var fileSystem = sp.GetService(); var variableProvider = sp.GetService(); @@ -91,10 +88,7 @@ public void UpdateWixVersionFileWhenFileAlreadyExists() var logAppender = new TestLogAppender(Action); var log = new Log(logAppender); - var sp = ConfigureServices(service => - { - service.AddSingleton(log); - }); + var sp = ConfigureServices(service => service.AddSingleton(log)); var fileSystem = sp.GetService(); var variableProvider = sp.GetService(); diff --git a/src/GitVersion.LibGit2Sharp/Git/ReferenceCollection.cs b/src/GitVersion.LibGit2Sharp/Git/ReferenceCollection.cs index 55488ea56b..b31f65db70 100644 --- a/src/GitVersion.LibGit2Sharp/Git/ReferenceCollection.cs +++ b/src/GitVersion.LibGit2Sharp/Git/ReferenceCollection.cs @@ -13,10 +13,7 @@ internal sealed class ReferenceCollection : IReferenceCollection public void Add(string name, string canonicalRefNameOrObjectish, bool allowOverwrite = false) => this.innerCollection.Add(name, canonicalRefNameOrObjectish, allowOverwrite); - public void UpdateTarget(IReference directRef, IObjectId targetId) => RepositoryExtensions.RunSafe(() => - { - this.innerCollection.UpdateTarget((Reference)directRef, (ObjectId)targetId); - }); + public void UpdateTarget(IReference directRef, IObjectId targetId) => RepositoryExtensions.RunSafe(() => this.innerCollection.UpdateTarget((Reference)directRef, (ObjectId)targetId)); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); diff --git a/src/GitVersion.MsBuild.Tests/Tasks/GenerateGitVersionInformationTest.cs b/src/GitVersion.MsBuild.Tests/Tasks/GenerateGitVersionInformationTest.cs index 662d17a795..1887d5b47c 100644 --- a/src/GitVersion.MsBuild.Tests/Tasks/GenerateGitVersionInformationTest.cs +++ b/src/GitVersion.MsBuild.Tests/Tasks/GenerateGitVersionInformationTest.cs @@ -59,10 +59,7 @@ public void GenerateGitVersionInformationTaskShouldCreateFileWhenRunWithMsBuild( const string taskName = nameof(GenerateGitVersionInformation); const string outputProperty = nameof(GenerateGitVersionInformation.GitVersionInformationFilePath); - using var result = ExecuteMsBuildExe(project => - { - AddGenerateGitVersionInformationTask(project, taskName, taskName, outputProperty); - }); + using var result = ExecuteMsBuildExe(project => AddGenerateGitVersionInformationTask(project, taskName, taskName, outputProperty)); result.ProjectPath.ShouldNotBeNullOrWhiteSpace(); result.MsBuild.Count.ShouldBeGreaterThan(0); @@ -89,10 +86,7 @@ public void GenerateGitVersionInformationTaskShouldCreateFileWhenRunWithMsBuildI const string taskName = nameof(GenerateGitVersionInformation); const string outputProperty = nameof(GenerateGitVersionInformation.GitVersionInformationFilePath); - using var result = ExecuteMsBuildExeInAzurePipeline(project => - { - AddGenerateGitVersionInformationTask(project, taskName, taskName, outputProperty); - }); + using var result = ExecuteMsBuildExeInAzurePipeline(project => AddGenerateGitVersionInformationTask(project, taskName, taskName, outputProperty)); result.ProjectPath.ShouldNotBeNullOrWhiteSpace(); result.MsBuild.Count.ShouldBeGreaterThan(0); diff --git a/src/GitVersion.MsBuild.Tests/Tasks/GetVersionTaskTests.cs b/src/GitVersion.MsBuild.Tests/Tasks/GetVersionTaskTests.cs index df8459ec23..3f56366489 100644 --- a/src/GitVersion.MsBuild.Tests/Tasks/GetVersionTaskTests.cs +++ b/src/GitVersion.MsBuild.Tests/Tasks/GetVersionTaskTests.cs @@ -69,10 +69,7 @@ public void GetVersionTaskShouldReturnVersionOutputVariablesWhenRunWithMsBuild(s { const string taskName = nameof(GetVersion); - using var result = ExecuteMsBuildExe(project => - { - AddGetVersionTask(project, taskName, taskName, outputProperty); - }); + using var result = ExecuteMsBuildExe(project => AddGetVersionTask(project, taskName, taskName, outputProperty)); result.ProjectPath.ShouldNotBeNullOrWhiteSpace(); result.MsBuild.Count.ShouldBeGreaterThan(0); @@ -93,10 +90,7 @@ public void GetVersionTaskShouldReturnVersionOutputVariablesWhenRunWithMsBuildIn { const string taskName = nameof(GetVersion); - using var result = ExecuteMsBuildExeInAzurePipeline(project => - { - AddGetVersionTask(project, taskName, taskName, outputProperty); - }); + using var result = ExecuteMsBuildExeInAzurePipeline(project => AddGetVersionTask(project, taskName, taskName, outputProperty)); result.ProjectPath.ShouldNotBeNullOrWhiteSpace(); result.MsBuild.Count.ShouldBeGreaterThan(0); diff --git a/src/GitVersion.MsBuild.Tests/Tasks/UpdateAssemblyInfoTaskTest.cs b/src/GitVersion.MsBuild.Tests/Tasks/UpdateAssemblyInfoTaskTest.cs index 56182cb021..74310fd7ae 100644 --- a/src/GitVersion.MsBuild.Tests/Tasks/UpdateAssemblyInfoTaskTest.cs +++ b/src/GitVersion.MsBuild.Tests/Tasks/UpdateAssemblyInfoTaskTest.cs @@ -50,10 +50,7 @@ public void UpdateAssemblyInfoTaskShouldCreateFileWhenRunWithMsBuild() const string taskName = nameof(UpdateAssemblyInfo); const string outputProperty = nameof(UpdateAssemblyInfo.AssemblyInfoTempFilePath); - using var result = ExecuteMsBuildExe(project => - { - AddUpdateAssemblyInfoTask(project, taskName, taskName, outputProperty); - }); + using var result = ExecuteMsBuildExe(project => AddUpdateAssemblyInfoTask(project, taskName, taskName, outputProperty)); result.ProjectPath.ShouldNotBeNullOrWhiteSpace(); result.MsBuild.Count.ShouldBeGreaterThan(0); @@ -76,10 +73,7 @@ public void UpdateAssemblyInfoTaskShouldCreateFileWhenRunWithMsBuildInBuildServe const string taskName = nameof(UpdateAssemblyInfo); const string outputProperty = nameof(UpdateAssemblyInfo.AssemblyInfoTempFilePath); - using var result = ExecuteMsBuildExeInAzurePipeline(project => - { - AddUpdateAssemblyInfoTask(project, taskName, taskName, outputProperty); - }); + using var result = ExecuteMsBuildExeInAzurePipeline(project => AddUpdateAssemblyInfoTask(project, taskName, taskName, outputProperty)); result.ProjectPath.ShouldNotBeNullOrWhiteSpace(); result.MsBuild.Count.ShouldBeGreaterThan(0); diff --git a/src/GitVersion.MsBuild.Tests/Tasks/WriteVersionInfoTest.cs b/src/GitVersion.MsBuild.Tests/Tasks/WriteVersionInfoTest.cs index 03f261b3db..b330f8ec79 100644 --- a/src/GitVersion.MsBuild.Tests/Tasks/WriteVersionInfoTest.cs +++ b/src/GitVersion.MsBuild.Tests/Tasks/WriteVersionInfoTest.cs @@ -100,10 +100,7 @@ public void WriteVersionInfoTaskShouldNotLogOutputVariablesToBuildOutputWhenRunW { const string taskName = nameof(WriteVersionInfoToBuildLog); - using var result = ExecuteMsBuildExe(project => - { - AddWriteVersionInfoToBuildLogTask(project, taskName, taskName); - }); + using var result = ExecuteMsBuildExe(project => AddWriteVersionInfoToBuildLogTask(project, taskName, taskName)); result.ProjectPath.ShouldNotBeNullOrWhiteSpace(); result.MsBuild.Count.ShouldBeGreaterThan(0); @@ -120,10 +117,7 @@ public void WriteVersionInfoTaskShouldLogOutputVariablesToBuildOutputWhenRunWith { const string taskName = nameof(WriteVersionInfoToBuildLog); - using var result = ExecuteMsBuildExeInAzurePipeline(project => - { - AddWriteVersionInfoToBuildLogTask(project, taskName, taskName); - }); + using var result = ExecuteMsBuildExeInAzurePipeline(project => AddWriteVersionInfoToBuildLogTask(project, taskName, taskName)); result.ProjectPath.ShouldNotBeNullOrWhiteSpace(); result.MsBuild.Count.ShouldBeGreaterThan(0); From 31da906814f56f4a9bcb22c3d967dd596da458cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Fri, 16 Jul 2021 19:25:38 +0200 Subject: [PATCH 54/79] Expression body for operators --- src/GitVersion.Core/Model/BranchCommit.cs | 10 ++---- .../SemanticVersioning/SemanticVersion.cs | 5 +-- .../SemanticVersionBuildMetaData.cs | 12 +++---- .../SemanticVersionPreReleaseTag.cs | 36 +++++++------------ 4 files changed, 19 insertions(+), 44 deletions(-) diff --git a/src/GitVersion.Core/Model/BranchCommit.cs b/src/GitVersion.Core/Model/BranchCommit.cs index 8db9e720ec..3b8d6eb8fd 100644 --- a/src/GitVersion.Core/Model/BranchCommit.cs +++ b/src/GitVersion.Core/Model/BranchCommit.cs @@ -35,14 +35,8 @@ public override int GetHashCode() } } - public static bool operator ==(BranchCommit left, BranchCommit right) - { - return left.Equals(right); - } + public static bool operator ==(BranchCommit left, BranchCommit right) => left.Equals(right); - public static bool operator !=(BranchCommit left, BranchCommit right) - { - return !left.Equals(right); - } + public static bool operator !=(BranchCommit left, BranchCommit right) => !left.Equals(right); } } diff --git a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs index b6f3014472..3f9b9abc9b 100644 --- a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs +++ b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs @@ -92,10 +92,7 @@ public override int GetHashCode() return v1.Equals(v2); } - public static bool operator !=(SemanticVersion? v1, SemanticVersion? v2) - { - return !(v1 == v2); - } + public static bool operator !=(SemanticVersion? v1, SemanticVersion? v2) => !(v1 == v2); public static bool operator >(SemanticVersion v1, SemanticVersion v2) { diff --git a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionBuildMetaData.cs b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionBuildMetaData.cs index cb06d85964..c7272b9df6 100644 --- a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionBuildMetaData.cs +++ b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionBuildMetaData.cs @@ -105,15 +105,11 @@ public string ToString(string? format, IFormatProvider? formatProvider = null) }; } - public static bool operator ==(SemanticVersionBuildMetaData? left, SemanticVersionBuildMetaData? right) - { - return Equals(left, right); - } + public static bool operator ==(SemanticVersionBuildMetaData? left, SemanticVersionBuildMetaData? right) => + Equals(left, right); - public static bool operator !=(SemanticVersionBuildMetaData? left, SemanticVersionBuildMetaData? right) - { - return !Equals(left, right); - } + public static bool operator !=(SemanticVersionBuildMetaData? left, SemanticVersionBuildMetaData? right) => + !Equals(left, right); public static implicit operator string?(SemanticVersionBuildMetaData? preReleaseTag) { diff --git a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionPreReleaseTag.cs b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionPreReleaseTag.cs index bf0a476b07..65ffc67e93 100644 --- a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionPreReleaseTag.cs +++ b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionPreReleaseTag.cs @@ -39,35 +39,23 @@ public SemanticVersionPreReleaseTag(SemanticVersionPreReleaseTag? preReleaseTag) public override int GetHashCode() => EqualityHelper.GetHashCode(this); - public static bool operator ==(SemanticVersionPreReleaseTag? left, SemanticVersionPreReleaseTag? right) - { - return Equals(left, right); - } + public static bool operator ==(SemanticVersionPreReleaseTag? left, SemanticVersionPreReleaseTag? right) => + Equals(left, right); - public static bool operator !=(SemanticVersionPreReleaseTag? left, SemanticVersionPreReleaseTag? right) - { - return !Equals(left, right); - } + public static bool operator !=(SemanticVersionPreReleaseTag? left, SemanticVersionPreReleaseTag? right) => + !Equals(left, right); - public static bool operator >(SemanticVersionPreReleaseTag? left, SemanticVersionPreReleaseTag? right) - { - return left?.CompareTo(right) > 0; - } + public static bool operator >(SemanticVersionPreReleaseTag? left, SemanticVersionPreReleaseTag? right) => + left?.CompareTo(right) > 0; - public static bool operator <(SemanticVersionPreReleaseTag? left, SemanticVersionPreReleaseTag? right) - { - return left?.CompareTo(right) < 0; - } + public static bool operator <(SemanticVersionPreReleaseTag? left, SemanticVersionPreReleaseTag? right) => + left?.CompareTo(right) < 0; - public static bool operator >=(SemanticVersionPreReleaseTag? left, SemanticVersionPreReleaseTag? right) - { - return left?.CompareTo(right) >= 0; - } + public static bool operator >=(SemanticVersionPreReleaseTag? left, SemanticVersionPreReleaseTag? right) => + left?.CompareTo(right) >= 0; - public static bool operator <=(SemanticVersionPreReleaseTag? left, SemanticVersionPreReleaseTag? right) - { - return StringComparerUtils.IgnoreCaseComparer.Compare(left?.Name, right?.Name) != 1; - } + public static bool operator <=(SemanticVersionPreReleaseTag? left, SemanticVersionPreReleaseTag? right) => + StringComparerUtils.IgnoreCaseComparer.Compare(left?.Name, right?.Name) != 1; public static implicit operator string?(SemanticVersionPreReleaseTag? preReleaseTag) { From 03b3c2c55d250424e7bf99048a31de1a73a9636b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Fri, 16 Jul 2021 19:07:46 +0200 Subject: [PATCH 55/79] Add missing accessibilities --- .../Fixtures/BaseGitFlowRepositoryFixture.cs | 2 +- src/GitTools.Testing/Fixtures/RepositoryFixtureBase.cs | 2 +- src/GitTools.Testing/Fixtures/SequenceDiagram.cs | 6 +++--- src/GitTools.Testing/GitTestExtensions.cs | 2 +- src/GitTools.Testing/Internal/DirectoryHelper.cs | 6 +++--- src/GitTools.Testing/Internal/PathHelper.cs | 2 +- src/GitTools.Testing/VirtualTime.cs | 2 +- .../IntegrationTests/VersionInTagScenarios.cs | 2 +- 8 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/GitTools.Testing/Fixtures/BaseGitFlowRepositoryFixture.cs b/src/GitTools.Testing/Fixtures/BaseGitFlowRepositoryFixture.cs index 1932bf59f9..8048cceef9 100644 --- a/src/GitTools.Testing/Fixtures/BaseGitFlowRepositoryFixture.cs +++ b/src/GitTools.Testing/Fixtures/BaseGitFlowRepositoryFixture.cs @@ -26,7 +26,7 @@ public BaseGitFlowRepositoryFixture(string initialVersion) : /// public BaseGitFlowRepositoryFixture(Action initialMainAction) => SetupRepo(initialMainAction); - void SetupRepo(Action initialMainAction) + private void SetupRepo(Action initialMainAction) { var randomFile = Path.Combine(Repository.Info.WorkingDirectory, Guid.NewGuid().ToString()); File.WriteAllText(randomFile, string.Empty); diff --git a/src/GitTools.Testing/Fixtures/RepositoryFixtureBase.cs b/src/GitTools.Testing/Fixtures/RepositoryFixtureBase.cs index a1112da059..6a2c95b6d7 100644 --- a/src/GitTools.Testing/Fixtures/RepositoryFixtureBase.cs +++ b/src/GitTools.Testing/Fixtures/RepositoryFixtureBase.cs @@ -9,7 +9,7 @@ namespace GitTools.Testing /// public abstract class RepositoryFixtureBase : IDisposable { - readonly SequenceDiagram _sequenceDiagram; + private readonly SequenceDiagram _sequenceDiagram; protected RepositoryFixtureBase(Func repoBuilder) : this(repoBuilder(PathHelper.GetTempPath())) diff --git a/src/GitTools.Testing/Fixtures/SequenceDiagram.cs b/src/GitTools.Testing/Fixtures/SequenceDiagram.cs index 5c83bcd6bd..1af3037e1c 100644 --- a/src/GitTools.Testing/Fixtures/SequenceDiagram.cs +++ b/src/GitTools.Testing/Fixtures/SequenceDiagram.cs @@ -9,8 +9,8 @@ namespace GitTools.Testing /// public class SequenceDiagram { - readonly Dictionary _participants = new Dictionary(); - readonly StringBuilder _diagramBuilder; + private readonly Dictionary _participants = new Dictionary(); + private readonly StringBuilder _diagramBuilder; /// /// Initializes a new instance of the class. @@ -106,7 +106,7 @@ public void BranchToFromTag(string branchName, string fromTag, string onBranch, /// public void Merge(string @from, string to) => this._diagramBuilder.AppendLineFormat("{0} -> {1}: merge", GetParticipant(@from), GetParticipant(to)); - string GetParticipant(string branch) + private string GetParticipant(string branch) { if (this._participants.ContainsKey(branch)) return this._participants[branch]; diff --git a/src/GitTools.Testing/GitTestExtensions.cs b/src/GitTools.Testing/GitTestExtensions.cs index 7b45c369f1..bebbd03670 100644 --- a/src/GitTools.Testing/GitTestExtensions.cs +++ b/src/GitTools.Testing/GitTestExtensions.cs @@ -9,7 +9,7 @@ namespace GitTools.Testing { public static class GitTestExtensions { - static int _pad = 1; + private static int _pad = 1; public static Commit MakeACommit(this IRepository repository, string commitMessage = null) => CreateFileAndCommit(repository, Guid.NewGuid().ToString(), commitMessage); diff --git a/src/GitTools.Testing/Internal/DirectoryHelper.cs b/src/GitTools.Testing/Internal/DirectoryHelper.cs index e98baab01d..e150bc31ab 100644 --- a/src/GitTools.Testing/Internal/DirectoryHelper.cs +++ b/src/GitTools.Testing/Internal/DirectoryHelper.cs @@ -5,9 +5,9 @@ namespace GitTools.Testing.Internal { - static class DirectoryHelper + internal static class DirectoryHelper { - static readonly Dictionary ToRename = new Dictionary + private static readonly Dictionary ToRename = new Dictionary { { "gitted", ".git" }, { "gitmodules", ".gitmodules" }, @@ -28,7 +28,7 @@ public static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo targ } } - static string Rename(string name) => ToRename.ContainsKey(name) ? ToRename[name] : name; + private static string Rename(string name) => ToRename.ContainsKey(name) ? ToRename[name] : name; public static void DeleteSubDirectories(string parentPath) { diff --git a/src/GitTools.Testing/Internal/PathHelper.cs b/src/GitTools.Testing/Internal/PathHelper.cs index ee38b23efd..47fff86064 100644 --- a/src/GitTools.Testing/Internal/PathHelper.cs +++ b/src/GitTools.Testing/Internal/PathHelper.cs @@ -3,7 +3,7 @@ namespace GitTools.Testing.Internal { - static class PathHelper + internal static class PathHelper { public static string GetTempPath() => Path.Combine(Path.GetTempPath(), "TestRepositories", Guid.NewGuid().ToString()); } diff --git a/src/GitTools.Testing/VirtualTime.cs b/src/GitTools.Testing/VirtualTime.cs index 6e659e70f8..9cff927a96 100644 --- a/src/GitTools.Testing/VirtualTime.cs +++ b/src/GitTools.Testing/VirtualTime.cs @@ -8,7 +8,7 @@ namespace GitTools.Testing /// public static class VirtualTime { - static DateTimeOffset _simulatedTime = DateTimeOffset.Now.AddHours(-1); + private static DateTimeOffset _simulatedTime = DateTimeOffset.Now.AddHours(-1); /// /// Increments by 1 minute each time it is called diff --git a/src/GitVersion.Core.Tests/IntegrationTests/VersionInTagScenarios.cs b/src/GitVersion.Core.Tests/IntegrationTests/VersionInTagScenarios.cs index cb0f3b2483..64765a0f4e 100644 --- a/src/GitVersion.Core.Tests/IntegrationTests/VersionInTagScenarios.cs +++ b/src/GitVersion.Core.Tests/IntegrationTests/VersionInTagScenarios.cs @@ -9,7 +9,7 @@ namespace GitVersion.Core.Tests.IntegrationTests { [TestFixture] - class VersionInTagScenarios + internal class VersionInTagScenarios { [Test] public void TagPreReleaseWeightIsNotConfigured_HeadIsATaggedCommit_WeightedPreReleaseNumberShouldBeTheDefaultValue() From 77a0cba62f354358fe965cddeb3ea93fd4ef404c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Fri, 16 Jul 2021 19:08:25 +0200 Subject: [PATCH 56/79] Make fields readonly --- .../Extensions/GitToolsTestingExtensions.cs | 2 +- .../VersionCalculation/SemanticVersioning/SemanticVersion.cs | 2 +- src/GitVersion.MsBuild.Tests/Tasks/TestTaskBase.cs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/GitVersion.Core.Tests/Extensions/GitToolsTestingExtensions.cs b/src/GitVersion.Core.Tests/Extensions/GitToolsTestingExtensions.cs index 78216b815b..aa1e5108f7 100644 --- a/src/GitVersion.Core.Tests/Extensions/GitToolsTestingExtensions.cs +++ b/src/GitVersion.Core.Tests/Extensions/GitToolsTestingExtensions.cs @@ -21,7 +21,7 @@ namespace GitVersion.Core.Tests public static class GitToolsTestingExtensions { private static int commitCount = 1; - private static DateTimeOffset when = DateTimeOffset.Now; + private static readonly DateTimeOffset when = DateTimeOffset.Now; public static ICommit CreateMockCommit() { diff --git a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs index 3f9b9abc9b..8a0f18430f 100644 --- a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs +++ b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs @@ -7,7 +7,7 @@ namespace GitVersion { public class SemanticVersion : IFormattable, IComparable { - private static SemanticVersion Empty = new SemanticVersion(); + private static readonly SemanticVersion Empty = new SemanticVersion(); private static readonly Regex ParseSemVer = new Regex( @"^(?(?\d+)(\.(?\d+))?(\.(?\d+))?)(\.(?\d+))?(-(?[^\+]*))?(\+(?.*))?$", diff --git a/src/GitVersion.MsBuild.Tests/Tasks/TestTaskBase.cs b/src/GitVersion.MsBuild.Tests/Tasks/TestTaskBase.cs index 1d3afb0352..a61fe5de20 100644 --- a/src/GitVersion.MsBuild.Tests/Tasks/TestTaskBase.cs +++ b/src/GitVersion.MsBuild.Tests/Tasks/TestTaskBase.cs @@ -13,7 +13,7 @@ namespace GitVersion.MsBuild.Tests.Tasks { public class TestTaskBase : TestBase { - private static IDictionary env = new Dictionary + private static readonly IDictionary env = new Dictionary { { AzurePipelines.EnvironmentVariableName, "true" }, { "BUILD_SOURCEBRANCH", null } From 850b350fbab1a5e50b4d87cdd8d105e03c5b22dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Fri, 16 Jul 2021 19:09:36 +0200 Subject: [PATCH 57/79] Disable warning for braces for ifs (IDE0011) --- .editorconfig | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.editorconfig b/.editorconfig index a9c3d9fccb..ab297e6295 100644 --- a/.editorconfig +++ b/.editorconfig @@ -92,7 +92,7 @@ csharp_prefer_static_local_function = true:warning csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:silent # Code-block preferences -csharp_prefer_braces = when_multiline:warning +csharp_prefer_braces = when_multiline:none csharp_prefer_simple_using_statement = true:warning # Expression-level preferences @@ -151,3 +151,6 @@ csharp_space_between_method_declaration_name_and_open_parenthesis = false csharp_space_between_method_declaration_parameter_list_parentheses = false csharp_space_between_parentheses = false csharp_space_between_square_brackets = false + +# IDE0011: Add braces +dotnet_diagnostic.IDE0011.severity = none From 50fb5afee0c1c72b4afca202238715fb20fdf8a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Fri, 16 Jul 2021 19:17:24 +0200 Subject: [PATCH 58/79] IDE0090 use new(...) syntax --- .editorconfig | 3 +++ src/GitTools.Testing/Fixtures/SequenceDiagram.cs | 2 +- src/GitTools.Testing/Generate.cs | 2 +- src/GitTools.Testing/Internal/DirectoryHelper.cs | 2 +- src/GitTools.Testing/Internal/ProcessHelper.cs | 2 +- src/GitVersion.App/Arguments.cs | 2 +- src/GitVersion.App/GlobbingResolver.cs | 2 +- src/GitVersion.App/OverrideConfigOptionParser.cs | 4 ++-- src/GitVersion.Core.Tests/Helpers/DirectoryHelper.cs | 2 +- src/GitVersion.Core.Tests/Helpers/TestFileSystem.cs | 2 +- src/GitVersion.Core.Tests/Helpers/TestStream.cs | 2 +- .../IntegrationTests/MainlineDevelopmentMode.cs | 2 +- src/GitVersion.Core.Tests/Model/MergeMessageTests.cs | 2 +- .../VersionCalculation/TestBaseVersionCalculator.cs | 2 +- src/GitVersion.Core/Configuration/Init/StepResult.cs | 8 ++++---- src/GitVersion.Core/Helpers/ProcessHelper.cs | 2 +- src/GitVersion.Core/Helpers/StringFormatWith.cs | 2 +- src/GitVersion.Core/Logging/Log.cs | 2 +- src/GitVersion.Core/Model/BranchCommit.cs | 2 +- .../Model/Configuration/BranchConfig.cs | 2 +- .../SemanticVersioning/SemanticVersion.cs | 4 ++-- .../SemanticVersioning/SemanticVersionBuildMetaData.cs | 4 ++-- .../SemanticVersioning/SemanticVersionPreReleaseTag.cs | 2 +- .../AssemblyInfo/AssemblyInfoFileUpdater.cs | 10 +++++----- .../AssemblyInfo/ProjectFileUpdater.cs | 4 ++-- .../Helpers/MsBuildExeFixture.cs | 2 +- src/GitVersion.MsBuild.Tests/Mocks/MockEngine.cs | 6 +++--- src/GitVersion.MsBuild/Helpers/FileHelper.cs | 2 +- 28 files changed, 43 insertions(+), 40 deletions(-) diff --git a/.editorconfig b/.editorconfig index ab297e6295..56a10cf0ac 100644 --- a/.editorconfig +++ b/.editorconfig @@ -154,3 +154,6 @@ csharp_space_between_square_brackets = false # IDE0011: Add braces dotnet_diagnostic.IDE0011.severity = none + +# IDE0090: Use 'new(...)' +dotnet_diagnostic.IDE0090.severity = warning diff --git a/src/GitTools.Testing/Fixtures/SequenceDiagram.cs b/src/GitTools.Testing/Fixtures/SequenceDiagram.cs index 1af3037e1c..6a2e6a8b71 100644 --- a/src/GitTools.Testing/Fixtures/SequenceDiagram.cs +++ b/src/GitTools.Testing/Fixtures/SequenceDiagram.cs @@ -9,7 +9,7 @@ namespace GitTools.Testing /// public class SequenceDiagram { - private readonly Dictionary _participants = new Dictionary(); + private readonly Dictionary _participants = new(); private readonly StringBuilder _diagramBuilder; /// diff --git a/src/GitTools.Testing/Generate.cs b/src/GitTools.Testing/Generate.cs index 7ed980c3a2..ec7bb2bdf1 100644 --- a/src/GitTools.Testing/Generate.cs +++ b/src/GitTools.Testing/Generate.cs @@ -20,6 +20,6 @@ public static Signature SignatureNow() /// /// Creates a libgit2sharp signature at the specified time /// - public static Signature Signature(DateTimeOffset dateTimeOffset) => new Signature("A. U. Thor", "thor@valhalla.asgard.com", dateTimeOffset); + public static Signature Signature(DateTimeOffset dateTimeOffset) => new("A. U. Thor", "thor@valhalla.asgard.com", dateTimeOffset); } } diff --git a/src/GitTools.Testing/Internal/DirectoryHelper.cs b/src/GitTools.Testing/Internal/DirectoryHelper.cs index e150bc31ab..278f0ba942 100644 --- a/src/GitTools.Testing/Internal/DirectoryHelper.cs +++ b/src/GitTools.Testing/Internal/DirectoryHelper.cs @@ -7,7 +7,7 @@ namespace GitTools.Testing.Internal { internal static class DirectoryHelper { - private static readonly Dictionary ToRename = new Dictionary + private static readonly Dictionary ToRename = new() { { "gitted", ".git" }, { "gitmodules", ".gitmodules" }, diff --git a/src/GitTools.Testing/Internal/ProcessHelper.cs b/src/GitTools.Testing/Internal/ProcessHelper.cs index 71117c654f..90de503e3a 100644 --- a/src/GitTools.Testing/Internal/ProcessHelper.cs +++ b/src/GitTools.Testing/Internal/ProcessHelper.cs @@ -10,7 +10,7 @@ namespace GitTools.Testing.Internal { public static class ProcessHelper { - private static readonly object LockObject = new object(); + private static readonly object LockObject = new(); // http://social.msdn.microsoft.com/Forums/en/netfxbcl/thread/f6069441-4ab1-4299-ad6a-b8bb9ed36be3 private static Process Start(ProcessStartInfo startInfo) diff --git a/src/GitVersion.App/Arguments.cs b/src/GitVersion.App/Arguments.cs index 1b97531b90..117e24ed8f 100644 --- a/src/GitVersion.App/Arguments.cs +++ b/src/GitVersion.App/Arguments.cs @@ -7,7 +7,7 @@ namespace GitVersion { public class Arguments { - public AuthenticationInfo Authentication = new AuthenticationInfo(); + public AuthenticationInfo Authentication = new(); public string ConfigFile; public Config OverrideConfig; diff --git a/src/GitVersion.App/GlobbingResolver.cs b/src/GitVersion.App/GlobbingResolver.cs index 513e53f26b..2f8f81efe9 100644 --- a/src/GitVersion.App/GlobbingResolver.cs +++ b/src/GitVersion.App/GlobbingResolver.cs @@ -9,7 +9,7 @@ namespace GitVersion { public class GlobbingResolver : IGlobbingResolver { - private readonly Matcher matcher = new Matcher(StringComparison.OrdinalIgnoreCase); + private readonly Matcher matcher = new(StringComparison.OrdinalIgnoreCase); public IEnumerable Resolve(string workingDirectory, string pattern) { diff --git a/src/GitVersion.App/OverrideConfigOptionParser.cs b/src/GitVersion.App/OverrideConfigOptionParser.cs index eeb25d8b3a..86ce338e72 100644 --- a/src/GitVersion.App/OverrideConfigOptionParser.cs +++ b/src/GitVersion.App/OverrideConfigOptionParser.cs @@ -8,9 +8,9 @@ namespace GitVersion internal class OverrideConfigOptionParser { private static readonly Lazy> _lazySupportedProperties = - new Lazy>(GetSupportedProperties, true); + new(GetSupportedProperties, true); - private readonly Lazy _lazyConfig = new Lazy(); + private readonly Lazy _lazyConfig = new(); internal ILookup SupportedProperties => _lazySupportedProperties.Value; diff --git a/src/GitVersion.Core.Tests/Helpers/DirectoryHelper.cs b/src/GitVersion.Core.Tests/Helpers/DirectoryHelper.cs index 0e8656e749..4d75e308a4 100644 --- a/src/GitVersion.Core.Tests/Helpers/DirectoryHelper.cs +++ b/src/GitVersion.Core.Tests/Helpers/DirectoryHelper.cs @@ -6,7 +6,7 @@ namespace GitVersion.Core.Tests.Helpers { public static class DirectoryHelper { - private static readonly Dictionary ToRename = new Dictionary + private static readonly Dictionary ToRename = new() { {"gitted", ".git"}, {"gitmodules", ".gitmodules"}, diff --git a/src/GitVersion.Core.Tests/Helpers/TestFileSystem.cs b/src/GitVersion.Core.Tests/Helpers/TestFileSystem.cs index 4c487b9954..baaa8c3d92 100644 --- a/src/GitVersion.Core.Tests/Helpers/TestFileSystem.cs +++ b/src/GitVersion.Core.Tests/Helpers/TestFileSystem.cs @@ -8,7 +8,7 @@ namespace GitVersion.Core.Tests.Helpers { public class TestFileSystem : IFileSystem { - private readonly Dictionary fileSystem = new Dictionary(StringComparerUtils.OsDependentComparer); + private readonly Dictionary fileSystem = new(StringComparerUtils.OsDependentComparer); public void Copy(string from, string to, bool overwrite) { diff --git a/src/GitVersion.Core.Tests/Helpers/TestStream.cs b/src/GitVersion.Core.Tests/Helpers/TestStream.cs index a1a5f550d9..1a353fa299 100644 --- a/src/GitVersion.Core.Tests/Helpers/TestStream.cs +++ b/src/GitVersion.Core.Tests/Helpers/TestStream.cs @@ -6,7 +6,7 @@ public class TestStream : Stream { private readonly string path; private readonly TestFileSystem testFileSystem; - private readonly MemoryStream underlying = new MemoryStream(); + private readonly MemoryStream underlying = new(); public TestStream(string path, TestFileSystem testFileSystem) { diff --git a/src/GitVersion.Core.Tests/IntegrationTests/MainlineDevelopmentMode.cs b/src/GitVersion.Core.Tests/IntegrationTests/MainlineDevelopmentMode.cs index 637003090c..5cfc428e42 100644 --- a/src/GitVersion.Core.Tests/IntegrationTests/MainlineDevelopmentMode.cs +++ b/src/GitVersion.Core.Tests/IntegrationTests/MainlineDevelopmentMode.cs @@ -14,7 +14,7 @@ namespace GitVersion.Core.Tests.IntegrationTests { public class MainlineDevelopmentMode : TestBase { - private readonly Config config = new Config + private readonly Config config = new() { VersioningMode = VersioningMode.Mainline }; diff --git a/src/GitVersion.Core.Tests/Model/MergeMessageTests.cs b/src/GitVersion.Core.Tests/Model/MergeMessageTests.cs index 7164a1303b..d4a7ca87b4 100644 --- a/src/GitVersion.Core.Tests/Model/MergeMessageTests.cs +++ b/src/GitVersion.Core.Tests/Model/MergeMessageTests.cs @@ -10,7 +10,7 @@ namespace GitVersion.Core.Tests [TestFixture] public class MergeMessageTests : TestBase { - private readonly Config config = new Config { TagPrefix = "[vV]" }; + private readonly Config config = new() { TagPrefix = "[vV]" }; [Test] public void NullMessageStringThrows() => diff --git a/src/GitVersion.Core.Tests/VersionCalculation/TestBaseVersionCalculator.cs b/src/GitVersion.Core.Tests/VersionCalculation/TestBaseVersionCalculator.cs index 315743b06e..579ccf6ae3 100644 --- a/src/GitVersion.Core.Tests/VersionCalculation/TestBaseVersionCalculator.cs +++ b/src/GitVersion.Core.Tests/VersionCalculation/TestBaseVersionCalculator.cs @@ -15,6 +15,6 @@ public TestBaseVersionCalculator(bool shouldIncrement, SemanticVersion semanticV this.shouldIncrement = shouldIncrement; } - public BaseVersion GetBaseVersion() => new BaseVersion("Test source", this.shouldIncrement, this.semanticVersion, this.source, null); + public BaseVersion GetBaseVersion() => new("Test source", this.shouldIncrement, this.semanticVersion, this.source, null); } } diff --git a/src/GitVersion.Core/Configuration/Init/StepResult.cs b/src/GitVersion.Core/Configuration/Init/StepResult.cs index faa3f6c63f..3a80c13911 100644 --- a/src/GitVersion.Core/Configuration/Init/StepResult.cs +++ b/src/GitVersion.Core/Configuration/Init/StepResult.cs @@ -4,20 +4,20 @@ public class StepResult { private StepResult() { } - public static StepResult Ok() => new StepResult(); + public static StepResult Ok() => new(); - public static StepResult InvalidResponseSelected() => new StepResult + public static StepResult InvalidResponseSelected() => new() { InvalidResponse = true }; - public static StepResult SaveAndExit() => new StepResult + public static StepResult SaveAndExit() => new() { Save = true, Exit = true }; - public static StepResult ExitWithoutSaving() => new StepResult + public static StepResult ExitWithoutSaving() => new() { Save = false, Exit = true diff --git a/src/GitVersion.Core/Helpers/ProcessHelper.cs b/src/GitVersion.Core/Helpers/ProcessHelper.cs index d7497ad275..63cbb309b4 100644 --- a/src/GitVersion.Core/Helpers/ProcessHelper.cs +++ b/src/GitVersion.Core/Helpers/ProcessHelper.cs @@ -11,7 +11,7 @@ namespace GitVersion.Helpers { public static class ProcessHelper { - private static readonly object LockObject = new object(); + private static readonly object LockObject = new(); // http://social.msdn.microsoft.com/Forums/en/netfxbcl/thread/f6069441-4ab1-4299-ad6a-b8bb9ed36be3 private static Process? Start(ProcessStartInfo startInfo) diff --git a/src/GitVersion.Core/Helpers/StringFormatWith.cs b/src/GitVersion.Core/Helpers/StringFormatWith.cs index d841d7e7dc..ed2f5c04cf 100644 --- a/src/GitVersion.Core/Helpers/StringFormatWith.cs +++ b/src/GitVersion.Core/Helpers/StringFormatWith.cs @@ -11,7 +11,7 @@ internal static class StringFormatWithExtension // - env:ENV name OR a member name // - optional fallback value after " ?? " // - the fallback value should be a quoted string, but simple unquoted text is allowed for back compat - private static readonly Regex TokensRegex = new Regex(@"{((env:(?\w+))|(?\w+))(\s+(\?\?)??\s+((?\w+)|""(?.*)""))??}", RegexOptions.Compiled); + private static readonly Regex TokensRegex = new(@"{((env:(?\w+))|(?\w+))(\s+(\?\?)??\s+((?\w+)|""(?.*)""))??}", RegexOptions.Compiled); /// /// Formats the , replacing each expression wrapped in curly braces diff --git a/src/GitVersion.Core/Logging/Log.cs b/src/GitVersion.Core/Logging/Log.cs index c77953c21a..edcb4e15e5 100644 --- a/src/GitVersion.Core/Logging/Log.cs +++ b/src/GitVersion.Core/Logging/Log.cs @@ -10,7 +10,7 @@ namespace GitVersion.Logging public sealed class Log : ILog { private IEnumerable appenders; - private readonly Regex obscurePasswordRegex = new Regex("(https?://)(.+)(:.+@)", RegexOptions.Compiled); + private readonly Regex obscurePasswordRegex = new("(https?://)(.+)(:.+@)", RegexOptions.Compiled); private readonly StringBuilder sb; private string indent = string.Empty; diff --git a/src/GitVersion.Core/Model/BranchCommit.cs b/src/GitVersion.Core/Model/BranchCommit.cs index 3b8d6eb8fd..f9468c8317 100644 --- a/src/GitVersion.Core/Model/BranchCommit.cs +++ b/src/GitVersion.Core/Model/BranchCommit.cs @@ -7,7 +7,7 @@ namespace GitVersion /// public readonly struct BranchCommit { - public static readonly BranchCommit Empty = new BranchCommit(); + public static readonly BranchCommit Empty = new(); public BranchCommit(ICommit commit, IBranch branch) : this() { diff --git a/src/GitVersion.Core/Model/Configuration/BranchConfig.cs b/src/GitVersion.Core/Model/Configuration/BranchConfig.cs index bb18552750..07dbb99535 100644 --- a/src/GitVersion.Core/Model/Configuration/BranchConfig.cs +++ b/src/GitVersion.Core/Model/Configuration/BranchConfig.cs @@ -113,7 +113,7 @@ public BranchConfig Apply([NotNull] BranchConfig overrides) return this; } - public static BranchConfig CreateDefaultBranchConfig(string name) => new BranchConfig + public static BranchConfig CreateDefaultBranchConfig(string name) => new() { Name = name, Tag = "useBranchName", diff --git a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs index 8a0f18430f..9d08cb35d7 100644 --- a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs +++ b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs @@ -7,9 +7,9 @@ namespace GitVersion { public class SemanticVersion : IFormattable, IComparable { - private static readonly SemanticVersion Empty = new SemanticVersion(); + private static readonly SemanticVersion Empty = new(); - private static readonly Regex ParseSemVer = new Regex( + private static readonly Regex ParseSemVer = new( @"^(?(?\d+)(\.(?\d+))?(\.(?\d+))?)(\.(?\d+))?(-(?[^\+]*))?(\+(?.*))?$", RegexOptions.Compiled); diff --git a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionBuildMetaData.cs b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionBuildMetaData.cs index c7272b9df6..90803e71bc 100644 --- a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionBuildMetaData.cs +++ b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionBuildMetaData.cs @@ -7,12 +7,12 @@ namespace GitVersion { public class SemanticVersionBuildMetaData : IFormattable, IEquatable { - private static readonly Regex ParseRegex = new Regex( + private static readonly Regex ParseRegex = new( @"(?\d+)?(\.?Branch(Name)?\.(?[^\.]+))?(\.?Sha?\.(?[^\.]+))?(?.*)", RegexOptions.Compiled | RegexOptions.IgnoreCase); private static readonly LambdaEqualityHelper EqualityHelper = - new LambdaEqualityHelper(x => x?.CommitsSinceTag, x => x?.Branch, x => x?.Sha); + new(x => x?.CommitsSinceTag, x => x?.Branch, x => x?.Sha); public int? CommitsSinceTag; public string? Branch; diff --git a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionPreReleaseTag.cs b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionPreReleaseTag.cs index 65ffc67e93..0f24cc04d0 100644 --- a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionPreReleaseTag.cs +++ b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionPreReleaseTag.cs @@ -10,7 +10,7 @@ public class SemanticVersionPreReleaseTag : IFormattable, IComparable, IEquatable { private static readonly LambdaEqualityHelper EqualityHelper = - new LambdaEqualityHelper(x => x?.Name, x => x?.Number); + new(x => x?.Name, x => x?.Number); public SemanticVersionPreReleaseTag() { diff --git a/src/GitVersion.Core/VersionConverters/AssemblyInfo/AssemblyInfoFileUpdater.cs b/src/GitVersion.Core/VersionConverters/AssemblyInfo/AssemblyInfoFileUpdater.cs index 92de52eef7..a92d32238f 100644 --- a/src/GitVersion.Core/VersionConverters/AssemblyInfo/AssemblyInfoFileUpdater.cs +++ b/src/GitVersion.Core/VersionConverters/AssemblyInfo/AssemblyInfoFileUpdater.cs @@ -15,8 +15,8 @@ public interface IAssemblyInfoFileUpdater : IVersionConverter restoreBackupTasks = new List(); - private readonly List cleanupBackupTasks = new List(); + private readonly List restoreBackupTasks = new(); + private readonly List cleanupBackupTasks = new(); private readonly IDictionary assemblyAttributeRegexes = new Dictionary { @@ -25,9 +25,9 @@ public class AssemblyInfoFileUpdater : IAssemblyInfoFileUpdater {".vb", new Regex( @"(\s*\\s*$(\r?\n)?)", RegexOptions.Multiline) }, }; - private readonly Regex assemblyVersionRegex = new Regex(@"AssemblyVersion(Attribute)?\s*\(.*\)\s*"); - private readonly Regex assemblyInfoVersionRegex = new Regex(@"AssemblyInformationalVersion(Attribute)?\s*\(.*\)\s*"); - private readonly Regex assemblyFileVersionRegex = new Regex(@"AssemblyFileVersion(Attribute)?\s*\(.*\)\s*"); + private readonly Regex assemblyVersionRegex = new(@"AssemblyVersion(Attribute)?\s*\(.*\)\s*"); + private readonly Regex assemblyInfoVersionRegex = new(@"AssemblyInformationalVersion(Attribute)?\s*\(.*\)\s*"); + private readonly Regex assemblyFileVersionRegex = new(@"AssemblyFileVersion(Attribute)?\s*\(.*\)\s*"); private const string NewLine = "\r\n"; diff --git a/src/GitVersion.Core/VersionConverters/AssemblyInfo/ProjectFileUpdater.cs b/src/GitVersion.Core/VersionConverters/AssemblyInfo/ProjectFileUpdater.cs index 015607766d..bd975faa94 100644 --- a/src/GitVersion.Core/VersionConverters/AssemblyInfo/ProjectFileUpdater.cs +++ b/src/GitVersion.Core/VersionConverters/AssemblyInfo/ProjectFileUpdater.cs @@ -20,8 +20,8 @@ public class ProjectFileUpdater : IProjectFileUpdater internal const string InformationalVersionElement = "InformationalVersion"; internal const string VersionElement = "Version"; - private readonly List restoreBackupTasks = new List(); - private readonly List cleanupBackupTasks = new List(); + private readonly List restoreBackupTasks = new(); + private readonly List cleanupBackupTasks = new(); private readonly IFileSystem fileSystem; private readonly ILog log; diff --git a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildExeFixture.cs b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildExeFixture.cs index 1b66f62051..a502f526c7 100644 --- a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildExeFixture.cs +++ b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildExeFixture.cs @@ -22,7 +22,7 @@ public class MsBuildExeFixture public const string OutputTarget = "GitVersionOutput"; - private readonly AnalyzerManager manager = new AnalyzerManager(); + private readonly AnalyzerManager manager = new(); private readonly string ProjectPath; public MsBuildExeFixture(RepositoryFixtureBase fixture, string workingDirectory = "") diff --git a/src/GitVersion.MsBuild.Tests/Mocks/MockEngine.cs b/src/GitVersion.MsBuild.Tests/Mocks/MockEngine.cs index 3757dcc7a1..aa24d21c83 100644 --- a/src/GitVersion.MsBuild.Tests/Mocks/MockEngine.cs +++ b/src/GitVersion.MsBuild.Tests/Mocks/MockEngine.cs @@ -11,8 +11,8 @@ namespace GitVersion.MsBuild.Tests.Mocks { internal sealed class MockEngine : IBuildEngine4 { - private readonly ConcurrentDictionary _objectCache = new ConcurrentDictionary(); - private StringBuilder _log = new StringBuilder(); + private readonly ConcurrentDictionary _objectCache = new(); + private StringBuilder _log = new(); internal MessageImportance MinimumMessageImportance { get; set; } = MessageImportance.Low; @@ -102,7 +102,7 @@ public BuildEngineResult BuildProjectFilesInParallel( IDictionary[] globalProperties, IList[] undefineProperties, string[] toolsVersion, - bool includeTargetOutputs) => new BuildEngineResult(false, null); + bool includeTargetOutputs) => new(false, null); public void Yield() { diff --git a/src/GitVersion.MsBuild/Helpers/FileHelper.cs b/src/GitVersion.MsBuild/Helpers/FileHelper.cs index 7ddeb971de..e5dc121eea 100644 --- a/src/GitVersion.MsBuild/Helpers/FileHelper.cs +++ b/src/GitVersion.MsBuild/Helpers/FileHelper.cs @@ -9,7 +9,7 @@ namespace GitVersion.MsBuild { public static class FileHelper { - private static readonly Dictionary> VersionAttributeFinders = new Dictionary> + private static readonly Dictionary> VersionAttributeFinders = new() { { ".cs", CSharpFileContainsVersionAttribute }, { ".vb", VisualBasicFileContainsVersionAttribute } From 6989112ee3d311614a27a342ae538c7ba1fa4e72 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Fri, 16 Jul 2021 19:28:07 +0200 Subject: [PATCH 59/79] IDE0041: Use 'is null' check --- .editorconfig | 5 ++++- src/GitVersion.Core/Helpers/LambdaEqualityHelper.cs | 2 +- src/GitVersion.Core/Model/BranchCommit.cs | 2 +- .../SemanticVersioning/SemanticVersion.cs | 6 +++--- 4 files changed, 9 insertions(+), 6 deletions(-) diff --git a/.editorconfig b/.editorconfig index 56a10cf0ac..574890bcd8 100644 --- a/.editorconfig +++ b/.editorconfig @@ -57,7 +57,7 @@ dotnet_style_prefer_conditional_expression_over_assignment = true:silent dotnet_style_prefer_conditional_expression_over_return = true:silent dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion dotnet_style_prefer_inferred_tuple_names = true:suggestion -dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:warning dotnet_style_prefer_simplified_interpolation = true:suggestion # Dispose rules (CA2000 and CA2213) ported to IDE analyzers. We already execute the CA rules on the repo, so disable the IDE ones. @@ -157,3 +157,6 @@ dotnet_diagnostic.IDE0011.severity = none # IDE0090: Use 'new(...)' dotnet_diagnostic.IDE0090.severity = warning + +# IDE0041: Use 'is null' check +dotnet_diagnostic.IDE0041.severity = warning diff --git a/src/GitVersion.Core/Helpers/LambdaEqualityHelper.cs b/src/GitVersion.Core/Helpers/LambdaEqualityHelper.cs index 1c21989d3b..50e410bbb8 100644 --- a/src/GitVersion.Core/Helpers/LambdaEqualityHelper.cs +++ b/src/GitVersion.Core/Helpers/LambdaEqualityHelper.cs @@ -14,7 +14,7 @@ public LambdaEqualityHelper(params Func[] equalityContributorAccess public bool Equals(T? instance, T? other) { - if (ReferenceEquals(null, instance) || ReferenceEquals(null, other)) + if (instance is null || other is null) { return false; } diff --git a/src/GitVersion.Core/Model/BranchCommit.cs b/src/GitVersion.Core/Model/BranchCommit.cs index f9468c8317..1922e31b30 100644 --- a/src/GitVersion.Core/Model/BranchCommit.cs +++ b/src/GitVersion.Core/Model/BranchCommit.cs @@ -22,7 +22,7 @@ public BranchCommit(ICommit commit, IBranch branch) : this() public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) + if (obj is null) return false; return obj is BranchCommit commit && Equals(commit); } diff --git a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs index 9d08cb35d7..2b0ae36ae9 100644 --- a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs +++ b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs @@ -55,7 +55,7 @@ public bool Equals(SemanticVersion? obj) public override bool Equals(object? obj) { - if (ReferenceEquals(null, obj)) + if (obj is null) { return false; } @@ -85,9 +85,9 @@ public override int GetHashCode() public static bool operator ==(SemanticVersion? v1, SemanticVersion? v2) { - if (ReferenceEquals(v1, null)) + if (v1 is null) { - return ReferenceEquals(v2, null); + return v2 is null; } return v1.Equals(v2); } From 321a381678881b8eded5c94cc1cea3f9410bc57c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Fri, 16 Jul 2021 18:06:27 +0200 Subject: [PATCH 60/79] Add Microsoft.CodeAnalysis.NetAnalyzers --- src/GitTools.Testing/GitTools.Testing.csproj | 4 +++ .../GitVersion.App.Tests.csproj | 33 +++++++++++-------- src/GitVersion.App/GitVersion.App.csproj | 4 +++ .../GitVersion.Core.Tests.csproj | 4 +++ src/GitVersion.Core/GitVersion.Core.csproj | 4 +++ .../GitVersion.LibGit2Sharp.csproj | 4 +++ .../GitVersion.MsBuild.Tests.csproj | 4 +++ .../GitVersion.MsBuild.csproj | 8 +++-- 8 files changed, 49 insertions(+), 16 deletions(-) diff --git a/src/GitTools.Testing/GitTools.Testing.csproj b/src/GitTools.Testing/GitTools.Testing.csproj index 569a353c27..42a1cff0a6 100644 --- a/src/GitTools.Testing/GitTools.Testing.csproj +++ b/src/GitTools.Testing/GitTools.Testing.csproj @@ -10,5 +10,9 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/src/GitVersion.App.Tests/GitVersion.App.Tests.csproj b/src/GitVersion.App.Tests/GitVersion.App.Tests.csproj index bf6100c6a3..d55c33df9d 100644 --- a/src/GitVersion.App.Tests/GitVersion.App.Tests.csproj +++ b/src/GitVersion.App.Tests/GitVersion.App.Tests.csproj @@ -11,28 +11,33 @@ runtime; build; native; contentfiles; analyzers; buildtransitive + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + - - + + - + - + - - - - - - - - - - + + + + + + + + + + diff --git a/src/GitVersion.App/GitVersion.App.csproj b/src/GitVersion.App/GitVersion.App.csproj index 544744355b..a3d2d73836 100644 --- a/src/GitVersion.App/GitVersion.App.csproj +++ b/src/GitVersion.App/GitVersion.App.csproj @@ -30,6 +30,10 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/src/GitVersion.Core.Tests/GitVersion.Core.Tests.csproj b/src/GitVersion.Core.Tests/GitVersion.Core.Tests.csproj index 7cf3f3778f..84adfd0f4a 100644 --- a/src/GitVersion.Core.Tests/GitVersion.Core.Tests.csproj +++ b/src/GitVersion.Core.Tests/GitVersion.Core.Tests.csproj @@ -17,6 +17,10 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/src/GitVersion.Core/GitVersion.Core.csproj b/src/GitVersion.Core/GitVersion.Core.csproj index d39025a07d..bdcb6183da 100644 --- a/src/GitVersion.Core/GitVersion.Core.csproj +++ b/src/GitVersion.Core/GitVersion.Core.csproj @@ -18,6 +18,10 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/src/GitVersion.LibGit2Sharp/GitVersion.LibGit2Sharp.csproj b/src/GitVersion.LibGit2Sharp/GitVersion.LibGit2Sharp.csproj index a04c027bd1..3c847543a5 100644 --- a/src/GitVersion.LibGit2Sharp/GitVersion.LibGit2Sharp.csproj +++ b/src/GitVersion.LibGit2Sharp/GitVersion.LibGit2Sharp.csproj @@ -11,6 +11,10 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/src/GitVersion.MsBuild.Tests/GitVersion.MsBuild.Tests.csproj b/src/GitVersion.MsBuild.Tests/GitVersion.MsBuild.Tests.csproj index 33f9923b58..418a2ba532 100644 --- a/src/GitVersion.MsBuild.Tests/GitVersion.MsBuild.Tests.csproj +++ b/src/GitVersion.MsBuild.Tests/GitVersion.MsBuild.Tests.csproj @@ -14,6 +14,10 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/src/GitVersion.MsBuild/GitVersion.MsBuild.csproj b/src/GitVersion.MsBuild/GitVersion.MsBuild.csproj index f31898deca..5b02a4aad3 100644 --- a/src/GitVersion.MsBuild/GitVersion.MsBuild.csproj +++ b/src/GitVersion.MsBuild/GitVersion.MsBuild.csproj @@ -18,6 +18,10 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + @@ -25,9 +29,9 @@ - + - + From 5cb623b9756431eef9c0813a1ac07c9092b4dc09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Fri, 16 Jul 2021 19:22:14 +0200 Subject: [PATCH 61/79] CA1825: Avoid zero-length array allocations --- .editorconfig | 3 +++ src/GitVersion.App.Tests/PullRequestInBuildAgentTest.cs | 2 +- src/GitVersion.App.Tests/TagCheckoutInBuildAgentTests.cs | 2 +- .../BuildAgents/BuildServerBaseTests.cs | 2 +- .../BuildAgents/GitHubActionsTests.cs | 2 +- src/GitVersion.Core.Tests/Helpers/TestFileSystem.cs | 4 ++-- .../IntegrationTests/OtherScenarios.cs | 4 ++-- .../VersionInCurrentBranchNameScenarios.cs | 4 ++-- .../VersionInMergedBranchNameScenarios.cs | 4 ++-- .../VersionInBranchNameBaseVersionStrategyTests.cs | 2 +- src/GitVersion.Core/BuildAgents/GitHubActions.cs | 2 +- src/GitVersion.Core/BuildAgents/SpaceAutomation.cs | 2 +- src/GitVersion.Core/Core/RepositoryStore.cs | 2 +- .../TrackReleaseBranchesVersionStrategy.cs | 8 ++++---- src/GitVersion.MsBuild.Tests/Tasks/TestTaskBase.cs | 2 +- 15 files changed, 24 insertions(+), 21 deletions(-) diff --git a/.editorconfig b/.editorconfig index 574890bcd8..0956d7aad8 100644 --- a/.editorconfig +++ b/.editorconfig @@ -160,3 +160,6 @@ dotnet_diagnostic.IDE0090.severity = warning # IDE0041: Use 'is null' check dotnet_diagnostic.IDE0041.severity = warning + +# CA1825: Avoid zero-length array allocations +dotnet_diagnostic.CA1825.severity = warning diff --git a/src/GitVersion.App.Tests/PullRequestInBuildAgentTest.cs b/src/GitVersion.App.Tests/PullRequestInBuildAgentTest.cs index 21c985ed70..dccd02cdeb 100644 --- a/src/GitVersion.App.Tests/PullRequestInBuildAgentTest.cs +++ b/src/GitVersion.App.Tests/PullRequestInBuildAgentTest.cs @@ -155,7 +155,7 @@ private static async Task VerifyPullRequestVersionIsCalculatedProperly(string pu remoteRepository.Refs.Add(pullRequestRef, new ObjectId(mergeCommitSha)); // Checkout PR commit - Commands.Fetch((Repository)fixture.Repository, "origin", new string[0], new FetchOptions(), null); + Commands.Fetch((Repository)fixture.Repository, "origin", Array.Empty(), new FetchOptions(), null); Commands.Checkout(fixture.Repository, mergeCommitSha); } diff --git a/src/GitVersion.App.Tests/TagCheckoutInBuildAgentTests.cs b/src/GitVersion.App.Tests/TagCheckoutInBuildAgentTests.cs index ba9e2c6ace..ee53cf685e 100644 --- a/src/GitVersion.App.Tests/TagCheckoutInBuildAgentTests.cs +++ b/src/GitVersion.App.Tests/TagCheckoutInBuildAgentTests.cs @@ -58,7 +58,7 @@ private static async Task VerifyTagCheckoutVersionIsCalculatedProperly(Dictionar remoteRepository.MergeNoFF("release/0.2.0", Generate.SignatureNow()); remoteRepository.MakeATaggedCommit("0.2.0"); - Commands.Fetch((Repository)fixture.Repository, "origin", new string[0], new FetchOptions(), null); + Commands.Fetch((Repository)fixture.Repository, "origin", Array.Empty(), new FetchOptions(), null); Commands.Checkout(fixture.Repository, "0.2.0"); } diff --git a/src/GitVersion.Core.Tests/BuildAgents/BuildServerBaseTests.cs b/src/GitVersion.Core.Tests/BuildAgents/BuildServerBaseTests.cs index 3d8dbcd5bb..ee6db63c07 100644 --- a/src/GitVersion.Core.Tests/BuildAgents/BuildServerBaseTests.cs +++ b/src/GitVersion.Core.Tests/BuildAgents/BuildServerBaseTests.cs @@ -65,7 +65,7 @@ public BuildAgent(IEnvironment environment, ILog log) : base(environment, log) public override string GenerateSetVersionMessage(VersionVariables variables) => variables.FullSemVer; - public override string[] GenerateSetParameterMessage(string name, string value) => new string[0]; + public override string[] GenerateSetParameterMessage(string name, string value) => Array.Empty(); } } } diff --git a/src/GitVersion.Core.Tests/BuildAgents/GitHubActionsTests.cs b/src/GitVersion.Core.Tests/BuildAgents/GitHubActionsTests.cs index 148a15d458..29ce765971 100644 --- a/src/GitVersion.Core.Tests/BuildAgents/GitHubActionsTests.cs +++ b/src/GitVersion.Core.Tests/BuildAgents/GitHubActionsTests.cs @@ -122,7 +122,7 @@ public void SkipEmptySetParameterMessage() var result = this.buildServer.GenerateSetParameterMessage("Hello", string.Empty); // Assert - result.ShouldBeEquivalentTo(new string[0]); + result.ShouldBeEquivalentTo(System.Array.Empty()); } [Test] diff --git a/src/GitVersion.Core.Tests/Helpers/TestFileSystem.cs b/src/GitVersion.Core.Tests/Helpers/TestFileSystem.cs index baaa8c3d92..13d0dccaef 100644 --- a/src/GitVersion.Core.Tests/Helpers/TestFileSystem.cs +++ b/src/GitVersion.Core.Tests/Helpers/TestFileSystem.cs @@ -93,11 +93,11 @@ public void CreateDirectory(string directory) var path = Path.GetFullPath(directory); if (this.fileSystem.ContainsKey(path)) { - this.fileSystem[path] = new byte[0]; + this.fileSystem[path] = Array.Empty(); } else { - this.fileSystem.Add(path, new byte[0]); + this.fileSystem.Add(path, Array.Empty()); } } diff --git a/src/GitVersion.Core.Tests/IntegrationTests/OtherScenarios.cs b/src/GitVersion.Core.Tests/IntegrationTests/OtherScenarios.cs index 51eca96aba..bfc43fbec5 100644 --- a/src/GitVersion.Core.Tests/IntegrationTests/OtherScenarios.cs +++ b/src/GitVersion.Core.Tests/IntegrationTests/OtherScenarios.cs @@ -24,7 +24,7 @@ public void DoNotBlowUpWhenMainAndDevelopPointAtSameCommit() fixture.Repository.MakeACommit(); fixture.Repository.CreateBranch("develop"); - Commands.Fetch((Repository)fixture.LocalRepositoryFixture.Repository, fixture.LocalRepositoryFixture.Repository.Network.Remotes.First().Name, new string[0], new FetchOptions(), null); + Commands.Fetch((Repository)fixture.LocalRepositoryFixture.Repository, fixture.LocalRepositoryFixture.Repository.Network.Remotes.First().Name, System.Array.Empty(), new FetchOptions(), null); Commands.Checkout(fixture.LocalRepositoryFixture.Repository, fixture.Repository.Head.Tip); fixture.LocalRepositoryFixture.Repository.Branches.Remove(MainBranch); fixture.InitializeRepo(); @@ -91,7 +91,7 @@ public void DoNotBlowUpWhenDevelopAndFeatureBranchPointAtSameCommit() fixture.Repository.MakeACommit(); fixture.Repository.CreateBranch("feature/someFeature"); - Commands.Fetch((Repository)fixture.LocalRepositoryFixture.Repository, fixture.LocalRepositoryFixture.Repository.Network.Remotes.First().Name, new string[0], new FetchOptions(), null); + Commands.Fetch((Repository)fixture.LocalRepositoryFixture.Repository, fixture.LocalRepositoryFixture.Repository.Network.Remotes.First().Name, System.Array.Empty(), new FetchOptions(), null); Commands.Checkout(fixture.LocalRepositoryFixture.Repository, fixture.Repository.Head.Tip); fixture.LocalRepositoryFixture.Repository.Branches.Remove(MainBranch); fixture.InitializeRepo(); diff --git a/src/GitVersion.Core.Tests/IntegrationTests/VersionInCurrentBranchNameScenarios.cs b/src/GitVersion.Core.Tests/IntegrationTests/VersionInCurrentBranchNameScenarios.cs index 323551702b..cad3920368 100644 --- a/src/GitVersion.Core.Tests/IntegrationTests/VersionInCurrentBranchNameScenarios.cs +++ b/src/GitVersion.Core.Tests/IntegrationTests/VersionInCurrentBranchNameScenarios.cs @@ -49,7 +49,7 @@ public void TakesVersionFromNameOfRemoteReleaseBranchInOrigin() using var fixture = new RemoteRepositoryFixture(); fixture.BranchTo("release/2.0.0"); fixture.MakeACommit(); - Commands.Fetch((Repository)fixture.LocalRepositoryFixture.Repository, fixture.LocalRepositoryFixture.Repository.Network.Remotes.First().Name, new string[0], new FetchOptions(), null); + Commands.Fetch((Repository)fixture.LocalRepositoryFixture.Repository, fixture.LocalRepositoryFixture.Repository.Network.Remotes.First().Name, System.Array.Empty(), new FetchOptions(), null); fixture.LocalRepositoryFixture.Checkout("origin/release/2.0.0"); @@ -63,7 +63,7 @@ public void DoesNotTakeVersionFromNameOfRemoteReleaseBranchInCustomRemote() fixture.LocalRepositoryFixture.Repository.Network.Remotes.Rename("origin", "upstream"); fixture.BranchTo("release/2.0.0"); fixture.MakeACommit(); - Commands.Fetch((Repository)fixture.LocalRepositoryFixture.Repository, fixture.LocalRepositoryFixture.Repository.Network.Remotes.First().Name, new string[0], new FetchOptions(), null); + Commands.Fetch((Repository)fixture.LocalRepositoryFixture.Repository, fixture.LocalRepositoryFixture.Repository.Network.Remotes.First().Name, System.Array.Empty(), new FetchOptions(), null); fixture.LocalRepositoryFixture.Checkout("upstream/release/2.0.0"); diff --git a/src/GitVersion.Core.Tests/IntegrationTests/VersionInMergedBranchNameScenarios.cs b/src/GitVersion.Core.Tests/IntegrationTests/VersionInMergedBranchNameScenarios.cs index e8793627f2..b2cf86a8d4 100644 --- a/src/GitVersion.Core.Tests/IntegrationTests/VersionInMergedBranchNameScenarios.cs +++ b/src/GitVersion.Core.Tests/IntegrationTests/VersionInMergedBranchNameScenarios.cs @@ -50,7 +50,7 @@ public void TakesVersionFromNameOfRemoteReleaseBranchInOrigin() using var fixture = new RemoteRepositoryFixture(); fixture.BranchTo("release/2.0.0"); fixture.MakeACommit(); - Commands.Fetch((Repository)fixture.LocalRepositoryFixture.Repository, fixture.LocalRepositoryFixture.Repository.Network.Remotes.First().Name, new string[0], new FetchOptions(), null); + Commands.Fetch((Repository)fixture.LocalRepositoryFixture.Repository, fixture.LocalRepositoryFixture.Repository.Network.Remotes.First().Name, System.Array.Empty(), new FetchOptions(), null); fixture.LocalRepositoryFixture.MergeNoFF("origin/release/2.0.0"); @@ -64,7 +64,7 @@ public void DoesNotTakeVersionFromNameOfRemoteReleaseBranchInCustomRemote() fixture.LocalRepositoryFixture.Repository.Network.Remotes.Rename("origin", "upstream"); fixture.BranchTo("release/2.0.0"); fixture.MakeACommit(); - Commands.Fetch((Repository)fixture.LocalRepositoryFixture.Repository, fixture.LocalRepositoryFixture.Repository.Network.Remotes.First().Name, new string[0], new FetchOptions(), null); + Commands.Fetch((Repository)fixture.LocalRepositoryFixture.Repository, fixture.LocalRepositoryFixture.Repository.Network.Remotes.First().Name, System.Array.Empty(), new FetchOptions(), null); fixture.LocalRepositoryFixture.MergeNoFF("upstream/release/2.0.0"); diff --git a/src/GitVersion.Core.Tests/VersionCalculation/Strategies/VersionInBranchNameBaseVersionStrategyTests.cs b/src/GitVersion.Core.Tests/VersionCalculation/Strategies/VersionInBranchNameBaseVersionStrategyTests.cs index 64d325d77c..7907fcd4ef 100644 --- a/src/GitVersion.Core.Tests/VersionCalculation/Strategies/VersionInBranchNameBaseVersionStrategyTests.cs +++ b/src/GitVersion.Core.Tests/VersionCalculation/Strategies/VersionInBranchNameBaseVersionStrategyTests.cs @@ -72,7 +72,7 @@ public void CanTakeVersionFromNameOfRemoteReleaseBranch(string branchName, strin Commands.Checkout(fixture.Repository, branch); fixture.MakeACommit(); - Commands.Fetch((Repository)fixture.LocalRepositoryFixture.Repository, fixture.LocalRepositoryFixture.Repository.Network.Remotes.First().Name, new string[0], new FetchOptions(), null); + Commands.Fetch((Repository)fixture.LocalRepositoryFixture.Repository, fixture.LocalRepositoryFixture.Repository.Network.Remotes.First().Name, System.Array.Empty(), new FetchOptions(), null); fixture.LocalRepositoryFixture.Checkout($"origin/{branchName}"); var strategy = GetVersionStrategy(fixture.RepositoryPath, fixture.Repository.ToGitRepository(), branchName); diff --git a/src/GitVersion.Core/BuildAgents/GitHubActions.cs b/src/GitVersion.Core/BuildAgents/GitHubActions.cs index b84f59f24b..8229b8488a 100644 --- a/src/GitVersion.Core/BuildAgents/GitHubActions.cs +++ b/src/GitVersion.Core/BuildAgents/GitHubActions.cs @@ -26,7 +26,7 @@ public override string GenerateSetVersionMessage(VersionVariables variables) => public override string[] GenerateSetParameterMessage(string name, string value) => // There is no equivalent function in GitHub Actions. - new string[0]; + System.Array.Empty(); public override void WriteIntegration(System.Action writer, VersionVariables variables, bool updateBuildNumber = true) { diff --git a/src/GitVersion.Core/BuildAgents/SpaceAutomation.cs b/src/GitVersion.Core/BuildAgents/SpaceAutomation.cs index 381b641bc9..8e15fa20d5 100644 --- a/src/GitVersion.Core/BuildAgents/SpaceAutomation.cs +++ b/src/GitVersion.Core/BuildAgents/SpaceAutomation.cs @@ -15,7 +15,7 @@ public SpaceAutomation(IEnvironment environment, ILog log) : base(environment, l public override string? GetCurrentBranch(bool usingDynamicRepos) => Environment.GetEnvironmentVariable("JB_SPACE_GIT_BRANCH"); - public override string[] GenerateSetParameterMessage(string name, string value) => new string[0]; + public override string[] GenerateSetParameterMessage(string name, string value) => System.Array.Empty(); public override string GenerateSetVersionMessage(VersionVariables variables) => string.Empty; } diff --git a/src/GitVersion.Core/Core/RepositoryStore.cs b/src/GitVersion.Core/Core/RepositoryStore.cs index 3ee8dcf3bf..48b9c1e4cc 100644 --- a/src/GitVersion.Core/Core/RepositoryStore.cs +++ b/src/GitVersion.Core/Core/RepositoryStore.cs @@ -345,7 +345,7 @@ public SemanticVersion GetCurrentCommitTaggedVersion(ICommit? commit, EffectiveC { version }; - return new SemanticVersion[0]; + return Array.Empty(); }) .Max(); diff --git a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/TrackReleaseBranchesVersionStrategy.cs b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/TrackReleaseBranchesVersionStrategy.cs index d73e9ce21c..cd7cc0b587 100644 --- a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/TrackReleaseBranchesVersionStrategy.cs +++ b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/TrackReleaseBranchesVersionStrategy.cs @@ -45,13 +45,13 @@ public override IEnumerable GetVersions() return ReleaseBranchBaseVersions().Union(MainTagsVersions()); } - return new BaseVersion[0]; + return Array.Empty(); } private IEnumerable MainTagsVersions() { var main = this.repositoryStore.FindBranch(Config.MainBranchKey); - return main != null ? this.taggedCommitVersionStrategy.GetTaggedVersions(main, null) : new BaseVersion[0]; + return main != null ? this.taggedCommitVersionStrategy.GetTaggedVersions(main, null) : Array.Empty(); } @@ -78,7 +78,7 @@ private IEnumerable ReleaseBranchBaseVersions() }) .ToList(); } - return new BaseVersion[0]; + return Array.Empty(); } private IEnumerable GetReleaseVersion(GitVersionContext context, IBranch releaseBranch) @@ -90,7 +90,7 @@ private IEnumerable GetReleaseVersion(GitVersionContext context, IB if (Equals(baseSource, context.CurrentCommit)) { // Ignore the branch if it has no commits. - return new BaseVersion[0]; + return Array.Empty(); } return this.releaseVersionStrategy diff --git a/src/GitVersion.MsBuild.Tests/Tasks/TestTaskBase.cs b/src/GitVersion.MsBuild.Tests/Tasks/TestTaskBase.cs index a61fe5de20..aa190580fe 100644 --- a/src/GitVersion.MsBuild.Tests/Tasks/TestTaskBase.cs +++ b/src/GitVersion.MsBuild.Tests/Tasks/TestTaskBase.cs @@ -111,7 +111,7 @@ private static RemoteRepositoryFixture CreateRemoteRepositoryFixture() fixture.Repository.MakeACommit(); fixture.Repository.CreateBranch("develop"); - Commands.Fetch((Repository)fixture.LocalRepositoryFixture.Repository, fixture.LocalRepositoryFixture.Repository.Network.Remotes.First().Name, new string[0], new FetchOptions(), null); + Commands.Fetch((Repository)fixture.LocalRepositoryFixture.Repository, fixture.LocalRepositoryFixture.Repository.Network.Remotes.First().Name, Array.Empty(), new FetchOptions(), null); Commands.Checkout(fixture.LocalRepositoryFixture.Repository, fixture.Repository.Head.Tip); fixture.LocalRepositoryFixture.Repository.Branches.Remove(MainBranch); fixture.InitializeRepo(); From 263eaa6b73e8cf676fe2a61e2081b79ea074c45c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Fri, 16 Jul 2021 19:23:06 +0200 Subject: [PATCH 62/79] CA1822: Mark members as static --- .editorconfig | 3 +++ src/GitVersion.App.Tests/UpdateWixVersionFileTests.cs | 2 +- src/GitVersion.App.Tests/VersionWriterTests.cs | 2 +- src/GitVersion.App/ArgumentParser.cs | 2 +- src/GitVersion.App/OverrideConfigOptionParser.cs | 2 +- .../IntegrationTests/ReleaseBranchScenarios.cs | 2 +- .../VersionConverters/ProjectFileUpdaterTests.cs | 8 ++++---- .../Configuration/Init/BuildServer/AppVeyorSetup.cs | 2 +- src/GitVersion.Core/Logging/ConsoleAppender.cs | 2 +- .../SemanticVersioning/SemanticVersionBuildMetaData.cs | 2 +- .../SemanticVersioning/SemanticVersionPreReleaseTag.cs | 2 +- .../VersionConverters/AssemblyInfo/ProjectFileUpdater.cs | 2 +- 12 files changed, 17 insertions(+), 14 deletions(-) diff --git a/.editorconfig b/.editorconfig index 0956d7aad8..da573c3bac 100644 --- a/.editorconfig +++ b/.editorconfig @@ -163,3 +163,6 @@ dotnet_diagnostic.IDE0041.severity = warning # CA1825: Avoid zero-length array allocations dotnet_diagnostic.CA1825.severity = warning + +# CA1822: Mark members as static +dotnet_diagnostic.CA1822.severity = warning diff --git a/src/GitVersion.App.Tests/UpdateWixVersionFileTests.cs b/src/GitVersion.App.Tests/UpdateWixVersionFileTests.cs index 75713ed59a..b6ced7f1a7 100644 --- a/src/GitVersion.App.Tests/UpdateWixVersionFileTests.cs +++ b/src/GitVersion.App.Tests/UpdateWixVersionFileTests.cs @@ -72,7 +72,7 @@ public void WixVersionFileContentTest() } } - private Dictionary GetGitVersionVarsInWixFile(string file) + private static Dictionary GetGitVersionVarsInWixFile(string file) { var gitVersionVarsInWix = new Dictionary(); using (var reader = new XmlTextReader(file)) diff --git a/src/GitVersion.App.Tests/VersionWriterTests.cs b/src/GitVersion.App.Tests/VersionWriterTests.cs index ee3b33457c..2504d84f07 100644 --- a/src/GitVersion.App.Tests/VersionWriterTests.cs +++ b/src/GitVersion.App.Tests/VersionWriterTests.cs @@ -44,7 +44,7 @@ public void WriteVersionShouldWriteFileVersionWithPrereleaseTag() Assert.AreEqual("1.0.0-beta0004", version); } - private Assembly GenerateAssembly(Version fileVersion, string prereleaseInfo) + private static Assembly GenerateAssembly(Version fileVersion, string prereleaseInfo) { var definition = new AssemblyNameDefinition("test-asm", fileVersion); diff --git a/src/GitVersion.App/ArgumentParser.cs b/src/GitVersion.App/ArgumentParser.cs index a8191543b5..354036dfc3 100644 --- a/src/GitVersion.App/ArgumentParser.cs +++ b/src/GitVersion.App/ArgumentParser.cs @@ -439,7 +439,7 @@ private static void ParseOverrideConfig(Arguments arguments, string[] values) } var optionKey = keyAndValue[0].ToLowerInvariant(); - if (!parser.SupportedProperties.Contains(optionKey)) + if (!OverrideConfigOptionParser.SupportedProperties.Contains(optionKey)) { throw new WarningException($"Could not parse /overrideconfig option: {keyValueOption}. Unsuported 'key'."); } diff --git a/src/GitVersion.App/OverrideConfigOptionParser.cs b/src/GitVersion.App/OverrideConfigOptionParser.cs index 86ce338e72..ac9561dd1a 100644 --- a/src/GitVersion.App/OverrideConfigOptionParser.cs +++ b/src/GitVersion.App/OverrideConfigOptionParser.cs @@ -12,7 +12,7 @@ internal class OverrideConfigOptionParser private readonly Lazy _lazyConfig = new(); - internal ILookup SupportedProperties => _lazySupportedProperties.Value; + internal static ILookup SupportedProperties => _lazySupportedProperties.Value; /// /// Dynamically creates of diff --git a/src/GitVersion.Core.Tests/IntegrationTests/ReleaseBranchScenarios.cs b/src/GitVersion.Core.Tests/IntegrationTests/ReleaseBranchScenarios.cs index 245033d053..5393864ef2 100644 --- a/src/GitVersion.Core.Tests/IntegrationTests/ReleaseBranchScenarios.cs +++ b/src/GitVersion.Core.Tests/IntegrationTests/ReleaseBranchScenarios.cs @@ -469,7 +469,7 @@ public void CommitBeetweenMergeReleaseToDevelopShouldNotResetCount() fixture.AssertFullSemver("2.0.0-beta.4", config); } - public void ReleaseBranchShouldUseBranchNameVersionDespiteBumpInPreviousCommit() + public static void ReleaseBranchShouldUseBranchNameVersionDespiteBumpInPreviousCommit() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0"); diff --git a/src/GitVersion.Core.Tests/VersionConverters/ProjectFileUpdaterTests.cs b/src/GitVersion.Core.Tests/VersionConverters/ProjectFileUpdaterTests.cs index 224cbb1038..22303c55de 100644 --- a/src/GitVersion.Core.Tests/VersionConverters/ProjectFileUpdaterTests.cs +++ b/src/GitVersion.Core.Tests/VersionConverters/ProjectFileUpdaterTests.cs @@ -215,7 +215,7 @@ public void UpdateProjectXmlVersionElementWithStandardXmlInsertsElement(string x var variables = this.variableProvider.GetVariablesFor(SemanticVersion.Parse("2.0.0", "v"), new TestEffectiveConfiguration(), false); var xmlRoot = XElement.Parse(xml); - projectFileUpdater.UpdateProjectVersionElement(xmlRoot, ProjectFileUpdater.AssemblyVersionElement, variables.AssemblySemVer); + ProjectFileUpdater.UpdateProjectVersionElement(xmlRoot, ProjectFileUpdater.AssemblyVersionElement, variables.AssemblySemVer); var expectedXml = XElement.Parse(@" @@ -245,7 +245,7 @@ public void UpdateProjectXmlVersionElementWithStandardXmlModifiesElement(string var variables = this.variableProvider.GetVariablesFor(SemanticVersion.Parse("2.0.0", "v"), new TestEffectiveConfiguration(), false); var xmlRoot = XElement.Parse(xml); - projectFileUpdater.UpdateProjectVersionElement(xmlRoot, ProjectFileUpdater.AssemblyVersionElement, variables.AssemblySemVer); + ProjectFileUpdater.UpdateProjectVersionElement(xmlRoot, ProjectFileUpdater.AssemblyVersionElement, variables.AssemblySemVer); var expectedXml = XElement.Parse(@" @@ -278,7 +278,7 @@ public void UpdateProjectXmlVersionElementWithDuplicatePropertyGroupsModifiesLas var variables = this.variableProvider.GetVariablesFor(SemanticVersion.Parse("2.0.0", "v"), new TestEffectiveConfiguration(), false); var xmlRoot = XElement.Parse(xml); - projectFileUpdater.UpdateProjectVersionElement(xmlRoot, ProjectFileUpdater.AssemblyVersionElement, variables.AssemblySemVer); + ProjectFileUpdater.UpdateProjectVersionElement(xmlRoot, ProjectFileUpdater.AssemblyVersionElement, variables.AssemblySemVer); var expectedXml = XElement.Parse(@" @@ -312,7 +312,7 @@ public void UpdateProjectXmlVersionElementWithMultipleVersionElementsLastOneIsMo var variables = this.variableProvider.GetVariablesFor(SemanticVersion.Parse("2.0.0", "v"), new TestEffectiveConfiguration(), false); var xmlRoot = XElement.Parse(xml); - projectFileUpdater.UpdateProjectVersionElement(xmlRoot, ProjectFileUpdater.AssemblyVersionElement, variables.AssemblySemVer); + ProjectFileUpdater.UpdateProjectVersionElement(xmlRoot, ProjectFileUpdater.AssemblyVersionElement, variables.AssemblySemVer); var expectedXml = XElement.Parse(@" diff --git a/src/GitVersion.Core/Configuration/Init/BuildServer/AppVeyorSetup.cs b/src/GitVersion.Core/Configuration/Init/BuildServer/AppVeyorSetup.cs index 28c4bb8531..40b9aac869 100644 --- a/src/GitVersion.Core/Configuration/Init/BuildServer/AppVeyorSetup.cs +++ b/src/GitVersion.Core/Configuration/Init/BuildServer/AppVeyorSetup.cs @@ -108,7 +108,7 @@ protected override string GetPrompt(Config config, string workingDirectory) return prompt.ToString(); } - private string GetOutputFilename(string workingDirectory, IFileSystem fileSystem) + private static string GetOutputFilename(string workingDirectory, IFileSystem fileSystem) { if (AppVeyorConfigExists(workingDirectory, fileSystem)) { diff --git a/src/GitVersion.Core/Logging/ConsoleAppender.cs b/src/GitVersion.Core/Logging/ConsoleAppender.cs index 038e3e9464..bb3c0a81ff 100644 --- a/src/GitVersion.Core/Logging/ConsoleAppender.cs +++ b/src/GitVersion.Core/Logging/ConsoleAppender.cs @@ -47,7 +47,7 @@ public void WriteTo(LogLevel level, string message) } } - private IDictionary CreatePalette() + private static IDictionary CreatePalette() { var background = Console.BackgroundColor; var palette = new Dictionary diff --git a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionBuildMetaData.cs b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionBuildMetaData.cs index 90803e71bc..395187537e 100644 --- a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionBuildMetaData.cs +++ b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionBuildMetaData.cs @@ -147,7 +147,7 @@ public static SemanticVersionBuildMetaData Parse(string? buildMetaData) return semanticVersionBuildMetaData; } - private string FormatMetaDataPart(string value) + private static string FormatMetaDataPart(string value) { if (!value.IsNullOrEmpty()) value = Regex.Replace(value, "[^0-9A-Za-z-.]", "-"); diff --git a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionPreReleaseTag.cs b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionPreReleaseTag.cs index 0f24cc04d0..1149d4e255 100644 --- a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionPreReleaseTag.cs +++ b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersionPreReleaseTag.cs @@ -153,7 +153,7 @@ public int CompareTo(SemanticVersionPreReleaseTag? other) }; } - private string FormatLegacy(string tag, string number = "") + private static string FormatLegacy(string tag, string number = "") { var tagEndsWithANumber = char.IsNumber(tag.LastOrDefault()); if (tagEndsWithANumber && number.Length > 0) diff --git a/src/GitVersion.Core/VersionConverters/AssemblyInfo/ProjectFileUpdater.cs b/src/GitVersion.Core/VersionConverters/AssemblyInfo/ProjectFileUpdater.cs index bd975faa94..99427541e9 100644 --- a/src/GitVersion.Core/VersionConverters/AssemblyInfo/ProjectFileUpdater.cs +++ b/src/GitVersion.Core/VersionConverters/AssemblyInfo/ProjectFileUpdater.cs @@ -138,7 +138,7 @@ internal bool CanUpdateProjectFile(XElement xmlRoot) return true; } - internal void UpdateProjectVersionElement(XElement xmlRoot, string versionElement, string versionValue) + internal static void UpdateProjectVersionElement(XElement xmlRoot, string versionElement, string versionValue) { var propertyGroups = xmlRoot.Descendants("PropertyGroup").ToList(); From 3e71df3a83899e5e1d241b2d5d474435ee3792a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Fri, 16 Jul 2021 19:24:14 +0200 Subject: [PATCH 63/79] CA2208: Instantiate argument exceptions correctly --- .editorconfig | 3 +++ .../VersionCalculation/SemanticVersioning/SemanticVersion.cs | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/.editorconfig b/.editorconfig index da573c3bac..fbebc3cd02 100644 --- a/.editorconfig +++ b/.editorconfig @@ -166,3 +166,6 @@ dotnet_diagnostic.CA1825.severity = warning # CA1822: Mark members as static dotnet_diagnostic.CA1822.severity = warning + +# CA2208: Instantiate argument exceptions correctly +dotnet_diagnostic.CA2208.severity = warning diff --git a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs index 2b0ae36ae9..04c2f66a7f 100644 --- a/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs +++ b/src/GitVersion.Core/VersionCalculation/SemanticVersioning/SemanticVersion.cs @@ -298,7 +298,7 @@ public SemanticVersion IncrementVersion(VersionField incrementStrategy) incremented.Patch++; break; default: - throw new ArgumentOutOfRangeException(); + throw new ArgumentOutOfRangeException(nameof(incrementStrategy)); } } else From 19e45fcd3977ef6d41c0f3acec492bb03cec82a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Fri, 16 Jul 2021 21:01:16 +0200 Subject: [PATCH 64/79] Fix formatting --- src/GitVersion.Core.Tests/Helpers/DirectoryHelper.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/GitVersion.Core.Tests/Helpers/DirectoryHelper.cs b/src/GitVersion.Core.Tests/Helpers/DirectoryHelper.cs index 4d75e308a4..8ba59b9d91 100644 --- a/src/GitVersion.Core.Tests/Helpers/DirectoryHelper.cs +++ b/src/GitVersion.Core.Tests/Helpers/DirectoryHelper.cs @@ -8,8 +8,8 @@ public static class DirectoryHelper { private static readonly Dictionary ToRename = new() { - {"gitted", ".git"}, - {"gitmodules", ".gitmodules"}, + { "gitted", ".git" }, + { "gitmodules", ".gitmodules" }, }; public static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target) From 0cc298eed412e3eb883250fa5920bc4d644dd2dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Fri, 16 Jul 2021 23:14:39 +0200 Subject: [PATCH 65/79] Extract the analyzers into Directory.Build.props --- src/Directory.Build.props | 14 ++++++++++++++ src/GitTools.Testing/GitTools.Testing.csproj | 8 -------- .../GitVersion.App.Tests.csproj | 9 --------- src/GitVersion.App/GitVersion.App.csproj | 8 -------- .../GitVersion.Core.Tests.csproj | 8 -------- src/GitVersion.Core/GitVersion.Core.csproj | 8 -------- .../GitVersion.LibGit2Sharp.csproj | 8 -------- .../GitVersion.MsBuild.Tests.csproj | 8 -------- src/GitVersion.MsBuild/GitVersion.MsBuild.csproj | 8 -------- 9 files changed, 14 insertions(+), 65 deletions(-) diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 4a52b34715..ac6abe8a32 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -39,6 +39,8 @@ 3.0.107 4.0.3 + 3.10.0 + 5.0.3 @@ -82,4 +84,16 @@ + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + diff --git a/src/GitTools.Testing/GitTools.Testing.csproj b/src/GitTools.Testing/GitTools.Testing.csproj index 42a1cff0a6..5c885c3877 100644 --- a/src/GitTools.Testing/GitTools.Testing.csproj +++ b/src/GitTools.Testing/GitTools.Testing.csproj @@ -6,13 +6,5 @@ - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - diff --git a/src/GitVersion.App.Tests/GitVersion.App.Tests.csproj b/src/GitVersion.App.Tests/GitVersion.App.Tests.csproj index d55c33df9d..11ccc6fe55 100644 --- a/src/GitVersion.App.Tests/GitVersion.App.Tests.csproj +++ b/src/GitVersion.App.Tests/GitVersion.App.Tests.csproj @@ -6,15 +6,6 @@ - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - diff --git a/src/GitVersion.App/GitVersion.App.csproj b/src/GitVersion.App/GitVersion.App.csproj index a3d2d73836..c98673eb24 100644 --- a/src/GitVersion.App/GitVersion.App.csproj +++ b/src/GitVersion.App/GitVersion.App.csproj @@ -26,14 +26,6 @@ - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - diff --git a/src/GitVersion.Core.Tests/GitVersion.Core.Tests.csproj b/src/GitVersion.Core.Tests/GitVersion.Core.Tests.csproj index 84adfd0f4a..5e6ed30613 100644 --- a/src/GitVersion.Core.Tests/GitVersion.Core.Tests.csproj +++ b/src/GitVersion.Core.Tests/GitVersion.Core.Tests.csproj @@ -13,14 +13,6 @@ - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - diff --git a/src/GitVersion.Core/GitVersion.Core.csproj b/src/GitVersion.Core/GitVersion.Core.csproj index bdcb6183da..8558d2c327 100644 --- a/src/GitVersion.Core/GitVersion.Core.csproj +++ b/src/GitVersion.Core/GitVersion.Core.csproj @@ -14,14 +14,6 @@ - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - diff --git a/src/GitVersion.LibGit2Sharp/GitVersion.LibGit2Sharp.csproj b/src/GitVersion.LibGit2Sharp/GitVersion.LibGit2Sharp.csproj index 3c847543a5..0fe8d0c06c 100644 --- a/src/GitVersion.LibGit2Sharp/GitVersion.LibGit2Sharp.csproj +++ b/src/GitVersion.LibGit2Sharp/GitVersion.LibGit2Sharp.csproj @@ -7,14 +7,6 @@ - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - diff --git a/src/GitVersion.MsBuild.Tests/GitVersion.MsBuild.Tests.csproj b/src/GitVersion.MsBuild.Tests/GitVersion.MsBuild.Tests.csproj index 418a2ba532..ce2aee7142 100644 --- a/src/GitVersion.MsBuild.Tests/GitVersion.MsBuild.Tests.csproj +++ b/src/GitVersion.MsBuild.Tests/GitVersion.MsBuild.Tests.csproj @@ -10,14 +10,6 @@ - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - diff --git a/src/GitVersion.MsBuild/GitVersion.MsBuild.csproj b/src/GitVersion.MsBuild/GitVersion.MsBuild.csproj index 5b02a4aad3..5a44bda44b 100644 --- a/src/GitVersion.MsBuild/GitVersion.MsBuild.csproj +++ b/src/GitVersion.MsBuild/GitVersion.MsBuild.csproj @@ -14,14 +14,6 @@ - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - From 01f61ed40a1ec929fb2af73b8ff1b2959e1ebcf3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Fri, 16 Jul 2021 23:26:02 +0200 Subject: [PATCH 66/79] Remove underscore prefix for fields --- .../Fixtures/RepositoryFixtureBase.cs | 20 ++++---- .../Fixtures/SequenceDiagram.cs | 48 +++++++++---------- .../OverrideConfigOptionParser.cs | 12 ++--- .../Configuration/ConfigurationBuilder.cs | 6 +-- .../Mocks/MockEngine.cs | 22 ++++----- 5 files changed, 54 insertions(+), 54 deletions(-) diff --git a/src/GitTools.Testing/Fixtures/RepositoryFixtureBase.cs b/src/GitTools.Testing/Fixtures/RepositoryFixtureBase.cs index 6a2c95b6d7..8a6f2bdd62 100644 --- a/src/GitTools.Testing/Fixtures/RepositoryFixtureBase.cs +++ b/src/GitTools.Testing/Fixtures/RepositoryFixtureBase.cs @@ -9,7 +9,7 @@ namespace GitTools.Testing /// public abstract class RepositoryFixtureBase : IDisposable { - private readonly SequenceDiagram _sequenceDiagram; + private readonly SequenceDiagram sequenceDiagram; protected RepositoryFixtureBase(Func repoBuilder) : this(repoBuilder(PathHelper.GetTempPath())) @@ -18,7 +18,7 @@ protected RepositoryFixtureBase(Func repoBuilder) protected RepositoryFixtureBase(IRepository repository) { - this._sequenceDiagram = new SequenceDiagram(); + this.sequenceDiagram = new SequenceDiagram(); Repository = repository; Repository.Config.Set("user.name", "Test"); Repository.Config.Set("user.email", "test@email.com"); @@ -33,7 +33,7 @@ public string RepositoryPath public SequenceDiagram SequenceDiagram { - get { return this._sequenceDiagram; } + get { return this.sequenceDiagram; } } /// @@ -53,10 +53,10 @@ public virtual void Dispose() e.Message); } - this._sequenceDiagram.End(); + this.sequenceDiagram.End(); Console.WriteLine("**Visualisation of test:**"); Console.WriteLine(string.Empty); - Console.WriteLine(this._sequenceDiagram.GetDiagram()); + Console.WriteLine(this.sequenceDiagram.GetDiagram()); } public void Checkout(string branch) => Commands.Checkout(Repository, branch); @@ -71,20 +71,20 @@ public void MakeATaggedCommit(string tag) public void ApplyTag(string tag) { - this._sequenceDiagram.ApplyTag(tag, Repository.Head.FriendlyName); + this.sequenceDiagram.ApplyTag(tag, Repository.Head.FriendlyName); Repository.ApplyTag(tag); } public void BranchTo(string branchName, string @as = null) { - this._sequenceDiagram.BranchTo(branchName, Repository.Head.FriendlyName, @as); + this.sequenceDiagram.BranchTo(branchName, Repository.Head.FriendlyName, @as); var branch = Repository.CreateBranch(branchName); Commands.Checkout(Repository, branch); } public void BranchToFromTag(string branchName, string fromTag, string onBranch, string @as = null) { - this._sequenceDiagram.BranchToFromTag(branchName, fromTag, onBranch, @as); + this.sequenceDiagram.BranchToFromTag(branchName, fromTag, onBranch, @as); var branch = Repository.CreateBranch(branchName); Commands.Checkout(Repository, branch); } @@ -92,7 +92,7 @@ public void BranchToFromTag(string branchName, string fromTag, string onBranch, public void MakeACommit() { var to = Repository.Head.FriendlyName; - this._sequenceDiagram.MakeACommit(to); + this.sequenceDiagram.MakeACommit(to); Repository.MakeACommit(); } @@ -101,7 +101,7 @@ public void MakeACommit() /// public void MergeNoFF(string mergeSource) { - this._sequenceDiagram.Merge(mergeSource, Repository.Head.FriendlyName); + this.sequenceDiagram.Merge(mergeSource, Repository.Head.FriendlyName); Repository.MergeNoFF(mergeSource, Generate.SignatureNow()); } diff --git a/src/GitTools.Testing/Fixtures/SequenceDiagram.cs b/src/GitTools.Testing/Fixtures/SequenceDiagram.cs index 6a2e6a8b71..62b2641034 100644 --- a/src/GitTools.Testing/Fixtures/SequenceDiagram.cs +++ b/src/GitTools.Testing/Fixtures/SequenceDiagram.cs @@ -9,49 +9,49 @@ namespace GitTools.Testing /// public class SequenceDiagram { - private readonly Dictionary _participants = new(); - private readonly StringBuilder _diagramBuilder; + private readonly Dictionary participants = new(); + private readonly StringBuilder diagramBuilder; /// /// Initializes a new instance of the class. /// public SequenceDiagram() { - this._diagramBuilder = new StringBuilder(); - this._diagramBuilder.AppendLine("@startuml"); + this.diagramBuilder = new StringBuilder(); + this.diagramBuilder.AppendLine("@startuml"); } /// /// Activates a branch/participant in the sequence diagram /// - public void Activate(string branch) => this._diagramBuilder.AppendLineFormat("activate {0}", GetParticipant(branch)); + public void Activate(string branch) => this.diagramBuilder.AppendLineFormat("activate {0}", GetParticipant(branch)); /// /// Destroys a branch/participant in the sequence diagram /// - public void Destroy(string branch) => this._diagramBuilder.AppendLineFormat("destroy {0}", GetParticipant(branch)); + public void Destroy(string branch) => this.diagramBuilder.AppendLineFormat("destroy {0}", GetParticipant(branch)); /// /// Creates a participant in the sequence diagram /// public void Participant(string participant, string @as = null) { - this._participants.Add(participant, @as ?? participant); + this.participants.Add(participant, @as ?? participant); if (@as == null) - this._diagramBuilder.AppendLineFormat("participant {0}", participant); + this.diagramBuilder.AppendLineFormat("participant {0}", participant); else - this._diagramBuilder.AppendLineFormat("participant \"{0}\" as {1}", participant, @as); + this.diagramBuilder.AppendLineFormat("participant \"{0}\" as {1}", participant, @as); } /// /// Appends a divider with specified text to the sequence diagram /// - public void Divider(string text) => this._diagramBuilder.AppendLineFormat("== {0} ==", text); + public void Divider(string text) => this.diagramBuilder.AppendLineFormat("== {0} ==", text); /// /// Appends a note over one or many participants to the sequence diagram /// - public void NoteOver(string noteText, string startParticipant, string endParticipant = null, string prefix = null, string color = null) => this._diagramBuilder.AppendLineFormat( + public void NoteOver(string noteText, string startParticipant, string endParticipant = null, string prefix = null, string color = null) => this.diagramBuilder.AppendLineFormat( prefix + @"note over {0}{1}{2} {3} end note", @@ -63,20 +63,20 @@ public void NoteOver(string noteText, string startParticipant, string endPartici /// /// Appends applying a tag to the specified branch/participant to the sequence diagram /// - public void ApplyTag(string tag, string toBranch) => this._diagramBuilder.AppendLineFormat("{0} -> {0}: tag {1}", GetParticipant(toBranch), tag); + public void ApplyTag(string tag, string toBranch) => this.diagramBuilder.AppendLineFormat("{0} -> {0}: tag {1}", GetParticipant(toBranch), tag); /// /// Appends branching from a branch to another branch, @as can override the participant name /// public void BranchTo(string branchName, string currentName, string @as) { - if (!this._participants.ContainsKey(branchName)) + if (!this.participants.ContainsKey(branchName)) { - this._diagramBuilder.Append("create "); + this.diagramBuilder.Append("create "); Participant(branchName, @as); } - this._diagramBuilder.AppendLineFormat( + this.diagramBuilder.AppendLineFormat( "{0} -> {1}: branch from {2}", GetParticipant(currentName), GetParticipant(branchName), currentName); @@ -87,29 +87,29 @@ public void BranchTo(string branchName, string currentName, string @as) /// public void BranchToFromTag(string branchName, string fromTag, string onBranch, string @as) { - if (!this._participants.ContainsKey(branchName)) + if (!this.participants.ContainsKey(branchName)) { - this._diagramBuilder.Append("create "); + this.diagramBuilder.Append("create "); Participant(branchName, @as); } - this._diagramBuilder.AppendLineFormat("{0} -> {1}: branch from tag ({2})", GetParticipant(onBranch), GetParticipant(branchName), fromTag); + this.diagramBuilder.AppendLineFormat("{0} -> {1}: branch from tag ({2})", GetParticipant(onBranch), GetParticipant(branchName), fromTag); } /// /// Appends a commit on the target participant/branch to the sequence diagram /// - public void MakeACommit(string toParticipant) => this._diagramBuilder.AppendLineFormat("{0} -> {0}: commit", GetParticipant(toParticipant)); + public void MakeACommit(string toParticipant) => this.diagramBuilder.AppendLineFormat("{0} -> {0}: commit", GetParticipant(toParticipant)); /// /// Append a merge to the sequence diagram /// - public void Merge(string @from, string to) => this._diagramBuilder.AppendLineFormat("{0} -> {1}: merge", GetParticipant(@from), GetParticipant(to)); + public void Merge(string @from, string to) => this.diagramBuilder.AppendLineFormat("{0} -> {1}: merge", GetParticipant(@from), GetParticipant(to)); private string GetParticipant(string branch) { - if (this._participants.ContainsKey(branch)) - return this._participants[branch]; + if (this.participants.ContainsKey(branch)) + return this.participants[branch]; return branch; } @@ -117,11 +117,11 @@ private string GetParticipant(string branch) /// /// Ends the sequence diagram /// - public void End() => this._diagramBuilder.AppendLine("@enduml"); + public void End() => this.diagramBuilder.AppendLine("@enduml"); /// /// returns the plantUML representation of the Sequence Diagram /// - public string GetDiagram() => this._diagramBuilder.ToString(); + public string GetDiagram() => this.diagramBuilder.ToString(); } } diff --git a/src/GitVersion.App/OverrideConfigOptionParser.cs b/src/GitVersion.App/OverrideConfigOptionParser.cs index ac9561dd1a..ba6ff97482 100644 --- a/src/GitVersion.App/OverrideConfigOptionParser.cs +++ b/src/GitVersion.App/OverrideConfigOptionParser.cs @@ -10,7 +10,7 @@ internal class OverrideConfigOptionParser private static readonly Lazy> _lazySupportedProperties = new(GetSupportedProperties, true); - private readonly Lazy _lazyConfig = new(); + private readonly Lazy lazyConfig = new(); internal static ILookup SupportedProperties => _lazySupportedProperties.Value; @@ -66,13 +66,13 @@ internal void SetValue(string key, string value) unwrapped = pi.PropertyType; if (unwrapped == typeof(string)) - pi.SetValue(this._lazyConfig.Value, unwrappedText); + pi.SetValue(this.lazyConfig.Value, unwrappedText); else if (unwrapped.IsEnum) { try { var parsedEnum = Enum.Parse(unwrapped, unwrappedText); - pi.SetValue(this._lazyConfig.Value, parsedEnum); + pi.SetValue(this.lazyConfig.Value, parsedEnum); } catch (ArgumentException) { @@ -89,20 +89,20 @@ internal void SetValue(string key, string value) else if (unwrapped == typeof(int)) { if (int.TryParse(unwrappedText, out int parsedInt)) - pi.SetValue(this._lazyConfig.Value, parsedInt); + pi.SetValue(this.lazyConfig.Value, parsedInt); else throw new WarningException($"Could not parse /overrideconfig option: {key}={value}. Ensure that 'value' is valid integer number."); } else if (unwrapped == typeof(bool)) { if (bool.TryParse(unwrappedText, out bool parsedBool)) - pi.SetValue(this._lazyConfig.Value, parsedBool); + pi.SetValue(this.lazyConfig.Value, parsedBool); else throw new WarningException($"Could not parse /overrideconfig option: {key}={value}. Ensure that 'value' is 'true' or 'false'."); } } } - internal Config GetConfig() => this._lazyConfig.IsValueCreated ? this._lazyConfig.Value : null; + internal Config GetConfig() => this.lazyConfig.IsValueCreated ? this.lazyConfig.Value : null; } } diff --git a/src/GitVersion.Core/Configuration/ConfigurationBuilder.cs b/src/GitVersion.Core/Configuration/ConfigurationBuilder.cs index 859a47041b..17d37d8845 100644 --- a/src/GitVersion.Core/Configuration/ConfigurationBuilder.cs +++ b/src/GitVersion.Core/Configuration/ConfigurationBuilder.cs @@ -12,13 +12,13 @@ public class ConfigurationBuilder { private const int DefaultTagPreReleaseWeight = 60000; - private readonly List _overrides = new(); + private readonly List overrides = new(); public ConfigurationBuilder Add([NotNull] Config config) { if (config == null) throw new ArgumentNullException(nameof(config)); - this._overrides.Add(config); + this.overrides.Add(config); return this; } @@ -27,7 +27,7 @@ public Config Build() { var config = CreateDefaultConfiguration(); - foreach (var overrideConfig in this._overrides) + foreach (var overrideConfig in this.overrides) { ApplyOverrides(config, overrideConfig); } diff --git a/src/GitVersion.MsBuild.Tests/Mocks/MockEngine.cs b/src/GitVersion.MsBuild.Tests/Mocks/MockEngine.cs index aa24d21c83..7df299b491 100644 --- a/src/GitVersion.MsBuild.Tests/Mocks/MockEngine.cs +++ b/src/GitVersion.MsBuild.Tests/Mocks/MockEngine.cs @@ -11,8 +11,8 @@ namespace GitVersion.MsBuild.Tests.Mocks { internal sealed class MockEngine : IBuildEngine4 { - private readonly ConcurrentDictionary _objectCache = new(); - private StringBuilder _log = new(); + private readonly ConcurrentDictionary objectCache = new(); + private StringBuilder log = new(); internal MessageImportance MinimumMessageImportance { get; set; } = MessageImportance.Low; @@ -27,21 +27,21 @@ internal sealed class MockEngine : IBuildEngine4 public void LogErrorEvent(BuildErrorEventArgs eventArgs) { Console.WriteLine(EventArgsFormatting.FormatEventMessage(eventArgs)); - this._log.AppendLine(EventArgsFormatting.FormatEventMessage(eventArgs)); + this.log.AppendLine(EventArgsFormatting.FormatEventMessage(eventArgs)); ++Errors; } public void LogWarningEvent(BuildWarningEventArgs eventArgs) { Console.WriteLine(EventArgsFormatting.FormatEventMessage(eventArgs)); - this._log.AppendLine(EventArgsFormatting.FormatEventMessage(eventArgs)); + this.log.AppendLine(EventArgsFormatting.FormatEventMessage(eventArgs)); ++Warnings; } public void LogCustomEvent(CustomBuildEventArgs eventArgs) { Console.WriteLine(eventArgs.Message); - this._log.AppendLine(eventArgs.Message); + this.log.AppendLine(eventArgs.Message); } public void LogMessageEvent(BuildMessageEventArgs eventArgs) @@ -50,7 +50,7 @@ public void LogMessageEvent(BuildMessageEventArgs eventArgs) if (eventArgs.Importance <= MinimumMessageImportance) { Console.WriteLine(eventArgs.Message); - this._log.AppendLine(eventArgs.Message); + this.log.AppendLine(eventArgs.Message); ++Messages; } } @@ -65,8 +65,8 @@ public void LogMessageEvent(BuildMessageEventArgs eventArgs) public string Log { - set => this._log = new StringBuilder(value); - get => this._log.ToString(); + set => this.log = new StringBuilder(value); + get => this.log.ToString(); } public bool BuildProjectFile(string projectFileName, string[] targetNames, IDictionary globalProperties, IDictionary targetOutputs) => false; @@ -114,15 +114,15 @@ public void Reacquire() public object GetRegisteredTaskObject(object key, RegisteredTaskObjectLifetime lifetime) { - this._objectCache.TryGetValue(key, out var obj); + this.objectCache.TryGetValue(key, out var obj); return obj; } - public void RegisterTaskObject(object key, object obj, RegisteredTaskObjectLifetime lifetime, bool allowEarlyCollection) => this._objectCache[key] = obj; + public void RegisterTaskObject(object key, object obj, RegisteredTaskObjectLifetime lifetime, bool allowEarlyCollection) => this.objectCache[key] = obj; public object UnregisterTaskObject(object key, RegisteredTaskObjectLifetime lifetime) { - this._objectCache.TryRemove(key, out var obj); + this.objectCache.TryRemove(key, out var obj); return obj; } } From 243fd75a5b0c4c346038c0f548cbcec55790d81a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Fri, 16 Jul 2021 23:28:16 +0200 Subject: [PATCH 67/79] Run dotnet format command --- .../ArgumentParserOnBuildServerTests.cs | 2 +- src/GitVersion.App.Tests/ArgumentParserTests.cs | 2 +- src/GitVersion.App.Tests/ExecCmdLineArgumentTest.cs | 2 +- src/GitVersion.App.Tests/HelpWriterTests.cs | 2 +- src/GitVersion.App.Tests/Helpers/GitVersionHelper.cs | 2 +- src/GitVersion.App.Tests/Helpers/ProgramFixture.cs | 2 +- src/GitVersion.App.Tests/QuotedStringHelpersTests.cs | 2 +- src/GitVersion.App.Tests/VersionWriterTests.cs | 2 +- src/GitVersion.App/OverrideConfigOptionParser.cs | 2 +- .../BuildAgents/SpaceAutomationTests.cs | 1 - src/GitVersion.Core.Tests/Core/RepositoryStoreTests.cs | 3 +-- .../IntegrationTests/OtherBranchScenarios.cs | 2 +- .../VersionCalculation/NextVersionCalculatorTests.cs | 2 +- .../VersionConverters/ProjectFileUpdaterTests.cs | 8 ++++---- src/GitVersion.Core/BuildAgents/AppVeyor.cs | 2 +- src/GitVersion.Core/BuildAgents/GitHubActions.cs | 2 +- .../Configuration/Init/SetConfig/GlobalModeSetting.cs | 1 - .../Init/SetConfig/SetBranchIncrementMode.cs | 1 - src/GitVersion.Core/Model/VersionVariables.cs | 4 ++-- .../BaseVersionCalculators/TaggedCommitVersionStrategy.cs | 1 - .../VersionCalculation/IncrementStrategyFinder.cs | 1 - .../Helpers/GitToolsTestingExtensions.cs | 2 +- .../Helpers/MsBuildTaskFixture.cs | 2 +- src/GitVersion.MsBuild.Tests/InvalidFileCheckerTests.cs | 2 +- src/GitVersion.MsBuild.Tests/Tasks/TestTaskBase.cs | 4 ++-- 25 files changed, 25 insertions(+), 31 deletions(-) diff --git a/src/GitVersion.App.Tests/ArgumentParserOnBuildServerTests.cs b/src/GitVersion.App.Tests/ArgumentParserOnBuildServerTests.cs index 58fcae2cd2..e66317f350 100644 --- a/src/GitVersion.App.Tests/ArgumentParserOnBuildServerTests.cs +++ b/src/GitVersion.App.Tests/ArgumentParserOnBuildServerTests.cs @@ -1,7 +1,7 @@ using System; using GitVersion.BuildAgents; -using GitVersion.OutputVariables; using GitVersion.Core.Tests.Helpers; +using GitVersion.OutputVariables; using Microsoft.Extensions.DependencyInjection; using NUnit.Framework; using Shouldly; diff --git a/src/GitVersion.App.Tests/ArgumentParserTests.cs b/src/GitVersion.App.Tests/ArgumentParserTests.cs index a9758c5513..d906fd47d8 100644 --- a/src/GitVersion.App.Tests/ArgumentParserTests.cs +++ b/src/GitVersion.App.Tests/ArgumentParserTests.cs @@ -1,11 +1,11 @@ using System.Collections.Generic; using System.IO; +using GitTools.Testing; using GitVersion.Core.Tests.Helpers; using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.Model; using GitVersion.Model.Configuration; -using GitTools.Testing; using Microsoft.Extensions.DependencyInjection; using NUnit.Framework; using Shouldly; diff --git a/src/GitVersion.App.Tests/ExecCmdLineArgumentTest.cs b/src/GitVersion.App.Tests/ExecCmdLineArgumentTest.cs index 501b20973b..c20106d271 100644 --- a/src/GitVersion.App.Tests/ExecCmdLineArgumentTest.cs +++ b/src/GitVersion.App.Tests/ExecCmdLineArgumentTest.cs @@ -2,8 +2,8 @@ using System.IO; using System.Text; using GitTools.Testing; -using GitVersion.Helpers; using GitVersion.Core.Tests.Helpers; +using GitVersion.Helpers; using NUnit.Framework; using Shouldly; diff --git a/src/GitVersion.App.Tests/HelpWriterTests.cs b/src/GitVersion.App.Tests/HelpWriterTests.cs index 17a566c23d..b287a13df3 100644 --- a/src/GitVersion.App.Tests/HelpWriterTests.cs +++ b/src/GitVersion.App.Tests/HelpWriterTests.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; -using GitVersion.Extensions; using GitVersion.Core.Tests.Helpers; +using GitVersion.Extensions; using Microsoft.Extensions.DependencyInjection; using NUnit.Framework; using Shouldly; diff --git a/src/GitVersion.App.Tests/Helpers/GitVersionHelper.cs b/src/GitVersion.App.Tests/Helpers/GitVersionHelper.cs index 9a9182e83a..5f00236504 100644 --- a/src/GitVersion.App.Tests/Helpers/GitVersionHelper.cs +++ b/src/GitVersion.App.Tests/Helpers/GitVersionHelper.cs @@ -4,8 +4,8 @@ using System.Linq; using System.Text; using GitVersion.BuildAgents; -using GitVersion.Helpers; using GitVersion.Core.Tests.Helpers; +using GitVersion.Helpers; using GitVersion.Extensions; namespace GitVersion.App.Tests diff --git a/src/GitVersion.App.Tests/Helpers/ProgramFixture.cs b/src/GitVersion.App.Tests/Helpers/ProgramFixture.cs index cc4d455494..49670a4bb7 100644 --- a/src/GitVersion.App.Tests/Helpers/ProgramFixture.cs +++ b/src/GitVersion.App.Tests/Helpers/ProgramFixture.cs @@ -3,9 +3,9 @@ using System.Linq; using System.Text; using System.Threading.Tasks; +using GitVersion.Core.Tests.Helpers; using GitVersion.Logging; using GitVersion.OutputVariables; -using GitVersion.Core.Tests.Helpers; using Microsoft.Extensions.DependencyInjection; using GitVersion.Extensions; diff --git a/src/GitVersion.App.Tests/QuotedStringHelpersTests.cs b/src/GitVersion.App.Tests/QuotedStringHelpersTests.cs index 0df1721152..79c8275a37 100644 --- a/src/GitVersion.App.Tests/QuotedStringHelpersTests.cs +++ b/src/GitVersion.App.Tests/QuotedStringHelpersTests.cs @@ -1,6 +1,6 @@ +using System.Collections.Generic; using GitVersion; using NUnit.Framework; -using System.Collections.Generic; namespace GitVersionExe.Tests { diff --git a/src/GitVersion.App.Tests/VersionWriterTests.cs b/src/GitVersion.App.Tests/VersionWriterTests.cs index 2504d84f07..8f22e12c6a 100644 --- a/src/GitVersion.App.Tests/VersionWriterTests.cs +++ b/src/GitVersion.App.Tests/VersionWriterTests.cs @@ -1,8 +1,8 @@ using System; using System.IO; using System.Reflection; -using GitVersion.Extensions; using GitVersion.Core.Tests.Helpers; +using GitVersion.Extensions; using Microsoft.Extensions.DependencyInjection; using Mono.Cecil; using NUnit.Framework; diff --git a/src/GitVersion.App/OverrideConfigOptionParser.cs b/src/GitVersion.App/OverrideConfigOptionParser.cs index ba6ff97482..b9c9ebdb87 100644 --- a/src/GitVersion.App/OverrideConfigOptionParser.cs +++ b/src/GitVersion.App/OverrideConfigOptionParser.cs @@ -1,7 +1,7 @@ -using GitVersion.Model.Configuration; using System; using System.Linq; using System.Reflection; +using GitVersion.Model.Configuration; namespace GitVersion { diff --git a/src/GitVersion.Core.Tests/BuildAgents/SpaceAutomationTests.cs b/src/GitVersion.Core.Tests/BuildAgents/SpaceAutomationTests.cs index d3f022000c..4f041b5627 100644 --- a/src/GitVersion.Core.Tests/BuildAgents/SpaceAutomationTests.cs +++ b/src/GitVersion.Core.Tests/BuildAgents/SpaceAutomationTests.cs @@ -1,4 +1,3 @@ -using System.IO; using GitVersion; using GitVersion.BuildAgents; using GitVersion.Core.Tests.Helpers; diff --git a/src/GitVersion.Core.Tests/Core/RepositoryStoreTests.cs b/src/GitVersion.Core.Tests/Core/RepositoryStoreTests.cs index 4943728446..c6862460d1 100644 --- a/src/GitVersion.Core.Tests/Core/RepositoryStoreTests.cs +++ b/src/GitVersion.Core.Tests/Core/RepositoryStoreTests.cs @@ -1,12 +1,11 @@ using System; using GitTools.Testing; using GitVersion.Core.Tests.Helpers; -using GitVersion.Logging; using GitVersion.Core.Tests.IntegrationTests; +using GitVersion.Logging; using Microsoft.Extensions.DependencyInjection; using NUnit.Framework; using Shouldly; -using NSubstitute.ExceptionExtensions; namespace GitVersion.Core.Tests { diff --git a/src/GitVersion.Core.Tests/IntegrationTests/OtherBranchScenarios.cs b/src/GitVersion.Core.Tests/IntegrationTests/OtherBranchScenarios.cs index 2210da627d..ba6a499978 100644 --- a/src/GitVersion.Core.Tests/IntegrationTests/OtherBranchScenarios.cs +++ b/src/GitVersion.Core.Tests/IntegrationTests/OtherBranchScenarios.cs @@ -1,10 +1,10 @@ +using System.Collections.Generic; using GitTools.Testing; using GitVersion.Core.Tests.Helpers; using GitVersion.Model.Configuration; using LibGit2Sharp; using NUnit.Framework; using Shouldly; -using System.Collections.Generic; namespace GitVersion.Core.Tests.IntegrationTests { diff --git a/src/GitVersion.Core.Tests/VersionCalculation/NextVersionCalculatorTests.cs b/src/GitVersion.Core.Tests/VersionCalculation/NextVersionCalculatorTests.cs index 3feb75a69e..a8f2a406a7 100644 --- a/src/GitVersion.Core.Tests/VersionCalculation/NextVersionCalculatorTests.cs +++ b/src/GitVersion.Core.Tests/VersionCalculation/NextVersionCalculatorTests.cs @@ -2,9 +2,9 @@ using System.Collections.Generic; using GitTools.Testing; using GitVersion.Core.Tests.Helpers; +using GitVersion.Core.Tests.IntegrationTests; using GitVersion.Model.Configuration; using GitVersion.VersionCalculation; -using GitVersion.Core.Tests.IntegrationTests; using LibGit2Sharp; using Microsoft.Extensions.DependencyInjection; using NUnit.Framework; diff --git a/src/GitVersion.Core.Tests/VersionConverters/ProjectFileUpdaterTests.cs b/src/GitVersion.Core.Tests/VersionConverters/ProjectFileUpdaterTests.cs index 22303c55de..1111354109 100644 --- a/src/GitVersion.Core.Tests/VersionConverters/ProjectFileUpdaterTests.cs +++ b/src/GitVersion.Core.Tests/VersionConverters/ProjectFileUpdaterTests.cs @@ -1,3 +1,7 @@ +using System; +using System.IO; +using System.Xml.Linq; +using GitVersion.Core.Tests.Helpers; using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.OutputVariables; @@ -7,10 +11,6 @@ using NSubstitute; using NUnit.Framework; using Shouldly; -using System; -using System.IO; -using System.Xml.Linq; -using GitVersion.Core.Tests.Helpers; namespace GitVersion.Core.Tests { diff --git a/src/GitVersion.Core/BuildAgents/AppVeyor.cs b/src/GitVersion.Core/BuildAgents/AppVeyor.cs index a71b0efa3e..b785b2a689 100644 --- a/src/GitVersion.Core/BuildAgents/AppVeyor.cs +++ b/src/GitVersion.Core/BuildAgents/AppVeyor.cs @@ -1,9 +1,9 @@ using System; using System.Net.Http; using System.Text; +using System.Text.Json; using GitVersion.Logging; using GitVersion.OutputVariables; -using System.Text.Json; using GitVersion.Extensions; namespace GitVersion.BuildAgents diff --git a/src/GitVersion.Core/BuildAgents/GitHubActions.cs b/src/GitVersion.Core/BuildAgents/GitHubActions.cs index 8229b8488a..219d0e2a93 100644 --- a/src/GitVersion.Core/BuildAgents/GitHubActions.cs +++ b/src/GitVersion.Core/BuildAgents/GitHubActions.cs @@ -1,7 +1,7 @@ using GitVersion.Extensions; +using System.IO; using GitVersion.Logging; using GitVersion.OutputVariables; -using System.IO; namespace GitVersion.BuildAgents { diff --git a/src/GitVersion.Core/Configuration/Init/SetConfig/GlobalModeSetting.cs b/src/GitVersion.Core/Configuration/Init/SetConfig/GlobalModeSetting.cs index e27f0b652b..7d4045e646 100644 --- a/src/GitVersion.Core/Configuration/Init/SetConfig/GlobalModeSetting.cs +++ b/src/GitVersion.Core/Configuration/Init/SetConfig/GlobalModeSetting.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using GitVersion.Configuration.Init.Wizard; -using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.Model.Configuration; using GitVersion.VersionCalculation; diff --git a/src/GitVersion.Core/Configuration/Init/SetConfig/SetBranchIncrementMode.cs b/src/GitVersion.Core/Configuration/Init/SetConfig/SetBranchIncrementMode.cs index 6f88b61c12..aaa82dfe98 100644 --- a/src/GitVersion.Core/Configuration/Init/SetConfig/SetBranchIncrementMode.cs +++ b/src/GitVersion.Core/Configuration/Init/SetConfig/SetBranchIncrementMode.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using GitVersion.Configuration.Init.Wizard; -using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.Model.Configuration; using GitVersion.VersionCalculation; diff --git a/src/GitVersion.Core/Model/VersionVariables.cs b/src/GitVersion.Core/Model/VersionVariables.cs index 07c0c78add..8570257193 100644 --- a/src/GitVersion.Core/Model/VersionVariables.cs +++ b/src/GitVersion.Core/Model/VersionVariables.cs @@ -1,5 +1,3 @@ -using GitVersion.Helpers; -using GitVersion.Logging; using System; using System.Collections; using System.Collections.Generic; @@ -7,6 +5,8 @@ using System.Linq; using System.Text.Encodings.Web; using System.Text.Json; +using GitVersion.Helpers; +using GitVersion.Logging; using YamlDotNet.Serialization; using static GitVersion.Extensions.ObjectExtensions; diff --git a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/TaggedCommitVersionStrategy.cs b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/TaggedCommitVersionStrategy.cs index a32d260627..81224f2a09 100644 --- a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/TaggedCommitVersionStrategy.cs +++ b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/TaggedCommitVersionStrategy.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using GitVersion.Common; -using GitVersion.Extensions; namespace GitVersion.VersionCalculation { diff --git a/src/GitVersion.Core/VersionCalculation/IncrementStrategyFinder.cs b/src/GitVersion.Core/VersionCalculation/IncrementStrategyFinder.cs index 4165f21950..90b47f8390 100644 --- a/src/GitVersion.Core/VersionCalculation/IncrementStrategyFinder.cs +++ b/src/GitVersion.Core/VersionCalculation/IncrementStrategyFinder.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; -using GitVersion.Extensions; using GitVersion.VersionCalculation; namespace GitVersion diff --git a/src/GitVersion.MsBuild.Tests/Helpers/GitToolsTestingExtensions.cs b/src/GitVersion.MsBuild.Tests/Helpers/GitToolsTestingExtensions.cs index cdae720e0b..13b5d626a4 100644 --- a/src/GitVersion.MsBuild.Tests/Helpers/GitToolsTestingExtensions.cs +++ b/src/GitVersion.MsBuild.Tests/Helpers/GitToolsTestingExtensions.cs @@ -1,8 +1,8 @@ using System; using GitTools.Testing; using GitVersion.BuildAgents; -using GitVersion.Extensions; using GitVersion.Core.Tests.Helpers; +using GitVersion.Extensions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; diff --git a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixture.cs b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixture.cs index 55884fcec9..b60f0f78c7 100644 --- a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixture.cs +++ b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixture.cs @@ -4,8 +4,8 @@ using System.Linq; using GitTools.Testing; using GitVersion.BuildAgents; -using GitVersion.MsBuild.Tests.Mocks; using GitVersion.Core.Tests; +using GitVersion.MsBuild.Tests.Mocks; namespace GitVersion.MsBuild.Tests.Helpers { diff --git a/src/GitVersion.MsBuild.Tests/InvalidFileCheckerTests.cs b/src/GitVersion.MsBuild.Tests/InvalidFileCheckerTests.cs index 7a30e148b6..d4c38d5134 100644 --- a/src/GitVersion.MsBuild.Tests/InvalidFileCheckerTests.cs +++ b/src/GitVersion.MsBuild.Tests/InvalidFileCheckerTests.cs @@ -1,7 +1,7 @@ using System; using System.IO; -using GitVersion.MsBuild.Tests.Mocks; using GitVersion.Core.Tests.Helpers; +using GitVersion.MsBuild.Tests.Mocks; using Microsoft.Build.Framework; using NUnit.Framework; diff --git a/src/GitVersion.MsBuild.Tests/Tasks/TestTaskBase.cs b/src/GitVersion.MsBuild.Tests/Tasks/TestTaskBase.cs index aa190580fe..7c56773981 100644 --- a/src/GitVersion.MsBuild.Tests/Tasks/TestTaskBase.cs +++ b/src/GitVersion.MsBuild.Tests/Tasks/TestTaskBase.cs @@ -1,13 +1,13 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using GitTools.Testing; using GitVersion.BuildAgents; -using GitVersion.MsBuild.Tests.Helpers; using GitVersion.Core.Tests.Helpers; +using GitVersion.MsBuild.Tests.Helpers; using LibGit2Sharp; using Microsoft.Build.Utilities.ProjectCreation; -using System.IO; namespace GitVersion.MsBuild.Tests.Tasks { From aa6f96a65cfe10ac87a9bae28786f89daa2160e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Fri, 16 Jul 2021 23:31:55 +0200 Subject: [PATCH 68/79] Fix formatting issues --- .../DefaultConfigFileLocatorTests.cs | 11 +++++----- .../Core/GitVersionExecutorTests.cs | 21 ++++++++++--------- 2 files changed, 17 insertions(+), 15 deletions(-) diff --git a/src/GitVersion.Core.Tests/Configuration/DefaultConfigFileLocatorTests.cs b/src/GitVersion.Core.Tests/Configuration/DefaultConfigFileLocatorTests.cs index f2c940cb8a..31eb29278a 100644 --- a/src/GitVersion.Core.Tests/Configuration/DefaultConfigFileLocatorTests.cs +++ b/src/GitVersion.Core.Tests/Configuration/DefaultConfigFileLocatorTests.cs @@ -219,11 +219,12 @@ private string SetupConfigFileContent(string text, string fileName = null, strin return filePath; } - private static IServiceProvider GetServiceProvider(GitVersionOptions gitVersionOptions, ILog log = null) => ConfigureServices(services => - { - if (log != null) services.AddSingleton(log); - services.AddSingleton(Options.Create(gitVersionOptions)); - }); + private static IServiceProvider GetServiceProvider(GitVersionOptions gitVersionOptions, ILog log = null) => + ConfigureServices(services => + { + if (log != null) services.AddSingleton(log); + services.AddSingleton(Options.Create(gitVersionOptions)); + }); } } } diff --git a/src/GitVersion.Core.Tests/Core/GitVersionExecutorTests.cs b/src/GitVersion.Core.Tests/Core/GitVersionExecutorTests.cs index 8058be4316..82176a570a 100644 --- a/src/GitVersion.Core.Tests/Core/GitVersionExecutorTests.cs +++ b/src/GitVersion.Core.Tests/Core/GitVersionExecutorTests.cs @@ -556,15 +556,16 @@ private IGitVersionCalculateTool GetGitVersionCalculator(GitVersionOptions gitVe return this.sp.GetService(); } - private static IServiceProvider GetServiceProvider(GitVersionOptions gitVersionOptions, ILog log = null, IGitRepository repository = null, IFileSystem fileSystem = null, IEnvironment environment = null) => ConfigureServices(services => - { - if (log != null) services.AddSingleton(log); - if (fileSystem != null) services.AddSingleton(fileSystem); - if (repository != null) services.AddSingleton(repository); - if (environment != null) services.AddSingleton(environment); - var options = Options.Create(gitVersionOptions); - services.AddSingleton(options); - services.AddSingleton(RepositoryExtensions.ToGitRepositoryInfo(options)); - }); + private static IServiceProvider GetServiceProvider(GitVersionOptions gitVersionOptions, ILog log = null, IGitRepository repository = null, IFileSystem fileSystem = null, IEnvironment environment = null) => + ConfigureServices(services => + { + if (log != null) services.AddSingleton(log); + if (fileSystem != null) services.AddSingleton(fileSystem); + if (repository != null) services.AddSingleton(repository); + if (environment != null) services.AddSingleton(environment); + var options = Options.Create(gitVersionOptions); + services.AddSingleton(options); + services.AddSingleton(RepositoryExtensions.ToGitRepositoryInfo(options)); + }); } } From 437b5ab7f68e05f9ee6f74f7cbf359743d77a622 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Fri, 16 Jul 2021 23:46:11 +0200 Subject: [PATCH 69/79] Fix some formatting issues --- .../BaseVersionCalculatorTests.cs | 39 ++++++++++--------- .../BuildAgents/GitHubActions.cs | 8 +--- .../Helpers/MsBuildTaskFixture.cs | 37 +++++++++--------- 3 files changed, 42 insertions(+), 42 deletions(-) diff --git a/src/GitVersion.Core.Tests/VersionCalculation/BaseVersionCalculatorTests.cs b/src/GitVersion.Core.Tests/VersionCalculation/BaseVersionCalculatorTests.cs index 6dd3f00f50..cd46be0ca7 100644 --- a/src/GitVersion.Core.Tests/VersionCalculation/BaseVersionCalculatorTests.cs +++ b/src/GitVersion.Core.Tests/VersionCalculation/BaseVersionCalculatorTests.cs @@ -18,12 +18,13 @@ public class BaseVersionCalculatorTests : TestBase public void ChoosesHighestVersionReturnedFromStrategies() { var dateTimeOffset = DateTimeOffset.Now; - var versionCalculator = GetBaseVersionCalculator(contextBuilder => contextBuilder.OverrideServices(services => -{ - services.RemoveAll(); - services.AddSingleton(new V1Strategy(DateTimeOffset.Now)); - services.AddSingleton(new V2Strategy(dateTimeOffset)); -})); + var versionCalculator = GetBaseVersionCalculator(contextBuilder => + contextBuilder.OverrideServices(services => + { + services.RemoveAll(); + services.AddSingleton(new V1Strategy(DateTimeOffset.Now)); + services.AddSingleton(new V2Strategy(dateTimeOffset)); + })); var baseVersion = versionCalculator.GetBaseVersion(); @@ -37,12 +38,13 @@ public void UsesWhenFromNextBestMatchIfHighestDoesntHaveWhen() { var when = DateTimeOffset.Now; - var versionCalculator = GetBaseVersionCalculator(contextBuilder => contextBuilder.OverrideServices(services => -{ - services.RemoveAll(); - services.AddSingleton(new V1Strategy(when)); - services.AddSingleton(new V2Strategy(null)); -})); + var versionCalculator = GetBaseVersionCalculator(contextBuilder => + contextBuilder.OverrideServices(services => + { + services.RemoveAll(); + services.AddSingleton(new V1Strategy(when)); + services.AddSingleton(new V2Strategy(null)); + })); var baseVersion = versionCalculator.GetBaseVersion(); @@ -56,12 +58,13 @@ public void UsesWhenFromNextBestMatchIfHighestDoesntHaveWhenReversedOrder() { var when = DateTimeOffset.Now; - var versionCalculator = GetBaseVersionCalculator(contextBuilder => contextBuilder.OverrideServices(services => -{ - services.RemoveAll(); - services.AddSingleton(new V1Strategy(null)); - services.AddSingleton(new V2Strategy(when)); -})); + var versionCalculator = GetBaseVersionCalculator(contextBuilder => + contextBuilder.OverrideServices(services => + { + services.RemoveAll(); + services.AddSingleton(new V1Strategy(null)); + services.AddSingleton(new V2Strategy(when)); + })); var baseVersion = versionCalculator.GetBaseVersion(); diff --git a/src/GitVersion.Core/BuildAgents/GitHubActions.cs b/src/GitVersion.Core/BuildAgents/GitHubActions.cs index 219d0e2a93..4993f9a6f3 100644 --- a/src/GitVersion.Core/BuildAgents/GitHubActions.cs +++ b/src/GitVersion.Core/BuildAgents/GitHubActions.cs @@ -19,14 +19,10 @@ public GitHubActions(IEnvironment environment, ILog log) : base(environment, log protected override string EnvironmentVariable { get; } = EnvironmentVariableName; public override string GenerateSetVersionMessage(VersionVariables variables) => - // There is no equivalent function in GitHub Actions. - - string.Empty; + string.Empty; // There is no equivalent function in GitHub Actions. public override string[] GenerateSetParameterMessage(string name, string value) => - // There is no equivalent function in GitHub Actions. - - System.Array.Empty(); + System.Array.Empty(); // There is no equivalent function in GitHub Actions. public override void WriteIntegration(System.Action writer, VersionVariables variables, bool updateBuildNumber = true) { diff --git a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixture.cs b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixture.cs index b60f0f78c7..73338bcfd7 100644 --- a/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixture.cs +++ b/src/GitVersion.MsBuild.Tests/Helpers/MsBuildTaskFixture.cs @@ -18,29 +18,30 @@ public class MsBuildTaskFixture public void WithEnv(params KeyValuePair[] envs) => this.environmentVariables = envs; - public MsBuildTaskFixtureResult Execute(T task) where T : GitVersionTaskBase => UsingEnv(() => - { - var buildEngine = new MockEngine(); + public MsBuildTaskFixtureResult Execute(T task) where T : GitVersionTaskBase => + UsingEnv(() => + { + var buildEngine = new MockEngine(); - task.BuildEngine = buildEngine; + task.BuildEngine = buildEngine; - var versionFile = Path.Combine(task.SolutionDirectory, "gitversion.json"); - this.fixture.WriteVersionVariables(versionFile); + var versionFile = Path.Combine(task.SolutionDirectory, "gitversion.json"); + this.fixture.WriteVersionVariables(versionFile); - task.VersionFile = versionFile; + task.VersionFile = versionFile; - var result = task.Execute(); + var result = task.Execute(); - return new MsBuildTaskFixtureResult(this.fixture) - { - Success = result, - Task = task, - Errors = buildEngine.Errors, - Warnings = buildEngine.Warnings, - Messages = buildEngine.Messages, - Log = buildEngine.Log, - }; - }); + return new MsBuildTaskFixtureResult(this.fixture) + { + Success = result, + Task = task, + Errors = buildEngine.Errors, + Warnings = buildEngine.Warnings, + Messages = buildEngine.Messages, + Log = buildEngine.Log, + }; + }); private T UsingEnv(Func func) { From daf3f0b51c4ac88ee728687aece3bd657b7a6ded Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Sat, 17 Jul 2021 00:00:44 +0200 Subject: [PATCH 70/79] Fix more alignment --- src/GitTools.Testing/Fixtures/SequenceDiagram.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/GitTools.Testing/Fixtures/SequenceDiagram.cs b/src/GitTools.Testing/Fixtures/SequenceDiagram.cs index 62b2641034..0a263f1c2f 100644 --- a/src/GitTools.Testing/Fixtures/SequenceDiagram.cs +++ b/src/GitTools.Testing/Fixtures/SequenceDiagram.cs @@ -51,7 +51,8 @@ public void Participant(string participant, string @as = null) /// /// Appends a note over one or many participants to the sequence diagram /// - public void NoteOver(string noteText, string startParticipant, string endParticipant = null, string prefix = null, string color = null) => this.diagramBuilder.AppendLineFormat( + public void NoteOver(string noteText, string startParticipant, string endParticipant = null, string prefix = null, string color = null) => + this.diagramBuilder.AppendLineFormat( prefix + @"note over {0}{1}{2} {3} end note", From 26ea42acadb783b57c3c7ee40e0846000bbf7622 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Sat, 17 Jul 2021 11:42:10 +0200 Subject: [PATCH 71/79] Expression body for property, accessor and indexer --- .editorconfig | 3 +++ src/GitTools.Testing/Fixtures/RepositoryFixtureBase.cs | 10 ++-------- src/GitVersion.Core/Model/VersionVariables.cs | 8 +------- 3 files changed, 6 insertions(+), 15 deletions(-) diff --git a/.editorconfig b/.editorconfig index fbebc3cd02..8352c240c2 100644 --- a/.editorconfig +++ b/.editorconfig @@ -78,6 +78,9 @@ csharp_style_expression_bodied_constructors = true:warning csharp_style_expression_bodied_operators = true:warning csharp_style_expression_bodied_local_functions = true:warning csharp_style_expression_bodied_lambdas = true:warning +csharp_style_expression_bodied_properties = true:warning +csharp_style_expression_bodied_accessors = true:warning +csharp_style_expression_bodied_indexers = true:warning # Pattern matching preferences csharp_style_pattern_matching_over_as_with_null_check = true:warning diff --git a/src/GitTools.Testing/Fixtures/RepositoryFixtureBase.cs b/src/GitTools.Testing/Fixtures/RepositoryFixtureBase.cs index 8a6f2bdd62..3b833aa99f 100644 --- a/src/GitTools.Testing/Fixtures/RepositoryFixtureBase.cs +++ b/src/GitTools.Testing/Fixtures/RepositoryFixtureBase.cs @@ -26,15 +26,9 @@ protected RepositoryFixtureBase(IRepository repository) public IRepository Repository { get; } - public string RepositoryPath - { - get { return Repository.Info.WorkingDirectory.TrimEnd('\\'); } - } + public string RepositoryPath => Repository.Info.WorkingDirectory.TrimEnd('\\'); - public SequenceDiagram SequenceDiagram - { - get { return this.sequenceDiagram; } - } + public SequenceDiagram SequenceDiagram => this.sequenceDiagram; /// /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. diff --git a/src/GitVersion.Core/Model/VersionVariables.cs b/src/GitVersion.Core/Model/VersionVariables.cs index 8570257193..c6446e74fd 100644 --- a/src/GitVersion.Core/Model/VersionVariables.cs +++ b/src/GitVersion.Core/Model/VersionVariables.cs @@ -118,17 +118,11 @@ public VersionVariables(string major, public string? CommitDate { get; set; } [ReflectionIgnore] - public static IEnumerable AvailableVariables - { - get - { - return typeof(VersionVariables) + public static IEnumerable AvailableVariables => typeof(VersionVariables) .GetProperties() .Where(p => !p.GetCustomAttributes(typeof(ReflectionIgnoreAttribute), false).Any()) .Select(p => p.Name) .OrderBy(a => a, StringComparer.Ordinal); - } - } [ReflectionIgnore] public string? FileName { get; set; } From 58b52c63a8b9b1abb8f7fa342bb7efbefa14e463 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Sat, 17 Jul 2021 16:37:11 +0200 Subject: [PATCH 72/79] Fix field name in reflection --- .../IntegrationTests/MainlineDevelopmentMode.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/GitVersion.Core.Tests/IntegrationTests/MainlineDevelopmentMode.cs b/src/GitVersion.Core.Tests/IntegrationTests/MainlineDevelopmentMode.cs index 5cfc428e42..147fe2aae0 100644 --- a/src/GitVersion.Core.Tests/IntegrationTests/MainlineDevelopmentMode.cs +++ b/src/GitVersion.Core.Tests/IntegrationTests/MainlineDevelopmentMode.cs @@ -529,7 +529,7 @@ public static void MakeACommit(this RepositoryFixtureBase fixture, string commit { fixture.Repository.MakeACommit(commitMsg); var diagramBuilder = (StringBuilder)typeof(SequenceDiagram) - .GetField("_diagramBuilder", BindingFlags.Instance | BindingFlags.NonPublic) + .GetField("diagramBuilder", BindingFlags.Instance | BindingFlags.NonPublic) ?.GetValue(fixture.SequenceDiagram); string GetParticipant(string participant) => From bd6db4758a6a2869ddbc2b19b5b74d7f6df37c00 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Sat, 17 Jul 2021 16:39:06 +0200 Subject: [PATCH 73/79] Add missing `this.` prefix --- src/GitVersion.Core.Tests/Core/RepositoryStoreTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/GitVersion.Core.Tests/Core/RepositoryStoreTests.cs b/src/GitVersion.Core.Tests/Core/RepositoryStoreTests.cs index c6862460d1..863b4a99fc 100644 --- a/src/GitVersion.Core.Tests/Core/RepositoryStoreTests.cs +++ b/src/GitVersion.Core.Tests/Core/RepositoryStoreTests.cs @@ -210,7 +210,7 @@ public void GetBranchesContainingCommitThrowsDirectlyOnNullCommit() { using var fixture = new EmptyRepositoryFixture(); var fixtureRepository = fixture.Repository.ToGitRepository(); - var gitRepoMetadataProvider = new RepositoryStore(log, fixtureRepository); + var gitRepoMetadataProvider = new RepositoryStore(this.log, fixtureRepository); Assert.Throws(() => gitRepoMetadataProvider.GetBranchesContainingCommit(null)); } From 3f26f06e6874b95273bb719302910721e887601f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Thu, 22 Jul 2021 17:04:10 +0200 Subject: [PATCH 74/79] Post rebase cleanup --- .../Extensions/AssemblyVersionsGeneratorExtensions.cs | 2 +- .../VersionCalculation/BaseVersionCalculator.cs | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/src/GitVersion.Core/Extensions/AssemblyVersionsGeneratorExtensions.cs b/src/GitVersion.Core/Extensions/AssemblyVersionsGeneratorExtensions.cs index 3c00b1a56c..8715fa340c 100644 --- a/src/GitVersion.Core/Extensions/AssemblyVersionsGeneratorExtensions.cs +++ b/src/GitVersion.Core/Extensions/AssemblyVersionsGeneratorExtensions.cs @@ -28,7 +28,7 @@ public static class AssemblyVersionsGeneratorExtensions AssemblyVersioningScheme.Major => $"{sv.Major}.0.0.0", AssemblyVersioningScheme.MajorMinor => $"{sv.Major}.{sv.Minor}.0.0", AssemblyVersioningScheme.MajorMinorPatch => $"{sv.Major}.{sv.Minor}.{sv.Patch}.0", - AssemblyVersioningScheme.MajorMinorPatchTag => $"{sv.Major}.{sv.Minor}.{sv.Patch}.{sv.PreReleaseTag.Number ?? 0}", + AssemblyVersioningScheme.MajorMinorPatchTag => $"{sv.Major}.{sv.Minor}.{sv.Patch}.{sv.PreReleaseTag?.Number ?? 0}", AssemblyVersioningScheme.None => null, _ => throw new ArgumentException($"Unexpected value ({scheme}).", nameof(scheme)) }; diff --git a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculator.cs b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculator.cs index 68f5d97eff..8f4243c77a 100644 --- a/src/GitVersion.Core/VersionCalculation/BaseVersionCalculator.cs +++ b/src/GitVersion.Core/VersionCalculation/BaseVersionCalculator.cs @@ -59,9 +59,7 @@ public BaseVersion GetBaseVersion() if (matchingVersionsOnceIncremented.Any()) { var oldest = matchingVersionsOnceIncremented.Aggregate((v1, v2) => - { - return v1.Version!.BaseVersionSource!.When < v2.Version!.BaseVersionSource!.When ? v1 : v2; - }); + v1.Version!.BaseVersionSource!.When < v2.Version!.BaseVersionSource!.When ? v1 : v2); baseVersionWithOldestSource = oldest!.Version!; maxVersion = oldest; this.log.Info($"Found multiple base versions which will produce the same SemVer ({maxVersion.IncrementedVersion}), taking oldest source for commit counting ({baseVersionWithOldestSource!.Source})"); From f6acbd289361c6d3faa31c39ac1e21e160ec4261 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Fri, 23 Jul 2021 09:15:16 +0200 Subject: [PATCH 75/79] Fix using order --- src/GitVersion.App.Tests/Helpers/GitVersionHelper.cs | 2 +- src/GitVersion.App.Tests/Helpers/ProgramFixture.cs | 2 +- src/GitVersion.Core/BuildAgents/AppVeyor.cs | 2 +- src/GitVersion.Core/BuildAgents/GitHubActions.cs | 2 +- .../VersionConverters/AssemblyInfo/ProjectFileUpdater.cs | 6 +++--- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/GitVersion.App.Tests/Helpers/GitVersionHelper.cs b/src/GitVersion.App.Tests/Helpers/GitVersionHelper.cs index 5f00236504..e1552a0987 100644 --- a/src/GitVersion.App.Tests/Helpers/GitVersionHelper.cs +++ b/src/GitVersion.App.Tests/Helpers/GitVersionHelper.cs @@ -5,8 +5,8 @@ using System.Text; using GitVersion.BuildAgents; using GitVersion.Core.Tests.Helpers; -using GitVersion.Helpers; using GitVersion.Extensions; +using GitVersion.Helpers; namespace GitVersion.App.Tests { diff --git a/src/GitVersion.App.Tests/Helpers/ProgramFixture.cs b/src/GitVersion.App.Tests/Helpers/ProgramFixture.cs index 49670a4bb7..16b9dabeda 100644 --- a/src/GitVersion.App.Tests/Helpers/ProgramFixture.cs +++ b/src/GitVersion.App.Tests/Helpers/ProgramFixture.cs @@ -4,10 +4,10 @@ using System.Text; using System.Threading.Tasks; using GitVersion.Core.Tests.Helpers; +using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.OutputVariables; using Microsoft.Extensions.DependencyInjection; -using GitVersion.Extensions; namespace GitVersion.App.Tests { diff --git a/src/GitVersion.Core/BuildAgents/AppVeyor.cs b/src/GitVersion.Core/BuildAgents/AppVeyor.cs index b785b2a689..d68e743d1a 100644 --- a/src/GitVersion.Core/BuildAgents/AppVeyor.cs +++ b/src/GitVersion.Core/BuildAgents/AppVeyor.cs @@ -2,9 +2,9 @@ using System.Net.Http; using System.Text; using System.Text.Json; +using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.OutputVariables; -using GitVersion.Extensions; namespace GitVersion.BuildAgents { diff --git a/src/GitVersion.Core/BuildAgents/GitHubActions.cs b/src/GitVersion.Core/BuildAgents/GitHubActions.cs index 4993f9a6f3..54b2ce33b7 100644 --- a/src/GitVersion.Core/BuildAgents/GitHubActions.cs +++ b/src/GitVersion.Core/BuildAgents/GitHubActions.cs @@ -1,5 +1,5 @@ -using GitVersion.Extensions; using System.IO; +using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.OutputVariables; diff --git a/src/GitVersion.Core/VersionConverters/AssemblyInfo/ProjectFileUpdater.cs b/src/GitVersion.Core/VersionConverters/AssemblyInfo/ProjectFileUpdater.cs index 99427541e9..5c49a7609b 100644 --- a/src/GitVersion.Core/VersionConverters/AssemblyInfo/ProjectFileUpdater.cs +++ b/src/GitVersion.Core/VersionConverters/AssemblyInfo/ProjectFileUpdater.cs @@ -1,11 +1,11 @@ -using GitVersion.Extensions; -using GitVersion.Logging; -using GitVersion.OutputVariables; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; +using GitVersion.Extensions; +using GitVersion.Logging; +using GitVersion.OutputVariables; namespace GitVersion.VersionConverters.AssemblyInfo { From a2445ac2f9e33a883dd726486da6050fcef62c68 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Fri, 23 Jul 2021 15:45:05 +0200 Subject: [PATCH 76/79] CA1810: Initialize reference type static fields inline --- .editorconfig | 3 +++ .../Extensions/StringExtensions.cs | 20 ++----------------- src/GitVersion.Core/Logging/Disposable.cs | 4 +--- src/GitVersion.MsBuild/Helpers/FileHelper.cs | 6 +++--- 4 files changed, 9 insertions(+), 24 deletions(-) diff --git a/.editorconfig b/.editorconfig index 8352c240c2..a5ff20fba2 100644 --- a/.editorconfig +++ b/.editorconfig @@ -172,3 +172,6 @@ dotnet_diagnostic.CA1822.severity = warning # CA2208: Instantiate argument exceptions correctly dotnet_diagnostic.CA2208.severity = warning + +# CA1810: Initialize reference type static fields inline +dotnet_diagnostic.CA1810.severity = warning diff --git a/src/GitVersion.Core/Extensions/StringExtensions.cs b/src/GitVersion.Core/Extensions/StringExtensions.cs index 749be269d6..99663d73ba 100644 --- a/src/GitVersion.Core/Extensions/StringExtensions.cs +++ b/src/GitVersion.Core/Extensions/StringExtensions.cs @@ -9,24 +9,8 @@ namespace GitVersion.Extensions { public static class StringExtensions { - private static readonly string[] Trues; - private static readonly string[] Falses; - - - static StringExtensions() - { - Trues = new[] - { - "1", - "true" - }; - - Falses = new[] - { - "0", - "false" - }; - } + private static readonly string[] Trues = new[] { "1", "true" }; + private static readonly string[] Falses = new[] { "0", "false" }; public static bool IsTrue(this string value) => Trues.Contains(value, StringComparer.OrdinalIgnoreCase); diff --git a/src/GitVersion.Core/Logging/Disposable.cs b/src/GitVersion.Core/Logging/Disposable.cs index 6135bafde7..117509e6f2 100644 --- a/src/GitVersion.Core/Logging/Disposable.cs +++ b/src/GitVersion.Core/Logging/Disposable.cs @@ -4,11 +4,9 @@ namespace GitVersion.Logging { public static class Disposable { - static Disposable() => Empty = Create(() => { }); - public static IDisposable Create(Action disposer) => new AnonymousDisposable(disposer); - public static readonly IDisposable Empty; + public static readonly IDisposable Empty = Create(() => { }); private sealed class AnonymousDisposable : IDisposable { diff --git a/src/GitVersion.MsBuild/Helpers/FileHelper.cs b/src/GitVersion.MsBuild/Helpers/FileHelper.cs index e5dc121eea..29ae3e6a9f 100644 --- a/src/GitVersion.MsBuild/Helpers/FileHelper.cs +++ b/src/GitVersion.MsBuild/Helpers/FileHelper.cs @@ -15,12 +15,12 @@ public static class FileHelper { ".vb", VisualBasicFileContainsVersionAttribute } }; - public static string TempPath; + public static string TempPath = MakeAndGetTempPath(); - static FileHelper() + private static string MakeAndGetTempPath() { - TempPath = Path.Combine(Path.GetTempPath(), "GitVersionTask"); Directory.CreateDirectory(TempPath); + return Path.Combine(Path.GetTempPath(), "GitVersionTask"); } public static void DeleteTempFiles() From 000a8e79e1b2dfbb1abdf7204d779c6addaf5476 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Fri, 23 Jul 2021 21:58:59 +0200 Subject: [PATCH 77/79] Fix stupid code move --- src/GitVersion.MsBuild/Helpers/FileHelper.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/GitVersion.MsBuild/Helpers/FileHelper.cs b/src/GitVersion.MsBuild/Helpers/FileHelper.cs index 29ae3e6a9f..88ae45b1a7 100644 --- a/src/GitVersion.MsBuild/Helpers/FileHelper.cs +++ b/src/GitVersion.MsBuild/Helpers/FileHelper.cs @@ -15,12 +15,13 @@ public static class FileHelper { ".vb", VisualBasicFileContainsVersionAttribute } }; - public static string TempPath = MakeAndGetTempPath(); + public static readonly string TempPath = MakeAndGetTempPath(); private static string MakeAndGetTempPath() { - Directory.CreateDirectory(TempPath); - return Path.Combine(Path.GetTempPath(), "GitVersionTask"); + var tempPath = Path.Combine(Path.GetTempPath(), "GitVersionTask"); + Directory.CreateDirectory(tempPath); + return tempPath; } public static void DeleteTempFiles() From 39ba66bf2fe48caa141264cb88b346b7bf674368 Mon Sep 17 00:00:00 2001 From: Artur Date: Sat, 24 Jul 2021 17:42:00 +0200 Subject: [PATCH 78/79] (build) update cake dependencies --- GitReleaseManager.yaml => GitReleaseManager.yml | 0 build.cake | 14 +++++++------- 2 files changed, 7 insertions(+), 7 deletions(-) rename GitReleaseManager.yaml => GitReleaseManager.yml (100%) diff --git a/GitReleaseManager.yaml b/GitReleaseManager.yml similarity index 100% rename from GitReleaseManager.yaml rename to GitReleaseManager.yml diff --git a/build.cake b/build.cake index 70e7662fe1..fa5159ce86 100644 --- a/build.cake +++ b/build.cake @@ -2,30 +2,30 @@ #module nuget:?package=Cake.DotNetTool.Module&version=1.1.0 // Install addins. -#addin "nuget:?package=Cake.Codecov&version=1.0.0" +#addin "nuget:?package=Cake.Codecov&version=1.0.1" #addin "nuget:?package=Cake.Compression&version=0.2.6" #addin "nuget:?package=Cake.Coverlet&version=2.5.4" #addin "nuget:?package=Cake.Docker&version=1.0.0" #addin "nuget:?package=Cake.Git&version=1.0.1" -#addin "nuget:?package=Cake.Gitter&version=1.0.2" +#addin "nuget:?package=Cake.Gitter&version=1.1.0" #addin "nuget:?package=Cake.Incubator&version=6.0.0" #addin "nuget:?package=Cake.Json&version=6.0.1" #addin "nuget:?package=Cake.Kudu&version=1.0.1" -#addin "nuget:?package=Cake.Wyam&version=2.2.10" +#addin "nuget:?package=Cake.Wyam&version=2.2.12" #addin "nuget:?package=Newtonsoft.Json&version=12.0.3" -#addin "nuget:?package=SharpZipLib&version=1.3.1" +#addin "nuget:?package=SharpZipLib&version=1.3.2" #addin "nuget:?package=xunit.assert&version=2.4.1" // Install tools. #tool "nuget:?package=NUnit.ConsoleRunner&version=3.12.0" -#tool "nuget:?package=nuget.commandline&version=5.8.1" +#tool "nuget:?package=nuget.commandline&version=5.9.1" #tool "nuget:?package=KuduSync.NET&version=1.5.3" // Install .NET Core Global tools. #tool "dotnet:?package=Codecov.Tool&version=1.13.0" -#tool "dotnet:?package=dotnet-format&version=5.0.211103" -#tool "dotnet:?package=GitReleaseManager.Tool&version=0.11.0" +#tool "dotnet:?package=dotnet-format&version=5.1.225507" +#tool "dotnet:?package=GitReleaseManager.Tool&version=0.12.0" #tool "dotnet:?package=Wyam.Tool&version=2.2.9" // Load other scripts. From 1680a89918cb1b3b15cd37ccf78079e1fc3bfdff Mon Sep 17 00:00:00 2001 From: Artur Date: Sat, 24 Jul 2021 19:10:35 +0200 Subject: [PATCH 79/79] (build) update cake to 1.1.0 --- .config/dotnet-tools.json | 2 +- build.cake | 3 --- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json index 4745f6d727..eea98b1537 100644 --- a/.config/dotnet-tools.json +++ b/.config/dotnet-tools.json @@ -3,7 +3,7 @@ "isRoot": true, "tools": { "cake.tool": { - "version": "1.0.0", + "version": "1.1.0", "commands": [ "dotnet-cake" ] diff --git a/build.cake b/build.cake index fa5159ce86..0babc48dbe 100644 --- a/build.cake +++ b/build.cake @@ -1,6 +1,3 @@ -// Install modules -#module nuget:?package=Cake.DotNetTool.Module&version=1.1.0 - // Install addins. #addin "nuget:?package=Cake.Codecov&version=1.0.1" #addin "nuget:?package=Cake.Compression&version=0.2.6"