diff --git a/Source/cmExportPackageInfoGenerator.cxx b/Source/cmExportPackageInfoGenerator.cxx index bd3db81ace..1376a45f0b 100644 --- a/Source/cmExportPackageInfoGenerator.cxx +++ b/Source/cmExportPackageInfoGenerator.cxx @@ -63,6 +63,16 @@ void cmExportPackageInfoGenerator::WritePackageInfo( } namespace { +bool SetProperty(Json::Value& object, std::string const& property, + std::string const& value) +{ + if (!value.empty()) { + object[property] = value; + return true; + } + return false; +} + template void BuildArray(Json::Value& object, std::string const& property, T const& values) @@ -105,14 +115,9 @@ Json::Value cmExportPackageInfoGenerator::GeneratePackageInfo() const package["name"] = this->GetPackageName(); package["cps_version"] = std::string(kCPS_VERSION_STR); - if (!this->PackageVersion.empty()) { - package["version"] = this->PackageVersion; - if (!this->PackageVersionCompat.empty()) { - package["compat_version"] = this->PackageVersionCompat; - } - if (!this->PackageVersionSchema.empty()) { - package["version_schema"] = this->PackageVersionSchema; - } + if (SetProperty(package, "version", this->PackageVersion)) { + SetProperty(package, "compat_version", this->PackageVersionCompat); + SetProperty(package, "version_schema", this->PackageVersionSchema); } BuildArray(package, "default_components", this->DefaultTargets); diff --git a/Source/cmPackageInfoArguments.cxx b/Source/cmPackageInfoArguments.cxx index f9eac81f27..c53d57eb76 100644 --- a/Source/cmPackageInfoArguments.cxx +++ b/Source/cmPackageInfoArguments.cxx @@ -4,6 +4,8 @@ #include +#include + #include "cmExecutionStatus.h" #include "cmGeneratorExpression.h" #include "cmMakefile.h" @@ -118,16 +120,19 @@ bool cmPackageInfoArguments::SetMetadataFromProject(cmExecutionStatus& status) } cmMakefile& mf = status.GetMakefile(); + auto mapProjectValue = [&](std::string& arg, cm::string_view suffix) { + cmValue const& projectValue = + mf.GetDefinition(cmStrCat(this->ProjectName, '_', suffix)); + if (projectValue) { + arg = *projectValue; + return true; + } + return false; + }; + if (this->Version.empty()) { - cmValue const& version = - mf.GetDefinition(cmStrCat(this->ProjectName, "_VERSION"_s)); - if (version) { - this->Version = version; - cmValue const& compatVersion = - mf.GetDefinition(cmStrCat(this->ProjectName, "_COMPAT_VERSION"_s)); - if (compatVersion) { - this->VersionCompat = compatVersion; - } + if (mapProjectValue(this->Version, "VERSION"_s)) { + mapProjectValue(this->VersionCompat, "COMPAT_VERSION"_s); } }