Просмотр исходного кода

CPS: Refactor metadata handling

Add some helper functions to simplify some repetitive code dealing with
CPS metadata. The duplication isn't bad now, but in the future we will
be handling additional properties that will benefit from these helpers.
Matthew Woehlke 6 месяцев назад
Родитель
Сommit
f224e131a5
2 измененных файлов с 27 добавлено и 17 удалено
  1. 13 8
      Source/cmExportPackageInfoGenerator.cxx
  2. 14 9
      Source/cmPackageInfoArguments.cxx

+ 13 - 8
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 <typename T>
 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);

+ 14 - 9
Source/cmPackageInfoArguments.cxx

@@ -4,6 +4,8 @@
 
 #include <utility>
 
+#include <cm/string_view>
+
 #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);
     }
   }