diff --git a/cmf-cli/Commands/BaseCommand.cs b/cmf-cli/Commands/BaseCommand.cs index 8f6adb647..65e872d95 100644 --- a/cmf-cli/Commands/BaseCommand.cs +++ b/cmf-cli/Commands/BaseCommand.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.CommandLine; +using Cmf.CLI.Utilities; using System.IO; using System.IO.Abstractions; using System.Linq; diff --git a/cmf-cli/Commands/bump/BumpCommand.cs b/cmf-cli/Commands/bump/BumpCommand.cs index 4b87dff55..483c4af90 100644 --- a/cmf-cli/Commands/bump/BumpCommand.cs +++ b/cmf-cli/Commands/bump/BumpCommand.cs @@ -1,5 +1,8 @@ +using System; +using NuGet.Versioning; using Cmf.CLI.Constants; using Cmf.CLI.Core.Attributes; +using Cmf.CLI.Core; using Cmf.CLI.Core.Interfaces; using Cmf.CLI.Core.Objects; using Cmf.CLI.Factories; @@ -9,6 +12,7 @@ using System.CommandLine; using System.IO; using System.IO.Abstractions; +using System.Linq; using System.Threading.Tasks; namespace Cmf.CLI.Commands @@ -20,6 +24,60 @@ namespace Cmf.CLI.Commands [CmfCommand("bump", Id = "bump")] public class BumpCommand : BaseCommand { + internal static void ValidateVersionOptions(Command command, Option version, + Option build, Option prerelease, bool iot = false, bool requireVersion = true, bool npm = false) + where T : SemanticVersion + { + command.Validators.Add(result => + { + if (result.GetResult(version)?.Errors.Any() == true || + result.GetResult(build)?.Errors.Any() == true || + result.GetResult(prerelease)?.Errors.Any() == true) return; + try + { + ValidateBumpVersion(VersionUtilities.GetOptionalVersion(result, version), result.GetValue(build), + result.GetValue(prerelease), iot, requireVersion, npm); + } + catch (CliException exception) + { + result.AddError(exception.Message); + } + catch (InvalidOperationException) + { + // Failed option parsers already supply their own diagnostics. + } + }); + } + + private static void ValidateBumpVersion(SemanticVersion version, string build, string prerelease, + bool iot = false, bool requireVersion = true, bool npm = false) + { + if (requireVersion && version == null) + throw new CliException(string.Format(CliMessages.MissingMandatoryProperty, "version")); + var buildField = iot ? "--buildNrVersion" : "--buildNr"; + var prereleaseField = iot ? "--preReleaseVersion" : "--preRelease"; + if (!string.IsNullOrEmpty(build) && !string.IsNullOrEmpty(prerelease)) + throw new CliException(string.Format(CliMessages.MutuallyExclusiveProperties, + $"{buildField.TrimStart('-')}, {prereleaseField.TrimStart('-')}")); + var suffix = !string.IsNullOrEmpty(build) ? build : prerelease; + if (version != null) + { + if (!string.IsNullOrEmpty(suffix)) + { + var finalVersion = GenericUtilities.RetrieveNewVersion(null, VersionUtilities.GetVersionText(version), suffix); + if (npm) VersionUtilities.ParseNpmVersion(finalVersion, "--version"); + else VersionUtilities.ParseNuGetVersion(finalVersion, "--version"); + } + } + } + + /// Creates the command. + public BumpCommand() { } + + /// Creates the command with a filesystem. + /// The project filesystem. + public BumpCommand(IFileSystem fileSystem) : base(fileSystem) { } + /// /// Configure command /// @@ -33,23 +91,26 @@ public override void Configure(Command cmd) }; cmd.Add(packagePathArgument); - var versionOption = new Option("--version", "-v") + var versionOption = new Option("--version", "-v") { - Description = "Will bump all versions to the version specified" + Description = "Will bump all versions to the version specified", + CustomParser = result => VersionUtilities.ParseVersion(result, text => VersionUtilities.ParseNuGetVersion(text, "--version")) }; - cmd.Add(versionOption); - - var buildNrOption = new Option("--buildNr", "-b") + var buildOption = new Option("--buildNr", "-b") { - Description = "Will add this version next to the version (v-b)" + Description = "Will add this version next to the version (v-b)", + CustomParser = result => VersionUtilities.ParseSuffix(result, "--buildNr") }; - cmd.Add(buildNrOption); - - var preReleaseOption = new Option("--preRelease", "-p") + var prereleaseOption = new Option("--preRelease", "-p") { - Description = "Will add this version as pre-release version (v-p)" + Description = "Will add this version as pre-release version (v-p)", + CustomParser = result => VersionUtilities.ParseSuffix(result, "--preRelease") }; - cmd.Add(preReleaseOption); + cmd.Add(versionOption); + cmd.Add(buildOption); + cmd.Add(prereleaseOption); + BumpCommand.ValidateVersionOptions(cmd, versionOption, buildOption, prereleaseOption, + iot: false, requireVersion: true, npm: false); var rootOption = new Option("--root", "-r") { @@ -61,12 +122,10 @@ public override void Configure(Command cmd) cmd.SetAction((parseResult, cancellationToken) => { var packagePath = parseResult.GetValue(packagePathArgument); - var version = parseResult.GetValue(versionOption); - var buildNr = parseResult.GetValue(buildNrOption); - var preRelease = parseResult.GetValue(preReleaseOption); var root = parseResult.GetValue(rootOption); - Execute(packagePath, version, buildNr, preRelease, root); + Execute(packagePath, parseResult.GetValue(versionOption), + parseResult.GetValue(buildOption), parseResult.GetValue(prereleaseOption), root); return Task.FromResult(0); }); } @@ -81,21 +140,11 @@ public override void Configure(Command cmd) /// The root. /// /// - public void Execute(DirectoryInfo packagePath, string version, string buildNr, string preRelease, string root) + public void Execute(DirectoryInfo packagePath, NuGetVersion version, string buildNr, string preRelease, string root) { using var activity = ExecutionContext.ServiceProvider?.GetService()?.StartExtendedActivity(this.GetType().Name); IFileInfo cmfpackageFile = this.fileSystem.FileInfo.New($"{packagePath}/{CliConstants.CmfPackageFileName}"); - if (string.IsNullOrEmpty(version) && (string.IsNullOrEmpty(buildNr) || string.IsNullOrEmpty(preRelease))) - { - throw new CliException(string.Format(CliMessages.MissingMandatoryProperties, "version, buildNr, preRelease")); - } - - if (!string.IsNullOrEmpty(buildNr) && !string.IsNullOrEmpty(preRelease)) - { - throw new CliException(string.Format(CliMessages.MutuallyExclusiveProperties, "buildNr, preRelease")); - } - // Reading cmfPackage CmfPackage cmfPackage = CmfPackage.Load(cmfpackageFile); @@ -110,8 +159,9 @@ public void Execute(DirectoryInfo packagePath, string version, string buildNr, s /// The version for build Nr. /// The root. /// - public void Execute(CmfPackage cmfPackage, string version, string buildNr, string preRelease, string root) + public void Execute(CmfPackage cmfPackage, NuGetVersion version, string buildNr, string preRelease, string root) { + var suffix = !string.IsNullOrEmpty(buildNr) ? buildNr : preRelease; IDirectoryInfo packageDirectory = cmfPackage.GetFileInfo().Directory; IPackageTypeHandler packageTypeHandler = PackageTypeFactory.GetPackageTypeHandler(cmfPackage); @@ -121,9 +171,7 @@ public void Execute(CmfPackage cmfPackage, string version, string buildNr, strin { "root", root } }; - string versionSuffix = !string.IsNullOrEmpty(buildNr) ? buildNr : preRelease; - - packageTypeHandler.Bump(version, versionSuffix, bumpInformation); + packageTypeHandler.Bump(VersionUtilities.GetVersionText(version), suffix, bumpInformation); // will save with new version cmfPackage.SaveCmfPackage(); diff --git a/cmf-cli/Commands/bump/BumpIoTConfigurationCommand.cs b/cmf-cli/Commands/bump/BumpIoTConfigurationCommand.cs index fd7cac25b..9f62c957f 100644 --- a/cmf-cli/Commands/bump/BumpIoTConfigurationCommand.cs +++ b/cmf-cli/Commands/bump/BumpIoTConfigurationCommand.cs @@ -1,3 +1,4 @@ +using NuGet.Versioning; using System; using System.Collections.Generic; using System.CommandLine; @@ -20,6 +21,13 @@ namespace Cmf.CLI.Commands [CmfCommand(name: "configuration", ParentId = "bump_iot")] public class BumpIoTConfigurationCommand : BumpCommand { + /// Creates the command. + public BumpIoTConfigurationCommand() { } + + /// Creates the command with a filesystem. + /// The project filesystem. + public BumpIoTConfigurationCommand(IFileSystem fileSystem) : base(fileSystem) { } + /// /// Configure command /// @@ -34,23 +42,26 @@ public override void Configure(Command cmd) }; cmd.Add(pathArgument); - var versionOption = new Option("--version", "-v") - { - Description = "Will bump all versions to the version specified" - }; - cmd.Add(versionOption); - - var buildNrVersionOption = new Option("--buildNrVersion", "-b") - { - Description = "Will add this version next to the version (v-b)" - }; - cmd.Add(buildNrVersionOption); - - var preReleaseVersionOption = new Option("--preReleaseVersion", "-p") - { - Description = "Will add this version as pre-release version (v-p)" - }; - cmd.Add(preReleaseVersionOption); + var versionOption = new Option("--version", "-v") + { + Description = "Will bump all versions to the version specified", + CustomParser = result => VersionUtilities.ParseVersion(result, text => string.IsNullOrEmpty(text) ? null : VersionUtilities.ParseNuGetVersion(text, "--version")) + }; + var buildOption = new Option("--buildNrVersion", "-b") + { + Description = "Will add this version next to the version (v-b)", + CustomParser = result => VersionUtilities.ParseSuffix(result, "--buildNrVersion") + }; + var prereleaseOption = new Option("--preReleaseVersion", "-p") + { + Description = "Will add this version as pre-release version (v-p)", + CustomParser = result => VersionUtilities.ParseSuffix(result, "--preReleaseVersion") + }; + cmd.Add(versionOption); + cmd.Add(buildOption); + cmd.Add(prereleaseOption); + BumpCommand.ValidateVersionOptions(cmd, versionOption, buildOption, prereleaseOption, + iot: true, requireVersion: false, npm: false); var masterDataOption = new Option("--masterData", "-md") { @@ -108,9 +119,6 @@ public override void Configure(Command cmd) cmd.SetAction((parseResult, cancellationToken) => { var path = parseResult.GetValue(pathArgument); - var version = parseResult.GetValue(versionOption); - var buildNr = parseResult.GetValue(buildNrVersionOption); - var preReleaseVersion = parseResult.GetValue(preReleaseVersionOption); var isToBumpMasterdata = parseResult.GetValue(masterDataOption); var isToBumpIoT = parseResult.GetValue(iotOption); var packageNames = parseResult.GetValue(packageNamesOption); @@ -120,7 +128,8 @@ public override void Configure(Command cmd) var isToTag = parseResult.GetValue(isToTagOption); var onlyMdCustomization = parseResult.GetValue(mdCustomizationOption); - Execute(path, version, buildNr, preReleaseVersion, isToBumpMasterdata, isToBumpIoT, packageNames, root, group, workflowName, isToTag, onlyMdCustomization); + Execute(path, VersionUtilities.GetOptionalVersion(parseResult.CommandResult, versionOption), + parseResult.GetValue(buildOption), parseResult.GetValue(prereleaseOption), isToBumpMasterdata, isToBumpIoT, packageNames, root, group, workflowName, isToTag, onlyMdCustomization); return Task.FromResult(0); }); } @@ -142,8 +151,9 @@ public override void Configure(Command cmd) /// if set to true [only md customization]. /// /// - public void Execute(IDirectoryInfo path, string version, string buildNrVersion, string preReleaseVersion, bool isToBumpMasterdata, bool isToBumpIoT, string packageNames, string root, string group, string workflowName, bool isToTag, bool onlyMdCustomization) + public void Execute(IDirectoryInfo path, NuGetVersion version, string buildNrVersion, string preReleaseVersion, bool isToBumpMasterdata, bool isToBumpIoT, string packageNames, string root, string group, string workflowName, bool isToTag, bool onlyMdCustomization) { + var suffix = !string.IsNullOrEmpty(buildNrVersion) ? buildNrVersion : preReleaseVersion; using var activity = ExecutionContext.ServiceProvider?.GetService()?.StartExtendedActivity(this.GetType().Name); // Get All AutomationWorkflowFiles Folders @@ -159,13 +169,6 @@ public void Execute(IDirectoryInfo path, string version, string buildNrVersion, automationWorkflowDirectories = automationWorkflowDirectories.Where(awf => awf.Contains(root))?.ToList(); } - if (!string.IsNullOrEmpty(buildNrVersion) && !string.IsNullOrEmpty(preReleaseVersion)) - { - throw new CliException(string.Format(CliMessages.MutuallyExclusiveProperties, "buildNrVersion, preReleaseVersion")); - } - - string versionSuffix = !string.IsNullOrEmpty(buildNrVersion) ? buildNrVersion : preReleaseVersion; - foreach (string automationWorkflowDirectory in automationWorkflowDirectories) { #region Bump AutomationWorkflow @@ -180,7 +183,7 @@ public void Execute(IDirectoryInfo path, string version, string buildNrVersion, groups = groups.Where(gr => gr.Contains(group)).ToList(); } - groups.ForEach(group => IoTUtilities.BumpWorkflowFiles(group, version, versionSuffix, workflowName, packageNames, this.fileSystem)); + groups.ForEach(group => IoTUtilities.BumpWorkflowFiles(group, VersionUtilities.GetVersionText(version), suffix, workflowName, packageNames, this.fileSystem)); } #endregion Bump AutomationWorkflow @@ -189,7 +192,7 @@ public void Execute(IDirectoryInfo path, string version, string buildNrVersion, if (isToBumpMasterdata) { - IoTUtilities.BumpIoTMasterData(automationWorkflowDirectory, version, versionSuffix, this.fileSystem, onlyCustomization: onlyMdCustomization); + IoTUtilities.BumpIoTMasterData(automationWorkflowDirectory, VersionUtilities.GetVersionText(version), suffix, this.fileSystem, onlyCustomization: onlyMdCustomization); } #endregion Bump IoT Masterdata diff --git a/cmf-cli/Commands/bump/BumpIoTCustomizationCommand.cs b/cmf-cli/Commands/bump/BumpIoTCustomizationCommand.cs index d316f847e..201e131c4 100644 --- a/cmf-cli/Commands/bump/BumpIoTCustomizationCommand.cs +++ b/cmf-cli/Commands/bump/BumpIoTCustomizationCommand.cs @@ -1,11 +1,14 @@ +using NuGet.Versioning; using System.CommandLine; using System.IO.Abstractions; +using System.Linq; using Cmf.CLI.Constants; using Cmf.CLI.Core.Attributes; using Cmf.CLI.Core.Enums; using Cmf.CLI.Core.Objects; using Cmf.CLI.Utilities; using Microsoft.Extensions.DependencyInjection; +using Newtonsoft.Json.Linq; using System.Threading.Tasks; namespace Cmf.CLI.Commands @@ -17,6 +20,13 @@ namespace Cmf.CLI.Commands [CmfCommand(name: "customization", ParentId = "bump_iot")] public class BumpIoTCustomizationCommand : BaseCommand { + /// Creates the command. + public BumpIoTCustomizationCommand() { } + + /// Creates the command with a filesystem. + /// The project filesystem. + public BumpIoTCustomizationCommand(IFileSystem fileSystem) : base(fileSystem) { } + /// /// Configure command /// @@ -31,23 +41,26 @@ public override void Configure(Command cmd) }; cmd.Add(pathArgument); - var versionOption = new Option("--version", "-v") + var versionOption = new Option("--version", "-v") { - Description = "Will bump all versions to the version specified" + Description = "Will bump all versions to the version specified", + CustomParser = result => VersionUtilities.ParseVersion(result, text => VersionUtilities.ParseNpmVersion(text, "--version")) }; - cmd.Add(versionOption); - var buildNrVersionOption = new Option("--buildNrVersion", "-b") { - Description = "Will add this version next to the version (v-b)" + Description = "Will add this version next to the version (v-b)", + CustomParser = result => VersionUtilities.ParseSuffix(result, "--buildNrVersion") }; - cmd.Add(buildNrVersionOption); - var preReleaseVersionOption = new Option("--preReleaseVersion", "-p") { - Description = "Will add this version as pre-release version (v-p)" + Description = "Will add this version as pre-release version (v-p)", + CustomParser = result => VersionUtilities.ParseSuffix(result, "--preReleaseVersion") }; + cmd.Add(versionOption); + cmd.Add(buildNrVersionOption); cmd.Add(preReleaseVersionOption); + BumpCommand.ValidateVersionOptions(cmd, versionOption, buildNrVersionOption, preReleaseVersionOption, + iot: true, requireVersion: true, npm: true); var packageNamesOption = new Option("--packageNames", "-pckNames") { @@ -87,21 +100,11 @@ public override void Configure(Command cmd) /// if set to true [is to tag]. /// /// - public void Execute(IDirectoryInfo packagePath, string version, string buildNrVersion, string preReleaseVersion, string packageNames, bool isToTag) + public void Execute(IDirectoryInfo packagePath, SemanticVersion version, string buildNrVersion, string preReleaseVersion, string packageNames, bool isToTag) { using var activity = ExecutionContext.ServiceProvider?.GetService()?.StartExtendedActivity(this.GetType().Name); IFileInfo cmfpackageFile = this.fileSystem.FileInfo.New($"{packagePath}/{CliConstants.CmfPackageFileName}"); - if (string.IsNullOrEmpty(version)) - { - throw new CliException(string.Format(CliMessages.MissingMandatoryProperty, "version")); - } - - if (!string.IsNullOrEmpty(buildNrVersion) && !string.IsNullOrEmpty(preReleaseVersion)) - { - throw new CliException(string.Format(CliMessages.MutuallyExclusiveProperties, "buildNrVersion, preReleaseVersion")); - } - // Reading cmfPackage CmfPackage cmfPackage = CmfPackage.Load(cmfpackageFile); @@ -118,23 +121,39 @@ public void Execute(IDirectoryInfo packagePath, string version, string buildNrVe /// The package names. /// if set to true [is to tag]. /// - public void Execute(CmfPackage cmfPackage, string version, string buildNrVersion, string preReleaseVersion, string packageNames, bool isToTag) + public void Execute(CmfPackage cmfPackage, SemanticVersion version, string buildNrVersion, string preReleaseVersion, string packageNames, bool isToTag) { - string versionSuffix = !string.IsNullOrEmpty(buildNrVersion) ? buildNrVersion : preReleaseVersion; - if (cmfPackage.PackageType != PackageType.IoT) + var suffix = !string.IsNullOrEmpty(buildNrVersion) ? buildNrVersion : preReleaseVersion; + var finalVersion = version == null ? null : GenericUtilities.RetrieveNewVersion(null, VersionUtilities.GetVersionText(version), suffix); + var iotPackages = cmfPackage.PackageType == PackageType.IoT + ? new[] { cmfPackage } + : cmfPackage.GetFileInfo().Directory.LoadCmfPackagesFromSubDirectories(packageType: PackageType.IoT).ToArray(); + + // The public package overload historically permits suffix-only updates. + // Validate every selected npm version before the first package is changed. + if (version == null) { - IDirectoryInfo packageDirectory = cmfPackage.GetFileInfo().Directory; - CmfPackageCollection iotPackages = packageDirectory.LoadCmfPackagesFromSubDirectories(packageType: PackageType.IoT); - foreach (var iotPackage in iotPackages) + foreach (var package in iotPackages) { - // IoT -> src -> Package XPTO - IoTUtilities.BumpIoTCustomPackages(iotPackage.GetFileInfo().DirectoryName, version, versionSuffix, packageNames, this.fileSystem); + foreach (var directory in fileSystem.Directory.GetDirectories(package.GetFileInfo().DirectoryName + "/src/", "*")) + { + var name = directory.Split('/').Last(); + var packageJson = fileSystem.Path.Combine(directory, "package.json"); + if ((string.IsNullOrEmpty(packageNames) || packageNames.Contains(name)) && fileSystem.File.Exists(packageJson)) + { + var current = JObject.Parse(fileSystem.File.ReadAllText(packageJson))["version"]?.Value(); + VersionUtilities.ParseNpmVersion( + GenericUtilities.RetrieveNewVersion(current, null, suffix), "--version"); + } + } } } - else + + foreach (var package in iotPackages) { - IoTUtilities.BumpIoTCustomPackages(cmfPackage.GetFileInfo().DirectoryName, version, versionSuffix, packageNames, this.fileSystem); + IoTUtilities.BumpIoTCustomPackages(package.GetFileInfo().DirectoryName, + finalVersion, finalVersion == null ? suffix : null, packageNames, this.fileSystem); } } } -} \ No newline at end of file +} diff --git a/cmf-cli/Commands/init/InitCommand.cs b/cmf-cli/Commands/init/InitCommand.cs index 71aa15879..43d430ba8 100644 --- a/cmf-cli/Commands/init/InitCommand.cs +++ b/cmf-cli/Commands/init/InitCommand.cs @@ -31,19 +31,19 @@ internal class InitArguments public IDirectoryInfo workingDir { get; set; } public string projectName { get; set; } public string rootPackageName { get; set; } - public string version { get; set; } + public NuGetVersion version { get; set; } public IFileInfo config { get; set; } public IFileInfo appConfig { get; set; } public Uri deploymentDir { get; set; } public Uri ciRepo { get; set; } public List releaseRepos { get; set; } - public string BaseVersion { get; set; } - public string DevTasksVersion { get; set; } - public string HTMLStarterVersion { get; set; } - public string yoGeneratorVersion { get; set; } + public NuGetVersion BaseVersion { get; set; } + public SemanticVersion DevTasksVersion { get; set; } + public SemanticVersion HTMLStarterVersion { get; set; } + public SemanticVersion yoGeneratorVersion { get; set; } public string ngxSchematicsVersion { get; set; } - public string nugetVersion { get; set; } - public string testScenariosNugetVersion { get; set; } + public NuGetVersion nugetVersion { get; set; } + public NuGetVersion testScenariosNugetVersion { get; set; } public IFileInfo infrastructure { get; set; } public Uri nugetRegistry { get; set; } public Uri npmRegistry { get; set; } @@ -132,10 +132,11 @@ public override void Configure(Command cmd) }; cmd.Add(workingDirArgument); - var versionOption = new Option("--version") + var versionOption = new Option("--version") { + CustomParser = result => VersionUtilities.ParseVersion(result, text => VersionUtilities.ParseNuGetVersion(text, "--version")), Description = "Package Version", - DefaultValueFactory = _ => "1.0.0" + DefaultValueFactory = _ => NuGetVersion.Parse("1.0.0") }; cmd.Add(versionOption); @@ -162,31 +163,35 @@ public override void Configure(Command cmd) cmd.Add(repositoryTypeOption); // Template-time options - var baseVersionOption = new Option("--baseVersion", "--MESVersion") + var baseVersionOption = new Option("--baseVersion", "--MESVersion") { + CustomParser = result => VersionUtilities.ParseVersion(result, text => VersionUtilities.ParseMesVersion(text, "--baseVersion/--MESVersion")), Description = "Target CM framework/MES version", Required = true }; cmd.Add(baseVersionOption); - var devTasksVersionOption = new Option("--DevTasksVersion") + var devTasksVersionOption = new Option("--DevTasksVersion") { + CustomParser = result => VersionUtilities.ParseVersion(result, text => string.IsNullOrEmpty(text) ? null : VersionUtilities.ParseSemanticVersion(text, "--DevTasksVersion")), Description = CliMessages.InitLegacyDevTasksDescription, Hidden = true, Required = false }; cmd.Add(devTasksVersionOption); - var htmlStarterVersionOption = new Option("--HTMLStarterVersion") + var htmlStarterVersionOption = new Option("--HTMLStarterVersion") { + CustomParser = result => VersionUtilities.ParseVersion(result, text => string.IsNullOrEmpty(text) ? null : VersionUtilities.ParseSemanticVersion(text, "--HTMLStarterVersion")), Description = CliMessages.InitLegacyHtmlStarterDescription, Hidden = true, Required = false }; cmd.Add(htmlStarterVersionOption); - var yoGeneratorVersionOption = new Option("--yoGeneratorVersion") + var yoGeneratorVersionOption = new Option("--yoGeneratorVersion") { + CustomParser = result => VersionUtilities.ParseVersion(result, text => string.IsNullOrEmpty(text) ? null : VersionUtilities.ParseSemanticVersion(text, "--yoGeneratorVersion")), Description = CliMessages.InitLegacyYoGeneratorDescription, Hidden = true, Required = false @@ -200,16 +205,18 @@ public override void Configure(Command cmd) }; cmd.Add(ngxSchematicsVersionOption); - var nugetVersionOption = new Option("--nugetVersion") + var nugetVersionOption = new Option("--nugetVersion") { + CustomParser = result => VersionUtilities.ParseVersion(result, text => VersionUtilities.ParseNuGetVersion(text, "--nugetVersion")), Description = "NuGet versions to target. Defaults to --MESVersion when not specified.", Required = false, DefaultValueFactory = argResult => { try { return argResult.GetValue(baseVersionOption); } catch { return null; } } }; cmd.Add(nugetVersionOption); - var testScenariosNugetVersionOption = new Option("--testScenariosNugetVersion") + var testScenariosNugetVersionOption = new Option("--testScenariosNugetVersion") { + CustomParser = result => VersionUtilities.ParseVersion(result, text => VersionUtilities.ParseNuGetVersion(text, "--testScenariosNugetVersion")), Description = "Test Scenarios NuGet version. Defaults to --MESVersion when not specified.", Required = false, DefaultValueFactory = argResult => { try { return argResult.GetValue(baseVersionOption); } catch { return null; } } @@ -343,17 +350,18 @@ public override void Configure(Command cmd) projectName = parseResult.GetValue(projectNameArgument), rootPackageName = parseResult.GetValue(rootPackageNameArgument), workingDir = parseResult.GetValue(workingDirArgument), - version = parseResult.GetValue(versionOption), + version = parseResult.GetValue(versionOption), config = parseResult.GetValue(configOption), appConfig = parseResult.GetValue(appConfigOption), repositoryType = parseResult.GetValue(repositoryTypeOption), - BaseVersion = parseResult.GetValue(baseVersionOption), - DevTasksVersion = parseResult.GetValue(devTasksVersionOption), - HTMLStarterVersion = parseResult.GetValue(htmlStarterVersionOption), - yoGeneratorVersion = parseResult.GetValue(yoGeneratorVersionOption), + // Forward the validated input verbatim; native version parsing trims whitespace. + BaseVersion = parseResult.GetValue(baseVersionOption), + DevTasksVersion = VersionUtilities.GetOptionalVersion(parseResult.CommandResult, devTasksVersionOption), + HTMLStarterVersion = VersionUtilities.GetOptionalVersion(parseResult.CommandResult, htmlStarterVersionOption), + yoGeneratorVersion = VersionUtilities.GetOptionalVersion(parseResult.CommandResult, yoGeneratorVersionOption), ngxSchematicsVersion = parseResult.GetValue(ngxSchematicsVersionOption), - nugetVersion = parseResult.GetValue(nugetVersionOption), - testScenariosNugetVersion = parseResult.GetValue(testScenariosNugetVersionOption), + nugetVersion = parseResult.GetValue(nugetVersionOption), + testScenariosNugetVersion = parseResult.GetValue(testScenariosNugetVersionOption), deploymentDir = parseResult.GetValue(deploymentDirOption), ciRepo = parseResult.GetValue(ciRepoOption), releaseRepos = parseResult.GetValue(releaseReposOption), @@ -382,9 +390,10 @@ public override void Configure(Command cmd) /// internal void Execute(InitArguments x) { + var mesVersion = x.BaseVersion; using var activity = ExecutionContext.ServiceProvider?.GetService()?.StartExtendedActivity(this.GetType().Name); - Log.Information($"Starting scaffolding for MES Version: {x.BaseVersion}"); + Log.Information($"Starting scaffolding for MES Version: {VersionUtilities.GetVersionText(x.BaseVersion)}"); var args = new List() { @@ -438,15 +447,15 @@ internal void Execute(InitArguments x) "--appId", x.appId, "--appIcon", appIconPath, "--appDescription", x.appDescription, - "--appTargetFramework", x.BaseVersion, + "--appTargetFramework", VersionUtilities.GetVersionText(x.BaseVersion), "--appAuthor", x.appAuthor, "--appLicensedApplication", x.appLicensedApplication }); } - if (x.version != null) + if (x.version != null) { - args.AddRange(new [] {"--packageVersion", x.version}); + args.AddRange(new [] {"--packageVersion", VersionUtilities.GetVersionText(x.version)}); } if (x.deploymentDir != null) @@ -518,19 +527,16 @@ internal void Execute(InitArguments x) args.AddRange(new[] { "--CIRepo", x.ciRepo.AbsoluteUri }); } - if (x.BaseVersion != null) - { - args.AddRange(new[] { "--MESVersion", x.BaseVersion }); - args.AddRange(new[] { "--projectConfigV2", (NuGetVersion.Parse(x.BaseVersion).Major >= 12).ToString() }); - } + args.AddRange(new[] { "--MESVersion", VersionUtilities.GetVersionText(x.BaseVersion) }); + args.AddRange(new[] { "--projectConfigV2", (mesVersion.Major >= 12).ToString() }); - args.AddRange(new [] {"--DevTasksVersion", x.DevTasksVersion ?? ""}); - args.AddRange(new [] {"--HTMLStarterVersion", x.HTMLStarterVersion ?? ""}); - args.AddRange(new [] {"--yoGeneratorVersion", x.yoGeneratorVersion ?? ""}); + args.AddRange(new [] {"--DevTasksVersion", VersionUtilities.GetVersionText(x.DevTasksVersion) ?? ""}); + args.AddRange(new [] {"--HTMLStarterVersion", VersionUtilities.GetVersionText(x.HTMLStarterVersion) ?? ""}); + args.AddRange(new [] {"--yoGeneratorVersion", VersionUtilities.GetVersionText(x.yoGeneratorVersion) ?? ""}); - args.AddRange(new [] {"--nugetVersion", x.nugetVersion}); + args.AddRange(new [] {"--nugetVersion", VersionUtilities.GetVersionText(x.nugetVersion)}); - args.AddRange(new [] {"--testScenariosNugetVersion", x.testScenariosNugetVersion}); + args.AddRange(new [] {"--testScenariosNugetVersion", VersionUtilities.GetVersionText(x.testScenariosNugetVersion)}); #region infrastructure @@ -584,20 +590,13 @@ internal void Execute(InitArguments x) if (string.IsNullOrWhiteSpace(x.ngxSchematicsVersion)) { - var mesVer = NuGetVersion.Parse(x.BaseVersion); - x.ngxSchematicsVersion = GenericUtilities.GetNgxSchematicsVersion(mesVer, x.npmRegistry.AbsoluteUri, this.npmDistTagResolver); + x.ngxSchematicsVersion = GenericUtilities.GetNgxSchematicsVersion(mesVersion, x.npmRegistry.AbsoluteUri, this.npmDistTagResolver); } Log.Information($"Using ngx-schematics version: {x.ngxSchematicsVersion}"); args.AddRange(new [] {"--ngxSchematicsVersion", x.ngxSchematicsVersion}); - var version = new NuGetVersion(x.BaseVersion); - args.AddRange(new []{ "--dotnetSDKVersion", ExecutionContext.ServiceProvider.GetService().DotNetSdk(version) }); - - if(version < new NuGetVersion(10, 0, 0)) - { - throw new CliException("MES Versions under 10 are no longer supported with the newest version of the CLI. Please use cmf-cli 5.8.0 or lower."); - } + args.AddRange(new []{ "--dotnetSDKVersion", ExecutionContext.ServiceProvider.GetService().DotNetSdk(mesVersion) }); #endregion diff --git a/cmf-cli/Commands/new/TestCommand.cs b/cmf-cli/Commands/new/TestCommand.cs index 54bad2b3f..066175589 100644 --- a/cmf-cli/Commands/new/TestCommand.cs +++ b/cmf-cli/Commands/new/TestCommand.cs @@ -1,9 +1,12 @@ using Cmf.CLI.Constants; +using Cmf.CLI.Core; using Cmf.CLI.Core.Attributes; +using Cmf.CLI.Core.Constants; using Cmf.CLI.Core.Enums; using Cmf.CLI.Core.Objects; using Cmf.CLI.Utilities; using System.Collections.Generic; +using System.Linq; using System.CommandLine; using System.IO.Abstractions; using System.Threading.Tasks; @@ -32,10 +35,11 @@ public TestCommand(IFileSystem fileSystem) : base("tests", PackageType.Tests, fi /// public override void Configure(Command cmd) { - var versionOption = new Option("--version") + var versionOption = new Option("--version") { Description = "Package Version", - DefaultValueFactory = _ => "1.0.0" + CustomParser = result => VersionUtilities.ParseVersion(result, text => VersionUtilities.ParseNuGetVersion(text, "--version")), + DefaultValueFactory = _ => NuGetVersion.Parse("1.0.0") }; cmd.Add(versionOption); @@ -57,16 +61,20 @@ protected override List GenerateArgs(IDirectoryInfo projectRoot, IDirect /// Execute the command /// /// the package version - public void Execute(string version) + public void Execute(NuGetVersion version) { CommandUtilities.ThrowIfNoProjectConfig(ExecutionContext.Instance); + var projectConfig = ExecutionContext.Instance.ProjectConfig; + var mesVersion = projectConfig.MESVersion ?? throw VersionUtilities.InvalidVersion(null, + nameof(ProjectConfig.MESVersion), CoreMessages.NuGetVersionExpectedFormat, CoreConstants.ProjectConfigFileName); + var testScenariosNugetVersion = projectConfig.TestScenariosNugetVersion ?? throw VersionUtilities.InvalidVersion(null, + nameof(ProjectConfig.TestScenariosNugetVersion), CoreMessages.NuGetVersionExpectedFormat, CoreConstants.ProjectConfigFileName); var (organization, product) = GetOrganizationAndProductFromProjectConfig(); var packageName = $"{organization}.{product}.Tests"; var projectRoot = FileSystemUtilities.GetProjectRoot(this.fileSystem); var repoType = ExecutionContext.Instance.ProjectConfig.RepositoryType ?? CliConstants.DefaultRepositoryType; - var projectConfig = ExecutionContext.Instance.ProjectConfig; var tenant = projectConfig.Tenant; var args = new List() { @@ -75,14 +83,12 @@ public void Execute(string version) // template symbols "--name", packageName, - "--packageVersion", version, + "--packageVersion", VersionUtilities.GetVersionText(version), "--idSegment", tenant, "--Tenant", tenant }; var projectName = projectConfig.ProjectName; - var mesVersion = projectConfig.MESVersion; - var testScenariosNugetVersion = projectConfig.TestScenariosNugetVersion; var legacyProjectConfig = projectConfig as ProjectConfigV1; var restPort = legacyProjectConfig?.RESTPort; var htmlPort = legacyProjectConfig?.HTMLPort; @@ -138,9 +144,9 @@ public void Execute(string version) } this.executedArgs = args.ToArray(); - base.RunCommand(args); - base.RegisterAsDependencyInParent(packageName, version, projectRoot.FullName, isTestPackage: true); - base.RegisterAsDependencyInParent("Cmf.Custom.Tests.MasterData", version, projectRoot.FullName, isTestPackage: true); + RunCommand(args); + base.RegisterAsDependencyInParent(packageName, VersionUtilities.GetVersionText(version), projectRoot.FullName, isTestPackage: true); + base.RegisterAsDependencyInParent("Cmf.Custom.Tests.MasterData", VersionUtilities.GetVersionText(version), projectRoot.FullName, isTestPackage: true); } } -} \ No newline at end of file +} diff --git a/cmf-cli/Commands/upgrade/UpgradeBaseCommand.cs b/cmf-cli/Commands/upgrade/UpgradeBaseCommand.cs index 609ef8f43..a443f71e7 100644 --- a/cmf-cli/Commands/upgrade/UpgradeBaseCommand.cs +++ b/cmf-cli/Commands/upgrade/UpgradeBaseCommand.cs @@ -1,3 +1,6 @@ +using NuGet.Versioning; +using System.Linq; +using System; using Cmf.CLI.Core; using Cmf.CLI.Core.Attributes; using Cmf.CLI.Core.Constants; @@ -6,7 +9,6 @@ using Cmf.CLI.Factories; using Cmf.CLI.Utilities; using Microsoft.Extensions.DependencyInjection; -using NuGet.Versioning; using System.Collections.Generic; using System.CommandLine; using System.IO; @@ -22,6 +24,13 @@ namespace Cmf.CLI.Commands [CmfCommand(name: "base", Id = "upgrade_base", ParentId = "upgrade", Description = "Upgrade the baseline version of the MES.")] public class UpgradeBaseCommand : BaseCommand { + private readonly Func loadProjectConfig = new ProjectConfigService().Load; + + internal UpgradeBaseCommand(IFileSystem fileSystem, Func loadProjectConfig) : base(fileSystem) + { + this.loadProjectConfig = loadProjectConfig; + } + /// /// constructor for System.IO filesystem @@ -51,15 +60,17 @@ public override void Configure(Command cmd) }; cmd.Add(packagePathArgument); - var baseVersionArgument = new Argument("BaseVersion") + var baseVersionArgument = new Argument("BaseVersion") { - Description = "New framework/MES Version" + Description = "New framework/MES Version", + CustomParser = result => VersionUtilities.ParseVersion(result, text => VersionUtilities.ParseMesVersion(text, "BaseVersion")) }; cmd.Add(baseVersionArgument); - var iotVersionOption = new Option("--iotVersion", "-iot") + var iotVersionOption = new Option("--iotVersion", "-iot") { - Description = "New MES version for the IoT workflows & masterdatas." + Description = "New MES version for the IoT workflows & masterdatas.", + CustomParser = result => VersionUtilities.ParseVersion(result, text => VersionUtilities.ParseMesVersion(text, "--iotVersion")) }; cmd.Add(iotVersionOption); @@ -74,11 +85,11 @@ public override void Configure(Command cmd) cmd.SetAction((parseResult, cancellationToken) => { var packagePath = parseResult.GetValue(packagePathArgument); - var baseVersion = parseResult.GetValue(baseVersionArgument); - var iotVersion = parseResult.GetValue(iotVersionOption); + var baseVersion = parseResult.GetValue(baseVersionArgument); + var iotVersion = parseResult.GetValue(iotVersionOption); var iotPackagesToIgnore = parseResult.GetValue(iotPackagesToIgnoreOption); - Execute(packagePath, baseVersion, iotVersion, iotPackagesToIgnore); + Execute(packagePath, baseVersion, iotVersion, iotPackagesToIgnore); return Task.FromResult(0); }); } @@ -91,16 +102,23 @@ public override void Configure(Command cmd) /// New MES version for the IoT workflows & masterdata /// IoT packages to ignore when updating the MES version of the tasks in IoT workflows /// - public void Execute(IDirectoryInfo packagePath, string baseVersion, string iotVersion, List iotPackagesToIgnore) + public void Execute(IDirectoryInfo packagePath, NuGetVersion baseVersion, NuGetVersion iotVersion, List iotPackagesToIgnore) { + var configurations = new HashSet(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); + ValidateProjectConfig(packagePath, configurations); using var activity = ExecutionContext.ServiceProvider?.GetService()?.StartExtendedActivity(this.GetType().Name); var cmfPackagePaths = packagePath.GetFiles("cmfpackage.json", SearchOption.AllDirectories); + + foreach (var path in cmfPackagePaths) + { + ValidateProjectConfig(path.Directory, configurations); + } foreach (IFileInfo path in cmfPackagePaths) { Log.Debug($"Processing {path.FullName}"); - Execute(CmfPackage.Load(path), baseVersion, iotVersion, iotPackagesToIgnore); + UpgradePackage(CmfPackage.Load(path), baseVersion, iotVersion, iotPackagesToIgnore); } UpdateProjectConfig(packagePath, baseVersion); @@ -115,12 +133,35 @@ public void Execute(IDirectoryInfo packagePath, string baseVersion, string iotVe /// New MES version for the IoT workflows & masterdata /// IoT packages to ignore when updating the MES version of the tasks in IoT workflows /// - public void Execute(CmfPackage cmfPackage, string version, string iotVersion, List iotPackagesToIgnore) + public void Execute(CmfPackage cmfPackage, NuGetVersion version, NuGetVersion iotVersion, List iotPackagesToIgnore) { - IDirectoryInfo packageDirectory = cmfPackage.GetFileInfo().Directory; + ValidateProjectConfig(cmfPackage.GetFileInfo().Directory, + new HashSet(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal)); + UpgradePackage(cmfPackage, version, iotVersion, iotPackagesToIgnore); + } + + private static void UpgradePackage(CmfPackage cmfPackage, NuGetVersion version, NuGetVersion iotVersion, List iotPackagesToIgnore) + { IPackageTypeHandler packageTypeHandler = PackageTypeFactory.GetPackageTypeHandler(cmfPackage); - packageTypeHandler.UpgradeBase(version, iotVersion, iotPackagesToIgnore); + packageTypeHandler.UpgradeBase(VersionUtilities.GetVersionText(version), VersionUtilities.GetVersionText(iotVersion), iotPackagesToIgnore); + } + + private void ValidateProjectConfig(IDirectoryInfo directory, HashSet configurations) + { + while (directory != null) + { + var config = fileSystem.FileInfo.New(fileSystem.Path.Combine(directory.FullName, CoreConstants.ProjectConfigFileName)); + if (config.Exists) + { + if (configurations.Add(config.FullName)) + { + loadProjectConfig(config); + } + return; + } + directory = directory.Parent; + } } #region Utilities @@ -130,7 +171,7 @@ public void Execute(CmfPackage cmfPackage, string version, string iotVersion, Li /// /// The package path. /// The new Base version. - private void UpdateProjectConfig(IDirectoryInfo packagePath, string baseVersion) + private void UpdateProjectConfig(IDirectoryInfo packagePath, NuGetVersion baseVersion) { IFileInfo projectConfig = this.fileSystem.FileInfo.New(Path.Combine(packagePath.FullName, CoreConstants.ProjectConfigFileName)); @@ -141,10 +182,10 @@ private void UpdateProjectConfig(IDirectoryInfo packagePath, string baseVersion) string text = fileSystem.File.ReadAllText(projectConfig.FullName); foreach (string key in new string[] { "MESVersion", "NugetVersion", "TestScenariosNugetVersion" }) { - text = UpgradeBaseUtilities.UpdateJsonValue(text, key, baseVersion); + text = UpgradeBaseUtilities.UpdateJsonValue(text, key, VersionUtilities.GetVersionText(baseVersion)); } - if (NuGetVersion.Parse(baseVersion).Major >= 11) + if (baseVersion.Major >= 11) { // TODO: find a more elegant way to apply these changes to files/packages when this command is executed. // For the moment, sneaking this if-statement in will do the job but long-term we'll need an approach that diff --git a/core/CoreMessages.Designer.cs b/core/CoreMessages.Designer.cs index 0e032c46e..6c7436863 100644 --- a/core/CoreMessages.Designer.cs +++ b/core/CoreMessages.Designer.cs @@ -23,9 +23,9 @@ namespace Cmf.CLI.Core { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class CoreMessages { - + private static global::System.Resources.ResourceManager resourceMan; - + private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] @@ -230,5 +230,32 @@ public static string NuGetMissingPassword { } } + /// Looks up the invalid version input error. + public static string InvalidVersionInput => ResourceManager.GetString("InvalidVersionInput", resourceCulture); + + /// Looks up the missing required version error. + public static string MissingVersionInput => ResourceManager.GetString("MissingVersionInput", resourceCulture); + + /// Looks up the optional version input source description. + public static string VersionInputSource => ResourceManager.GetString("VersionInputSource", resourceCulture); + + /// Looks up the missing version value placeholder. + public static string MissingVersionValue => ResourceManager.GetString("MissingVersionValue", resourceCulture); + + /// Looks up the expected NuGet version format. + public static string NuGetVersionExpectedFormat => ResourceManager.GetString("NuGetVersionExpectedFormat", resourceCulture); + + /// Looks up the expected semantic version format. + public static string SemanticVersionExpectedFormat => ResourceManager.GetString("SemanticVersionExpectedFormat", resourceCulture); + + /// Looks up the project configuration error with its source file. + public static string InvalidProjectConfiguration => ResourceManager.GetString("InvalidProjectConfiguration", resourceCulture); + + /// Looks up the expected version suffix format. + public static string VersionSuffixExpectedFormat => ResourceManager.GetString("VersionSuffixExpectedFormat", resourceCulture); + + /// Looks up the existing unsupported MES version error. + public static string UnsupportedMesVersion => ResourceManager.GetString("UnsupportedMesVersion", resourceCulture); + } } diff --git a/core/CoreMessages.resx b/core/CoreMessages.resx index 1762df858..cb3bedaa7 100644 --- a/core/CoreMessages.resx +++ b/core/CoreMessages.resx @@ -83,4 +83,33 @@ Customer Portal PAT has expired. Generate a replacement PAT and supply it with --token; in a pipeline, update CustomerPortalPAT. + + Invalid version for '{0}'{1}: '{2}'. Expected {3}. + 0 - Field; 1 - Optional source; 2 - Invalid value; 3 - Format or range + + + Required version '{0}'{1} is missing or empty (value: '{2}'). Expected {3}. + + + in '{0}' + + + <missing> + + + a NuGet version such as '11.2.0' or '12.0.0-beta.1' + + + a semantic version in major.minor.patch form, optionally followed by a prerelease label or build metadata, such as '1.2.3-beta.1+build.4' + + + Invalid project configuration '{0}': {1} + 0 - Configuration file path; 1 - Validation or JSON error + + + a version suffix such as '1234', 'beta.1' or 'beta.1+build.4' + + + MES Versions under 10 are no longer supported with the newest version of the CLI. Please use cmf-cli 5.8.0 or lower. + diff --git a/core/Objects/ProjectConfig/ProjectConfigV1.cs b/core/Objects/ProjectConfig/ProjectConfigV1.cs index 2afa4de6e..6e531baa0 100644 --- a/core/Objects/ProjectConfig/ProjectConfigV1.cs +++ b/core/Objects/ProjectConfig/ProjectConfigV1.cs @@ -2,6 +2,7 @@ using System.Text.Json.Serialization; using Cmf.CLI.Core.Enums; using Newtonsoft.Json; +using Newtonsoft.Json.Linq; using NuGet.Versioning; namespace Cmf.CLI.Core.Objects; @@ -69,25 +70,37 @@ public class VersionStringConverter : Newtonsoft.Json.JsonConverter { public override T ReadJson(JsonReader reader, Type objectType, T existingValue, bool hasExistingValue, JsonSerializer serializer) { - if (reader.TokenType == JsonToken.Null || reader.Value is null) + if (reader.TokenType == JsonToken.Null) { return null; } - var value = reader.Value?.ToString(); + var field = reader.Path; + var token = JToken.Load(reader); + var value = token.Type == JTokenType.String ? token.Value() : token.ToString(Formatting.None); if (string.IsNullOrWhiteSpace(value)) { return null; } - if (typeof(T) == typeof(NuGetVersion)) + try { - return (T)(object)NuGetVersion.Parse(value); - } + if (typeof(T) == typeof(NuGetVersion)) + { + return (T)(object)NuGetVersion.Parse(value); + } - if (typeof(T) == typeof(SemanticVersion)) + if (typeof(T) == typeof(SemanticVersion)) + { + return (T)(object)SemanticVersion.Parse(value); + } + } + catch (ArgumentException exception) { - return (T)(object)SemanticVersion.Parse(value); + var expected = typeof(T) == typeof(NuGetVersion) + ? CoreMessages.NuGetVersionExpectedFormat : CoreMessages.SemanticVersionExpectedFormat; + throw new JsonSerializationException( + string.Format(CoreMessages.InvalidVersionInput, field, string.Empty, value, expected), exception); } throw new NotSupportedException($"Unsupported version type: {typeof(T).FullName}"); @@ -134,4 +147,4 @@ public override void WriteJson( JsonWriter writer, object value, JsonSerializer { } -} \ No newline at end of file +} diff --git a/core/Objects/ProjectConfigService.cs b/core/Objects/ProjectConfigService.cs index 77b739169..1d7cbcca4 100644 --- a/core/Objects/ProjectConfigService.cs +++ b/core/Objects/ProjectConfigService.cs @@ -1,9 +1,10 @@ +using System; using System.IO.Abstractions; using Cmf.CLI.Core.Constants; using Cmf.CLI.Utilities; +using NuGet.Versioning; using Newtonsoft.Json; using Newtonsoft.Json.Linq; -using NuGet.Versioning; namespace Cmf.CLI.Core.Objects; @@ -32,19 +33,50 @@ public ProjectConfig Load(IFileSystem fileSystem) return null; } Log.Debug($"Loading .project-config.json"); - var json = fileSystem.File.ReadAllText(projectCfg); - var jsonObject = JObject.Parse(json); - var mesVersion = NuGetVersion.TryParse(jsonObject.Value("MESVersion"), out var parsedVersion) - ? parsedVersion - : null; - var projectConfigType = mesVersion != null && mesVersion.Major >= 12 - ? typeof(ProjectConfigV2) - : typeof(ProjectConfigV1); - this.ProjectConfig = (ProjectConfig)JsonConvert.DeserializeObject(json, projectConfigType); + this.ProjectConfig = Load(fileSystem.FileInfo.New(projectCfg)); Log.Debug($"Loaded .project-config.json"); isInsideProject = true; } } return this.ProjectConfig; } -} \ No newline at end of file + + /// Loads and validates a configuration file without using the current project cache. + /// The configuration file to load. + /// The validated project configuration. + public ProjectConfig Load(IFileInfo projectConfigFile) + { + using var reader = projectConfigFile.OpenText(); + var json = reader.ReadToEnd(); + ProjectConfig projectConfig; + string mesVersionText = null; + try + { + var jsonObject = JObject.Parse(json); + var mesVersionProperty = jsonObject.Property(nameof(ProjectConfig.MESVersion), StringComparison.OrdinalIgnoreCase); + mesVersionText = mesVersionProperty?.Value.ToString(); + var mesVersion = string.IsNullOrWhiteSpace(mesVersionText) + ? null + : NuGetVersion.Parse(mesVersionText); + var projectConfigType = mesVersion?.Major >= 12 + ? typeof(ProjectConfigV2) + : typeof(ProjectConfigV1); + + // Reuse the version parsed for model selection instead of parsing it again during deserialization. + mesVersionProperty?.Remove(); + projectConfig = (ProjectConfig)jsonObject.ToObject(projectConfigType); + projectConfig.MESVersion = mesVersion; + } + catch (ArgumentException exception) + { + var message = string.Format(CoreMessages.InvalidVersionInput, nameof(ProjectConfig.MESVersion), + string.Empty, mesVersionText, CoreMessages.NuGetVersionExpectedFormat); + throw new CliException(string.Format(CoreMessages.InvalidProjectConfiguration, projectConfigFile.FullName, message), exception); + } + catch (JsonException exception) + { + throw new CliException(string.Format(CoreMessages.InvalidProjectConfiguration, projectConfigFile.FullName, exception.Message), exception); + } + return projectConfig; + } +} diff --git a/core/Utilities/VersionUtilities.cs b/core/Utilities/VersionUtilities.cs new file mode 100644 index 000000000..792627e69 --- /dev/null +++ b/core/Utilities/VersionUtilities.cs @@ -0,0 +1,132 @@ +using System; +using System.CommandLine; +using System.CommandLine.Parsing; +using System.Linq; +using System.Text.RegularExpressions; +using Cmf.CLI.Core; +using NuGet.Versioning; + +namespace Cmf.CLI.Utilities; + +/// Parses and formats versions used by CLI commands and plugins. +public static class VersionUtilities +{ + // Translate input failures into command-line diagnostics before any handler runs. + /// Parses a version argument, reporting validation failures as command-line errors. + /// The parsed version type. + /// The argument being parsed. + /// The version parser. + /// The parsed value, or the default value when validation fails. + public static T ParseVersion(ArgumentResult result, Func parse) + { + try + { + return parse(result.Tokens.SingleOrDefault()?.Value); + } + catch (CliException exception) + { + result.AddError(exception.Message); + return default; + } + } + + /// Parses a NuGet version while preserving its original text. + /// The version text. + /// The option or configuration field used in diagnostics. + /// The parsed NuGet version. + public static NuGetVersion ParseNuGetVersion(string text, string field) + { + if (!NuGetVersion.TryParse(text, out var version)) + throw InvalidVersion(text, field, CoreMessages.NuGetVersionExpectedFormat); + // NuGet's parser trims whitespace; its native constructor can retain the original text. + return new NuGetVersion(version.Version, version.ReleaseLabels, version.Metadata, text); + } + + /// Parses a semantic version. + /// The version text. + /// The option or configuration field used in diagnostics. + /// The parsed semantic version. + public static SemanticVersion ParseSemanticVersion(string text, string field) + { + if (!SemanticVersion.TryParse(text, out var version)) + throw InvalidVersion(text, field, CoreMessages.SemanticVersionExpectedFormat); + return version; + } + + /// Parses a MES version and enforces the minimum supported major version of 10. + /// The version text. + /// The option or configuration field used in diagnostics. + /// The supported MES version. + public static NuGetVersion ParseMesVersion(string text, string field) + { + var version = ParseNuGetVersion(text, field); + if (version.Major < 10) + throw new CliException(CoreMessages.UnsupportedMesVersion); + return version; + } + + /// Creates a diagnostic for a missing or invalid version. + /// The supplied version text. + /// The affected option or configuration field. + /// The expected version format. + /// The optional source of the value. + /// The exception describing the validation failure. + public static CliException InvalidVersion(string value, string field, string expected, string source = null) + { + var location = string.IsNullOrEmpty(source) ? string.Empty : string.Format(CoreMessages.VersionInputSource, source); + var message = string.IsNullOrWhiteSpace(value) ? CoreMessages.MissingVersionInput : CoreMessages.InvalidVersionInput; + return new CliException(string.Format(message, field, location, value ?? CoreMessages.MissingVersionValue, expected)); + } + + /// Parses a semantic version using strict npm version syntax. + /// The version text. + /// The option or configuration field used in diagnostics. + /// The parsed npm version. + public static SemanticVersion ParseNpmVersion(string value, string field) + { + var version = ParseSemanticVersion(value, field); + // NuGet's parser accepts relaxed numeric syntax that npm rejects. + const string numeric = @"(?:0|[1-9][0-9]*)"; + const string prereleaseIdentifier = @"(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)"; + var pattern = $@"\A{numeric}\.{numeric}\.{numeric}(?:-{prereleaseIdentifier}(?:\.{prereleaseIdentifier})*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?\z"; + if (value.Length > 256 || !Regex.IsMatch(value, pattern, RegexOptions.NonBacktracking)) + throw InvalidVersion(value, field, CoreMessages.SemanticVersionExpectedFormat); + return version; + } + + private static void ValidateVersionSuffix(string value, string field) + { + if (string.IsNullOrWhiteSpace(value) || !NuGetVersion.TryParse($"1.0.0-{value}", out _)) + { + var message = string.IsNullOrWhiteSpace(value) ? CoreMessages.MissingVersionInput : CoreMessages.InvalidVersionInput; + throw new CliException(string.Format(message, field, string.Empty, + value ?? CoreMessages.MissingVersionValue, CoreMessages.VersionSuffixExpectedFormat)); + } + } + + /// Parses an optional build or prerelease suffix. + /// The argument being parsed. + /// The option name used in diagnostics. + /// The validated suffix, or the default value when validation fails. + public static string ParseSuffix(ArgumentResult result, string field) + => ParseVersion(result, text => + { + if (!string.IsNullOrEmpty(text)) ValidateVersionSuffix(text, field); + return text; + }); + + /// Formats a version, preserving original NuGet text when available. + /// The version to format, or null. + /// The version text, or null when no version is supplied. + public static string GetVersionText(SemanticVersion version) + => version is NuGetVersion nuget ? nuget.OriginalVersion ?? nuget.ToFullString() : version?.ToFullString(); + + // System.CommandLine cannot convert an explicitly empty token to a null native version. + /// Reads an optional version, treating an explicitly empty token as null. + /// The semantic version type. + /// The parsed symbol containing the option. + /// The version option. + /// The parsed version, or null for an explicitly empty token. + public static T GetOptionalVersion(SymbolResult result, Option option) where T : SemanticVersion + => result.GetResult(option)?.Tokens.SingleOrDefault()?.Value == string.Empty ? null : result.GetValue(option); +} diff --git a/docs/src/03-explore/commands/bump.md b/docs/src/03-explore/commands/bump.md index 9203d916b..b58781ab5 100644 --- a/docs/src/03-explore/commands/bump.md +++ b/docs/src/03-explore/commands/bump.md @@ -1,5 +1,7 @@ # bump +Versions and suffixes are checked before package updates. Empty suffixes are ignored; invalid values report the option and expected format. Package versions below 10 remain supported. + Usage diff --git a/docs/src/03-explore/commands/bump_iot_configuration.md b/docs/src/03-explore/commands/bump_iot_configuration.md index 74b04fb55..dd1669ec2 100644 --- a/docs/src/03-explore/commands/bump_iot_configuration.md +++ b/docs/src/03-explore/commands/bump_iot_configuration.md @@ -1,5 +1,7 @@ # bump iot configuration +Versions and suffixes are checked before configuration updates. Empty suffixes are ignored; omitting `--version` or passing an empty value preserves suffix-only updates. Invalid values report the option and expected format. + Usage diff --git a/docs/src/03-explore/commands/bump_iot_customization.md b/docs/src/03-explore/commands/bump_iot_customization.md index 43cef3ac1..e985c5e8e 100644 --- a/docs/src/03-explore/commands/bump_iot_customization.md +++ b/docs/src/03-explore/commands/bump_iot_customization.md @@ -1,5 +1,7 @@ # bump iot customization +The final version, including any suffix, must be an exact npm SemVer such as `1.2.3` or `1.2.3-beta.1+build.4`. Short (`1.2`) and four-part (`1.2.3.4`) versions are rejected before files change. Empty suffixes are ignored; package versions below 10 remain supported. + Usage diff --git a/docs/src/03-explore/commands/init.md b/docs/src/03-explore/commands/init.md index 2a05d812a..51864010d 100644 --- a/docs/src/03-explore/commands/init.md +++ b/docs/src/03-explore/commands/init.md @@ -17,6 +17,8 @@ cmf init test --tenant test --baseVersion 12.0.0-beta.2 --ciRepo https://dev.cri * New configs omit unused database server/replica backup paths, AlwaysOn, ReportServer, Installation, Temporary, and Gateway fields; model API properties remain for legacy compatibility. * `--DevTasksVersion`, `--HTMLStarterVersion`, and `--yoGeneratorVersion` are hidden legacy options but remain accepted. MES v9 and earlier require CM CLI **5.8.0 or earlier**. +Versions are checked before registry lookups or scaffolding; invalid values leave files unchanged. `--baseVersion` / `--MESVersion` requires a NuGet MES version with major version 10 or higher, including prereleases. Package and NuGet overrides use NuGet syntax; nonempty legacy tool overrides use semantic version syntax. Empty legacy overrides are ignored. These overrides have no MES minimum, and explicit `--ngxSchematicsVersion` npm dist-tags remain supported. Errors identify the option, rejected value, and expected format. + Use `cmf init --help` for the installed version's options. diff --git a/docs/src/03-explore/commands/new_test.md b/docs/src/03-explore/commands/new_test.md index 4a5194872..16d834f3a 100644 --- a/docs/src/03-explore/commands/new_test.md +++ b/docs/src/03-explore/commands/new_test.md @@ -1,5 +1,9 @@ # new test +The project configuration must provide `MESVersion` and `TestScenariosNugetVersion` as NuGet versions. The CLI requires MES 10 or later; the minimum does not apply to test-scenario or package versions. + +`--version` defaults to `1.0.0` and accepts NuGet release, prerelease, metadata, and four-part versions. Invalid or missing required versions report the option or configuration field before scaffolding or dependency resolution; files remain unchanged. + Usage diff --git a/docs/src/03-explore/commands/upgrade_base.md b/docs/src/03-explore/commands/upgrade_base.md new file mode 100644 index 000000000..065389bf7 --- /dev/null +++ b/docs/src/03-explore/commands/upgrade_base.md @@ -0,0 +1,11 @@ +# upgrade base + +Upgrade the MES baseline of a package directory and its project configuration: + +```sh +cmf upgrade base . 12.0.0-beta.1 --iotVersion 12.0.0-beta.1 +``` + +`BaseVersion` and a supplied `--iotVersion` require NuGet MES versions with major version 10 or higher; prereleases are supported. Omitting `--iotVersion` preserves the existing IoT workflow and masterdata behavior. + +Arguments and target project configurations are validated before files change, including targets outside the current project. Errors identify the argument or configuration field and expected format. diff --git a/docs/src/03-explore/config-files/.pages b/docs/src/03-explore/config-files/.pages index 42c4f4fc5..797636b5f 100644 --- a/docs/src/03-explore/config-files/.pages +++ b/docs/src/03-explore/config-files/.pages @@ -1,4 +1,5 @@ nav: + - project-config.json - infrastructure.json - repositories.json - cmfpackage.json diff --git a/docs/src/03-explore/config-files/project-config.json/index.md b/docs/src/03-explore/config-files/project-config.json/index.md new file mode 100644 index 000000000..d2df7c91e --- /dev/null +++ b/docs/src/03-explore/config-files/project-config.json/index.md @@ -0,0 +1,15 @@ +# .project-config.json + +The CLI validates nonblank version fields when loading the project configuration. Errors identify the file, field, rejected value, and expected format before processing changes files. Fields may be omitted, null, or blank unless required by a command. + +| Field | Format | Required | +| --- | --- | --- | +| `MESVersion` | NuGet | By commands that use it, including `cmf new test` | +| `NugetVersion` | NuGet | No | +| `TestScenariosNugetVersion` | NuGet | By `cmf new test` | +| `DevTasksVersion`, `HTMLStarterVersion`, `YoGeneratorVersion` | Semantic version | No; used in MES 10/11 configurations | +| `NGXSchematicsVersion` | npm version or dist-tag | Existing defaults apply | + +Both version formats support prereleases and build metadata. NuGet also accepts four-part versions such as `1.2.3.4`; semantic versions use `major.minor.patch`. Schematics dist-tags such as `release-1120` remain supported. + +The CLI requires MES 10 or later at command entry; loading configuration alone does not enforce that minimum or require `MESVersion`. Other versions may be below 10. MES 12+ selects the V2 model; earlier or omitted MES versions select V1. diff --git a/tests/Specs/ConfigurationVersionCommands.cs b/tests/Specs/ConfigurationVersionCommands.cs new file mode 100644 index 000000000..fdc8da1a5 --- /dev/null +++ b/tests/Specs/ConfigurationVersionCommands.cs @@ -0,0 +1,193 @@ +using System; +using System.Collections.Generic; +using System.CommandLine; +using System.Linq; +using Cmf.CLI.Commands; +using Cmf.CLI.Commands.New; +using Cmf.CLI.Core.Objects; +using Cmf.CLI.Services; +using Cmf.CLI.Utilities; +using FluentAssertions; +using Microsoft.Extensions.DependencyInjection; +using Moq; +using Newtonsoft.Json.Linq; +using NuGet.Versioning; +using Xunit; + +namespace tests.Specs; + +public class ConfigurationVersionCommands : IDisposable +{ + private readonly ServiceProvider previousServices = ExecutionContext.ServiceProvider; + private readonly Mock dependencies = new(MockBehavior.Strict); + + public ConfigurationVersionCommands() + { + ExecutionContext.ServiceProvider = new ServiceCollection() + .AddSingleton() + .AddSingleton(dependencies.Object) + .BuildServiceProvider(); + } + + [Theory] + [InlineData("build")] + [InlineData("new data")] + [InlineData("new html")] + public void InvalidConfiguration_RejectsCommandAtLoadTimeBeforeOperations(string name) + { + var fileSystem = ProjectConfigVersionValidation.CreateFileSystem(new JObject { ["MESVersion"] = "invalid-version" }); + var before = fileSystem.AllFiles.ToDictionary(path => path, path => fileSystem.File.ReadAllText(path)); + + Action createCommand = () => + { + switch (name) + { + case "build": _ = new BuildCommand(fileSystem); break; + case "new data": _ = new DataCommand(fileSystem); break; + case "new html": _ = new HTMLCommand(fileSystem); break; + } + }; + + createCommand.Should().Throw() + .WithMessage("*.project-config.json*MESVersion*invalid-version*Expected a NuGet version*"); + dependencies.VerifyNoOtherCalls(); + fileSystem.AllFiles.ToDictionary(path => path, path => fileSystem.File.ReadAllText(path)).Should().BeEquivalentTo(before); + } + + [Theory] + [InlineData(false, null)] + [InlineData(true, null)] + [InlineData(true, "")] + [InlineData(true, " ")] + public void NewTest_RequiresMesVersionBeforeOperations(bool includeField, string value) + { + var config = new JObject { ["TestScenariosNugetVersion"] = "11.2.0" }; + if (includeField) + { + config["MESVersion"] = value == null ? JValue.CreateNull() : new JValue(value); + } + var fileSystem = ProjectConfigVersionValidation.CreateFileSystem(config); + var before = fileSystem.AllFiles.ToDictionary(path => path, path => fileSystem.File.ReadAllText(path)); + var handler = new Mock(fileSystem) { CallBase = true }; + handler.Setup(x => x.RunCommand(It.IsAny>())); + var command = new Command("test"); + handler.Object.Configure(command); + var console = new TestConsole(); + + var exitCode = command.Parse(Array.Empty()).Invoke(console); + + exitCode.Should().NotBe(0); + console.Error.ToString().Should().Contain("MESVersion").And.Contain(".project-config.json") + .And.Contain("missing or empty").And.Contain("Expected a NuGet version"); + handler.Verify(x => x.RunCommand(It.IsAny>()), Times.Never); + dependencies.VerifyNoOtherCalls(); + fileSystem.AllFiles.ToDictionary(path => path, path => fileSystem.File.ReadAllText(path)).Should().BeEquivalentTo(before); + } + + [Theory] + [InlineData(false, null)] + [InlineData(true, null)] + [InlineData(true, "")] + [InlineData(true, " ")] + public void NewTest_RequiresTestScenariosVersionBeforeOperations(bool includeField, string value) + { + var config = new JObject { ["MESVersion"] = "11.2.0" }; + if (includeField) + { + config["TestScenariosNugetVersion"] = value == null ? JValue.CreateNull() : new JValue(value); + } + var fileSystem = ProjectConfigVersionValidation.CreateFileSystem(config); + var before = fileSystem.AllFiles.ToDictionary(path => path, path => fileSystem.File.ReadAllText(path)); + var command = new Command("test"); + new TestCommand(fileSystem).Configure(command); + var console = new TestConsole(); + + var exitCode = command.Parse(Array.Empty()).Invoke(console); + + exitCode.Should().NotBe(0); + console.Error.ToString().Should().Contain("TestScenariosNugetVersion") + .And.Contain(".project-config.json").And.Contain("missing or empty").And.Contain("Expected a NuGet version"); + dependencies.VerifyNoOtherCalls(); + fileSystem.AllFiles.ToDictionary(path => path, path => fileSystem.File.ReadAllText(path)).Should().BeEquivalentTo(before); + } + + [Theory] + [InlineData("invalid")] + [InlineData("")] + [InlineData(" ")] + [InlineData("1.2.3-beta..1")] + [InlineData(null)] + public void NewTest_InvalidPackageVersionStopsBeforeOperationsAndPreservesFiles(string value) + { + var fileSystem = ProjectConfigVersionValidation.CreateFileSystem(new JObject + { + ["MESVersion"] = "11.2.0", + ["TestScenariosNugetVersion"] = "11.2.0" + }); + var before = fileSystem.AllFiles.ToDictionary(path => path, path => fileSystem.File.ReadAllText(path)); + var handler = new Mock(fileSystem) { CallBase = true }; + handler.Setup(x => x.RunCommand(It.IsAny>())); + var command = new Command("test"); + handler.Object.Configure(command); + var console = new TestConsole(); + var args = value == null ? new[] { "--version" } : new[] { "--version", value }; + + var exitCode = command.Parse(args).Invoke(console); + + exitCode.Should().NotBe(0); + console.Error.ToString().Should().Contain("--version"); + if (value != null) + { + console.Error.ToString().Should().Contain($"'{value}'").And.Contain("Expected a NuGet version"); + } + handler.Verify(x => x.RunCommand(It.IsAny>()), Times.Never); + dependencies.VerifyNoOtherCalls(); + fileSystem.AllFiles.ToDictionary(path => path, path => fileSystem.File.ReadAllText(path)).Should().BeEquivalentTo(before); + } + + [Theory] + [InlineData(null, "1.0.0")] + [InlineData("1.2.3", "1.2.3")] + [InlineData("1.2.3-beta.1+build.4", "1.2.3-beta.1+build.4")] + [InlineData("1.2.3.4", "1.2.3.4")] + [InlineData("1.2", "1.2")] + [InlineData("01.2.3", "01.2.3")] + [InlineData("1.2.3.0", "1.2.3.0")] + [InlineData(" 1.2.3 ", " 1.2.3 ")] + public void NewTest_ValidPackageVersionPreservesDefaultAndScaffoldingArguments(string value, string expected) + { + var fileSystem = ProjectConfigVersionValidation.CreateFileSystem(new JObject + { + ["MESVersion"] = "11.2.0", + ["TestScenariosNugetVersion"] = "11.2.0" + }); + var packagePath = fileSystem.Path.Combine(fileSystem.Directory.GetCurrentDirectory(), "cmfpackage.json"); + fileSystem.File.WriteAllText(packagePath, + "{\"packageId\":\"Cmf.Custom\",\"packageType\":\"Root\",\"version\":\"1.0.0\"}"); + dependencies.Setup(x => x.DotNetTargetFramework(It.IsAny())).Returns("net8.0"); + List templateArguments = null; + var handler = new Mock(fileSystem) { CallBase = true }; + handler.Setup(x => x.RunCommand(It.IsAny>())) + .Callback>(args => templateArguments = args.ToList()); + var command = new Command("test"); + handler.Object.Configure(command); + var console = new TestConsole(); + + var exitCode = command.Parse(value == null ? Array.Empty() : new[] { "--version", value }).Invoke(console); + + console.Error.ToString().Should().BeEmpty(); + exitCode.Should().Be(0); + handler.Verify(x => x.RunCommand(It.IsAny>()), Times.Once); + templateArguments[templateArguments.IndexOf("--packageVersion") + 1].Should().Be(expected); + var package = JObject.Parse(fileSystem.File.ReadAllText(packagePath)); + package["testPackages"].Values().Should().HaveCount(2) + .And.OnlyContain(dependency => dependency["version"].Value() == expected); + dependencies.Verify(x => x.DotNetTargetFramework(It.IsAny()), Times.Once); + } + + public void Dispose() + { + ExecutionContext.ServiceProvider.Dispose(); + ExecutionContext.ServiceProvider = previousServices; + } +} diff --git a/tests/Specs/Init.cs b/tests/Specs/Init.cs index bf49c735f..1a004e8b1 100644 --- a/tests/Specs/Init.cs +++ b/tests/Specs/Init.cs @@ -643,7 +643,7 @@ public void Init_WithoutJsonFiles_ScaffoldsSupportedVersions(string mesVersion, .AddSingleton() .AddSingleton() .BuildServiceProvider(); - new Cmf.CLI.Commands.New.TestCommand().Execute("1.0.0"); + new Cmf.CLI.Commands.New.TestCommand().Execute(NuGetVersion.Parse("1.0.0")); File.Exists("Cmf.Custom.Tests/cmfpackage.json").Should().BeTrue(); File.ReadAllText("Cmf.Custom.Tests/integration.runsettings").Should().NotContain("<%="); }); diff --git a/tests/Specs/InitVersionValidation.cs b/tests/Specs/InitVersionValidation.cs new file mode 100644 index 000000000..a62b5ceab --- /dev/null +++ b/tests/Specs/InitVersionValidation.cs @@ -0,0 +1,254 @@ +using System; +using System.Collections.Generic; +using System.CommandLine; +using System.Linq; +using Cmf.CLI.Commands; +using Cmf.CLI.Core.Objects; +using Cmf.CLI.Services; +using Cmf.CLI.Utilities; +using FluentAssertions; +using Microsoft.Extensions.DependencyInjection; +using Moq; +using NuGet.Versioning; +using System.IO.Abstractions.TestingHelpers; +using Xunit; + +namespace tests.Specs; + +public class InitVersionValidation : IDisposable +{ + private readonly ServiceProvider previousServices = ExecutionContext.ServiceProvider; + private readonly MockFileSystem fileSystem = new(); + private readonly Mock resolver = new(MockBehavior.Strict); + private readonly Mock dependencies = new(MockBehavior.Strict); + private readonly Mock handler; + private readonly Command command = new("init"); + private List templateArguments; + + public InitVersionValidation() + { + ExecutionContext.ServiceProvider = new ServiceCollection() + .AddSingleton(new VersionService("CriticalManufacturing.CLI", "6.0.1")) + .AddSingleton(dependencies.Object) + .BuildServiceProvider(); + fileSystem.AddFile("existing.txt", new MockFileData("Keep this file unchanged.")); + fileSystem.AddFile(".project-config.json", new MockFileData("{\"MESVersion\":\"11.0.0\"}")); + fileSystem.AddFile("cmfpackage.json", new MockFileData("{\"version\":\"1.0.0\"}")); + handler = new Mock(fileSystem, resolver.Object) { CallBase = true }; + handler.Setup(x => x.RunCommand(It.IsAny>())) + .Callback>(args => templateArguments = args.ToList()); + handler.Object.Configure(command); + } + + public static IEnumerable InvalidInputs() + { + foreach (var option in new[] + { + "--baseVersion", "--MESVersion", "--version", "--nugetVersion", + "--testScenariosNugetVersion", "--DevTasksVersion", "--HTMLStarterVersion", "--yoGeneratorVersion" + }) + { + foreach (var value in new[] { "not-a-version", "", " ", "1.2.3-beta..1" }) + { + if (value == "" && (option == "--DevTasksVersion" || option == "--HTMLStarterVersion" || option == "--yoGeneratorVersion")) + { + continue; + } + yield return new object[] { option, value }; + } + } + + foreach (var option in new[] { "--DevTasksVersion", "--HTMLStarterVersion", "--yoGeneratorVersion" }) + { + yield return new object[] { option, "01.2.3" }; + yield return new object[] { option, " 1.2.3 " }; + } + + foreach (var option in new[] { "--baseVersion", "--MESVersion" }) + { + yield return new object[] { option, "9.9.9" }; + yield return new object[] { option, "9.9.9-rc.1" }; + } + } + + [Theory] + [MemberData(nameof(InvalidInputs))] + public void InvalidVersion_StopsBeforeResolversOrScaffoldingAndPreservesFiles(string option, string value) + { + var before = fileSystem.AllFiles.ToDictionary(path => path, path => fileSystem.File.ReadAllText(path)); + var options = new List(); + if (option != "--baseVersion" && option != "--MESVersion") + { + options.AddRange(new[] { "--baseVersion", "12.0.0-beta.1" }); + } + options.AddRange(new[] { option, value }); + var console = new TestConsole(); + + var result = command.Parse(Arguments(options.ToArray())); + result.Errors.Should().NotBeEmpty(); + var exitCode = result.Invoke(console); + + exitCode.Should().NotBe(0); + if ((option == "--baseVersion" || option == "--MESVersion") && NuGetVersion.TryParse(value, out var parsed) && parsed.Major < 10) + { + console.Error.ToString().Should().Contain("MES Versions under 10 are no longer supported with the newest version of the CLI. Please use cmf-cli 5.8.0 or lower."); + } + else + { + console.Error.ToString().Should().Contain(option).And.Contain($"'{value}'").And.Contain("Expected "); + } + AssertNoOperationsOrFileChanges(before); + } + + [Fact] + public void MissingMesVersion_StopsBeforeOperations() + { + var before = fileSystem.AllFiles.ToDictionary(path => path, path => fileSystem.File.ReadAllText(path)); + var console = new TestConsole(); + + var exitCode = command.Parse(Arguments()).Invoke(console); + + exitCode.Should().NotBe(0); + console.Error.ToString().Should().Contain("--baseVersion").And.Contain("required"); + AssertNoOperationsOrFileChanges(before); + } + + [Theory] + [InlineData("--version")] + [InlineData("--nugetVersion")] + [InlineData("--testScenariosNugetVersion")] + [InlineData("--DevTasksVersion")] + [InlineData("--HTMLStarterVersion")] + [InlineData("--yoGeneratorVersion")] + public void OptionWithoutValue_StopsBeforeOperations(string option) + { + var before = fileSystem.AllFiles.ToDictionary(path => path, path => fileSystem.File.ReadAllText(path)); + var console = new TestConsole(); + + var exitCode = command.Parse(Arguments("--baseVersion", "12.0.0-beta.1", option)).Invoke(console); + + exitCode.Should().NotBe(0); + console.Error.ToString().Should().Contain(option); + AssertNoOperationsOrFileChanges(before); + } + + [Theory] + [InlineData("--baseVersion", "10.0.0")] + [InlineData("--MESVersion", "10.0.0-alpha.1")] + [InlineData("--MESVersion", "11.1.5")] + [InlineData("--baseVersion", "12.0.0-beta.2+build.4")] + [InlineData("--baseVersion", "12.0.0.0")] + [InlineData("--baseVersion", " 12.0.0 ")] + public void ValidMesVersion_PreservesDefaultsAndPassesTypedVersionToDependencies(string option, string input) + { + var version = NuGetVersion.Parse(input); + dependencies.Setup(x => x.DotNetSdk(It.Is(v => v.ToFullString() == version.ToFullString()))) + .Returns("10.0.301"); + var expectedSchematics = GenericUtilities.GetNpmDistTag(version); + if (version.IsPrerelease) + { + var distTag = expectedSchematics; + resolver.Setup(x => x.ResolveDistTag("@criticalmanufacturing/ngx-schematics", distTag)) + .ReturnsAsync("12.0.0-beta.99"); + expectedSchematics = "12.0.0-beta.99"; + } + var console = new TestConsole(); + + var exitCode = command.Parse(Arguments(option, input)).Invoke(console); + + exitCode.Should().Be(0, console.Error.ToString()); + console.Error.ToString().Should().BeEmpty(); + TemplateValue("--MESVersion").Should().Be(input); + TemplateValue("--nugetVersion").Should().Be(input); + TemplateValue("--testScenariosNugetVersion").Should().Be(input); + TemplateValue("--packageVersion").Should().Be("1.0.0"); + TemplateValue("--DevTasksVersion").Should().BeEmpty(); + TemplateValue("--HTMLStarterVersion").Should().BeEmpty(); + TemplateValue("--yoGeneratorVersion").Should().BeEmpty(); + TemplateValue("--ngxSchematicsVersion").Should().Be(expectedSchematics); + TemplateValue("--projectConfigV2").Should().Be((version.Major >= 12).ToString()); + handler.Verify(x => x.RunCommand(It.IsAny>()), Times.Once); + dependencies.VerifyAll(); + resolver.VerifyAll(); + } + + [Theory] + [InlineData("--DevTasksVersion")] + [InlineData("--HTMLStarterVersion")] + [InlineData("--yoGeneratorVersion")] + public void EmptyLegacyOverride_PreservesOmittedOverrideBehavior(string option) + { + dependencies.Setup(x => x.DotNetSdk(It.IsAny())).Returns("10.0.301"); + var console = new TestConsole(); + + var exitCode = command.Parse(Arguments("--baseVersion", "12.0.0", option, "")).Invoke(console); + + exitCode.Should().Be(0, console.Error.ToString()); + console.Error.ToString().Should().BeEmpty(); + TemplateValue("--DevTasksVersion").Should().BeEmpty(); + TemplateValue("--HTMLStarterVersion").Should().BeEmpty(); + TemplateValue("--yoGeneratorVersion").Should().BeEmpty(); + handler.Verify(x => x.RunCommand(It.IsAny>()), Times.Once); + dependencies.VerifyAll(); + resolver.VerifyNoOtherCalls(); + } + + [Theory] + [InlineData("1.2.3", "1.2.3.4", "1.2.3")] + [InlineData("1.2.3-beta.1+build.4", "1.2.3-rc.1+build.4", "1.2.3-alpha.1+build.4")] + [InlineData("1.2", "01.2.3", "1.2.3+build.4")] + [InlineData(" 1.2.3 ", "1.2.3.0", "1.2.3-alpha.1")] + public void ValidOverrides_PreserveVersionsBelowTenAndExplicitNpmDistTags(string packageVersion, string nugetVersion, string legacyVersion) + { + dependencies.Setup(x => x.DotNetSdk(It.IsAny())).Returns("10.0.301"); + var console = new TestConsole(); + + var exitCode = command.Parse(Arguments( + "--baseVersion", "12.0.0-beta.1", + "--version", packageVersion, + "--nugetVersion", nugetVersion, + "--testScenariosNugetVersion", nugetVersion, + "--DevTasksVersion", legacyVersion, + "--HTMLStarterVersion", legacyVersion, + "--yoGeneratorVersion", legacyVersion, + "--ngxSchematicsVersion", "my-custom-schematics-tag")).Invoke(console); + + exitCode.Should().Be(0, console.Error.ToString()); + console.Error.ToString().Should().BeEmpty(); + TemplateValue("--packageVersion").Should().Be(packageVersion); + TemplateValue("--nugetVersion").Should().Be(nugetVersion); + TemplateValue("--testScenariosNugetVersion").Should().Be(nugetVersion); + TemplateValue("--DevTasksVersion").Should().Be(legacyVersion); + TemplateValue("--HTMLStarterVersion").Should().Be(legacyVersion); + TemplateValue("--yoGeneratorVersion").Should().Be(legacyVersion); + TemplateValue("--ngxSchematicsVersion").Should().Be("my-custom-schematics-tag"); + resolver.VerifyNoOtherCalls(); + } + + private static string[] Arguments(params string[] options) => new[] + { + "project", "--tenant", "test", + "--ciRepo", "https://ci.example", "--releaseRepos", "https://release.example" + }.Concat(options).ToArray(); + + private string TemplateValue(string name) + { + templateArguments.Should().NotBeNull(); + templateArguments.Should().Contain(name); + return templateArguments[templateArguments.IndexOf(name) + 1]; + } + + private void AssertNoOperationsOrFileChanges(Dictionary before) + { + handler.Verify(x => x.RunCommand(It.IsAny>()), Times.Never); + resolver.VerifyNoOtherCalls(); + dependencies.VerifyNoOtherCalls(); + fileSystem.AllFiles.ToDictionary(path => path, path => fileSystem.File.ReadAllText(path)).Should().BeEquivalentTo(before); + } + + public void Dispose() + { + ExecutionContext.ServiceProvider.Dispose(); + ExecutionContext.ServiceProvider = previousServices; + } +} diff --git a/tests/Specs/ProjectConfigVersionValidation.cs b/tests/Specs/ProjectConfigVersionValidation.cs new file mode 100644 index 000000000..53077253b --- /dev/null +++ b/tests/Specs/ProjectConfigVersionValidation.cs @@ -0,0 +1,224 @@ +using System; +using System.Collections.Generic; +using System.IO.Abstractions.TestingHelpers; +using System.Linq; +using Cmf.CLI.Core.Objects; +using Cmf.CLI.Utilities; +using FluentAssertions; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Xunit; + +namespace tests.Specs; + +public class ProjectConfigVersionValidation +{ + [Theory] + [InlineData(false, null)] + [InlineData(true, null)] + [InlineData(true, "")] + [InlineData(true, " ")] + public void Load_PreservesMissingOrBlankMesVersion(bool includeField, string value) + { + var json = new JObject(); + if (includeField) + { + json["MESVersion"] = value == null ? JValue.CreateNull() : new JValue(value); + } + var fileSystem = CreateFileSystem(json); + + var before = fileSystem.AllFiles.ToDictionary(path => path, path => fileSystem.File.ReadAllText(path)); + + var config = new ProjectConfigService().Load(fileSystem); + + config.Should().BeOfType(); + config.MESVersion.Should().BeNull(); + fileSystem.AllFiles.ToDictionary(path => path, path => fileSystem.File.ReadAllText(path)).Should().BeEquivalentTo(before); + } + + public static IEnumerable MalformedVersions() + { + foreach (var field in new[] { "MESVersion", "NugetVersion", "TestScenariosNugetVersion" }) + { + yield return new object[] { "11.2.0", field, "invalid-version" }; + yield return new object[] { "12.0.0-beta.1", field, "1.2.3-beta..1" }; + } + foreach (var field in new[] { "DevTasksVersion", "HTMLStarterVersion", "YoGeneratorVersion" }) + { + yield return new object[] { "11.2.0", field, "invalid-version" }; + yield return new object[] { "11.2.0", field, "1.2.3.4" }; + } + } + + [Theory] + [MemberData(nameof(MalformedVersions))] + public void Load_RejectsMalformedVersionsWithFieldValueAndSource(string mesVersion, string field, string value) + { + var json = new JObject { ["MESVersion"] = mesVersion, [field] = value }; + var fileSystem = CreateFileSystem(json); + + AssertRejectedWithoutChanges(fileSystem, field, value); + } + + [Theory] + [InlineData("MESVersion")] + [InlineData("NugetVersion")] + [InlineData("TestScenariosNugetVersion")] + [InlineData("DevTasksVersion")] + public void Load_RejectsStructuredVersionValues(string field) + { + var json = new JObject { ["MESVersion"] = "11.2.0", [field] = new JObject() }; + + AssertRejectedWithoutChanges(CreateFileSystem(json), field, "{}"); + } + + [Theory] + [InlineData("9.9.9")] + [InlineData("9.9.9-rc.1")] + [InlineData("9.9.9-rc.1+build.4")] + public void Load_PreservesLegacyMesVersionsWithoutApplyingTheCliSupportGate(string value) + { + var fileSystem = CreateFileSystem(new JObject { ["MESVersion"] = value }); + + var before = fileSystem.AllFiles.ToDictionary(path => path, path => fileSystem.File.ReadAllText(path)); + var service = new ProjectConfigService(); + + var config = service.Load(fileSystem); + + config.Should().BeOfType(); + config.MESVersion.ToFullString().Should().Be(value); + service.ProjectConfig.Should().BeSameAs(config); + fileSystem.AllFiles.ToDictionary(path => path, path => fileSystem.File.ReadAllText(path)).Should().BeEquivalentTo(before); + } + + [Theory] + [InlineData("10.0.0", typeof(ProjectConfigV1))] + [InlineData("10.0.0-alpha.1", typeof(ProjectConfigV1))] + [InlineData("11.2.0", typeof(ProjectConfigV1))] + [InlineData("12.0.0-beta.1+build.4", typeof(ProjectConfigV2))] + [InlineData("13.0.0", typeof(ProjectConfigV2))] + public void Load_PreservesValidVersionsAndSelectsModel(string value, Type expectedType) + { + var json = new JObject + { + ["MESVersion"] = value, + ["NugetVersion"] = "1.2.3.4", + ["TestScenariosNugetVersion"] = "1.2.3-beta.1+build.4", + ["NGXSchematicsVersion"] = "custom-dist-tag", + ["DevTasksVersion"] = "1.2.3-alpha.1+build.4", + ["HTMLStarterVersion"] = "1.2.3", + ["YoGeneratorVersion"] = "1.2.3-rc.1" + }; + var fileSystem = CreateFileSystem(json); + + var config = new ProjectConfigService().Load(fileSystem); + + config.GetType().Should().Be(expectedType); + config.MESVersion.ToFullString().Should().Be(value); + config.NugetVersion.ToFullString().Should().Be("1.2.3.4"); + config.TestScenariosNugetVersion.ToFullString().Should().Be("1.2.3-beta.1+build.4"); + config.NGXSchematicsVersion.Should().Be("custom-dist-tag"); + if (config is ProjectConfigV1 legacy) + { + legacy.DevTasksVersion.ToFullString().Should().Be("1.2.3-alpha.1+build.4"); + legacy.HTMLStarterVersion.ToFullString().Should().Be("1.2.3"); + legacy.YoGeneratorVersion.ToFullString().Should().Be("1.2.3-rc.1"); + } + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public void Load_PreservesBlankOptionalVersions(string value) + { + var json = new JObject { ["MESVersion"] = "11.2.0" }; + foreach (var field in new[] { "NugetVersion", "TestScenariosNugetVersion", "DevTasksVersion", "HTMLStarterVersion", "YoGeneratorVersion" }) + { + json[field] = value == null ? JValue.CreateNull() : new JValue(value); + } + + var config = (ProjectConfigV1)new ProjectConfigService().Load(CreateFileSystem(json)); + + config.NugetVersion.Should().BeNull(); + config.TestScenariosNugetVersion.Should().BeNull(); + config.DevTasksVersion.Should().BeNull(); + config.HTMLStarterVersion.Should().BeNull(); + config.YoGeneratorVersion.Should().BeNull(); + } + + [Fact] + public void Load_DoesNotRequireOptionalVersions() + { + var config = new ProjectConfigService().Load(CreateFileSystem(new JObject { ["MESVersion"] = "11.2.0" })); + + config.MESVersion.Major.Should().Be(11); + config.NugetVersion.Should().BeNull(); + config.TestScenariosNugetVersion.Should().BeNull(); + } + + [Fact] + public void Load_PreservesCaseInsensitivePropertyMatching() + { + var json = new JObject { ["mesVersion"] = "12.0.0-beta.1", ["nugetVersion"] = "1.0.0" }; + + var config = new ProjectConfigService().Load(CreateFileSystem(json)); + + config.Should().BeOfType(); + config.MESVersion.ToFullString().Should().Be("12.0.0-beta.1"); + config.NugetVersion.ToFullString().Should().Be("1.0.0"); + } + + [Fact] + public void Load_V2PreservesExistingBehaviorForUnusedLegacyFields() + { + var json = new JObject { ["MESVersion"] = "12.0.0", ["DevTasksVersion"] = "unused-legacy-value" }; + + new ProjectConfigService().Load(CreateFileSystem(json)).Should().BeOfType(); + } + + [Fact] + public void Load_OutsideProjectReturnsNull() + { + new ProjectConfigService().Load(new MockFileSystem()).Should().BeNull(); + } + + [Fact] + public void Load_DoesNotCacheInvalidConfigurationAndAllowsCorrection() + { + var fileSystem = CreateFileSystem(new JObject { ["MESVersion"] = "12.0.0", ["NugetVersion"] = "bad-version" }); + var service = new ProjectConfigService(); + + Action load = () => service.Load(fileSystem); + load.Should().Throw(); + service.ProjectConfig.Should().BeNull(); + fileSystem.File.WriteAllText(ConfigPath(fileSystem), "{\"MESVersion\":\"12.0.0\",\"NugetVersion\":\"1.0.0\"}"); + + service.Load(fileSystem).NugetVersion.ToFullString().Should().Be("1.0.0"); + } + + private static CliException AssertRejectedWithoutChanges(MockFileSystem fileSystem, string field, string value) + { + var before = fileSystem.AllFiles.ToDictionary(path => path, path => fileSystem.File.ReadAllText(path)); + var service = new ProjectConfigService(); + + Action load = () => service.Load(fileSystem); + + var exception = load.Should().Throw().Which; + exception.Message.Should().Contain(ConfigPath(fileSystem)).And.Contain(field).And.Contain(value).And.Contain("Expected "); + service.ProjectConfig.Should().BeNull(); + fileSystem.AllFiles.ToDictionary(path => path, path => fileSystem.File.ReadAllText(path)).Should().BeEquivalentTo(before); + return exception; + } + + internal static MockFileSystem CreateFileSystem(JObject config) + { + var fileSystem = new MockFileSystem(); + fileSystem.AddFile(ConfigPath(fileSystem), new MockFileData(config.ToString(Formatting.None))); + fileSystem.AddFile("cmfpackage.json", new MockFileData("{\"version\":\"1.0.0\"}")); + return fileSystem; + } + + private static string ConfigPath(MockFileSystem fileSystem) + => fileSystem.Path.Combine(fileSystem.Directory.GetCurrentDirectory(), ".project-config.json"); +} diff --git a/tests/Specs/ScaffoldingProjectContext.cs b/tests/Specs/ScaffoldingProjectContext.cs index 245b22393..3a3d57f1a 100644 --- a/tests/Specs/ScaffoldingProjectContext.cs +++ b/tests/Specs/ScaffoldingProjectContext.cs @@ -1,3 +1,4 @@ +using NuGet.Versioning; using System; using System.IO.Abstractions; using System.IO.Abstractions.TestingHelpers; @@ -71,7 +72,7 @@ private static void Execute(string name, IFileSystem fileSystem, IDirectoryInfo case "html": new HTMLCommand(fileSystem).Execute(directory, "1.0.0"); break; case "help": new HelpCommand(fileSystem).Execute(directory, "1.0.0"); break; case "iot": new IoTCommand(fileSystem).Execute(directory, "1.0.0", null, false); break; - case "test": new TestCommand(fileSystem).Execute("1.0.0"); break; + case "test": new TestCommand(fileSystem).Execute(NuGetVersion.Parse("1.0.0")); break; case "feature": new FeatureCommand(fileSystem).Execute(directory, "Feature", "1.0.0"); break; case "data": new DataCommand(fileSystem).Execute(directory, "1.0.0", null); break; case "database": new DatabaseCommand(fileSystem).Execute(directory, "1.0.0"); break; diff --git a/tests/Specs/UpgradeAndBumpVersionValidation.cs b/tests/Specs/UpgradeAndBumpVersionValidation.cs new file mode 100644 index 000000000..c9726f542 --- /dev/null +++ b/tests/Specs/UpgradeAndBumpVersionValidation.cs @@ -0,0 +1,545 @@ +using NuGet.Versioning; +using System; +using System.Collections.Generic; +using System.CommandLine; +using System.IO.Abstractions.TestingHelpers; +using System.Linq; +using Cmf.CLI.Commands; +using Cmf.CLI.Core.Objects; +using Cmf.CLI.Utilities; +using FluentAssertions; +using Microsoft.Extensions.DependencyInjection; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Xunit; + +namespace tests.Specs; + +public class UpgradeAndBumpVersionValidation : IDisposable +{ + private readonly ServiceProvider previousServices = ExecutionContext.ServiceProvider; + private readonly MockFileSystem fileSystem = new(); + private readonly string root; + + public UpgradeAndBumpVersionValidation() + { + ExecutionContext.ServiceProvider = new ServiceCollection() + .AddSingleton() + .BuildServiceProvider(); + fileSystem.Directory.CreateDirectory("/project"); + fileSystem.Directory.SetCurrentDirectory("/project"); + root = fileSystem.Directory.GetCurrentDirectory(); + fileSystem.AddFile(Path(".project-config.json"), new MockFileData(""" + { + "MESVersion": "11.2.0", + "NugetVersion": "11.2.0", + "TestScenariosNugetVersion": "11.2.0" + } + """)); + fileSystem.AddFile(Path("cmfpackage.json"), new MockFileData(""" + { + "packageId": "Cmf.Custom.Package", + "packageType": "Generic", + "version": "1.0.0", + "dependencies": [{ "id": "Cmf.Environment", "version": "11.2.0" }] + } + """)); + } + + public static IEnumerable InvalidBumpInputs() + { + foreach (var name in new[] { "bump", "customization", "configuration" }) + { + foreach (var value in new[] { "not-a-version", " ", "1.0.0-beta..1" }) + { + yield return new object[] { name, "--version", value }; + } + var suffixes = name == "bump" + ? new[] { "--buildNr", "--preRelease" } + : new[] { "--buildNrVersion", "--preReleaseVersion" }; + foreach (var suffix in suffixes) + { + foreach (var value in new[] { "bad label", "beta..1", " " }) + { + yield return new object[] { name, suffix, value }; + } + } + } + } + + [Theory] + [MemberData(nameof(InvalidBumpInputs))] + public void InvalidBumpArguments_AreRejectedDuringParsing(string name, string option, string value) + { + var before = Snapshot(); + var args = new List { root }; + if (option != "--version") args.AddRange(new[] { "--version", "1.1.0" }); + args.AddRange(new[] { option, value }); + + var result = CreateCommand(name).Parse(args.ToArray()); + + result.Errors.Should().NotBeEmpty(); + Snapshot().Should().BeEquivalentTo(before); + } + + [Theory] + [MemberData(nameof(InvalidBumpInputs))] + public void InvalidBumpArguments_LeaveAllFilesUnchanged(string name, string option, string value) + { + var before = Snapshot(); + var options = new List { root }; + if (option != "--version") + { + options.AddRange(new[] { "--version", "1.1.0" }); + } + options.AddRange(new[] { option, value }); + + var console = Invoke(name, options.ToArray()); + + console.Error.ToString().Should().Contain(option).And.Contain($"'{value}'").And.Contain("Expected "); + Snapshot().Should().BeEquivalentTo(before); + } + + [Theory] + [InlineData("bump")] + [InlineData("customization")] + public void RequiredBumpVersion_RejectsMissingValue(string name) + { + var before = Snapshot(); + + var console = Invoke(name, root); + + console.Error.ToString().Should().Contain("version"); + Snapshot().Should().BeEquivalentTo(before); + } + + [Theory] + [InlineData("bump")] + [InlineData("customization")] + [InlineData("configuration")] + public void MutuallyExclusiveSuffixes_RejectBeforeWrites(string name) + { + var before = Snapshot(); + var build = name == "bump" ? "--buildNr" : "--buildNrVersion"; + var prerelease = name == "bump" ? "--preRelease" : "--preReleaseVersion"; + + var console = Invoke(name, root, "--version", "1.1.0", build, "123", prerelease, "beta.1"); + + console.Error.ToString().Should().Contain("Mutually exclusive properties") + .And.Contain(build.TrimStart('-')).And.Contain(prerelease.TrimStart('-')); + Snapshot().Should().BeEquivalentTo(before); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("invalid")] + [InlineData("9.9.9")] + [InlineData("9.9.9-beta.1")] + public void Upgrade_RejectsInvalidBaseBeforeWrites(string value) + { + var before = Snapshot(); + var console = value == null ? Invoke("upgrade", root) : Invoke("upgrade", root, value); + + if (NuGet.Versioning.NuGetVersion.TryParse(value, out var parsed) && parsed.Major < 10) + { + console.Error.ToString().Should().Contain("MES Versions under 10 are no longer supported with the newest version of the CLI. Please use cmf-cli 5.8.0 or lower."); + } + else if (value == null) + { + console.Error.ToString().Should().Contain("Required argument missing"); + } + else + { + console.Error.ToString().Should().Contain("BaseVersion").And.Contain("Expected "); + } + Snapshot().Should().BeEquivalentTo(before); + } + + [Theory] + [InlineData("invalid")] + [InlineData("9.9.9")] + public void Upgrade_RejectsInvalidIoTVersionBeforeWrites(string value) + { + var before = Snapshot(); + + var console = Invoke("upgrade", root, "12.0.0-beta.1", "--iotVersion", value); + + if (NuGet.Versioning.NuGetVersion.TryParse(value, out var parsed) && parsed.Major < 10) + { + console.Error.ToString().Should().Contain("MES Versions under 10 are no longer supported with the newest version of the CLI. Please use cmf-cli 5.8.0 or lower."); + } + else + { + console.Error.ToString().Should().Contain("--iotVersion").And.Contain(value).And.Contain("Expected "); + } + Snapshot().Should().BeEquivalentTo(before); + } + + [Theory] + [InlineData("10.0.0-alpha.1")] + [InlineData("12.0.0-beta.1")] + [InlineData("12.0.0-beta.1+build.4")] + [InlineData("12.0.0.0")] + [InlineData(" 12.0.0 ")] + public void Upgrade_ValidReleaseOrPrereleaseUpdatesPackageAndConfiguration(string value) + { + var console = Invoke("upgrade", root, value); + + console.Error.ToString().Should().BeEmpty(); + JObject.Parse(fileSystem.File.ReadAllText(Path(".project-config.json")))["MESVersion"].Value().Should().Be(value); + JObject.Parse(fileSystem.File.ReadAllText(Path("cmfpackage.json")))["dependencies"][0]["version"].Value().Should().Be(value); + } + + [Fact] + public void Upgrade_PreflightLoadsEachDistinctConfigurationOncePerInvocation() + { + var originalPackage = fileSystem.File.ReadAllText(Path("cmfpackage.json")); + fileSystem.AddFile(Path("child", "cmfpackage.json"), new MockFileData(originalPackage)); + fileSystem.AddFile(Path("nested", ".project-config.json"), new MockFileData("{\"MESVersion\":\"12.0.0\"}")); + fileSystem.AddFile(Path("nested", "cmfpackage.json"), new MockFileData(originalPackage)); + fileSystem.AddFile(Path("nested", "child", "cmfpackage.json"), new MockFileData(originalPackage)); + var loaded = new List(); + var before = Snapshot(); + var command = new UpgradeBaseCommand(fileSystem, config => + { + Snapshot().Should().BeEquivalentTo(before, "all configuration loads must finish before writes"); + loaded.Add(config.FullName); + return new ProjectConfigService().Load(config); + }); + + command.Execute(fileSystem.DirectoryInfo.New(root), NuGetVersion.Parse("12.0.0"), null, []); + + loaded.Should().BeEquivalentTo(new[] { Path(".project-config.json"), Path("nested", ".project-config.json") }); + before = Snapshot(); + command.Execute(fileSystem.DirectoryInfo.New(root), NuGetVersion.Parse("12.0.1"), null, []); + loaded.Count(path => path == Path(".project-config.json")).Should().Be(2); + loaded.Count(path => path == Path("nested", ".project-config.json")).Should().Be(2); + } + + [Fact] + public void Bump_ReusingCommandKeepsValidatedInputsLocalToEachParse() + { + var command = CreateCommand("bump"); + var first = command.Parse(new[] { root, "--version", "1.2.3" }); + var second = command.Parse(new[] { root, "--version", "2.3.4" }); + + first.Invoke(new TestConsole()).Should().Be(0); + JObject.Parse(fileSystem.File.ReadAllText(Path("cmfpackage.json")))["version"].Value().Should().Be("1.2.3"); + second.Invoke(new TestConsole()).Should().Be(0); + JObject.Parse(fileSystem.File.ReadAllText(Path("cmfpackage.json")))["version"].Value().Should().Be("2.3.4"); + } + + [Theory] + [InlineData("bump")] + [InlineData("customization")] + [InlineData("configuration")] + public void Bump_InvalidVersionStopsBeforeExecution(string name) + { + var command = CreateCommand(name); + var executed = false; + command.SetAction(_ => { executed = true; }); + var before = Snapshot(); + var console = new TestConsole(); + + var exitCode = command.Parse(new[] { root, "--version", "invalid" }).Invoke(console); + + exitCode.Should().NotBe(0); + executed.Should().BeFalse(); + console.Error.ToString().Should().Contain("--version").And.Contain("Expected "); + Snapshot().Should().BeEquivalentTo(before); + } + + [Fact] + public void Upgrade_ValidatesTargetConfigurationOutsideCurrentProjectBeforeWrites() + { + var target = Path("other-project"); + fileSystem.AddFile(fileSystem.Path.Combine(target, ".project-config.json"), new MockFileData("{\"MESVersion\":\"invalid\"}")); + fileSystem.AddFile(fileSystem.Path.Combine(target, "cmfpackage.json"), new MockFileData(fileSystem.File.ReadAllText(Path("cmfpackage.json")))); + var command = new UpgradeBaseCommand(fileSystem); + var before = Snapshot(); + + Action execute = () => command.Execute(fileSystem.DirectoryInfo.New(target), NuGetVersion.Parse("12.0.0"), null, []); + + execute.Should().Throw().WithMessage("*other-project*.project-config.json*MESVersion*invalid*"); + Snapshot().Should().BeEquivalentTo(before); + } + + [Fact] + public void Upgrade_ValidatesNestedConfigurationBeforeUpdatingAnyPackage() + { + var target = Path("nested-project"); + fileSystem.AddFile(fileSystem.Path.Combine(target, ".project-config.json"), + new MockFileData("{\"MESVersion\":\"12.0.0\",\"NugetVersion\":\"invalid\"}")); + fileSystem.AddFile(fileSystem.Path.Combine(target, "cmfpackage.json"), + new MockFileData(fileSystem.File.ReadAllText(Path("cmfpackage.json")))); + var command = new UpgradeBaseCommand(fileSystem); + var before = Snapshot(); + + Action execute = () => command.Execute(fileSystem.DirectoryInfo.New(root), NuGetVersion.Parse("12.0.0"), null, []); + + execute.Should().Throw().WithMessage("*nested-project*.project-config.json*NugetVersion*invalid*"); + Snapshot().Should().BeEquivalentTo(before); + } + + [Theory] + [InlineData("1.2")] + [InlineData("1.2.3")] + [InlineData("1.2.3-beta.1")] + [InlineData("1.2.3-beta.1+build.4")] + [InlineData("1.2.3.4")] + [InlineData("01.2.3")] + [InlineData("1.2.3.0")] + [InlineData(" 1.2.3 ")] + public void Bump_ValidPackageVersionsBelowTenAreSupported(string value) + { + var console = Invoke("bump", root, "--version", value); + + console.Error.ToString().Should().BeEmpty(); + JObject.Parse(fileSystem.File.ReadAllText(Path("cmfpackage.json")))["version"].Value().Should().Be(value); + } + + [Theory] + [InlineData("bump", "--buildNr")] + [InlineData("bump", "--preRelease")] + [InlineData("customization", "--buildNrVersion")] + [InlineData("customization", "--preReleaseVersion")] + [InlineData("configuration", "--buildNrVersion")] + [InlineData("configuration", "--preReleaseVersion")] + public void EmptyBumpSuffix_UpdatesVersionWithoutSuffix(string name, string option) + { + if (name == "customization") + { + fileSystem.AddFile(Path("cmfpackage.json"), new MockFileData(""" + { "packageId": "Cmf.Custom.IoT", "packageType": "IoT", "version": "1.0.0" } + """)); + fileSystem.AddFile(Path("src", "selected", "package.json"), new MockFileData("{\"version\":\"1.0.0\"}")); + } + if (name == "configuration") + { + AddWorkflow("first", "1.0.0-beta.1"); + } + var args = new List { root, "--version", "1.2.3", option, "" }; + if (name == "customization") + { + args.AddRange(new[] { "--packageNames", "selected" }); + } + + var console = Invoke(name, args.ToArray()); + + console.Error.ToString().Should().BeEmpty(); + if (name == "configuration") + { + WorkflowVersion("first").Should().Be("1.2.3"); + } + else + { + var packagePath = name == "customization" ? Path("src", "selected", "package.json") : Path("cmfpackage.json"); + JObject.Parse(fileSystem.File.ReadAllText(packagePath))["version"].Value().Should().Be("1.2.3"); + } + } + + [Fact] + public void Bump_PreservesSuffixWithBuildMetadata() + { + var console = Invoke("bump", root, "--version", "1.2.3", "--preRelease", "beta.1+build.4"); + + console.Error.ToString().Should().BeEmpty(); + JObject.Parse(fileSystem.File.ReadAllText(Path("cmfpackage.json")))["version"].Value() + .Should().Be("1.2.3-beta.1+build.4"); + } + + [Fact] + public void Configuration_ValidSuffixOnlyUpdatesAllSelectedFiles() + { + AddWorkflow("first", "1.0.0"); + AddWorkflow("second", "2.0.0-previous.1"); + + var console = Invoke("configuration", root, "--preReleaseVersion", "beta.1", "--iot"); + + console.Error.ToString().Should().BeEmpty(); + WorkflowVersion("first").Should().Be("1.0.0-beta.1"); + WorkflowVersion("second").Should().Be("2.0.0-beta.1"); + } + + [Theory] + [InlineData("--buildNrVersion")] + [InlineData("--preReleaseVersion")] + public void Configuration_EmptyOptionalVersionPreservesSuffixOnlyBehavior(string suffixOption) + { + AddWorkflow("first", "1.0.0"); + AddWorkflow("second", "2.0.0"); + + var console = Invoke("configuration", root, "--version", "", suffixOption, "beta.1", "--iot"); + + console.Error.ToString().Should().BeEmpty(); + WorkflowVersion("first").Should().Be("1.0.0-beta.1"); + WorkflowVersion("second").Should().Be("2.0.0-beta.1"); + } + + [Theory] + [InlineData(null, true)] + [InlineData("", true)] + [InlineData(null, false)] + [InlineData("", false)] + public void Bump_PackageOverloadPreservesOptionalVersionAndSuffixBehavior(string version, bool buildSuffix) + { + var package = CmfPackage.Load(fileSystem.FileInfo.New(Path("cmfpackage.json")), fileSystem: fileSystem); + fileSystem.AddFile(Path("legacy", "cmfpackage.json"), new MockFileData(fileSystem.File.ReadAllText(Path("cmfpackage.json")))); + var legacyPackage = CmfPackage.Load(fileSystem.FileInfo.New(Path("legacy", "cmfpackage.json")), fileSystem: fileSystem); + var suffix = "beta.1"; + + // Compare against the unchanged package handler used before validation + // moved into the adapter, including its existing suffix-only behavior. + Cmf.CLI.Factories.PackageTypeFactory.GetPackageTypeHandler(legacyPackage).Bump(version, suffix, + new Dictionary { ["root"] = null }); + + new BumpCommand(fileSystem).Execute(package, string.IsNullOrEmpty(version) ? null : NuGetVersion.Parse(version), + buildSuffix ? suffix : null, buildSuffix ? null : suffix, null); + + JObject.Parse(fileSystem.File.ReadAllText(Path("cmfpackage.json")))["version"].Value() + .Should().Be(legacyPackage.Version); + } + + [Theory] + [InlineData("1.2.3", null, "1.2.3")] + [InlineData("1.2.3-beta.1+build.4", null, "1.2.3-beta.1+build.4")] + [InlineData("1.2.3", "beta.1+build.4", "1.2.3-beta.1+build.4")] + [InlineData("1.2.3-0.01a+001", null, "1.2.3-0.01a+001")] + public void Customization_ValidVersionsUpdateSelectedNpmPackages(string version, string suffix, string expected) + { + fileSystem.AddFile(Path("cmfpackage.json"), new MockFileData(""" + { "packageId": "Cmf.Custom.IoT", "packageType": "IoT", "version": "1.0.0" } + """)); + var selected = Path("src", "selected", "package.json"); + var unselected = Path("src", "unselected", "package.json"); + const string original = "{\"version\":\"1.0.0\"}"; + fileSystem.AddFile(selected, new MockFileData(original)); + fileSystem.AddFile(unselected, new MockFileData(original)); + var args = new List { root, "--version", version, "--packageNames", "selected" }; + if (suffix != null) + { + args.AddRange(new[] { "--preReleaseVersion", suffix }); + } + + var console = Invoke("customization", args.ToArray()); + + console.Error.ToString().Should().BeEmpty(); + JObject.Parse(fileSystem.File.ReadAllText(selected))["version"].Value().Should().Be(expected); + fileSystem.File.ReadAllText(unselected).Should().Be(original); + } + + [Theory] + [InlineData(null, false)] + [InlineData("", false)] + [InlineData(null, true)] + [InlineData("", true)] + public void Customization_PackageOverloadPreservesSuffixOnlyUpdatesAndPreflightsAllSelectedVersions(string version, bool invalidSecondPackage) + { + fileSystem.AddFile(Path("cmfpackage.json"), new MockFileData(""" + { "packageId": "Cmf.Custom.IoT", "packageType": "IoT", "version": "1.0.0" } + """)); + var first = Path("src", "first", "package.json"); + var second = Path("src", "second", "package.json"); + fileSystem.AddFile(first, new MockFileData("{\"version\":\"1.0.0\"}")); + fileSystem.AddFile(second, new MockFileData(invalidSecondPackage ? "{\"version\":\"1.2\"}" : "{\"version\":\"2.0.0\"}")); + var package = CmfPackage.Load(fileSystem.FileInfo.New(Path("cmfpackage.json")), fileSystem: fileSystem); + var before = Snapshot(); + Action execute = () => new BumpIoTCustomizationCommand(fileSystem).Execute(package, string.IsNullOrEmpty(version) ? null : SemanticVersion.Parse(version), null, "beta.1", "first,second", false); + + if (invalidSecondPackage) + { + execute.Should().Throw().WithMessage("*Expected a semantic version*"); + Snapshot().Should().BeEquivalentTo(before); + } + else + { + execute.Should().NotThrow(); + JObject.Parse(fileSystem.File.ReadAllText(first))["version"].Value().Should().Be("1.0.0-beta.1"); + JObject.Parse(fileSystem.File.ReadAllText(second))["version"].Value().Should().Be("2.0.0-beta.1"); + } + } + + [Theory] + [InlineData("1.2", null, null)] + [InlineData("1.2.3.4", null, null)] + [InlineData("1.2", "--buildNrVersion", "beta.1")] + [InlineData("1.2.3.4", "--buildNrVersion", "beta.1")] + [InlineData("1.2", "--preReleaseVersion", "beta.1")] + [InlineData("1.2.3.4", "--preReleaseVersion", "beta.1")] + [InlineData("01.2.3", null, null)] + [InlineData("1.2.3", "--preReleaseVersion", "01")] + [InlineData("1.2.3-beta.01", null, null)] + public void Customization_InvalidNpmVersionLeavesAllSelectedFilesUnchanged(string version, string suffixOption, string suffix) + { + fileSystem.AddFile(Path("cmfpackage.json"), new MockFileData(""" + { "packageId": "Cmf.Custom.IoT", "packageType": "IoT", "version": "1.0.0" } + """)); + foreach (var name in new[] { "first", "second" }) + { + fileSystem.AddFile(Path("src", name, "package.json"), new MockFileData("{\"version\":\"1.0.0\"}")); + fileSystem.AddFile(Path("src", name, "src", "metadata.ts"), new MockFileData("version: \"1.0.0\",")); + } + var before = Snapshot(); + var args = new List { root, "--version", version, "--packageNames", "first,second" }; + if (suffixOption != null) + { + args.AddRange(new[] { suffixOption, suffix }); + } + + var console = Invoke("customization", args.ToArray()); + + console.Error.ToString().Should().Contain("Expected "); + Snapshot().Should().BeEquivalentTo(before); + } + + private void AddWorkflow(string name, string version) + { + var json = new JObject + { + ["tasks"] = new JArray(new JObject + { + ["reference"] = new JObject + { + ["package"] = new JObject { ["name"] = "@custom/connect-iot-example", ["version"] = version } + } + }), + ["converters"] = new JArray() + }; + fileSystem.AddFile(Path("AutomationWorkflowFiles", "group", name + ".json"), new MockFileData(json.ToString(Formatting.None))); + } + + private string WorkflowVersion(string name) => JObject.Parse(fileSystem.File.ReadAllText( + Path("AutomationWorkflowFiles", "group", name + ".json")))["tasks"][0]["reference"]["package"]["version"].Value(); + + private Command CreateCommand(string name) + { + var command = new Command("test"); + Cmf.CLI.Core.Commands.BaseCommand handler = name switch + { + "upgrade" => new UpgradeBaseCommand(fileSystem), + "bump" => new BumpCommand(fileSystem), + "customization" => new BumpIoTCustomizationCommand(fileSystem), + "configuration" => new BumpIoTConfigurationCommand(fileSystem), + _ => throw new ArgumentOutOfRangeException(nameof(name)) + }; + handler.Configure(command); + return command; + } + + private TestConsole Invoke(string name, params string[] args) + { + var console = new TestConsole(); + CreateCommand(name).Parse(args).Invoke(console); + return console; + } + + private string Path(params string[] parts) => fileSystem.Path.Combine(new[] { root }.Concat(parts).ToArray()); + private Dictionary Snapshot() => fileSystem.AllFiles.ToDictionary(path => path, path => fileSystem.File.ReadAllText(path)); + + public void Dispose() + { + ExecutionContext.ServiceProvider.Dispose(); + ExecutionContext.ServiceProvider = previousServices; + } +} diff --git a/tests/Specs/UpgradeBase.cs b/tests/Specs/UpgradeBase.cs index 97f2caf80..87d0fef35 100644 --- a/tests/Specs/UpgradeBase.cs +++ b/tests/Specs/UpgradeBase.cs @@ -1,3 +1,4 @@ +using NuGet.Versioning; using System; using System.Collections.Generic; using System.IO.Abstractions.TestingHelpers; @@ -53,7 +54,7 @@ public void ProjectConfig() }); UpgradeBaseCommand cmd = new UpgradeBaseCommand(fileSystem); - cmd.Execute(fileSystem.FileInfo.New(projectConfigPath).Directory, "11.1.6", "11.1.6", []); + cmd.Execute(fileSystem.FileInfo.New(projectConfigPath).Directory, NuGetVersion.Parse("11.1.6"), NuGetVersion.Parse("11.1.6"), []); string projectConfigContents = fileSystem.File.ReadAllText(projectConfigPath); @@ -179,7 +180,7 @@ public void BusinessPackage() UpgradeBaseCommand cmd = new UpgradeBaseCommand(fileSystem); - cmd.Execute(fileSystem.DirectoryInfo.New("/"), version, version, []); + cmd.Execute(fileSystem.DirectoryInfo.New("/"), NuGetVersion.Parse(version), NuGetVersion.Parse(version), []); string rootCmfpackageContents = fileSystem.File.ReadAllText("/cmfpackage.json"); @@ -509,7 +510,7 @@ public void DataPackage(bool iotShouldBeUpdated) }); UpgradeBaseCommand cmd = new UpgradeBaseCommand(fileSystem); - cmd.Execute(fileSystem.DirectoryInfo.New(@"/"), version, iotShouldBeUpdated ? iotVersion : null, ["ignore-this-package"]); + cmd.Execute(fileSystem.DirectoryInfo.New(@"/"), NuGetVersion.Parse(version), iotShouldBeUpdated ? NuGetVersion.Parse(iotVersion) : null, ["ignore-this-package"]); string csprojContents = fileSystem.File.ReadAllText(@"/DEEs/a.b.c.csproj"); csprojContents.Should().Contain( @@ -781,7 +782,7 @@ public void TestPackage() UpgradeBaseCommand cmd = new UpgradeBaseCommand(fileSystem); - cmd.Execute(fileSystem.DirectoryInfo.New("/"), version, null, []); + cmd.Execute(fileSystem.DirectoryInfo.New("/"), NuGetVersion.Parse(version), null, []); string csprojContents = fileSystem.File.ReadAllText("/Common/a.b.c.csproj"); csprojContents.Should().Contain(