diff --git a/BREAKING_CHANGES.md b/BREAKING_CHANGES.md index 7fdd5d2c9f..e1c1153918 100644 --- a/BREAKING_CHANGES.md +++ b/BREAKING_CHANGES.md @@ -1,5 +1,19 @@ ## Unreleased +### GitVersion 7.1 removes the v6 parser and configuration runtime + +Only POSIX CLI arguments and nested `calculation` / `output` configuration are +supported. `GITVERSION_ARGUMENT_PARSER_VERSION=v6` and +`GITVERSION_CONFIGURATION_VERSION=v6` now fail with migration guidance. Unset +these variables or set them to `v7`, which remains an accepted no-op throughout +v7.x. The retired `GITVERSION_USE_V6_ARGUMENT_PARSER` variable must remain unset. + +`gitversion config migrate` still converts flat v6 configuration, including +outside a Git repository. Migrate the file before using it for calculation or +validation. Diagnostic logs remain on stderr; machine-readable stdout is unchanged. +The Git backend selector and LibGit2Sharp removal are tracked separately in #5040; +selector-variable removal belongs to v8 (#5136). + ### Docker images run as non-root Docker images now default to UID/GID `10001:10001`. On Linux, bind-mounted @@ -123,7 +137,7 @@ writes YAML to stdout by default, supports `--config`, `--output`, `--in-place`, and `--force`, and warns that comments cannot be preserved when replacing a file. -Flat v6 runtime support is scheduled for removal in v7.1. Explicit `v7` remains +Flat v6 runtime support is removed in v7.1. Explicit `v7` remains accepted throughout v7.x, and the configuration selector is removed in v8. `gitversion config migrate` remains available after runtime removal. diff --git a/docs/design/managed-git-migration.md b/docs/design/managed-git-migration.md index e78e219b5b..72de504be3 100644 --- a/docs/design/managed-git-migration.md +++ b/docs/design/managed-git-migration.md @@ -231,7 +231,7 @@ Delete `src/GitVersion.LibGit2Sharp` and `new-cli/GitVersion.Core.Libgit2Sharp`; **only** for dynamic-repo/CI-normalization scenarios — pure version calculation on a prepared checkout needs no git binary at all (a strict improvement for MSBuild-task users). -Parser and flat configuration runtime removal in v7.1 is tracked separately +Parser and flat configuration runtime removal in v7.1 is implemented separately by #5188. Keep `gitversion config migrate` and actionable retired selector value diagnostics throughout v7.x. #5136 removes all three selectors in v8; explicit `v7` and `managed` remain accepted until then. @@ -303,3 +303,11 @@ Commit-graph reader (generation numbers for topo sort and merge-base), benchmark [gitreader]: https://github.com/kekyo/GitReader [managedgitlib]: https://github.com/GlebChili/ManagedGitLib + +### v7.1 parser/configuration compatibility boundary + +The CLI registers only the POSIX parser and nested v7 configuration runtime. +Parser/configuration selectors retain their v7.x compatibility validators: explicit +`v7` is a no-op and `v6` fails with migration guidance. `config migrate` continues +to read flat v6 input independently of runtime loading. Git backend selection is +unchanged by #5188 and remains governed by #5040; v8 selector removal is #5136. diff --git a/docs/input/docs/migration/v6-to-v7.md b/docs/input/docs/migration/v6-to-v7.md index 65111bcd87..a7b42907f7 100644 --- a/docs/input/docs/migration/v6-to-v7.md +++ b/docs/input/docs/migration/v6-to-v7.md @@ -26,9 +26,10 @@ matching-version schema and loader checks. resolution, without waiting for calculation. With `Strict`, use a complete version such as `2.0.0`. Select `Loose` explicitly when using partial values such as `2.1`. -Explicit `GITVERSION_CONFIGURATION_VERSION=v6` retains its existing v7.0 warning -and v7.1 removal schedule. It selects the flat layout independently of the parser; -invalid v7 documents never trigger automatic v6 fallback. See +In v7.0, explicit `GITVERSION_CONFIGURATION_VERSION=v6` selected the flat layout +with a compatibility warning. Starting in v7.1 this selector value is rejected: +unset it or set it to `v7`, then run `gitversion config migrate` on the old file. +Invalid v7 documents never trigger automatic v6 fallback. See [configuration validation][configuration-validation] for output and error contracts. ## Docker images run as non-root @@ -177,7 +178,7 @@ GitVersion now uses POSIX-style command-line arguments powered by System.Command :::{.alert .alert-warning} **Breaking change:** Legacy Windows-style (`/switch`) and legacy single-dash long-form (`-switch`) arguments are no longer accepted by default. -As a temporary v7.0 migration aid, set `GITVERSION_ARGUMENT_PARSER_VERSION=v6` to restore legacy argument handling. The legacy parser is removed in v7.1. Unset the retired `GITVERSION_USE_V6_ARGUMENT_PARSER` variable: its presence is an error, even when set to `false`; it is not an alias for the new selector. +GitVersion v7.0 offered `GITVERSION_ARGUMENT_PARSER_VERSION=v6` as a temporary migration aid. In v7.1 that value is an error: use POSIX arguments and unset the selector or set it to `v7`. Unset the retired `GITVERSION_USE_V6_ARGUMENT_PARSER` variable: its presence is an error, even when set to `false`; it is not an alias for the new selector. ::: ### What you need to change @@ -262,7 +263,9 @@ with `--in-place`. In-place migration warns because comments cannot be preserved. The command does not need a Git repository and migrating its v7 output again is idempotent. In v7.0, you can temporarily validate a flat file with `GITVERSION_CONFIGURATION_VERSION=v6`; GitVersion warns once for that -fallback. +fallback. Starting in v7.1, both parser and configuration selectors reject `v6`; +unset them or set them to `v7` before running the retained migration command. +Flat-file runtime loading and serialization are no longer available. GitVersion 7 publishes a nested-only schema at `https://gitversion.net/schemas/7.0/GitVersion.configuration.json`. If you @@ -294,18 +297,18 @@ The environment variables relevant to migrating from v6 to v7: | Variable | Purpose | | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------- | -| `GITVERSION_CONFIGURATION_VERSION` | Selects the configuration layout: `v7` (default) or temporary flat `v6` fallback. | +| `GITVERSION_CONFIGURATION_VERSION` | In v7.1, accepts `v7` as a no-op; `v6` is rejected with configuration migration guidance. | | `GITVERSION_GIT_BACKEND` | Selects the Git backend: `managed` (default) or temporary `libgit2` fallback. See [Git backend][git-backend]. | -| `GITVERSION_ARGUMENT_PARSER_VERSION` | Selects the argument parser: `v7` (default, POSIX syntax) or temporary `v6` fallback (`/switch` and `-switch`). | +| `GITVERSION_ARGUMENT_PARSER_VERSION` | In v7.1, accepts `v7` as a no-op; `v6` is rejected with POSIX migration guidance. | | `GITVERSION_REMOTE_USERNAME` | Alternative to `--username` for dynamic-repository credentials. | | `GITVERSION_REMOTE_PASSWORD` | Alternative to `--password` for dynamic-repository credentials. | -The three selectors are independent: selecting the v6 parser does not select -flat configuration or libgit2. Values are trimmed and case-insensitive; +The selectors remain independent compatibility validators: `v7` parser and +configuration values do not change the selected Git backend. Values are trimmed and case-insensitive; unset, empty, and whitespace-only values use the defaults. Unknown values fail before execution and list the accepted values. Replace `GITVERSION_USE_V6_ARGUMENT_PARSER=true` with -`GITVERSION_ARGUMENT_PARSER_VERSION=v6` and unset the old variable. +`GITVERSION_ARGUMENT_PARSER_VERSION=v7` (or unset the selector) and use POSIX syntax. Effective selections are logged at information level. Use `--log-file ` to capture them or `--log-file console` to see them on stderr. Console logs @@ -314,9 +317,9 @@ with JSON or other machine-readable output. Build-server integration commands retain their normal output channel. For migration, place logging options before the command: `gitversion --log-file console config migrate --config GitVersion.yml`. -In v7.1, legacy parser and flat configuration runtime support are scheduled -for removal alongside libgit2. Retired `v6`/`libgit2` selections will report -actionable errors; explicit `v7`/`managed` selections remain accepted during +In v7.1, legacy parser and flat configuration runtime support are removed. +Retired `v6` selections report actionable errors; LibGit2Sharp removal is +tracked independently in #5040. Explicit `v7`/`managed` selections remain accepted during v7.x. All three selectors are removed in v8. `gitversion config migrate` remains available to convert flat files after runtime support is removed. diff --git a/docs/input/docs/reference/environment-variables.md b/docs/input/docs/reference/environment-variables.md index ece909a905..70e88d1b63 100644 --- a/docs/input/docs/reference/environment-variables.md +++ b/docs/input/docs/reference/environment-variables.md @@ -48,7 +48,7 @@ GitVersion reads the configuration file from the working/project directory as usual; an environment branch override does not check out another configuration file. Provider-specific detection is described in the [CI guides][ci-guides]. -The [v6 to v7 migration guide][v6-to-v7-migration-guide] documents the independent selectors `GITVERSION_ARGUMENT_PARSER_VERSION`, `GITVERSION_CONFIGURATION_VERSION`, and `GITVERSION_GIT_BACKEND`. Their v7.0 defaults are `v7`, `v7`, and `managed`; temporary fallbacks are `v6`, `v6`, and `libgit2`. Values are trimmed and case-insensitive; blank values use the defaults and unknown values fail with accepted-value guidance. The retired `GITVERSION_USE_V6_ARGUMENT_PARSER` variable must be unset. Legacy implementations are removed in v7.1 and selectors in v8. +The [v6 to v7 migration guide][v6-to-v7-migration-guide] documents the independent selectors `GITVERSION_ARGUMENT_PARSER_VERSION`, `GITVERSION_CONFIGURATION_VERSION`, and `GITVERSION_GIT_BACKEND`. Their v7.0 defaults are `v7`, `v7`, and `managed`. In v7.1, parser/configuration `v6` values are rejected with removal guidance; unset those variables or use `v7` as a compatibility no-op. Flat v6 files can still be converted with `gitversion config migrate`. Git backend removal is tracked separately in #5040. Values are trimmed and case-insensitive; blank values use the defaults and unknown values fail with accepted-value guidance. The retired `GITVERSION_USE_V6_ARGUMENT_PARSER` variable must be unset. Parser/configuration runtime fallbacks were removed in v7.1; selector variables remain until v8. ## Output variables diff --git a/docs/input/docs/usage/cli/arguments.md b/docs/input/docs/usage/cli/arguments.md index 8de9b6a560..80edc405be 100644 --- a/docs/input/docs/usage/cli/arguments.md +++ b/docs/input/docs/usage/cli/arguments.md @@ -8,7 +8,8 @@ Description: The supported arguments of the GitVersion Command Line Interface **Note:** GitVersion uses POSIX-style `--long-name` arguments from version 7 and up. Long-form arguments are recommended for readability in scripts and documentation. Short aliases (e.g. `-l`, `-o`, `-b`) are also supported. The legacy `/switch` and `-switch` -syntax is available during v7.0 when `GITVERSION_ARGUMENT_PARSER_VERSION=v6` is set. +syntax was available only as a temporary v7.0 fallback. Starting in v7.1, +`GITVERSION_ARGUMENT_PARSER_VERSION=v6` fails with POSIX migration guidance. The default is `v7`. Unset the retired `GITVERSION_USE_V6_ARGUMENT_PARSER` variable; it now produces a replacement diagnostic. The legacy parser is removed in v7.1 and the selector in v8. @@ -192,15 +193,14 @@ Codes are stable within schema version 1; human messages may change: | `GVCONFIG_REGEX` | Invalid regular expression | | `GVCONFIG_BRANCH` | Missing branch regex or unresolved branch reference | | `GVCONFIG_VALUE` | Invalid semantic value or invocation path | -| `GVCONFIG_V6_COMPATIBILITY` | Non-failing temporary v6 compatibility warning | Parser failures before command execution (unknown options, missing option arguments, extra positional arguments) retain ordinary stderr/exit 1 behavior without JSON. Feature-selector errors also occur before command execution. -Configuration layout selection remains separate from parser selection. Explicit -`GITVERSION_CONFIGURATION_VERSION=v6` accepts flat files during v7.0 and emits the -existing warning; legacy loading is removed in v7.1. Invalid v7 documents never +Configuration layout selection remains separate from parser selection. Starting in v7.1, +`GITVERSION_CONFIGURATION_VERSION=v6` is rejected before command execution. +Unset the variable or set it to `v7`; flat files must be migrated before validation. Invalid v7 documents never fall back to v6. Use `config migrate` to convert a legacy file. This command is unavailable with the legacy parser and published v6 tools. @@ -266,12 +266,10 @@ Supported options are `--config`/`-c`, repeated `--override-config key=value`, must precede `config get`. Version-output, calculation and file-update options cannot be combined with this command. Use `gitversion config get --help` for help. -The command requires the default modern argument parser and default or explicit -`GITVERSION_CONFIGURATION_VERSION=v7`. Selecting v6 configuration produces a -v7-required error before configuration loading, even when the modern parser is -selected; GitVersion does not switch versions implicitly. Existing v6 full -configuration display retains its behavior. With v7 configuration, -`--show-config` now includes runtime overrides, matching the query result. +The command uses the v7 parser and configuration runtime. In v7.1, selecting +`GITVERSION_CONFIGURATION_VERSION=v6` fails with migration guidance before +configuration loading. `--show-config` includes runtime overrides, matching +the query result. ## CLI schema @@ -293,9 +291,9 @@ It discovers a supported configuration filename when `--config` is omitted and writes YAML to stdout unless `--output` or `--in-place` is selected. `--output` will not replace an existing file without `--force`; it cannot be combined with `--in-place`. Replacing a file warns that comments are not preserved. The -command does not require a Git repository and is unavailable when -`GITVERSION_ARGUMENT_PARSER_VERSION=v6` selects the legacy parser. Migration -remains available after v6 runtime support is removed in v7.1. +command does not require a Git repository. Starting in v7.1, unset the parser +and configuration selectors or set them to `v7` before migration; `v6` selector +values are retired, while flat v6 input remains supported by this command. ## Override config @@ -305,12 +303,8 @@ With the v7 default configuration layout, use a version-aware nested key. For example, `calculation.tag-prefix=custom`, `calculation.branches.main.increment=Patch`, and `output.branches.main.pre-release-weight=55000`. Flat v6 keys are rejected in -v7 mode with their nested replacement. Set -`GITVERSION_CONFIGURATION_VERSION=v6` only while validating a legacy file in -v7.0. - -When that temporary v6 fallback is selected, use the legacy branch override -path, for example `--override-config branches.main.increment=Patch`. +v7 mode with their nested replacement. Starting in v7.1, no flat runtime +override path is supported; migrate old files with `gitversion config migrate`. To specify multiple options add multiple `--override-config key=value` entries: `--override-config key1=value1 --override-config key2=value2`. @@ -319,9 +313,8 @@ To have **space characters** as a part of `value`, `value` has to be enclosed wi Double quote character inside of the double quoted `value` has to be escaped with a backslash '\\' - `key="My \"escaped-quotes\""`. -The following override paths are supported in v7. For the temporary v6 -fallback, omit the `calculation.` or `output.` prefix. The shared `workflow` -key stays at the root in both versions: +The following override paths are supported in v7. The shared `workflow` +key stays at the root: 1. `output.assembly-file-versioning-format` 2. `output.assembly-file-versioning-scheme` diff --git a/src/GitVersion.App.Tests/ArgumentParserTests.cs b/src/GitVersion.App.Tests/ArgumentParserTests.cs index 4a4070a464..ca8d2c4375 100644 --- a/src/GitVersion.App.Tests/ArgumentParserTests.cs +++ b/src/GitVersion.App.Tests/ArgumentParserTests.cs @@ -21,7 +21,7 @@ public class ArgumentParserTests : TestBase public void SetUp() { this.originalConfigurationVersion = System.Environment.GetEnvironmentVariable(ConfigurationVersionSelector.EnvironmentVariableName); - System.Environment.SetEnvironmentVariable(ConfigurationVersionSelector.EnvironmentVariableName, "v6"); + System.Environment.SetEnvironmentVariable(ConfigurationVersionSelector.EnvironmentVariableName, "v7"); var sp = ConfigureServices(services => services.AddModule(new GitVersionAppModule())); this.environment = sp.GetRequiredService(); this.argumentParser = sp.GetRequiredService(); @@ -56,7 +56,7 @@ public void OverrideConfigSupportsNestedV7RootAndBranchPaths() "--override-config output.branches.main.pre-release-weight=42"); var normalized = ConfigurationDocumentMapper.Normalize( - arguments.OverrideConfiguration!, ConfigurationVersion.V7, "test override"); + arguments.OverrideConfiguration!, "test override"); ConfigurationHelper configurationHelper = new(normalized); var configuration = configurationHelper.Configuration; configuration.Workflow.ShouldBe("GitHubFlow/v1"); @@ -124,13 +124,13 @@ public void ConfigGetRequiresExactlyOneProperty(string command) [Test] public void ConfigGetRejectsV6BeforeConfigFileValidation() { + SysEnv.SetEnvironmentVariable(ConfigurationVersionSelector.EnvironmentVariableName, "v6"); var exception = Should.Throw(() => this.argumentParser.ParseArguments("config get calculation.tag-prefix --config missing.yml")); - exception.Message.ShouldContain("require v7 configuration"); + exception.Message.ShouldContain("removed in GitVersion 7.1"); } - [TestCase("v6")] [TestCase("v7")] public void OverrideConfigAcceptsWorkflowOnlyInEitherVersion(string version) { @@ -164,7 +164,7 @@ public void OverrideConfigPreservesV7BranchNameCasing() "--override-config Calculation.Branches.ReleaseCandidate.Increment=Major"); var normalized = ConfigurationDocumentMapper.Normalize( - arguments.OverrideConfiguration!, ConfigurationVersion.V7, "test override"); + arguments.OverrideConfiguration!, "test override"); ConfigurationHelper configurationHelper = new(normalized); configurationHelper.Configuration.Branches["ReleaseCandidate"].Increment.ShouldBe(IncrementStrategy.Major); } @@ -205,35 +205,6 @@ public void OverrideConfigRejectsPropertyInWrongV7SectionWithReplacement() exception.Message.ShouldContain("output.update-build-number"); } - [Test] - public void OverrideConfigSupportsV6BranchPath() - { - var arguments = this.argumentParser.ParseArguments("--override-config branches.main.increment=Major"); - - ConfigurationHelper configurationHelper = new(arguments.OverrideConfiguration); - configurationHelper.Configuration.Branches["main"].Increment.ShouldBe(IncrementStrategy.Major); - } - - [Test] - public void OverrideConfigPreservesV6BranchNameCasing() - { - var arguments = this.argumentParser.ParseArguments( - "--override-config Branches.ReleaseCandidate.Increment=Major"); - - ConfigurationHelper configurationHelper = new(arguments.OverrideConfiguration); - configurationHelper.Configuration.Branches["ReleaseCandidate"].Increment.ShouldBe(IncrementStrategy.Major); - } - - [Test] - public void OverrideConfigRejectsV7PathInV6WithReplacement() - { - var exception = Should.Throw(() => - this.argumentParser.ParseArguments("--override-config output.update-build-number=false")); - - exception.Message.ShouldContain("update-build-number"); - exception.Message.ShouldContain("config migrate"); - } - [Test] public void OverrideConfigBatchValidationDoesNotApplyAnyValues() { @@ -674,154 +645,154 @@ public void OverrideConfigWithSingleOptions(string options, IGitVersionConfigura { var arguments = this.argumentParser.ParseArguments($"--override-config {options}"); - ConfigurationHelper configurationHelper = new(arguments.OverrideConfiguration); + ConfigurationHelper configurationHelper = new(ConfigurationDocumentMapper.Normalize(arguments.OverrideConfiguration!, "test override")); configurationHelper.Configuration.ShouldBeEquivalentTo(expected); } private static IEnumerable> OverrideConfigWithSingleOptionTestData() { yield return TestCaseData.Create( - "assembly-versioning-scheme=MajorMinor", + "output.assembly-versioning-scheme=MajorMinor", new GitVersionConfiguration { AssemblyVersioningScheme = AssemblyVersioningScheme.MajorMinor } ); yield return TestCaseData.Create( - "assembly-file-versioning-scheme=\"MajorMinorPatch\"", + "output.assembly-file-versioning-scheme=\"MajorMinorPatch\"", new GitVersionConfiguration { AssemblyFileVersioningScheme = AssemblyFileVersioningScheme.MajorMinorPatch } ); yield return TestCaseData.Create( - "assembly-informational-format=\"{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}\"", + "output.assembly-informational-format=\"{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}\"", new GitVersionConfiguration { AssemblyInformationalFormat = "{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}" } ); yield return TestCaseData.Create( - "assembly-versioning-format=\"{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}\"", + "output.assembly-versioning-format=\"{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}\"", new GitVersionConfiguration { AssemblyVersioningFormat = "{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}" } ); yield return TestCaseData.Create( - "assembly-file-versioning-format=\"{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}\"", + "output.assembly-file-versioning-format=\"{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}\"", new GitVersionConfiguration { AssemblyFileVersioningFormat = "{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}" } ); yield return TestCaseData.Create( - "custom-version-format=\"{Major}.{Minor}.{Patch}{PreReleaseLabelName:l}{PreReleaseNumber}\"", + "output.custom-version-format=\"{Major}.{Minor}.{Patch}{PreReleaseLabelName:l}{PreReleaseNumber}\"", new GitVersionConfiguration { CustomVersionFormat = "{Major}.{Minor}.{Patch}{PreReleaseLabelName:l}{PreReleaseNumber}" } ); yield return TestCaseData.Create( - "mode=ContinuousDelivery", + "calculation.mode=ContinuousDelivery", new GitVersionConfiguration { DeploymentMode = DeploymentMode.ContinuousDelivery } ); yield return TestCaseData.Create( - "tag-prefix=sample", + "calculation.tag-prefix=sample", new GitVersionConfiguration { TagPrefixPattern = "sample" } ); yield return TestCaseData.Create( - "label=cd-label", + "calculation.label=cd-label", new GitVersionConfiguration { Label = "cd-label" } ); yield return TestCaseData.Create( - "next-version=1", + "calculation.next-version=1", new GitVersionConfiguration { NextVersion = "1" } ); yield return TestCaseData.Create( - "major-version-bump-message=\"This is major version bump message.\"", + "calculation.major-version-bump-message=\"This is major version bump message.\"", new GitVersionConfiguration { MajorVersionBumpMessage = "This is major version bump message." } ); yield return TestCaseData.Create( - "minor-version-bump-message=\"This is minor version bump message.\"", + "calculation.minor-version-bump-message=\"This is minor version bump message.\"", new GitVersionConfiguration { MinorVersionBumpMessage = "This is minor version bump message." } ); yield return TestCaseData.Create( - "patch-version-bump-message=\"This is patch version bump message.\"", + "calculation.patch-version-bump-message=\"This is patch version bump message.\"", new GitVersionConfiguration { PatchVersionBumpMessage = "This is patch version bump message." } ); yield return TestCaseData.Create( - "no-bump-message=\"This is no bump message.\"", + "calculation.no-bump-message=\"This is no bump message.\"", new GitVersionConfiguration { NoBumpMessage = "This is no bump message." } ); yield return TestCaseData.Create( - "version-bump-reset-message=\"baseline:\"", + "calculation.version-bump-reset-message=\"baseline:\"", new GitVersionConfiguration { VersionBumpResetMessage = "baseline:" } ); yield return TestCaseData.Create( - "tag-pre-release-weight=2", + "output.tag-pre-release-weight=2", new GitVersionConfiguration { TagPreReleaseWeight = 2 } ); yield return TestCaseData.Create( - "commit-message-incrementing=MergeMessageOnly", + "calculation.commit-message-incrementing=MergeMessageOnly", new GitVersionConfiguration { CommitMessageIncrementing = CommitMessageIncrementMode.MergeMessageOnly } ); yield return TestCaseData.Create( - "increment=Minor", + "calculation.increment=Minor", new GitVersionConfiguration { Increment = IncrementStrategy.Minor } ); yield return TestCaseData.Create( - "commit-date-format=\"MM/dd/yyyy h:mm tt\"", + "output.commit-date-format=\"MM/dd/yyyy h:mm tt\"", new GitVersionConfiguration { CommitDateFormat = "MM/dd/yyyy h:mm tt" } ); yield return TestCaseData.Create( - "update-build-number=true", + "output.update-build-number=true", new GitVersionConfiguration { UpdateBuildNumber = true } ); yield return TestCaseData.Create( - "strategies=[\"None\",\"Mainline\"]", + "calculation.strategies=[\"None\",\"Mainline\"]", new GitVersionConfiguration { VersionStrategies = [VersionStrategies.None, VersionStrategies.Mainline] @@ -833,14 +804,14 @@ private static IEnumerable> Overri public void OverrideConfigWithMultipleOptions(string options, IGitVersionConfiguration expected) { var arguments = this.argumentParser.ParseArguments(options); - ConfigurationHelper configurationHelper = new(arguments.OverrideConfiguration); + ConfigurationHelper configurationHelper = new(ConfigurationDocumentMapper.Normalize(arguments.OverrideConfiguration!, "test override")); configurationHelper.Configuration.ShouldBeEquivalentTo(expected); } private static IEnumerable> OverrideConfigWithMultipleOptionsTestData() { yield return TestCaseData.Create( - "--override-config tag-prefix=sample --override-config assembly-versioning-scheme=MajorMinor", + "--override-config calculation.tag-prefix=sample --override-config output.assembly-versioning-scheme=MajorMinor", new GitVersionConfiguration { TagPrefixPattern = "sample", @@ -848,7 +819,7 @@ private static IEnumerable> Overri } ); yield return TestCaseData.Create( - "--override-config tag-prefix=sample --override-config assembly-versioning-format=\"{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}\"", + "--override-config calculation.tag-prefix=sample --override-config output.assembly-versioning-format=\"{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}\"", new GitVersionConfiguration { TagPrefixPattern = "sample", @@ -856,7 +827,7 @@ private static IEnumerable> Overri } ); yield return TestCaseData.Create( - "--override-config tag-prefix=sample --override-config assembly-versioning-format=\"{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}\" --override-config update-build-number=true --override-config assembly-versioning-scheme=MajorMinorPatchTag --override-config mode=ContinuousDelivery --override-config tag-pre-release-weight=4", + "--override-config calculation.tag-prefix=sample --override-config output.assembly-versioning-format=\"{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}\" --override-config output.update-build-number=true --override-config output.assembly-versioning-scheme=MajorMinorPatchTag --override-config calculation.mode=ContinuousDelivery --override-config output.tag-pre-release-weight=4", new GitVersionConfiguration { TagPrefixPattern = "sample", diff --git a/src/GitVersion.App.Tests/CliSchemaTests.cs b/src/GitVersion.App.Tests/CliSchemaTests.cs index ad34082ea8..14539e5d3f 100644 --- a/src/GitVersion.App.Tests/CliSchemaTests.cs +++ b/src/GitVersion.App.Tests/CliSchemaTests.cs @@ -119,11 +119,11 @@ public async Task HostSkipsExecutorsAndFeatureLogging() CliSchemaExporterTests.ValidateSchema(result.Output!); } - [TestCase("v6", "libgit2")] [TestCase("v7", "libgit2")] - [TestCase("v6", "managed")] + [TestCase(null, "libgit2")] [TestCase("v7", "managed")] - public void ProcessExportsSameDocumentWithoutRepositoryOrFiles(string configuration, string backend) + [TestCase(null, "managed")] + public void ProcessExportsSameDocumentWithoutRepositoryOrFiles(string? configuration, string backend) { var directory = Directory.CreateTempSubdirectory("gitversion-schema-"); try @@ -186,7 +186,7 @@ public void ProcessRejectsInvalidSyntaxAndLegacyParser(string arguments, string result.ExitCode.ShouldNotBe(0); result.StandardOutput.ShouldBeEmpty(); - result.StandardError!.ShouldContain("Could not parse command line parameter"); + result.StandardError!.ShouldContain(parser == "v6" ? "removed in GitVersion 7.1" : "Could not parse command line parameter"); } finally { @@ -257,10 +257,10 @@ public void ProcessIgnoresBuildServerOutputAndPreservesExistingConfiguration() } } - private static ExecutionResults RunProcess(string directory, string arguments, string parser, string configuration, string backend) + private static ExecutionResults RunProcess(string directory, string arguments, string parser, string? configuration, string backend) => RunProcess(directory, arguments, parser, configuration, backend, []); - private static ExecutionResults RunProcess(string directory, string arguments, string parser, string configuration, string backend, + private static ExecutionResults RunProcess(string directory, string arguments, string parser, string? configuration, string backend, KeyValuePair[] additionalEnvironment) { var stdout = new StringBuilder(); diff --git a/src/GitVersion.App.Tests/ConfigurationQueryIntegrationTests.cs b/src/GitVersion.App.Tests/ConfigurationQueryIntegrationTests.cs index bcb7df3a81..ccf9c25f49 100644 --- a/src/GitVersion.App.Tests/ConfigurationQueryIntegrationTests.cs +++ b/src/GitVersion.App.Tests/ConfigurationQueryIntegrationTests.cs @@ -79,7 +79,7 @@ public void QueryPreservesNullBooleanAndStringValues(string path, string expecte result.StandardOutput.ShouldBe(expected + SysEnv.NewLine); } - [TestCase("v6", "require v7 configuration")] + [TestCase("v6", "removed in GitVersion 7.1")] [TestCase("invalid", "Unrecognized GITVERSION_CONFIGURATION_VERSION")] public void QueryRejectsUnsupportedConfigurationBeforeReadingFile(string version, string diagnostic) { @@ -223,7 +223,6 @@ public void QueryIsUnavailableWithLegacyArgumentParser() result.StandardOutput.ShouldBeEmpty(); } - [TestCase("v6", "tag-prefix", "[vV]?")] [TestCase("v7", "calculation.tag-prefix", "overridden-")] public void ShowConfigOverrideCorrectionIsLimitedToV7(string version, string path, string expected) { diff --git a/src/GitVersion.App.Tests/ConfigurationValidationIntegrationTests.cs b/src/GitVersion.App.Tests/ConfigurationValidationIntegrationTests.cs index 5dd85fbda6..b7b769b4a3 100644 --- a/src/GitVersion.App.Tests/ConfigurationValidationIntegrationTests.cs +++ b/src/GitVersion.App.Tests/ConfigurationValidationIntegrationTests.cs @@ -106,18 +106,16 @@ public void OverridesUseRuntimeRulesAndSafeDiagnostics(string overrides, bool va } [Test] - public void ExplicitV6CompatibilityWarnsWithoutFailing() + public void RetiredV6SelectionFailsWithMigrationGuidance() { Write("tag-prefix: '[vV]?'"); var result = Execute("config validate --config candidate.yml --format json", version: "v6"); - result.ExitCode.ShouldBe(0, result.Output); - using var json = JsonDocument.Parse(result.StandardOutput!); - json.RootElement.GetProperty("configurationVersion").GetString().ShouldBe("v6"); - json.RootElement.GetProperty("valid").GetBoolean().ShouldBeTrue(); - json.RootElement.GetProperty("diagnostics")[0].GetProperty("code").GetString().ShouldBe("GVCONFIG_V6_COMPATIBILITY"); + result.ExitCode.ShouldBe(1); + result.StandardOutput.ShouldBeEmpty(); result.StandardError.ShouldNotBeNull(); result.StandardError.ShouldContain("removed in GitVersion 7.1"); + result.StandardError.ShouldContain("gitversion config migrate"); } [TestCase("config validate --config missing.yml --format json")] @@ -310,11 +308,11 @@ public void NestedV7DocumentDoesNotFallBackWhenV6IsSelected() Write("calculation:\n tag-prefix: v"); var result = Execute("config validate --config candidate.yml --format json", version: "v6"); - result.ExitCode.ShouldBe(1, result.Output); - using var json = JsonDocument.Parse(result.StandardOutput!); - json.RootElement.GetProperty("configurationVersion").GetString().ShouldBe("v6"); - json.RootElement.GetProperty("valid").GetBoolean().ShouldBeFalse(); - json.RootElement.GetProperty("diagnostics")[0].GetProperty("code").GetString().ShouldBe("GVCONFIG_LAYOUT"); + result.ExitCode.ShouldBe(1); + result.StandardOutput.ShouldBeEmpty(); + result.StandardError.ShouldNotBeNull(); + result.StandardError.ShouldContain("removed in GitVersion 7.1"); + result.StandardError.ShouldContain("gitversion config migrate"); } [Test] diff --git a/src/GitVersion.App.Tests/ConfigurationVersionIntegrationTests.cs b/src/GitVersion.App.Tests/ConfigurationVersionIntegrationTests.cs index d3236c5668..801b7ab2fe 100644 --- a/src/GitVersion.App.Tests/ConfigurationVersionIntegrationTests.cs +++ b/src/GitVersion.App.Tests/ConfigurationVersionIntegrationTests.cs @@ -9,7 +9,7 @@ public class ConfigurationVersionIntegrationTests { [TestCase("ShortSha")] [TestCase("Sha")] - public async Task V6V7AndMigratedConfigurationCalculateCurrentCommitLabel(string placeholder) + public async Task MigratedAndNativeV7ConfigurationCalculateCurrentCommitLabel(string placeholder) { using var fixture = new EmptyRepositoryFixture(); fixture.MakeACommit(); @@ -20,7 +20,6 @@ public async Task V6V7AndMigratedConfigurationCalculateCurrentCommitLabel(string var configurationPath = Path.Combine(fixture.RepositoryPath, ConfigurationFileLocator.DefaultFileName); await File.WriteAllTextAsync(configurationPath, $"next-version: 2.0.0\nbranches:\n feature:\n label: '{label}'"); - var v6 = Execute(fixture.RepositoryPath, "v6"); var migration = await new ProgramFixture(fixture.RepositoryPath).Run("config", "migrate"); migration.ExitCode.ShouldBe(0); @@ -33,14 +32,14 @@ public async Task V6V7AndMigratedConfigurationCalculateCurrentCommitLabel(string await File.WriteAllTextAsync(configurationPath, $"calculation:\n next-version: 2.0.0\n branches:\n feature:\n label: '{label}'\noutput: {{}}"); var v7 = Execute(fixture.RepositoryPath, "v7"); - foreach (var result in new[] { v6, v7, migrated }) + foreach (var result in new[] { v7, migrated }) { result.ExitCode.ShouldBe(0); using var json = JsonDocument.Parse(result.StandardOutput!); json.RootElement.GetProperty("PreReleaseLabelName").GetString().ShouldBe("ci." + (placeholder == "Sha" ? sha : sha[..7])); json.RootElement.GetProperty("Sha").GetString().ShouldBe(sha); json.RootElement.GetProperty("ShortSha").GetString().ShouldBe(sha[..7]); - GetFullSemVer(result.StandardOutput!).ShouldBe(GetFullSemVer(v6.StandardOutput!)); + GetFullSemVer(result.StandardOutput!).ShouldBe(GetFullSemVer(v7.StandardOutput!)); } } @@ -244,58 +243,7 @@ public async Task ConfigMigrateDoesNotEmitLegacyFallbackWarning() } } - [Test] - public void V6AndV7ConfigurationCalculateTheSameVersion() - { - using var fixture = new EmptyRepositoryFixture(); - fixture.MakeACommit(); - var configurationPath = FileSystemHelper.Path.Combine(fixture.RepositoryPath, ConfigurationFileLocator.DefaultFileName); - - FileSystemHelper.File.WriteAllText(configurationPath, "next-version: 2.0.0"); - var v6Result = Execute(fixture.RepositoryPath, "v6"); - - FileSystemHelper.File.WriteAllText(configurationPath, """ - calculation: - next-version: 2.0.0 - output: {} - """); - var v7Result = Execute(fixture.RepositoryPath, "v7"); - - v6Result.ExitCode.ShouldBe(0); - v7Result.ExitCode.ShouldBe(0); - GetFullSemVer(v7Result.StandardOutput!).ShouldBe(GetFullSemVer(v6Result.StandardOutput!)); - } - - [TestCase(false)] - [TestCase(true)] - public void ExplicitV6WarningUsesStandardErrorOnceWithoutContaminatingJson(bool logToFile) - { - using var fixture = new EmptyRepositoryFixture(); - fixture.MakeACommit(); - var configurationPath = Path.Combine(fixture.RepositoryPath, ConfigurationFileLocator.DefaultFileName); - File.WriteAllText(configurationPath, "next-version: 2.0.0"); - - var result = GitVersionHelper.ExecuteIn(fixture.RepositoryPath, " --no-cache", logToFile, - new KeyValuePair(ConfigurationVersionSelector.EnvironmentVariableName, "v6")); - - result.ExitCode.ShouldBe(0); - GetFullSemVer(result.StandardOutput!).ShouldBe("2.0.0-1"); - result.StandardError.ShouldNotBeNull(); - result.StandardError.Split("temporary v6 compatibility mode").Length.ShouldBe(2); - result.StandardError.ShouldContain(configurationPath); - result.StandardError.ShouldContain("GitVersion 7.1"); - result.StandardError.ShouldContain("gitversion config migrate"); - result.StandardError.ShouldContain("GITVERSION_CONFIGURATION_VERSION=v7"); - if (logToFile) - { - result.Log.ShouldNotBeNull(); - result.Log.ShouldContain("temporary v6 compatibility mode"); - } - } - - [TestCase("v6", "")] [TestCase("v7", "")] - [TestCase("v6", "workflow: GitHubFlow/v1")] [TestCase("v7", "workflow: GitHubFlow/v1")] public void CalculatesVersionWithSharedRootConfiguration(string version, string configuration) { @@ -349,20 +297,6 @@ public void RootWorkflowAppliesDefaultsToBothSectionsAndPreservesOverrides(bool effective.Branches["main"].PreReleaseWeight.ShouldBe(hasOverrides ? 42 : 55000); } - [Test] - public void ExplicitV6WithoutUserConfigurationDoesNotWarnOnStandardError() - { - using var fixture = new EmptyRepositoryFixture(); - fixture.MakeACommit(); - - var result = Execute(fixture.RepositoryPath, "v6"); - - result.ExitCode.ShouldBe(0); - result.StandardError.ShouldBeEmpty(); - GetFullSemVer(result.StandardOutput!).ShouldNotBeNullOrEmpty(); - } - - [TestCase("v6", false)] [TestCase("v7", true)] public void ShowConfigUsesSelectedConfigurationStructure(string version, bool nested) { @@ -408,7 +342,7 @@ public void InvalidConfigurationVersionDisplaysDiagnosticOnStandardError() result.Output.ShouldNotBeNull(); result.Output.ShouldContain("An error occurred:"); result.Output.ShouldContain("Unrecognized GITVERSION_CONFIGURATION_VERSION value 'invalid'"); - result.Output.ShouldContain("Valid values are 'v6' and 'v7'"); + result.Output.ShouldContain("Valid value is 'v7'"); } private static ExecutionResults Execute(string repositoryPath, string version) => diff --git a/src/GitVersion.App.Tests/ExecCmdLineArgumentTest.cs b/src/GitVersion.App.Tests/ExecCmdLineArgumentTest.cs index e291cd3b58..7c626980bd 100644 --- a/src/GitVersion.App.Tests/ExecCmdLineArgumentTest.cs +++ b/src/GitVersion.App.Tests/ExecCmdLineArgumentTest.cs @@ -36,9 +36,8 @@ public void LogPathContainsForwardSlash() """); } - [TestCase(false)] - [TestCase(true)] - public void CommitArgumentUsesRequestedCommitWhenCacheExists(bool useLegacyParser) + [Test] + public void CommitArgumentUsesRequestedCommitWhenCacheExists() { using var fixture = new EmptyRepositoryFixture(); fixture.MakeATaggedCommit("1.0.0"); @@ -46,11 +45,11 @@ public void CommitArgumentUsesRequestedCommitWhenCacheExists(bool useLegacyParse var headCommit = fixture.MakeACommit(); var environment = new KeyValuePair( - "GITVERSION_ARGUMENT_PARSER_VERSION", useLegacyParser ? "v6" : null); - var showVariableArgument = useLegacyParser ? "-showvariable" : "--show-variable"; - var commitArgument = useLegacyParser ? "-c" : "--commit"; - var workingDirectory = useLegacyParser ? null : fixture.RepositoryPath; - var targetPathArgument = useLegacyParser ? $" \"{fixture.RepositoryPath}\"" : string.Empty; + "GITVERSION_ARGUMENT_PARSER_VERSION", "v7"); + var showVariableArgument = "--show-variable"; + var commitArgument = "--commit"; + var workingDirectory = fixture.RepositoryPath; + var targetPathArgument = string.Empty; var headResult = GitVersionHelper.ExecuteIn(workingDirectory, $"{targetPathArgument} {showVariableArgument} Sha", false, environment); @@ -63,25 +62,20 @@ public void CommitArgumentUsesRequestedCommitWhenCacheExists(bool useLegacyParse requestedCommitResult.Output!.Trim().ShouldBe(requestedCommit); } - [TestCase(false, "", true)] - [TestCase(false, "--verbosity NORMAL", true)] - [TestCase(false, "--verbosity quiet", false)] - [TestCase(true, "", true)] - [TestCase(true, "/verbosity NORMAL", true)] - [TestCase(true, "/verbosity quiet", false)] - public void CheckBuildServerVerbosityConsole(bool useLegacyParser, string verbosityArgument, bool expectInformation) + [TestCase("", true)] + [TestCase("--verbosity NORMAL", true)] + [TestCase("--verbosity quiet", false)] + public void CheckBuildServerVerbosityConsole(string verbosityArgument, bool expectInformation) { using var fixture = new EmptyRepositoryFixture(); fixture.MakeATaggedCommit("1.2.3"); fixture.MakeACommit(); var environment = new KeyValuePair( - "GITVERSION_ARGUMENT_PARSER_VERSION", useLegacyParser ? "v6" : null); - var workingDirectory = useLegacyParser ? null : fixture.RepositoryPath; - var targetPathArgument = useLegacyParser ? $" \"{fixture.RepositoryPath}\"" : string.Empty; - var outputArguments = useLegacyParser - ? "-output buildserver -l console" - : "--output buildserver --log-file console"; + "GITVERSION_ARGUMENT_PARSER_VERSION", "v7"); + var workingDirectory = fixture.RepositoryPath; + var targetPathArgument = string.Empty; + var outputArguments = "--output buildserver --log-file console"; var result = GitVersionHelper.ExecuteIn(workingDirectory, $"{targetPathArgument} {verbosityArgument} {outputArguments}", false, environment); @@ -98,22 +92,19 @@ public void CheckBuildServerVerbosityConsole(bool useLegacyParser, string verbos } } - [TestCase(false)] - [TestCase(true)] - public void VerboseVerbosityIncludesDebugOutput(bool useLegacyParser) + [Test] + public void VerboseVerbosityIncludesDebugOutput() { using var fixture = new EmptyRepositoryFixture(); fixture.MakeATaggedCommit("1.2.3"); fixture.MakeACommit(); var environment = new KeyValuePair( - "GITVERSION_ARGUMENT_PARSER_VERSION", useLegacyParser ? "v6" : null); - var workingDirectory = useLegacyParser ? null : fixture.RepositoryPath; - var targetPathArgument = useLegacyParser ? $" \"{fixture.RepositoryPath}\"" : string.Empty; - var verbosityArgument = useLegacyParser ? "/verbosity Verbose" : "--verbosity verbose"; - var outputArguments = useLegacyParser - ? "-nocache -output buildserver -l console" - : "--no-cache --output buildserver --log-file console"; + "GITVERSION_ARGUMENT_PARSER_VERSION", "v7"); + var workingDirectory = fixture.RepositoryPath; + var targetPathArgument = string.Empty; + var verbosityArgument = "--verbosity verbose"; + var outputArguments = "--no-cache --output buildserver --log-file console"; var result = GitVersionHelper.ExecuteIn(workingDirectory, $"{targetPathArgument} {verbosityArgument} {outputArguments}", false, environment); diff --git a/src/GitVersion.App.Tests/ExecFeatureSelectorTests.cs b/src/GitVersion.App.Tests/ExecFeatureSelectorTests.cs index 23a030d8fe..01e4718d9e 100644 --- a/src/GitVersion.App.Tests/ExecFeatureSelectorTests.cs +++ b/src/GitVersion.App.Tests/ExecFeatureSelectorTests.cs @@ -7,8 +7,8 @@ public class ExecFeatureSelectorTests [Test] [Combinatorial] public void SelectorCombinationsCalculateAndLogWithoutPollutingOutput( - [Values("v6", "v7")] string parser, - [Values("v6", "v7")] string configuration, + [Values("v7")] string parser, + [Values("v7")] string configuration, [Values("libgit2", "managed")] string backend, [Values("json", "variable", "config")] string output, [Values(false, true)] bool buildServer) @@ -16,11 +16,10 @@ public void SelectorCombinationsCalculateAndLogWithoutPollutingOutput( using var fixture = new EmptyRepositoryFixture(); fixture.MakeATaggedCommit("release-1.2.3"); File.WriteAllText(Path.Combine(fixture.RepositoryPath, "GitVersion.yml"), - configuration == "v6" ? "tag-prefix: release-" : "calculation:\n tag-prefix: release-"); - var legacy = parser == "v6"; + "calculation:\n tag-prefix: release-"); var logPath = Path.Combine(fixture.RepositoryPath, "selectors.log"); - var outputArgument = OutputArguments(output, legacy, buildServer); - var arguments = $"\"{fixture.RepositoryPath}\" {(legacy ? "/l" : "--log-file")} \"{logPath}\" {outputArgument}"; + var outputArgument = OutputArguments(output, buildServer); + var arguments = $"\"{fixture.RepositoryPath}\" --log-file \"{logPath}\" {outputArgument}"; var result = GitVersionHelper.ExecuteIn(null, arguments, false, Selectors(parser, configuration, backend)); @@ -45,13 +44,13 @@ public void SelectorCombinationsCalculateAndLogWithoutPollutingOutput( else { stdout.ShouldContain("tag-prefix: release-"); - stdout.Contains("calculation:", StringComparison.Ordinal).ShouldBe(configuration == "v7"); + stdout.ShouldContain("calculation:"); } stdout.ShouldNotContain("Argument parser version:"); stdout.ShouldNotContain("Configuration version:"); stdout.ShouldNotContain("Git backend:"); - if (buildServer && (!legacy || output != "config")) + if (buildServer) { result.StandardError.ShouldNotBeNull(); result.StandardError.ShouldContain($"Argument parser version: {parser}"); @@ -83,12 +82,14 @@ public void DefaultsSelectV7AndManagedWithConsoleLogsOnStderr(string? value) result.StandardError.ShouldContain("Git backend: managed"); } - [TestCase("GITVERSION_ARGUMENT_PARSER_VERSION", "true", "'v6' and 'v7'")] - [TestCase("GITVERSION_CONFIGURATION_VERSION", "v8", "'v6' and 'v7'")] + [TestCase("GITVERSION_ARGUMENT_PARSER_VERSION", "v6", "POSIX-style arguments")] + [TestCase("GITVERSION_CONFIGURATION_VERSION", " V6 ", "gitversion config migrate")] + [TestCase("GITVERSION_ARGUMENT_PARSER_VERSION", "true", "'v7'")] + [TestCase("GITVERSION_CONFIGURATION_VERSION", "v8", "'v7'")] [TestCase("GITVERSION_GIT_BACKEND", "manged", "'libgit2' and 'managed'")] - [TestCase("GITVERSION_USE_V6_ARGUMENT_PARSER", "true", "GITVERSION_ARGUMENT_PARSER_VERSION=v6")] - [TestCase("GITVERSION_USE_V6_ARGUMENT_PARSER", "false", "GITVERSION_ARGUMENT_PARSER_VERSION=v6")] - [TestCase("GITVERSION_USE_V6_ARGUMENT_PARSER", "", "GITVERSION_ARGUMENT_PARSER_VERSION=v6")] + [TestCase("GITVERSION_USE_V6_ARGUMENT_PARSER", "true", "GITVERSION_ARGUMENT_PARSER_VERSION=v7")] + [TestCase("GITVERSION_USE_V6_ARGUMENT_PARSER", "false", "GITVERSION_ARGUMENT_PARSER_VERSION=v7")] + [TestCase("GITVERSION_USE_V6_ARGUMENT_PARSER", "", "GITVERSION_ARGUMENT_PARSER_VERSION=v7")] public void InvalidSelectorsFailBeforeHelpWithActionableStderr(string variable, string value, string guidance) { var environment = Selectors("v7", "v7", "managed").ToDictionary(pair => pair.Key, pair => pair.Value); @@ -106,8 +107,8 @@ public void InvalidSelectorsFailBeforeHelpWithActionableStderr(string variable, [Test] [Combinatorial] - public void MigrationRetainsYamlStdoutWithEitherConfigurationAndBackend( - [Values("v6", "v7")] string configuration, + public void MigrationRetainsV6InputAndYamlStdoutWithEitherBackend( + [Values("v7")] string configuration, [Values("libgit2", "managed")] string backend) { var directory = Directory.CreateTempSubdirectory(); @@ -133,22 +134,15 @@ public void MigrationRetainsYamlStdoutWithEitherConfigurationAndBackend( } } - private static string OutputArguments(string output, bool legacy, bool buildServer) + private static string OutputArguments(string output, bool buildServer) { - var arguments = (legacy, output) switch + var arguments = output switch { - (true, "variable") => "/output json /showvariable FullSemVer", - (false, "variable") => "--output json --show-variable FullSemVer", - (true, "config") => "/showconfig", - (false, "config") => "--show-config", - (true, _) => "/output json", + "variable" => "--output json --show-variable FullSemVer", + "config" => "--show-config", _ => "--output json" }; - if (buildServer) - { - arguments += legacy ? " /output buildserver" : " --output buildserver"; - } - return arguments; + return buildServer ? arguments + " --output buildserver" : arguments; } private static KeyValuePair[] Selectors(string? parser, string? configuration, string? backend) => diff --git a/src/GitVersion.App.Tests/FeatureSelectorTests.cs b/src/GitVersion.App.Tests/FeatureSelectorTests.cs index 261a7d0178..f3aeadc3ba 100644 --- a/src/GitVersion.App.Tests/FeatureSelectorTests.cs +++ b/src/GitVersion.App.Tests/FeatureSelectorTests.cs @@ -7,18 +7,16 @@ namespace GitVersion.App.Tests; [NonParallelizable] public class FeatureSelectorTests { - [TestCase(null, false)] - [TestCase("", false)] - [TestCase(" \t ", false)] - [TestCase("v6", true)] - [TestCase(" V6 ", true)] - [TestCase("v7", false)] - [TestCase(" V7 ", false)] - public void ParserResolvesKnownValues(string? value, bool legacy) + [TestCase(null)] + [TestCase("")] + [TestCase(" \t ")] + [TestCase("v7")] + [TestCase(" V7 ")] + public void ParserResolvesKnownValues(string? value) { using var scope = new SelectorScope(parser: value); - ArgumentParserVersionSelector.Resolve().ShouldBe(legacy ? ArgumentParserVersion.V6 : ArgumentParserVersion.V7); + ArgumentParserVersionSelector.Resolve().ShouldBe(ArgumentParserVersion.V7); } [TestCase("true")] @@ -31,7 +29,7 @@ public void ParserRejectsUnknownValues(string value) var exception = Should.Throw(() => ArgumentParserVersionSelector.Resolve()); exception.Message.ShouldContain(ArgumentParserVersionSelector.EnvironmentVariableName); exception.Message.ShouldContain(value); - exception.Message.ShouldContain("'v6' and 'v7'"); + exception.Message.ShouldContain("'v7'"); } [TestCase("true")] @@ -43,14 +41,14 @@ public void RetiredBooleanIsRejectedEvenWithNewSelector(string value) var exception = Should.Throw(() => ArgumentParserVersionSelector.Resolve()); exception.Message.ShouldContain(ArgumentParserVersionSelector.RetiredEnvironmentVariableName); - exception.Message.ShouldContain("GITVERSION_ARGUMENT_PARSER_VERSION=v6"); + exception.Message.ShouldContain("GITVERSION_ARGUMENT_PARSER_VERSION=v7"); } [Test] [Combinatorial] public void CompositionRegistersSelectedImplementations( - [Values("v6", "v7")] string parser, - [Values("v6", "v7")] string configuration, + [Values("v7")] string parser, + [Values("v7")] string configuration, [Values("libgit2", "managed")] string backend) { using var scope = new SelectorScope(parser, configuration, backend); @@ -59,7 +57,7 @@ public void CompositionRegistersSelectedImplementations( using var host = builder.Build(); host.Services.GetRequiredService().GetType() - .ShouldBe(parser == "v6" ? typeof(LegacyArgumentParser) : typeof(ArgumentParser)); + .ShouldBe(typeof(ArgumentParser)); host.Services.GetRequiredService().GetType().Assembly .ShouldBe(backend == "libgit2" ? typeof(GitVersionLibGit2SharpModule).Assembly : typeof(GitVersionManagedGitModule).Assembly); } @@ -68,7 +66,7 @@ public void CompositionRegistersSelectedImplementations( public void SelectionLogUsesCapturedValues() { FeatureSelections selections; - using (new SelectorScope("v6", "v6", "libgit2")) + using (new SelectorScope("v7", "v7", "libgit2")) { selections = FeatureSelections.Resolve(); } @@ -77,7 +75,18 @@ public void SelectionLogUsesCapturedValues() var messages = new List(); selections.Log(new TestLogger(messages.Add)); - messages.ShouldBe(new[] { "Argument parser version: v6; Configuration version: v6; Git backend: libgit2" }); + messages.ShouldBe(new[] { "Argument parser version: v7; Configuration version: v7; Git backend: libgit2" }); + } + + [TestCase("v6")] + [TestCase(" V6 ")] + public void ParserRejectsRetiredVersion(string value) + { + using var scope = new SelectorScope(parser: value); + var error = Should.Throw(() => ArgumentParserVersionSelector.Resolve()); + error.Message.ShouldContain("removed in GitVersion 7.1"); + error.Message.ShouldContain("POSIX"); + error.Message.ShouldContain("v7"); } private sealed class SelectorScope : IDisposable diff --git a/src/GitVersion.App.Tests/GitVersionExecutorRoutingTests.cs b/src/GitVersion.App.Tests/GitVersionExecutorRoutingTests.cs index e02067064e..d613fc162a 100644 --- a/src/GitVersion.App.Tests/GitVersionExecutorRoutingTests.cs +++ b/src/GitVersion.App.Tests/GitVersionExecutorRoutingTests.cs @@ -53,7 +53,6 @@ public void RestoreVersion() SysEnv.SetEnvironmentVariable(ConfigurationVersionSelector.EnvironmentVariableName, this.originalVersion); } - [TestCase("v6")] [TestCase("v7")] public void DisplayUsesVersionSpecificOverridesWithoutCalculating(string version) { @@ -92,8 +91,8 @@ public void LegacyPropertyQueryStillThrowsBeforeLoadingConfiguration() SysEnv.SetEnvironmentVariable(ConfigurationVersionSelector.EnvironmentVariableName, "v6"); var options = new GitVersionOptions { ConfigurationInfo = { PropertyPath = "output.update-build-number" } }; - Should.Throw(() => this.executor.Execute(options)) - .Message.ShouldBe("Configuration property queries require v7 configuration. Set GITVERSION_CONFIGURATION_VERSION=v7."); + Should.Throw(() => this.executor.Execute(options)) + .Message.ShouldContain("removed in GitVersion 7.1"); this.provider.ReceivedCalls().ShouldBeEmpty(); this.console.ReceivedCalls().ShouldBeEmpty(); diff --git a/src/GitVersion.App.Tests/HelpWriterTests.cs b/src/GitVersion.App.Tests/HelpWriterTests.cs deleted file mode 100644 index b63888b308..0000000000 --- a/src/GitVersion.App.Tests/HelpWriterTests.cs +++ /dev/null @@ -1,82 +0,0 @@ -using GitVersion.Extensions; -using GitVersion.Tests; - -namespace GitVersion.App.Tests; - -public class HelpWriterTests : TestBase -{ - private readonly IHelpWriter helpWriter; - - public HelpWriterTests() - { - var sp = ConfigureServices(services => services.AddModule(new GitVersionAppModule(useLegacyParser: true))); - this.helpWriter = sp.GetRequiredService(); - } - - [Test] - public void AllArgsAreInHelp() - { - var lookup = new Dictionary - { - { nameof(Arguments.IsHelp), "/?" }, - { nameof(Arguments.IsVersion), "/version" }, - - { nameof(Arguments.TargetUrl), "/url" }, - { nameof(Arguments.TargetBranch), "/b" }, - { nameof(Arguments.ClonePath), "/dynamicRepoLocation" }, - { nameof(Arguments.CommitId), "/c" }, - - { nameof(Arguments.Diag) , "/diag" }, - { nameof(Arguments.LogFilePath) , "/l" }, - { "verbosity", "/verbosity" }, - { nameof(Arguments.Output) , "/output" }, - { nameof(Arguments.OutputFile) , "/outputfile" }, - { nameof(Arguments.ShowVariable), "/showvariable" }, - { nameof(Arguments.Format), "/format" }, - - { nameof(Arguments.UpdateWixVersionFile), "/updatewixversionfile" }, - { nameof(Arguments.UpdateProjectFiles), "/updateprojectfiles" }, - { nameof(Arguments.UpdateAssemblyInfo), "/updateassemblyinfo" }, - { nameof(Arguments.EnsureAssemblyInfo), "/ensureassemblyinfo" }, - - { nameof(Arguments.ConfigurationFile), "/config" }, - { nameof(Arguments.ShowConfiguration), "/showconfig" }, - { nameof(Arguments.OverrideConfiguration), "/overrideconfig" }, - - { nameof(Arguments.NoCache), "/nocache" }, - { nameof(Arguments.NoFetch), "/nofetch" }, - { nameof(Arguments.NoNormalize), "/nonormalize" }, - { nameof(Arguments.AllowShallow), "/allowshallow" } - }; - var helpText = string.Empty; - - this.helpWriter.WriteTo(s => helpText = s); - - var ignored = new[] - { - nameof(Arguments.Authentication), - nameof(Arguments.UpdateAssemblyInfoFileName), - nameof(Arguments.ConfigurationPropertyPath), // Only available through the modern parser. - nameof(Arguments.IsConfigurationMigration), - nameof(Arguments.MigrationInputFile), - nameof(Arguments.MigrationOutputFile), - nameof(Arguments.MigrationInPlace), - nameof(Arguments.MigrationForce) - }; - typeof(Arguments).GetFields() - .Select(p => p.Name) - .Where(p => IsNotInHelp(lookup, p, helpText)) - .Except(ignored) - .ShouldBeEmpty(); - } - - private static bool IsNotInHelp(Dictionary lookup, string propertyName, string helpText) - { - if (lookup.TryGetValue(propertyName, out var value)) - { - return !helpText.Contains(value); - } - - return !helpText.Contains("/" + propertyName.ToLower()); - } -} diff --git a/src/GitVersion.App.Tests/LegacyArgumentParserTests.cs b/src/GitVersion.App.Tests/LegacyArgumentParserTests.cs deleted file mode 100644 index 27148ae43e..0000000000 --- a/src/GitVersion.App.Tests/LegacyArgumentParserTests.cs +++ /dev/null @@ -1,874 +0,0 @@ -using System.IO.Abstractions; -using GitVersion.Configuration; -using GitVersion.Extensions; -using GitVersion.Helpers; -using GitVersion.Logging; -using GitVersion.Tests; -using GitVersion.VersionCalculation; - -namespace GitVersion.App.Tests; - -[TestFixture] -[NonParallelizable] -public class LegacyArgumentParserTests : TestBase -{ - private IEnvironment environment = null!; - private IArgumentParser argumentParser = null!; - private IFileSystem fileSystem = null!; - private string? originalConfigurationVersion; - - [SetUp] - public void SetUp() - { - this.originalConfigurationVersion = System.Environment.GetEnvironmentVariable(ConfigurationVersionSelector.EnvironmentVariableName); - System.Environment.SetEnvironmentVariable(ConfigurationVersionSelector.EnvironmentVariableName, "v6"); - var sp = ConfigureServices(services => services.AddModule(new GitVersionAppModule(useLegacyParser: true))); - this.environment = sp.GetRequiredService(); - this.argumentParser = sp.GetRequiredService(); - this.fileSystem = sp.GetRequiredService(); - } - - [TearDown] - public void TearDown() => - System.Environment.SetEnvironmentVariable(ConfigurationVersionSelector.EnvironmentVariableName, this.originalConfigurationVersion); - - [Test] - public void OverrideConfigSupportsNestedV7RootAndBranchPaths() - { - System.Environment.SetEnvironmentVariable(ConfigurationVersionSelector.EnvironmentVariableName, "v7"); - - var arguments = this.argumentParser.ParseArguments( - "/overrideconfig calculation.tag-prefix=custom- " + - "/overrideconfig calculation.branches.main.increment=Major " + - "/overrideconfig output.branches.main.pre-release-weight=42"); - - var normalized = ConfigurationDocumentMapper.Normalize( - arguments.OverrideConfiguration!, ConfigurationVersion.V7, "test override"); - ConfigurationHelper configurationHelper = new(normalized); - var configuration = configurationHelper.Configuration; - configuration.TagPrefixPattern.ShouldBe("custom-"); - configuration.Branches["main"].Increment.ShouldBe(IncrementStrategy.Major); - configuration.Branches["main"].PreReleaseWeight.ShouldBe(42); - } - - [Test] - public void OverrideConfigRejectsV6PathInV7WithReplacement() - { - System.Environment.SetEnvironmentVariable(ConfigurationVersionSelector.EnvironmentVariableName, "v7"); - - var exception = Should.Throw(() => - this.argumentParser.ParseArguments("/overrideconfig tag-prefix=custom-")); - - exception.Message.ShouldContain("calculation.tag-prefix"); - exception.Message.ShouldContain("config migrate"); - } - - [Test] - public void ConfigMigrateIsRejectedAsASubcommand() - { - var exception = Should.Throw(() => this.argumentParser.ParseArguments("config migrate")); - - exception.Message.ShouldContain("only available with the POSIX argument parser"); - } - - [Test] - public void EmptyMeansUseCurrentDirectory() - { - var arguments = this.argumentParser.ParseArguments(""); - arguments.TargetPath.ShouldBe(SysEnv.CurrentDirectory); - arguments.LogFilePath.ShouldBe(null); - arguments.IsHelp.ShouldBe(false); - } - - [Test] - public void SingleMeansUseAsTargetDirectory() - { - var arguments = this.argumentParser.ParseArguments("path"); - arguments.TargetPath.ShouldBe("path"); - arguments.LogFilePath.ShouldBe(null); - arguments.IsHelp.ShouldBe(false); - } - - [Test] - public void NoPathAndLogfileShouldUseCurrentDirectoryTargetDirectory() - { - var arguments = this.argumentParser.ParseArguments("-l logFilePath"); - arguments.TargetPath.ShouldBe(SysEnv.CurrentDirectory); - arguments.LogFilePath.ShouldBe("logFilePath"); - arguments.IsHelp.ShouldBe(false); - } - - [Test] - public void HelpSwitchTest() - { - var arguments = this.argumentParser.ParseArguments("-h"); - Assert.Multiple(() => - { - Assert.That(arguments.TargetPath, Is.Null); - Assert.That(arguments.LogFilePath, Is.Null); - }); - arguments.IsHelp.ShouldBe(true); - } - - [Test] - public void VersionSwitchTest() - { - var arguments = this.argumentParser.ParseArguments("-version"); - Assert.Multiple(() => - { - Assert.That(arguments.TargetPath, Is.Null); - Assert.That(arguments.LogFilePath, Is.Null); - }); - arguments.IsVersion.ShouldBe(true); - } - - [Test] - public void TargetDirectoryAndLogFilePathCanBeParsed() - { - var arguments = this.argumentParser.ParseArguments("targetDirectoryPath -l logFilePath"); - arguments.TargetPath.ShouldBe("targetDirectoryPath"); - arguments.LogFilePath.ShouldBe("logFilePath"); - arguments.IsHelp.ShouldBe(false); - } - - [Test] - public void UsernameAndPasswordCanBeParsed() - { - var arguments = this.argumentParser.ParseArguments("targetDirectoryPath -u [username] -p [password]"); - arguments.TargetPath.ShouldBe("targetDirectoryPath"); - arguments.Authentication.Username.ShouldBe("[username]"); - arguments.Authentication.Password.ShouldBe("[password]"); - arguments.IsHelp.ShouldBe(false); - } - - [Test] - public void UnknownOutputShouldThrow() - { - var exception = Assert.Throws(() => this.argumentParser.ParseArguments("targetDirectoryPath -output invalid_value")); - exception.ShouldNotBeNull(); - exception.Message.ShouldBe("Value 'invalid_value' cannot be parsed as output type, please use 'json', 'file', 'buildserver' or 'dotenv'"); - } - - [Test] - public void OutputDefaultsToJson() - { - var arguments = this.argumentParser.ParseArguments("targetDirectoryPath"); - arguments.Output.ShouldContain(OutputType.Json); - arguments.Output.ShouldNotContain(OutputType.BuildServer); - arguments.Output.ShouldNotContain(OutputType.File); - } - - [Test] - public void OutputJsonCanBeParsed() - { - var arguments = this.argumentParser.ParseArguments("targetDirectoryPath -output json"); - arguments.Output.ShouldContain(OutputType.Json); - arguments.Output.ShouldNotContain(OutputType.BuildServer); - arguments.Output.ShouldNotContain(OutputType.File); - } - - [Test] - public void MultipleOutputJsonCanBeParsed() - { - 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); - } - - [Test] - public void OutputBuildserverCanBeParsed() - { - var arguments = this.argumentParser.ParseArguments("targetDirectoryPath -output buildserver"); - arguments.Output.ShouldContain(OutputType.BuildServer); - arguments.Output.ShouldNotContain(OutputType.Json); - arguments.Output.ShouldNotContain(OutputType.File); - } - - [Test] - public void MultipleOutputBuildserverCanBeParsed() - { - 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); - } - - [Test] - public void OutputFileCanBeParsed() - { - var arguments = this.argumentParser.ParseArguments("targetDirectoryPath -output file"); - arguments.Output.ShouldContain(OutputType.File); - arguments.Output.ShouldNotContain(OutputType.BuildServer); - arguments.Output.ShouldNotContain(OutputType.Json); - } - - [Test] - public void MultipleOutputFileCanBeParsed() - { - 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); - } - - [Test] - public void OutputBuildserverAndJsonCanBeParsed() - { - 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); - } - - [Test] - public void OutputBuildserverAndJsonAndFileCanBeParsed() - { - 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); - } - - [Test] - public void MultipleArgsAndFlag() - { - var arguments = this.argumentParser.ParseArguments("targetDirectoryPath -output buildserver -updateAssemblyInfo"); - arguments.Output.ShouldContain(OutputType.BuildServer); - } - - [TestCase("-output file", "GitVersion.json")] - [TestCase("-output file -outputfile version.json", "version.json")] - public void OutputFileArgumentCanBeParsed(string args, string outputFile) - { - var arguments = this.argumentParser.ParseArguments(args); - - arguments.Output.ShouldContain(OutputType.File); - arguments.OutputFile.ShouldBe(outputFile); - } - - [Test] - public void UrlAndBranchNameCanBeParsed() - { - var arguments = this.argumentParser.ParseArguments("targetDirectoryPath -url https://github.com/Particular/GitVersion.git -b someBranch"); - arguments.TargetPath.ShouldBe("targetDirectoryPath"); - arguments.TargetUrl.ShouldBe("https://github.com/Particular/GitVersion.git"); - arguments.TargetBranch.ShouldBe("someBranch"); - arguments.IsHelp.ShouldBe(false); - } - - [Test] - public void WrongNumberOfArgumentsShouldThrow() - { - var exception = Assert.Throws(() => this.argumentParser.ParseArguments("targetDirectoryPath -l logFilePath extraArg")); - exception.ShouldNotBeNull(); - exception.Message.ShouldBe("Could not parse command line parameter 'extraArg'."); - } - - [TestCase("targetDirectoryPath -x logFilePath")] - [TestCase("/invalid-argument")] - public void UnknownArgumentsShouldThrow(string arguments) - { - var exception = Assert.Throws(() => this.argumentParser.ParseArguments(arguments)); - exception.ShouldNotBeNull(); - exception.Message.ShouldStartWith("Could not parse command line parameter"); - } - - [TestCase("-updateAssemblyInfo true")] - [TestCase("-updateAssemblyInfo 1")] - [TestCase("-updateAssemblyInfo")] - [TestCase("-updateAssemblyInfo assemblyInfo.cs")] - [TestCase("-updateAssemblyInfo assemblyInfo.cs -ensureassemblyinfo")] - [TestCase("-updateAssemblyInfo assemblyInfo.cs otherAssemblyInfo.cs")] - [TestCase("-updateAssemblyInfo Assembly.cs Assembly.cs -ensureassemblyinfo")] - public void UpdateAssemblyInfoTrue(string command) - { - var arguments = this.argumentParser.ParseArguments(command); - arguments.UpdateAssemblyInfo.ShouldBe(true); - } - - [TestCase("-updateProjectFiles assemblyInfo.csproj")] - [TestCase("-updateProjectFiles assemblyInfo.csproj")] - [TestCase("-updateProjectFiles assemblyInfo.csproj otherAssemblyInfo.fsproj")] - [TestCase("-updateProjectFiles")] - public void UpdateProjectTrue(string command) - { - var arguments = this.argumentParser.ParseArguments(command); - arguments.UpdateProjectFiles.ShouldBe(true); - } - - [TestCase("-updateAssemblyInfo false")] - [TestCase("-updateAssemblyInfo 0")] - public void UpdateAssemblyInfoFalse(string command) - { - var arguments = this.argumentParser.ParseArguments(command); - arguments.UpdateAssemblyInfo.ShouldBe(false); - } - - [TestCase("-updateAssemblyInfo Assembly.cs Assembly1.cs -ensureassemblyinfo")] - public void CreateMultipleAssemblyInfoProtected(string command) - { - var exception = Assert.Throws(() => this.argumentParser.ParseArguments(command)); - exception.ShouldNotBeNull(); - 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(() => this.argumentParser.ParseArguments(command)); - exception.ShouldNotBeNull(); - exception.Message.ShouldBe("Cannot specify -ensureassemblyinfo with updateprojectfiles: please ensure your project file exists before attempting to update it"); - } - - [Test] - public void UpdateAssemblyInfoWithFilename() - { - using var repo = new EmptyRepositoryFixture(); - - var assemblyFile = FileSystemHelper.Path.Combine(repo.RepositoryPath, "CommonAssemblyInfo.cs"); - using var file = this.fileSystem.File.Create(assemblyFile); - - var arguments = this.argumentParser.ParseArguments($"-targetpath {repo.RepositoryPath} -updateAssemblyInfo CommonAssemblyInfo.cs"); - arguments.UpdateAssemblyInfo.ShouldBe(true); - arguments.UpdateAssemblyInfoFileName.Count.ShouldBe(1); - arguments.UpdateAssemblyInfoFileName.ShouldContain(x => FileSystemHelper.Path.GetFileName(x).Equals("CommonAssemblyInfo.cs")); - } - - [Test] - public void UpdateAssemblyInfoWithMultipleFilenames() - { - using var repo = new EmptyRepositoryFixture(); - - var assemblyFile1 = FileSystemHelper.Path.Combine(repo.RepositoryPath, "CommonAssemblyInfo.cs"); - using var file = this.fileSystem.File.Create(assemblyFile1); - - var assemblyFile2 = FileSystemHelper.Path.Combine(repo.RepositoryPath, "VersionAssemblyInfo.cs"); - using var file2 = this.fileSystem.File.Create(assemblyFile2); - - 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 => FileSystemHelper.Path.GetFileName(x).Equals("CommonAssemblyInfo.cs")); - arguments.UpdateAssemblyInfoFileName.ShouldContain(x => FileSystemHelper.Path.GetFileName(x).Equals("VersionAssemblyInfo.cs")); - } - - [Test] - public void UpdateProjectFilesWithMultipleFilenames() - { - using var repo = new EmptyRepositoryFixture(); - - var assemblyFile1 = FileSystemHelper.Path.Combine(repo.RepositoryPath, "CommonAssemblyInfo.csproj"); - using var file = this.fileSystem.File.Create(assemblyFile1); - - var assemblyFile2 = FileSystemHelper.Path.Combine(repo.RepositoryPath, "VersionAssemblyInfo.csproj"); - using var file2 = this.fileSystem.File.Create(assemblyFile2); - - 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 => FileSystemHelper.Path.GetFileName(x).Equals("CommonAssemblyInfo.csproj")); - arguments.UpdateAssemblyInfoFileName.ShouldContain(x => FileSystemHelper.Path.GetFileName(x).Equals("VersionAssemblyInfo.csproj")); - } - - [Test] - public void UpdateAssemblyInfoWithMultipleFilenamesMatchingGlobbing() - { - using var repo = new EmptyRepositoryFixture(); - - var assemblyFile1 = FileSystemHelper.Path.Combine(repo.RepositoryPath, "CommonAssemblyInfo.cs"); - using var file = this.fileSystem.File.Create(assemblyFile1); - - var assemblyFile2 = FileSystemHelper.Path.Combine(repo.RepositoryPath, "VersionAssemblyInfo.cs"); - using var file2 = this.fileSystem.File.Create(assemblyFile2); - - var subdir = FileSystemHelper.Path.Combine(repo.RepositoryPath, "subdir"); - - this.fileSystem.Directory.CreateDirectory(subdir); - var assemblyFile3 = FileSystemHelper.Path.Combine(subdir, "LocalAssemblyInfo.cs"); - using var file3 = this.fileSystem.File.Create(assemblyFile3); - - var arguments = this.argumentParser.ParseArguments($"-targetpath {repo.RepositoryPath} -updateAssemblyInfo **/*AssemblyInfo.cs"); - arguments.UpdateAssemblyInfo.ShouldBe(true); - arguments.UpdateAssemblyInfoFileName.Count.ShouldBe(3); - arguments.UpdateAssemblyInfoFileName.ShouldContain(x => FileSystemHelper.Path.GetFileName(x).Equals("CommonAssemblyInfo.cs")); - arguments.UpdateAssemblyInfoFileName.ShouldContain(x => FileSystemHelper.Path.GetFileName(x).Equals("VersionAssemblyInfo.cs")); - arguments.UpdateAssemblyInfoFileName.ShouldContain(x => FileSystemHelper.Path.GetFileName(x).Equals("LocalAssemblyInfo.cs")); - } - - [Test] - public void UpdateAssemblyInfoWithRelativeFilename() - { - using var repo = new EmptyRepositoryFixture(); - - var assemblyFile = FileSystemHelper.Path.Combine(repo.RepositoryPath, "CommonAssemblyInfo.cs"); - using var file = this.fileSystem.File.Create(assemblyFile); - - var targetPath = FileSystemHelper.Path.Combine(repo.RepositoryPath, "subdir1", "subdir2"); - this.fileSystem.Directory.CreateDirectory(targetPath); - - var arguments = this.argumentParser.ParseArguments($@"-targetpath {targetPath} -updateAssemblyInfo ..\..\CommonAssemblyInfo.cs"); - arguments.UpdateAssemblyInfo.ShouldBe(true); - arguments.UpdateAssemblyInfoFileName.Count.ShouldBe(1); - arguments.UpdateAssemblyInfoFileName.ShouldContain(x => FileSystemHelper.Path.GetFileName(x).Equals("CommonAssemblyInfo.cs")); - } - - [Test] - public void OverrideconfigWithNoOptions() - { - var arguments = this.argumentParser.ParseArguments("/overrideconfig"); - arguments.OverrideConfiguration.ShouldBeEmpty(); - } - - [TestCaseSource(nameof(OverrideconfigWithInvalidOptionTestData))] - public string OverrideconfigWithInvalidOption(string options) - { - var exception = Assert.Throws(() => this.argumentParser.ParseArguments($"/overrideconfig {options}")); - exception.ShouldNotBeNull(); - return exception.Message; - } - - private static IEnumerable> OverrideconfigWithInvalidOptionTestData() - { - yield return TestCaseData.Create("tag-prefix=sample=asdf").Returns("Could not parse /overrideconfig option: tag-prefix=sample=asdf. Ensure it is in format 'key=value'."); - yield return TestCaseData.Create("unknown-option=25").Returns("Could not parse /overrideconfig option: unknown-option=25. Unsupported key 'unknown-option'."); - } - - [TestCaseSource(nameof(OverrideConfigWithSingleOptionTestData))] - public void OverrideConfigWithSingleOptions(string options, IGitVersionConfiguration expected) - { - var arguments = this.argumentParser.ParseArguments($"/overrideconfig {options}"); - - ConfigurationHelper configurationHelper = new(arguments.OverrideConfiguration); - configurationHelper.Configuration.ShouldBeEquivalentTo(expected); - } - - private static IEnumerable> OverrideConfigWithSingleOptionTestData() - { - yield return TestCaseData.Create( - "assembly-versioning-scheme=MajorMinor", - new GitVersionConfiguration - { - AssemblyVersioningScheme = AssemblyVersioningScheme.MajorMinor - } - ); - yield return TestCaseData.Create( - "assembly-file-versioning-scheme=\"MajorMinorPatch\"", - new GitVersionConfiguration - { - AssemblyFileVersioningScheme = AssemblyFileVersioningScheme.MajorMinorPatch - } - ); - yield return TestCaseData.Create( - "assembly-informational-format=\"{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}\"", - new GitVersionConfiguration - { - AssemblyInformationalFormat = "{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}" - } - ); - yield return TestCaseData.Create( - "assembly-versioning-format=\"{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}\"", - new GitVersionConfiguration - { - AssemblyVersioningFormat = "{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}" - } - ); - yield return TestCaseData.Create( - "assembly-file-versioning-format=\"{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}\"", - new GitVersionConfiguration - { - AssemblyFileVersioningFormat = "{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}" - } - ); - yield return TestCaseData.Create( - "custom-version-format=\"{Major}.{Minor}.{Patch}{PreReleaseLabelName:l}{PreReleaseNumber}\"", - new GitVersionConfiguration - { - CustomVersionFormat = "{Major}.{Minor}.{Patch}{PreReleaseLabelName:l}{PreReleaseNumber}" - } - ); - yield return TestCaseData.Create( - "mode=ContinuousDelivery", - new GitVersionConfiguration - { - DeploymentMode = DeploymentMode.ContinuousDelivery - } - ); - yield return TestCaseData.Create( - "tag-prefix=sample", - new GitVersionConfiguration - { - TagPrefixPattern = "sample" - } - ); - yield return TestCaseData.Create( - "label=cd-label", - new GitVersionConfiguration - { - Label = "cd-label" - } - ); - yield return TestCaseData.Create( - "next-version=1", - new GitVersionConfiguration - { - NextVersion = "1" - } - ); - yield return TestCaseData.Create( - "major-version-bump-message=\"This is major version bump message.\"", - new GitVersionConfiguration - { - MajorVersionBumpMessage = "This is major version bump message." - } - ); - yield return TestCaseData.Create( - "minor-version-bump-message=\"This is minor version bump message.\"", - new GitVersionConfiguration - { - MinorVersionBumpMessage = "This is minor version bump message." - } - ); - yield return TestCaseData.Create( - "patch-version-bump-message=\"This is patch version bump message.\"", - new GitVersionConfiguration - { - PatchVersionBumpMessage = "This is patch version bump message." - } - ); - yield return TestCaseData.Create( - "no-bump-message=\"This is no bump message.\"", - new GitVersionConfiguration - { - NoBumpMessage = "This is no bump message." - } - ); - yield return TestCaseData.Create( - "version-bump-reset-message=\"baseline:\"", - new GitVersionConfiguration - { - VersionBumpResetMessage = "baseline:" - } - ); - yield return TestCaseData.Create( - "tag-pre-release-weight=2", - new GitVersionConfiguration - { - TagPreReleaseWeight = 2 - } - ); - yield return TestCaseData.Create( - "commit-message-incrementing=MergeMessageOnly", - new GitVersionConfiguration - { - CommitMessageIncrementing = CommitMessageIncrementMode.MergeMessageOnly - } - ); - yield return TestCaseData.Create( - "increment=Minor", - new GitVersionConfiguration - { - Increment = IncrementStrategy.Minor - } - ); - yield return TestCaseData.Create( - "commit-date-format=\"MM/dd/yyyy h:mm tt\"", - new GitVersionConfiguration - { - CommitDateFormat = "MM/dd/yyyy h:mm tt" - } - ); - yield return TestCaseData.Create( - "update-build-number=true", - new GitVersionConfiguration - { - UpdateBuildNumber = true - } - ); - yield return TestCaseData.Create( - "strategies=[\"None\",\"Mainline\"]", - new GitVersionConfiguration - { - VersionStrategies = [VersionStrategies.None, VersionStrategies.Mainline] - } - ); - } - - [TestCaseSource(nameof(OverrideConfigWithMultipleOptionsTestData))] - public void OverrideConfigWithMultipleOptions(string options, IGitVersionConfiguration expected) - { - var arguments = this.argumentParser.ParseArguments(options); - ConfigurationHelper configurationHelper = new(arguments.OverrideConfiguration); - configurationHelper.Configuration.ShouldBeEquivalentTo(expected); - } - - private static IEnumerable> OverrideConfigWithMultipleOptionsTestData() - { - yield return TestCaseData.Create( - "/overrideconfig tag-prefix=sample /overrideconfig assembly-versioning-scheme=MajorMinor", - new GitVersionConfiguration - { - TagPrefixPattern = "sample", - AssemblyVersioningScheme = AssemblyVersioningScheme.MajorMinor - } - ); - yield return TestCaseData.Create( - "/overrideconfig tag-prefix=sample /overrideconfig assembly-versioning-format=\"{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}\"", - new GitVersionConfiguration - { - TagPrefixPattern = "sample", - AssemblyVersioningFormat = "{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}" - } - ); - yield return TestCaseData.Create( - "/overrideconfig tag-prefix=sample /overrideconfig assembly-versioning-format=\"{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}\" /overrideconfig update-build-number=true /overrideconfig assembly-versioning-scheme=MajorMinorPatchTag /overrideconfig mode=ContinuousDelivery /overrideconfig tag-pre-release-weight=4", - new GitVersionConfiguration - { - TagPrefixPattern = "sample", - AssemblyVersioningFormat = "{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}", - UpdateBuildNumber = true, - AssemblyVersioningScheme = AssemblyVersioningScheme.MajorMinorPatchTag, - DeploymentMode = DeploymentMode.ContinuousDelivery, - TagPreReleaseWeight = 4 - } - ); - } - - [Test] - public void EnsureAssemblyInfoTrueWhenFound() - { - var arguments = this.argumentParser.ParseArguments("-ensureAssemblyInfo"); - arguments.EnsureAssemblyInfo.ShouldBe(true); - } - - [Test] - public void EnsureAssemblyInfoTrue() - { - var arguments = this.argumentParser.ParseArguments("-ensureAssemblyInfo true"); - arguments.EnsureAssemblyInfo.ShouldBe(true); - } - - [Test] - public void EnsureAssemblyInfoFalse() - { - var arguments = this.argumentParser.ParseArguments("-ensureAssemblyInfo false"); - arguments.EnsureAssemblyInfo.ShouldBe(false); - } - - [Test] - public void DynamicRepoLocation() - { - var arguments = this.argumentParser.ParseArguments("-dynamicRepoLocation /path/to/repo"); - arguments.ClonePath.ShouldBe("/path/to/repo"); - } - - [Test] - public void CanLogToConsole() - { - var arguments = this.argumentParser.ParseArguments("-l console"); - arguments.LogFilePath.ShouldBe("console"); - } - - [Test] - public void NofetchTrueWhenDefined() - { - var arguments = this.argumentParser.ParseArguments("-nofetch"); - arguments.NoFetch.ShouldBe(true); - } - - [Test] - public void NoNormalizeTrueWhenDefined() - { - var arguments = this.argumentParser.ParseArguments("-nonormalize"); - arguments.NoNormalize.ShouldBe(true); - } - - [Test] - public void AllowshallowTrueWhenDefined() - { - var arguments = this.argumentParser.ParseArguments("-allowshallow"); - arguments.AllowShallow.ShouldBe(true); - } - - [Test] - public void DiagTrueWhenDefined() - { - var arguments = this.argumentParser.ParseArguments("-diag"); - arguments.Diag.ShouldBe(true); - } - - [Test] - public void DiagAndLogToConsoleIsNotIgnored() - { - var arguments = this.argumentParser.ParseArguments("-diag -l console"); - arguments.Diag.ShouldBe(true); - arguments.LogFilePath.ShouldBe("console"); - } - - [Test] - public void OtherArgumentsCanBeParsedBeforeNofetch() - { - var arguments = this.argumentParser.ParseArguments("targetpath -nofetch "); - arguments.TargetPath.ShouldBe("targetpath"); - arguments.NoFetch.ShouldBe(true); - } - - [Test] - public void OtherArgumentsCanBeParsedBeforeNonormalize() - { - var arguments = this.argumentParser.ParseArguments("targetpath -nonormalize"); - arguments.TargetPath.ShouldBe("targetpath"); - arguments.NoNormalize.ShouldBe(true); - } - - [Test] - public void OtherArgumentsCanBeParsedBeforeNocache() - { - var arguments = this.argumentParser.ParseArguments("targetpath -nocache"); - arguments.TargetPath.ShouldBe("targetpath"); - arguments.NoCache.ShouldBe(true); - } - - [Test] - public void OtherArgumentsCanBeParsedBeforeAllowshallow() - { - var arguments = this.argumentParser.ParseArguments("targetpath -allowshallow"); - arguments.TargetPath.ShouldBe("targetpath"); - arguments.AllowShallow.ShouldBe(true); - } - - [TestCase("-nofetch -nonormalize -nocache -allowshallow")] - [TestCase("-nofetch -nonormalize -allowshallow -nocache")] - [TestCase("-nofetch -nocache -nonormalize -allowshallow")] - [TestCase("-nofetch -nocache -allowshallow -nonormalize")] - [TestCase("-nofetch -allowshallow -nonormalize -nocache")] - [TestCase("-nofetch -allowshallow -nocache -nonormalize")] - [TestCase("-nonormalize -nofetch -nocache -allowshallow")] - [TestCase("-nonormalize -nofetch -allowshallow -nocache")] - [TestCase("-nonormalize -nocache -nofetch -allowshallow")] - [TestCase("-nonormalize -nocache -allowshallow -nofetch")] - [TestCase("-nonormalize -allowshallow -nofetch -nocache")] - [TestCase("-nonormalize -allowshallow -nocache -nofetch")] - [TestCase("-nocache -nofetch -nonormalize -allowshallow")] - [TestCase("-nocache -nofetch -allowshallow -nonormalize")] - [TestCase("-nocache -nonormalize -nofetch -allowshallow")] - [TestCase("-nocache -nonormalize -allowshallow -nofetch")] - [TestCase("-nocache -allowshallow -nofetch -nonormalize")] - [TestCase("-nocache -allowshallow -nonormalize -nofetch")] - [TestCase("-allowshallow -nofetch -nonormalize -nocache")] - [TestCase("-allowshallow -nofetch -nocache -nonormalize")] - [TestCase("-allowshallow -nonormalize -nofetch -nocache")] - [TestCase("-allowshallow -nonormalize -nocache -nofetch")] - [TestCase("-allowshallow -nocache -nofetch -nonormalize")] - [TestCase("-allowshallow -nocache -nonormalize -nofetch")] - public void SeveralSwitchesCanBeParsed(string commandLineArgs) - { - var arguments = this.argumentParser.ParseArguments(commandLineArgs); - arguments.NoCache.ShouldBe(true); - arguments.NoNormalize.ShouldBe(true); - arguments.NoFetch.ShouldBe(true); - arguments.AllowShallow.ShouldBe(true); - } - - [Test] - public void LogPathCanContainForwardSlash() - { - var arguments = this.argumentParser.ParseArguments("-l /some/path"); - arguments.LogFilePath.ShouldBe("/some/path"); - } - - [Test] - public void BooleanArgumentHandling() - { - var arguments = this.argumentParser.ParseArguments("/nofetch /updateassemblyinfo true"); - arguments.NoFetch.ShouldBe(true); - arguments.UpdateAssemblyInfo.ShouldBe(true); - } - - [Test] - public void NocacheTrueWhenDefined() - { - var arguments = this.argumentParser.ParseArguments("-nocache"); - arguments.NoCache.ShouldBe(true); - } - - [TestCase("x", true, Verbosity.Normal)] - [TestCase("diagnostic", false, Verbosity.Diagnostic)] - [TestCase("Minimal", false, Verbosity.Minimal)] - [TestCase("NORMAL", false, Verbosity.Normal)] - [TestCase("quiet", false, Verbosity.Quiet)] - [TestCase("Verbose", false, Verbosity.Verbose)] - public void CheckVerbosityParsing(string command, bool shouldThrow, Verbosity expectedVerbosity) - { - if (shouldThrow) - { - Assert.Throws(() => LegacyArgumentParser.ParseVerbosity(command)); - } - else - { - var verbosity = LegacyArgumentParser.ParseVerbosity(command); - verbosity.ShouldBe(expectedVerbosity); - } - } - - [Test] - public void EmptyArgumentsRemoteUsernameDefinedSetsUsername() - { - this.environment.SetEnvironmentVariable("GITVERSION_REMOTE_USERNAME", "value"); - var arguments = this.argumentParser.ParseArguments(string.Empty); - arguments.Authentication.Username.ShouldBe("value"); - } - - [Test] - public void EmptyArgumentsRemotePasswordDefinedSetsPassword() - { - this.environment.SetEnvironmentVariable("GITVERSION_REMOTE_PASSWORD", "value"); - var arguments = this.argumentParser.ParseArguments(string.Empty); - arguments.Authentication.Password.ShouldBe("value"); - } - - [Test] - public void ArbitraryArgumentsRemoteUsernameDefinedSetsUsername() - { - this.environment.SetEnvironmentVariable("GITVERSION_REMOTE_USERNAME", "value"); - var arguments = this.argumentParser.ParseArguments("-nocache"); - arguments.Authentication.Username.ShouldBe("value"); - } - - [Test] - public void ArbitraryArgumentsRemotePasswordDefinedSetsPassword() - { - this.environment.SetEnvironmentVariable("GITVERSION_REMOTE_PASSWORD", "value"); - var arguments = this.argumentParser.ParseArguments("-nocache"); - arguments.Authentication.Password.ShouldBe("value"); - } - - [Test] - public void EnsureShowVariableIsSet() - { - var arguments = this.argumentParser.ParseArguments("-showvariable SemVer"); - arguments.ShowVariable.ShouldBe("SemVer"); - } - - [Test] - public void EnsureFormatIsSet() - { - var arguments = this.argumentParser.ParseArguments("-format {Major}.{Minor}.{Patch}"); - arguments.Format.ShouldBe("{Major}.{Minor}.{Patch}"); - } - - [TestCase("custom-config.yaml")] - [TestCase("/path/to/custom-config.yaml")] - public void ThrowIfConfigurationFileDoesNotExist(string configFile) => - Should.Throw(() => _ = this.argumentParser.ParseArguments($"-config {configFile}")); - - [Test] - public void EnsureConfigurationFileIsSet() - { - var configFile = FileSystemHelper.Path.GetTempPath() + Guid.NewGuid() + ".yaml"; - this.fileSystem.File.WriteAllText(configFile, "next-version: 1.0.0"); - var arguments = this.argumentParser.ParseArguments($"-config {configFile}"); - arguments.ConfigurationFile.ShouldBe(configFile); - this.fileSystem.File.Delete(configFile); - } -} diff --git a/src/GitVersion.App.Tests/VersionWriterTests.cs b/src/GitVersion.App.Tests/VersionWriterTests.cs deleted file mode 100644 index 60fc4d1c80..0000000000 --- a/src/GitVersion.App.Tests/VersionWriterTests.cs +++ /dev/null @@ -1,62 +0,0 @@ -using GitVersion.Extensions; -using GitVersion.Tests; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; - -namespace GitVersion.App.Tests; - -[TestFixture] -public class VersionWriterTests : TestBase -{ - private readonly IVersionWriter versionWriter; - - public VersionWriterTests() - { - var sp = ConfigureServices(services => services.AddModule(new GitVersionAppModule(useLegacyParser: true))); - - this.versionWriter = sp.GetRequiredService(); - } - [Test] - public void WriteVersionShouldWriteFileVersionWithNoPrereleaseTag() - { - var asm = GenerateAssembly(new Version(1, 0, 0), ""); - - var version = string.Empty; - this.versionWriter.WriteTo(asm, v => version = v); - Assert.Multiple(() => - { - Assert.That(asm, Is.Not.Null); - Assert.That(version, Is.EqualTo("1.0.0")); - }); - } - - [Test] - public void WriteVersionShouldWriteFileVersionWithPrereleaseTag() - { - var asm = GenerateAssembly(new Version(1, 0, 0), "-beta4"); - - var version = string.Empty; - this.versionWriter.WriteTo(asm, v => version = v); - Assert.Multiple(() => - { - Assert.That(asm, Is.Not.Null); - Assert.That(version, Is.EqualTo("1.0.0-beta4")); - }); - } - - private static Assembly GenerateAssembly(Version fileVersion, string prereleaseInfo) - { - var attribute = typeof(AssemblyInformationalVersionAttribute); - var csharpCode = $"""[assembly: {attribute.FullName}("{fileVersion + prereleaseInfo}")]"""; - var compilation = CSharpCompilation.Create("test-asm") - .WithOptions(new(OutputKind.DynamicallyLinkedLibrary)) - .AddReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location)) - .AddReferences(MetadataReference.CreateFromFile(attribute.Assembly.Location)) - .AddSyntaxTrees(CSharpSyntaxTree.ParseText(csharpCode)); - - using var memoryStream = new MemoryStream(); - compilation.Emit(memoryStream); - - return Assembly.Load(memoryStream.ToArray()); - } -} diff --git a/src/GitVersion.App/ArgumentParser.cs b/src/GitVersion.App/ArgumentParser.cs index 605b2052ce..6b93812233 100644 --- a/src/GitVersion.App/ArgumentParser.cs +++ b/src/GitVersion.App/ArgumentParser.cs @@ -237,10 +237,7 @@ private static Arguments MapMigrationValues(ParseResult parseResult, CommandOpti /// Maps a v7 configuration property query while accepting the global telemetry opt-out. private Arguments MapQueryValues(ParseResult parseResult, CommandOptions options, RootCommand rootCommand) { - if (ConfigurationVersionSelector.Resolve() != ConfigurationVersion.V7) - { - throw new WarningException("Configuration property queries require v7 configuration. Set GITVERSION_CONFIGURATION_VERSION=v7."); - } + _ = ConfigurationVersionSelector.Resolve(); var unsupportedOption = rootCommand.Options.Except(options.Get.Options).Where(option => option != options.TelemetryOptOut) .FirstOrDefault(option => parseResult.GetResult(option) is { Implicit: false }); diff --git a/src/GitVersion.App/ArgumentParserVersion.cs b/src/GitVersion.App/ArgumentParserVersion.cs index e67569f6ef..041dd6f4be 100644 --- a/src/GitVersion.App/ArgumentParserVersion.cs +++ b/src/GitVersion.App/ArgumentParserVersion.cs @@ -2,7 +2,6 @@ namespace GitVersion; internal enum ArgumentParserVersion { - V6, V7 } @@ -16,11 +15,16 @@ public static ArgumentParserVersion Resolve() if (SysEnv.GetEnvironmentVariable(RetiredEnvironmentVariableName) is not null) { throw new WarningException( - $"{RetiredEnvironmentVariableName} has been removed. Unset it and use {EnvironmentVariableName}=v6 for the temporary legacy parser, or {EnvironmentVariableName}=v7 (the default)."); + $"{RetiredEnvironmentVariableName} has been removed. Unset it and use POSIX-style arguments with {EnvironmentVariableName}=v7 (the default)."); } - return FeatureSelector.Resolve(EnvironmentVariableName, "v7", "v6", "v7") == "v6" - ? ArgumentParserVersion.V6 - : ArgumentParserVersion.V7; + var value = SysEnv.GetEnvironmentVariable(EnvironmentVariableName)?.Trim().ToLowerInvariant(); + if (value == "v6") + { + throw new WarningException($"{EnvironmentVariableName}=v6 was removed in GitVersion 7.1. Use POSIX-style arguments and unset this variable or set it to v7."); + } + + _ = FeatureSelector.Resolve(EnvironmentVariableName, "v7", "v7"); + return ArgumentParserVersion.V7; } } diff --git a/src/GitVersion.App/CliHost.cs b/src/GitVersion.App/CliHost.cs index cd4fb38749..d4f5d5e700 100644 --- a/src/GitVersion.App/CliHost.cs +++ b/src/GitVersion.App/CliHost.cs @@ -36,12 +36,12 @@ private static void RegisterGitVersionModules(IServiceCollection services, strin services.AddModule(new GitVersionBuildAgentsModule()); services.AddModule(new GitVersionConfigurationModule()); services.AddModule(new GitVersionOutputModule()); - services.AddModule(new GitVersionTelemetryModule(selections.ArgumentParser == ArgumentParserVersion.V6)); + services.AddModule(new GitVersionTelemetryModule()); services.AddModule(selections.GitBackend == GitBackend.Managed ? new GitVersionManagedGitModule() : new GitVersionLibGit2SharpModule()); - services.AddModule(new GitVersionAppModule(args, selections.ArgumentParser == ArgumentParserVersion.V6)); + services.AddModule(new GitVersionAppModule(args)); } } diff --git a/src/GitVersion.App/ConfigurationQueryExecutor.cs b/src/GitVersion.App/ConfigurationQueryExecutor.cs index 854fca09ad..3386afb472 100644 --- a/src/GitVersion.App/ConfigurationQueryExecutor.cs +++ b/src/GitVersion.App/ConfigurationQueryExecutor.cs @@ -25,18 +25,14 @@ public bool TryExecute(GitVersionOptions gitVersionOptions) return false; } - var version = ConfigurationVersionSelector.Resolve(); - if (configurationInfo.PropertyPath is not null && version != ConfigurationVersion.V7) - { - throw new ConfigurationException("Configuration property queries require v7 configuration. Set GITVERSION_CONFIGURATION_VERSION=v7."); - } + _ = ConfigurationVersionSelector.Resolve(); if (gitVersionOptions.RepositoryInfo.TargetUrl.IsNullOrWhiteSpace()) { this.configurationFileLocator.Verify(gitVersionOptions.WorkingDirectory, this.repositoryInfo.ProjectRootDirectory); } - var configurationValue = this.configurationProvider.Provide(version == ConfigurationVersion.V7 ? configurationInfo.OverrideConfiguration : null); + var configurationValue = this.configurationProvider.Provide(configurationInfo.OverrideConfiguration); var serializedConfiguration = configurationInfo.PropertyPath is { } path ? this.configurationSerializer.SerializeProperty(configurationValue, path) : this.configurationSerializer.Serialize(configurationValue); diff --git a/src/GitVersion.App/ConfigurationValidationExecutor.cs b/src/GitVersion.App/ConfigurationValidationExecutor.cs index d2d13dcf3b..2c148530f1 100644 --- a/src/GitVersion.App/ConfigurationValidationExecutor.cs +++ b/src/GitVersion.App/ConfigurationValidationExecutor.cs @@ -25,10 +25,7 @@ public int Execute(GitVersionOptions options) ValidateInvocation(options); file = SelectFile(options); ValidateFile(file, info.ValidationOverrides); - if (ConfigurationVersionSelector.IsExplicitV6()) - { - diagnostics.Add(new("GVCONFIG_V6_COMPATIBILITY", "warning", "", "Temporary v6 compatibility mode is removed in GitVersion 7.1. Run 'gitversion config migrate' and validate with GITVERSION_CONFIGURATION_VERSION=v7.")); - } + } catch (ConfigurationValidationException exception) { diff --git a/src/GitVersion.App/FeatureSelections.cs b/src/GitVersion.App/FeatureSelections.cs index 631d7072e5..0363fc23d7 100644 --- a/src/GitVersion.App/FeatureSelections.cs +++ b/src/GitVersion.App/FeatureSelections.cs @@ -11,7 +11,7 @@ internal sealed record FeatureSelections(ArgumentParserVersion ArgumentParser, C public void Log(ILogger logger) => logger.LogInformation( "Argument parser version: {ArgumentParserVersion}; Configuration version: {ConfigurationVersion}; Git backend: {GitBackend}", - ArgumentParser == ArgumentParserVersion.V6 ? "v6" : "v7", - Configuration == ConfigurationVersion.V6 ? "v6" : "v7", + "v7", + "v7", GitBackend == GitBackend.Managed ? "managed" : "libgit2"); } diff --git a/src/GitVersion.App/GitVersion.App.csproj b/src/GitVersion.App/GitVersion.App.csproj index e816b7fe99..5220ee4af1 100644 --- a/src/GitVersion.App/GitVersion.App.csproj +++ b/src/GitVersion.App/GitVersion.App.csproj @@ -41,10 +41,6 @@ - - - - diff --git a/src/GitVersion.App/GitVersionAppModule.cs b/src/GitVersion.App/GitVersionAppModule.cs index ad9b169d92..57500241d8 100644 --- a/src/GitVersion.App/GitVersionAppModule.cs +++ b/src/GitVersion.App/GitVersionAppModule.cs @@ -4,22 +4,13 @@ namespace GitVersion; /// Registers CLI services and the allowlisted invocation projection used by telemetry. -internal class GitVersionAppModule(string[]? args = null, bool useLegacyParser = false) : IGitVersionModule +internal class GitVersionAppModule(string[]? args = null) : IGitVersionModule { /// Registers argument parsing, execution, and the deferred telemetry argument projection. public void RegisterTypes(IServiceCollection services) { - if (useLegacyParser) - { - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - } - else - { - services.AddSingleton(); - services.AddSingleton(); - } + services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); diff --git a/src/GitVersion.App/HelpWriter.cs b/src/GitVersion.App/HelpWriter.cs deleted file mode 100644 index 7f95db3398..0000000000 --- a/src/GitVersion.App/HelpWriter.cs +++ /dev/null @@ -1,38 +0,0 @@ -using GitVersion.Extensions; - -namespace GitVersion; - -internal class HelpWriter(IVersionWriter versionWriter, IConsole console) : IHelpWriter -{ - private readonly IVersionWriter versionWriter = versionWriter.NotNull(); - private readonly IConsole console = console.NotNull(); - - public void Write() => WriteTo(this.console.WriteLine); - - public void WriteTo(Action writeAction) - { - var version = string.Empty; - var assembly = Assembly.GetExecutingAssembly(); - this.versionWriter.WriteTo(assembly, v => version = v); - - var args = LegacyArgumentList(); - var message = $""" - GitVersion {version} - - {args} - """; - - writeAction(message); - } - - private string LegacyArgumentList() - { - using var argumentsMarkdownStream = GetType().Assembly.GetManifestResourceStream("GitVersion.legacy_help.md"); - argumentsMarkdownStream.NotNull(); - using var sr = new StreamReader(argumentsMarkdownStream); - var argsMarkdown = sr.ReadToEnd(); - var codeBlockStart = argsMarkdown.IndexOf("```bash", StringComparison.Ordinal) + 7; - var codeBlockEnd = argsMarkdown.LastIndexOf("```", StringComparison.Ordinal) - codeBlockStart; - return argsMarkdown.Substring(codeBlockStart, codeBlockEnd).Trim(); - } -} diff --git a/src/GitVersion.App/IHelpWriter.cs b/src/GitVersion.App/IHelpWriter.cs deleted file mode 100644 index 652badd469..0000000000 --- a/src/GitVersion.App/IHelpWriter.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace GitVersion; - -internal interface IHelpWriter -{ - void Write(); - void WriteTo(Action writeAction); -} diff --git a/src/GitVersion.App/IVersionWriter.cs b/src/GitVersion.App/IVersionWriter.cs deleted file mode 100644 index cadaec1b79..0000000000 --- a/src/GitVersion.App/IVersionWriter.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace GitVersion; - -internal interface IVersionWriter -{ - void Write(Assembly assembly); - void WriteTo(Assembly assembly, Action writeAction); -} diff --git a/src/GitVersion.App/LegacyArgumentParser.cs b/src/GitVersion.App/LegacyArgumentParser.cs deleted file mode 100644 index 5a5dedd895..0000000000 --- a/src/GitVersion.App/LegacyArgumentParser.cs +++ /dev/null @@ -1,659 +0,0 @@ -using System.IO.Abstractions; -using GitVersion.Extensions; -using GitVersion.FileSystemGlobbing; -using GitVersion.Helpers; -using GitVersion.Logging; -using GitVersion.OutputVariables; -using Serilog.Core; -using Serilog.Events; - -namespace GitVersion; - -internal class LegacyArgumentParser( - IEnvironment environment, - IFileSystem fileSystem, - IConsole console, - IHelpWriter helpWriter, - IVersionWriter versionWriter, - IGlobbingResolver globbingResolver, - LoggingLevelSwitch loggingLevelSwitch -) - : IArgumentParser -{ - private readonly IEnvironment environment = environment.NotNull(); - private readonly IFileSystem fileSystem = fileSystem.NotNull(); - private readonly IConsole console = console.NotNull(); - private readonly IHelpWriter helpWriter = helpWriter.NotNull(); - private readonly IVersionWriter versionWriter = versionWriter.NotNull(); - private readonly IGlobbingResolver globbingResolver = globbingResolver.NotNull(); - private readonly LoggingLevelSwitch loggingLevelSwitch = loggingLevelSwitch.NotNull(); - - private const string defaultOutputFileName = "GitVersion.json"; - private static readonly IEnumerable availableVariables = GitVersionVariables.AvailableVariables; - - private static readonly Dictionary VerbosityMaps = new() - { - { Verbosity.Verbose, LogEventLevel.Verbose }, - { Verbosity.Diagnostic, LogEventLevel.Debug }, - { Verbosity.Normal, LogEventLevel.Information }, - { Verbosity.Minimal, LogEventLevel.Warning }, - { Verbosity.Quiet, LogEventLevel.Error } - }; - - public Arguments ParseArguments(string commandLineArguments) - { - var arguments = QuotedStringHelpers.SplitUnquoted(commandLineArguments, ' '); - - return ParseArguments(arguments); - } - - public Arguments ParseArguments(string[] commandLineArguments) - { - if (commandLineArguments.Length == 0) - { - var args = new Arguments - { - TargetPath = SysEnv.CurrentDirectory - }; - - args.Output.Add(OutputType.Json); - - AddAuthentication(args); - - return args; - } - - var firstArgument = commandLineArguments[0]; - - if (firstArgument.IsHelp()) - { - this.helpWriter.Write(); - return new Arguments { IsHelp = true }; - } - - if (firstArgument.IsSwitch("version")) - { - var assembly = Assembly.GetExecutingAssembly(); - this.versionWriter.Write(assembly); - return new Arguments { IsVersion = true }; - } - - if (firstArgument.Equals("config", StringComparison.OrdinalIgnoreCase) - && commandLineArguments.Skip(1).FirstOrDefault()?.Equals("migrate", StringComparison.OrdinalIgnoreCase) == true) - { - throw new WarningException("The 'config migrate' command is only available with the POSIX argument parser."); - } - - var arguments = new Arguments(); - - AddAuthentication(arguments); - - var switchesAndValues = CollectSwitchesAndValuesFromArguments(commandLineArguments, out var firstArgumentIsSwitch); - - for (var i = 0; i < switchesAndValues.AllKeys.Length; i++) - { - ParseSwitchArguments(arguments, switchesAndValues, i); - } - - if (arguments.Output.Count == 0) - { - arguments.Output.Add(OutputType.Json); - } - - if (arguments.Output.Contains(OutputType.File) && arguments.OutputFile == null) - { - arguments.OutputFile = defaultOutputFileName; - } - - // If the first argument is a switch, it should already have been consumed in the above loop, - // or else a WarningException should have been thrown and we wouldn't end up here. - arguments.TargetPath ??= firstArgumentIsSwitch - ? SysEnv.CurrentDirectory - : firstArgument; - - arguments.TargetPath = arguments.TargetPath.TrimEnd('/', '\\'); - - if (!arguments.EnsureAssemblyInfo) - { - arguments.UpdateAssemblyInfoFileName = ResolveFiles(arguments.TargetPath, arguments.UpdateAssemblyInfoFileName).ToHashSet(); - } - - ValidateConfigurationFile(arguments); - - return arguments; - } - - private void ValidateConfigurationFile(Arguments arguments) - { - if (arguments.ConfigurationFile.IsNullOrWhiteSpace()) - { - return; - } - - if (FileSystemHelper.Path.IsPathRooted(arguments.ConfigurationFile)) - { - if (!this.fileSystem.File.Exists(arguments.ConfigurationFile)) - { - throw new WarningException($"Could not find config file at '{arguments.ConfigurationFile}'"); - } - - arguments.ConfigurationFile = FileSystemHelper.Path.GetFullPath(arguments.ConfigurationFile); - } - else - { - var configFilePath = FileSystemHelper.Path.GetFullPath(FileSystemHelper.Path.Combine(arguments.TargetPath, arguments.ConfigurationFile)); - if (!this.fileSystem.File.Exists(configFilePath)) - { - throw new WarningException($"Could not find config file at '{configFilePath}'"); - } - - arguments.ConfigurationFile = configFilePath; - } - } - - private void ParseSwitchArguments(Arguments arguments, NameValueCollection switchesAndValues, int i) // NOSONAR: Calls instance parsing methods that use injected services. - { - var name = switchesAndValues.AllKeys[i]; - var values = switchesAndValues.GetValues(name); - var value = values?.FirstOrDefault(); - - if (ParseSwitches(arguments, name, values, value)) - { - return; - } - - ParseTargetPath(arguments, name, values, value, i == 0); - } - - private void AddAuthentication(Arguments arguments) - { - var username = this.environment.GetEnvironmentVariable("GITVERSION_REMOTE_USERNAME"); - if (!username.IsNullOrWhiteSpace()) - { - arguments.Authentication.Username = username; - } - - var password = this.environment.GetEnvironmentVariable("GITVERSION_REMOTE_PASSWORD"); - if (!password.IsNullOrWhiteSpace()) - { - arguments.Authentication.Password = password; - } - } - - private IEnumerable ResolveFiles(string workingDirectory, ISet? assemblyInfoFiles) - { - if (assemblyInfoFiles == null) - { - yield break; - } - - foreach (var file in assemblyInfoFiles) - { - foreach (var path in this.globbingResolver.Resolve(workingDirectory, file)) - { - yield return path; - } - } - } - - private void ParseTargetPath(Arguments arguments, string? name, IReadOnlyList? values, string? value, bool parseEnded) - { - if (name.IsSwitch("targetpath")) - { - EnsureArgumentValueCount(values); - arguments.TargetPath = value; - if (string.IsNullOrWhiteSpace(value) || !this.fileSystem.Directory.Exists(value)) - { - this.console.WriteLine($"The working directory '{value}' does not exist."); - } - - return; - } - - var couldNotParseMessage = $"Could not parse command line parameter '{name}'."; - - // If we've reached through all argument switches without a match, we can relatively safely assume that the first argument isn't a switch, but the target path. - if (!parseEnded) - { - throw new WarningException(couldNotParseMessage); - } - - if (name is not null && name.StartsWith('/')) - { - if (FileSystemHelper.Path.DirectorySeparatorChar == '/' && name.IsValidPath()) - { - arguments.TargetPath = name; - return; - } - } - else if (name is null || !name.IsSwitchArgument()) - { - arguments.TargetPath = name; - return; - } - - couldNotParseMessage += " If it is the target path, make sure it exists."; - - throw new WarningException(couldNotParseMessage); - } - - private bool ParseSwitches(Arguments arguments, string? name, IReadOnlyList? values, string? value) - { - if (name.IsSwitch("l")) - { - EnsureArgumentValueCount(values); - arguments.LogFilePath = value; - return true; - } - - if (ParseConfigArguments(arguments, name, values, value)) - { - return true; - } - - if (ParseRemoteArguments(arguments, name, values, value)) - { - return true; - } - - if (ParseBooleanArguments(arguments, name)) - { - return true; - } - - if (name.IsSwitch("updateprojectfiles")) - { - ParseUpdateProjectInfo(arguments, value, values); - return true; - } - - if (name.IsSwitch("updateAssemblyInfo")) - { - ParseUpdateAssemblyInfo(arguments, value, values); - return true; - } - - if (name.IsSwitch("ensureassemblyinfo")) - { - ParseEnsureAssemblyInfo(arguments, value); - return true; - } - - if (name.IsSwitch("v") || name.IsSwitch("showvariable")) - { - ParseShowVariable(arguments, value, name); - return true; - } - - if (name.IsSwitch("format")) - { - ParseFormat(arguments, value); - return true; - } - - if (name.IsSwitch("output")) - { - ParseOutput(arguments, values); - return true; - } - - if (name.IsSwitch("outputfile")) - { - EnsureArgumentValueCount(values); - arguments.OutputFile = value; - return true; - } - - if (!name.IsSwitch("verbosity")) - { - return false; - } - - var verbosity = ParseVerbosity(value); - this.loggingLevelSwitch.MinimumLevel = VerbosityMaps[verbosity]; - return true; - } - - private static bool ParseBooleanArguments(Arguments arguments, string? name) - { - if (name.IsSwitch("diag")) - { - arguments.Diag = true; - return true; - } - - if (name.IsSwitch("nofetch")) - { - arguments.NoFetch = true; - return true; - } - - if (name.IsSwitch("nonormalize")) - { - arguments.NoNormalize = true; - return true; - } - - if (name.IsSwitch("nocache")) - { - arguments.NoCache = true; - return true; - } - - if (name.IsSwitch("allowshallow")) - { - arguments.AllowShallow = true; - return true; - } - - if (!name.IsSwitch("updatewixversionfile")) - { - return false; - } - - arguments.UpdateWixVersionFile = true; - return true; - } - - private static bool ParseConfigArguments(Arguments arguments, string? name, IReadOnlyList? values, string? value) - { - if (name.IsSwitch("config")) - { - EnsureArgumentValueCount(values); - arguments.ConfigurationFile = value; - return true; - } - - if (name.IsSwitch("overrideconfig")) - { - ParseOverrideConfig(arguments, values); - return true; - } - - if (!name.IsSwitch("showConfig")) - { - return false; - } - - arguments.ShowConfiguration = value.IsTrue() || !value.IsFalse(); - return true; - } - - private static bool ParseRemoteArguments(Arguments arguments, string? name, IReadOnlyList? values, string? value) - { - if (name.IsSwitch("dynamicRepoLocation")) - { - EnsureArgumentValueCount(values); - arguments.ClonePath = value; - return true; - } - - if (name.IsSwitch("url")) - { - EnsureArgumentValueCount(values); - arguments.TargetUrl = value; - return true; - } - - if (name.IsSwitch("u")) - { - EnsureArgumentValueCount(values); - arguments.Authentication.Username = value; - return true; - } - - if (name.IsSwitch("p")) - { - EnsureArgumentValueCount(values); - arguments.Authentication.Password = value; - return true; - } - - if (name.IsSwitch("c")) - { - EnsureArgumentValueCount(values); - arguments.CommitId = value; - return true; - } - - if (!name.IsSwitch("b")) - { - return false; - } - - EnsureArgumentValueCount(values); - arguments.TargetBranch = value; - return true; - } - - private static void ParseShowVariable(Arguments arguments, string? value, string? name) - { - string? versionVariable = null; - - if (!value.IsNullOrWhiteSpace()) - { - versionVariable = availableVariables.SingleOrDefault(av => av.Equals(value.Replace("'", ""), StringComparison.CurrentCultureIgnoreCase)); - } - - if (versionVariable == null) - { - var message = $"{name} requires a valid version variable. Available variables are:{FileSystemHelper.Path.NewLine}" + - string.Join(", ", availableVariables.Select(x => $"'{x}'")); - throw new WarningException(message); - } - - arguments.ShowVariable = versionVariable; - } - - private static void ParseFormat(Arguments arguments, string? value) - { - if (value.IsNullOrWhiteSpace()) - { - throw new WarningException("Format requires a valid format string. Available variables are: " + string.Join(", ", availableVariables)); - } - - var foundVariable = availableVariables.Any(variable => value.Contains(variable, StringComparison.CurrentCultureIgnoreCase)); - - if (!foundVariable) - { - throw new WarningException("Format requires a valid format string. Available variables are: " + string.Join(", ", availableVariables)); - } - - arguments.Format = value; - } - - private static void ParseEnsureAssemblyInfo(Arguments arguments, string? value) - { - arguments.EnsureAssemblyInfo = true; - if (value.IsFalse()) - { - arguments.EnsureAssemblyInfo = false; - } - - if (arguments.UpdateProjectFiles) - { - throw new WarningException("Cannot specify -ensureassemblyinfo with updateprojectfiles: please ensure your project file exists before attempting to update it"); - } - - if (arguments.UpdateAssemblyInfoFileName.Count > 1 && arguments.EnsureAssemblyInfo) - { - throw new WarningException("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"); - } - } - - private static void ParseOutput(Arguments arguments, IEnumerable? values) - { - if (values == null) - { - return; - } - - foreach (var v in values) - { - if (!Enum.TryParse(v, true, out OutputType outputType)) - { - throw new WarningException($"Value '{v}' cannot be parsed as output type, please use 'json', 'file', 'buildserver' or 'dotenv'"); - } - - arguments.Output.Add(outputType); - } - } - - internal static Verbosity ParseVerbosity(string? value) - { - if (!Enum.TryParse(value, true, out Verbosity verbosity)) - { - throw new WarningException($"Could not parse Verbosity value '{value}'"); - } - - return verbosity; - } - - private static void ParseOverrideConfig(Arguments arguments, IReadOnlyCollection? values) - { - if (values == null || values.Count == 0) - { - return; - } - - var parser = new OverrideConfigurationOptionParser(); - parser.SetValues(values, "/overrideconfig"); - arguments.OverrideConfiguration = parser.GetOverrideConfiguration(); - } - - private static void ParseUpdateAssemblyInfo(Arguments arguments, string? value, IReadOnlyCollection? values) - { - if (value.IsTrue()) - { - arguments.UpdateAssemblyInfo = true; - } - else if (value.IsFalse()) - { - arguments.UpdateAssemblyInfo = false; - } - else if (values is { Count: > 1 }) - { - arguments.UpdateAssemblyInfo = true; - foreach (var v in values) - { - arguments.UpdateAssemblyInfoFileName.Add(v); - } - } - else if (!value.IsSwitchArgument()) - { - arguments.UpdateAssemblyInfo = true; - if (value != null) - { - arguments.UpdateAssemblyInfoFileName.Add(value); - } - } - else - { - arguments.UpdateAssemblyInfo = true; - } - - if (arguments.UpdateProjectFiles) - { - throw new WarningException("Cannot specify both updateprojectfiles and updateassemblyinfo in the same run. Please rerun GitVersion with only one parameter"); - } - - if (arguments.UpdateAssemblyInfoFileName.Count > 1 && arguments.EnsureAssemblyInfo) - { - throw new WarningException("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"); - } - } - - private static void ParseUpdateProjectInfo(Arguments arguments, string? value, IReadOnlyCollection? values) - { - if (value.IsTrue()) - { - arguments.UpdateProjectFiles = true; - } - else if (value.IsFalse()) - { - arguments.UpdateProjectFiles = false; - } - else if (values is { Count: > 1 }) - { - arguments.UpdateProjectFiles = true; - foreach (var v in values) - { - arguments.UpdateAssemblyInfoFileName.Add(v); - } - } - else if (!value.IsSwitchArgument()) - { - arguments.UpdateProjectFiles = true; - if (value != null) - { - arguments.UpdateAssemblyInfoFileName.Add(value); - } - } - else - { - arguments.UpdateProjectFiles = true; - } - - if (arguments.UpdateAssemblyInfo) - { - throw new WarningException("Cannot specify both updateassemblyinfo and updateprojectfiles in the same run. Please rerun GitVersion with only one parameter"); - } - - if (arguments.EnsureAssemblyInfo) - { - throw new WarningException("Cannot specify -ensureassemblyinfo with updateprojectfiles: please ensure your project file exists before attempting to update it"); - } - } - - private static void EnsureArgumentValueCount(IReadOnlyList? values) - { - if (values is { Count: > 1 }) - { - throw new WarningException($"Could not parse command line parameter '{values[1]}'."); - } - } - - private static NameValueCollection CollectSwitchesAndValuesFromArguments(string[] namedArguments, out bool firstArgumentIsSwitch) - { - firstArgumentIsSwitch = true; - var switchesAndValues = new NameValueCollection(); - string? currentKey = null; - var argumentRequiresValue = false; - - for (var i = 0; i < namedArguments.Length; ++i) - { - var arg = namedArguments[i]; - - // If the current (previous) argument doesn't require a value parameter and this is a switch, create new name/value entry for it, with a null value. - if (!argumentRequiresValue && arg.IsSwitchArgument()) - { - currentKey = arg; - argumentRequiresValue = arg.ArgumentRequiresValue(i); - switchesAndValues.Add(currentKey, null); - } - // If this is a value (not a switch) - else if (currentKey != null) - { - // And if the current switch does not have a value yet and the value is not itself a switch, set its value to this argument. - if (switchesAndValues[currentKey].IsNullOrEmpty()) - { - switchesAndValues[currentKey] = arg; - } - // Otherwise add the value under the same switch. - else - { - switchesAndValues.Add(currentKey, arg); - } - - // Reset the boolean argument flag so the next argument won't be ignored. - argumentRequiresValue = false; - } - else if (i == 0) - { - firstArgumentIsSwitch = false; - } - } - - return switchesAndValues; - } -} diff --git a/src/GitVersion.App/OverrideConfigurationOptionParser.cs b/src/GitVersion.App/OverrideConfigurationOptionParser.cs index a0eea8641d..ae96ce1e54 100644 --- a/src/GitVersion.App/OverrideConfigurationOptionParser.cs +++ b/src/GitVersion.App/OverrideConfigurationOptionParser.cs @@ -55,7 +55,7 @@ private static bool IsSupportedPropertyType(Type propertyType) private static bool TryNormalizeAndValidate(string key, out string normalizedKey, out string? error) { - var version = ConfigurationVersionSelector.Resolve(); + _ = ConfigurationVersionSelector.Resolve(); var segments = key.Split('.'); NormalizeSegments(segments); normalizedKey = string.Join('.', segments); @@ -67,13 +67,13 @@ private static bool TryNormalizeAndValidate(string key, out string normalizedKey return false; } - if (IsValidPath(version, segments)) + if (IsValidPath(segments)) { error = null; return true; } - var replacement = GetReplacement(version, segments); + var replacement = GetReplacement(segments); error = replacement is null ? $"Unsupported key '{normalizedKey}'." : $"Key '{normalizedKey}' is not valid in the selected configuration structure. Use '{replacement}' instead. " + @@ -135,24 +135,13 @@ private static HashSet GetSupportedBranchProperties() => typeof(BranchCo .OfType() .ToHashSet(StringComparer.Ordinal); - private static bool IsValidPath(ConfigurationVersion version, IReadOnlyList segments) + private static bool IsValidPath(IReadOnlyList segments) { if (segments.Count == 1 && segments[0] == ConfigurationDocumentMapper.WorkflowPropertyName) { return true; } - if (version == ConfigurationVersion.V6) - { - return segments.Count switch - { - 1 => SupportedProperties.Contains(segments[0]), - 3 when segments[0] == ConfigurationDocumentMapper.BranchesPropertyName - => _lazySupportedBranchProperties.Value.Contains(segments[2]), - _ => false - }; - } - if (segments.Count == 2 && IsSection(segments[0])) { return segments[1] != ConfigurationDocumentMapper.WorkflowPropertyName @@ -167,10 +156,7 @@ private static bool IsValidPath(ConfigurationVersion version, IReadOnlyList segments) => - version == ConfigurationVersion.V7 - ? GetV7Replacement(segments) - : GetV6Replacement(segments); + private static string? GetReplacement(IReadOnlyList segments) => GetV7Replacement(segments); private static string? GetV7Replacement(IReadOnlyList segments) { @@ -199,16 +185,6 @@ private static bool IsValidPath(ConfigurationVersion version, IReadOnlyList segments) - { - if (IsNestedRootPath(segments)) - { - return segments[1]; - } - - return IsNestedBranchPath(segments) ? string.Join('.', segments.Skip(1)) : null; - } - private static bool IsFlatRootPath(IReadOnlyList segments) => segments.Count == 1 && SupportedProperties.Contains(segments[0]); diff --git a/src/GitVersion.App/VersionWriter.cs b/src/GitVersion.App/VersionWriter.cs deleted file mode 100644 index d1f0a1ebb0..0000000000 --- a/src/GitVersion.App/VersionWriter.cs +++ /dev/null @@ -1,28 +0,0 @@ -using GitVersion.Extensions; - -namespace GitVersion; - -internal class VersionWriter(IConsole console) : IVersionWriter -{ - private readonly IConsole console = console.NotNull(); - - public void Write(Assembly assembly) => WriteTo(assembly, this.console.WriteLine); - - public void WriteTo(Assembly assembly, Action writeAction) - { - var version = GetAssemblyVersion(assembly); - writeAction(version); - } - - private static string? GetAssemblyVersion(Assembly assembly) - { - if (assembly - .GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false) - .FirstOrDefault() is AssemblyInformationalVersionAttribute attribute) - { - return attribute.InformationalVersion; - } - - return assembly.GetName().Version?.ToString(); - } -} diff --git a/src/GitVersion.App/legacy_help.md b/src/GitVersion.App/legacy_help.md deleted file mode 100644 index f7b5879c3f..0000000000 --- a/src/GitVersion.App/legacy_help.md +++ /dev/null @@ -1,86 +0,0 @@ -```bash -Use convention to derive a SemVer product version from a GitFlow or GitHub based -repository. - -GitVersion [path] - - path The directory containing .git. If not defined current - directory is used. (Must be first argument) - /version Displays the version of GitVersion - /diag Runs GitVersion with additional diagnostic information; - also needs the '/l' argument to specify a logfile or stdout - (requires git.exe to be installed) - /h or /? Shows Help - - /targetpath Same as 'path', but not positional - /output Determines the output to the console. Can be either 'json', - 'file', 'buildserver' or 'dotenv', will default to 'json'. - /outputfile Path to output file. It is used in combination with /output - 'file'. - /showvariable Used in conjunction with /output json, will output just a - particular variable. E.g. /output json /showvariable SemVer - - will output `1.2.3+beta.4` - /format Used in conjunction with /output json, will output a format - containing version variables. - Supports C# format strings - see [Format Strings](/docs/reference/custom-formatting) for details. - E.g. /output json /format {SemVer} - will output `1.2.3+beta.4` - /output json /format {Major}.{Minor} - will output `1.2` - /l Path to logfile; specify 'console' to emit to stderr. - /config Path to config file (defaults to GitVersion.yml, GitVersion.yaml, .GitVersion.yml or .GitVersion.yaml) - /showconfig Outputs the effective GitVersion config (defaults + custom - from GitVersion.yml, GitVersion.yaml, .GitVersion.yml or .GitVersion.yaml) in yaml format - /overrideconfig Overrides GitVersion config values inline (semicolon- - separated key value pairs e.g. /overrideconfig - tag-prefix=Foo) - Currently supported config overrides: tag-prefix - /nocache Bypasses the cache, result will not be written to the cache. - /nonormalize Disables normalize step on a build server. - /allowshallow Allows GitVersion to run on a shallow clone. - This is not recommended, but can be used if you are sure - that the shallow clone contains all the information needed - to calculate the version. - /verbosity Specifies the amount of information to be displayed. - (Quiet, Minimal, Normal, Verbose, Diagnostic) - Default is Normal - -# AssemblyInfo updating - - /updateassemblyinfo - Will recursively search for all 'AssemblyInfo.cs' files in - the git repo and update them - /updateprojectfiles - Will recursively search for all project files - (.csproj/.vbproj/.fsproj/.sqlproj) files in the git repo and update - them - Note: This is only compatible with the newer Sdk projects - /ensureassemblyinfo - If the assembly info file specified with - /updateassemblyinfo is not - found, it will be created with these attributes: - AssemblyFileVersion, AssemblyVersion and - AssemblyInformationalVersion. - Supports writing version info for: C#, F#, VB - -# Create or update Wix version file - - /updatewixversionfile - All the GitVersion variables are written to - 'GitVersion_WixVersion.wxi'. The variables can then be - referenced in other WiX project files for versioning. - -# Remote repository args - - /url Url to remote git repository. - /b Target branch to version (local or with /url). Takes - precedence over GIT_BRANCH/Git_Branch, which only supply - branch context at HEAD. - /u Username in case authentication is required. - /p Password in case authentication is required. - /c The commit id to check. If not specified, the latest - available commit on the specified branch will be used. - /dynamicRepoLocation - By default dynamic repositories will be cloned to %tmp%. - Use this switch to override - /nofetch Disables 'git fetch' during version calculation. Might cause - GitVersion to not calculate your version as expected. -``` diff --git a/src/GitVersion.Configuration.Tests/Configuration/ConfigurationDocumentMapperTests.cs b/src/GitVersion.Configuration.Tests/Configuration/ConfigurationDocumentMapperTests.cs index 1a462528d1..67bbf4fc49 100644 --- a/src/GitVersion.Configuration.Tests/Configuration/ConfigurationDocumentMapperTests.cs +++ b/src/GitVersion.Configuration.Tests/Configuration/ConfigurationDocumentMapperTests.cs @@ -109,7 +109,7 @@ public void FlattensAndMergesCalculationAndOutputBranches() } [Test] - public void RejectsMixedAndSelectedVersionMismatches() + public void RejectsFlatAndMixedRuntimeDocuments() { Dictionary flat = new() { ["tag-prefix"] = "v" }; Dictionary nested = new() { ["calculation"] = new Dictionary() }; @@ -120,11 +120,10 @@ public void RejectsMixedAndSelectedVersionMismatches() }; Should.Throw(() => - ConfigurationDocumentMapper.Normalize(flat, ConfigurationVersion.V7, "test")); + ConfigurationDocumentMapper.Normalize(flat, "test")); + ConfigurationDocumentMapper.Normalize(nested, "test").ShouldBeEmpty(); Should.Throw(() => - ConfigurationDocumentMapper.Normalize(nested, ConfigurationVersion.V6, "test")); - Should.Throw(() => - ConfigurationDocumentMapper.Normalize(mixed, ConfigurationVersion.V7, "test")); + ConfigurationDocumentMapper.Normalize(mixed, "test")); } [Test] @@ -151,11 +150,9 @@ public void RejectsPropertiesInTheWrongV7SectionWithReplacement() .Message.ShouldContain("calculation.branches..increment"); } - [TestCase(false, false)] - [TestCase(false, true)] - [TestCase(true, false)] - [TestCase(true, true)] - public void AcceptsEmptyAndWorkflowOnlyDocumentsInEitherVersion(bool v7, bool hasWorkflow) + [TestCase(false)] + [TestCase(true)] + public void AcceptsEmptyAndWorkflowOnlyDocuments(bool hasWorkflow) { Dictionary document = []; if (hasWorkflow) @@ -164,7 +161,7 @@ public void AcceptsEmptyAndWorkflowOnlyDocumentsInEitherVersion(bool v7, bool ha } ConfigurationDocumentMapper.Detect(document).ShouldBe(hasWorkflow ? ConfigurationDocumentKind.Shared : ConfigurationDocumentKind.Empty); - var normalized = ConfigurationDocumentMapper.Normalize(document, v7 ? ConfigurationVersion.V7 : ConfigurationVersion.V6, "test"); + var normalized = ConfigurationDocumentMapper.Normalize(document, "test"); var internalNormalized = ConfigurationDocumentMapper.NormalizeInternal(document, "template"); normalized.ShouldBe(document); @@ -185,9 +182,8 @@ public void RootWorkflowDoesNotDetermineDocumentVersion(string property, bool ne ConfigurationDocumentMapper.Detect(document).ShouldBe(nested ? ConfigurationDocumentKind.V7 : ConfigurationDocumentKind.V6); } - [TestCase(false)] - [TestCase(true)] - public void RootWorkflowDoesNotMakeMixedDocumentValid(bool v7) + [Test] + public void RootWorkflowDoesNotMakeMixedDocumentValid() { Dictionary document = new() { @@ -197,7 +193,7 @@ public void RootWorkflowDoesNotMakeMixedDocumentValid(bool v7) }; ConfigurationDocumentMapper.Detect(document).ShouldBe(ConfigurationDocumentKind.Mixed); - Should.Throw(() => ConfigurationDocumentMapper.Normalize(document, v7 ? ConfigurationVersion.V7 : ConfigurationVersion.V6, "test")) + Should.Throw(() => ConfigurationDocumentMapper.Normalize(document, "test")) .Message.ShouldContain("unsupported root-level properties"); } @@ -217,7 +213,7 @@ public void RejectsNestedWorkflowEvenWhenRootWorkflowExists(string section, bool } var exception = Should.Throw(() => - ConfigurationDocumentMapper.Normalize(document, ConfigurationVersion.V7, "test")); + ConfigurationDocumentMapper.Normalize(document, "test")); exception.Message.ShouldContain($"{section}.workflow"); exception.Message.ShouldContain("root"); diff --git a/src/GitVersion.Configuration.Tests/Configuration/ConfigurationPropertyQueryTests.cs b/src/GitVersion.Configuration.Tests/Configuration/ConfigurationPropertyQueryTests.cs index 73356126da..9f4f3b18b4 100644 --- a/src/GitVersion.Configuration.Tests/Configuration/ConfigurationPropertyQueryTests.cs +++ b/src/GitVersion.Configuration.Tests/Configuration/ConfigurationPropertyQueryTests.cs @@ -119,8 +119,8 @@ public void RejectsV6EvenForAValidV7Path() { SysEnv.SetEnvironmentVariable(ConfigurationVersionSelector.EnvironmentVariableName, "v6"); - Should.Throw(() => this.serializer.SerializeProperty(new GitVersionConfiguration(), "calculation.tag-prefix")) - .Message.ShouldContain("require v7 configuration"); + Should.Throw(() => this.serializer.SerializeProperty(new GitVersionConfiguration(), "calculation.tag-prefix")) + .Message.ShouldContain("removed in GitVersion 7.1"); } [Test] diff --git a/src/GitVersion.Configuration.Tests/Configuration/ConfigurationProviderTests.CanWriteOutEffectiveConfiguration.approved.txt b/src/GitVersion.Configuration.Tests/Configuration/ConfigurationProviderTests.CanWriteOutEffectiveConfiguration.approved.txt index cb02dab624..eb3ec5ba8a 100644 --- a/src/GitVersion.Configuration.Tests/Configuration/ConfigurationProviderTests.CanWriteOutEffectiveConfiguration.approved.txt +++ b/src/GitVersion.Configuration.Tests/Configuration/ConfigurationProviderTests.CanWriteOutEffectiveConfiguration.approved.txt @@ -1,170 +1,180 @@ -assembly-file-versioning-scheme: MajorMinorPatch -assembly-versioning-scheme: MajorMinorPatch -branches: - develop: - increment: Minor - is-main-branch: false - is-release-branch: false - is-source-branch-for: [] - label: alpha - mode: ContinuousDelivery - pre-release-weight: 0 - prevent-increment: - when-current-commit-tagged: false - regex: ^dev(elop)?(ment)?$ - source-branches: - - main - track-merge-message: true - track-merge-target: true - tracks-release-branches: true - main: - increment: Patch - is-main-branch: true - is-release-branch: false - is-source-branch-for: [] - label: '' - pre-release-weight: 55000 - prevent-increment: - of-merged-branch: true - regex: "^master$|^main$" - source-branches: [] - track-merge-message: true - track-merge-target: false - tracks-release-branches: false - release: - increment: Minor - is-main-branch: false - is-release-branch: true - is-source-branch-for: [] - label: beta - mode: ManualDeployment - pre-release-weight: 30000 - prevent-increment: - of-merged-branch: true - when-current-commit-tagged: false - regex: "^releases?[\\/-](?.+)" - source-branches: - - main - - support - track-merge-target: false - tracks-release-branches: false - feature: - increment: Inherit - is-main-branch: false - is-source-branch-for: [] - label: "{BranchName}" - mode: ManualDeployment - pre-release-weight: 30000 - prevent-increment: - when-current-commit-tagged: false - regex: "^features?[\\/-](?.+)" - source-branches: - - develop - - main - - release - - support - - hotfix - track-merge-message: true - pull-request: - increment: Inherit - is-source-branch-for: [] - label: "PullRequest{Number}" - mode: ContinuousDelivery - pre-release-weight: 30000 - prevent-increment: - of-merged-branch: true - when-current-commit-tagged: false - regex: "^(pull-requests|pull|pr)[\\/-](?\\d*)" - source-branches: - - develop - - main - - release - - feature - - support - - hotfix - track-merge-message: true - hotfix: - increment: Inherit - is-main-branch: false - is-release-branch: true - is-source-branch-for: [] - label: beta - mode: ManualDeployment - pre-release-weight: 30000 - prevent-increment: - when-current-commit-tagged: false - regex: "^hotfix(es)?[\\/-](?.+)" - source-branches: - - main - - support - support: - increment: Patch - is-main-branch: true - is-release-branch: false - is-source-branch-for: [] - label: '' - pre-release-weight: 55000 - prevent-increment: - of-merged-branch: true - regex: "^support[\\/-](?.+)" - source-branches: - - main - track-merge-target: false - tracks-release-branches: false - unknown: - increment: Inherit - is-main-branch: false - is-source-branch-for: [] - label: "{BranchName}" - mode: ManualDeployment - prevent-increment: - when-current-commit-tagged: true - regex: "(?.+)" - source-branches: - - main - - develop - - release - - feature - - pull-request - - hotfix - - support -commit-date-format: yyyy-MM-dd -commit-message-incrementing: Enabled -ignore: - branches: [] - paths: [] - sha: [] - tags: [] -increment: Inherit -is-main-branch: false -is-release-branch: false -is-source-branch-for: [] -label: "{BranchName}" -major-version-bump-message: "[+=]semver:\\s?(breaking|major)" -merge-message-formats: {} -minor-version-bump-message: "[+=]semver:\\s?(feature|minor)" -mode: ContinuousDelivery -no-bump-message: "[+=]semver:\\s?(none|skip)" -patch-version-bump-message: "[+=]semver:\\s?(fix|patch)" -prevent-increment: - of-merged-branch: false - when-branch-merged: false - when-current-commit-tagged: true -regex: '' -semantic-version-format: Strict -source-branches: [] -strategies: - - Fallback - - ConfiguredNextVersion - - MergeMessage - - TaggedCommit - - TrackReleaseBranches - - VersionInBranchName -tag-pre-release-weight: 60000 -tag-prefix: "[vV]?" -track-merge-message: true -track-merge-target: false -tracks-release-branches: false -update-build-number: true -version-bump-reset-message: "=semver:" -version-in-branch-pattern: "(?[vV]?\\d+(\\.\\d+)?(\\.\\d+)?).*" +calculation: + branches: + develop: + increment: Minor + is-main-branch: false + is-release-branch: false + is-source-branch-for: [] + label: alpha + mode: ContinuousDelivery + prevent-increment: + when-current-commit-tagged: false + regex: ^dev(elop)?(ment)?$ + source-branches: + - main + track-merge-message: true + track-merge-target: true + tracks-release-branches: true + main: + increment: Patch + is-main-branch: true + is-release-branch: false + is-source-branch-for: [] + label: '' + prevent-increment: + of-merged-branch: true + regex: "^master$|^main$" + source-branches: [] + track-merge-message: true + track-merge-target: false + tracks-release-branches: false + release: + increment: Minor + is-main-branch: false + is-release-branch: true + is-source-branch-for: [] + label: beta + mode: ManualDeployment + prevent-increment: + of-merged-branch: true + when-current-commit-tagged: false + regex: "^releases?[\\/-](?.+)" + source-branches: + - main + - support + track-merge-target: false + tracks-release-branches: false + feature: + increment: Inherit + is-main-branch: false + is-source-branch-for: [] + label: "{BranchName}" + mode: ManualDeployment + prevent-increment: + when-current-commit-tagged: false + regex: "^features?[\\/-](?.+)" + source-branches: + - develop + - main + - release + - support + - hotfix + track-merge-message: true + pull-request: + increment: Inherit + is-source-branch-for: [] + label: "PullRequest{Number}" + mode: ContinuousDelivery + prevent-increment: + of-merged-branch: true + when-current-commit-tagged: false + regex: "^(pull-requests|pull|pr)[\\/-](?\\d*)" + source-branches: + - develop + - main + - release + - feature + - support + - hotfix + track-merge-message: true + hotfix: + increment: Inherit + is-main-branch: false + is-release-branch: true + is-source-branch-for: [] + label: beta + mode: ManualDeployment + prevent-increment: + when-current-commit-tagged: false + regex: "^hotfix(es)?[\\/-](?.+)" + source-branches: + - main + - support + support: + increment: Patch + is-main-branch: true + is-release-branch: false + is-source-branch-for: [] + label: '' + prevent-increment: + of-merged-branch: true + regex: "^support[\\/-](?.+)" + source-branches: + - main + track-merge-target: false + tracks-release-branches: false + unknown: + increment: Inherit + is-main-branch: false + is-source-branch-for: [] + label: "{BranchName}" + mode: ManualDeployment + prevent-increment: + when-current-commit-tagged: true + regex: "(?.+)" + source-branches: + - main + - develop + - release + - feature + - pull-request + - hotfix + - support + commit-message-incrementing: Enabled + ignore: + branches: [] + paths: [] + sha: [] + tags: [] + increment: Inherit + is-main-branch: false + is-release-branch: false + is-source-branch-for: [] + label: "{BranchName}" + major-version-bump-message: "[+=]semver:\\s?(breaking|major)" + merge-message-formats: {} + minor-version-bump-message: "[+=]semver:\\s?(feature|minor)" + mode: ContinuousDelivery + no-bump-message: "[+=]semver:\\s?(none|skip)" + patch-version-bump-message: "[+=]semver:\\s?(fix|patch)" + prevent-increment: + of-merged-branch: false + when-branch-merged: false + when-current-commit-tagged: true + regex: '' + semantic-version-format: Strict + source-branches: [] + strategies: + - Fallback + - ConfiguredNextVersion + - MergeMessage + - TaggedCommit + - TrackReleaseBranches + - VersionInBranchName + tag-prefix: "[vV]?" + track-merge-message: true + track-merge-target: false + tracks-release-branches: false + version-bump-reset-message: "=semver:" + version-in-branch-pattern: "(?[vV]?\\d+(\\.\\d+)?(\\.\\d+)?).*" +output: + assembly-file-versioning-scheme: MajorMinorPatch + assembly-versioning-scheme: MajorMinorPatch + branches: + develop: + pre-release-weight: 0 + main: + pre-release-weight: 55000 + release: + pre-release-weight: 30000 + feature: + pre-release-weight: 30000 + pull-request: + pre-release-weight: 30000 + hotfix: + pre-release-weight: 30000 + support: + pre-release-weight: 55000 + commit-date-format: yyyy-MM-dd + tag-pre-release-weight: 60000 + update-build-number: true diff --git a/src/GitVersion.Configuration.Tests/Configuration/ConfigurationProviderTests.cs b/src/GitVersion.Configuration.Tests/Configuration/ConfigurationProviderTests.cs index 8a24e7ed75..f548333925 100644 --- a/src/GitVersion.Configuration.Tests/Configuration/ConfigurationProviderTests.cs +++ b/src/GitVersion.Configuration.Tests/Configuration/ConfigurationProviderTests.cs @@ -19,7 +19,7 @@ public class ConfigurationProviderTests : TestBase public void Setup() { this.originalConfigurationVersion = System.Environment.GetEnvironmentVariable(ConfigurationVersionSelector.EnvironmentVariableName); - System.Environment.SetEnvironmentVariable(ConfigurationVersionSelector.EnvironmentVariableName, "v6"); + System.Environment.SetEnvironmentVariable(ConfigurationVersionSelector.EnvironmentVariableName, "v7"); this.repoPath = FileSystemHelper.Path.Combine(FileSystemHelper.Path.GetTempPath(), "MyGitRepo"); var options = Options.Create(new GitVersionOptions { WorkingDirectory = this.repoPath }); var sp = ConfigureServices(services => services.AddSingleton(options)); @@ -48,7 +48,7 @@ public void ProvidesNestedV7ConfigurationAndMergesOutputOnlyWorkflowBranch() custom-version-format: '{SemVer}' pre-release-weight: 42 """; - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); + using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: NestConfiguration(text)); var configuration = this.configurationProvider.ProvideForDirectory(this.repoPath); @@ -60,7 +60,7 @@ public void ProvidesNestedV7ConfigurationAndMergesOutputOnlyWorkflowBranch() } [Test] - public void ResolvesEquivalentV6AndV7Configuration() + public void MigratedV6ConfigurationMatchesNativeV7() { const string v6 = """ tag-prefix: custom- @@ -83,9 +83,9 @@ public void ResolvesEquivalentV6AndV7Configuration() pre-release-weight: 42 """; - System.Environment.SetEnvironmentVariable(ConfigurationVersionSelector.EnvironmentVariableName, "v6"); + System.Environment.SetEnvironmentVariable(ConfigurationVersionSelector.EnvironmentVariableName, "v7"); IGitVersionConfiguration legacy; - using (this.fileSystem.SetupConfigFile(path: this.repoPath, text: v6)) + using (this.fileSystem.SetupConfigFile(path: this.repoPath, text: new ConfigurationMigrationService(new ConfigurationSerializer()).Migrate(v6))) { legacy = this.configurationProvider.ProvideForDirectory(this.repoPath); } @@ -105,7 +105,7 @@ public void ResolvesEquivalentV6AndV7Configuration() [TestCase("TrunkBased/preview1")] public void V7SerializationRoundTripsDefaultsAndBuiltInWorkflows(string? workflow) { - System.Environment.SetEnvironmentVariable(ConfigurationVersionSelector.EnvironmentVariableName, "v6"); + System.Environment.SetEnvironmentVariable(ConfigurationVersionSelector.EnvironmentVariableName, "v7"); using var configurationFile = workflow is null ? null : this.fileSystem.SetupConfigFile(path: this.repoPath, text: $"workflow: {workflow}"); @@ -131,7 +131,7 @@ public void RejectsMixedV7Configuration() tag-prefix: custom- update-build-number: false """; - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); + using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: NestConfiguration(text)); var exception = Should.Throw(() => this.configurationProvider.ProvideForDirectory(this.repoPath)); @@ -151,7 +151,7 @@ public void OverwritesDefaultsWithProvidedConfig() mode: ContinuousDelivery label: dev """; - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); + using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: NestConfiguration(text)); var configuration = this.configurationProvider.ProvideForDirectory(this.repoPath); configuration.NextVersion.ShouldBe("2.0.0"); @@ -170,7 +170,7 @@ public void CombineVersionStrategyConfigNextAndTaggedCommit() { // Arrange const string text = "strategies: [ConfiguredNextVersion, TaggedCommit]"; - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); + using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: NestConfiguration(text)); // Act var configuration = this.configurationProvider.ProvideForDirectory(this.repoPath); @@ -189,7 +189,7 @@ public void CanRemoveLabel() release: label: "" """; - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); + using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: NestConfiguration(text)); var configuration = this.configurationProvider.ProvideForDirectory(this.repoPath); configuration.NextVersion.ShouldBe("2.0.0"); @@ -205,16 +205,16 @@ public void RegexIsRequired() bug: label: bugfix """; - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); + using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: NestConfiguration(text)); var ex = Should.Throw(() => this.configurationProvider.ProvideForDirectory(this.repoPath)); - ex.Message.ShouldBe("Configuration property 'branches.bug.regex': Branch configuration requires a regex."); + ex.Message.ShouldBe("Configuration property 'calculation.branches.bug.regex': Branch configuration requires a regex."); } [Test] public void CanConfigureVersionBumpResetMessage() { const string text = @"version-bump-reset-message: 'baseline:'"; - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); + using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: NestConfiguration(text)); var configuration = this.configurationProvider.ProvideForDirectory(this.repoPath); @@ -231,9 +231,9 @@ public void SourceBranchesValidationShouldFailWhenMatchingBranchConfigurationIsM label: bugfix source-branches: [notconfigured] """; - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); + using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: NestConfiguration(text)); var ex = Should.Throw(() => this.configurationProvider.ProvideForDirectory(this.repoPath)); - ex.Message.ShouldBe("Configuration property 'branches.bug.source-branches': Referenced branch configuration does not exist."); + ex.Message.ShouldBe("Configuration property 'calculation.branches.bug.source-branches': Referenced branch configuration does not exist."); } [Test(Description = "Well-known branches may not be present in the configuration file. This test confirms the validation check succeeds when the source-branches configuration contain these well-known branches.")] @@ -248,7 +248,7 @@ public void SourceBranchesValidationShouldSucceedForWellKnownBranches(string wel label: bugfix source-branches: [{wellKnownBranchKey}] """; - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); + using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: NestConfiguration(text)); var configuration = this.configurationProvider.ProvideForDirectory(this.repoPath); configuration.Branches["bug"].SourceBranches.ShouldBe([wellKnownBranchKey]); @@ -265,7 +265,7 @@ public void CanProvideConfigForNewBranch() label: bugfix source-branches: [] """; - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); + using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: NestConfiguration(text)); var configuration = this.configurationProvider.ProvideForDirectory(this.repoPath); configuration.Branches["bug"].RegularExpression.ShouldBe(@"bug[\/-]"); @@ -276,7 +276,7 @@ public void CanProvideConfigForNewBranch() public void NextVersionCanBeInteger() { const string text = "next-version: 2\nsemantic-version-format: Loose"; - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); + using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: NestConfiguration(text)); var configuration = this.configurationProvider.ProvideForDirectory(this.repoPath); configuration.NextVersion.ShouldBe("2.0"); @@ -286,7 +286,7 @@ public void NextVersionCanBeInteger() public void NextVersionCanHaveEnormousMinorVersion() { const string text = "next-version: 2.118998723\nsemantic-version-format: Loose"; - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); + using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: NestConfiguration(text)); var configuration = this.configurationProvider.ProvideForDirectory(this.repoPath); configuration.NextVersion.ShouldBe("2.118998723"); @@ -296,7 +296,7 @@ public void NextVersionCanHaveEnormousMinorVersion() public void NextVersionCanHavePatch() { const string text = "next-version: 2.12.654651698"; - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); + using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: NestConfiguration(text)); var configuration = this.configurationProvider.ProvideForDirectory(this.repoPath); configuration.NextVersion.ShouldBe("2.12.654651698"); @@ -320,7 +320,7 @@ public void CanUpdateAssemblyInformationalVersioningScheme() assembly-informational-format: '{NugetVersion}' """; - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); + using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: NestConfiguration(text)); var configuration = this.configurationProvider.ProvideForDirectory(this.repoPath); configuration.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinor); @@ -337,7 +337,7 @@ public void CanUpdateAssemblyInformationalVersioningSchemeWithMultipleVariables( assembly-informational-format: '{Major}.{Minor}.{Patch}' """; - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); + using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: NestConfiguration(text)); var configuration = this.configurationProvider.ProvideForDirectory(this.repoPath); configuration.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinor); @@ -357,7 +357,7 @@ public void CanUpdateAssemblyInformationalVersioningSchemeWithFullSemVer() branches: {} """; - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); + using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: NestConfiguration(text)); var configuration = this.configurationProvider.ProvideForDirectory(this.repoPath); configuration.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinorPatch); @@ -369,7 +369,7 @@ public void CanUpdateAssemblyInformationalVersioningSchemeWithFullSemVer() public void CanReadCustomVersionFormat() { const string text = "custom-version-format: '{Major}.{Minor}.{Patch}{PreReleaseLabelName:l}{PreReleaseNumber}'"; - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); + using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: NestConfiguration(text)); var configuration = this.configurationProvider.ProvideForDirectory(this.repoPath); @@ -385,7 +385,7 @@ public void CanReadBranchSpecificCustomVersionFormat() feature: custom-version-format: '{Major}.{Minor}.{Patch}{PreReleaseLabelName:l}{PreReleaseNumber}' """; - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); + using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: NestConfiguration(text)); var configuration = this.configurationProvider.ProvideForDirectory(this.repoPath); @@ -397,7 +397,7 @@ public void CanReadBranchSpecificCustomVersionFormat() public void CanOverrideCustomVersionFormat() { const string text = "custom-version-format: '{SemVer}'"; - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); + using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: NestConfiguration(text)); var overrideConfiguration = new Dictionary { ["custom-version-format"] = "{Major:00}{Minor:00}{Patch:000}" @@ -412,7 +412,7 @@ public void CanOverrideCustomVersionFormat() public void CanReadDefaultDocument() { const string text = ""; - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); + using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: NestConfiguration(text)); var configuration = this.configurationProvider.ProvideForDirectory(this.repoPath); configuration.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinorPatch); configuration.AssemblyFileVersioningScheme.ShouldBe(AssemblyFileVersioningScheme.MajorMinorPatch); @@ -437,97 +437,6 @@ public void VerifyAliases() propertiesMissingAlias.ShouldBeEmpty(); } - [Test] - public void WarnsOnceWhenExplicitV6LoadsAConfigurationFile() - { - const string text = ""; - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); - - var logMessages = new List(); - - var loggerFactory = new TestLoggerFactory(logMessages.Add); - - var options = Options.Create(new GitVersionOptions { WorkingDirectory = this.repoPath }); - var sp = ConfigureServices(services => - { - services.AddSingleton(options); - loggerFactory.RegisterWith(services); - }); - this.configurationProvider = (ConfigurationProvider)sp.GetRequiredService(); - - this.configurationProvider.ProvideForDirectory(this.repoPath); - this.configurationProvider.ProvideForDirectory(this.repoPath); - - var filePath = FileSystemHelper.Path.Combine(this.repoPath, ConfigurationFileLocator.DefaultFileName); - logMessages.ShouldContain(message => message.Contains($"Configuration file '{filePath}' uses the temporary v6 compatibility mode.", StringComparison.Ordinal)); - logMessages.Count(message => message.Contains("temporary v6 compatibility mode", StringComparison.Ordinal)).ShouldBe(1); - logMessages.ShouldContain(message => message.Contains("GitVersion 7.1", StringComparison.Ordinal)); - logMessages.ShouldContain(message => message.Contains("gitversion config migrate", StringComparison.Ordinal)); - } - - [TestCase(null)] - [TestCase("v7")] - public void DoesNotWarnWhenV6IsNotExplicitlySelected(string? configurationVersion) - { - System.Environment.SetEnvironmentVariable(ConfigurationVersionSelector.EnvironmentVariableName, configurationVersion); - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: ""); - var logMessages = new List(); - var loggerFactory = new TestLoggerFactory(logMessages.Add); - var options = Options.Create(new GitVersionOptions { WorkingDirectory = this.repoPath }); - var sp = ConfigureServices(services => - { - services.AddSingleton(options); - loggerFactory.RegisterWith(services); - }); - this.configurationProvider = (ConfigurationProvider)sp.GetRequiredService(); - - this.configurationProvider.ProvideForDirectory(this.repoPath); - - logMessages.ShouldNotContain(message => message.Contains("temporary v6 compatibility mode", StringComparison.Ordinal)); - } - - [Test] - public void DoesNotWarnForExplicitV6BuiltInDefaults() - { - var logMessages = new List(); - var loggerFactory = new TestLoggerFactory(logMessages.Add); - var options = Options.Create(new GitVersionOptions { WorkingDirectory = this.repoPath }); - var sp = ConfigureServices(services => - { - services.AddSingleton(options); - loggerFactory.RegisterWith(services); - }); - this.configurationProvider = (ConfigurationProvider)sp.GetRequiredService(); - - this.configurationProvider.ProvideForDirectory(this.repoPath); - - logMessages.ShouldNotContain(message => message.Contains("temporary v6 compatibility mode", StringComparison.Ordinal)); - } - - [Test] - public void DoesNotWarnWhenExplicitV6ConfigurationFailsNormalization() - { - const string text = """ - calculation: - next-version: 2.0.0 - output: {} - """; - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); - var logMessages = new List(); - var loggerFactory = new TestLoggerFactory(logMessages.Add); - var options = Options.Create(new GitVersionOptions { WorkingDirectory = this.repoPath }); - var sp = ConfigureServices(services => - { - services.AddSingleton(options); - loggerFactory.RegisterWith(services); - }); - this.configurationProvider = (ConfigurationProvider)sp.GetRequiredService(); - - Should.Throw(() => this.configurationProvider.ProvideForDirectory(this.repoPath)); - - logMessages.ShouldNotContain(message => message.Contains("temporary v6 compatibility mode", StringComparison.Ordinal)); - } - [Test] public void ShouldUseSpecifiedSourceBranchesForDevelop() { @@ -539,7 +448,7 @@ public void ShouldUseSpecifiedSourceBranchesForDevelop() source-branches: ['develop'] label: dev """; - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); + using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: NestConfiguration(text)); var configuration = this.configurationProvider.ProvideForDirectory(this.repoPath); configuration.Branches["develop"].SourceBranches.ShouldBe(["develop"]); @@ -555,7 +464,7 @@ public void ShouldUseDefaultSourceBranchesWhenNotSpecifiedForDevelop() mode: ContinuousDeployment label: dev """; - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); + using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: NestConfiguration(text)); var configuration = this.configurationProvider.ProvideForDirectory(this.repoPath); configuration.Branches["develop"].SourceBranches.ShouldBe(["main"]); @@ -572,7 +481,7 @@ public void ShouldUseSpecifiedSourceBranchesForFeature() source-branches: ['develop', 'release'] label: dev """; - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); + using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: NestConfiguration(text)); var configuration = this.configurationProvider.ProvideForDirectory(this.repoPath); configuration.Branches["feature"].SourceBranches.ShouldBe(["develop", "release"]); @@ -588,7 +497,7 @@ public void ShouldUseDefaultSourceBranchesWhenNotSpecifiedForFeature() mode: ContinuousDeployment label: dev """; - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); + using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: NestConfiguration(text)); var configuration = this.configurationProvider.ProvideForDirectory(this.repoPath); configuration.Branches["feature"].SourceBranches.ShouldBe( @@ -602,7 +511,7 @@ public void ShouldNotOverrideAnythingWhenOverrideConfigIsEmpty() next-version: 1.2.3 tag-prefix: custom-tag-prefix-from-yml """; - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); + using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: NestConfiguration(text)); var expectedConfig = GitFlowConfigurationBuilder.New .WithNextVersion("1.2.3") @@ -642,7 +551,7 @@ public void ShouldNotOverrideAnythingWhenOverrideConfigIsEmpty() public void ShouldUseDefaultTagPrefixWhenNotSetInConfigFile() { const string text = ""; - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); + using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: NestConfiguration(text)); var configuration = this.configurationProvider.ProvideForDirectory(this.repoPath); configuration.TagPrefixPattern.ShouldBe(RegexPatterns.Configuration.DefaultTagPrefixRegexPattern); @@ -652,7 +561,7 @@ public void ShouldUseDefaultTagPrefixWhenNotSetInConfigFile() public void ShouldUseTagPrefixFromConfigFileWhenProvided() { const string text = "tag-prefix: custom-tag-prefix-from-yml"; - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); + using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: NestConfiguration(text)); var configuration = this.configurationProvider.ProvideForDirectory(this.repoPath); configuration.TagPrefixPattern.ShouldBe("custom-tag-prefix-from-yml"); @@ -662,7 +571,7 @@ public void ShouldUseTagPrefixFromConfigFileWhenProvided() public void ShouldOverrideTagPrefixWithOverrideConfigValue([Values] bool tagPrefixSetAtYmlFile) { var text = tagPrefixSetAtYmlFile ? "tag-prefix: custom-tag-prefix-from-yml" : ""; - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); + using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: NestConfiguration(text)); var overrideConfiguration = new Dictionary { { "tag-prefix", "tag-prefix-from-override-configuration" } @@ -676,7 +585,7 @@ public void ShouldOverrideTagPrefixWithOverrideConfigValue([Values] bool tagPref public void ShouldNotOverrideDefaultTagPrefixWhenNotSetInOverrideConfig() { const string text = ""; - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); + using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: NestConfiguration(text)); var overrideConfiguration = new Dictionary { { "next-version", "1.0.0" } @@ -691,7 +600,7 @@ public void ShouldNotOverrideDefaultTagPrefixWhenNotSetInOverrideConfig() public void ShouldNotOverrideTagPrefixFromConfigFileWhenNotSetInOverrideConfig() { const string text = "tag-prefix: custom-tag-prefix-from-yml"; - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); + using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: NestConfiguration(text)); var overrideConfiguration = new Dictionary { { "next-version", "1.0.0" } @@ -705,7 +614,7 @@ public void ShouldNotOverrideTagPrefixFromConfigFileWhenNotSetInOverrideConfig() public void ShouldOverrideTagPrefixFromConfigFileWhenSetInOverrideConfig() { const string text = "tag-prefix: custom-tag-prefix-from-yml"; - using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: text); + using var _ = this.fileSystem.SetupConfigFile(path: this.repoPath, text: NestConfiguration(text)); var overrideConfiguration = new Dictionary { { "tag-prefix", "custom-tag-prefix-from-console" } @@ -714,4 +623,24 @@ public void ShouldOverrideTagPrefixFromConfigFileWhenSetInOverrideConfig() configuration.TagPrefixPattern.ShouldBe("custom-tag-prefix-from-console"); } + [Test] + public void FlatV6RuntimeDocumentRequiresMigration() + { + using var file = this.fileSystem.SetupConfigFile(path: this.repoPath, text: "next-version: 2.0.0"); + var error = Should.Throw(() => this.configurationProvider.ProvideForDirectory(this.repoPath)); + error.Message.ShouldContain("removed in GitVersion 7.1"); + error.Message.ShouldContain("gitversion config migrate"); + } + + private static string NestConfiguration(string yaml) + { + var serializer = new ConfigurationSerializer(); + var document = serializer.Deserialize>(yaml); + return ConfigurationDocumentMapper.Detect(document) == ConfigurationDocumentKind.V6 + ? ConfigurationSerializer.SerializeDocument(ConfigurationDocumentMapper.Nest(document)) + : yaml; + } + + + } diff --git a/src/GitVersion.Configuration.Tests/Configuration/ConfigurationSerializerTests.cs b/src/GitVersion.Configuration.Tests/Configuration/ConfigurationSerializerTests.cs index 2cff57f136..7ad8601972 100644 --- a/src/GitVersion.Configuration.Tests/Configuration/ConfigurationSerializerTests.cs +++ b/src/GitVersion.Configuration.Tests/Configuration/ConfigurationSerializerTests.cs @@ -35,16 +35,14 @@ public void SerializesV7CalculationAndOutputSectionsAndRoundTrips() } [Test] - public void SerializesFlatConfigurationWhenV6IsSelected() + public void RejectsRemovedV6RuntimeSerialization() { using var scope = new EnvironmentVariableScope("v6"); var configuration = new GitVersionConfiguration { TagPrefixPattern = "custom-" }; - var yaml = this.serializer.Serialize(configuration); - - yaml.ShouldContain("tag-prefix: custom-"); - yaml.ShouldNotContain("calculation:"); - yaml.ShouldNotContain("output:"); + var error = Should.Throw(() => this.serializer.Serialize(configuration)); + error.Message.ShouldContain("removed in GitVersion 7.1"); + error.Message.ShouldContain("gitversion config migrate"); } [Test] diff --git a/src/GitVersion.Configuration.Tests/Configuration/IgnoreConfigurationTests.cs b/src/GitVersion.Configuration.Tests/Configuration/IgnoreConfigurationTests.cs index df03de552e..e0878f88d8 100644 --- a/src/GitVersion.Configuration.Tests/Configuration/IgnoreConfigurationTests.cs +++ b/src/GitVersion.Configuration.Tests/Configuration/IgnoreConfigurationTests.cs @@ -16,7 +16,7 @@ public class IgnoreConfigurationTests : TestBase public void Setup() { this.originalConfigurationVersion = System.Environment.GetEnvironmentVariable(ConfigurationVersionSelector.EnvironmentVariableName); - System.Environment.SetEnvironmentVariable(ConfigurationVersionSelector.EnvironmentVariableName, "v6"); + System.Environment.SetEnvironmentVariable(ConfigurationVersionSelector.EnvironmentVariableName, "v7"); } [TearDown] @@ -28,9 +28,10 @@ public void CanDeserialize() { const string yaml = """ - ignore: - commits-before: 2015-10-23T12:23:15 - sha: [b6c0c9fda88830ebcd563e500a5a7da5a1658e98] + calculation: + ignore: + commits-before: 2015-10-23T12:23:15 + sha: [b6c0c9fda88830ebcd563e500a5a7da5a1658e98] """; var configuration = ConfigurationSerializer.ReadConfiguration(yaml); @@ -47,10 +48,11 @@ public void ShouldSupportsOtherSequenceFormat() { const string yaml = """ - ignore: - sha: - - b6c0c9fda88830ebcd563e500a5a7da5a1658e98 - - 6c19c7c219ecf8dbc468042baefa73a1b213e8b1 + calculation: + ignore: + sha: + - b6c0c9fda88830ebcd563e500a5a7da5a1658e98 + - 6c19c7c219ecf8dbc468042baefa73a1b213e8b1 """; var configuration = ConfigurationSerializer.ReadConfiguration(yaml); @@ -64,7 +66,7 @@ public void ShouldSupportsOtherSequenceFormat() [Test] public void CanDeserializeCompactBranchesSequence() { - const string yaml = "ignore:\n branches: ['^legacy/', '^release/old$']"; + const string yaml = "calculation:\n ignore:\n branches: ['^legacy/', '^release/old$']"; var configuration = ConfigurationSerializer.ReadConfiguration(yaml); @@ -75,7 +77,7 @@ public void CanDeserializeCompactBranchesSequence() [Test] public void CanDeserializeCompactTagsSequence() { - const string yaml = "ignore:\n tags: ['^preview-', '^v0\\.']"; + const string yaml = "calculation:\n ignore:\n tags: ['^preview-', '^v0\\.']"; var configuration = ConfigurationSerializer.ReadConfiguration(yaml); @@ -88,12 +90,13 @@ public void CanDeserializeMultilineBranchesAndTagsSequences() { const string yaml = """ - ignore: - branches: - - ^legacy/ - - ^release/old$ - tags: - - ^preview- + calculation: + ignore: + branches: + - ^legacy/ + - ^release/old$ + tags: + - ^preview- """; var configuration = ConfigurationSerializer.ReadConfiguration(yaml); @@ -108,10 +111,11 @@ public void CanDeserializeMultilineTagsSequence() { const string yaml = """ - ignore: - tags: - - ^preview- - - ^v0\. + calculation: + ignore: + tags: + - ^preview- + - ^v0\. """; var configuration = ConfigurationSerializer.ReadConfiguration(yaml); @@ -123,7 +127,7 @@ public void CanDeserializeMultilineTagsSequence() [Test] public void WhenNotInConfigShouldHaveDefaults() { - const string yaml = "next-version: 1.0"; + const string yaml = "calculation:\n next-version: 1.0"; var configuration = ConfigurationSerializer.ReadConfiguration(yaml); @@ -221,8 +225,9 @@ public void WhenBadDateFormatShouldFail() { const string yaml = """ - ignore: - commits-before: bad format date + calculation: + ignore: + commits-before: bad format date """; Should.Throw(() => ConfigurationSerializer.ReadConfiguration(yaml)); @@ -231,7 +236,7 @@ public void WhenBadDateFormatShouldFail() [Test] public void ShouldSupportScalarVersionStrategiesOverrideFormat() { - const string yaml = "strategies: ConfiguredNextVersion, TaggedCommit"; + const string yaml = "calculation:\n strategies: ConfiguredNextVersion, TaggedCommit"; var configuration = ConfigurationSerializer.ReadConfiguration(yaml); diff --git a/src/GitVersion.Configuration/Builders/ConfigurationBuilderBase.cs b/src/GitVersion.Configuration/Builders/ConfigurationBuilderBase.cs index 8e32532ca2..b0ab28be11 100644 --- a/src/GitVersion.Configuration/Builders/ConfigurationBuilderBase.cs +++ b/src/GitVersion.Configuration/Builders/ConfigurationBuilderBase.cs @@ -538,7 +538,7 @@ private static void ValidateIgnoreExpressions(string propertyName, IEnumerable ConfigurationVersionSelector.Resolve() == ConfigurationVersion.V7 ? "calculation." + path : path; + private static string PublicPath(string path) => "calculation." + path; private static void ValidateRegex(string path, string? expression) { diff --git a/src/GitVersion.Configuration/ConfigurationDocumentMapper.cs b/src/GitVersion.Configuration/ConfigurationDocumentMapper.cs index 9e8bdf7d25..26439f668c 100644 --- a/src/GitVersion.Configuration/ConfigurationDocumentMapper.cs +++ b/src/GitVersion.Configuration/ConfigurationDocumentMapper.cs @@ -76,7 +76,6 @@ public static ConfigurationDocumentKind Detect(IReadOnlyDictionary Normalize( IReadOnlyDictionary document, - ConfigurationVersion selectedVersion, string source) { var kind = Detect(document); @@ -88,18 +87,11 @@ public static ConfigurationDocumentKind Detect(IReadOnlyDictionary document, ConfigurationVersion version) - => ValidateObject(document, typeof(GitVersionConfiguration), "", version); + public static void Validate(IReadOnlyDictionary document) + => ValidateObject(document, typeof(GitVersionConfiguration), ""); - private static void ValidateObject(IReadOnlyDictionary document, Type type, string prefix, ConfigurationVersion version) + private static void ValidateObject(IReadOnlyDictionary document, Type type, string prefix) { var properties = type.GetProperties().Where(p => p.GetCustomAttribute() is not null) .ToDictionary(p => p.GetCustomAttribute()!.Name); @@ -17,7 +17,7 @@ private static void ValidateObject(IReadOnlyDictionary document { var name = key as string ?? ""; var path = prefix + name; - if (prefix.Length == 0 && name != "workflow" && version == ConfigurationVersion.V7) + if (prefix.Length == 0 && name != "workflow") { path = (ConfigurationDocumentMapper.IsOutputProperty(name) ? "output." : "calculation.") + name; } @@ -27,7 +27,7 @@ private static void ValidateObject(IReadOnlyDictionary document throw Error(path, "Unknown configuration property."); } - if (version == ConfigurationVersion.V7 && prefix.StartsWith("calculation.branches.", StringComparison.Ordinal) + if (prefix.StartsWith("calculation.branches.", StringComparison.Ordinal) && ConfigurationDocumentMapper.IsOutputBranchProperty(name)) { path = "output." + path["calculation.".Length..]; @@ -42,11 +42,11 @@ private static void ValidateObject(IReadOnlyDictionary document throw Error(path, "Expected a valid commit cutoff date."); } - ValidateValue(value, property.PropertyType, path, version); + ValidateValue(value, property.PropertyType, path); } } - private static void ValidateValue(object? value, Type type, string path, ConfigurationVersion version) + private static void ValidateValue(object? value, Type type, string path) { if (value is null) { @@ -66,17 +66,17 @@ private static void ValidateValue(object? value, Type type, string path, Configu } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>)) { - ValidateDictionary(value, type.GenericTypeArguments[1], path, version); + ValidateDictionary(value, type.GenericTypeArguments[1], path); return; } if (type.IsArray || type.IsGenericType && type.GetGenericTypeDefinition() == typeof(HashSet<>)) { var elementType = type.IsArray ? type.GetElementType()! : type.GenericTypeArguments[0]; - ValidateSequence(value, elementType, path, version); + ValidateSequence(value, elementType, path); return; } - ValidateLeaf(value, type, path, version); + ValidateLeaf(value, type, path); } private static void ValidateStrategies(object value, string path) @@ -95,7 +95,7 @@ private static void ValidateStrategies(object value, string path) } } - private static void ValidateDictionary(object value, Type elementType, string path, ConfigurationVersion version) + private static void ValidateDictionary(object value, Type elementType, string path) { if (value is not IReadOnlyDictionary map) { @@ -108,11 +108,11 @@ private static void ValidateDictionary(object value, Type elementType, string pa { throw Error(path + "." + key, "Expected a non-null mapping value."); } - ValidateValue(item, elementType, path + "." + key, version); + ValidateValue(item, elementType, path + "." + key); } } - private static void ValidateSequence(object value, Type elementType, string path, ConfigurationVersion version) + private static void ValidateSequence(object value, Type elementType, string path) { if (value is not IEnumerable sequence || value is string or IDictionary or IReadOnlyDictionary) { @@ -126,11 +126,11 @@ private static void ValidateSequence(object value, Type elementType, string path { throw Error($"{path}[{index}]", "Expected a non-null sequence item."); } - ValidateValue(list[index], elementType, $"{path}[{index}]", version); + ValidateValue(list[index], elementType, $"{path}[{index}]"); } } - private static void ValidateLeaf(object value, Type type, string path, ConfigurationVersion version) + private static void ValidateLeaf(object value, Type type, string path) { if (type == typeof(string)) { @@ -162,7 +162,7 @@ private static void ValidateLeaf(object value, Type type, string path, Configura } else if (value is IReadOnlyDictionary nested) { - ValidateObject(nested, type, path + ".", version); + ValidateObject(nested, type, path + "."); } else { diff --git a/src/GitVersion.Configuration/ConfigurationPropertyQuery.cs b/src/GitVersion.Configuration/ConfigurationPropertyQuery.cs index b8d2fa2221..3cd54d4d6a 100644 --- a/src/GitVersion.Configuration/ConfigurationPropertyQuery.cs +++ b/src/GitVersion.Configuration/ConfigurationPropertyQuery.cs @@ -4,10 +4,7 @@ internal static class ConfigurationPropertyQuery { public static object? GetValue(IGitVersionConfiguration configuration, string path) { - if (ConfigurationVersionSelector.Resolve() != ConfigurationVersion.V7) - { - throw new ConfigurationException("Configuration property queries require v7 configuration. Set GITVERSION_CONFIGURATION_VERSION=v7."); - } + _ = ConfigurationVersionSelector.Resolve(); var segments = ParsePath(path); var offset = GetPropertyOffset(segments, path); diff --git a/src/GitVersion.Configuration/ConfigurationProvider.cs b/src/GitVersion.Configuration/ConfigurationProvider.cs index 3a19dba6a1..480b206847 100644 --- a/src/GitVersion.Configuration/ConfigurationProvider.cs +++ b/src/GitVersion.Configuration/ConfigurationProvider.cs @@ -17,7 +17,6 @@ internal class ConfigurationProvider( private readonly ILogger logger = logger.NotNull(); private readonly IConfigurationSerializer configurationSerializer = configurationSerializer.NotNull(); private readonly IOptions options = options.NotNull(); - private bool legacyConfigurationWarningLogged; public IGitVersionConfiguration Provide(IReadOnlyDictionary? overrideConfiguration = null) { @@ -43,11 +42,9 @@ internal IGitVersionConfiguration ProvideForDirectory(string? workingDirectory, private IGitVersionConfiguration ProvideConfiguration(string? configFile, IReadOnlyDictionary? overrideConfiguration = null) { - var configurationVersion = ConfigurationVersionSelector.Resolve(); - this.logger.LogInformation("Configuration version: {ConfigurationVersion}", configurationVersion == ConfigurationVersion.V6 ? "v6" : "v7"); + this.logger.LogInformation("Configuration version: {ConfigurationVersion}", ConfigurationVersionSelector.ResolveName()); var configurationFromFile = ReadOverrideConfiguration(configFile); var configuration = resolver.Resolve(configurationFromFile is null ? null : ConfigurationSerializer.SerializeLegacy(configurationFromFile), overrideConfiguration); - WarnAboutExplicitLegacyConfiguration(configFile, configurationFromFile); return configuration; } @@ -70,19 +67,4 @@ private IGitVersionConfiguration ProvideConfiguration(string? configFile, return this.configurationSerializer.Deserialize>(content); } - private void WarnAboutExplicitLegacyConfiguration(string? configFilePath, Dictionary? configuration) - { - if (configuration is null || this.legacyConfigurationWarningLogged || !ConfigurationVersionSelector.IsExplicitV6()) - { - return; - } - - this.legacyConfigurationWarningLogged = true; - this.logger.LogWarning( - "Configuration file '{ConfigurationFile}' uses the temporary v6 compatibility mode. Legacy configuration loading is removed in GitVersion 7.1. " + - "Run 'gitversion config migrate' and validate with {ConfigurationVersion}=v7.", - configFilePath, - ConfigurationVersionSelector.EnvironmentVariableName); - } - } diff --git a/src/GitVersion.Configuration/ConfigurationResolver.cs b/src/GitVersion.Configuration/ConfigurationResolver.cs index 22badadf31..70581dd5ae 100644 --- a/src/GitVersion.Configuration/ConfigurationResolver.cs +++ b/src/GitVersion.Configuration/ConfigurationResolver.cs @@ -7,18 +7,18 @@ internal sealed class ConfigurationResolver(IConfigurationSerializer serializer) { public IGitVersionConfiguration Resolve(string? content, IReadOnlyDictionary? overrides = null) { - var version = ConfigurationVersionSelector.Resolve(); + _ = ConfigurationVersionSelector.Resolve(); var document = content is null ? null : serializer.Deserialize>(content); - var file = document is null ? null : ConfigurationDocumentMapper.Normalize(document, version, "configuration file"); + var file = document is null ? null : ConfigurationDocumentMapper.Normalize(document, "configuration file"); var runtime = overrides is null ? null : ConfigurationDocumentMapper.NormalizeInternal(overrides, "runtime override configuration"); if (file is not null) { - ConfigurationInputValidator.Validate(file, version); + ConfigurationInputValidator.Validate(file); } if (runtime is not null) { - ConfigurationInputValidator.Validate(runtime, version); + ConfigurationInputValidator.Validate(runtime); } var workflow = GetWorkflow(file, runtime); diff --git a/src/GitVersion.Configuration/ConfigurationSerializer.cs b/src/GitVersion.Configuration/ConfigurationSerializer.cs index 2cbcb83e94..5bba37a2b8 100644 --- a/src/GitVersion.Configuration/ConfigurationSerializer.cs +++ b/src/GitVersion.Configuration/ConfigurationSerializer.cs @@ -29,7 +29,7 @@ public T Deserialize(string input) // NOSONAR: IConfigurationSerializer requi if (typeof(T) == typeof(GitVersionConfiguration)) { - return (T)(object)DeserializeConfiguration(input, ConfigurationVersionSelector.Resolve(), "configuration document")!; + return (T)(object)DeserializeConfiguration(input, "configuration document")!; } return YamlSerializer.Deserialize(input, SerializerOptions)!; @@ -37,9 +37,10 @@ public T Deserialize(string input) // NOSONAR: IConfigurationSerializer requi public string Serialize(object graph) // NOSONAR: IConfigurationSerializer requires an instance method. { + _ = ConfigurationVersionSelector.Resolve(); var yaml = SerializeLegacy(graph); var configuration = YamlSerializer.Deserialize>(yaml, SerializerOptions) ?? []; - if (graph is IGitVersionConfiguration && ConfigurationVersionSelector.Resolve() == ConfigurationVersion.V7) + if (graph is IGitVersionConfiguration) { configuration = ConfigurationDocumentMapper.Nest(configuration); } @@ -63,23 +64,23 @@ public string SerializeProperty(IGitVersionConfiguration configuration, string p } public static IGitVersionConfiguration? ReadConfiguration(string input) - => DeserializeConfiguration(input, ConfigurationVersionSelector.Resolve(), "configuration document"); + => DeserializeConfiguration(input, "configuration document"); internal static string SerializeLegacy(object graph) => YamlSerializer.Serialize(graph, SerializerOptions); internal static GitVersionConfiguration? DeserializeLegacyConfiguration(string input) - => DeserializeConfiguration(input, ConfigurationVersion.V6, "internal effective configuration"); + => YamlSerializer.Deserialize(input, GeneratedContext); private static GitVersionConfiguration? DeserializeConfiguration( string input, - ConfigurationVersion version, string source) { + _ = ConfigurationVersionSelector.Resolve(); try { var graph = YamlSerializer.Deserialize>(input, SerializerOptions); var objectGraph = ConvertToObjectDictionary(graph); - var normalized = ConfigurationDocumentMapper.Normalize(objectGraph, version, source); + var normalized = ConfigurationDocumentMapper.Normalize(objectGraph, source); var normalizedYaml = YamlSerializer.Serialize(normalized, SerializerOptions); return YamlSerializer.Deserialize(normalizedYaml, GeneratedContext); } diff --git a/src/GitVersion.Core.Tests/Core/ConfigurationVersionSelectorTests.cs b/src/GitVersion.Core.Tests/Core/ConfigurationVersionSelectorTests.cs index 6d5eb19699..020779d245 100644 --- a/src/GitVersion.Core.Tests/Core/ConfigurationVersionSelectorTests.cs +++ b/src/GitVersion.Core.Tests/Core/ConfigurationVersionSelectorTests.cs @@ -6,31 +6,17 @@ namespace GitVersion.Tests; [NonParallelizable] public class ConfigurationVersionSelectorTests : TestBase { - [TestCase(null, false)] - [TestCase("", false)] - [TestCase(" \t ", false)] - [TestCase("v6", true)] - [TestCase("V6", true)] - [TestCase(" v6 ", true)] - [TestCase("v7", false)] - [TestCase("V7", false)] - [TestCase(" v7 ", false)] - public void ResolvesKnownValues(string? value, bool isV6) + [TestCase(null)] + [TestCase("")] + [TestCase(" \t ")] + [TestCase("v7")] + [TestCase("V7")] + [TestCase(" v7 ")] + public void ResolvesKnownValues(string? value) { using var scope = new EnvironmentVariableScope(value); - ConfigurationVersionSelector.Resolve().ShouldBe(isV6 ? ConfigurationVersion.V6 : ConfigurationVersion.V7); - } - - [TestCase(null, false)] - [TestCase("v6", true)] - [TestCase(" V6 ", true)] - [TestCase("v7", false)] - public void IdentifiesExplicitV6Selection(string? value, bool expected) - { - using var scope = new EnvironmentVariableScope(value); - - ConfigurationVersionSelector.IsExplicitV6().ShouldBe(expected); + ConfigurationVersionSelector.Resolve().ShouldBe(ConfigurationVersion.V7); } [TestCase("6")] @@ -43,10 +29,20 @@ public void FailsFastOnUnknownValues(string value) var exception = Should.Throw(() => ConfigurationVersionSelector.Resolve()); exception.Message.ShouldContain(value); - exception.Message.ShouldContain("v6"); exception.Message.ShouldContain("v7"); } + [TestCase("v6")] + [TestCase(" V6 ")] + public void RejectsRetiredConfigurationWithMigrationGuidance(string value) + { + using var scope = new EnvironmentVariableScope(value); + var error = Should.Throw(() => ConfigurationVersionSelector.Resolve()); + error.Message.ShouldContain("removed in GitVersion 7.1"); + error.Message.ShouldContain("gitversion config migrate"); + error.Message.ShouldContain("v7"); + } + private sealed class EnvironmentVariableScope : IDisposable { private readonly string? original = System.Environment.GetEnvironmentVariable(ConfigurationVersionSelector.EnvironmentVariableName); diff --git a/src/GitVersion.Core.Tests/Core/GitVersionExecutorTests.cs b/src/GitVersion.Core.Tests/Core/GitVersionExecutorTests.cs index 143e76287b..d80a7ce915 100644 --- a/src/GitVersion.Core.Tests/Core/GitVersionExecutorTests.cs +++ b/src/GitVersion.Core.Tests/Core/GitVersionExecutorTests.cs @@ -58,30 +58,13 @@ public class GitVersionExecutorTests : TestBase public void SetupConfigurationVersion() { this.originalConfigurationVersion = System.Environment.GetEnvironmentVariable(ConfigurationVersionSelector.EnvironmentVariableName); - System.Environment.SetEnvironmentVariable(ConfigurationVersionSelector.EnvironmentVariableName, "v6"); + System.Environment.SetEnvironmentVariable(ConfigurationVersionSelector.EnvironmentVariableName, "v7"); } [TearDown] public void RestoreConfigurationVersion() => System.Environment.SetEnvironmentVariable(ConfigurationVersionSelector.EnvironmentVariableName, this.originalConfigurationVersion); - [Test] - public void ConfigurationVersionChangeInvalidatesCache() - { - using var fixture = new EmptyRepositoryFixture(); - fixture.Repository.MakeACommit(); - var options = new GitVersionOptions { WorkingDirectory = fixture.RepositoryPath }; - _ = GetGitVersionCalculator(options); - var cacheKeyFactory = this.sp.GetRequiredService(); - - System.Environment.SetEnvironmentVariable(ConfigurationVersionSelector.EnvironmentVariableName, "v6"); - var v6Key = cacheKeyFactory.Create(null); - System.Environment.SetEnvironmentVariable(ConfigurationVersionSelector.EnvironmentVariableName, "v7"); - var v7Key = cacheKeyFactory.Create(null); - - v7Key.ShouldNotBe(v6Key); - } - [Test] public void ResolvedConfiguration_IsCreatedOncePerExecution() { @@ -333,7 +316,7 @@ public void ConfigChangeInvalidatesCache(string configFileName) versionVariables.AssemblySemVer.ShouldBe("4.10.3.0"); var configPath = FileSystemHelper.Path.Combine(fixture.RepositoryPath, configFileName); - this.fileSystem.File.WriteAllText(configPath, "next-version: 5.0.0"); + this.fileSystem.File.WriteAllText(configPath, "calculation:\n next-version: 5.0.0"); gitVersionCalculator = GetGitVersionCalculator(gitVersionOptions, fs: this.fileSystem); diff --git a/src/GitVersion.Core/Configuration/ConfigurationVersion.cs b/src/GitVersion.Core/Configuration/ConfigurationVersion.cs index accd677346..e7174b2bb0 100644 --- a/src/GitVersion.Core/Configuration/ConfigurationVersion.cs +++ b/src/GitVersion.Core/Configuration/ConfigurationVersion.cs @@ -2,7 +2,6 @@ namespace GitVersion.Configuration; internal enum ConfigurationVersion { - V6, V7 } @@ -10,13 +9,21 @@ internal static class ConfigurationVersionSelector { public const string EnvironmentVariableName = "GITVERSION_CONFIGURATION_VERSION"; - public static ConfigurationVersion Resolve() => - FeatureSelector.Resolve(EnvironmentVariableName, "v7", "v6", "v7") == "v6" - ? ConfigurationVersion.V6 - : ConfigurationVersion.V7; + public static ConfigurationVersion Resolve() + { + var value = SysEnv.GetEnvironmentVariable(EnvironmentVariableName)?.Trim().ToLowerInvariant(); + if (value == "v6") + { + throw new WarningException($"{EnvironmentVariableName}=v6 was removed in GitVersion 7.1. Unset this variable or set it to v7, then run 'gitversion config migrate' to convert a v6 configuration."); + } - public static string ResolveName() => Resolve() == ConfigurationVersion.V6 ? "v6" : "v7"; + _ = FeatureSelector.Resolve(EnvironmentVariableName, "v7", "v7"); + return ConfigurationVersion.V7; + } - public static bool IsExplicitV6() => - SysEnv.GetEnvironmentVariable(EnvironmentVariableName)?.Trim().Equals("v6", StringComparison.OrdinalIgnoreCase) ?? false; + public static string ResolveName() + { + _ = Resolve(); + return "v7"; + } } diff --git a/src/GitVersion.Core/FeatureSelector.cs b/src/GitVersion.Core/FeatureSelector.cs index 7037d08204..469269f28c 100644 --- a/src/GitVersion.Core/FeatureSelector.cs +++ b/src/GitVersion.Core/FeatureSelector.cs @@ -2,7 +2,7 @@ namespace GitVersion; internal static class FeatureSelector { - public static string Resolve(string environmentVariableName, string defaultValue, string firstValue, string secondValue) + public static string Resolve(string environmentVariableName, string defaultValue, string firstValue, string? secondValue = null) { var value = SysEnv.GetEnvironmentVariable(environmentVariableName)?.Trim(); return value switch @@ -11,7 +11,8 @@ public static string Resolve(string environmentVariableName, string defaultValue _ when value.Equals(firstValue, StringComparison.OrdinalIgnoreCase) => firstValue, _ when value.Equals(secondValue, StringComparison.OrdinalIgnoreCase) => secondValue, _ => throw new WarningException( - $"Unrecognized {environmentVariableName} value '{value}'. Valid values are '{firstValue}' and '{secondValue}'.") + $"Unrecognized {environmentVariableName} value '{value}'. " + + (secondValue is null ? $"Valid value is '{firstValue}'." : $"Valid values are '{firstValue}' and '{secondValue}'.")) }; } }