diff options
Diffstat (limited to 'Source')
349 files changed, 6841 insertions, 8827 deletions
diff --git a/Source/CMakeLists.txt b/Source/CMakeLists.txt index fe40af3..7cd07a8 100644 --- a/Source/CMakeLists.txt +++ b/Source/CMakeLists.txt @@ -95,9 +95,6 @@ include_directories( ${CMake_HAIKU_INCLUDE_DIRS} ) -# let cmake know it is supposed to use it -add_definitions(-DCMAKE_BUILD_WITH_CMAKE) - # Check if we can build the ELF parser. if(CMAKE_USE_ELF_PARSER) set(ELF_SRCS cmELF.h cmELF.cxx) @@ -532,6 +529,8 @@ set(SRCS cmFindProgramCommand.h cmForEachCommand.cxx cmForEachCommand.h + cmFunctionBlocker.cxx + cmFunctionBlocker.h cmFunctionCommand.cxx cmFunctionCommand.h cmGetCMakePropertyCommand.cxx @@ -637,6 +636,8 @@ set(SRCS cmStringReplaceHelper.cxx cmStringCommand.cxx cmStringCommand.h + cmSubcommandTable.cxx + cmSubcommandTable.h cmSubdirCommand.cxx cmSubdirCommand.h cmSubdirDependsCommand.cxx diff --git a/Source/CMakeVersion.cmake b/Source/CMakeVersion.cmake index 04564a0..fdc482d 100644 --- a/Source/CMakeVersion.cmake +++ b/Source/CMakeVersion.cmake @@ -1,7 +1,7 @@ # CMake version number components. set(CMake_VERSION_MAJOR 3) set(CMake_VERSION_MINOR 15) -set(CMake_VERSION_PATCH 20190803) +set(CMake_VERSION_PATCH 20190823) #set(CMake_VERSION_RC 0) set(CMake_VERSION_IS_DIRTY 0) diff --git a/Source/CPack/IFW/cmCPackIFWCommon.cxx b/Source/CPack/IFW/cmCPackIFWCommon.cxx index 1e72641..5b1ccbd 100644 --- a/Source/CPack/IFW/cmCPackIFWCommon.cxx +++ b/Source/CPack/IFW/cmCPackIFWCommon.cxx @@ -5,6 +5,7 @@ #include "cmCPackGenerator.h" #include "cmCPackIFWGenerator.h" #include "cmCPackLog.h" // IWYU pragma: keep +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmTimestamp.h" #include "cmVersionConfig.h" @@ -78,7 +79,7 @@ void cmCPackIFWCommon::ExpandListArgument( const std::string& arg, std::map<std::string, std::string>& argsOut) { std::vector<std::string> args; - cmSystemTools::ExpandListArgument(arg, args, false); + cmExpandList(arg, args, false); if (args.empty()) { return; } @@ -100,7 +101,7 @@ void cmCPackIFWCommon::ExpandListArgument( const std::string& arg, std::multimap<std::string, std::string>& argsOut) { std::vector<std::string> args; - cmSystemTools::ExpandListArgument(arg, args, false); + cmExpandList(arg, args, false); if (args.empty()) { return; } diff --git a/Source/CPack/IFW/cmCPackIFWGenerator.cxx b/Source/CPack/IFW/cmCPackIFWGenerator.cxx index c1b6eea..234da2f 100644 --- a/Source/CPack/IFW/cmCPackIFWGenerator.cxx +++ b/Source/CPack/IFW/cmCPackIFWGenerator.cxx @@ -11,6 +11,7 @@ #include "cmCPackLog.h" // IWYU pragma: keep #include "cmDuration.h" #include "cmGeneratedFileStream.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include <sstream> @@ -34,8 +35,7 @@ int cmCPackIFWGenerator::PackageFiles() this->Installer.GeneratePackageFiles(); std::string ifwTLD = this->GetOption("CPACK_TOPLEVEL_DIRECTORY"); - std::string ifwTmpFile = ifwTLD; - ifwTmpFile += "/IFWOutput.log"; + std::string ifwTmpFile = cmStrCat(ifwTLD, "/IFWOutput.log"); // Run repogen if (!this->Installer.RemoteRepositories.empty()) { @@ -116,8 +116,8 @@ int cmCPackIFWGenerator::PackageFiles() // Run binary creator { - std::string ifwCmd = this->BinCreator; - ifwCmd += " -c " + this->toplevel + "/config/config.xml"; + std::string ifwCmd = + cmStrCat(this->BinCreator, " -c ", this->toplevel, "/config/config.xml"); if (!this->Installer.Resources.empty()) { ifwCmd += " -r "; @@ -253,7 +253,7 @@ int cmCPackIFWGenerator::InitializeInternal() // Look 'binarycreator' executable (needs) const char* BinCreatorStr = this->GetOption(BinCreatorOpt); - if (!BinCreatorStr || cmSystemTools::IsNOTFOUND(BinCreatorStr)) { + if (!BinCreatorStr || cmIsNOTFOUND(BinCreatorStr)) { this->BinCreator.clear(); } else { this->BinCreator = BinCreatorStr; @@ -270,7 +270,7 @@ int cmCPackIFWGenerator::InitializeInternal() // Look 'repogen' executable (optional) const char* RepoGenStr = this->GetOption(RepoGenOpt); - if (!RepoGenStr || cmSystemTools::IsNOTFOUND(RepoGenStr)) { + if (!RepoGenStr || cmIsNOTFOUND(RepoGenStr)) { this->RepoGen.clear(); } else { this->RepoGen = RepoGenStr; @@ -292,14 +292,14 @@ int cmCPackIFWGenerator::InitializeInternal() // Additional packages dirs this->PkgsDirsVector.clear(); if (const char* dirs = this->GetOption("CPACK_IFW_PACKAGES_DIRECTORIES")) { - cmSystemTools::ExpandListArgument(dirs, this->PkgsDirsVector); + cmExpandList(dirs, this->PkgsDirsVector); } // Additional repositories dirs this->RepoDirsVector.clear(); if (const char* dirs = this->GetOption("CPACK_IFW_REPOSITORIES_DIRECTORIES")) { - cmSystemTools::ExpandListArgument(dirs, this->RepoDirsVector); + cmExpandList(dirs, this->RepoDirsVector); } // Installer @@ -317,17 +317,17 @@ int cmCPackIFWGenerator::InitializeInternal() // Repositories if (const char* RepoAllStr = this->GetOption("CPACK_IFW_REPOSITORIES_ALL")) { std::vector<std::string> RepoAllVector; - cmSystemTools::ExpandListArgument(RepoAllStr, RepoAllVector); + cmExpandList(RepoAllStr, RepoAllVector); for (std::string const& r : RepoAllVector) { this->GetRepository(r); } } if (const char* ifwDownloadAll = this->GetOption("CPACK_IFW_DOWNLOAD_ALL")) { - this->OnlineOnly = cmSystemTools::IsOn(ifwDownloadAll); + this->OnlineOnly = cmIsOn(ifwDownloadAll); } else if (const char* cpackDownloadAll = this->GetOption("CPACK_DOWNLOAD_ALL")) { - this->OnlineOnly = cmSystemTools::IsOn(cpackDownloadAll); + this->OnlineOnly = cmIsOn(cpackDownloadAll); } else { this->OnlineOnly = false; } diff --git a/Source/CPack/IFW/cmCPackIFWInstaller.cxx b/Source/CPack/IFW/cmCPackIFWInstaller.cxx index a075a17..b4bfea7 100644 --- a/Source/CPack/IFW/cmCPackIFWInstaller.cxx +++ b/Source/CPack/IFW/cmCPackIFWInstaller.cxx @@ -8,6 +8,7 @@ #include "cmCPackIFWRepository.h" #include "cmCPackLog.h" // IWYU pragma: keep #include "cmGeneratedFileStream.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmXMLParser.h" #include "cmXMLWriter.h" @@ -192,8 +193,8 @@ void cmCPackIFWInstaller::ConfigureFromOptions() this->TargetDir = optIFW_TARGET_DIRECTORY; } else if (const char* optPACKAGE_INSTALL_DIRECTORY = this->GetOption("CPACK_PACKAGE_INSTALL_DIRECTORY")) { - this->TargetDir = "@ApplicationsDir@/"; - this->TargetDir += optPACKAGE_INSTALL_DIRECTORY; + this->TargetDir = + cmStrCat("@ApplicationsDir@/", optPACKAGE_INSTALL_DIRECTORY); } else { this->TargetDir = "@RootDir@/usr/local"; } @@ -244,8 +245,7 @@ void cmCPackIFWInstaller::ConfigureFromOptions() if (const char* optIFW_PACKAGE_RESOURCES = this->GetOption("CPACK_IFW_PACKAGE_RESOURCES")) { this->Resources.clear(); - cmSystemTools::ExpandListArgument(optIFW_PACKAGE_RESOURCES, - this->Resources); + cmExpandList(optIFW_PACKAGE_RESOURCES, this->Resources); } } @@ -292,7 +292,7 @@ protected: { if (this->file) { std::string content(data, data + length); - content = cmSystemTools::TrimWhitespace(content); + content = cmTrimWhitespace(content); std::string source = this->basePath + "/" + content; std::string destination = this->path + "/" + content; if (!cmSystemTools::CopyFileIfDifferent(source, destination)) { diff --git a/Source/CPack/IFW/cmCPackIFWPackage.cxx b/Source/CPack/IFW/cmCPackIFWPackage.cxx index a1a52b1..7407c49 100644 --- a/Source/CPack/IFW/cmCPackIFWPackage.cxx +++ b/Source/CPack/IFW/cmCPackIFWPackage.cxx @@ -8,6 +8,7 @@ #include "cmCPackIFWInstaller.h" #include "cmCPackLog.h" // IWYU pragma: keep #include "cmGeneratedFileStream.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmTimestamp.h" #include "cmXMLWriter.h" @@ -196,7 +197,7 @@ int cmCPackIFWPackage::ConfigureFromComponent(cmCPackComponent* component) // User interfaces if (const char* option = this->GetOption(prefix + "USER_INTERFACES")) { this->UserInterfaces.clear(); - cmSystemTools::ExpandListArgument(option, this->UserInterfaces); + cmExpandList(option, this->UserInterfaces); } // CMake dependencies @@ -209,7 +210,7 @@ int cmCPackIFWPackage::ConfigureFromComponent(cmCPackComponent* component) // Licenses if (const char* option = this->GetOption(prefix + "LICENSES")) { this->Licenses.clear(); - cmSystemTools::ExpandListArgument(option, this->Licenses); + cmExpandList(option, this->Licenses); if (this->Licenses.size() % 2 != 0) { cmCPackIFWLogger( WARNING, @@ -281,13 +282,13 @@ int cmCPackIFWPackage::ConfigureFromGroup(cmCPackComponentGroup* group) // User interfaces if (const char* option = this->GetOption(prefix + "USER_INTERFACES")) { this->UserInterfaces.clear(); - cmSystemTools::ExpandListArgument(option, this->UserInterfaces); + cmExpandList(option, this->UserInterfaces); } // Licenses if (const char* option = this->GetOption(prefix + "LICENSES")) { this->Licenses.clear(); - cmSystemTools::ExpandListArgument(option, this->Licenses); + cmExpandList(option, this->Licenses); if (this->Licenses.size() % 2 != 0) { cmCPackIFWLogger( WARNING, @@ -398,18 +399,18 @@ int cmCPackIFWPackage::ConfigureFromPrefix(const std::string& prefix) this->Translations.clear(); } else if (const char* value = this->GetOption(option)) { this->Translations.clear(); - cmSystemTools::ExpandListArgument(value, this->Translations); + cmExpandList(value, this->Translations); } // QtIFW dependencies std::vector<std::string> deps; option = prefix + "DEPENDS"; if (const char* value = this->GetOption(option)) { - cmSystemTools::ExpandListArgument(value, deps); + cmExpandList(value, deps); } option = prefix + "DEPENDENCIES"; if (const char* value = this->GetOption(option)) { - cmSystemTools::ExpandListArgument(value, deps); + cmExpandList(value, deps); } for (std::string const& d : deps) { DependenceStruct dep(d); @@ -431,7 +432,7 @@ int cmCPackIFWPackage::ConfigureFromPrefix(const std::string& prefix) this->AlienAutoDependOn.clear(); } else if (const char* value = this->GetOption(option)) { std::vector<std::string> depsOn; - cmSystemTools::ExpandListArgument(value, depsOn); + cmExpandList(value, depsOn); for (std::string const& d : depsOn) { DependenceStruct dep(d); if (this->Generator->Packages.count(dep.Name)) { @@ -488,7 +489,7 @@ int cmCPackIFWPackage::ConfigureFromPrefix(const std::string& prefix) this->Replaces.clear(); } else if (const char* value = this->GetOption(option)) { this->Replaces.clear(); - cmSystemTools::ExpandListArgument(value, this->Replaces); + cmExpandList(value, this->Replaces); } // Requires admin rights diff --git a/Source/CPack/WiX/cmCMakeToWixPath.cxx b/Source/CPack/WiX/cmCMakeToWixPath.cxx index b3889cf..630a8f8 100644 --- a/Source/CPack/WiX/cmCMakeToWixPath.cxx +++ b/Source/CPack/WiX/cmCMakeToWixPath.cxx @@ -2,7 +2,7 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmCMakeToWixPath.h" -#include "cmSystemTools.h" +#include "cmStringAlgorithms.h" #include <string> #include <vector> @@ -29,7 +29,7 @@ std::string CMakeToWixPath(const std::string& cygpath) return cygpath; } - return cmSystemTools::TrimWhitespace(winpath_chars.data()); + return cmTrimWhitespace(winpath_chars.data()); } #else std::string CMakeToWixPath(const std::string& path) diff --git a/Source/CPack/WiX/cmCPackWIXGenerator.cxx b/Source/CPack/WiX/cmCPackWIXGenerator.cxx index fa64d79..e960fab 100644 --- a/Source/CPack/WiX/cmCPackWIXGenerator.cxx +++ b/Source/CPack/WiX/cmCPackWIXGenerator.cxx @@ -2,13 +2,16 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmCPackWIXGenerator.h" +#include "cmAlgorithms.h" #include "cmCPackComponentGroup.h" #include "cmCPackLog.h" #include "cmCryptoHash.h" #include "cmGeneratedFileStream.h" #include "cmInstalledFile.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmUuid.h" +#include "cm_string_view.hxx" #include <algorithm> #include "cmWIXDirectoriesSourceWriter.h" @@ -226,7 +229,7 @@ bool cmCPackWIXGenerator::InitializeWiXConfiguration() const char* patchFilePath = GetOption("CPACK_WIX_PATCH_FILE"); if (patchFilePath) { std::vector<std::string> patchFilePaths; - cmSystemTools::ExpandListArgument(patchFilePath, patchFilePaths); + cmExpandList(patchFilePath, patchFilePaths); for (std::string const& p : patchFilePaths) { if (!this->Patch->LoadFragments(p)) { @@ -237,7 +240,7 @@ bool cmCPackWIXGenerator::InitializeWiXConfiguration() // if install folder is supposed to be set absolutely, the default // component guid "*" cannot be used - if (cmSystemTools::IsOn(GetOption("CPACK_WIX_SKIP_PROGRAM_FOLDER"))) { + if (cmIsOn(GetOption("CPACK_WIX_SKIP_PROGRAM_FOLDER"))) { this->ComponentGuidType = cmWIXSourceWriter::CMAKE_GENERATED_GUID; } @@ -300,7 +303,7 @@ void cmCPackWIXGenerator::AppendUserSuppliedExtraSources() if (!cpackWixExtraSources) return; - cmSystemTools::ExpandListArgument(cpackWixExtraSources, this->WixSources); + cmExpandList(cpackWixExtraSources, this->WixSources); } void cmCPackWIXGenerator::AppendUserSuppliedExtraObjects(std::ostream& stream) @@ -311,8 +314,7 @@ void cmCPackWIXGenerator::AppendUserSuppliedExtraObjects(std::ostream& stream) std::vector<std::string> expandedExtraObjects; - cmSystemTools::ExpandListArgument(cpackWixExtraObjects, - expandedExtraObjects); + cmExpandList(cpackWixExtraObjects, expandedExtraObjects); for (std::string const& obj : expandedExtraObjects) { stream << " " << QuotePath(obj); @@ -518,9 +520,7 @@ bool cmCPackWIXGenerator::CreateWiXSourceFiles() for (auto const& i : this->Components) { cmCPackComponent const& component = i.second; - std::string componentPath = toplevel; - componentPath += "/"; - componentPath += component.Name; + std::string componentPath = cmStrCat(toplevel, '/', component.Name); std::string const componentFeatureId = "CM_C_" + component.Name; @@ -582,7 +582,7 @@ bool cmCPackWIXGenerator::CreateWiXSourceFiles() std::string cmCPackWIXGenerator::GetRootFolderId() const { - if (cmSystemTools::IsOn(GetOption("CPACK_WIX_SKIP_PROGRAM_FOLDER"))) { + if (cmIsOn(GetOption("CPACK_WIX_SKIP_PROGRAM_FOLDER"))) { return ""; } @@ -664,8 +664,7 @@ bool cmCPackWIXGenerator::AddComponentsToFeature( std::vector<std::string> cpackPackageExecutablesList; const char* cpackPackageExecutables = GetOption("CPACK_PACKAGE_EXECUTABLES"); if (cpackPackageExecutables) { - cmSystemTools::ExpandListArgument(cpackPackageExecutables, - cpackPackageExecutablesList); + cmExpandList(cpackPackageExecutables, cpackPackageExecutablesList); if (cpackPackageExecutablesList.size() % 2 != 0) { cmCPackLogger( cmCPackLog::LOG_ERROR, @@ -680,8 +679,7 @@ bool cmCPackWIXGenerator::AddComponentsToFeature( const char* cpackPackageDesktopLinks = GetOption("CPACK_CREATE_DESKTOP_LINKS"); if (cpackPackageDesktopLinks) { - cmSystemTools::ExpandListArgument(cpackPackageDesktopLinks, - cpackPackageDesktopLinksList); + cmExpandList(cpackPackageDesktopLinks, cpackPackageDesktopLinksList); } AddDirectoryAndFileDefinitions( @@ -944,9 +942,7 @@ void cmCPackWIXGenerator::AddDirectoryAndFileDefinitions( shortcut.workingDirectoryId = directoryId; shortcuts.insert(cmWIXShortcuts::START_MENU, id, shortcut); - if (!desktopExecutables.empty() && - std::find(desktopExecutables.begin(), desktopExecutables.end(), - executableName) != desktopExecutables.end()) { + if (cmContains(desktopExecutables, executableName)) { shortcuts.insert(cmWIXShortcuts::DESKTOP, id, shortcut); } } @@ -1090,8 +1086,7 @@ std::string cmCPackWIXGenerator::CreateHashedId( cmCryptoHash sha1(cmCryptoHash::AlgoSHA1); std::string const hash = sha1.HashString(path); - std::string identifier; - identifier += hash.substr(0, 7) + "_"; + std::string identifier = cmStrCat(cm::string_view(hash).substr(0, 7), '_'); const size_t maxFileNameLength = 52; if (normalizedFilename.length() > maxFileNameLength) { @@ -1137,7 +1132,7 @@ void cmCPackWIXGenerator::CollectExtensions(std::string const& variableName, return; std::vector<std::string> list; - cmSystemTools::ExpandListArgument(variableContent, list); + cmExpandList(variableContent, list); extensions.insert(list.begin(), list.end()); } @@ -1149,7 +1144,7 @@ void cmCPackWIXGenerator::AddCustomFlags(std::string const& variableName, return; std::vector<std::string> list; - cmSystemTools::ExpandListArgument(variableContent, list); + cmExpandList(variableContent, list); for (std::string const& i : list) { stream << " " << QuotePath(i); diff --git a/Source/CPack/WiX/cmWIXAccessControlList.cxx b/Source/CPack/WiX/cmWIXAccessControlList.cxx index 563de02..b5e287d 100644 --- a/Source/CPack/WiX/cmWIXAccessControlList.cxx +++ b/Source/CPack/WiX/cmWIXAccessControlList.cxx @@ -4,6 +4,7 @@ #include "cmCPackGenerator.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" cmWIXAccessControlList::cmWIXAccessControlList( @@ -48,8 +49,7 @@ void cmWIXAccessControlList::CreatePermissionElement(std::string const& entry) user = user_and_domain; } - std::vector<std::string> permissions = - cmSystemTools::tokenize(permission_string, ","); + std::vector<std::string> permissions = cmTokenize(permission_string, ","); this->SourceWriter.BeginElement("Permission"); this->SourceWriter.AddAttribute("User", user); @@ -57,8 +57,7 @@ void cmWIXAccessControlList::CreatePermissionElement(std::string const& entry) this->SourceWriter.AddAttribute("Domain", domain); } for (std::string const& permission : permissions) { - this->EmitBooleanAttribute(entry, - cmSystemTools::TrimWhitespace(permission)); + this->EmitBooleanAttribute(entry, cmTrimWhitespace(permission)); } this->SourceWriter.EndElement("Permission"); } diff --git a/Source/CPack/cmCPackArchiveGenerator.cxx b/Source/CPack/cmCPackArchiveGenerator.cxx index 98fb29d..6c9c6b9 100644 --- a/Source/CPack/cmCPackArchiveGenerator.cxx +++ b/Source/CPack/cmCPackArchiveGenerator.cxx @@ -6,6 +6,7 @@ #include "cmCPackGenerator.h" #include "cmCPackLog.h" #include "cmGeneratedFileStream.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmWorkingDirectory.h" @@ -71,8 +72,7 @@ int cmCPackArchiveGenerator::addOneComponentToArchive( } std::string filePrefix; if (this->IsOn("CPACK_COMPONENT_INCLUDE_TOPLEVEL_DIRECTORY")) { - filePrefix = this->GetOption("CPACK_PACKAGE_FILE_NAME"); - filePrefix += "/"; + filePrefix = cmStrCat(this->GetOption("CPACK_PACKAGE_FILE_NAME"), '/'); } const char* installPrefix = this->GetOption("CPACK_PACKAGING_INSTALL_PREFIX"); diff --git a/Source/CPack/cmCPackBundleGenerator.cxx b/Source/CPack/cmCPackBundleGenerator.cxx index 3a476f4..f58cc0a 100644 --- a/Source/CPack/cmCPackBundleGenerator.cxx +++ b/Source/CPack/cmCPackBundleGenerator.cxx @@ -6,6 +6,7 @@ #include <vector> #include "cmCPackLog.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" cmCPackBundleGenerator::cmCPackBundleGenerator() = default; @@ -40,9 +41,8 @@ int cmCPackBundleGenerator::InitializeInternal() const char* cmCPackBundleGenerator::GetPackagingInstallPrefix() { - this->InstallPrefix = "/"; - this->InstallPrefix += this->GetOption("CPACK_BUNDLE_NAME"); - this->InstallPrefix += ".app/Contents/Resources"; + this->InstallPrefix = cmStrCat('/', this->GetOption("CPACK_BUNDLE_NAME"), + ".app/Contents/Resources"); return this->InstallPrefix.c_str(); } @@ -190,9 +190,8 @@ int cmCPackBundleGenerator::SignBundle(const std::string& src_dir) if (!cpack_apple_cert_app.empty()) { std::string output; std::string bundle_path; - bundle_path = src_dir + "/"; - bundle_path += this->GetOption("CPACK_BUNDLE_NAME"); - bundle_path += ".app"; + bundle_path = + cmStrCat(src_dir, '/', this->GetOption("CPACK_BUNDLE_NAME"), ".app"); // A list of additional files to sign, ie. frameworks and plugins. const std::string sign_parameter = @@ -206,7 +205,7 @@ int cmCPackBundleGenerator::SignBundle(const std::string& src_dir) : ""; std::vector<std::string> relFiles; - cmSystemTools::ExpandListArgument(sign_files, relFiles); + cmExpandList(sign_files, relFiles); // sign the files supplied by the user, ie. frameworks. for (auto const& file : relFiles) { diff --git a/Source/CPack/cmCPackComponentGroup.cxx b/Source/CPack/cmCPackComponentGroup.cxx index f888a5f..9e05d86 100644 --- a/Source/CPack/cmCPackComponentGroup.cxx +++ b/Source/CPack/cmCPackComponentGroup.cxx @@ -2,6 +2,7 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmCPackComponentGroup.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include <string> @@ -14,9 +15,7 @@ unsigned long cmCPackComponent::GetInstalledSize( } for (std::string const& file : this->Files) { - std::string path = installDir; - path += '/'; - path += file; + std::string path = cmStrCat(installDir, '/', file); this->TotalSize += cmSystemTools::FileLength(path); } diff --git a/Source/CPack/cmCPackCygwinBinaryGenerator.cxx b/Source/CPack/cmCPackCygwinBinaryGenerator.cxx index 49a9f15..553a677 100644 --- a/Source/CPack/cmCPackCygwinBinaryGenerator.cxx +++ b/Source/CPack/cmCPackCygwinBinaryGenerator.cxx @@ -28,13 +28,11 @@ int cmCPackCygwinBinaryGenerator::InitializeInternal() int cmCPackCygwinBinaryGenerator::PackageFiles() { - std::string packageName = this->GetOption("CPACK_PACKAGE_NAME"); - packageName += "-"; - packageName += this->GetOption("CPACK_PACKAGE_VERSION"); + std::string packageName = + cmStrCat(this->GetOption("CPACK_PACKAGE_NAME"), '-', + this->GetOption("CPACK_PACKAGE_VERSION")); packageName = cmsys::SystemTools::LowerCase(packageName); - std::string manifest = "/usr/share/doc/"; - manifest += packageName; - manifest += "/MANIFEST"; + std::string manifest = cmStrCat("/usr/share/doc/", packageName, "/MANIFEST"); std::string manifestFile = this->GetOption("CPACK_TEMPORARY_DIRECTORY"); // Create a MANIFEST file that contains all of the files in // the tar file diff --git a/Source/CPack/cmCPackCygwinSourceGenerator.cxx b/Source/CPack/cmCPackCygwinSourceGenerator.cxx index 889f29a..8cae9b4 100644 --- a/Source/CPack/cmCPackCygwinSourceGenerator.cxx +++ b/Source/CPack/cmCPackCygwinSourceGenerator.cxx @@ -37,8 +37,7 @@ int cmCPackCygwinSourceGenerator::PackageFiles() { // Create a tar file of the sources std::string packageDirFileName = - this->GetOption("CPACK_TEMPORARY_DIRECTORY"); - packageDirFileName += ".tar.bz2"; + cmStrCat(this->GetOption("CPACK_TEMPORARY_DIRECTORY"), ".tar.bz2"); packageFileNames[0] = packageDirFileName; std::string output; // skip one parent up to the cmCPackTarBZip2Generator @@ -94,8 +93,8 @@ int cmCPackCygwinSourceGenerator::PackageFiles() << this->GetOption("CPACK_TOPLEVEL_DIRECTORY") << "]\n"); return 0; } - std::string outerTarFile = this->GetOption("CPACK_TEMPORARY_DIRECTORY"); - outerTarFile += "-"; + std::string outerTarFile = + cmStrCat(this->GetOption("CPACK_TEMPORARY_DIRECTORY"), '-'); const char* patch = this->GetOption("CPACK_CYGWIN_PATCH_NUMBER"); if (!patch) { cmCPackLogger(cmCPackLog::LOG_WARNING, @@ -106,19 +105,18 @@ int cmCPackCygwinSourceGenerator::PackageFiles() outerTarFile += patch; outerTarFile += "-src.tar.bz2"; std::string tmpDir = this->GetOption("CPACK_TOPLEVEL_DIRECTORY"); - std::string buildScript = tmpDir; - buildScript += "/"; - buildScript += cmSystemTools::GetFilenameName( - this->GetOption("CPACK_CYGWIN_BUILD_SCRIPT")); - std::string patchFile = tmpDir; - patchFile += "/"; - patchFile += - cmSystemTools::GetFilenameName(this->GetOption("CPACK_CYGWIN_PATCH_FILE")); + std::string buildScript = + cmStrCat(tmpDir, '/', + cmSystemTools::GetFilenameName( + this->GetOption("CPACK_CYGWIN_BUILD_SCRIPT"))); + std::string patchFile = + cmStrCat(tmpDir, '/', + cmSystemTools::GetFilenameName( + this->GetOption("CPACK_CYGWIN_PATCH_FILE"))); std::string file = cmSystemTools::GetFilenameName(compressOutFile); - std::string sourceTar = cmSystemTools::GetFilenamePath(compressOutFile); - sourceTar += "/"; - sourceTar += file; + std::string sourceTar = + cmStrCat(cmSystemTools::GetFilenamePath(compressOutFile), '/', file); /* reset list of file to be packaged */ files.clear(); // a source release in cygwin should have the build script used @@ -140,8 +138,8 @@ int cmCPackCygwinSourceGenerator::PackageFiles() const char* cmCPackCygwinSourceGenerator::GetPackagingInstallPrefix() { - this->InstallPrefix = "/"; - this->InstallPrefix += this->GetOption("CPACK_PACKAGE_FILE_NAME"); + this->InstallPrefix = + cmStrCat('/', this->GetOption("CPACK_PACKAGE_FILE_NAME")); return this->InstallPrefix.c_str(); } diff --git a/Source/CPack/cmCPackDebGenerator.cxx b/Source/CPack/cmCPackDebGenerator.cxx index cfb5efd..db336b0 100644 --- a/Source/CPack/cmCPackDebGenerator.cxx +++ b/Source/CPack/cmCPackDebGenerator.cxx @@ -8,6 +8,7 @@ #include "cmCPackLog.h" #include "cmCryptoHash.h" #include "cmGeneratedFileStream.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cm_sys_stat.h" @@ -148,8 +149,7 @@ void DebGenerator::generateControlFile() const unsigned long totalSize = 0; { - std::string dirName = TemporaryDir; - dirName += '/'; + std::string dirName = cmStrCat(TemporaryDir, '/'); for (std::string const& file : PackageFiles) { totalSize += cmSystemTools::FileLength(file); } @@ -247,8 +247,7 @@ std::string DebGenerator::generateMD5File() const cmGeneratedFileStream out(md5filename); - std::string topLevelWithTrailingSlash = TemporaryDir; - topLevelWithTrailingSlash += '/'; + std::string topLevelWithTrailingSlash = cmStrCat(TemporaryDir, '/'); for (std::string const& file : PackageFiles) { // hash only regular files if (cmSystemTools::FileIsDirectory(file) || @@ -378,7 +377,7 @@ bool DebGenerator::generateControlTar(std::string const& md5Filename) const control_tar.ClearPermissions(); std::vector<std::string> controlExtraList; - cmSystemTools::ExpandListArgument(ControlExtra, controlExtraList); + cmExpandList(ControlExtra, controlExtraList); for (std::string const& i : controlExtraList) { std::string filenamename = cmsys::SystemTools::GetFilenameName(i); std::string localcopy = WorkDir + "/" + filenamename; @@ -439,7 +438,7 @@ cmCPackDebGenerator::~cmCPackDebGenerator() = default; int cmCPackDebGenerator::InitializeInternal() { this->SetOptionIfNotSet("CPACK_PACKAGING_INSTALL_PREFIX", "/usr"); - if (cmSystemTools::IsOff(this->GetOption("CPACK_SET_DESTDIR"))) { + if (cmIsOff(this->GetOption("CPACK_SET_DESTDIR"))) { this->SetOption("CPACK_SET_DESTDIR", "I_ON"); } return this->Superclass::InitializeInternal(); @@ -468,8 +467,7 @@ int cmCPackDebGenerator::PackageOnePack(std::string const& initialTopLevel, // Tell CPackDeb.cmake the name of the component GROUP. this->SetOption("CPACK_DEB_PACKAGE_COMPONENT", packageName.c_str()); // Tell CPackDeb.cmake the path where the component is. - std::string component_path = "/"; - component_path += packageName; + std::string component_path = cmStrCat('/', packageName); this->SetOption("CPACK_DEB_PACKAGE_COMPONENT_PART_PATH", component_path.c_str()); if (!this->ReadListFile("Internal/CPack/CPackDeb.cmake")) { @@ -499,9 +497,8 @@ int cmCPackDebGenerator::PackageOnePack(std::string const& initialTopLevel, retval = 0; } // add the generated package to package file names list - packageFileName = this->GetOption("CPACK_TOPLEVEL_DIRECTORY"); - packageFileName += "/"; - packageFileName += this->GetOption("GEN_CPACK_OUTPUT_FILE_NAME"); + packageFileName = cmStrCat(this->GetOption("CPACK_TOPLEVEL_DIRECTORY"), '/', + this->GetOption("GEN_CPACK_OUTPUT_FILE_NAME")); packageFileNames.push_back(std::move(packageFileName)); if (this->IsOn("GEN_CPACK_DEBIAN_DEBUGINFO_PACKAGE")) { @@ -523,9 +520,9 @@ int cmCPackDebGenerator::PackageOnePack(std::string const& initialTopLevel, retval = 0; } // add the generated package to package file names list - packageFileName = this->GetOption("CPACK_TOPLEVEL_DIRECTORY"); - packageFileName += "/"; - packageFileName += this->GetOption("GEN_CPACK_DBGSYM_OUTPUT_FILE_NAME"); + packageFileName = + cmStrCat(this->GetOption("CPACK_TOPLEVEL_DIRECTORY"), '/', + this->GetOption("GEN_CPACK_DBGSYM_OUTPUT_FILE_NAME")); packageFileNames.push_back(std::move(packageFileName)); } @@ -613,8 +610,7 @@ int cmCPackDebGenerator::PackageComponentsAllInOne( if (!compInstDirName.empty()) { // Tell CPackDeb.cmake the path where the component is. - std::string component_path = "/"; - component_path += compInstDirName; + std::string component_path = cmStrCat('/', compInstDirName); this->SetOption("CPACK_DEB_PACKAGE_COMPONENT_PART_PATH", component_path.c_str()); } @@ -643,9 +639,8 @@ int cmCPackDebGenerator::PackageComponentsAllInOne( retval = 0; } // add the generated package to package file names list - packageFileName = this->GetOption("CPACK_TOPLEVEL_DIRECTORY"); - packageFileName += "/"; - packageFileName += this->GetOption("GEN_CPACK_OUTPUT_FILE_NAME"); + packageFileName = cmStrCat(this->GetOption("CPACK_TOPLEVEL_DIRECTORY"), '/', + this->GetOption("GEN_CPACK_OUTPUT_FILE_NAME")); packageFileNames.push_back(std::move(packageFileName)); return retval; } diff --git a/Source/CPack/cmCPackDragNDropGenerator.cxx b/Source/CPack/cmCPackDragNDropGenerator.cxx index 7a3742b..2aa0612 100644 --- a/Source/CPack/cmCPackDragNDropGenerator.cxx +++ b/Source/CPack/cmCPackDragNDropGenerator.cxx @@ -6,6 +6,7 @@ #include "cmCPackLog.h" #include "cmDuration.h" #include "cmGeneratedFileStream.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmsys/FStream.hxx" @@ -128,8 +129,7 @@ int cmCPackDragNDropGenerator::InitializeInternal() } std::vector<std::string> languages; - cmSystemTools::ExpandListArgument( - this->GetOption("CPACK_DMG_SLA_LANGUAGES"), languages); + cmExpandList(this->GetOption("CPACK_DMG_SLA_LANGUAGES"), languages); if (languages.empty()) { cmCPackLogger(cmCPackLog::LOG_ERROR, "CPACK_DMG_SLA_LANGUAGES set but empty" << std::endl); @@ -196,9 +196,7 @@ int cmCPackDragNDropGenerator::PackageFiles() full_package_name += std::string(GetOutputExtension()); packageFileNames.push_back(full_package_name); - std::string src_dir = toplevel; - src_dir += "/"; - src_dir += package_file; + std::string src_dir = cmStrCat(toplevel, '/', package_file); if (0 == this->CreateDMG(src_dir, full_package_name)) { return 0; @@ -409,8 +407,8 @@ int cmCPackDragNDropGenerator::CreateDMG(const std::string& src_dir, } // Create a temporary read-write disk image ... - std::string temp_image = this->GetOption("CPACK_TOPLEVEL_DIRECTORY"); - temp_image += "/temp.dmg"; + std::string temp_image = + cmStrCat(this->GetOption("CPACK_TOPLEVEL_DIRECTORY"), "/temp.dmg"); std::string create_error; std::ostringstream temp_image_command; @@ -522,12 +520,12 @@ int cmCPackDragNDropGenerator::CreateDMG(const std::string& src_dir, if (!cpack_license_file.empty() || !slaDirectory.empty()) { // Use old hardcoded style if sla_dir is not set bool oldStyle = slaDirectory.empty(); - std::string sla_r = this->GetOption("CPACK_TOPLEVEL_DIRECTORY"); - sla_r += "/sla.r"; + std::string sla_r = + cmStrCat(this->GetOption("CPACK_TOPLEVEL_DIRECTORY"), "/sla.r"); std::vector<std::string> languages; if (!oldStyle) { - cmSystemTools::ExpandListArgument(cpack_dmg_languages, languages); + cmExpandList(cpack_dmg_languages, languages); } cmGeneratedFileStream ofs(sla_r); @@ -649,8 +647,8 @@ int cmCPackDragNDropGenerator::CreateDMG(const std::string& src_dir, if (temp_image_format != "UDZO") { temp_image_format = "UDZO"; // convert to UDZO to enable unflatten/flatten - std::string temp_udzo = this->GetOption("CPACK_TOPLEVEL_DIRECTORY"); - temp_udzo += "/temp-udzo.dmg"; + std::string temp_udzo = cmStrCat( + this->GetOption("CPACK_TOPLEVEL_DIRECTORY"), "/temp-udzo.dmg"); std::ostringstream udco_image_command; udco_image_command << this->GetOption("CPACK_COMMAND_HDIUTIL"); diff --git a/Source/CPack/cmCPackExternalGenerator.cxx b/Source/CPack/cmCPackExternalGenerator.cxx index b4c7a5a..5dc6ace 100644 --- a/Source/CPack/cmCPackExternalGenerator.cxx +++ b/Source/CPack/cmCPackExternalGenerator.cxx @@ -5,6 +5,7 @@ #include "cmCPackComponentGroup.h" #include "cmCPackLog.h" #include "cmMakefile.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cm_jsoncpp_value.h" @@ -149,8 +150,7 @@ int cmCPackExternalGenerator::InstallCMakeProject( bool cmCPackExternalGenerator::StagingEnabled() const { - return !cmSystemTools::IsOff( - this->GetOption("CPACK_EXTERNAL_ENABLE_STAGING")); + return !cmIsOff(this->GetOption("CPACK_EXTERNAL_ENABLE_STAGING")); } cmCPackExternalGenerator::cmCPackExternalVersionGenerator:: @@ -208,8 +208,7 @@ int cmCPackExternalGenerator::cmCPackExternalVersionGenerator::WriteToJSON( if (defaultDirectoryPermissions && *defaultDirectoryPermissions) { root["defaultDirectoryPermissions"] = defaultDirectoryPermissions; } - if (cmSystemTools::IsInternallyOn( - this->Parent->GetOption("CPACK_SET_DESTDIR"))) { + if (cmIsInternallyOn(this->Parent->GetOption("CPACK_SET_DESTDIR"))) { root["setDestdir"] = true; root["packagingInstallPrefix"] = this->Parent->GetOption("CPACK_PACKAGING_INSTALL_PREFIX"); @@ -217,8 +216,7 @@ int cmCPackExternalGenerator::cmCPackExternalVersionGenerator::WriteToJSON( root["setDestdir"] = false; } - root["stripFiles"] = - !cmSystemTools::IsOff(this->Parent->GetOption("CPACK_STRIP_FILES")); + root["stripFiles"] = !cmIsOff(this->Parent->GetOption("CPACK_STRIP_FILES")); root["warnOnAbsoluteInstallDestination"] = this->Parent->IsOn("CPACK_WARN_ON_ABSOLUTE_INSTALL_DESTINATION"); root["errorOnAbsoluteInstallDestination"] = diff --git a/Source/CPack/cmCPackFreeBSDGenerator.cxx b/Source/CPack/cmCPackFreeBSDGenerator.cxx index 9fdafa4..b90a27c 100644 --- a/Source/CPack/cmCPackFreeBSDGenerator.cxx +++ b/Source/CPack/cmCPackFreeBSDGenerator.cxx @@ -6,6 +6,7 @@ #include "cmCPackArchiveGenerator.h" #include "cmCPackLog.h" #include "cmGeneratedFileStream.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" // Needed for ::open() and ::stat() @@ -228,8 +229,7 @@ void cmCPackFreeBSDGenerator::write_manifest_fields( "desc", var_lookup("CPACK_FREEBSD_PACKAGE_DESCRIPTION")); manifest << ManifestKeyValue("www", var_lookup("CPACK_FREEBSD_PACKAGE_WWW")); std::vector<std::string> licenses; - cmSystemTools::ExpandListArgument( - var_lookup("CPACK_FREEBSD_PACKAGE_LICENSE"), licenses); + cmExpandList(var_lookup("CPACK_FREEBSD_PACKAGE_LICENSE"), licenses); std::string licenselogic("single"); if (licenses.empty()) { cmSystemTools::SetFatalErrorOccured(); @@ -239,13 +239,11 @@ void cmCPackFreeBSDGenerator::write_manifest_fields( manifest << ManifestKeyValue("licenselogic", licenselogic); manifest << (ManifestKeyListValue("licenses") << licenses); std::vector<std::string> categories; - cmSystemTools::ExpandListArgument( - var_lookup("CPACK_FREEBSD_PACKAGE_CATEGORIES"), categories); + cmExpandList(var_lookup("CPACK_FREEBSD_PACKAGE_CATEGORIES"), categories); manifest << (ManifestKeyListValue("categories") << categories); manifest << ManifestKeyValue("prefix", var_lookup("CMAKE_INSTALL_PREFIX")); std::vector<std::string> deps; - cmSystemTools::ExpandListArgument(var_lookup("CPACK_FREEBSD_PACKAGE_DEPS"), - deps); + cmExpandList(var_lookup("CPACK_FREEBSD_PACKAGE_DEPS"), deps); if (!deps.empty()) { manifest << (ManifestKeyDepsValue("deps") << deps); } diff --git a/Source/CPack/cmCPackGenerator.cxx b/Source/CPack/cmCPackGenerator.cxx index 3fd124b..0e9f1b6 100644 --- a/Source/CPack/cmCPackGenerator.cxx +++ b/Source/CPack/cmCPackGenerator.cxx @@ -73,8 +73,8 @@ int cmCPackGenerator::PrepareNames() } } - std::string tempDirectory = this->GetOption("CPACK_PACKAGE_DIRECTORY"); - tempDirectory += "/_CPack_Packages/"; + std::string tempDirectory = + cmStrCat(this->GetOption("CPACK_PACKAGE_DIRECTORY"), "/_CPack_Packages/"); const char* toplevelTag = this->GetOption("CPACK_TOPLEVEL_TAG"); if (toplevelTag) { tempDirectory += toplevelTag; @@ -180,8 +180,8 @@ int cmCPackGenerator::InstallProject() std::string bareTempInstallDirectory = this->GetOption("CPACK_TEMPORARY_INSTALL_DIRECTORY"); std::string tempInstallDirectoryStr = bareTempInstallDirectory; - bool setDestDir = cmSystemTools::IsOn(this->GetOption("CPACK_SET_DESTDIR")) | - cmSystemTools::IsInternallyOn(this->GetOption("CPACK_SET_DESTDIR")); + bool setDestDir = cmIsOn(this->GetOption("CPACK_SET_DESTDIR")) | + cmIsInternallyOn(this->GetOption("CPACK_SET_DESTDIR")); if (!setDestDir) { tempInstallDirectoryStr += this->GetPackagingInstallPrefix(); } @@ -197,8 +197,7 @@ int cmCPackGenerator::InstallProject() } if (setDestDir) { - std::string destDir = "DESTDIR="; - destDir += tempInstallDirectory; + std::string destDir = cmStrCat("DESTDIR=", tempInstallDirectory); cmSystemTools::PutEnv(destDir); } else { // Make sure there is no destdir @@ -212,7 +211,7 @@ int cmCPackGenerator::InstallProject() this->GetOption("CPACK_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS"); if (default_dir_install_permissions && *default_dir_install_permissions) { std::vector<std::string> items; - cmSystemTools::ExpandListArgument(default_dir_install_permissions, items); + cmExpandList(default_dir_install_permissions, items); for (const auto& arg : items) { if (!cmFSPermissions::stringToModeT(arg, default_dir_mode_v)) { cmCPackLogger(cmCPackLog::LOG_ERROR, @@ -271,11 +270,11 @@ int cmCPackGenerator::InstallProjectViaInstallCommands( (void)setDestDir; const char* installCommands = this->GetOption("CPACK_INSTALL_COMMANDS"); if (installCommands && *installCommands) { - std::string tempInstallDirectoryEnv = "CMAKE_INSTALL_PREFIX="; - tempInstallDirectoryEnv += tempInstallDirectory; + std::string tempInstallDirectoryEnv = + cmStrCat("CMAKE_INSTALL_PREFIX=", tempInstallDirectory); cmSystemTools::PutEnv(tempInstallDirectoryEnv); std::vector<std::string> installCommandsVector; - cmSystemTools::ExpandListArgument(installCommands, installCommandsVector); + cmExpandList(installCommands, installCommandsVector); for (std::string const& ic : installCommandsVector) { cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Execute: " << ic << std::endl); std::string output; @@ -284,8 +283,8 @@ int cmCPackGenerator::InstallProjectViaInstallCommands( ic, &output, &output, &retVal, nullptr, this->GeneratorVerbose, cmDuration::zero()); if (!resB || retVal) { - std::string tmpFile = this->GetOption("CPACK_TOPLEVEL_DIRECTORY"); - tmpFile += "/InstallOutput.log"; + std::string tmpFile = cmStrCat( + this->GetOption("CPACK_TOPLEVEL_DIRECTORY"), "/InstallOutput.log"); cmGeneratedFileStream ofs(tmpFile); ofs << "# Run command: " << ic << std::endl << "# Output:" << std::endl @@ -312,8 +311,7 @@ int cmCPackGenerator::InstallProjectViaInstalledDirectories( const char* cpackIgnoreFiles = this->GetOption("CPACK_IGNORE_FILES"); if (cpackIgnoreFiles) { std::vector<std::string> ignoreFilesRegexString; - cmSystemTools::ExpandListArgument(cpackIgnoreFiles, - ignoreFilesRegexString); + cmExpandList(cpackIgnoreFiles, ignoreFilesRegexString); for (std::string const& ifr : ignoreFilesRegexString) { cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Create ignore files regex for: " << ifr << std::endl); @@ -324,8 +322,7 @@ int cmCPackGenerator::InstallProjectViaInstalledDirectories( this->GetOption("CPACK_INSTALLED_DIRECTORIES"); if (installDirectories && *installDirectories) { std::vector<std::string> installDirectoriesVector; - cmSystemTools::ExpandListArgument(installDirectories, - installDirectoriesVector); + cmExpandList(installDirectories, installDirectoriesVector); if (installDirectoriesVector.size() % 2 != 0) { cmCPackLogger( cmCPackLog::LOG_ERROR, @@ -345,8 +342,7 @@ int cmCPackGenerator::InstallProjectViaInstalledDirectories( std::string top = *it; it++; std::string subdir = *it; - std::string findExpr = top; - findExpr += "/*"; + std::string findExpr = cmStrCat(top, "/*"); cmCPackLogger(cmCPackLog::LOG_OUTPUT, "- Install directory: " << top << std::endl); gl.RecurseOn(); @@ -374,8 +370,8 @@ int cmCPackGenerator::InstallProjectViaInstalledDirectories( if (skip) { continue; } - std::string filePath = tempDir; - filePath += "/" + subdir + "/" + cmSystemTools::RelativePath(top, gf); + std::string filePath = cmStrCat(tempDir, '/', subdir, '/', + cmSystemTools::RelativePath(top, gf)); cmCPackLogger(cmCPackLog::LOG_DEBUG, "Copy file: " << inFile << " -> " << filePath << std::endl); @@ -400,8 +396,7 @@ int cmCPackGenerator::InstallProjectViaInstalledDirectories( /* rebuild symlinks in the installed tree */ if (!symlinkedFiles.empty()) { std::string curDir = cmSystemTools::GetCurrentWorkingDirectory(); - std::string goToDir = tempDir; - goToDir += "/" + subdir; + std::string goToDir = cmStrCat(tempDir, '/', subdir); cmCPackLogger(cmCPackLog::LOG_DEBUG, "Change dir to: " << goToDir << std::endl); cmWorkingDirectory workdir(goToDir); @@ -466,7 +461,7 @@ int cmCPackGenerator::InstallProjectViaInstallScript( cmCPackLogger(cmCPackLog::LOG_OUTPUT, "- Install scripts: " << cmakeScripts << std::endl); std::vector<std::string> cmakeScriptsVector; - cmSystemTools::ExpandListArgument(cmakeScripts, cmakeScriptsVector); + cmExpandList(cmakeScripts, cmakeScriptsVector); for (std::string const& installScript : cmakeScriptsVector) { cmCPackLogger(cmCPackLog::LOG_OUTPUT, @@ -531,7 +526,7 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects( return 0; } std::vector<std::string> cmakeProjectsVector; - cmSystemTools::ExpandListArgument(cmakeProjects, cmakeProjectsVector); + cmExpandList(cmakeProjects, cmakeProjectsVector); std::vector<std::string>::iterator it; for (it = cmakeProjectsVector.begin(); it != cmakeProjectsVector.end(); ++it) { @@ -576,7 +571,7 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects( const char* installTypes = this->GetOption(installTypesVar); if (installTypes && *installTypes) { std::vector<std::string> installTypesVector; - cmSystemTools::ExpandListArgument(installTypes, installTypesVector); + cmExpandList(installTypes, installTypesVector); for (std::string const& installType : installTypesVector) { project.InstallationTypes.push_back( this->GetInstallationType(project.ProjectName, installType)); @@ -588,7 +583,7 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects( "CPACK_COMPONENTS_" + cmSystemTools::UpperCase(project.Component); const char* components = this->GetOption(componentsVar); if (components && *components) { - cmSystemTools::ExpandListArgument(components, componentsVector); + cmExpandList(components, componentsVector); for (std::string const& comp : componentsVector) { project.Components.push_back( this->GetComponent(project.ProjectName, comp)); @@ -664,8 +659,8 @@ int cmCPackGenerator::RunPreinstallTarget( buildCommand, &output, &output, &retVal, installDirectory.c_str(), this->GeneratorVerbose, cmDuration::zero()); if (!resB || retVal) { - std::string tmpFile = this->GetOption("CPACK_TOPLEVEL_DIRECTORY"); - tmpFile += "/PreinstallOutput.log"; + std::string tmpFile = cmStrCat( + this->GetOption("CPACK_TOPLEVEL_DIRECTORY"), "/PreinstallOutput.log"); cmGeneratedFileStream ofs(tmpFile); ofs << "# Run command: " << buildCommand << std::endl << "# Directory: " << installDirectory << std::endl @@ -752,7 +747,7 @@ int cmCPackGenerator::InstallCMakeProject( // CPACK_PACKAGING_INSTALL_PREFIX // I know this is tricky and awkward but it's the price for // CPACK_SET_DESTDIR backward compatibility. - if (cmSystemTools::IsInternallyOn(this->GetOption("CPACK_SET_DESTDIR"))) { + if (cmIsInternallyOn(this->GetOption("CPACK_SET_DESTDIR"))) { this->SetOption("CPACK_INSTALL_PREFIX", this->GetOption("CPACK_PACKAGING_INSTALL_PREFIX")); } @@ -828,7 +823,7 @@ int cmCPackGenerator::InstallCMakeProject( // strip on TRUE, ON, 1, one or several file names, but not on // FALSE, OFF, 0 and an empty string - if (!cmSystemTools::IsOff(this->GetOption("CPACK_STRIP_FILES"))) { + if (!cmIsOff(this->GetOption("CPACK_STRIP_FILES"))) { mf.AddDefinition("CMAKE_INSTALL_DO_STRIP", "1"); } // Remember the list of files before installation @@ -913,10 +908,8 @@ int cmCPackGenerator::InstallCMakeProject( GetComponentInstallDirNameSuffix(component); if (nullptr != this->GetOption(absoluteDestFileComponent)) { std::string absoluteDestFilesListComponent = - this->GetOption(absoluteDestFileComponent); - absoluteDestFilesListComponent += ";"; - absoluteDestFilesListComponent += - mf.GetDefinition("CPACK_ABSOLUTE_DESTINATION_FILES"); + cmStrCat(this->GetOption(absoluteDestFileComponent), ';', + mf.GetDefinition("CPACK_ABSOLUTE_DESTINATION_FILES")); this->SetOption(absoluteDestFileComponent, absoluteDestFilesListComponent.c_str()); } else { @@ -979,8 +972,7 @@ int cmCPackGenerator::DoPackage() return 0; } - if (cmSystemTools::IsOn( - this->GetOption("CPACK_REMOVE_TOPLEVEL_DIRECTORY"))) { + if (cmIsOn(this->GetOption("CPACK_REMOVE_TOPLEVEL_DIRECTORY"))) { const char* toplevelDirectory = this->GetOption("CPACK_TOPLEVEL_DIRECTORY"); if (cmSystemTools::FileExists(toplevelDirectory)) { @@ -1009,8 +1001,7 @@ int cmCPackGenerator::DoPackage() cmCPackLogger(cmCPackLog::LOG_DEBUG, "Find files" << std::endl); cmsys::Glob gl; - std::string findExpr = tempDirectory; - findExpr += "/*"; + std::string findExpr = cmStrCat(tempDirectory, "/*"); gl.RecurseOn(); gl.SetRecurseListDirs(true); gl.SetRecurseThroughSymlinks(false); @@ -1030,8 +1021,7 @@ int cmCPackGenerator::DoPackage() "Remove old package file" << std::endl); cmSystemTools::RemoveFile(tempPackageFileName); } - if (cmSystemTools::IsOn( - this->GetOption("CPACK_INCLUDE_TOPLEVEL_DIRECTORY"))) { + if (cmIsOn(this->GetOption("CPACK_INCLUDE_TOPLEVEL_DIRECTORY"))) { tempDirectory = this->GetOption("CPACK_TOPLEVEL_DIRECTORY"); } @@ -1155,14 +1145,14 @@ bool cmCPackGenerator::IsSet(const std::string& name) const bool cmCPackGenerator::IsOn(const std::string& name) const { - return cmSystemTools::IsOn(GetOption(name)); + return cmIsOn(GetOption(name)); } bool cmCPackGenerator::IsSetToOff(const std::string& op) const { const char* ret = this->MakefileMap->GetDefinition(op); if (ret && *ret) { - return cmSystemTools::IsOff(ret); + return cmIsOff(ret); } return false; } @@ -1207,8 +1197,7 @@ const char* cmCPackGenerator::GetInstallPath() if (cmsys::SystemTools::GetEnv("ProgramFiles", prgfiles)) { this->InstallPath = prgfiles; } else if (cmsys::SystemTools::GetEnv("SystemDrive", sysDrive)) { - this->InstallPath = sysDrive; - this->InstallPath += "/Program Files"; + this->InstallPath = cmStrCat(sysDrive, "/Program Files"); } else { this->InstallPath = "c:/Program Files"; } @@ -1476,7 +1465,7 @@ cmCPackComponent* cmCPackGenerator::GetComponent( component->IsRequired = this->IsOn(macroPrefix + "_REQUIRED"); component->IsDisabledByDefault = this->IsOn(macroPrefix + "_DISABLED"); component->IsDownloaded = this->IsOn(macroPrefix + "_DOWNLOADED") || - cmSystemTools::IsOn(this->GetOption("CPACK_DOWNLOAD_ALL")); + cmIsOn(this->GetOption("CPACK_DOWNLOAD_ALL")); const char* archiveFile = this->GetOption(macroPrefix + "_ARCHIVE_FILE"); if (archiveFile && *archiveFile) { @@ -1505,7 +1494,7 @@ cmCPackComponent* cmCPackGenerator::GetComponent( const char* installTypes = this->GetOption(macroPrefix + "_INSTALL_TYPES"); if (installTypes && *installTypes) { std::vector<std::string> installTypesVector; - cmSystemTools::ExpandListArgument(installTypes, installTypesVector); + cmExpandList(installTypes, installTypesVector); for (std::string const& installType : installTypesVector) { component->InstallationTypes.push_back( this->GetInstallationType(projectName, installType)); @@ -1516,7 +1505,7 @@ cmCPackComponent* cmCPackGenerator::GetComponent( const char* depends = this->GetOption(macroPrefix + "_DEPENDS"); if (depends && *depends) { std::vector<std::string> dependsVector; - cmSystemTools::ExpandListArgument(depends, dependsVector); + cmExpandList(depends, dependsVector); for (std::string const& depend : dependsVector) { cmCPackComponent* child = GetComponent(projectName, depend); component->Dependencies.push_back(child); diff --git a/Source/CPack/cmCPackNSISGenerator.cxx b/Source/CPack/cmCPackNSISGenerator.cxx index 87c36fa..41ffa0e 100644 --- a/Source/CPack/cmCPackNSISGenerator.cxx +++ b/Source/CPack/cmCPackNSISGenerator.cxx @@ -2,11 +2,13 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmCPackNSISGenerator.h" +#include "cmAlgorithms.h" #include "cmCPackComponentGroup.h" #include "cmCPackGenerator.h" #include "cmCPackLog.h" #include "cmDuration.h" #include "cmGeneratedFileStream.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmsys/Directory.hxx" @@ -54,8 +56,7 @@ int cmCPackNSISGenerator::PackageFiles() } std::string nsisFileName = this->GetOption("CPACK_TOPLEVEL_DIRECTORY"); - std::string tmpFile = nsisFileName; - tmpFile += "/NSISOutput.log"; + std::string tmpFile = cmStrCat(nsisFileName, "/NSISOutput.log"); std::string nsisInstallOptions = nsisFileName + "/NSIS.InstallOptions.ini"; nsisFileName += "/project.nsi"; std::ostringstream str; @@ -140,39 +141,34 @@ int cmCPackNSISGenerator::PackageFiles() installerIconCode.c_str()); } if (this->IsSet("CPACK_PACKAGE_ICON")) { - std::string installerIconCode = "!define MUI_HEADERIMAGE_BITMAP \""; - installerIconCode += this->GetOption("CPACK_PACKAGE_ICON"); - installerIconCode += "\"\n"; + std::string installerIconCode = + cmStrCat("!define MUI_HEADERIMAGE_BITMAP \"", + this->GetOption("CPACK_PACKAGE_ICON"), "\"\n"); this->SetOptionIfNotSet("CPACK_NSIS_INSTALLER_ICON_CODE", installerIconCode.c_str()); } if (this->IsSet("CPACK_NSIS_MUI_WELCOMEFINISHPAGE_BITMAP")) { - std::string installerBitmapCode = - "!define MUI_WELCOMEFINISHPAGE_BITMAP \""; - installerBitmapCode += - this->GetOption("CPACK_NSIS_MUI_WELCOMEFINISHPAGE_BITMAP"); - installerBitmapCode += "\"\n"; + std::string installerBitmapCode = cmStrCat( + "!define MUI_WELCOMEFINISHPAGE_BITMAP \"", + this->GetOption("CPACK_NSIS_MUI_WELCOMEFINISHPAGE_BITMAP"), "\"\n"); this->SetOptionIfNotSet("CPACK_NSIS_INSTALLER_MUI_WELCOMEFINISH_CODE", installerBitmapCode.c_str()); } if (this->IsSet("CPACK_NSIS_MUI_UNWELCOMEFINISHPAGE_BITMAP")) { - std::string installerBitmapCode = - "!define MUI_UNWELCOMEFINISHPAGE_BITMAP \""; - installerBitmapCode += - this->GetOption("CPACK_NSIS_MUI_UNWELCOMEFINISHPAGE_BITMAP"); - installerBitmapCode += "\"\n"; + std::string installerBitmapCode = cmStrCat( + "!define MUI_UNWELCOMEFINISHPAGE_BITMAP \"", + this->GetOption("CPACK_NSIS_MUI_UNWELCOMEFINISHPAGE_BITMAP"), "\"\n"); this->SetOptionIfNotSet("CPACK_NSIS_INSTALLER_MUI_UNWELCOMEFINISH_CODE", installerBitmapCode.c_str()); } if (this->IsSet("CPACK_NSIS_MUI_FINISHPAGE_RUN")) { - std::string installerRunCode = "!define MUI_FINISHPAGE_RUN \"$INSTDIR\\"; - installerRunCode += this->GetOption("CPACK_NSIS_EXECUTABLES_DIRECTORY"); - installerRunCode += "\\"; - installerRunCode += this->GetOption("CPACK_NSIS_MUI_FINISHPAGE_RUN"); - installerRunCode += "\"\n"; + std::string installerRunCode = + cmStrCat("!define MUI_FINISHPAGE_RUN \"$INSTDIR\\", + this->GetOption("CPACK_NSIS_EXECUTABLES_DIRECTORY"), '\\', + this->GetOption("CPACK_NSIS_MUI_FINISHPAGE_RUN"), "\"\n"); this->SetOptionIfNotSet("CPACK_NSIS_INSTALLER_MUI_FINISHPAGE_RUN_CODE", installerRunCode.c_str()); } @@ -274,7 +270,7 @@ int cmCPackNSISGenerator::PackageFiles() if (anyDownloadedComponents) { defines += "!define CPACK_USES_DOWNLOAD\n"; - if (cmSystemTools::IsOn(this->GetOption("CPACK_ADD_REMOVE"))) { + if (cmIsOn(this->GetOption("CPACK_ADD_REMOVE"))) { defines += "!define CPACK_NSIS_ADD_REMOVE\n"; } } @@ -295,9 +291,9 @@ int cmCPackNSISGenerator::PackageFiles() this->ConfigureFile(nsisInInstallOptions, nsisInstallOptions); this->ConfigureFile(nsisInFileName, nsisFileName); - std::string nsisCmd = "\""; - nsisCmd += this->GetOption("CPACK_INSTALLER_PROGRAM"); - nsisCmd += "\" \"" + nsisFileName + "\""; + std::string nsisCmd = + cmStrCat('"', this->GetOption("CPACK_INSTALLER_PROGRAM"), "\" \"", + nsisFileName, '"'); cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Execute: " << nsisCmd << std::endl); std::string output; int retVal = 1; @@ -321,8 +317,7 @@ int cmCPackNSISGenerator::PackageFiles() int cmCPackNSISGenerator::InitializeInternal() { - if (cmSystemTools::IsOn( - this->GetOption("CPACK_INCLUDE_TOPLEVEL_DIRECTORY"))) { + if (cmIsOn(this->GetOption("CPACK_INCLUDE_TOPLEVEL_DIRECTORY"))) { cmCPackLogger( cmCPackLog::LOG_WARNING, "NSIS Generator cannot work with CPACK_INCLUDE_TOPLEVEL_DIRECTORY set. " @@ -414,8 +409,7 @@ int cmCPackNSISGenerator::InitializeInternal() if (!resS || retVal || (!versionRex.find(output) && !versionRexCVS.find(output))) { const char* topDir = this->GetOption("CPACK_TOPLEVEL_DIRECTORY"); - std::string tmpFile = topDir ? topDir : "."; - tmpFile += "/NSISOutput.log"; + std::string tmpFile = cmStrCat(topDir ? topDir : ".", "/NSISOutput.log"); cmGeneratedFileStream ofs(tmpFile); ofs << "# Run command: " << nsisCmd << std::endl << "# Output:" << std::endl @@ -459,8 +453,7 @@ int cmCPackNSISGenerator::InitializeInternal() "CPACK_CREATE_DESKTOP_LINKS: " << cpackPackageDeskTopLinks << std::endl); - cmSystemTools::ExpandListArgument(cpackPackageDeskTopLinks, - cpackPackageDesktopLinksVector); + cmExpandList(cpackPackageDeskTopLinks, cpackPackageDesktopLinksVector); for (std::string const& cpdl : cpackPackageDesktopLinksVector) { cmCPackLogger(cmCPackLog::LOG_DEBUG, "CPACK_CREATE_DESKTOP_LINKS: " << cpdl << std::endl); @@ -479,8 +472,7 @@ int cmCPackNSISGenerator::InitializeInternal() "The cpackPackageExecutables: " << cpackPackageExecutables << "." << std::endl); std::vector<std::string> cpackPackageExecutablesVector; - cmSystemTools::ExpandListArgument(cpackPackageExecutables, - cpackPackageExecutablesVector); + cmExpandList(cpackPackageExecutables, cpackPackageExecutablesVector); if (cpackPackageExecutablesVector.size() % 2 != 0) { cmCPackLogger( cmCPackLog::LOG_ERROR, @@ -502,10 +494,7 @@ int cmCPackNSISGenerator::InitializeInternal() << ".lnk\"" << std::endl; // see if CPACK_CREATE_DESKTOP_LINK_ExeName is on // if so add a desktop link - if (!cpackPackageDesktopLinksVector.empty() && - std::find(cpackPackageDesktopLinksVector.begin(), - cpackPackageDesktopLinksVector.end(), - execName) != cpackPackageDesktopLinksVector.end()) { + if (cmContains(cpackPackageDesktopLinksVector, execName)) { str << " StrCmp \"$INSTALL_DESKTOP\" \"1\" 0 +2\n"; str << " CreateShortCut \"$DESKTOP\\" << linkName << R"(.lnk" "$INSTDIR\)" << cpackNsisExecutablesDirectory << "\\" @@ -536,7 +525,7 @@ void cmCPackNSISGenerator::CreateMenuLinks(std::ostream& str, cmCPackLogger(cmCPackLog::LOG_DEBUG, "The cpackMenuLinks: " << cpackMenuLinks << "." << std::endl); std::vector<std::string> cpackMenuLinksVector; - cmSystemTools::ExpandListArgument(cpackMenuLinks, cpackMenuLinksVector); + cmExpandList(cpackMenuLinks, cpackMenuLinksVector); if (cpackMenuLinksVector.size() % 2 != 0) { cmCPackLogger( cmCPackLog::LOG_ERROR, @@ -577,8 +566,7 @@ void cmCPackNSISGenerator::CreateMenuLinks(std::ostream& str, } // see if CPACK_CREATE_DESKTOP_LINK_ExeName is on // if so add a desktop link - std::string desktop = "CPACK_CREATE_DESKTOP_LINK_"; - desktop += linkName; + std::string desktop = cmStrCat("CPACK_CREATE_DESKTOP_LINK_", linkName); if (this->IsSet(desktop)) { str << " StrCmp \"$INSTALL_DESKTOP\" \"1\" 0 +2\n"; str << " CreateShortCut \"$DESKTOP\\" << linkName @@ -660,8 +648,8 @@ std::string cmCPackNSISGenerator::CreateComponentDescription( if (component->IsDownloaded) { if (component->ArchiveFile.empty()) { // Compute the name of the archive. - std::string packagesDir = this->GetOption("CPACK_TEMPORARY_DIRECTORY"); - packagesDir += ".dummy"; + std::string packagesDir = + cmStrCat(this->GetOption("CPACK_TEMPORARY_DIRECTORY"), ".dummy"); std::ostringstream out; out << cmSystemTools::GetFilenameWithoutLastExtension(packagesDir) << "-" << component->Name << ".zip"; @@ -675,8 +663,8 @@ std::string cmCPackNSISGenerator::CreateComponentDescription( if (userUploadDirectory && *userUploadDirectory) { uploadDirectory = userUploadDirectory; } else { - uploadDirectory = this->GetOption("CPACK_PACKAGE_DIRECTORY"); - uploadDirectory += "/CPackUploads"; + uploadDirectory = + cmStrCat(this->GetOption("CPACK_PACKAGE_DIRECTORY"), "/CPackUploads"); } if (!cmSystemTools::FileExists(uploadDirectory)) { if (!cmSystemTools::MakeDirectory(uploadDirectory)) { @@ -713,17 +701,14 @@ std::string cmCPackNSISGenerator::CreateComponentDescription( } // The directory where this component's files reside - std::string dirName = this->GetOption("CPACK_TEMPORARY_DIRECTORY"); - dirName += '/'; - dirName += component->Name; - dirName += '/'; + std::string dirName = cmStrCat( + this->GetOption("CPACK_TEMPORARY_DIRECTORY"), '/', component->Name, '/'); // Build the list of files to go into this archive, and determine the // size of the installed component. - std::string zipListFileName = this->GetOption("CPACK_TEMPORARY_DIRECTORY"); - zipListFileName += "/winZip.filelist"; - bool needQuotesInFile = - cmSystemTools::IsOn(this->GetOption("CPACK_ZIP_NEED_QUOTES")); + std::string zipListFileName = cmStrCat( + this->GetOption("CPACK_TEMPORARY_DIRECTORY"), "/winZip.filelist"); + bool needQuotesInFile = cmIsOn(this->GetOption("CPACK_ZIP_NEED_QUOTES")); unsigned long totalSize = 0; { // the scope is needed for cmGeneratedFileStream cmGeneratedFileStream out(zipListFileName); @@ -752,8 +737,8 @@ std::string cmCPackNSISGenerator::CreateComponentDescription( cmd, &output, &output, &retVal, dirName.c_str(), cmSystemTools::OUTPUT_NONE, cmDuration::zero()); if (!res || retVal) { - std::string tmpFile = this->GetOption("CPACK_TOPLEVEL_DIRECTORY"); - tmpFile += "/CompressZip.log"; + std::string tmpFile = cmStrCat( + this->GetOption("CPACK_TOPLEVEL_DIRECTORY"), "/CompressZip.log"); cmGeneratedFileStream ofs(tmpFile); ofs << "# Run command: " << cmd << std::endl << "# Output:" << std::endl diff --git a/Source/CPack/cmCPackOSXX11Generator.cxx b/Source/CPack/cmCPackOSXX11Generator.cxx index 41470c9..ffa8a42 100644 --- a/Source/CPack/cmCPackOSXX11Generator.cxx +++ b/Source/CPack/cmCPackOSXX11Generator.cxx @@ -8,6 +8,7 @@ #include "cmCPackLog.h" #include "cmDuration.h" #include "cmGeneratedFileStream.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cm_sys_stat.h" @@ -29,8 +30,7 @@ int cmCPackOSXX11Generator::PackageFiles() std::ostringstream str; std::ostringstream deleteStr; std::vector<std::string> cpackPackageExecutablesVector; - cmSystemTools::ExpandListArgument(cpackPackageExecutables, - cpackPackageExecutablesVector); + cmExpandList(cpackPackageExecutables, cpackPackageExecutablesVector); if (cpackPackageExecutablesVector.size() % 2 != 0) { cmCPackLogger( cmCPackLog::LOG_ERROR, @@ -55,16 +55,14 @@ int cmCPackOSXX11Generator::PackageFiles() diskImageDirectory + "/.background"; // App bundle directories - std::string packageDirFileName = toplevel; - packageDirFileName += "/"; - packageDirFileName += this->GetOption("CPACK_PACKAGE_FILE_NAME"); - packageDirFileName += ".app"; + std::string packageDirFileName = cmStrCat( + toplevel, '/', this->GetOption("CPACK_PACKAGE_FILE_NAME"), ".app"); std::string contentsDirectory = packageDirFileName + "/Contents"; std::string resourcesDirectory = contentsDirectory + "/Resources"; std::string appDirectory = contentsDirectory + "/MacOS"; std::string scriptDirectory = resourcesDirectory + "/Scripts"; - std::string resourceFileName = this->GetOption("CPACK_PACKAGE_FILE_NAME"); - resourceFileName += ".rsrc"; + std::string resourceFileName = + cmStrCat(this->GetOption("CPACK_PACKAGE_FILE_NAME"), ".rsrc"); const char* dir = resourcesDirectory.c_str(); const char* appdir = appDirectory.c_str(); @@ -113,13 +111,10 @@ int cmCPackOSXX11Generator::PackageFiles() } // Two of the files need to have execute permission, so ensure they do: - std::string runTimeScript = dir; - runTimeScript += "/"; - runTimeScript += "RuntimeScript"; + std::string runTimeScript = cmStrCat(dir, "/RuntimeScript"); - std::string appScriptName = appdir; - appScriptName += "/"; - appScriptName += this->GetOption("CPACK_PACKAGE_FILE_NAME"); + std::string appScriptName = + cmStrCat(appdir, '/', this->GetOption("CPACK_PACKAGE_FILE_NAME")); mode_t mode; if (cmsys::SystemTools::GetPermissions(runTimeScript.c_str(), mode)) { @@ -139,8 +134,8 @@ int cmCPackOSXX11Generator::PackageFiles() } std::string output; - std::string tmpFile = this->GetOption("CPACK_TOPLEVEL_DIRECTORY"); - tmpFile += "/hdiutilOutput.log"; + std::string tmpFile = cmStrCat(this->GetOption("CPACK_TOPLEVEL_DIRECTORY"), + "/hdiutilOutput.log"); std::ostringstream dmgCmd; dmgCmd << "\"" << this->GetOption("CPACK_INSTALLER_PROGRAM_DISK_IMAGE") << "\" create -ov -fs HFS+ -format UDZO -srcfolder \"" @@ -228,9 +223,8 @@ bool cmCPackOSXX11Generator::CopyCreateResourceFile(const std::string& name) return false; } - std::string destFileName = this->GetOption("CPACK_TOPLEVEL_DIRECTORY"); - destFileName += "/Resources/"; - destFileName += name + ext; + std::string destFileName = cmStrCat( +this->GetOption("CPACK_TOPLEVEL_DIRECTORY"), "/Resources/", name, ext ); cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Configure file: " @@ -245,9 +239,7 @@ bool cmCPackOSXX11Generator::CopyResourcePlistFile( const std::string& name, const std::string& dir, const char* outputFileName /* = 0 */, bool copyOnly /* = false */) { - std::string inFName = "Internal/CPack/CPack."; - inFName += name; - inFName += ".in"; + std::string inFName = cmStrCat("Internal/CPack/CPack.", name, ".in"); std::string inFileName = this->FindTemplate(inFName.c_str()); if (inFileName.empty()) { cmCPackLogger(cmCPackLog::LOG_ERROR, @@ -259,9 +251,7 @@ bool cmCPackOSXX11Generator::CopyResourcePlistFile( outputFileName = name.c_str(); } - std::string destFileName = dir; - destFileName += "/"; - destFileName += outputFileName; + std::string destFileName = cmStrCat(dir, '/', outputFileName); cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Configure file: " << inFileName << " to " << destFileName @@ -272,8 +262,8 @@ bool cmCPackOSXX11Generator::CopyResourcePlistFile( const char* cmCPackOSXX11Generator::GetPackagingInstallPrefix() { - this->InstallPrefix = "/"; - this->InstallPrefix += this->GetOption("CPACK_PACKAGE_FILE_NAME"); - this->InstallPrefix += ".app/Contents/Resources"; + this->InstallPrefix = + cmStrCat('/', this->GetOption("CPACK_PACKAGE_FILE_NAME"), + ".app/Contents/Resources"); return this->InstallPrefix.c_str(); } diff --git a/Source/CPack/cmCPackPKGGenerator.cxx b/Source/CPack/cmCPackPKGGenerator.cxx index d361921..3e1a51b 100644 --- a/Source/CPack/cmCPackPKGGenerator.cxx +++ b/Source/CPack/cmCPackPKGGenerator.cxx @@ -7,6 +7,7 @@ #include "cmCPackComponentGroup.h" #include "cmCPackGenerator.h" #include "cmCPackLog.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmXMLWriter.h" @@ -34,8 +35,8 @@ std::string cmCPackPKGGenerator::GetPackageName( const cmCPackComponent& component) { if (component.ArchiveFile.empty()) { - std::string packagesDir = this->GetOption("CPACK_TEMPORARY_DIRECTORY"); - packagesDir += ".dummy"; + std::string packagesDir = + cmStrCat(this->GetOption("CPACK_TEMPORARY_DIRECTORY"), ".dummy"); std::ostringstream out; out << cmSystemTools::GetFilenameWithoutLastExtension(packagesDir) << "-" << component.Name << ".pkg"; @@ -56,8 +57,8 @@ void cmCPackPKGGenerator::WriteDistributionFile(const char* metapackageFile) return; } - std::string distributionFile = metapackageFile; - distributionFile += "/Contents/distribution.dist"; + std::string distributionFile = + cmStrCat(metapackageFile, "/Contents/distribution.dist"); // Create the choice outline, which provides a tree-based view of // the components in their groups. @@ -144,12 +145,9 @@ void cmCPackPKGGenerator::CreateChoice(const cmCPackComponentGroup& group, void cmCPackPKGGenerator::CreateChoice(const cmCPackComponent& component, cmXMLWriter& xout) { - std::string packageId = "com."; - packageId += this->GetOption("CPACK_PACKAGE_VENDOR"); - packageId += '.'; - packageId += this->GetOption("CPACK_PACKAGE_NAME"); - packageId += '.'; - packageId += component.Name; + std::string packageId = + cmStrCat("com.", this->GetOption("CPACK_PACKAGE_VENDOR"), '.', + this->GetOption("CPACK_PACKAGE_NAME"), '.', component.Name); xout.StartElement("choice"); xout.Attribute("id", component.Name + "Choice"); @@ -192,14 +190,13 @@ void cmCPackPKGGenerator::CreateChoice(const cmCPackComponent& component, // Create a description of the package associated with this // component. - std::string relativePackageLocation = "Contents/Packages/"; - relativePackageLocation += this->GetPackageName(component); + std::string relativePackageLocation = + cmStrCat("Contents/Packages/", this->GetPackageName(component)); // Determine the installed size of the package. - std::string dirName = this->GetOption("CPACK_TEMPORARY_DIRECTORY"); - dirName += '/'; - dirName += component.Name; - dirName += this->GetOption("CPACK_PACKAGING_INSTALL_PREFIX"); + std::string dirName = + cmStrCat(this->GetOption("CPACK_TEMPORARY_DIRECTORY"), '/', component.Name, + this->GetOption("CPACK_PACKAGING_INSTALL_PREFIX")); unsigned long installedSize = component.GetInstalledSizeInKbytes(dirName); xout.StartElement("pkg-ref"); @@ -282,9 +279,7 @@ bool cmCPackPKGGenerator::CopyCreateResourceFile(const std::string& name, return false; } - std::string destFileName = dirName; - destFileName += '/'; - destFileName += name + ext; + std::string destFileName = cmStrCat(dirName, '/', name, ext); // Set this so that distribution.dist gets the right name (without // the path). @@ -305,9 +300,7 @@ bool cmCPackPKGGenerator::CopyResourcePlistFile(const std::string& name, outName = name.c_str(); } - std::string inFName = "Internal/CPack/CPack."; - inFName += name; - inFName += ".in"; + std::string inFName = cmStrCat("Internal/CPack/CPack.", name, ".in"); std::string inFileName = this->FindTemplate(inFName.c_str()); if (inFileName.empty()) { cmCPackLogger(cmCPackLog::LOG_ERROR, @@ -315,9 +308,8 @@ bool cmCPackPKGGenerator::CopyResourcePlistFile(const std::string& name, return false; } - std::string destFileName = this->GetOption("CPACK_TOPLEVEL_DIRECTORY"); - destFileName += "/"; - destFileName += outName; + std::string destFileName = + cmStrCat(this->GetOption("CPACK_TOPLEVEL_DIRECTORY"), '/', outName); cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Configure file: " << inFileName << " to " << destFileName @@ -330,9 +322,7 @@ int cmCPackPKGGenerator::CopyInstallScript(const std::string& resdir, const std::string& script, const std::string& name) { - std::string dst = resdir; - dst += "/"; - dst += name; + std::string dst = cmStrCat(resdir, '/', name); cmSystemTools::CopyFileAlways(script, dst); cmSystemTools::SetPermissions(dst.c_str(), 0777); cmCPackLogger(cmCPackLog::LOG_VERBOSE, diff --git a/Source/CPack/cmCPackPackageMakerGenerator.cxx b/Source/CPack/cmCPackPackageMakerGenerator.cxx index 3d93c48..5dc36ab 100644 --- a/Source/CPack/cmCPackPackageMakerGenerator.cxx +++ b/Source/CPack/cmCPackPackageMakerGenerator.cxx @@ -15,6 +15,7 @@ #include "cmCPackLog.h" #include "cmDuration.h" #include "cmGeneratedFileStream.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmXMLWriter.h" @@ -47,8 +48,8 @@ int cmCPackPackageMakerGenerator::PackageFiles() this->GetOption("CPACK_TEMPORARY_DIRECTORY"); if (this->Components.empty()) { packageDirFileName += ".pkg"; - resDir = this->GetOption("CPACK_TOPLEVEL_DIRECTORY"); - resDir += "/Resources"; + resDir = + cmStrCat(this->GetOption("CPACK_TOPLEVEL_DIRECTORY"), "/Resources"); } else { packageDirFileName += ".mpkg"; if (!cmsys::SystemTools::MakeDirectory(packageDirFileName.c_str())) { @@ -58,8 +59,7 @@ int cmCPackPackageMakerGenerator::PackageFiles() return 0; } - resDir = packageDirFileName; - resDir += "/Contents"; + resDir = cmStrCat(packageDirFileName, "/Contents"); if (!cmsys::SystemTools::MakeDirectory(resDir.c_str())) { cmCPackLogger(cmCPackLog::LOG_ERROR, "unable to create package subdirectory " << resDir @@ -155,8 +155,8 @@ int cmCPackPackageMakerGenerator::PackageFiles() if (!this->Components.empty()) { // Create the directory where component packages will be built. - std::string basePackageDir = packageDirFileName; - basePackageDir += "/Contents/Packages"; + std::string basePackageDir = + cmStrCat(packageDirFileName, "/Contents/Packages"); if (!cmsys::SystemTools::MakeDirectory(basePackageDir.c_str())) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem creating component packages directory: " @@ -172,8 +172,8 @@ int cmCPackPackageMakerGenerator::PackageFiles() if (userUploadDirectory && *userUploadDirectory) { uploadDirectory = userUploadDirectory; } else { - uploadDirectory = this->GetOption("CPACK_PACKAGE_DIRECTORY"); - uploadDirectory += "/CPackUploads"; + uploadDirectory = + cmStrCat(this->GetOption("CPACK_PACKAGE_DIRECTORY"), "/CPackUploads"); } // Create packages for each component @@ -232,9 +232,7 @@ int cmCPackPackageMakerGenerator::PackageFiles() packageFile += '/'; packageFile += GetPackageName(compIt->second); - std::string packageDir = toplevel; - packageDir += '/'; - packageDir += compIt->first; + std::string packageDir = cmStrCat(toplevel, '/', compIt->first); if (!this->GenerateComponentPackage( packageFile.c_str(), packageDir.c_str(), compIt->second)) { return 0; @@ -283,8 +281,8 @@ int cmCPackPackageMakerGenerator::PackageFiles() WriteDistributionFile(packageDirFileName.c_str()); } - std::string tmpFile = this->GetOption("CPACK_TOPLEVEL_DIRECTORY"); - tmpFile += "/hdiutilOutput.log"; + std::string tmpFile = cmStrCat(this->GetOption("CPACK_TOPLEVEL_DIRECTORY"), + "/hdiutilOutput.log"); std::ostringstream dmgCmd; dmgCmd << "\"" << this->GetOption("CPACK_INSTALLER_PROGRAM_DISK_IMAGE") << "\" create -ov -fs HFS+ -format UDZO -srcfolder \"" @@ -461,8 +459,8 @@ int cmCPackPackageMakerGenerator::InitializeInternal() bool cmCPackPackageMakerGenerator::RunPackageMaker(const char* command, const char* packageFile) { - std::string tmpFile = this->GetOption("CPACK_TOPLEVEL_DIRECTORY"); - tmpFile += "/PackageMakerOutput.log"; + std::string tmpFile = cmStrCat(this->GetOption("CPACK_TOPLEVEL_DIRECTORY"), + "/PackageMakerOutput.log"); cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Execute: " << command << std::endl); std::string output; @@ -517,8 +515,9 @@ bool cmCPackPackageMakerGenerator::GenerateComponentPackage( this->PackageMakerVersion < 3.0) { // Create Description.plist and Info.plist files for normal Mac OS // X packages, which work on Mac OS X 10.3 and newer. - std::string descriptionFile = this->GetOption("CPACK_TOPLEVEL_DIRECTORY"); - descriptionFile += '/' + component.Name + "-Description.plist"; + std::string descriptionFile = + cmStrCat(this->GetOption("CPACK_TOPLEVEL_DIRECTORY"), '/', + component.Name, "-Description.plist"); cmsys::ofstream out(descriptionFile.c_str()); cmXMLWriter xout(out); xout.StartDocument(); @@ -539,12 +538,10 @@ bool cmCPackPackageMakerGenerator::GenerateComponentPackage( out.close(); // Create the Info.plist file for this component - std::string moduleVersionSuffix = "."; - moduleVersionSuffix += component.Name; + std::string moduleVersionSuffix = cmStrCat('.', component.Name); this->SetOption("CPACK_MODULE_VERSION_SUFFIX", moduleVersionSuffix.c_str()); - std::string infoFileName = component.Name; - infoFileName += "-Info.plist"; + std::string infoFileName = cmStrCat(component.Name, "-Info.plist"); if (!this->CopyResourcePlistFile("Info.plist", infoFileName.c_str())) { return false; } @@ -561,12 +558,9 @@ bool cmCPackPackageMakerGenerator::GenerateComponentPackage( // like normal packages, and can be downloaded by the installer // on-the-fly in Mac OS X 10.5 or newer. Thus, we need to create // flat packages when the packages will be downloaded on the fly. - std::string pkgId = "com."; - pkgId += this->GetOption("CPACK_PACKAGE_VENDOR"); - pkgId += '.'; - pkgId += this->GetOption("CPACK_PACKAGE_NAME"); - pkgId += '.'; - pkgId += component.Name; + std::string pkgId = + cmStrCat("com.", this->GetOption("CPACK_PACKAGE_VENDOR"), '.', + this->GetOption("CPACK_PACKAGE_NAME"), '.', component.Name); pkgCmd << "\"" << this->GetOption("CPACK_INSTALLER_PROGRAM") << "\" --root \"" << packageDir << "\"" diff --git a/Source/CPack/cmCPackProductBuildGenerator.cxx b/Source/CPack/cmCPackProductBuildGenerator.cxx index 94b5b5f..800af28 100644 --- a/Source/CPack/cmCPackProductBuildGenerator.cxx +++ b/Source/CPack/cmCPackProductBuildGenerator.cxx @@ -10,6 +10,7 @@ #include "cmCPackLog.h" #include "cmDuration.h" #include "cmGeneratedFileStream.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" cmCPackProductBuildGenerator::cmCPackProductBuildGenerator() @@ -28,8 +29,8 @@ int cmCPackProductBuildGenerator::PackageFiles() this->GetOption("CPACK_TEMPORARY_DIRECTORY"); // Create the directory where component packages will be built. - std::string basePackageDir = packageDirFileName; - basePackageDir += "/Contents/Packages"; + std::string basePackageDir = + cmStrCat(packageDirFileName, "/Contents/Packages"); if (!cmsys::SystemTools::MakeDirectory(basePackageDir.c_str())) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem creating component packages directory: " @@ -41,9 +42,7 @@ int cmCPackProductBuildGenerator::PackageFiles() std::map<std::string, cmCPackComponent>::iterator compIt; for (compIt = this->Components.begin(); compIt != this->Components.end(); ++compIt) { - std::string packageDir = toplevel; - packageDir += '/'; - packageDir += compIt->first; + std::string packageDir = cmStrCat(toplevel, '/', compIt->first); if (!this->GenerateComponentPackage(basePackageDir, GetPackageName(compIt->second), packageDir, &compIt->second)) { @@ -138,8 +137,8 @@ int cmCPackProductBuildGenerator::InitializeInternal() bool cmCPackProductBuildGenerator::RunProductBuild(const std::string& command) { - std::string tmpFile = this->GetOption("CPACK_TOPLEVEL_DIRECTORY"); - tmpFile += "/ProductBuildOutput.log"; + std::string tmpFile = cmStrCat(this->GetOption("CPACK_TOPLEVEL_DIRECTORY"), + "/ProductBuildOutput.log"); cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Execute: " << command << std::endl); std::string output; @@ -166,9 +165,7 @@ bool cmCPackProductBuildGenerator::GenerateComponentPackage( const std::string& packageFileDir, const std::string& packageFileName, const std::string& packageDir, const cmCPackComponent* component) { - std::string packageFile = packageFileDir; - packageFile += '/'; - packageFile += packageFileName; + std::string packageFile = cmStrCat(packageFileDir, '/', packageFileName); cmCPackLogger(cmCPackLog::LOG_OUTPUT, "- Building component package: " << packageFile @@ -206,10 +203,8 @@ bool cmCPackProductBuildGenerator::GenerateComponentPackage( // The command that will be used to run ProductBuild std::ostringstream pkgCmd; - std::string pkgId = "com."; - pkgId += this->GetOption("CPACK_PACKAGE_VENDOR"); - pkgId += '.'; - pkgId += this->GetOption("CPACK_PACKAGE_NAME"); + std::string pkgId = cmStrCat("com.", this->GetOption("CPACK_PACKAGE_VENDOR"), + '.', this->GetOption("CPACK_PACKAGE_NAME")); if (component) { pkgId += '.'; pkgId += component->Name; diff --git a/Source/CPack/cmCPackRPMGenerator.cxx b/Source/CPack/cmCPackRPMGenerator.cxx index 33ab62b..0f621cc 100644 --- a/Source/CPack/cmCPackRPMGenerator.cxx +++ b/Source/CPack/cmCPackRPMGenerator.cxx @@ -12,6 +12,7 @@ #include "cmCPackComponentGroup.h" #include "cmCPackGenerator.h" #include "cmCPackLog.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" cmCPackRPMGenerator::cmCPackRPMGenerator() = default; @@ -21,7 +22,7 @@ cmCPackRPMGenerator::~cmCPackRPMGenerator() = default; int cmCPackRPMGenerator::InitializeInternal() { this->SetOptionIfNotSet("CPACK_PACKAGING_INSTALL_PREFIX", "/usr"); - if (cmSystemTools::IsOff(this->GetOption("CPACK_SET_DESTDIR"))) { + if (cmIsOff(this->GetOption("CPACK_SET_DESTDIR"))) { this->SetOption("CPACK_SET_DESTDIR", "I_ON"); } /* Replace space in CPACK_PACKAGE_NAME in order to avoid @@ -81,8 +82,7 @@ int cmCPackRPMGenerator::PackageOnePack(std::string const& initialToplevel, // Tell CPackRPM.cmake the name of the component NAME. this->SetOption("CPACK_RPM_PACKAGE_COMPONENT", packageName.c_str()); // Tell CPackRPM.cmake the path where the component is. - std::string component_path = "/"; - component_path += packageName; + std::string component_path = cmStrCat('/', packageName); this->SetOption("CPACK_RPM_PACKAGE_COMPONENT_PART_PATH", component_path.c_str()); if (!this->ReadListFile("Internal/CPack/CPackRPM.cmake")) { @@ -375,8 +375,7 @@ int cmCPackRPMGenerator::PackageComponentsAllInOne( if (!compInstDirName.empty()) { // Tell CPackRPM.cmake the path where the component is. - std::string component_path = "/"; - component_path += compInstDirName; + std::string component_path = cmStrCat('/', compInstDirName); this->SetOption("CPACK_RPM_PACKAGE_COMPONENT_PART_PATH", component_path.c_str()); } diff --git a/Source/CPack/cpack.cxx b/Source/CPack/cpack.cxx index 89c3b1c..a98fabc 100644 --- a/Source/CPack/cpack.cxx +++ b/Source/CPack/cpack.cxx @@ -1,20 +1,6 @@ /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://cmake.org/licensing for details. */ -#include "cmsys/CommandLineArguments.hxx" -#include "cmsys/Encoding.hxx" -#include <iostream> -#include <map> -#include <sstream> -#include <stddef.h> -#include <string> -#include <utility> -#include <vector> - -#if defined(_WIN32) && defined(CMAKE_BUILD_WITH_CMAKE) -# include "cmsys/ConsoleBuf.hxx" -#endif - #include "cmCPackGenerator.h" #include "cmCPackGeneratorFactory.h" #include "cmCPackLog.h" @@ -25,9 +11,25 @@ #include "cmMakefile.h" #include "cmState.h" #include "cmStateSnapshot.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmake.h" +#include "cmsys/CommandLineArguments.hxx" +#include "cmsys/Encoding.hxx" + +#if defined(_WIN32) && !defined(CMAKE_BOOTSTRAP) +# include "cmsys/ConsoleBuf.hxx" +#endif + +#include <iostream> +#include <map> +#include <sstream> +#include <stddef.h> +#include <string> +#include <utility> +#include <vector> + namespace { const char* cmDocumentationName[][2] = { { nullptr, " cpack - Packaging driver provided by CMake." }, @@ -100,7 +102,7 @@ void cpackProgressCallback(const std::string& message, float /*unused*/) int main(int argc, char const* const* argv) { cmSystemTools::EnsureStdPipes(); -#if defined(_WIN32) && defined(CMAKE_BUILD_WITH_CMAKE) +#if defined(_WIN32) && !defined(CMAKE_BOOTSTRAP) // Replace streambuf so we can output Unicode to console cmsys::ConsoleBuf::Manager consoleOut(std::cout); consoleOut.SetUTF8Pipes(); @@ -228,8 +230,8 @@ int main(int argc, char const* const* argv) bool cpackConfigFileSpecified = true; if (cpackConfigFile.empty()) { - cpackConfigFile = cmSystemTools::GetCurrentWorkingDirectory(); - cpackConfigFile += "/CPackConfig.cmake"; + cpackConfigFile = cmStrCat(cmSystemTools::GetCurrentWorkingDirectory(), + "/CPackConfig.cmake"); cpackConfigFileSpecified = false; } @@ -332,7 +334,7 @@ int main(int argc, char const* const* argv) "CPack generator not specified" << std::endl); } else { std::vector<std::string> generatorsVector; - cmSystemTools::ExpandListArgument(genList, generatorsVector); + cmExpandList(genList, generatorsVector); for (std::string const& gen : generatorsVector) { cmMakefile::ScopePushPop raii(&globalMF); cmMakefile* mf = &globalMF; diff --git a/Source/CTest/cmCTestBuildAndTestHandler.cxx b/Source/CTest/cmCTestBuildAndTestHandler.cxx index 3aea1f4..e7fb4c7 100644 --- a/Source/CTest/cmCTestBuildAndTestHandler.cxx +++ b/Source/CTest/cmCTestBuildAndTestHandler.cxx @@ -7,6 +7,7 @@ #include "cmGlobalGenerator.h" #include "cmMakefile.h" #include "cmState.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmWorkingDirectory.h" #include "cmake.h" @@ -289,9 +290,8 @@ int cmCTestBuildAndTestHandler::RunCMakeAndTest(std::string* outstring) std::vector<std::string> extraPaths; // if this->ExecutableDirectory is set try that as well if (!this->ExecutableDirectory.empty()) { - std::string tempPath = this->ExecutableDirectory; - tempPath += "/"; - tempPath += this->TestCommand; + std::string tempPath = + cmStrCat(this->ExecutableDirectory, '/', this->TestCommand); extraPaths.push_back(tempPath); } std::vector<std::string> failed; diff --git a/Source/CTest/cmCTestBuildCommand.cxx b/Source/CTest/cmCTestBuildCommand.cxx index e71eafe..6e76f08 100644 --- a/Source/CTest/cmCTestBuildCommand.cxx +++ b/Source/CTest/cmCTestBuildCommand.cxx @@ -7,6 +7,7 @@ #include "cmGlobalGenerator.h" #include "cmMakefile.h" #include "cmMessageType.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmake.h" @@ -90,9 +91,8 @@ cmCTestGenericHandler* cmCTestBuildCommand::InitializeHandler() this->Makefile->GetCMakeInstance()->CreateGlobalGenerator( cmakeGeneratorName); if (!this->GlobalGenerator) { - std::string e = "could not create generator named \""; - e += cmakeGeneratorName; - e += "\""; + std::string e = cmStrCat("could not create generator named \"", + cmakeGeneratorName, '"'); this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e); cmSystemTools::SetFatalErrorOccured(); return nullptr; diff --git a/Source/CTest/cmCTestBuildHandler.cxx b/Source/CTest/cmCTestBuildHandler.cxx index 407e9f8..8d1f76b 100644 --- a/Source/CTest/cmCTestBuildHandler.cxx +++ b/Source/CTest/cmCTestBuildHandler.cxx @@ -247,13 +247,11 @@ void cmCTestBuildHandler::PopulateCustomVectors(cmMakefile* mf) // Record the user-specified custom warning rules. if (const char* customWarningMatchers = mf->GetDefinition("CTEST_CUSTOM_WARNING_MATCH")) { - cmSystemTools::ExpandListArgument(customWarningMatchers, - this->ReallyCustomWarningMatches); + cmExpandList(customWarningMatchers, this->ReallyCustomWarningMatches); } if (const char* customWarningExceptions = mf->GetDefinition("CTEST_CUSTOM_WARNING_EXCEPTION")) { - cmSystemTools::ExpandListArgument(customWarningExceptions, - this->ReallyCustomWarningExceptions); + cmExpandList(customWarningExceptions, this->ReallyCustomWarningExceptions); } } @@ -328,7 +326,7 @@ int cmCTestBuildHandler::ProcessHandler() std::string const& useLaunchers = this->CTest->GetCTestConfiguration("UseLaunchers"); - this->UseCTestLaunch = cmSystemTools::IsOn(useLaunchers); + this->UseCTestLaunch = cmIsOn(useLaunchers); // Create a last build log cmGeneratedFileStream ofs; @@ -385,11 +383,8 @@ int cmCTestBuildHandler::ProcessHandler() if (this->CTest->GetCTestConfiguration("SourceDirectory").size() > 20) { std::string srcdir = this->CTest->GetCTestConfiguration("SourceDirectory") + "/"; - std::string srcdirrep; for (cc = srcdir.size() - 2; cc > 0; cc--) { if (srcdir[cc] == '/') { - srcdirrep = srcdir.substr(cc); - srcdirrep = "/..." + srcdirrep; srcdir = srcdir.substr(0, cc + 1); break; } @@ -399,11 +394,8 @@ int cmCTestBuildHandler::ProcessHandler() if (this->CTest->GetCTestConfiguration("BuildDirectory").size() > 20) { std::string bindir = this->CTest->GetCTestConfiguration("BuildDirectory") + "/"; - std::string bindirrep; for (cc = bindir.size() - 2; cc > 0; cc--) { if (bindir[cc] == '/') { - bindirrep = bindir.substr(cc); - bindirrep = "/..." + bindirrep; bindir = bindir.substr(0, cc + 1); break; } @@ -573,8 +565,7 @@ void cmCTestBuildHandler::GenerateXMLLogScraped(cmXMLWriter& xml) std::string srcdir = this->CTest->GetCTestConfiguration("SourceDirectory"); // make sure the source dir is in the correct case on windows // via a call to collapse full path. - srcdir = cmSystemTools::CollapseFullPath(srcdir); - srcdir += "/"; + srcdir = cmStrCat(cmSystemTools::CollapseFullPath(srcdir), '/'); for (it = ew.begin(); it != ew.end() && (numErrorsAllowed || numWarningsAllowed); it++) { cmCTestBuildErrorWarning* cm = &(*it); @@ -705,10 +696,8 @@ cmCTestBuildHandler::LaunchHelper::LaunchHelper(cmCTestBuildHandler* handler) } else { // Compute a directory in which to store launcher fragments. std::string& launchDir = this->Handler->CTestLaunchDir; - launchDir = this->CTest->GetBinaryDir(); - launchDir += "/Testing/"; - launchDir += tag; - launchDir += "/Build"; + launchDir = + cmStrCat(this->CTest->GetBinaryDir(), "/Testing/", tag, "/Build"); // Clean out any existing launcher fragments. cmSystemTools::RemoveADirectory(launchDir); @@ -717,8 +706,7 @@ cmCTestBuildHandler::LaunchHelper::LaunchHelper(cmCTestBuildHandler* handler) // Enable launcher fragments. cmSystemTools::MakeDirectory(launchDir); this->WriteLauncherConfig(); - std::string launchEnv = "CTEST_LAUNCH_LOGS="; - launchEnv += launchDir; + std::string launchEnv = cmStrCat("CTEST_LAUNCH_LOGS=", launchDir); cmSystemTools::PutEnv(launchEnv); } } @@ -744,8 +732,8 @@ void cmCTestBuildHandler::LaunchHelper::WriteLauncherConfig() this->Handler->ReallyCustomWarningExceptions); // Give some testing configuration information to the launcher. - std::string fname = this->Handler->CTestLaunchDir; - fname += "/CTestLaunchConfig.cmake"; + std::string fname = + cmStrCat(this->Handler->CTestLaunchDir, "/CTestLaunchConfig.cmake"); cmGeneratedFileStream fout(fname); std::string srcdir = this->CTest->GetCTestConfiguration("SourceDirectory"); fout << "set(CTEST_SOURCE_DIRECTORY \"" << srcdir << "\")\n"; @@ -757,10 +745,8 @@ void cmCTestBuildHandler::LaunchHelper::WriteScrapeMatchers( if (matchers.empty()) { return; } - std::string fname = this->Handler->CTestLaunchDir; - fname += "/Custom"; - fname += purpose; - fname += ".txt"; + std::string fname = + cmStrCat(this->Handler->CTestLaunchDir, "/Custom", purpose, ".txt"); cmGeneratedFileStream fout(fname); for (std::string const& m : matchers) { fout << m << "\n"; @@ -899,9 +885,8 @@ int cmCTestBuildHandler::RunMakeCommand(const std::string& command, // dashboard. cmCTestBuildErrorWarning errorwarning; errorwarning.LogLine = 1; - errorwarning.Text = - "*** WARNING non-zero return value in ctest from: "; - errorwarning.Text += argv[0]; + errorwarning.Text = cmStrCat( + "*** WARNING non-zero return value in ctest from: ", argv[0]); errorwarning.PreContext.clear(); errorwarning.PostContext.clear(); errorwarning.Error = false; @@ -923,8 +908,8 @@ int cmCTestBuildHandler::RunMakeCommand(const std::string& command, // If there was an error running command, report that on the dashboard. cmCTestBuildErrorWarning errorwarning; errorwarning.LogLine = 1; - errorwarning.Text = "*** ERROR executing: "; - errorwarning.Text += cmsysProcess_GetErrorString(cp); + errorwarning.Text = + cmStrCat("*** ERROR executing: ", cmsysProcess_GetErrorString(cp)); errorwarning.PreContext.clear(); errorwarning.PostContext.clear(); errorwarning.Error = true; diff --git a/Source/CTest/cmCTestCVS.cxx b/Source/CTest/cmCTestCVS.cxx index 9c03839..560c169 100644 --- a/Source/CTest/cmCTestCVS.cxx +++ b/Source/CTest/cmCTestCVS.cxx @@ -4,8 +4,10 @@ #include "cmCTest.h" #include "cmProcessTools.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmXMLWriter.h" +#include "cm_string_view.hxx" #include "cmsys/FStream.hxx" #include "cmsys/RegularExpression.hxx" @@ -204,8 +206,7 @@ std::string cmCTestCVS::ComputeBranchFlag(std::string const& dir) if (tagStream && cmSystemTools::GetLineFromStream(tagStream, tagLine) && tagLine.size() > 1 && tagLine[0] == 'T') { // Use the branch specified in the tag file. - std::string flag = "-r"; - flag += tagLine.substr(1); + std::string flag = cmStrCat("-r", cm::string_view(tagLine).substr(1)); return flag; } // Use the default branch. diff --git a/Source/CTest/cmCTestConfigureCommand.cxx b/Source/CTest/cmCTestConfigureCommand.cxx index 74a932a..320c184 100644 --- a/Source/CTest/cmCTestConfigureCommand.cxx +++ b/Source/CTest/cmCTestConfigureCommand.cxx @@ -6,6 +6,7 @@ #include "cmCTestConfigureHandler.h" #include "cmGlobalGenerator.h" #include "cmMakefile.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmake.h" @@ -25,7 +26,7 @@ cmCTestGenericHandler* cmCTestConfigureCommand::InitializeHandler() std::vector<std::string> options; if (this->Values[ctc_OPTIONS]) { - cmSystemTools::ExpandListArgument(this->Values[ctc_OPTIONS], options); + cmExpandList(this->Values[ctc_OPTIONS], options); } if (this->CTest->GetCTestConfiguration("BuildDirectory").empty()) { @@ -75,9 +76,8 @@ cmCTestGenericHandler* cmCTestConfigureCommand::InitializeHandler() delete gg; } - std::string cmakeConfigureCommand = "\""; - cmakeConfigureCommand += cmSystemTools::GetCMakeCommand(); - cmakeConfigureCommand += "\""; + std::string cmakeConfigureCommand = + cmStrCat('"', cmSystemTools::GetCMakeCommand(), '"'); for (std::string const& option : options) { cmakeConfigureCommand += " \""; diff --git a/Source/CTest/cmCTestCoverageHandler.cxx b/Source/CTest/cmCTestCoverageHandler.cxx index 54fe612..772fa47 100644 --- a/Source/CTest/cmCTestCoverageHandler.cxx +++ b/Source/CTest/cmCTestCoverageHandler.cxx @@ -130,10 +130,9 @@ void cmCTestCoverageHandler::Initialize() void cmCTestCoverageHandler::CleanCoverageLogFiles(std::ostream& log) { - std::string logGlob = this->CTest->GetCTestConfiguration("BuildDirectory"); - logGlob += "/Testing/"; - logGlob += this->CTest->GetCurrentTag(); - logGlob += "/CoverageLog*"; + std::string logGlob = + cmStrCat(this->CTest->GetCTestConfiguration("BuildDirectory"), "/Testing/", + this->CTest->GetCurrentTag(), "/CoverageLog*"); cmsys::Glob gl; gl.FindFiles(logGlob); std::vector<std::string> const& files = gl.GetFiles(); @@ -1456,8 +1455,7 @@ int cmCTestCoverageHandler::HandleLCovCoverage( std::vector<std::string> lcovFiles; dir = this->CTest->GetBinaryDir(); std::string daGlob; - daGlob = dir; - daGlob += "/*.LCOV"; + daGlob = cmStrCat(dir, "/*.LCOV"); cmCTestOptionalLog( this->CTest, HANDLER_VERBOSE_OUTPUT, " looking for LCOV files in: " << daGlob << std::endl, this->Quiet); @@ -1598,12 +1596,10 @@ void cmCTestCoverageHandler::FindGCovFiles(std::vector<std::string>& files) cmCTestOptionalLog( this->CTest, HANDLER_VERBOSE_OUTPUT, " globbing for coverage in: " << lm.first << std::endl, this->Quiet); - std::string daGlob = lm.first; - daGlob += "/*.da"; + std::string daGlob = cmStrCat(lm.first, "/*.da"); gl.FindFiles(daGlob); cmAppend(files, gl.GetFiles()); - daGlob = lm.first; - daGlob += "/*.gcda"; + daGlob = cmStrCat(lm.first, "/*.gcda"); gl.FindFiles(daGlob); cmAppend(files, gl.GetFiles()); } @@ -1632,8 +1628,7 @@ bool cmCTestCoverageHandler::FindLCovFiles(std::vector<std::string>& files) // DPI file should appear in build directory std::string daGlob; - daGlob = buildDir; - daGlob += "/*.dpi"; + daGlob = cmStrCat(buildDir, "/*.dpi"); cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, " looking for dpi files in: " << daGlob << std::endl, this->Quiet); @@ -1946,10 +1941,9 @@ int cmCTestCoverageHandler::RunBullseyeCommand( cmCTestRunProcess runCoverageSrc; runCoverageSrc.SetCommand(program.c_str()); runCoverageSrc.AddArgument(arg); - std::string stdoutFile = cont->BinaryDir + "/Testing/Temporary/"; - stdoutFile += this->GetCTestInstance()->GetCurrentTag(); - stdoutFile += "-"; - stdoutFile += cmd; + std::string stdoutFile = + cmStrCat(cont->BinaryDir, "/Testing/Temporary/", + this->GetCTestInstance()->GetCurrentTag(), '-', cmd); std::string stderrFile = stdoutFile; stdoutFile += ".stdout"; stderrFile += ".stderr"; @@ -2038,9 +2032,7 @@ int cmCTestCoverageHandler::RunBullseyeSourceSummary( coveredFileNames.insert(file); if (!cmSystemTools::FileIsFullPath(sourceFile)) { // file will be relative to the binary dir - file = cont->BinaryDir; - file += "/"; - file += sourceFile; + file = cmStrCat(cont->BinaryDir, '/', sourceFile); } file = cmSystemTools::CollapseFullPath(file); bool shouldIDoCoverage = @@ -2222,9 +2214,8 @@ int cmCTestCoverageHandler::GetLabelId(std::string const& label) void cmCTestCoverageHandler::LoadLabels() { - std::string fileList = this->CTest->GetBinaryDir(); - fileList += "/CMakeFiles"; - fileList += "/TargetDirectories.txt"; + std::string fileList = + cmStrCat(this->CTest->GetBinaryDir(), "/CMakeFiles/TargetDirectories.txt"); cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, " target directory list [" << fileList << "]\n", this->Quiet); @@ -2238,8 +2229,7 @@ void cmCTestCoverageHandler::LoadLabels() void cmCTestCoverageHandler::LoadLabels(const char* dir) { LabelSet& dirLabels = this->TargetDirs[dir]; - std::string fname = dir; - fname += "/Labels.txt"; + std::string fname = cmStrCat(dir, "/Labels.txt"); cmsys::ifstream fin(fname.c_str()); if (!fin) { return; diff --git a/Source/CTest/cmCTestCurl.cxx b/Source/CTest/cmCTestCurl.cxx index cc63e45..40f5918 100644 --- a/Source/CTest/cmCTestCurl.cxx +++ b/Source/CTest/cmCTestCurl.cxx @@ -5,6 +5,7 @@ #include "cmAlgorithms.h" #include "cmCTest.h" #include "cmCurl.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include <ostream> @@ -127,9 +128,7 @@ bool cmCTestCurl::UploadFile(std::string const& local_file, return false; } // set the url - std::string upload_url = url; - upload_url += "?"; - upload_url += fields; + std::string upload_url = cmStrCat(url, '?', fields); ::curl_easy_setopt(this->Curl, CURLOPT_URL, upload_url.c_str()); // now specify which file to upload ::curl_easy_setopt(this->Curl, CURLOPT_INFILE, ftpfile); diff --git a/Source/CTest/cmCTestGIT.cxx b/Source/CTest/cmCTestGIT.cxx index 093017c..c13cc80 100644 --- a/Source/CTest/cmCTestGIT.cxx +++ b/Source/CTest/cmCTestGIT.cxx @@ -111,8 +111,8 @@ std::string cmCTestGIT::FindGitDir() else if (git_dir[0] == '/') { // Cygwin Git reports a full path that Cygwin understands, but we // are a Windows application. Run "cygpath" to get Windows path. - std::string cygpath_exe = cmSystemTools::GetFilenamePath(git); - cygpath_exe += "/cygpath.exe"; + std::string cygpath_exe = + cmStrCat(cmSystemTools::GetFilenamePath(git), "/cygpath.exe"); if (cmSystemTools::FileExists(cygpath_exe)) { char const* cygpath[] = { cygpath_exe.c_str(), "-w", git_dir.c_str(), 0 }; @@ -212,7 +212,7 @@ bool cmCTestGIT::UpdateByFetchAndReset() bool cmCTestGIT::UpdateByCustom(std::string const& custom) { std::vector<std::string> git_custom_command; - cmSystemTools::ExpandListArgument(custom, git_custom_command, true); + cmExpandList(custom, git_custom_command, true); std::vector<char const*> git_custom; git_custom.reserve(git_custom_command.size() + 1); for (std::string const& i : git_custom_command) { @@ -270,7 +270,7 @@ bool cmCTestGIT::UpdateImpl() std::string init_submodules = this->CTest->GetCTestConfiguration("GITInitSubmodules"); - if (cmSystemTools::IsOn(init_submodules)) { + if (cmIsOn(init_submodules)) { char const* git_submodule_init[] = { git, "submodule", "init", nullptr }; ret = this->RunChild(git_submodule_init, &submodule_out, &submodule_err, top_dir.c_str()); diff --git a/Source/CTest/cmCTestLaunch.cxx b/Source/CTest/cmCTestLaunch.cxx index bbf490e..ac52581 100644 --- a/Source/CTest/cmCTestLaunch.cxx +++ b/Source/CTest/cmCTestLaunch.cxx @@ -176,14 +176,8 @@ void cmCTestLaunch::ComputeFileNames() this->LogHash = md5.FinalizeHex(); // We store stdout and stderr in temporary log files. - this->LogOut = this->LogDir; - this->LogOut += "launch-"; - this->LogOut += this->LogHash; - this->LogOut += "-out.txt"; - this->LogErr = this->LogDir; - this->LogErr += "launch-"; - this->LogErr += this->LogHash; - this->LogErr += "-err.txt"; + this->LogOut = cmStrCat(this->LogDir, "launch-", this->LogHash, "-out.txt"); + this->LogErr = cmStrCat(this->LogDir, "launch-", this->LogHash, "-err.txt"); } void cmCTestLaunch::RunChild() @@ -282,11 +276,8 @@ void cmCTestLaunch::LoadLabels() } // Labels are listed in per-target files. - std::string fname = this->OptionBuildDir; - fname += "/CMakeFiles"; - fname += "/"; - fname += this->OptionTargetName; - fname += ".dir/Labels.txt"; + std::string fname = cmStrCat(this->OptionBuildDir, "/CMakeFiles/", + this->OptionTargetName, ".dir/Labels.txt"); // We are interested in per-target labels for this source file. std::string source = this->OptionSource; @@ -340,10 +331,9 @@ bool cmCTestLaunch::IsError() const void cmCTestLaunch::WriteXML() { // Name the xml file. - std::string logXML = this->LogDir; - logXML += this->IsError() ? "error-" : "warning-"; - logXML += this->LogHash; - logXML += ".xml"; + std::string logXML = + cmStrCat(this->LogDir, this->IsError() ? "error-" : "warning-", + this->LogHash, ".xml"); // Use cmGeneratedFileStream to atomically create the report file. cmGeneratedFileStream fxml(logXML); @@ -494,9 +484,9 @@ void cmCTestLaunch::DumpFileToXML(cmXMLElement& e3, const char* tag, continue; } if (this->Match(line, this->RegexWarningSuppress)) { - line = "[CTest: warning suppressed] " + line; + line = cmStrCat("[CTest: warning suppressed] ", line); } else if (this->Match(line, this->RegexWarning)) { - line = "[CTest: warning matched] " + line; + line = cmStrCat("[CTest: warning matched] ", line); } e4.Content(sep); e4.Content(line); @@ -546,10 +536,7 @@ void cmCTestLaunch::LoadScrapeRules() void cmCTestLaunch::LoadScrapeRules( const char* purpose, std::vector<cmsys::RegularExpression>& regexps) { - std::string fname = this->LogDir; - fname += "Custom"; - fname += purpose; - fname += ".txt"; + std::string fname = cmStrCat(this->LogDir, "Custom", purpose, ".txt"); cmsys::ifstream fin(fname.c_str(), std::ios::in | std::ios::binary); std::string line; cmsys::RegularExpression rex; @@ -617,8 +604,7 @@ void cmCTestLaunch::LoadConfig() cm.GetCurrentSnapshot().SetDefaultDefinitions(); cmGlobalGenerator gg(&cm); cmMakefile mf(&gg, cm.GetCurrentSnapshot()); - std::string fname = this->LogDir; - fname += "CTestLaunchConfig.cmake"; + std::string fname = cmStrCat(this->LogDir, "CTestLaunchConfig.cmake"); if (cmSystemTools::FileExists(fname) && mf.ReadListFile(fname)) { this->SourceDir = mf.GetSafeDefinition("CTEST_SOURCE_DIRECTORY"); cmSystemTools::ConvertToUnixSlashes(this->SourceDir); diff --git a/Source/CTest/cmCTestMultiProcessHandler.cxx b/Source/CTest/cmCTestMultiProcessHandler.cxx index 42534f7..9925dc1 100644 --- a/Source/CTest/cmCTestMultiProcessHandler.cxx +++ b/Source/CTest/cmCTestMultiProcessHandler.cxx @@ -10,6 +10,7 @@ #include "cmDuration.h" #include "cmListFileCache.h" #include "cmRange.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmWorkingDirectory.h" @@ -110,8 +111,7 @@ void cmCTestMultiProcessHandler::SetTestLoad(unsigned long load) std::string fake_load_value; if (cmSystemTools::GetEnv("__CTEST_FAKE_LOAD_AVERAGE_FOR_TESTING", fake_load_value)) { - if (!cmSystemTools::StringToULong(fake_load_value.c_str(), - &this->FakeLoadForTesting)) { + if (!cmStrToULong(fake_load_value, &this->FakeLoadForTesting)) { cmSystemTools::Error("Failed to parse fake load value: " + fake_load_value); } @@ -173,8 +173,7 @@ bool cmCTestMultiProcessHandler::StartTestProcess(int test) // Find any failed dependencies for this test. We assume the more common // scenario has no failed tests, so make it the outer loop. for (std::string const& f : *this->Failed) { - if (this->Properties[test]->RequireSuccessDepends.find(f) != - this->Properties[test]->RequireSuccessDepends.end()) { + if (cmContains(this->Properties[test]->RequireSuccessDepends, f)) { testRun->AddFailedDependency(f); } } @@ -275,7 +274,7 @@ bool cmCTestMultiProcessHandler::StartTest(int test) { // Check for locked resources for (std::string const& i : this->Properties[test]->LockedResources) { - if (this->LockedResources.find(i) != this->LockedResources.end()) { + if (cmContains(this->LockedResources, i)) { return false; } } @@ -621,9 +620,7 @@ void cmCTestMultiProcessHandler::CreateParallelTestCostList() // In parallel test runs add previously failed tests to the front // of the cost list and queue other tests for further sorting for (auto const& t : this->Tests) { - if (std::find(this->LastTestsFailed.begin(), this->LastTestsFailed.end(), - this->Properties[t.first]->Name) != - this->LastTestsFailed.end()) { + if (cmContains(this->LastTestsFailed, this->Properties[t.first]->Name)) { // If the test failed last time, it should be run first. this->SortedTests.push_back(t.first); alreadySortedTests.insert(t.first); @@ -662,7 +659,7 @@ void cmCTestMultiProcessHandler::CreateParallelTestCostList() TestComparator(this)); for (auto const& j : sortedCopy) { - if (alreadySortedTests.find(j) == alreadySortedTests.end()) { + if (!cmContains(alreadySortedTests, j)) { this->SortedTests.push_back(j); alreadySortedTests.insert(j); } @@ -694,7 +691,7 @@ void cmCTestMultiProcessHandler::CreateSerialTestCostList() TestSet alreadySortedTests; for (int test : presortedList) { - if (alreadySortedTests.find(test) != alreadySortedTests.end()) { + if (cmContains(alreadySortedTests, test)) { continue; } @@ -702,8 +699,7 @@ void cmCTestMultiProcessHandler::CreateSerialTestCostList() GetAllTestDependencies(test, dependencies); for (int testDependency : dependencies) { - if (alreadySortedTests.find(testDependency) == - alreadySortedTests.end()) { + if (!cmContains(alreadySortedTests, testDependency)) { alreadySortedTests.insert(testDependency); this->SortedTests.push_back(testDependency); } @@ -862,8 +858,8 @@ static Json::Value DumpCTestProperties( DumpCTestProperty("PROCESSORS", testProperties.Processors)); } if (!testProperties.RequiredFiles.empty()) { - properties["REQUIRED_FILES"] = - DumpToJsonArray(testProperties.RequiredFiles); + properties.append(DumpCTestProperty( + "REQUIRED_FILES", DumpToJsonArray(testProperties.RequiredFiles))); } if (!testProperties.LockedResources.empty()) { properties.append(DumpCTestProperty( diff --git a/Source/CTest/cmCTestP4.cxx b/Source/CTest/cmCTestP4.cxx index 2eb8dba..80eb8d9 100644 --- a/Source/CTest/cmCTestP4.cxx +++ b/Source/CTest/cmCTestP4.cxx @@ -7,6 +7,7 @@ #include "cmCTestVC.h" #include "cmProcessTools.h" #include "cmRange.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmsys/RegularExpression.hxx" @@ -460,7 +461,7 @@ bool cmCTestP4::LoadModifications() bool cmCTestP4::UpdateCustom(const std::string& custom) { std::vector<std::string> p4_custom_command; - cmSystemTools::ExpandListArgument(custom, p4_custom_command, true); + cmExpandList(custom, p4_custom_command, true); std::vector<char const*> p4_custom; p4_custom.reserve(p4_custom_command.size() + 1); diff --git a/Source/CTest/cmCTestRunTest.cxx b/Source/CTest/cmCTestRunTest.cxx index 65cf646..89b585e 100644 --- a/Source/CTest/cmCTestRunTest.cxx +++ b/Source/CTest/cmCTestRunTest.cxx @@ -6,6 +6,7 @@ #include "cmCTestMemCheckHandler.h" #include "cmCTestMultiProcessHandler.h" #include "cmProcess.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmWorkingDirectory.h" @@ -86,16 +87,13 @@ bool cmCTestRunTest::EndTest(size_t completed, size_t total, bool started) for (auto& pass : this->TestProperties->RequiredRegularExpressions) { if (pass.first.find(this->ProcessOutput)) { found = true; - reason = "Required regular expression found."; - reason += " Regex=["; - reason += pass.second; - reason += "]"; + reason = cmStrCat("Required regular expression found. Regex=[", + pass.second, ']'); break; } } if (!found) { - reason = "Required regular expression not found."; - reason += " Regex=["; + reason = "Required regular expression not found. Regex=["; for (auto& pass : this->TestProperties->RequiredRegularExpressions) { reason += pass.second; reason += "\n"; @@ -108,10 +106,8 @@ bool cmCTestRunTest::EndTest(size_t completed, size_t total, bool started) this->FailedDependencies.empty()) { for (auto& fail : this->TestProperties->ErrorRegularExpressions) { if (fail.first.find(this->ProcessOutput)) { - reason = "Error regular expression found in output."; - reason += " Regex=["; - reason += fail.second; - reason += "]"; + reason = cmStrCat("Error regular expression found in output. Regex=[", + fail.second, ']'); forceFail = true; break; } @@ -121,10 +117,8 @@ bool cmCTestRunTest::EndTest(size_t completed, size_t total, bool started) this->FailedDependencies.empty()) { for (auto& skip : this->TestProperties->SkipRegularExpressions) { if (skip.first.find(this->ProcessOutput)) { - reason = "Skip regular expression found in output."; - reason += " Regex=["; - reason += skip.second; - reason += "]"; + reason = cmStrCat("Skip regular expression found in output. Regex=[", + skip.second, ']'); forceSkip = true; break; } @@ -504,12 +498,11 @@ bool cmCTestRunTest::StartTest(size_t completed, size_t total) this->TestProcess = cm::make_unique<cmProcess>(*this); std::string msg; if (this->CTest->GetConfigType().empty()) { - msg = "Test not available without configuration."; - msg += " (Missing \"-C <config>\"?)"; + msg = "Test not available without configuration. (Missing \"-C " + "<config>\"?)"; } else { - msg = "Test not available in configuration \""; - msg += this->CTest->GetConfigType(); - msg += "\"."; + msg = cmStrCat("Test not available in configuration \"", + this->CTest->GetConfigType(), "\"."); } *this->TestHandler->LogFile << msg << std::endl; cmCTestLog(this->CTest, ERROR_MESSAGE, msg << std::endl); @@ -689,7 +682,7 @@ bool cmCTestRunTest::ForkProcess(cmDuration testTimeOut, bool explicitTimeout, this->TestProcess->SetTimeout(timeout); -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP cmSystemTools::SaveRestoreEnvironment sre; #endif diff --git a/Source/CTest/cmCTestSVN.cxx b/Source/CTest/cmCTestSVN.cxx index c834686..dc1472b 100644 --- a/Source/CTest/cmCTestSVN.cxx +++ b/Source/CTest/cmCTestSVN.cxx @@ -6,6 +6,7 @@ #include "cmCTest.h" #include "cmCTestVC.h" #include "cmProcessTools.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmXMLParser.h" #include "cmXMLWriter.h" @@ -143,9 +144,8 @@ bool cmCTestSVN::NoteNewRevision() // the repository root. if (!svninfo.Root.empty() && cmCTestSVNPathStarts(svninfo.URL, svninfo.Root)) { - svninfo.Base = - cmCTest::DecodeURL(svninfo.URL.substr(svninfo.Root.size())); - svninfo.Base += "/"; + svninfo.Base = cmStrCat( + cmCTest::DecodeURL(svninfo.URL.substr(svninfo.Root.size())), '/'); } this->Log << "Repository '" << svninfo.LocalPath << "' Base = " << svninfo.Base << "\n"; diff --git a/Source/CTest/cmCTestScriptHandler.cxx b/Source/CTest/cmCTestScriptHandler.cxx index 7a5b8d1..52d4596 100644 --- a/Source/CTest/cmCTestScriptHandler.cxx +++ b/Source/CTest/cmCTestScriptHandler.cxx @@ -24,13 +24,13 @@ #include "cmCTestUploadCommand.h" #include "cmCommand.h" #include "cmDuration.h" -#include "cmFunctionBlocker.h" #include "cmGeneratedFileStream.h" #include "cmGlobalGenerator.h" #include "cmMakefile.h" #include "cmState.h" #include "cmStateDirectory.h" #include "cmStateSnapshot.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmake.h" @@ -49,32 +49,8 @@ # include <unistd.h> #endif -class cmExecutionStatus; -struct cmListFileFunction; - #define CTEST_INITIAL_CMAKE_OUTPUT_FILE_NAME "CTestInitialCMakeOutput.log" -// used to keep elapsed time up to date -class cmCTestScriptFunctionBlocker : public cmFunctionBlocker -{ -public: - bool IsFunctionBlocked(const cmListFileFunction& lff, cmMakefile& mf, - cmExecutionStatus& /*status*/) override; - // virtual bool ShouldRemove(const cmListFileFunction& lff, cmMakefile &mf); - // virtual void ScopeEnded(cmMakefile &mf); - - cmCTestScriptHandler* CTestScriptHandler; -}; - -// simply update the time and don't block anything -bool cmCTestScriptFunctionBlocker::IsFunctionBlocked( - const cmListFileFunction& /*lff*/, cmMakefile& /*mf*/, - cmExecutionStatus& /*status*/) -{ - this->CTestScriptHandler->UpdateElapsedTime(); - return false; -} - cmCTestScriptHandler::cmCTestScriptHandler() { this->Backup = false; @@ -373,12 +349,8 @@ int cmCTestScriptHandler::ReadInScript(const std::string& total_script_arg) this->Makefile->AddDefinition("CMAKE_LEGACY_CYGWIN_WIN32", "0"); #endif - // always add a function blocker to update the elapsed time - { - auto fb = cm::make_unique<cmCTestScriptFunctionBlocker>(); - fb->CTestScriptHandler = this; - this->Makefile->AddFunctionBlocker(std::move(fb)); - } + // set a callback function to update the elapsed time + this->Makefile->OnExecuteCommand([this] { this->UpdateElapsedTime(); }); /* Execute CTestScriptMode.cmake, which loads CMakeDetermineSystem and CMakeSystemSpecificInformation, so @@ -479,12 +451,13 @@ int cmCTestScriptHandler::ExtractVariables() // make sure the required info is here if (this->SourceDir.empty() || this->BinaryDir.empty() || this->CTestCmd.empty()) { - std::string msg = "CTEST_SOURCE_DIRECTORY = "; - msg += (!this->SourceDir.empty()) ? this->SourceDir.c_str() : "(Null)"; - msg += "\nCTEST_BINARY_DIRECTORY = "; - msg += (!this->BinaryDir.empty()) ? this->BinaryDir.c_str() : "(Null)"; - msg += "\nCTEST_COMMAND = "; - msg += (!this->CTestCmd.empty()) ? this->CTestCmd.c_str() : "(Null)"; + std::string msg = + cmStrCat("CTEST_SOURCE_DIRECTORY = ", + (!this->SourceDir.empty()) ? this->SourceDir.c_str() : "(Null)", + "\nCTEST_BINARY_DIRECTORY = ", + (!this->BinaryDir.empty()) ? this->BinaryDir.c_str() : "(Null)", + "\nCTEST_COMMAND = ", + (!this->CTestCmd.empty()) ? this->CTestCmd.c_str() : "(Null)"); cmSystemTools::Error( "Some required settings in the configuration file were missing:\n" + msg); @@ -523,7 +496,7 @@ void cmCTestScriptHandler::SleepInSeconds(unsigned int secondsToWait) int cmCTestScriptHandler::RunConfigurationScript( const std::string& total_script_arg, bool pscope) { -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP cmSystemTools::SaveRestoreEnvironment sre; #endif @@ -572,7 +545,7 @@ int cmCTestScriptHandler::RunCurrentScript() // set any environment variables if (!this->CTestEnv.empty()) { std::vector<std::string> envArgs; - cmSystemTools::ExpandListArgument(this->CTestEnv, envArgs); + cmExpandList(this->CTestEnv, envArgs); cmSystemTools::AppendEnv(envArgs); } @@ -638,10 +611,8 @@ int cmCTestScriptHandler::BackupDirectories() int retVal; // compute the backup names - this->BackupSourceDir = this->SourceDir; - this->BackupSourceDir += "_CMakeBackup"; - this->BackupBinaryDir = this->BinaryDir; - this->BackupBinaryDir += "_CMakeBackup"; + this->BackupSourceDir = cmStrCat(this->SourceDir, "_CMakeBackup"); + this->BackupBinaryDir = cmStrCat(this->BinaryDir, "_CMakeBackup"); // backup the binary and src directories if requested if (this->Backup) { @@ -679,11 +650,9 @@ int cmCTestScriptHandler::PerformExtraUpdates() command = this->UpdateCmd; for (std::string const& eu : this->ExtraUpdates) { std::vector<std::string> cvsArgs; - cmSystemTools::ExpandListArgument(eu, cvsArgs); + cmExpandList(eu, cvsArgs); if (cvsArgs.size() == 2) { - std::string fullCommand = command; - fullCommand += " update "; - fullCommand += cvsArgs[1]; + std::string fullCommand = cmStrCat(command, " update ", cvsArgs[1]); output.clear(); retVal = 0; cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, @@ -692,8 +661,8 @@ int cmCTestScriptHandler::PerformExtraUpdates() fullCommand, &output, &output, &retVal, cvsArgs[0].c_str(), this->HandlerVerbose, cmDuration::zero() /*this->TimeOut*/); if (!res || retVal != 0) { - cmSystemTools::Error("Unable to perform extra updates:\n" + eu + - "\nWith output:\n" + output); + cmSystemTools::Error(cmStrCat("Unable to perform extra updates:\n", eu, + "\nWith output:\n", output)); return 0; } } @@ -784,9 +753,7 @@ int cmCTestScriptHandler::RunConfigurationDashboard() int cmakeFailed = 0; std::string cmakeFailedOuput; if (!this->CMakeCmd.empty()) { - command = this->CMakeCmd; - command += " \""; - command += this->SourceDir; + command = cmStrCat(this->CMakeCmd, " \"", this->SourceDir); output.clear(); command += "\""; retVal = 0; @@ -823,7 +790,7 @@ int cmCTestScriptHandler::RunConfigurationDashboard() // run ctest, it may be more than one command in here std::vector<std::string> ctestCommands; - cmSystemTools::ExpandListArgument(this->CTestCmd, ctestCommands); + cmExpandList(this->CTestCmd, ctestCommands); // for each variable/argument do a putenv for (std::string const& ctestCommand : ctestCommands) { command = ctestCommand; @@ -867,8 +834,7 @@ int cmCTestScriptHandler::RunConfigurationDashboard() bool cmCTestScriptHandler::WriteInitialCache(const char* directory, const char* text) { - std::string cacheFile = directory; - cacheFile += "/CMakeCache.txt"; + std::string cacheFile = cmStrCat(directory, "/CMakeCache.txt"); cmGeneratedFileStream fout(cacheFile); if (!fout) { return false; @@ -933,8 +899,7 @@ bool cmCTestScriptHandler::EmptyBinaryDirectory(const char* sname) } // try to avoid deleting directories that we shouldn't - std::string check = sname; - check += "/CMakeCache.txt"; + std::string check = cmStrCat(sname, "/CMakeCache.txt"); if (!cmSystemTools::FileExists(check)) { return false; @@ -963,7 +928,7 @@ bool cmCTestScriptHandler::TryToRemoveBinaryDirectoryOnce( continue; } - std::string fullPath = directoryPath + std::string("/") + path; + std::string fullPath = cmStrCat(directoryPath, "/", path); bool isDirectory = cmSystemTools::FileIsDirectory(fullPath) && !cmSystemTools::FileIsSymlink(fullPath); diff --git a/Source/CTest/cmCTestSubmitCommand.cxx b/Source/CTest/cmCTestSubmitCommand.cxx index 58c0a1b..ec1e9bb 100644 --- a/Source/CTest/cmCTestSubmitCommand.cxx +++ b/Source/CTest/cmCTestSubmitCommand.cxx @@ -7,6 +7,7 @@ #include "cmCommand.h" #include "cmMakefile.h" #include "cmMessageType.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include <sstream> @@ -68,7 +69,7 @@ cmCTestGenericHandler* cmCTestSubmitCommand::InitializeHandler() this->Makefile->GetDefinition("CTEST_NOTES_FILES"); if (notesFilesVariable) { std::vector<std::string> notesFiles; - cmSystemTools::ExpandListArgument(notesFilesVariable, notesFiles); + cmExpandList(notesFilesVariable, notesFiles); this->CTest->GenerateNotesFile(notesFiles); } @@ -76,7 +77,7 @@ cmCTestGenericHandler* cmCTestSubmitCommand::InitializeHandler() this->Makefile->GetDefinition("CTEST_EXTRA_SUBMIT_FILES"); if (extraFilesVariable) { std::vector<std::string> extraFiles; - cmSystemTools::ExpandListArgument(extraFilesVariable, extraFiles); + cmExpandList(extraFilesVariable, extraFiles); if (!this->CTest->SubmitExtraFiles(extraFiles)) { this->SetError("problem submitting extra files."); return nullptr; diff --git a/Source/CTest/cmCTestSubmitHandler.cxx b/Source/CTest/cmCTestSubmitHandler.cxx index 2c6ff83..a30999b 100644 --- a/Source/CTest/cmCTestSubmitHandler.cxx +++ b/Source/CTest/cmCTestSubmitHandler.cxx @@ -156,7 +156,7 @@ bool cmCTestSubmitHandler::SubmitUsingHTTP( ::curl_global_init(CURL_GLOBAL_ALL); std::string curlopt(this->CTest->GetCTestConfiguration("CurlOptions")); std::vector<std::string> args; - cmSystemTools::ExpandListArgument(curlopt, args); + cmExpandList(curlopt, args); bool verifyPeerOff = false; bool verifyHostOff = false; for (std::string const& arg : args) { @@ -225,7 +225,7 @@ bool cmCTestSubmitHandler::SubmitUsingHTTP( std::string local_file = file; bool initialize_cdash_buildid = false; if (!cmSystemTools::FileExists(local_file)) { - local_file = localprefix + "/" + file; + local_file = cmStrCat(localprefix, "/", file); // If this file exists within the local Testing directory we assume // that it will be associated with the current build in CDash. initialize_cdash_buildid = true; @@ -237,9 +237,9 @@ bool cmCTestSubmitHandler::SubmitUsingHTTP( << remote_file << std::endl; std::string ofile = cmSystemTools::EncodeURL(remote_file); - std::string upload_as = url + - ((url.find('?') == std::string::npos) ? '?' : '&') + - "FileName=" + ofile; + std::string upload_as = + cmStrCat(url, ((url.find('?') == std::string::npos) ? '?' : '&'), + "FileName=", ofile); if (initialize_cdash_buildid) { // Provide extra arguments to CDash so that it can initialize and @@ -280,7 +280,7 @@ bool cmCTestSubmitHandler::SubmitUsingHTTP( upload_as += "&MD5="; - if (cmSystemTools::IsOn(this->GetOption("InternalTest"))) { + if (cmIsOn(this->GetOption("InternalTest"))) { upload_as += "bad_md5sum"; } else { upload_as += @@ -500,7 +500,7 @@ int cmCTestSubmitHandler::HandleCDashUploadFile(std::string const& file, curl.SetQuiet(this->Quiet); std::string curlopt(this->CTest->GetCTestConfiguration("CurlOptions")); std::vector<std::string> args; - cmSystemTools::ExpandListArgument(curlopt, args); + cmExpandList(curlopt, args); curl.SetCurlOptions(args); curl.SetTimeOutSeconds(SUBMIT_TIMEOUT_IN_SECONDS_DEFAULT); curl.SetHttpHeaders(this->HttpHeaders); @@ -517,7 +517,7 @@ int cmCTestSubmitHandler::HandleCDashUploadFile(std::string const& file, "Only http and https are supported for CDASH_UPLOAD\n"); return -1; } - bool internalTest = cmSystemTools::IsOn(this->GetOption("InternalTest")); + bool internalTest = cmIsOn(this->GetOption("InternalTest")); // Get RETRY_COUNT and RETRY_DELAY values if they were set. std::string retryDelayString = this->GetOption("RetryDelay") == nullptr @@ -529,8 +529,7 @@ int cmCTestSubmitHandler::HandleCDashUploadFile(std::string const& file, auto retryDelay = std::chrono::seconds(0); if (!retryDelayString.empty()) { unsigned long retryDelayValue = 0; - if (!cmSystemTools::StringToULong(retryDelayString.c_str(), - &retryDelayValue)) { + if (!cmStrToULong(retryDelayString, &retryDelayValue)) { cmCTestLog(this->CTest, WARNING, "Invalid value for 'RETRY_DELAY' : " << retryDelayString << std::endl); @@ -540,7 +539,7 @@ int cmCTestSubmitHandler::HandleCDashUploadFile(std::string const& file, } unsigned long retryCount = 0; if (!retryCountString.empty()) { - if (!cmSystemTools::StringToULong(retryCountString.c_str(), &retryCount)) { + if (!cmStrToULong(retryCountString, &retryCount)) { cmCTestLog(this->CTest, WARNING, "Invalid value for 'RETRY_DELAY' : " << retryCountString << std::endl); diff --git a/Source/CTest/cmCTestTestCommand.cxx b/Source/CTest/cmCTestTestCommand.cxx index cfd5e3d..24de5b4 100644 --- a/Source/CTest/cmCTestTestCommand.cxx +++ b/Source/CTest/cmCTestTestCommand.cxx @@ -7,7 +7,7 @@ #include "cmCTestTestHandler.h" #include "cmDuration.h" #include "cmMakefile.h" -#include "cmSystemTools.h" +#include "cmStringAlgorithms.h" #include <chrono> #include <sstream> @@ -110,15 +110,14 @@ cmCTestGenericHandler* cmCTestTestCommand::InitializeHandler() unsigned long testLoad; const char* ctestTestLoad = this->Makefile->GetDefinition("CTEST_TEST_LOAD"); if (this->Values[ctt_TEST_LOAD] && *this->Values[ctt_TEST_LOAD]) { - if (!cmSystemTools::StringToULong(this->Values[ctt_TEST_LOAD], - &testLoad)) { + if (!cmStrToULong(this->Values[ctt_TEST_LOAD], &testLoad)) { testLoad = 0; cmCTestLog(this->CTest, WARNING, "Invalid value for 'TEST_LOAD' : " << this->Values[ctt_TEST_LOAD] << std::endl); } } else if (ctestTestLoad && *ctestTestLoad) { - if (!cmSystemTools::StringToULong(ctestTestLoad, &testLoad)) { + if (!cmStrToULong(ctestTestLoad, &testLoad)) { testLoad = 0; cmCTestLog(this->CTest, WARNING, "Invalid value for 'CTEST_TEST_LOAD' : " << ctestTestLoad diff --git a/Source/CTest/cmCTestTestHandler.cxx b/Source/CTest/cmCTestTestHandler.cxx index 67c24ca..4cb19f8 100644 --- a/Source/CTest/cmCTestTestHandler.cxx +++ b/Source/CTest/cmCTestTestHandler.cxx @@ -20,6 +20,7 @@ #include "cm_memory.hxx" +#include "cmAlgorithms.h" #include "cmCTest.h" #include "cmCTestMultiProcessHandler.h" #include "cmCommand.h" @@ -76,9 +77,7 @@ bool cmCTestSubdirCommand::InitialPass(std::vector<std::string> const& args, if (cmSystemTools::FileIsFullPath(arg)) { fname = arg; } else { - fname = cwd; - fname += "/"; - fname += arg; + fname = cmStrCat(cwd, '/', arg); } if (!cmSystemTools::FileIsDirectory(fname)) { @@ -109,8 +108,7 @@ bool cmCTestSubdirCommand::InitialPass(std::vector<std::string> const& args, readit = this->Makefile->ReadDependentFile(fname); } if (!readit) { - std::string m = "Could not find include file: "; - m += fname; + std::string m = cmStrCat("Could not find include file: ", fname); this->SetError(m); return false; } @@ -149,9 +147,8 @@ bool cmCTestAddSubdirectoryCommand::InitialPass( return false; } - std::string fname = cmSystemTools::GetCurrentWorkingDirectory(); - fname += "/"; - fname += args[0]; + std::string fname = + cmStrCat(cmSystemTools::GetCurrentWorkingDirectory(), '/', args[0]); if (!cmSystemTools::FileExists(fname)) { // No subdirectory? So what... @@ -175,8 +172,7 @@ bool cmCTestAddSubdirectoryCommand::InitialPass( readit = this->Makefile->ReadDependentFile(fname); } if (!readit) { - std::string m = "Could not find include file: "; - m += fname; + std::string m = cmStrCat("Could not find include file: ", fname); this->SetError(m); return false; } @@ -512,8 +508,8 @@ bool cmCTestTestHandler::ProcessOptions() { // Update internal data structure from generic one this->SetTestsToRunInformation(this->GetOption("TestsToRunInformation")); - this->SetUseUnion(cmSystemTools::IsOn(this->GetOption("UseUnion"))); - if (cmSystemTools::IsOn(this->GetOption("ScheduleRandom"))) { + this->SetUseUnion(cmIsOn(this->GetOption("UseUnion"))); + if (cmIsOn(this->GetOption("ScheduleRandom"))) { this->CTest->SetScheduleType("Random"); } if (this->GetOption("ParallelLevel")) { @@ -553,7 +549,7 @@ bool cmCTestTestHandler::ProcessOptions() if (val) { this->ExcludeFixtureCleanupRegExp = val; } - this->SetRerunFailed(cmSystemTools::IsOn(this->GetOption("RerunFailed"))); + this->SetRerunFailed(cmIsOn(this->GetOption("RerunFailed"))); return true; } @@ -715,7 +711,7 @@ void cmCTestTestHandler::PrintLabelOrSubprojectSummary(bool doSubProject) cmCTestTestProperties& p = *result.Properties; for (std::string const& l : p.Labels) { // only use labels found in labels - if (labels.find(l) != labels.end()) { + if (cmContains(labels, l)) { labelTimes[l] += result.ExecutionTime.count() * result.Properties->Processors; ++labelCounts[l]; @@ -857,17 +853,14 @@ void cmCTestTestHandler::ComputeTestList() if (this->UseUnion) { // if it is not in the list and not in the regexp then skip - if ((!this->TestsToRun.empty() && - std::find(this->TestsToRun.begin(), this->TestsToRun.end(), cnt) == - this->TestsToRun.end()) && + if ((!this->TestsToRun.empty() && !cmContains(this->TestsToRun, cnt)) && !tp.IsInBasedOnREOptions) { continue; } } else { // is this test in the list of tests to run? If not then skip it if ((!this->TestsToRun.empty() && - std::find(this->TestsToRun.begin(), this->TestsToRun.end(), - inREcnt) == this->TestsToRun.end()) || + !cmContains(this->TestsToRun, inREcnt)) || !tp.IsInBasedOnREOptions) { continue; } @@ -896,9 +889,7 @@ void cmCTestTestHandler::ComputeTestListForRerunFailed() cnt++; // if this test is not in our list of tests to run, then skip it. - if ((!this->TestsToRun.empty() && - std::find(this->TestsToRun.begin(), this->TestsToRun.end(), cnt) == - this->TestsToRun.end())) { + if ((!this->TestsToRun.empty() && !cmContains(TestsToRun, cnt))) { continue; } @@ -1019,8 +1010,7 @@ void cmCTestTestHandler::UpdateForFixtures(ListOfTests& tests) const sIt != setupRange.second; ++sIt) { const std::string& setupTestName = sIt->second->Name; tests[i].RequireSuccessDepends.insert(setupTestName); - if (std::find(tests[i].Depends.begin(), tests[i].Depends.end(), - setupTestName) == tests[i].Depends.end()) { + if (!cmContains(tests[i].Depends, setupTestName)) { tests[i].Depends.push_back(setupTestName); } } @@ -1127,8 +1117,7 @@ void cmCTestTestHandler::UpdateForFixtures(ListOfTests& tests) const const std::vector<size_t>& indices = cIt->second; for (size_t index : indices) { const std::string& reqTestName = tests[index].Name; - if (std::find(p.Depends.begin(), p.Depends.end(), reqTestName) == - p.Depends.end()) { + if (!cmContains(p.Depends, reqTestName)) { p.Depends.push_back(reqTestName); } } @@ -1141,8 +1130,7 @@ void cmCTestTestHandler::UpdateForFixtures(ListOfTests& tests) const const std::vector<size_t>& indices = cIt->second; for (size_t index : indices) { const std::string& setupTestName = tests[index].Name; - if (std::find(p.Depends.begin(), p.Depends.end(), setupTestName) == - p.Depends.end()) { + if (!cmContains(p.Depends, setupTestName)) { p.Depends.push_back(setupTestName); } } @@ -1559,50 +1547,32 @@ void cmCTestTestHandler::AddConfigurations( attemptedConfigs.emplace_back(); if (!ctest->GetConfigType().empty()) { - tempPath = filepath; - tempPath += ctest->GetConfigType(); - tempPath += "/"; - tempPath += filename; + tempPath = cmStrCat(filepath, ctest->GetConfigType(), '/', filename); attempted.push_back(tempPath); attemptedConfigs.push_back(ctest->GetConfigType()); // If the file is an OSX bundle then the configtype // will be at the start of the path - tempPath = ctest->GetConfigType(); - tempPath += "/"; - tempPath += filepath; - tempPath += filename; + tempPath = cmStrCat(ctest->GetConfigType(), '/', filepath, filename); attempted.push_back(tempPath); attemptedConfigs.push_back(ctest->GetConfigType()); } else { // no config specified - try some options... - tempPath = filepath; - tempPath += "Release/"; - tempPath += filename; + tempPath = cmStrCat(filepath, "Release/", filename); attempted.push_back(tempPath); attemptedConfigs.emplace_back("Release"); - tempPath = filepath; - tempPath += "Debug/"; - tempPath += filename; + tempPath = cmStrCat(filepath, "Debug/", filename); attempted.push_back(tempPath); attemptedConfigs.emplace_back("Debug"); - tempPath = filepath; - tempPath += "MinSizeRel/"; - tempPath += filename; + tempPath = cmStrCat(filepath, "MinSizeRel/", filename); attempted.push_back(tempPath); attemptedConfigs.emplace_back("MinSizeRel"); - tempPath = filepath; - tempPath += "RelWithDebInfo/"; - tempPath += filename; + tempPath = cmStrCat(filepath, "RelWithDebInfo/", filename); attempted.push_back(tempPath); attemptedConfigs.emplace_back("RelWithDebInfo"); - tempPath = filepath; - tempPath += "Deployment/"; - tempPath += filename; + tempPath = cmStrCat(filepath, "Deployment/", filename); attempted.push_back(tempPath); attemptedConfigs.emplace_back("Deployment"); - tempPath = filepath; - tempPath += "Development/"; - tempPath += filename; + tempPath = cmStrCat(filepath, "Development/", filename); attempted.push_back(tempPath); attemptedConfigs.emplace_back("Deployment"); } @@ -1656,8 +1626,8 @@ std::string cmCTestTestHandler::FindExecutable( // then try with the exe extension else { failed.push_back(attempted[ai]); - tempPath = attempted[ai]; - tempPath += cmSystemTools::GetExecutableExtension(); + tempPath = + cmStrCat(attempted[ai], cmSystemTools::GetExecutableExtension()); if (cmSystemTools::FileExists(tempPath) && !cmSystemTools::FileIsDirectory(tempPath)) { fullPath = cmSystemTools::CollapseFullPath(tempPath); @@ -2180,7 +2150,7 @@ bool cmCTestTestHandler::SetTestsProperties( if (key == "_BACKTRACE_TRIPLES") { std::vector<std::string> triples; // allow empty args in the triples - cmSystemTools::ExpandListArgument(val, triples, true); + cmExpandList(val, triples, true); // Ensure we have complete triples otherwise the data is corrupt. if (triples.size() % 3 == 0) { @@ -2193,8 +2163,7 @@ bool cmCTestTestHandler::SetTestsProperties( cmListFileContext fc; fc.FilePath = triples[i - 3]; long line = 0; - if (!cmSystemTools::StringToLong(triples[i - 2].c_str(), - &line)) { + if (!cmStrToLong(triples[i - 2], &line)) { line = 0; } fc.Line = line; @@ -2204,38 +2173,38 @@ bool cmCTestTestHandler::SetTestsProperties( } } if (key == "WILL_FAIL") { - rt.WillFail = cmSystemTools::IsOn(val); + rt.WillFail = cmIsOn(val); } if (key == "DISABLED") { - rt.Disabled = cmSystemTools::IsOn(val); + rt.Disabled = cmIsOn(val); } if (key == "ATTACHED_FILES") { - cmSystemTools::ExpandListArgument(val, rt.AttachedFiles); + cmExpandList(val, rt.AttachedFiles); } if (key == "ATTACHED_FILES_ON_FAIL") { - cmSystemTools::ExpandListArgument(val, rt.AttachOnFail); + cmExpandList(val, rt.AttachOnFail); } if (key == "RESOURCE_LOCK") { std::vector<std::string> lval; - cmSystemTools::ExpandListArgument(val, lval); + cmExpandList(val, lval); rt.LockedResources.insert(lval.begin(), lval.end()); } if (key == "FIXTURES_SETUP") { std::vector<std::string> lval; - cmSystemTools::ExpandListArgument(val, lval); + cmExpandList(val, lval); rt.FixturesSetup.insert(lval.begin(), lval.end()); } if (key == "FIXTURES_CLEANUP") { std::vector<std::string> lval; - cmSystemTools::ExpandListArgument(val, lval); + cmExpandList(val, lval); rt.FixturesCleanup.insert(lval.begin(), lval.end()); } if (key == "FIXTURES_REQUIRED") { std::vector<std::string> lval; - cmSystemTools::ExpandListArgument(val, lval); + cmExpandList(val, lval); rt.FixturesRequired.insert(lval.begin(), lval.end()); } @@ -2247,21 +2216,21 @@ bool cmCTestTestHandler::SetTestsProperties( rt.Cost = static_cast<float>(atof(val.c_str())); } if (key == "REQUIRED_FILES") { - cmSystemTools::ExpandListArgument(val, rt.RequiredFiles); + cmExpandList(val, rt.RequiredFiles); } if (key == "RUN_SERIAL") { - rt.RunSerial = cmSystemTools::IsOn(val); + rt.RunSerial = cmIsOn(val); } if (key == "FAIL_REGULAR_EXPRESSION") { std::vector<std::string> lval; - cmSystemTools::ExpandListArgument(val, lval); + cmExpandList(val, lval); for (std::string const& cr : lval) { rt.ErrorRegularExpressions.emplace_back(cr, cr); } } if (key == "SKIP_REGULAR_EXPRESSION") { std::vector<std::string> lval; - cmSystemTools::ExpandListArgument(val, lval); + cmExpandList(val, lval); for (std::string const& cr : lval) { rt.SkipRegularExpressions.emplace_back(cr, cr); } @@ -2273,7 +2242,7 @@ bool cmCTestTestHandler::SetTestsProperties( } } if (key == "PROCESSOR_AFFINITY") { - rt.WantAffinity = cmSystemTools::IsOn(val); + rt.WantAffinity = cmIsOn(val); } if (key == "SKIP_RETURN_CODE") { rt.SkipReturnCode = atoi(val.c_str()); @@ -2282,14 +2251,14 @@ bool cmCTestTestHandler::SetTestsProperties( } } if (key == "DEPENDS") { - cmSystemTools::ExpandListArgument(val, rt.Depends); + cmExpandList(val, rt.Depends); } if (key == "ENVIRONMENT") { - cmSystemTools::ExpandListArgument(val, rt.Environment); + cmExpandList(val, rt.Environment); } if (key == "LABELS") { std::vector<std::string> Labels; - cmSystemTools::ExpandListArgument(val, Labels); + cmExpandList(val, Labels); rt.Labels.insert(rt.Labels.end(), Labels.begin(), Labels.end()); // sort the array std::sort(rt.Labels.begin(), rt.Labels.end()); @@ -2310,7 +2279,7 @@ bool cmCTestTestHandler::SetTestsProperties( } if (key == "PASS_REGULAR_EXPRESSION") { std::vector<std::string> lval; - cmSystemTools::ExpandListArgument(val, lval); + cmExpandList(val, lval); for (std::string const& cr : lval) { rt.RequiredRegularExpressions.emplace_back(cr, cr); } @@ -2320,7 +2289,7 @@ bool cmCTestTestHandler::SetTestsProperties( } if (key == "TIMEOUT_AFTER_MATCH") { std::vector<std::string> propArgs; - cmSystemTools::ExpandListArgument(val, propArgs); + cmExpandList(val, propArgs); if (propArgs.size() != 2) { cmCTestLog(this->CTest, WARNING, "TIMEOUT_AFTER_MATCH expects two arguments, found " @@ -2328,7 +2297,7 @@ bool cmCTestTestHandler::SetTestsProperties( } else { rt.AlternateTimeout = cmDuration(atof(propArgs[0].c_str())); std::vector<std::string> lval; - cmSystemTools::ExpandListArgument(propArgs[1], lval); + cmExpandList(propArgs[1], lval); for (std::string const& cr : lval) { rt.TimeoutRegularExpressions.emplace_back(cr, cr); } @@ -2371,7 +2340,7 @@ bool cmCTestTestHandler::SetDirectoryProperties( if (cwd == rt.Directory) { if (key == "LABELS") { std::vector<std::string> DirectoryLabels; - cmSystemTools::ExpandListArgument(val, DirectoryLabels); + cmExpandList(val, DirectoryLabels); rt.Labels.insert(rt.Labels.end(), DirectoryLabels.begin(), DirectoryLabels.end()); diff --git a/Source/CTest/cmCTestUpdateHandler.cxx b/Source/CTest/cmCTestUpdateHandler.cxx index d80b5a5..a6a3542 100644 --- a/Source/CTest/cmCTestUpdateHandler.cxx +++ b/Source/CTest/cmCTestUpdateHandler.cxx @@ -12,6 +12,7 @@ #include "cmCTestSVN.h" #include "cmCTestVC.h" #include "cmGeneratedFileStream.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmVersion.h" #include "cmXMLWriter.h" @@ -266,33 +267,27 @@ int cmCTestUpdateHandler::DetectVCS(const char* dir) if (cmSystemTools::FileExists(sourceDirectory)) { return cmCTestUpdateHandler::e_SVN; } - sourceDirectory = dir; - sourceDirectory += "/CVS"; + sourceDirectory = cmStrCat(dir, "/CVS"); if (cmSystemTools::FileExists(sourceDirectory)) { return cmCTestUpdateHandler::e_CVS; } - sourceDirectory = dir; - sourceDirectory += "/.bzr"; + sourceDirectory = cmStrCat(dir, "/.bzr"); if (cmSystemTools::FileExists(sourceDirectory)) { return cmCTestUpdateHandler::e_BZR; } - sourceDirectory = dir; - sourceDirectory += "/.git"; + sourceDirectory = cmStrCat(dir, "/.git"); if (cmSystemTools::FileExists(sourceDirectory)) { return cmCTestUpdateHandler::e_GIT; } - sourceDirectory = dir; - sourceDirectory += "/.hg"; + sourceDirectory = cmStrCat(dir, "/.hg"); if (cmSystemTools::FileExists(sourceDirectory)) { return cmCTestUpdateHandler::e_HG; } - sourceDirectory = dir; - sourceDirectory += "/.p4"; + sourceDirectory = cmStrCat(dir, "/.p4"); if (cmSystemTools::FileExists(sourceDirectory)) { return cmCTestUpdateHandler::e_P4; } - sourceDirectory = dir; - sourceDirectory += "/.p4config"; + sourceDirectory = cmStrCat(dir, "/.p4config"); if (cmSystemTools::FileExists(sourceDirectory)) { return cmCTestUpdateHandler::e_P4; } diff --git a/Source/CTest/cmCTestVC.cxx b/Source/CTest/cmCTestVC.cxx index eea41cf..773886d 100644 --- a/Source/CTest/cmCTestVC.cxx +++ b/Source/CTest/cmCTestVC.cxx @@ -3,6 +3,7 @@ #include "cmCTestVC.h" #include "cmCTest.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmXMLWriter.h" @@ -152,8 +153,7 @@ bool cmCTestVC::Update() // if update version only is on then do not actually update, // just note the current version and finish - if (!cmSystemTools::IsOn( - this->CTest->GetCTestConfiguration("UpdateVersionOnly"))) { + if (!cmIsOn(this->CTest->GetCTestConfiguration("UpdateVersionOnly"))) { result = this->NoteOldRevision() && result; this->Log << "--- Begin Update ---\n"; result = this->UpdateImpl() && result; diff --git a/Source/CTest/cmParseCacheCoverage.cxx b/Source/CTest/cmParseCacheCoverage.cxx index ca1fe70..cd2bb1a 100644 --- a/Source/CTest/cmParseCacheCoverage.cxx +++ b/Source/CTest/cmParseCacheCoverage.cxx @@ -2,6 +2,7 @@ #include "cmCTest.h" #include "cmCTestCoverageHandler.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmsys/Directory.hxx" @@ -30,9 +31,7 @@ bool cmParseCacheCoverage::LoadCoverageData(const char* d) for (i = 0; i < numf; i++) { std::string file = dir.GetFile(i); if (file != "." && file != ".." && !cmSystemTools::FileIsDirectory(file)) { - std::string path = d; - path += "/"; - path += file; + std::string path = cmStrCat(d, '/', file); if (cmSystemTools::GetFilenameLastExtension(path) == ".cmcov") { if (!this->ReadCMCovFile(path.c_str())) { return false; diff --git a/Source/CTest/cmParseCoberturaCoverage.cxx b/Source/CTest/cmParseCoberturaCoverage.cxx index 848a034..e0186c9 100644 --- a/Source/CTest/cmParseCoberturaCoverage.cxx +++ b/Source/CTest/cmParseCoberturaCoverage.cxx @@ -2,6 +2,7 @@ #include "cmCTest.h" #include "cmCTestCoverageHandler.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmXMLParser.h" @@ -75,7 +76,7 @@ protected: // Check if this is a path that is relative to our source or // binary directories. for (std::string const& filePath : FilePaths) { - finalpath = filePath + "/" + filename; + finalpath = cmStrCat(filePath, "/", filename); if (cmSystemTools::FileExists(finalpath)) { this->CurFileName = finalpath; break; @@ -86,7 +87,7 @@ protected: cmsys::ifstream fin(this->CurFileName.c_str()); if (this->CurFileName.empty() || !fin) { this->CurFileName = - this->Coverage.BinaryDir + "/" + atts[tagCount + 1]; + cmStrCat(this->Coverage.BinaryDir, "/", atts[tagCount + 1]); fin.open(this->CurFileName.c_str()); if (!fin) { cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, diff --git a/Source/CTest/cmParseGTMCoverage.cxx b/Source/CTest/cmParseGTMCoverage.cxx index 881bf2d..621ca79 100644 --- a/Source/CTest/cmParseGTMCoverage.cxx +++ b/Source/CTest/cmParseGTMCoverage.cxx @@ -31,9 +31,7 @@ bool cmParseGTMCoverage::LoadCoverageData(const char* d) for (i = 0; i < numf; i++) { std::string file = dir.GetFile(i); if (file != "." && file != ".." && !cmSystemTools::FileIsDirectory(file)) { - std::string path = d; - path += "/"; - path += file; + std::string path = cmStrCat(d, '/', file); if (cmSystemTools::GetFilenameLastExtension(path) == ".mcov") { if (!this->ReadMCovFile(path.c_str())) { return false; diff --git a/Source/CTest/cmParseJacocoCoverage.cxx b/Source/CTest/cmParseJacocoCoverage.cxx index 5f1e712..374acad 100644 --- a/Source/CTest/cmParseJacocoCoverage.cxx +++ b/Source/CTest/cmParseJacocoCoverage.cxx @@ -104,9 +104,7 @@ protected: std::string const& baseDir) { // Search for the file in the baseDir and its subdirectories. - std::string packageGlob = baseDir; - packageGlob += "/"; - packageGlob += fileName; + std::string packageGlob = cmStrCat(baseDir, '/', fileName); cmsys::Glob gl; gl.RecurseOn(); gl.RecurseThroughSymlinksOn(); diff --git a/Source/CTest/cmParseMumpsCoverage.cxx b/Source/CTest/cmParseMumpsCoverage.cxx index 4a81ee4..afd7dc3 100644 --- a/Source/CTest/cmParseMumpsCoverage.cxx +++ b/Source/CTest/cmParseMumpsCoverage.cxx @@ -2,6 +2,7 @@ #include "cmCTest.h" #include "cmCTestCoverageHandler.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmsys/FStream.hxx" @@ -107,8 +108,7 @@ bool cmParseMumpsCoverage::LoadPackages(const char* d) { cmsys::Glob glob; glob.RecurseOn(); - std::string pat = d; - pat += "/*.m"; + std::string pat = cmStrCat(d, "/*.m"); glob.FindFiles(pat); for (std::string& file : glob.GetFiles()) { std::string name = cmSystemTools::GetFilenameName(file); diff --git a/Source/CTest/cmParsePHPCoverage.cxx b/Source/CTest/cmParsePHPCoverage.cxx index a6e65c9..870e222 100644 --- a/Source/CTest/cmParsePHPCoverage.cxx +++ b/Source/CTest/cmParsePHPCoverage.cxx @@ -2,6 +2,7 @@ #include "cmCTest.h" #include "cmCTestCoverageHandler.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmsys/Directory.hxx" @@ -210,9 +211,7 @@ bool cmParsePHPCoverage::ReadPHPCoverageDirectory(const char* d) for (i = 0; i < numf; i++) { std::string file = dir.GetFile(i); if (file != "." && file != ".." && !cmSystemTools::FileIsDirectory(file)) { - std::string path = d; - path += "/"; - path += file; + std::string path = cmStrCat(d, '/', file); if (!this->ReadPHPData(path.c_str())) { return false; } diff --git a/Source/CTest/cmProcess.cxx b/Source/CTest/cmProcess.cxx index 7a3b82e..61d2ed3 100644 --- a/Source/CTest/cmProcess.cxx +++ b/Source/CTest/cmProcess.cxx @@ -7,6 +7,7 @@ #include "cmCTestRunTest.h" #include "cmCTestTestHandler.h" #include "cmGetPipes.h" +#include "cmStringAlgorithms.h" #include "cmsys/Process.h" #include <iostream> @@ -694,8 +695,7 @@ std::string cmProcess::GetExitExceptionString() # endif # endif default: - exception_str = "Signal "; - exception_str += std::to_string(this->Signal); + exception_str = cmStrCat("Signal ", this->Signal); } #endif return exception_str; diff --git a/Source/CursesDialog/CMakeLists.txt b/Source/CursesDialog/CMakeLists.txt index c51b0dd..270b07e 100644 --- a/Source/CursesDialog/CMakeLists.txt +++ b/Source/CursesDialog/CMakeLists.txt @@ -23,6 +23,10 @@ include_directories(${CURSES_INCLUDE_PATH}) add_executable(ccmake ${CURSES_SRCS} ) target_link_libraries(ccmake CMakeLib) if(CMAKE_USE_SYSTEM_FORM) + find_path(CURSES_FORM_INCLUDE_DIR NAMES form.h HINTS ${CURSES_INCLUDE_PATH} ${CURSES_INCLUDE_PATH}/ncurses) + if(CURSES_FORM_INCLUDE_DIR) + target_include_directories(ccmake PRIVATE ${CURSES_FORM_INCLUDE_DIR}) + endif() target_link_libraries(ccmake ${CURSES_FORM_LIBRARY} ${CURSES_LIBRARY} diff --git a/Source/CursesDialog/ccmake.cxx b/Source/CursesDialog/ccmake.cxx index 7caed0c..ce32898 100644 --- a/Source/CursesDialog/ccmake.cxx +++ b/Source/CursesDialog/ccmake.cxx @@ -56,7 +56,8 @@ void onsig(int /*unused*/) cbreak(); /* nl- or cr not needed */ keypad(stdscr, true); /* Use key symbols as KEY_DOWN */ refresh(); - int x, y; + int x; + int y; getmaxyx(stdscr, y, x); cmCursesForm::CurrentForm->Render(1, 1, x, y); cmCursesForm::CurrentForm->UpdateStatusBar(); @@ -127,7 +128,8 @@ int main(int argc, char const* const* argv) signal(SIGWINCH, onsig); - int x, y; + int x; + int y; getmaxyx(stdscr, y, x); if (x < cmCursesMainForm::MIN_WIDTH || y < cmCursesMainForm::MIN_HEIGHT) { endwin(); diff --git a/Source/CursesDialog/cmCursesCacheEntryComposite.cxx b/Source/CursesDialog/cmCursesCacheEntryComposite.cxx index c1dd591..f7e3920 100644 --- a/Source/CursesDialog/cmCursesCacheEntryComposite.cxx +++ b/Source/CursesDialog/cmCursesCacheEntryComposite.cxx @@ -11,6 +11,7 @@ #include "cmCursesWidget.h" #include "cmState.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmake.h" @@ -49,7 +50,7 @@ cmCursesCacheEntryComposite::cmCursesCacheEntryComposite( switch (cm->GetState()->GetCacheEntryType(key)) { case cmStateEnums::BOOL: this->Entry = new cmCursesBoolWidget(this->EntryWidth, 1, 1, 1); - if (cmSystemTools::IsOn(value)) { + if (cmIsOn(value)) { static_cast<cmCursesBoolWidget*>(this->Entry)->SetValueAsBool(true); } else { static_cast<cmCursesBoolWidget*>(this->Entry)->SetValueAsBool(false); @@ -71,7 +72,7 @@ cmCursesCacheEntryComposite::cmCursesCacheEntryComposite( new cmCursesOptionsWidget(this->EntryWidth, 1, 1, 1); this->Entry = ow; std::vector<std::string> options; - cmSystemTools::ExpandListArgument(stringsProp, options); + cmExpandList(stringsProp, options); for (auto const& opt : options) { ow->AddOption(opt); } diff --git a/Source/CursesDialog/cmCursesLongMessageForm.cxx b/Source/CursesDialog/cmCursesLongMessageForm.cxx index 4e887d6..95026d5 100644 --- a/Source/CursesDialog/cmCursesLongMessageForm.cxx +++ b/Source/CursesDialog/cmCursesLongMessageForm.cxx @@ -38,7 +38,8 @@ cmCursesLongMessageForm::~cmCursesLongMessageForm() void cmCursesLongMessageForm::UpdateStatusBar() { - int x, y; + int x; + int y; getmaxyx(stdscr, y, x); char bar[cmCursesMainForm::MAX_WIDTH]; @@ -81,7 +82,8 @@ void cmCursesLongMessageForm::UpdateStatusBar() void cmCursesLongMessageForm::PrintKeys() { - int x, y; + int x; + int y; getmaxyx(stdscr, y, x); if (x < cmCursesMainForm::MIN_WIDTH || y < cmCursesMainForm::MIN_HEIGHT) { return; @@ -98,7 +100,8 @@ void cmCursesLongMessageForm::PrintKeys() void cmCursesLongMessageForm::Render(int /*left*/, int /*top*/, int /*width*/, int /*height*/) { - int x, y; + int x; + int y; getmaxyx(stdscr, y, x); if (this->Form) { diff --git a/Source/CursesDialog/cmCursesMainForm.cxx b/Source/CursesDialog/cmCursesMainForm.cxx index 028e852..1b25716 100644 --- a/Source/CursesDialog/cmCursesMainForm.cxx +++ b/Source/CursesDialog/cmCursesMainForm.cxx @@ -13,6 +13,7 @@ #include "cmCursesWidget.h" #include "cmState.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmVersion.h" #include "cmake.h" @@ -47,8 +48,8 @@ cmCursesMainForm::cmCursesMainForm(std::vector<std::string> args, cmSystemTools::GetCMakeCursesCommand()); // create the arguments for the cmake object - std::string whereCMake = cmSystemTools::GetProgramPath(this->Args[0]); - whereCMake += "/cmake"; + std::string whereCMake = + cmStrCat(cmSystemTools::GetProgramPath(this->Args[0]), "/cmake"); this->Args[0] = whereCMake; this->CMakeInstance->SetArgs(this->Args); this->SearchString = ""; @@ -319,7 +320,8 @@ void cmCursesMainForm::Render(int left, int top, int width, int height) void cmCursesMainForm::PrintKeys(int process /* = 0 */) { - int x, y; + int x; + int y; getmaxyx(stdscr, y, x); if (x < cmCursesMainForm::MIN_WIDTH || x < this->InitialWidth || y < cmCursesMainForm::MIN_HEIGHT) { @@ -390,7 +392,8 @@ void cmCursesMainForm::PrintKeys(int process /* = 0 */) // on the status bar. Designed for a width of 80 chars. void cmCursesMainForm::UpdateStatusBar(const char* message) { - int x, y; + int x; + int y; getmaxyx(stdscr, y, x); // If window size is too small, display error and return if (x < cmCursesMainForm::MIN_WIDTH || x < this->InitialWidth || @@ -508,7 +511,8 @@ void cmCursesMainForm::UpdateProgress(const std::string& msg, float prog) int cmCursesMainForm::Configure(int noconfigure) { - int xi, yi; + int xi; + int yi; getmaxyx(stdscr, yi, xi); curses_move(1, 1); @@ -551,7 +555,8 @@ int cmCursesMainForm::Configure(int noconfigure) if (cmSystemTools::GetErrorOccuredFlag()) { this->OkToGenerate = false; } - int xx, yy; + int xx; + int yy; getmaxyx(stdscr, yy, xx); cmCursesLongMessageForm* msgs = new cmCursesLongMessageForm(this->Errors, @@ -580,7 +585,8 @@ int cmCursesMainForm::Configure(int noconfigure) int cmCursesMainForm::Generate() { - int xi, yi; + int xi; + int yi; getmaxyx(stdscr, yi, xi); curses_move(1, 1); @@ -609,7 +615,8 @@ int cmCursesMainForm::Generate() } // reset error condition cmSystemTools::ResetErrorOccuredFlag(); - int xx, yy; + int xx; + int yy; getmaxyx(stdscr, yy, xx); const char* title = "Messages during last pass."; if (cmSystemTools::GetErrorOccuredFlag()) { @@ -696,7 +703,7 @@ void cmCursesMainForm::FixValue(cmStateEnums::CacheEntryType type, cmSystemTools::ConvertToUnixSlashes(out); } if (type == cmStateEnums::BOOL) { - if (cmSystemTools::IsOff(out)) { + if (cmIsOff(out)) { out = "OFF"; } else { out = "ON"; @@ -706,7 +713,8 @@ void cmCursesMainForm::FixValue(cmStateEnums::CacheEntryType type, void cmCursesMainForm::HandleInput() { - int x = 0, y = 0; + int x = 0; + int y = 0; if (!this->Form) { return; diff --git a/Source/CursesDialog/cmCursesOptionsWidget.cxx b/Source/CursesDialog/cmCursesOptionsWidget.cxx index a8c4933..eb773ad 100644 --- a/Source/CursesDialog/cmCursesOptionsWidget.cxx +++ b/Source/CursesDialog/cmCursesOptionsWidget.cxx @@ -23,6 +23,9 @@ cmCursesOptionsWidget::cmCursesOptionsWidget(int width, int height, int left, bool cmCursesOptionsWidget::HandleInput(int& key, cmCursesMainForm* /*fm*/, WINDOW* w) { + if (this->Options.empty()) { + return false; + } switch (key) { case 10: // 10 == enter case KEY_ENTER: diff --git a/Source/CursesDialog/cmCursesStringWidget.cxx b/Source/CursesDialog/cmCursesStringWidget.cxx index 5e2a329..26724e7 100644 --- a/Source/CursesDialog/cmCursesStringWidget.cxx +++ b/Source/CursesDialog/cmCursesStringWidget.cxx @@ -64,7 +64,8 @@ void cmCursesStringWidget::OnType(int& key, cmCursesMainForm* fm, bool cmCursesStringWidget::HandleInput(int& key, cmCursesMainForm* fm, WINDOW* w) { - int x, y; + int x; + int y; FORM* form = fm->GetForm(); // when not in edit mode, edit mode is entered by pressing enter or i (vim @@ -179,7 +180,8 @@ const char* cmCursesStringWidget::GetValue() bool cmCursesStringWidget::PrintKeys() { - int x, y; + int x; + int y; getmaxyx(stdscr, y, x); if (x < cmCursesMainForm::MIN_WIDTH || y < cmCursesMainForm::MIN_HEIGHT) { return false; diff --git a/Source/QtDialog/FirstConfigure.cxx b/Source/QtDialog/FirstConfigure.cxx index 364a378..d9a8aff 100644 --- a/Source/QtDialog/FirstConfigure.cxx +++ b/Source/QtDialog/FirstConfigure.cxx @@ -2,6 +2,7 @@ #include "FirstConfigure.h" #include "Compilers.h" +#include "cmStringAlgorithms.h" #include <QComboBox> #include <QRadioButton> @@ -183,10 +184,9 @@ void StartCompilerSetup::onGeneratorChanged(QString const& name) if (GeneratorsSupportingPlatform.contains(name)) { // Change the label title to include the default platform - std::string label = "Optional platform for generator"; - label += "(if empty, generator uses: "; - label += this->GeneratorDefaultPlatform[name].toStdString(); - label += ")"; + std::string label = + cmStrCat("Optional platform for generator(if empty, generator uses: ", + this->GeneratorDefaultPlatform[name].toStdString(), ')'); this->PlatformLabel->setText(tr(label.c_str())); // Regenerate the list of supported platform diff --git a/Source/QtDialog/QCMake.cxx b/Source/QtDialog/QCMake.cxx index f357f90..ece3307 100644 --- a/Source/QtDialog/QCMake.cxx +++ b/Source/QtDialog/QCMake.cxx @@ -7,6 +7,7 @@ #include "cmExternalMakefileProjectGenerator.h" #include "cmState.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #ifdef Q_OS_WIN @@ -312,7 +313,7 @@ QCMakePropertyList QCMake::properties() const prop.Advanced = state->GetCacheEntryPropertyAsBool(key, "ADVANCED"); if (t == cmStateEnums::BOOL) { prop.Type = QCMakeProperty::BOOL; - prop.Value = cmSystemTools::IsOn(cachedValue); + prop.Value = cmIsOn(cachedValue); } else if (t == cmStateEnums::PATH) { prop.Type = QCMakeProperty::PATH; } else if (t == cmStateEnums::FILEPATH) { diff --git a/Source/QtDialog/QCMakeCacheView.cxx b/Source/QtDialog/QCMakeCacheView.cxx index 78a2710..5e8636a 100644 --- a/Source/QtDialog/QCMakeCacheView.cxx +++ b/Source/QtDialog/QCMakeCacheView.cxx @@ -210,7 +210,8 @@ void QCMakeCacheModel::clear() void QCMakeCacheModel::setProperties(const QCMakePropertyList& props) { - QSet<QCMakeProperty> newProps, newProps2; + QSet<QCMakeProperty> newProps; + QSet<QCMakeProperty> newProps2; if (this->ShowNewProperties) { newProps = props.toSet(); diff --git a/Source/cmAddCompileDefinitionsCommand.cxx b/Source/cmAddCompileDefinitionsCommand.cxx index 0474819..b00a4a7 100644 --- a/Source/cmAddCompileDefinitionsCommand.cxx +++ b/Source/cmAddCompileDefinitionsCommand.cxx @@ -2,19 +2,15 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmAddCompileDefinitionsCommand.h" +#include "cmExecutionStatus.h" #include "cmMakefile.h" -class cmExecutionStatus; - -bool cmAddCompileDefinitionsCommand::InitialPass( - std::vector<std::string> const& args, cmExecutionStatus&) +bool cmAddCompileDefinitionsCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { - if (args.empty()) { - return true; - } - + cmMakefile& mf = status.GetMakefile(); for (std::string const& i : args) { - this->Makefile->AddCompileDefinition(i); + mf.AddCompileDefinition(i); } return true; } diff --git a/Source/cmAddCompileDefinitionsCommand.h b/Source/cmAddCompileDefinitionsCommand.h index 5f90ed9..4bd621c 100644 --- a/Source/cmAddCompileDefinitionsCommand.h +++ b/Source/cmAddCompileDefinitionsCommand.h @@ -8,29 +8,9 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -class cmAddCompileDefinitionsCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmAddCompileDefinitionsCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; -}; +bool cmAddCompileDefinitionsCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmAddCompileOptionsCommand.cxx b/Source/cmAddCompileOptionsCommand.cxx index 412fb38..8ccb512 100644 --- a/Source/cmAddCompileOptionsCommand.cxx +++ b/Source/cmAddCompileOptionsCommand.cxx @@ -2,19 +2,15 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmAddCompileOptionsCommand.h" +#include "cmExecutionStatus.h" #include "cmMakefile.h" -class cmExecutionStatus; - -bool cmAddCompileOptionsCommand::InitialPass( - std::vector<std::string> const& args, cmExecutionStatus&) +bool cmAddCompileOptionsCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { - if (args.empty()) { - return true; - } - + cmMakefile& mf = status.GetMakefile(); for (std::string const& i : args) { - this->Makefile->AddCompileOption(i); + mf.AddCompileOption(i); } return true; } diff --git a/Source/cmAddCompileOptionsCommand.h b/Source/cmAddCompileOptionsCommand.h index b34b7fc..b172412 100644 --- a/Source/cmAddCompileOptionsCommand.h +++ b/Source/cmAddCompileOptionsCommand.h @@ -8,29 +8,9 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -class cmAddCompileOptionsCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmAddCompileOptionsCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; -}; +bool cmAddCompileOptionsCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmAddCustomCommandCommand.cxx b/Source/cmAddCustomCommandCommand.cxx index 6eb38bd..d2330e1 100644 --- a/Source/cmAddCustomCommandCommand.cxx +++ b/Source/cmAddCustomCommandCommand.cxx @@ -8,33 +8,44 @@ #include "cmCustomCommand.h" #include "cmCustomCommandLines.h" +#include "cmExecutionStatus.h" #include "cmGlobalGenerator.h" #include "cmMakefile.h" #include "cmMessageType.h" #include "cmPolicies.h" #include "cmSourceFile.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmTarget.h" -class cmExecutionStatus; +static bool cmAddCustomCommandCommandCheckOutputs( + const std::vector<std::string>& outputs, cmExecutionStatus& status); -// cmAddCustomCommandCommand -bool cmAddCustomCommandCommand::InitialPass( - std::vector<std::string> const& args, cmExecutionStatus&) +bool cmAddCustomCommandCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { /* Let's complain at the end of this function about the lack of a particular arg. For the moment, let's say that COMMAND, and either TARGET or SOURCE are required. */ if (args.size() < 4) { - this->SetError("called with wrong number of arguments."); + status.SetError("called with wrong number of arguments."); return false; } - std::string source, target, main_dependency, working, depfile, job_pool; + cmMakefile& mf = status.GetMakefile(); + std::string source; + std::string target; + std::string main_dependency; + std::string working; + std::string depfile; + std::string job_pool; std::string comment_buffer; const char* comment = nullptr; - std::vector<std::string> depends, outputs, output, byproducts; + std::vector<std::string> depends; + std::vector<std::string> outputs; + std::vector<std::string> output; + std::vector<std::string> byproducts; bool verbatim = false; bool append = false; bool uses_terminal = false; @@ -167,9 +178,9 @@ bool cmAddCustomCommandCommand::InitialPass( doing = doing_comment; } else if (copy == keyDEPFILE) { doing = doing_depfile; - if (this->Makefile->GetGlobalGenerator()->GetName() != "Ninja") { - this->SetError("Option DEPFILE not supported by " + - this->Makefile->GetGlobalGenerator()->GetName()); + if (mf.GetGlobalGenerator()->GetName() != "Ninja") { + status.SetError("Option DEPFILE not supported by " + + mf.GetGlobalGenerator()->GetName()); return false; } } else if (copy == keyJOB_POOL) { @@ -192,8 +203,7 @@ bool cmAddCustomCommandCommand::InitialPass( // and later references "${CMAKE_CURRENT_SOURCE_DIR}/out.txt". // This is fairly obscure so we can wait for someone to // complain. - filename = this->Makefile->GetCurrentBinaryDirectory(); - filename += "/"; + filename = cmStrCat(mf.GetCurrentBinaryDirectory(), '/'); } filename += copy; cmSystemTools::ConvertToUnixSlashes(filename); @@ -269,7 +279,7 @@ bool cmAddCustomCommandCommand::InitialPass( comment = comment_buffer.c_str(); break; default: - this->SetError("Wrong syntax. Unknown type of argument."); + status.SetError("Wrong syntax. Unknown type of argument."); return false; } } @@ -284,31 +294,31 @@ bool cmAddCustomCommandCommand::InitialPass( // At this point we could complain about the lack of arguments. For // the moment, let's say that COMMAND, TARGET are always required. if (output.empty() && target.empty()) { - this->SetError("Wrong syntax. A TARGET or OUTPUT must be specified."); + status.SetError("Wrong syntax. A TARGET or OUTPUT must be specified."); return false; } if (source.empty() && !target.empty() && !output.empty()) { - this->SetError( + status.SetError( "Wrong syntax. A TARGET and OUTPUT can not both be specified."); return false; } if (append && output.empty()) { - this->SetError("given APPEND option with no OUTPUT."); + status.SetError("given APPEND option with no OUTPUT."); return false; } // Make sure the output names and locations are safe. - if (!this->CheckOutputs(output) || !this->CheckOutputs(outputs) || - !this->CheckOutputs(byproducts)) { + if (!cmAddCustomCommandCommandCheckOutputs(output, status) || + !cmAddCustomCommandCommandCheckOutputs(outputs, status) || + !cmAddCustomCommandCommandCheckOutputs(byproducts, status)) { return false; } // Check for an append request. if (append) { // Lookup an existing command. - if (cmSourceFile* sf = - this->Makefile->GetSourceFileWithOutput(output[0])) { + if (cmSourceFile* sf = mf.GetSourceFileWithOutput(output[0])) { if (cmCustomCommand* cc = sf->GetCustomCommand()) { cc->AppendCommands(commandLines); cc->AppendDepends(depends); @@ -321,12 +331,12 @@ bool cmAddCustomCommandCommand::InitialPass( std::ostringstream e; e << "given APPEND option with output\n\"" << output[0] << "\"\nwhich is not already a custom command output."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } if (uses_terminal && !job_pool.empty()) { - this->SetError("JOB_POOL is shadowed by USES_TERMINAL."); + status.SetError("JOB_POOL is shadowed by USES_TERMINAL."); return false; } @@ -335,22 +345,21 @@ bool cmAddCustomCommandCommand::InitialPass( if (source.empty() && output.empty()) { // Source is empty, use the target. std::vector<std::string> no_depends; - this->Makefile->AddCustomCommandToTarget( - target, byproducts, no_depends, commandLines, cctype, comment, - working.c_str(), escapeOldStyle, uses_terminal, depfile, job_pool, - command_expand_lists); + mf.AddCustomCommandToTarget(target, byproducts, no_depends, commandLines, + cctype, comment, working.c_str(), + escapeOldStyle, uses_terminal, depfile, + job_pool, command_expand_lists); } else if (target.empty()) { // Target is empty, use the output. - this->Makefile->AddCustomCommandToOutput( - output, byproducts, depends, main_dependency, commandLines, comment, - working.c_str(), false, escapeOldStyle, uses_terminal, - command_expand_lists, depfile, job_pool); + mf.AddCustomCommandToOutput(output, byproducts, depends, main_dependency, + commandLines, comment, working.c_str(), false, + escapeOldStyle, uses_terminal, + command_expand_lists, depfile, job_pool); // Add implicit dependency scanning requests if any were given. if (!implicit_depends.empty()) { bool okay = false; - if (cmSourceFile* sf = - this->Makefile->GetSourceFileWithOutput(output[0])) { + if (cmSourceFile* sf = mf.GetSourceFileWithOutput(output[0])) { if (cmCustomCommand* cc = sf->GetCustomCommand()) { okay = true; cc->SetImplicitDepends(implicit_depends); @@ -360,21 +369,21 @@ bool cmAddCustomCommandCommand::InitialPass( std::ostringstream e; e << "could not locate source file with a custom command producing \"" << output[0] << "\" even though this command tried to create it!"; - this->SetError(e.str()); + status.SetError(e.str()); return false; } } } else if (!byproducts.empty()) { - this->SetError("BYPRODUCTS may not be specified with SOURCE signatures"); + status.SetError("BYPRODUCTS may not be specified with SOURCE signatures"); return false; } else if (uses_terminal) { - this->SetError("USES_TERMINAL may not be used with SOURCE signatures"); + status.SetError("USES_TERMINAL may not be used with SOURCE signatures"); return false; } else { bool issueMessage = true; std::ostringstream e; MessageType messageType = MessageType::AUTHOR_WARNING; - switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0050)) { + switch (mf.GetPolicyStatus(cmPolicies::CMP0050)) { case cmPolicies::WARN: e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0050) << "\n"; break; @@ -391,30 +400,31 @@ bool cmAddCustomCommandCommand::InitialPass( if (issueMessage) { e << "The SOURCE signatures of add_custom_command are no longer " "supported."; - this->Makefile->IssueMessage(messageType, e.str()); + mf.IssueMessage(messageType, e.str()); if (messageType == MessageType::FATAL_ERROR) { return false; } } // Use the old-style mode for backward compatibility. - this->Makefile->AddCustomCommandOldStyle(target, outputs, depends, source, - commandLines, comment); + mf.AddCustomCommandOldStyle(target, outputs, depends, source, commandLines, + comment); } return true; } -bool cmAddCustomCommandCommand::CheckOutputs( - const std::vector<std::string>& outputs) +bool cmAddCustomCommandCommandCheckOutputs( + const std::vector<std::string>& outputs, cmExecutionStatus& status) { + cmMakefile& mf = status.GetMakefile(); for (std::string const& o : outputs) { // Make sure the file will not be generated into the source // directory during an out of source build. - if (!this->Makefile->CanIWriteThisFile(o)) { + if (!mf.CanIWriteThisFile(o)) { std::string e = "attempted to have a file \"" + o + "\" in a source directory as an output of custom command."; - this->SetError(e); + status.SetError(e); cmSystemTools::SetFatalErrorOccured(); return false; } @@ -425,7 +435,7 @@ bool cmAddCustomCommandCommand::CheckOutputs( std::ostringstream msg; msg << "called with OUTPUT containing a \"" << o[pos] << "\". This character is not allowed."; - this->SetError(msg.str()); + status.SetError(msg.str()); return false; } } diff --git a/Source/cmAddCustomCommandCommand.h b/Source/cmAddCustomCommandCommand.h index 931aeab..4f8c58f 100644 --- a/Source/cmAddCustomCommandCommand.h +++ b/Source/cmAddCustomCommandCommand.h @@ -8,38 +8,9 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -/** \class cmAddCustomCommandCommand - * \brief cmAddCustomCommandCommand defines a new command (rule) that can - * be executed within the build process - * - */ - -class cmAddCustomCommandCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmAddCustomCommandCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; - -protected: - bool CheckOutputs(const std::vector<std::string>& outputs); -}; +bool cmAddCustomCommandCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmAddCustomTargetCommand.cxx b/Source/cmAddCustomTargetCommand.cxx index 0ecd5f5..caea510 100644 --- a/Source/cmAddCustomTargetCommand.cxx +++ b/Source/cmAddCustomTargetCommand.cxx @@ -6,25 +6,25 @@ #include <utility> #include "cmCustomCommandLines.h" +#include "cmExecutionStatus.h" #include "cmGeneratorExpression.h" #include "cmGlobalGenerator.h" #include "cmMakefile.h" #include "cmMessageType.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmTarget.h" -class cmExecutionStatus; - -// cmAddCustomTargetCommand -bool cmAddCustomTargetCommand::InitialPass( - std::vector<std::string> const& args, cmExecutionStatus&) +bool cmAddCustomTargetCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.empty()) { - this->SetError("called with incorrect number of arguments"); + status.SetError("called with incorrect number of arguments"); return false; } + cmMakefile& mf = status.GetMakefile(); std::string const& targetName = args[0]; // Check the target name. @@ -33,7 +33,7 @@ bool cmAddCustomTargetCommand::InitialPass( e << "called with invalid target name \"" << targetName << "\". Target names may not contain a slash. " << "Use ADD_CUSTOM_COMMAND to generate files."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } @@ -44,7 +44,8 @@ bool cmAddCustomTargetCommand::InitialPass( cmCustomCommandLines commandLines; // Accumulate dependencies. - std::vector<std::string> depends, byproducts; + std::vector<std::string> depends; + std::vector<std::string> byproducts; std::string working_directory; bool verbatim = false; bool uses_terminal = false; @@ -122,8 +123,7 @@ bool cmAddCustomTargetCommand::InitialPass( case doing_byproducts: { std::string filename; if (!cmSystemTools::FileIsFullPath(copy)) { - filename = this->Makefile->GetCurrentBinaryDirectory(); - filename += "/"; + filename = cmStrCat(mf.GetCurrentBinaryDirectory(), '/'); } filename += copy; cmSystemTools::ConvertToUnixSlashes(filename); @@ -145,7 +145,7 @@ bool cmAddCustomTargetCommand::InitialPass( job_pool = copy; break; default: - this->SetError("Wrong syntax. Unknown type of argument."); + status.SetError("Wrong syntax. Unknown type of argument."); return false; } } @@ -156,7 +156,7 @@ bool cmAddCustomTargetCommand::InitialPass( std::ostringstream msg; msg << "called with target name containing a \"" << targetName[pos] << "\". This character is not allowed."; - this->SetError(msg.str()); + status.SetError(msg.str()); return false; } @@ -168,8 +168,7 @@ bool cmAddCustomTargetCommand::InitialPass( if (nameOk) { nameOk = targetName.find(':') == std::string::npos; } - if (!nameOk && - !this->Makefile->CheckCMP0037(targetName, cmStateEnums::UTILITY)) { + if (!nameOk && !mf.CheckCMP0037(targetName, cmStateEnums::UTILITY)) { return false; } @@ -182,39 +181,37 @@ bool cmAddCustomTargetCommand::InitialPass( // Enforce name uniqueness. { std::string msg; - if (!this->Makefile->EnforceUniqueName(targetName, msg, true)) { - this->SetError(msg); + if (!mf.EnforceUniqueName(targetName, msg, true)) { + status.SetError(msg); return false; } } if (commandLines.empty() && !byproducts.empty()) { - this->Makefile->IssueMessage( - MessageType::FATAL_ERROR, - "BYPRODUCTS may not be specified without any COMMAND"); + mf.IssueMessage(MessageType::FATAL_ERROR, + "BYPRODUCTS may not be specified without any COMMAND"); return true; } if (commandLines.empty() && uses_terminal) { - this->Makefile->IssueMessage( - MessageType::FATAL_ERROR, - "USES_TERMINAL may not be specified without any COMMAND"); + mf.IssueMessage(MessageType::FATAL_ERROR, + "USES_TERMINAL may not be specified without any COMMAND"); return true; } if (commandLines.empty() && command_expand_lists) { - this->Makefile->IssueMessage( + mf.IssueMessage( MessageType::FATAL_ERROR, "COMMAND_EXPAND_LISTS may not be specified without any COMMAND"); return true; } if (uses_terminal && !job_pool.empty()) { - this->SetError("JOB_POOL is shadowed by USES_TERMINAL."); + status.SetError("JOB_POOL is shadowed by USES_TERMINAL."); return false; } // Add the utility target to the makefile. bool escapeOldStyle = !verbatim; - cmTarget* target = this->Makefile->AddUtilityCommand( + cmTarget* target = mf.AddUtilityCommand( targetName, cmMakefile::TargetOrigin::Project, excludeFromAll, working_directory.c_str(), byproducts, depends, commandLines, escapeOldStyle, comment, uses_terminal, command_expand_lists, job_pool); diff --git a/Source/cmAddCustomTargetCommand.h b/Source/cmAddCustomTargetCommand.h index db577bc..e23ef9f 100644 --- a/Source/cmAddCustomTargetCommand.h +++ b/Source/cmAddCustomTargetCommand.h @@ -8,36 +8,9 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -/** \class cmAddCustomTargetCommand - * \brief Command that adds a target to the build system. - * - * cmAddCustomTargetCommand adds an extra target to the build system. - * This is useful when you would like to add special - * targets like "install,", "clean," and so on. - */ -class cmAddCustomTargetCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmAddCustomTargetCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; -}; +bool cmAddCustomTargetCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmAddDefinitionsCommand.cxx b/Source/cmAddDefinitionsCommand.cxx index 62e57a3..0b10aee 100644 --- a/Source/cmAddDefinitionsCommand.cxx +++ b/Source/cmAddDefinitionsCommand.cxx @@ -2,21 +2,15 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmAddDefinitionsCommand.h" +#include "cmExecutionStatus.h" #include "cmMakefile.h" -class cmExecutionStatus; - -// cmAddDefinitionsCommand -bool cmAddDefinitionsCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus&) +bool cmAddDefinitionsCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { - // it is OK to have no arguments - if (args.empty()) { - return true; - } - + cmMakefile& mf = status.GetMakefile(); for (std::string const& i : args) { - this->Makefile->AddDefineFlag(i); + mf.AddDefineFlag(i); } return true; } diff --git a/Source/cmAddDefinitionsCommand.h b/Source/cmAddDefinitionsCommand.h index 0e32c83..a67f095 100644 --- a/Source/cmAddDefinitionsCommand.h +++ b/Source/cmAddDefinitionsCommand.h @@ -8,35 +8,9 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -/** \class cmAddDefinitionsCommand - * \brief Specify a list of compiler defines - * - * cmAddDefinitionsCommand specifies a list of compiler defines. These defines - * will be added to the compile command. - */ -class cmAddDefinitionsCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmAddDefinitionsCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; -}; +bool cmAddDefinitionsCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmAddDependenciesCommand.cxx b/Source/cmAddDependenciesCommand.cxx index 4956a47..0ddbda8 100644 --- a/Source/cmAddDependenciesCommand.cxx +++ b/Source/cmAddDependenciesCommand.cxx @@ -4,34 +4,33 @@ #include <sstream> +#include "cmExecutionStatus.h" #include "cmMakefile.h" #include "cmMessageType.h" #include "cmRange.h" #include "cmTarget.h" -class cmExecutionStatus; - -// cmDependenciesCommand -bool cmAddDependenciesCommand::InitialPass( - std::vector<std::string> const& args, cmExecutionStatus&) +bool cmAddDependenciesCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() < 2) { - this->SetError("called with incorrect number of arguments"); + status.SetError("called with incorrect number of arguments"); return false; } + cmMakefile& mf = status.GetMakefile(); std::string const& target_name = args[0]; - if (this->Makefile->IsAlias(target_name)) { + if (mf.IsAlias(target_name)) { std::ostringstream e; e << "Cannot add target-level dependencies to alias target \"" << target_name << "\".\n"; - this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str()); + mf.IssueMessage(MessageType::FATAL_ERROR, e.str()); } - if (cmTarget* target = this->Makefile->FindTargetToUse(target_name)) { + if (cmTarget* target = mf.FindTargetToUse(target_name)) { // skip over target_name for (std::string const& arg : cmMakeRange(args).advance(1)) { - target->AddUtility(arg, this->Makefile); + target->AddUtility(arg, &mf); } } else { std::ostringstream e; @@ -41,7 +40,7 @@ bool cmAddDependenciesCommand::InitialPass( << "by the add_executable, add_library, or add_custom_target commands. " << "If you want to add file-level dependencies see the DEPENDS option " << "of the add_custom_target and add_custom_command commands."; - this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str()); + mf.IssueMessage(MessageType::FATAL_ERROR, e.str()); } return true; diff --git a/Source/cmAddDependenciesCommand.h b/Source/cmAddDependenciesCommand.h index ce912d3..0c60e3a 100644 --- a/Source/cmAddDependenciesCommand.h +++ b/Source/cmAddDependenciesCommand.h @@ -8,34 +8,9 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -/** \class cmAddDependenciesCommand - * \brief Add a dependency to a target - * - * cmAddDependenciesCommand adds a dependency to a target - */ -class cmAddDependenciesCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmAddDependenciesCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; -}; +bool cmAddDependenciesCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmAddExecutableCommand.cxx b/Source/cmAddExecutableCommand.cxx index 5685fdf..59d6be3 100644 --- a/Source/cmAddExecutableCommand.cxx +++ b/Source/cmAddExecutableCommand.cxx @@ -4,22 +4,22 @@ #include <sstream> +#include "cmExecutionStatus.h" #include "cmGeneratorExpression.h" #include "cmGlobalGenerator.h" #include "cmMakefile.h" #include "cmStateTypes.h" #include "cmTarget.h" -class cmExecutionStatus; - -// cmExecutableCommand -bool cmAddExecutableCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus&) +bool cmAddExecutableCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.empty()) { - this->SetError("called with incorrect number of arguments"); + status.SetError("called with incorrect number of arguments"); return false; } + + cmMakefile& mf = status.GetMakefile(); std::vector<std::string>::const_iterator s = args.begin(); std::string const& exename = *s; @@ -61,59 +61,58 @@ bool cmAddExecutableCommand::InitialPass(std::vector<std::string> const& args, if (nameOk && !importTarget && !isAlias) { nameOk = exename.find(':') == std::string::npos; } - if (!nameOk && - !this->Makefile->CheckCMP0037(exename, cmStateEnums::EXECUTABLE)) { + if (!nameOk && !mf.CheckCMP0037(exename, cmStateEnums::EXECUTABLE)) { return false; } // Special modifiers are not allowed with IMPORTED signature. if (importTarget && (use_win32 || use_macbundle || excludeFromAll)) { if (use_win32) { - this->SetError("may not be given WIN32 for an IMPORTED target."); + status.SetError("may not be given WIN32 for an IMPORTED target."); } else if (use_macbundle) { - this->SetError("may not be given MACOSX_BUNDLE for an IMPORTED target."); + status.SetError( + "may not be given MACOSX_BUNDLE for an IMPORTED target."); } else // if(excludeFromAll) { - this->SetError( + status.SetError( "may not be given EXCLUDE_FROM_ALL for an IMPORTED target."); } return false; } if (isAlias) { if (!cmGeneratorExpression::IsValidTargetName(exename)) { - this->SetError("Invalid name for ALIAS: " + exename); + status.SetError("Invalid name for ALIAS: " + exename); return false; } if (excludeFromAll) { - this->SetError("EXCLUDE_FROM_ALL with ALIAS makes no sense."); + status.SetError("EXCLUDE_FROM_ALL with ALIAS makes no sense."); return false; } if (importTarget || importGlobal) { - this->SetError("IMPORTED with ALIAS is not allowed."); + status.SetError("IMPORTED with ALIAS is not allowed."); return false; } if (args.size() != 3) { std::ostringstream e; e << "ALIAS requires exactly one target argument."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } std::string const& aliasedName = *s; - if (this->Makefile->IsAlias(aliasedName)) { + if (mf.IsAlias(aliasedName)) { std::ostringstream e; e << "cannot create ALIAS target \"" << exename << "\" because target \"" << aliasedName << "\" is itself an ALIAS."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } - cmTarget* aliasedTarget = - this->Makefile->FindTargetToUse(aliasedName, true); + cmTarget* aliasedTarget = mf.FindTargetToUse(aliasedName, true); if (!aliasedTarget) { std::ostringstream e; e << "cannot create ALIAS target \"" << exename << "\" because target \"" << aliasedName << "\" does not already exist."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } cmStateEnums::TargetType type = aliasedTarget->GetType(); @@ -121,7 +120,7 @@ bool cmAddExecutableCommand::InitialPass(std::vector<std::string> const& args, std::ostringstream e; e << "cannot create ALIAS target \"" << exename << "\" because target \"" << aliasedName << "\" is not an executable."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } if (aliasedTarget->IsImported() && @@ -129,42 +128,40 @@ bool cmAddExecutableCommand::InitialPass(std::vector<std::string> const& args, std::ostringstream e; e << "cannot create ALIAS target \"" << exename << "\" because target \"" << aliasedName << "\" is imported but not globally visible."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } - this->Makefile->AddAlias(exename, aliasedName); + mf.AddAlias(exename, aliasedName); return true; } // Handle imported target creation. if (importTarget) { // Make sure the target does not already exist. - if (this->Makefile->FindTargetToUse(exename)) { + if (mf.FindTargetToUse(exename)) { std::ostringstream e; e << "cannot create imported target \"" << exename << "\" because another target with the same name already exists."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } // Create the imported target. - this->Makefile->AddImportedTarget(exename, cmStateEnums::EXECUTABLE, - importGlobal); + mf.AddImportedTarget(exename, cmStateEnums::EXECUTABLE, importGlobal); return true; } // Enforce name uniqueness. { std::string msg; - if (!this->Makefile->EnforceUniqueName(exename, msg)) { - this->SetError(msg); + if (!mf.EnforceUniqueName(exename, msg)) { + status.SetError(msg); return false; } } std::vector<std::string> srclists(s, args.end()); - cmTarget* tgt = - this->Makefile->AddExecutable(exename, srclists, excludeFromAll); + cmTarget* tgt = mf.AddExecutable(exename, srclists, excludeFromAll); if (use_win32) { tgt->SetProperty("WIN32_EXECUTABLE", "ON"); } diff --git a/Source/cmAddExecutableCommand.h b/Source/cmAddExecutableCommand.h index ec57c3f..f7bc273 100644 --- a/Source/cmAddExecutableCommand.h +++ b/Source/cmAddExecutableCommand.h @@ -8,35 +8,9 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -/** \class cmExecutablesCommand - * \brief Defines a list of executables to build. - * - * cmExecutablesCommand defines a list of executable (i.e., test) - * programs to create. - */ -class cmAddExecutableCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmAddExecutableCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; -}; +bool cmAddExecutableCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmAddLibraryCommand.cxx b/Source/cmAddLibraryCommand.cxx index ad12e89..46fc61d 100644 --- a/Source/cmAddLibraryCommand.cxx +++ b/Source/cmAddLibraryCommand.cxx @@ -5,30 +5,29 @@ #include <sstream> #include "cmAlgorithms.h" +#include "cmExecutionStatus.h" #include "cmGeneratorExpression.h" #include "cmGlobalGenerator.h" #include "cmMakefile.h" #include "cmMessageType.h" #include "cmState.h" #include "cmStateTypes.h" -#include "cmSystemTools.h" +#include "cmStringAlgorithms.h" #include "cmTarget.h" -class cmExecutionStatus; - -// cmLibraryCommand -bool cmAddLibraryCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus&) +bool cmAddLibraryCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.empty()) { - this->SetError("called with incorrect number of arguments"); + status.SetError("called with incorrect number of arguments"); return false; } + + cmMakefile& mf = status.GetMakefile(); // Library type defaults to value of BUILD_SHARED_LIBS, if it exists, // otherwise it defaults to static library. cmStateEnums::TargetType type = cmStateEnums::SHARED_LIBRARY; - if (cmSystemTools::IsOff( - this->Makefile->GetDefinition("BUILD_SHARED_LIBS"))) { + if (cmIsOff(mf.GetDefinition("BUILD_SHARED_LIBS"))) { type = cmStateEnums::STATIC_LIBRARY; } bool excludeFromAll = false; @@ -52,7 +51,7 @@ bool cmAddLibraryCommand::InitialPass(std::vector<std::string> const& args, if (type == cmStateEnums::INTERFACE_LIBRARY) { std::ostringstream e; e << "INTERFACE library specified with conflicting STATIC type."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } ++s; @@ -62,7 +61,7 @@ bool cmAddLibraryCommand::InitialPass(std::vector<std::string> const& args, if (type == cmStateEnums::INTERFACE_LIBRARY) { std::ostringstream e; e << "INTERFACE library specified with conflicting SHARED type."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } ++s; @@ -72,7 +71,7 @@ bool cmAddLibraryCommand::InitialPass(std::vector<std::string> const& args, if (type == cmStateEnums::INTERFACE_LIBRARY) { std::ostringstream e; e << "INTERFACE library specified with conflicting MODULE type."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } ++s; @@ -82,7 +81,7 @@ bool cmAddLibraryCommand::InitialPass(std::vector<std::string> const& args, if (type == cmStateEnums::INTERFACE_LIBRARY) { std::ostringstream e; e << "INTERFACE library specified with conflicting OBJECT type."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } ++s; @@ -92,7 +91,7 @@ bool cmAddLibraryCommand::InitialPass(std::vector<std::string> const& args, if (type == cmStateEnums::INTERFACE_LIBRARY) { std::ostringstream e; e << "INTERFACE library specified with conflicting UNKNOWN type."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } ++s; @@ -102,7 +101,7 @@ bool cmAddLibraryCommand::InitialPass(std::vector<std::string> const& args, if (type == cmStateEnums::INTERFACE_LIBRARY) { std::ostringstream e; e << "INTERFACE library specified with conflicting ALIAS type."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } ++s; @@ -111,19 +110,19 @@ bool cmAddLibraryCommand::InitialPass(std::vector<std::string> const& args, if (haveSpecifiedType) { std::ostringstream e; e << "INTERFACE library specified with conflicting/multiple types."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } if (isAlias) { std::ostringstream e; e << "INTERFACE library specified with conflicting ALIAS type."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } if (excludeFromAll) { std::ostringstream e; e << "INTERFACE library may not be used with EXCLUDE_FROM_ALL."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } ++s; @@ -133,7 +132,7 @@ bool cmAddLibraryCommand::InitialPass(std::vector<std::string> const& args, if (type == cmStateEnums::INTERFACE_LIBRARY) { std::ostringstream e; e << "INTERFACE library may not be used with EXCLUDE_FROM_ALL."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } ++s; @@ -147,7 +146,7 @@ bool cmAddLibraryCommand::InitialPass(std::vector<std::string> const& args, } else if (type == cmStateEnums::INTERFACE_LIBRARY && *s == "GLOBAL") { std::ostringstream e; e << "GLOBAL option may only be used with IMPORTED libraries."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } else { break; @@ -158,13 +157,13 @@ bool cmAddLibraryCommand::InitialPass(std::vector<std::string> const& args, if (s != args.end()) { std::ostringstream e; e << "INTERFACE library requires no source arguments."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } if (importGlobal && !importTarget) { std::ostringstream e; e << "INTERFACE library specified as GLOBAL, but not as IMPORTED."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } } @@ -175,47 +174,46 @@ bool cmAddLibraryCommand::InitialPass(std::vector<std::string> const& args, if (nameOk && !importTarget && !isAlias) { nameOk = libName.find(':') == std::string::npos; } - if (!nameOk && !this->Makefile->CheckCMP0037(libName, type)) { + if (!nameOk && !mf.CheckCMP0037(libName, type)) { return false; } if (isAlias) { if (!cmGeneratorExpression::IsValidTargetName(libName)) { - this->SetError("Invalid name for ALIAS: " + libName); + status.SetError("Invalid name for ALIAS: " + libName); return false; } if (excludeFromAll) { - this->SetError("EXCLUDE_FROM_ALL with ALIAS makes no sense."); + status.SetError("EXCLUDE_FROM_ALL with ALIAS makes no sense."); return false; } if (importTarget || importGlobal) { - this->SetError("IMPORTED with ALIAS is not allowed."); + status.SetError("IMPORTED with ALIAS is not allowed."); return false; } if (args.size() != 3) { std::ostringstream e; e << "ALIAS requires exactly one target argument."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } std::string const& aliasedName = *s; - if (this->Makefile->IsAlias(aliasedName)) { + if (mf.IsAlias(aliasedName)) { std::ostringstream e; e << "cannot create ALIAS target \"" << libName << "\" because target \"" << aliasedName << "\" is itself an ALIAS."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } - cmTarget* aliasedTarget = - this->Makefile->FindTargetToUse(aliasedName, true); + cmTarget* aliasedTarget = mf.FindTargetToUse(aliasedName, true); if (!aliasedTarget) { std::ostringstream e; e << "cannot create ALIAS target \"" << libName << "\" because target \"" << aliasedName << "\" does not already " "exist."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } cmStateEnums::TargetType aliasedType = aliasedTarget->GetType(); @@ -229,7 +227,7 @@ bool cmAddLibraryCommand::InitialPass(std::vector<std::string> const& args, std::ostringstream e; e << "cannot create ALIAS target \"" << libName << "\" because target \"" << aliasedName << "\" is not a library."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } if (aliasedTarget->IsImported() && @@ -237,15 +235,15 @@ bool cmAddLibraryCommand::InitialPass(std::vector<std::string> const& args, std::ostringstream e; e << "cannot create ALIAS target \"" << libName << "\" because target \"" << aliasedName << "\" is imported but not globally visible."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } - this->Makefile->AddAlias(libName, aliasedName); + mf.AddAlias(libName, aliasedName); return true; } if (importTarget && excludeFromAll) { - this->SetError("excludeFromAll with IMPORTED target makes no sense."); + status.SetError("excludeFromAll with IMPORTED target makes no sense."); return false; } @@ -255,14 +253,13 @@ bool cmAddLibraryCommand::InitialPass(std::vector<std::string> const& args, yet its linker language. */ if ((type == cmStateEnums::SHARED_LIBRARY || type == cmStateEnums::MODULE_LIBRARY) && - !this->Makefile->GetState()->GetGlobalPropertyAsBool( - "TARGET_SUPPORTS_SHARED_LIBS")) { + !mf.GetState()->GetGlobalPropertyAsBool("TARGET_SUPPORTS_SHARED_LIBS")) { std::ostringstream w; w << "ADD_LIBRARY called with " << (type == cmStateEnums::SHARED_LIBRARY ? "SHARED" : "MODULE") << " option but the target platform does not support dynamic linking. " "Building a STATIC library instead. This may lead to problems."; - this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, w.str()); + mf.IssueMessage(MessageType::AUTHOR_WARNING, w.str()); type = cmStateEnums::STATIC_LIBRARY; } @@ -270,14 +267,13 @@ bool cmAddLibraryCommand::InitialPass(std::vector<std::string> const& args, if (importTarget) { // The IMPORTED signature requires a type to be specified explicitly. if (!haveSpecifiedType) { - this->SetError("called with IMPORTED argument but no library type."); + status.SetError("called with IMPORTED argument but no library type."); return false; } if (type == cmStateEnums::OBJECT_LIBRARY) { std::string reason; - if (!this->Makefile->GetGlobalGenerator()->HasKnownObjectFileLocation( - &reason)) { - this->Makefile->IssueMessage( + if (!mf.GetGlobalGenerator()->HasKnownObjectFileLocation(&reason)) { + mf.IssueMessage( MessageType::FATAL_ERROR, "The OBJECT library type may not be used for IMPORTED libraries" + reason + "."); @@ -288,28 +284,28 @@ bool cmAddLibraryCommand::InitialPass(std::vector<std::string> const& args, if (!cmGeneratorExpression::IsValidTargetName(libName)) { std::ostringstream e; e << "Invalid name for IMPORTED INTERFACE library target: " << libName; - this->SetError(e.str()); + status.SetError(e.str()); return false; } } // Make sure the target does not already exist. - if (this->Makefile->FindTargetToUse(libName)) { + if (mf.FindTargetToUse(libName)) { std::ostringstream e; e << "cannot create imported target \"" << libName << "\" because another target with the same name already exists."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } // Create the imported target. - this->Makefile->AddImportedTarget(libName, type, importGlobal); + mf.AddImportedTarget(libName, type, importGlobal); return true; } // A non-imported target may not have UNKNOWN type. if (type == cmStateEnums::UNKNOWN_LIBRARY) { - this->Makefile->IssueMessage( + mf.IssueMessage( MessageType::FATAL_ERROR, "The UNKNOWN library type may be used only for IMPORTED libraries."); return true; @@ -318,8 +314,8 @@ bool cmAddLibraryCommand::InitialPass(std::vector<std::string> const& args, // Enforce name uniqueness. { std::string msg; - if (!this->Makefile->EnforceUniqueName(libName, msg)) { - this->SetError(msg); + if (!mf.EnforceUniqueName(libName, msg)) { + status.SetError(msg); return false; } } @@ -331,17 +327,17 @@ bool cmAddLibraryCommand::InitialPass(std::vector<std::string> const& args, libName.find("::") != std::string::npos) { std::ostringstream e; e << "Invalid name for INTERFACE library target: " << libName; - this->SetError(e.str()); + status.SetError(e.str()); return false; } - this->Makefile->AddLibrary(libName, type, srclists, excludeFromAll); + mf.AddLibrary(libName, type, srclists, excludeFromAll); return true; } cmAppend(srclists, s, args.end()); - this->Makefile->AddLibrary(libName, type, srclists, excludeFromAll); + mf.AddLibrary(libName, type, srclists, excludeFromAll); return true; } diff --git a/Source/cmAddLibraryCommand.h b/Source/cmAddLibraryCommand.h index 56dab41..609449c 100644 --- a/Source/cmAddLibraryCommand.h +++ b/Source/cmAddLibraryCommand.h @@ -8,35 +8,9 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -/** \class cmLibrarysCommand - * \brief Defines a list of executables to build. - * - * cmLibrarysCommand defines a list of executable (i.e., test) - * programs to create. - */ -class cmAddLibraryCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmAddLibraryCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; -}; +bool cmAddLibraryCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmAddLinkOptionsCommand.cxx b/Source/cmAddLinkOptionsCommand.cxx index 10ebd12..7ed31bd 100644 --- a/Source/cmAddLinkOptionsCommand.cxx +++ b/Source/cmAddLinkOptionsCommand.cxx @@ -2,19 +2,15 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmAddLinkOptionsCommand.h" +#include "cmExecutionStatus.h" #include "cmMakefile.h" -class cmExecutionStatus; - -bool cmAddLinkOptionsCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus&) +bool cmAddLinkOptionsCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { - if (args.empty()) { - return true; - } - + cmMakefile& mf = status.GetMakefile(); for (std::string const& i : args) { - this->Makefile->AddLinkOption(i); + mf.AddLinkOption(i); } return true; } diff --git a/Source/cmAddLinkOptionsCommand.h b/Source/cmAddLinkOptionsCommand.h index 8e46be6..466fc32 100644 --- a/Source/cmAddLinkOptionsCommand.h +++ b/Source/cmAddLinkOptionsCommand.h @@ -8,29 +8,9 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -class cmAddLinkOptionsCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmAddLinkOptionsCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; -}; +bool cmAddLinkOptionsCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmAddSubDirectoryCommand.cxx b/Source/cmAddSubDirectoryCommand.cxx index 7947188..17bdc4a 100644 --- a/Source/cmAddSubDirectoryCommand.cxx +++ b/Source/cmAddSubDirectoryCommand.cxx @@ -5,21 +5,21 @@ #include <sstream> #include <string.h> +#include "cmExecutionStatus.h" #include "cmMakefile.h" #include "cmRange.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" -class cmExecutionStatus; - -// cmAddSubDirectoryCommand -bool cmAddSubDirectoryCommand::InitialPass( - std::vector<std::string> const& args, cmExecutionStatus&) +bool cmAddSubDirectoryCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.empty()) { - this->SetError("called with incorrect number of arguments"); + status.SetError("called with incorrect number of arguments"); return false; } + cmMakefile& mf = status.GetMakefile(); // store the binpath std::string const& srcArg = args.front(); std::string binArg; @@ -35,7 +35,7 @@ bool cmAddSubDirectoryCommand::InitialPass( if (binArg.empty()) { binArg = arg; } else { - this->SetError("called with incorrect number of arguments"); + status.SetError("called with incorrect number of arguments"); return false; } } @@ -46,15 +46,12 @@ bool cmAddSubDirectoryCommand::InitialPass( if (cmSystemTools::FileIsFullPath(srcArg)) { srcPath = srcArg; } else { - srcPath = this->Makefile->GetCurrentSourceDirectory(); - srcPath += "/"; - srcPath += srcArg; + srcPath = cmStrCat(mf.GetCurrentSourceDirectory(), '/', srcArg); } if (!cmSystemTools::FileIsDirectory(srcPath)) { - std::string error = "given source \""; - error += srcArg; - error += "\" which is not an existing directory."; - this->SetError(error); + std::string error = cmStrCat("given source \"", srcArg, + "\" which is not an existing directory."); + status.SetError(error); return false; } srcPath = cmSystemTools::CollapseFullPath(srcPath); @@ -65,22 +62,22 @@ bool cmAddSubDirectoryCommand::InitialPass( // No binary directory was specified. If the source directory is // not a subdirectory of the current directory then it is an // error. - if (!cmSystemTools::IsSubDirectory( - srcPath, this->Makefile->GetCurrentSourceDirectory())) { + if (!cmSystemTools::IsSubDirectory(srcPath, + mf.GetCurrentSourceDirectory())) { std::ostringstream e; e << "not given a binary directory but the given source directory " << "\"" << srcPath << "\" is not a subdirectory of \"" - << this->Makefile->GetCurrentSourceDirectory() << "\". " + << mf.GetCurrentSourceDirectory() << "\". " << "When specifying an out-of-tree source a binary directory " << "must be explicitly specified."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } // Remove the CurrentDirectory from the srcPath and replace it // with the CurrentOutputDirectory. - const std::string& src = this->Makefile->GetCurrentSourceDirectory(); - const std::string& bin = this->Makefile->GetCurrentBinaryDirectory(); + const std::string& src = mf.GetCurrentSourceDirectory(); + const std::string& bin = mf.GetCurrentBinaryDirectory(); size_t srcLen = src.length(); size_t binLen = bin.length(); if (srcLen > 0 && src.back() == '/') { @@ -96,15 +93,13 @@ bool cmAddSubDirectoryCommand::InitialPass( if (cmSystemTools::FileIsFullPath(binArg)) { binPath = binArg; } else { - binPath = this->Makefile->GetCurrentBinaryDirectory(); - binPath += "/"; - binPath += binArg; + binPath = cmStrCat(mf.GetCurrentBinaryDirectory(), '/', binArg); } } binPath = cmSystemTools::CollapseFullPath(binPath); // Add the subdirectory using the computed full paths. - this->Makefile->AddSubDirectory(srcPath, binPath, excludeFromAll, true); + mf.AddSubDirectory(srcPath, binPath, excludeFromAll, true); return true; } diff --git a/Source/cmAddSubDirectoryCommand.h b/Source/cmAddSubDirectoryCommand.h index 664334e..87da840 100644 --- a/Source/cmAddSubDirectoryCommand.h +++ b/Source/cmAddSubDirectoryCommand.h @@ -8,36 +8,9 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -/** \class cmAddSubDirectoryCommand - * \brief Specify a subdirectory to build - * - * cmAddSubDirectoryCommand specifies a subdirectory to process - * by CMake. CMake will descend - * into the specified source directory and process any CMakeLists.txt found. - */ -class cmAddSubDirectoryCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmAddSubDirectoryCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; -}; +bool cmAddSubDirectoryCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmAddTestCommand.cxx b/Source/cmAddTestCommand.cxx index b0c462b..7904bf5 100644 --- a/Source/cmAddTestCommand.cxx +++ b/Source/cmAddTestCommand.cxx @@ -4,34 +4,36 @@ #include <sstream> +#include "cmExecutionStatus.h" #include "cmMakefile.h" #include "cmTest.h" #include "cmTestGenerator.h" -class cmExecutionStatus; +static bool cmAddTestCommandHandleNameMode( + std::vector<std::string> const& args, cmExecutionStatus& status); -// cmExecutableCommand -bool cmAddTestCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus&) +bool cmAddTestCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (!args.empty() && args[0] == "NAME") { - return this->HandleNameMode(args); + return cmAddTestCommandHandleNameMode(args, status); } // First argument is the name of the test Second argument is the name of // the executable to run (a target or external program) Remaining arguments // are the arguments to pass to the executable if (args.size() < 2) { - this->SetError("called with incorrect number of arguments"); + status.SetError("called with incorrect number of arguments"); return false; } + cmMakefile& mf = status.GetMakefile(); // Collect the command with arguments. std::vector<std::string> command(args.begin() + 1, args.end()); // Create the test but add a generator only the first time it is // seen. This preserves behavior from before test generators. - cmTest* test = this->Makefile->GetTest(args[0]); + cmTest* test = mf.GetTest(args[0]); if (test) { // If the test was already added by a new-style signature do not // allow it to be duplicated. @@ -39,20 +41,21 @@ bool cmAddTestCommand::InitialPass(std::vector<std::string> const& args, std::ostringstream e; e << " given test name \"" << args[0] << "\" which already exists in this directory."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } } else { - test = this->Makefile->CreateTest(args[0]); + test = mf.CreateTest(args[0]); test->SetOldStyle(true); - this->Makefile->AddTestGenerator(new cmTestGenerator(test)); + mf.AddTestGenerator(new cmTestGenerator(test)); } test->SetCommand(command); return true; } -bool cmAddTestCommand::HandleNameMode(std::vector<std::string> const& args) +bool cmAddTestCommandHandleNameMode(std::vector<std::string> const& args, + cmExecutionStatus& status) { std::string name; std::vector<std::string> configurations; @@ -73,25 +76,25 @@ bool cmAddTestCommand::HandleNameMode(std::vector<std::string> const& args) for (unsigned int i = 1; i < args.size(); ++i) { if (args[i] == "COMMAND") { if (!command.empty()) { - this->SetError(" may be given at most one COMMAND."); + status.SetError(" may be given at most one COMMAND."); return false; } doing = DoingCommand; } else if (args[i] == "CONFIGURATIONS") { if (!configurations.empty()) { - this->SetError(" may be given at most one set of CONFIGURATIONS."); + status.SetError(" may be given at most one set of CONFIGURATIONS."); return false; } doing = DoingConfigs; } else if (args[i] == "WORKING_DIRECTORY") { if (!working_directory.empty()) { - this->SetError(" may be given at most one WORKING_DIRECTORY."); + status.SetError(" may be given at most one WORKING_DIRECTORY."); return false; } doing = DoingWorkingDirectory; } else if (args[i] == "COMMAND_EXPAND_LISTS") { if (command_expand_lists) { - this->SetError(" may be given at most one COMMAND_EXPAND_LISTS."); + status.SetError(" may be given at most one COMMAND_EXPAND_LISTS."); return false; } command_expand_lists = true; @@ -109,41 +112,43 @@ bool cmAddTestCommand::HandleNameMode(std::vector<std::string> const& args) } else { std::ostringstream e; e << " given unknown argument:\n " << args[i] << "\n"; - this->SetError(e.str()); + status.SetError(e.str()); return false; } } // Require a test name. if (name.empty()) { - this->SetError(" must be given non-empty NAME."); + status.SetError(" must be given non-empty NAME."); return false; } // Require a command. if (command.empty()) { - this->SetError(" must be given non-empty COMMAND."); + status.SetError(" must be given non-empty COMMAND."); return false; } + cmMakefile& mf = status.GetMakefile(); + // Require a unique test name within the directory. - if (this->Makefile->GetTest(name)) { + if (mf.GetTest(name)) { std::ostringstream e; e << " given test NAME \"" << name << "\" which already exists in this directory."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } // Add the test. - cmTest* test = this->Makefile->CreateTest(name); + cmTest* test = mf.CreateTest(name); test->SetOldStyle(false); test->SetCommand(command); if (!working_directory.empty()) { test->SetProperty("WORKING_DIRECTORY", working_directory.c_str()); } test->SetCommandExpandLists(command_expand_lists); - this->Makefile->AddTestGenerator(new cmTestGenerator(test, configurations)); + mf.AddTestGenerator(new cmTestGenerator(test, configurations)); return true; } diff --git a/Source/cmAddTestCommand.h b/Source/cmAddTestCommand.h index 3d37d2b..5877547 100644 --- a/Source/cmAddTestCommand.h +++ b/Source/cmAddTestCommand.h @@ -8,37 +8,9 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -/** \class cmAddTestCommand - * \brief Add a test to the lists of tests to run. - * - * cmAddTestCommand adds a test to the list of tests to run . - */ -class cmAddTestCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmAddTestCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; - -private: - bool HandleNameMode(std::vector<std::string> const& args); -}; +bool cmAddTestCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmAlgorithms.h b/Source/cmAlgorithms.h index d7ea483..59aa86f 100644 --- a/Source/cmAlgorithms.h +++ b/Source/cmAlgorithms.h @@ -14,6 +14,16 @@ #include <utility> #include <vector> +template <std::size_t N> +struct cmOverloadPriority : cmOverloadPriority<N - 1> +{ +}; + +template <> +struct cmOverloadPriority<0> +{ +}; + template <typename FwdIt> FwdIt cmRotate(FwdIt first, FwdIt middle, FwdIt last) { @@ -30,6 +40,34 @@ void cmEraseIf(Container& cont, Predicate pred) cont.erase(std::remove_if(cont.begin(), cont.end(), pred), cont.end()); } +template <typename Range, typename Key> +auto cmContainsImpl(Range const& range, Key const& key, cmOverloadPriority<2>) + -> decltype(range.exists(key)) +{ + return range.exists(key); +} + +template <typename Range, typename Key> +auto cmContainsImpl(Range const& range, Key const& key, cmOverloadPriority<1>) + -> decltype(range.find(key) != range.end()) +{ + return range.find(key) != range.end(); +} + +template <typename Range, typename Key> +bool cmContainsImpl(Range const& range, Key const& key, cmOverloadPriority<0>) +{ + using std::begin; + using std::end; + return std::find(begin(range), end(range), key) != end(range); +} + +template <typename Range, typename Key> +bool cmContains(Range const& range, Key const& key) +{ + return cmContainsImpl(range, key, cmOverloadPriority<2>{}); +} + namespace ContainerAlgorithms { template <typename T> @@ -176,7 +214,7 @@ ForwardIterator cmRemoveDuplicates(ForwardIterator first, ForwardIterator last) ForwardIterator result = first; while (first != last) { - if (uniq.find(first) == uniq.end()) { + if (!cmContains(uniq, first)) { if (result != first) { *result = std::move(*first); } diff --git a/Source/cmArchiveWrite.cxx b/Source/cmArchiveWrite.cxx index 359d57a..a063fd9 100644 --- a/Source/cmArchiveWrite.cxx +++ b/Source/cmArchiveWrite.cxx @@ -3,12 +3,14 @@ #include "cmArchiveWrite.h" #include "cmLocale.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cm_get_date.h" #include "cm_libarchive.h" #include "cmsys/Directory.hxx" #include "cmsys/Encoding.hxx" #include "cmsys/FStream.hxx" + #include <iostream> #include <sstream> #include <string.h> @@ -85,22 +87,22 @@ cmArchiveWrite::cmArchiveWrite(std::ostream& os, Compress c, switch (c) { case CompressNone: if (archive_write_add_filter_none(this->Archive) != ARCHIVE_OK) { - this->Error = "archive_write_add_filter_none: "; - this->Error += cm_archive_error_string(this->Archive); + this->Error = cmStrCat("archive_write_add_filter_none: ", + cm_archive_error_string(this->Archive)); return; } break; case CompressCompress: if (archive_write_add_filter_compress(this->Archive) != ARCHIVE_OK) { - this->Error = "archive_write_add_filter_compress: "; - this->Error += cm_archive_error_string(this->Archive); + this->Error = cmStrCat("archive_write_add_filter_compress: ", + cm_archive_error_string(this->Archive)); return; } break; case CompressGZip: { if (archive_write_add_filter_gzip(this->Archive) != ARCHIVE_OK) { - this->Error = "archive_write_add_filter_gzip: "; - this->Error += cm_archive_error_string(this->Archive); + this->Error = cmStrCat("archive_write_add_filter_gzip: ", + cm_archive_error_string(this->Archive)); return; } std::string source_date_epoch; @@ -110,60 +112,60 @@ cmArchiveWrite::cmArchiveWrite(std::ostream& os, Compress c, // The next best thing is to omit the timestamp entirely. if (archive_write_set_filter_option(this->Archive, "gzip", "timestamp", nullptr) != ARCHIVE_OK) { - this->Error = "archive_write_set_filter_option: "; - this->Error += cm_archive_error_string(this->Archive); + this->Error = cmStrCat("archive_write_set_filter_option: ", + cm_archive_error_string(this->Archive)); return; } } } break; case CompressBZip2: if (archive_write_add_filter_bzip2(this->Archive) != ARCHIVE_OK) { - this->Error = "archive_write_add_filter_bzip2: "; - this->Error += cm_archive_error_string(this->Archive); + this->Error = cmStrCat("archive_write_add_filter_bzip2: ", + cm_archive_error_string(this->Archive)); return; } break; case CompressLZMA: if (archive_write_add_filter_lzma(this->Archive) != ARCHIVE_OK) { - this->Error = "archive_write_add_filter_lzma: "; - this->Error += cm_archive_error_string(this->Archive); + this->Error = cmStrCat("archive_write_add_filter_lzma: ", + cm_archive_error_string(this->Archive)); return; } break; case CompressXZ: if (archive_write_add_filter_xz(this->Archive) != ARCHIVE_OK) { - this->Error = "archive_write_add_filter_xz: "; - this->Error += cm_archive_error_string(this->Archive); + this->Error = cmStrCat("archive_write_add_filter_xz: ", + cm_archive_error_string(this->Archive)); return; } break; case CompressZstd: if (archive_write_add_filter_zstd(this->Archive) != ARCHIVE_OK) { - this->Error = "archive_write_add_filter_zstd: "; - this->Error += cm_archive_error_string(this->Archive); + this->Error = cmStrCat("archive_write_add_filter_zstd: ", + cm_archive_error_string(this->Archive)); return; } break; } #if !defined(_WIN32) || defined(__CYGWIN__) if (archive_read_disk_set_standard_lookup(this->Disk) != ARCHIVE_OK) { - this->Error = "archive_read_disk_set_standard_lookup: "; - this->Error += cm_archive_error_string(this->Archive); + this->Error = cmStrCat("archive_read_disk_set_standard_lookup: ", + cm_archive_error_string(this->Archive)); return; } #endif if (archive_write_set_format_by_name(this->Archive, format.c_str()) != ARCHIVE_OK) { - this->Error = "archive_write_set_format_by_name: "; - this->Error += cm_archive_error_string(this->Archive); + this->Error = cmStrCat("archive_write_set_format_by_name: ", + cm_archive_error_string(this->Archive)); return; } // do not pad the last block!! if (archive_write_set_bytes_in_last_block(this->Archive, 1)) { - this->Error = "archive_write_set_bytes_in_last_block: "; - this->Error += cm_archive_error_string(this->Archive); + this->Error = cmStrCat("archive_write_set_bytes_in_last_block: ", + cm_archive_error_string(this->Archive)); return; } @@ -171,8 +173,8 @@ cmArchiveWrite::cmArchiveWrite(std::ostream& os, Compress c, this->Archive, this, nullptr, reinterpret_cast<archive_write_callback*>(&Callback::Write), nullptr) != ARCHIVE_OK) { - this->Error = "archive_write_open: "; - this->Error += cm_archive_error_string(this->Archive); + this->Error = + cmStrCat("archive_write_open: ", cm_archive_error_string(this->Archive)); return; } } @@ -205,8 +207,7 @@ bool cmArchiveWrite::AddPath(const char* path, size_t skip, const char* prefix, } cmsys::Directory d; if (d.Load(path)) { - std::string next = path; - next += "/"; + std::string next = cmStrCat(path, '/'); std::string::size_type end = next.size(); unsigned long n = d.GetNumberOfFiles(); for (unsigned long i = 0; i < n; ++i) { @@ -237,8 +238,7 @@ bool cmArchiveWrite::AddFile(const char* file, size_t skip, const char* prefix) static_cast<void>(localeRAII); // Meta-data. - std::string dest = prefix ? prefix : ""; - dest += out; + std::string dest = cmStrCat(prefix ? prefix : "", out); if (this->Verbose) { std::cout << dest << "\n"; } @@ -247,10 +247,8 @@ bool cmArchiveWrite::AddFile(const char* file, size_t skip, const char* prefix) cm_archive_entry_copy_pathname(e, dest); if (archive_read_disk_entry_from_file(this->Disk, e, -1, nullptr) != ARCHIVE_OK) { - this->Error = "Unable to read from file '"; - this->Error += file; - this->Error += "': "; - this->Error += cm_archive_error_string(this->Disk); + this->Error = cmStrCat("Unable to read from file '", file, + "': ", cm_archive_error_string(this->Disk)); return false; } if (!this->MTime.empty()) { @@ -258,9 +256,7 @@ bool cmArchiveWrite::AddFile(const char* file, size_t skip, const char* prefix) time(&now); time_t t = cm_get_date(now, this->MTime.c_str()); if (t == -1) { - this->Error = "unable to parse mtime '"; - this->Error += this->MTime; - this->Error += "'"; + this->Error = cmStrCat("unable to parse mtime '", this->MTime, '\''); return false; } archive_entry_set_mtime(e, t, 0); @@ -310,8 +306,8 @@ bool cmArchiveWrite::AddFile(const char* file, size_t skip, const char* prefix) } if (archive_write_header(this->Archive, e) != ARCHIVE_OK) { - this->Error = "archive_write_header: "; - this->Error += cm_archive_error_string(this->Archive); + this->Error = cmStrCat("archive_write_header: ", + cm_archive_error_string(this->Archive)); return false; } @@ -329,10 +325,8 @@ bool cmArchiveWrite::AddData(const char* file, size_t size) { cmsys::ifstream fin(file, std::ios::in | std::ios::binary); if (!fin) { - this->Error = "Error opening \""; - this->Error += file; - this->Error += "\": "; - this->Error += cmSystemTools::GetLastSystemError(); + this->Error = cmStrCat("Error opening \"", file, + "\": ", cmSystemTools::GetLastSystemError()); return false; } @@ -350,17 +344,15 @@ bool cmArchiveWrite::AddData(const char* file, size_t size) break; } if (archive_write_data(this->Archive, buffer, nnext) != nnext_s) { - this->Error = "archive_write_data: "; - this->Error += cm_archive_error_string(this->Archive); + this->Error = cmStrCat("archive_write_data: ", + cm_archive_error_string(this->Archive)); return false; } nleft -= nnext; } if (nleft > 0) { - this->Error = "Error reading \""; - this->Error += file; - this->Error += "\": "; - this->Error += cmSystemTools::GetLastSystemError(); + this->Error = cmStrCat("Error reading \"", file, + "\": ", cmSystemTools::GetLastSystemError()); return false; } return true; diff --git a/Source/cmArchiveWrite.h b/Source/cmArchiveWrite.h index 9ea88d3..e90a603 100644 --- a/Source/cmArchiveWrite.h +++ b/Source/cmArchiveWrite.h @@ -9,7 +9,7 @@ #include <stddef.h> #include <string> -#if !defined(CMAKE_BUILD_WITH_CMAKE) +#if defined(CMAKE_BOOTSTRAP) # error "cmArchiveWrite not allowed during bootstrap build!" #endif diff --git a/Source/cmAuxSourceDirectoryCommand.cxx b/Source/cmAuxSourceDirectoryCommand.cxx index 45c6411..7bf19d0 100644 --- a/Source/cmAuxSourceDirectoryCommand.cxx +++ b/Source/cmAuxSourceDirectoryCommand.cxx @@ -7,36 +7,33 @@ #include <stddef.h> #include <utility> +#include "cmExecutionStatus.h" #include "cmMakefile.h" #include "cmSourceFile.h" #include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmake.h" -class cmExecutionStatus; - -// cmAuxSourceDirectoryCommand -bool cmAuxSourceDirectoryCommand::InitialPass( - std::vector<std::string> const& args, cmExecutionStatus&) +bool cmAuxSourceDirectoryCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() != 2) { - this->SetError("called with incorrect number of arguments"); + status.SetError("called with incorrect number of arguments"); return false; } + cmMakefile& mf = status.GetMakefile(); std::string sourceListValue; std::string const& templateDirectory = args[0]; std::string tdir; if (!cmSystemTools::FileIsFullPath(templateDirectory)) { - tdir = this->Makefile->GetCurrentSourceDirectory(); - tdir += "/"; - tdir += templateDirectory; + tdir = cmStrCat(mf.GetCurrentSourceDirectory(), '/', templateDirectory); } else { tdir = templateDirectory; } // was the list already populated - const char* def = this->Makefile->GetDefinition(args[1]); + const char* def = mf.GetDefinition(args[1]); if (def) { sourceListValue = def; } @@ -55,14 +52,12 @@ bool cmAuxSourceDirectoryCommand::InitialPass( std::string ext = file.substr(dotpos + 1); std::string base = file.substr(0, dotpos); // Process only source files - auto cm = this->Makefile->GetCMakeInstance(); + auto cm = mf.GetCMakeInstance(); if (!base.empty() && cm->IsSourceExtension(ext)) { - std::string fullname = templateDirectory; - fullname += "/"; - fullname += file; + std::string fullname = cmStrCat(templateDirectory, '/', file); // add the file as a class file so // depends can be done - cmSourceFile* sf = this->Makefile->GetOrCreateSource(fullname); + cmSourceFile* sf = mf.GetOrCreateSource(fullname); sf->SetProperty("ABSTRACT", "0"); files.push_back(std::move(fullname)); } @@ -74,6 +69,6 @@ bool cmAuxSourceDirectoryCommand::InitialPass( sourceListValue += ";"; } sourceListValue += cmJoin(files, ";"); - this->Makefile->AddDefinition(args[1], sourceListValue); + mf.AddDefinition(args[1], sourceListValue); return true; } diff --git a/Source/cmAuxSourceDirectoryCommand.h b/Source/cmAuxSourceDirectoryCommand.h index 973a464..ae26092 100644 --- a/Source/cmAuxSourceDirectoryCommand.h +++ b/Source/cmAuxSourceDirectoryCommand.h @@ -8,38 +8,9 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -/** \class cmAuxSourceDirectoryCommand - * \brief Specify auxiliary source code directories. - * - * cmAuxSourceDirectoryCommand specifies source code directories - * that must be built as part of this build process. This directories - * are not recursively processed like the SUBDIR command (cmSubdirCommand). - * A side effect of this command is to create a subdirectory in the build - * directory structure. - */ -class cmAuxSourceDirectoryCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmAuxSourceDirectoryCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; -}; +bool cmAuxSourceDirectoryCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmBinUtilsLinuxELFLinker.cxx b/Source/cmBinUtilsLinuxELFLinker.cxx index 86846cb..6316a29 100644 --- a/Source/cmBinUtilsLinuxELFLinker.cxx +++ b/Source/cmBinUtilsLinuxELFLinker.cxx @@ -8,6 +8,7 @@ #include "cmMakefile.h" #include "cmMessageType.h" #include "cmRuntimeDependencyArchive.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include <cmsys/RegularExpression.hxx> @@ -151,7 +152,7 @@ bool cmBinUtilsLinuxELFLinker::ResolveDependency( std::string& path, bool& resolved) { for (auto const& searchPath : searchPaths) { - path = searchPath + '/' + name; + path = cmStrCat(searchPath, '/', name); if (cmSystemTools::PathExists(path)) { resolved = true; return true; @@ -159,7 +160,7 @@ bool cmBinUtilsLinuxELFLinker::ResolveDependency( } for (auto const& searchPath : this->Archive->GetSearchDirectories()) { - path = searchPath + '/' + name; + path = cmStrCat(searchPath, '/', name); if (cmSystemTools::PathExists(path)) { std::ostringstream warning; warning << "Dependency " << name << " found in search directory:\n " diff --git a/Source/cmBinUtilsMacOSMachOLinker.cxx b/Source/cmBinUtilsMacOSMachOLinker.cxx index 0c73ac8..7ff8584 100644 --- a/Source/cmBinUtilsMacOSMachOLinker.cxx +++ b/Source/cmBinUtilsMacOSMachOLinker.cxx @@ -59,7 +59,8 @@ bool cmBinUtilsMacOSMachOLinker::ScanDependencies( bool cmBinUtilsMacOSMachOLinker::ScanDependencies( std::string const& file, std::string const& executablePath) { - std::vector<std::string> libs, rpaths; + std::vector<std::string> libs; + std::vector<std::string> rpaths; if (!this->Tool->GetFileInfo(file, libs, rpaths)) { return false; } diff --git a/Source/cmBinUtilsWindowsPELinker.cxx b/Source/cmBinUtilsWindowsPELinker.cxx index 31602c4..5a9ad66 100644 --- a/Source/cmBinUtilsWindowsPELinker.cxx +++ b/Source/cmBinUtilsWindowsPELinker.cxx @@ -6,6 +6,7 @@ #include "cmBinUtilsWindowsPEDumpbinGetRuntimeDependenciesTool.h" #include "cmBinUtilsWindowsPEObjdumpGetRuntimeDependenciesTool.h" #include "cmRuntimeDependencyArchive.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include <sstream> @@ -110,7 +111,7 @@ bool cmBinUtilsWindowsPELinker::ResolveDependency(std::string const& name, dirs.insert(dirs.begin(), origin); for (auto const& searchPath : dirs) { - path = searchPath + '/' + name; + path = cmStrCat(searchPath, '/', name); if (cmSystemTools::PathExists(path)) { resolved = true; return true; diff --git a/Source/cmBreakCommand.cxx b/Source/cmBreakCommand.cxx index d07898f..95db689 100644 --- a/Source/cmBreakCommand.cxx +++ b/Source/cmBreakCommand.cxx @@ -10,14 +10,14 @@ #include "cmPolicies.h" // cmBreakCommand -bool cmBreakCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) +bool cmBreakCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { - if (!this->Makefile->IsLoopBlock()) { + if (!status.GetMakefile().IsLoopBlock()) { bool issueMessage = true; std::ostringstream e; MessageType messageType = MessageType::AUTHOR_WARNING; - switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0055)) { + switch (status.GetMakefile().GetPolicyStatus(cmPolicies::CMP0055)) { case cmPolicies::WARN: e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0055) << "\n"; break; @@ -34,7 +34,7 @@ bool cmBreakCommand::InitialPass(std::vector<std::string> const& args, if (issueMessage) { e << "A BREAK command was found outside of a proper " "FOREACH or WHILE loop scope."; - this->Makefile->IssueMessage(messageType, e.str()); + status.GetMakefile().IssueMessage(messageType, e.str()); if (messageType == MessageType::FATAL_ERROR) { return false; } @@ -47,7 +47,7 @@ bool cmBreakCommand::InitialPass(std::vector<std::string> const& args, bool issueMessage = true; std::ostringstream e; MessageType messageType = MessageType::AUTHOR_WARNING; - switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0055)) { + switch (status.GetMakefile().GetPolicyStatus(cmPolicies::CMP0055)) { case cmPolicies::WARN: e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0055) << "\n"; break; @@ -63,7 +63,7 @@ bool cmBreakCommand::InitialPass(std::vector<std::string> const& args, if (issueMessage) { e << "The BREAK command does not accept any arguments."; - this->Makefile->IssueMessage(messageType, e.str()); + status.GetMakefile().IssueMessage(messageType, e.str()); if (messageType == MessageType::FATAL_ERROR) { return false; } diff --git a/Source/cmBreakCommand.h b/Source/cmBreakCommand.h index e6f218e..e6ce6fe 100644 --- a/Source/cmBreakCommand.h +++ b/Source/cmBreakCommand.h @@ -8,34 +8,14 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -/** \class cmBreakCommand +/** * \brief Break from an enclosing foreach or while loop * * cmBreakCommand returns from an enclosing foreach or while loop */ -class cmBreakCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmBreakCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; -}; +bool cmBreakCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmBuildNameCommand.cxx b/Source/cmBuildNameCommand.cxx index ddff686..df94f1d 100644 --- a/Source/cmBuildNameCommand.cxx +++ b/Source/cmBuildNameCommand.cxx @@ -5,21 +5,20 @@ #include "cmsys/RegularExpression.hxx" #include <algorithm> +#include "cmExecutionStatus.h" #include "cmMakefile.h" #include "cmStateTypes.h" #include "cmSystemTools.h" -class cmExecutionStatus; - -// cmBuildNameCommand -bool cmBuildNameCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus&) +bool cmBuildNameCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.empty()) { - this->SetError("called with incorrect number of arguments"); + status.SetError("called with incorrect number of arguments"); return false; } - const char* cacheValue = this->Makefile->GetDefinition(args[0]); + cmMakefile& mf = status.GetMakefile(); + const char* cacheValue = mf.GetDefinition(args[0]); if (cacheValue) { // do we need to correct the value? cmsys::RegularExpression reg("[()/]"); @@ -28,14 +27,14 @@ bool cmBuildNameCommand::InitialPass(std::vector<std::string> const& args, std::replace(cv.begin(), cv.end(), '/', '_'); std::replace(cv.begin(), cv.end(), '(', '_'); std::replace(cv.begin(), cv.end(), ')', '_'); - this->Makefile->AddCacheDefinition(args[0], cv.c_str(), "Name of build.", - cmStateEnums::STRING); + mf.AddCacheDefinition(args[0], cv.c_str(), "Name of build.", + cmStateEnums::STRING); } return true; } std::string buildname = "WinNT"; - if (this->Makefile->GetDefinition("UNIX")) { + if (mf.GetDefinition("UNIX")) { buildname.clear(); cmSystemTools::RunSingleCommand("uname -a", &buildname, &buildname); if (!buildname.empty()) { @@ -47,14 +46,14 @@ bool cmBuildNameCommand::InitialPass(std::vector<std::string> const& args, } } std::string compiler = "${CMAKE_CXX_COMPILER}"; - this->Makefile->ExpandVariablesInString(compiler); + mf.ExpandVariablesInString(compiler); buildname += "-"; buildname += cmSystemTools::GetFilenameName(compiler); std::replace(buildname.begin(), buildname.end(), '/', '_'); std::replace(buildname.begin(), buildname.end(), '(', '_'); std::replace(buildname.begin(), buildname.end(), ')', '_'); - this->Makefile->AddCacheDefinition(args[0], buildname.c_str(), - "Name of build.", cmStateEnums::STRING); + mf.AddCacheDefinition(args[0], buildname.c_str(), "Name of build.", + cmStateEnums::STRING); return true; } diff --git a/Source/cmBuildNameCommand.h b/Source/cmBuildNameCommand.h index bd2d146..37a7268 100644 --- a/Source/cmBuildNameCommand.h +++ b/Source/cmBuildNameCommand.h @@ -8,21 +8,9 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -class cmBuildNameCommand : public cmCommand -{ -public: - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmBuildNameCommand>(); - } - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; -}; +bool cmBuildNameCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmCMakeHostSystemInformationCommand.cxx b/Source/cmCMakeHostSystemInformationCommand.cxx index b4cd2a5..1669853 100644 --- a/Source/cmCMakeHostSystemInformationCommand.cxx +++ b/Source/cmCMakeHostSystemInformationCommand.cxx @@ -3,7 +3,9 @@ #include "cmCMakeHostSystemInformationCommand.h" #include <sstream> +#include <stddef.h> +#include "cmExecutionStatus.h" #include "cmMakefile.h" #include "cmsys/SystemInformation.hxx" @@ -16,16 +18,22 @@ # define HAVE_VS_SETUP_HELPER #endif -class cmExecutionStatus; +namespace { +bool GetValue(cmExecutionStatus& status, cmsys::SystemInformation& info, + std::string const& key, std::string& value); +std::string ValueToString(size_t value); +std::string ValueToString(const char* value); +std::string ValueToString(std::string const& value); +} // cmCMakeHostSystemInformation -bool cmCMakeHostSystemInformationCommand::InitialPass( - std::vector<std::string> const& args, cmExecutionStatus&) +bool cmCMakeHostSystemInformationCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { size_t current_index = 0; if (args.size() < (current_index + 2) || args[current_index] != "RESULT") { - this->SetError("missing RESULT specification."); + status.SetError("missing RESULT specification."); return false; } @@ -33,7 +41,7 @@ bool cmCMakeHostSystemInformationCommand::InitialPass( current_index += 2; if (args.size() < (current_index + 2) || args[current_index] != "QUERY") { - this->SetError("missing QUERY specification"); + status.SetError("missing QUERY specification"); return false; } @@ -49,89 +57,91 @@ bool cmCMakeHostSystemInformationCommand::InitialPass( result_list += ";"; } std::string value; - if (!this->GetValue(info, key, value)) { + if (!GetValue(status, info, key, value)) { return false; } result_list += value; } - this->Makefile->AddDefinition(variable, result_list); + status.GetMakefile().AddDefinition(variable, result_list); return true; } -bool cmCMakeHostSystemInformationCommand::GetValue( - cmsys::SystemInformation& info, std::string const& key, std::string& value) +namespace { + +bool GetValue(cmExecutionStatus& status, cmsys::SystemInformation& info, + std::string const& key, std::string& value) { if (key == "NUMBER_OF_LOGICAL_CORES") { - value = this->ValueToString(info.GetNumberOfLogicalCPU()); + value = ValueToString(info.GetNumberOfLogicalCPU()); } else if (key == "NUMBER_OF_PHYSICAL_CORES") { - value = this->ValueToString(info.GetNumberOfPhysicalCPU()); + value = ValueToString(info.GetNumberOfPhysicalCPU()); } else if (key == "HOSTNAME") { - value = this->ValueToString(info.GetHostname()); + value = ValueToString(info.GetHostname()); } else if (key == "FQDN") { - value = this->ValueToString(info.GetFullyQualifiedDomainName()); + value = ValueToString(info.GetFullyQualifiedDomainName()); } else if (key == "TOTAL_VIRTUAL_MEMORY") { - value = this->ValueToString(info.GetTotalVirtualMemory()); + value = ValueToString(info.GetTotalVirtualMemory()); } else if (key == "AVAILABLE_VIRTUAL_MEMORY") { - value = this->ValueToString(info.GetAvailableVirtualMemory()); + value = ValueToString(info.GetAvailableVirtualMemory()); } else if (key == "TOTAL_PHYSICAL_MEMORY") { - value = this->ValueToString(info.GetTotalPhysicalMemory()); + value = ValueToString(info.GetTotalPhysicalMemory()); } else if (key == "AVAILABLE_PHYSICAL_MEMORY") { - value = this->ValueToString(info.GetAvailablePhysicalMemory()); + value = ValueToString(info.GetAvailablePhysicalMemory()); } else if (key == "IS_64BIT") { - value = this->ValueToString(info.Is64Bits()); + value = ValueToString(info.Is64Bits()); } else if (key == "HAS_FPU") { - value = this->ValueToString( + value = ValueToString( info.DoesCPUSupportFeature(cmsys::SystemInformation::CPU_FEATURE_FPU)); } else if (key == "HAS_MMX") { - value = this->ValueToString( + value = ValueToString( info.DoesCPUSupportFeature(cmsys::SystemInformation::CPU_FEATURE_MMX)); } else if (key == "HAS_MMX_PLUS") { - value = this->ValueToString(info.DoesCPUSupportFeature( + value = ValueToString(info.DoesCPUSupportFeature( cmsys::SystemInformation::CPU_FEATURE_MMX_PLUS)); } else if (key == "HAS_SSE") { - value = this->ValueToString( + value = ValueToString( info.DoesCPUSupportFeature(cmsys::SystemInformation::CPU_FEATURE_SSE)); } else if (key == "HAS_SSE2") { - value = this->ValueToString( + value = ValueToString( info.DoesCPUSupportFeature(cmsys::SystemInformation::CPU_FEATURE_SSE2)); } else if (key == "HAS_SSE_FP") { - value = this->ValueToString(info.DoesCPUSupportFeature( + value = ValueToString(info.DoesCPUSupportFeature( cmsys::SystemInformation::CPU_FEATURE_SSE_FP)); } else if (key == "HAS_SSE_MMX") { - value = this->ValueToString(info.DoesCPUSupportFeature( + value = ValueToString(info.DoesCPUSupportFeature( cmsys::SystemInformation::CPU_FEATURE_SSE_MMX)); } else if (key == "HAS_AMD_3DNOW") { - value = this->ValueToString(info.DoesCPUSupportFeature( + value = ValueToString(info.DoesCPUSupportFeature( cmsys::SystemInformation::CPU_FEATURE_AMD_3DNOW)); } else if (key == "HAS_AMD_3DNOW_PLUS") { - value = this->ValueToString(info.DoesCPUSupportFeature( + value = ValueToString(info.DoesCPUSupportFeature( cmsys::SystemInformation::CPU_FEATURE_AMD_3DNOW_PLUS)); } else if (key == "HAS_IA64") { - value = this->ValueToString( + value = ValueToString( info.DoesCPUSupportFeature(cmsys::SystemInformation::CPU_FEATURE_IA64)); } else if (key == "HAS_SERIAL_NUMBER") { - value = this->ValueToString(info.DoesCPUSupportFeature( + value = ValueToString(info.DoesCPUSupportFeature( cmsys::SystemInformation::CPU_FEATURE_SERIALNUMBER)); } else if (key == "PROCESSOR_NAME") { - value = this->ValueToString(info.GetExtendedProcessorName()); + value = ValueToString(info.GetExtendedProcessorName()); } else if (key == "PROCESSOR_DESCRIPTION") { value = info.GetCPUDescription(); } else if (key == "PROCESSOR_SERIAL_NUMBER") { - value = this->ValueToString(info.GetProcessorSerialNumber()); + value = ValueToString(info.GetProcessorSerialNumber()); } else if (key == "OS_NAME") { - value = this->ValueToString(info.GetOSName()); + value = ValueToString(info.GetOSName()); } else if (key == "OS_RELEASE") { - value = this->ValueToString(info.GetOSRelease()); + value = ValueToString(info.GetOSRelease()); } else if (key == "OS_VERSION") { - value = this->ValueToString(info.GetOSVersion()); + value = ValueToString(info.GetOSVersion()); } else if (key == "OS_PLATFORM") { - value = this->ValueToString(info.GetOSPlatform()); + value = ValueToString(info.GetOSPlatform()); #ifdef HAVE_VS_SETUP_HELPER } else if (key == "VS_15_DIR") { // If generating for the VS 15 IDE, use the same instance. - cmGlobalGenerator* gg = this->Makefile->GetGlobalGenerator(); + cmGlobalGenerator* gg = status.GetMakefile().GetGlobalGenerator(); if (cmHasLiteralPrefix(gg->GetName(), "Visual Studio 15 ")) { cmGlobalVisualStudioVersionedGenerator* vs15gen = static_cast<cmGlobalVisualStudioVersionedGenerator*>(gg); @@ -147,7 +157,7 @@ bool cmCMakeHostSystemInformationCommand::GetValue( } } else if (key == "VS_16_DIR") { // If generating for the VS 16 IDE, use the same instance. - cmGlobalGenerator* gg = this->Makefile->GetGlobalGenerator(); + cmGlobalGenerator* gg = status.GetMakefile().GetGlobalGenerator(); if (cmHasLiteralPrefix(gg->GetName(), "Visual Studio 16 ")) { cmGlobalVisualStudioVersionedGenerator* vs16gen = static_cast<cmGlobalVisualStudioVersionedGenerator*>(gg); @@ -164,30 +174,28 @@ bool cmCMakeHostSystemInformationCommand::GetValue( #endif } else { std::string e = "does not recognize <key> " + key; - this->SetError(e); + status.SetError(e); return false; } return true; } -std::string cmCMakeHostSystemInformationCommand::ValueToString( - size_t value) const +std::string ValueToString(size_t value) { std::ostringstream tmp; tmp << value; return tmp.str(); } -std::string cmCMakeHostSystemInformationCommand::ValueToString( - const char* value) const +std::string ValueToString(const char* value) { std::string safe_string = value ? value : ""; return safe_string; } -std::string cmCMakeHostSystemInformationCommand::ValueToString( - std::string const& value) const +std::string ValueToString(std::string const& value) { return value; } +} diff --git a/Source/cmCMakeHostSystemInformationCommand.h b/Source/cmCMakeHostSystemInformationCommand.h index 8ea2d55..79e3f27 100644 --- a/Source/cmCMakeHostSystemInformationCommand.h +++ b/Source/cmCMakeHostSystemInformationCommand.h @@ -5,50 +5,18 @@ #include "cmConfigure.h" // IWYU pragma: keep -#include <stddef.h> #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -namespace cmsys { -class SystemInformation; -} // namespace cmsys -/** \class cmCMakeHostSystemInformationCommand +/** * \brief Query host system specific information * * cmCMakeHostSystemInformationCommand queries system information of * the system on which CMake runs. */ -class cmCMakeHostSystemInformationCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmCMakeHostSystemInformationCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; - -private: - bool GetValue(cmsys::SystemInformation& info, std::string const& key, - std::string& value); - - std::string ValueToString(size_t value) const; - std::string ValueToString(const char* value) const; - std::string ValueToString(std::string const& value) const; -}; +bool cmCMakeHostSystemInformationCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmCMakeMinimumRequired.cxx b/Source/cmCMakeMinimumRequired.cxx index f2eae38..f93c266 100644 --- a/Source/cmCMakeMinimumRequired.cxx +++ b/Source/cmCMakeMinimumRequired.cxx @@ -5,26 +5,32 @@ #include <sstream> #include <stdio.h> +#include "cmExecutionStatus.h" #include "cmMakefile.h" #include "cmMessageType.h" #include "cmSystemTools.h" #include "cmVersion.h" -class cmExecutionStatus; +namespace { +bool EnforceUnknownArguments(std::string const& version_max, + std::vector<std::string> const& unknown_arguments, + cmExecutionStatus& status); +} // cmCMakeMinimumRequired -bool cmCMakeMinimumRequired::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus&) +bool cmCMakeMinimumRequired(std::vector<std::string> const& args, + cmExecutionStatus& status) { // Process arguments. std::string version_string; bool doing_version = false; + std::vector<std::string> unknown_arguments; for (std::string const& arg : args) { if (arg == "VERSION") { doing_version = true; } else if (arg == "FATAL_ERROR") { if (doing_version) { - this->SetError("called with no value for VERSION."); + status.SetError("called with no value for VERSION."); return false; } doing_version = false; @@ -32,17 +38,17 @@ bool cmCMakeMinimumRequired::InitialPass(std::vector<std::string> const& args, doing_version = false; version_string = arg; } else { - this->UnknownArguments.push_back(arg); + unknown_arguments.push_back(arg); } } if (doing_version) { - this->SetError("called with no value for VERSION."); + status.SetError("called with no value for VERSION."); return false; } // Make sure there was a version to check. if (version_string.empty()) { - return this->EnforceUnknownArguments(std::string()); + return EnforceUnknownArguments(std::string(), unknown_arguments, status); } // Separate the <min> version and any trailing ...<max> component. @@ -56,12 +62,13 @@ bool cmCMakeMinimumRequired::InitialPass(std::vector<std::string> const& args, std::ostringstream e; e << "VERSION \"" << version_string << R"(" does not have a version on both sides of "...".)"; - this->SetError(e.str()); + status.SetError(e.str()); return false; } // Save the required version string. - this->Makefile->AddDefinition("CMAKE_MINIMUM_REQUIRED_VERSION", version_min); + status.GetMakefile().AddDefinition("CMAKE_MINIMUM_REQUIRED_VERSION", + version_min); // Get the current version number. unsigned int current_major = cmVersion::GetMajorVersion(); @@ -79,7 +86,7 @@ bool cmCMakeMinimumRequired::InitialPass(std::vector<std::string> const& args, &required_minor, &required_patch, &required_tweak) < 2) { std::ostringstream e; e << "could not parse VERSION \"" << version_min << "\"."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } @@ -95,32 +102,34 @@ bool cmCMakeMinimumRequired::InitialPass(std::vector<std::string> const& args, e << "CMake " << version_min << " or higher is required. You are running version " << cmVersion::GetCMakeVersion(); - this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str()); + status.GetMakefile().IssueMessage(MessageType::FATAL_ERROR, e.str()); cmSystemTools::SetFatalErrorOccured(); return true; } // The version is not from the future, so enforce unknown arguments. - if (!this->EnforceUnknownArguments(version_max)) { + if (!EnforceUnknownArguments(version_max, unknown_arguments, status)) { return false; } if (required_major < 2 || (required_major == 2 && required_minor < 4)) { - this->Makefile->IssueMessage( + status.GetMakefile().IssueMessage( MessageType::AUTHOR_WARNING, "Compatibility with CMake < 2.4 is not supported by CMake >= 3.0."); - this->Makefile->SetPolicyVersion("2.4", version_max); + status.GetMakefile().SetPolicyVersion("2.4", version_max); } else { - this->Makefile->SetPolicyVersion(version_min, version_max); + status.GetMakefile().SetPolicyVersion(version_min, version_max); } return true; } -bool cmCMakeMinimumRequired::EnforceUnknownArguments( - std::string const& version_max) +namespace { +bool EnforceUnknownArguments(std::string const& version_max, + std::vector<std::string> const& unknown_arguments, + cmExecutionStatus& status) { - if (this->UnknownArguments.empty()) { + if (unknown_arguments.empty()) { return true; } @@ -149,7 +158,8 @@ bool cmCMakeMinimumRequired::EnforceUnknownArguments( } std::ostringstream e; - e << "called with unknown argument \"" << this->UnknownArguments[0] << "\"."; - this->SetError(e.str()); + e << "called with unknown argument \"" << unknown_arguments[0] << "\"."; + status.SetError(e.str()); return false; } +} diff --git a/Source/cmCMakeMinimumRequired.h b/Source/cmCMakeMinimumRequired.h index 3881133..53f78f6 100644 --- a/Source/cmCMakeMinimumRequired.h +++ b/Source/cmCMakeMinimumRequired.h @@ -8,38 +8,14 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -/** \class cmCMakeMinimumRequired +/** * \brief cmake_minimum_required command * * cmCMakeMinimumRequired implements the cmake_minimum_required CMake command */ -class cmCMakeMinimumRequired : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmCMakeMinimumRequired>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; - -private: - std::vector<std::string> UnknownArguments; - bool EnforceUnknownArguments(std::string const& version_max); -}; +bool cmCMakeMinimumRequired(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmCMakePolicyCommand.cxx b/Source/cmCMakePolicyCommand.cxx index ce046fc..9b1aea9 100644 --- a/Source/cmCMakePolicyCommand.cxx +++ b/Source/cmCMakePolicyCommand.cxx @@ -4,88 +4,101 @@ #include <sstream> +#include "cmExecutionStatus.h" #include "cmMakefile.h" #include "cmMessageType.h" #include "cmPolicies.h" #include "cmState.h" #include "cmStateTypes.h" -class cmExecutionStatus; +namespace { +bool HandleSetMode(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool HandleGetMode(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool HandleVersionMode(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool HandleGetWarningMode(std::vector<std::string> const& args, + cmExecutionStatus& status); +} // cmCMakePolicyCommand -bool cmCMakePolicyCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus&) +bool cmCMakePolicyCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.empty()) { - this->SetError("requires at least one argument."); + status.SetError("requires at least one argument."); return false; } if (args[0] == "SET") { - return this->HandleSetMode(args); + return HandleSetMode(args, status); } if (args[0] == "GET") { - return this->HandleGetMode(args); + return HandleGetMode(args, status); } if (args[0] == "PUSH") { if (args.size() > 1) { - this->SetError("PUSH may not be given additional arguments."); + status.SetError("PUSH may not be given additional arguments."); return false; } - this->Makefile->PushPolicy(); + status.GetMakefile().PushPolicy(); return true; } if (args[0] == "POP") { if (args.size() > 1) { - this->SetError("POP may not be given additional arguments."); + status.SetError("POP may not be given additional arguments."); return false; } - this->Makefile->PopPolicy(); + status.GetMakefile().PopPolicy(); return true; } if (args[0] == "VERSION") { - return this->HandleVersionMode(args); + return HandleVersionMode(args, status); } if (args[0] == "GET_WARNING") { - return this->HandleGetWarningMode(args); + return HandleGetWarningMode(args, status); } std::ostringstream e; e << "given unknown first argument \"" << args[0] << "\""; - this->SetError(e.str()); + status.SetError(e.str()); return false; } -bool cmCMakePolicyCommand::HandleSetMode(std::vector<std::string> const& args) +namespace { + +bool HandleSetMode(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() != 3) { - this->SetError("SET must be given exactly 2 additional arguments."); + status.SetError("SET must be given exactly 2 additional arguments."); return false; } - cmPolicies::PolicyStatus status; + cmPolicies::PolicyStatus policyStatus; if (args[2] == "OLD") { - status = cmPolicies::OLD; + policyStatus = cmPolicies::OLD; } else if (args[2] == "NEW") { - status = cmPolicies::NEW; + policyStatus = cmPolicies::NEW; } else { std::ostringstream e; e << "SET given unrecognized policy status \"" << args[2] << "\""; - this->SetError(e.str()); + status.SetError(e.str()); return false; } - if (!this->Makefile->SetPolicy(args[1].c_str(), status)) { - this->SetError("SET failed to set policy."); + if (!status.GetMakefile().SetPolicy(args[1].c_str(), policyStatus)) { + status.SetError("SET failed to set policy."); return false; } if (args[1] == "CMP0001" && - (status == cmPolicies::WARN || status == cmPolicies::OLD)) { - if (!(this->Makefile->GetState()->GetInitializedCacheValue( + (policyStatus == cmPolicies::WARN || policyStatus == cmPolicies::OLD)) { + if (!(status.GetMakefile().GetState()->GetInitializedCacheValue( "CMAKE_BACKWARDS_COMPATIBILITY"))) { // Set it to 2.4 because that is the last version where the // variable had meaning. - this->Makefile->AddCacheDefinition( + status.GetMakefile().AddCacheDefinition( "CMAKE_BACKWARDS_COMPATIBILITY", "2.4", "For backwards compatibility, what version of CMake " "commands and " @@ -96,14 +109,15 @@ bool cmCMakePolicyCommand::HandleSetMode(std::vector<std::string> const& args) return true; } -bool cmCMakePolicyCommand::HandleGetMode(std::vector<std::string> const& args) +bool HandleGetMode(std::vector<std::string> const& args, + cmExecutionStatus& status) { bool parent_scope = false; if (args.size() == 4 && args[3] == "PARENT_SCOPE") { // Undocumented PARENT_SCOPE option for use within CMake. parent_scope = true; } else if (args.size() != 3) { - this->SetError("GET must be given exactly 2 additional arguments."); + status.SetError("GET must be given exactly 2 additional arguments."); return false; } @@ -117,25 +131,25 @@ bool cmCMakePolicyCommand::HandleGetMode(std::vector<std::string> const& args) std::ostringstream e; e << "GET given policy \"" << id << "\" which is not known to this " << "version of CMake."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } // Lookup the policy setting. - cmPolicies::PolicyStatus status = - this->Makefile->GetPolicyStatus(pid, parent_scope); - switch (status) { + cmPolicies::PolicyStatus policyStatus = + status.GetMakefile().GetPolicyStatus(pid, parent_scope); + switch (policyStatus) { case cmPolicies::OLD: // Report that the policy is set to OLD. - this->Makefile->AddDefinition(var, "OLD"); + status.GetMakefile().AddDefinition(var, "OLD"); break; case cmPolicies::WARN: // Report that the policy is not set. - this->Makefile->AddDefinition(var, ""); + status.GetMakefile().AddDefinition(var, ""); break; case cmPolicies::NEW: // Report that the policy is set to NEW. - this->Makefile->AddDefinition(var, "NEW"); + status.GetMakefile().AddDefinition(var, "NEW"); break; case cmPolicies::REQUIRED_IF_USED: case cmPolicies::REQUIRED_ALWAYS: @@ -146,22 +160,22 @@ bool cmCMakePolicyCommand::HandleGetMode(std::vector<std::string> const& args) << "The call to cmake_policy(GET " << id << " ...) at which this " << "error appears requests the policy, and this version of CMake " << "requires that the policy be set to NEW before it is checked."; - this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str()); + status.GetMakefile().IssueMessage(MessageType::FATAL_ERROR, e.str()); } } return true; } -bool cmCMakePolicyCommand::HandleVersionMode( - std::vector<std::string> const& args) +bool HandleVersionMode(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() <= 1) { - this->SetError("VERSION not given an argument"); + status.SetError("VERSION not given an argument"); return false; } if (args.size() >= 3) { - this->SetError("VERSION given too many arguments"); + status.SetError("VERSION given too many arguments"); return false; } std::string const& version_string = args[1]; @@ -177,19 +191,19 @@ bool cmCMakePolicyCommand::HandleVersionMode( std::ostringstream e; e << "VERSION \"" << version_string << R"(" does not have a version on both sides of "...".)"; - this->SetError(e.str()); + status.SetError(e.str()); return false; } - this->Makefile->SetPolicyVersion(version_min, version_max); + status.GetMakefile().SetPolicyVersion(version_min, version_max); return true; } -bool cmCMakePolicyCommand::HandleGetWarningMode( - std::vector<std::string> const& args) +bool HandleGetWarningMode(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() != 3) { - this->SetError( + status.SetError( "GET_WARNING must be given exactly 2 additional arguments."); return false; } @@ -204,12 +218,13 @@ bool cmCMakePolicyCommand::HandleGetWarningMode( std::ostringstream e; e << "GET_WARNING given policy \"" << id << "\" which is not known to this version of CMake."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } // Lookup the policy warning. - this->Makefile->AddDefinition(var, cmPolicies::GetPolicyWarning(pid)); + status.GetMakefile().AddDefinition(var, cmPolicies::GetPolicyWarning(pid)); return true; } +} diff --git a/Source/cmCMakePolicyCommand.h b/Source/cmCMakePolicyCommand.h index 919402c..ba9397d 100644 --- a/Source/cmCMakePolicyCommand.h +++ b/Source/cmCMakePolicyCommand.h @@ -8,41 +8,15 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -/** \class cmCMakePolicyCommand +/** * \brief Set how CMake should handle policies * * cmCMakePolicyCommand sets how CMake should deal with backwards * compatibility policies. */ -class cmCMakePolicyCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmCMakePolicyCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; - -private: - bool HandleSetMode(std::vector<std::string> const& args); - bool HandleGetMode(std::vector<std::string> const& args); - bool HandleVersionMode(std::vector<std::string> const& args); - bool HandleGetWarningMode(std::vector<std::string> const& args); -}; +bool cmCMakePolicyCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmCPluginAPI.cxx b/Source/cmCPluginAPI.cxx index 80ca898..f0c1845 100644 --- a/Source/cmCPluginAPI.cxx +++ b/Source/cmCPluginAPI.cxx @@ -608,7 +608,7 @@ int CCONV cmSourceFileGetPropertyAsBool(void* arg, const char* prop) if (cmSourceFile* rsf = sf->RealSourceFile) { return rsf->GetPropertyAsBool(prop) ? 1 : 0; } - return cmSystemTools::IsOn(cmSourceFileGetProperty(arg, prop)) ? 1 : 0; + return cmIsOn(cmSourceFileGetProperty(arg, prop)) ? 1 : 0; } void CCONV cmSourceFileSetProperty(void* arg, const char* prop, @@ -690,9 +690,7 @@ void CCONV cmSourceFileSetName(void* arg, const char* name, const char* dir, // Next, try the various source extensions for (std::string const& ext : sourceExts) { - hname = pathname; - hname += "."; - hname += ext; + hname = cmStrCat(pathname, '.', ext); if (cmSystemTools::FileExists(hname)) { sf->SourceExtension = ext; sf->FullPath = hname; @@ -702,9 +700,7 @@ void CCONV cmSourceFileSetName(void* arg, const char* name, const char* dir, // Finally, try the various header extensions for (std::string const& ext : headerExts) { - hname = pathname; - hname += "."; - hname += ext; + hname = cmStrCat(pathname, '.', ext); if (cmSystemTools::FileExists(hname)) { sf->SourceExtension = ext; sf->FullPath = hname; diff --git a/Source/cmCTest.cxx b/Source/cmCTest.cxx index 026250d..866d262 100644 --- a/Source/cmCTest.cxx +++ b/Source/cmCTest.cxx @@ -323,12 +323,11 @@ cmCTest::cmCTest() { std::string envValue; if (cmSystemTools::GetEnv("CTEST_OUTPUT_ON_FAILURE", envValue)) { - this->Impl->OutputTestOutputOnTestFailure = - !cmSystemTools::IsOff(envValue); + this->Impl->OutputTestOutputOnTestFailure = !cmIsOff(envValue); } envValue.clear(); if (cmSystemTools::GetEnv("CTEST_PROGRESS_OUTPUT", envValue)) { - this->Impl->TestProgressOutput = !cmSystemTools::IsOff(envValue); + this->Impl->TestProgressOutput = !cmIsOff(envValue); } this->Impl->Parts[PartStart].SetName("Start"); @@ -642,12 +641,10 @@ bool cmCTest::InitializeFromCommand(cmCTestStartCommand* command) cmMakefile* mf = command->GetMakefile(); std::string fname; - std::string src_dir_fname = src_dir; - src_dir_fname += "/CTestConfig.cmake"; + std::string src_dir_fname = cmStrCat(src_dir, "/CTestConfig.cmake"); cmSystemTools::ConvertToUnixSlashes(src_dir_fname); - std::string bld_dir_fname = bld_dir; - bld_dir_fname += "/CTestConfig.cmake"; + std::string bld_dir_fname = cmStrCat(bld_dir, "/CTestConfig.cmake"); cmSystemTools::ConvertToUnixSlashes(bld_dir_fname); if (cmSystemTools::FileExists(bld_dir_fname)) { @@ -663,8 +660,7 @@ bool cmCTest::InitializeFromCommand(cmCTestStartCommand* command) command->ShouldBeQuiet()); bool readit = mf->ReadDependentFile(fname); if (!readit) { - std::string m = "Could not find include file: "; - m += fname; + std::string m = cmStrCat("Could not find include file: ", fname); command->SetError(m); return false; } @@ -754,7 +750,7 @@ bool cmCTest::UpdateCTestConfiguration() std::string const& testLoad = this->GetCTestConfiguration("TestLoad"); if (!testLoad.empty()) { unsigned long load; - if (cmSystemTools::StringToULong(testLoad.c_str(), &load)) { + if (cmStrToULong(testLoad, &load)) { this->SetTestLoad(load); } else { cmCTestLog(this, WARNING, @@ -763,7 +759,7 @@ bool cmCTest::UpdateCTestConfiguration() } if (this->Impl->ProduceXML) { this->Impl->CompressXMLFiles = - cmSystemTools::IsOn(this->GetCTestConfiguration("CompressSubmission")); + cmIsOn(this->GetCTestConfiguration("CompressSubmission")); } return true; } @@ -857,8 +853,7 @@ bool cmCTest::AddIfExists(Part part, const char* file) if (this->CTestFileExists(file)) { this->AddSubmitFile(part, file); } else { - std::string name = file; - name += ".gz"; + std::string name = cmStrCat(file, ".gz"); if (this->CTestFileExists(name)) { this->AddSubmitFile(part, file); } else { @@ -1321,15 +1316,15 @@ int cmCTest::RunTest(std::vector<const char*> argv, std::string* output, OutputTestErrors(tempOutput); } *retVal = cmsysProcess_GetExitException(cp); - std::string outerr = "\n*** Exception executing: "; - outerr += cmsysProcess_GetExceptionString(cp); + std::string outerr = cmStrCat("\n*** Exception executing: ", + cmsysProcess_GetExceptionString(cp)); if (output) { *output += outerr; } cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, outerr << std::endl); } else if (result == cmsysProcess_State_Error) { - std::string outerr = "\n*** ERROR executing: "; - outerr += cmsysProcess_GetErrorString(cp); + std::string outerr = + cmStrCat("\n*** ERROR executing: ", cmsysProcess_GetErrorString(cp)); if (output) { *output += outerr; } @@ -1454,7 +1449,7 @@ void cmCTest::AddSiteProperties(cmXMLWriter& xml) xml.StartElement("Labels"); std::string l = labels; std::vector<std::string> args; - cmSystemTools::ExpandListArgument(l, args); + cmExpandList(l, args); for (std::string const& i : args) { xml.Element("Label", i); } @@ -1487,7 +1482,7 @@ std::vector<std::string> cmCTest::GetLabelsForSubprojects() std::string labelsForSubprojects = this->GetCTestConfiguration("LabelsForSubprojects"); std::vector<std::string> subprojects; - cmSystemTools::ExpandListArgument(labelsForSubprojects, subprojects); + cmExpandList(labelsForSubprojects, subprojects); // sort the array std::sort(subprojects.begin(), subprojects.end()); @@ -1854,7 +1849,7 @@ bool cmCTest::HandleCommandLineArguments(size_t& i, } i++; long repeat = 1; - if (!cmSystemTools::StringToLong(args[i].c_str(), &repeat)) { + if (!cmStrToLong(args[i], &repeat)) { errormsg = "'--repeat-until-fail' given non-integer value '" + args[i] + "'"; return false; @@ -1868,7 +1863,7 @@ bool cmCTest::HandleCommandLineArguments(size_t& i, if (this->CheckArgument(arg, "--test-load") && i < args.size() - 1) { i++; unsigned long load; - if (cmSystemTools::StringToULong(args[i].c_str(), &load)) { + if (cmStrToULong(args[i], &load)) { this->SetTestLoad(load); } else { cmCTestLog(this, WARNING, @@ -1942,7 +1937,7 @@ bool cmCTest::HandleCommandLineArguments(size_t& i, i < args.size() - 1) { i++; long outputSize; - if (cmSystemTools::StringToLong(args[i].c_str(), &outputSize)) { + if (cmStrToLong(args[i], &outputSize)) { this->Impl->TestHandler.SetTestOutputSizePassed(int(outputSize)); } else { cmCTestLog(this, WARNING, @@ -1954,7 +1949,7 @@ bool cmCTest::HandleCommandLineArguments(size_t& i, i < args.size() - 1) { i++; long outputSize; - if (cmSystemTools::StringToLong(args[i].c_str(), &outputSize)) { + if (cmStrToLong(args[i], &outputSize)) { this->Impl->TestHandler.SetTestOutputSizeFailed(int(outputSize)); } else { cmCTestLog(this, WARNING, @@ -2001,7 +1996,7 @@ bool cmCTest::HandleCommandLineArguments(size_t& i, if (this->CheckArgument(arg, "--interactive-debug-mode") && i < args.size() - 1) { i++; - this->Impl->InteractiveDebugMode = cmSystemTools::IsOn(args[i]); + this->Impl->InteractiveDebugMode = cmIsOn(args[i]); } if (this->CheckArgument(arg, "--submit-index") && i < args.size() - 1) { i++; @@ -2423,7 +2418,7 @@ int cmCTest::RunCMakeAndTest(std::string* output) cmCTestBuildAndTestHandler* handler = this->GetBuildAndTestHandler(); int retv = handler->ProcessHandler(); *output = handler->GetOutput(); -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP cmDynamicLoader::FlushCache(); #endif if (retv != 0) { @@ -2500,8 +2495,7 @@ int cmCTest::ReadCustomConfigurationFileTree(const char* dir, cmMakefile* mf) "* Read custom CTest configuration directory: " << dir << std::endl); - std::string fname = dir; - fname += "/CTestCustom.cmake"; + std::string fname = cmStrCat(dir, "/CTestCustom.cmake"); cmCTestLog(this, DEBUG, "* Check for file: " << fname << std::endl); if (cmSystemTools::FileExists(fname)) { cmCTestLog(this, DEBUG, @@ -2521,8 +2515,7 @@ int cmCTest::ReadCustomConfigurationFileTree(const char* dir, cmMakefile* mf) } } - std::string rexpr = dir; - rexpr += "/CTestCustom.ctest"; + std::string rexpr = cmStrCat(dir, "/CTestCustom.ctest"); cmCTestLog(this, DEBUG, "* Check for file: " << rexpr << std::endl); if (!found && cmSystemTools::FileExists(rexpr)) { cmsys::Glob gl; @@ -2565,7 +2558,7 @@ void cmCTest::PopulateCustomVector(cmMakefile* mf, const std::string& def, cmCTestLog(this, DEBUG, "PopulateCustomVector: " << def << std::endl); vec.clear(); - cmSystemTools::ExpandListArgument(dval, vec); + cmExpandList(dval, vec); for (std::string const& it : vec) { cmCTestLog(this, DEBUG, " -- " << it << std::endl); @@ -2674,8 +2667,7 @@ std::string cmCTest::GetSubmitURL() std::string site = this->GetCTestConfiguration("DropSite"); std::string location = this->GetCTestConfiguration("DropLocation"); - url = method.empty() ? "http" : method; - url += "://"; + url = cmStrCat(method.empty() ? "http" : method, "://"); if (!user.empty()) { url += user; if (!password.empty()) { diff --git a/Source/cmCacheManager.cxx b/Source/cmCacheManager.cxx index e8fc350..67ff94b 100644 --- a/Source/cmCacheManager.cxx +++ b/Source/cmCacheManager.cxx @@ -14,6 +14,7 @@ #include "cmMessageType.h" #include "cmMessenger.h" #include "cmState.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmVersion.h" @@ -25,9 +26,7 @@ cmCacheManager::cmCacheManager() void cmCacheManager::CleanCMakeFiles(const std::string& path) { - std::string glob = path; - glob += "/CMakeFiles"; - glob += "/*.cmake"; + std::string glob = cmStrCat(path, "/CMakeFiles/*.cmake"); cmsys::Glob globIt; globIt.FindFiles(glob); std::vector<std::string> files = globIt.GetFiles(); @@ -38,8 +37,7 @@ bool cmCacheManager::LoadCache(const std::string& path, bool internal, std::set<std::string>& excludes, std::set<std::string>& includes) { - std::string cacheFile = path; - cacheFile += "/CMakeCache.txt"; + std::string cacheFile = cmStrCat(path, "/CMakeCache.txt"); // clear the old cache, if we are reading in internal values if (internal) { this->Cache.clear(); @@ -104,12 +102,10 @@ bool cmCacheManager::LoadCache(const std::string& path, bool internal, // not visible in the gui if (!internal) { e.Type = cmStateEnums::INTERNAL; - helpString = "DO NOT EDIT, "; - helpString += entryKey; - helpString += " loaded from external file. " - "To change this value edit this file: "; - helpString += path; - helpString += "/CMakeCache.txt"; + helpString = cmStrCat("DO NOT EDIT, ", entryKey, + " loaded from external file. " + "To change this value edit this file: ", + path, "/CMakeCache.txt"); e.SetProperty("HELPSTRING", helpString.c_str()); } if (!this->ReadPropertyEntry(entryKey, e)) { @@ -214,14 +210,11 @@ void cmCacheManager::WritePropertyEntries(std::ostream& os, CacheIterator i, { for (const char** p = cmCacheManager::PersistentProperties; *p; ++p) { if (const char* value = i.GetProperty(*p)) { - std::string helpstring = *p; - helpstring += " property for variable: "; - helpstring += i.GetName(); + std::string helpstring = + cmStrCat(*p, " property for variable: ", i.GetName()); cmCacheManager::OutputHelpString(os, helpstring); - std::string key = i.GetName(); - key += "-"; - key += *p; + std::string key = cmStrCat(i.GetName(), '-', *p); cmCacheManager::OutputKey(os, key); os << ":INTERNAL="; cmCacheManager::OutputValue(os, value); @@ -234,8 +227,7 @@ void cmCacheManager::WritePropertyEntries(std::ostream& os, CacheIterator i, bool cmCacheManager::SaveCache(const std::string& path, cmMessenger* messenger) { - std::string cacheFile = path; - cacheFile += "/CMakeCache.txt"; + std::string cacheFile = cmStrCat(path, "/CMakeCache.txt"); cmGeneratedFileStream fout(cacheFile); fout.SetCopyIfDifferent(true); if (!fout) { @@ -356,8 +348,7 @@ bool cmCacheManager::SaveCache(const std::string& path, cmMessenger* messenger) } fout << "\n"; fout.Close(); - std::string checkCacheFile = path; - checkCacheFile += "/CMakeFiles"; + std::string checkCacheFile = cmStrCat(path, "/CMakeFiles"); cmSystemTools::MakeDirectory(checkCacheFile); checkCacheFile += "/cmake.check_cache"; cmsys::ofstream checkCache(checkCacheFile.c_str()); @@ -473,15 +464,14 @@ void cmCacheManager::OutputNewlineTruncationWarning(std::ostream& fout, { if (value.find('\n') != std::string::npos) { if (messenger) { - std::string message = "Value of "; - message += key; - message += " contained a newline; truncating"; + std::string message = + cmStrCat("Value of ", key, " contained a newline; truncating"); messenger->IssueMessage(MessageType::WARNING, message); } - std::string comment = "WARNING: Value of "; - comment += key; - comment += " contained a newline and was truncated. Original value:"; + std::string comment = + cmStrCat("WARNING: Value of ", key, + " contained a newline and was truncated. Original value:"); OutputWarningComment(fout, comment, true); OutputWarningComment(fout, value, false); @@ -552,7 +542,7 @@ void cmCacheManager::AddCacheEntry(const std::string& key, const char* value, if (type == cmStateEnums::FILEPATH || type == cmStateEnums::PATH) { if (e.Value.find(';') != std::string::npos) { std::vector<std::string> paths; - cmSystemTools::ExpandListArgument(e.Value, paths); + cmExpandList(e.Value, paths); const char* sep = ""; e.Value = ""; for (std::string& i : paths) { @@ -615,7 +605,7 @@ void cmCacheManager::CacheIterator::SetValue(const char* value) bool cmCacheManager::CacheIterator::GetValueAsBool() const { - return cmSystemTools::IsOn(this->GetEntry().Value); + return cmIsOn(this->GetEntry().Value); } std::vector<std::string> cmCacheManager::CacheEntry::GetPropertyList() const @@ -695,7 +685,7 @@ bool cmCacheManager::CacheIterator::GetPropertyAsBool( const std::string& prop) const { if (const char* value = this->GetProperty(prop)) { - return cmSystemTools::IsOn(value); + return cmIsOn(value); } return false; } diff --git a/Source/cmCommandArgumentParserHelper.cxx b/Source/cmCommandArgumentParserHelper.cxx index ca29967..073a0cd 100644 --- a/Source/cmCommandArgumentParserHelper.cxx +++ b/Source/cmCommandArgumentParserHelper.cxx @@ -5,6 +5,7 @@ #include "cmCommandArgumentLexer.h" #include "cmMakefile.h" #include "cmState.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include <iostream> @@ -58,7 +59,7 @@ const char* cmCommandArgumentParserHelper::ExpandSpecialVariable( std::string str; if (cmSystemTools::GetEnv(var, str)) { if (this->EscapeQuotes) { - return this->AddString(cmSystemTools::EscapeQuotes(str)); + return this->AddString(cmEscapeQuotes(str)); } return this->AddString(str); } @@ -68,7 +69,7 @@ const char* cmCommandArgumentParserHelper::ExpandSpecialVariable( if (const std::string* c = this->Makefile->GetState()->GetInitializedCacheValue(var)) { if (this->EscapeQuotes) { - return this->AddString(cmSystemTools::EscapeQuotes(*c)); + return this->AddString(cmEscapeQuotes(*c)); } return this->AddString(*c); } @@ -99,7 +100,7 @@ const char* cmCommandArgumentParserHelper::ExpandVariable(const char* var) } } if (this->EscapeQuotes && value) { - return this->AddString(cmSystemTools::EscapeQuotes(value)); + return this->AddString(cmEscapeQuotes(value)); } return this->AddString(value ? value : ""); } @@ -123,9 +124,7 @@ const char* cmCommandArgumentParserHelper::ExpandVariableForAt(const char* var) // - this->ReplaceAtSyntax is false // - this->ReplaceAtSyntax is true, but this->RemoveEmpty is false, // and the variable was not defined - std::string ref = "@"; - ref += var; - ref += "@"; + std::string ref = cmStrCat('@', var, '@'); return this->AddString(ref); } diff --git a/Source/cmCommands.cxx b/Source/cmCommands.cxx index f351ff8..ead16d2 100644 --- a/Source/cmCommands.cxx +++ b/Source/cmCommands.cxx @@ -84,7 +84,7 @@ #include "cmUnsetCommand.h" #include "cmWhileCommand.h" -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) # include "cmAddCompileOptionsCommand.h" # include "cmAddLinkOptionsCommand.h" # include "cmAuxSourceDirectoryCommand.h" @@ -116,19 +116,14 @@ void GetScriptingCommands(cmState* state) { - state->AddBuiltinCommand("break", cm::make_unique<cmBreakCommand>()); - state->AddBuiltinCommand("cmake_minimum_required", - cm::make_unique<cmCMakeMinimumRequired>()); - state->AddBuiltinCommand("cmake_policy", - cm::make_unique<cmCMakePolicyCommand>()); - state->AddBuiltinCommand("configure_file", - cm::make_unique<cmConfigureFileCommand>()); - state->AddBuiltinCommand("continue", cm::make_unique<cmContinueCommand>()); - state->AddBuiltinCommand("exec_program", - cm::make_unique<cmExecProgramCommand>()); - state->AddBuiltinCommand("execute_process", - cm::make_unique<cmExecuteProcessCommand>()); - state->AddBuiltinCommand("file", cm::make_unique<cmFileCommand>()); + state->AddBuiltinCommand("break", cmBreakCommand); + state->AddBuiltinCommand("cmake_minimum_required", cmCMakeMinimumRequired); + state->AddBuiltinCommand("cmake_policy", cmCMakePolicyCommand); + state->AddBuiltinCommand("configure_file", cmConfigureFileCommand); + state->AddBuiltinCommand("continue", cmContinueCommand); + state->AddBuiltinCommand("exec_program", cmExecProgramCommand); + state->AddBuiltinCommand("execute_process", cmExecuteProcessCommand); + state->AddBuiltinCommand("file", cmFileCommand); state->AddBuiltinCommand("find_file", cm::make_unique<cmFindFileCommand>()); state->AddBuiltinCommand("find_library", cm::make_unique<cmFindLibraryCommand>()); @@ -137,42 +132,34 @@ void GetScriptingCommands(cmState* state) state->AddBuiltinCommand("find_path", cm::make_unique<cmFindPathCommand>()); state->AddBuiltinCommand("find_program", cm::make_unique<cmFindProgramCommand>()); - state->AddBuiltinCommand("foreach", cm::make_unique<cmForEachCommand>()); - state->AddBuiltinCommand("function", cm::make_unique<cmFunctionCommand>()); - state->AddBuiltinCommand("get_cmake_property", - cm::make_unique<cmGetCMakePropertyCommand>()); + state->AddBuiltinCommand("foreach", cmForEachCommand); + state->AddBuiltinCommand("function", cmFunctionCommand); + state->AddBuiltinCommand("get_cmake_property", cmGetCMakePropertyCommand); state->AddBuiltinCommand("get_directory_property", - cm::make_unique<cmGetDirectoryPropertyCommand>()); + cmGetDirectoryPropertyCommand); state->AddBuiltinCommand("get_filename_component", - cm::make_unique<cmGetFilenameComponentCommand>()); - state->AddBuiltinCommand("get_property", - cm::make_unique<cmGetPropertyCommand>()); + cmGetFilenameComponentCommand); + state->AddBuiltinCommand("get_property", cmGetPropertyCommand); state->AddBuiltinCommand("if", cmIfCommand); - state->AddBuiltinCommand("include", cm::make_unique<cmIncludeCommand>()); - state->AddBuiltinCommand("include_guard", - cm::make_unique<cmIncludeGuardCommand>()); - state->AddBuiltinCommand("list", cm::make_unique<cmListCommand>()); - state->AddBuiltinCommand("macro", cm::make_unique<cmMacroCommand>()); - state->AddBuiltinCommand("make_directory", - cm::make_unique<cmMakeDirectoryCommand>()); - state->AddBuiltinCommand("mark_as_advanced", - cm::make_unique<cmMarkAsAdvancedCommand>()); - state->AddBuiltinCommand("math", cm::make_unique<cmMathCommand>()); - state->AddBuiltinCommand("message", cm::make_unique<cmMessageCommand>()); - state->AddBuiltinCommand("option", cm::make_unique<cmOptionCommand>()); - state->AddBuiltinCommand("cmake_parse_arguments", - cm::make_unique<cmParseArgumentsCommand>()); + state->AddBuiltinCommand("include", cmIncludeCommand); + state->AddBuiltinCommand("include_guard", cmIncludeGuardCommand); + state->AddBuiltinCommand("list", cmListCommand); + state->AddBuiltinCommand("macro", cmMacroCommand); + state->AddBuiltinCommand("make_directory", cmMakeDirectoryCommand); + state->AddBuiltinCommand("mark_as_advanced", cmMarkAsAdvancedCommand); + state->AddBuiltinCommand("math", cmMathCommand); + state->AddBuiltinCommand("message", cmMessageCommand); + state->AddBuiltinCommand("option", cmOptionCommand); + state->AddBuiltinCommand("cmake_parse_arguments", cmParseArgumentsCommand); state->AddBuiltinCommand("return", cmReturnCommand); - state->AddBuiltinCommand("separate_arguments", - cm::make_unique<cmSeparateArgumentsCommand>()); - state->AddBuiltinCommand("set", cm::make_unique<cmSetCommand>()); + state->AddBuiltinCommand("separate_arguments", cmSeparateArgumentsCommand); + state->AddBuiltinCommand("set", cmSetCommand); state->AddBuiltinCommand("set_directory_properties", - cm::make_unique<cmSetDirectoryPropertiesCommand>()); - state->AddBuiltinCommand("set_property", - cm::make_unique<cmSetPropertyCommand>()); - state->AddBuiltinCommand("site_name", cm::make_unique<cmSiteNameCommand>()); - state->AddBuiltinCommand("string", cm::make_unique<cmStringCommand>()); - state->AddBuiltinCommand("unset", cm::make_unique<cmUnsetCommand>()); + cmSetDirectoryPropertiesCommand); + state->AddBuiltinCommand("set_property", cmSetPropertyCommand); + state->AddBuiltinCommand("site_name", cmSiteNameCommand); + state->AddBuiltinCommand("string", cmStringCommand); + state->AddBuiltinCommand("unset", cmUnsetCommand); state->AddBuiltinCommand("while", cmWhileCommand); state->AddUnexpectedCommand( @@ -210,18 +197,15 @@ void GetScriptingCommands(cmState* state) "WHILE ENDWHILE structure. Or its arguments did not " "match the opening WHILE command."); -#if defined(CMAKE_BUILD_WITH_CMAKE) - state->AddBuiltinCommand( - "cmake_host_system_information", - cm::make_unique<cmCMakeHostSystemInformationCommand>()); - state->AddBuiltinCommand("remove", cm::make_unique<cmRemoveCommand>()); - state->AddBuiltinCommand("variable_watch", - cm::make_unique<cmVariableWatchCommand>()); - state->AddBuiltinCommand("write_file", - cm::make_unique<cmWriteFileCommand>()); +#if !defined(CMAKE_BOOTSTRAP) + state->AddBuiltinCommand("cmake_host_system_information", + cmCMakeHostSystemInformationCommand); + state->AddBuiltinCommand("remove", cmRemoveCommand); + state->AddBuiltinCommand("variable_watch", cmVariableWatchCommand); + state->AddBuiltinCommand("write_file", cmWriteFileCommand); state->AddDisallowedCommand( - "build_name", cm::make_unique<cmBuildNameCommand>(), cmPolicies::CMP0036, + "build_name", cmBuildNameCommand, cmPolicies::CMP0036, "The build_name command should not be called; see CMP0036."); state->AddDisallowedCommand( "use_mangled_mesa", cm::make_unique<cmUseMangledMesaCommand>(), @@ -233,21 +217,14 @@ void GetScriptingCommands(cmState* state) void GetProjectCommands(cmState* state) { - state->AddBuiltinCommand("add_custom_command", - cm::make_unique<cmAddCustomCommandCommand>()); - state->AddBuiltinCommand("add_custom_target", - cm::make_unique<cmAddCustomTargetCommand>()); - state->AddBuiltinCommand("add_definitions", - cm::make_unique<cmAddDefinitionsCommand>()); - state->AddBuiltinCommand("add_dependencies", - cm::make_unique<cmAddDependenciesCommand>()); - state->AddBuiltinCommand("add_executable", - cm::make_unique<cmAddExecutableCommand>()); - state->AddBuiltinCommand("add_library", - cm::make_unique<cmAddLibraryCommand>()); - state->AddBuiltinCommand("add_subdirectory", - cm::make_unique<cmAddSubDirectoryCommand>()); - state->AddBuiltinCommand("add_test", cm::make_unique<cmAddTestCommand>()); + state->AddBuiltinCommand("add_custom_command", cmAddCustomCommandCommand); + state->AddBuiltinCommand("add_custom_target", cmAddCustomTargetCommand); + state->AddBuiltinCommand("add_definitions", cmAddDefinitionsCommand); + state->AddBuiltinCommand("add_dependencies", cmAddDependenciesCommand); + state->AddBuiltinCommand("add_executable", cmAddExecutableCommand); + state->AddBuiltinCommand("add_library", cmAddLibraryCommand); + state->AddBuiltinCommand("add_subdirectory", cmAddSubDirectoryCommand); + state->AddBuiltinCommand("add_test", cmAddTestCommand); state->AddBuiltinCommand("build_command", cm::make_unique<cmBuildCommand>()); state->AddBuiltinCommand("create_test_sourcelist", cm::make_unique<cmCreateTestSourceList>()); @@ -301,13 +278,12 @@ void GetProjectCommands(cmState* state) cm::make_unique<cmTryCompileCommand>()); state->AddBuiltinCommand("try_run", cm::make_unique<cmTryRunCommand>()); -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) state->AddBuiltinCommand("add_compile_definitions", - cm::make_unique<cmAddCompileDefinitionsCommand>()); - state->AddBuiltinCommand("add_compile_options", - cm::make_unique<cmAddCompileOptionsCommand>()); + cmAddCompileDefinitionsCommand); + state->AddBuiltinCommand("add_compile_options", cmAddCompileOptionsCommand); state->AddBuiltinCommand("aux_source_directory", - cm::make_unique<cmAuxSourceDirectoryCommand>()); + cmAuxSourceDirectoryCommand); state->AddBuiltinCommand("export", cm::make_unique<cmExportCommand>()); state->AddBuiltinCommand("fltk_wrap_ui", cm::make_unique<cmFLTKWrapUICommand>()); @@ -316,8 +292,7 @@ void GetProjectCommands(cmState* state) cm::make_unique<cmIncludeExternalMSProjectCommand>()); state->AddBuiltinCommand("install_programs", cm::make_unique<cmInstallProgramsCommand>()); - state->AddBuiltinCommand("add_link_options", - cm::make_unique<cmAddLinkOptionsCommand>()); + state->AddBuiltinCommand("add_link_options", cmAddLinkOptionsCommand); state->AddBuiltinCommand("link_libraries", cm::make_unique<cmLinkLibrariesCommand>()); state->AddBuiltinCommand("target_link_options", diff --git a/Source/cmCommonTargetGenerator.cxx b/Source/cmCommonTargetGenerator.cxx index 61880c2..49db505 100644 --- a/Source/cmCommonTargetGenerator.cxx +++ b/Source/cmCommonTargetGenerator.cxx @@ -59,10 +59,11 @@ void cmCommonTargetGenerator::AddModuleDefinitionFlag( // Append the flag and value. Use ConvertToLinkReference to help // vs6's "cl -link" pass it to the linker. - std::string flag = defFileFlag; - flag += this->LocalCommonGenerator->ConvertToOutputFormat( - linkLineComputer->ConvertToLinkReference(mdi->DefFile), - cmOutputConverter::SHELL); + std::string flag = + cmStrCat(defFileFlag, + this->LocalCommonGenerator->ConvertToOutputFormat( + linkLineComputer->ConvertToLinkReference(mdi->DefFile), + cmOutputConverter::SHELL)); this->LocalCommonGenerator->AppendFlags(flags, flag); } @@ -155,9 +156,8 @@ std::vector<std::string> cmCommonTargetGenerator::GetLinkedTargetDirectories() && linkee->GetType() != cmStateEnums::INTERFACE_LIBRARY && emitted.insert(linkee).second) { cmLocalGenerator* lg = linkee->GetLocalGenerator(); - std::string di = lg->GetCurrentBinaryDirectory(); - di += "/"; - di += lg->GetTargetDirectory(linkee); + std::string di = cmStrCat(lg->GetCurrentBinaryDirectory(), '/', + lg->GetTargetDirectory(linkee)); dirs.push_back(std::move(di)); } } @@ -210,11 +210,7 @@ void cmCommonTargetGenerator::AppendOSXVerFlag(std::string& flags, const char* name, bool so) { // Lookup the flag to specify the version. - std::string fvar = "CMAKE_"; - fvar += lang; - fvar += "_OSX_"; - fvar += name; - fvar += "_VERSION_FLAG"; + std::string fvar = cmStrCat("CMAKE_", lang, "_OSX_", name, "_VERSION_FLAG"); const char* flag = this->Makefile->GetDefinition(fvar); // Skip if no such flag. diff --git a/Source/cmComputeLinkDepends.cxx b/Source/cmComputeLinkDepends.cxx index f8b78b4..c4b0c05 100644 --- a/Source/cmComputeLinkDepends.cxx +++ b/Source/cmComputeLinkDepends.cxx @@ -12,7 +12,6 @@ #include "cmRange.h" #include "cmStateTypes.h" #include "cmStringAlgorithms.h" -#include "cmSystemTools.h" #include "cmTarget.h" #include "cmake.h" @@ -320,8 +319,7 @@ int cmComputeLinkDepends::AddLinkEntry(cmLinkItem const& item) this->BFSQueue.push(qe); } else { // Look for an old-style <item>_LIB_DEPENDS variable. - std::string var = entry.Item; - var += "_LIB_DEPENDS"; + std::string var = cmStrCat(entry.Item, "_LIB_DEPENDS"); if (const char* val = this->Makefile->GetDefinition(var)) { // The item dependencies are known. Follow them. BFSEntry qe = { index, val }; @@ -439,7 +437,7 @@ void cmComputeLinkDepends::AddVarLinkEntries(int depender_index, // <item>_LIB_DEPENDS. The variable contains a semicolon-separated // list. The list contains link-type;item pairs and just items. std::vector<std::string> deplist; - cmSystemTools::ExpandListArgument(value, deplist); + cmExpandList(value, deplist); // Look for entries meant for this configuration. std::vector<cmLinkItem> actual_libs; @@ -462,8 +460,7 @@ void cmComputeLinkDepends::AddVarLinkEntries(int depender_index, // the export_library_dependencies command from CMake 2.4 and // lower. if (!haveLLT) { - std::string var = d; - var += "_LINK_TYPE"; + std::string var = cmStrCat(d, "_LINK_TYPE"); if (const char* val = this->Makefile->GetDefinition(var)) { if (strcmp(val, "debug") == 0) { llt = DEBUG_LibraryType; diff --git a/Source/cmComputeLinkInformation.cxx b/Source/cmComputeLinkInformation.cxx index 78cddf0..0ff0c3a 100644 --- a/Source/cmComputeLinkInformation.cxx +++ b/Source/cmComputeLinkInformation.cxx @@ -2,6 +2,7 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmComputeLinkInformation.h" +#include "cmAlgorithms.h" #include "cmComputeLinkDepends.h" #include "cmGeneratorTarget.h" #include "cmGlobalGenerator.h" @@ -278,15 +279,19 @@ cmComputeLinkInformation::cmComputeLinkInformation( this->LoaderFlag = nullptr; if (!this->Target->IsDLLPlatform() && this->Target->GetType() == cmStateEnums::MODULE_LIBRARY) { - std::string loader_flag_var = "CMAKE_SHARED_MODULE_LOADER_"; - loader_flag_var += this->LinkLanguage; - loader_flag_var += "_FLAG"; + std::string loader_flag_var = + cmStrCat("CMAKE_SHARED_MODULE_LOADER_", this->LinkLanguage, "_FLAG"); this->LoaderFlag = this->Makefile->GetDefinition(loader_flag_var); } // Get options needed to link libraries. - this->LibLinkFlag = - this->Makefile->GetSafeDefinition("CMAKE_LINK_LIBRARY_FLAG"); + if (const char* flag = this->Makefile->GetDefinition( + "CMAKE_" + this->LinkLanguage + "_LINK_LIBRARY_FLAG")) { + this->LibLinkFlag = flag; + } else { + this->LibLinkFlag = + this->Makefile->GetSafeDefinition("CMAKE_LINK_LIBRARY_FLAG"); + } this->LibLinkFileFlag = this->Makefile->GetSafeDefinition("CMAKE_LINK_LIBRARY_FILE_FLAG"); this->LibLinkSuffix = @@ -298,11 +303,8 @@ cmComputeLinkInformation::cmComputeLinkInformation( const char* tType = ((this->Target->GetType() == cmStateEnums::EXECUTABLE) ? "EXECUTABLE" : "SHARED_LIBRARY"); - std::string rtVar = "CMAKE_"; - rtVar += tType; - rtVar += "_RUNTIME_"; - rtVar += this->LinkLanguage; - rtVar += "_FLAG"; + std::string rtVar = + cmStrCat("CMAKE_", tType, "_RUNTIME_", this->LinkLanguage, "_FLAG"); std::string rtSepVar = rtVar + "_SEP"; this->RuntimeFlag = this->Makefile->GetSafeDefinition(rtVar); this->RuntimeSep = this->Makefile->GetSafeDefinition(rtSepVar); @@ -312,19 +314,15 @@ cmComputeLinkInformation::cmComputeLinkInformation( this->RuntimeUseChrpath = this->Target->IsChrpathUsed(config); // Get options needed to help find dependent libraries. - std::string rlVar = "CMAKE_"; - rlVar += tType; - rlVar += "_RPATH_LINK_"; - rlVar += this->LinkLanguage; - rlVar += "_FLAG"; + std::string rlVar = + cmStrCat("CMAKE_", tType, "_RPATH_LINK_", this->LinkLanguage, "_FLAG"); this->RPathLinkFlag = this->Makefile->GetSafeDefinition(rlVar); } // Check if we need to include the runtime search path at link time. { - std::string var = "CMAKE_SHARED_LIBRARY_LINK_"; - var += this->LinkLanguage; - var += "_WITH_RUNTIME_PATH"; + std::string var = cmStrCat("CMAKE_SHARED_LIBRARY_LINK_", + this->LinkLanguage, "_WITH_RUNTIME_PATH"); this->LinkWithRuntimePath = this->Makefile->IsOn(var); } @@ -475,7 +473,7 @@ bool cmComputeLinkInformation::Compute() // Restore the target link type so the correct system runtime // libraries are found. const char* lss = this->Target->GetProperty("LINK_SEARCH_END_STATIC"); - if (cmSystemTools::IsOn(lss)) { + if (cmIsOn(lss)) { this->SetCurrentLinkType(LinkStatic); } else { this->SetCurrentLinkType(this->StartLinkType); @@ -541,14 +539,12 @@ void cmComputeLinkInformation::AddImplicitLinkInfo(std::string const& lang) { // Add libraries for this language that are not implied by the // linker language. - std::string libVar = "CMAKE_"; - libVar += lang; - libVar += "_IMPLICIT_LINK_LIBRARIES"; + std::string libVar = cmStrCat("CMAKE_", lang, "_IMPLICIT_LINK_LIBRARIES"); if (const char* libs = this->Makefile->GetDefinition(libVar)) { std::vector<std::string> libsVec; - cmSystemTools::ExpandListArgument(libs, libsVec); + cmExpandList(libs, libsVec); for (std::string const& i : libsVec) { - if (this->ImplicitLinkLibs.find(i) == this->ImplicitLinkLibs.end()) { + if (!cmContains(this->ImplicitLinkLibs, i)) { this->AddItem(i, nullptr); } } @@ -556,12 +552,10 @@ void cmComputeLinkInformation::AddImplicitLinkInfo(std::string const& lang) // Add linker search paths for this language that are not // implied by the linker language. - std::string dirVar = "CMAKE_"; - dirVar += lang; - dirVar += "_IMPLICIT_LINK_DIRECTORIES"; + std::string dirVar = cmStrCat("CMAKE_", lang, "_IMPLICIT_LINK_DIRECTORIES"); if (const char* dirs = this->Makefile->GetDefinition(dirVar)) { std::vector<std::string> dirsVec; - cmSystemTools::ExpandListArgument(dirs, dirsVec); + cmExpandList(dirs, dirsVec); this->OrderLinkerSearchPath->AddLanguageDirectories(dirsVec); } } @@ -754,19 +748,15 @@ void cmComputeLinkInformation::ComputeLinkTypeInfo() break; } if (target_type_str) { - std::string static_link_type_flag_var = "CMAKE_"; - static_link_type_flag_var += target_type_str; - static_link_type_flag_var += "_LINK_STATIC_"; - static_link_type_flag_var += this->LinkLanguage; - static_link_type_flag_var += "_FLAGS"; + std::string static_link_type_flag_var = + cmStrCat("CMAKE_", target_type_str, "_LINK_STATIC_", this->LinkLanguage, + "_FLAGS"); static_link_type_flag = this->Makefile->GetDefinition(static_link_type_flag_var); - std::string shared_link_type_flag_var = "CMAKE_"; - shared_link_type_flag_var += target_type_str; - shared_link_type_flag_var += "_LINK_DYNAMIC_"; - shared_link_type_flag_var += this->LinkLanguage; - shared_link_type_flag_var += "_FLAGS"; + std::string shared_link_type_flag_var = + cmStrCat("CMAKE_", target_type_str, "_LINK_DYNAMIC_", this->LinkLanguage, + "_FLAGS"); shared_link_type_flag = this->Makefile->GetDefinition(shared_link_type_flag_var); } @@ -782,7 +772,7 @@ void cmComputeLinkInformation::ComputeLinkTypeInfo() // Lookup the starting link type from the target (linked statically?). const char* lss = this->Target->GetProperty("LINK_SEARCH_START_STATIC"); - this->StartLinkType = cmSystemTools::IsOn(lss) ? LinkStatic : LinkShared; + this->StartLinkType = cmIsOn(lss) ? LinkStatic : LinkShared; this->CurrentLinkType = this->StartLinkType; } @@ -806,7 +796,7 @@ void cmComputeLinkInformation::ComputeItemParserInfo() if (const char* linkSuffixes = mf->GetDefinition("CMAKE_EXTRA_LINK_EXTENSIONS")) { std::vector<std::string> linkSuffixVec; - cmSystemTools::ExpandListArgument(linkSuffixes, linkSuffixVec); + cmExpandList(linkSuffixes, linkSuffixVec); for (std::string const& i : linkSuffixVec) { this->AddLinkExtension(i.c_str(), LinkUnknown); } @@ -814,7 +804,7 @@ void cmComputeLinkInformation::ComputeItemParserInfo() if (const char* sharedSuffixes = mf->GetDefinition("CMAKE_EXTRA_SHARED_LIBRARY_SUFFIXES")) { std::vector<std::string> sharedSuffixVec; - cmSystemTools::ExpandListArgument(sharedSuffixes, sharedSuffixVec); + cmExpandList(sharedSuffixes, sharedSuffixVec); for (std::string const& i : sharedSuffixVec) { this->AddLinkExtension(i.c_str(), LinkShared); } @@ -842,8 +832,7 @@ void cmComputeLinkInformation::ComputeItemParserInfo() reg += "([^/:]*)"; // Create a regex to match any library name. - std::string reg_any = reg; - reg_any += libext; + std::string reg_any = cmStrCat(reg, libext); #ifdef CM_COMPUTE_LINK_INFO_DEBUG fprintf(stderr, "any regex [%s]\n", reg_any.c_str()); #endif @@ -851,9 +840,8 @@ void cmComputeLinkInformation::ComputeItemParserInfo() // Create a regex to match static library names. if (!this->StaticLinkExtensions.empty()) { - std::string reg_static = reg; - reg_static += - this->CreateExtensionRegex(this->StaticLinkExtensions, LinkStatic); + std::string reg_static = cmStrCat( + reg, this->CreateExtensionRegex(this->StaticLinkExtensions, LinkStatic)); #ifdef CM_COMPUTE_LINK_INFO_DEBUG fprintf(stderr, "static regex [%s]\n", reg_static.c_str()); #endif @@ -990,16 +978,11 @@ void cmComputeLinkInformation::AddTargetItem(std::string const& item, return; } - // If this platform wants a flag before the full path, add it. - if (!this->LibLinkFileFlag.empty()) { - this->Items.emplace_back(this->LibLinkFileFlag, false); - } - // For compatibility with CMake 2.4 include the item's directory in // the linker search path. if (this->OldLinkDirMode && !target->IsFrameworkOnApple() && - this->OldLinkDirMask.find(cmSystemTools::GetFilenamePath(item)) == - this->OldLinkDirMask.end()) { + !cmContains(this->OldLinkDirMask, + cmSystemTools::GetFilenamePath(item))) { this->OldLinkDirItems.push_back(item); } @@ -1052,16 +1035,11 @@ void cmComputeLinkInformation::AddFullItem(std::string const& item) // For compatibility with CMake 2.4 include the item's directory in // the linker search path. if (this->OldLinkDirMode && - this->OldLinkDirMask.find(cmSystemTools::GetFilenamePath(item)) == - this->OldLinkDirMask.end()) { + !cmContains(this->OldLinkDirMask, + cmSystemTools::GetFilenamePath(item))) { this->OldLinkDirItems.push_back(item); } - // If this platform wants a flag before the full path, add it. - if (!this->LibLinkFileFlag.empty()) { - this->Items.emplace_back(this->LibLinkFileFlag, false); - } - // Now add the full path to the library. this->Items.emplace_back(item, true); } @@ -1077,7 +1055,7 @@ bool cmComputeLinkInformation::CheckImplicitDirItem(std::string const& item) // Check if this item is in an implicit link directory. std::string dir = cmSystemTools::GetFilenamePath(item); - if (this->ImplicitLinkDirs.find(dir) == this->ImplicitLinkDirs.end()) { + if (!cmContains(this->ImplicitLinkDirs, dir)) { // Only libraries in implicit link directories are converted to // pathless items. return false; @@ -1219,9 +1197,7 @@ void cmComputeLinkInformation::AddUserItem(std::string const& item, } // Create an option to ask the linker to search for the library. - std::string out = this->LibLinkFlag; - out += lib; - out += this->LibLinkSuffix; + std::string out = cmStrCat(this->LibLinkFlag, lib, this->LibLinkSuffix); this->Items.emplace_back(out, false); // Here we could try to find the library the linker will find and @@ -1243,12 +1219,7 @@ void cmComputeLinkInformation::AddFrameworkItem(std::string const& item) std::string fw_path = this->SplitFramework.match(1); std::string fw = this->SplitFramework.match(2); - std::string full_fw = fw_path; - full_fw += "/"; - full_fw += fw; - full_fw += ".framework"; - full_fw += "/"; - full_fw += fw; + std::string full_fw = cmStrCat(fw_path, '/', fw, ".framework/", fw); // Add the directory portion to the framework search path. this->AddFrameworkPath(fw_path); @@ -1293,16 +1264,15 @@ void cmComputeLinkInformation::ComputeFrameworkInfo() // Get platform-wide implicit directories. if (const char* implicitLinks = this->Makefile->GetDefinition( "CMAKE_PLATFORM_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES")) { - cmSystemTools::ExpandListArgument(implicitLinks, implicitDirVec); + cmExpandList(implicitLinks, implicitDirVec); } // Get language-specific implicit directories. - std::string implicitDirVar = "CMAKE_"; - implicitDirVar += this->LinkLanguage; - implicitDirVar += "_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES"; + std::string implicitDirVar = cmStrCat( + "CMAKE_", this->LinkLanguage, "_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES"); if (const char* implicitDirs = this->Makefile->GetDefinition(implicitDirVar)) { - cmSystemTools::ExpandListArgument(implicitDirs, implicitDirVec); + cmExpandList(implicitDirs, implicitDirVec); } this->FrameworkPathsEmmitted.insert(implicitDirVec.begin(), @@ -1372,8 +1342,7 @@ void cmComputeLinkInformation::HandleBadFullItem(std::string const& item, switch (this->Target->GetPolicyStatusCMP0008()) { case cmPolicies::WARN: { // Print the warning at most once for this item. - std::string wid = "CMP0008-WARNING-GIVEN-"; - wid += item; + std::string wid = cmStrCat("CMP0008-WARNING-GIVEN-", item); if (!this->CMakeInstance->GetState()->GetGlobalPropertyAsBool(wid)) { this->CMakeInstance->GetState()->SetGlobalProperty(wid, "1"); std::ostringstream w; @@ -1521,7 +1490,7 @@ void cmComputeLinkInformation::LoadImplicitLinkInfo() // Get platform-wide implicit directories. if (const char* implicitLinks = (this->Makefile->GetDefinition( "CMAKE_PLATFORM_IMPLICIT_LINK_DIRECTORIES"))) { - cmSystemTools::ExpandListArgument(implicitLinks, implicitDirVec); + cmExpandList(implicitLinks, implicitDirVec); } // Append library architecture to all implicit platform directories @@ -1534,12 +1503,11 @@ void cmComputeLinkInformation::LoadImplicitLinkInfo() } // Get language-specific implicit directories. - std::string implicitDirVar = "CMAKE_"; - implicitDirVar += this->LinkLanguage; - implicitDirVar += "_IMPLICIT_LINK_DIRECTORIES"; + std::string implicitDirVar = + cmStrCat("CMAKE_", this->LinkLanguage, "_IMPLICIT_LINK_DIRECTORIES"); if (const char* implicitDirs = this->Makefile->GetDefinition(implicitDirVar)) { - cmSystemTools::ExpandListArgument(implicitDirs, implicitDirVec); + cmExpandList(implicitDirs, implicitDirVec); } // Store implicit link directories. @@ -1547,12 +1515,11 @@ void cmComputeLinkInformation::LoadImplicitLinkInfo() // Get language-specific implicit libraries. std::vector<std::string> implicitLibVec; - std::string implicitLibVar = "CMAKE_"; - implicitLibVar += this->LinkLanguage; - implicitLibVar += "_IMPLICIT_LINK_LIBRARIES"; + std::string implicitLibVar = + cmStrCat("CMAKE_", this->LinkLanguage, "_IMPLICIT_LINK_LIBRARIES"); if (const char* implicitLibs = this->Makefile->GetDefinition(implicitLibVar)) { - cmSystemTools::ExpandListArgument(implicitLibs, implicitLibVec); + cmExpandList(implicitLibs, implicitLibVec); } // Store implicit link libraries. @@ -1567,7 +1534,7 @@ void cmComputeLinkInformation::LoadImplicitLinkInfo() // Get platform specific rpath link directories if (const char* rpathDirs = (this->Makefile->GetDefinition("CMAKE_PLATFORM_RUNTIME_PATH"))) { - cmSystemTools::ExpandListArgument(rpathDirs, this->RuntimeLinkDirs); + cmExpandList(rpathDirs, this->RuntimeLinkDirs); } } @@ -1674,7 +1641,7 @@ static void cmCLI_ExpandListUnique(const char* str, std::set<std::string>& emitted) { std::vector<std::string> tmp; - cmSystemTools::ExpandListArgument(str, tmp); + cmExpandList(str, tmp); for (std::string const& i : tmp) { if (emitted.insert(i).second) { out.push_back(i); @@ -1753,9 +1720,7 @@ void cmComputeLinkInformation::GetRPath(std::vector<std::string>& runtimeDirs, d = d.substr(rootPath.size()); } else if (stagePath && *stagePath && d.find(stagePath) == 0) { std::string suffix = d.substr(strlen(stagePath)); - d = installPrefix; - d += "/"; - d += suffix; + d = cmStrCat(installPrefix, '/', suffix); cmSystemTools::ConvertToUnixSlashes(d); } else if (use_relative_build_rpath) { // If expansion of the $ORIGIN token is supported and permitted per @@ -1764,7 +1729,7 @@ void cmComputeLinkInformation::GetRPath(std::vector<std::string>& runtimeDirs, cmSystemTools::IsSubDirectory(d, topBinaryDir)) { d = cmSystemTools::RelativePath(targetOutputDir, d); if (!d.empty()) { - d = originToken + "/" + d; + d = cmStrCat(originToken, "/", d); } else { d = originToken; } @@ -1786,9 +1751,7 @@ void cmComputeLinkInformation::GetRPath(std::vector<std::string>& runtimeDirs, d = d.substr(rootPath.size()); } else if (stagePath && *stagePath && d.find(stagePath) == 0) { std::string suffix = d.substr(strlen(stagePath)); - d = installPrefix; - d += "/"; - d += suffix; + d = cmStrCat(installPrefix, '/', suffix); cmSystemTools::ConvertToUnixSlashes(d); } if (emitted.insert(d).second) { diff --git a/Source/cmComputeLinkInformation.h b/Source/cmComputeLinkInformation.h index 3be2c7f..784d3fa 100644 --- a/Source/cmComputeLinkInformation.h +++ b/Source/cmComputeLinkInformation.h @@ -56,6 +56,11 @@ public: std::string GetChrpathString() const; std::set<cmGeneratorTarget const*> const& GetSharedLibrariesLinked() const; + std::string const& GetLibLinkFileFlag() const + { + return this->LibLinkFileFlag; + } + std::string const& GetRPathLinkFlag() const { return this->RPathLinkFlag; } std::string GetRPathLinkString() const; diff --git a/Source/cmConditionEvaluator.cxx b/Source/cmConditionEvaluator.cxx index 5b88807..d72f561 100644 --- a/Source/cmConditionEvaluator.cxx +++ b/Source/cmConditionEvaluator.cxx @@ -3,7 +3,6 @@ #include "cmConditionEvaluator.h" #include "cmsys/RegularExpression.hxx" -#include <algorithm> #include <functional> #include <sstream> #include <stdio.h> @@ -220,10 +219,10 @@ bool cmConditionEvaluator::GetBooleanValue( } // Check named constants. - if (cmSystemTools::IsOn(arg.c_str())) { + if (cmIsOn(arg.GetValue())) { return true; } - if (cmSystemTools::IsOff(arg.c_str())) { + if (cmIsOff(arg.GetValue())) { return false; } @@ -239,7 +238,7 @@ bool cmConditionEvaluator::GetBooleanValue( // Check definition. const char* def = this->GetDefinitionIfUnquoted(arg); - return !cmSystemTools::IsOff(def); + return !cmIsOff(def); } //========================================================================= @@ -256,14 +255,14 @@ bool cmConditionEvaluator::GetBooleanValueOld( return true; } const char* def = this->GetDefinitionIfUnquoted(arg); - return !cmSystemTools::IsOff(def); + return !cmIsOff(def); } // Old GetVariableOrNumber behavior. const char* def = this->GetDefinitionIfUnquoted(arg); if (!def && atoi(arg.c_str())) { def = arg.c_str(); } - return !cmSystemTools::IsOff(def); + return !cmIsOff(def); } //========================================================================= @@ -670,9 +669,9 @@ bool cmConditionEvaluator::HandleLevel2(cmArgumentList& newArgs, if (def2) { std::vector<std::string> list; - cmSystemTools::ExpandListArgument(def2, list, true); + cmExpandList(def2, list, true); - result = std::find(list.begin(), list.end(), def) != list.end(); + result = cmContains(list, def); } this->HandleBinaryOp(result, reducible, arg, newArgs, argP1, argP2); diff --git a/Source/cmConfigure.cmake.h.in b/Source/cmConfigure.cmake.h.in index 19b1cd4..4de1c5d 100644 --- a/Source/cmConfigure.cmake.h.in +++ b/Source/cmConfigure.cmake.h.in @@ -26,4 +26,8 @@ #define CM_FALLTHROUGH cmsys_FALLTHROUGH +#if defined(_WIN32) && !defined(NOMINMAX) +# define NOMINMAX +#endif + #endif diff --git a/Source/cmConfigureFileCommand.cxx b/Source/cmConfigureFileCommand.cxx index 0917d11..7e37f32 100644 --- a/Source/cmConfigureFileCommand.cxx +++ b/Source/cmConfigureFileCommand.cxx @@ -4,76 +4,78 @@ #include <sstream> +#include "cmExecutionStatus.h" #include "cmMakefile.h" #include "cmMessageType.h" +#include "cmNewLineStyle.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" -class cmExecutionStatus; - // cmConfigureFileCommand -bool cmConfigureFileCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus&) +bool cmConfigureFileCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() < 2) { - this->SetError("called with incorrect number of arguments, expected 2"); + status.SetError("called with incorrect number of arguments, expected 2"); return false; } std::string const& inFile = args[0]; - this->InputFile = cmSystemTools::CollapseFullPath( - inFile, this->Makefile->GetCurrentSourceDirectory()); + const std::string inputFile = cmSystemTools::CollapseFullPath( + inFile, status.GetMakefile().GetCurrentSourceDirectory()); // If the input location is a directory, error out. - if (cmSystemTools::FileIsDirectory(this->InputFile)) { + if (cmSystemTools::FileIsDirectory(inputFile)) { std::ostringstream e; /* clang-format off */ e << "input location\n" - << " " << this->InputFile << "\n" + << " " << inputFile << "\n" << "is a directory but a file was expected."; /* clang-format on */ - this->SetError(e.str()); + status.SetError(e.str()); return false; } std::string const& outFile = args[1]; - this->OutputFile = cmSystemTools::CollapseFullPath( - outFile, this->Makefile->GetCurrentBinaryDirectory()); + std::string outputFile = cmSystemTools::CollapseFullPath( + outFile, status.GetMakefile().GetCurrentBinaryDirectory()); // If the output location is already a directory put the file in it. - if (cmSystemTools::FileIsDirectory(this->OutputFile)) { - this->OutputFile += "/"; - this->OutputFile += cmSystemTools::GetFilenameName(inFile); + if (cmSystemTools::FileIsDirectory(outputFile)) { + outputFile += "/"; + outputFile += cmSystemTools::GetFilenameName(inFile); } - if (!this->Makefile->CanIWriteThisFile(this->OutputFile)) { - std::string e = "attempted to configure a file: " + this->OutputFile + + if (!status.GetMakefile().CanIWriteThisFile(outputFile)) { + std::string e = "attempted to configure a file: " + outputFile + " into a source directory."; - this->SetError(e); + status.SetError(e); cmSystemTools::SetFatalErrorOccured(); return false; } std::string errorMessage; - if (!this->NewLineStyle.ReadFromArguments(args, errorMessage)) { - this->SetError(errorMessage); + cmNewLineStyle newLineStyle; + if (!newLineStyle.ReadFromArguments(args, errorMessage)) { + status.SetError(errorMessage); return false; } - this->CopyOnly = false; - this->EscapeQuotes = false; + bool copyOnly = false; + bool escapeQuotes = false; std::string unknown_args; - this->AtOnly = false; + bool atOnly = false; for (unsigned int i = 2; i < args.size(); ++i) { if (args[i] == "COPYONLY") { - this->CopyOnly = true; - if (this->NewLineStyle.IsValid()) { - this->SetError("COPYONLY could not be used in combination " - "with NEWLINE_STYLE"); + copyOnly = true; + if (newLineStyle.IsValid()) { + status.SetError("COPYONLY could not be used in combination " + "with NEWLINE_STYLE"); return false; } } else if (args[i] == "ESCAPE_QUOTES") { - this->EscapeQuotes = true; + escapeQuotes = true; } else if (args[i] == "@ONLY") { - this->AtOnly = true; + atOnly = true; } else if (args[i] == "IMMEDIATE") { /* Ignore legacy option. */ } else if (args[i] == "NEWLINE_STYLE" || args[i] == "LF" || @@ -87,22 +89,16 @@ bool cmConfigureFileCommand::InitialPass(std::vector<std::string> const& args, } } if (!unknown_args.empty()) { - std::string msg = "configure_file called with unknown argument(s):\n"; - msg += unknown_args; - this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, msg); + std::string msg = cmStrCat( + "configure_file called with unknown argument(s):\n", unknown_args); + status.GetMakefile().IssueMessage(MessageType::AUTHOR_WARNING, msg); } - if (!this->ConfigureFile()) { - this->SetError("Problem configuring file"); + if (!status.GetMakefile().ConfigureFile( + inputFile, outputFile, copyOnly, atOnly, escapeQuotes, newLineStyle)) { + status.SetError("Problem configuring file"); return false; } return true; } - -int cmConfigureFileCommand::ConfigureFile() -{ - return this->Makefile->ConfigureFile(this->InputFile, this->OutputFile, - this->CopyOnly, this->AtOnly, - this->EscapeQuotes, this->NewLineStyle); -} diff --git a/Source/cmConfigureFileCommand.h b/Source/cmConfigureFileCommand.h index b3a99d7..c7f95b8 100644 --- a/Source/cmConfigureFileCommand.h +++ b/Source/cmConfigureFileCommand.h @@ -8,38 +8,8 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" -#include "cmNewLineStyle.h" - class cmExecutionStatus; -class cmConfigureFileCommand : public cmCommand -{ -public: - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmConfigureFileCommand>(); - } - - /** - * This is called when the command is first encountered in - * the input file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; - -private: - int ConfigureFile(); - - cmNewLineStyle NewLineStyle; - - std::string InputFile; - std::string OutputFile; - bool CopyOnly = false; - bool EscapeQuotes = false; - bool AtOnly = false; -}; - +bool cmConfigureFileCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmContinueCommand.cxx b/Source/cmContinueCommand.cxx index 48f1f41..bb63dff 100644 --- a/Source/cmContinueCommand.cxx +++ b/Source/cmContinueCommand.cxx @@ -8,13 +8,14 @@ #include "cmSystemTools.h" // cmContinueCommand -bool cmContinueCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) +bool cmContinueCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { - if (!this->Makefile->IsLoopBlock()) { - this->Makefile->IssueMessage(MessageType::FATAL_ERROR, - "A CONTINUE command was found outside of a " - "proper FOREACH or WHILE loop scope."); + if (!status.GetMakefile().IsLoopBlock()) { + status.GetMakefile().IssueMessage( + MessageType::FATAL_ERROR, + "A CONTINUE command was found outside of a " + "proper FOREACH or WHILE loop scope."); cmSystemTools::SetFatalErrorOccured(); return true; } @@ -22,9 +23,10 @@ bool cmContinueCommand::InitialPass(std::vector<std::string> const& args, status.SetContinueInvoked(); if (!args.empty()) { - this->Makefile->IssueMessage(MessageType::FATAL_ERROR, - "The CONTINUE command does not accept any " - "arguments."); + status.GetMakefile().IssueMessage( + MessageType::FATAL_ERROR, + "The CONTINUE command does not accept any " + "arguments."); cmSystemTools::SetFatalErrorOccured(); return true; } diff --git a/Source/cmContinueCommand.h b/Source/cmContinueCommand.h index a85010a..ff903aa 100644 --- a/Source/cmContinueCommand.h +++ b/Source/cmContinueCommand.h @@ -8,34 +8,14 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -/** \class cmContinueCommand +/** * \brief Continue from an enclosing foreach or while loop * * cmContinueCommand returns from an enclosing foreach or while loop */ -class cmContinueCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmContinueCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; -}; +bool cmContinueCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmCoreTryCompile.cxx b/Source/cmCoreTryCompile.cxx index d2a4148..f696b95 100644 --- a/Source/cmCoreTryCompile.cxx +++ b/Source/cmCoreTryCompile.cxx @@ -234,11 +234,11 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv, } else if (doing == DoingCMakeFlags) { cmakeFlags.push_back(argv[i]); } else if (doing == DoingCompileDefinitions) { - cmSystemTools::ExpandListArgument(argv[i], compileDefs); + cmExpandList(argv[i], compileDefs); } else if (doing == DoingLinkOptions) { linkOptions.push_back(argv[i]); } else if (doing == DoingLinkLibraries) { - libsToLink += "\"" + cmSystemTools::TrimWhitespace(argv[i]) + "\" "; + libsToLink += "\"" + cmTrimWhitespace(argv[i]) + "\" "; if (cmTarget* tgt = this->Makefile->FindTargetToUse(argv[i])) { switch (tgt->GetType()) { case cmStateEnums::SHARED_LIBRARY: @@ -411,8 +411,7 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv, // compute the binary dir when TRY_COMPILE is called with a src file // signature if (this->SrcFileSignature) { - this->BinaryDirectory += "/CMakeFiles"; - this->BinaryDirectory += "/CMakeTmp"; + this->BinaryDirectory += "/CMakeFiles/CMakeTmp"; } else { // only valid for srcfile signatures if (!compileDefs.empty()) { @@ -514,7 +513,7 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv, for (std::string const& li : testLangs) { projectLangs += " " + li; std::string rulesOverrideBase = "CMAKE_USER_MAKE_RULES_OVERRIDE"; - std::string rulesOverrideLang = rulesOverrideBase + "_" + li; + std::string rulesOverrideLang = cmStrCat(rulesOverrideBase, "_", li); if (const char* rulesOverridePath = this->Makefile->GetDefinition(rulesOverrideLang)) { fprintf(fout, "set(%s \"%s\")\n", rulesOverrideLang.c_str(), @@ -574,7 +573,8 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv, std::string const cfg = !tcConfig.empty() ? cmSystemTools::UpperCase(tcConfig) : cfgDefault; for (std::string const& li : testLangs) { - std::string const langFlagsCfg = "CMAKE_" + li + "_FLAGS_" + cfg; + std::string const langFlagsCfg = + cmStrCat("CMAKE_", li, "_FLAGS_", cfg); const char* flagsCfg = this->Makefile->GetDefinition(langFlagsCfg); fprintf(fout, "set(%s %s)\n", langFlagsCfg.c_str(), cmOutputConverter::EscapeForCMake(flagsCfg ? flagsCfg : "") @@ -675,7 +675,7 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv, if (const char* varListStr = this->Makefile->GetDefinition( kCMAKE_TRY_COMPILE_PLATFORM_VARIABLES)) { std::vector<std::string> varList; - cmSystemTools::ExpandListArgument(varListStr, varList); + cmExpandList(varListStr, varList); vars.insert(varList.begin(), varList.end()); } @@ -1045,16 +1045,14 @@ void cmCoreTryCompile::FindOutputFile(const std::string& targetName, this->Makefile->GetDefinition("CMAKE_TRY_COMPILE_CONFIGURATION"); // if a config was specified try that first if (config && config[0]) { - std::string tmp = "/"; - tmp += config; + std::string tmp = cmStrCat('/', config); searchDirs.push_back(std::move(tmp)); } searchDirs.emplace_back("/Debug"); #if defined(__APPLE__) std::string app = "/" + targetName + ".app"; if (config && config[0]) { - std::string tmp = "/"; - tmp += config + app; + std::string tmp = cmStrCat('/', config, app); searchDirs.push_back(std::move(tmp)); } std::string tmp = "/Debug" + app; @@ -1064,9 +1062,7 @@ void cmCoreTryCompile::FindOutputFile(const std::string& targetName, searchDirs.emplace_back("/Development"); for (std::string const& sdir : searchDirs) { - std::string command = this->BinaryDirectory; - command += sdir; - command += tmpOutputFile; + std::string command = cmStrCat(this->BinaryDirectory, sdir, tmpOutputFile); if (cmSystemTools::FileExists(command)) { this->OutputFile = cmSystemTools::CollapseFullPath(command); return; diff --git a/Source/cmCreateTestSourceList.cxx b/Source/cmCreateTestSourceList.cxx index 427db72..4a1825f 100644 --- a/Source/cmCreateTestSourceList.cxx +++ b/Source/cmCreateTestSourceList.cxx @@ -6,6 +6,7 @@ #include "cmMakefile.h" #include "cmSourceFile.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" class cmExecutionStatus; @@ -31,17 +32,14 @@ bool cmCreateTestSourceList::InitialPass(std::vector<std::string> const& args, this->SetError("incorrect arguments to EXTRA_INCLUDE"); return false; } - extraInclude = "#include \""; - extraInclude += *i; - extraInclude += "\"\n"; + extraInclude = cmStrCat("#include \"", *i, "\"\n"); } else if (*i == "FUNCTION") { ++i; if (i == args.end()) { this->SetError("incorrect arguments to FUNCTION"); return false; } - function = *i; - function += "(&ac, &av);\n"; + function = cmStrCat(*i, "(&ac, &av);\n"); } else { tests.push_back(*i); } @@ -60,9 +58,8 @@ bool cmCreateTestSourceList::InitialPass(std::vector<std::string> const& args, "You must specify a file extension for the test driver file."); return false; } - std::string driver = this->Makefile->GetCurrentBinaryDirectory(); - driver += "/"; - driver += *i; + std::string driver = + cmStrCat(this->Makefile->GetCurrentBinaryDirectory(), '/', *i); ++i; std::string configFile = cmSystemTools::GetCMakeRoot(); diff --git a/Source/cmCryptoHash.cxx b/Source/cmCryptoHash.cxx index 5e919af..f9f9581 100644 --- a/Source/cmCryptoHash.cxx +++ b/Source/cmCryptoHash.cxx @@ -6,8 +6,6 @@ #include "cm_rhash.h" #include "cmsys/FStream.hxx" -#include <string.h> - #include "cm_memory.hxx" static unsigned int const cmCryptoHashAlgoToId[] = { @@ -46,36 +44,36 @@ cmCryptoHash::~cmCryptoHash() rhash_free(this->CTX); } -std::unique_ptr<cmCryptoHash> cmCryptoHash::New(const char* algo) +std::unique_ptr<cmCryptoHash> cmCryptoHash::New(cm::string_view algo) { - if (strcmp(algo, "MD5") == 0) { + if (algo == "MD5") { return cm::make_unique<cmCryptoHash>(AlgoMD5); } - if (strcmp(algo, "SHA1") == 0) { + if (algo == "SHA1") { return cm::make_unique<cmCryptoHash>(AlgoSHA1); } - if (strcmp(algo, "SHA224") == 0) { + if (algo == "SHA224") { return cm::make_unique<cmCryptoHash>(AlgoSHA224); } - if (strcmp(algo, "SHA256") == 0) { + if (algo == "SHA256") { return cm::make_unique<cmCryptoHash>(AlgoSHA256); } - if (strcmp(algo, "SHA384") == 0) { + if (algo == "SHA384") { return cm::make_unique<cmCryptoHash>(AlgoSHA384); } - if (strcmp(algo, "SHA512") == 0) { + if (algo == "SHA512") { return cm::make_unique<cmCryptoHash>(AlgoSHA512); } - if (strcmp(algo, "SHA3_224") == 0) { + if (algo == "SHA3_224") { return cm::make_unique<cmCryptoHash>(AlgoSHA3_224); } - if (strcmp(algo, "SHA3_256") == 0) { + if (algo == "SHA3_256") { return cm::make_unique<cmCryptoHash>(AlgoSHA3_256); } - if (strcmp(algo, "SHA3_384") == 0) { + if (algo == "SHA3_384") { return cm::make_unique<cmCryptoHash>(AlgoSHA3_384); } - if (strcmp(algo, "SHA3_512") == 0) { + if (algo == "SHA3_512") { return cm::make_unique<cmCryptoHash>(AlgoSHA3_512); } return std::unique_ptr<cmCryptoHash>(nullptr); @@ -106,6 +104,7 @@ std::string cmCryptoHash::ByteHashToString( '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; std::string res; + res.reserve(hash.size() * 2); for (unsigned char v : hash) { res.push_back(hex[v >> 4]); res.push_back(hex[v & 0xF]); @@ -113,12 +112,10 @@ std::string cmCryptoHash::ByteHashToString( return res; } -std::vector<unsigned char> cmCryptoHash::ByteHashString( - const std::string& input) +std::vector<unsigned char> cmCryptoHash::ByteHashString(cm::string_view input) { this->Initialize(); - this->Append(reinterpret_cast<unsigned char const*>(input.c_str()), - static_cast<int>(input.size())); + this->Append(input); return this->Finalize(); } @@ -156,7 +153,7 @@ std::vector<unsigned char> cmCryptoHash::ByteHashFile(const std::string& file) return std::vector<unsigned char>(); } -std::string cmCryptoHash::HashString(const std::string& input) +std::string cmCryptoHash::HashString(cm::string_view input) { return ByteHashToString(this->ByteHashString(input)); } @@ -176,9 +173,9 @@ void cmCryptoHash::Append(void const* buf, size_t sz) rhash_update(this->CTX, buf, sz); } -void cmCryptoHash::Append(std::string const& str) +void cmCryptoHash::Append(cm::string_view input) { - this->Append(str.c_str(), str.size()); + rhash_update(this->CTX, input.data(), input.size()); } std::vector<unsigned char> cmCryptoHash::Finalize() diff --git a/Source/cmCryptoHash.h b/Source/cmCryptoHash.h index c7d3377..681f5cc 100644 --- a/Source/cmCryptoHash.h +++ b/Source/cmCryptoHash.h @@ -5,6 +5,8 @@ #include "cmConfigure.h" // IWYU pragma: keep +#include "cm_string_view.hxx" + #include <memory> #include <stddef.h> #include <string> @@ -42,7 +44,7 @@ public: /// SHA3_224, SHA3_256, SHA3_384, SHA3_512 /// @return A valid auto pointer if algo is supported or /// an invalid/NULL pointer otherwise - static std::unique_ptr<cmCryptoHash> New(const char* algo); + static std::unique_ptr<cmCryptoHash> New(cm::string_view algo); /// @brief Converts a hex character to its binary value (4 bits) /// @arg input Hex character [0-9a-fA-F]. @@ -55,7 +57,7 @@ public: /// @brief Calculates a binary hash from string input data /// @return Binary hash vector - std::vector<unsigned char> ByteHashString(const std::string& input); + std::vector<unsigned char> ByteHashString(cm::string_view input); /// @brief Calculates a binary hash from file content /// @see ByteHashString() @@ -65,7 +67,7 @@ public: /// @brief Calculates a hash string from string input data /// @return Sequence of hex characters pairs for each byte of the binary hash - std::string HashString(const std::string& input); + std::string HashString(cm::string_view input); /// @brief Calculates a hash string from file content /// @see HashString() @@ -75,7 +77,7 @@ public: void Initialize(); void Append(void const*, size_t); - void Append(std::string const& str); + void Append(cm::string_view input); std::vector<unsigned char> Finalize(); std::string FinalizeHex(); diff --git a/Source/cmCurl.cxx b/Source/cmCurl.cxx index 0004f66..233790e 100644 --- a/Source/cmCurl.cxx +++ b/Source/cmCurl.cxx @@ -7,6 +7,7 @@ # define CMAKE_FIND_CAFILE # include "cmSystemTools.h" #endif +#include "cmStringAlgorithms.h" // curl versions before 7.21.5 did not provide this error code #if defined(LIBCURL_VERSION_NUM) && LIBCURL_VERSION_NUM < 0x071505 @@ -72,8 +73,8 @@ std::string cmCurlSetNETRCOption(::CURL* curl, const std::string& netrc_level, } else if (netrc_level == "IGNORED") { curl_netrc_level = CURL_NETRC_IGNORED; } else { - e = "NETRC accepts OPTIONAL, IGNORED or REQUIRED but got: "; - e += netrc_level; + e = cmStrCat("NETRC accepts OPTIONAL, IGNORED or REQUIRED but got: ", + netrc_level); return e; } } diff --git a/Source/cmCustomCommandGenerator.cxx b/Source/cmCustomCommandGenerator.cxx index 758a69a..82cc037 100644 --- a/Source/cmCustomCommandGenerator.cxx +++ b/Source/cmCustomCommandGenerator.cxx @@ -10,6 +10,7 @@ #include "cmLocalGenerator.h" #include "cmMakefile.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include <memory> @@ -35,7 +36,7 @@ cmCustomCommandGenerator::cmCustomCommandGenerator(cmCustomCommand const& cc, this->GE->Parse(clarg); std::string parsed_arg = cge->Evaluate(this->LG, this->Config); if (this->CC.GetCommandExpandLists()) { - cmAppend(argv, cmSystemTools::ExpandedListArgument(parsed_arg)); + cmAppend(argv, cmExpandedList(parsed_arg)); } else { argv.push_back(std::move(parsed_arg)); } @@ -54,8 +55,8 @@ cmCustomCommandGenerator::cmCustomCommandGenerator(cmCustomCommand const& cc, std::vector<std::string> depends = this->CC.GetDepends(); for (std::string const& d : depends) { std::unique_ptr<cmCompiledGeneratorExpression> cge = this->GE->Parse(d); - std::vector<std::string> result = cmSystemTools::ExpandedListArgument( - cge->Evaluate(this->LG, this->Config)); + std::vector<std::string> result = + cmExpandedList(cge->Evaluate(this->LG, this->Config)); for (std::string& it : result) { if (cmSystemTools::FileIsFullPath(it)) { it = cmSystemTools::CollapseFullPath(it); @@ -108,8 +109,7 @@ void cmCustomCommandGenerator::FillEmulatorsWithArguments() continue; } - cmSystemTools::ExpandListArgument(emulator_property, - this->EmulatorsWithArguments[c]); + cmExpandList(emulator_property, this->EmulatorsWithArguments[c]); } } } @@ -169,9 +169,7 @@ std::string escapeForShellOldStyle(const std::string& str) std::string temp = str; if (temp.find(" ") != std::string::npos && temp.find("\"") == std::string::npos) { - result = "\""; - result += str; - result += "\""; + result = cmStrCat('"', str, '"'); return result; } return str; diff --git a/Source/cmDefinitions.cxx b/Source/cmDefinitions.cxx index 42e70d6..e688890 100644 --- a/Source/cmDefinitions.cxx +++ b/Source/cmDefinitions.cxx @@ -2,8 +2,11 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmDefinitions.h" +#include "cm_string_view.hxx" + #include <assert.h> -#include <set> +#include <functional> +#include <unordered_set> #include <utility> cmDefinitions::Def cmDefinitions::NoDef; @@ -14,7 +17,7 @@ cmDefinitions::Def const& cmDefinitions::GetInternal(const std::string& key, { assert(begin != end); { - MapType::iterator it = begin->Map.find(key); + auto it = begin->Map.find(cm::String::borrow(key)); if (it != begin->Map.end()) { it->second.Used = true; return it->second; @@ -36,7 +39,7 @@ const std::string* cmDefinitions::Get(const std::string& key, StackIter begin, StackIter end) { Def const& def = cmDefinitions::GetInternal(key, begin, end, false); - return def.Exists ? &def.Value : nullptr; + return def.Value ? def.Value.str_if_stable() : nullptr; } void cmDefinitions::Raise(const std::string& key, StackIter begin, @@ -49,50 +52,27 @@ bool cmDefinitions::HasKey(const std::string& key, StackIter begin, StackIter end) { for (StackIter it = begin; it != end; ++it) { - if (it->Map.find(key) != it->Map.end()) { + if (it->Map.find(cm::String::borrow(key)) != it->Map.end()) { return true; } } return false; } -void cmDefinitions::Set(const std::string& key, cm::string_view value) -{ - this->Map[key] = Def(value); -} - -void cmDefinitions::Unset(const std::string& key) -{ - this->Map[key] = Def(); -} - -std::vector<std::string> cmDefinitions::UnusedKeys() const -{ - std::vector<std::string> keys; - keys.reserve(this->Map.size()); - // Consider local definitions. - for (auto const& mi : this->Map) { - if (!mi.second.Used) { - keys.push_back(mi.first); - } - } - return keys; -} - cmDefinitions cmDefinitions::MakeClosure(StackIter begin, StackIter end) { cmDefinitions closure; - std::set<std::string> undefined; + std::unordered_set<cm::string_view> undefined; for (StackIter it = begin; it != end; ++it) { // Consider local definitions. for (auto const& mi : it->Map) { // Use this key if it is not already set or unset. if (closure.Map.find(mi.first) == closure.Map.end() && - undefined.find(mi.first) == undefined.end()) { - if (mi.second.Exists) { + undefined.find(mi.first.view()) == undefined.end()) { + if (mi.second.Value) { closure.Map.insert(mi); } else { - undefined.insert(mi.first); + undefined.emplace(mi.first.view()); } } } @@ -104,17 +84,40 @@ std::vector<std::string> cmDefinitions::ClosureKeys(StackIter begin, StackIter end) { std::vector<std::string> defined; - std::set<std::string> bound; + std::unordered_set<cm::string_view> bound; for (StackIter it = begin; it != end; ++it) { defined.reserve(defined.size() + it->Map.size()); for (auto const& mi : it->Map) { // Use this key if it is not already set or unset. - if (bound.insert(mi.first).second && mi.second.Exists) { - defined.push_back(mi.first); + if (bound.emplace(mi.first.view()).second && mi.second.Value) { + defined.push_back(*mi.first.str_if_stable()); } } } return defined; } + +void cmDefinitions::Set(const std::string& key, cm::string_view value) +{ + this->Map[key] = Def(value); +} + +void cmDefinitions::Unset(const std::string& key) +{ + this->Map[key] = Def(); +} + +std::vector<std::string> cmDefinitions::UnusedKeys() const +{ + std::vector<std::string> keys; + keys.reserve(this->Map.size()); + // Consider local definitions. + for (auto const& mi : this->Map) { + if (!mi.second.Used) { + keys.push_back(*mi.first.str_if_stable()); + } + } + return keys; +} diff --git a/Source/cmDefinitions.h b/Source/cmDefinitions.h index 4d8810a..b4d6419 100644 --- a/Source/cmDefinitions.h +++ b/Source/cmDefinitions.h @@ -8,7 +8,9 @@ #include "cm_string_view.hxx" #include "cmLinkedTree.h" +#include "cmString.hxx" +#include <functional> #include <string> #include <unordered_map> #include <vector> @@ -25,6 +27,8 @@ class cmDefinitions typedef cmLinkedTree<cmDefinitions>::iterator StackIter; public: + // -- Static member functions + static const std::string* Get(const std::string& key, StackIter begin, StackIter end); @@ -32,18 +36,21 @@ public: static bool HasKey(const std::string& key, StackIter begin, StackIter end); + static std::vector<std::string> ClosureKeys(StackIter begin, StackIter end); + + static cmDefinitions MakeClosure(StackIter begin, StackIter end); + + // -- Member functions + /** Set a value associated with a key. */ void Set(const std::string& key, cm::string_view value); /** Unset a definition. */ void Unset(const std::string& key); + /** List of unused keys. */ std::vector<std::string> UnusedKeys() const; - static std::vector<std::string> ClosureKeys(StackIter begin, StackIter end); - - static cmDefinitions MakeClosure(StackIter begin, StackIter end); - private: /** String with existence boolean. */ struct Def @@ -52,17 +59,14 @@ private: Def() = default; Def(cm::string_view value) : Value(value) - , Exists(true) { } - std::string Value; - bool Exists = false; + cm::String Value; bool Used = false; }; static Def NoDef; - typedef std::unordered_map<std::string, Def> MapType; - MapType Map; + std::unordered_map<cm::String, Def> Map; static Def const& GetInternal(const std::string& key, StackIter begin, StackIter end, bool raise); diff --git a/Source/cmDepends.cxx b/Source/cmDepends.cxx index ed76dbf..06a442b 100644 --- a/Source/cmDepends.cxx +++ b/Source/cmDepends.cxx @@ -7,6 +7,7 @@ #include "cmGeneratedFileStream.h" #include "cmLocalGenerator.h" #include "cmMakefile.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmsys/FStream.hxx" @@ -30,7 +31,7 @@ bool cmDepends::Write(std::ostream& makeDepends, std::ostream& internalDepends) { std::string const srcLang = "CMAKE_DEPENDS_CHECK_" + this->Language; cmMakefile* mf = this->LocalGenerator->GetMakefile(); - cmSystemTools::ExpandListArgument(mf->GetSafeDefinition(srcLang), pairs); + cmExpandList(mf->GetSafeDefinition(srcLang), pairs); } for (std::vector<std::string>::iterator si = pairs.begin(); si != pairs.end();) { @@ -235,21 +236,18 @@ void cmDepends::SetIncludePathFromLanguage(const std::string& lang) { // Look for the new per "TARGET_" variant first: const char* includePath = nullptr; - std::string includePathVar = "CMAKE_"; - includePathVar += lang; - includePathVar += "_TARGET_INCLUDE_PATH"; + std::string includePathVar = + cmStrCat("CMAKE_", lang, "_TARGET_INCLUDE_PATH"); cmMakefile* mf = this->LocalGenerator->GetMakefile(); includePath = mf->GetDefinition(includePathVar); if (includePath) { - cmSystemTools::ExpandListArgument(includePath, this->IncludePath); + cmExpandList(includePath, this->IncludePath); } else { // Fallback to the old directory level variable if no per-target var: - includePathVar = "CMAKE_"; - includePathVar += lang; - includePathVar += "_INCLUDE_PATH"; + includePathVar = cmStrCat("CMAKE_", lang, "_INCLUDE_PATH"); includePath = mf->GetDefinition(includePathVar); if (includePath) { - cmSystemTools::ExpandListArgument(includePath, this->IncludePath); + cmExpandList(includePath, this->IncludePath); } } } diff --git a/Source/cmDependsC.cxx b/Source/cmDependsC.cxx index dc49c18..0f9f166 100644 --- a/Source/cmDependsC.cxx +++ b/Source/cmDependsC.cxx @@ -9,6 +9,7 @@ #include "cmFileTime.h" #include "cmLocalGenerator.h" #include "cmMakefile.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #define INCLUDE_REGEX_LINE \ @@ -35,15 +36,12 @@ cmDependsC::cmDependsC(cmLocalGenerator* lg, const std::string& targetDir, std::string scanRegex = "^.*$"; std::string complainRegex = "^$"; { - std::string scanRegexVar = "CMAKE_"; - scanRegexVar += lang; - scanRegexVar += "_INCLUDE_REGEX_SCAN"; + std::string scanRegexVar = cmStrCat("CMAKE_", lang, "_INCLUDE_REGEX_SCAN"); if (const char* sr = mf->GetDefinition(scanRegexVar)) { scanRegex = sr; } - std::string complainRegexVar = "CMAKE_"; - complainRegexVar += lang; - complainRegexVar += "_INCLUDE_REGEX_COMPLAIN"; + std::string complainRegexVar = + cmStrCat("CMAKE_", lang, "_INCLUDE_REGEX_COMPLAIN"); if (const char* cr = mf->GetDefinition(complainRegexVar)) { complainRegex = cr; } @@ -53,17 +51,15 @@ cmDependsC::cmDependsC(cmLocalGenerator* lg, const std::string& targetDir, this->IncludeRegexScan.compile(scanRegex); this->IncludeRegexComplain.compile(complainRegex); this->IncludeRegexLineString = INCLUDE_REGEX_LINE_MARKER INCLUDE_REGEX_LINE; - this->IncludeRegexScanString = INCLUDE_REGEX_SCAN_MARKER; - this->IncludeRegexScanString += scanRegex; - this->IncludeRegexComplainString = INCLUDE_REGEX_COMPLAIN_MARKER; - this->IncludeRegexComplainString += complainRegex; + this->IncludeRegexScanString = + cmStrCat(INCLUDE_REGEX_SCAN_MARKER, scanRegex); + this->IncludeRegexComplainString = + cmStrCat(INCLUDE_REGEX_COMPLAIN_MARKER, complainRegex); this->SetupTransforms(); - this->CacheFileName = this->TargetDirectory; - this->CacheFileName += "/"; - this->CacheFileName += lang; - this->CacheFileName += ".includecache"; + this->CacheFileName = + cmStrCat(this->TargetDirectory, '/', lang, ".includecache"); this->ReadCacheFile(); } @@ -391,7 +387,7 @@ void cmDependsC::SetupTransforms() std::vector<std::string> transformRules; cmMakefile* mf = this->LocalGenerator->GetMakefile(); if (const char* xform = mf->GetDefinition("CMAKE_INCLUDE_TRANSFORMS")) { - cmSystemTools::ExpandListArgument(xform, transformRules, true); + cmExpandList(xform, transformRules, true); } for (std::string const& tr : transformRules) { this->ParseTransform(tr); diff --git a/Source/cmDependsFortran.cxx b/Source/cmDependsFortran.cxx index 764ba30..6c77db9 100644 --- a/Source/cmDependsFortran.cxx +++ b/Source/cmDependsFortran.cxx @@ -82,7 +82,7 @@ cmDependsFortran::cmDependsFortran(cmLocalGenerator* lg) cmMakefile* mf = this->LocalGenerator->GetMakefile(); if (const char* c_defines = mf->GetDefinition("CMAKE_TARGET_DEFINITIONS_Fortran")) { - cmSystemTools::ExpandListArgument(c_defines, definitions); + cmExpandList(c_defines, definitions); } // translate i.e. FOO=BAR to FOO and add it to the list of defined @@ -180,8 +180,7 @@ bool cmDependsFortran::Finalize(std::ostream& makeDepends, } // Store the list of modules provided by this target. - std::string fiName = this->TargetDirectory; - fiName += "/fortran.internal"; + std::string fiName = cmStrCat(this->TargetDirectory, "/fortran.internal"); cmGeneratedFileStream fiStream(fiName); fiStream << "# The fortran modules provided by this target.\n"; fiStream << "provides\n"; @@ -192,23 +191,18 @@ bool cmDependsFortran::Finalize(std::ostream& makeDepends, // Create a script to clean the modules. if (!provides.empty()) { - std::string fcName = this->TargetDirectory; - fcName += "/cmake_clean_Fortran.cmake"; + std::string fcName = + cmStrCat(this->TargetDirectory, "/cmake_clean_Fortran.cmake"); cmGeneratedFileStream fcStream(fcName); fcStream << "# Remove fortran modules provided by this target.\n"; fcStream << "FILE(REMOVE"; std::string currentBinDir = this->LocalGenerator->GetCurrentBinaryDirectory(); for (std::string const& i : provides) { - std::string mod_upper = mod_dir; - mod_upper += "/"; - std::string mod_lower = mod_dir; - mod_lower += "/"; + std::string mod_upper = cmStrCat(mod_dir, '/'); + std::string mod_lower = cmStrCat(mod_dir, '/'); cmFortranModuleAppendUpperLower(i, mod_upper, mod_lower); - std::string stamp = stamp_dir; - stamp += "/"; - stamp += i; - stamp += ".stamp"; + std::string stamp = cmStrCat(stamp_dir, '/', i, ".stamp"); fcStream << "\n"; fcStream << " \"" << this->MaybeConvertToRelativePath(currentBinDir, mod_lower) @@ -254,7 +248,7 @@ void cmDependsFortran::LocateModules() std::vector<std::string> infoFiles; if (const char* infoFilesValue = mf->GetDefinition("CMAKE_TARGET_LINKED_INFO_FILES")) { - cmSystemTools::ExpandListArgument(infoFilesValue, infoFiles); + cmExpandList(infoFilesValue, infoFiles); } for (std::string const& i : infoFiles) { std::string targetDir = cmSystemTools::GetFilenamePath(i); @@ -315,10 +309,7 @@ void cmDependsFortran::ConsiderModule(const std::string& name, if (required != this->Internal->TargetRequires.end() && required->second.empty()) { // The module is provided by a CMake target. It will have a stamp file. - std::string stampFile = stampDir; - stampFile += "/"; - stampFile += name; - stampFile += ".stamp"; + std::string stampFile = cmStrCat(stampDir, '/', name, ".stamp"); required->second = stampFile; } } @@ -392,16 +383,11 @@ bool cmDependsFortran::WriteDependenciesReal(std::string const& obj, // Always use lower case for the mod stamp file name. The // cmake_copy_f90_mod will call back to this class, which will // try various cases for the real mod file name. - std::string modFile = mod_dir; - modFile += "/"; - modFile += i; + std::string modFile = cmStrCat(mod_dir, '/', i); modFile = this->LocalGenerator->ConvertToOutputFormat( this->MaybeConvertToRelativePath(binDir, modFile), cmOutputConverter::SHELL); - std::string stampFile = stamp_dir; - stampFile += "/"; - stampFile += i; - stampFile += ".stamp"; + std::string stampFile = cmStrCat(stamp_dir, '/', i, ".stamp"); stampFile = this->MaybeConvertToRelativePath(binDir, stampFile); std::string const stampFileForShell = this->LocalGenerator->ConvertToOutputFormat(stampFile, @@ -435,8 +421,7 @@ bool cmDependsFortran::WriteDependenciesReal(std::string const& obj, // Make sure the module timestamp rule is evaluated by the time // the target finishes building. - std::string driver = this->TargetDirectory; - driver += "/build"; + std::string driver = cmStrCat(this->TargetDirectory, "/build"); driver = cmSystemTools::ConvertToOutputPath( this->MaybeConvertToRelativePath(binDir, driver)); makeDepends << driver << ": " << obj_m << ".provides.build\n"; @@ -456,18 +441,14 @@ bool cmDependsFortran::FindModule(std::string const& name, std::string& module) std::string fullName; for (std::string const& ip : this->IncludePath) { // Try the lower-case name. - fullName = ip; - fullName += "/"; - fullName += mod_lower; + fullName = cmStrCat(ip, '/', mod_lower); if (cmSystemTools::FileExists(fullName, true)) { module = fullName; return true; } // Try the upper-case name. - fullName = ip; - fullName += "/"; - fullName += mod_upper; + fullName = cmStrCat(ip, '/', mod_upper); if (cmSystemTools::FileExists(fullName, true)) { module = fullName; return true; diff --git a/Source/cmExecProgramCommand.cxx b/Source/cmExecProgramCommand.cxx index bc1d173..7f41640 100644 --- a/Source/cmExecProgramCommand.cxx +++ b/Source/cmExecProgramCommand.cxx @@ -5,18 +5,26 @@ #include "cmsys/Process.h" #include <stdio.h> +#include "cmExecutionStatus.h" #include "cmMakefile.h" #include "cmProcessOutput.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" -class cmExecutionStatus; +typedef cmProcessOutput::Encoding Encoding; + +namespace { +bool RunCommand(std::string command, std::string& output, int& retVal, + const char* directory = nullptr, bool verbose = true, + Encoding encoding = cmProcessOutput::Auto); +} // cmExecProgramCommand -bool cmExecProgramCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus&) +bool cmExecProgramCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.empty()) { - this->SetError("called with incorrect number of arguments"); + status.SetError("called with incorrect number of arguments"); return false; } std::string arguments; @@ -34,7 +42,7 @@ bool cmExecProgramCommand::InitialPass(std::vector<std::string> const& args, haveoutput_variable = true; } else if (haveoutput_variable) { if (!output_variable.empty()) { - this->SetError("called with incorrect number of arguments"); + status.SetError("called with incorrect number of arguments"); return false; } output_variable = arg; @@ -47,7 +55,7 @@ bool cmExecProgramCommand::InitialPass(std::vector<std::string> const& args, havereturn_variable = true; } else if (havereturn_variable) { if (!return_variable.empty()) { - this->SetError("called with incorrect number of arguments"); + status.SetError("called with incorrect number of arguments"); return false; } return_variable = arg; @@ -67,9 +75,8 @@ bool cmExecProgramCommand::InitialPass(std::vector<std::string> const& args, std::string command; if (!arguments.empty()) { - command = cmSystemTools::ConvertToRunCommandPath(args[0]); - command += " "; - command += arguments; + command = cmStrCat(cmSystemTools::ConvertToRunCommandPath(args[0]), ' ', + arguments); } else { command = args[0]; } @@ -82,11 +89,9 @@ bool cmExecProgramCommand::InitialPass(std::vector<std::string> const& args, bool result = true; if (args.size() - count == 2) { cmSystemTools::MakeDirectory(args[1]); - result = cmExecProgramCommand::RunCommand(command, output, retVal, - args[1].c_str(), verbose); + result = RunCommand(command, output, retVal, args[1].c_str(), verbose); } else { - result = cmExecProgramCommand::RunCommand(command, output, retVal, nullptr, - verbose); + result = RunCommand(command, output, retVal, nullptr, verbose); } if (!result) { retVal = -1; @@ -103,21 +108,21 @@ bool cmExecProgramCommand::InitialPass(std::vector<std::string> const& args, } std::string coutput = std::string(output, first, last - first + 1); - this->Makefile->AddDefinition(output_variable, coutput); + status.GetMakefile().AddDefinition(output_variable, coutput); } if (!return_variable.empty()) { char buffer[100]; sprintf(buffer, "%d", retVal); - this->Makefile->AddDefinition(return_variable, buffer); + status.GetMakefile().AddDefinition(return_variable, buffer); } return true; } -bool cmExecProgramCommand::RunCommand(std::string command, std::string& output, - int& retVal, const char* dir, - bool verbose, Encoding encoding) +namespace { +bool RunCommand(std::string command, std::string& output, int& retVal, + const char* dir, bool verbose, Encoding encoding) { if (cmSystemTools::GetRunCommandOutput()) { verbose = false; @@ -187,10 +192,7 @@ bool cmExecProgramCommand::RunCommand(std::string command, std::string& output, #else std::string commandInDir; if (dir) { - commandInDir = "cd \""; - commandInDir += dir; - commandInDir += "\" && "; - commandInDir += command; + commandInDir = cmStrCat("cd \"", dir, "\" && ", command); } else { commandInDir = command; } @@ -284,3 +286,4 @@ bool cmExecProgramCommand::RunCommand(std::string command, std::string& output, return true; } +} diff --git a/Source/cmExecProgramCommand.h b/Source/cmExecProgramCommand.h index 70f833a..7c751e1 100644 --- a/Source/cmExecProgramCommand.h +++ b/Source/cmExecProgramCommand.h @@ -8,43 +8,16 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" -#include "cmProcessOutput.h" - class cmExecutionStatus; -/** \class cmExecProgramCommand +/** * \brief Command that adds a target to the build system. * * cmExecProgramCommand adds an extra target to the build system. * This is useful when you would like to add special * targets like "install,", "clean," and so on. */ -class cmExecProgramCommand : public cmCommand -{ -public: - typedef cmProcessOutput::Encoding Encoding; - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmExecProgramCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; - -private: - static bool RunCommand(std::string command, std::string& output, int& retVal, - const char* directory = nullptr, bool verbose = true, - Encoding encoding = cmProcessOutput::Auto); -}; +bool cmExecProgramCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmExecuteProcessCommand.cxx b/Source/cmExecuteProcessCommand.cxx index 465f4b3..acf2a83 100644 --- a/Source/cmExecuteProcessCommand.cxx +++ b/Source/cmExecuteProcessCommand.cxx @@ -8,20 +8,21 @@ #include <algorithm> #include <ctype.h> /* isspace */ #include <iostream> +#include <memory> #include <stdio.h> #include <vector> #include "cmAlgorithms.h" #include "cmArgumentParser.h" +#include "cmExecutionStatus.h" #include "cmMakefile.h" #include "cmMessageType.h" #include "cmProcessOutput.h" #include "cmStringAlgorithms.h" #include "cmSystemTools.h" -class cmExecutionStatus; - -static bool cmExecuteProcessCommandIsWhitespace(char c) +namespace { +bool cmExecuteProcessCommandIsWhitespace(char c) { return (isspace(static_cast<int>(c)) || c == '\n' || c == '\r'); } @@ -30,13 +31,14 @@ void cmExecuteProcessCommandFixText(std::vector<char>& output, bool strip_trailing_whitespace); void cmExecuteProcessCommandAppend(std::vector<char>& output, const char* data, int length); +} // cmExecuteProcessCommand -bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus&) +bool cmExecuteProcessCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.empty()) { - this->SetError("called with incorrect number of arguments"); + status.SetError("called with incorrect number of arguments"); return false; } @@ -87,31 +89,31 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args, parser.Parse(args, &unparsedArguments, &keywordsMissingValue); if (!keywordsMissingValue.empty()) { - this->SetError(" called with no value for " + - keywordsMissingValue.front() + "."); + status.SetError(" called with no value for " + + keywordsMissingValue.front() + "."); return false; } if (!unparsedArguments.empty()) { - this->SetError(" given unknown argument \"" + unparsedArguments.front() + - "\"."); + status.SetError(" given unknown argument \"" + unparsedArguments.front() + + "\"."); return false; } - if (!this->Makefile->CanIWriteThisFile(arguments.OutputFile)) { - this->SetError("attempted to output into a file: " + arguments.OutputFile + - " into a source directory."); + if (!status.GetMakefile().CanIWriteThisFile(arguments.OutputFile)) { + status.SetError("attempted to output into a file: " + + arguments.OutputFile + " into a source directory."); cmSystemTools::SetFatalErrorOccured(); return false; } // Check for commands given. if (arguments.Commands.empty()) { - this->SetError(" called with no COMMAND argument."); + status.SetError(" called with no COMMAND argument."); return false; } for (std::vector<std::string> const& cmd : arguments.Commands) { if (cmd.empty()) { - this->SetError(" given COMMAND argument with no value."); + status.SetError(" given COMMAND argument with no value."); return false; } } @@ -120,7 +122,7 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args, double timeout = -1; if (!arguments.Timeout.empty()) { if (sscanf(arguments.Timeout.c_str(), "%lg", &timeout) != 1) { - this->SetError(" called with TIMEOUT value that could not be parsed."); + status.SetError(" called with TIMEOUT value that could not be parsed."); return false; } } @@ -180,8 +182,8 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args, bool echo_stdout = false; bool echo_stderr = false; bool echo_output_from_variable = true; - std::string echo_output = - this->Makefile->GetSafeDefinition("CMAKE_EXECUTE_PROCESS_COMMAND_ECHO"); + std::string echo_output = status.GetMakefile().GetSafeDefinition( + "CMAKE_EXECUTE_PROCESS_COMMAND_ECHO"); if (!arguments.CommandEcho.empty()) { echo_output_from_variable = false; echo_output = arguments.CommandEcho; @@ -204,7 +206,7 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args, if (!echo_output_from_variable) { error += " for COMMAND_ECHO."; } - this->Makefile->IssueMessage(MessageType::FATAL_ERROR, error); + status.GetMakefile().IssueMessage(MessageType::FATAL_ERROR, error); return true; } } @@ -278,11 +280,13 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args, // Store the output obtained. if (!arguments.OutputVariable.empty() && !tempOutput.empty()) { - this->Makefile->AddDefinition(arguments.OutputVariable, tempOutput.data()); + status.GetMakefile().AddDefinition(arguments.OutputVariable, + tempOutput.data()); } if (!merge_output && !arguments.ErrorVariable.empty() && !tempError.empty()) { - this->Makefile->AddDefinition(arguments.ErrorVariable, tempError.data()); + status.GetMakefile().AddDefinition(arguments.ErrorVariable, + tempError.data()); } // Store the result of running the process. @@ -292,19 +296,19 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args, int v = cmsysProcess_GetExitValue(cp); char buf[16]; sprintf(buf, "%d", v); - this->Makefile->AddDefinition(arguments.ResultVariable, buf); + status.GetMakefile().AddDefinition(arguments.ResultVariable, buf); } break; case cmsysProcess_State_Exception: - this->Makefile->AddDefinition(arguments.ResultVariable, - cmsysProcess_GetExceptionString(cp)); + status.GetMakefile().AddDefinition( + arguments.ResultVariable, cmsysProcess_GetExceptionString(cp)); break; case cmsysProcess_State_Error: - this->Makefile->AddDefinition(arguments.ResultVariable, - cmsysProcess_GetErrorString(cp)); + status.GetMakefile().AddDefinition(arguments.ResultVariable, + cmsysProcess_GetErrorString(cp)); break; case cmsysProcess_State_Expired: - this->Makefile->AddDefinition(arguments.ResultVariable, - "Process terminated due to timeout"); + status.GetMakefile().AddDefinition( + arguments.ResultVariable, "Process terminated due to timeout"); break; } } @@ -332,20 +336,20 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args, break; } } - this->Makefile->AddDefinition(arguments.ResultsVariable, - cmJoin(res, ";")); + status.GetMakefile().AddDefinition(arguments.ResultsVariable, + cmJoin(res, ";")); } break; case cmsysProcess_State_Exception: - this->Makefile->AddDefinition(arguments.ResultsVariable, - cmsysProcess_GetExceptionString(cp)); + status.GetMakefile().AddDefinition( + arguments.ResultsVariable, cmsysProcess_GetExceptionString(cp)); break; case cmsysProcess_State_Error: - this->Makefile->AddDefinition(arguments.ResultsVariable, - cmsysProcess_GetErrorString(cp)); + status.GetMakefile().AddDefinition(arguments.ResultsVariable, + cmsysProcess_GetErrorString(cp)); break; case cmsysProcess_State_Expired: - this->Makefile->AddDefinition(arguments.ResultsVariable, - "Process terminated due to timeout"); + status.GetMakefile().AddDefinition( + arguments.ResultsVariable, "Process terminated due to timeout"); break; } } @@ -353,6 +357,7 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args, return true; } +namespace { void cmExecuteProcessCommandFixText(std::vector<char>& output, bool strip_trailing_whitespace) { @@ -398,3 +403,4 @@ void cmExecuteProcessCommandAppend(std::vector<char>& output, const char* data, #endif cmAppend(output, data, data + length); } +} diff --git a/Source/cmExecuteProcessCommand.h b/Source/cmExecuteProcessCommand.h index 1d5445f..9c4b600 100644 --- a/Source/cmExecuteProcessCommand.h +++ b/Source/cmExecuteProcessCommand.h @@ -8,35 +8,15 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -/** \class cmExecuteProcessCommand +/** * \brief Command that adds a target to the build system. * * cmExecuteProcessCommand is a CMake language interface to the KWSys * Process Execution implementation. */ -class cmExecuteProcessCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmExecuteProcessCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; -}; +bool cmExecuteProcessCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmExecutionStatus.h b/Source/cmExecutionStatus.h index bcacc2f..654922c 100644 --- a/Source/cmExecutionStatus.h +++ b/Source/cmExecutionStatus.h @@ -22,15 +22,6 @@ public: { } - void Clear() - { - this->Error = "unknown error."; - this->ReturnInvoked = false; - this->BreakInvoked = false; - this->ContinueInvoked = false; - this->NestedError = false; - } - cmMakefile& GetMakefile() { return this->Makefile; } void SetError(std::string const& e) { this->Error = e; } diff --git a/Source/cmExportBuildAndroidMKGenerator.cxx b/Source/cmExportBuildAndroidMKGenerator.cxx index 5edf7ca..f8ce592 100644 --- a/Source/cmExportBuildAndroidMKGenerator.cxx +++ b/Source/cmExportBuildAndroidMKGenerator.cxx @@ -2,10 +2,10 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmExportBuildAndroidMKGenerator.h" -#include <algorithm> #include <sstream> #include <utility> +#include "cmAlgorithms.h" #include "cmGeneratorTarget.h" #include "cmLinkItem.h" #include "cmMakefile.h" @@ -41,8 +41,7 @@ void cmExportBuildAndroidMKGenerator::GenerateImportTargetCode( std::ostream& os, cmGeneratorTarget const* target, cmStateEnums::TargetType /*targetType*/) { - std::string targetName = this->Namespace; - targetName += target->GetExportName(); + std::string targetName = cmStrCat(this->Namespace, target->GetExportName()); os << "include $(CLEAR_VARS)\n"; os << "LOCAL_MODULE := "; os << targetName << "\n"; @@ -145,7 +144,7 @@ void cmExportBuildAndroidMKGenerator::GenerateInterfaceProperties( } else if (property.first == "INTERFACE_INCLUDE_DIRECTORIES") { std::string includes = property.second; std::vector<std::string> includeList; - cmSystemTools::ExpandListArgument(includes, includeList); + cmExpandList(includes, includeList); os << "LOCAL_EXPORT_C_INCLUDES := "; std::string end; for (std::string const& i : includeList) { @@ -156,7 +155,7 @@ void cmExportBuildAndroidMKGenerator::GenerateInterfaceProperties( } else if (property.first == "INTERFACE_LINK_OPTIONS") { os << "LOCAL_EXPORT_LDFLAGS := "; std::vector<std::string> linkFlagsList; - cmSystemTools::ExpandListArgument(property.second, linkFlagsList); + cmExpandList(property.second, linkFlagsList); os << cmJoin(linkFlagsList, " ") << "\n"; } else { os << "# " << property.first << " " << (property.second) << "\n"; @@ -167,8 +166,7 @@ void cmExportBuildAndroidMKGenerator::GenerateInterfaceProperties( // Tell the NDK build system if prebuilt static libraries use C++. if (target->GetType() == cmStateEnums::STATIC_LIBRARY) { cmLinkImplementation const* li = target->GetLinkImplementation(config); - if (std::find(li->Languages.begin(), li->Languages.end(), "CXX") != - li->Languages.end()) { + if (cmContains(li->Languages, "CXX")) { os << "LOCAL_HAS_CPP := true\n"; } } diff --git a/Source/cmExportBuildFileGenerator.cxx b/Source/cmExportBuildFileGenerator.cxx index 33806f2..8a1a305 100644 --- a/Source/cmExportBuildFileGenerator.cxx +++ b/Source/cmExportBuildFileGenerator.cxx @@ -16,7 +16,6 @@ #include "cmTargetExport.h" #include "cmake.h" -#include <algorithm> #include <map> #include <set> #include <sstream> @@ -203,8 +202,7 @@ void cmExportBuildFileGenerator::SetImportLocationProperty( cmMakefile* mf = target->Makefile; if (target->GetType() == cmStateEnums::OBJECT_LIBRARY) { - std::string prop = "IMPORTED_OBJECTS"; - prop += suffix; + std::string prop = cmStrCat("IMPORTED_OBJECTS", suffix); // Compute all the object files inside this target and setup // IMPORTED_OBJECTS as a list of object files @@ -222,8 +220,7 @@ void cmExportBuildFileGenerator::SetImportLocationProperty( } else { // Add the main target file. { - std::string prop = "IMPORTED_LOCATION"; - prop += suffix; + std::string prop = cmStrCat("IMPORTED_LOCATION", suffix); std::string value; if (target->IsAppBundleOnApple()) { value = @@ -237,8 +234,7 @@ void cmExportBuildFileGenerator::SetImportLocationProperty( // Add the import library for windows DLLs. if (target->HasImportLibrary(config)) { - std::string prop = "IMPORTED_IMPLIB"; - prop += suffix; + std::string prop = cmStrCat("IMPORTED_IMPLIB", suffix); std::string value = target->GetFullPath(config, cmStateEnums::ImportLibraryArtifact); if (mf->GetDefinition("CMAKE_IMPORT_LIBRARY_SUFFIX")) { @@ -306,7 +302,7 @@ cmExportBuildFileGenerator::FindBuildExportInfo(cmGlobalGenerator* gg, const cmExportBuildFileGenerator* exportSet = exp.second; std::vector<std::string> targets; exportSet->GetTargets(targets); - if (std::find(targets.begin(), targets.end(), name) != targets.end()) { + if (cmContains(targets, name)) { exportFiles.push_back(exp.first); ns = exportSet->GetNamespace(); } diff --git a/Source/cmExportCommand.cxx b/Source/cmExportCommand.cxx index a849aa2..4046f91 100644 --- a/Source/cmExportCommand.cxx +++ b/Source/cmExportCommand.cxx @@ -5,11 +5,11 @@ #include "cm_static_string_view.hxx" #include "cmsys/RegularExpression.hxx" -#include <algorithm> #include <map> #include <sstream> #include <utility> +#include "cmAlgorithms.h" #include "cmArgumentParser.h" #include "cmExportBuildAndroidMKGenerator.h" #include "cmExportBuildFileGenerator.h" @@ -133,9 +133,7 @@ bool cmExportCommand::InitialPass(std::vector<std::string> const& args, } ExportSet = it->second; } else if (!arguments.Targets.empty() || - std::find(keywordsMissingValue.begin(), - keywordsMissingValue.end(), - "TARGETS") != keywordsMissingValue.end()) { + cmContains(keywordsMissingValue, "TARGETS")) { for (std::string const& currentTarget : arguments.Targets) { if (this->Makefile->IsAlias(currentTarget)) { std::ostringstream e; @@ -301,8 +299,7 @@ void cmExportCommand::StorePackageRegistryWin(std::string const& package, const char* content, const char* hash) { - std::string key = "Software\\Kitware\\CMake\\Packages\\"; - key += package; + std::string key = cmStrCat("Software\\Kitware\\CMake\\Packages\\", package); HKEY hKey; LONG err = RegCreateKeyExW(HKEY_CURRENT_USER, cmsys::Encoding::ToWide(key).c_str(), 0, @@ -336,9 +333,7 @@ void cmExportCommand::StorePackageRegistryDir(std::string const& package, B_OK) { return; } - std::string fname = dir; - fname += "/cmake/packages/"; - fname += package; + std::string fname = cmStrCat(dir, "/cmake/packages/", package); # else std::string fname; if (!cmSystemTools::GetEnv("HOME", fname)) { diff --git a/Source/cmExportFileGenerator.cxx b/Source/cmExportFileGenerator.cxx index 87f9b4c..96733f2 100644 --- a/Source/cmExportFileGenerator.cxx +++ b/Source/cmExportFileGenerator.cxx @@ -500,7 +500,7 @@ void getPropertyContents(cmGeneratorTarget const* tgt, const std::string& prop, return; } std::vector<std::string> content; - cmSystemTools::ExpandListArgument(p, content); + cmExpandList(p, content); ifaceProperties.insert(content.begin(), content.end()); } @@ -584,8 +584,8 @@ void cmExportFileGenerator::GenerateInterfaceProperties( const ImportPropertyMap& properties) { if (!properties.empty()) { - std::string targetName = this->Namespace; - targetName += target->GetExportName(); + std::string targetName = + cmStrCat(this->Namespace, target->GetExportName()); os << "set_target_properties(" << targetName << " PROPERTIES\n"; for (auto const& property : properties) { os << " " << property.first << " " @@ -841,8 +841,8 @@ void cmExportFileGenerator::SetImportDetailProperties( "IMPORTED_LINK_DEPENDENT_LIBRARIES", iface->SharedDeps, properties, dummy); if (iface->Multiplicity > 0) { - std::string prop = "IMPORTED_LINK_INTERFACE_MULTIPLICITY"; - prop += suffix; + std::string prop = + cmStrCat("IMPORTED_LINK_INTERFACE_MULTIPLICITY", suffix); std::ostringstream m; m << iface->Multiplicity; properties[prop] = m.str(); @@ -852,8 +852,7 @@ void cmExportFileGenerator::SetImportDetailProperties( // Add information if this target is a managed target if (target->GetManagedType(config) != cmGeneratorTarget::ManagedType::Native) { - std::string prop = "IMPORTED_COMMON_LANGUAGE_RUNTIME"; - prop += suffix; + std::string prop = cmStrCat("IMPORTED_COMMON_LANGUAGE_RUNTIME", suffix); std::string propval; if (auto* p = target->GetProperty("COMMON_LANGUAGE_RUNTIME")) { propval = p; @@ -904,8 +903,7 @@ void cmExportFileGenerator::SetImportLinkProperty( } // Store the property. - std::string prop = propName; - prop += suffix; + std::string prop = cmStrCat(propName, suffix); properties[prop] = link_entries; } @@ -1182,8 +1180,7 @@ void cmExportFileGenerator::GenerateImportedFileChecksCode( const std::set<std::string>& importedLocations) { // Construct the imported target name. - std::string targetName = this->Namespace; - targetName += target->GetExportName(); + std::string targetName = cmStrCat(this->Namespace, target->GetExportName()); os << "list(APPEND _IMPORT_CHECK_TARGETS " << targetName << " )\n" @@ -1207,7 +1204,7 @@ bool cmExportFileGenerator::PopulateExportProperties( auto& targetProperties = gte->Target->GetProperties(); if (const char* exportProperties = targetProperties.GetPropertyValue("EXPORT_PROPERTIES")) { - for (auto& prop : cmSystemTools::ExpandedListArgument(exportProperties)) { + for (auto& prop : cmExpandedList(exportProperties)) { /* Black list reserved properties */ if (cmHasLiteralPrefix(prop, "IMPORTED_") || cmHasLiteralPrefix(prop, "INTERFACE_")) { diff --git a/Source/cmExportInstallAndroidMKGenerator.cxx b/Source/cmExportInstallAndroidMKGenerator.cxx index 9bc8089..1b536c9 100644 --- a/Source/cmExportInstallAndroidMKGenerator.cxx +++ b/Source/cmExportInstallAndroidMKGenerator.cxx @@ -11,6 +11,7 @@ #include "cmInstallExportGenerator.h" #include "cmInstallTargetGenerator.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmTarget.h" #include "cmTargetExport.h" @@ -58,8 +59,7 @@ void cmExportInstallAndroidMKGenerator::GenerateImportTargetCode( std::ostream& os, cmGeneratorTarget const* target, cmStateEnums::TargetType /*targetType*/) { - std::string targetName = this->Namespace; - targetName += target->GetExportName(); + std::string targetName = cmStrCat(this->Namespace, target->GetExportName()); os << "include $(CLEAR_VARS)\n"; os << "LOCAL_MODULE := "; os << targetName << "\n"; diff --git a/Source/cmExportInstallFileGenerator.cxx b/Source/cmExportInstallFileGenerator.cxx index ab4a62b..e7f301e 100644 --- a/Source/cmExportInstallFileGenerator.cxx +++ b/Source/cmExportInstallFileGenerator.cxx @@ -30,9 +30,7 @@ cmExportInstallFileGenerator::cmExportInstallFileGenerator( std::string cmExportInstallFileGenerator::GetConfigImportFileGlob() { - std::string glob = this->FileBase; - glob += "-*"; - glob += this->FileExt; + std::string glob = cmStrCat(this->FileBase, "-*", this->FileExt); return glob; } @@ -277,10 +275,7 @@ bool cmExportInstallFileGenerator::GenerateImportFileConfig( } // Construct the name of the file to generate. - std::string fileName = this->FileDir; - fileName += "/"; - fileName += this->FileBase; - fileName += "-"; + std::string fileName = cmStrCat(this->FileDir, '/', this->FileBase, '-'); if (!config.empty()) { fileName += cmSystemTools::LowerCase(config); } else { @@ -392,8 +387,7 @@ void cmExportInstallFileGenerator::SetImportLocationProperty( if (itgen->IsImportLibrary()) { // Construct the property name. - std::string prop = "IMPORTED_IMPLIB"; - prop += suffix; + std::string prop = cmStrCat("IMPORTED_IMPLIB", suffix); // Append the installed file name. value += cmInstallTargetGenerator::GetInstallFilename( @@ -404,15 +398,14 @@ void cmExportInstallFileGenerator::SetImportLocationProperty( importedLocations.insert(prop); } else if (itgen->GetTarget()->GetType() == cmStateEnums::OBJECT_LIBRARY) { // Construct the property name. - std::string prop = "IMPORTED_OBJECTS"; - prop += suffix; + std::string prop = cmStrCat("IMPORTED_OBJECTS", suffix); // Compute all the object files inside this target and setup // IMPORTED_OBJECTS as a list of object files std::vector<std::string> objects; itgen->GetInstallObjectNames(config, objects); for (std::string& obj : objects) { - obj = value + obj; + obj = cmStrCat(value, obj); } // Store the property. @@ -420,8 +413,7 @@ void cmExportInstallFileGenerator::SetImportLocationProperty( importedLocations.insert(prop); } else { // Construct the property name. - std::string prop = "IMPORTED_LOCATION"; - prop += suffix; + std::string prop = cmStrCat("IMPORTED_LOCATION", suffix); // Append the installed file name. if (target->IsAppBundleOnApple()) { @@ -458,10 +450,10 @@ void cmExportInstallFileGenerator::HandleMissingTarget( { const std::string name = dependee->GetName(); cmGlobalGenerator* gg = dependee->GetLocalGenerator()->GetGlobalGenerator(); - std::vector<std::string> namespaces = this->FindNamespaces(gg, name); - int targetOccurrences = static_cast<int>(namespaces.size()); - if (targetOccurrences == 1) { - std::string missingTarget = namespaces[0]; + auto exportInfo = this->FindNamespaces(gg, name); + std::vector<std::string> const& exportFiles = exportInfo.first; + if (exportFiles.size() == 1) { + std::string missingTarget = exportInfo.second; missingTarget += dependee->GetExportName(); link_libs += missingTarget; @@ -469,14 +461,16 @@ void cmExportInstallFileGenerator::HandleMissingTarget( } else { // All exported targets should be known here and should be unique. // This is probably user-error. - this->ComplainAboutMissingTarget(depender, dependee, targetOccurrences); + this->ComplainAboutMissingTarget(depender, dependee, exportFiles); } } -std::vector<std::string> cmExportInstallFileGenerator::FindNamespaces( - cmGlobalGenerator* gg, const std::string& name) +std::pair<std::vector<std::string>, std::string> +cmExportInstallFileGenerator::FindNamespaces(cmGlobalGenerator* gg, + const std::string& name) { - std::vector<std::string> namespaces; + std::vector<std::string> exportFiles; + std::string ns; const cmExportSetMap& exportSets = gg->GetExportSets(); for (auto const& expIt : exportSets) { @@ -496,27 +490,33 @@ std::vector<std::string> cmExportInstallFileGenerator::FindNamespaces( std::vector<cmInstallExportGenerator const*> const* installs = exportSet->GetInstallations(); for (cmInstallExportGenerator const* install : *installs) { - namespaces.push_back(install->GetNamespace()); + exportFiles.push_back(install->GetDestinationFile()); + ns = install->GetNamespace(); } } } - return namespaces; + return std::make_pair(exportFiles, ns); } void cmExportInstallFileGenerator::ComplainAboutMissingTarget( - cmGeneratorTarget* depender, cmGeneratorTarget* dependee, int occurrences) + cmGeneratorTarget* depender, cmGeneratorTarget* dependee, + std::vector<std::string> const& exportFiles) { std::ostringstream e; e << "install(EXPORT \"" << this->IEGen->GetExportSet()->GetName() << "\" ...) " << "includes target \"" << depender->GetName() << "\" which requires target \"" << dependee->GetName() << "\" "; - if (occurrences == 0) { - e << "that is not in the export set."; + if (exportFiles.empty()) { + e << "that is not in any export set."; } else { - e << "that is not in this export set, but " << occurrences - << " times in others."; + e << "that is not in this export set, but in multiple other export sets: " + << cmJoin(exportFiles, ", ") << ".\n"; + e << "An exported target cannot depend upon another target which is " + "exported multiple times. Consider consolidating the exports of the " + "\"" + << dependee->GetName() << "\" target to a single export."; } cmSystemTools::Error(e.str()); } diff --git a/Source/cmExportInstallFileGenerator.h b/Source/cmExportInstallFileGenerator.h index cbd6507..fcd1aca 100644 --- a/Source/cmExportInstallFileGenerator.h +++ b/Source/cmExportInstallFileGenerator.h @@ -12,6 +12,7 @@ #include <map> #include <set> #include <string> +#include <utility> #include <vector> class cmGeneratorTarget; @@ -70,10 +71,10 @@ protected: void ComplainAboutMissingTarget(cmGeneratorTarget* depender, cmGeneratorTarget* dependee, - int occurrences); + std::vector<std::string> const& exportFiles); - std::vector<std::string> FindNamespaces(cmGlobalGenerator* gg, - const std::string& name); + std::pair<std::vector<std::string>, std::string> FindNamespaces( + cmGlobalGenerator* gg, const std::string& name); /** Generate the relative import prefix. */ virtual void GenerateImportPrefix(std::ostream&); diff --git a/Source/cmExportLibraryDependenciesCommand.cxx b/Source/cmExportLibraryDependenciesCommand.cxx index 8f2fff5..81237db 100644 --- a/Source/cmExportLibraryDependenciesCommand.cxx +++ b/Source/cmExportLibraryDependenciesCommand.cxx @@ -12,6 +12,7 @@ #include "cmGlobalGenerator.h" #include "cmMakefile.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmTarget.h" #include "cmTargetLinkLibraryType.h" @@ -61,8 +62,7 @@ static void FinalAction(cmMakefile& makefile, std::string const& filename, } // Construct the dependency variable name. - std::string targetEntry = target.GetName(); - targetEntry += "_LIB_DEPENDS"; + std::string targetEntry = cmStrCat(target.GetName(), "_LIB_DEPENDS"); // Construct the dependency variable value with the direct link // dependencies. @@ -71,8 +71,7 @@ static void FinalAction(cmMakefile& makefile, std::string const& filename, cmTarget::LinkLibraryVectorType const& libs = target.GetOriginalLinkLibraries(); for (cmTarget::LibraryID const& li : libs) { - std::string ltVar = li.first; - ltVar += "_LINK_TYPE"; + std::string ltVar = cmStrCat(li.first, "_LINK_TYPE"); std::string ltValue; switch (li.second) { case GENERAL_LibraryType: diff --git a/Source/cmExportTryCompileFileGenerator.cxx b/Source/cmExportTryCompileFileGenerator.cxx index a3c9802..f77fd3a 100644 --- a/Source/cmExportTryCompileFileGenerator.cxx +++ b/Source/cmExportTryCompileFileGenerator.cxx @@ -9,7 +9,7 @@ #include "cmLocalGenerator.h" #include "cmMakefile.h" #include "cmStateTypes.h" -#include "cmSystemTools.h" +#include "cmStringAlgorithms.h" #include "cmTarget.h" #include <map> @@ -104,7 +104,7 @@ void cmExportTryCompileFileGenerator::PopulateProperties( this->FindTargets(p, target, std::string(), emitted); std::vector<std::string> depends; - cmSystemTools::ExpandListArgument(evalResult, depends); + cmExpandList(evalResult, depends); for (std::string const& li : depends) { cmGeneratorTarget* tgt = target->GetLocalGenerator()->FindGeneratorTargetToUse(li); diff --git a/Source/cmExprParserHelper.cxx b/Source/cmExprParserHelper.cxx index 80c78a3..c01e959 100644 --- a/Source/cmExprParserHelper.cxx +++ b/Source/cmExprParserHelper.cxx @@ -3,6 +3,7 @@ #include "cmExprParserHelper.h" #include "cmExprLexer.h" +#include "cmStringAlgorithms.h" #include <iostream> #include <sstream> @@ -41,16 +42,13 @@ int cmExprParserHelper::ParseString(const char* str, int verb) try { int res = cmExpr_yyparse(yyscanner); if (res != 0) { - std::string e = "cannot parse the expression: \"" + InputBuffer + "\": "; - e += ErrorString; - e += "."; + std::string e = cmStrCat("cannot parse the expression: \"", InputBuffer, + "\": ", ErrorString, '.'); this->SetError(std::move(e)); } } catch (std::runtime_error const& fail) { - std::string e = - "cannot evaluate the expression: \"" + InputBuffer + "\": "; - e += fail.what(); - e += "."; + std::string e = cmStrCat("cannot evaluate the expression: \"", InputBuffer, + "\": ", fail.what(), '.'); this->SetError(std::move(e)); } catch (std::out_of_range const&) { std::string e = "cannot evaluate the expression: \"" + InputBuffer + diff --git a/Source/cmExternalMakefileProjectGenerator.cxx b/Source/cmExternalMakefileProjectGenerator.cxx index ac54811..83a0ba6 100644 --- a/Source/cmExternalMakefileProjectGenerator.cxx +++ b/Source/cmExternalMakefileProjectGenerator.cxx @@ -2,6 +2,8 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmExternalMakefileProjectGenerator.h" +#include "cmStringAlgorithms.h" + #include <utility> class cmMakefile; @@ -18,8 +20,7 @@ std::string cmExternalMakefileProjectGenerator::CreateFullGeneratorName( std::string fullName; if (!globalGenerator.empty()) { if (!extraGenerator.empty()) { - fullName = extraGenerator; - fullName += " - "; + fullName = cmStrCat(extraGenerator, " - "); } fullName += globalGenerator; } diff --git a/Source/cmExtraCodeBlocksGenerator.cxx b/Source/cmExtraCodeBlocksGenerator.cxx index f47744b..d8a1a49 100644 --- a/Source/cmExtraCodeBlocksGenerator.cxx +++ b/Source/cmExtraCodeBlocksGenerator.cxx @@ -16,6 +16,7 @@ #include "cmRange.h" #include "cmSourceFile.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmXMLWriter.h" #include "cmake.h" @@ -73,10 +74,9 @@ void cmExtraCodeBlocksGenerator::CreateProjectFile( std::string outputDir = lgs[0]->GetCurrentBinaryDirectory(); std::string projectName = lgs[0]->GetProjectName(); - std::string filename = outputDir + "/"; - filename += projectName + ".cbp"; - std::string sessionFilename = outputDir + "/"; - sessionFilename += projectName + ".layout"; + std::string filename = cmStrCat(outputDir, '/', projectName, ".cbp"); + std::string sessionFilename = + cmStrCat(outputDir, '/', projectName, ".layout"); this->CreateNewProjectFile(lgs, filename); } @@ -178,18 +178,18 @@ void Tree::BuildUnitImpl(cmXMLWriter& xml, { for (std::string const& f : files) { xml.StartElement("Unit"); - xml.Attribute("filename", fsPath + path + "/" + f); + xml.Attribute("filename", cmStrCat(fsPath, path, "/", f)); xml.StartElement("Option"); xml.Attribute("virtualFolder", - "CMake Files\\" + virtualFolderPath + path + "\\"); + cmStrCat("CMake Files\\", virtualFolderPath, path, "\\")); xml.EndElement(); xml.EndElement(); } for (Tree const& folder : folders) { - folder.BuildUnitImpl(xml, virtualFolderPath + path + "\\", - fsPath + path + "/"); + folder.BuildUnitImpl(xml, cmStrCat(virtualFolderPath, path, "\\"), + cmStrCat(fsPath, path, "/")); } } @@ -234,7 +234,7 @@ void cmExtraCodeBlocksGenerator::CreateNewProjectFile( // Also we can disable external (outside the project) files by setting ON // CMAKE_CODEBLOCKS_EXCLUDE_EXTERNAL_FILES variable. const bool excludeExternal = - cmSystemTools::IsOn(it.second[0]->GetMakefile()->GetSafeDefinition( + cmIsOn(it.second[0]->GetMakefile()->GetSafeDefinition( "CMAKE_CODEBLOCKS_EXCLUDE_EXTERNAL_FILES")); if (!splitted.empty() && (!excludeExternal || (relative.find("..") == std::string::npos)) && @@ -318,8 +318,7 @@ void cmExtraCodeBlocksGenerator::CreateNewProjectFile( cmGeneratorTarget* gt = target; this->AppendTarget(xml, targetName, gt, make, lg, compiler, makeArgs); - std::string fastTarget = targetName; - fastTarget += "/fast"; + std::string fastTarget = cmStrCat(targetName, "/fast"); this->AppendTarget(xml, fastTarget, gt, make, lg, compiler, makeArgs); } break; @@ -380,7 +379,7 @@ void cmExtraCodeBlocksGenerator::CreateNewProjectFile( // Do not add this file if it has ".." in relative path and // if CMAKE_CODEBLOCKS_EXCLUDE_EXTERNAL_FILES variable is on. const bool excludeExternal = - cmSystemTools::IsOn(lg->GetMakefile()->GetSafeDefinition( + cmIsOn(lg->GetMakefile()->GetSafeDefinition( "CMAKE_CODEBLOCKS_EXCLUDE_EXTERNAL_FILES")); if (excludeExternal && (relative.find("..") != std::string::npos)) { @@ -412,15 +411,13 @@ void cmExtraCodeBlocksGenerator::CreateNewProjectFile( // A very similar version of that code exists also in the CodeLite // project generator. for (std::string const& fileName : cFiles) { - std::string headerBasename = cmSystemTools::GetFilenamePath(fileName); - headerBasename += "/"; - headerBasename += cmSystemTools::GetFilenameWithoutExtension(fileName); + std::string headerBasename = + cmStrCat(cmSystemTools::GetFilenamePath(fileName), '/', + cmSystemTools::GetFilenameWithoutExtension(fileName)); // check if there's a matching header around for (std::string const& ext : headerExts) { - std::string hname = headerBasename; - hname += "."; - hname += ext; + std::string hname = cmStrCat(headerBasename, '.', ext); // if it's already in the set, don't check if it exists on disk if (allFiles.find(hname) != allFiles.end()) { break; @@ -465,12 +462,9 @@ std::string cmExtraCodeBlocksGenerator::CreateDummyTargetFile( // this file doesn't seem to be used by C::B in custom makefile mode, // but we generate a unique file for each OBJECT library so in case // C::B uses it in some way, the targets don't interfere with each other. - std::string filename = lg->GetCurrentBinaryDirectory(); - filename += "/"; - filename += lg->GetTargetDirectory(target); - filename += "/"; - filename += target->GetName(); - filename += ".objlib"; + std::string filename = cmStrCat(lg->GetCurrentBinaryDirectory(), '/', + lg->GetTargetDirectory(target), '/', + target->GetName(), ".objlib"); cmGeneratedFileStream fout(filename); if (fout) { /* clang-format off */ @@ -490,8 +484,8 @@ void cmExtraCodeBlocksGenerator::AppendTarget( const std::string& compiler, const std::string& makeFlags) { cmMakefile const* makefile = lg->GetMakefile(); - std::string makefileName = lg->GetCurrentBinaryDirectory(); - makefileName += "/Makefile"; + std::string makefileName = + cmStrCat(lg->GetCurrentBinaryDirectory(), "/Makefile"); xml.StartElement("Target"); xml.Attribute("title", targetName); @@ -570,15 +564,13 @@ void cmExtraCodeBlocksGenerator::AppendTarget( std::string systemIncludeDirs = makefile->GetSafeDefinition( "CMAKE_EXTRA_GENERATOR_CXX_SYSTEM_INCLUDE_DIRS"); if (!systemIncludeDirs.empty()) { - cmAppend(allIncludeDirs, - cmSystemTools::ExpandedListArgument(systemIncludeDirs)); + cmAppend(allIncludeDirs, cmExpandedList(systemIncludeDirs)); } systemIncludeDirs = makefile->GetSafeDefinition( "CMAKE_EXTRA_GENERATOR_C_SYSTEM_INCLUDE_DIRS"); if (!systemIncludeDirs.empty()) { - cmAppend(allIncludeDirs, - cmSystemTools::ExpandedListArgument(systemIncludeDirs)); + cmAppend(allIncludeDirs, cmExpandedList(systemIncludeDirs)); } std::vector<std::string>::const_iterator end = diff --git a/Source/cmExtraCodeLiteGenerator.cxx b/Source/cmExtraCodeLiteGenerator.cxx index 30b3f0d..7f71a2c 100644 --- a/Source/cmExtraCodeLiteGenerator.cxx +++ b/Source/cmExtraCodeLiteGenerator.cxx @@ -9,6 +9,7 @@ #include "cmMakefile.h" #include "cmSourceFile.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmXMLWriter.h" #include "cmake.h" @@ -67,8 +68,8 @@ void cmExtraCodeLiteGenerator::Generate() workspaceOutputDir = lg->GetCurrentBinaryDirectory(); workspaceProjectName = lg->GetProjectName(); workspaceSourcePath = lg->GetSourceDirectory(); - workspaceFileName = workspaceOutputDir + "/"; - workspaceFileName += workspaceProjectName + ".workspace"; + workspaceFileName = + cmStrCat(workspaceOutputDir, '/', workspaceProjectName, ".workspace"); this->WorkspacePath = lg->GetCurrentBinaryDirectory(); break; } @@ -121,7 +122,7 @@ std::vector<std::string> cmExtraCodeLiteGenerator::CreateProjectsByTarget( cmStateEnums::TargetType type = lt->GetType(); std::string const& outputDir = lg->GetCurrentBinaryDirectory(); std::string targetName = lt->GetName(); - std::string filename = outputDir + "/" + targetName + ".project"; + std::string filename = cmStrCat(outputDir, "/", targetName, ".project"); retval.push_back(targetName); // Make the project file relative to the workspace std::string relafilename = @@ -131,7 +132,7 @@ std::vector<std::string> cmExtraCodeLiteGenerator::CreateProjectsByTarget( case cmStateEnums::SHARED_LIBRARY: case cmStateEnums::STATIC_LIBRARY: case cmStateEnums::MODULE_LIBRARY: - visualname = "lib" + visualname; + visualname = cmStrCat("lib", visualname); CM_FALLTHROUGH; case cmStateEnums::EXECUTABLE: xml->StartElement("Project"); @@ -161,7 +162,7 @@ std::vector<std::string> cmExtraCodeLiteGenerator::CreateProjectsByProjectMaps( std::string const& outputDir = it.second[0]->GetCurrentBinaryDirectory(); std::string projectName = it.second[0]->GetProjectName(); retval.push_back(projectName); - std::string filename = outputDir + "/" + projectName + ".project"; + std::string filename = cmStrCat(outputDir, "/", projectName, ".project"); // Make the project file relative to the workspace filename = cmSystemTools::RelativePath(this->WorkspacePath, filename); @@ -298,15 +299,13 @@ void cmExtraCodeLiteGenerator::FindMatchingHeaderfiles( // A very similar version of that code exists also in the CodeBlocks // project generator. for (auto const& sit : cFiles) { - std::string headerBasename = cmSystemTools::GetFilenamePath(sit.first); - headerBasename += "/"; - headerBasename += cmSystemTools::GetFilenameWithoutExtension(sit.first); + std::string headerBasename = + cmStrCat(cmSystemTools::GetFilenamePath(sit.first), '/', + cmSystemTools::GetFilenameWithoutExtension(sit.first)); // check if there's a matching header around for (std::string const& ext : headerExts) { - std::string hname = headerBasename; - hname += "."; - hname += ext; + std::string hname = cmStrCat(headerBasename, '.', ext); // if it's already in the set, don't check if it exists on disk std::set<std::string>::const_iterator headerIt = otherFiles.find(hname); if (headerIt != otherFiles.end()) { diff --git a/Source/cmExtraEclipseCDT4Generator.cxx b/Source/cmExtraEclipseCDT4Generator.cxx index 06709f1..5ff638d 100644 --- a/Source/cmExtraEclipseCDT4Generator.cxx +++ b/Source/cmExtraEclipseCDT4Generator.cxx @@ -21,6 +21,7 @@ #include "cmSourceGroup.h" #include "cmState.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmXMLWriter.h" #include "cmake.h" @@ -239,8 +240,7 @@ void cmExtraEclipseCDT4Generator::AddEnvVar(std::ostream& out, std::string envVarValue; const bool envVarSet = cmSystemTools::GetEnv(envVar, envVarValue); - std::string cacheEntryName = "CMAKE_ECLIPSE_ENVVAR_"; - cacheEntryName += envVar; + std::string cacheEntryName = cmStrCat("CMAKE_ECLIPSE_ENVVAR_", envVar); const std::string* cacheValue = lg->GetState()->GetInitializedCacheValue(cacheEntryName); @@ -416,7 +416,7 @@ void cmExtraEclipseCDT4Generator::CreateProjectFile() if (const char* extraNaturesProp = mf->GetState()->GetGlobalProperty("ECLIPSE_EXTRA_NATURES")) { std::vector<std::string> extraNatures; - cmSystemTools::ExpandListArgument(extraNaturesProp, extraNatures); + cmExpandList(extraNaturesProp, extraNatures); for (std::string const& n : extraNatures) { xml.Element("nature", n); } @@ -463,9 +463,7 @@ void cmExtraEclipseCDT4Generator::WriteGroups( cmXMLWriter& xml) { for (cmSourceGroup const& sg : sourceGroups) { - std::string linkName3 = linkName; - linkName3 += "/"; - linkName3 += sg.GetFullName(); + std::string linkName3 = cmStrCat(linkName, '/', sg.GetFullName()); std::replace(linkName3.begin(), linkName3.end(), '\\', '/'); @@ -480,9 +478,8 @@ void cmExtraEclipseCDT4Generator::WriteGroups( std::string const& fullPath = file->GetFullPath(); if (!cmSystemTools::FileIsDirectory(fullPath)) { - std::string linkName4 = linkName3; - linkName4 += "/"; - linkName4 += cmSystemTools::GetFilenameName(fullPath); + std::string linkName4 = + cmStrCat(linkName3, '/', cmSystemTools::GetFilenameName(fullPath)); cmExtraEclipseCDT4Generator::AppendLinkedResource( xml, linkName4, cmExtraEclipseCDT4Generator::GetEclipsePath(fullPath), LinkToFile); @@ -502,8 +499,7 @@ void cmExtraEclipseCDT4Generator::CreateLinksForTargets(cmXMLWriter& xml) const std::vector<cmGeneratorTarget*>& targets = lg->GetGeneratorTargets(); for (cmGeneratorTarget* target : targets) { - std::string linkName2 = linkName; - linkName2 += "/"; + std::string linkName2 = cmStrCat(linkName, '/'); switch (target->GetType()) { case cmStateEnums::EXECUTABLE: case cmStateEnums::STATIC_LIBRARY: @@ -565,8 +561,7 @@ void cmExtraEclipseCDT4Generator::CreateLinksToSubprojects( // .project itself if ((baseDir != linkSourceDirectory) && !cmSystemTools::IsSubDirectory(baseDir, linkSourceDirectory)) { - std::string linkName = "[Subprojects]/"; - linkName += it.first; + std::string linkName = cmStrCat("[Subprojects]/", it.first); cmExtraEclipseCDT4Generator::AppendLinkedResource( xml, linkName, cmExtraEclipseCDT4Generator::GetEclipsePath(linkSourceDirectory), @@ -803,7 +798,7 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const if (this->CEnabled && cDefs) { // Expand the list. std::vector<std::string> defs; - cmSystemTools::ExpandListArgument(cDefs, defs, true); + cmExpandList(cDefs, defs, true); // the list must contain only definition-value pairs: if ((defs.size() % 2) == 0) { @@ -836,7 +831,7 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const if (this->CXXEnabled && cxxDefs) { // Expand the list. std::vector<std::string> defs; - cmSystemTools::ExpandListArgument(cxxDefs, defs, true); + cmExpandList(cxxDefs, defs, true); // the list must contain only definition-value pairs: if ((defs.size() % 2) == 0) { @@ -887,7 +882,7 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const std::string systemIncludeDirs = mf->GetSafeDefinition("CMAKE_EXTRA_GENERATOR_C_SYSTEM_INCLUDE_DIRS"); std::vector<std::string> dirs; - cmSystemTools::ExpandListArgument(systemIncludeDirs, dirs); + cmExpandList(systemIncludeDirs, dirs); this->AppendIncludeDirectories(xml, dirs, emmited); } compiler = mf->GetSafeDefinition("CMAKE_CXX_COMPILER"); @@ -895,7 +890,7 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const std::string systemIncludeDirs = mf->GetSafeDefinition("CMAKE_EXTRA_GENERATOR_CXX_SYSTEM_INCLUDE_DIRS"); std::vector<std::string> dirs; - cmSystemTools::ExpandListArgument(systemIncludeDirs, dirs); + cmExpandList(systemIncludeDirs, dirs); this->AppendIncludeDirectories(xml, dirs, emmited); } @@ -969,28 +964,21 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const : "[lib] "); cmExtraEclipseCDT4Generator::AppendTarget(xml, targetName, make, makeArgs, subdir, prefix); - std::string fastTarget = targetName; - fastTarget += "/fast"; + std::string fastTarget = cmStrCat(targetName, "/fast"); cmExtraEclipseCDT4Generator::AppendTarget(xml, fastTarget, make, makeArgs, subdir, prefix); // Add Build and Clean targets in the virtual folder of targets: if (this->SupportsVirtualFolders) { - std::string virtDir = "[Targets]/"; - virtDir += prefix; - virtDir += targetName; - std::string buildArgs = "-C \""; - buildArgs += lgen->GetBinaryDirectory(); - buildArgs += "\" "; - buildArgs += makeArgs; + std::string virtDir = cmStrCat("[Targets]/", prefix, targetName); + std::string buildArgs = + cmStrCat("-C \"", lgen->GetBinaryDirectory(), "\" ", makeArgs); cmExtraEclipseCDT4Generator::AppendTarget( xml, "Build", make, buildArgs, virtDir, "", targetName.c_str()); - std::string cleanArgs = "-E chdir \""; - cleanArgs += lgen->GetCurrentBinaryDirectory(); - cleanArgs += "\" \""; - cleanArgs += cmSystemTools::GetCMakeCommand(); - cleanArgs += "\" -P \""; + std::string cleanArgs = + cmStrCat("-E chdir \"", lgen->GetCurrentBinaryDirectory(), + "\" \"", cmSystemTools::GetCMakeCommand(), "\" -P \""); cmGeneratorTarget* gt = target; cleanArgs += lgen->GetTargetDirectory(gt); cleanArgs += "/cmake_clean.cmake\""; diff --git a/Source/cmExtraKateGenerator.cxx b/Source/cmExtraKateGenerator.cxx index 877f109..2bfbb0d 100644 --- a/Source/cmExtraKateGenerator.cxx +++ b/Source/cmExtraKateGenerator.cxx @@ -9,6 +9,7 @@ #include "cmMakefile.h" #include "cmSourceFile.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include <ostream> @@ -53,8 +54,7 @@ void cmExtraKateGenerator::Generate() void cmExtraKateGenerator::CreateKateProjectFile( const cmLocalGenerator* lg) const { - std::string filename = lg->GetBinaryDirectory(); - filename += "/.kateproject"; + std::string filename = cmStrCat(lg->GetBinaryDirectory(), "/.kateproject"); cmGeneratedFileStream fout(filename); if (!fout) { return; @@ -164,8 +164,7 @@ void cmExtraKateGenerator::WriteTargets(const cmLocalGenerator* lg, case cmStateEnums::OBJECT_LIBRARY: { this->AppendTarget(fout, targetName, make, makeArgs, currentDir, homeOutputDir); - std::string fastTarget = targetName; - fastTarget += "/fast"; + std::string fastTarget = cmStrCat(targetName, "/fast"); this->AppendTarget(fout, fastTarget, make, makeArgs, currentDir, homeOutputDir); @@ -208,10 +207,8 @@ void cmExtraKateGenerator::AppendTarget(cmGeneratedFileStream& fout, void cmExtraKateGenerator::CreateDummyKateProjectFile( const cmLocalGenerator* lg) const { - std::string filename = lg->GetBinaryDirectory(); - filename += "/"; - filename += this->ProjectName; - filename += ".kateproject"; + std::string filename = + cmStrCat(lg->GetBinaryDirectory(), '/', this->ProjectName, ".kateproject"); cmGeneratedFileStream fout(filename); if (!fout) { return; @@ -224,20 +221,17 @@ void cmExtraKateGenerator::CreateDummyKateProjectFile( std::string cmExtraKateGenerator::GenerateFilesString( const cmLocalGenerator* lg) const { - std::string s = lg->GetSourceDirectory(); - s += "/.git"; + std::string s = cmStrCat(lg->GetSourceDirectory(), "/.git"); if (cmSystemTools::FileExists(s)) { return "\"git\": 1 "; } - s = lg->GetSourceDirectory(); - s += "/.svn"; + s = cmStrCat(lg->GetSourceDirectory(), "/.svn"); if (cmSystemTools::FileExists(s)) { return "\"svn\": 1 "; } - s = lg->GetSourceDirectory(); - s += "/"; + s = cmStrCat(lg->GetSourceDirectory(), '/'); std::set<std::string> files; std::string tmp; diff --git a/Source/cmExtraSublimeTextGenerator.cxx b/Source/cmExtraSublimeTextGenerator.cxx index 71c8fcd..36d9afd 100644 --- a/Source/cmExtraSublimeTextGenerator.cxx +++ b/Source/cmExtraSublimeTextGenerator.cxx @@ -17,6 +17,7 @@ #include "cmMessageType.h" #include "cmSourceFile.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmake.h" @@ -134,7 +135,7 @@ void cmExtraSublimeTextGenerator::CreateNewProjectFile( fout << "\n\t]"; std::string systemName = mf->GetSafeDefinition("CMAKE_SYSTEM_NAME"); std::vector<std::string> tokens; - cmSystemTools::ExpandListArgument(this->EnvSettings, tokens); + cmExpandList(this->EnvSettings, tokens); if (!this->EnvSettings.empty()) { fout << ","; @@ -218,8 +219,7 @@ void cmExtraSublimeTextGenerator::AppendAllTargets( this->AppendTarget(fout, targetName, lg, target, make.c_str(), makefile, compiler.c_str(), sourceFileFlags, false); - std::string fastTarget = targetName; - fastTarget += "/fast"; + std::string fastTarget = cmStrCat(targetName, "/fast"); this->AppendTarget(fout, fastTarget, lg, target, make.c_str(), makefile, compiler.c_str(), sourceFileFlags, false); @@ -266,7 +266,7 @@ void cmExtraSublimeTextGenerator::AppendTarget( R"((^|[ ])-[DIOUWfgs][^= ]+(=\"[^"]+\"|=[^"][^ ]+)?)"; flagRegex.compile(regexString); std::string workString = - flagsString + " " + definesString + " " + includesString; + cmStrCat(flagsString, " ", definesString, " ", includesString); while (flagRegex.find(workString)) { std::string::size_type start = flagRegex.start(); if (workString[start] == ' ') { @@ -310,8 +310,7 @@ void cmExtraSublimeTextGenerator::AppendTarget( std::string cmExtraSublimeTextGenerator::BuildMakeCommand( const std::string& make, const char* makefile, const std::string& target) { - std::string command = "\""; - command += make + "\""; + std::string command = cmStrCat('"', make, '"'); std::string generator = this->GlobalGenerator->GetName(); if (generator == "NMake Makefiles") { std::string makefileName = cmSystemTools::ConvertToOutputPath(makefile); @@ -392,8 +391,8 @@ std::string cmExtraSublimeTextGenerator::ComputeDefines( defines, genexInterpreter.Evaluate(compile_defs, COMPILE_DEFINITIONS)); } - std::string defPropName = "COMPILE_DEFINITIONS_"; - defPropName += cmSystemTools::UpperCase(config); + std::string defPropName = + cmStrCat("COMPILE_DEFINITIONS_", cmSystemTools::UpperCase(config)); if (const char* config_compile_defs = source->GetProperty(defPropName)) { lg->AppendDefines( defines, @@ -444,7 +443,7 @@ bool cmExtraSublimeTextGenerator::Open(const std::string& bindir, if (!sublExecutable) { return false; } - if (cmSystemTools::IsNOTFOUND(sublExecutable)) { + if (cmIsNOTFOUND(sublExecutable)) { return false; } diff --git a/Source/cmFLTKWrapUICommand.cxx b/Source/cmFLTKWrapUICommand.cxx index b7a2b27..2150051 100644 --- a/Source/cmFLTKWrapUICommand.cxx +++ b/Source/cmFLTKWrapUICommand.cxx @@ -8,6 +8,7 @@ #include "cmMakefile.h" #include "cmRange.h" #include "cmSourceFile.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" class cmExecutionStatus; @@ -20,12 +21,11 @@ static void FinalAction(cmMakefile& makefile, std::string const& name) // they didn;t then print a warning and add then anyhow cmTarget* target = makefile.FindLocalNonAliasTarget(name); if (!target) { - std::string msg = - "FLTK_WRAP_UI was called with a target that was never created: "; - msg += name; - msg += ". The problem was found while processing the source directory: "; - msg += makefile.GetCurrentSourceDirectory(); - msg += ". This FLTK_WRAP_UI call will be ignored."; + std::string msg = cmStrCat( + "FLTK_WRAP_UI was called with a target that was never created: ", name, + ". The problem was found while processing the source directory: ", + makefile.GetCurrentSourceDirectory(), + ". This FLTK_WRAP_UI call will be ignored."); cmSystemTools::Message(msg, "Warning"); } } @@ -66,18 +66,15 @@ bool cmFLTKWrapUICommand::InitialPass(std::vector<std::string> const& args, // if we should use the source GUI // to generate .cxx and .h files if (!curr || !curr->GetPropertyAsBool("WRAP_EXCLUDE")) { - std::string outName = outputDirectory; - outName += "/"; - outName += cmSystemTools::GetFilenameWithoutExtension(arg); - std::string hname = outName; - hname += ".h"; - std::string origname = cdir + "/" + arg; + std::string outName = cmStrCat( + outputDirectory, "/", cmSystemTools::GetFilenameWithoutExtension(arg)); + std::string hname = cmStrCat(outName, ".h"); + std::string origname = cmStrCat(cdir, "/", arg); // add starting depends std::vector<std::string> depends; depends.push_back(origname); depends.push_back(fluid_exe); - std::string cxxres = outName; - cxxres += ".cxx"; + std::string cxxres = cmStrCat(outName, ".cxx"); cmCustomCommandLine commandLine; commandLine.push_back(fluid_exe); diff --git a/Source/cmFileAPI.cxx b/Source/cmFileAPI.cxx index 2594287..5d9181a 100644 --- a/Source/cmFileAPI.cxx +++ b/Source/cmFileAPI.cxx @@ -94,7 +94,7 @@ void cmFileAPI::RemoveOldReplyFiles() std::vector<std::string> files = this->LoadDir(reply_dir); for (std::string const& f : files) { if (this->ReplyFiles.find(f) == this->ReplyFiles.end()) { - std::string file = reply_dir + "/" + f; + std::string file = cmStrCat(reply_dir, "/", f); cmSystemTools::RemoveFile(file); } } @@ -407,9 +407,7 @@ const char* cmFileAPI::ObjectKindName(ObjectKind kind) std::string cmFileAPI::ObjectName(Object const& o) { - std::string name = ObjectKindName(o.Kind); - name += "-v"; - name += std::to_string(o.Version); + std::string name = cmStrCat(ObjectKindName(o.Kind), "-v", o.Version); return name; } diff --git a/Source/cmFileAPICodemodel.cxx b/Source/cmFileAPICodemodel.cxx index e9ee7f5..e4b7670 100644 --- a/Source/cmFileAPICodemodel.cxx +++ b/Source/cmFileAPICodemodel.cxx @@ -21,6 +21,7 @@ #include "cmStateDirectory.h" #include "cmStateSnapshot.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmTarget.h" #include "cmTargetDepend.h" @@ -1144,12 +1145,9 @@ Json::Value Target::DumpInstallPrefix() Json::Value Target::DumpInstallDestinations() { Json::Value destinations = Json::arrayValue; - auto installGens = this->GT->Makefile->GetInstallGenerators(); - for (auto iGen : installGens) { - auto itGen = dynamic_cast<cmInstallTargetGenerator*>(iGen); - if (itGen != nullptr && itGen->GetTarget() == this->GT) { - destinations.append(this->DumpInstallDestination(itGen)); - } + auto installGens = this->GT->Target->GetInstallGenerators(); + for (auto itGen : installGens) { + destinations.append(this->DumpInstallDestination(itGen)); } return destinations; } @@ -1273,11 +1271,11 @@ Json::Value Target::DumpLinkCommandFragments() lg->GetTargetFlags(&linkLineComputer, this->Config, linkLibs, linkLanguageFlags, linkFlags, frameworkPath, linkPath, this->GT); - linkLanguageFlags = cmSystemTools::TrimWhitespace(linkLanguageFlags); - linkFlags = cmSystemTools::TrimWhitespace(linkFlags); - frameworkPath = cmSystemTools::TrimWhitespace(frameworkPath); - linkPath = cmSystemTools::TrimWhitespace(linkPath); - linkLibs = cmSystemTools::TrimWhitespace(linkLibs); + linkLanguageFlags = cmTrimWhitespace(linkLanguageFlags); + linkFlags = cmTrimWhitespace(linkFlags); + frameworkPath = cmTrimWhitespace(frameworkPath); + linkPath = cmTrimWhitespace(linkPath); + linkLibs = cmTrimWhitespace(linkLibs); if (!linkLanguageFlags.empty()) { linkFragments.append( diff --git a/Source/cmFileCommand.cxx b/Source/cmFileCommand.cxx index 22f0d1f..5589537 100644 --- a/Source/cmFileCommand.cxx +++ b/Source/cmFileCommand.cxx @@ -25,6 +25,7 @@ #include "cmAlgorithms.h" #include "cmArgumentParser.h" #include "cmCryptoHash.h" +#include "cmExecutionStatus.h" #include "cmFileCopier.h" #include "cmFileInstaller.h" #include "cmFileLockPool.h" @@ -40,12 +41,13 @@ #include "cmRuntimeDependencyArchive.h" #include "cmState.h" #include "cmStringAlgorithms.h" +#include "cmSubcommandTable.h" #include "cmSystemTools.h" #include "cmTimestamp.h" #include "cm_sys_stat.h" #include "cmake.h" -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) # include "cmCurl.h" # include "cmFileLockResult.h" # include "cm_curl.h" @@ -59,10 +61,12 @@ # include <windows.h> #endif +namespace { + #if defined(_WIN32) // libcurl doesn't support file:// urls for unicode filenames on Windows. // Convert string from UTF-8 to ACP if this is a file:// URL. -static std::string fix_file_url_windows(const std::string& url) +std::string fix_file_url_windows(const std::string& url) { std::string ret = url; if (strncmp(url.c_str(), "file://", 7) == 0) { @@ -84,123 +88,8 @@ static std::string fix_file_url_windows(const std::string& url) } #endif -// cmLibraryCommand -bool cmFileCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus&) -{ - if (args.size() < 2) { - this->SetError("must be called with at least two arguments."); - return false; - } - std::string const& subCommand = args[0]; - if (subCommand == "WRITE") { - return this->HandleWriteCommand(args, false); - } - if (subCommand == "APPEND") { - return this->HandleWriteCommand(args, true); - } - if (subCommand == "DOWNLOAD") { - return this->HandleDownloadCommand(args); - } - if (subCommand == "UPLOAD") { - return this->HandleUploadCommand(args); - } - if (subCommand == "READ") { - return this->HandleReadCommand(args); - } - if (subCommand == "MD5" || subCommand == "SHA1" || subCommand == "SHA224" || - subCommand == "SHA256" || subCommand == "SHA384" || - subCommand == "SHA512" || subCommand == "SHA3_224" || - subCommand == "SHA3_256" || subCommand == "SHA3_384" || - subCommand == "SHA3_512") { - return this->HandleHashCommand(args); - } - if (subCommand == "STRINGS") { - return this->HandleStringsCommand(args); - } - if (subCommand == "GLOB") { - return this->HandleGlobCommand(args, false); - } - if (subCommand == "GLOB_RECURSE") { - return this->HandleGlobCommand(args, true); - } - if (subCommand == "MAKE_DIRECTORY") { - return this->HandleMakeDirectoryCommand(args); - } - if (subCommand == "RENAME") { - return this->HandleRename(args); - } - if (subCommand == "REMOVE") { - return this->HandleRemove(args, false); - } - if (subCommand == "REMOVE_RECURSE") { - return this->HandleRemove(args, true); - } - if (subCommand == "COPY") { - return this->HandleCopyCommand(args); - } - if (subCommand == "INSTALL") { - return this->HandleInstallCommand(args); - } - if (subCommand == "DIFFERENT") { - return this->HandleDifferentCommand(args); - } - if (subCommand == "RPATH_CHANGE" || subCommand == "CHRPATH") { - return this->HandleRPathChangeCommand(args); - } - if (subCommand == "RPATH_CHECK") { - return this->HandleRPathCheckCommand(args); - } - if (subCommand == "RPATH_REMOVE") { - return this->HandleRPathRemoveCommand(args); - } - if (subCommand == "READ_ELF") { - return this->HandleReadElfCommand(args); - } - if (subCommand == "RELATIVE_PATH") { - return this->HandleRelativePathCommand(args); - } - if (subCommand == "TO_CMAKE_PATH") { - return this->HandleCMakePathCommand(args, false); - } - if (subCommand == "TO_NATIVE_PATH") { - return this->HandleCMakePathCommand(args, true); - } - if (subCommand == "TOUCH") { - return this->HandleTouchCommand(args, true); - } - if (subCommand == "TOUCH_NOCREATE") { - return this->HandleTouchCommand(args, false); - } - if (subCommand == "TIMESTAMP") { - return this->HandleTimestampCommand(args); - } - if (subCommand == "GENERATE") { - return this->HandleGenerateCommand(args); - } - if (subCommand == "LOCK") { - return this->HandleLockCommand(args); - } - if (subCommand == "SIZE") { - return this->HandleSizeCommand(args); - } - if (subCommand == "READ_SYMLINK") { - return this->HandleReadSymlinkCommand(args); - } - if (subCommand == "CREATE_LINK") { - return this->HandleCreateLinkCommand(args); - } - if (subCommand == "GET_RUNTIME_DEPENDENCIES") { - return this->HandleGetRuntimeDependenciesCommand(args); - } - - std::string e = "does not recognize sub-command " + subCommand; - this->SetError(e); - return false; -} - -bool cmFileCommand::HandleWriteCommand(std::vector<std::string> const& args, - bool append) +bool HandleWriteImpl(std::vector<std::string> const& args, bool append, + cmExecutionStatus& status) { std::vector<std::string>::const_iterator i = args.begin(); @@ -208,16 +97,16 @@ bool cmFileCommand::HandleWriteCommand(std::vector<std::string> const& args, std::string fileName = *i; if (!cmsys::SystemTools::FileIsFullPath(*i)) { - fileName = this->Makefile->GetCurrentSourceDirectory(); - fileName += "/" + *i; + fileName = + cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', *i); } i++; - if (!this->Makefile->CanIWriteThisFile(fileName)) { + if (!status.GetMakefile().CanIWriteThisFile(fileName)) { std::string e = "attempted to write a file: " + fileName + " into a source directory."; - this->SetError(e); + status.SetError(e); cmSystemTools::SetFatalErrorOccured(); return false; } @@ -245,21 +134,19 @@ bool cmFileCommand::HandleWriteCommand(std::vector<std::string> const& args, cmsys::ofstream file(fileName.c_str(), append ? std::ios::app : std::ios::out); if (!file) { - std::string error = "failed to open for writing ("; - error += cmSystemTools::GetLastSystemError(); - error += "):\n "; - error += fileName; - this->SetError(error); + std::string error = + cmStrCat("failed to open for writing (", + cmSystemTools::GetLastSystemError(), "):\n ", fileName); + status.SetError(error); return false; } std::string message = cmJoin(cmMakeRange(i, args.end()), std::string()); file << message; if (!file) { - std::string error = "write failed ("; - error += cmSystemTools::GetLastSystemError(); - error += "):\n "; - error += fileName; - this->SetError(error); + std::string error = + cmStrCat("write failed (", cmSystemTools::GetLastSystemError(), "):\n ", + fileName); + status.SetError(error); return false; } file.close(); @@ -269,11 +156,24 @@ bool cmFileCommand::HandleWriteCommand(std::vector<std::string> const& args, return true; } -bool cmFileCommand::HandleReadCommand(std::vector<std::string> const& args) +bool HandleWriteCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) +{ + return HandleWriteImpl(args, false, status); +} + +bool HandleAppendCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) +{ + return HandleWriteImpl(args, true, status); +} + +bool HandleReadCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() < 3) { - this->SetError("READ must be called with at least two additional " - "arguments"); + status.SetError("READ must be called with at least two additional " + "arguments"); return false; } @@ -296,8 +196,8 @@ bool cmFileCommand::HandleReadCommand(std::vector<std::string> const& args) std::string fileName = fileNameArg; if (!cmsys::SystemTools::FileIsFullPath(fileName)) { - fileName = this->Makefile->GetCurrentSourceDirectory(); - fileName += "/" + fileNameArg; + fileName = cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', + fileNameArg); } // Open the specified file. @@ -310,11 +210,10 @@ bool cmFileCommand::HandleReadCommand(std::vector<std::string> const& args) #endif if (!file) { - std::string error = "failed to open for reading ("; - error += cmSystemTools::GetLastSystemError(); - error += "):\n "; - error += fileName; - this->SetError(error); + std::string error = + cmStrCat("failed to open for reading (", + cmSystemTools::GetLastSystemError(), "):\n ", fileName); + status.SetError(error); return false; } @@ -366,53 +265,55 @@ bool cmFileCommand::HandleReadCommand(std::vector<std::string> const& args) } } } - this->Makefile->AddDefinition(variable, output); + status.GetMakefile().AddDefinition(variable, output); return true; } -bool cmFileCommand::HandleHashCommand(std::vector<std::string> const& args) +bool HandleHashCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) if (args.size() != 3) { std::ostringstream e; e << args[0] << " requires a file name and output variable"; - this->SetError(e.str()); + status.SetError(e.str()); return false; } - std::unique_ptr<cmCryptoHash> hash(cmCryptoHash::New(args[0].c_str())); + std::unique_ptr<cmCryptoHash> hash(cmCryptoHash::New(args[0])); if (hash) { std::string out = hash->HashFile(args[1]); if (!out.empty()) { - this->Makefile->AddDefinition(args[2], out); + status.GetMakefile().AddDefinition(args[2], out); return true; } std::ostringstream e; e << args[0] << " failed to read file \"" << args[1] << "\": " << cmSystemTools::GetLastSystemError(); - this->SetError(e.str()); + status.SetError(e.str()); } return false; #else std::ostringstream e; e << args[0] << " not available during bootstrap"; - this->SetError(e.str()); + status.SetError(e.str()); return false; #endif } -bool cmFileCommand::HandleStringsCommand(std::vector<std::string> const& args) +bool HandleStringsCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() < 3) { - this->SetError("STRINGS requires a file name and output variable"); + status.SetError("STRINGS requires a file name and output variable"); return false; } // Get the file to read. std::string fileName = args[1]; if (!cmsys::SystemTools::FileIsFullPath(fileName)) { - fileName = this->Makefile->GetCurrentSourceDirectory(); - fileName += "/" + args[1]; + fileName = + cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', args[1]); } // Get the variable in which to store the results. @@ -478,7 +379,7 @@ bool cmFileCommand::HandleStringsCommand(std::vector<std::string> const& args) std::ostringstream e; e << "STRINGS option LIMIT_INPUT value \"" << args[i] << "\" is not an unsigned integer."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } arg_mode = arg_none; @@ -488,7 +389,7 @@ bool cmFileCommand::HandleStringsCommand(std::vector<std::string> const& args) std::ostringstream e; e << "STRINGS option LIMIT_OUTPUT value \"" << args[i] << "\" is not an unsigned integer."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } arg_mode = arg_none; @@ -498,7 +399,7 @@ bool cmFileCommand::HandleStringsCommand(std::vector<std::string> const& args) std::ostringstream e; e << "STRINGS option LIMIT_COUNT value \"" << args[i] << "\" is not an unsigned integer."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } limit_count = count; @@ -509,7 +410,7 @@ bool cmFileCommand::HandleStringsCommand(std::vector<std::string> const& args) std::ostringstream e; e << "STRINGS option LENGTH_MINIMUM value \"" << args[i] << "\" is not an unsigned integer."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } minlen = len; @@ -520,7 +421,7 @@ bool cmFileCommand::HandleStringsCommand(std::vector<std::string> const& args) std::ostringstream e; e << "STRINGS option LENGTH_MAXIMUM value \"" << args[i] << "\" is not an unsigned integer."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } maxlen = len; @@ -530,7 +431,7 @@ bool cmFileCommand::HandleStringsCommand(std::vector<std::string> const& args) std::ostringstream e; e << "STRINGS option REGEX value \"" << args[i] << "\" could not be compiled."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } have_regex = true; @@ -549,23 +450,23 @@ bool cmFileCommand::HandleStringsCommand(std::vector<std::string> const& args) } else { std::ostringstream e; e << "STRINGS option ENCODING \"" << args[i] << "\" not recognized."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } arg_mode = arg_none; } else { std::ostringstream e; e << "STRINGS given unknown argument \"" << args[i] << "\""; - this->SetError(e.str()); + status.SetError(e.str()); return false; } } if (hex_conversion_enabled) { // TODO: should work without temp file, but just on a memory buffer - std::string binaryFileName = this->Makefile->GetCurrentBinaryDirectory(); - binaryFileName += "/CMakeFiles"; - binaryFileName += "/FileCommandStringsBinaryFile"; + std::string binaryFileName = + cmStrCat(status.GetMakefile().GetCurrentBinaryDirectory(), + "/CMakeFiles/FileCommandStringsBinaryFile"); if (cmHexFileConverter::TryConvert(fileName, binaryFileName)) { fileName = binaryFileName; } @@ -580,7 +481,7 @@ bool cmFileCommand::HandleStringsCommand(std::vector<std::string> const& args) if (!fin) { std::ostringstream e; e << "STRINGS file \"" << fileName << "\" cannot be read."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } @@ -752,12 +653,12 @@ bool cmFileCommand::HandleStringsCommand(std::vector<std::string> const& args) } // Save the output in a makefile variable. - this->Makefile->AddDefinition(outVar, output); + status.GetMakefile().AddDefinition(outVar, output); return true; } -bool cmFileCommand::HandleGlobCommand(std::vector<std::string> const& args, - bool recurse) +bool HandleGlobImpl(std::vector<std::string> const& args, bool recurse, + cmExecutionStatus& status) { // File commands has at least one argument assert(args.size() > 1); @@ -772,10 +673,10 @@ bool cmFileCommand::HandleGlobCommand(std::vector<std::string> const& args, g.SetRecurse(recurse); bool explicitFollowSymlinks = false; - cmPolicies::PolicyStatus status = - this->Makefile->GetPolicyStatus(cmPolicies::CMP0009); + cmPolicies::PolicyStatus policyStatus = + status.GetMakefile().GetPolicyStatus(cmPolicies::CMP0009); if (recurse) { - switch (status) { + switch (policyStatus) { case cmPolicies::REQUIRED_IF_USED: case cmPolicies::REQUIRED_ALWAYS: case cmPolicies::NEW: @@ -793,24 +694,24 @@ bool cmFileCommand::HandleGlobCommand(std::vector<std::string> const& args, bool warnConfigureLate = false; bool warnFollowedSymlinks = false; const cmake::WorkingMode workingMode = - this->Makefile->GetCMakeInstance()->GetWorkingMode(); + status.GetMakefile().GetCMakeInstance()->GetWorkingMode(); while (i != args.end()) { if (*i == "LIST_DIRECTORIES") { ++i; // skip LIST_DIRECTORIES if (i != args.end()) { - if (cmSystemTools::IsOn(*i)) { + if (cmIsOn(*i)) { g.SetListDirs(true); g.SetRecurseListDirs(true); - } else if (cmSystemTools::IsOff(*i)) { + } else if (cmIsOff(*i)) { g.SetListDirs(false); g.SetRecurseListDirs(false); } else { - this->SetError("LIST_DIRECTORIES missing bool value."); + status.SetError("LIST_DIRECTORIES missing bool value."); return false; } ++i; } else { - this->SetError("LIST_DIRECTORIES missing bool value."); + status.SetError("LIST_DIRECTORIES missing bool value."); return false; } } else if (*i == "FOLLOW_SYMLINKS") { @@ -819,7 +720,7 @@ bool cmFileCommand::HandleGlobCommand(std::vector<std::string> const& args, explicitFollowSymlinks = true; g.RecurseThroughSymlinksOn(); if (i == args.end()) { - this->SetError( + status.SetError( "GLOB_RECURSE requires a glob expression after FOLLOW_SYMLINKS."); return false; } @@ -827,25 +728,26 @@ bool cmFileCommand::HandleGlobCommand(std::vector<std::string> const& args, } else if (*i == "RELATIVE") { ++i; // skip RELATIVE if (i == args.end()) { - this->SetError("GLOB requires a directory after the RELATIVE tag."); + status.SetError("GLOB requires a directory after the RELATIVE tag."); return false; } g.SetRelative(i->c_str()); ++i; if (i == args.end()) { - this->SetError("GLOB requires a glob expression after the directory."); + status.SetError( + "GLOB requires a glob expression after the directory."); return false; } } else if (*i == "CONFIGURE_DEPENDS") { // Generated build system depends on glob results if (!configureDepends && warnConfigureLate) { - this->Makefile->IssueMessage( + status.GetMakefile().IssueMessage( MessageType::AUTHOR_WARNING, "CONFIGURE_DEPENDS flag was given after a glob expression was " "already evaluated."); } if (workingMode != cmake::NORMAL_MODE) { - this->Makefile->IssueMessage( + status.GetMakefile().IssueMessage( MessageType::FATAL_ERROR, "CONFIGURE_DEPENDS is invalid for script and find package modes."); return false; @@ -853,14 +755,14 @@ bool cmFileCommand::HandleGlobCommand(std::vector<std::string> const& args, configureDepends = true; ++i; if (i == args.end()) { - this->SetError( + status.SetError( "GLOB requires a glob expression after CONFIGURE_DEPENDS."); return false; } } else { std::string expr = *i; if (!cmsys::SystemTools::FileIsFullPath(*i)) { - expr = this->Makefile->GetCurrentSourceDirectory(); + expr = status.GetMakefile().GetCurrentSourceDirectory(); // Handle script mode if (!expr.empty()) { expr += "/" + *i; @@ -876,12 +778,12 @@ bool cmFileCommand::HandleGlobCommand(std::vector<std::string> const& args, bool shouldExit = false; for (cmsys::Glob::Message const& globMessage : globMessages) { if (globMessage.type == cmsys::Glob::cyclicRecursion) { - this->Makefile->IssueMessage( + status.GetMakefile().IssueMessage( MessageType::AUTHOR_WARNING, "Cyclic recursion detected while globbing for '" + *i + "':\n" + globMessage.content); } else { - this->Makefile->IssueMessage( + status.GetMakefile().IssueMessage( MessageType::FATAL_ERROR, "Error has occurred while globbing for '" + *i + "' - " + globMessage.content); @@ -905,11 +807,11 @@ bool cmFileCommand::HandleGlobCommand(std::vector<std::string> const& args, std::sort(foundFiles.begin(), foundFiles.end()); foundFiles.erase(std::unique(foundFiles.begin(), foundFiles.end()), foundFiles.end()); - this->Makefile->GetCMakeInstance()->AddGlobCacheEntry( + status.GetMakefile().GetCMakeInstance()->AddGlobCacheEntry( recurse, (recurse ? g.GetRecurseListDirs() : g.GetListDirs()), (recurse ? g.GetRecurseThroughSymlinks() : false), (g.GetRelative() ? g.GetRelative() : ""), expr, foundFiles, variable, - this->Makefile->GetBacktrace()); + status.GetMakefile().GetBacktrace()); } else { warnConfigureLate = true; } @@ -917,7 +819,7 @@ bool cmFileCommand::HandleGlobCommand(std::vector<std::string> const& args, } } - switch (status) { + switch (policyStatus) { case cmPolicies::REQUIRED_IF_USED: case cmPolicies::REQUIRED_ALWAYS: case cmPolicies::NEW: @@ -930,7 +832,7 @@ bool cmFileCommand::HandleGlobCommand(std::vector<std::string> const& args, // Possibly unexpected old behavior *and* we actually traversed // symlinks without being explicitly asked to: warn the author. if (warnFollowedSymlinks) { - this->Makefile->IssueMessage( + status.GetMakefile().IssueMessage( MessageType::AUTHOR_WARNING, cmPolicies::GetPolicyWarning(cmPolicies::CMP0009)); } @@ -939,12 +841,24 @@ bool cmFileCommand::HandleGlobCommand(std::vector<std::string> const& args, std::sort(files.begin(), files.end()); files.erase(std::unique(files.begin(), files.end()), files.end()); - this->Makefile->AddDefinition(variable, cmJoin(files, ";")); + status.GetMakefile().AddDefinition(variable, cmJoin(files, ";")); return true; } -bool cmFileCommand::HandleMakeDirectoryCommand( - std::vector<std::string> const& args) +bool HandleGlobCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) +{ + return HandleGlobImpl(args, false, status); +} + +bool HandleGlobRecurseCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) +{ + return HandleGlobImpl(args, true, status); +} + +bool HandleMakeDirectoryCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { // File command has at least one argument assert(args.size() > 1); @@ -955,28 +869,28 @@ bool cmFileCommand::HandleMakeDirectoryCommand( { const std::string* cdir = &arg; if (!cmsys::SystemTools::FileIsFullPath(arg)) { - expr = this->Makefile->GetCurrentSourceDirectory(); - expr += "/" + arg; + expr = + cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', arg); cdir = &expr; } - if (!this->Makefile->CanIWriteThisFile(*cdir)) { + if (!status.GetMakefile().CanIWriteThisFile(*cdir)) { std::string e = "attempted to create a directory: " + *cdir + " into a source directory."; - this->SetError(e); + status.SetError(e); cmSystemTools::SetFatalErrorOccured(); return false; } if (!cmSystemTools::MakeDirectory(*cdir)) { std::string error = "problem creating directory: " + *cdir; - this->SetError(error); + status.SetError(error); return false; } } return true; } -bool cmFileCommand::HandleTouchCommand(std::vector<std::string> const& args, - bool create) +bool HandleTouchImpl(std::vector<std::string> const& args, bool create, + cmExecutionStatus& status) { // File command has at least one argument assert(args.size() > 1); @@ -986,27 +900,39 @@ bool cmFileCommand::HandleTouchCommand(std::vector<std::string> const& args, { std::string tfile = arg; if (!cmsys::SystemTools::FileIsFullPath(tfile)) { - tfile = this->Makefile->GetCurrentSourceDirectory(); - tfile += "/" + arg; + tfile = + cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', arg); } - if (!this->Makefile->CanIWriteThisFile(tfile)) { + if (!status.GetMakefile().CanIWriteThisFile(tfile)) { std::string e = "attempted to touch a file: " + tfile + " in a source directory."; - this->SetError(e); + status.SetError(e); cmSystemTools::SetFatalErrorOccured(); return false; } if (!cmSystemTools::Touch(tfile, create)) { std::string error = "problem touching file: " + tfile; - this->SetError(error); + status.SetError(error); return false; } } return true; } -bool cmFileCommand::HandleDifferentCommand( - std::vector<std::string> const& args) +bool HandleTouchCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) +{ + return HandleTouchImpl(args, true, status); +} + +bool HandleTouchNocreateCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) +{ + return HandleTouchImpl(args, false, status); +} + +bool HandleDifferentCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { /* FILE(DIFFERENT <variable> FILES <lhs> <rhs>) @@ -1039,34 +965,35 @@ bool cmFileCommand::HandleDifferentCommand( } else { std::ostringstream e; e << "DIFFERENT given unknown argument " << args[i]; - this->SetError(e.str()); + status.SetError(e.str()); return false; } } if (!var) { - this->SetError("DIFFERENT not given result variable name."); + status.SetError("DIFFERENT not given result variable name."); return false; } if (!file_lhs || !file_rhs) { - this->SetError("DIFFERENT not given FILES option with two file names."); + status.SetError("DIFFERENT not given FILES option with two file names."); return false; } // Compare the files. const char* result = cmSystemTools::FilesDiffer(file_lhs, file_rhs) ? "1" : "0"; - this->Makefile->AddDefinition(var, result); + status.GetMakefile().AddDefinition(var, result); return true; } -bool cmFileCommand::HandleCopyCommand(std::vector<std::string> const& args) +bool HandleCopyCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { - cmFileCopier copier(this); + cmFileCopier copier(status); return copier.Run(args); } -bool cmFileCommand::HandleRPathChangeCommand( - std::vector<std::string> const& args) +bool HandleRPathChangeCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { // Evaluate arguments. std::string file; @@ -1102,26 +1029,26 @@ bool cmFileCommand::HandleRPathChangeCommand( } else { std::ostringstream e; e << "RPATH_CHANGE given unknown argument " << args[i]; - this->SetError(e.str()); + status.SetError(e.str()); return false; } } if (file.empty()) { - this->SetError("RPATH_CHANGE not given FILE option."); + status.SetError("RPATH_CHANGE not given FILE option."); return false; } if (!oldRPath) { - this->SetError("RPATH_CHANGE not given OLD_RPATH option."); + status.SetError("RPATH_CHANGE not given OLD_RPATH option."); return false; } if (!newRPath) { - this->SetError("RPATH_CHANGE not given NEW_RPATH option."); + status.SetError("RPATH_CHANGE not given NEW_RPATH option."); return false; } if (!cmSystemTools::FileExists(file, true)) { std::ostringstream e; e << "RPATH_CHANGE given FILE \"" << file << "\" that does not exist."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } bool success = true; @@ -1139,25 +1066,22 @@ bool cmFileCommand::HandleRPathChangeCommand( << " " << file << "\n" << emsg; /* clang-format on */ - this->SetError(e.str()); + status.SetError(e.str()); success = false; } if (success) { if (changed) { - std::string message = "Set runtime path of \""; - message += file; - message += "\" to \""; - message += newRPath; - message += "\""; - this->Makefile->DisplayStatus(message, -1); + std::string message = + cmStrCat("Set runtime path of \"", file, "\" to \"", newRPath, '"'); + status.GetMakefile().DisplayStatus(message, -1); } ft.Store(file); } return success; } -bool cmFileCommand::HandleRPathRemoveCommand( - std::vector<std::string> const& args) +bool HandleRPathRemoveCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { // Evaluate arguments. std::string file; @@ -1176,18 +1100,18 @@ bool cmFileCommand::HandleRPathRemoveCommand( } else { std::ostringstream e; e << "RPATH_REMOVE given unknown argument " << args[i]; - this->SetError(e.str()); + status.SetError(e.str()); return false; } } if (file.empty()) { - this->SetError("RPATH_REMOVE not given FILE option."); + status.SetError("RPATH_REMOVE not given FILE option."); return false; } if (!cmSystemTools::FileExists(file, true)) { std::ostringstream e; e << "RPATH_REMOVE given FILE \"" << file << "\" that does not exist."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } bool success = true; @@ -1201,23 +1125,22 @@ bool cmFileCommand::HandleRPathRemoveCommand( << " " << file << "\n" << emsg; /* clang-format on */ - this->SetError(e.str()); + status.SetError(e.str()); success = false; } if (success) { if (removed) { - std::string message = "Removed runtime path from \""; - message += file; - message += "\""; - this->Makefile->DisplayStatus(message, -1); + std::string message = + cmStrCat("Removed runtime path from \"", file, '"'); + status.GetMakefile().DisplayStatus(message, -1); } ft.Store(file); } return success; } -bool cmFileCommand::HandleRPathCheckCommand( - std::vector<std::string> const& args) +bool HandleRPathCheckCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { // Evaluate arguments. std::string file; @@ -1243,16 +1166,16 @@ bool cmFileCommand::HandleRPathCheckCommand( } else { std::ostringstream e; e << "RPATH_CHECK given unknown argument " << args[i]; - this->SetError(e.str()); + status.SetError(e.str()); return false; } } if (file.empty()) { - this->SetError("RPATH_CHECK not given FILE option."); + status.SetError("RPATH_CHECK not given FILE option."); return false; } if (!rpath) { - this->SetError("RPATH_CHECK not given RPATH option."); + status.SetError("RPATH_CHECK not given RPATH option."); return false; } @@ -1267,11 +1190,12 @@ bool cmFileCommand::HandleRPathCheckCommand( return true; } -bool cmFileCommand::HandleReadElfCommand(std::vector<std::string> const& args) +bool HandleReadElfCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() < 4) { - this->SetError("READ_ELF must be called with at least three additional " - "arguments."); + status.SetError("READ_ELF must be called with at least three additional " + "arguments."); return false; } @@ -1293,7 +1217,7 @@ bool cmFileCommand::HandleReadElfCommand(std::vector<std::string> const& args) if (!cmSystemTools::FileExists(fileNameArg, true)) { std::ostringstream e; e << "READ_ELF given FILE \"" << fileNameArg << "\" that does not exist."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } @@ -1304,14 +1228,14 @@ bool cmFileCommand::HandleReadElfCommand(std::vector<std::string> const& args) if (cmELF::StringEntry const* se_rpath = elf.GetRPath()) { std::string rpath(se_rpath->Value); std::replace(rpath.begin(), rpath.end(), ':', ';'); - this->Makefile->AddDefinition(arguments.RPath, rpath); + status.GetMakefile().AddDefinition(arguments.RPath, rpath); } } if (!arguments.RunPath.empty()) { if (cmELF::StringEntry const* se_runpath = elf.GetRunPath()) { std::string runpath(se_runpath->Value); std::replace(runpath.begin(), runpath.end(), ':', ';'); - this->Makefile->AddDefinition(arguments.RunPath, runpath); + status.GetMakefile().AddDefinition(arguments.RunPath, runpath); } } @@ -1319,25 +1243,26 @@ bool cmFileCommand::HandleReadElfCommand(std::vector<std::string> const& args) #else std::string error = "ELF parser not available on this platform."; if (arguments.Error.empty()) { - this->SetError(error); + status.SetError(error); return false; } - this->Makefile->AddDefinition(arguments.Error, error); + status.GetMakefile().AddDefinition(arguments.Error, error); return true; #endif } -bool cmFileCommand::HandleInstallCommand(std::vector<std::string> const& args) +bool HandleInstallCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { - cmFileInstaller installer(this); + cmFileInstaller installer(status); return installer.Run(args); } -bool cmFileCommand::HandleRelativePathCommand( - std::vector<std::string> const& args) +bool HandleRelativePathCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() != 4) { - this->SetError("RELATIVE_PATH called with incorrect number of arguments"); + status.SetError("RELATIVE_PATH called with incorrect number of arguments"); return false; } @@ -1349,38 +1274,39 @@ bool cmFileCommand::HandleRelativePathCommand( std::string errstring = "RELATIVE_PATH must be passed a full path to the directory: " + directoryName; - this->SetError(errstring); + status.SetError(errstring); return false; } if (!cmSystemTools::FileIsFullPath(fileName)) { std::string errstring = "RELATIVE_PATH must be passed a full path to the file: " + fileName; - this->SetError(errstring); + status.SetError(errstring); return false; } std::string res = cmSystemTools::RelativePath(directoryName, fileName); - this->Makefile->AddDefinition(outVar, res); + status.GetMakefile().AddDefinition(outVar, res); return true; } -bool cmFileCommand::HandleRename(std::vector<std::string> const& args) +bool HandleRename(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() != 3) { - this->SetError("RENAME given incorrect number of arguments."); + status.SetError("RENAME given incorrect number of arguments."); return false; } // Compute full path for old and new names. std::string oldname = args[1]; if (!cmsys::SystemTools::FileIsFullPath(oldname)) { - oldname = this->Makefile->GetCurrentSourceDirectory(); - oldname += "/" + args[1]; + oldname = + cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', args[1]); } std::string newname = args[2]; if (!cmsys::SystemTools::FileIsFullPath(newname)) { - newname = this->Makefile->GetCurrentSourceDirectory(); - newname += "/" + args[2]; + newname = + cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', args[2]); } if (!cmSystemTools::RenameFile(oldname, newname)) { @@ -1393,14 +1319,14 @@ bool cmFileCommand::HandleRename(std::vector<std::string> const& args) << " " << newname << "\n" << "because: " << err << "\n"; /* clang-format on */ - this->SetError(e.str()); + status.SetError(e.str()); return false; } return true; } -bool cmFileCommand::HandleRemove(std::vector<std::string> const& args, - bool recurse) +bool HandleRemoveImpl(std::vector<std::string> const& args, bool recurse, + cmExecutionStatus& status) { std::string message; @@ -1411,18 +1337,18 @@ bool cmFileCommand::HandleRemove(std::vector<std::string> const& args, std::string fileName = arg; if (fileName.empty()) { std::string const r = recurse ? "REMOVE_RECURSE" : "REMOVE"; - this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, - "Ignoring empty file name in " + r + "."); + status.GetMakefile().IssueMessage( + MessageType::AUTHOR_WARNING, "Ignoring empty file name in " + r + "."); continue; } if (!cmsys::SystemTools::FileIsFullPath(fileName)) { - fileName = this->Makefile->GetCurrentSourceDirectory(); - fileName += "/" + arg; + fileName = + cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', arg); } if (cmSystemTools::FileIsDirectory(fileName) && !cmSystemTools::FileIsSymlink(fileName) && recurse) { - cmSystemTools::RemoveADirectory(fileName); + cmSystemTools::RepeatedRemoveDirectory(fileName); } else { cmSystemTools::RemoveFile(fileName); } @@ -1430,7 +1356,18 @@ bool cmFileCommand::HandleRemove(std::vector<std::string> const& args, return true; } -namespace { +bool HandleRemove(std::vector<std::string> const& args, + cmExecutionStatus& status) +{ + return HandleRemoveImpl(args, false, status); +} + +bool HandleRemoveRecurse(std::vector<std::string> const& args, + cmExecutionStatus& status) +{ + return HandleRemoveImpl(args, true, status); +} + std::string ToNativePath(const std::string& path) { const auto& outPath = cmSystemTools::ConvertToOutputPath(path); @@ -1447,14 +1384,14 @@ std::string ToCMakePath(const std::string& path) cmSystemTools::ConvertToUnixSlashes(temp); return temp; } -} -bool cmFileCommand::HandleCMakePathCommand( - std::vector<std::string> const& args, bool nativePath) +bool HandlePathCommand(std::vector<std::string> const& args, + std::string (*convert)(std::string const&), + cmExecutionStatus& status) { if (args.size() != 3) { - this->SetError("FILE([TO_CMAKE_PATH|TO_NATIVE_PATH] path result) must be " - "called with exactly three arguments."); + status.SetError("FILE([TO_CMAKE_PATH|TO_NATIVE_PATH] path result) must be " + "called with exactly three arguments."); return false; } #if defined(_WIN32) && !defined(__CYGWIN__) @@ -1464,19 +1401,28 @@ bool cmFileCommand::HandleCMakePathCommand( #endif std::vector<std::string> path = cmSystemTools::SplitString(args[1], pathSep); - std::string value = cmJoin( - cmMakeRange(path).transform(nativePath ? ToNativePath : ToCMakePath), ";"); - this->Makefile->AddDefinition(args[2], value); + std::string value = cmJoin(cmMakeRange(path).transform(convert), ";"); + status.GetMakefile().AddDefinition(args[2], value); return true; } -#if defined(CMAKE_BUILD_WITH_CMAKE) +bool HandleCMakePathCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) +{ + return HandlePathCommand(args, ToCMakePath, status); +} + +bool HandleNativePathCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) +{ + return HandlePathCommand(args, ToNativePath, status); +} + +#if !defined(CMAKE_BOOTSTRAP) // Stuff for curl download/upload typedef std::vector<char> cmFileCommandVectorOfChar; -namespace { - size_t cmWriteToFileCallback(void* ptr, size_t size, size_t nmemb, void* data) { int realsize = static_cast<int>(size * nmemb); @@ -1527,11 +1473,10 @@ size_t cmFileCommandCurlDebugCallback(CURL*, curl_infotype type, char* chPtr, class cURLProgressHelper { public: - cURLProgressHelper(cmFileCommand* fc, const char* text) + cURLProgressHelper(cmMakefile* mf, const char* text) + : Makefile(mf) + , Text(text) { - this->CurrentPercentage = -1; - this->FileCommand = fc; - this->Text = text; } bool UpdatePercentage(double value, double total, std::string& status) @@ -1558,11 +1503,11 @@ public: return updated; } - cmFileCommand* GetFileCommand() { return this->FileCommand; } + cmMakefile* GetMakefile() { return this->Makefile; } private: - long CurrentPercentage; - cmFileCommand* FileCommand; + long CurrentPercentage = -1; + cmMakefile* Makefile; std::string Text; }; @@ -1576,8 +1521,7 @@ int cmFileDownloadProgressCallback(void* clientp, double dltotal, double dlnow, std::string status; if (helper->UpdatePercentage(dlnow, dltotal, status)) { - cmFileCommand* fc = helper->GetFileCommand(); - cmMakefile* mf = fc->GetMakefile(); + cmMakefile* mf = helper->GetMakefile(); mf->DisplayStatus(status, -1); } @@ -1594,16 +1538,12 @@ int cmFileUploadProgressCallback(void* clientp, double dltotal, double dlnow, std::string status; if (helper->UpdatePercentage(ulnow, ultotal, status)) { - cmFileCommand* fc = helper->GetFileCommand(); - cmMakefile* mf = fc->GetMakefile(); + cmMakefile* mf = helper->GetMakefile(); mf->DisplayStatus(status, -1); } return 0; } -} - -namespace { class cURLEasyGuard { @@ -1628,7 +1568,7 @@ public: private: ::CURL* Easy; }; -} + #endif #define check_curl_result(result, errstr) \ @@ -1636,17 +1576,18 @@ private: if (result != CURLE_OK) { \ std::string e(errstr); \ e += ::curl_easy_strerror(result); \ - this->SetError(e); \ + status.SetError(e); \ return false; \ } \ } while (false) -bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args) +bool HandleDownloadCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) std::vector<std::string>::const_iterator i = args.begin(); if (args.size() < 3) { - this->SetError("DOWNLOAD must be called with at least three arguments."); + status.SetError("DOWNLOAD must be called with at least three arguments."); return false; } ++i; // Get rid of subcommand @@ -1659,11 +1600,12 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args) long inactivity_timeout = 0; std::string logVar; std::string statusVar; - bool tls_verify = this->Makefile->IsOn("CMAKE_TLS_VERIFY"); - const char* cainfo = this->Makefile->GetDefinition("CMAKE_TLS_CAINFO"); - std::string netrc_level = this->Makefile->GetSafeDefinition("CMAKE_NETRC"); + bool tls_verify = status.GetMakefile().IsOn("CMAKE_TLS_VERIFY"); + const char* cainfo = status.GetMakefile().GetDefinition("CMAKE_TLS_CAINFO"); + std::string netrc_level = + status.GetMakefile().GetSafeDefinition("CMAKE_NETRC"); std::string netrc_file = - this->Makefile->GetSafeDefinition("CMAKE_NETRC_FILE"); + status.GetMakefile().GetSafeDefinition("CMAKE_NETRC_FILE"); std::string expectedHash; std::string hashMatchMSG; std::unique_ptr<cmCryptoHash> hash; @@ -1678,7 +1620,7 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args) if (i != args.end()) { timeout = atol(i->c_str()); } else { - this->SetError("DOWNLOAD missing time for TIMEOUT."); + status.SetError("DOWNLOAD missing time for TIMEOUT."); return false; } } else if (*i == "INACTIVITY_TIMEOUT") { @@ -1686,29 +1628,29 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args) if (i != args.end()) { inactivity_timeout = atol(i->c_str()); } else { - this->SetError("DOWNLOAD missing time for INACTIVITY_TIMEOUT."); + status.SetError("DOWNLOAD missing time for INACTIVITY_TIMEOUT."); return false; } } else if (*i == "LOG") { ++i; if (i == args.end()) { - this->SetError("DOWNLOAD missing VAR for LOG."); + status.SetError("DOWNLOAD missing VAR for LOG."); return false; } logVar = *i; } else if (*i == "STATUS") { ++i; if (i == args.end()) { - this->SetError("DOWNLOAD missing VAR for STATUS."); + status.SetError("DOWNLOAD missing VAR for STATUS."); return false; } statusVar = *i; } else if (*i == "TLS_VERIFY") { ++i; if (i != args.end()) { - tls_verify = cmSystemTools::IsOn(*i); + tls_verify = cmIsOn(*i); } else { - this->SetError("TLS_VERIFY missing bool value."); + status.SetError("TLS_VERIFY missing bool value."); return false; } } else if (*i == "TLS_CAINFO") { @@ -1716,7 +1658,7 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args) if (i != args.end()) { cainfo = i->c_str(); } else { - this->SetError("TLS_CAFILE missing file value."); + status.SetError("TLS_CAFILE missing file value."); return false; } } else if (*i == "NETRC_FILE") { @@ -1724,7 +1666,7 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args) if (i != args.end()) { netrc_file = *i; } else { - this->SetError("DOWNLOAD missing file value for NETRC_FILE."); + status.SetError("DOWNLOAD missing file value for NETRC_FILE."); return false; } } else if (*i == "NETRC") { @@ -1732,13 +1674,13 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args) if (i != args.end()) { netrc_level = *i; } else { - this->SetError("DOWNLOAD missing level value for NETRC."); + status.SetError("DOWNLOAD missing level value for NETRC."); return false; } } else if (*i == "EXPECTED_MD5") { ++i; if (i == args.end()) { - this->SetError("DOWNLOAD missing sum value for EXPECTED_MD5."); + status.SetError("DOWNLOAD missing sum value for EXPECTED_MD5."); return false; } hash = cm::make_unique<cmCryptoHash>(cmCryptoHash::AlgoMD5); @@ -1749,46 +1691,44 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args) } else if (*i == "EXPECTED_HASH") { ++i; if (i == args.end()) { - this->SetError("DOWNLOAD missing ALGO=value for EXPECTED_HASH."); + status.SetError("DOWNLOAD missing ALGO=value for EXPECTED_HASH."); return false; } std::string::size_type pos = i->find("="); if (pos == std::string::npos) { std::string err = - "DOWNLOAD EXPECTED_HASH expects ALGO=value but got: "; - err += *i; - this->SetError(err); + cmStrCat("DOWNLOAD EXPECTED_HASH expects ALGO=value but got: ", *i); + status.SetError(err); return false; } std::string algo = i->substr(0, pos); expectedHash = cmSystemTools::LowerCase(i->substr(pos + 1)); - hash = std::unique_ptr<cmCryptoHash>(cmCryptoHash::New(algo.c_str())); + hash = std::unique_ptr<cmCryptoHash>(cmCryptoHash::New(algo)); if (!hash) { - std::string err = "DOWNLOAD EXPECTED_HASH given unknown ALGO: "; - err += algo; - this->SetError(err); + std::string err = + cmStrCat("DOWNLOAD EXPECTED_HASH given unknown ALGO: ", algo); + status.SetError(err); return false; } hashMatchMSG = algo + " hash"; } else if (*i == "USERPWD") { ++i; if (i == args.end()) { - this->SetError("DOWNLOAD missing string for USERPWD."); + status.SetError("DOWNLOAD missing string for USERPWD."); return false; } userpwd = *i; } else if (*i == "HTTPHEADER") { ++i; if (i == args.end()) { - this->SetError("DOWNLOAD missing string for HTTPHEADER."); + status.SetError("DOWNLOAD missing string for HTTPHEADER."); return false; } curl_headers.push_back(*i); } else { // Do not return error for compatibility reason. - std::string err = "Unexpected argument: "; - err += *i; - this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, err); + std::string err = cmStrCat("Unexpected argument: ", *i); + status.GetMakefile().IssueMessage(MessageType::AUTHOR_WARNING, err); } ++i; } @@ -1800,13 +1740,12 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args) std::string msg; std::string actualHash = hash->HashFile(file); if (actualHash == expectedHash) { - msg = "returning early; file already exists with expected "; - msg += hashMatchMSG; - msg += "\""; + msg = cmStrCat("returning early; file already exists with expected ", + hashMatchMSG, '"'); if (!statusVar.empty()) { std::ostringstream result; result << 0 << ";\"" << msg; - this->Makefile->AddDefinition(statusVar, result.str()); + status.GetMakefile().AddDefinition(statusVar, result.str()); } return true; } @@ -1819,13 +1758,13 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args) std::string errstring = "DOWNLOAD error: cannot create directory '" + dir + "' - Specify file by full path name and verify that you " "have directory creation and file write privileges."; - this->SetError(errstring); + status.SetError(errstring); return false; } cmsys::ofstream fout(file.c_str(), std::ios::binary); if (!fout) { - this->SetError("DOWNLOAD cannot open file for write."); + status.SetError("DOWNLOAD cannot open file for write."); return false; } @@ -1837,7 +1776,7 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args) ::curl_global_init(CURL_GLOBAL_DEFAULT); curl = ::curl_easy_init(); if (!curl) { - this->SetError("DOWNLOAD error initializing curl."); + status.SetError("DOWNLOAD error initializing curl."); return false; } @@ -1871,7 +1810,7 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args) // command arg comes first std::string const& cainfo_err = cmCurlSetCAInfo(curl, cainfo); if (!cainfo_err.empty()) { - this->SetError(cainfo_err); + status.SetError(cainfo_err); return false; } @@ -1881,7 +1820,7 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args) std::string const& netrc_option_err = cmCurlSetNETRCOption(curl, netrc_level, netrc_file); if (!netrc_option_err.empty()) { - this->SetError(netrc_option_err); + status.SetError(netrc_option_err); return false; } @@ -1917,7 +1856,7 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args) // scope intentionally, rather than inside the "if(showProgress)" // block... // - cURLProgressHelper helper(this, "download"); + cURLProgressHelper helper(&status.GetMakefile(), "download"); if (showProgress) { res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0); @@ -1955,7 +1894,7 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args) std::ostringstream result; result << static_cast<int>(res) << ";\"" << ::curl_easy_strerror(res) << "\""; - this->Makefile->AddDefinition(statusVar, result.str()); + status.GetMakefile().AddDefinition(statusVar, result.str()); } ::curl_global_cleanup(); @@ -1970,7 +1909,7 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args) if (hash) { std::string actualHash = hash->HashFile(file); if (actualHash.empty()) { - this->SetError("DOWNLOAD cannot compute hash on downloaded file"); + status.SetError("DOWNLOAD cannot compute hash on downloaded file"); return false; } @@ -1984,34 +1923,36 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args) << ::curl_easy_strerror(res) << "\"]" << std::endl; if (!statusVar.empty() && res == 0) { - std::string status = "1;HASH mismatch: " - "expected: " + - expectedHash + " actual: " + actualHash; - this->Makefile->AddDefinition(statusVar, status); + status.GetMakefile().AddDefinition(statusVar, + "1;HASH mismatch: " + "expected: " + + expectedHash + + " actual: " + actualHash); } - this->SetError(oss.str()); + status.SetError(oss.str()); return false; } } if (!logVar.empty()) { chunkDebug.push_back(0); - this->Makefile->AddDefinition(logVar, chunkDebug.data()); + status.GetMakefile().AddDefinition(logVar, chunkDebug.data()); } return true; #else - this->SetError("DOWNLOAD not supported by bootstrap cmake."); + status.SetError("DOWNLOAD not supported by bootstrap cmake."); return false; #endif } -bool cmFileCommand::HandleUploadCommand(std::vector<std::string> const& args) +bool HandleUploadCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) if (args.size() < 3) { - this->SetError("UPLOAD must be called with at least three arguments."); + status.SetError("UPLOAD must be called with at least three arguments."); return false; } std::vector<std::string>::const_iterator i = args.begin(); @@ -2027,9 +1968,10 @@ bool cmFileCommand::HandleUploadCommand(std::vector<std::string> const& args) std::string statusVar; bool showProgress = false; std::string userpwd; - std::string netrc_level = this->Makefile->GetSafeDefinition("CMAKE_NETRC"); + std::string netrc_level = + status.GetMakefile().GetSafeDefinition("CMAKE_NETRC"); std::string netrc_file = - this->Makefile->GetSafeDefinition("CMAKE_NETRC_FILE"); + status.GetMakefile().GetSafeDefinition("CMAKE_NETRC_FILE"); std::vector<std::string> curl_headers; @@ -2039,7 +1981,7 @@ bool cmFileCommand::HandleUploadCommand(std::vector<std::string> const& args) if (i != args.end()) { timeout = atol(i->c_str()); } else { - this->SetError("UPLOAD missing time for TIMEOUT."); + status.SetError("UPLOAD missing time for TIMEOUT."); return false; } } else if (*i == "INACTIVITY_TIMEOUT") { @@ -2047,20 +1989,20 @@ bool cmFileCommand::HandleUploadCommand(std::vector<std::string> const& args) if (i != args.end()) { inactivity_timeout = atol(i->c_str()); } else { - this->SetError("UPLOAD missing time for INACTIVITY_TIMEOUT."); + status.SetError("UPLOAD missing time for INACTIVITY_TIMEOUT."); return false; } } else if (*i == "LOG") { ++i; if (i == args.end()) { - this->SetError("UPLOAD missing VAR for LOG."); + status.SetError("UPLOAD missing VAR for LOG."); return false; } logVar = *i; } else if (*i == "STATUS") { ++i; if (i == args.end()) { - this->SetError("UPLOAD missing VAR for STATUS."); + status.SetError("UPLOAD missing VAR for STATUS."); return false; } statusVar = *i; @@ -2071,7 +2013,7 @@ bool cmFileCommand::HandleUploadCommand(std::vector<std::string> const& args) if (i != args.end()) { netrc_file = *i; } else { - this->SetError("UPLOAD missing file value for NETRC_FILE."); + status.SetError("UPLOAD missing file value for NETRC_FILE."); return false; } } else if (*i == "NETRC") { @@ -2079,28 +2021,27 @@ bool cmFileCommand::HandleUploadCommand(std::vector<std::string> const& args) if (i != args.end()) { netrc_level = *i; } else { - this->SetError("UPLOAD missing level value for NETRC."); + status.SetError("UPLOAD missing level value for NETRC."); return false; } } else if (*i == "USERPWD") { ++i; if (i == args.end()) { - this->SetError("UPLOAD missing string for USERPWD."); + status.SetError("UPLOAD missing string for USERPWD."); return false; } userpwd = *i; } else if (*i == "HTTPHEADER") { ++i; if (i == args.end()) { - this->SetError("UPLOAD missing string for HTTPHEADER."); + status.SetError("UPLOAD missing string for HTTPHEADER."); return false; } curl_headers.push_back(*i); } else { // Do not return error for compatibility reason. - std::string err = "Unexpected argument: "; - err += *i; - this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, err); + std::string err = cmStrCat("Unexpected argument: ", *i); + status.GetMakefile().IssueMessage(MessageType::AUTHOR_WARNING, err); } ++i; @@ -2110,9 +2051,9 @@ bool cmFileCommand::HandleUploadCommand(std::vector<std::string> const& args) // FILE* fin = cmsys::SystemTools::Fopen(filename, "rb"); if (!fin) { - std::string errStr = "UPLOAD cannot open file '"; - errStr += filename + "' for reading."; - this->SetError(errStr); + std::string errStr = + cmStrCat("UPLOAD cannot open file '", filename, "' for reading."); + status.SetError(errStr); return false; } @@ -2126,7 +2067,7 @@ bool cmFileCommand::HandleUploadCommand(std::vector<std::string> const& args) ::curl_global_init(CURL_GLOBAL_DEFAULT); curl = ::curl_easy_init(); if (!curl) { - this->SetError("UPLOAD error initializing curl."); + status.SetError("UPLOAD error initializing curl."); fclose(fin); return false; } @@ -2185,7 +2126,7 @@ bool cmFileCommand::HandleUploadCommand(std::vector<std::string> const& args) // scope intentionally, rather than inside the "if(showProgress)" // block... // - cURLProgressHelper helper(this, "upload"); + cURLProgressHelper helper(&status.GetMakefile(), "upload"); if (showProgress) { res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0); @@ -2220,7 +2161,7 @@ bool cmFileCommand::HandleUploadCommand(std::vector<std::string> const& args) std::string const& netrc_option_err = cmCurlSetNETRCOption(curl, netrc_level, netrc_file); if (!netrc_option_err.empty()) { - this->SetError(netrc_option_err); + status.SetError(netrc_option_err); return false; } @@ -2242,7 +2183,7 @@ bool cmFileCommand::HandleUploadCommand(std::vector<std::string> const& args) std::ostringstream result; result << static_cast<int>(res) << ";\"" << ::curl_easy_strerror(res) << "\""; - this->Makefile->AddDefinition(statusVar, result.str()); + status.GetMakefile().AddDefinition(statusVar, result.str()); } ::curl_global_cleanup(); @@ -2267,22 +2208,22 @@ bool cmFileCommand::HandleUploadCommand(std::vector<std::string> const& args) log += "\n"; } - this->Makefile->AddDefinition(logVar, log); + status.GetMakefile().AddDefinition(logVar, log); } return true; #else - this->SetError("UPLOAD not supported by bootstrap cmake."); + status.SetError("UPLOAD not supported by bootstrap cmake."); return false; #endif } -void cmFileCommand::AddEvaluationFile(const std::string& inputName, - const std::string& outputExpr, - const std::string& condition, - bool inputIsContent) +void AddEvaluationFile(const std::string& inputName, + const std::string& outputExpr, + const std::string& condition, bool inputIsContent, + cmExecutionStatus& status) { - cmListFileBacktrace lfbt = this->Makefile->GetBacktrace(); + cmListFileBacktrace lfbt = status.GetMakefile().GetBacktrace(); cmGeneratorExpression outputGe(lfbt); std::unique_ptr<cmCompiledGeneratorExpression> outputCge = @@ -2292,52 +2233,54 @@ void cmFileCommand::AddEvaluationFile(const std::string& inputName, std::unique_ptr<cmCompiledGeneratorExpression> conditionCge = conditionGe.Parse(condition); - this->Makefile->AddEvaluationFile(inputName, std::move(outputCge), - std::move(conditionCge), inputIsContent); + status.GetMakefile().AddEvaluationFile( + inputName, std::move(outputCge), std::move(conditionCge), inputIsContent); } -bool cmFileCommand::HandleGenerateCommand(std::vector<std::string> const& args) +bool HandleGenerateCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() < 5) { - this->SetError("Incorrect arguments to GENERATE subcommand."); + status.SetError("Incorrect arguments to GENERATE subcommand."); return false; } if (args[1] != "OUTPUT") { - this->SetError("Incorrect arguments to GENERATE subcommand."); + status.SetError("Incorrect arguments to GENERATE subcommand."); return false; } std::string condition; if (args.size() > 5) { if (args[5] != "CONDITION") { - this->SetError("Incorrect arguments to GENERATE subcommand."); + status.SetError("Incorrect arguments to GENERATE subcommand."); return false; } if (args.size() != 7) { - this->SetError("Incorrect arguments to GENERATE subcommand."); + status.SetError("Incorrect arguments to GENERATE subcommand."); return false; } condition = args[6]; if (condition.empty()) { - this->SetError("CONDITION of sub-command GENERATE must not be empty if " - "specified."); + status.SetError("CONDITION of sub-command GENERATE must not be empty if " + "specified."); return false; } } std::string output = args[2]; const bool inputIsContent = args[3] != "INPUT"; if (inputIsContent && args[3] != "CONTENT") { - this->SetError("Incorrect arguments to GENERATE subcommand."); + status.SetError("Incorrect arguments to GENERATE subcommand."); return false; } std::string input = args[4]; - this->AddEvaluationFile(input, output, condition, inputIsContent); + AddEvaluationFile(input, output, condition, inputIsContent, status); return true; } -bool cmFileCommand::HandleLockCommand(std::vector<std::string> const& args) +bool HandleLockCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) // Default values bool directory = false; bool release = false; @@ -2353,7 +2296,7 @@ bool cmFileCommand::HandleLockCommand(std::vector<std::string> const& args) // Parse arguments if (args.size() < 2) { - this->Makefile->IssueMessage( + status.GetMakefile().IssueMessage( MessageType::FATAL_ERROR, "sub-command LOCK requires at least two arguments."); return false; @@ -2369,7 +2312,7 @@ bool cmFileCommand::HandleLockCommand(std::vector<std::string> const& args) ++i; const char* merr = "expected FUNCTION, FILE or PROCESS after GUARD"; if (i >= args.size()) { - this->Makefile->IssueMessage(MessageType::FATAL_ERROR, merr); + status.GetMakefile().IssueMessage(MessageType::FATAL_ERROR, merr); return false; } if (args[i] == "FUNCTION") { @@ -2381,14 +2324,14 @@ bool cmFileCommand::HandleLockCommand(std::vector<std::string> const& args) } else { std::ostringstream e; e << merr << ", but got:\n \"" << args[i] << "\"."; - this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str()); + status.GetMakefile().IssueMessage(MessageType::FATAL_ERROR, e.str()); return false; } } else if (args[i] == "RESULT_VARIABLE") { ++i; if (i >= args.size()) { - this->Makefile->IssueMessage( + status.GetMakefile().IssueMessage( MessageType::FATAL_ERROR, "expected variable name after RESULT_VARIABLE"); return false; @@ -2397,16 +2340,15 @@ bool cmFileCommand::HandleLockCommand(std::vector<std::string> const& args) } else if (args[i] == "TIMEOUT") { ++i; if (i >= args.size()) { - this->Makefile->IssueMessage(MessageType::FATAL_ERROR, - "expected timeout value after TIMEOUT"); + status.GetMakefile().IssueMessage( + MessageType::FATAL_ERROR, "expected timeout value after TIMEOUT"); return false; } long scanned; - if (!cmSystemTools::StringToLong(args[i].c_str(), &scanned) || - scanned < 0) { + if (!cmStrToLong(args[i], &scanned) || scanned < 0) { std::ostringstream e; e << "TIMEOUT value \"" << args[i] << "\" is not an unsigned integer."; - this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str()); + status.GetMakefile().IssueMessage(MessageType::FATAL_ERROR, e.str()); return false; } timeout = static_cast<unsigned long>(scanned); @@ -2414,7 +2356,7 @@ bool cmFileCommand::HandleLockCommand(std::vector<std::string> const& args) std::ostringstream e; e << "expected DIRECTORY, RELEASE, GUARD, RESULT_VARIABLE or TIMEOUT\n"; e << "but got: \"" << args[i] << "\"."; - this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str()); + status.GetMakefile().IssueMessage(MessageType::FATAL_ERROR, e.str()); return false; } } @@ -2424,7 +2366,7 @@ bool cmFileCommand::HandleLockCommand(std::vector<std::string> const& args) } if (!cmsys::SystemTools::FileIsFullPath(path)) { - path = this->Makefile->GetCurrentSourceDirectory() + "/" + path; + path = status.GetMakefile().GetCurrentSourceDirectory() + "/" + path; } // Unify path (remove '//', '/../', ...) @@ -2436,7 +2378,7 @@ bool cmFileCommand::HandleLockCommand(std::vector<std::string> const& args) std::ostringstream e; e << "directory\n \"" << parentDir << "\"\ncreation failed "; e << "(check permissions)."; - this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str()); + status.GetMakefile().IssueMessage(MessageType::FATAL_ERROR, e.str()); cmSystemTools::SetFatalErrorOccured(); return false; } @@ -2444,7 +2386,7 @@ bool cmFileCommand::HandleLockCommand(std::vector<std::string> const& args) if (!file) { std::ostringstream e; e << "file\n \"" << path << "\"\ncreation failed (check permissions)."; - this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str()); + status.GetMakefile().IssueMessage(MessageType::FATAL_ERROR, e.str()); cmSystemTools::SetFatalErrorOccured(); return false; } @@ -2452,7 +2394,7 @@ bool cmFileCommand::HandleLockCommand(std::vector<std::string> const& args) // Actual lock/unlock cmFileLockPool& lockPool = - this->Makefile->GetGlobalGenerator()->GetFileLockPool(); + status.GetMakefile().GetGlobalGenerator()->GetFileLockPool(); cmFileLockResult fileLockResult(cmFileLockResult::MakeOk()); if (release) { @@ -2479,32 +2421,32 @@ bool cmFileCommand::HandleLockCommand(std::vector<std::string> const& args) if (resultVariable.empty() && !fileLockResult.IsOk()) { std::ostringstream e; e << "error locking file\n \"" << path << "\"\n" << result << "."; - this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str()); + status.GetMakefile().IssueMessage(MessageType::FATAL_ERROR, e.str()); cmSystemTools::SetFatalErrorOccured(); return false; } if (!resultVariable.empty()) { - this->Makefile->AddDefinition(resultVariable, result); + status.GetMakefile().AddDefinition(resultVariable, result); } return true; #else static_cast<void>(args); - this->SetError("sub-command LOCK not implemented in bootstrap cmake"); + status.SetError("sub-command LOCK not implemented in bootstrap cmake"); return false; #endif } -bool cmFileCommand::HandleTimestampCommand( - std::vector<std::string> const& args) +bool HandleTimestampCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() < 3) { - this->SetError("sub-command TIMESTAMP requires at least two arguments."); + status.SetError("sub-command TIMESTAMP requires at least two arguments."); return false; } if (args.size() > 5) { - this->SetError("sub-command TIMESTAMP takes at most four arguments."); + status.SetError("sub-command TIMESTAMP takes at most four arguments."); return false; } @@ -2526,7 +2468,7 @@ bool cmFileCommand::HandleTimestampCommand( } else { std::string e = " TIMESTAMP sub-command does not recognize option " + args[argsIndex] + "."; - this->SetError(e); + status.SetError(e); return false; } } @@ -2534,17 +2476,18 @@ bool cmFileCommand::HandleTimestampCommand( cmTimestamp timestamp; std::string result = timestamp.FileModificationTime(filename.c_str(), formatString, utcFlag); - this->Makefile->AddDefinition(outputVariable, result); + status.GetMakefile().AddDefinition(outputVariable, result); return true; } -bool cmFileCommand::HandleSizeCommand(std::vector<std::string> const& args) +bool HandleSizeCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() != 3) { std::ostringstream e; e << args[0] << " requires a file name and output variable"; - this->SetError(e.str()); + status.SetError(e.str()); return false; } @@ -2557,23 +2500,23 @@ bool cmFileCommand::HandleSizeCommand(std::vector<std::string> const& args) if (!cmSystemTools::FileExists(filename, true)) { std::ostringstream e; e << "SIZE requested of path that is not readable:\n " << filename; - this->SetError(e.str()); + status.SetError(e.str()); return false; } - this->Makefile->AddDefinition( + status.GetMakefile().AddDefinition( outputVariable, std::to_string(cmSystemTools::FileLength(filename))); return true; } -bool cmFileCommand::HandleReadSymlinkCommand( - std::vector<std::string> const& args) +bool HandleReadSymlinkCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() != 3) { std::ostringstream e; e << args[0] << " requires a file name and output variable"; - this->SetError(e.str()); + status.SetError(e.str()); return false; } @@ -2585,21 +2528,21 @@ bool cmFileCommand::HandleReadSymlinkCommand( std::ostringstream e; e << "READ_SYMLINK requested of path that is not a symlink:\n " << filename; - this->SetError(e.str()); + status.SetError(e.str()); return false; } - this->Makefile->AddDefinition(outputVariable, result); + status.GetMakefile().AddDefinition(outputVariable, result); return true; } -bool cmFileCommand::HandleCreateLinkCommand( - std::vector<std::string> const& args) +bool HandleCreateLinkCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() < 3) { - this->SetError("CREATE_LINK must be called with at least two additional " - "arguments"); + status.SetError("CREATE_LINK must be called with at least two additional " + "arguments"); return false; } @@ -2624,7 +2567,7 @@ bool cmFileCommand::HandleCreateLinkCommand( parser.Parse(cmMakeRange(args).advance(3), &unconsumedArgs); if (!unconsumedArgs.empty()) { - this->SetError("unknown argument: \"" + unconsumedArgs.front() + '\"'); + status.SetError("unknown argument: \"" + unconsumedArgs.front() + '\"'); return false; } @@ -2635,10 +2578,10 @@ bool cmFileCommand::HandleCreateLinkCommand( if (fileName == newFileName) { result = "CREATE_LINK cannot use same file and newfile"; if (!arguments.Result.empty()) { - this->Makefile->AddDefinition(arguments.Result, result); + status.GetMakefile().AddDefinition(arguments.Result, result); return true; } - this->SetError(result); + status.SetError(result); return false; } @@ -2646,10 +2589,10 @@ bool cmFileCommand::HandleCreateLinkCommand( if (!arguments.Symbolic && !cmSystemTools::FileExists(fileName)) { result = "Cannot hard link \'" + fileName + "\' as it does not exist."; if (!arguments.Result.empty()) { - this->Makefile->AddDefinition(arguments.Result, result); + status.GetMakefile().AddDefinition(arguments.Result, result); return true; } - this->SetError(result); + status.SetError(result); return false; } @@ -2663,10 +2606,10 @@ bool cmFileCommand::HandleCreateLinkCommand( << cmSystemTools::GetLastSystemError() << "\n"; if (!arguments.Result.empty()) { - this->Makefile->AddDefinition(arguments.Result, e.str()); + status.GetMakefile().AddDefinition(arguments.Result, e.str()); return true; } - this->SetError(e.str()); + status.SetError(e.str()); return false; } @@ -2693,45 +2636,46 @@ bool cmFileCommand::HandleCreateLinkCommand( result = "0"; } else if (arguments.Result.empty()) { // The operation failed and the result is not reported in a variable. - this->SetError(result); + status.SetError(result); return false; } if (!arguments.Result.empty()) { - this->Makefile->AddDefinition(arguments.Result, result); + status.GetMakefile().AddDefinition(arguments.Result, result); } return true; } -bool cmFileCommand::HandleGetRuntimeDependenciesCommand( - std::vector<std::string> const& args) +bool HandleGetRuntimeDependenciesCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { static const std::set<std::string> supportedPlatforms = { "Windows", "Linux", "Darwin" }; std::string platform = - this->Makefile->GetSafeDefinition("CMAKE_HOST_SYSTEM_NAME"); + status.GetMakefile().GetSafeDefinition("CMAKE_HOST_SYSTEM_NAME"); if (!supportedPlatforms.count(platform)) { std::ostringstream e; e << "GET_RUNTIME_DEPENDENCIES is not supported on system \"" << platform << "\""; - this->SetError(e.str()); + status.SetError(e.str()); cmSystemTools::SetFatalErrorOccured(); return false; } - if (this->Makefile->GetState()->GetMode() == cmState::Project) { - this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, - "You have used file(GET_RUNTIME_DEPENDENCIES)" - " in project mode. This is probably not what " - "you intended to do. Instead, please consider" - " using it in an install(CODE) or " - "install(SCRIPT) command. For example:" - "\n install(CODE [[" - "\n file(GET_RUNTIME_DEPENDENCIES" - "\n # ..." - "\n )" - "\n ]])"); + if (status.GetMakefile().GetState()->GetMode() == cmState::Project) { + status.GetMakefile().IssueMessage( + MessageType::AUTHOR_WARNING, + "You have used file(GET_RUNTIME_DEPENDENCIES)" + " in project mode. This is probably not what " + "you intended to do. Instead, please consider" + " using it in an install(CODE) or " + "install(SCRIPT) command. For example:" + "\n install(CODE [[" + "\n file(GET_RUNTIME_DEPENDENCIES" + "\n # ..." + "\n )" + "\n ]])"); } struct Arguments @@ -2776,7 +2720,7 @@ bool cmFileCommand::HandleGetRuntimeDependenciesCommand( if (argIt != unrecognizedArguments.end()) { std::ostringstream e; e << "Unrecognized argument: \"" << *argIt << "\""; - this->SetError(e.str()); + status.SetError(e.str()); cmSystemTools::SetFatalErrorOccured(); return false; } @@ -2784,13 +2728,13 @@ bool cmFileCommand::HandleGetRuntimeDependenciesCommand( if (argIt != keywordsMissingValues.end()) { std::ostringstream e; e << "Keyword missing value: " << *argIt; - this->SetError(e.str()); + status.SetError(e.str()); cmSystemTools::SetFatalErrorOccured(); return false; } cmRuntimeDependencyArchive archive( - this, parsedArgs.Directories, parsedArgs.BundleExecutable, + status, parsedArgs.Directories, parsedArgs.BundleExecutable, parsedArgs.PreIncludeRegexes, parsedArgs.PreExcludeRegexes, parsedArgs.PostIncludeRegexes, parsedArgs.PostExcludeRegexes); if (!archive.Prepare()) { @@ -2804,7 +2748,9 @@ bool cmFileCommand::HandleGetRuntimeDependenciesCommand( return false; } - std::vector<std::string> deps, unresolvedDeps, conflictingDeps; + std::vector<std::string> deps; + std::vector<std::string> unresolvedDeps; + std::vector<std::string> conflictingDeps; for (auto const& val : archive.GetResolvedPaths()) { bool unique = true; auto it = val.second.begin(); @@ -2826,14 +2772,14 @@ bool cmFileCommand::HandleGetRuntimeDependenciesCommand( std::string varName = parsedArgs.ConflictingDependenciesPrefix + "_" + val.first; std::string pathsStr = cmJoin(paths, ";"); - this->Makefile->AddDefinition(varName, pathsStr); + status.GetMakefile().AddDefinition(varName, pathsStr); } else { std::ostringstream e; e << "Multiple conflicting paths found for " << val.first << ":"; for (auto const& path : val.second) { e << "\n " << path; } - this->SetError(e.str()); + status.SetError(e.str()); cmSystemTools::SetFatalErrorOccured(); return false; } @@ -2848,7 +2794,7 @@ bool cmFileCommand::HandleGetRuntimeDependenciesCommand( assert(it != archive.GetUnresolvedPaths().end()); std::ostringstream e; e << "Could not resolve file " << *it; - this->SetError(e.str()); + status.SetError(e.str()); cmSystemTools::SetFatalErrorOccured(); return false; } @@ -2856,16 +2802,76 @@ bool cmFileCommand::HandleGetRuntimeDependenciesCommand( if (!parsedArgs.ResolvedDependenciesVar.empty()) { std::string val = cmJoin(deps, ";"); - this->Makefile->AddDefinition(parsedArgs.ResolvedDependenciesVar, val); + status.GetMakefile().AddDefinition(parsedArgs.ResolvedDependenciesVar, + val); } if (!parsedArgs.UnresolvedDependenciesVar.empty()) { std::string val = cmJoin(unresolvedDeps, ";"); - this->Makefile->AddDefinition(parsedArgs.UnresolvedDependenciesVar, val); + status.GetMakefile().AddDefinition(parsedArgs.UnresolvedDependenciesVar, + val); } if (!parsedArgs.ConflictingDependenciesPrefix.empty()) { std::string val = cmJoin(conflictingDeps, ";"); - this->Makefile->AddDefinition( + status.GetMakefile().AddDefinition( parsedArgs.ConflictingDependenciesPrefix + "_FILENAMES", val); } return true; } + +} // namespace + +bool cmFileCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) +{ + if (args.size() < 2) { + status.SetError("must be called with at least two arguments."); + return false; + } + + static cmSubcommandTable const subcommand{ + { "WRITE"_s, HandleWriteCommand }, + { "APPEND"_s, HandleAppendCommand }, + { "DOWNLOAD"_s, HandleDownloadCommand }, + { "UPLOAD"_s, HandleUploadCommand }, + { "READ"_s, HandleReadCommand }, + { "MD5"_s, HandleHashCommand }, + { "SHA1"_s, HandleHashCommand }, + { "SHA224"_s, HandleHashCommand }, + { "SHA256"_s, HandleHashCommand }, + { "SHA384"_s, HandleHashCommand }, + { "SHA512"_s, HandleHashCommand }, + { "SHA3_224"_s, HandleHashCommand }, + { "SHA3_256"_s, HandleHashCommand }, + { "SHA3_384"_s, HandleHashCommand }, + { "SHA3_512"_s, HandleHashCommand }, + { "STRINGS"_s, HandleStringsCommand }, + { "GLOB"_s, HandleGlobCommand }, + { "GLOB_RECURSE"_s, HandleGlobRecurseCommand }, + { "MAKE_DIRECTORY"_s, HandleMakeDirectoryCommand }, + { "RENAME"_s, HandleRename }, + { "REMOVE"_s, HandleRemove }, + { "REMOVE_RECURSE"_s, HandleRemoveRecurse }, + { "COPY"_s, HandleCopyCommand }, + { "INSTALL"_s, HandleInstallCommand }, + { "DIFFERENT"_s, HandleDifferentCommand }, + { "RPATH_CHANGE"_s, HandleRPathChangeCommand }, + { "CHRPATH"_s, HandleRPathChangeCommand }, + { "RPATH_CHECK"_s, HandleRPathCheckCommand }, + { "RPATH_REMOVE"_s, HandleRPathRemoveCommand }, + { "READ_ELF"_s, HandleReadElfCommand }, + { "RELATIVE_PATH"_s, HandleRelativePathCommand }, + { "TO_CMAKE_PATH"_s, HandleCMakePathCommand }, + { "TO_NATIVE_PATH"_s, HandleNativePathCommand }, + { "TOUCH"_s, HandleTouchCommand }, + { "TOUCH_NOCREATE"_s, HandleTouchNocreateCommand }, + { "TIMESTAMP"_s, HandleTimestampCommand }, + { "GENERATE"_s, HandleGenerateCommand }, + { "LOCK"_s, HandleLockCommand }, + { "SIZE"_s, HandleSizeCommand }, + { "READ_SYMLINK"_s, HandleReadSymlinkCommand }, + { "CREATE_LINK"_s, HandleCreateLinkCommand }, + { "GET_RUNTIME_DEPENDENCIES"_s, HandleGetRuntimeDependenciesCommand }, + }; + + return subcommand(args[0], args, status); +} diff --git a/Source/cmFileCommand.h b/Source/cmFileCommand.h index d4b980e..8c9b219 100644 --- a/Source/cmFileCommand.h +++ b/Source/cmFileCommand.h @@ -8,72 +8,9 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -/** \class cmFileCommand - * \brief Command for manipulation of files - * - */ -class cmFileCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmFileCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; - -protected: - bool HandleRename(std::vector<std::string> const& args); - bool HandleRemove(std::vector<std::string> const& args, bool recurse); - bool HandleWriteCommand(std::vector<std::string> const& args, bool append); - bool HandleReadCommand(std::vector<std::string> const& args); - bool HandleHashCommand(std::vector<std::string> const& args); - bool HandleStringsCommand(std::vector<std::string> const& args); - bool HandleGlobCommand(std::vector<std::string> const& args, bool recurse); - bool HandleTouchCommand(std::vector<std::string> const& args, bool create); - bool HandleMakeDirectoryCommand(std::vector<std::string> const& args); - - bool HandleRelativePathCommand(std::vector<std::string> const& args); - bool HandleCMakePathCommand(std::vector<std::string> const& args, - bool nativePath); - bool HandleReadElfCommand(std::vector<std::string> const& args); - bool HandleRPathChangeCommand(std::vector<std::string> const& args); - bool HandleRPathCheckCommand(std::vector<std::string> const& args); - bool HandleRPathRemoveCommand(std::vector<std::string> const& args); - bool HandleDifferentCommand(std::vector<std::string> const& args); - - bool HandleCopyCommand(std::vector<std::string> const& args); - bool HandleInstallCommand(std::vector<std::string> const& args); - bool HandleDownloadCommand(std::vector<std::string> const& args); - bool HandleUploadCommand(std::vector<std::string> const& args); - - bool HandleTimestampCommand(std::vector<std::string> const& args); - bool HandleGenerateCommand(std::vector<std::string> const& args); - bool HandleLockCommand(std::vector<std::string> const& args); - bool HandleSizeCommand(std::vector<std::string> const& args); - bool HandleReadSymlinkCommand(std::vector<std::string> const& args); - bool HandleCreateLinkCommand(std::vector<std::string> const& args); - bool HandleGetRuntimeDependenciesCommand( - std::vector<std::string> const& args); - -private: - void AddEvaluationFile(const std::string& inputName, - const std::string& outputExpr, - const std::string& condition, bool inputIsContent); -}; +bool cmFileCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmFileCopier.cxx b/Source/cmFileCopier.cxx index 4f1a158..3156c95 100644 --- a/Source/cmFileCopier.cxx +++ b/Source/cmFileCopier.cxx @@ -3,10 +3,11 @@ #include "cmFileCopier.h" +#include "cmExecutionStatus.h" #include "cmFSPermissions.h" -#include "cmFileCommand.h" #include "cmFileTimes.h" #include "cmMakefile.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmsys/Directory.hxx" #include "cmsys/Glob.hxx" @@ -20,9 +21,9 @@ using namespace cmFSPermissions; -cmFileCopier::cmFileCopier(cmFileCommand* command, const char* name) - : FileCommand(command) - , Makefile(command->GetMakefile()) +cmFileCopier::cmFileCopier(cmExecutionStatus& status, const char* name) + : Status(status) + , Makefile(&status.GetMakefile()) , Name(name) , Always(false) , MatchlessFiles(true) @@ -90,8 +91,9 @@ bool cmFileCopier::SetPermissions(const std::string& toFile, if (!cmSystemTools::SetPermissions(toFile, permissions)) { std::ostringstream e; - e << this->Name << " cannot set permissions on \"" << toFile << "\""; - this->FileCommand->SetError(e.str()); + e << this->Name << " cannot set permissions on \"" << toFile + << "\": " << cmSystemTools::GetLastSystemError() << "."; + this->Status.SetError(e.str()); return false; } } @@ -105,7 +107,7 @@ bool cmFileCopier::CheckPermissions(std::string const& arg, if (!cmFSPermissions::stringToModeT(arg, permissions)) { std::ostringstream e; e << this->Name << " given invalid permission \"" << arg << "\"."; - this->FileCommand->SetError(e.str()); + this->Status.SetError(e.str()); return false; } return true; @@ -120,8 +122,9 @@ bool cmFileCopier::ReportMissing(const std::string& fromFile) { // The input file does not exist and installation is not optional. std::ostringstream e; - e << this->Name << " cannot find \"" << fromFile << "\"."; - this->FileCommand->SetError(e.str()); + e << this->Name << " cannot find \"" << fromFile + << "\": " << cmSystemTools::GetLastSystemError() << "."; + this->Status.SetError(e.str()); return false; } @@ -129,7 +132,7 @@ void cmFileCopier::NotBeforeMatch(std::string const& arg) { std::ostringstream e; e << "option " << arg << " may not appear before PATTERN or REGEX."; - this->FileCommand->SetError(e.str()); + this->Status.SetError(e.str()); this->Doing = DoingError; } @@ -137,7 +140,7 @@ void cmFileCopier::NotAfterMatch(std::string const& arg) { std::ostringstream e; e << "option " << arg << " may not appear after PATTERN or REGEX."; - this->FileCommand->SetError(e.str()); + this->Status.SetError(e.str()); this->Doing = DoingError; } @@ -171,10 +174,10 @@ bool cmFileCopier::GetDefaultDirectoryPermissions(mode_t** mode) "CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS"); if (default_dir_install_permissions && *default_dir_install_permissions) { std::vector<std::string> items; - cmSystemTools::ExpandListArgument(default_dir_install_permissions, items); + cmExpandList(default_dir_install_permissions, items); for (const auto& arg : items) { if (!this->CheckPermissions(arg, **mode)) { - this->FileCommand->SetError( + this->Status.SetError( " Set with CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS variable."); return false; } @@ -194,7 +197,7 @@ bool cmFileCopier::Parse(std::vector<std::string> const& args) if (!this->CheckKeyword(args[i]) && !this->CheckValue(args[i])) { std::ostringstream e; e << "called with unknown argument \"" << args[i] << "\"."; - this->FileCommand->SetError(e.str()); + this->Status.SetError(e.str()); return false; } @@ -208,7 +211,7 @@ bool cmFileCopier::Parse(std::vector<std::string> const& args) if (this->Destination.empty()) { std::ostringstream e; e << this->Name << " given no DESTINATION"; - this->FileCommand->SetError(e.str()); + this->Status.SetError(e.str()); return false; } @@ -311,8 +314,8 @@ bool cmFileCopier::CheckValue(std::string const& arg) if (arg.empty() || cmSystemTools::FileIsFullPath(arg)) { this->Destination = arg; } else { - this->Destination = this->Makefile->GetCurrentBinaryDirectory(); - this->Destination += "/" + arg; + this->Destination = + cmStrCat(this->Makefile->GetCurrentBinaryDirectory(), '/', arg); } this->Doing = DoingNone; break; @@ -320,8 +323,8 @@ bool cmFileCopier::CheckValue(std::string const& arg) if (cmSystemTools::FileIsFullPath(arg)) { this->FilesFromDir = arg; } else { - this->FilesFromDir = this->Makefile->GetCurrentSourceDirectory(); - this->FilesFromDir += "/" + arg; + this->FilesFromDir = + cmStrCat(this->Makefile->GetCurrentSourceDirectory(), '/', arg); } cmSystemTools::ConvertToUnixSlashes(this->FilesFromDir); this->Doing = DoingNone; @@ -331,9 +334,8 @@ bool cmFileCopier::CheckValue(std::string const& arg) // leading slash and trailing end-of-string in the matched // string to make sure the pattern matches only whole file // names. - std::string regex = "/"; - regex += cmsys::Glob::PatternToRegex(arg, false); - regex += "$"; + std::string regex = + cmStrCat('/', cmsys::Glob::PatternToRegex(arg, false), '$'); this->MatchRules.emplace_back(regex); this->CurrentMatchRule = &*(this->MatchRules.end() - 1); if (this->CurrentMatchRule->Regex.is_valid()) { @@ -341,7 +343,7 @@ bool cmFileCopier::CheckValue(std::string const& arg) } else { std::ostringstream e; e << "could not compile PATTERN \"" << arg << "\"."; - this->FileCommand->SetError(e.str()); + this->Status.SetError(e.str()); this->Doing = DoingError; } } break; @@ -353,7 +355,7 @@ bool cmFileCopier::CheckValue(std::string const& arg) } else { std::ostringstream e; e << "could not compile REGEX \"" << arg << "\"."; - this->FileCommand->SetError(e.str()); + this->Status.SetError(e.str()); this->Doing = DoingError; } break; @@ -396,8 +398,8 @@ bool cmFileCopier::Run(std::vector<std::string> const& args) file += "/"; file += f; } else if (!this->FilesFromDir.empty()) { - this->FileCommand->SetError("option FILES_FROM_DIR requires all files " - "to be specified as relative paths."); + this->Status.SetError("option FILES_FROM_DIR requires all files " + "to be specified as relative paths."); return false; } else { file = f; @@ -446,7 +448,7 @@ bool cmFileCopier::Install(const std::string& fromFile, if (fromFile.empty()) { std::ostringstream e; e << "INSTALL encountered an empty string input file name."; - this->FileCommand->SetError(e.str()); + this->Status.SetError(e.str()); return false; } @@ -490,7 +492,7 @@ bool cmFileCopier::InstallSymlinkChain(std::string& fromFile, while (cmSystemTools::ReadSymlink(fromFile, newFromFile)) { if (!cmSystemTools::FileIsFullPath(newFromFile)) { std::string fromFilePath = cmSystemTools::GetFilenamePath(fromFile); - newFromFile = fromFilePath + "/" + newFromFile; + newFromFile = cmStrCat(fromFilePath, "/", newFromFile); } std::string symlinkTarget = cmSystemTools::GetFilenameName(newFromFile); @@ -513,14 +515,15 @@ bool cmFileCopier::InstallSymlinkChain(std::string& fromFile, if (!cmSystemTools::CreateSymlink(symlinkTarget, toFile)) { std::ostringstream e; - e << this->Name << " cannot create symlink \"" << toFile << "\"."; - this->FileCommand->SetError(e.str()); + e << this->Name << " cannot create symlink \"" << toFile + << "\": " << cmSystemTools::GetLastSystemError() << "."; + this->Status.SetError(e.str()); return false; } } fromFile = newFromFile; - toFile = toFilePath + "/" + symlinkTarget; + toFile = cmStrCat(toFilePath, "/", symlinkTarget); } return true; @@ -534,8 +537,9 @@ bool cmFileCopier::InstallSymlink(const std::string& fromFile, if (!cmSystemTools::ReadSymlink(fromFile, symlinkTarget)) { std::ostringstream e; e << this->Name << " cannot read symlink \"" << fromFile - << "\" to duplicate at \"" << toFile << "\"."; - this->FileCommand->SetError(e.str()); + << "\" to duplicate at \"" << toFile + << "\": " << cmSystemTools::GetLastSystemError() << "."; + this->Status.SetError(e.str()); return false; } @@ -565,8 +569,9 @@ bool cmFileCopier::InstallSymlink(const std::string& fromFile, if (!cmSystemTools::CreateSymlink(symlinkTarget, toFile)) { std::ostringstream e; e << this->Name << " cannot duplicate symlink \"" << fromFile - << "\" at \"" << toFile << "\"."; - this->FileCommand->SetError(e.str()); + << "\" at \"" << toFile + << "\": " << cmSystemTools::GetLastSystemError() << "."; + this->Status.SetError(e.str()); return false; } } @@ -594,8 +599,8 @@ bool cmFileCopier::InstallFile(const std::string& fromFile, if (copy && !cmSystemTools::CopyAFile(fromFile, toFile, true)) { std::ostringstream e; e << this->Name << " cannot copy file \"" << fromFile << "\" to \"" - << toFile << "\"."; - this->FileCommand->SetError(e.str()); + << toFile << "\": " << cmSystemTools::GetLastSystemError() << "."; + this->Status.SetError(e.str()); return false; } @@ -610,8 +615,8 @@ bool cmFileCopier::InstallFile(const std::string& fromFile, if (!cmFileTimes::Copy(fromFile, toFile)) { std::ostringstream e; e << this->Name << " cannot set modification time on \"" << toFile - << "\""; - this->FileCommand->SetError(e.str()); + << "\": " << cmSystemTools::GetLastSystemError() << "."; + this->Status.SetError(e.str()); return false; } } @@ -647,8 +652,8 @@ bool cmFileCopier::InstallDirectory(const std::string& source, if (!cmSystemTools::MakeDirectory(destination, default_dir_mode)) { std::ostringstream e; e << this->Name << " cannot make directory \"" << destination - << "\": " << cmSystemTools::GetLastSystemError(); - this->FileCommand->SetError(e.str()); + << "\": " << cmSystemTools::GetLastSystemError() << "."; + this->Status.SetError(e.str()); return false; } @@ -693,12 +698,8 @@ bool cmFileCopier::InstallDirectory(const std::string& source, for (unsigned long fileNum = 0; fileNum < numFiles; ++fileNum) { if (!(strcmp(dir.GetFile(fileNum), ".") == 0 || strcmp(dir.GetFile(fileNum), "..") == 0)) { - std::string fromPath = source; - fromPath += "/"; - fromPath += dir.GetFile(fileNum); - std::string toPath = destination; - toPath += "/"; - toPath += dir.GetFile(fileNum); + std::string fromPath = cmStrCat(source, '/', dir.GetFile(fileNum)); + std::string toPath = cmStrCat(destination, '/', dir.GetFile(fileNum)); if (!this->Install(fromPath, toPath)) { return false; } diff --git a/Source/cmFileCopier.h b/Source/cmFileCopier.h index a79a60b..263a365 100644 --- a/Source/cmFileCopier.h +++ b/Source/cmFileCopier.h @@ -12,19 +12,19 @@ #include <string> #include <vector> -class cmFileCommand; +class cmExecutionStatus; class cmMakefile; // File installation helper class. struct cmFileCopier { - cmFileCopier(cmFileCommand* command, const char* name = "COPY"); + cmFileCopier(cmExecutionStatus& status, const char* name = "COPY"); virtual ~cmFileCopier(); bool Run(std::vector<std::string> const& args); protected: - cmFileCommand* FileCommand; + cmExecutionStatus& Status; cmMakefile* Makefile; const char* Name; bool Always; diff --git a/Source/cmFileInstaller.cxx b/Source/cmFileInstaller.cxx index 9378439..a773738 100644 --- a/Source/cmFileInstaller.cxx +++ b/Source/cmFileInstaller.cxx @@ -3,9 +3,10 @@ #include "cmFileInstaller.h" +#include "cmExecutionStatus.h" #include "cmFSPermissions.h" -#include "cmFileCommand.h" #include "cmMakefile.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cm_sys_stat.h" @@ -14,8 +15,8 @@ using namespace cmFSPermissions; -cmFileInstaller::cmFileInstaller(cmFileCommand* command) - : cmFileCopier(command, "INSTALL") +cmFileInstaller::cmFileInstaller(cmExecutionStatus& status) + : cmFileCopier(status, "INSTALL") , InstallType(cmInstallType_FILES) , Optional(false) , MessageAlways(false) @@ -28,7 +29,7 @@ cmFileInstaller::cmFileInstaller(cmFileCommand* command) // Check whether to copy files always or only if they have changed. std::string install_always; if (cmSystemTools::GetEnv("CMAKE_INSTALL_ALWAYS", install_always)) { - this->Always = cmSystemTools::IsOn(install_always); + this->Always = cmIsOn(install_always); } // Get the current manifest. this->Manifest = @@ -58,8 +59,8 @@ void cmFileInstaller::ReportCopy(const std::string& toFile, Type type, bool copy) { if (!this->MessageNever && (copy || !this->MessageLazy)) { - std::string message = (copy ? "Installing: " : "Up-to-date: "); - message += toFile; + std::string message = + cmStrCat((copy ? "Installing: " : "Up-to-date: "), toFile); this->Makefile->DisplayStatus(message, -1); } if (type != TypeDir) { @@ -111,19 +112,19 @@ bool cmFileInstaller::Parse(std::vector<std::string> const& args) if (!this->Rename.empty()) { if (!this->FilesFromDir.empty()) { - this->FileCommand->SetError("INSTALL option RENAME may not be " - "combined with FILES_FROM_DIR."); + this->Status.SetError("INSTALL option RENAME may not be " + "combined with FILES_FROM_DIR."); return false; } if (this->InstallType != cmInstallType_FILES && this->InstallType != cmInstallType_PROGRAMS) { - this->FileCommand->SetError("INSTALL option RENAME may be used " - "only with FILES or PROGRAMS."); + this->Status.SetError("INSTALL option RENAME may be used " + "only with FILES or PROGRAMS."); return false; } if (this->Files.size() > 1) { - this->FileCommand->SetError("INSTALL option RENAME may be used " - "only with one file."); + this->Status.SetError("INSTALL option RENAME may be used " + "only with one file."); return false; } } @@ -134,9 +135,9 @@ bool cmFileInstaller::Parse(std::vector<std::string> const& args) if (((this->MessageAlways ? 1 : 0) + (this->MessageLazy ? 1 : 0) + (this->MessageNever ? 1 : 0)) > 1) { - this->FileCommand->SetError("INSTALL options MESSAGE_ALWAYS, " - "MESSAGE_LAZY, and MESSAGE_NEVER " - "are mutually exclusive."); + this->Status.SetError("INSTALL options MESSAGE_ALWAYS, " + "MESSAGE_LAZY, and MESSAGE_NEVER " + "are mutually exclusive."); return false; } @@ -213,7 +214,7 @@ bool cmFileInstaller::CheckKeyword(std::string const& arg) e << "INSTALL called with old-style " << arg << " argument. " << "This script was generated with an older version of CMake. " << "Re-run this cmake version on your build tree."; - this->FileCommand->SetError(e.str()); + this->Status.SetError(e.str()); this->Doing = DoingError; } else { return this->cmFileCopier::CheckKeyword(arg); @@ -257,7 +258,7 @@ bool cmFileInstaller::GetTargetTypeFromString(const std::string& stype) } else { std::ostringstream e; e << "Option TYPE given unknown value \"" << stype << "\"."; - this->FileCommand->SetError(e.str()); + this->Status.SetError(e.str()); return false; } return true; @@ -269,8 +270,8 @@ bool cmFileInstaller::HandleInstallDestination() // allow for / to be a valid destination if (destination.size() < 2 && destination != "/") { - this->FileCommand->SetError("called with inappropriate arguments. " - "No DESTINATION provided or ."); + this->Status.SetError("called with inappropriate arguments. " + "No DESTINATION provided or ."); return false; } @@ -300,7 +301,7 @@ bool cmFileInstaller::HandleInstallDestination() if (relative) { // This is relative path on unix or windows. Since we are doing // destdir, this case does not make sense. - this->FileCommand->SetError( + this->Status.SetError( "called with relative DESTINATION. This " "does not make sense when using DESTDIR. Specify " "absolute path or remove DESTDIR environment variable."); @@ -310,12 +311,12 @@ bool cmFileInstaller::HandleInstallDestination() if (ch2 == '/') { // looks like a network path. std::string message = - "called with network path DESTINATION. This " - "does not make sense when using DESTDIR. Specify local " - "absolute path or remove DESTDIR environment variable." - "\nDESTINATION=\n"; - message += destination; - this->FileCommand->SetError(message); + cmStrCat("called with network path DESTINATION. This " + "does not make sense when using DESTDIR. Specify local " + "absolute path or remove DESTDIR environment variable." + "\nDESTINATION=\n", + destination); + this->Status.SetError(message); return false; } } @@ -335,14 +336,14 @@ bool cmFileInstaller::HandleInstallDestination() if (!cmSystemTools::MakeDirectory(destination, default_dir_mode)) { std::string errstring = "cannot create directory: " + destination + ". Maybe need administrative privileges."; - this->FileCommand->SetError(errstring); + this->Status.SetError(errstring); return false; } } if (!cmSystemTools::FileIsDirectory(destination)) { std::string errstring = "INSTALL destination: " + destination + " is not a directory."; - this->FileCommand->SetError(errstring); + this->Status.SetError(errstring); return false; } } diff --git a/Source/cmFileInstaller.h b/Source/cmFileInstaller.h index 312529a..fd883ea 100644 --- a/Source/cmFileInstaller.h +++ b/Source/cmFileInstaller.h @@ -12,11 +12,11 @@ #include <string> #include <vector> -class cmFileCommand; +class cmExecutionStatus; struct cmFileInstaller : public cmFileCopier { - cmFileInstaller(cmFileCommand* command); + cmFileInstaller(cmExecutionStatus& status); ~cmFileInstaller() override; protected: diff --git a/Source/cmFileTimeCache.cxx b/Source/cmFileTimeCache.cxx index 24d6bf6..0d1dae5 100644 --- a/Source/cmFileTimeCache.cxx +++ b/Source/cmFileTimeCache.cxx @@ -38,7 +38,8 @@ bool cmFileTimeCache::Compare(std::string const& f1, std::string const& f2, int* result) { // Get the modification time for each file. - cmFileTime ft1, ft2; + cmFileTime ft1; + cmFileTime ft2; if (this->Load(f1, ft1) && this->Load(f2, ft2)) { // Compare the two modification times. *result = ft1.Compare(ft2); @@ -52,7 +53,8 @@ bool cmFileTimeCache::Compare(std::string const& f1, std::string const& f2, bool cmFileTimeCache::DifferS(std::string const& f1, std::string const& f2) { // Get the modification time for each file. - cmFileTime ft1, ft2; + cmFileTime ft1; + cmFileTime ft2; if (this->Load(f1, ft1) && this->Load(f2, ft2)) { // Compare the two modification times. return ft1.DifferS(ft2); diff --git a/Source/cmFindBase.cxx b/Source/cmFindBase.cxx index b1ccc83..191d7bb 100644 --- a/Source/cmFindBase.cxx +++ b/Source/cmFindBase.cxx @@ -189,9 +189,7 @@ void cmFindBase::FillCMakeEnvironmentPath() cmSearchPath& paths = this->LabeledPaths[PathLabel::CMakeEnvironment]; // Add CMAKE_*_PATH environment variables - std::string var = "CMAKE_"; - var += this->CMakePathName; - var += "_PATH"; + std::string var = cmStrCat("CMAKE_", this->CMakePathName, "_PATH"); paths.AddEnvPrefixPath("CMAKE_PREFIX_PATH"); paths.AddEnvPath(var); @@ -223,9 +221,7 @@ void cmFindBase::FillCMakeVariablePath() // Add CMake variables of the same name as the previous environment // variables CMAKE_*_PATH to be used most of the time with -D // command line options - std::string var = "CMAKE_"; - var += this->CMakePathName; - var += "_PATH"; + std::string var = cmStrCat("CMAKE_", this->CMakePathName, "_PATH"); paths.AddCMakePrefixPath("CMAKE_PREFIX_PATH"); paths.AddCMakePath(var); @@ -257,9 +253,7 @@ void cmFindBase::FillCMakeSystemVariablePath() { cmSearchPath& paths = this->LabeledPaths[PathLabel::CMakeSystem]; - std::string var = "CMAKE_SYSTEM_"; - var += this->CMakePathName; - var += "_PATH"; + std::string var = cmStrCat("CMAKE_SYSTEM_", this->CMakePathName, "_PATH"); paths.AddCMakePrefixPath("CMAKE_SYSTEM_PREFIX_PATH"); paths.AddCMakePath(var); @@ -324,7 +318,7 @@ bool cmFindBase::CheckForVariableInCache() this->Makefile->GetDefinition(this->VariableName)) { cmState* state = this->Makefile->GetState(); const char* cacheEntry = state->GetCacheEntryValue(this->VariableName); - bool found = !cmSystemTools::IsNOTFOUND(cacheValue); + bool found = !cmIsNOTFOUND(cacheValue); bool cached = cacheEntry != nullptr; if (found) { // If the user specifies the entry on the command line without a diff --git a/Source/cmFindCommon.cxx b/Source/cmFindCommon.cxx index a5937a0..9425f99 100644 --- a/Source/cmFindCommon.cxx +++ b/Source/cmFindCommon.cxx @@ -9,6 +9,7 @@ #include "cmAlgorithms.h" #include "cmMakefile.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" cmFindCommon::PathGroup cmFindCommon::PathGroup::All("ALL"); @@ -91,8 +92,8 @@ void cmFindCommon::InitializeSearchPathGroups() void cmFindCommon::SelectDefaultRootPathMode() { // Check the policy variable for this find command type. - std::string findRootPathVar = "CMAKE_FIND_ROOT_PATH_MODE_"; - findRootPathVar += this->CMakePathName; + std::string findRootPathVar = + cmStrCat("CMAKE_FIND_ROOT_PATH_MODE_", this->CMakePathName); std::string rootPathMode = this->Makefile->GetSafeDefinition(findRootPathVar); if (rootPathMode == "NEVER") { @@ -160,7 +161,7 @@ void cmFindCommon::SelectDefaultSearchModes() for (auto& path : search_paths) { const char* def = this->Makefile->GetDefinition(path.second); if (def) { - path.first = !cmSystemTools::IsOn(def); + path.first = !cmIsOn(def); } } } @@ -195,7 +196,7 @@ void cmFindCommon::RerootPaths(std::vector<std::string>& paths) // Construct the list of path roots with no trailing slashes. std::vector<std::string> roots; if (rootPath) { - cmSystemTools::ExpandListArgument(rootPath, roots); + cmExpandList(rootPath, roots); } if (sysrootCompile) { roots.emplace_back(sysrootCompile); @@ -228,8 +229,7 @@ void cmFindCommon::RerootPaths(std::vector<std::string>& paths) rootedDir = up; } else if (!up.empty() && up[0] != '~') { // Start with the new root. - rootedDir = r; - rootedDir += "/"; + rootedDir = cmStrCat(r, '/'); // Append the original path with its old root removed. rootedDir += cmSystemTools::SplitPathRootComponent(up); @@ -261,7 +261,7 @@ void cmFindCommon::GetIgnoredPaths(std::vector<std::string>& ignore) continue; } - cmSystemTools::ExpandListArgument(ignorePath, ignore); + cmExpandList(ignorePath, ignore); } for (std::string& i : ignore) { diff --git a/Source/cmFindLibraryCommand.cxx b/Source/cmFindLibraryCommand.cxx index 73d602d..924a14e 100644 --- a/Source/cmFindLibraryCommand.cxx +++ b/Source/cmFindLibraryCommand.cxx @@ -13,6 +13,7 @@ #include "cmMakefile.h" #include "cmState.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" class cmExecutionStatus; @@ -237,8 +238,8 @@ cmFindLibraryHelper::cmFindLibraryHelper(cmMakefile* mf) this->Makefile->GetRequiredDefinition("CMAKE_FIND_LIBRARY_PREFIXES"); std::string const& suffixes_list = this->Makefile->GetRequiredDefinition("CMAKE_FIND_LIBRARY_SUFFIXES"); - cmSystemTools::ExpandListArgument(prefixes_list, this->Prefixes, true); - cmSystemTools::ExpandListArgument(suffixes_list, this->Suffixes, true); + cmExpandList(prefixes_list, this->Prefixes, true); + cmExpandList(suffixes_list, this->Suffixes, true); this->RegexFromList(this->PrefixRegexStr, this->Prefixes); this->RegexFromList(this->SuffixRegexStr, this->Suffixes); @@ -311,8 +312,7 @@ void cmFindLibraryHelper::AddName(std::string const& name) entry.Raw = name; // Build a regular expression to match library names. - std::string regex = "^"; - regex += this->PrefixRegexStr; + std::string regex = cmStrCat('^', this->PrefixRegexStr); this->RegexFromLiteral(regex, name); regex += this->SuffixRegexStr; if (this->OpenBSD) { @@ -348,8 +348,7 @@ bool cmFindLibraryHelper::CheckDirectoryForName(std::string const& path, // one cannot tell just from the library name whether it is a static // library or an import library). if (name.TryRaw) { - this->TestPath = path; - this->TestPath += name.Raw; + this->TestPath = cmStrCat(path, name.Raw); if (cmSystemTools::FileExists(this->TestPath, true)) { this->BestPath = cmSystemTools::CollapseFullPath(this->TestPath); cmSystemTools::ConvertToUnixSlashes(this->BestPath); @@ -374,8 +373,7 @@ bool cmFindLibraryHelper::CheckDirectoryForName(std::string const& path, std::string const& testName = origName; #endif if (name.Regex.find(testName)) { - this->TestPath = path; - this->TestPath += origName; + this->TestPath = cmStrCat(path, origName); if (!cmSystemTools::FileIsDirectory(this->TestPath)) { // This is a matching file. Check if it is better than the // best name found so far. Earlier prefixes are preferred, @@ -465,9 +463,7 @@ std::string cmFindLibraryCommand::FindFrameworkLibraryNamesPerDir() // Search for all names in each search path. for (std::string const& d : this->SearchPaths) { for (std::string const& n : this->Names) { - fwPath = d; - fwPath += n; - fwPath += ".framework"; + fwPath = cmStrCat(d, n, ".framework"); if (cmSystemTools::FileIsDirectory(fwPath)) { return cmSystemTools::CollapseFullPath(fwPath); } @@ -484,9 +480,7 @@ std::string cmFindLibraryCommand::FindFrameworkLibraryDirsPerName() // Search for each name in all search paths. for (std::string const& n : this->Names) { for (std::string const& d : this->SearchPaths) { - fwPath = d; - fwPath += n; - fwPath += ".framework"; + fwPath = cmStrCat(d, n, ".framework"); if (cmSystemTools::FileIsDirectory(fwPath)) { return cmSystemTools::CollapseFullPath(fwPath); } diff --git a/Source/cmFindPackageCommand.cxx b/Source/cmFindPackageCommand.cxx index 04fbbad..9132760 100644 --- a/Source/cmFindPackageCommand.cxx +++ b/Source/cmFindPackageCommand.cxx @@ -194,7 +194,7 @@ bool cmFindPackageCommand::InitialPass(std::vector<std::string> const& args, // priority over the deprecated CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY if (const char* def = this->Makefile->GetDefinition("CMAKE_FIND_USE_PACKAGE_REGISTRY")) { - this->NoUserRegistry = !cmSystemTools::IsOn(def); + this->NoUserRegistry = !cmIsOn(def); } else if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY")) { this->NoUserRegistry = true; } @@ -408,19 +408,16 @@ bool cmFindPackageCommand::InitialPass(std::vector<std::string> const& args, if (this->Version.empty() || components.empty()) { // Check whether we are recursing inside "Find<name>.cmake" within // another find_package(<name>) call. - std::string mod = this->Name; - mod += "_FIND_MODULE"; + std::string mod = cmStrCat(this->Name, "_FIND_MODULE"); if (this->Makefile->IsOn(mod)) { if (this->Version.empty()) { // Get version information from the outer call if necessary. // Requested version string. - std::string ver = this->Name; - ver += "_FIND_VERSION"; + std::string ver = cmStrCat(this->Name, "_FIND_VERSION"); this->Version = this->Makefile->GetSafeDefinition(ver); // Whether an exact version is required. - std::string exact = this->Name; - exact += "_FIND_VERSION_EXACT"; + std::string exact = cmStrCat(this->Name, "_FIND_VERSION_EXACT"); this->VersionExact = this->Makefile->IsOn(exact); } if (components.empty()) { @@ -458,8 +455,8 @@ bool cmFindPackageCommand::InitialPass(std::vector<std::string> const& args, } } - std::string disableFindPackageVar = "CMAKE_DISABLE_FIND_PACKAGE_"; - disableFindPackageVar += this->Name; + std::string disableFindPackageVar = + cmStrCat("CMAKE_DISABLE_FIND_PACKAGE_", this->Name); if (this->Makefile->IsOn(disableFindPackageVar)) { if (this->Required) { std::ostringstream e; @@ -498,7 +495,7 @@ bool cmFindPackageCommand::InitialPass(std::vector<std::string> const& args, // NEW behavior is to honor the <pkg>_ROOT variables. std::string const rootVar = this->Name + "_ROOT"; if (const char* pkgRoot = this->Makefile->GetDefinition(rootVar)) { - cmSystemTools::ExpandListArgument(pkgRoot, rootPaths, false); + cmExpandList(pkgRoot, rootPaths, false); } cmSystemTools::GetPath(rootPaths, rootVar.c_str()); } break; @@ -517,7 +514,9 @@ bool cmFindPackageCommand::InitialPass(std::vector<std::string> const& args, loadedPackage = true; } else { // The package was not loaded. Report errors. - HandlePackageMode(HandlePackageModeType::Module); + if (HandlePackageMode(HandlePackageModeType::Module)) { + loadedPackage = true; + } } } } else { @@ -587,8 +586,7 @@ bool cmFindPackageCommand::FindPackageUsingModuleMode() bool cmFindPackageCommand::FindPackageUsingConfigMode() { - this->Variable = this->Name; - this->Variable += "_DIR"; + this->Variable = cmStrCat(this->Name, "_DIR"); // Add the default name. if (this->Names.empty()) { @@ -598,12 +596,10 @@ bool cmFindPackageCommand::FindPackageUsingConfigMode() // Add the default configs. if (this->Configs.empty()) { for (std::string const& n : this->Names) { - std::string config = n; - config += "Config.cmake"; + std::string config = cmStrCat(n, "Config.cmake"); this->Configs.push_back(config); - config = cmSystemTools::LowerCase(n); - config += "-config.cmake"; + config = cmStrCat(cmSystemTools::LowerCase(n), "-config.cmake"); this->Configs.push_back(std::move(config)); } } @@ -632,24 +628,21 @@ void cmFindPackageCommand::SetModuleVariables(const std::string& components) if (this->Quiet) { // Tell the module that is about to be read that it should find // quietly. - std::string quietly = this->Name; - quietly += "_FIND_QUIETLY"; + std::string quietly = cmStrCat(this->Name, "_FIND_QUIETLY"); this->AddFindDefinition(quietly, "1"); } if (this->Required) { // Tell the module that is about to be read that it should report // a fatal error if the package is not found. - std::string req = this->Name; - req += "_FIND_REQUIRED"; + std::string req = cmStrCat(this->Name, "_FIND_REQUIRED"); this->AddFindDefinition(req, "1"); } if (!this->Version.empty()) { // Tell the module that is about to be read what version of the // package has been requested. - std::string ver = this->Name; - ver += "_FIND_VERSION"; + std::string ver = cmStrCat(this->Name, "_FIND_VERSION"); this->AddFindDefinition(ver, this->Version.c_str()); char buf[64]; sprintf(buf, "%u", this->VersionMajor); @@ -664,8 +657,7 @@ void cmFindPackageCommand::SetModuleVariables(const std::string& components) this->AddFindDefinition(ver + "_COUNT", buf); // Tell the module whether an exact version has been requested. - std::string exact = this->Name; - exact += "_FIND_VERSION_EXACT"; + std::string exact = cmStrCat(this->Name, "_FIND_VERSION_EXACT"); this->AddFindDefinition(exact, this->VersionExact ? "1" : "0"); } } @@ -698,9 +690,7 @@ void cmFindPackageCommand::RestoreFindDefinitions() bool cmFindPackageCommand::FindModule(bool& found) { - std::string module = "Find"; - module += this->Name; - module += ".cmake"; + std::string module = cmStrCat("Find", this->Name, ".cmake"); bool system = false; std::string mfile = this->Makefile->GetModulesFile(module, system); if (!mfile.empty()) { @@ -729,8 +719,7 @@ bool cmFindPackageCommand::FindModule(bool& found) // Load the module we found, and set "<name>_FIND_MODULE" to true // while inside it. found = true; - std::string var = this->Name; - var += "_FIND_MODULE"; + std::string var = cmStrCat(this->Name, "_FIND_MODULE"); this->Makefile->AddDefinition(var, "1"); bool result = this->ReadListFile(mfile, DoPolicyScope); this->Makefile->RemoveDefinition(var); @@ -750,7 +739,7 @@ bool cmFindPackageCommand::HandlePackageMode( // Try to load the config file if the directory is known bool fileFound = false; if (this->UseConfigFiles) { - if (!cmSystemTools::IsOff(def)) { + if (!cmIsOff(def)) { // Get the directory from the variable value. std::string dir = def; cmSystemTools::ConvertToUnixSlashes(dir); @@ -770,7 +759,7 @@ bool cmFindPackageCommand::HandlePackageMode( } // Search for the config file if it is not already found. - if (cmSystemTools::IsOff(def) || !fileFound) { + if (cmIsOff(def) || !fileFound) { fileFound = this->FindConfig(); } @@ -783,10 +772,8 @@ bool cmFindPackageCommand::HandlePackageMode( } } - std::string foundVar = this->Name; - foundVar += "_FOUND"; - std::string notFoundMessageVar = this->Name; - notFoundMessageVar += "_NOT_FOUND_MESSAGE"; + std::string foundVar = cmStrCat(this->Name, "_FOUND"); + std::string notFoundMessageVar = cmStrCat(this->Name, "_NOT_FOUND_MESSAGE"); std::string notFoundMessage; // If the directory for the config file was found, try to read the file. @@ -876,9 +863,8 @@ bool cmFindPackageCommand::HandlePackageMode( } else { std::string requestedVersionString; if (!this->Version.empty()) { - requestedVersionString = " (requested version "; - requestedVersionString += this->Version; - requestedVersionString += ")"; + requestedVersionString = + cmStrCat(" (requested version ", this->Version, ')'); } if (this->UseConfigFiles) { @@ -960,18 +946,17 @@ bool cmFindPackageCommand::HandlePackageMode( this->Makefile->AddDefinition(foundVar, found ? "1" : "0"); // Set a variable naming the configuration file that was found. - std::string fileVar = this->Name; - fileVar += "_CONFIG"; + std::string fileVar = cmStrCat(this->Name, "_CONFIG"); if (found) { this->Makefile->AddDefinition(fileVar, this->FileFound); } else { this->Makefile->RemoveDefinition(fileVar); } - std::string consideredConfigsVar = this->Name; - consideredConfigsVar += "_CONSIDERED_CONFIGS"; - std::string consideredVersionsVar = this->Name; - consideredVersionsVar += "_CONSIDERED_VERSIONS"; + std::string consideredConfigsVar = + cmStrCat(this->Name, "_CONSIDERED_CONFIGS"); + std::string consideredVersionsVar = + cmStrCat(this->Name, "_CONSIDERED_VERSIONS"); std::string consideredConfigFiles; std::string consideredVersions; @@ -1033,9 +1018,8 @@ bool cmFindPackageCommand::FindConfig() init = this->Variable + "-NOTFOUND"; } std::string help = - "The directory containing a CMake configuration file for "; - help += this->Name; - help += "."; + cmStrCat("The directory containing a CMake configuration file for ", + this->Name, '.'); // We force the value since we do not get here if it was already set. this->Makefile->AddCacheDefinition(this->Variable, init.c_str(), help.c_str(), cmStateEnums::PATH, true); @@ -1082,9 +1066,7 @@ bool cmFindPackageCommand::ReadListFile(const std::string& f, if (this->Makefile->ReadDependentFile(f, noPolicyScope)) { return true; } - std::string e = "Error reading CMake code from \""; - e += f; - e += "\"."; + std::string e = cmStrCat("Error reading CMake code from \"", f, "\"."); this->SetError(e); return false; } @@ -1097,7 +1079,7 @@ void cmFindPackageCommand::AppendToFoundProperty(bool found) if (foundProp && *foundProp) { std::string tmp = foundProp; - cmSystemTools::ExpandListArgument(tmp, foundContents, false); + cmExpandList(tmp, foundContents, false); std::vector<std::string>::iterator nameIt = std::find(foundContents.begin(), foundContents.end(), this->Name); if (nameIt != foundContents.end()) { @@ -1111,7 +1093,7 @@ void cmFindPackageCommand::AppendToFoundProperty(bool found) if (notFoundProp && *notFoundProp) { std::string tmp = notFoundProp; - cmSystemTools::ExpandListArgument(tmp, notFoundContents, false); + cmExpandList(tmp, notFoundContents, false); std::vector<std::string>::iterator nameIt = std::find(notFoundContents.begin(), notFoundContents.end(), this->Name); if (nameIt != notFoundContents.end()) { @@ -1136,45 +1118,38 @@ void cmFindPackageCommand::AppendToFoundProperty(bool found) void cmFindPackageCommand::AppendSuccessInformation() { { - std::string transitivePropName = "_CMAKE_"; - transitivePropName += this->Name + "_TRANSITIVE_DEPENDENCY"; + std::string transitivePropName = + cmStrCat("_CMAKE_", this->Name, "_TRANSITIVE_DEPENDENCY"); this->Makefile->GetState()->SetGlobalProperty(transitivePropName, "False"); } - std::string found = this->Name; - found += "_FOUND"; + std::string found = cmStrCat(this->Name, "_FOUND"); std::string upperFound = cmSystemTools::UpperCase(found); const char* upperResult = this->Makefile->GetDefinition(upperFound); const char* result = this->Makefile->GetDefinition(found); - bool packageFound = - ((cmSystemTools::IsOn(result)) || (cmSystemTools::IsOn(upperResult))); + bool packageFound = ((cmIsOn(result)) || (cmIsOn(upperResult))); this->AppendToFoundProperty(packageFound); // Record whether the find was quiet or not, so this can be used // e.g. in FeatureSummary.cmake - std::string quietInfoPropName = "_CMAKE_"; - quietInfoPropName += this->Name; - quietInfoPropName += "_QUIET"; + std::string quietInfoPropName = cmStrCat("_CMAKE_", this->Name, "_QUIET"); this->Makefile->GetState()->SetGlobalProperty( quietInfoPropName, this->Quiet ? "TRUE" : "FALSE"); // set a global property to record the required version of this package - std::string versionInfoPropName = "_CMAKE_"; - versionInfoPropName += this->Name; - versionInfoPropName += "_REQUIRED_VERSION"; + std::string versionInfoPropName = + cmStrCat("_CMAKE_", this->Name, "_REQUIRED_VERSION"); std::string versionInfo; if (!this->Version.empty()) { - versionInfo = this->VersionExact ? "==" : ">="; - versionInfo += " "; - versionInfo += this->Version; + versionInfo = + cmStrCat(this->VersionExact ? "==" : ">=", ' ', this->Version); } this->Makefile->GetState()->SetGlobalProperty(versionInfoPropName, versionInfo.c_str()); if (this->Required) { - std::string requiredInfoPropName = "_CMAKE_"; - requiredInfoPropName += this->Name; - requiredInfoPropName += "_TYPE"; + std::string requiredInfoPropName = + cmStrCat("_CMAKE_", this->Name, "_TYPE"); this->Makefile->GetState()->SetGlobalProperty(requiredInfoPropName, "REQUIRED"); } @@ -1284,9 +1259,7 @@ void cmFindPackageCommand::FillPrefixesUserRegistry() char dir[B_PATH_NAME_LENGTH]; if (find_directory(B_USER_SETTINGS_DIRECTORY, -1, false, dir, sizeof(dir)) == B_OK) { - std::string fname = dir; - fname += "/cmake/packages/"; - fname += Name; + std::string fname = cmStrCat(dir, "/cmake/packages/", Name); this->LoadPackageRegistryDir(fname, this->LabeledPaths[PathLabel::UserRegistry]); } @@ -1427,9 +1400,7 @@ void cmFindPackageCommand::LoadPackageRegistryDir(std::string const& dir, std::string fname; for (unsigned long i = 0; i < files.GetNumberOfFiles(); ++i) { - fname = dir; - fname += "/"; - fname += files.GetFile(i); + fname = cmStrCat(dir, '/', files.GetFile(i)); if (!cmSystemTools::FileIsDirectory(fname)) { // Hold this file hostage until it behaves. @@ -1544,9 +1515,7 @@ bool cmFindPackageCommand::FindConfigFile(std::string const& dir, } for (std::string const& c : this->Configs) { - file = dir; - file += "/"; - file += c; + file = cmStrCat(dir, '/', c); if (this->DebugMode) { fprintf(stderr, "Checking file [%s]\n", file.c_str()); } @@ -1572,16 +1541,14 @@ bool cmFindPackageCommand::CheckVersion(std::string const& config_file) std::string version_file_base = config_file.substr(0, pos); // Look for foo-config-version.cmake - std::string version_file = version_file_base; - version_file += "-version.cmake"; + std::string version_file = cmStrCat(version_file_base, "-version.cmake"); if (!haveResult && cmSystemTools::FileExists(version_file, true)) { result = this->CheckVersionFile(version_file, version); haveResult = true; } // Look for fooConfigVersion.cmake - version_file = version_file_base; - version_file += "Version.cmake"; + version_file = cmStrCat(version_file_base, "Version.cmake"); if (!haveResult && cmSystemTools::FileExists(version_file, true)) { result = this->CheckVersionFile(version_file, version); haveResult = true; @@ -1689,8 +1656,7 @@ bool cmFindPackageCommand::CheckVersionFile(std::string const& version_file, void cmFindPackageCommand::StoreVersionFound() { // Store the whole version string. - std::string ver = this->Name; - ver += "_VERSION"; + std::string ver = cmStrCat(this->Name, "_VERSION"); if (this->VersionFound.empty()) { this->Makefile->RemoveDefinition(ver); } else { @@ -2038,8 +2004,7 @@ private: bool Search(std::string const& parent, cmFileList& lister) override { // Glob the set of matching files. - std::string expr = parent; - expr += this->Pattern; + std::string expr = cmStrCat(parent, this->Pattern); cmsys::Glob g; if (!g.FindFiles(expr)) { return false; diff --git a/Source/cmFindPathCommand.cxx b/Source/cmFindPathCommand.cxx index 38ff2ed..41f5e51 100644 --- a/Source/cmFindPathCommand.cxx +++ b/Source/cmFindPathCommand.cxx @@ -6,6 +6,7 @@ #include "cmMakefile.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" class cmExecutionStatus; @@ -88,12 +89,8 @@ std::string cmFindPathCommand::FindHeaderInFramework(std::string const& file, frameWorkName.clear(); } if (!frameWorkName.empty()) { - std::string fpath = dir; - fpath += frameWorkName; - fpath += ".framework"; - std::string intPath = fpath; - intPath += "/Headers/"; - intPath += fileName; + std::string fpath = cmStrCat(dir, frameWorkName, ".framework"); + std::string intPath = cmStrCat(fpath, "/Headers/", fileName); if (cmSystemTools::FileExists(intPath)) { if (this->IncludeFileInPath) { return intPath; @@ -104,9 +101,7 @@ std::string cmFindPathCommand::FindHeaderInFramework(std::string const& file, } // if it is not found yet or not a framework header, then do a glob search // for all frameworks in the directory: dir/*.framework/Headers/<file> - std::string glob = dir; - glob += "*.framework/Headers/"; - glob += file; + std::string glob = cmStrCat(dir, "*.framework/Headers/", file); cmsys::Glob globIt; globIt.FindFiles(glob); std::vector<std::string> files = globIt.GetFiles(); @@ -126,8 +121,7 @@ std::string cmFindPathCommand::FindNormalHeader() std::string tryPath; for (std::string const& n : this->Names) { for (std::string const& sp : this->SearchPaths) { - tryPath = sp; - tryPath += n; + tryPath = cmStrCat(sp, n); if (cmSystemTools::FileExists(tryPath)) { if (this->IncludeFileInPath) { return tryPath; diff --git a/Source/cmFindProgramCommand.cxx b/Source/cmFindProgramCommand.cxx index 8fcf1ac..a2db65c 100644 --- a/Source/cmFindProgramCommand.cxx +++ b/Source/cmFindProgramCommand.cxx @@ -75,8 +75,7 @@ struct cmFindProgramHelper if (!ext.empty() && cmHasSuffix(name, ext)) { continue; } - this->TestNameExt = name; - this->TestNameExt += ext; + this->TestNameExt = cmStrCat(name, ext); this->TestPath = cmSystemTools::CollapseFullPath(this->TestNameExt, path); diff --git a/Source/cmForEachCommand.cxx b/Source/cmForEachCommand.cxx index 06dce2c..f0633aa 100644 --- a/Source/cmForEachCommand.cxx +++ b/Source/cmForEachCommand.cxx @@ -8,16 +8,44 @@ #include <utility> #include "cm_memory.hxx" +#include "cm_static_string_view.hxx" +#include "cm_string_view.hxx" #include "cmExecutionStatus.h" +#include "cmFunctionBlocker.h" +#include "cmListFileCache.h" #include "cmMakefile.h" #include "cmMessageType.h" #include "cmRange.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" +namespace { +bool HandleInMode(std::vector<std::string> const& args, cmMakefile& makefile); + +class cmForEachFunctionBlocker : public cmFunctionBlocker +{ +public: + cmForEachFunctionBlocker(cmMakefile* mf); + ~cmForEachFunctionBlocker() override; + + cm::string_view StartCommandName() const override { return "foreach"_s; } + cm::string_view EndCommandName() const override { return "endforeach"_s; } + + bool ArgumentsMatch(cmListFileFunction const& lff, + cmMakefile& mf) const override; + + bool Replay(std::vector<cmListFileFunction> functions, + cmExecutionStatus& inStatus) override; + + std::vector<std::string> Args; + +private: + cmMakefile* Makefile; +}; + cmForEachFunctionBlocker::cmForEachFunctionBlocker(cmMakefile* mf) : Makefile(mf) - , Depth(0) { this->Makefile->PushLoopBlock(); } @@ -27,102 +55,71 @@ cmForEachFunctionBlocker::~cmForEachFunctionBlocker() this->Makefile->PopLoopBlock(); } -bool cmForEachFunctionBlocker::IsFunctionBlocked(const cmListFileFunction& lff, - cmMakefile& mf, - cmExecutionStatus& inStatus) +bool cmForEachFunctionBlocker::ArgumentsMatch(cmListFileFunction const& lff, + cmMakefile& mf) const { - if (lff.Name.Lower == "foreach") { - // record the number of nested foreach commands - this->Depth++; - } else if (lff.Name.Lower == "endforeach") { - // if this is the endofreach for this statement - if (!this->Depth) { - // Remove the function blocker for this scope or bail. - std::unique_ptr<cmFunctionBlocker> fb( - mf.RemoveFunctionBlocker(this, lff)); - if (!fb) { - return false; - } + std::vector<std::string> expandedArguments; + mf.ExpandArguments(lff.Arguments, expandedArguments); + return expandedArguments.empty() || expandedArguments[0] == this->Args[0]; +} - // at end of for each execute recorded commands - // store the old value - std::string oldDef; - if (mf.GetDefinition(this->Args[0])) { - oldDef = mf.GetDefinition(this->Args[0]); - } +bool cmForEachFunctionBlocker::Replay( + std::vector<cmListFileFunction> functions, cmExecutionStatus& inStatus) +{ + cmMakefile& mf = inStatus.GetMakefile(); + // at end of for each execute recorded commands + // store the old value + std::string oldDef; + if (mf.GetDefinition(this->Args[0])) { + oldDef = mf.GetDefinition(this->Args[0]); + } - for (std::string const& arg : cmMakeRange(this->Args).advance(1)) { - // set the variable to the loop value - mf.AddDefinition(this->Args[0], arg); - // Invoke all the functions that were collected in the block. - cmExecutionStatus status(mf); - for (cmListFileFunction const& func : this->Functions) { - status.Clear(); - mf.ExecuteCommand(func, status); - if (status.GetReturnInvoked()) { - inStatus.SetReturnInvoked(); - // restore the variable to its prior value - mf.AddDefinition(this->Args[0], oldDef); - return true; - } - if (status.GetBreakInvoked()) { - // restore the variable to its prior value - mf.AddDefinition(this->Args[0], oldDef); - return true; - } - if (status.GetContinueInvoked()) { - break; - } - if (cmSystemTools::GetFatalErrorOccured()) { - return true; - } - } + for (std::string const& arg : cmMakeRange(this->Args).advance(1)) { + // set the variable to the loop value + mf.AddDefinition(this->Args[0], arg); + // Invoke all the functions that were collected in the block. + for (cmListFileFunction const& func : functions) { + cmExecutionStatus status(mf); + mf.ExecuteCommand(func, status); + if (status.GetReturnInvoked()) { + inStatus.SetReturnInvoked(); + // restore the variable to its prior value + mf.AddDefinition(this->Args[0], oldDef); + return true; + } + if (status.GetBreakInvoked()) { + // restore the variable to its prior value + mf.AddDefinition(this->Args[0], oldDef); + return true; + } + if (status.GetContinueInvoked()) { + break; + } + if (cmSystemTools::GetFatalErrorOccured()) { + return true; } - - // restore the variable to its prior value - mf.AddDefinition(this->Args[0], oldDef); - return true; } - // close out a nested foreach - this->Depth--; } - // record the command - this->Functions.push_back(lff); - - // always return true + // restore the variable to its prior value + mf.AddDefinition(this->Args[0], oldDef); return true; } - -bool cmForEachFunctionBlocker::ShouldRemove(const cmListFileFunction& lff, - cmMakefile& mf) -{ - if (lff.Name.Lower == "endforeach") { - std::vector<std::string> expandedArguments; - mf.ExpandArguments(lff.Arguments, expandedArguments); - // if the endforeach has arguments then make sure - // they match the begin foreach arguments - if ((expandedArguments.empty() || - (expandedArguments[0] == this->Args[0]))) { - return true; - } - } - return false; } -bool cmForEachCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus&) +bool cmForEachCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.empty()) { - this->SetError("called with incorrect number of arguments"); + status.SetError("called with incorrect number of arguments"); return false; } if (args.size() > 1 && args[1] == "IN") { - return this->HandleInMode(args); + return HandleInMode(args, status.GetMakefile()); } // create a function blocker - auto fb = cm::make_unique<cmForEachFunctionBlocker>(this->Makefile); + auto fb = cm::make_unique<cmForEachFunctionBlocker>(&status.GetMakefile()); if (args.size() > 1) { if (args[1] == "RANGE") { int start = 0; @@ -152,7 +149,7 @@ bool cmForEachCommand::InitialPass(std::vector<std::string> const& args, std::ostringstream str; str << "called with incorrect range specification: start "; str << start << ", stop " << stop << ", step " << step; - this->SetError(str.str()); + status.SetError(str.str()); return false; } std::vector<std::string> range; @@ -176,14 +173,15 @@ bool cmForEachCommand::InitialPass(std::vector<std::string> const& args, } else { fb->Args = args; } - this->Makefile->AddFunctionBlocker(std::move(fb)); + status.GetMakefile().AddFunctionBlocker(std::move(fb)); return true; } -bool cmForEachCommand::HandleInMode(std::vector<std::string> const& args) +namespace { +bool HandleInMode(std::vector<std::string> const& args, cmMakefile& makefile) { - auto fb = cm::make_unique<cmForEachFunctionBlocker>(this->Makefile); + auto fb = cm::make_unique<cmForEachFunctionBlocker>(&makefile); fb->Args.push_back(args[0]); enum Doing @@ -201,20 +199,21 @@ bool cmForEachCommand::HandleInMode(std::vector<std::string> const& args) } else if (args[i] == "ITEMS") { doing = DoingItems; } else if (doing == DoingLists) { - const char* value = this->Makefile->GetDefinition(args[i]); + const char* value = makefile.GetDefinition(args[i]); if (value && *value) { - cmSystemTools::ExpandListArgument(value, fb->Args, true); + cmExpandList(value, fb->Args, true); } } else { std::ostringstream e; e << "Unknown argument:\n" << " " << args[i] << "\n"; - this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str()); + makefile.IssueMessage(MessageType::FATAL_ERROR, e.str()); return true; } } - this->Makefile->AddFunctionBlocker(std::move(fb)); + makefile.AddFunctionBlocker(std::move(fb)); return true; } +} diff --git a/Source/cmForEachCommand.h b/Source/cmForEachCommand.h index cd112b8..1feb965 100644 --- a/Source/cmForEachCommand.h +++ b/Source/cmForEachCommand.h @@ -8,53 +8,9 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" -#include "cmFunctionBlocker.h" -#include "cmListFileCache.h" - class cmExecutionStatus; -class cmMakefile; - -class cmForEachFunctionBlocker : public cmFunctionBlocker -{ -public: - cmForEachFunctionBlocker(cmMakefile* mf); - ~cmForEachFunctionBlocker() override; - bool IsFunctionBlocked(const cmListFileFunction& lff, cmMakefile& mf, - cmExecutionStatus&) override; - bool ShouldRemove(const cmListFileFunction& lff, cmMakefile& mf) override; - - std::vector<std::string> Args; - std::vector<cmListFileFunction> Functions; - -private: - cmMakefile* Makefile; - int Depth; -}; /// Starts foreach() ... endforeach() block -class cmForEachCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmForEachCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; - -private: - bool HandleInMode(std::vector<std::string> const& args); -}; - +bool cmForEachCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmFortranParserImpl.cxx b/Source/cmFortranParserImpl.cxx index e8b1da8..ad377de 100644 --- a/Source/cmFortranParserImpl.cxx +++ b/Source/cmFortranParserImpl.cxx @@ -1,6 +1,8 @@ /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmFortranParser.h" + +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include <assert.h> @@ -22,9 +24,7 @@ bool cmFortranParser_s::FindIncludeFile(const char* dir, } // Check for the file in the directory containing the including // file. - std::string fullName = dir; - fullName += "/"; - fullName += includeName; + std::string fullName = cmStrCat(dir, '/', includeName); if (cmSystemTools::FileExists(fullName, true)) { fileName = fullName; return true; @@ -32,9 +32,7 @@ bool cmFortranParser_s::FindIncludeFile(const char* dir, // Search the include path for the file. for (std::string const& i : this->IncludePath) { - fullName = i; - fullName += "/"; - fullName += includeName; + fullName = cmStrCat(i, '/', includeName); if (cmSystemTools::FileExists(fullName, true)) { fileName = fullName; return true; diff --git a/Source/cmFunctionBlocker.cxx b/Source/cmFunctionBlocker.cxx new file mode 100644 index 0000000..5778a71 --- /dev/null +++ b/Source/cmFunctionBlocker.cxx @@ -0,0 +1,46 @@ +/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying + file Copyright.txt or https://cmake.org/licensing for details. */ +#include "cmFunctionBlocker.h" + +#include <cassert> +#include <sstream> +#include <utility> + +#include "cmExecutionStatus.h" +#include "cmMakefile.h" +#include "cmMessageType.h" + +bool cmFunctionBlocker::IsFunctionBlocked(const cmListFileFunction& lff, + cmExecutionStatus& status) +{ + if (lff.Name.Lower == this->StartCommandName()) { + this->ScopeDepth++; + } else if (lff.Name.Lower == this->EndCommandName()) { + this->ScopeDepth--; + if (this->ScopeDepth == 0U) { + cmMakefile& mf = status.GetMakefile(); + auto self = mf.RemoveFunctionBlocker(); + assert(self.get() == this); + + if (!this->ArgumentsMatch(lff, mf)) { + cmListFileContext const& lfc = this->GetStartingContext(); + cmListFileContext closingContext = + cmListFileContext::FromCommandContext(lff, lfc.FilePath); + std::ostringstream e; + /* clang-format off */ + e << "A logical block opening on the line\n" + << " " << lfc << "\n" + << "closes on the line\n" + << " " << closingContext << "\n" + << "with mis-matching arguments."; + /* clang-format on */ + mf.IssueMessage(MessageType::AUTHOR_WARNING, e.str()); + } + + return this->Replay(std::move(this->Functions), status); + } + } + + this->Functions.push_back(lff); + return true; +} diff --git a/Source/cmFunctionBlocker.h b/Source/cmFunctionBlocker.h index cd6b05d..87bdccd 100644 --- a/Source/cmFunctionBlocker.h +++ b/Source/cmFunctionBlocker.h @@ -3,6 +3,12 @@ #ifndef cmFunctionBlocker_h #define cmFunctionBlocker_h +#include "cmConfigure.h" // IWYU pragma: keep + +#include <vector> + +#include "cm_string_view.hxx" + #include "cmListFileCache.h" class cmExecutionStatus; @@ -14,17 +20,8 @@ public: /** * should a function be blocked */ - virtual bool IsFunctionBlocked(const cmListFileFunction& lff, cmMakefile& mf, - cmExecutionStatus& status) = 0; - - /** - * should this function blocker be removed, useful when one function adds a - * blocker and another must remove it - */ - virtual bool ShouldRemove(const cmListFileFunction&, cmMakefile&) - { - return false; - } + bool IsFunctionBlocked(cmListFileFunction const& lff, + cmExecutionStatus& status); virtual ~cmFunctionBlocker() = default; @@ -39,7 +36,19 @@ public: } private: + virtual cm::string_view StartCommandName() const = 0; + virtual cm::string_view EndCommandName() const = 0; + + virtual bool ArgumentsMatch(cmListFileFunction const& lff, + cmMakefile& mf) const = 0; + + virtual bool Replay(std::vector<cmListFileFunction> functions, + cmExecutionStatus& status) = 0; + +private: cmListFileContext StartingContext; + std::vector<cmListFileFunction> Functions; + unsigned int ScopeDepth = 1; }; #endif diff --git a/Source/cmFunctionCommand.cxx b/Source/cmFunctionCommand.cxx index 2809cf7..e8f03d7 100644 --- a/Source/cmFunctionCommand.cxx +++ b/Source/cmFunctionCommand.cxx @@ -5,14 +5,21 @@ #include <sstream> #include <utility> +#include "cm_memory.hxx" +#include "cm_static_string_view.hxx" +#include "cm_string_view.hxx" + #include "cmAlgorithms.h" #include "cmExecutionStatus.h" +#include "cmFunctionBlocker.h" +#include "cmListFileCache.h" #include "cmMakefile.h" #include "cmPolicies.h" #include "cmRange.h" #include "cmState.h" #include "cmStringAlgorithms.h" +namespace { // define the class for function commands class cmFunctionHelperCommand { @@ -29,6 +36,7 @@ public: cmPolicies::PolicyMap Policies; std::string FilePath; }; +} bool cmFunctionHelperCommand::operator()( std::vector<cmListFileArgument> const& args, @@ -43,9 +51,9 @@ bool cmFunctionHelperCommand::operator()( // make sure the number of arguments passed is at least the number // required by the signature if (expandedArgs.size() < this->Args.size() - 1) { - std::string errorMsg = - "Function invoked with incorrect arguments for function named: "; - errorMsg += this->Args[0]; + std::string errorMsg = cmStrCat( + "Function invoked with incorrect arguments for function named: ", + this->Args[0]); inStatus.SetError(errorMsg); return false; } @@ -102,60 +110,49 @@ bool cmFunctionHelperCommand::operator()( return true; } -bool cmFunctionFunctionBlocker::IsFunctionBlocked( - const cmListFileFunction& lff, cmMakefile& mf, cmExecutionStatus&) +class cmFunctionFunctionBlocker : public cmFunctionBlocker { - // record commands until we hit the ENDFUNCTION - // at the ENDFUNCTION call we shift gears and start looking for invocations - if (lff.Name.Lower == "function") { - this->Depth++; - } else if (lff.Name.Lower == "endfunction") { - // if this is the endfunction for this function then execute - if (!this->Depth) { - // create a new command and add it to cmake - cmFunctionHelperCommand f; - f.Args = this->Args; - f.Functions = this->Functions; - f.FilePath = this->GetStartingContext().FilePath; - mf.RecordPolicies(f.Policies); - mf.GetState()->AddScriptedCommand(this->Args[0], std::move(f)); - // remove the function blocker now that the function is defined - mf.RemoveFunctionBlocker(this, lff); - return true; - } - // decrement for each nested function that ends - this->Depth--; - } +public: + cm::string_view StartCommandName() const override { return "function"_s; } + cm::string_view EndCommandName() const override { return "endfunction"_s; } - // if it wasn't an endfunction and we are not executing then we must be - // recording - this->Functions.push_back(lff); - return true; -} + bool ArgumentsMatch(cmListFileFunction const&, + cmMakefile& mf) const override; + + bool Replay(std::vector<cmListFileFunction> functions, + cmExecutionStatus& status) override; -bool cmFunctionFunctionBlocker::ShouldRemove(const cmListFileFunction& lff, - cmMakefile& mf) + std::vector<std::string> Args; +}; + +bool cmFunctionFunctionBlocker::ArgumentsMatch(cmListFileFunction const& lff, + cmMakefile& mf) const { - if (lff.Name.Lower == "endfunction") { - std::vector<std::string> expandedArguments; - mf.ExpandArguments(lff.Arguments, expandedArguments, - this->GetStartingContext().FilePath.c_str()); - // if the endfunction has arguments then make sure - // they match the ones in the opening function command - if ((expandedArguments.empty() || - (expandedArguments[0] == this->Args[0]))) { - return true; - } - } + std::vector<std::string> expandedArguments; + mf.ExpandArguments(lff.Arguments, expandedArguments, + this->GetStartingContext().FilePath.c_str()); + return expandedArguments.empty() || expandedArguments[0] == this->Args[0]; +} - return false; +bool cmFunctionFunctionBlocker::Replay( + std::vector<cmListFileFunction> functions, cmExecutionStatus& status) +{ + cmMakefile& mf = status.GetMakefile(); + // create a new command and add it to cmake + cmFunctionHelperCommand f; + f.Args = this->Args; + f.Functions = std::move(functions); + f.FilePath = this->GetStartingContext().FilePath; + mf.RecordPolicies(f.Policies); + mf.GetState()->AddScriptedCommand(this->Args[0], std::move(f)); + return true; } -bool cmFunctionCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus&) +bool cmFunctionCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.empty()) { - this->SetError("called with incorrect number of arguments"); + status.SetError("called with incorrect number of arguments"); return false; } @@ -163,7 +160,7 @@ bool cmFunctionCommand::InitialPass(std::vector<std::string> const& args, { auto fb = cm::make_unique<cmFunctionFunctionBlocker>(); cmAppend(fb->Args, args); - this->Makefile->AddFunctionBlocker(std::move(fb)); + status.GetMakefile().AddFunctionBlocker(std::move(fb)); } return true; } diff --git a/Source/cmFunctionCommand.h b/Source/cmFunctionCommand.h index 449a180..d6b549c 100644 --- a/Source/cmFunctionCommand.h +++ b/Source/cmFunctionCommand.h @@ -8,45 +8,10 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" -#include "cmFunctionBlocker.h" -#include "cmListFileCache.h" - class cmExecutionStatus; -class cmMakefile; - -class cmFunctionFunctionBlocker : public cmFunctionBlocker -{ -public: - bool IsFunctionBlocked(const cmListFileFunction&, cmMakefile& mf, - cmExecutionStatus&) override; - bool ShouldRemove(const cmListFileFunction&, cmMakefile& mf) override; - - std::vector<std::string> Args; - std::vector<cmListFileFunction> Functions; - int Depth = 0; -}; /// Starts function() ... endfunction() block -class cmFunctionCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmFunctionCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; -}; +bool cmFunctionCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmGeneratedFileStream.cxx b/Source/cmGeneratedFileStream.cxx index 2f47788..7475e9f 100644 --- a/Source/cmGeneratedFileStream.cxx +++ b/Source/cmGeneratedFileStream.cxx @@ -6,14 +6,14 @@ #include "cmSystemTools.h" -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) # include "cm_codecvt.hxx" # include "cm_zlib.h" #endif cmGeneratedFileStream::cmGeneratedFileStream(Encoding encoding) { -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP if (encoding != codecvt::None) { imbue(std::locale(getloc(), new codecvt(encoding))); } @@ -32,7 +32,7 @@ cmGeneratedFileStream::cmGeneratedFileStream(std::string const& name, cmSystemTools::Error("Cannot open file for write: " + this->TempName); cmSystemTools::ReportLastSystemError(""); } -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP if (encoding != codecvt::None) { imbue(std::locale(getloc(), new codecvt(encoding))); } @@ -169,7 +169,7 @@ bool cmGeneratedFileStreamBase::Close() return replaced; } -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP int cmGeneratedFileStreamBase::CompressFile(std::string const& oldname, std::string const& newname) { diff --git a/Source/cmGeneratorExpression.cxx b/Source/cmGeneratorExpression.cxx index 4d3a005..133a72b 100644 --- a/Source/cmGeneratorExpression.cxx +++ b/Source/cmGeneratorExpression.cxx @@ -13,6 +13,7 @@ #include "cmGeneratorExpressionEvaluator.h" #include "cmGeneratorExpressionLexer.h" #include "cmGeneratorExpressionParser.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" cmGeneratorExpression::cmGeneratorExpression(cmListFileBacktrace backtrace) @@ -294,7 +295,7 @@ void cmGeneratorExpression::Split(const std::string& input, preGenex = input.substr(startPos + 1, pos - startPos - 1); } if (!part.empty()) { - cmSystemTools::ExpandListArgument(part, output); + cmExpandList(part, output); } } pos += 2; @@ -327,7 +328,7 @@ void cmGeneratorExpression::Split(const std::string& input, lastPos = pos; } if (lastPos < input.size()) { - cmSystemTools::ExpandListArgument(input.substr(lastPos), output); + cmExpandList(input.substr(lastPos), output); } } diff --git a/Source/cmGeneratorExpressionNode.cxx b/Source/cmGeneratorExpressionNode.cxx index 14dc7b8..9a4e13e 100644 --- a/Source/cmGeneratorExpressionNode.cxx +++ b/Source/cmGeneratorExpressionNode.cxx @@ -19,11 +19,11 @@ #include "cmState.h" #include "cmStateSnapshot.h" #include "cmStateTypes.h" +#include "cmString.hxx" #include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmTarget.h" #include "cm_static_string_view.hxx" -#include "cm_string_view.hxx" #include "cmake.h" #include "cmsys/RegularExpression.hxx" @@ -169,7 +169,7 @@ static const struct BoolNode : public cmGeneratorExpressionNode const GeneratorExpressionContent* /*content*/, cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override { - return !cmSystemTools::IsOff(parameters.front()) ? "1" : "0"; + return !cmIsOff(parameters.front()) ? "1" : "0"; } } boolNode; @@ -275,17 +275,18 @@ static const struct InListNode : public cmGeneratorExpressionNode const GeneratorExpressionContent* /*content*/, cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override { - std::vector<std::string> values, checkValues; + std::vector<std::string> values; + std::vector<std::string> checkValues; bool check = false; switch (context->LG->GetPolicyStatus(cmPolicies::CMP0085)) { case cmPolicies::WARN: if (parameters.front().empty()) { check = true; - cmSystemTools::ExpandListArgument(parameters[1], checkValues, true); + cmExpandList(parameters[1], checkValues, true); } CM_FALLTHROUGH; case cmPolicies::OLD: - cmSystemTools::ExpandListArgument(parameters[1], values); + cmExpandList(parameters[1], values); if (check && values != checkValues) { std::ostringstream e; e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0085) @@ -302,14 +303,11 @@ static const struct InListNode : public cmGeneratorExpressionNode case cmPolicies::REQUIRED_IF_USED: case cmPolicies::REQUIRED_ALWAYS: case cmPolicies::NEW: - cmSystemTools::ExpandListArgument(parameters[1], values, true); + cmExpandList(parameters[1], values, true); break; } - return std::find(values.cbegin(), values.cend(), parameters.front()) == - values.cend() - ? "0" - : "1"; + return cmContains(values, parameters.front()) ? "1" : "0"; } } inListNode; @@ -347,8 +345,9 @@ static const struct FilterNode : public cmGeneratorExpressionNode return {}; } - std::vector<std::string> values, result; - cmSystemTools::ExpandListArgument(parameters.front(), values, true); + std::vector<std::string> values; + std::vector<std::string> result; + cmExpandList(parameters.front(), values, true); std::copy_if(values.cbegin(), values.cend(), std::back_inserter(result), [&re, exclude](std::string const& input) { @@ -377,7 +376,7 @@ static const struct RemoveDuplicatesNode : public cmGeneratorExpressionNode } std::vector<std::string> values; - cmSystemTools::ExpandListArgument(parameters.front(), values, true); + cmExpandList(parameters.front(), values, true); auto valuesEnd = cmRemoveDuplicates(values); auto valuesBegin = values.cbegin(); @@ -910,15 +909,13 @@ static const struct ConfigurationTestNode : public cmGeneratorExpressionNode // for this (possibly mapped) config. // Check if there is a proper config mapping for the tested config. std::vector<std::string> mappedConfigs; - std::string mapProp = "MAP_IMPORTED_CONFIG_"; - mapProp += cmSystemTools::UpperCase(context->Config); + std::string mapProp = cmStrCat( + "MAP_IMPORTED_CONFIG_", cmSystemTools::UpperCase(context->Config)); if (const char* mapValue = context->CurrentTarget->GetProperty(mapProp)) { - cmSystemTools::ExpandListArgument(cmSystemTools::UpperCase(mapValue), - mappedConfigs); - return std::find(mappedConfigs.begin(), mappedConfigs.end(), - cmSystemTools::UpperCase(parameters.front())) != - mappedConfigs.end() + cmExpandList(cmSystemTools::UpperCase(mapValue), mappedConfigs); + return cmContains(mappedConfigs, + cmSystemTools::UpperCase(parameters.front())) ? "1" : "0"; } @@ -943,7 +940,7 @@ static const struct JoinNode : public cmGeneratorExpressionNode cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override { std::vector<std::string> list; - cmSystemTools::ExpandListArgument(parameters.front(), list); + cmExpandList(parameters.front(), list); return cmJoin(list, parameters[1]); } } joinNode; @@ -1110,7 +1107,8 @@ static const struct TargetPropertyNode : public cmGeneratorExpressionNode static cmsys::RegularExpression propertyNameValidator("^[A-Za-z0-9_]+$"); cmGeneratorTarget const* target = nullptr; - std::string targetName, propertyName; + std::string targetName; + std::string propertyName; if (parameters.size() == 2) { targetName = parameters[0]; @@ -1421,7 +1419,7 @@ static const struct TargetObjectsNode : public cmGeneratorExpressionNode const char* imp = nullptr; std::string suffix; if (gt->Target->GetMappedConfig(context->Config, &loc, &imp, suffix)) { - cmSystemTools::ExpandListArgument(loc, objects); + cmExpandList(loc, objects); } context->HadContextSensitiveCondition = true; } else { @@ -1441,7 +1439,7 @@ static const struct TargetObjectsNode : public cmGeneratorExpressionNode } for (std::string& o : objects) { - o = obj_dir + o; + o = cmStrCat(obj_dir, o); } } @@ -1499,8 +1497,7 @@ static const struct CompileFeaturesNode : public cmGeneratorExpressionNode reportError(context, content->GetOriginalExpression(), error); return std::string(); } - cmSystemTools::ExpandListArgument(featuresKnown, - availableFeatures[lang]); + cmExpandList(featuresKnown, availableFeatures[lang]); } } @@ -1512,8 +1509,7 @@ static const struct CompileFeaturesNode : public cmGeneratorExpressionNode const char* standardDefault = context->LG->GetMakefile()->GetDefinition( "CMAKE_" + lit.first + "_STANDARD_DEFAULT"); for (std::string const& it : lit.second) { - if (std::find(langAvailable.begin(), langAvailable.end(), it) == - langAvailable.end()) { + if (!cmContains(langAvailable, it)) { return "0"; } if (standardDefault && !*standardDefault) { @@ -1699,9 +1695,8 @@ struct TargetFilesystemArtifactResultCreator<ArtifactSonameTag> "SHARED libraries."); return std::string(); } - std::string result = target->GetDirectory(context->Config); - result += "/"; - result += target->GetSOName(context->Config); + std::string result = cmStrCat(target->GetDirectory(context->Config), '/', + target->GetSOName(context->Config)); return result; } }; @@ -1740,9 +1735,8 @@ struct TargetFilesystemArtifactResultCreator<ArtifactPdbTag> return std::string(); } - std::string result = target->GetPDBDirectory(context->Config); - result += "/"; - result += target->GetPDBName(context->Config); + std::string result = cmStrCat(target->GetPDBDirectory(context->Config), + '/', target->GetPDBName(context->Config)); return result; } }; @@ -2216,7 +2210,7 @@ static const struct ShellPathNode : public cmGeneratorExpressionNode cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override { std::vector<std::string> listIn; - cmSystemTools::ExpandListArgument(parameters.front(), listIn); + cmExpandList(parameters.front(), listIn); if (listIn.empty()) { reportError(context, content->GetOriginalExpression(), "\"\" is not an absolute path."); diff --git a/Source/cmGeneratorTarget.cxx b/Source/cmGeneratorTarget.cxx index 7340bc2..2e9a11a 100644 --- a/Source/cmGeneratorTarget.cxx +++ b/Source/cmGeneratorTarget.cxx @@ -39,6 +39,7 @@ #include "cmTarget.h" #include "cmTargetLinkLibraryType.h" #include "cmTargetPropertyComputer.h" +#include "cm_string_view.hxx" #include "cmake.h" class cmMessenger; @@ -241,10 +242,9 @@ EvaluatedTargetPropertyEntry EvaluateTargetPropertyEntry( cmGeneratorTarget::TargetPropertyEntry* entry) { EvaluatedTargetPropertyEntry ee(entry->LinkImplItem, entry->GetBacktrace()); - cmSystemTools::ExpandListArgument( - entry->Evaluate(thisTarget->GetLocalGenerator(), config, false, thisTarget, - dagChecker, lang), - ee.Values); + cmExpandList(entry->Evaluate(thisTarget->GetLocalGenerator(), config, false, + thisTarget, dagChecker, lang), + ee.Values); if (entry->GetHadContextSensitiveCondition()) { ee.ContextDependent = true; } @@ -527,7 +527,9 @@ std::string cmGeneratorTarget::GetFilePrefix( return prefix ? prefix : std::string(); } - std::string prefix, suffix, base; + std::string prefix; + std::string suffix; + std::string base; this->GetFullNameInternal(config, artifact, prefix, base, suffix); return prefix; } @@ -540,7 +542,9 @@ std::string cmGeneratorTarget::GetFileSuffix( return suffix ? suffix : std::string(); } - std::string prefix, suffix, base; + std::string prefix; + std::string suffix; + std::string base; this->GetFullNameInternal(config, artifact, prefix, base, suffix); return suffix; } @@ -549,8 +553,8 @@ std::string cmGeneratorTarget::GetFilePostfix(const std::string& config) const { const char* postfix = nullptr; if (!config.empty()) { - std::string configProp = cmSystemTools::UpperCase(config); - configProp += "_POSTFIX"; + std::string configProp = + cmStrCat(cmSystemTools::UpperCase(config), "_POSTFIX"); postfix = this->GetProperty(configProp); // Mac application bundles and frameworks have no postfix. if (!this->IsImported() && postfix && @@ -723,10 +727,9 @@ void handleSystemIncludesDep(cmLocalGenerator* lg, if (const char* dirs = depTgt->GetProperty("INTERFACE_SYSTEM_INCLUDE_DIRECTORIES")) { cmGeneratorExpression ge; - cmSystemTools::ExpandListArgument( - ge.Parse(dirs)->Evaluate(lg, config, false, headTarget, depTgt, - dagChecker, language), - result); + cmExpandList(ge.Parse(dirs)->Evaluate(lg, config, false, headTarget, + depTgt, dagChecker, language), + result); } if (!depTgt->IsImported() || excludeImported) { return; @@ -735,10 +738,9 @@ void handleSystemIncludesDep(cmLocalGenerator* lg, if (const char* dirs = depTgt->GetProperty("INTERFACE_INCLUDE_DIRECTORIES")) { cmGeneratorExpression ge; - cmSystemTools::ExpandListArgument( - ge.Parse(dirs)->Evaluate(lg, config, false, headTarget, depTgt, - dagChecker, language), - result); + cmExpandList(ge.Parse(dirs)->Evaluate(lg, config, false, headTarget, + depTgt, dagChecker, language), + result); } } } @@ -792,9 +794,8 @@ const char* cmGeneratorTarget::GetFeature(const std::string& feature, const std::string& config) const { if (!config.empty()) { - std::string featureConfig = feature; - featureConfig += "_"; - featureConfig += cmSystemTools::UpperCase(config); + std::string featureConfig = + cmStrCat(feature, '_', cmSystemTools::UpperCase(config)); if (const char* value = this->GetProperty(featureConfig)) { return value; } @@ -828,7 +829,7 @@ bool cmGeneratorTarget::IsIPOEnabled(std::string const& lang, std::string const& config) const { const char* feature = "INTERPROCEDURAL_OPTIMIZATION"; - const bool result = cmSystemTools::IsOn(this->GetFeature(feature, config)); + const bool result = cmIsOn(this->GetFeature(feature, config)); if (!result) { // 'INTERPROCEDURAL_OPTIMIZATION' is off, no need to check policies @@ -1114,10 +1115,9 @@ bool cmGeneratorTarget::IsSystemIncludeDirectory( std::vector<std::string> result; for (std::string const& it : this->Target->GetSystemIncludeDirectories()) { cmGeneratorExpression ge; - cmSystemTools::ExpandListArgument( - ge.Parse(it)->Evaluate(this->LocalGenerator, config, false, this, - &dagChecker, language), - result); + cmExpandList(ge.Parse(it)->Evaluate(this->LocalGenerator, config, false, + this, &dagChecker, language), + result); } std::vector<cmGeneratorTarget const*> const& deps = @@ -1282,7 +1282,7 @@ void AddInterfaceEntries(cmGeneratorTarget const* headTarget, cmGeneratorExpressionContext context( headTarget->GetLocalGenerator(), config, false, headTarget, headTarget, true, lib.Backtrace, lang); - cmSystemTools::ExpandListArgument( + cmExpandList( lib.Target->EvaluateInterfaceProperty(prop, &context, dagChecker), ee.Values); ee.ContextDependent = context.HadContextSensitiveCondition; @@ -1311,10 +1311,9 @@ void AddObjectEntries(cmGeneratorTarget const* headTarget, cge->SetEvaluateForBuildsystem(true); EvaluatedTargetPropertyEntry ee(lib, lib.Backtrace); - cmSystemTools::ExpandListArgument( - cge->Evaluate(headTarget->GetLocalGenerator(), config, false, - headTarget, dagChecker), - ee.Values); + cmExpandList(cge->Evaluate(headTarget->GetLocalGenerator(), config, + false, headTarget, dagChecker), + ee.Values); if (cge->GetHadContextSensitiveCondition()) { ee.ContextDependent = true; } @@ -1407,7 +1406,7 @@ std::vector<BT<std::string>> cmGeneratorTarget::GetSourceFilePaths( cmStringRange sourceEntries = this->Target->GetSourceEntries(); for (std::string const& entry : sourceEntries) { std::vector<std::string> items; - cmSystemTools::ExpandListArgument(entry, items); + cmExpandList(entry, items); for (std::string const& item : items) { if (cmHasLiteralPrefix(item, "$<TARGET_OBJECTS:") && item.back() == '>') { @@ -1423,12 +1422,11 @@ std::vector<BT<std::string>> cmGeneratorTarget::GetSourceFilePaths( const char* debugProp = this->Makefile->GetDefinition("CMAKE_DEBUG_TARGET_PROPERTIES"); if (debugProp) { - cmSystemTools::ExpandListArgument(debugProp, debugProperties); + cmExpandList(debugProp, debugProperties); } - bool debugSources = !this->DebugSourcesDone && - std::find(debugProperties.begin(), debugProperties.end(), "SOURCES") != - debugProperties.end(); + bool debugSources = + !this->DebugSourcesDone && cmContains(debugProperties, "SOURCES"); if (this->LocalGenerator->GetGlobalGenerator()->GetConfigureDoneCMP0026()) { this->DebugSourcesDone = true; @@ -1705,8 +1703,7 @@ std::string cmGeneratorTarget::GetCompilePDBName( // Check for a per-configuration output directory target property. std::string configUpper = cmSystemTools::UpperCase(config); - std::string configProp = "COMPILE_PDB_NAME_"; - configProp += configUpper; + std::string configProp = cmStrCat("COMPILE_PDB_NAME_", configUpper); const char* config_name = this->GetProperty(configProp); if (config_name && *config_name) { return prefix + config_name + ".pdb"; @@ -1778,9 +1775,8 @@ bool cmGeneratorTarget::NeedRelinkBeforeInstall( // Check for rpath support on this platform. std::string ll = this->GetLinkerLanguage(config); if (!ll.empty()) { - std::string flagVar = "CMAKE_SHARED_LIBRARY_RUNTIME_"; - flagVar += ll; - flagVar += "_FLAG"; + std::string flagVar = + cmStrCat("CMAKE_SHARED_LIBRARY_RUNTIME_", ll, "_FLAG"); if (!this->Makefile->IsSet(flagVar)) { // There is no rpath support on this platform so nothing needs // relinking. @@ -1858,9 +1854,8 @@ bool cmGeneratorTarget::IsChrpathUsed(const std::string& config) const // binaries. std::string ll = this->GetLinkerLanguage(config); if (!ll.empty()) { - std::string sepVar = "CMAKE_SHARED_LIBRARY_RUNTIME_"; - sepVar += ll; - sepVar += "_FLAG_SEP"; + std::string sepVar = + cmStrCat("CMAKE_SHARED_LIBRARY_RUNTIME_", ll, "_FLAG_SEP"); const char* sep = this->Makefile->GetDefinition(sepVar); if (sep && *sep) { // TODO: Add ELF check to ABI detection and get rid of @@ -1977,7 +1972,7 @@ bool cmGeneratorTarget::MacOSXUseInstallNameDir() const const char* build_with_install_name = this->GetProperty("BUILD_WITH_INSTALL_NAME_DIR"); if (build_with_install_name) { - return cmSystemTools::IsOn(build_with_install_name); + return cmIsOn(build_with_install_name); } cmPolicies::PolicyStatus cmp0068 = this->GetPolicyStatusCMP0068(); @@ -2057,9 +2052,8 @@ bool shouldAddContentLevel(cmGeneratorTarget::BundleDirectoryLevel level) std::string cmGeneratorTarget::GetAppBundleDirectory( const std::string& config, BundleDirectoryLevel level) const { - std::string fpath = - this->GetFullName(config, cmStateEnums::RuntimeBinaryArtifact); - fpath += "."; + std::string fpath = cmStrCat( + this->GetFullName(config, cmStateEnums::RuntimeBinaryArtifact), '.'); const char* ext = this->GetProperty("BUNDLE_EXTENSION"); if (!ext) { ext = "app"; @@ -2084,9 +2078,8 @@ bool cmGeneratorTarget::IsBundleOnApple() const std::string cmGeneratorTarget::GetCFBundleDirectory( const std::string& config, BundleDirectoryLevel level) const { - std::string fpath; - fpath += this->GetOutputName(config, cmStateEnums::RuntimeBinaryArtifact); - fpath += "."; + std::string fpath = cmStrCat( + this->GetOutputName(config, cmStateEnums::RuntimeBinaryArtifact), '.'); const char* ext = this->GetProperty("BUNDLE_EXTENSION"); if (!ext) { if (this->IsXCTestOnApple()) { @@ -2109,9 +2102,8 @@ std::string cmGeneratorTarget::GetCFBundleDirectory( std::string cmGeneratorTarget::GetFrameworkDirectory( const std::string& config, BundleDirectoryLevel level) const { - std::string fpath; - fpath += this->GetOutputName(config, cmStateEnums::RuntimeBinaryArtifact); - fpath += "."; + std::string fpath = cmStrCat( + this->GetOutputName(config, cmStateEnums::RuntimeBinaryArtifact), '.'); const char* ext = this->GetProperty("BUNDLE_EXTENSION"); if (!ext) { ext = "framework"; @@ -2168,8 +2160,7 @@ std::string cmGeneratorTarget::GetInstallNameDirForInstallTree() const if (this->CanGenerateInstallNameDir(INSTALL_NAME_FOR_INSTALL)) { if (install_name_dir && *install_name_dir) { - dir = install_name_dir; - dir += "/"; + dir = cmStrCat(install_name_dir, '/'); } } if (!install_name_dir) { @@ -2210,8 +2201,7 @@ const std::string* cmGeneratorTarget::GetExportMacro() const if (const char* custom_export_name = this->GetProperty("DEFINE_SYMBOL")) { this->ExportMacro = custom_export_name; } else { - std::string in = this->GetName(); - in += "_EXPORTS"; + std::string in = cmStrCat(this->GetName(), "_EXPORTS"); this->ExportMacro = cmSystemTools::MakeCidentifier(in); } return &this->ExportMacro; @@ -2432,8 +2422,7 @@ std::string cmGeneratorTarget::GetMacContentDirectory( const std::string& config, cmStateEnums::ArtifactType artifact) const { // Start with the output directory for the target. - std::string fpath = this->GetDirectory(config, artifact); - fpath += "/"; + std::string fpath = cmStrCat(this->GetDirectory(config, artifact), '/'); BundleDirectoryLevel level = ContentLevel; if (this->IsFrameworkOnApple()) { // additional files with a framework go into the version specific @@ -2469,10 +2458,9 @@ cmGeneratorTarget::CompileInfo const* cmGeneratorTarget::GetCompileInfo( } if (this->GetType() > cmStateEnums::OBJECT_LIBRARY) { - std::string msg = "cmTarget::GetCompileInfo called for "; - msg += this->GetName(); - msg += " which has type "; - msg += cmState::GetTargetTypeName(this->GetType()); + std::string msg = cmStrCat("cmTarget::GetCompileInfo called for ", + this->GetName(), " which has type ", + cmState::GetTargetTypeName(this->GetType())); this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg); return nullptr; } @@ -2526,7 +2514,7 @@ void cmGeneratorTarget::ComputeModuleDefinitionInfo( info.WindowsExportAllSymbols = this->Makefile->IsOn("CMAKE_SUPPORT_WINDOWS_EXPORT_ALL_SYMBOLS") && this->GetPropertyAsBool("WINDOWS_EXPORT_ALL_SYMBOLS"); -#if defined(_WIN32) && defined(CMAKE_BUILD_WITH_CMAKE) +#if defined(_WIN32) && !defined(CMAKE_BOOTSTRAP) info.DefFileGenerated = info.WindowsExportAllSymbols || info.Sources.size() > 1; #else @@ -2557,10 +2545,9 @@ void cmGeneratorTarget::GetAutoUicOptions(std::vector<std::string>& result, cmGeneratorExpressionDAGChecker dagChecker(this, "AUTOUIC_OPTIONS", nullptr, nullptr); - cmSystemTools::ExpandListArgument( - ge.Parse(prop)->Evaluate(this->LocalGenerator, config, false, this, - &dagChecker), - result); + cmExpandList(ge.Parse(prop)->Evaluate(this->LocalGenerator, config, false, + this, &dagChecker), + result); } void processILibs(const std::string& config, @@ -2653,7 +2640,7 @@ cmTargetTraceDependencies::cmTargetTraceDependencies(cmGeneratorTarget* target) for (cmSourceFile* sf : sources) { const std::set<cmGeneratorTarget const*> tgts = this->GlobalGenerator->GetFilenameTargetDepends(sf); - if (tgts.find(this->GeneratorTarget) != tgts.end()) { + if (cmContains(tgts, this->GeneratorTarget)) { std::ostringstream e; e << "Evaluation output file\n \"" << sf->GetFullPath() << "\"\ndepends on the sources of a target it is used in. This " @@ -2688,7 +2675,7 @@ void cmTargetTraceDependencies::Trace() // Queue dependencies added explicitly by the user. if (const char* additionalDeps = sf->GetProperty("OBJECT_DEPENDS")) { std::vector<std::string> objDeps; - cmSystemTools::ExpandListArgument(additionalDeps, objDeps); + cmExpandList(additionalDeps, objDeps); for (std::string& objDep : objDeps) { if (cmSystemTools::FileIsFullPath(objDep)) { objDep = cmSystemTools::CollapseFullPath(objDep); @@ -2901,15 +2888,15 @@ void cmGeneratorTarget::GetAppleArchs(const std::string& config, { const char* archs = nullptr; if (!config.empty()) { - std::string defVarName = "OSX_ARCHITECTURES_"; - defVarName += cmSystemTools::UpperCase(config); + std::string defVarName = + cmStrCat("OSX_ARCHITECTURES_", cmSystemTools::UpperCase(config)); archs = this->GetProperty(defVarName); } if (!archs) { archs = this->GetProperty("OSX_ARCHITECTURES"); } if (archs) { - cmSystemTools::ExpandListArgument(std::string(archs), archVec); + cmExpandList(std::string(archs), archVec); } } @@ -3039,7 +3026,7 @@ void processIncludeDirectories( } } - if (!cmSystemTools::IsOff(entryInclude)) { + if (!cmIsOff(entryInclude)) { cmSystemTools::ConvertToUnixSlashes(entryInclude); } @@ -3074,12 +3061,11 @@ std::vector<BT<std::string>> cmGeneratorTarget::GetIncludeDirectories( const char* debugProp = this->Makefile->GetDefinition("CMAKE_DEBUG_TARGET_PROPERTIES"); if (debugProp) { - cmSystemTools::ExpandListArgument(debugProp, debugProperties); + cmExpandList(debugProp, debugProperties); } bool debugIncludes = !this->DebugIncludesDone && - std::find(debugProperties.begin(), debugProperties.end(), - "INCLUDE_DIRECTORIES") != debugProperties.end(); + cmContains(debugProperties, "INCLUDE_DIRECTORIES"); if (this->GlobalGenerator->GetConfigureDoneCMP0026()) { this->DebugIncludesDone = true; @@ -3185,12 +3171,11 @@ std::vector<BT<std::string>> cmGeneratorTarget::GetCompileOptions( const char* debugProp = this->Makefile->GetDefinition("CMAKE_DEBUG_TARGET_PROPERTIES"); if (debugProp) { - cmSystemTools::ExpandListArgument(debugProp, debugProperties); + cmExpandList(debugProp, debugProperties); } bool debugOptions = !this->DebugCompileOptionsDone && - std::find(debugProperties.begin(), debugProperties.end(), - "COMPILE_OPTIONS") != debugProperties.end(); + cmContains(debugProperties, "COMPILE_OPTIONS"); if (this->GlobalGenerator->GetConfigureDoneCMP0026()) { this->DebugCompileOptionsDone = true; @@ -3232,12 +3217,11 @@ std::vector<BT<std::string>> cmGeneratorTarget::GetCompileFeatures( const char* debugProp = this->Makefile->GetDefinition("CMAKE_DEBUG_TARGET_PROPERTIES"); if (debugProp) { - cmSystemTools::ExpandListArgument(debugProp, debugProperties); + cmExpandList(debugProp, debugProperties); } bool debugFeatures = !this->DebugCompileFeaturesDone && - std::find(debugProperties.begin(), debugProperties.end(), - "COMPILE_FEATURES") != debugProperties.end(); + cmContains(debugProperties, "COMPILE_FEATURES"); if (this->GlobalGenerator->GetConfigureDoneCMP0026()) { this->DebugCompileFeaturesDone = true; @@ -3281,12 +3265,11 @@ std::vector<BT<std::string>> cmGeneratorTarget::GetCompileDefinitions( const char* debugProp = this->Makefile->GetDefinition("CMAKE_DEBUG_TARGET_PROPERTIES"); if (debugProp) { - cmSystemTools::ExpandListArgument(debugProp, debugProperties); + cmExpandList(debugProp, debugProperties); } bool debugDefines = !this->DebugCompileDefinitionsDone && - std::find(debugProperties.begin(), debugProperties.end(), - "COMPILE_DEFINITIONS") != debugProperties.end(); + cmContains(debugProperties, "COMPILE_DEFINITIONS"); if (this->GlobalGenerator->GetConfigureDoneCMP0026()) { this->DebugCompileDefinitionsDone = true; @@ -3356,12 +3339,11 @@ std::vector<BT<std::string>> cmGeneratorTarget::GetLinkOptions( const char* debugProp = this->Makefile->GetDefinition("CMAKE_DEBUG_TARGET_PROPERTIES"); if (debugProp) { - cmSystemTools::ExpandListArgument(debugProp, debugProperties); + cmExpandList(debugProp, debugProperties); } - bool debugOptions = !this->DebugLinkOptionsDone && - std::find(debugProperties.begin(), debugProperties.end(), - "LINK_OPTIONS") != debugProperties.end(); + bool debugOptions = + !this->DebugLinkOptionsDone && cmContains(debugProperties, "LINK_OPTIONS"); if (this->GlobalGenerator->GetConfigureDoneCMP0026()) { this->DebugLinkOptionsDone = true; @@ -3382,7 +3364,7 @@ std::vector<BT<std::string>> cmGeneratorTarget::GetLinkOptions( const std::string wrapper(this->Makefile->GetSafeDefinition( "CMAKE_" + language + "_LINKER_WRAPPER_FLAG")); std::vector<std::string> wrapperFlag; - cmSystemTools::ExpandListArgument(wrapper, wrapperFlag); + cmExpandList(wrapper, wrapperFlag); const std::string wrapperSep(this->Makefile->GetSafeDefinition( "CMAKE_" + language + "_LINKER_WRAPPER_FLAG_SEP")); bool concatFlagAndArgs = true; @@ -3410,8 +3392,7 @@ std::vector<BT<std::string>> cmGeneratorTarget::GetLinkOptions( cmSystemTools::ParseUnixCommandLine( value.c_str() + LINKER_SHELL.length(), linkerOptions); } else { - linkerOptions = - cmSystemTools::tokenize(value.substr(LINKER.length()), ","); + linkerOptions = cmTokenize(value.substr(LINKER.length()), ","); } if (linkerOptions.empty() || @@ -3505,7 +3486,7 @@ std::vector<BT<std::string>> cmGeneratorTarget::GetStaticLibraryLinkOptions( std::vector<EvaluatedTargetPropertyEntry> entries; if (const char* linkOptions = this->GetProperty("STATIC_LIBRARY_OPTIONS")) { std::vector<std::string> options; - cmSystemTools::ExpandListArgument(linkOptions, options); + cmExpandList(linkOptions, options); for (const auto& option : options) { std::unique_ptr<TargetPropertyEntry> entry( CreateTargetPropertyEntry(option)); @@ -3615,12 +3596,11 @@ std::vector<BT<std::string>> cmGeneratorTarget::GetLinkDirectories( const char* debugProp = this->Makefile->GetDefinition("CMAKE_DEBUG_TARGET_PROPERTIES"); if (debugProp) { - cmSystemTools::ExpandListArgument(debugProp, debugProperties); + cmExpandList(debugProp, debugProperties); } bool debugDirectories = !this->DebugLinkDirectoriesDone && - std::find(debugProperties.begin(), debugProperties.end(), - "LINK_DIRECTORIES") != debugProperties.end(); + cmContains(debugProperties, "LINK_DIRECTORIES"); if (this->GlobalGenerator->GetConfigureDoneCMP0026()) { this->DebugLinkDirectoriesDone = true; @@ -3661,7 +3641,7 @@ std::vector<BT<std::string>> cmGeneratorTarget::GetLinkDepends( std::vector<EvaluatedTargetPropertyEntry> entries; if (const char* linkDepends = this->GetProperty("LINK_DEPENDS")) { std::vector<std::string> depends; - cmSystemTools::ExpandListArgument(linkDepends, depends); + cmExpandList(linkDepends, depends); for (const auto& depend : depends) { std::unique_ptr<TargetPropertyEntry> entry( CreateTargetPropertyEntry(depend)); @@ -3704,33 +3684,25 @@ void cmGeneratorTarget::ComputeTargetManifest(const std::string& config) const // Add each name. std::string f; if (!targetNames.Output.empty()) { - f = dir; - f += "/"; - f += targetNames.Output; + f = cmStrCat(dir, '/', targetNames.Output); gg->AddToManifest(f); } if (!targetNames.SharedObject.empty()) { - f = dir; - f += "/"; - f += targetNames.SharedObject; + f = cmStrCat(dir, '/', targetNames.SharedObject); gg->AddToManifest(f); } if (!targetNames.Real.empty()) { - f = dir; - f += "/"; - f += targetNames.Real; + f = cmStrCat(dir, '/', targetNames.Real); gg->AddToManifest(f); } if (!targetNames.PDB.empty()) { - f = dir; - f += "/"; - f += targetNames.PDB; + f = cmStrCat(dir, '/', targetNames.PDB); gg->AddToManifest(f); } if (!targetNames.ImportLibrary.empty()) { - f = this->GetDirectory(config, cmStateEnums::ImportLibraryArtifact); - f += "/"; - f += targetNames.ImportLibrary; + f = + cmStrCat(this->GetDirectory(config, cmStateEnums::ImportLibraryArtifact), + '/', targetNames.ImportLibrary); gg->AddToManifest(f); } } @@ -3770,11 +3742,10 @@ std::string cmGeneratorTarget::NormalGetFullPath( const std::string& config, cmStateEnums::ArtifactType artifact, bool realname) const { - std::string fpath = this->GetDirectory(config, artifact); - fpath += "/"; + std::string fpath = cmStrCat(this->GetDirectory(config, artifact), '/'); if (this->IsAppBundleOnApple()) { - fpath = this->BuildBundleDirectory(fpath, config, FullLevel); - fpath += "/"; + fpath = + cmStrCat(this->BuildBundleDirectory(fpath, config, FullLevel), '/'); } // Add the full name of the target. @@ -3801,8 +3772,8 @@ std::string cmGeneratorTarget::NormalGetRealName( // TODO: Split cmTarget into a class hierarchy to get compile-time // enforcement of the limited imported target API. if (this->IsImported()) { - std::string msg = "NormalGetRealName called on imported target: "; - msg += this->GetName(); + std::string msg = cmStrCat("NormalGetRealName called on imported target: ", + this->GetName()); this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg); } @@ -3823,8 +3794,8 @@ cmGeneratorTarget::Names cmGeneratorTarget::GetLibraryNames( // TODO: Split cmTarget into a class hierarchy to get compile-time // enforcement of the limited imported target API. if (this->IsImported()) { - std::string msg = "GetLibraryNames called on imported target: "; - msg += this->GetName(); + std::string msg = + cmStrCat("GetLibraryNames called on imported target: ", this->GetName()); this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg); } @@ -3900,8 +3871,8 @@ cmGeneratorTarget::Names cmGeneratorTarget::GetExecutableNames( // TODO: Split cmTarget into a class hierarchy to get compile-time // enforcement of the limited imported target API. if (this->IsImported()) { - std::string msg = "GetExecutableNames called on imported target: "; - msg += this->GetName(); + std::string msg = cmStrCat( + "GetExecutableNames called on imported target: ", this->GetName()); this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg); } @@ -4022,15 +3993,14 @@ void cmGeneratorTarget::GetFullNameInternal( // frameworks have directory prefix but no suffix std::string fw_prefix; if (this->IsFrameworkOnApple()) { - fw_prefix = this->GetFrameworkDirectory(config, ContentLevel); - fw_prefix += "/"; + fw_prefix = + cmStrCat(this->GetFrameworkDirectory(config, ContentLevel), '/'); targetPrefix = fw_prefix.c_str(); targetSuffix = nullptr; } if (this->IsCFBundleOnApple()) { - fw_prefix = this->GetCFBundleDirectory(config, FullLevel); - fw_prefix += "/"; + fw_prefix = cmStrCat(this->GetCFBundleDirectory(config, FullLevel), '/'); targetPrefix = fw_prefix.c_str(); targetSuffix = nullptr; } @@ -4215,7 +4185,7 @@ void cmGeneratorTarget::ConstructSourceFileFlags() const // Process public headers to mark the source files. if (const char* files = this->GetProperty("PUBLIC_HEADER")) { std::vector<std::string> relFiles; - cmSystemTools::ExpandListArgument(files, relFiles); + cmExpandList(files, relFiles); for (std::string const& relFile : relFiles) { if (cmSourceFile* sf = this->Makefile->GetSource(relFile)) { SourceFileFlags& flags = this->SourceFlagsMap[sf]; @@ -4229,7 +4199,7 @@ void cmGeneratorTarget::ConstructSourceFileFlags() const // precedence if a file is listed in both. if (const char* files = this->GetProperty("PRIVATE_HEADER")) { std::vector<std::string> relFiles; - cmSystemTools::ExpandListArgument(files, relFiles); + cmExpandList(files, relFiles); for (std::string const& relFile : relFiles) { if (cmSourceFile* sf = this->Makefile->GetSource(relFile)) { SourceFileFlags& flags = this->SourceFlagsMap[sf]; @@ -4242,7 +4212,7 @@ void cmGeneratorTarget::ConstructSourceFileFlags() const // Mark sources listed as resources. if (const char* files = this->GetProperty("RESOURCE")) { std::vector<std::string> relFiles; - cmSystemTools::ExpandListArgument(files, relFiles); + cmExpandList(files, relFiles); for (std::string const& relFile : relFiles) { if (cmSourceFile* sf = this->Makefile->GetSource(relFile)) { SourceFileFlags& flags = this->SourceFlagsMap[sf]; @@ -4271,7 +4241,7 @@ cmGeneratorTarget::GetCompatibleInterfaces(std::string const& config) const #define CM_READ_COMPATIBLE_INTERFACE(X, x) \ if (const char* prop = li->GetProperty("COMPATIBLE_INTERFACE_" #X)) { \ std::vector<std::string> props; \ - cmSystemTools::ExpandListArgument(prop, props); \ + cmExpandList(prop, props); \ compat.Props##x.insert(props.begin(), props.end()); \ } CM_READ_COMPATIBLE_INTERFACE(BOOL, Bool) @@ -4385,9 +4355,9 @@ void checkPropertyConsistency(cmGeneratorTarget const* depender, } std::vector<std::string> props; - cmSystemTools::ExpandListArgument(prop, props); - std::string pdir = cmSystemTools::GetCMakeRoot(); - pdir += "/Help/prop_tgt/"; + cmExpandList(prop, props); + std::string pdir = + cmStrCat(cmSystemTools::GetCMakeRoot(), "/Help/prop_tgt/"); for (std::string const& p : props) { std::string pname = cmSystemTools::HelpFileName(p); @@ -4533,8 +4503,8 @@ void cmGeneratorTarget::CheckPropertyCompatibility( } std::sort(props.begin(), props.end()); - std::string propsString = cmJoin(cmMakeRange(props).retreat(1), ", "); - propsString += " and the " + props.back(); + std::string propsString = cmStrCat( + cmJoin(cmMakeRange(props).retreat(1), ", "), " and the ", props.back()); std::ostringstream e; e << "Property \"" << prop << "\" appears in both the " << propsString @@ -4615,7 +4585,7 @@ bool getTypedProperty<bool>(cmGeneratorTarget const* tgt, } const char* value = tgt->GetProperty(prop); - return cmSystemTools::IsOn(genexInterpreter->Evaluate(value, prop)); + return cmIsOn(genexInterpreter->Evaluate(value, prop)); } template <> @@ -4733,7 +4703,7 @@ std::pair<bool, const char*> consistentProperty(const char* lhs, switch (t) { case BoolType: { - bool same = cmSystemTools::IsOn(lhs) == cmSystemTools::IsOn(rhs); + bool same = cmIsOn(lhs) == cmIsOn(rhs); return std::make_pair(same, same ? lhs : nullptr); } case StringType: @@ -4764,7 +4734,7 @@ std::pair<bool, std::string> consistentProperty(const std::string& lhs, switch (t) { case BoolType: { - bool same = cmSystemTools::IsOn(lhs) == cmSystemTools::IsOn(rhs); + bool same = cmIsOn(lhs) == cmIsOn(rhs); return std::make_pair(same, same ? lhs : null_ptr); } case StringType: @@ -4791,9 +4761,7 @@ PropertyType checkInterfacePropertyCompatibility(cmGeneratorTarget const* tgt, PropertyType propContent = getTypedProperty<PropertyType>(tgt, p); std::vector<std::string> headPropKeys = tgt->GetPropertyKeys(); - const bool explicitlySet = - std::find(headPropKeys.begin(), headPropKeys.end(), p) != - headPropKeys.end(); + const bool explicitlySet = cmContains(headPropKeys, p); const bool impliedByUse = tgt->IsNullImpliedByLinkLibraries(p); assert((impliedByUse ^ explicitlySet) || (!impliedByUse && !explicitlySet)); @@ -4806,8 +4774,7 @@ PropertyType checkInterfacePropertyCompatibility(cmGeneratorTarget const* tgt, } bool propInitialized = explicitlySet; - std::string report = " * Target \""; - report += tgt->GetName(); + std::string report = cmStrCat(" * Target \"", tgt->GetName()); if (explicitlySet) { report += "\" has property content \""; report += valueAsString<PropertyType>(propContent); @@ -4833,8 +4800,7 @@ PropertyType checkInterfacePropertyCompatibility(cmGeneratorTarget const* tgt, std::vector<std::string> propKeys = theTarget->GetPropertyKeys(); - const bool ifaceIsSet = std::find(propKeys.begin(), propKeys.end(), - interfaceProperty) != propKeys.end(); + const bool ifaceIsSet = cmContains(propKeys, interfaceProperty); PropertyType ifacePropContent = getTypedProperty<PropertyType>( theTarget, interfaceProperty, genexInterpreter.get()); @@ -5064,9 +5030,8 @@ std::string cmGeneratorTarget::CreateFortranModuleDirectory( mod_dir = target_mod_dir; } else { // Interpret relative to the current output directory. - mod_dir = this->LocalGenerator->GetCurrentBinaryDirectory(); - mod_dir += "/"; - mod_dir += target_mod_dir; + mod_dir = cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(), + '/', target_mod_dir); } // Make sure the module output directory exists. @@ -5116,12 +5081,11 @@ void cmGeneratorTarget::ReportPropertyOrigin( const char* debugProp = this->Target->GetMakefile()->GetDefinition( "CMAKE_DEBUG_TARGET_PROPERTIES"); if (debugProp) { - cmSystemTools::ExpandListArgument(debugProp, debugProperties); + cmExpandList(debugProp, debugProperties); } - bool debugOrigin = !this->DebugCompatiblePropertiesDone[p] && - std::find(debugProperties.begin(), debugProperties.end(), p) != - debugProperties.end(); + bool debugOrigin = + !this->DebugCompatiblePropertiesDone[p] && cmContains(debugProperties, p); if (this->GlobalGenerator->GetConfigureDoneCMP0026()) { this->DebugCompatiblePropertiesDone[p] = true; @@ -5130,12 +5094,9 @@ void cmGeneratorTarget::ReportPropertyOrigin( return; } - std::string areport = compatibilityType; - areport += std::string(" of property \"") + p + "\" for target \""; - areport += std::string(this->GetName()); - areport += "\" (result: \""; - areport += result; - areport += "\"):\n" + report; + std::string areport = + cmStrCat(compatibilityType, " of property \"", p, "\" for target \"", + this->GetName(), "\" (result: \"", result, "\"):\n", report); this->LocalGenerator->GetCMakeInstance()->IssueMessage(MessageType::LOG, areport); @@ -5168,10 +5129,9 @@ void cmGeneratorTarget::ExpandLinkItems( } std::vector<std::string> libs; std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(value); - cmSystemTools::ExpandListArgument(cge->Evaluate(this->LocalGenerator, config, - false, headTarget, this, - &dagChecker), - libs); + cmExpandList(cge->Evaluate(this->LocalGenerator, config, false, headTarget, + this, &dagChecker), + libs); this->LookupLinkItems(libs, cge->GetBacktrace(), items); hadHeadSensitiveCondition = cge->GetHadHeadSensitiveCondition(); } @@ -5219,7 +5179,7 @@ void cmGeneratorTarget::ComputeLinkInterface( const std::string& config, cmOptionalLinkInterface& iface, cmGeneratorTarget const* headTarget) const { - if (iface.ExplicitLibraries) { + if (iface.Explicit) { if (this->GetType() == cmStateEnums::SHARED_LIBRARY || this->GetType() == cmStateEnums::STATIC_LIBRARY || this->GetType() == cmStateEnums::INTERFACE_LIBRARY) { @@ -5276,8 +5236,7 @@ void cmGeneratorTarget::ComputeLinkInterface( // How many repetitions are needed if this library has cyclic // dependencies? - std::string propName = "LINK_INTERFACE_MULTIPLICITY"; - propName += suffix; + std::string propName = cmStrCat("LINK_INTERFACE_MULTIPLICITY", suffix); if (const char* config_reps = this->GetProperty(propName)) { sscanf(config_reps, "%u", &iface.Multiplicity); } else if (const char* reps = @@ -5363,10 +5322,9 @@ cmGeneratorTarget::OutputInfo const* cmGeneratorTarget::GetOutputInfo( // Only libraries and executables have well-defined output files. if (!this->HaveWellDefinedOutputFiles()) { - std::string msg = "cmGeneratorTarget::GetOutputInfo called for "; - msg += this->GetName(); - msg += " which has type "; - msg += cmState::GetTargetTypeName(this->GetType()); + std::string msg = cmStrCat("cmGeneratorTarget::GetOutputInfo called for ", + this->GetName(), " which has type ", + cmState::GetTargetTypeName(this->GetType())); this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg); return nullptr; } @@ -5603,8 +5561,9 @@ void cmGeneratorTarget::ComputeLinkInterfaceLibraries( // libraries and executables that export symbols. const char* explicitLibraries = nullptr; std::string linkIfaceProp; - if (this->GetPolicyStatusCMP0022() != cmPolicies::OLD && - this->GetPolicyStatusCMP0022() != cmPolicies::WARN) { + bool const cmp0022NEW = (this->GetPolicyStatusCMP0022() != cmPolicies::OLD && + this->GetPolicyStatusCMP0022() != cmPolicies::WARN); + if (cmp0022NEW) { // CMP0022 NEW behavior is to use INTERFACE_LINK_LIBRARIES. linkIfaceProp = "INTERFACE_LINK_LIBRARIES"; explicitLibraries = this->GetProperty(linkIfaceProp); @@ -5614,8 +5573,7 @@ void cmGeneratorTarget::ComputeLinkInterfaceLibraries( // shared lib or executable. // Lookup the per-configuration property. - linkIfaceProp = "LINK_INTERFACE_LIBRARIES"; - linkIfaceProp += suffix; + linkIfaceProp = cmStrCat("LINK_INTERFACE_LIBRARIES", suffix); explicitLibraries = this->GetProperty(linkIfaceProp); // If not set, try the generic property. @@ -5659,15 +5617,14 @@ void cmGeneratorTarget::ComputeLinkInterfaceLibraries( return; } iface.Exists = true; - iface.ExplicitLibraries = explicitLibraries; + iface.Explicit = cmp0022NEW || explicitLibraries != nullptr; if (explicitLibraries) { // The interface libraries have been explicitly set. this->ExpandLinkItems(linkIfaceProp, explicitLibraries, config, headTarget, usage_requirements_only, iface.Libraries, iface.HadHeadSensitiveCondition); - } else if (this->GetPolicyStatusCMP0022() == cmPolicies::WARN || - this->GetPolicyStatusCMP0022() == cmPolicies::OLD) + } else if (!cmp0022NEW) // If CMP0022 is NEW then the plain tll signature sets the // INTERFACE_LINK_LIBRARIES, so if we get here then the project // cleared the property explicitly and we should not fall back @@ -5748,12 +5705,12 @@ const cmLinkInterface* cmGeneratorTarget::GetImportLinkInterface( if (!iface.AllDone) { iface.AllDone = true; iface.Multiplicity = info->Multiplicity; - cmSystemTools::ExpandListArgument(info->Languages, iface.Languages); + cmExpandList(info->Languages, iface.Languages); this->ExpandLinkItems(info->LibrariesProp, info->Libraries, config, headTarget, usage_requirements_only, iface.Libraries, iface.HadHeadSensitiveCondition); std::vector<std::string> deps; - cmSystemTools::ExpandListArgument(info->SharedDeps, deps); + cmExpandList(info->SharedDeps, deps); this->LookupLinkItems(deps, cmListFileBacktrace(), iface.SharedDeps); } @@ -5822,8 +5779,7 @@ void cmGeneratorTarget::ComputeImportInfo(std::string const& desired_config, if (this->GetType() != cmStateEnums::INTERFACE_LIBRARY) { if (!propertyLibs) { - linkProp = "IMPORTED_LINK_INTERFACE_LIBRARIES"; - linkProp += suffix; + linkProp = cmStrCat("IMPORTED_LINK_INTERFACE_LIBRARIES", suffix); propertyLibs = this->GetProperty(linkProp); } @@ -5851,8 +5807,7 @@ void cmGeneratorTarget::ComputeImportInfo(std::string const& desired_config, if (loc) { info.Location = loc; } else { - std::string impProp = "IMPORTED_LOCATION"; - impProp += suffix; + std::string impProp = cmStrCat("IMPORTED_LOCATION", suffix); if (const char* config_location = this->GetProperty(impProp)) { info.Location = config_location; } else if (const char* location = this->GetProperty("IMPORTED_LOCATION")) { @@ -5862,8 +5817,7 @@ void cmGeneratorTarget::ComputeImportInfo(std::string const& desired_config, // Get the soname. if (this->GetType() == cmStateEnums::SHARED_LIBRARY) { - std::string soProp = "IMPORTED_SONAME"; - soProp += suffix; + std::string soProp = cmStrCat("IMPORTED_SONAME", suffix); if (const char* config_soname = this->GetProperty(soProp)) { info.SOName = config_soname; } else if (const char* soname = this->GetProperty("IMPORTED_SONAME")) { @@ -5873,13 +5827,12 @@ void cmGeneratorTarget::ComputeImportInfo(std::string const& desired_config, // Get the "no-soname" mark. if (this->GetType() == cmStateEnums::SHARED_LIBRARY) { - std::string soProp = "IMPORTED_NO_SONAME"; - soProp += suffix; + std::string soProp = cmStrCat("IMPORTED_NO_SONAME", suffix); if (const char* config_no_soname = this->GetProperty(soProp)) { - info.NoSOName = cmSystemTools::IsOn(config_no_soname); + info.NoSOName = cmIsOn(config_no_soname); } else if (const char* no_soname = this->GetProperty("IMPORTED_NO_SONAME")) { - info.NoSOName = cmSystemTools::IsOn(no_soname); + info.NoSOName = cmIsOn(no_soname); } } @@ -5888,8 +5841,7 @@ void cmGeneratorTarget::ComputeImportInfo(std::string const& desired_config, info.ImportLibrary = imp; } else if (this->GetType() == cmStateEnums::SHARED_LIBRARY || this->IsExecutableWithExports()) { - std::string impProp = "IMPORTED_IMPLIB"; - impProp += suffix; + std::string impProp = cmStrCat("IMPORTED_IMPLIB", suffix); if (const char* config_implib = this->GetProperty(impProp)) { info.ImportLibrary = config_implib; } else if (const char* implib = this->GetProperty("IMPORTED_IMPLIB")) { @@ -5899,8 +5851,8 @@ void cmGeneratorTarget::ComputeImportInfo(std::string const& desired_config, // Get the link dependencies. { - std::string linkProp = "IMPORTED_LINK_DEPENDENT_LIBRARIES"; - linkProp += suffix; + std::string linkProp = + cmStrCat("IMPORTED_LINK_DEPENDENT_LIBRARIES", suffix); if (const char* config_libs = this->GetProperty(linkProp)) { info.SharedDeps = config_libs; } else if (const char* libs = @@ -5911,8 +5863,8 @@ void cmGeneratorTarget::ComputeImportInfo(std::string const& desired_config, // Get the link languages. if (this->LinkLanguagePropagatesToDependents()) { - std::string linkProp = "IMPORTED_LINK_INTERFACE_LANGUAGES"; - linkProp += suffix; + std::string linkProp = + cmStrCat("IMPORTED_LINK_INTERFACE_LANGUAGES", suffix); if (const char* config_libs = this->GetProperty(linkProp)) { info.Languages = config_libs; } else if (const char* libs = @@ -5933,8 +5885,8 @@ void cmGeneratorTarget::ComputeImportInfo(std::string const& desired_config, // Get the cyclic repetition count. if (this->GetType() == cmStateEnums::STATIC_LIBRARY) { - std::string linkProp = "IMPORTED_LINK_INTERFACE_MULTIPLICITY"; - linkProp += suffix; + std::string linkProp = + cmStrCat("IMPORTED_LINK_INTERFACE_MULTIPLICITY", suffix); if (const char* config_reps = this->GetProperty(linkProp)) { sscanf(config_reps, "%u", &info.Multiplicity); } else if (const char* reps = @@ -6042,7 +5994,7 @@ void cmGeneratorTarget::GetObjectLibrariesCMP0026( cmStringRange rng = this->Target->GetSourceEntries(); for (std::string const& entry : rng) { std::vector<std::string> files; - cmSystemTools::ExpandListArgument(entry, files); + cmExpandList(entry, files); for (std::string const& li : files) { if (cmHasLiteralPrefix(li, "$<TARGET_OBJECTS:") && li.back() == '>') { std::string objLibName = li.substr(17, li.size() - 18); @@ -6234,8 +6186,7 @@ cmGeneratorTarget::GetLinkImplementationLibrariesInternal( bool cmGeneratorTarget::IsNullImpliedByLinkLibraries( const std::string& p) const { - return this->LinkImplicitNullProperties.find(p) != - this->LinkImplicitNullProperties.end(); + return cmContains(this->LinkImplicitNullProperties, p); } void cmGeneratorTarget::ComputeLinkImplementationLibraries( @@ -6256,7 +6207,7 @@ void cmGeneratorTarget::ComputeLinkImplementationLibraries( std::unique_ptr<cmCompiledGeneratorExpression> const cge = ge.Parse(*le); std::string const& evaluated = cge->Evaluate(this->LocalGenerator, config, false, head, &dagChecker); - cmSystemTools::ExpandListArgument(evaluated, llibs); + cmExpandList(evaluated, llibs); if (cge->GetHadHeadSensitiveCondition()) { impl.HadHeadSensitiveCondition = true; } @@ -6413,8 +6364,8 @@ bool cmGeneratorTarget::GetImplibGNUtoMS(std::string const& config, { if (this->HasImplibGNUtoMS(config) && gnuName.size() > 6 && gnuName.substr(gnuName.size() - 6) == ".dll.a") { - out = gnuName.substr(0, gnuName.size() - 6); - out += newExt ? newExt : ".lib"; + out = cmStrCat(cm::string_view(gnuName).substr(0, gnuName.size() - 6), + newExt ? newExt : ".lib"); return true; } return false; @@ -6449,10 +6400,8 @@ bool cmGeneratorTarget::NeedImportLibraryName(std::string const& config) const std::string cmGeneratorTarget::GetSupportDirectory() const { - std::string dir = this->LocalGenerator->GetCurrentBinaryDirectory(); - dir += "/CMakeFiles"; - dir += "/"; - dir += this->GetName(); + std::string dir = cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(), + "/CMakeFiles/", this->GetName()); #if defined(__VMS) dir += "_dir"; #else diff --git a/Source/cmGetCMakePropertyCommand.cxx b/Source/cmGetCMakePropertyCommand.cxx index 38fee28..ff4e312 100644 --- a/Source/cmGetCMakePropertyCommand.cxx +++ b/Source/cmGetCMakePropertyCommand.cxx @@ -4,19 +4,18 @@ #include <set> +#include "cmExecutionStatus.h" #include "cmGlobalGenerator.h" #include "cmMakefile.h" #include "cmState.h" #include "cmStringAlgorithms.h" -class cmExecutionStatus; - // cmGetCMakePropertyCommand -bool cmGetCMakePropertyCommand::InitialPass( - std::vector<std::string> const& args, cmExecutionStatus&) +bool cmGetCMakePropertyCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() < 2) { - this->SetError("called with incorrect number of arguments"); + status.SetError("called with incorrect number of arguments"); return false; } @@ -24,29 +23,29 @@ bool cmGetCMakePropertyCommand::InitialPass( std::string output = "NOTFOUND"; if (args[1] == "VARIABLES") { - if (const char* varsProp = this->Makefile->GetProperty("VARIABLES")) { + if (const char* varsProp = status.GetMakefile().GetProperty("VARIABLES")) { output = varsProp; } } else if (args[1] == "MACROS") { output.clear(); - if (const char* macrosProp = this->Makefile->GetProperty("MACROS")) { + if (const char* macrosProp = status.GetMakefile().GetProperty("MACROS")) { output = macrosProp; } } else if (args[1] == "COMPONENTS") { const std::set<std::string>* components = - this->Makefile->GetGlobalGenerator()->GetInstallComponents(); + status.GetMakefile().GetGlobalGenerator()->GetInstallComponents(); output = cmJoin(*components, ";"); } else { const char* prop = nullptr; if (!args[1].empty()) { - prop = this->Makefile->GetState()->GetGlobalProperty(args[1]); + prop = status.GetMakefile().GetState()->GetGlobalProperty(args[1]); } if (prop) { output = prop; } } - this->Makefile->AddDefinition(variable, output); + status.GetMakefile().AddDefinition(variable, output); return true; } diff --git a/Source/cmGetCMakePropertyCommand.h b/Source/cmGetCMakePropertyCommand.h index 7790a6b..7a6728c 100644 --- a/Source/cmGetCMakePropertyCommand.h +++ b/Source/cmGetCMakePropertyCommand.h @@ -8,26 +8,9 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -class cmGetCMakePropertyCommand : public cmCommand -{ -public: - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmGetCMakePropertyCommand>(); - } - - /** - * This is called when the command is first encountered in - * the input file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; -}; +bool cmGetCMakePropertyCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmGetDirectoryPropertyCommand.cxx b/Source/cmGetDirectoryPropertyCommand.cxx index 98ccb0a..d078a7a 100644 --- a/Source/cmGetDirectoryPropertyCommand.cxx +++ b/Source/cmGetDirectoryPropertyCommand.cxx @@ -2,20 +2,25 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmGetDirectoryPropertyCommand.h" +#include "cmExecutionStatus.h" #include "cmGlobalGenerator.h" #include "cmMakefile.h" #include "cmMessageType.h" #include "cmPolicies.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" -class cmExecutionStatus; +namespace { +void StoreResult(cmMakefile& makefile, std::string const& variable, + const char* prop); +} // cmGetDirectoryPropertyCommand -bool cmGetDirectoryPropertyCommand::InitialPass( - std::vector<std::string> const& args, cmExecutionStatus&) +bool cmGetDirectoryPropertyCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() < 2) { - this->SetError("called with incorrect number of arguments"); + status.SetError("called with incorrect number of arguments"); return false; } @@ -24,29 +29,27 @@ bool cmGetDirectoryPropertyCommand::InitialPass( ++i; // get the directory argument if there is one - cmMakefile* dir = this->Makefile; + cmMakefile* dir = &status.GetMakefile(); if (*i == "DIRECTORY") { ++i; if (i == args.end()) { - this->SetError( + status.SetError( "DIRECTORY argument provided without subsequent arguments"); return false; } std::string sd = *i; // make sure the start dir is a full path if (!cmSystemTools::FileIsFullPath(sd)) { - sd = this->Makefile->GetCurrentSourceDirectory(); - sd += "/"; - sd += *i; + sd = cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', *i); } // The local generators are associated with collapsed paths. sd = cmSystemTools::CollapseFullPath(sd); // lookup the makefile from the directory name - dir = this->Makefile->GetGlobalGenerator()->FindMakefile(sd); + dir = status.GetMakefile().GetGlobalGenerator()->FindMakefile(sd); if (!dir) { - this->SetError( + status.SetError( "DIRECTORY argument provided but requested directory not found. " "This could be because the directory argument was invalid or, " "it is valid but has not been processed yet."); @@ -61,26 +64,27 @@ bool cmGetDirectoryPropertyCommand::InitialPass( if (*i == "DEFINITION") { ++i; if (i == args.end()) { - this->SetError("A request for a variable definition was made without " - "providing the name of the variable to get."); + status.SetError("A request for a variable definition was made without " + "providing the name of the variable to get."); return false; } std::string const& output = dir->GetSafeDefinition(*i); - this->Makefile->AddDefinition(variable, output); + status.GetMakefile().AddDefinition(variable, output); return true; } const char* prop = nullptr; if (!i->empty()) { if (*i == "DEFINITIONS") { - switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0059)) { + switch (status.GetMakefile().GetPolicyStatus(cmPolicies::CMP0059)) { case cmPolicies::WARN: - this->Makefile->IssueMessage( + status.GetMakefile().IssueMessage( MessageType::AUTHOR_WARNING, cmPolicies::GetPolicyWarning(cmPolicies::CMP0059)); CM_FALLTHROUGH; case cmPolicies::OLD: - this->StoreResult(variable, this->Makefile->GetDefineFlagsCMP0059()); + StoreResult(status.GetMakefile(), variable, + status.GetMakefile().GetDefineFlagsCMP0059()); return true; case cmPolicies::NEW: case cmPolicies::REQUIRED_ALWAYS: @@ -90,12 +94,14 @@ bool cmGetDirectoryPropertyCommand::InitialPass( } prop = dir->GetProperty(*i); } - this->StoreResult(variable, prop); + StoreResult(status.GetMakefile(), variable, prop); return true; } -void cmGetDirectoryPropertyCommand::StoreResult(std::string const& variable, - const char* prop) +namespace { +void StoreResult(cmMakefile& makefile, std::string const& variable, + const char* prop) { - this->Makefile->AddDefinition(variable, prop ? prop : ""); + makefile.AddDefinition(variable, prop ? prop : ""); +} } diff --git a/Source/cmGetDirectoryPropertyCommand.h b/Source/cmGetDirectoryPropertyCommand.h index 63a198a..f356ea5 100644 --- a/Source/cmGetDirectoryPropertyCommand.h +++ b/Source/cmGetDirectoryPropertyCommand.h @@ -8,29 +8,9 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -class cmGetDirectoryPropertyCommand : public cmCommand -{ -public: - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmGetDirectoryPropertyCommand>(); - } - - /** - * This is called when the command is first encountered in - * the input file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; - -private: - void StoreResult(const std::string& variable, const char* prop); -}; +bool cmGetDirectoryPropertyCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmGetFilenameComponentCommand.cxx b/Source/cmGetFilenameComponentCommand.cxx index fc82535..7d91a75 100644 --- a/Source/cmGetFilenameComponentCommand.cxx +++ b/Source/cmGetFilenameComponentCommand.cxx @@ -2,26 +2,26 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmGetFilenameComponentCommand.h" +#include "cmExecutionStatus.h" #include "cmMakefile.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" -class cmExecutionStatus; - // cmGetFilenameComponentCommand -bool cmGetFilenameComponentCommand::InitialPass( - std::vector<std::string> const& args, cmExecutionStatus&) +bool cmGetFilenameComponentCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() < 3) { - this->SetError("called with incorrect number of arguments"); + status.SetError("called with incorrect number of arguments"); return false; } // Check and see if the value has been stored in the cache // already, if so use that value if (args.size() >= 4 && args.back() == "CACHE") { - const char* cacheValue = this->Makefile->GetDefinition(args.front()); - if (cacheValue && !cmSystemTools::IsNOTFOUND(cacheValue)) { + const char* cacheValue = status.GetMakefile().GetDefinition(args.front()); + if (cacheValue && !cmIsNOTFOUND(cacheValue)) { return true; } } @@ -32,7 +32,7 @@ bool cmGetFilenameComponentCommand::InitialPass( // Check the registry as the target application would view it. cmSystemTools::KeyWOW64 view = cmSystemTools::KeyWOW64_32; cmSystemTools::KeyWOW64 other_view = cmSystemTools::KeyWOW64_64; - if (this->Makefile->PlatformIs64Bit()) { + if (status.GetMakefile().PlatformIs64Bit()) { view = cmSystemTools::KeyWOW64_64; other_view = cmSystemTools::KeyWOW64_32; } @@ -64,7 +64,7 @@ bool cmGetFilenameComponentCommand::InitialPass( // First assume the path to the program was specified with no // arguments and with no quoting or escaping for spaces. // Only bother doing this if there is non-whitespace. - if (!cmSystemTools::TrimWhitespace(filename).empty()) { + if (!cmTrimWhitespace(filename).empty()) { result = cmSystemTools::FindProgram(filename); } @@ -96,7 +96,7 @@ bool cmGetFilenameComponentCommand::InitialPass( // If the path given is relative, evaluate it relative to the // current source directory unless the user passes a different // base directory. - std::string baseDir = this->Makefile->GetCurrentSourceDirectory(); + std::string baseDir = status.GetMakefile().GetCurrentSourceDirectory(); for (unsigned int i = 3; i < args.size(); ++i) { if (args[i] == "BASE_DIR") { ++i; @@ -113,24 +113,24 @@ bool cmGetFilenameComponentCommand::InitialPass( } } else { std::string err = "unknown component " + args[2]; - this->SetError(err); + status.SetError(err); return false; } if (args.size() >= 4 && args.back() == "CACHE") { if (!programArgs.empty() && !storeArgs.empty()) { - this->Makefile->AddCacheDefinition( + status.GetMakefile().AddCacheDefinition( storeArgs, programArgs.c_str(), "", args[2] == "PATH" ? cmStateEnums::FILEPATH : cmStateEnums::STRING); } - this->Makefile->AddCacheDefinition( + status.GetMakefile().AddCacheDefinition( args.front(), result.c_str(), "", args[2] == "PATH" ? cmStateEnums::FILEPATH : cmStateEnums::STRING); } else { if (!programArgs.empty() && !storeArgs.empty()) { - this->Makefile->AddDefinition(storeArgs, programArgs); + status.GetMakefile().AddDefinition(storeArgs, programArgs); } - this->Makefile->AddDefinition(args.front(), result); + status.GetMakefile().AddDefinition(args.front(), result); } return true; diff --git a/Source/cmGetFilenameComponentCommand.h b/Source/cmGetFilenameComponentCommand.h index 1780b96..db5293b 100644 --- a/Source/cmGetFilenameComponentCommand.h +++ b/Source/cmGetFilenameComponentCommand.h @@ -8,35 +8,15 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -/** \class cmGetFilenameComponentCommand +/** * \brief Get a specific component of a filename. * * cmGetFilenameComponentCommand is a utility command used to get the path, * name, extension or name without extension of a full filename. */ -class cmGetFilenameComponentCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmGetFilenameComponentCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; -}; +bool cmGetFilenameComponentCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmGetPropertyCommand.cxx b/Source/cmGetPropertyCommand.cxx index de462ed..e8e87e7 100644 --- a/Source/cmGetPropertyCommand.cxx +++ b/Source/cmGetPropertyCommand.cxx @@ -4,6 +4,7 @@ #include <sstream> +#include "cmExecutionStatus.h" #include "cmGlobalGenerator.h" #include "cmInstalledFile.h" #include "cmListFileCache.h" @@ -14,30 +15,70 @@ #include "cmPropertyDefinition.h" #include "cmSourceFile.h" #include "cmState.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmTarget.h" #include "cmTargetPropertyComputer.h" #include "cmTest.h" #include "cmake.h" -class cmExecutionStatus; class cmMessenger; -cmGetPropertyCommand::cmGetPropertyCommand() +namespace { +enum OutType { - this->InfoType = OutValue; + OutValue, + OutDefined, + OutBriefDoc, + OutFullDoc, + OutSet +}; + +// Implementation of result storage. +bool StoreResult(OutType infoType, cmMakefile& makefile, + const std::string& variable, const char* value); + +// Implementation of each property type. +bool HandleGlobalMode(cmExecutionStatus& status, const std::string& name, + OutType infoType, const std::string& variable, + const std::string& propertyName); +bool HandleDirectoryMode(cmExecutionStatus& status, const std::string& name, + OutType infoType, const std::string& variable, + const std::string& propertyName); +bool HandleTargetMode(cmExecutionStatus& status, const std::string& name, + OutType infoType, const std::string& variable, + const std::string& propertyName); +bool HandleSourceMode(cmExecutionStatus& status, const std::string& name, + OutType infoType, const std::string& variable, + const std::string& propertyName); +bool HandleTestMode(cmExecutionStatus& status, const std::string& name, + OutType infoType, const std::string& variable, + const std::string& propertyName); +bool HandleVariableMode(cmExecutionStatus& status, const std::string& name, + OutType infoType, const std::string& variable, + const std::string& propertyName); +bool HandleCacheMode(cmExecutionStatus& status, const std::string& name, + OutType infoType, const std::string& variable, + const std::string& propertyName); +bool HandleInstallMode(cmExecutionStatus& status, const std::string& name, + OutType infoType, const std::string& variable, + const std::string& propertyName); } -bool cmGetPropertyCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus&) +bool cmGetPropertyCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { + OutType infoType = OutValue; if (args.size() < 3) { - this->SetError("called with incorrect number of arguments"); + status.SetError("called with incorrect number of arguments"); return false; } // The cmake variable in which to store the result. - this->Variable = args[0]; + const std::string variable = args[0]; + + std::string name; + std::string propertyName; // Get the scope from which to get the property. cmProperty::ScopeType scope; @@ -62,7 +103,7 @@ bool cmGetPropertyCommand::InitialPass(std::vector<std::string> const& args, e << "given invalid scope " << args[1] << ". " << "Valid scopes are " << "GLOBAL, DIRECTORY, TARGET, SOURCE, TEST, VARIABLE, CACHE, INSTALL."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } @@ -80,86 +121,92 @@ bool cmGetPropertyCommand::InitialPass(std::vector<std::string> const& args, doing = DoingProperty; } else if (args[i] == "BRIEF_DOCS") { doing = DoingNone; - this->InfoType = OutBriefDoc; + infoType = OutBriefDoc; } else if (args[i] == "FULL_DOCS") { doing = DoingNone; - this->InfoType = OutFullDoc; + infoType = OutFullDoc; } else if (args[i] == "SET") { doing = DoingNone; - this->InfoType = OutSet; + infoType = OutSet; } else if (args[i] == "DEFINED") { doing = DoingNone; - this->InfoType = OutDefined; + infoType = OutDefined; } else if (doing == DoingName) { doing = DoingNone; - this->Name = args[i]; + name = args[i]; } else if (doing == DoingProperty) { doing = DoingNone; - this->PropertyName = args[i]; + propertyName = args[i]; } else { std::ostringstream e; e << "given invalid argument \"" << args[i] << "\"."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } } // Make sure a property name was found. - if (this->PropertyName.empty()) { - this->SetError("not given a PROPERTY <name> argument."); + if (propertyName.empty()) { + status.SetError("not given a PROPERTY <name> argument."); return false; } // Compute requested output. - if (this->InfoType == OutBriefDoc) { + if (infoType == OutBriefDoc) { // Lookup brief documentation. std::string output; if (cmPropertyDefinition const* def = - this->Makefile->GetState()->GetPropertyDefinition(this->PropertyName, - scope)) { + status.GetMakefile().GetState()->GetPropertyDefinition(propertyName, + scope)) { output = def->GetShortDescription(); } else { output = "NOTFOUND"; } - this->Makefile->AddDefinition(this->Variable, output); - } else if (this->InfoType == OutFullDoc) { + status.GetMakefile().AddDefinition(variable, output); + } else if (infoType == OutFullDoc) { // Lookup full documentation. std::string output; if (cmPropertyDefinition const* def = - this->Makefile->GetState()->GetPropertyDefinition(this->PropertyName, - scope)) { + status.GetMakefile().GetState()->GetPropertyDefinition(propertyName, + scope)) { output = def->GetFullDescription(); } else { output = "NOTFOUND"; } - this->Makefile->AddDefinition(this->Variable, output); - } else if (this->InfoType == OutDefined) { + status.GetMakefile().AddDefinition(variable, output); + } else if (infoType == OutDefined) { // Lookup if the property is defined - if (this->Makefile->GetState()->GetPropertyDefinition(this->PropertyName, - scope)) { - this->Makefile->AddDefinition(this->Variable, "1"); + if (status.GetMakefile().GetState()->GetPropertyDefinition(propertyName, + scope)) { + status.GetMakefile().AddDefinition(variable, "1"); } else { - this->Makefile->AddDefinition(this->Variable, "0"); + status.GetMakefile().AddDefinition(variable, "0"); } } else { // Dispatch property getting. switch (scope) { case cmProperty::GLOBAL: - return this->HandleGlobalMode(); + return HandleGlobalMode(status, name, infoType, variable, + propertyName); case cmProperty::DIRECTORY: - return this->HandleDirectoryMode(); + return HandleDirectoryMode(status, name, infoType, variable, + propertyName); case cmProperty::TARGET: - return this->HandleTargetMode(); + return HandleTargetMode(status, name, infoType, variable, + propertyName); case cmProperty::SOURCE_FILE: - return this->HandleSourceMode(); + return HandleSourceMode(status, name, infoType, variable, + propertyName); case cmProperty::TEST: - return this->HandleTestMode(); + return HandleTestMode(status, name, infoType, variable, propertyName); case cmProperty::VARIABLE: - return this->HandleVariableMode(); + return HandleVariableMode(status, name, infoType, variable, + propertyName); case cmProperty::CACHE: - return this->HandleCacheMode(); + return HandleCacheMode(status, name, infoType, variable, propertyName); case cmProperty::INSTALL: - return this->HandleInstallMode(); + return HandleInstallMode(status, name, infoType, variable, + propertyName); case cmProperty::CACHED_VARIABLE: break; // should never happen @@ -169,58 +216,64 @@ bool cmGetPropertyCommand::InitialPass(std::vector<std::string> const& args, return true; } -bool cmGetPropertyCommand::StoreResult(const char* value) +namespace { + +bool StoreResult(OutType infoType, cmMakefile& makefile, + const std::string& variable, const char* value) { - if (this->InfoType == OutSet) { - this->Makefile->AddDefinition(this->Variable, value ? "1" : "0"); - } else // if(this->InfoType == OutValue) + if (infoType == OutSet) { + makefile.AddDefinition(variable, value ? "1" : "0"); + } else // if(infoType == OutValue) { if (value) { - this->Makefile->AddDefinition(this->Variable, value); + makefile.AddDefinition(variable, value); } else { - this->Makefile->RemoveDefinition(this->Variable); + makefile.RemoveDefinition(variable); } } return true; } -bool cmGetPropertyCommand::HandleGlobalMode() +bool HandleGlobalMode(cmExecutionStatus& status, const std::string& name, + OutType infoType, const std::string& variable, + const std::string& propertyName) { - if (!this->Name.empty()) { - this->SetError("given name for GLOBAL scope."); + if (!name.empty()) { + status.SetError("given name for GLOBAL scope."); return false; } // Get the property. - cmake* cm = this->Makefile->GetCMakeInstance(); - return this->StoreResult( - cm->GetState()->GetGlobalProperty(this->PropertyName)); + cmake* cm = status.GetMakefile().GetCMakeInstance(); + return StoreResult(infoType, status.GetMakefile(), variable, + cm->GetState()->GetGlobalProperty(propertyName)); } -bool cmGetPropertyCommand::HandleDirectoryMode() +bool HandleDirectoryMode(cmExecutionStatus& status, const std::string& name, + OutType infoType, const std::string& variable, + const std::string& propertyName) { // Default to the current directory. - cmMakefile* mf = this->Makefile; + cmMakefile* mf = &status.GetMakefile(); // Lookup the directory if given. - if (!this->Name.empty()) { + if (!name.empty()) { // Construct the directory name. Interpret relative paths with // respect to the current directory. - std::string dir = this->Name; + std::string dir = name; if (!cmSystemTools::FileIsFullPath(dir)) { - dir = this->Makefile->GetCurrentSourceDirectory(); - dir += "/"; - dir += this->Name; + dir = + cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', name); } // The local generators are associated with collapsed paths. dir = cmSystemTools::CollapseFullPath(dir); // Lookup the generator. - mf = this->Makefile->GetGlobalGenerator()->FindMakefile(dir); + mf = status.GetMakefile().GetGlobalGenerator()->FindMakefile(dir); if (!mf) { // Could not find the directory. - this->SetError( + status.SetError( "DIRECTORY scope provided but requested directory was not found. " "This could be because the directory argument was invalid or, " "it is valid but has not been processed yet."); @@ -228,14 +281,15 @@ bool cmGetPropertyCommand::HandleDirectoryMode() } } - if (this->PropertyName == "DEFINITIONS") { + if (propertyName == "DEFINITIONS") { switch (mf->GetPolicyStatus(cmPolicies::CMP0059)) { case cmPolicies::WARN: mf->IssueMessage(MessageType::AUTHOR_WARNING, cmPolicies::GetPolicyWarning(cmPolicies::CMP0059)); CM_FALLTHROUGH; case cmPolicies::OLD: - return this->StoreResult(mf->GetDefineFlagsCMP0059()); + return StoreResult(infoType, status.GetMakefile(), variable, + mf->GetDefineFlagsCMP0059()); case cmPolicies::NEW: case cmPolicies::REQUIRED_ALWAYS: case cmPolicies::REQUIRED_IF_USED: @@ -244,124 +298,142 @@ bool cmGetPropertyCommand::HandleDirectoryMode() } // Get the property. - return this->StoreResult(mf->GetProperty(this->PropertyName)); + return StoreResult(infoType, status.GetMakefile(), variable, + mf->GetProperty(propertyName)); } -bool cmGetPropertyCommand::HandleTargetMode() +bool HandleTargetMode(cmExecutionStatus& status, const std::string& name, + OutType infoType, const std::string& variable, + const std::string& propertyName) { - if (this->Name.empty()) { - this->SetError("not given name for TARGET scope."); + if (name.empty()) { + status.SetError("not given name for TARGET scope."); return false; } - if (cmTarget* target = this->Makefile->FindTargetToUse(this->Name)) { - if (this->PropertyName == "ALIASED_TARGET") { - if (this->Makefile->IsAlias(this->Name)) { - return this->StoreResult(target->GetName().c_str()); + if (cmTarget* target = status.GetMakefile().FindTargetToUse(name)) { + if (propertyName == "ALIASED_TARGET") { + if (status.GetMakefile().IsAlias(name)) { + return StoreResult(infoType, status.GetMakefile(), variable, + target->GetName().c_str()); } - return this->StoreResult(nullptr); + return StoreResult(infoType, status.GetMakefile(), variable, nullptr); } const char* prop_cstr = nullptr; - cmListFileBacktrace bt = this->Makefile->GetBacktrace(); - cmMessenger* messenger = this->Makefile->GetMessenger(); + cmListFileBacktrace bt = status.GetMakefile().GetBacktrace(); + cmMessenger* messenger = status.GetMakefile().GetMessenger(); if (cmTargetPropertyComputer::PassesWhitelist( - target->GetType(), this->PropertyName, messenger, bt)) { - prop_cstr = - target->GetComputedProperty(this->PropertyName, messenger, bt); + target->GetType(), propertyName, messenger, bt)) { + prop_cstr = target->GetComputedProperty(propertyName, messenger, bt); if (!prop_cstr) { - prop_cstr = target->GetProperty(this->PropertyName); + prop_cstr = target->GetProperty(propertyName); } } - return this->StoreResult(prop_cstr); + return StoreResult(infoType, status.GetMakefile(), variable, prop_cstr); } std::ostringstream e; - e << "could not find TARGET " << this->Name + e << "could not find TARGET " << name << ". Perhaps it has not yet been created."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } -bool cmGetPropertyCommand::HandleSourceMode() +bool HandleSourceMode(cmExecutionStatus& status, const std::string& name, + OutType infoType, const std::string& variable, + const std::string& propertyName) { - if (this->Name.empty()) { - this->SetError("not given name for SOURCE scope."); + if (name.empty()) { + status.SetError("not given name for SOURCE scope."); return false; } // Get the source file. - if (cmSourceFile* sf = this->Makefile->GetOrCreateSource(this->Name)) { - return this->StoreResult(sf->GetPropertyForUser(this->PropertyName)); + if (cmSourceFile* sf = status.GetMakefile().GetOrCreateSource(name)) { + return StoreResult(infoType, status.GetMakefile(), variable, + sf->GetPropertyForUser(propertyName)); } std::ostringstream e; - e << "given SOURCE name that could not be found or created: " << this->Name; - this->SetError(e.str()); + e << "given SOURCE name that could not be found or created: " << name; + status.SetError(e.str()); return false; } -bool cmGetPropertyCommand::HandleTestMode() +bool HandleTestMode(cmExecutionStatus& status, const std::string& name, + OutType infoType, const std::string& variable, + const std::string& propertyName) { - if (this->Name.empty()) { - this->SetError("not given name for TEST scope."); + if (name.empty()) { + status.SetError("not given name for TEST scope."); return false; } // Loop over all tests looking for matching names. - if (cmTest* test = this->Makefile->GetTest(this->Name)) { - return this->StoreResult(test->GetProperty(this->PropertyName)); + if (cmTest* test = status.GetMakefile().GetTest(name)) { + return StoreResult(infoType, status.GetMakefile(), variable, + test->GetProperty(propertyName)); } // If not found it is an error. std::ostringstream e; - e << "given TEST name that does not exist: " << this->Name; - this->SetError(e.str()); + e << "given TEST name that does not exist: " << name; + status.SetError(e.str()); return false; } -bool cmGetPropertyCommand::HandleVariableMode() +bool HandleVariableMode(cmExecutionStatus& status, const std::string& name, + OutType infoType, const std::string& variable, + const std::string& propertyName) { - if (!this->Name.empty()) { - this->SetError("given name for VARIABLE scope."); + if (!name.empty()) { + status.SetError("given name for VARIABLE scope."); return false; } - return this->StoreResult(this->Makefile->GetDefinition(this->PropertyName)); + return StoreResult(infoType, status.GetMakefile(), variable, + status.GetMakefile().GetDefinition(propertyName)); } -bool cmGetPropertyCommand::HandleCacheMode() +bool HandleCacheMode(cmExecutionStatus& status, const std::string& name, + OutType infoType, const std::string& variable, + const std::string& propertyName) { - if (this->Name.empty()) { - this->SetError("not given name for CACHE scope."); + if (name.empty()) { + status.SetError("not given name for CACHE scope."); return false; } const char* value = nullptr; - if (this->Makefile->GetState()->GetCacheEntryValue(this->Name)) { - value = this->Makefile->GetState()->GetCacheEntryProperty( - this->Name, this->PropertyName); + if (status.GetMakefile().GetState()->GetCacheEntryValue(name)) { + value = status.GetMakefile().GetState()->GetCacheEntryProperty( + name, propertyName); } - this->StoreResult(value); + StoreResult(infoType, status.GetMakefile(), variable, value); return true; } -bool cmGetPropertyCommand::HandleInstallMode() +bool HandleInstallMode(cmExecutionStatus& status, const std::string& name, + OutType infoType, const std::string& variable, + const std::string& propertyName) { - if (this->Name.empty()) { - this->SetError("not given name for INSTALL scope."); + if (name.empty()) { + status.SetError("not given name for INSTALL scope."); return false; } // Get the installed file. - cmake* cm = this->Makefile->GetCMakeInstance(); + cmake* cm = status.GetMakefile().GetCMakeInstance(); if (cmInstalledFile* file = - cm->GetOrCreateInstalledFile(this->Makefile, this->Name)) { + cm->GetOrCreateInstalledFile(&status.GetMakefile(), name)) { std::string value; - bool isSet = file->GetProperty(this->PropertyName, value); + bool isSet = file->GetProperty(propertyName, value); - return this->StoreResult(isSet ? value.c_str() : nullptr); + return StoreResult(infoType, status.GetMakefile(), variable, + isSet ? value.c_str() : nullptr); } std::ostringstream e; - e << "given INSTALL name that could not be found or created: " << this->Name; - this->SetError(e.str()); + e << "given INSTALL name that could not be found or created: " << name; + status.SetError(e.str()); return false; } +} diff --git a/Source/cmGetPropertyCommand.h b/Source/cmGetPropertyCommand.h index 50e4014..cc600f4 100644 --- a/Source/cmGetPropertyCommand.h +++ b/Source/cmGetPropertyCommand.h @@ -8,55 +8,9 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -class cmGetPropertyCommand : public cmCommand -{ -public: - cmGetPropertyCommand(); - - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmGetPropertyCommand>(); - } - - /** - * This is called when the command is first encountered in - * the input file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; - -private: - enum OutType - { - OutValue, - OutDefined, - OutBriefDoc, - OutFullDoc, - OutSet - }; - std::string Variable; - std::string Name; - std::string PropertyName; - OutType InfoType; - - // Implementation of result storage. - bool StoreResult(const char* value); - - // Implementation of each property type. - bool HandleGlobalMode(); - bool HandleDirectoryMode(); - bool HandleTargetMode(); - bool HandleSourceMode(); - bool HandleTestMode(); - bool HandleVariableMode(); - bool HandleCacheMode(); - bool HandleInstallMode(); -}; +bool cmGetPropertyCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmGhsMultiTargetGenerator.cxx b/Source/cmGhsMultiTargetGenerator.cxx index 997595b..26fc226 100644 --- a/Source/cmGhsMultiTargetGenerator.cxx +++ b/Source/cmGhsMultiTargetGenerator.cxx @@ -18,6 +18,7 @@ #include "cmStateDirectory.h" #include "cmStateSnapshot.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmTarget.h" @@ -74,8 +75,8 @@ void cmGhsMultiTargetGenerator::Generate() break; } case cmStateEnums::SHARED_LIBRARY: { - std::string msg = "add_library(<name> SHARED ...) not supported: "; - msg += this->Name; + std::string msg = + cmStrCat("add_library(<name> SHARED ...) not supported: ", this->Name); cmSystemTools::Message(msg); return; } @@ -86,8 +87,8 @@ void cmGhsMultiTargetGenerator::Generate() break; } case cmStateEnums::MODULE_LIBRARY: { - std::string msg = "add_library(<name> MODULE ...) not supported: "; - msg += this->Name; + std::string msg = + cmStrCat("add_library(<name> MODULE ...) not supported: ", this->Name); cmSystemTools::Message(msg); return; } @@ -122,10 +123,9 @@ void cmGhsMultiTargetGenerator::Generate() void cmGhsMultiTargetGenerator::GenerateTarget() { // Open the target file in copy-if-different mode. - std::string fproj = this->LocalGenerator->GetCurrentBinaryDirectory(); - fproj += "/"; - fproj += this->Name; - fproj += cmGlobalGhsMultiGenerator::FILE_EXTENSION; + std::string fproj = + cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(), '/', + this->Name, cmGlobalGhsMultiGenerator::FILE_EXTENSION); cmGeneratedFileStream fout(fproj); fout.SetCopyIfDifferent(true); @@ -346,12 +346,11 @@ void cmGhsMultiTargetGenerator::WriteBuildEventsHelper( for (cmCustomCommand const& cc : ccv) { cmCustomCommandGenerator ccg(cc, this->ConfigName, this->LocalGenerator); // Open the filestream for this custom command - std::string fname = this->LocalGenerator->GetCurrentBinaryDirectory(); - fname += - "/" + this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget); - fname += "/" + this->Name + "_" + name; - fname += std::to_string(cmdcount++); - fname += this->CmdWindowsShell ? ".bat" : ".sh"; + std::string fname = + cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(), '/', + this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget), + '/', this->Name, '_', name, cmdcount++, + this->CmdWindowsShell ? ".bat" : ".sh"); cmGeneratedFileStream f(fname); f.SetCopyIfDifferent(true); this->WriteCustomCommandsHelper(f, ccg); @@ -394,8 +393,7 @@ void cmGhsMultiTargetGenerator::WriteCustomCommandsHelper( // Echo the custom command's comment text. const char* comment = ccg.GetComment(); if (comment && *comment) { - std::string echocmd = "echo "; - echocmd += comment; + std::string echocmd = cmStrCat("echo ", comment); cmdLines.push_back(std::move(echocmd)); } @@ -442,12 +440,12 @@ void cmGhsMultiTargetGenerator::WriteCustomCommandsHelper( // This command was specified as a path to a file in the // current directory. Add a leading "./" so it can run // without the current directory being in the search path. - cmd = "./" + cmd; + cmd = cmStrCat("./", cmd); } cmd = this->LocalGenerator->ConvertToOutputFormat( cmd, cmOutputConverter::SHELL); if (useCall) { - cmd = "call " + cmd; + cmd = cmStrCat("call ", cmd); } ccg.AppendArguments(c, cmd); cmdLines.push_back(std::move(cmd)); @@ -468,7 +466,7 @@ void cmGhsMultiTargetGenerator::WriteSourceProperty( const char* prop = sf->GetProperty(propName); if (prop) { std::vector<std::string> list; - cmSystemTools::ExpandListArgument(prop, list); + cmExpandList(prop, list); for (auto& p : list) { fout << " " << propFlag << p << std::endl; } @@ -560,24 +558,19 @@ void cmGhsMultiTargetGenerator::WriteSources(std::ostream& fout_proj) for (auto& sg : groupFilesList) { std::ostream* fout; bool useProjectFile = - cmSystemTools::IsOn( - this->GeneratorTarget->GetProperty("GHS_NO_SOURCE_GROUP_FILE")) || - cmSystemTools::IsOn( - this->Makefile->GetDefinition("CMAKE_GHS_NO_SOURCE_GROUP_FILE")); + cmIsOn(this->GeneratorTarget->GetProperty("GHS_NO_SOURCE_GROUP_FILE")) || + cmIsOn(this->Makefile->GetDefinition("CMAKE_GHS_NO_SOURCE_GROUP_FILE")); if (useProjectFile || sg.empty()) { fout = &fout_proj; } else { // Open the filestream in copy-if-different mode. std::string gname = sg; cmsys::SystemTools::ReplaceString(gname, "\\", "_"); - std::string lpath = - this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget); - lpath += "/"; - lpath += gname; - lpath += cmGlobalGhsMultiGenerator::FILE_EXTENSION; - std::string fpath = this->LocalGenerator->GetCurrentBinaryDirectory(); - fpath += "/"; - fpath += lpath; + std::string lpath = cmStrCat( + this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget), '/', + gname, cmGlobalGhsMultiGenerator::FILE_EXTENSION); + std::string fpath = cmStrCat( + this->LocalGenerator->GetCurrentBinaryDirectory(), '/', lpath); cmGeneratedFileStream* f = new cmGeneratedFileStream(fpath); f->SetCopyIfDifferent(true); gfiles.push_back(f); @@ -669,14 +662,12 @@ void cmGhsMultiTargetGenerator::WriteSources(std::ostream& fout_proj) this->LocalGenerator); // Open the filestream for this custom command - std::string fname = - this->LocalGenerator->GetCurrentBinaryDirectory(); - fname += "/" + - this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget); - fname += "/" + this->Name + "_cc"; - fname += std::to_string(cmdcount++) + "_"; - fname += (sf->GetLocation()).GetName(); - fname += this->CmdWindowsShell ? ".bat" : ".sh"; + std::string fname = cmStrCat( + this->LocalGenerator->GetCurrentBinaryDirectory(), '/', + this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget), + '/', this->Name, "_cc", cmdcount++, '_', + (sf->GetLocation()).GetName(), + this->CmdWindowsShell ? ".bat" : ".sh"); cmGeneratedFileStream f(fname); f.SetCopyIfDifferent(true); this->WriteCustomCommandsHelper(f, ccg); @@ -739,8 +730,7 @@ bool cmGhsMultiTargetGenerator::DetermineIfIntegrityApp() { const char* p = this->GeneratorTarget->GetProperty("ghs_integrity_app"); if (p) { - return cmSystemTools::IsOn( - this->GeneratorTarget->GetProperty("ghs_integrity_app")); + return cmIsOn(this->GeneratorTarget->GetProperty("ghs_integrity_app")); } std::vector<cmSourceFile*> sources; this->GeneratorTarget->GetSourceFiles(sources, this->ConfigName); diff --git a/Source/cmGlobVerificationManager.cxx b/Source/cmGlobVerificationManager.cxx index 9fb4170..72451b2 100644 --- a/Source/cmGlobVerificationManager.cxx +++ b/Source/cmGlobVerificationManager.cxx @@ -7,6 +7,7 @@ #include "cmGeneratedFileStream.h" #include "cmListFileCache.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmVersion.h" @@ -16,8 +17,7 @@ bool cmGlobVerificationManager::SaveVerificationScript(const std::string& path) return true; } - std::string scriptFile = path; - scriptFile += "/CMakeFiles"; + std::string scriptFile = cmStrCat(path, "/CMakeFiles"); std::string stampFile = scriptFile; cmSystemTools::MakeDirectory(scriptFile); scriptFile += "/VerifyGlobs.cmake"; diff --git a/Source/cmGlobalGenerator.cxx b/Source/cmGlobalGenerator.cxx index 88da5eb..e145ad4 100644 --- a/Source/cmGlobalGenerator.cxx +++ b/Source/cmGlobalGenerator.cxx @@ -44,7 +44,7 @@ #include "cmWorkingDirectory.h" #include "cmake.h" -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) # include "cmCryptoHash.h" # include "cmQtAutoGenGlobalInitializer.h" # include "cm_jsoncpp_value.h" @@ -114,7 +114,7 @@ cmGlobalGenerator::~cmGlobalGenerator() this->ClearGeneratorMembers(); } -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) Json::Value cmGlobalGenerator::GetJson() const { Json::Value generator = Json::objectValue; @@ -186,15 +186,15 @@ std::string cmGlobalGenerator::SelectMakeProgram( const std::string& inMakeProgram, const std::string& makeDefault) const { std::string makeProgram = inMakeProgram; - if (cmSystemTools::IsOff(makeProgram)) { + if (cmIsOff(makeProgram)) { const char* makeProgramCSTR = this->CMakeInstance->GetCacheDefinition("CMAKE_MAKE_PROGRAM"); - if (cmSystemTools::IsOff(makeProgramCSTR)) { + if (cmIsOff(makeProgramCSTR)) { makeProgram = makeDefault; } else { makeProgram = makeProgramCSTR; } - if (cmSystemTools::IsOff(makeProgram) && !makeProgram.empty()) { + if (cmIsOff(makeProgram) && !makeProgram.empty()) { makeProgram = "CMAKE_MAKE_PROGRAM-NOTFOUND"; } } @@ -205,9 +205,7 @@ void cmGlobalGenerator::ResolveLanguageCompiler(const std::string& lang, cmMakefile* mf, bool optional) const { - std::string langComp = "CMAKE_"; - langComp += lang; - langComp += "_COMPILER"; + std::string langComp = cmStrCat("CMAKE_", lang, "_COMPILER"); if (!mf->GetDefinition(langComp)) { if (!optional) { @@ -300,7 +298,7 @@ bool cmGlobalGenerator::CheckTargetsForMissingSources() const if (target->GetType() == cmStateEnums::TargetType::GLOBAL_TARGET || target->GetType() == cmStateEnums::TargetType::INTERFACE_LIBRARY || target->GetType() == cmStateEnums::TargetType::UTILITY || - cmSystemTools::IsOn(target->GetProperty("ghs_integrity_app"))) { + cmIsOn(target->GetProperty("ghs_integrity_app"))) { continue; } @@ -368,8 +366,7 @@ bool cmGlobalGenerator::IsExportedTargetsFile( if (it == this->BuildExportSets.end()) { return false; } - return this->BuildExportExportSets.find(filename) == - this->BuildExportExportSets.end(); + return !cmContains(this->BuildExportExportSets, filename); } // Find the make program for the generator, required for try compiles @@ -382,14 +379,14 @@ bool cmGlobalGenerator::FindMakeProgram(cmMakefile* mf) return false; } if (!mf->GetDefinition("CMAKE_MAKE_PROGRAM") || - cmSystemTools::IsOff(mf->GetDefinition("CMAKE_MAKE_PROGRAM"))) { + cmIsOff(mf->GetDefinition("CMAKE_MAKE_PROGRAM"))) { std::string setMakeProgram = mf->GetModulesFile(this->FindMakeProgramFile); if (!setMakeProgram.empty()) { mf->ReadListFile(setMakeProgram); } } if (!mf->GetDefinition("CMAKE_MAKE_PROGRAM") || - cmSystemTools::IsOff(mf->GetDefinition("CMAKE_MAKE_PROGRAM"))) { + cmIsOff(mf->GetDefinition("CMAKE_MAKE_PROGRAM"))) { std::ostringstream err; err << "CMake was unable to find a build program corresponding to \"" << this->GetName() << "\". CMAKE_MAKE_PROGRAM is not set. You " @@ -409,9 +406,7 @@ bool cmGlobalGenerator::FindMakeProgram(cmMakefile* mf) std::string saveFile = file; cmSystemTools::GetShortPath(makeProgram, makeProgram); cmSystemTools::SplitProgramPath(makeProgram, dir, file); - makeProgram = dir; - makeProgram += "/"; - makeProgram += saveFile; + makeProgram = cmStrCat(dir, '/', saveFile); mf->AddCacheDefinition("CMAKE_MAKE_PROGRAM", makeProgram.c_str(), "make program", cmStateEnums::FILEPATH); } @@ -497,7 +492,7 @@ void cmGlobalGenerator::EnableLanguage( if (lang == "NONE") { this->SetLanguageEnabled("NONE", mf); } else { - if (this->LanguagesReady.find(lang) == this->LanguagesReady.end()) { + if (!cmContains(this->LanguagesReady, lang)) { std::ostringstream e; e << "The test project needs language " << lang << " which is not enabled."; @@ -513,8 +508,8 @@ void cmGlobalGenerator::EnableLanguage( bool fatalError = false; mf->AddDefinitionBool("RUN_CONFIGURE", true); - std::string rootBin = this->CMakeInstance->GetHomeOutputDirectory(); - rootBin += "/CMakeFiles"; + std::string rootBin = + cmStrCat(this->CMakeInstance->GetHomeOutputDirectory(), "/CMakeFiles"); // If the configuration files path has been set, // then we are in a try compile and need to copy the enable language @@ -522,7 +517,7 @@ void cmGlobalGenerator::EnableLanguage( if (!this->ConfiguredFilesPath.empty()) { rootBin = this->ConfiguredFilesPath; } - rootBin += "/"; + rootBin += '/'; rootBin += cmVersion::GetCMakeVersion(); // set the dir for parent files so they can be used by modules @@ -593,8 +588,7 @@ void cmGlobalGenerator::EnableLanguage( mf->ReadListFile(systemFile); // load the CMakeSystem.cmake from the binary directory // this file is configured by the CMakeDetermineSystem.cmake file - fpath = rootBin; - fpath += "/CMakeSystem.cmake"; + fpath = cmStrCat(rootBin, "/CMakeSystem.cmake"); mf->ReadListFile(fpath); } @@ -660,14 +654,9 @@ void cmGlobalGenerator::EnableLanguage( this->SetLanguageEnabled("NONE", mf); continue; } - std::string loadedLang = "CMAKE_"; - loadedLang += lang; - loadedLang += "_COMPILER_LOADED"; + std::string loadedLang = cmStrCat("CMAKE_", lang, "_COMPILER_LOADED"); if (!mf->GetDefinition(loadedLang)) { - fpath = rootBin; - fpath += "/CMake"; - fpath += lang; - fpath += "Compiler.cmake"; + fpath = cmStrCat(rootBin, "/CMake", lang, "Compiler.cmake"); // If the existing build tree was already configured with this // version of CMake then try to load the configured file first @@ -694,9 +683,8 @@ void cmGlobalGenerator::EnableLanguage( } // if the CMake(LANG)Compiler.cmake file was not found then // load CMakeDetermine(LANG)Compiler.cmake - std::string determineCompiler = "CMakeDetermine"; - determineCompiler += lang; - determineCompiler += "Compiler.cmake"; + std::string determineCompiler = + cmStrCat("CMakeDetermine", lang, "Compiler.cmake"); std::string determineFile = mf->GetModulesFile(determineCompiler); if (!mf->ReadListFile(determineFile)) { cmSystemTools::Error("Could not find cmake module file: " + @@ -712,27 +700,19 @@ void cmGlobalGenerator::EnableLanguage( // put ${CMake_(LANG)_COMPILER_ENV_VAR}=${CMAKE_(LANG)_COMPILER // into the environment, in case user scripts want to run // configure, or sub cmakes - std::string compilerName = "CMAKE_"; - compilerName += lang; - compilerName += "_COMPILER"; - std::string compilerEnv = "CMAKE_"; - compilerEnv += lang; - compilerEnv += "_COMPILER_ENV_VAR"; + std::string compilerName = cmStrCat("CMAKE_", lang, "_COMPILER"); + std::string compilerEnv = + cmStrCat("CMAKE_", lang, "_COMPILER_ENV_VAR"); const std::string& envVar = mf->GetRequiredDefinition(compilerEnv); const std::string& envVarValue = mf->GetRequiredDefinition(compilerName); - std::string env = envVar; - env += "="; - env += envVarValue; + std::string env = cmStrCat(envVar, '=', envVarValue); cmSystemTools::PutEnv(env); } // if determineLanguage was called then load the file it // configures CMake(LANG)Compiler.cmake - fpath = rootBin; - fpath += "/CMake"; - fpath += lang; - fpath += "Compiler.cmake"; + fpath = cmStrCat(rootBin, "/CMake", lang, "Compiler.cmake"); if (!mf->ReadListFile(fpath)) { cmSystemTools::Error("Could not find cmake module file: " + fpath); } @@ -763,16 +743,11 @@ void cmGlobalGenerator::EnableLanguage( } // Check that the compiler was found. - std::string compilerName = "CMAKE_"; - compilerName += lang; - compilerName += "_COMPILER"; - std::string compilerEnv = "CMAKE_"; - compilerEnv += lang; - compilerEnv += "_COMPILER_ENV_VAR"; + std::string compilerName = cmStrCat("CMAKE_", lang, "_COMPILER"); + std::string compilerEnv = cmStrCat("CMAKE_", lang, "_COMPILER_ENV_VAR"); std::ostringstream noCompiler; const char* compilerFile = mf->GetDefinition(compilerName); - if (!compilerFile || !*compilerFile || - cmSystemTools::IsNOTFOUND(compilerFile)) { + if (!compilerFile || !*compilerFile || cmIsNOTFOUND(compilerFile)) { /* clang-format off */ noCompiler << "No " << compilerName << " could be found.\n" @@ -803,10 +778,8 @@ void cmGlobalGenerator::EnableLanguage( if (!optional) { // The compiler was not found and it is not optional. Remove // CMake(LANG)Compiler.cmake so we try again next time CMake runs. - std::string compilerLangFile = rootBin; - compilerLangFile += "/CMake"; - compilerLangFile += lang; - compilerLangFile += "Compiler.cmake"; + std::string compilerLangFile = + cmStrCat(rootBin, "/CMake", lang, "Compiler.cmake"); cmSystemTools::RemoveFile(compilerLangFile); if (!this->CMakeInstance->GetIsInTryCompile()) { this->PrintCompilerAdvice(noCompiler, lang, @@ -817,13 +790,10 @@ void cmGlobalGenerator::EnableLanguage( } } - std::string langLoadedVar = "CMAKE_"; - langLoadedVar += lang; - langLoadedVar += "_INFORMATION_LOADED"; + std::string langLoadedVar = + cmStrCat("CMAKE_", lang, "_INFORMATION_LOADED"); if (!mf->GetDefinition(langLoadedVar)) { - fpath = "CMake"; - fpath += lang; - fpath += "Information.cmake"; + fpath = cmStrCat("CMake", lang, "Information.cmake"); std::string informationFile = mf->GetModulesFile(fpath); if (informationFile.empty()) { cmSystemTools::Error("Could not find cmake module file: " + fpath); @@ -844,33 +814,27 @@ void cmGlobalGenerator::EnableLanguage( // If the language is untested then test it now with a try compile. if (needTestLanguage[lang]) { if (!this->CMakeInstance->GetIsInTryCompile()) { - std::string testLang = "CMakeTest"; - testLang += lang; - testLang += "Compiler.cmake"; + std::string testLang = cmStrCat("CMakeTest", lang, "Compiler.cmake"); std::string ifpath = mf->GetModulesFile(testLang); if (!mf->ReadListFile(ifpath)) { cmSystemTools::Error("Could not find cmake module file: " + testLang); } - std::string compilerWorks = "CMAKE_"; - compilerWorks += lang; - compilerWorks += "_COMPILER_WORKS"; + std::string compilerWorks = + cmStrCat("CMAKE_", lang, "_COMPILER_WORKS"); // if the compiler did not work, then remove the // CMake(LANG)Compiler.cmake file so that it will get tested the // next time cmake is run if (!mf->IsOn(compilerWorks)) { - std::string compilerLangFile = rootBin; - compilerLangFile += "/CMake"; - compilerLangFile += lang; - compilerLangFile += "Compiler.cmake"; + std::string compilerLangFile = + cmStrCat(rootBin, "/CMake", lang, "Compiler.cmake"); cmSystemTools::RemoveFile(compilerLangFile); } } // end if in try compile } // end need test language // Store the shared library flags so that we can satisfy CMP0018 - std::string sharedLibFlagsVar = "CMAKE_SHARED_LIBRARY_"; - sharedLibFlagsVar += lang; - sharedLibFlagsVar += "_FLAGS"; + std::string sharedLibFlagsVar = + cmStrCat("CMAKE_SHARED_LIBRARY_", lang, "_FLAGS"); this->LanguageToOriginalSharedLibFlags[lang] = mf->GetSafeDefinition(sharedLibFlagsVar); @@ -881,10 +845,9 @@ void cmGlobalGenerator::EnableLanguage( // Now load files that can override any settings on the platform or for // the project First load the project compatibility file if it is in // cmake - std::string projectCompatibility = cmSystemTools::GetCMakeRoot(); - projectCompatibility += "/Modules/"; - projectCompatibility += mf->GetSafeDefinition("PROJECT_NAME"); - projectCompatibility += "Compatibility.cmake"; + std::string projectCompatibility = + cmStrCat(cmSystemTools::GetCMakeRoot(), "/Modules/", + mf->GetSafeDefinition("PROJECT_NAME"), "Compatibility.cmake"); if (cmSystemTools::FileExists(projectCompatibility)) { mf->ReadListFile(projectCompatibility); } @@ -1097,8 +1060,7 @@ void cmGlobalGenerator::SetLanguageEnabledMaps(const std::string& l, { // use LanguageToLinkerPreference to detect whether this functions has // run before - if (this->LanguageToLinkerPreference.find(l) != - this->LanguageToLinkerPreference.end()) { + if (cmContains(this->LanguageToLinkerPreference, l)) { return; } @@ -1121,8 +1083,8 @@ void cmGlobalGenerator::SetLanguageEnabledMaps(const std::string& l, } if (preference < 0) { - std::string msg = linkerPrefVar; - msg += " is negative, adjusting it to 0"; + std::string msg = + cmStrCat(linkerPrefVar, " is negative, adjusting it to 0"); cmSystemTools::Message(msg, "Warning"); preference = 0; } @@ -1149,7 +1111,7 @@ void cmGlobalGenerator::SetLanguageEnabledMaps(const std::string& l, std::string("CMAKE_") + std::string(l) + std::string("_IGNORE_EXTENSIONS"); std::string ignoreExts = mf->GetSafeDefinition(ignoreExtensionsVar); std::vector<std::string> extensionList; - cmSystemTools::ExpandListArgument(ignoreExts, extensionList); + cmExpandList(ignoreExts, extensionList); for (std::string const& i : extensionList) { this->IgnoreExtensions[i] = true; } @@ -1162,7 +1124,7 @@ void cmGlobalGenerator::FillExtensionToLanguageMap(const std::string& l, std::string("_SOURCE_FILE_EXTENSIONS"); const std::string& exts = mf->GetSafeDefinition(extensionsVar); std::vector<std::string> extensionList; - cmSystemTools::ExpandListArgument(exts, extensionList); + cmExpandList(exts, extensionList); for (std::string const& i : extensionList) { this->ExtensionToLanguage[i] = l; } @@ -1277,10 +1239,8 @@ void cmGlobalGenerator::Configure() msg << "Configuring incomplete, errors occurred!"; const char* logs[] = { "CMakeOutput.log", "CMakeError.log", nullptr }; for (const char** log = logs; *log; ++log) { - std::string f = this->CMakeInstance->GetHomeOutputDirectory(); - f += "/CMakeFiles"; - f += "/"; - f += *log; + std::string f = cmStrCat(this->CMakeInstance->GetHomeOutputDirectory(), + "/CMakeFiles/", *log); if (cmSystemTools::FileExists(f)) { msg << "\nSee also \"" << f << "\"."; } @@ -1547,7 +1507,7 @@ bool cmGlobalGenerator::ComputeTargetDepends() bool cmGlobalGenerator::QtAutoGen() { -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP cmQtAutoGenGlobalInitializer initializer(this->LocalGenerators); return initializer.generate(); #else @@ -1606,8 +1566,8 @@ void cmGlobalGenerator::FinalizeTargetCompileInfo() mf->GetConfigurations(configs); for (std::string const& c : configs) { - std::string defPropName = "COMPILE_DEFINITIONS_"; - defPropName += cmSystemTools::UpperCase(c); + std::string defPropName = + cmStrCat("COMPILE_DEFINITIONS_", cmSystemTools::UpperCase(c)); t->AppendProperty(defPropName, mf->GetProperty(defPropName)); } } @@ -1622,8 +1582,7 @@ void cmGlobalGenerator::FinalizeTargetCompileInfo() std::string const& standardIncludesStr = mf->GetSafeDefinition(standardIncludesVar); std::vector<std::string> standardIncludesVec; - cmSystemTools::ExpandListArgument(standardIncludesStr, - standardIncludesVec); + cmExpandList(standardIncludesStr, standardIncludesVec); standardIncludesSet.insert(standardIncludesVec.begin(), standardIncludesVec.end()); } @@ -1710,17 +1669,15 @@ void cmGlobalGenerator::CheckTargetProperties() continue; } for (auto const& lib : target.second.GetOriginalLinkLibraries()) { - if (lib.first.size() > 9 && - cmSystemTools::IsNOTFOUND(lib.first.c_str())) { + if (lib.first.size() > 9 && cmIsNOTFOUND(lib.first)) { std::string varName = lib.first.substr(0, lib.first.size() - 9); if (state->GetCacheEntryPropertyAsBool(varName, "ADVANCED")) { varName += " (ADVANCED)"; } - std::string text = notFoundMap[varName]; - text += "\n linked by target \""; - text += target.second.GetName(); - text += "\" in directory "; - text += this->Makefiles[i]->GetCurrentSourceDirectory(); + std::string text = + cmStrCat(notFoundMap[varName], "\n linked by target \"", + target.second.GetName(), "\" in directory ", + this->Makefiles[i]->GetCurrentSourceDirectory()); notFoundMap[varName] = text; } } @@ -1734,17 +1691,18 @@ void cmGlobalGenerator::CheckTargetProperties() std::string incDirs = cmGeneratorExpression::Preprocess( incDirProp, cmGeneratorExpression::StripAllGeneratorExpressions); - cmSystemTools::ExpandListArgument(incDirs, incs); + cmExpandList(incDirs, incs); for (std::string const& incDir : incs) { - if (incDir.size() > 9 && cmSystemTools::IsNOTFOUND(incDir.c_str())) { + if (incDir.size() > 9 && cmIsNOTFOUND(incDir)) { std::string varName = incDir.substr(0, incDir.size() - 9); if (state->GetCacheEntryPropertyAsBool(varName, "ADVANCED")) { varName += " (ADVANCED)"; } - std::string text = notFoundMap[varName]; - text += "\n used as include directory in directory "; - text += this->Makefiles[i]->GetCurrentSourceDirectory(); + std::string text = + cmStrCat(notFoundMap[varName], + "\n used as include directory in directory ", + this->Makefiles[i]->GetCurrentSourceDirectory()); notFoundMap[varName] = text; } } @@ -1843,8 +1801,8 @@ int cmGlobalGenerator::Build( output += "\n"; if (workdir.Failed()) { cmSystemTools::SetRunCommandHideConsole(hideconsole); - std::string err = "Failed to change directory: "; - err += std::strerror(workdir.GetLastResult()); + std::string err = cmStrCat("Failed to change directory: ", + std::strerror(workdir.GetLastResult())); cmSystemTools::Error(err); output += err; output += "\n"; @@ -1949,8 +1907,8 @@ std::string cmGlobalGenerator::GenerateCMakeBuildCommand( const std::string& native, bool ignoreErrors) { std::string makeCommand = cmSystemTools::GetCMakeCommand(); - makeCommand = cmSystemTools::ConvertToOutputPath(makeCommand); - makeCommand += " --build ."; + makeCommand = + cmStrCat(cmSystemTools::ConvertToOutputPath(makeCommand), " --build ."); if (!config.empty()) { makeCommand += " --config \""; makeCommand += config; @@ -2053,8 +2011,8 @@ void cmGlobalGenerator::SetConfiguredFilesPath(cmGlobalGenerator* gen) if (!gen->ConfiguredFilesPath.empty()) { this->ConfiguredFilesPath = gen->ConfiguredFilesPath; } else { - this->ConfiguredFilesPath = gen->CMakeInstance->GetHomeOutputDirectory(); - this->ConfiguredFilesPath += "/CMakeFiles"; + this->ConfiguredFilesPath = + cmStrCat(gen->CMakeInstance->GetHomeOutputDirectory(), "/CMakeFiles"); } } @@ -2154,7 +2112,7 @@ void cmGlobalGenerator::AddAlias(const std::string& name, bool cmGlobalGenerator::IsAlias(const std::string& name) const { - return this->AliasTargets.find(name) != this->AliasTargets.end(); + return cmContains(this->AliasTargets, name); } void cmGlobalGenerator::IndexTarget(cmTarget* t) @@ -2270,14 +2228,6 @@ bool cmGlobalGenerator::NameResolvesToFramework( return false; } -inline std::string removeQuotes(const std::string& s) -{ - if (s.front() == '\"' && s.back() == '\"') { - return s.substr(1, s.size() - 2); - } - return s; -} - bool cmGlobalGenerator::CheckCMP0037(std::string const& targetName, std::string const& reason) const { @@ -2332,8 +2282,8 @@ void cmGlobalGenerator::AddGlobalTarget_Package( std::vector<GlobalTargetInfo>& targets) { cmMakefile* mf = this->Makefiles[0]; - std::string configFile = mf->GetCurrentBinaryDirectory(); - configFile += "/CPackConfig.cmake"; + std::string configFile = + cmStrCat(mf->GetCurrentBinaryDirectory(), "/CPackConfig.cmake"); if (!cmSystemTools::FileExists(configFile)) { return; } @@ -2365,7 +2315,7 @@ void cmGlobalGenerator::AddGlobalTarget_Package( } else { const char* noPackageAll = mf->GetDefinition("CMAKE_SKIP_PACKAGE_ALL_DEPENDENCY"); - if (!noPackageAll || cmSystemTools::IsOff(noPackageAll)) { + if (!noPackageAll || cmIsOff(noPackageAll)) { gti.Depends.emplace_back(this->GetAllTargetName()); } } @@ -2381,8 +2331,8 @@ void cmGlobalGenerator::AddGlobalTarget_PackageSource( } cmMakefile* mf = this->Makefiles[0]; - std::string configFile = mf->GetCurrentBinaryDirectory(); - configFile += "/CPackSourceConfig.cmake"; + std::string configFile = + cmStrCat(mf->GetCurrentBinaryDirectory(), "/CPackSourceConfig.cmake"); if (!cmSystemTools::FileExists(configFile)) { return; } @@ -2534,7 +2484,7 @@ void cmGlobalGenerator::AddGlobalTarget_Install( } else { const char* noall = mf->GetDefinition("CMAKE_SKIP_INSTALL_ALL_DEPENDENCY"); - if (!noall || cmSystemTools::IsOff(noall)) { + if (!noall || cmIsOff(noall)) { gti.Depends.emplace_back(this->GetAllTargetName()); } } @@ -2617,7 +2567,7 @@ bool cmGlobalGenerator::UseFolderProperty() const // If this property is defined, let the setter turn this on or off... // if (prop) { - return cmSystemTools::IsOn(prop); + return cmIsOn(prop); } // By default, this feature is OFF, since it is not supported in the @@ -2661,8 +2611,7 @@ cmTarget cmGlobalGenerator::CreateGlobalTarget(GlobalTargetInfo const& gti, std::string cmGlobalGenerator::GenerateRuleFile( std::string const& output) const { - std::string ruleFile = output; - ruleFile += ".rule"; + std::string ruleFile = cmStrCat(output, ".rule"); const char* dir = this->GetCMakeCFGIntDir(); if (dir && dir[0] == '$') { cmSystemTools::ReplaceString(ruleFile, dir, "/CMakeFiles"); @@ -2712,8 +2661,7 @@ bool cmGlobalGenerator::IsReservedTarget(std::string const& name) "clean", "edit_cache", "rebuild_cache", "ZERO_CHECK" }; - return std::find(cm::cbegin(reservedTargets), cm::cend(reservedTargets), - name) != cm::cend(reservedTargets); + return cmContains(reservedTargets, name); } void cmGlobalGenerator::SetExternalMakefileProjectGenerator( @@ -2829,7 +2777,7 @@ std::set<std::string> const& cmGlobalGenerator::GetDirectoryContent( void cmGlobalGenerator::AddRuleHash(const std::vector<std::string>& outputs, std::string const& content) { -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) // Ignore if there are no outputs. if (outputs.empty()) { return; @@ -2859,11 +2807,9 @@ void cmGlobalGenerator::AddRuleHash(const std::vector<std::string>& outputs, void cmGlobalGenerator::CheckRuleHashes() { -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) std::string home = this->GetCMakeInstance()->GetHomeOutputDirectory(); - std::string pfile = home; - pfile += "/CMakeFiles"; - pfile += "/CMakeRuleHashes.txt"; + std::string pfile = cmStrCat(home, "/CMakeFiles/CMakeRuleHashes.txt"); this->CheckRuleHashes(pfile, home); this->WriteRuleHashes(pfile); #endif @@ -2939,9 +2885,8 @@ void cmGlobalGenerator::WriteRuleHashes(std::string const& pfile) void cmGlobalGenerator::WriteSummary() { // Record all target directories in a central location. - std::string fname = this->CMakeInstance->GetHomeOutputDirectory(); - fname += "/CMakeFiles"; - fname += "/TargetDirectories.txt"; + std::string fname = cmStrCat(this->CMakeInstance->GetHomeOutputDirectory(), + "/CMakeFiles/TargetDirectories.txt"); cmGeneratedFileStream fout(fname); for (cmLocalGenerator* lg : this->LocalGenerators) { @@ -2959,11 +2904,10 @@ void cmGlobalGenerator::WriteSummary(cmGeneratorTarget* target) { // Place the labels file in a per-target support directory. std::string dir = target->GetSupportDirectory(); - std::string file = dir; - file += "/Labels.txt"; + std::string file = cmStrCat(dir, "/Labels.txt"); std::string json_file = dir + "/Labels.json"; -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP // Check whether labels are enabled for this target. const char* targetLabels = target->GetProperty("LABELS"); const char* directoryLabels = @@ -2985,7 +2929,7 @@ void cmGlobalGenerator::WriteSummary(cmGeneratorTarget* target) // List the target-wide labels. All sources in the target get // these labels. if (targetLabels) { - cmSystemTools::ExpandListArgument(targetLabels, labels); + cmExpandList(targetLabels, labels); if (!labels.empty()) { fout << "# Target labels\n"; for (std::string const& l : labels) { @@ -3000,12 +2944,11 @@ void cmGlobalGenerator::WriteSummary(cmGeneratorTarget* target) std::vector<std::string> cmakeDirectoryLabelsList; if (directoryLabels) { - cmSystemTools::ExpandListArgument(directoryLabels, directoryLabelsList); + cmExpandList(directoryLabels, directoryLabelsList); } if (cmakeDirectoryLabels) { - cmSystemTools::ExpandListArgument(cmakeDirectoryLabels, - cmakeDirectoryLabelsList); + cmExpandList(cmakeDirectoryLabels, cmakeDirectoryLabelsList); } if (!directoryLabelsList.empty() || !cmakeDirectoryLabelsList.empty()) { @@ -3042,7 +2985,7 @@ void cmGlobalGenerator::WriteSummary(cmGeneratorTarget* target) if (const char* svalue = sf->GetProperty("LABELS")) { labels.clear(); Json::Value& lj_source_labels = lj_source["labels"] = Json::arrayValue; - cmSystemTools::ExpandListArgument(svalue, labels); + cmExpandList(svalue, labels); for (std::string const& label : labels) { fout << " " << label << "\n"; lj_source_labels.append(label); @@ -3129,8 +3072,8 @@ bool cmGlobalGenerator::GenerateCPackPropertiesFile() std::vector<std::string> configs; std::string config = mf->GetConfigurations(configs, false); - std::string path = this->CMakeInstance->GetHomeOutputDirectory(); - path += "/CPackProperties.cmake"; + std::string path = cmStrCat(this->CMakeInstance->GetHomeOutputDirectory(), + "/CPackProperties.cmake"); if (!cmSystemTools::FileExists(path) && installedFiles.empty()) { return true; diff --git a/Source/cmGlobalGenerator.h b/Source/cmGlobalGenerator.h index ea40ebc..830974d 100644 --- a/Source/cmGlobalGenerator.h +++ b/Source/cmGlobalGenerator.h @@ -25,7 +25,7 @@ #include "cmTargetDepend.h" #include "cm_codecvt.hxx" -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) # include "cmFileLockPool.h" # include "cm_jsoncpp_value.h" #endif @@ -109,7 +109,7 @@ public: return codecvt::None; } -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) /** Get a JSON object describing the generator. */ virtual Json::Value GetJson() const; #endif @@ -462,7 +462,7 @@ public: const std::set<const cmGeneratorTarget*>& GetFilenameTargetDepends( cmSourceFile* sf) const; -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) cmFileLockPool& GetFileLockPool() { return FileLockPool; } #endif @@ -665,7 +665,7 @@ private: mutable std::map<cmSourceFile*, std::set<cmGeneratorTarget const*>> FilenameTargetDepends; -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) // Pool of file locks cmFileLockPool FileLockPool; #endif diff --git a/Source/cmGlobalGhsMultiGenerator.cxx b/Source/cmGlobalGhsMultiGenerator.cxx index 7cfbea6..25d678f 100644 --- a/Source/cmGlobalGhsMultiGenerator.cxx +++ b/Source/cmGlobalGhsMultiGenerator.cxx @@ -2,6 +2,7 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmGlobalGhsMultiGenerator.h" +#include "cmAlgorithms.h" #include "cmDocumentationEntry.h" #include "cmGeneratedFileStream.h" #include "cmGeneratorTarget.h" @@ -11,6 +12,7 @@ #include "cmMakefile.h" #include "cmState.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmVersion.h" #include "cmake.h" @@ -55,11 +57,9 @@ void cmGlobalGhsMultiGenerator::ComputeTargetObjectDirectory( cmGeneratorTarget* gt) const { // Compute full path to object file directory for this target. - std::string dir; - dir += gt->LocalGenerator->GetCurrentBinaryDirectory(); - dir += "/"; - dir += gt->LocalGenerator->GetTargetDirectory(gt); - dir += "/"; + std::string dir = + cmStrCat(gt->LocalGenerator->GetCurrentBinaryDirectory(), '/', + gt->LocalGenerator->GetTargetDirectory(gt), '/'); gt->ObjectDirectory = dir; } @@ -76,10 +76,9 @@ bool cmGlobalGhsMultiGenerator::SetGeneratorToolset(std::string const& ts, } if (ts.empty()) { std::string message; - message = - "Green Hills MULTI: -T <toolset> not specified; defaulting to \""; - message += tsp; - message += "\""; + message = cmStrCat( + "Green Hills MULTI: -T <toolset> not specified; defaulting to \"", tsp, + '"'); cmSystemTools::Message(message); /* store the full toolset for later use @@ -97,12 +96,11 @@ bool cmGlobalGhsMultiGenerator::SetGeneratorToolset(std::string const& ts, /* check if the toolset changed from last generate */ if (prevTool != nullptr && (gbuild != prevTool)) { - std::string message = "toolset build tool: "; - message += gbuild; - message += "\nDoes not match the previously used build tool: "; - message += prevTool; - message += "\nEither remove the CMakeCache.txt file and CMakeFiles " - "directory or choose a different binary directory."; + std::string message = + cmStrCat("toolset build tool: ", gbuild, + "\nDoes not match the previously used build tool: ", prevTool, + "\nEither remove the CMakeCache.txt file and CMakeFiles " + "directory or choose a different binary directory."); cmSystemTools::Error(message); return false; } @@ -138,24 +136,20 @@ bool cmGlobalGhsMultiGenerator::SetGeneratorPlatform(std::string const& p, /* check if OS location has been updated by platform scripts */ std::string platform = mf->GetSafeDefinition("GHS_TARGET_PLATFORM"); std::string osdir = mf->GetSafeDefinition("GHS_OS_DIR"); - if (cmSystemTools::IsOff(osdir.c_str()) && - platform.find("integrity") != std::string::npos) { + if (cmIsOff(osdir) && platform.find("integrity") != std::string::npos) { if (!this->CMakeInstance->GetIsInTryCompile()) { /* required OS location is not found */ - std::string m = - "Green Hills MULTI: GHS_OS_DIR not specified; No OS found in \""; - m += mf->GetSafeDefinition("GHS_OS_ROOT"); - m += "\""; + std::string m = cmStrCat( + "Green Hills MULTI: GHS_OS_DIR not specified; No OS found in \"", + mf->GetSafeDefinition("GHS_OS_ROOT"), '"'); cmSystemTools::Message(m); } osdir = "GHS_OS_DIR-NOT-SPECIFIED"; } else if (!this->CMakeInstance->GetIsInTryCompile() && - cmSystemTools::IsOff(this->OsDir) && - !cmSystemTools::IsOff(osdir)) { + cmIsOff(this->OsDir) && !cmIsOff(osdir)) { /* OS location was updated by auto-selection */ - std::string m = "Green Hills MULTI: GHS_OS_DIR not specified; found \""; - m += osdir; - m += "\""; + std::string m = cmStrCat( + "Green Hills MULTI: GHS_OS_DIR not specified; found \"", osdir, '"'); cmSystemTools::Message(m); } this->OsDir = osdir; @@ -163,17 +157,15 @@ bool cmGlobalGhsMultiGenerator::SetGeneratorPlatform(std::string const& p, // Determine GHS_BSP_NAME std::string bspName = mf->GetSafeDefinition("GHS_BSP_NAME"); - if (cmSystemTools::IsOff(bspName.c_str()) && - platform.find("integrity") != std::string::npos) { + if (cmIsOff(bspName) && platform.find("integrity") != std::string::npos) { bspName = "sim" + arch; /* write back the calculate name for next time */ mf->AddCacheDefinition("GHS_BSP_NAME", bspName.c_str(), "Name of GHS target platform.", cmStateEnums::STRING, true); - std::string m = - "Green Hills MULTI: GHS_BSP_NAME not specified; defaulting to \""; - m += bspName; - m += "\""; + std::string m = cmStrCat( + "Green Hills MULTI: GHS_BSP_NAME not specified; defaulting to \"", + bspName, '"'); cmSystemTools::Message(m); } @@ -334,18 +326,18 @@ void cmGlobalGhsMultiGenerator::WriteTopLevelProject(std::ostream& fout, // Specify BSP option if supplied by user const char* bspName = this->GetCMakeInstance()->GetCacheDefinition("GHS_BSP_NAME"); - if (!cmSystemTools::IsOff(bspName)) { + if (!cmIsOff(bspName)) { fout << " -bsp " << bspName << std::endl; } // Specify OS DIR if supplied by user // -- not all platforms require this entry in the project file - if (!cmSystemTools::IsOff(this->OsDir.c_str())) { + if (!cmIsOff(this->OsDir)) { const char* osDirOption = this->GetCMakeInstance()->GetCacheDefinition("GHS_OS_DIR_OPTION"); std::replace(this->OsDir.begin(), this->OsDir.end(), '\\', '/'); fout << " "; - if (cmSystemTools::IsOff(osDirOption)) { + if (cmIsOff(osDirOption)) { fout << ""; } else { fout << osDirOption; @@ -404,8 +396,8 @@ void cmGlobalGhsMultiGenerator::WriteProjectLine( void cmGlobalGhsMultiGenerator::WriteTargets(cmLocalGenerator* root) { - std::string rootBinaryDir = root->GetCurrentBinaryDirectory(); - rootBinaryDir += "/CMakeFiles"; + std::string rootBinaryDir = + cmStrCat(root->GetCurrentBinaryDirectory(), "/CMakeFiles"); // All known targets for (cmGeneratorTarget const* target : this->ProjectTargets) { @@ -418,17 +410,17 @@ void cmGlobalGhsMultiGenerator::WriteTargets(cmLocalGenerator* root) } // create target build file - std::string name = target->GetName() + ".tgt" + FILE_EXTENSION; - std::string fname = rootBinaryDir + "/" + name; + std::string name = cmStrCat(target->GetName(), ".tgt", FILE_EXTENSION); + std::string fname = cmStrCat(rootBinaryDir, "/", name); cmGeneratedFileStream fbld(fname); fbld.SetCopyIfDifferent(true); this->WriteFileHeader(fbld); GhsMultiGpj::WriteGpjTag(GhsMultiGpj::PROJECT, fbld); std::vector<cmGeneratorTarget const*> build; if (ComputeTargetBuildOrder(target, build)) { - std::string message = "The inter-target dependency graph for target [" + - target->GetName() + "] had a cycle.\n"; - cmSystemTools::Error(message); + cmSystemTools::Error( + cmStrCat("The inter-target dependency graph for target [", + target->GetName(), "] had a cycle.\n")); } else { for (auto& tgt : build) { WriteProjectLine(fbld, tgt, root, rootBinaryDir); @@ -469,7 +461,7 @@ void cmGlobalGhsMultiGenerator::WriteAllTarget( if (t->GetType() == cmStateEnums::INTERFACE_LIBRARY) { continue; } - if (!cmSystemTools::IsOn(t->GetProperty("EXCLUDE_FROM_ALL"))) { + if (!cmIsOn(t->GetProperty("EXCLUDE_FROM_ALL"))) { defaultTargets.push_back(t); } } @@ -480,8 +472,8 @@ void cmGlobalGhsMultiGenerator::WriteAllTarget( cmSystemTools::Error(message); } else { // determine the targets for ALL target - std::string rootBinaryDir = root->GetCurrentBinaryDirectory(); - rootBinaryDir += "/CMakeFiles"; + std::string rootBinaryDir = + cmStrCat(root->GetCurrentBinaryDirectory(), "/CMakeFiles"); for (cmGeneratorTarget const* target : build) { if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY || target->GetType() == cmStateEnums::MODULE_LIBRARY || @@ -539,11 +531,8 @@ void cmGlobalGhsMultiGenerator::OutputTopLevelProject( * with target projects. This avoid the issue where the project has * the same name as the executable target. */ - fname = root->GetCurrentBinaryDirectory(); - fname += "/"; - fname += root->GetProjectName(); - fname += ".top"; - fname += FILE_EXTENSION; + fname = cmStrCat(root->GetCurrentBinaryDirectory(), '/', + root->GetProjectName(), ".top", FILE_EXTENSION); cmGeneratedFileStream top(fname); top.SetCopyIfDifferent(true); @@ -588,16 +577,14 @@ cmGlobalGhsMultiGenerator::GenerateBuildCommand( /* if multiple top-projects are found in build directory * then prefer projectName top-project. */ - auto p = std::find(files.begin(), files.end(), proj); - if (p == files.end()) { + if (!cmContains(files, proj)) { proj = files.at(0); } } makeCommand.Add("-top", proj); if (!targetNames.empty()) { - if (std::find(targetNames.begin(), targetNames.end(), "clean") != - targetNames.end()) { + if (cmContains(targetNames, "clean")) { makeCommand.Add("-clean"); } else { for (const auto& tname : targetNames) { @@ -624,7 +611,7 @@ void cmGlobalGhsMultiGenerator::WriteMacros(std::ostream& fout, this->GetCMakeInstance()->GetCacheDefinition("GHS_GPJ_MACROS"); if (nullptr != ghsGpjMacros) { std::vector<std::string> expandedList; - cmSystemTools::ExpandListArgument(std::string(ghsGpjMacros), expandedList); + cmExpandList(std::string(ghsGpjMacros), expandedList); for (std::string const& arg : expandedList) { fout << "macro " << arg << std::endl; } @@ -646,10 +633,7 @@ void cmGlobalGhsMultiGenerator::WriteHighLevelDirectives( this->GetCMakeInstance()->GetCacheDefinition("CMAKE_GENERATOR_PLATFORM"); const char* p = this->GetCMakeInstance()->GetCacheDefinition("GHS_TARGET_PLATFORM"); - tgt = (a ? a : ""); - tgt += "_"; - tgt += (p ? p : ""); - tgt += ".tgt"; + tgt = cmStrCat((a ? a : ""), '_', (p ? p : ""), ".tgt"); } fout << "primaryTarget=" << tgt << std::endl; diff --git a/Source/cmGlobalMSYSMakefileGenerator.cxx b/Source/cmGlobalMSYSMakefileGenerator.cxx index 483d4ab..ae9d5a7 100644 --- a/Source/cmGlobalMSYSMakefileGenerator.cxx +++ b/Source/cmGlobalMSYSMakefileGenerator.cxx @@ -24,8 +24,7 @@ cmGlobalMSYSMakefileGenerator::cmGlobalMSYSMakefileGenerator(cmake* cm) std::string cmGlobalMSYSMakefileGenerator::FindMinGW( std::string const& makeloc) { - std::string fstab = makeloc; - fstab += "/../etc/fstab"; + std::string fstab = cmStrCat(makeloc, "/../etc/fstab"); cmsys::ifstream fin(fstab.c_str()); std::string path; std::string mount; @@ -34,8 +33,7 @@ std::string cmGlobalMSYSMakefileGenerator::FindMinGW( fin >> path; fin >> mount; if (mount == "/mingw") { - mingwBin = path; - mingwBin += "/bin"; + mingwBin = cmStrCat(path, "/bin"); } } return mingwBin; diff --git a/Source/cmGlobalNinjaGenerator.cxx b/Source/cmGlobalNinjaGenerator.cxx index 0b68966..062eccb 100644 --- a/Source/cmGlobalNinjaGenerator.cxx +++ b/Source/cmGlobalNinjaGenerator.cxx @@ -383,7 +383,7 @@ void cmGlobalNinjaGenerator::WriteVariable(std::ostream& os, } // Do not add a variable if the value is empty. - std::string val = cmSystemTools::TrimWhitespace(value); + std::string val = cmTrimWhitespace(value); if (val.empty()) { return; } @@ -528,7 +528,7 @@ bool cmGlobalNinjaGenerator::FindMakeProgram(cmMakefile* mf) cmSystemTools::SetFatalErrorOccured(); return false; } - this->NinjaVersion = cmSystemTools::TrimWhitespace(version); + this->NinjaVersion = cmTrimWhitespace(version); this->CheckNinjaFeatures(); } return true; @@ -560,7 +560,7 @@ void cmGlobalNinjaGenerator::CheckNinjaFeatures() if (pos != std::string::npos) { const char* fv = &this->NinjaVersion[pos + k_DYNDEP_.size()]; unsigned long dyndep = 0; - cmSystemTools::StringToULong(fv, &dyndep); + cmStrToULong(fv, &dyndep); if (dyndep == 1) { this->NinjaSupportsDyndeps = true; } @@ -571,8 +571,7 @@ void cmGlobalNinjaGenerator::CheckNinjaFeatures() bool cmGlobalNinjaGenerator::CheckLanguages( std::vector<std::string> const& languages, cmMakefile* mf) const { - if (std::find(languages.begin(), languages.end(), "Fortran") != - languages.end()) { + if (cmContains(languages, "Fortran")) { return this->CheckFortran(mf); } return true; @@ -705,11 +704,9 @@ void cmGlobalNinjaGenerator::ComputeTargetObjectDirectory( cmGeneratorTarget* gt) const { // Compute full path to object file directory for this target. - std::string dir; - dir += gt->LocalGenerator->GetCurrentBinaryDirectory(); - dir += "/"; - dir += gt->LocalGenerator->GetTargetDirectory(gt); - dir += "/"; + std::string dir = + cmStrCat(gt->LocalGenerator->GetCurrentBinaryDirectory(), '/', + gt->LocalGenerator->GetTargetDirectory(gt), '/'); gt->ObjectDirectory = dir; } @@ -719,9 +716,8 @@ bool cmGlobalNinjaGenerator::OpenBuildFileStream() { // Compute Ninja's build file path. std::string buildFilePath = - this->GetCMakeInstance()->GetHomeOutputDirectory(); - buildFilePath += "/"; - buildFilePath += cmGlobalNinjaGenerator::NINJA_BUILD_FILE; + cmStrCat(this->GetCMakeInstance()->GetHomeOutputDirectory(), '/', + cmGlobalNinjaGenerator::NINJA_BUILD_FILE); // Get a stream where to generate things. if (!this->BuildFileStream) { @@ -758,9 +754,8 @@ bool cmGlobalNinjaGenerator::OpenRulesFileStream() { // Compute Ninja's build file path. std::string rulesFilePath = - this->GetCMakeInstance()->GetHomeOutputDirectory(); - rulesFilePath += "/"; - rulesFilePath += cmGlobalNinjaGenerator::NINJA_RULES_FILE; + cmStrCat(this->GetCMakeInstance()->GetHomeOutputDirectory(), '/', + cmGlobalNinjaGenerator::NINJA_RULES_FILE); // Get a stream where to generate things. if (!this->RulesFileStream) { @@ -1315,13 +1310,13 @@ void cmGlobalNinjaGenerator::WriteTargetRebuildManifest(std::ostream& os) { cmNinjaRule rule("RERUN_CMAKE"); - rule.Command = CMakeCmd(); - rule.Command += " -S"; - rule.Command += lg->ConvertToOutputFormat(lg->GetSourceDirectory(), - cmOutputConverter::SHELL); - rule.Command += " -B"; - rule.Command += lg->ConvertToOutputFormat(lg->GetBinaryDirectory(), - cmOutputConverter::SHELL); + rule.Command = + cmStrCat(CMakeCmd(), " -S", + lg->ConvertToOutputFormat(lg->GetSourceDirectory(), + cmOutputConverter::SHELL), + " -B", + lg->ConvertToOutputFormat(lg->GetBinaryDirectory(), + cmOutputConverter::SHELL)); rule.Description = "Re-running CMake..."; rule.Comment = "Rule for re-running cmake."; rule.Generator = true; @@ -1349,10 +1344,10 @@ void cmGlobalNinjaGenerator::WriteTargetRebuildManifest(std::ostream& os) if (this->SupportsManifestRestat() && cm->DoWriteGlobVerifyTarget()) { { cmNinjaRule rule("VERIFY_GLOBS"); - rule.Command = CMakeCmd(); - rule.Command += " -P "; - rule.Command += lg->ConvertToOutputFormat(cm->GetGlobVerifyScript(), - cmOutputConverter::SHELL); + rule.Command = + cmStrCat(CMakeCmd(), " -P ", + lg->ConvertToOutputFormat(cm->GetGlobVerifyScript(), + cmOutputConverter::SHELL)); rule.Description = "Re-checking globbed directories..."; rule.Comment = "Rule for re-checking globbed directories."; rule.Generator = true; @@ -1458,9 +1453,8 @@ bool cmGlobalNinjaGenerator::WriteTargetCleanAdditional(std::ostream& os) { cmLocalGenerator* lgr = this->LocalGenerators.at(0); std::string cleanScriptRel = "CMakeFiles/clean_additional.cmake"; - std::string cleanScriptAbs = lgr->GetBinaryDirectory(); - cleanScriptAbs += '/'; - cleanScriptAbs += cleanScriptRel; + std::string cleanScriptAbs = + cmStrCat(lgr->GetBinaryDirectory(), '/', cleanScriptRel); // Check if there are additional files to clean if (this->AdditionalCleanFiles.empty()) { @@ -1490,10 +1484,10 @@ bool cmGlobalNinjaGenerator::WriteTargetCleanAdditional(std::ostream& os) // Write rule { cmNinjaRule rule("CLEAN_ADDITIONAL"); - rule.Command = CMakeCmd(); - rule.Command += " -P "; - rule.Command += lgr->ConvertToOutputFormat( - this->NinjaOutputPath(cleanScriptRel), cmOutputConverter::SHELL); + rule.Command = cmStrCat( + CMakeCmd(), " -P ", + lgr->ConvertToOutputFormat(this->NinjaOutputPath(cleanScriptRel), + cmOutputConverter::SHELL)); rule.Description = "Cleaning additional files..."; rule.Comment = "Rule for cleaning additional files."; WriteRule(*this->RulesFileStream, rule); @@ -1731,8 +1725,9 @@ int cmcmd_cmake_ninja_depends(std::vector<std::string>::const_iterator argBeg, if (arg_lang == "Fortran") { info = cmcmd_cmake_ninja_depends_fortran(arg_tdi, arg_pp); } else { - cmSystemTools::Error("-E cmake_ninja_depends does not understand the " + - arg_lang + " language"); + cmSystemTools::Error( + cmStrCat("-E cmake_ninja_depends does not understand the ", arg_lang, + " language")); return 1; } @@ -1786,8 +1781,9 @@ std::unique_ptr<cmSourceInfo> cmcmd_cmake_ninja_depends_fortran( cmsys::ifstream tdif(arg_tdi.c_str(), std::ios::in | std::ios::binary); Json::Reader reader; if (!reader.parse(tdif, tdio, false)) { - cmSystemTools::Error("-E cmake_ninja_depends failed to parse " + - arg_tdi + reader.getFormattedErrorMessages()); + cmSystemTools::Error( + cmStrCat("-E cmake_ninja_depends failed to parse ", arg_tdi, + reader.getFormattedErrorMessages())); return nullptr; } } @@ -1866,8 +1862,9 @@ bool cmGlobalNinjaGenerator::WriteDyndepFile( cmsys::ifstream ddif(arg_ddi.c_str(), std::ios::in | std::ios::binary); Json::Reader reader; if (!reader.parse(ddif, ddio, false)) { - cmSystemTools::Error("-E cmake_ninja_dyndep failed to parse " + arg_ddi + - reader.getFormattedErrorMessages()); + cmSystemTools::Error(cmStrCat("-E cmake_ninja_dyndep failed to parse ", + arg_ddi, + reader.getFormattedErrorMessages())); return false; } @@ -1894,14 +1891,14 @@ bool cmGlobalNinjaGenerator::WriteDyndepFile( // Populate the module map with those provided by linked targets first. for (std::string const& linked_target_dir : linked_target_dirs) { std::string const ltmn = - linked_target_dir + "/" + arg_lang + "Modules.json"; + cmStrCat(linked_target_dir, "/", arg_lang, "Modules.json"); Json::Value ltm; cmsys::ifstream ltmf(ltmn.c_str(), std::ios::in | std::ios::binary); Json::Reader reader; if (ltmf && !reader.parse(ltmf, ltm, false)) { - cmSystemTools::Error("-E cmake_ninja_dyndep failed to parse " + - linked_target_dir + - reader.getFormattedErrorMessages()); + cmSystemTools::Error(cmStrCat("-E cmake_ninja_dyndep failed to parse ", + linked_target_dir, + reader.getFormattedErrorMessages())); return false; } if (ltm.isObject()) { @@ -2005,8 +2002,9 @@ int cmcmd_cmake_ninja_dyndep(std::vector<std::string>::const_iterator argBeg, cmsys::ifstream tdif(arg_tdi.c_str(), std::ios::in | std::ios::binary); Json::Reader reader; if (!reader.parse(tdif, tdio, false)) { - cmSystemTools::Error("-E cmake_ninja_dyndep failed to parse " + arg_tdi + - reader.getFormattedErrorMessages()); + cmSystemTools::Error(cmStrCat("-E cmake_ninja_dyndep failed to parse ", + arg_tdi, + reader.getFormattedErrorMessages())); return 1; } } diff --git a/Source/cmGlobalUnixMakefileGenerator3.cxx b/Source/cmGlobalUnixMakefileGenerator3.cxx index 35af0e1..22c304e 100644 --- a/Source/cmGlobalUnixMakefileGenerator3.cxx +++ b/Source/cmGlobalUnixMakefileGenerator3.cxx @@ -22,6 +22,7 @@ #include "cmState.h" #include "cmStateDirectory.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmTargetDepend.h" #include "cmake.h" @@ -107,11 +108,9 @@ void cmGlobalUnixMakefileGenerator3::ComputeTargetObjectDirectory( cmGeneratorTarget* gt) const { // Compute full path to object file directory for this target. - std::string dir; - dir += gt->LocalGenerator->GetCurrentBinaryDirectory(); - dir += "/"; - dir += gt->LocalGenerator->GetTargetDirectory(gt); - dir += "/"; + std::string dir = + cmStrCat(gt->LocalGenerator->GetCurrentBinaryDirectory(), '/', + gt->LocalGenerator->GetTargetDirectory(gt), '/'); gt->ObjectDirectory = dir; } @@ -146,10 +145,8 @@ void cmGlobalUnixMakefileGenerator3::Generate() pmi.second.WriteProgressVariables(total, current); } for (cmLocalGenerator* lg : this->LocalGenerators) { - std::string markFileName = lg->GetCurrentBinaryDirectory(); - markFileName += "/"; - markFileName += "/CMakeFiles"; - markFileName += "/progress.marks"; + std::string markFileName = + cmStrCat(lg->GetCurrentBinaryDirectory(), "/CMakeFiles/progress.marks"); cmGeneratedFileStream markFile(markFileName); markFile << this->CountProgressMarksInAll(lg) << "\n"; } @@ -197,9 +194,8 @@ void cmGlobalUnixMakefileGenerator3::WriteMainMakefile2() // because the check-build-system step compares the makefile time to // see if the build system must be regenerated. std::string makefileName = - this->GetCMakeInstance()->GetHomeOutputDirectory(); - makefileName += "/CMakeFiles"; - makefileName += "/Makefile2"; + cmStrCat(this->GetCMakeInstance()->GetHomeOutputDirectory(), + "/CMakeFiles/Makefile2"); cmGeneratedFileStream makefileStream(makefileName, false, this->GetMakefileEncoding()); if (!makefileStream) { @@ -257,17 +253,15 @@ void cmGlobalUnixMakefileGenerator3::WriteMainCMakefile() // because the check-build-system step compares the makefile time to // see if the build system must be regenerated. std::string cmakefileName = - this->GetCMakeInstance()->GetHomeOutputDirectory(); - cmakefileName += "/CMakeFiles"; - cmakefileName += "/Makefile.cmake"; + cmStrCat(this->GetCMakeInstance()->GetHomeOutputDirectory(), + "/CMakeFiles/Makefile.cmake"); cmGeneratedFileStream cmakefileStream(cmakefileName); if (!cmakefileStream) { return; } std::string makefileName = - this->GetCMakeInstance()->GetHomeOutputDirectory(); - makefileName += "/Makefile"; + cmStrCat(this->GetCMakeInstance()->GetHomeOutputDirectory(), "/Makefile"); // get a local generator for some useful methods cmLocalUnixMakefileGenerator3* lg = @@ -319,9 +313,9 @@ void cmGlobalUnixMakefileGenerator3::WriteMainCMakefile() cmakefileStream << " )\n\n"; // Build the path to the cache check file. - std::string check = this->GetCMakeInstance()->GetHomeOutputDirectory(); - check += "/CMakeFiles"; - check += "/cmake.check_cache"; + std::string check = + cmStrCat(this->GetCMakeInstance()->GetHomeOutputDirectory(), + "/CMakeFiles/cmake.check_cache"); // Set the corresponding makefile in the cmake file. cmakefileStream << "# The corresponding makefile is:\n" @@ -351,9 +345,8 @@ void cmGlobalUnixMakefileGenerator3::WriteMainCMakefile() std::string tmpStr; for (cmLocalGenerator* localGen : this->LocalGenerators) { lg = static_cast<cmLocalUnixMakefileGenerator3*>(localGen); - tmpStr = lg->GetCurrentBinaryDirectory(); - tmpStr += "/CMakeFiles"; - tmpStr += "/CMakeDirectoryInformation.cmake"; + tmpStr = cmStrCat(lg->GetCurrentBinaryDirectory(), + "/CMakeFiles/CMakeDirectoryInformation.cmake"); cmakefileStream << " \"" << lg->MaybeConvertToRelativePath(binDir, tmpStr) << "\"\n"; @@ -385,8 +378,8 @@ void cmGlobalUnixMakefileGenerator3::WriteMainCMakefileLanguageRules( (tgt->GetType() == cmStateEnums::OBJECT_LIBRARY) || (tgt->GetType() == cmStateEnums::UTILITY)) { cmGeneratorTarget* gt = tgt; - std::string tname = lg->GetRelativeTargetDirectory(gt); - tname += "/DependInfo.cmake"; + std::string tname = + cmStrCat(lg->GetRelativeTargetDirectory(gt), "/DependInfo.cmake"); cmSystemTools::ConvertToUnixSlashes(tname); cmakefileStream << " \"" << tname << "\"\n"; } @@ -401,9 +394,8 @@ void cmGlobalUnixMakefileGenerator3::WriteDirectoryRule2( std::vector<std::string> const& commands) { // Get the relative path to the subdirectory from the top. - std::string makeTarget = lg->GetCurrentBinaryDirectory(); - makeTarget += '/'; - makeTarget += pass; + std::string makeTarget = + cmStrCat(lg->GetCurrentBinaryDirectory(), '/', pass); // The directory-level rule should depend on the target-level rules // for all targets in the directory. @@ -420,9 +412,8 @@ void cmGlobalUnixMakefileGenerator3::WriteDirectoryRule2( if ((!check_all || !gtarget->GetPropertyAsBool("EXCLUDE_FROM_ALL")) && (!check_relink || gtarget->NeedRelinkBeforeInstall(lg->GetConfigName()))) { - std::string tname = lg->GetRelativeTargetDirectory(gtarget); - tname += "/"; - tname += pass; + std::string tname = + cmStrCat(lg->GetRelativeTargetDirectory(gtarget), '/', pass); depends.push_back(std::move(tname)); } } @@ -431,9 +422,8 @@ void cmGlobalUnixMakefileGenerator3::WriteDirectoryRule2( // The directory-level rule should depend on the directory-level // rules of the subdirectories. for (cmStateSnapshot const& c : lg->GetStateSnapshot().GetChildren()) { - std::string subdir = c.GetDirectory().GetCurrentBinary(); - subdir += '/'; - subdir += pass; + std::string subdir = + cmStrCat(c.GetDirectory().GetCurrentBinary(), '/', pass); depends.push_back(std::move(subdir)); } @@ -446,13 +436,9 @@ void cmGlobalUnixMakefileGenerator3::WriteDirectoryRule2( // Write the rule. std::string doc; if (lg->IsRootMakefile()) { - doc = "The main recursive \""; - doc += pass; - doc += "\" target."; + doc = cmStrCat("The main recursive \"", pass, "\" target."); } else { - doc = "Recursive \""; - doc += pass; - doc += "\" directory target."; + doc = cmStrCat("Recursive \"", pass, "\" directory target."); } lg->WriteMakeRule(ruleFileStream, doc.c_str(), makeTarget, depends, commands, true); @@ -583,8 +569,7 @@ void cmGlobalUnixMakefileGenerator3::WriteConvenienceRules( // Write the rule. commands.clear(); - std::string tmp = "CMakeFiles/"; - tmp += "Makefile2"; + std::string tmp = "CMakeFiles/Makefile2"; commands.push_back(lg->GetRecursiveMakeCall(tmp, name)); depends.clear(); if (regenerate) { @@ -596,14 +581,11 @@ void cmGlobalUnixMakefileGenerator3::WriteConvenienceRules( // Add a fast rule to build the target std::string localName = lg->GetRelativeTargetDirectory(gtarget); std::string makefileName; - makefileName = localName; - makefileName += "/build.make"; + makefileName = cmStrCat(localName, "/build.make"); depends.clear(); commands.clear(); - std::string makeTargetName = localName; - makeTargetName += "/build"; - localName = name; - localName += "/fast"; + std::string makeTargetName = cmStrCat(localName, "/build"); + localName = cmStrCat(name, "/fast"); commands.push_back( lg->GetRecursiveMakeCall(makefileName, makeTargetName)); lg->WriteMakeRule(ruleFileStream, "fast build rule for target.", @@ -612,10 +594,9 @@ void cmGlobalUnixMakefileGenerator3::WriteConvenienceRules( // Add a local name for the rule to relink the target before // installation. if (gtarget->NeedRelinkBeforeInstall(lg->GetConfigName())) { - makeTargetName = lg->GetRelativeTargetDirectory(gtarget); - makeTargetName += "/preinstall"; - localName = name; - localName += "/preinstall"; + makeTargetName = + cmStrCat(lg->GetRelativeTargetDirectory(gtarget), "/preinstall"); + localName = cmStrCat(name, "/preinstall"); depends.clear(); commands.clear(); commands.push_back( @@ -659,20 +640,17 @@ void cmGlobalUnixMakefileGenerator3::WriteConvenienceRules2( std::string makefileName; // Add a rule to build the target by name. localName = lg->GetRelativeTargetDirectory(gtarget); - makefileName = localName; - makefileName += "/build.make"; + makefileName = cmStrCat(localName, "/build.make"); lg->WriteDivider(ruleFileStream); ruleFileStream << "# Target rules for target " << localName << "\n\n"; commands.clear(); - makeTargetName = localName; - makeTargetName += "/depend"; + makeTargetName = cmStrCat(localName, "/depend"); commands.push_back( lg->GetRecursiveMakeCall(makefileName, makeTargetName)); - makeTargetName = localName; - makeTargetName += "/build"; + makeTargetName = cmStrCat(localName, "/build"); commands.push_back( lg->GetRecursiveMakeCall(makefileName, makeTargetName)); @@ -681,8 +659,7 @@ void cmGlobalUnixMakefileGenerator3::WriteConvenienceRules2( depends.clear(); cmLocalUnixMakefileGenerator3::EchoProgress progress; - progress.Dir = lg->GetBinaryDirectory(); - progress.Dir += "/CMakeFiles"; + progress.Dir = cmStrCat(lg->GetBinaryDirectory(), "/CMakeFiles"); { std::ostringstream progressArg; const char* sep = ""; @@ -697,7 +674,7 @@ void cmGlobalUnixMakefileGenerator3::WriteConvenienceRules2( if (const char* tgtMsg = this->GetCMakeInstance()->GetState()->GetGlobalProperty( "TARGET_MESSAGES")) { - targetMessages = cmSystemTools::IsOn(tgtMsg); + targetMessages = cmIsOn(tgtMsg); } if (targetMessages) { @@ -725,8 +702,7 @@ void cmGlobalUnixMakefileGenerator3::WriteConvenienceRules2( progCmd << " " << this->CountProgressMarksInTarget(gtarget, emitted); commands.push_back(progCmd.str()); } - std::string tmp = "CMakeFiles/"; - tmp += "Makefile2"; + std::string tmp = "CMakeFiles/Makefile2"; commands.push_back(lg->GetRecursiveMakeCall(tmp, localName)); { std::ostringstream progCmd; @@ -741,8 +717,7 @@ void cmGlobalUnixMakefileGenerator3::WriteConvenienceRules2( if (regenerate) { depends.emplace_back("cmake_check_build_system"); } - localName = lg->GetRelativeTargetDirectory(gtarget); - localName += "/rule"; + localName = cmStrCat(lg->GetRelativeTargetDirectory(gtarget), "/rule"); lg->WriteMakeRule(ruleFileStream, "Build rule for subdir invocation for target.", localName, depends, commands, true); @@ -756,8 +731,8 @@ void cmGlobalUnixMakefileGenerator3::WriteConvenienceRules2( // Add rules to prepare the target for installation. if (gtarget->NeedRelinkBeforeInstall(lg->GetConfigName())) { - localName = lg->GetRelativeTargetDirectory(gtarget); - localName += "/preinstall"; + localName = + cmStrCat(lg->GetRelativeTargetDirectory(gtarget), "/preinstall"); depends.clear(); commands.clear(); commands.push_back(lg->GetRecursiveMakeCall(makefileName, localName)); @@ -776,8 +751,7 @@ void cmGlobalUnixMakefileGenerator3::WriteConvenienceRules2( // add the clean rule localName = lg->GetRelativeTargetDirectory(gtarget); - makeTargetName = localName; - makeTargetName += "/clean"; + makeTargetName = cmStrCat(localName, "/clean"); depends.clear(); commands.clear(); commands.push_back( @@ -896,9 +870,9 @@ void cmGlobalUnixMakefileGenerator3::AppendGlobalTargetDepends( } cmLocalUnixMakefileGenerator3* lg3 = static_cast<cmLocalUnixMakefileGenerator3*>(dep->GetLocalGenerator()); - std::string tgtName = - lg3->GetRelativeTargetDirectory(const_cast<cmGeneratorTarget*>(dep)); - tgtName += "/all"; + std::string tgtName = cmStrCat( + lg3->GetRelativeTargetDirectory(const_cast<cmGeneratorTarget*>(dep)), + "/all"); depends.push_back(tgtName); } } @@ -941,8 +915,7 @@ void cmGlobalUnixMakefileGenerator3::WriteHelpRule( (type == cmStateEnums::UTILITY)) { std::string const& name = target->GetName(); if (emittedTargets.insert(name).second) { - path = "... "; - path += name; + path = cmStrCat("... ", name); lg->AppendEcho(commands, path); } } @@ -950,8 +923,7 @@ void cmGlobalUnixMakefileGenerator3::WriteHelpRule( } } for (std::string const& o : lg->GetLocalHelp()) { - path = "... "; - path += o; + path = cmStrCat("... ", o); lg->AppendEcho(commands, path); } lg->WriteMakeRule(ruleFileStream, "Help Target", "help", no_depends, diff --git a/Source/cmGlobalVisualStudio10Generator.cxx b/Source/cmGlobalVisualStudio10Generator.cxx index 4a3cadd..48b17c0 100644 --- a/Source/cmGlobalVisualStudio10Generator.cxx +++ b/Source/cmGlobalVisualStudio10Generator.cxx @@ -325,7 +325,7 @@ bool cmGlobalVisualStudio10Generator::SetGeneratorToolset( bool cmGlobalVisualStudio10Generator::ParseGeneratorToolset( std::string const& ts, cmMakefile* mf) { - std::vector<std::string> const fields = cmSystemTools::tokenize(ts, ","); + std::vector<std::string> const fields = cmTokenize(ts, ","); std::vector<std::string>::const_iterator fi = fields.begin(); if (fi == fields.end()) { return true; @@ -678,9 +678,9 @@ std::string cmGlobalVisualStudio10Generator::FindMSBuildCommand() std::string mskey; // Search in standard location. - mskey = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\"; - mskey += this->GetToolsVersion(); - mskey += ";MSBuildToolsPath"; + mskey = cmStrCat( + "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\", + this->GetToolsVersion(), ";MSBuildToolsPath"); if (cmSystemTools::ReadRegistryValue(mskey.c_str(), msbuild, cmSystemTools::KeyWOW64_32)) { cmSystemTools::ConvertToUnixSlashes(msbuild); @@ -720,8 +720,8 @@ bool cmGlobalVisualStudio10Generator::FindVCTargetsPath(cmMakefile* mf) // In a try-compile we are given the outer CMakeFiles directory. wd = this->ConfiguredFilesPath; } else { - wd = this->GetCMakeInstance()->GetHomeOutputDirectory(); - wd += "/CMakeFiles"; + wd = cmStrCat(this->GetCMakeInstance()->GetHomeOutputDirectory(), + "/CMakeFiles"); } wd += "/"; wd += cmVersion::GetCMakeVersion(); @@ -905,8 +905,7 @@ cmGlobalVisualStudio10Generator::GenerateBuildCommand( { std::string slnFile; if (!projectDir.empty()) { - slnFile = projectDir; - slnFile += "/"; + slnFile = cmStrCat(projectDir, '/'); } slnFile += projectName; slnFile += ".sln"; @@ -953,8 +952,7 @@ cmGlobalVisualStudio10Generator::GenerateBuildCommand( makeCommand.Add(std::string(projectName) + ".sln"); makeCommand.Add("/t:Clean"); } else { - std::string targetProject(tname); - targetProject += ".vcxproj"; + std::string targetProject = cmStrCat(tname, ".vcxproj"); if (targetProject.find('/') == std::string::npos) { // it might be in a subdir if (cmSlnProjectEntry const* proj = slnData.GetProjectByName(tname)) { @@ -1037,14 +1035,12 @@ std::string cmGlobalVisualStudio10Generator::GenerateRuleFile( { // The VS 10 generator needs to create the .rule files on disk. // Hide them away under the CMakeFiles directory. - std::string ruleDir = this->GetCMakeInstance()->GetHomeOutputDirectory(); - ruleDir += "/CMakeFiles"; - ruleDir += "/"; - ruleDir += cmSystemTools::ComputeStringMD5( - cmSystemTools::GetFilenamePath(output).c_str()); - std::string ruleFile = ruleDir + "/"; - ruleFile += cmSystemTools::GetFilenameName(output); - ruleFile += ".rule"; + std::string ruleDir = cmStrCat( + this->GetCMakeInstance()->GetHomeOutputDirectory(), "/CMakeFiles/", + cmSystemTools::ComputeStringMD5( + cmSystemTools::GetFilenamePath(output).c_str())); + std::string ruleFile = + cmStrCat(ruleDir, '/', cmSystemTools::GetFilenameName(output), ".rule"); return ruleFile; } diff --git a/Source/cmGlobalVisualStudio71Generator.cxx b/Source/cmGlobalVisualStudio71Generator.cxx index 8e67fad..e8e9ece 100644 --- a/Source/cmGlobalVisualStudio71Generator.cxx +++ b/Source/cmGlobalVisualStudio71Generator.cxx @@ -145,10 +145,8 @@ void cmGlobalVisualStudio71Generator::WriteProjectDepends( for (std::string const& name : depends) { std::string guid = this->GetGUID(name); if (guid.empty()) { - std::string m = "Target: "; - m += target->GetName(); - m += " depends on unknown target: "; - m += name; + std::string m = cmStrCat("Target: ", target->GetName(), + " depends on unknown target: ", name); cmSystemTools::Error(m); } fout << "\t\t{" << guid << "} = {" << guid << "}\n"; @@ -201,7 +199,7 @@ void cmGlobalVisualStudio71Generator::WriteProjectConfigurations( if (target.GetProperty("EXTERNAL_MSPROJECT")) { if (const char* m = target.GetProperty("MAP_IMPORTED_CONFIG_" + cmSystemTools::UpperCase(i))) { - cmSystemTools::ExpandListArgument(m, mapConfig); + cmExpandList(m, mapConfig); if (!mapConfig.empty()) { dstConfig = mapConfig[0].c_str(); } diff --git a/Source/cmGlobalVisualStudio7Generator.cxx b/Source/cmGlobalVisualStudio7Generator.cxx index bead0e3..258e300 100644 --- a/Source/cmGlobalVisualStudio7Generator.cxx +++ b/Source/cmGlobalVisualStudio7Generator.cxx @@ -66,8 +66,9 @@ const std::string& cmGlobalVisualStudio7Generator::GetIntelProjectVersion() // Compute the version of the Intel plugin to the VS IDE. // If the key does not exist then use a default guess. std::string intelVersion; - std::string vskey = this->GetRegistryBase(); - vskey += "\\Packages\\" CM_INTEL_PLUGIN_GUID ";ProductVersion"; + std::string vskey = + cmStrCat(this->GetRegistryBase(), + "\\Packages\\" CM_INTEL_PLUGIN_GUID ";ProductVersion"); cmSystemTools::ReadRegistryValue(vskey, intelVersion, cmSystemTools::KeyWOW64_32); unsigned int intelVersionNumber = ~0u; @@ -153,8 +154,9 @@ std::string cmGlobalVisualStudio7Generator::FindDevEnvCommand() } // Search where VS15Preview places it. - vskey = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VS7;"; - vskey += this->GetIDEVersion(); + vskey = cmStrCat( + "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VS7;", + this->GetIDEVersion()); if (cmSystemTools::ReadRegistryValue(vskey.c_str(), vscmd, cmSystemTools::KeyWOW64_32)) { cmSystemTools::ConvertToUnixSlashes(vscmd); @@ -256,7 +258,7 @@ cmLocalGenerator* cmGlobalVisualStudio7Generator::CreateLocalGenerator( return lg; } -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) Json::Value cmGlobalVisualStudio7Generator::GetJson() const { Json::Value generator = this->cmGlobalVisualStudioGenerator::GetJson(); @@ -294,10 +296,8 @@ void cmGlobalVisualStudio7Generator::OutputSLNFile( return; } this->CurrentProject = root->GetProjectName(); - std::string fname = root->GetCurrentBinaryDirectory(); - fname += "/"; - fname += root->GetProjectName(); - fname += ".sln"; + std::string fname = cmStrCat(root->GetCurrentBinaryDirectory(), '/', + root->GetProjectName(), ".sln"); cmGeneratedFileStream fout(fname.c_str()); fout.SetCopyIfDifferent(true); if (!fout) { @@ -512,15 +512,14 @@ void cmGlobalVisualStudio7Generator::WriteSLNGlobalSections( } fout << "\tGlobalSection(" << name << ") = " << sectionType << "\n"; std::vector<std::string> keyValuePairs; - cmSystemTools::ExpandListArgument(root->GetMakefile()->GetProperty(it), - keyValuePairs); + cmExpandList(root->GetMakefile()->GetProperty(it), keyValuePairs); for (std::string const& itPair : keyValuePairs) { const std::string::size_type posEqual = itPair.find('='); if (posEqual != std::string::npos) { const std::string key = - cmSystemTools::TrimWhitespace(itPair.substr(0, posEqual)); + cmTrimWhitespace(itPair.substr(0, posEqual)); const std::string value = - cmSystemTools::TrimWhitespace(itPair.substr(posEqual + 1)); + cmTrimWhitespace(itPair.substr(posEqual + 1)); fout << "\t\t" << key << " = " << value << "\n"; if (key == "SolutionGuid") { addGuid = false; @@ -555,12 +554,10 @@ std::string cmGlobalVisualStudio7Generator::WriteUtilityDepend( { std::vector<std::string> configs; target->Target->GetMakefile()->GetConfigurations(configs); - std::string pname = target->GetName(); - pname += "_UTILITY"; - std::string fname = target->GetLocalGenerator()->GetCurrentBinaryDirectory(); - fname += "/"; - fname += pname; - fname += ".vcproj"; + std::string pname = cmStrCat(target->GetName(), "_UTILITY"); + std::string fname = + cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(), '/', + pname, ".vcproj"); cmGeneratedFileStream fout(fname.c_str()); fout.SetCopyIfDifferent(true); std::string guid = this->GetGUID(pname.c_str()); @@ -617,9 +614,8 @@ std::string cmGlobalVisualStudio7Generator::GetGUID(std::string const& name) return std::string(storedGUID); } // Compute a GUID that is deterministic but unique to the build tree. - std::string input = this->CMakeInstance->GetState()->GetBinaryDirectory(); - input += "|"; - input += name; + std::string input = + cmStrCat(this->CMakeInstance->GetState()->GetBinaryDirectory(), '|', name); cmUuid uuidGenerator; @@ -668,8 +664,7 @@ std::set<std::string> cmGlobalVisualStudio7Generator::IsPartOfDefaultBuild( cmGeneratorExpression ge; std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(propertyValue); - if (cmSystemTools::IsOn( - cge->Evaluate(target->GetLocalGenerator(), i))) { + if (cmIsOn(cge->Evaluate(target->GetLocalGenerator(), i))) { activeConfigs.insert(i); } } @@ -685,7 +680,7 @@ std::set<std::string> cmGlobalVisualStudio7Generator::IsPartOfDefaultBuild( for (std::string const& i : configs) { const char* propertyValue = target->GetFeature("EXCLUDE_FROM_DEFAULT_BUILD", i); - if (cmSystemTools::IsOff(propertyValue)) { + if (cmIsOff(propertyValue)) { activeConfigs.insert(i); } } diff --git a/Source/cmGlobalVisualStudio7Generator.h b/Source/cmGlobalVisualStudio7Generator.h index f004afb..9b84732 100644 --- a/Source/cmGlobalVisualStudio7Generator.h +++ b/Source/cmGlobalVisualStudio7Generator.h @@ -23,7 +23,7 @@ public: //! Create a local generator appropriate to this Global Generator cmLocalGenerator* CreateLocalGenerator(cmMakefile* mf) override; -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) Json::Value GetJson() const override; #endif diff --git a/Source/cmGlobalVisualStudio8Generator.cxx b/Source/cmGlobalVisualStudio8Generator.cxx index cc6e421..b0c065f 100644 --- a/Source/cmGlobalVisualStudio8Generator.cxx +++ b/Source/cmGlobalVisualStudio8Generator.cxx @@ -26,9 +26,9 @@ std::string cmGlobalVisualStudio8Generator::FindDevEnvCommand() { // First look for VCExpress. std::string vsxcmd; - std::string vsxkey = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VCExpress\\"; - vsxkey += this->GetIDEVersion(); - vsxkey += ";InstallDir"; + std::string vsxkey = + cmStrCat("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VCExpress\\", + this->GetIDEVersion(), ";InstallDir"); if (cmSystemTools::ReadRegistryValue(vsxkey.c_str(), vsxcmd, cmSystemTools::KeyWOW64_32)) { cmSystemTools::ConvertToUnixSlashes(vsxcmd); @@ -116,20 +116,17 @@ bool cmGlobalVisualStudio8Generator::AddCheckTarget() // Create a list of all stamp files for this project. std::vector<std::string> stamps; - std::string stampList = "CMakeFiles/"; - stampList += cmGlobalVisualStudio8Generator::GetGenerateStampList(); + std::string stampList = cmStrCat( + "CMakeFiles/", cmGlobalVisualStudio8Generator::GetGenerateStampList()); { std::string stampListFile = - generators[0]->GetMakefile()->GetCurrentBinaryDirectory(); - stampListFile += "/"; - stampListFile += stampList; + cmStrCat(generators[0]->GetMakefile()->GetCurrentBinaryDirectory(), '/', + stampList); std::string stampFile; cmGeneratedFileStream fout(stampListFile.c_str()); for (cmLocalGenerator const* gi : generators) { - stampFile = gi->GetMakefile()->GetCurrentBinaryDirectory(); - stampFile += "/"; - stampFile += "CMakeFiles/"; - stampFile += "generate.stamp"; + stampFile = cmStrCat(gi->GetMakefile()->GetCurrentBinaryDirectory(), + "/CMakeFiles/generate.stamp"); fout << stampFile << "\n"; stamps.push_back(stampFile); } @@ -176,11 +173,9 @@ bool cmGlobalVisualStudio8Generator::AddCheckTarget() // Create a rule to re-run CMake. cmCustomCommandLine commandLine; commandLine.push_back(cmSystemTools::GetCMakeCommand()); - std::string argS = "-S"; - argS += lg->GetSourceDirectory(); + std::string argS = cmStrCat("-S", lg->GetSourceDirectory()); commandLine.push_back(argS); - std::string argB = "-B"; - argB += lg->GetBinaryDirectory(); + std::string argB = cmStrCat("-B", lg->GetBinaryDirectory()); commandLine.push_back(argB); commandLine.push_back("--check-stamp-list"); commandLine.push_back(stampList.c_str()); @@ -250,7 +245,7 @@ void cmGlobalVisualStudio8Generator::WriteProjectConfigurations( if (target.GetProperty("EXTERNAL_MSPROJECT")) { if (const char* m = target.GetProperty("MAP_IMPORTED_CONFIG_" + cmSystemTools::UpperCase(i))) { - cmSystemTools::ExpandListArgument(m, mapConfig); + cmExpandList(m, mapConfig); if (!mapConfig.empty()) { dstConfig = mapConfig[0].c_str(); } @@ -299,7 +294,7 @@ bool cmGlobalVisualStudio8Generator::DeployInhibited( cmGeneratorExpression ge; std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(propStr); std::string prop = cge->Evaluate(target.LocalGenerator, config); - rVal = cmSystemTools::IsOn(prop); + rVal = cmIsOn(prop); } return rVal; } diff --git a/Source/cmGlobalVisualStudioGenerator.cxx b/Source/cmGlobalVisualStudioGenerator.cxx index ba541a9..bb6ad16 100644 --- a/Source/cmGlobalVisualStudioGenerator.cxx +++ b/Source/cmGlobalVisualStudioGenerator.cxx @@ -104,6 +104,9 @@ const char* cmGlobalVisualStudioGenerator::GetIDEVersion() const void cmGlobalVisualStudioGenerator::WriteSLNHeader(std::ostream& fout) { + char utf8bom[] = { char(0xEF), char(0xBB), char(0xBF) }; + fout.write(utf8bom, 3); + switch (this->Version) { case cmGlobalVisualStudioGenerator::VS9: fout << "Microsoft Visual Studio Solution File, Format Version 10.00\n"; @@ -224,8 +227,8 @@ void cmGlobalVisualStudioGenerator::AddExtraIDETargets() void cmGlobalVisualStudioGenerator::ComputeTargetObjectDirectory( cmGeneratorTarget* gt) const { - std::string dir = gt->LocalGenerator->GetCurrentBinaryDirectory(); - dir += "/"; + std::string dir = + cmStrCat(gt->LocalGenerator->GetCurrentBinaryDirectory(), '/'); std::string tgtDir = gt->LocalGenerator->GetTargetDirectory(gt); if (!tgtDir.empty()) { dir += tgtDir; @@ -258,8 +261,8 @@ void cmGlobalVisualStudioGenerator::ConfigureCMakeVisualStudioMacros() std::string dir = this->GetUserMacrosDirectory(); if (!dir.empty()) { - std::string src = cmSystemTools::GetCMakeRoot(); - src += "/Templates/" CMAKE_VSMACROS_FILENAME; + std::string src = cmStrCat(cmSystemTools::GetCMakeRoot(), + "/Templates/" CMAKE_VSMACROS_FILENAME); std::string dst = dir + "/CMakeMacros/" CMAKE_VSMACROS_FILENAME; @@ -306,10 +309,9 @@ void cmGlobalVisualStudioGenerator::CallVisualStudioMacro( if (vsSolutionFile) { topLevelSlnName = vsSolutionFile; } else { - topLevelSlnName = mf->GetCurrentBinaryDirectory(); - topLevelSlnName += "/"; - topLevelSlnName += this->LocalGenerators[0]->GetProjectName(); - topLevelSlnName += ".sln"; + topLevelSlnName = + cmStrCat(mf->GetCurrentBinaryDirectory(), '/', + this->LocalGenerators[0]->GetProjectName(), ".sln"); } if (m == MacroReload) { @@ -487,7 +489,7 @@ bool cmGlobalVisualStudioGenerator::FindMakeProgram(cmMakefile* mf) // Visual Studio generators know how to lookup their build tool // directly instead of needing a helper module to do it, so we // do not actually need to put CMAKE_MAKE_PROGRAM into the cache. - if (cmSystemTools::IsOff(mf->GetDefinition("CMAKE_MAKE_PROGRAM"))) { + if (cmIsOff(mf->GetDefinition("CMAKE_MAKE_PROGRAM"))) { mf->AddDefinition("CMAKE_MAKE_PROGRAM", this->GetVSMakeProgram()); } return true; diff --git a/Source/cmGlobalXCodeGenerator.cxx b/Source/cmGlobalXCodeGenerator.cxx index 8f4ae62..a8f27d6 100644 --- a/Source/cmGlobalXCodeGenerator.cxx +++ b/Source/cmGlobalXCodeGenerator.cxx @@ -38,12 +38,12 @@ struct cmLinkImplementation; -#if defined(CMAKE_BUILD_WITH_CMAKE) && defined(__APPLE__) +#if !defined(CMAKE_BOOTSTRAP) && defined(__APPLE__) # define HAVE_APPLICATION_SERVICES # include <ApplicationServices/ApplicationServices.h> #endif -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) # include "cmXMLParser.h" // parse the xml file storing the installed version of Xcode on @@ -188,7 +188,7 @@ cmGlobalGenerator* cmGlobalXCodeGenerator::Factory::CreateGlobalGenerator( if (name != GetActualName()) { return nullptr; } -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) cmXcodeVersionParser parser; std::string versionFile; { @@ -240,7 +240,7 @@ bool cmGlobalXCodeGenerator::FindMakeProgram(cmMakefile* mf) // The Xcode generator knows how to lookup its build tool // directly instead of needing a helper module to do it, so we // do not actually need to put CMAKE_MAKE_PROGRAM into the cache. - if (cmSystemTools::IsOff(mf->GetDefinition("CMAKE_MAKE_PROGRAM"))) { + if (cmIsOff(mf->GetDefinition("CMAKE_MAKE_PROGRAM"))) { mf->AddDefinition("CMAKE_MAKE_PROGRAM", this->GetXcodeBuildCommand()); } return true; @@ -349,13 +349,10 @@ cmGlobalXCodeGenerator::GenerateBuildCommand( if (!projectName.empty()) { makeCommand.Add("-project"); - std::string projectArg = projectName; - projectArg += ".xcode"; - projectArg += "proj"; + std::string projectArg = cmStrCat(projectName, ".xcodeproj"); makeCommand.Add(projectArg); } - if (std::find(targetNames.begin(), targetNames.end(), "clean") != - targetNames.end()) { + if (cmContains(targetNames, "clean")) { makeCommand.Add("clean"); makeCommand.Add("-target", "ALL_BUILD"); } else { @@ -476,8 +473,8 @@ void cmGlobalXCodeGenerator::SetGenerationRoot(cmLocalGenerator* root) this->CurrentLocalGenerator->GetCurrentBinaryDirectory(), this->ProjectOutputDirectoryComponents); - this->CurrentXCodeHackMakefile = root->GetCurrentBinaryDirectory(); - this->CurrentXCodeHackMakefile += "/CMakeScripts"; + this->CurrentXCodeHackMakefile = + cmStrCat(root->GetCurrentBinaryDirectory(), "/CMakeScripts"); cmSystemTools::MakeDirectory(this->CurrentXCodeHackMakefile); this->CurrentXCodeHackMakefile += "/XCODE_DEPEND_HELPER.make"; } @@ -487,8 +484,7 @@ std::string cmGlobalXCodeGenerator::PostBuildMakeTarget( { std::string target = tName; std::replace(target.begin(), target.end(), ' ', '_'); - std::string out = "PostBuild." + target; - out += "." + configName; + std::string out = cmStrCat("PostBuild.", target, '.', configName); return out; } @@ -596,8 +592,8 @@ void cmGlobalXCodeGenerator::CreateReRunCMakeFile( lfiles.emplace_back(cm->GetGlobVerifyStamp()); } - this->CurrentReRunCMakeMakefile = root->GetCurrentBinaryDirectory(); - this->CurrentReRunCMakeMakefile += "/CMakeScripts"; + this->CurrentReRunCMakeMakefile = + cmStrCat(root->GetCurrentBinaryDirectory(), "/CMakeScripts"); cmSystemTools::MakeDirectory(this->CurrentReRunCMakeMakefile); this->CurrentReRunCMakeMakefile += "/ReRunCMake.make"; cmGeneratedFileStream makefileStream(this->CurrentReRunCMakeMakefile); @@ -615,10 +611,8 @@ void cmGlobalXCodeGenerator::CreateReRunCMakeFile( } makefileStream << "\n"; - std::string checkCache = root->GetBinaryDirectory(); - checkCache += "/"; - checkCache += "CMakeFiles/"; - checkCache += "cmake.check_cache"; + std::string checkCache = + cmStrCat(root->GetBinaryDirectory(), "/CMakeFiles/cmake.check_cache"); if (cm->DoWriteGlobVerifyTarget()) { makefileStream << ".NOTPARALLEL:\n\n"; @@ -882,7 +876,7 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeSourceFile( if (extraFileAttributes) { // Expand the list of attributes. std::vector<std::string> attributes; - cmSystemTools::ExpandListArgument(extraFileAttributes, attributes); + cmExpandList(extraFileAttributes, attributes); // Store the attributes. for (const auto& attribute : attributes) { @@ -900,11 +894,10 @@ void cmGlobalXCodeGenerator::AddXCodeProjBuildRule( cmGeneratorTarget* target, std::vector<cmSourceFile*>& sources) const { std::string listfile = - target->GetLocalGenerator()->GetCurrentSourceDirectory(); - listfile += "/CMakeLists.txt"; + cmStrCat(target->GetLocalGenerator()->GetCurrentSourceDirectory(), + "/CMakeLists.txt"); cmSourceFile* srcCMakeLists = target->Makefile->GetOrCreateSource(listfile); - if (std::find(sources.begin(), sources.end(), srcCMakeLists) == - sources.end()) { + if (!cmContains(sources, srcCMakeLists)) { sources.push_back(srcCMakeLists); } } @@ -1398,13 +1391,9 @@ void cmGlobalXCodeGenerator::ForceLinkerLanguage(cmGeneratorTarget* gtgt) // linker language. This should convince Xcode to choose the proper // language. cmMakefile* mf = gtgt->Target->GetMakefile(); - std::string fname = gtgt->GetLocalGenerator()->GetCurrentBinaryDirectory(); - fname += "/CMakeFiles"; - fname += "/"; - fname += gtgt->GetName(); - fname += "-CMakeForceLinker"; - fname += "."; - fname += cmSystemTools::LowerCase(llang); + std::string fname = cmStrCat( + gtgt->GetLocalGenerator()->GetCurrentBinaryDirectory(), "/CMakeFiles/", + gtgt->GetName(), "-CMakeForceLinker.", cmSystemTools::LowerCase(llang)); { cmGeneratedFileStream fout(fname); fout << "\n"; @@ -1417,10 +1406,8 @@ void cmGlobalXCodeGenerator::ForceLinkerLanguage(cmGeneratorTarget* gtgt) bool cmGlobalXCodeGenerator::IsHeaderFile(cmSourceFile* sf) { - const std::vector<std::string>& hdrExts = - this->CMakeInstance->GetHeaderExtensions(); - return (std::find(hdrExts.begin(), hdrExts.end(), sf->GetExtension()) != - hdrExts.end()); + return cmContains(this->CMakeInstance->GetHeaderExtensions(), + sf->GetExtension()); } cmXCodeObject* cmGlobalXCodeGenerator::CreateBuildPhase( @@ -1461,15 +1448,11 @@ void cmGlobalXCodeGenerator::CreateCustomCommands( cmd[0].push_back(cmSystemTools::GetCMakeCommand()); cmd[0].push_back("-E"); cmd[0].push_back("cmake_symlink_library"); - std::string str_file = "$<TARGET_FILE:"; - str_file += gtgt->GetName(); - str_file += ">"; - std::string str_so_file = "$<TARGET_SONAME_FILE:"; - str_so_file += gtgt->GetName(); - str_so_file += ">"; - std::string str_link_file = "$<TARGET_LINKER_FILE:"; - str_link_file += gtgt->GetName(); - str_link_file += ">"; + std::string str_file = cmStrCat("$<TARGET_FILE:", gtgt->GetName(), '>'); + std::string str_so_file = + cmStrCat("$<TARGET_SONAME_FILE:", gtgt->GetName(), '>'); + std::string str_link_file = + cmStrCat("$<TARGET_LINKER_FILE:", gtgt->GetName(), '>'); cmd[0].push_back(str_file); cmd[0].push_back(str_so_file); cmd[0].push_back(str_link_file); @@ -1636,15 +1619,11 @@ void cmGlobalXCodeGenerator::AddCommandsToBuildPhase( cmXCodeObject* buildphase, cmGeneratorTarget* target, std::vector<cmCustomCommand> const& commands, const char* name) { - std::string dir = this->CurrentLocalGenerator->GetCurrentBinaryDirectory(); - dir += "/CMakeScripts"; + std::string dir = cmStrCat( + this->CurrentLocalGenerator->GetCurrentBinaryDirectory(), "/CMakeScripts"); cmSystemTools::MakeDirectory(dir); - std::string makefile = dir; - makefile += "/"; - makefile += target->GetName(); - makefile += "_"; - makefile += name; - makefile += ".make"; + std::string makefile = + cmStrCat(dir, '/', target->GetName(), '_', name, ".make"); for (const auto& currentConfig : this->CurrentConfigurationTypes) { this->CreateCustomRulesMakefile(makefile.c_str(), target, commands, @@ -1653,12 +1632,10 @@ void cmGlobalXCodeGenerator::AddCommandsToBuildPhase( std::string cdir = this->CurrentLocalGenerator->GetCurrentBinaryDirectory(); cdir = this->ConvertToRelativeForMake(cdir); - std::string makecmd = "make -C "; - makecmd += cdir; - makecmd += " -f "; - makecmd += this->ConvertToRelativeForMake((makefile + "$CONFIGURATION")); - makecmd += " OBJDIR=$(basename \"$OBJECT_FILE_DIR_normal\")"; - makecmd += " all"; + std::string makecmd = + cmStrCat("make -C ", cdir, " -f ", + this->ConvertToRelativeForMake((makefile + "$CONFIGURATION")), + " OBJDIR=$(basename \"$OBJECT_FILE_DIR_normal\") all"); buildphase->AddAttribute("shellScript", this->CreateString(makecmd)); buildphase->AddAttribute("showEnvVarsInLog", this->CreateString("0")); } @@ -1667,8 +1644,7 @@ void cmGlobalXCodeGenerator::CreateCustomRulesMakefile( const char* makefileBasename, cmGeneratorTarget* target, std::vector<cmCustomCommand> const& commands, const std::string& configName) { - std::string makefileName = makefileBasename; - makefileName += configName; + std::string makefileName = cmStrCat(makefileBasename, configName); cmGeneratedFileStream makefileStream(makefileName); if (!makefileStream) { return; @@ -1731,9 +1707,10 @@ void cmGlobalXCodeGenerator::CreateCustomRulesMakefile( makefileStream << "\n"; if (const char* comment = ccg.GetComment()) { - std::string echo_cmd = "echo "; - echo_cmd += (this->CurrentLocalGenerator->EscapeForShell( - comment, ccg.GetCC().GetEscapeAllowMakeVars())); + std::string echo_cmd = + cmStrCat("echo ", + (this->CurrentLocalGenerator->EscapeForShell( + comment, ccg.GetCC().GetEscapeAllowMakeVars()))); makefileStream << "\t" << echo_cmd << "\n"; } @@ -1774,8 +1751,7 @@ void cmGlobalXCodeGenerator::AddPositionIndependentLinkAttribute( } buildSettings->AddAttribute( - "LD_NO_PIE", - this->CreateString(cmSystemTools::IsOn(PICValue) ? "NO" : "YES")); + "LD_NO_PIE", this->CreateString(cmIsOn(PICValue) ? "NO" : "YES")); } void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt, @@ -1882,8 +1858,8 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt, targetLinkFlags); } if (!configName.empty()) { - std::string linkFlagsVar = "LINK_FLAGS_"; - linkFlagsVar += cmSystemTools::UpperCase(configName); + std::string linkFlagsVar = + cmStrCat("LINK_FLAGS_", cmSystemTools::UpperCase(configName)); if (const char* linkFlags = gtgt->GetProperty(linkFlagsVar)) { this->CurrentLocalGenerator->AppendFlags(extraLinkOptions, linkFlags); } @@ -2135,8 +2111,7 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt, for (auto& include : includes) { if (this->NameResolvesToFramework(include)) { - std::string frameworkDir = include; - frameworkDir += "/../"; + std::string frameworkDir = cmStrCat(include, "/../"); frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir); if (emitted.insert(frameworkDir).second) { std::string incpath = this->XCodeEscapePath(frameworkDir); @@ -2482,20 +2457,16 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateUtilityTarget( std::string cmGlobalXCodeGenerator::AddConfigurations(cmXCodeObject* target, cmGeneratorTarget* gtgt) { - std::vector<std::string> const configVector = - cmSystemTools::ExpandedListArgument( - this->CurrentMakefile->GetRequiredDefinition( - "CMAKE_CONFIGURATION_TYPES")); + std::vector<std::string> const configVector = cmExpandedList( + this->CurrentMakefile->GetRequiredDefinition("CMAKE_CONFIGURATION_TYPES")); cmXCodeObject* configlist = this->CreateObject(cmXCodeObject::XCConfigurationList); cmXCodeObject* buildConfigurations = this->CreateObject(cmXCodeObject::OBJECT_LIST); configlist->AddAttribute("buildConfigurations", buildConfigurations); - std::string comment = "Build configuration list for "; - comment += cmXCodeObject::PBXTypeNames[target->GetIsA()]; - comment += " \""; - comment += gtgt->GetName(); - comment += "\""; + std::string comment = cmStrCat("Build configuration list for ", + cmXCodeObject::PBXTypeNames[target->GetIsA()], + " \"", gtgt->GetName(), '"'); configlist->SetComment(comment); target->AddAttribute("buildConfigurationList", this->CreateObjectReference(configlist)); @@ -2623,9 +2594,7 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeTarget( } std::string fullName; if (gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY) { - fullName = "lib"; - fullName += gtgt->GetName(); - fullName += ".a"; + fullName = cmStrCat("lib", gtgt->GetName(), ".a"); } else { fullName = gtgt->GetFullName(defConfig); } @@ -2662,8 +2631,7 @@ cmXCodeObject* cmGlobalXCodeGenerator::FindXCodeTarget( std::string cmGlobalXCodeGenerator::GetOrCreateId(const std::string& name, const std::string& id) { - std::string guidStoreName = name; - guidStoreName += "_GUID_CMAKE"; + std::string guidStoreName = cmStrCat(name, "_GUID_CMAKE"); const char* storedGUID = this->CMakeInstance->GetCacheDefinition(guidStoreName); @@ -2718,9 +2686,7 @@ void cmGlobalXCodeGenerator::AppendOrAddBuildSetting(cmXCodeObject* settings, if (!attr) { settings->AddAttribute(attribute, this->CreateString(value)); } else { - std::string oldValue = attr->GetString(); - oldValue += " "; - oldValue += value; + std::string oldValue = cmStrCat(attr->GetString(), ' ', value); attr->SetString(oldValue); } } @@ -2885,8 +2851,8 @@ bool cmGlobalXCodeGenerator::CreateGroups( // Add CMakeLists.txt file for user convenience. { std::string listfile = - gtgt->GetLocalGenerator()->GetCurrentSourceDirectory(); - listfile += "/CMakeLists.txt"; + cmStrCat(gtgt->GetLocalGenerator()->GetCurrentSourceDirectory(), + "/CMakeLists.txt"); cmSourceFile* sf = gtgt->Makefile->GetOrCreateSource(listfile); addSourceToGroup(sf->GetFullPath()); } @@ -2928,12 +2894,10 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateOrGetPBXGroup( std::string target; const std::string targetFolder = gtgt->GetEffectiveFolderName(); if (!targetFolder.empty()) { - target = targetFolder; - target += "/"; + target = cmStrCat(targetFolder, '/'); } target += gtgt->GetName(); - s = target + "/"; - s += sg->GetFullName(); + s = cmStrCat(target, '/', sg->GetFullName()); std::map<std::string, cmXCodeObject*>::iterator it = this->GroupNameMap.find(s); if (it != this->GroupNameMap.end()) { @@ -2945,8 +2909,7 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateOrGetPBXGroup( if (it != this->TargetGroup.end()) { tgroup = it->second; } else { - std::vector<std::string> tgt_folders = - cmSystemTools::tokenize(target, "/"); + std::vector<std::string> tgt_folders = cmTokenize(target, "/"); std::string curr_tgt_folder; for (std::vector<std::string>::size_type i = 0; i < tgt_folders.size(); i++) { @@ -2978,10 +2941,8 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateOrGetPBXGroup( // It's a recursive folder structure, let's find the real parent group if (sg->GetFullName() != sg->GetName()) { - std::string curr_folder = target; - curr_folder += "/"; - for (auto const& folder : - cmSystemTools::tokenize(sg->GetFullName(), "\\")) { + std::string curr_folder = cmStrCat(target, '/'); + for (auto const& folder : cmTokenize(sg->GetFullName(), "\\")) { curr_folder += folder; std::map<std::string, cmXCodeObject*>::iterator i_folder = this->GroupNameMap.find(curr_folder); @@ -2993,7 +2954,7 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateOrGetPBXGroup( } else { tgroup = i_folder->second; } - curr_folder = curr_folder + "\\"; + curr_folder += "\\"; } return tgroup; } @@ -3045,8 +3006,7 @@ bool cmGlobalXCodeGenerator::CreateXCodeObjects( this->RootObject = this->CreateObject(cmXCodeObject::PBXProject); this->RootObject->SetComment("Project object"); - std::string project_id = "PROJECT_"; - project_id += root->GetProjectName(); + std::string project_id = cmStrCat("PROJECT_", root->GetProjectName()); this->RootObject->SetId( this->GetOrCreateId(project_id, this->RootObject->GetId())); @@ -3097,10 +3057,8 @@ bool cmGlobalXCodeGenerator::CreateXCodeObjects( } configlist->AddAttribute("buildConfigurations", buildConfigurations); - std::string comment = "Build configuration list for PBXProject"; - comment += " \""; - comment += this->CurrentProject; - comment += "\""; + std::string comment = cmStrCat("Build configuration list for PBXProject \"", + this->CurrentProject, '"'); configlist->SetComment(comment); configlist->AddAttribute("defaultConfigurationIsVisible", this->CreateString("0")); @@ -3149,8 +3107,7 @@ bool cmGlobalXCodeGenerator::CreateXCodeObjects( this->CreateString(swiftVersion)); } - std::string symroot = root->GetCurrentBinaryDirectory(); - symroot += "/build"; + std::string symroot = cmStrCat(root->GetCurrentBinaryDirectory(), "/build"); buildSettings->AddAttribute("SYMROOT", this->CreateString(symroot)); for (auto& config : configs) { @@ -3207,15 +3164,9 @@ std::string cmGlobalXCodeGenerator::GetObjectsDirectory( const std::string& projName, const std::string& configName, const cmGeneratorTarget* t, const std::string& variant) const { - std::string dir = t->GetLocalGenerator()->GetCurrentBinaryDirectory(); - dir += "/"; - dir += projName; - dir += ".build/"; - dir += configName; - dir += "/"; - dir += t->GetName(); - dir += ".build/"; - dir += variant; + std::string dir = cmStrCat( + t->GetLocalGenerator()->GetCurrentBinaryDirectory(), '/', projName, + ".build/", configName, '/', t->GetName(), ".build/", variant); return dir; } @@ -3225,8 +3176,7 @@ void cmGlobalXCodeGenerator::ComputeArchitectures(cmMakefile* mf) const char* osxArch = mf->GetDefinition("CMAKE_OSX_ARCHITECTURES"); const char* sysroot = mf->GetDefinition("CMAKE_OSX_SYSROOT"); if (osxArch && sysroot) { - cmSystemTools::ExpandListArgument(std::string(osxArch), - this->Architectures); + cmExpandList(std::string(osxArch), this->Architectures); } if (this->Architectures.empty()) { @@ -3341,12 +3291,10 @@ void cmGlobalXCodeGenerator::CreateXCodeDependHackTarget( for (auto objLib : objlibs) { const std::string objLibName = objLib->GetName(); - std::string d = + std::string d = cmStrCat( this->GetObjectsDirectory(this->CurrentProject, configName, objLib, - OBJECT_LIBRARY_ARTIFACT_DIR); - d += "lib"; - d += objLibName; - d += ".a"; + OBJECT_LIBRARY_ARTIFACT_DIR), + "lib", objLibName, ".a"); std::string dependency = this->ConvertToRelativeForMake(d); makefileStream << "\\\n\t" << dependency; @@ -3363,10 +3311,8 @@ void cmGlobalXCodeGenerator::CreateXCodeDependHackTarget( std::string universal = this->GetObjectsDirectory( this->CurrentProject, configName, gt, "$(OBJDIR)/"); for (const auto& architecture : this->Architectures) { - std::string universalFile = universal; - universalFile += architecture; - universalFile += "/"; - universalFile += gt->GetFullName(configName); + std::string universalFile = cmStrCat(universal, architecture, '/', + gt->GetFullName(configName)); makefileStream << "\t/bin/rm -f " << this->ConvertToRelativeForMake(universalFile) << "\n"; @@ -3394,10 +3340,8 @@ void cmGlobalXCodeGenerator::OutputXCodeProject( if (!this->CreateXCodeObjects(root, generators)) { return; } - std::string xcodeDir = root->GetCurrentBinaryDirectory(); - xcodeDir += "/"; - xcodeDir += root->GetProjectName(); - xcodeDir += ".xcodeproj"; + std::string xcodeDir = cmStrCat(root->GetCurrentBinaryDirectory(), '/', + root->GetProjectName(), ".xcodeproj"); cmSystemTools::MakeDirectory(xcodeDir); std::string xcodeProjFile = xcodeDir + "/project.pbxproj"; cmGeneratedFileStream fout(xcodeProjFile); @@ -3471,12 +3415,12 @@ bool cmGlobalXCodeGenerator::OutputXCodeSharedSchemes( void cmGlobalXCodeGenerator::OutputXCodeWorkspaceSettings( const std::string& xcProjDir, bool hasGeneratedSchemes) { - std::string xcodeSharedDataDir = xcProjDir; - xcodeSharedDataDir += "/project.xcworkspace/xcshareddata"; + std::string xcodeSharedDataDir = + cmStrCat(xcProjDir, "/project.xcworkspace/xcshareddata"); cmSystemTools::MakeDirectory(xcodeSharedDataDir); - std::string workspaceSettingsFile = xcodeSharedDataDir; - workspaceSettingsFile += "/WorkspaceSettings.xcsettings"; + std::string workspaceSettingsFile = + cmStrCat(xcodeSharedDataDir, "/WorkspaceSettings.xcsettings"); cmGeneratedFileStream fout(workspaceSettingsFile); fout.SetCopyIfDifferent(true); @@ -3582,9 +3526,7 @@ std::string cmGlobalXCodeGenerator::RelativeToBinary(const std::string& p) std::string cmGlobalXCodeGenerator::XCodeEscapePath(const std::string& p) { if (p.find(' ') != std::string::npos) { - std::string t = "\""; - t += p; - t += "\""; + std::string t = cmStrCat('"', p, '"'); return t; } return p; @@ -3606,9 +3548,7 @@ std::string cmGlobalXCodeGenerator::LookupFlags( const std::string& varNameSuffix, const std::string& default_flags) { if (!varNameLang.empty()) { - std::string varName = varNamePrefix; - varName += varNameLang; - varName += varNameSuffix; + std::string varName = cmStrCat(varNamePrefix, varNameLang, varNameSuffix); if (const char* varValue = this->CurrentMakefile->GetDefinition(varName)) { if (*varValue) { return varValue; @@ -3629,7 +3569,7 @@ void cmGlobalXCodeGenerator::AppendDefines(BuildObjectListOrString& defs, // Expand the list of definitions. std::vector<std::string> defines; - cmSystemTools::ExpandListArgument(defines_list, defines); + cmExpandList(defines_list, defines); // Store the definitions in the string. this->AppendDefines(defs, defines, dflag); @@ -3643,8 +3583,7 @@ void cmGlobalXCodeGenerator::AppendDefines( std::string def; for (auto const& define : defines) { // Start with -D if requested. - def = dflag ? "-D" : ""; - def += define; + def = cmStrCat(dflag ? "-D" : "", define); // Append the flag with needed escapes. std::string tmp; @@ -3705,11 +3644,9 @@ void cmGlobalXCodeGenerator::AppendFlag(std::string& flags, std::string cmGlobalXCodeGenerator::ComputeInfoPListLocation( cmGeneratorTarget* target) { - std::string plist = target->GetLocalGenerator()->GetCurrentBinaryDirectory(); - plist += "/CMakeFiles"; - plist += "/"; - plist += target->GetName(); - plist += ".dir/Info.plist"; + std::string plist = + cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(), + "/CMakeFiles/", target->GetName(), ".dir/Info.plist"); return plist; } @@ -3743,7 +3680,7 @@ bool cmGlobalXCodeGenerator::UseEffectivePlatformName(cmMakefile* mf) const return mf->PlatformIsAppleEmbedded(); } - return cmSystemTools::IsOn(epnValue); + return cmIsOn(epnValue); } bool cmGlobalXCodeGenerator::ShouldStripResourcePath(cmMakefile*) const @@ -3756,10 +3693,10 @@ void cmGlobalXCodeGenerator::ComputeTargetObjectDirectory( cmGeneratorTarget* gt) const { std::string configName = this->GetCMakeCFGIntDir(); - std::string dir = this->GetObjectsDirectory( - "$(PROJECT_NAME)", configName, gt, "$(OBJECT_FILE_DIR_normal:base)/"); - dir += this->ObjectDirArch; - dir += "/"; + std::string dir = + cmStrCat(this->GetObjectsDirectory("$(PROJECT_NAME)", configName, gt, + "$(OBJECT_FILE_DIR_normal:base)/"), + this->ObjectDirArch, '/'); gt->ObjectDirectory = dir; } diff --git a/Source/cmGraphVizWriter.cxx b/Source/cmGraphVizWriter.cxx index 9befb78..c5b5522 100644 --- a/Source/cmGraphVizWriter.cxx +++ b/Source/cmGraphVizWriter.cxx @@ -15,6 +15,7 @@ #include "cmMakefile.h" #include "cmState.h" #include "cmStateSnapshot.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmTarget.h" #include "cmake.h" @@ -73,7 +74,8 @@ std::map<std::string, LinkLibraryScopeType> getScopedLinkLibrariesFromTarget( { char sep = ';'; std::map<std::string, LinkLibraryScopeType> tokens; - size_t start = 0, end = 0; + size_t start = 0; + size_t end = 0; const char* pInterfaceLinkLibraries = Target->GetProperty("INTERFACE_LINK_LIBRARIES"); @@ -234,8 +236,7 @@ void cmGraphVizWriter::ReadSettings( this->TargetsToIgnoreRegex.clear(); if (!ignoreTargetsRegexes.empty()) { std::vector<std::string> ignoreTargetsRegExVector; - cmSystemTools::ExpandListArgument(ignoreTargetsRegexes, - ignoreTargetsRegExVector); + cmExpandList(ignoreTargetsRegexes, ignoreTargetsRegExVector); for (std::string const& currentRegexString : ignoreTargetsRegExVector) { cmsys::RegularExpression currentRegex; if (!currentRegex.compile(currentRegexString)) { @@ -266,10 +267,8 @@ void cmGraphVizWriter::WriteTargetDependersFiles(const std::string& fileName) continue; } - std::string currentFilename = fileName; - currentFilename += "."; - currentFilename += ptr.first; - currentFilename += ".dependers"; + std::string currentFilename = + cmStrCat(fileName, '.', ptr.first, ".dependers"); cmGeneratedFileStream str(currentFilename); if (!str) { @@ -311,9 +310,7 @@ void cmGraphVizWriter::WritePerTargetFiles(const std::string& fileName) std::set<std::string> insertedConnections; std::set<std::string> insertedNodes; - std::string currentFilename = fileName; - currentFilename += "."; - currentFilename += ptr.first; + std::string currentFilename = cmStrCat(fileName, '.', ptr.first); cmGeneratedFileStream str(currentFilename); if (!str) { return; @@ -401,9 +398,7 @@ void cmGraphVizWriter::WriteConnections( continue; } - std::string connectionName = myNodeName; - connectionName += "-"; - connectionName += libNameIt->second; + std::string connectionName = cmStrCat(myNodeName, '-', libNameIt->second); if (insertedConnections.find(connectionName) == insertedConnections.end()) { insertedConnections.insert(connectionName); @@ -463,9 +458,8 @@ void cmGraphVizWriter::WriteDependerConnections( this->TargetNamesNodes.find(tptr.first); if (dependerNodeNameIt != this->TargetNamesNodes.end()) { - std::string connectionName = dependerNodeNameIt->second; - connectionName += "-"; - connectionName += myNodeName; + std::string connectionName = + cmStrCat(dependerNodeNameIt->second, '-', myNodeName); if (insertedConnections.find(connectionName) == insertedConnections.end()) { diff --git a/Source/cmIDEOptions.cxx b/Source/cmIDEOptions.cxx index 7b992d7..e80aa8e 100644 --- a/Source/cmIDEOptions.cxx +++ b/Source/cmIDEOptions.cxx @@ -8,7 +8,7 @@ #include "cmAlgorithms.h" #include "cmIDEFlagTable.h" -#include "cmSystemTools.h" +#include "cmStringAlgorithms.h" cmIDEOptions::cmIDEOptions() { @@ -166,7 +166,7 @@ void cmIDEOptions::AddDefines(std::string const& defines) { if (!defines.empty()) { // Expand the list of definitions. - cmSystemTools::ExpandListArgument(defines, this->Defines); + cmExpandList(defines, this->Defines); } } void cmIDEOptions::AddDefines(const std::vector<std::string>& defines) @@ -188,7 +188,7 @@ void cmIDEOptions::AddIncludes(std::string const& includes) { if (!includes.empty()) { // Expand the list of includes. - cmSystemTools::ExpandListArgument(includes, this->Includes); + cmExpandList(includes, this->Includes); } } void cmIDEOptions::AddIncludes(const std::vector<std::string>& includes) diff --git a/Source/cmIfCommand.cxx b/Source/cmIfCommand.cxx index 385022c..f719041 100644 --- a/Source/cmIfCommand.cxx +++ b/Source/cmIfCommand.cxx @@ -3,13 +3,18 @@ #include "cmIfCommand.h" #include "cm_memory.hxx" +#include "cm_static_string_view.hxx" +#include "cm_string_view.hxx" #include "cmConditionEvaluator.h" #include "cmExecutionStatus.h" #include "cmExpandedCommandArgument.h" +#include "cmFunctionBlocker.h" +#include "cmListFileCache.h" #include "cmMakefile.h" #include "cmMessageType.h" #include "cmOutputConverter.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmake.h" @@ -28,152 +33,137 @@ static std::string cmIfCommandError( return err; } -//========================================================================= -bool cmIfFunctionBlocker::IsFunctionBlocked(const cmListFileFunction& lff, - cmMakefile& mf, - cmExecutionStatus& inStatus) +class cmIfFunctionBlocker : public cmFunctionBlocker { - // we start by recording all the functions - if (lff.Name.Lower == "if") { - this->ScopeDepth++; - } else if (lff.Name.Lower == "endif") { - this->ScopeDepth--; - // if this is the endif for this if statement, then start executing - if (!this->ScopeDepth) { - // Remove the function blocker for this scope or bail. - std::unique_ptr<cmFunctionBlocker> fb( - mf.RemoveFunctionBlocker(this, lff)); - if (!fb) { - return false; +public: + cm::string_view StartCommandName() const override { return "if"_s; } + cm::string_view EndCommandName() const override { return "endif"_s; } + + bool ArgumentsMatch(cmListFileFunction const& lff, + cmMakefile&) const override; + + bool Replay(std::vector<cmListFileFunction> functions, + cmExecutionStatus& inStatus) override; + + std::vector<cmListFileArgument> Args; + bool IsBlocking; + bool HasRun = false; + bool ElseSeen = false; +}; + +bool cmIfFunctionBlocker::ArgumentsMatch(cmListFileFunction const& lff, + cmMakefile&) const +{ + return lff.Arguments.empty() || lff.Arguments == this->Args; +} + +bool cmIfFunctionBlocker::Replay(std::vector<cmListFileFunction> functions, + cmExecutionStatus& inStatus) +{ + cmMakefile& mf = inStatus.GetMakefile(); + // execute the functions for the true parts of the if statement + int scopeDepth = 0; + for (cmListFileFunction const& func : functions) { + // keep track of scope depth + if (func.Name.Lower == "if") { + scopeDepth++; + } + if (func.Name.Lower == "endif") { + scopeDepth--; + } + // watch for our state change + if (scopeDepth == 0 && func.Name.Lower == "else") { + + if (this->ElseSeen) { + cmListFileBacktrace bt = mf.GetBacktrace(func); + mf.GetCMakeInstance()->IssueMessage( + MessageType::FATAL_ERROR, + "A duplicate ELSE command was found inside an IF block.", bt); + cmSystemTools::SetFatalErrorOccured(); + return true; } - // execute the functions for the true parts of the if statement - cmExecutionStatus status(mf); - int scopeDepth = 0; - for (cmListFileFunction const& func : this->Functions) { - // keep track of scope depth - if (func.Name.Lower == "if") { - scopeDepth++; - } - if (func.Name.Lower == "endif") { - scopeDepth--; + this->IsBlocking = this->HasRun; + this->HasRun = true; + this->ElseSeen = true; + + // if trace is enabled, print a (trivially) evaluated "else" + // statement + if (!this->IsBlocking && mf.GetCMakeInstance()->GetTrace()) { + mf.PrintCommandTrace(func); + } + } else if (scopeDepth == 0 && func.Name.Lower == "elseif") { + if (this->ElseSeen) { + cmListFileBacktrace bt = mf.GetBacktrace(func); + mf.GetCMakeInstance()->IssueMessage( + MessageType::FATAL_ERROR, + "An ELSEIF command was found after an ELSE command.", bt); + cmSystemTools::SetFatalErrorOccured(); + return true; + } + + if (this->HasRun) { + this->IsBlocking = true; + } else { + // if trace is enabled, print the evaluated "elseif" statement + if (mf.GetCMakeInstance()->GetTrace()) { + mf.PrintCommandTrace(func); } - // watch for our state change - if (scopeDepth == 0 && func.Name.Lower == "else") { - - if (this->ElseSeen) { - cmListFileBacktrace bt = mf.GetBacktrace(func); - mf.GetCMakeInstance()->IssueMessage( - MessageType::FATAL_ERROR, - "A duplicate ELSE command was found inside an IF block.", bt); - cmSystemTools::SetFatalErrorOccured(); - return true; - } - this->IsBlocking = this->HasRun; - this->HasRun = true; - this->ElseSeen = true; + std::string errorString; - // if trace is enabled, print a (trivially) evaluated "else" - // statement - if (!this->IsBlocking && mf.GetCMakeInstance()->GetTrace()) { - mf.PrintCommandTrace(func); - } - } else if (scopeDepth == 0 && func.Name.Lower == "elseif") { - if (this->ElseSeen) { - cmListFileBacktrace bt = mf.GetBacktrace(func); - mf.GetCMakeInstance()->IssueMessage( - MessageType::FATAL_ERROR, - "An ELSEIF command was found after an ELSE command.", bt); + std::vector<cmExpandedCommandArgument> expandedArguments; + mf.ExpandArguments(func.Arguments, expandedArguments); + + MessageType messType; + + cmListFileContext conditionContext = + cmListFileContext::FromCommandContext( + func, this->GetStartingContext().FilePath); + + cmConditionEvaluator conditionEvaluator(mf, conditionContext, + mf.GetBacktrace(func)); + + bool isTrue = + conditionEvaluator.IsTrue(expandedArguments, errorString, messType); + + if (!errorString.empty()) { + std::string err = + cmStrCat(cmIfCommandError(expandedArguments), errorString); + cmListFileBacktrace bt = mf.GetBacktrace(func); + mf.GetCMakeInstance()->IssueMessage(messType, err, bt); + if (messType == MessageType::FATAL_ERROR) { cmSystemTools::SetFatalErrorOccured(); return true; } - - if (this->HasRun) { - this->IsBlocking = true; - } else { - // if trace is enabled, print the evaluated "elseif" statement - if (mf.GetCMakeInstance()->GetTrace()) { - mf.PrintCommandTrace(func); - } - - std::string errorString; - - std::vector<cmExpandedCommandArgument> expandedArguments; - mf.ExpandArguments(func.Arguments, expandedArguments); - - MessageType messType; - - cmListFileContext conditionContext = - cmListFileContext::FromCommandContext( - func, this->GetStartingContext().FilePath); - - cmConditionEvaluator conditionEvaluator(mf, conditionContext, - mf.GetBacktrace(func)); - - bool isTrue = conditionEvaluator.IsTrue(expandedArguments, - errorString, messType); - - if (!errorString.empty()) { - std::string err = cmIfCommandError(expandedArguments); - err += errorString; - cmListFileBacktrace bt = mf.GetBacktrace(func); - mf.GetCMakeInstance()->IssueMessage(messType, err, bt); - if (messType == MessageType::FATAL_ERROR) { - cmSystemTools::SetFatalErrorOccured(); - return true; - } - } - - if (isTrue) { - this->IsBlocking = false; - this->HasRun = true; - } - } } - // should we execute? - else if (!this->IsBlocking) { - status.Clear(); - mf.ExecuteCommand(func, status); - if (status.GetReturnInvoked()) { - inStatus.SetReturnInvoked(); - return true; - } - if (status.GetBreakInvoked()) { - inStatus.SetBreakInvoked(); - return true; - } - if (status.GetContinueInvoked()) { - inStatus.SetContinueInvoked(); - return true; - } + if (isTrue) { + this->IsBlocking = false; + this->HasRun = true; } } - return true; } - } - - // record the command - this->Functions.push_back(lff); - // always return true - return true; -} - -//========================================================================= -bool cmIfFunctionBlocker::ShouldRemove(const cmListFileFunction& lff, - cmMakefile&) -{ - if (lff.Name.Lower == "endif") { - // if the endif has arguments, then make sure - // they match the arguments of the matching if - if (lff.Arguments.empty() || lff.Arguments == this->Args) { - return true; + // should we execute? + else if (!this->IsBlocking) { + cmExecutionStatus status(mf); + mf.ExecuteCommand(func, status); + if (status.GetReturnInvoked()) { + inStatus.SetReturnInvoked(); + return true; + } + if (status.GetBreakInvoked()) { + inStatus.SetBreakInvoked(); + return true; + } + if (status.GetContinueInvoked()) { + inStatus.SetContinueInvoked(); + return true; + } } } - - return false; + return true; } //========================================================================= @@ -195,8 +185,8 @@ bool cmIfCommand(std::vector<cmListFileArgument> const& args, conditionEvaluator.IsTrue(expandedArguments, errorString, status); if (!errorString.empty()) { - std::string err = "if " + cmIfCommandError(expandedArguments); - err += errorString; + std::string err = + cmStrCat("if ", cmIfCommandError(expandedArguments), errorString); if (status == MessageType::FATAL_ERROR) { makefile.IssueMessage(MessageType::FATAL_ERROR, err); cmSystemTools::SetFatalErrorOccured(); @@ -208,7 +198,6 @@ bool cmIfCommand(std::vector<cmListFileArgument> const& args, { auto fb = cm::make_unique<cmIfFunctionBlocker>(); // if is isn't true block the commands - fb->ScopeDepth = 1; fb->IsBlocking = !isTrue; if (isTrue) { fb->HasRun = true; diff --git a/Source/cmIfCommand.h b/Source/cmIfCommand.h index 775e609..820ffa4 100644 --- a/Source/cmIfCommand.h +++ b/Source/cmIfCommand.h @@ -7,26 +7,8 @@ #include <vector> -#include "cmFunctionBlocker.h" -#include "cmListFileCache.h" - class cmExecutionStatus; -class cmMakefile; - -class cmIfFunctionBlocker : public cmFunctionBlocker -{ -public: - bool IsFunctionBlocked(const cmListFileFunction& lff, cmMakefile& mf, - cmExecutionStatus&) override; - bool ShouldRemove(const cmListFileFunction& lff, cmMakefile& mf) override; - - std::vector<cmListFileArgument> Args; - std::vector<cmListFileFunction> Functions; - bool IsBlocking; - bool HasRun = false; - bool ElseSeen = false; - unsigned int ScopeDepth = 0; -}; +struct cmListFileArgument; /// Starts an if block bool cmIfCommand(std::vector<cmListFileArgument> const& args, diff --git a/Source/cmIncludeCommand.cxx b/Source/cmIncludeCommand.cxx index 0d608bb..14264f4 100644 --- a/Source/cmIncludeCommand.cxx +++ b/Source/cmIncludeCommand.cxx @@ -4,21 +4,21 @@ #include <sstream> +#include "cmExecutionStatus.h" #include "cmGlobalGenerator.h" #include "cmMakefile.h" #include "cmMessageType.h" #include "cmPolicies.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" -class cmExecutionStatus; - // cmIncludeCommand -bool cmIncludeCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus&) +bool cmIncludeCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.empty() || args.size() > 4) { - this->SetError("called with wrong number of arguments. " - "include() only takes one file."); + status.SetError("called with wrong number of arguments. " + "include() only takes one file."); return false; } bool optional = false; @@ -29,20 +29,20 @@ bool cmIncludeCommand::InitialPass(std::vector<std::string> const& args, for (unsigned int i = 1; i < args.size(); i++) { if (args[i] == "OPTIONAL") { if (optional) { - this->SetError("called with invalid arguments: OPTIONAL used twice"); + status.SetError("called with invalid arguments: OPTIONAL used twice"); return false; } optional = true; } else if (args[i] == "RESULT_VARIABLE") { if (!resultVarName.empty()) { - this->SetError("called with invalid arguments: " - "only one result variable allowed"); + status.SetError("called with invalid arguments: " + "only one result variable allowed"); return false; } if (++i < args.size()) { resultVarName = args[i]; } else { - this->SetError("called with no value for RESULT_VARIABLE."); + status.SetError("called with no value for RESULT_VARIABLE."); return false; } } else if (args[i] == "NO_POLICY_SCOPE") { @@ -50,39 +50,39 @@ bool cmIncludeCommand::InitialPass(std::vector<std::string> const& args, } else if (i > 1) // compat.: in previous cmake versions the second // parameter was ignored if it wasn't "OPTIONAL" { - std::string errorText = "called with invalid argument: "; - errorText += args[i]; - this->SetError(errorText); + std::string errorText = + cmStrCat("called with invalid argument: ", args[i]); + status.SetError(errorText); return false; } } if (fname.empty()) { - this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, - "include() given empty file name (ignored)."); + status.GetMakefile().IssueMessage( + MessageType::AUTHOR_WARNING, + "include() given empty file name (ignored)."); return true; } if (!cmSystemTools::FileIsFullPath(fname)) { // Not a path. Maybe module. - std::string module = fname; - module += ".cmake"; - std::string mfile = this->Makefile->GetModulesFile(module); + std::string module = cmStrCat(fname, ".cmake"); + std::string mfile = status.GetMakefile().GetModulesFile(module); if (!mfile.empty()) { fname = mfile; } } std::string fname_abs = cmSystemTools::CollapseFullPath( - fname, this->Makefile->GetCurrentSourceDirectory()); + fname, status.GetMakefile().GetCurrentSourceDirectory()); - cmGlobalGenerator* gg = this->Makefile->GetGlobalGenerator(); + cmGlobalGenerator* gg = status.GetMakefile().GetGlobalGenerator(); if (gg->IsExportedTargetsFile(fname_abs)) { const char* modal = nullptr; std::ostringstream e; MessageType messageType = MessageType::AUTHOR_WARNING; - switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0024)) { + switch (status.GetMakefile().GetPolicyStatus(cmPolicies::CMP0024)) { case cmPolicies::WARN: e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0024) << "\n"; modal = "should"; @@ -102,7 +102,7 @@ bool cmIncludeCommand::InitialPass(std::vector<std::string> const& args, << " not be used as the argument to the " "include() command. Use ALIAS targets instead to refer to targets " "by alternative names.\n"; - this->Makefile->IssueMessage(messageType, e.str()); + status.GetMakefile().IssueMessage(messageType, e.str()); if (messageType == MessageType::FATAL_ERROR) { return false; } @@ -112,27 +112,28 @@ bool cmIncludeCommand::InitialPass(std::vector<std::string> const& args, } std::string listFile = cmSystemTools::CollapseFullPath( - fname, this->Makefile->GetCurrentSourceDirectory()); + fname, status.GetMakefile().GetCurrentSourceDirectory()); if (optional && !cmSystemTools::FileExists(listFile)) { if (!resultVarName.empty()) { - this->Makefile->AddDefinition(resultVarName, "NOTFOUND"); + status.GetMakefile().AddDefinition(resultVarName, "NOTFOUND"); } return true; } - bool readit = this->Makefile->ReadDependentFile(listFile, noPolicyScope); + bool readit = + status.GetMakefile().ReadDependentFile(listFile, noPolicyScope); // add the location of the included file if a result variable was given if (!resultVarName.empty()) { - this->Makefile->AddDefinition(resultVarName, - readit ? fname_abs.c_str() : "NOTFOUND"); + status.GetMakefile().AddDefinition( + resultVarName, readit ? fname_abs.c_str() : "NOTFOUND"); } if (!optional && !readit && !cmSystemTools::GetFatalErrorOccured()) { - std::string m = "could not find load file:\n" - " "; - m += fname; - this->SetError(m); + std::string m = cmStrCat("could not find load file:\n" + " ", + fname); + status.SetError(m); return false; } return true; diff --git a/Source/cmIncludeCommand.h b/Source/cmIncludeCommand.h index 94d3fbd..b0dd779 100644 --- a/Source/cmIncludeCommand.h +++ b/Source/cmIncludeCommand.h @@ -8,35 +8,15 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -/** \class cmIncludeCommand +/** * \brief cmIncludeCommand defines a list of distant * files that can be "included" in the current list file. * In almost every sense, this is identical to a C/C++ * #include command. Arguments are first expended as usual. */ -class cmIncludeCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmIncludeCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; -}; +bool cmIncludeCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmIncludeDirectoryCommand.cxx b/Source/cmIncludeDirectoryCommand.cxx index 62e2abd..876bd95 100644 --- a/Source/cmIncludeDirectoryCommand.cxx +++ b/Source/cmIncludeDirectoryCommand.cxx @@ -9,6 +9,7 @@ #include "cmAlgorithms.h" #include "cmGeneratorExpression.h" #include "cmMakefile.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" class cmExecutionStatus; @@ -116,14 +117,13 @@ void cmIncludeDirectoryCommand::NormalizeInclude(std::string& inc) return; } - if (!cmSystemTools::IsOff(inc)) { + if (!cmIsOff(inc)) { cmSystemTools::ConvertToUnixSlashes(inc); if (!cmSystemTools::FileIsFullPath(inc)) { if (!cmGeneratorExpression::StartsWithGeneratorExpression(inc)) { - std::string tmp = this->Makefile->GetCurrentSourceDirectory(); - tmp += "/"; - tmp += inc; + std::string tmp = + cmStrCat(this->Makefile->GetCurrentSourceDirectory(), '/', inc); inc = tmp; } } diff --git a/Source/cmIncludeGuardCommand.cxx b/Source/cmIncludeGuardCommand.cxx index 3b126b0..ccb4496 100644 --- a/Source/cmIncludeGuardCommand.cxx +++ b/Source/cmIncludeGuardCommand.cxx @@ -21,7 +21,7 @@ enum IncludeGuardScope std::string GetIncludeGuardVariableName(std::string const& filePath) { std::string result = "__INCGUARD_"; -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP result += cmSystemTools::ComputeStringMD5(filePath); #else result += cmSystemTools::MakeCidentifier(filePath); @@ -50,11 +50,11 @@ bool CheckIncludeGuardIsSet(cmMakefile* mf, std::string const& includeGuardVar) } // anonymous namespace // cmIncludeGuardCommand -bool cmIncludeGuardCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) +bool cmIncludeGuardCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() > 1) { - this->SetError( + status.SetError( "given an invalid number of arguments. The command takes at " "most 1 argument."); return false; @@ -69,15 +69,15 @@ bool cmIncludeGuardCommand::InitialPass(std::vector<std::string> const& args, } else if (arg == "GLOBAL") { scope = GLOBAL; } else { - this->SetError("given an invalid scope: " + arg); + status.SetError("given an invalid scope: " + arg); return false; } } std::string includeGuardVar = GetIncludeGuardVariableName( - this->Makefile->GetDefinition("CMAKE_CURRENT_LIST_FILE")); + status.GetMakefile().GetDefinition("CMAKE_CURRENT_LIST_FILE")); - cmMakefile* const mf = this->Makefile; + cmMakefile* const mf = &status.GetMakefile(); switch (scope) { case VARIABLE: diff --git a/Source/cmIncludeGuardCommand.h b/Source/cmIncludeGuardCommand.h index 4306c4c..b86b760 100644 --- a/Source/cmIncludeGuardCommand.h +++ b/Source/cmIncludeGuardCommand.h @@ -8,35 +8,15 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -/** \class cmIncludeGuardCommand +/** * \brief cmIncludeGuardCommand identical to C++ #pragma_once command * Can work in 3 modes: GLOBAL (works on global properties), * DIRECTORY(use directory property), VARIABLE(unnamed overload without * arguments) define an ordinary variable to be used as include guard checker */ -class cmIncludeGuardCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmIncludeGuardCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; -}; +bool cmIncludeGuardCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmInstallCommand.cxx b/Source/cmInstallCommand.cxx index aca7268..8b428a9 100644 --- a/Source/cmInstallCommand.cxx +++ b/Source/cmInstallCommand.cxx @@ -43,11 +43,13 @@ static cmInstallTargetGenerator* CreateInstallTargetGenerator( target.SetHaveInstallRule(true); const char* component = namelink ? args.GetNamelinkComponent().c_str() : args.GetComponent().c_str(); - return new cmInstallTargetGenerator( + auto g = new cmInstallTargetGenerator( target.GetName(), destination.c_str(), impLib, args.GetPermissions().c_str(), args.GetConfigurations(), component, message, args.GetExcludeFromAll(), args.GetOptional() || forceOpt, backtrace); + target.AddInstallGenerator(g); + return g; } static cmInstallTargetGenerator* CreateInstallTargetGenerator( @@ -135,8 +137,7 @@ bool cmInstallCommand::InitialPass(std::vector<std::string> const& args, } // Unknown mode. - std::string e = "called with unknown mode "; - e += args[0]; + std::string e = cmStrCat("called with unknown mode ", args[0]); this->SetError(e); return false; } @@ -186,9 +187,8 @@ bool cmInstallCommand::HandleScriptMode(std::vector<std::string> const& args) doing_script = false; std::string script = arg; if (!cmSystemTools::FileIsFullPath(script)) { - script = this->Makefile->GetCurrentSourceDirectory(); - script += "/"; - script += arg; + script = + cmStrCat(this->Makefile->GetCurrentSourceDirectory(), '/', arg); } if (cmSystemTools::FileIsDirectory(script)) { this->SetError("given a directory as value of SCRIPT argument."); @@ -671,7 +671,7 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args) const char* files = target.GetProperty("PRIVATE_HEADER"); if ((files) && (*files)) { std::vector<std::string> relFiles; - cmSystemTools::ExpandListArgument(files, relFiles); + cmExpandList(files, relFiles); std::vector<std::string> absFiles; if (!this->MakeFilesFullPath("PRIVATE_HEADER", relFiles, absFiles)) { return false; @@ -686,7 +686,7 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args) files = target.GetProperty("PUBLIC_HEADER"); if ((files) && (*files)) { std::vector<std::string> relFiles; - cmSystemTools::ExpandListArgument(files, relFiles); + cmExpandList(files, relFiles); std::vector<std::string> absFiles; if (!this->MakeFilesFullPath("PUBLIC_HEADER", relFiles, absFiles)) { return false; @@ -701,7 +701,7 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args) files = target.GetProperty("RESOURCE"); if ((files) && (*files)) { std::vector<std::string> relFiles; - cmSystemTools::ExpandListArgument(files, relFiles); + cmExpandList(files, relFiles); std::vector<std::string> absFiles; if (!this->MakeFilesFullPath("RESOURCE", relFiles, absFiles)) { return false; @@ -1121,9 +1121,8 @@ bool cmInstallCommand::HandleDirectoryMode( std::string dir = args[i]; std::string::size_type gpos = cmGeneratorExpression::Find(dir); if (gpos != 0 && !cmSystemTools::FileIsFullPath(dir)) { - dir = this->Makefile->GetCurrentSourceDirectory(); - dir += "/"; - dir += args[i]; + dir = + cmStrCat(this->Makefile->GetCurrentSourceDirectory(), '/', args[i]); } // Make sure the name is a directory. @@ -1266,7 +1265,7 @@ bool cmInstallCommand::HandleDirectoryMode( bool cmInstallCommand::HandleExportAndroidMKMode( std::vector<std::string> const& args) { -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP // This is the EXPORT mode. cmInstallCommandArguments ica(this->DefaultComponentName); @@ -1422,8 +1421,7 @@ bool cmInstallCommand::HandleExportMode(std::vector<std::string> const& args) // Construct the file name. if (fname.empty()) { - fname = exp; - fname += ".cmake"; + fname = cmStrCat(exp, ".cmake"); if (fname.find_first_of(":/\\") != std::string::npos) { std::ostringstream e; @@ -1480,9 +1478,8 @@ bool cmInstallCommand::MakeFilesFullPath( std::string file = relFile; std::string::size_type gpos = cmGeneratorExpression::Find(file); if (gpos != 0 && !cmSystemTools::FileIsFullPath(file)) { - file = this->Makefile->GetCurrentSourceDirectory(); - file += "/"; - file += relFile; + file = + cmStrCat(this->Makefile->GetCurrentSourceDirectory(), '/', relFile); } // Make sure the file is not a directory. diff --git a/Source/cmInstallDirectoryGenerator.cxx b/Source/cmInstallDirectoryGenerator.cxx index c8ebc8c..1d8210c 100644 --- a/Source/cmInstallDirectoryGenerator.cxx +++ b/Source/cmInstallDirectoryGenerator.cxx @@ -6,6 +6,7 @@ #include "cmInstallType.h" #include "cmLocalGenerator.h" #include "cmMakefile.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include <memory> @@ -66,15 +67,14 @@ void cmInstallDirectoryGenerator::GenerateScriptForConfig( cmGeneratorExpression ge; for (std::string const& d : this->Directories) { std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(d); - cmSystemTools::ExpandListArgument( - cge->Evaluate(this->LocalGenerator, config), dirs); + cmExpandList(cge->Evaluate(this->LocalGenerator, config), dirs); } // Make sure all dirs have absolute paths. cmMakefile const& mf = *this->LocalGenerator->GetMakefile(); for (std::string& d : dirs) { if (!cmSystemTools::FileIsFullPath(d)) { - d = mf.GetCurrentSourceDirectory() + "/" + d; + d = cmStrCat(mf.GetCurrentSourceDirectory(), "/", d); } } diff --git a/Source/cmInstallExportAndroidMKGenerator.cxx b/Source/cmInstallExportAndroidMKGenerator.cxx index 55d3685..e8de029 100644 --- a/Source/cmInstallExportAndroidMKGenerator.cxx +++ b/Source/cmInstallExportAndroidMKGenerator.cxx @@ -53,9 +53,7 @@ void cmInstallExportAndroidMKGenerator::GenerateScript(std::ostream& os) cmSystemTools::MakeDirectory(this->TempDir.c_str()); // Construct a temporary location for the file. - this->MainImportFile = this->TempDir; - this->MainImportFile += "/"; - this->MainImportFile += this->FileName; + this->MainImportFile = cmStrCat(this->TempDir, '/', this->FileName); // Generate the import file for this export set. this->EFGen->SetExportFile(this->MainImportFile.c_str()); @@ -103,11 +101,10 @@ void cmInstallExportAndroidMKGenerator::GenerateScriptActions( std::ostream& os, Indent const& indent) { // Remove old per-configuration export files if the main changes. - std::string installedDir = "$ENV{DESTDIR}"; - installedDir += this->ConvertToAbsoluteDestination(this->Destination); - installedDir += "/"; - std::string installedFile = installedDir; - installedFile += this->FileName; + std::string installedDir = + cmStrCat("$ENV{DESTDIR}", + this->ConvertToAbsoluteDestination(this->Destination), '/'); + std::string installedFile = cmStrCat(installedDir, this->FileName); os << indent << "if(EXISTS \"" << installedFile << "\")\n"; Indent indentN = indent.Next(); Indent indentNN = indentN.Next(); diff --git a/Source/cmInstallExportGenerator.cxx b/Source/cmInstallExportGenerator.cxx index f5bedab..0b3617b 100644 --- a/Source/cmInstallExportGenerator.cxx +++ b/Source/cmInstallExportGenerator.cxx @@ -7,13 +7,14 @@ #include <sstream> #include <utility> -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP # include "cmExportInstallAndroidMKGenerator.h" #endif #include "cmExportInstallFileGenerator.h" #include "cmExportSet.h" #include "cmInstallType.h" #include "cmLocalGenerator.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" cmInstallExportGenerator::cmInstallExportGenerator( @@ -31,7 +32,7 @@ cmInstallExportGenerator::cmInstallExportGenerator( , LocalGenerator(nullptr) { if (android) { -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP this->EFGen = new cmExportInstallAndroidMKGenerator(this); #endif } else { @@ -56,9 +57,8 @@ void cmInstallExportGenerator::ComputeTempDir() { // Choose a temporary directory in which to generate the import // files to be installed. - this->TempDir = this->LocalGenerator->GetCurrentBinaryDirectory(); - this->TempDir += "/CMakeFiles"; - this->TempDir += "/Export"; + this->TempDir = cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(), + "/CMakeFiles/Export"); if (this->Destination.empty()) { return; } @@ -136,9 +136,7 @@ void cmInstallExportGenerator::GenerateScript(std::ostream& os) cmSystemTools::MakeDirectory(this->TempDir); // Construct a temporary location for the file. - this->MainImportFile = this->TempDir; - this->MainImportFile += "/"; - this->MainImportFile += this->FileName; + this->MainImportFile = cmStrCat(this->TempDir, '/', this->FileName); // Generate the import file for this export set. this->EFGen->SetExportFile(this->MainImportFile.c_str()); @@ -186,11 +184,10 @@ void cmInstallExportGenerator::GenerateScriptActions(std::ostream& os, Indent indent) { // Remove old per-configuration export files if the main changes. - std::string installedDir = "$ENV{DESTDIR}"; - installedDir += this->ConvertToAbsoluteDestination(this->Destination); - installedDir += "/"; - std::string installedFile = installedDir; - installedFile += this->FileName; + std::string installedDir = + cmStrCat("$ENV{DESTDIR}", + this->ConvertToAbsoluteDestination(this->Destination), '/'); + std::string installedFile = cmStrCat(installedDir, this->FileName); os << indent << "if(EXISTS \"" << installedFile << "\")\n"; Indent indentN = indent.Next(); Indent indentNN = indentN.Next(); @@ -218,3 +215,8 @@ void cmInstallExportGenerator::GenerateScriptActions(std::ostream& os, false, this->FilePermissions.c_str(), nullptr, nullptr, nullptr, indent); } + +std::string cmInstallExportGenerator::GetDestinationFile() const +{ + return this->Destination + '/' + this->FileName; +} diff --git a/Source/cmInstallExportGenerator.h b/Source/cmInstallExportGenerator.h index c4d252c..e680066 100644 --- a/Source/cmInstallExportGenerator.h +++ b/Source/cmInstallExportGenerator.h @@ -41,6 +41,7 @@ public: const std::string& GetNamespace() const { return this->Namespace; } std::string const& GetDestination() const { return this->Destination; } + std::string GetDestinationFile() const; protected: void GenerateScript(std::ostream& os) override; diff --git a/Source/cmInstallFilesCommand.cxx b/Source/cmInstallFilesCommand.cxx index 4522669..11687a8 100644 --- a/Source/cmInstallFilesCommand.cxx +++ b/Source/cmInstallFilesCommand.cxx @@ -8,6 +8,7 @@ #include "cmInstallGenerator.h" #include "cmMakefile.h" #include "cmRange.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" class cmExecutionStatus; @@ -135,12 +136,8 @@ static std::string FindInstallSource(cmMakefile& makefile, const char* name) } // This is a relative path. - std::string tb = makefile.GetCurrentBinaryDirectory(); - tb += "/"; - tb += name; - std::string ts = makefile.GetCurrentSourceDirectory(); - ts += "/"; - ts += name; + std::string tb = cmStrCat(makefile.GetCurrentBinaryDirectory(), '/', name); + std::string ts = cmStrCat(makefile.GetCurrentSourceDirectory(), '/', name); if (cmSystemTools::FileExists(tb)) { // The file exists in the binary tree. Use it. diff --git a/Source/cmInstallFilesGenerator.cxx b/Source/cmInstallFilesGenerator.cxx index e8e82cc..c4048d4 100644 --- a/Source/cmInstallFilesGenerator.cxx +++ b/Source/cmInstallFilesGenerator.cxx @@ -4,7 +4,7 @@ #include "cmGeneratorExpression.h" #include "cmInstallType.h" -#include "cmSystemTools.h" +#include "cmStringAlgorithms.h" #include <memory> @@ -85,8 +85,7 @@ void cmInstallFilesGenerator::GenerateScriptForConfig( cmGeneratorExpression ge; for (std::string const& f : this->Files) { std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(f); - cmSystemTools::ExpandListArgument( - cge->Evaluate(this->LocalGenerator, config), files); + cmExpandList(cge->Evaluate(this->LocalGenerator, config), files); } this->AddFilesInstallRule(os, config, indent, files); } diff --git a/Source/cmInstallProgramsCommand.cxx b/Source/cmInstallProgramsCommand.cxx index 6ec02e7..3eca0e0 100644 --- a/Source/cmInstallProgramsCommand.cxx +++ b/Source/cmInstallProgramsCommand.cxx @@ -7,6 +7,7 @@ #include "cmInstallFilesGenerator.h" #include "cmInstallGenerator.h" #include "cmMakefile.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" class cmExecutionStatus; @@ -110,12 +111,8 @@ static std::string FindInstallSource(cmMakefile& makefile, const char* name) } // This is a relative path. - std::string tb = makefile.GetCurrentBinaryDirectory(); - tb += "/"; - tb += name; - std::string ts = makefile.GetCurrentSourceDirectory(); - ts += "/"; - ts += name; + std::string tb = cmStrCat(makefile.GetCurrentBinaryDirectory(), '/', name); + std::string ts = cmStrCat(makefile.GetCurrentSourceDirectory(), '/', name); if (cmSystemTools::FileExists(tb)) { // The file exists in the binary tree. Use it. diff --git a/Source/cmInstallTargetGenerator.cxx b/Source/cmInstallTargetGenerator.cxx index a61239e..7bbef35 100644 --- a/Source/cmInstallTargetGenerator.cxx +++ b/Source/cmInstallTargetGenerator.cxx @@ -20,6 +20,7 @@ #include "cmOutputConverter.h" #include "cmPolicies.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmTarget.h" #include "cmake.h" @@ -86,20 +87,18 @@ void cmInstallTargetGenerator::GenerateScriptForConfig( std::string fromDirConfig; if (this->Target->NeedRelinkBeforeInstall(config)) { fromDirConfig = - this->Target->GetLocalGenerator()->GetCurrentBinaryDirectory(); - fromDirConfig += "/CMakeFiles"; - fromDirConfig += "/CMakeRelink.dir/"; + cmStrCat(this->Target->GetLocalGenerator()->GetCurrentBinaryDirectory(), + "/CMakeFiles/CMakeRelink.dir/"); } else { cmStateEnums::ArtifactType artifact = this->ImportLibrary ? cmStateEnums::ImportLibraryArtifact : cmStateEnums::RuntimeBinaryArtifact; - fromDirConfig = this->Target->GetDirectory(config, artifact); - fromDirConfig += "/"; + fromDirConfig = + cmStrCat(this->Target->GetDirectory(config, artifact), '/'); } - std::string toDir = - this->ConvertToAbsoluteDestination(this->GetDestination(config)); - toDir += "/"; + std::string toDir = cmStrCat( + this->ConvertToAbsoluteDestination(this->GetDestination(config)), '/'); // Compute the list of files to install for this target. std::vector<std::string> filesFrom; @@ -369,7 +368,7 @@ void cmInstallTargetGenerator::GetInstallObjectNames( { this->Target->GetTargetObjectNames(config, objects); for (std::string& o : objects) { - o = computeInstallObjectDir(this->Target, config) + "/" + o; + o = cmStrCat(computeInstallObjectDir(this->Target, config), "/", o); } } @@ -593,8 +592,8 @@ void cmInstallTargetGenerator::AddInstallNamePatchRule( // on the installed file. if (for_build != for_install) { // Prepare to refer to the install-tree install_name. - new_id = for_install; - new_id += this->GetInstallFilename(this->Target, config, NameSO); + new_id = cmStrCat( + for_install, this->GetInstallFilename(this->Target, config, NameSO)); } } @@ -688,7 +687,8 @@ void cmInstallTargetGenerator::AddChrpathPatchRule( std::string installNameTool = mf->GetSafeDefinition("CMAKE_INSTALL_NAME_TOOL"); - std::vector<std::string> oldRuntimeDirs, newRuntimeDirs; + std::vector<std::string> oldRuntimeDirs; + std::vector<std::string> newRuntimeDirs; cli->GetRPath(oldRuntimeDirs, false); cli->GetRPath(newRuntimeDirs, true); diff --git a/Source/cmInstalledFile.cxx b/Source/cmInstalledFile.cxx index 537b4ec..1e6c385 100644 --- a/Source/cmInstalledFile.cxx +++ b/Source/cmInstalledFile.cxx @@ -5,7 +5,7 @@ #include "cmAlgorithms.h" #include "cmListFileCache.h" #include "cmMakefile.h" -#include "cmSystemTools.h" +#include "cmStringAlgorithms.h" #include <utility> @@ -97,7 +97,7 @@ bool cmInstalledFile::GetPropertyAsBool(const std::string& prop) const { std::string value; bool isSet = this->GetProperty(prop, value); - return isSet && cmSystemTools::IsOn(value); + return isSet && cmIsOn(value); } void cmInstalledFile::GetPropertyAsList(const std::string& prop, @@ -107,5 +107,5 @@ void cmInstalledFile::GetPropertyAsList(const std::string& prop, this->GetProperty(prop, value); list.clear(); - cmSystemTools::ExpandListArgument(value, list); + cmExpandList(value, list); } diff --git a/Source/cmJsonObjects.cxx b/Source/cmJsonObjects.cxx index 2423faf..b8eed13 100644 --- a/Source/cmJsonObjects.cxx +++ b/Source/cmJsonObjects.cxx @@ -20,6 +20,7 @@ #include "cmStateDirectory.h" #include "cmStateSnapshot.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmTarget.h" #include "cmTest.h" @@ -500,9 +501,9 @@ static Json::Value DumpTarget(cmGeneratorTarget* target, if (!dest.empty() && cmSystemTools::FileIsFullPath(dest)) { installPath = dest; } else { - std::string installPrefix = - target->Makefile->GetSafeDefinition("CMAKE_INSTALL_PREFIX"); - installPath = installPrefix + '/' + dest; + installPath = cmStrCat( + target->Makefile->GetSafeDefinition("CMAKE_INSTALL_PREFIX"), '/', + dest); } installPaths.append(installPath); @@ -541,19 +542,19 @@ static Json::Value DumpTarget(cmGeneratorTarget* target, lg->GetTargetFlags(&linkLineComputer, config, linkLibs, linkLanguageFlags, linkFlags, frameworkPath, linkPath, target); - linkLibs = cmSystemTools::TrimWhitespace(linkLibs); - linkFlags = cmSystemTools::TrimWhitespace(linkFlags); - linkLanguageFlags = cmSystemTools::TrimWhitespace(linkLanguageFlags); - frameworkPath = cmSystemTools::TrimWhitespace(frameworkPath); - linkPath = cmSystemTools::TrimWhitespace(linkPath); + linkLibs = cmTrimWhitespace(linkLibs); + linkFlags = cmTrimWhitespace(linkFlags); + linkLanguageFlags = cmTrimWhitespace(linkLanguageFlags); + frameworkPath = cmTrimWhitespace(frameworkPath); + linkPath = cmTrimWhitespace(linkPath); - if (!cmSystemTools::TrimWhitespace(linkLibs).empty()) { + if (!cmTrimWhitespace(linkLibs).empty()) { result[kLINK_LIBRARIES_KEY] = linkLibs; } - if (!cmSystemTools::TrimWhitespace(linkFlags).empty()) { + if (!cmTrimWhitespace(linkFlags).empty()) { result[kLINK_FLAGS_KEY] = linkFlags; } - if (!cmSystemTools::TrimWhitespace(linkLanguageFlags).empty()) { + if (!cmTrimWhitespace(linkLanguageFlags).empty()) { result[kLINK_LANGUAGE_FLAGS_KEY] = linkLanguageFlags; } if (!frameworkPath.empty()) { diff --git a/Source/cmLDConfigLDConfigTool.cxx b/Source/cmLDConfigLDConfigTool.cxx index 586ea96..d5cc621 100644 --- a/Source/cmLDConfigLDConfigTool.cxx +++ b/Source/cmLDConfigLDConfigTool.cxx @@ -4,6 +4,7 @@ #include "cmLDConfigLDConfigTool.h" #include "cmMakefile.h" #include "cmRuntimeDependencyArchive.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmUVProcessChain.h" @@ -33,7 +34,7 @@ bool cmLDConfigLDConfigTool::GetLDConfigPaths(std::vector<std::string>& paths) } std::vector<std::string> ldConfigCommand; - cmSystemTools::ExpandListArgument(ldConfigPath, ldConfigCommand); + cmExpandList(ldConfigPath, ldConfigCommand); ldConfigCommand.emplace_back("-v"); ldConfigCommand.emplace_back("-N"); // Don't rebuild the cache. ldConfigCommand.emplace_back("-X"); // Don't update links. diff --git a/Source/cmLinkDirectoriesCommand.cxx b/Source/cmLinkDirectoriesCommand.cxx index a278925..57b69c8 100644 --- a/Source/cmLinkDirectoriesCommand.cxx +++ b/Source/cmLinkDirectoriesCommand.cxx @@ -75,9 +75,8 @@ void cmLinkDirectoriesCommand::AddLinkDir( break; } if (convertToAbsolute) { - std::string tmp = this->Makefile->GetCurrentSourceDirectory(); - tmp += "/"; - tmp += unixPath; + std::string tmp = + cmStrCat(this->Makefile->GetCurrentSourceDirectory(), '/', unixPath); unixPath = tmp; } } diff --git a/Source/cmLinkItem.h b/Source/cmLinkItem.h index 6450c62..2d9378b 100644 --- a/Source/cmLinkItem.h +++ b/Source/cmLinkItem.h @@ -5,12 +5,12 @@ #include "cmConfigure.h" // IWYU pragma: keep -#include <algorithm> #include <map> #include <ostream> #include <string> #include <vector> +#include "cmAlgorithms.h" #include "cmListFileCache.h" #include "cmSystemTools.h" #include "cmTargetLinkLibraryType.h" @@ -87,7 +87,7 @@ struct cmOptionalLinkInterface : public cmLinkInterface bool LibrariesDone = false; bool AllDone = false; bool Exists = false; - const char* ExplicitLibraries = nullptr; + bool Explicit = false; }; struct cmHeadToLinkInterfaceMap @@ -120,8 +120,7 @@ inline cmTargetLinkLibraryType CMP0003_ComputeLinkType( // Check if any entry in the list matches this configuration. std::string configUpper = cmSystemTools::UpperCase(config); - if (std::find(debugConfigs.begin(), debugConfigs.end(), configUpper) != - debugConfigs.end()) { + if (cmContains(debugConfigs, configUpper)) { return DEBUG_LibraryType; } // The current configuration is not a debug configuration. diff --git a/Source/cmLinkLineComputer.cxx b/Source/cmLinkLineComputer.cxx index 8746b35..5e3c790 100644 --- a/Source/cmLinkLineComputer.cxx +++ b/Source/cmLinkLineComputer.cxx @@ -11,6 +11,7 @@ #include "cmOutputConverter.h" #include "cmStateDirectory.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" cmLinkLineComputer::cmLinkLineComputer(cmOutputConverter* outputConverter, @@ -63,6 +64,7 @@ std::string cmLinkLineComputer::ComputeLinkLibs(cmComputeLinkInformation& cli) continue; } if (item.IsPath) { + linkLibs += cli.GetLibLinkFileFlag(); linkLibs += this->ConvertToOutputFormat(this->ConvertToLinkReference(item.Value)); } else { @@ -114,16 +116,17 @@ std::string cmLinkLineComputer::ComputeLinkPath( type = cmStateEnums::ImportLibraryArtifact; } - linkPath += " " + libPathFlag + - item.Target->GetDirectory(cli.GetConfig(), type) + - libPathTerminator + " "; + linkPath += cmStrCat(" ", libPathFlag, + item.Target->GetDirectory(cli.GetConfig(), type), + libPathTerminator, " "); } } } for (std::string const& libDir : cli.GetDirectories()) { - linkPath += " " + libPathFlag + this->ConvertToOutputForExisting(libDir) + - libPathTerminator + " "; + linkPath += + cmStrCat(" ", libPathFlag, this->ConvertToOutputForExisting(libDir), + libPathTerminator, " "); } return linkPath; diff --git a/Source/cmLinkLineDeviceComputer.cxx b/Source/cmLinkLineDeviceComputer.cxx index 656907a..96af388 100644 --- a/Source/cmLinkLineDeviceComputer.cxx +++ b/Source/cmLinkLineDeviceComputer.cxx @@ -3,21 +3,20 @@ #include "cmLinkLineDeviceComputer.h" -#include <algorithm> #include <set> #include <sstream> #include <utility> -#include <vector> +#include "cmAlgorithms.h" #include "cmComputeLinkInformation.h" #include "cmGeneratorTarget.h" #include "cmGlobalGenerator.h" #include "cmLocalGenerator.h" +#include "cmMakefile.h" #include "cmStateDirectory.h" #include "cmStateSnapshot.h" #include "cmStateTypes.h" #include "cmStringAlgorithms.h" -#include "cmSystemTools.h" class cmOutputConverter; @@ -156,16 +155,20 @@ bool requireDeviceLinking(cmGeneratorTarget& target, cmLocalGenerator& lg, return false; } + if (!lg.GetMakefile()->IsOn("CMAKE_CUDA_COMPILER_HAS_DEVICE_LINK_PHASE")) { + return false; + } + if (const char* resolveDeviceSymbols = target.GetProperty("CUDA_RESOLVE_DEVICE_SYMBOLS")) { // If CUDA_RESOLVE_DEVICE_SYMBOLS has been explicitly set we need // to honor the value no matter what it is. - return cmSystemTools::IsOn(resolveDeviceSymbols); + return cmIsOn(resolveDeviceSymbols); } if (const char* separableCompilation = target.GetProperty("CUDA_SEPARABLE_COMPILATION")) { - if (cmSystemTools::IsOn(separableCompilation)) { + if (cmIsOn(separableCompilation)) { bool doDeviceLinking = false; switch (target.GetType()) { case cmStateEnums::SHARED_LIBRARY: @@ -182,14 +185,10 @@ bool requireDeviceLinking(cmGeneratorTarget& target, cmLocalGenerator& lg, // Determine if we have any dependencies that require // us to do a device link step - const std::string cuda_lang("CUDA"); cmGeneratorTarget::LinkClosure const* closure = target.GetLinkClosure(config); - bool closureHasCUDA = - (std::find(closure->Languages.begin(), closure->Languages.end(), - cuda_lang) != closure->Languages.end()); - if (closureHasCUDA) { + if (cmContains(closure->Languages, "CUDA")) { cmComputeLinkInformation* pcli = target.GetLinkInformation(config); if (pcli) { cmLinkLineDeviceComputer deviceLinkComputer( diff --git a/Source/cmListCommand.cxx b/Source/cmListCommand.cxx index 8c14596..fe77b33 100644 --- a/Source/cmListCommand.cxx +++ b/Source/cmListCommand.cxx @@ -18,6 +18,7 @@ #include "cm_memory.hxx" #include "cmAlgorithms.h" +#include "cmExecutionStatus.h" #include "cmGeneratorExpression.h" #include "cmMakefile.h" #include "cmMessageType.h" @@ -27,79 +28,124 @@ #include "cmStringReplaceHelper.h" #include "cmSystemTools.h" -class cmExecutionStatus; +namespace { +bool HandleLengthCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool HandleGetCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool HandleAppendCommand(std::vector<std::string> const& args, + cmMakefile& makefile); +bool HandlePrependCommand(std::vector<std::string> const& args, + cmMakefile& makefile); +bool HandlePopBackCommand(std::vector<std::string> const& args, + cmMakefile& makefile); +bool HandlePopFrontCommand(std::vector<std::string> const& args, + cmMakefile& makefile); +bool HandleFindCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool HandleInsertCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool HandleJoinCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool HandleRemoveAtCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool HandleRemoveItemCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool HandleRemoveDuplicatesCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool HandleTransformCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool HandleSortCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool HandleSublistCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool HandleReverseCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool HandleFilterCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool FilterRegex(std::vector<std::string> const& args, bool includeMatches, + std::string const& listName, + std::vector<std::string>& varArgsExpanded, + cmExecutionStatus& status); + +bool GetList(std::vector<std::string>& list, const std::string& var, + const cmMakefile& makefile); +bool GetListString(std::string& listString, const std::string& var, + const cmMakefile& makefile); +} -bool cmListCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus&) +bool cmListCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() < 2) { - this->SetError("must be called with at least two arguments."); + status.SetError("must be called with at least two arguments."); return false; } const std::string& subCommand = args[0]; if (subCommand == "LENGTH") { - return this->HandleLengthCommand(args); + return HandleLengthCommand(args, status); } if (subCommand == "GET") { - return this->HandleGetCommand(args); + return HandleGetCommand(args, status); } if (subCommand == "APPEND") { - return this->HandleAppendCommand(args); + return HandleAppendCommand(args, status.GetMakefile()); } if (subCommand == "PREPEND") { - return this->HandlePrependCommand(args); + return HandlePrependCommand(args, status.GetMakefile()); } if (subCommand == "POP_BACK") { - return this->HandlePopBackCommand(args); + return HandlePopBackCommand(args, status.GetMakefile()); } if (subCommand == "POP_FRONT") { - return this->HandlePopFrontCommand(args); + return HandlePopFrontCommand(args, status.GetMakefile()); } if (subCommand == "FIND") { - return this->HandleFindCommand(args); + return HandleFindCommand(args, status); } if (subCommand == "INSERT") { - return this->HandleInsertCommand(args); + return HandleInsertCommand(args, status); } if (subCommand == "JOIN") { - return this->HandleJoinCommand(args); + return HandleJoinCommand(args, status); } if (subCommand == "REMOVE_AT") { - return this->HandleRemoveAtCommand(args); + return HandleRemoveAtCommand(args, status); } if (subCommand == "REMOVE_ITEM") { - return this->HandleRemoveItemCommand(args); + return HandleRemoveItemCommand(args, status); } if (subCommand == "REMOVE_DUPLICATES") { - return this->HandleRemoveDuplicatesCommand(args); + return HandleRemoveDuplicatesCommand(args, status); } if (subCommand == "TRANSFORM") { - return this->HandleTransformCommand(args); + return HandleTransformCommand(args, status); } if (subCommand == "SORT") { - return this->HandleSortCommand(args); + return HandleSortCommand(args, status); } if (subCommand == "SUBLIST") { - return this->HandleSublistCommand(args); + return HandleSublistCommand(args, status); } if (subCommand == "REVERSE") { - return this->HandleReverseCommand(args); + return HandleReverseCommand(args, status); } if (subCommand == "FILTER") { - return this->HandleFilterCommand(args); + return HandleFilterCommand(args, status); } std::string e = "does not recognize sub-command " + subCommand; - this->SetError(e); + status.SetError(e); return false; } -bool cmListCommand::GetListString(std::string& listString, - const std::string& var) +namespace { +bool GetListString(std::string& listString, const std::string& var, + const cmMakefile& makefile) { // get the old value - const char* cacheValue = this->Makefile->GetDefinition(var); + const char* cacheValue = makefile.GetDefinition(var); if (!cacheValue) { return false; } @@ -107,11 +153,11 @@ bool cmListCommand::GetListString(std::string& listString, return true; } -bool cmListCommand::GetList(std::vector<std::string>& list, - const std::string& var) +bool GetList(std::vector<std::string>& list, const std::string& var, + const cmMakefile& makefile) { std::string listString; - if (!this->GetListString(listString, var)) { + if (!GetListString(listString, var, makefile)) { return false; } // if the size of the list @@ -119,25 +165,24 @@ bool cmListCommand::GetList(std::vector<std::string>& list, return true; } // expand the variable into a list - cmSystemTools::ExpandListArgument(listString, list, true); + cmExpandList(listString, list, true); // if no empty elements then just return - if (std::find(list.begin(), list.end(), std::string()) == list.end()) { + if (!cmContains(list, std::string())) { return true; } // if we have empty elements we need to check policy CMP0007 - switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0007)) { + switch (makefile.GetPolicyStatus(cmPolicies::CMP0007)) { case cmPolicies::WARN: { // Default is to warn and use old behavior // OLD behavior is to allow compatibility, so recall // ExpandListArgument without the true which will remove // empty values list.clear(); - cmSystemTools::ExpandListArgument(listString, list); - std::string warn = cmPolicies::GetPolicyWarning(cmPolicies::CMP0007); - warn += " List has value = ["; - warn += listString; - warn += "]."; - this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, warn); + cmExpandList(listString, list); + std::string warn = + cmStrCat(cmPolicies::GetPolicyWarning(cmPolicies::CMP0007), + " List has value = [", listString, "]."); + makefile.IssueMessage(MessageType::AUTHOR_WARNING, warn); return true; } case cmPolicies::OLD: @@ -145,13 +190,13 @@ bool cmListCommand::GetList(std::vector<std::string>& list, // ExpandListArgument without the true which will remove // empty values list.clear(); - cmSystemTools::ExpandListArgument(listString, list); + cmExpandList(listString, list); return true; case cmPolicies::NEW: return true; case cmPolicies::REQUIRED_IF_USED: case cmPolicies::REQUIRED_ALWAYS: - this->Makefile->IssueMessage( + makefile.IssueMessage( MessageType::FATAL_ERROR, cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0007)); return false; @@ -159,10 +204,11 @@ bool cmListCommand::GetList(std::vector<std::string>& list, return true; } -bool cmListCommand::HandleLengthCommand(std::vector<std::string> const& args) +bool HandleLengthCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() != 3) { - this->SetError("sub-command LENGTH requires two arguments."); + status.SetError("sub-command LENGTH requires two arguments."); return false; } @@ -172,19 +218,20 @@ bool cmListCommand::HandleLengthCommand(std::vector<std::string> const& args) // do not check the return value here // if the list var is not found varArgsExpanded will have size 0 // and we will return 0 - this->GetList(varArgsExpanded, listName); + GetList(varArgsExpanded, listName, status.GetMakefile()); size_t length = varArgsExpanded.size(); char buffer[1024]; sprintf(buffer, "%d", static_cast<int>(length)); - this->Makefile->AddDefinition(variableName, buffer); + status.GetMakefile().AddDefinition(variableName, buffer); return true; } -bool cmListCommand::HandleGetCommand(std::vector<std::string> const& args) +bool HandleGetCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() < 4) { - this->SetError("sub-command GET requires at least three arguments."); + status.SetError("sub-command GET requires at least three arguments."); return false; } @@ -192,13 +239,13 @@ bool cmListCommand::HandleGetCommand(std::vector<std::string> const& args) const std::string& variableName = args.back(); // expand the variable std::vector<std::string> varArgsExpanded; - if (!this->GetList(varArgsExpanded, listName)) { - this->Makefile->AddDefinition(variableName, "NOTFOUND"); + if (!GetList(varArgsExpanded, listName, status.GetMakefile())) { + status.GetMakefile().AddDefinition(variableName, "NOTFOUND"); return true; } // FIXME: Add policy to make non-existing lists an error like empty lists. if (varArgsExpanded.empty()) { - this->SetError("GET given empty list"); + status.SetError("GET given empty list"); return false; } @@ -217,17 +264,18 @@ bool cmListCommand::HandleGetCommand(std::vector<std::string> const& args) std::ostringstream str; str << "index: " << item << " out of range (-" << nitem << ", " << nitem - 1 << ")"; - this->SetError(str.str()); + status.SetError(str.str()); return false; } value += varArgsExpanded[item]; } - this->Makefile->AddDefinition(variableName, value); + status.GetMakefile().AddDefinition(variableName, value); return true; } -bool cmListCommand::HandleAppendCommand(std::vector<std::string> const& args) +bool HandleAppendCommand(std::vector<std::string> const& args, + cmMakefile& makefile) { assert(args.size() >= 2); @@ -239,7 +287,7 @@ bool cmListCommand::HandleAppendCommand(std::vector<std::string> const& args) std::string const& listName = args[1]; // expand the variable std::string listString; - this->GetListString(listString, listName); + GetListString(listString, listName, makefile); // If `listString` or `args` is empty, no need to append `;`, // then index is going to be `1` and points to the end-of-string ";" @@ -247,11 +295,12 @@ bool cmListCommand::HandleAppendCommand(std::vector<std::string> const& args) std::string::size_type(listString.empty() || args.empty()); listString += &";"[offset] + cmJoin(cmMakeRange(args).advance(2), ";"); - this->Makefile->AddDefinition(listName, listString); + makefile.AddDefinition(listName, listString); return true; } -bool cmListCommand::HandlePrependCommand(std::vector<std::string> const& args) +bool HandlePrependCommand(std::vector<std::string> const& args, + cmMakefile& makefile) { assert(args.size() >= 2); @@ -263,7 +312,7 @@ bool cmListCommand::HandlePrependCommand(std::vector<std::string> const& args) std::string const& listName = args[1]; // expand the variable std::string listString; - this->GetListString(listString, listName); + GetListString(listString, listName, makefile); // If `listString` or `args` is empty, no need to append `;`, // then `offset` is going to be `1` and points to the end-of-string ";" @@ -272,11 +321,12 @@ bool cmListCommand::HandlePrependCommand(std::vector<std::string> const& args) listString.insert(0, cmJoin(cmMakeRange(args).advance(2), ";") + &";"[offset]); - this->Makefile->AddDefinition(listName, listString); + makefile.AddDefinition(listName, listString); return true; } -bool cmListCommand::HandlePopBackCommand(std::vector<std::string> const& args) +bool HandlePopBackCommand(std::vector<std::string> const& args, + cmMakefile& makefile) { assert(args.size() >= 2); @@ -284,10 +334,10 @@ bool cmListCommand::HandlePopBackCommand(std::vector<std::string> const& args) ++ai; // Skip subcommand name std::string const& listName = *ai++; std::vector<std::string> varArgsExpanded; - if (!this->GetList(varArgsExpanded, listName)) { + if (!GetList(varArgsExpanded, listName, makefile)) { // Can't get the list definition... undefine any vars given after. for (; ai != args.cend(); ++ai) { - this->Makefile->RemoveDefinition(*ai); + makefile.RemoveDefinition(*ai); } return true; } @@ -300,29 +350,30 @@ bool cmListCommand::HandlePopBackCommand(std::vector<std::string> const& args) // Ok, assign elements to be removed to the given variables for (; !varArgsExpanded.empty() && ai != args.cend(); ++ai) { assert(!ai->empty()); - this->Makefile->AddDefinition(*ai, varArgsExpanded.back()); + makefile.AddDefinition(*ai, varArgsExpanded.back()); varArgsExpanded.pop_back(); } // Undefine the rest variables if the list gets empty earlier... for (; ai != args.cend(); ++ai) { - this->Makefile->RemoveDefinition(*ai); + makefile.RemoveDefinition(*ai); } } - this->Makefile->AddDefinition(listName, cmJoin(varArgsExpanded, ";")); + makefile.AddDefinition(listName, cmJoin(varArgsExpanded, ";")); } else if (ai != args.cend()) { // The list is empty, but some args were given // Need to *undefine* 'em all, cuz there are no items to assign... for (; ai != args.cend(); ++ai) { - this->Makefile->RemoveDefinition(*ai); + makefile.RemoveDefinition(*ai); } } return true; } -bool cmListCommand::HandlePopFrontCommand(std::vector<std::string> const& args) +bool HandlePopFrontCommand(std::vector<std::string> const& args, + cmMakefile& makefile) { assert(args.size() >= 2); @@ -330,10 +381,10 @@ bool cmListCommand::HandlePopFrontCommand(std::vector<std::string> const& args) ++ai; // Skip subcommand name std::string const& listName = *ai++; std::vector<std::string> varArgsExpanded; - if (!this->GetList(varArgsExpanded, listName)) { + if (!GetList(varArgsExpanded, listName, makefile)) { // Can't get the list definition... undefine any vars given after. for (; ai != args.cend(); ++ai) { - this->Makefile->RemoveDefinition(*ai); + makefile.RemoveDefinition(*ai); } return true; } @@ -347,32 +398,33 @@ bool cmListCommand::HandlePopFrontCommand(std::vector<std::string> const& args) auto vi = varArgsExpanded.begin(); for (; vi != varArgsExpanded.end() && ai != args.cend(); ++ai, ++vi) { assert(!ai->empty()); - this->Makefile->AddDefinition(*ai, *vi); + makefile.AddDefinition(*ai, *vi); } varArgsExpanded.erase(varArgsExpanded.begin(), vi); // Undefine the rest variables if the list gets empty earlier... for (; ai != args.cend(); ++ai) { - this->Makefile->RemoveDefinition(*ai); + makefile.RemoveDefinition(*ai); } } - this->Makefile->AddDefinition(listName, cmJoin(varArgsExpanded, ";")); + makefile.AddDefinition(listName, cmJoin(varArgsExpanded, ";")); } else if (ai != args.cend()) { // The list is empty, but some args were given // Need to *undefine* 'em all, cuz there are no items to assign... for (; ai != args.cend(); ++ai) { - this->Makefile->RemoveDefinition(*ai); + makefile.RemoveDefinition(*ai); } } return true; } -bool cmListCommand::HandleFindCommand(std::vector<std::string> const& args) +bool HandleFindCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() != 4) { - this->SetError("sub-command FIND requires three arguments."); + status.SetError("sub-command FIND requires three arguments."); return false; } @@ -380,8 +432,8 @@ bool cmListCommand::HandleFindCommand(std::vector<std::string> const& args) const std::string& variableName = args.back(); // expand the variable std::vector<std::string> varArgsExpanded; - if (!this->GetList(varArgsExpanded, listName)) { - this->Makefile->AddDefinition(variableName, "-1"); + if (!GetList(varArgsExpanded, listName, status.GetMakefile())) { + status.GetMakefile().AddDefinition(variableName, "-1"); return true; } @@ -390,18 +442,19 @@ bool cmListCommand::HandleFindCommand(std::vector<std::string> const& args) if (it != varArgsExpanded.end()) { std::ostringstream indexStream; indexStream << std::distance(varArgsExpanded.begin(), it); - this->Makefile->AddDefinition(variableName, indexStream.str()); + status.GetMakefile().AddDefinition(variableName, indexStream.str()); return true; } - this->Makefile->AddDefinition(variableName, "-1"); + status.GetMakefile().AddDefinition(variableName, "-1"); return true; } -bool cmListCommand::HandleInsertCommand(std::vector<std::string> const& args) +bool HandleInsertCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() < 4) { - this->SetError("sub-command INSERT requires at least three arguments."); + status.SetError("sub-command INSERT requires at least three arguments."); return false; } @@ -410,11 +463,12 @@ bool cmListCommand::HandleInsertCommand(std::vector<std::string> const& args) // expand the variable int item = atoi(args[2].c_str()); std::vector<std::string> varArgsExpanded; - if ((!this->GetList(varArgsExpanded, listName) || varArgsExpanded.empty()) && + if ((!GetList(varArgsExpanded, listName, status.GetMakefile()) || + varArgsExpanded.empty()) && item != 0) { std::ostringstream str; str << "index: " << item << " out of range (0, 0)"; - this->SetError(str.str()); + status.SetError(str.str()); return false; } @@ -427,7 +481,7 @@ bool cmListCommand::HandleInsertCommand(std::vector<std::string> const& args) std::ostringstream str; str << "index: " << item << " out of range (-" << varArgsExpanded.size() << ", " << varArgsExpanded.size() << ")"; - this->SetError(str.str()); + status.SetError(str.str()); return false; } } @@ -436,17 +490,18 @@ bool cmListCommand::HandleInsertCommand(std::vector<std::string> const& args) args.end()); std::string value = cmJoin(varArgsExpanded, ";"); - this->Makefile->AddDefinition(listName, value); + status.GetMakefile().AddDefinition(listName, value); return true; } -bool cmListCommand::HandleJoinCommand(std::vector<std::string> const& args) +bool HandleJoinCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() != 4) { std::ostringstream error; error << "sub-command JOIN requires three arguments (" << args.size() - 1 << " found)."; - this->SetError(error.str()); + status.SetError(error.str()); return false; } @@ -456,30 +511,30 @@ bool cmListCommand::HandleJoinCommand(std::vector<std::string> const& args) // expand the variable std::vector<std::string> varArgsExpanded; - if (!this->GetList(varArgsExpanded, listName)) { - this->Makefile->AddDefinition(variableName, ""); + if (!GetList(varArgsExpanded, listName, status.GetMakefile())) { + status.GetMakefile().AddDefinition(variableName, ""); return true; } std::string value = cmJoin(cmMakeRange(varArgsExpanded.begin(), varArgsExpanded.end()), glue); - this->Makefile->AddDefinition(variableName, value); + status.GetMakefile().AddDefinition(variableName, value); return true; } -bool cmListCommand::HandleRemoveItemCommand( - std::vector<std::string> const& args) +bool HandleRemoveItemCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() < 3) { - this->SetError("sub-command REMOVE_ITEM requires two or more arguments."); + status.SetError("sub-command REMOVE_ITEM requires two or more arguments."); return false; } const std::string& listName = args[1]; // expand the variable std::vector<std::string> varArgsExpanded; - if (!this->GetList(varArgsExpanded, listName)) { + if (!GetList(varArgsExpanded, listName, status.GetMakefile())) { return true; } @@ -493,44 +548,45 @@ bool cmListCommand::HandleRemoveItemCommand( cmRemoveMatching(varArgsExpanded, cmMakeRange(remBegin, remEnd)); std::vector<std::string>::const_iterator argsBegin = varArgsExpanded.begin(); std::string value = cmJoin(cmMakeRange(argsBegin, argsEnd), ";"); - this->Makefile->AddDefinition(listName, value); + status.GetMakefile().AddDefinition(listName, value); return true; } -bool cmListCommand::HandleReverseCommand(std::vector<std::string> const& args) +bool HandleReverseCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { assert(args.size() >= 2); if (args.size() > 2) { - this->SetError("sub-command REVERSE only takes one argument."); + status.SetError("sub-command REVERSE only takes one argument."); return false; } const std::string& listName = args[1]; // expand the variable std::vector<std::string> varArgsExpanded; - if (!this->GetList(varArgsExpanded, listName)) { + if (!GetList(varArgsExpanded, listName, status.GetMakefile())) { return true; } std::string value = cmJoin(cmReverseRange(varArgsExpanded), ";"); - this->Makefile->AddDefinition(listName, value); + status.GetMakefile().AddDefinition(listName, value); return true; } -bool cmListCommand::HandleRemoveDuplicatesCommand( - std::vector<std::string> const& args) +bool HandleRemoveDuplicatesCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { assert(args.size() >= 2); if (args.size() > 2) { - this->SetError("sub-command REMOVE_DUPLICATES only takes one argument."); + status.SetError("sub-command REMOVE_DUPLICATES only takes one argument."); return false; } const std::string& listName = args[1]; // expand the variable std::vector<std::string> varArgsExpanded; - if (!this->GetList(varArgsExpanded, listName)) { + if (!GetList(varArgsExpanded, listName, status.GetMakefile())) { return true; } @@ -539,12 +595,11 @@ bool cmListCommand::HandleRemoveDuplicatesCommand( std::vector<std::string>::const_iterator argsBegin = varArgsExpanded.begin(); std::string value = cmJoin(cmMakeRange(argsBegin, argsEnd), ";"); - this->Makefile->AddDefinition(listName, value); + status.GetMakefile().AddDefinition(listName, value); return true; } // Helpers for list(TRANSFORM <list> ...) -namespace { using transform_type = std::function<std::string(const std::string&)>; class transform_error : public std::runtime_error @@ -695,7 +750,8 @@ public: } this->Indexes.resize(size); - auto start = this->Start, step = this->Step; + auto start = this->Start; + auto step = this->Step; std::generate(this->Indexes.begin(), this->Indexes.end(), [&start, step]() -> int { auto r = start; @@ -759,13 +815,12 @@ public: private: cmStringReplaceHelper ReplaceHelper; }; -} -bool cmListCommand::HandleTransformCommand( - std::vector<std::string> const& args) +bool HandleTransformCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() < 3) { - this->SetError( + status.SetError( "sub-command TRANSFORM requires an action to be specified."); return false; } @@ -855,7 +910,7 @@ bool cmListCommand::HandleTransformCommand( { "STRIP", 0, [&command](const std::string& s) -> std::string { if (command.Selector->InSelection(s)) { - return cmSystemTools::TrimWhitespace(s); + return cmTrimWhitespace(s); } return s; @@ -888,7 +943,7 @@ bool cmListCommand::HandleTransformCommand( if (descriptor == descriptors.end()) { std::ostringstream error; error << " sub-command TRANSFORM, " << args[index] << " invalid action."; - this->SetError(error.str()); + status.SetError(error.str()); return false; } @@ -898,7 +953,7 @@ bool cmListCommand::HandleTransformCommand( std::ostringstream error; error << "sub-command TRANSFORM, action " << descriptor->Name << " expects " << descriptor->Arity << " argument(s)."; - this->SetError(error.str()); + status.SetError(error.str()); return false; } @@ -911,16 +966,18 @@ bool cmListCommand::HandleTransformCommand( if (command.Name == "REPLACE") { try { - command.Action = - cm::make_unique<TransformReplace>(command.Arguments, this->Makefile); + command.Action = cm::make_unique<TransformReplace>( + command.Arguments, &status.GetMakefile()); } catch (const transform_error& e) { - this->SetError(e.what()); + status.SetError(e.what()); return false; } } - const std::string REGEX{ "REGEX" }, AT{ "AT" }, FOR{ "FOR" }, - OUTPUT_VARIABLE{ "OUTPUT_VARIABLE" }; + const std::string REGEX{ "REGEX" }; + const std::string AT{ "AT" }; + const std::string FOR{ "FOR" }; + const std::string OUTPUT_VARIABLE{ "OUTPUT_VARIABLE" }; // handle optional arguments while (args.size() > index) { @@ -929,15 +986,15 @@ bool cmListCommand::HandleTransformCommand( std::ostringstream error; error << "sub-command TRANSFORM, selector already specified (" << command.Selector->Tag << ")."; - this->SetError(error.str()); + status.SetError(error.str()); return false; } // REGEX selector if (args[index] == REGEX) { if (args.size() == ++index) { - this->SetError("sub-command TRANSFORM, selector REGEX expects " - "'regular expression' argument."); + status.SetError("sub-command TRANSFORM, selector REGEX expects " + "'regular expression' argument."); return false; } @@ -947,7 +1004,7 @@ bool cmListCommand::HandleTransformCommand( error << "sub-command TRANSFORM, selector REGEX failed to compile " "regex \""; error << args[index] << "\"."; - this->SetError(error.str()); + status.SetError(error.str()); return false; } @@ -977,7 +1034,7 @@ bool cmListCommand::HandleTransformCommand( } if (indexes.empty()) { - this->SetError( + status.SetError( "sub-command TRANSFORM, selector AT expects at least one " "numeric value."); return false; @@ -992,12 +1049,15 @@ bool cmListCommand::HandleTransformCommand( // FOR selector if (args[index] == FOR) { if (args.size() <= ++index + 1) { - this->SetError("sub-command TRANSFORM, selector FOR expects, at least," - " two arguments."); + status.SetError( + "sub-command TRANSFORM, selector FOR expects, at least," + " two arguments."); return false; } - int start = 0, stop = 0, step = 1; + int start = 0; + int stop = 0; + int step = 1; bool valid = true; try { std::size_t pos; @@ -1018,8 +1078,8 @@ bool cmListCommand::HandleTransformCommand( valid = false; } if (!valid) { - this->SetError("sub-command TRANSFORM, selector FOR expects, " - "at least, two numeric values."); + status.SetError("sub-command TRANSFORM, selector FOR expects, " + "at least, two numeric values."); return false; } // try to read a third numeric value for step @@ -1040,8 +1100,8 @@ bool cmListCommand::HandleTransformCommand( } if (step < 0) { - this->SetError("sub-command TRANSFORM, selector FOR expects " - "non negative numeric value for <step>."); + status.SetError("sub-command TRANSFORM, selector FOR expects " + "non negative numeric value for <step>."); } command.Selector = @@ -1053,8 +1113,8 @@ bool cmListCommand::HandleTransformCommand( // output variable if (args[index] == OUTPUT_VARIABLE) { if (args.size() == ++index) { - this->SetError("sub-command TRANSFORM, OUTPUT_VARIABLE " - "expects variable name argument."); + status.SetError("sub-command TRANSFORM, OUTPUT_VARIABLE " + "expects variable name argument."); return false; } @@ -1066,14 +1126,14 @@ bool cmListCommand::HandleTransformCommand( error << "sub-command TRANSFORM, '" << cmJoin(cmMakeRange(args).advance(index), " ") << "': unexpected argument(s)."; - this->SetError(error.str()); + status.SetError(error.str()); return false; } // expand the list variable std::vector<std::string> varArgsExpanded; - if (!this->GetList(varArgsExpanded, command.ListName)) { - this->Makefile->AddDefinition(command.OutputName, ""); + if (!GetList(varArgsExpanded, command.ListName, status.GetMakefile())) { + status.GetMakefile().AddDefinition(command.OutputName, ""); return true; } @@ -1085,12 +1145,12 @@ bool cmListCommand::HandleTransformCommand( try { command.Selector->Transform(varArgsExpanded, descriptor->Transform); } catch (const transform_error& e) { - this->SetError(e.what()); + status.SetError(e.what()); return false; } - this->Makefile->AddDefinition(command.OutputName, - cmJoin(varArgsExpanded, ";")); + status.GetMakefile().AddDefinition(command.OutputName, + cmJoin(varArgsExpanded, ";")); return true; } @@ -1170,11 +1230,12 @@ protected: bool descending; }; -bool cmListCommand::HandleSortCommand(std::vector<std::string> const& args) +bool HandleSortCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { assert(args.size() >= 2); if (args.size() > 8) { - this->SetError("sub-command SORT only takes up to six arguments."); + status.SetError("sub-command SORT only takes up to six arguments."); return false; } @@ -1189,9 +1250,9 @@ bool cmListCommand::HandleSortCommand(std::vector<std::string> const& args) const std::string option = args[argumentIndex++]; if (option == "COMPARE") { if (sortCompare != cmStringSorter::Compare::UNINITIALIZED) { - std::string error = messageHint + "option \"" + option + - "\" has been specified multiple times."; - this->SetError(error); + std::string error = cmStrCat(messageHint, "option \"", option, + "\" has been specified multiple times."); + status.SetError(error); return false; } if (argumentIndex < args.size()) { @@ -1201,23 +1262,22 @@ bool cmListCommand::HandleSortCommand(std::vector<std::string> const& args) } else if (argument == "FILE_BASENAME") { sortCompare = cmStringSorter::Compare::FILE_BASENAME; } else { - std::string error = messageHint + "value \"" + argument + - "\" for option \"" + option + "\" is invalid."; - this->SetError(error); + std::string error = + cmStrCat(messageHint, "value \"", argument, "\" for option \"", + option, "\" is invalid."); + status.SetError(error); return false; } } else { - std::string error = - messageHint + "missing argument for option \"" + option + "\"."; - this->SetError(error); + status.SetError(cmStrCat(messageHint, "missing argument for option \"", + option, "\".")); return false; } } else if (option == "CASE") { if (sortCaseSensitivity != cmStringSorter::CaseSensitivity::UNINITIALIZED) { - std::string error = messageHint + "option \"" + option + - "\" has been specified multiple times."; - this->SetError(error); + status.SetError(cmStrCat(messageHint, "option \"", option, + "\" has been specified multiple times.")); return false; } if (argumentIndex < args.size()) { @@ -1227,23 +1287,21 @@ bool cmListCommand::HandleSortCommand(std::vector<std::string> const& args) } else if (argument == "INSENSITIVE") { sortCaseSensitivity = cmStringSorter::CaseSensitivity::INSENSITIVE; } else { - std::string error = messageHint + "value \"" + argument + - "\" for option \"" + option + "\" is invalid."; - this->SetError(error); + status.SetError(cmStrCat(messageHint, "value \"", argument, + "\" for option \"", option, + "\" is invalid.")); return false; } } else { - std::string error = - messageHint + "missing argument for option \"" + option + "\"."; - this->SetError(error); + status.SetError(cmStrCat(messageHint, "missing argument for option \"", + option, "\".")); return false; } } else if (option == "ORDER") { if (sortOrder != cmStringSorter::Order::UNINITIALIZED) { - std::string error = messageHint + "option \"" + option + - "\" has been specified multiple times."; - this->SetError(error); + status.SetError(cmStrCat(messageHint, "option \"", option, + "\" has been specified multiple times.")); return false; } if (argumentIndex < args.size()) { @@ -1253,21 +1311,19 @@ bool cmListCommand::HandleSortCommand(std::vector<std::string> const& args) } else if (argument == "DESCENDING") { sortOrder = cmStringSorter::Order::DESCENDING; } else { - std::string error = messageHint + "value \"" + argument + - "\" for option \"" + option + "\" is invalid."; - this->SetError(error); + status.SetError(cmStrCat(messageHint, "value \"", argument, + "\" for option \"", option, + "\" is invalid.")); return false; } } else { - std::string error = - messageHint + "missing argument for option \"" + option + "\"."; - this->SetError(error); + status.SetError(cmStrCat(messageHint, "missing argument for option \"", + option, "\".")); return false; } } else { - std::string error = - messageHint + "option \"" + option + "\" is unknown."; - this->SetError(error); + status.SetError( + cmStrCat(messageHint, "option \"", option, "\" is unknown.")); return false; } } @@ -1285,7 +1341,7 @@ bool cmListCommand::HandleSortCommand(std::vector<std::string> const& args) const std::string& listName = args[1]; // expand the variable std::vector<std::string> varArgsExpanded; - if (!this->GetList(varArgsExpanded, listName)) { + if (!GetList(varArgsExpanded, listName, status.GetMakefile())) { return true; } @@ -1299,17 +1355,18 @@ bool cmListCommand::HandleSortCommand(std::vector<std::string> const& args) } std::string value = cmJoin(varArgsExpanded, ";"); - this->Makefile->AddDefinition(listName, value); + status.GetMakefile().AddDefinition(listName, value); return true; } -bool cmListCommand::HandleSublistCommand(std::vector<std::string> const& args) +bool HandleSublistCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() != 5) { std::ostringstream error; error << "sub-command SUBLIST requires four arguments (" << args.size() - 1 << " found)."; - this->SetError(error.str()); + status.SetError(error.str()); return false; } @@ -1318,8 +1375,9 @@ bool cmListCommand::HandleSublistCommand(std::vector<std::string> const& args) // expand the variable std::vector<std::string> varArgsExpanded; - if (!this->GetList(varArgsExpanded, listName) || varArgsExpanded.empty()) { - this->Makefile->AddDefinition(variableName, ""); + if (!GetList(varArgsExpanded, listName, status.GetMakefile()) || + varArgsExpanded.empty()) { + status.GetMakefile().AddDefinition(variableName, ""); return true; } @@ -1332,13 +1390,13 @@ bool cmListCommand::HandleSublistCommand(std::vector<std::string> const& args) std::ostringstream error; error << "begin index: " << start << " is out of range 0 - " << varArgsExpanded.size() - 1; - this->SetError(error.str()); + status.SetError(error.str()); return false; } if (length < -1) { std::ostringstream error; error << "length: " << length << " should be -1 or greater"; - this->SetError(error.str()); + status.SetError(error.str()); return false; } @@ -1348,22 +1406,24 @@ bool cmListCommand::HandleSublistCommand(std::vector<std::string> const& args) : size_type(start + length); std::vector<std::string> sublist(varArgsExpanded.begin() + start, varArgsExpanded.begin() + end); - this->Makefile->AddDefinition(variableName, cmJoin(sublist, ";")); + status.GetMakefile().AddDefinition(variableName, cmJoin(sublist, ";")); return true; } -bool cmListCommand::HandleRemoveAtCommand(std::vector<std::string> const& args) +bool HandleRemoveAtCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() < 3) { - this->SetError("sub-command REMOVE_AT requires at least " - "two arguments."); + status.SetError("sub-command REMOVE_AT requires at least " + "two arguments."); return false; } const std::string& listName = args[1]; // expand the variable std::vector<std::string> varArgsExpanded; - if (!this->GetList(varArgsExpanded, listName) || varArgsExpanded.empty()) { + if (!GetList(varArgsExpanded, listName, status.GetMakefile()) || + varArgsExpanded.empty()) { std::ostringstream str; str << "index: "; for (size_t i = 1; i < args.size(); ++i) { @@ -1373,7 +1433,7 @@ bool cmListCommand::HandleRemoveAtCommand(std::vector<std::string> const& args) } } str << " out of range (0, 0)"; - this->SetError(str.str()); + status.SetError(str.str()); return false; } @@ -1389,7 +1449,7 @@ bool cmListCommand::HandleRemoveAtCommand(std::vector<std::string> const& args) std::ostringstream str; str << "index: " << item << " out of range (-" << nitem << ", " << nitem - 1 << ")"; - this->SetError(str.str()); + status.SetError(str.str()); return false; } removed.push_back(static_cast<size_t>(item)); @@ -1405,24 +1465,26 @@ bool cmListCommand::HandleRemoveAtCommand(std::vector<std::string> const& args) std::vector<std::string>::const_iterator argsBegin = varArgsExpanded.begin(); std::string value = cmJoin(cmMakeRange(argsBegin, argsEnd), ";"); - this->Makefile->AddDefinition(listName, value); + status.GetMakefile().AddDefinition(listName, value); return true; } -bool cmListCommand::HandleFilterCommand(std::vector<std::string> const& args) +bool HandleFilterCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() < 2) { - this->SetError("sub-command FILTER requires a list to be specified."); + status.SetError("sub-command FILTER requires a list to be specified."); return false; } if (args.size() < 3) { - this->SetError("sub-command FILTER requires an operator to be specified."); + status.SetError( + "sub-command FILTER requires an operator to be specified."); return false; } if (args.size() < 4) { - this->SetError("sub-command FILTER requires a mode to be specified."); + status.SetError("sub-command FILTER requires a mode to be specified."); return false; } @@ -1433,28 +1495,29 @@ bool cmListCommand::HandleFilterCommand(std::vector<std::string> const& args) } else if (op == "EXCLUDE") { includeMatches = false; } else { - this->SetError("sub-command FILTER does not recognize operator " + op); + status.SetError("sub-command FILTER does not recognize operator " + op); return false; } const std::string& listName = args[1]; // expand the variable std::vector<std::string> varArgsExpanded; - if (!this->GetList(varArgsExpanded, listName)) { + if (!GetList(varArgsExpanded, listName, status.GetMakefile())) { return true; } const std::string& mode = args[3]; if (mode == "REGEX") { if (args.size() != 5) { - this->SetError("sub-command FILTER, mode REGEX " - "requires five arguments."); + status.SetError("sub-command FILTER, mode REGEX " + "requires five arguments."); return false; } - return this->FilterRegex(args, includeMatches, listName, varArgsExpanded); + return FilterRegex(args, includeMatches, listName, varArgsExpanded, + status); } - this->SetError("sub-command FILTER does not recognize mode " + mode); + status.SetError("sub-command FILTER does not recognize mode " + mode); return false; } @@ -1477,19 +1540,18 @@ private: const bool includeMatches; }; -bool cmListCommand::FilterRegex(std::vector<std::string> const& args, - bool includeMatches, - std::string const& listName, - std::vector<std::string>& varArgsExpanded) +bool FilterRegex(std::vector<std::string> const& args, bool includeMatches, + std::string const& listName, + std::vector<std::string>& varArgsExpanded, + cmExecutionStatus& status) { const std::string& pattern = args[4]; cmsys::RegularExpression regex(pattern); if (!regex.is_valid()) { - std::string error = "sub-command FILTER, mode REGEX "; - error += "failed to compile regex \""; - error += pattern; - error += "\"."; - this->SetError(error); + std::string error = + cmStrCat("sub-command FILTER, mode REGEX failed to compile regex \"", + pattern, "\"."); + status.SetError(error); return false; } @@ -1499,6 +1561,7 @@ bool cmListCommand::FilterRegex(std::vector<std::string> const& args, std::remove_if(argsBegin, argsEnd, MatchesRegex(regex, includeMatches)); std::string value = cmJoin(cmMakeRange(argsBegin, newArgsEnd), ";"); - this->Makefile->AddDefinition(listName, value); + status.GetMakefile().AddDefinition(listName, value); return true; } +} diff --git a/Source/cmListCommand.h b/Source/cmListCommand.h index 70c7f4e..274d9fd 100644 --- a/Source/cmListCommand.h +++ b/Source/cmListCommand.h @@ -8,58 +8,13 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -/** \class cmListCommand +/** * \brief Common list operations * */ -class cmListCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmListCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; - -protected: - bool HandleLengthCommand(std::vector<std::string> const& args); - bool HandleGetCommand(std::vector<std::string> const& args); - bool HandleAppendCommand(std::vector<std::string> const& args); - bool HandlePrependCommand(std::vector<std::string> const& args); - bool HandlePopBackCommand(std::vector<std::string> const& args); - bool HandlePopFrontCommand(std::vector<std::string> const& args); - bool HandleFindCommand(std::vector<std::string> const& args); - bool HandleInsertCommand(std::vector<std::string> const& args); - bool HandleJoinCommand(std::vector<std::string> const& args); - bool HandleRemoveAtCommand(std::vector<std::string> const& args); - bool HandleRemoveItemCommand(std::vector<std::string> const& args); - bool HandleRemoveDuplicatesCommand(std::vector<std::string> const& args); - bool HandleTransformCommand(std::vector<std::string> const& args); - bool HandleSortCommand(std::vector<std::string> const& args); - bool HandleSublistCommand(std::vector<std::string> const& args); - bool HandleReverseCommand(std::vector<std::string> const& args); - bool HandleFilterCommand(std::vector<std::string> const& args); - bool FilterRegex(std::vector<std::string> const& args, bool includeMatches, - std::string const& listName, - std::vector<std::string>& varArgsExpanded); - - bool GetList(std::vector<std::string>& list, const std::string& var); - bool GetListString(std::string& listString, const std::string& var); -}; +bool cmListCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmListFileCache.cxx b/Source/cmListFileCache.cxx index df0d00c..7ef475a 100644 --- a/Source/cmListFileCache.cxx +++ b/Source/cmListFileCache.cxx @@ -7,6 +7,7 @@ #include "cmMessenger.h" #include "cmState.h" #include "cmStateDirectory.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include <assert.h> @@ -483,7 +484,7 @@ std::vector<BT<std::string>> ExpandListWithBacktrace( { std::vector<BT<std::string>> result; std::vector<std::string> tmp; - cmSystemTools::ExpandListArgument(list, tmp); + cmExpandList(list, tmp); result.reserve(tmp.size()); for (std::string& i : tmp) { result.emplace_back(std::move(i), bt); diff --git a/Source/cmLoadCommandCommand.cxx b/Source/cmLoadCommandCommand.cxx index 5ae660a..180e65b 100644 --- a/Source/cmLoadCommandCommand.cxx +++ b/Source/cmLoadCommandCommand.cxx @@ -17,6 +17,7 @@ #include "cmDynamicLoader.h" #include "cmMakefile.h" #include "cmState.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" class cmExecutionStatus; @@ -183,16 +184,14 @@ bool cmLoadCommandCommand::InitialPass(std::vector<std::string> const& args, // Construct a variable to report what file was loaded, if any. // Start by removing the definition in case of failure. - std::string reportVar = "CMAKE_LOADED_COMMAND_"; - reportVar += args[0]; + std::string reportVar = cmStrCat("CMAKE_LOADED_COMMAND_", args[0]); this->Makefile->RemoveDefinition(reportVar); // the file must exist - std::string moduleName = - this->Makefile->GetRequiredDefinition("CMAKE_SHARED_MODULE_PREFIX"); - moduleName += "cm" + args[0]; - moduleName += - this->Makefile->GetRequiredDefinition("CMAKE_SHARED_MODULE_SUFFIX"); + std::string moduleName = cmStrCat( + this->Makefile->GetRequiredDefinition("CMAKE_SHARED_MODULE_PREFIX"), "cm", + args[0], + this->Makefile->GetRequiredDefinition("CMAKE_SHARED_MODULE_SUFFIX")); // search for the file std::vector<std::string> path; @@ -218,8 +217,8 @@ bool cmLoadCommandCommand::InitialPass(std::vector<std::string> const& args, cmsys::DynamicLoader::LibraryHandle lib = cmDynamicLoader::OpenLibrary(fullPath.c_str()); if (!lib) { - std::string err = "Attempt to load the library "; - err += fullPath + " failed."; + std::string err = + cmStrCat("Attempt to load the library ", fullPath, " failed."); const char* error = cmsys::DynamicLoader::LastError(); if (error) { err += " Additional error info is:\n"; @@ -237,9 +236,7 @@ bool cmLoadCommandCommand::InitialPass(std::vector<std::string> const& args, CM_INIT_FUNCTION initFunction = reinterpret_cast<CM_INIT_FUNCTION>( cmsys::DynamicLoader::GetSymbolAddress(lib, initFuncName)); if (!initFunction) { - initFuncName = "_"; - initFuncName += args[0]; - initFuncName += "Init"; + initFuncName = cmStrCat('_', args[0], "Init"); initFunction = reinterpret_cast<CM_INIT_FUNCTION>( cmsys::DynamicLoader::GetSymbolAddress(lib, initFuncName)); } diff --git a/Source/cmLocalCommonGenerator.cxx b/Source/cmLocalCommonGenerator.cxx index 75ad2a6..7c36bdc 100644 --- a/Source/cmLocalCommonGenerator.cxx +++ b/Source/cmLocalCommonGenerator.cxx @@ -8,6 +8,7 @@ #include "cmGeneratorTarget.h" #include "cmMakefile.h" #include "cmOutputConverter.h" +#include "cmStringAlgorithms.h" class cmGlobalGenerator; @@ -51,9 +52,9 @@ std::string cmLocalCommonGenerator::GetTargetFortranFlags( this->Makefile->GetSafeDefinition("CMAKE_Fortran_MODDIR_DEFAULT"); } if (!mod_dir.empty()) { - std::string modflag = - this->Makefile->GetRequiredDefinition("CMAKE_Fortran_MODDIR_FLAG"); - modflag += mod_dir; + std::string modflag = cmStrCat( + this->Makefile->GetRequiredDefinition("CMAKE_Fortran_MODDIR_FLAG"), + mod_dir); this->AppendFlags(flags, modflag); } @@ -65,8 +66,9 @@ std::string cmLocalCommonGenerator::GetTargetFortranFlags( std::vector<std::string> includes; this->GetIncludeDirectories(includes, target, "C", config); for (std::string const& id : includes) { - std::string flg = modpath_flag; - flg += this->ConvertToOutputFormat(id, cmOutputConverter::SHELL); + std::string flg = + cmStrCat(modpath_flag, + this->ConvertToOutputFormat(id, cmOutputConverter::SHELL)); this->AppendFlags(flags, flg); } } diff --git a/Source/cmLocalGenerator.cxx b/Source/cmLocalGenerator.cxx index 28ae82e..1827a42 100644 --- a/Source/cmLocalGenerator.cxx +++ b/Source/cmLocalGenerator.cxx @@ -26,10 +26,11 @@ #include "cmTarget.h" #include "cmTestGenerator.h" #include "cmVersion.h" +#include "cm_string_view.hxx" #include "cmake.h" #include "cmsys/RegularExpression.hxx" -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) # define CM_LG_ENCODE_OBJECT_NAMES # include "cmCryptoHash.h" #endif @@ -283,9 +284,9 @@ void cmLocalGenerator::GenerateTestFiles() const std::string& config = this->Makefile->GetConfigurations(configurationTypes, false); - std::string file = this->StateSnapshot.GetDirectory().GetCurrentBinary(); - file += "/"; - file += "CTestTestfile.cmake"; + std::string file = + cmStrCat(this->StateSnapshot.GetDirectory().GetCurrentBinary(), + "/CTestTestfile.cmake"); cmGeneratedFileStream fout(file); fout.SetCopyIfDifferent(true); @@ -311,7 +312,7 @@ void cmLocalGenerator::GenerateTestFiles() this->Makefile->GetProperty("TEST_INCLUDE_FILES"); if (testIncludeFiles) { std::vector<std::string> includesList; - cmSystemTools::ExpandListArgument(testIncludeFiles, includesList); + cmExpandList(testIncludeFiles, includesList); for (std::string const& i : includesList) { fout << "include(\"" << i << "\")" << std::endl; } @@ -745,12 +746,10 @@ std::string cmLocalGenerator::GetIncludeFlags( OutputFormat shellFormat = forResponseFile ? RESPONSE : SHELL; std::ostringstream includeFlags; - std::string flagVar = "CMAKE_INCLUDE_FLAG_"; - flagVar += lang; - std::string const& includeFlag = this->Makefile->GetSafeDefinition(flagVar); - flagVar = "CMAKE_INCLUDE_FLAG_SEP_"; - flagVar += lang; - const char* sep = this->Makefile->GetDefinition(flagVar); + std::string const& includeFlag = + this->Makefile->GetSafeDefinition(cmStrCat("CMAKE_INCLUDE_FLAG_", lang)); + const char* sep = + this->Makefile->GetDefinition(cmStrCat("CMAKE_INCLUDE_FLAG_SEP_", lang)); bool quotePaths = false; if (this->Makefile->GetDefinition("CMAKE_QUOTE_INCLUDE_PATHS")) { quotePaths = true; @@ -767,23 +766,16 @@ std::string cmLocalGenerator::GetIncludeFlags( // Support special system include flag if it is available and the // normal flag is repeated for each directory. - std::string sysFlagVar = "CMAKE_INCLUDE_SYSTEM_FLAG_"; - sysFlagVar += lang; const char* sysIncludeFlag = nullptr; if (repeatFlag) { - sysIncludeFlag = this->Makefile->GetDefinition(sysFlagVar); + sysIncludeFlag = this->Makefile->GetDefinition( + cmStrCat("CMAKE_INCLUDE_SYSTEM_FLAG_", lang)); } - std::string fwSearchFlagVar = "CMAKE_"; - fwSearchFlagVar += lang; - fwSearchFlagVar += "_FRAMEWORK_SEARCH_FLAG"; - const char* fwSearchFlag = this->Makefile->GetDefinition(fwSearchFlagVar); - - std::string sysFwSearchFlagVar = "CMAKE_"; - sysFwSearchFlagVar += lang; - sysFwSearchFlagVar += "_SYSTEM_FRAMEWORK_SEARCH_FLAG"; - const char* sysFwSearchFlag = - this->Makefile->GetDefinition(sysFwSearchFlagVar); + const char* fwSearchFlag = this->Makefile->GetDefinition( + cmStrCat("CMAKE_", lang, "_FRAMEWORK_SEARCH_FLAG")); + const char* sysFwSearchFlag = this->Makefile->GetDefinition( + cmStrCat("CMAKE_", lang, "_SYSTEM_FRAMEWORK_SEARCH_FLAG")); bool flagUsed = false; std::set<std::string> emitted; @@ -793,9 +785,8 @@ std::string cmLocalGenerator::GetIncludeFlags( for (std::string const& i : includes) { if (fwSearchFlag && *fwSearchFlag && this->Makefile->IsOn("APPLE") && cmSystemTools::IsPathToFramework(i)) { - std::string frameworkDir = i; - frameworkDir += "/../"; - frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir); + std::string const frameworkDir = + cmSystemTools::CollapseFullPath(cmStrCat(i, "/../")); if (emitted.insert(frameworkDir).second) { if (sysFwSearchFlag && target && target->IsSystemIncludeDirectory(i, config, lang)) { @@ -910,9 +901,9 @@ void cmLocalGenerator::AddCompileOptions(std::string& flags, std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(jmcExprGen); std::string isJMCEnabled = cge->Evaluate(this, config); - if (cmSystemTools::IsOn(isJMCEnabled)) { + if (cmIsOn(isJMCEnabled)) { std::vector<std::string> optVec; - cmSystemTools::ExpandListArgument(jmc, optVec); + cmExpandList(jmc, optVec); this->AppendCompileOptions(flags, optVec); } } @@ -963,11 +954,9 @@ std::vector<BT<std::string>> cmLocalGenerator::GetIncludeDirectoriesImplicit( // These are intended to simulate additional implicit include directories. std::vector<std::string> userStandardDirs; { - std::string key = "CMAKE_"; - key += lang; - key += "_STANDARD_INCLUDE_DIRECTORIES"; - std::string const value = this->Makefile->GetSafeDefinition(key); - cmSystemTools::ExpandListArgument(value, userStandardDirs); + std::string const value = this->Makefile->GetSafeDefinition( + cmStrCat("CMAKE_", lang, "_STANDARD_INCLUDE_DIRECTORIES")); + cmExpandList(value, userStandardDirs); for (std::string& usd : userStandardDirs) { cmSystemTools::ConvertToUnixSlashes(usd); } @@ -989,12 +978,11 @@ std::vector<BT<std::string>> cmLocalGenerator::GetIncludeDirectoriesImplicit( // * Compilers like gfortran do not search their own implicit include // directories for modules ('.mod' files). if (lang != "Fortran") { - std::string key = "CMAKE_"; - key += lang; - key += "_IMPLICIT_INCLUDE_DIRECTORIES"; - if (const char* value = this->Makefile->GetDefinition(key)) { + const char* value = this->Makefile->GetDefinition( + cmStrCat("CMAKE_", lang, "_IMPLICIT_INCLUDE_DIRECTORIES")); + if (value != nullptr) { size_t const impDirVecOldSize = impDirVec.size(); - cmSystemTools::ExpandListArgument(value, impDirVec); + cmExpandList(value, impDirVec); // FIXME: Use cmRange with 'advance()' when it supports non-const. for (size_t i = impDirVecOldSize; i < impDirVec.size(); ++i) { cmSystemTools::ConvertToUnixSlashes(impDirVec[i]); @@ -1009,8 +997,7 @@ std::vector<BT<std::string>> cmLocalGenerator::GetIncludeDirectoriesImplicit( // directly. In this case adding -I/usr/include can hide SDK headers so we // must still exclude it. if ((lang == "C" || lang == "CXX" || lang == "CUDA") && - std::find(impDirVec.begin(), impDirVec.end(), "/usr/include") == - impDirVec.end() && + !cmContains(impDirVec, "/usr/include") && std::find_if(impDirVec.begin(), impDirVec.end(), [](std::string const& d) { return cmHasLiteralSuffix(d, "/usr/include"); @@ -1031,15 +1018,13 @@ std::vector<BT<std::string>> cmLocalGenerator::GetIncludeDirectoriesImplicit( &lang](std::string const& dir) { return ( // Do not exclude directories that are not in an excluded set. - ((implicitSet.find(cmSystemTools::GetRealPath(dir)) == - implicitSet.end()) && - (implicitExclude.find(dir) == implicitExclude.end())) + ((!cmContains(implicitSet, cmSystemTools::GetRealPath(dir))) && + (!cmContains(implicitExclude, dir))) // Do not exclude entries of the CPATH environment variable even though // they are implicitly searched by the compiler. They are meant to be // user-specified directories that can be re-ordered or converted to // -isystem without breaking real compiler builtin headers. - || ((lang == "C" || lang == "CXX") && - (this->EnvCPATH.find(dir) != this->EnvCPATH.end()))); + || ((lang == "C" || lang == "CXX") && cmContains(this->EnvCPATH, dir))); }; // Get the target-specific include directories. @@ -1049,8 +1034,8 @@ std::vector<BT<std::string>> cmLocalGenerator::GetIncludeDirectoriesImplicit( // Support putting all the in-project include directories first if // it is requested by the project. if (this->Makefile->IsOn("CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE")) { - std::string const &topSourceDir = this->GetState()->GetSourceDirectory(), - &topBinaryDir = this->GetState()->GetBinaryDirectory(); + std::string const& topSourceDir = this->GetState()->GetSourceDirectory(); + std::string const& topBinaryDir = this->GetState()->GetBinaryDirectory(); for (BT<std::string> const& udr : userDirs) { // Emit this directory only if it is a subdirectory of the // top-level source or binary tree. @@ -1086,8 +1071,7 @@ std::vector<BT<std::string>> cmLocalGenerator::GetIncludeDirectoriesImplicit( if (!stripImplicitDirs) { // Append implicit directories that were requested by the user only for (BT<std::string> const& udr : userDirs) { - if (implicitSet.find(cmSystemTools::GetRealPath(udr.Value)) != - implicitSet.end()) { + if (cmContains(implicitSet, cmSystemTools::GetRealPath(udr.Value))) { emitBT(udr); } } @@ -1177,12 +1161,10 @@ void cmLocalGenerator::GetTargetFlags( CM_FALLTHROUGH; case cmStateEnums::SHARED_LIBRARY: { if (linkLanguage != "Swift") { - linkFlags = this->Makefile->GetSafeDefinition(libraryLinkVariable); - linkFlags += " "; + linkFlags = cmStrCat( + this->Makefile->GetSafeDefinition(libraryLinkVariable), ' '); if (!buildType.empty()) { - std::string build = libraryLinkVariable; - build += "_"; - build += buildType; + std::string build = cmStrCat(libraryLinkVariable, '_', buildType); linkFlags += this->Makefile->GetSafeDefinition(build); linkFlags += " "; } @@ -1210,9 +1192,8 @@ void cmLocalGenerator::GetTargetFlags( linkFlags += " "; } if (!buildType.empty()) { - std::string configLinkFlags = "LINK_FLAGS_"; - configLinkFlags += buildType; - targetLinkFlags = target->GetProperty(configLinkFlags); + targetLinkFlags = + target->GetProperty(cmStrCat("LINK_FLAGS_", buildType)); if (targetLinkFlags) { linkFlags += targetLinkFlags; linkFlags += " "; @@ -1234,9 +1215,8 @@ void cmLocalGenerator::GetTargetFlags( this->Makefile->GetSafeDefinition("CMAKE_EXE_LINKER_FLAGS"); linkFlags += " "; if (!buildType.empty()) { - std::string build = "CMAKE_EXE_LINKER_FLAGS_"; - build += buildType; - linkFlags += this->Makefile->GetSafeDefinition(build); + linkFlags += this->Makefile->GetSafeDefinition( + cmStrCat("CMAKE_EXE_LINKER_FLAGS_", buildType)); linkFlags += " "; } if (linkLanguage.empty()) { @@ -1257,11 +1237,8 @@ void cmLocalGenerator::GetTargetFlags( } if (target->IsExecutableWithExports()) { - std::string exportFlagVar = "CMAKE_EXE_EXPORTS_"; - exportFlagVar += linkLanguage; - exportFlagVar += "_FLAG"; - - linkFlags += this->Makefile->GetSafeDefinition(exportFlagVar); + linkFlags += this->Makefile->GetSafeDefinition( + cmStrCat("CMAKE_EXE_EXPORTS_", linkLanguage, "_FLAG")); linkFlags += " "; } } @@ -1272,8 +1249,7 @@ void cmLocalGenerator::GetTargetFlags( frameworkPath, linkPath); } - if (cmSystemTools::IsOn( - this->Makefile->GetDefinition("BUILD_SHARED_LIBS"))) { + if (cmIsOn(this->Makefile->GetDefinition("BUILD_SHARED_LIBS"))) { std::string sFlagVar = std::string("CMAKE_SHARED_BUILD_") + linkLanguage + std::string("_FLAGS"); linkFlags += this->Makefile->GetSafeDefinition(sFlagVar); @@ -1293,9 +1269,8 @@ void cmLocalGenerator::GetTargetFlags( linkFlags += " "; } if (!buildType.empty()) { - std::string configLinkFlags = "LINK_FLAGS_"; - configLinkFlags += buildType; - targetLinkFlags = target->GetProperty(configLinkFlags); + targetLinkFlags = + target->GetProperty(cmStrCat("LINK_FLAGS_", buildType)); if (targetLinkFlags) { linkFlags += targetLinkFlags; linkFlags += " "; @@ -1371,8 +1346,7 @@ static std::string GetFrameworkFlags(const std::string& lang, // will already have added a -F for the framework for (std::string const& include : includes) { if (lg->GetGlobalGenerator()->NameResolvesToFramework(include)) { - std::string frameworkDir = include; - frameworkDir += "/../"; + std::string frameworkDir = cmStrCat(include, "/../"); frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir); emitted.insert(frameworkDir); } @@ -1470,20 +1444,12 @@ void cmLocalGenerator::OutputLinkLibraries( } // Add standard libraries for this language. - std::string standardLibsVar = "CMAKE_"; - standardLibsVar += cli.GetLinkLanguage(); - standardLibsVar += "_STANDARD_LIBRARIES"; - std::string stdLibString; - if (const char* stdLibs = this->Makefile->GetDefinition(standardLibsVar)) { - stdLibString = stdLibs; - } + std::string stdLibString = this->Makefile->GetSafeDefinition( + cmStrCat("CMAKE_", cli.GetLinkLanguage(), "_STANDARD_LIBRARIES")); // Append the framework search path flags. - std::string fwSearchFlagVar = "CMAKE_"; - fwSearchFlagVar += linkLanguage; - fwSearchFlagVar += "_FRAMEWORK_SEARCH_FLAG"; - std::string fwSearchFlag = - this->Makefile->GetSafeDefinition(fwSearchFlagVar); + std::string fwSearchFlag = this->Makefile->GetSafeDefinition( + cmStrCat("CMAKE_", linkLanguage, "_FRAMEWORK_SEARCH_FLAG")); frameworkPath = linkLineComputer->ComputeFrameworkPath(cli, fwSearchFlag); linkPath = @@ -1538,10 +1504,8 @@ std::string cmLocalGenerator::GetLinkLibsCMP0065( } if (add_shlib_flags) { - std::string linkFlagsVar = "CMAKE_SHARED_LIBRARY_LINK_"; - linkFlagsVar += linkLanguage; - linkFlagsVar += "_FLAGS"; - linkFlags = this->Makefile->GetSafeDefinition(linkFlagsVar); + linkFlags = this->Makefile->GetSafeDefinition( + cmStrCat("CMAKE_SHARED_LIBRARY_LINK_", linkLanguage, "_FLAGS")); } } return linkFlags; @@ -1599,10 +1563,8 @@ void cmLocalGenerator::AddLanguageFlags(std::string& flags, const std::string& config) { // Add language-specific flags. - std::string flagsVar = "CMAKE_"; - flagsVar += lang; - flagsVar += "_FLAGS"; - this->AddConfigVariableFlags(flags, flagsVar, config); + this->AddConfigVariableFlags(flags, cmStrCat("CMAKE_", lang, "_FLAGS"), + config); // Add MSVC runtime library flags. This is activated by the presence // of a default selection whether or not it is overridden by a property. @@ -1760,9 +1722,8 @@ bool cmLocalGenerator::GetRealDependency(const std::string& inName, // Treat the name as relative to the source directory in which it // was given. - dep = this->StateSnapshot.GetDirectory().GetCurrentSource(); - dep += "/"; - dep += inName; + dep = cmStrCat(this->StateSnapshot.GetDirectory().GetCurrentSource(), '/', + inName); return true; } @@ -1773,10 +1734,9 @@ void cmLocalGenerator::AddSharedFlags(std::string& flags, // Add flags for dealing with shared libraries for this language. if (shared) { - flagsVar = "CMAKE_SHARED_LIBRARY_"; - flagsVar += lang; - flagsVar += "_FLAGS"; - this->AppendFlags(flags, this->Makefile->GetDefinition(flagsVar)); + this->AppendFlags(flags, + this->Makefile->GetDefinition( + cmStrCat("CMAKE_SHARED_LIBRARY_", lang, "_FLAGS"))); } } @@ -1795,7 +1755,7 @@ void cmLocalGenerator::AddCompilerRequirementFlag( std::string extProp = lang + "_EXTENSIONS"; bool ext = true; if (const char* extPropValue = target->GetProperty(extProp)) { - if (cmSystemTools::IsOff(extPropValue)) { + if (cmIsOff(extPropValue)) { ext = false; } } @@ -1810,7 +1770,7 @@ void cmLocalGenerator::AddCompilerRequirementFlag( if (const char* opt = target->Target->GetMakefile()->GetDefinition(option_flag)) { std::vector<std::string> optVec; - cmSystemTools::ExpandListArgument(opt, optVec); + cmExpandList(opt, optVec); for (std::string const& i : optVec) { this->AppendFlagEscape(flags, i); } @@ -1839,7 +1799,7 @@ void cmLocalGenerator::AddCompilerRequirementFlag( this->IssueMessage(MessageType::FATAL_ERROR, e.str()); } else { std::vector<std::string> optVec; - cmSystemTools::ExpandListArgument(opt, optVec); + cmExpandList(opt, optVec); for (std::string const& i : optVec) { this->AppendFlagEscape(flags, i); } @@ -1900,7 +1860,7 @@ void cmLocalGenerator::AddCompilerRequirementFlag( std::string const& opt = target->Target->GetMakefile()->GetRequiredDefinition(option_flag); std::vector<std::string> optVec; - cmSystemTools::ExpandListArgument(opt, optVec); + cmExpandList(opt, optVec); for (std::string const& i : optVec) { this->AppendFlagEscape(flags, i); } @@ -1912,12 +1872,12 @@ void cmLocalGenerator::AddCompilerRequirementFlag( // for which a flag is defined. for (; stdIt < defaultStdIt; ++stdIt) { std::string option_flag = - "CMAKE_" + lang + *stdIt + "_" + type + "_COMPILE_OPTION"; + cmStrCat("CMAKE_", lang, *stdIt, "_", type, "_COMPILE_OPTION"); if (const char* opt = target->Target->GetMakefile()->GetDefinition(option_flag)) { std::vector<std::string> optVec; - cmSystemTools::ExpandListArgument(opt, optVec); + cmExpandList(opt, optVec); for (std::string const& i : optVec) { this->AppendFlagEscape(flags, i); } @@ -2065,9 +2025,7 @@ bool cmLocalGenerator::GetShouldUseOldFlags(bool shared, std::string originalFlags = this->GlobalGenerator->GetSharedLibFlagsForLanguage(lang); if (shared) { - std::string flagsVar = "CMAKE_SHARED_LIBRARY_"; - flagsVar += lang; - flagsVar += "_FLAGS"; + std::string flagsVar = cmStrCat("CMAKE_SHARED_LIBRARY_", lang, "_FLAGS"); std::string const& flags = this->Makefile->GetSafeDefinition(flagsVar); if (flags != originalFlags) { @@ -2106,20 +2064,16 @@ void cmLocalGenerator::AddPositionIndependentFlags(std::string& flags, std::string picFlags; if (targetType == cmStateEnums::EXECUTABLE) { - std::string flagsVar = "CMAKE_"; - flagsVar += lang; - flagsVar += "_COMPILE_OPTIONS_PIE"; - picFlags = this->Makefile->GetSafeDefinition(flagsVar); + picFlags = this->Makefile->GetSafeDefinition( + cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_PIE")); } if (picFlags.empty()) { - std::string flagsVar = "CMAKE_"; - flagsVar += lang; - flagsVar += "_COMPILE_OPTIONS_PIC"; - picFlags = this->Makefile->GetSafeDefinition(flagsVar); + picFlags = this->Makefile->GetSafeDefinition( + cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_PIC")); } if (!picFlags.empty()) { std::vector<std::string> options; - cmSystemTools::ExpandListArgument(picFlags, options); + cmExpandList(picFlags, options); for (std::string const& o : options) { this->AppendFlagEscape(flags, o); } @@ -2191,7 +2145,7 @@ void cmLocalGenerator::AppendIPOLinkerFlags(std::string& flags, } std::vector<std::string> flagsList; - cmSystemTools::ExpandListArgument(rawFlagsList, flagsList); + cmExpandList(rawFlagsList, flagsList); for (std::string const& o : flagsList) { this->AppendFlagEscape(flags, o); } @@ -2212,10 +2166,10 @@ void cmLocalGenerator::AppendPositionIndependentLinkerFlags( return; } - const std::string mode = cmSystemTools::IsOn(PICValue) ? "PIE" : "NO_PIE"; + const std::string mode = cmIsOn(PICValue) ? "PIE" : "NO_PIE"; std::string supported = "CMAKE_" + lang + "_LINK_" + mode + "_SUPPORTED"; - if (cmSystemTools::IsOff(this->Makefile->GetDefinition(supported))) { + if (cmIsOff(this->Makefile->GetDefinition(supported))) { return; } @@ -2227,7 +2181,7 @@ void cmLocalGenerator::AppendPositionIndependentLinkerFlags( } std::vector<std::string> flagsList; - cmSystemTools::ExpandListArgument(pieFlags, flagsList); + cmExpandList(pieFlags, flagsList); for (const auto& flag : flagsList) { this->AppendFlagEscape(flags, flag); } @@ -2244,7 +2198,7 @@ void cmLocalGenerator::AppendCompileOptions(std::string& options, // Expand the list of options. std::vector<std::string> options_vec; - cmSystemTools::ExpandListArgument(options_list, options_vec); + cmExpandList(options_list, options_vec); this->AppendCompileOptions(options, options_vec, regex); } @@ -2279,7 +2233,7 @@ void cmLocalGenerator::AppendIncludeDirectories( // Expand the list of includes. std::vector<std::string> includes_vec; - cmSystemTools::ExpandListArgument(includes_list, includes_vec); + cmExpandList(includes_list, includes_vec); this->AppendIncludeDirectories(includes, includes_vec, sourceFile); } @@ -2304,7 +2258,7 @@ void cmLocalGenerator::AppendIncludeDirectories( std::string inc = include; - if (!cmSystemTools::IsOff(inc)) { + if (!cmIsOff(inc)) { cmSystemTools::ConvertToUnixSlashes(inc); } @@ -2356,10 +2310,8 @@ void cmLocalGenerator::JoinDefines(const std::set<std::string>& defines, // Lookup the define flag for the current language. std::string dflag = "-D"; if (!lang.empty()) { - std::string defineFlagVar = "CMAKE_"; - defineFlagVar += lang; - defineFlagVar += "_DEFINE_FLAG"; - const char* df = this->Makefile->GetDefinition(defineFlagVar); + const char* df = + this->Makefile->GetDefinition(cmStrCat("CMAKE_", lang, "_DEFINE_FLAG")); if (df && *df) { dflag = df; } @@ -2405,13 +2357,11 @@ void cmLocalGenerator::AppendFeatureOptions(std::string& flags, const std::string& lang, const char* feature) { - std::string optVar = "CMAKE_"; - optVar += lang; - optVar += "_COMPILE_OPTIONS_"; - optVar += feature; - if (const char* optionList = this->Makefile->GetDefinition(optVar)) { + const char* optionList = this->Makefile->GetDefinition( + cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_", feature)); + if (optionList != nullptr) { std::vector<std::string> options; - cmSystemTools::ExpandListArgument(optionList, options); + cmExpandList(optionList, options); for (std::string const& o : options) { this->AppendFlagEscape(flags, o); } @@ -2566,8 +2516,8 @@ static bool cmLocalGeneratorShortenObjectName(std::string& objName, objName.find('/', objName.size() - max_len + 32); if (pos != std::string::npos) { cmCryptoHash md5(cmCryptoHash::AlgoMD5); - std::string md5name = md5.HashString(objName.substr(0, pos)); - md5name += objName.substr(pos); + std::string md5name = cmStrCat(md5.HashString(objName.substr(0, pos)), + cm::string_view(objName).substr(pos)); objName = md5name; // The object name is now short enough. @@ -2762,10 +2712,8 @@ std::string cmLocalGenerator::GetObjectFileNameWithoutTarget( if (!replaceExt) { std::string lang = source.GetLanguage(); if (!lang.empty()) { - std::string repVar = "CMAKE_"; - repVar += lang; - repVar += "_OUTPUT_EXTENSION_REPLACE"; - replaceExt = this->Makefile->IsOn(repVar); + replaceExt = this->Makefile->IsOn( + cmStrCat("CMAKE_", lang, "_OUTPUT_EXTENSION_REPLACE")); } } diff --git a/Source/cmLocalGenerator.h b/Source/cmLocalGenerator.h index f0c6806..455e491 100644 --- a/Source/cmLocalGenerator.h +++ b/Source/cmLocalGenerator.h @@ -461,7 +461,7 @@ private: void ComputeObjectMaxPath(); }; -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) bool cmLocalGeneratorCheckObjectName(std::string& objName, std::string::size_type dir_len, std::string::size_type max_total_len); diff --git a/Source/cmLocalGhsMultiGenerator.cxx b/Source/cmLocalGhsMultiGenerator.cxx index bf25f98..b00dda1 100644 --- a/Source/cmLocalGhsMultiGenerator.cxx +++ b/Source/cmLocalGhsMultiGenerator.cxx @@ -7,6 +7,7 @@ #include "cmGlobalGenerator.h" #include "cmSourceFile.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include <algorithm> @@ -23,9 +24,7 @@ cmLocalGhsMultiGenerator::~cmLocalGhsMultiGenerator() = default; std::string cmLocalGhsMultiGenerator::GetTargetDirectory( cmGeneratorTarget const* target) const { - std::string dir; - dir += target->GetName(); - dir += ".dir"; + std::string dir = cmStrCat(target->GetName(), ".dir"); return dir; } @@ -63,11 +62,8 @@ void cmLocalGhsMultiGenerator::ComputeObjectFilenames( std::map<cmSourceFile const*, std::string>& mapping, cmGeneratorTarget const* gt) { - std::string dir_max; - dir_max += this->GetCurrentBinaryDirectory(); - dir_max += "/"; - dir_max += this->GetTargetDirectory(gt); - dir_max += "/"; + std::string dir_max = cmStrCat(this->GetCurrentBinaryDirectory(), '/', + this->GetTargetDirectory(gt), '/'); // Count the number of object files with each name. Note that // filesystem may not be case sensitive. @@ -75,9 +71,10 @@ void cmLocalGhsMultiGenerator::ComputeObjectFilenames( for (auto const& si : mapping) { cmSourceFile const* sf = si.first; - std::string objectNameLower = cmSystemTools::LowerCase( - cmSystemTools::GetFilenameWithoutLastExtension(sf->GetFullPath())); - objectNameLower += this->GlobalGenerator->GetLanguageOutputExtension(*sf); + std::string objectNameLower = cmStrCat( + cmSystemTools::LowerCase( + cmSystemTools::GetFilenameWithoutLastExtension(sf->GetFullPath())), + this->GlobalGenerator->GetLanguageOutputExtension(*sf)); counts[objectNameLower] += 1; } @@ -85,9 +82,9 @@ void cmLocalGhsMultiGenerator::ComputeObjectFilenames( // object name computation. for (auto& si : mapping) { cmSourceFile const* sf = si.first; - std::string objectName = - cmSystemTools::GetFilenameWithoutLastExtension(sf->GetFullPath()); - objectName += this->GlobalGenerator->GetLanguageOutputExtension(*sf); + std::string objectName = cmStrCat( + cmSystemTools::GetFilenameWithoutLastExtension(sf->GetFullPath()), + this->GlobalGenerator->GetLanguageOutputExtension(*sf)); if (counts[cmSystemTools::LowerCase(objectName)] > 1) { const_cast<cmGeneratorTarget*>(gt)->AddExplicitObjectName(sf); diff --git a/Source/cmLocalNinjaGenerator.cxx b/Source/cmLocalNinjaGenerator.cxx index 248f4a6..1be219c 100644 --- a/Source/cmLocalNinjaGenerator.cxx +++ b/Source/cmLocalNinjaGenerator.cxx @@ -25,6 +25,7 @@ #include "cmSourceFile.h" #include "cmState.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmake.h" #include "cmsys/FStream.hxx" @@ -102,8 +103,7 @@ void cmLocalNinjaGenerator::Generate() std::string cmLocalNinjaGenerator::GetTargetDirectory( cmGeneratorTarget const* target) const { - std::string dir = "CMakeFiles/"; - dir += target->GetName(); + std::string dir = cmStrCat("CMakeFiles/", target->GetName()); #if defined(__VMS) dir += "_dir"; #else @@ -222,7 +222,7 @@ void cmLocalNinjaGenerator::WritePools(std::ostream& os) cmGlobalNinjaGenerator::WriteComment( os, "Pools defined by global property JOB_POOLS"); std::vector<std::string> pools; - cmSystemTools::ExpandListArgument(jobpools, pools); + cmExpandList(jobpools, pools); for (std::string const& pool : pools) { const std::string::size_type eq = pool.find('='); unsigned int jobs; @@ -300,8 +300,7 @@ std::string cmLocalNinjaGenerator::WriteCommandScript( if (target) { scriptPath = target->GetSupportDirectory(); } else { - scriptPath = this->GetCurrentBinaryDirectory(); - scriptPath += "/CMakeFiles"; + scriptPath = cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles"); } cmSystemTools::MakeDirectory(scriptPath); scriptPath += '/'; @@ -555,7 +554,8 @@ void cmLocalNinjaGenerator::WriteCustomCommandBuildStatements() ++j; for (; j != i->second.end(); ++j) { - std::vector<std::string> jDeps, depsIntersection; + std::vector<std::string> jDeps; + std::vector<std::string> depsIntersection; this->GetGlobalNinjaGenerator()->AppendTargetDependsClosure(*j, jDeps); std::sort(jDeps.begin(), jDeps.end()); std::set_intersection(ccTargetDeps.begin(), ccTargetDeps.end(), @@ -613,7 +613,7 @@ void cmLocalNinjaGenerator::AdditionalCleanFiles() { cmGeneratorExpression ge; auto cge = ge.Parse(prop_value); - cmSystemTools::ExpandListArgument( + cmExpandList( cge->Evaluate(this, this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE")), cleanFiles); diff --git a/Source/cmLocalUnixMakefileGenerator3.cxx b/Source/cmLocalUnixMakefileGenerator3.cxx index 713c985..c301b1a 100644 --- a/Source/cmLocalUnixMakefileGenerator3.cxx +++ b/Source/cmLocalUnixMakefileGenerator3.cxx @@ -40,7 +40,7 @@ // Include dependency scanners for supported languages. Only the // C/C++ scanner is needed for bootstrapping CMake. #include "cmDependsC.h" -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP # include "cmDependsFortran.h" # include "cmDependsJava.h" #endif @@ -164,11 +164,8 @@ void cmLocalUnixMakefileGenerator3::GetLocalObjectFiles( gt->GetObjectSources( objectSources, this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE")); // Compute full path to object file directory for this target. - std::string dir; - dir += gt->LocalGenerator->GetCurrentBinaryDirectory(); - dir += "/"; - dir += this->GetTargetDirectory(gt); - dir += "/"; + std::string dir = cmStrCat(gt->LocalGenerator->GetCurrentBinaryDirectory(), + '/', this->GetTargetDirectory(gt), '/'); // Compute the name of each object file. for (cmSourceFile const* sf : objectSources) { bool hasSourceExtension = true; @@ -365,14 +362,12 @@ void cmLocalUnixMakefileGenerator3::WriteLocalMakefileTargets( emitted.insert(target->GetName()); // for subdirs add a rule to build this specific target by name. - localName = this->GetRelativeTargetDirectory(target); - localName += "/rule"; + localName = cmStrCat(this->GetRelativeTargetDirectory(target), "/rule"); commands.clear(); depends.clear(); // Build the target for this pass. - std::string makefile2 = "CMakeFiles/"; - makefile2 += "Makefile2"; + std::string makefile2 = "CMakeFiles/Makefile2"; commands.push_back(this->GetRecursiveMakeCall(makefile2, localName)); this->CreateCDCommand(commands, this->GetBinaryDirectory(), this->GetCurrentBinaryDirectory()); @@ -388,13 +383,12 @@ void cmLocalUnixMakefileGenerator3::WriteLocalMakefileTargets( } // Add a fast rule to build the target - std::string makefileName = this->GetRelativeTargetDirectory(target); - makefileName += "/build.make"; + std::string makefileName = + cmStrCat(this->GetRelativeTargetDirectory(target), "/build.make"); // make sure the makefile name is suitable for a makefile - std::string makeTargetName = this->GetRelativeTargetDirectory(target); - makeTargetName += "/build"; - localName = target->GetName(); - localName += "/fast"; + std::string makeTargetName = + cmStrCat(this->GetRelativeTargetDirectory(target), "/build"); + localName = cmStrCat(target->GetName(), "/fast"); depends.clear(); commands.clear(); commands.push_back( @@ -407,10 +401,9 @@ void cmLocalUnixMakefileGenerator3::WriteLocalMakefileTargets( // Add a local name for the rule to relink the target before // installation. if (target->NeedRelinkBeforeInstall(this->ConfigName)) { - makeTargetName = this->GetRelativeTargetDirectory(target); - makeTargetName += "/preinstall"; - localName = target->GetName(); - localName += "/preinstall"; + makeTargetName = + cmStrCat(this->GetRelativeTargetDirectory(target), "/preinstall"); + localName = cmStrCat(target->GetName(), "/preinstall"); depends.clear(); commands.clear(); commands.push_back( @@ -427,9 +420,9 @@ void cmLocalUnixMakefileGenerator3::WriteLocalMakefileTargets( void cmLocalUnixMakefileGenerator3::WriteDirectoryInformationFile() { - std::string infoFileName = this->GetCurrentBinaryDirectory(); - infoFileName += "/CMakeFiles"; - infoFileName += "/CMakeDirectoryInformation.cmake"; + std::string infoFileName = + cmStrCat(this->GetCurrentBinaryDirectory(), + "/CMakeFiles/CMakeDirectoryInformation.cmake"); // Open the output file. cmGeneratedFileStream infoFileStream(infoFileName); @@ -485,9 +478,8 @@ void cmLocalUnixMakefileGenerator3::WriteDirectoryInformationFile() std::string cmLocalUnixMakefileGenerator3::ConvertToFullPath( const std::string& localPath) { - std::string dir = this->GetCurrentBinaryDirectory(); - dir += "/"; - dir += localPath; + std::string dir = + cmStrCat(this->GetCurrentBinaryDirectory(), '/', localPath); return dir; } @@ -768,19 +760,18 @@ void cmLocalUnixMakefileGenerator3::WriteSpecialTargetsBottom( std::vector<std::string> commands; cmake* cm = this->GlobalGenerator->GetCMakeInstance(); if (cm->DoWriteGlobVerifyTarget()) { - std::string rescanRule = "$(CMAKE_COMMAND) -P "; - rescanRule += this->ConvertToOutputFormat(cm->GetGlobVerifyScript(), - cmOutputConverter::SHELL); + std::string rescanRule = + cmStrCat("$(CMAKE_COMMAND) -P ", + this->ConvertToOutputFormat(cm->GetGlobVerifyScript(), + cmOutputConverter::SHELL)); commands.push_back(rescanRule); } - std::string cmakefileName = "CMakeFiles/"; - cmakefileName += "Makefile.cmake"; - std::string runRule = - "$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)"; - runRule += " --check-build-system "; - runRule += - this->ConvertToOutputFormat(cmakefileName, cmOutputConverter::SHELL); - runRule += " 0"; + std::string cmakefileName = "CMakeFiles/Makefile.cmake"; + std::string runRule = cmStrCat( + "$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) " + "--check-build-system ", + this->ConvertToOutputFormat(cmakefileName, cmOutputConverter::SHELL), + " 0"); std::vector<std::string> no_depends; commands.push_back(std::move(runRule)); @@ -821,8 +812,8 @@ void cmLocalUnixMakefileGenerator3::WriteConvenienceRule( std::string cmLocalUnixMakefileGenerator3::GetRelativeTargetDirectory( cmGeneratorTarget* target) { - std::string dir = this->HomeRelativeOutputPath; - dir += this->GetTargetDirectory(target); + std::string dir = + cmStrCat(this->HomeRelativeOutputPath, this->GetTargetDirectory(target)); return dir; } @@ -853,7 +844,7 @@ void cmLocalUnixMakefileGenerator3::AppendRuleDepend( // it is specifically enabled by the user or project. const char* nodep = this->Makefile->GetDefinition("CMAKE_SKIP_RULE_DEPENDENCY"); - if (!nodep || cmSystemTools::IsOff(nodep)) { + if (!nodep || cmIsOff(nodep)) { depends.emplace_back(ruleFileName); } } @@ -963,7 +954,7 @@ void cmLocalUnixMakefileGenerator3::AppendCustomCommand( // This command was specified as a path to a file in the // current directory. Add a leading "./" so it can run // without the current directory being in the search path. - cmd = "./" + cmd; + cmd = cmStrCat("./", cmd); } std::string launcher; @@ -1017,18 +1008,16 @@ void cmLocalUnixMakefileGenerator3::AppendCustomCommand( std::string::size_type rcurly = cmd.find('}'); if (rcurly == std::string::npos || rcurly > lcurly) { // The first curly is a left curly. Use the hack. - std::string hack_cmd = cmd.substr(0, lcurly); - hack_cmd += "{{}"; - hack_cmd += cmd.substr(lcurly + 1); - cmd = hack_cmd; + cmd = + cmStrCat(cmd.substr(0, lcurly), "{{}", cmd.substr(lcurly + 1)); } } } if (launcher.empty()) { if (useCall) { - cmd = "call " + cmd; + cmd = cmStrCat("call ", cmd); } else if (this->IsNMake() && cmd[0] == '"') { - cmd = "echo >nul && " + cmd; + cmd = cmStrCat("echo >nul && ", cmd); } } commands1.push_back(std::move(cmd)); @@ -1047,10 +1036,8 @@ void cmLocalUnixMakefileGenerator3::AppendCleanCommand( cmGeneratorTarget* target, const char* filename) { std::string currentBinDir = this->GetCurrentBinaryDirectory(); - std::string cleanfile = currentBinDir; - cleanfile += "/"; - cleanfile += this->GetTargetDirectory(target); - cleanfile += "/cmake_clean"; + std::string cleanfile = cmStrCat( + currentBinDir, '/', this->GetTargetDirectory(target), "/cmake_clean"); if (filename) { cleanfile += "_"; cleanfile += filename; @@ -1070,11 +1057,12 @@ void cmLocalUnixMakefileGenerator3::AppendCleanCommand( fout << ")\n"; } { - std::string remove = "$(CMAKE_COMMAND) -P "; - remove += this->ConvertToOutputFormat( - this->MaybeConvertToRelativePath(this->GetCurrentBinaryDirectory(), - cleanfile), - cmOutputConverter::SHELL); + std::string remove = + cmStrCat("$(CMAKE_COMMAND) -P ", + this->ConvertToOutputFormat( + this->MaybeConvertToRelativePath( + this->GetCurrentBinaryDirectory(), cleanfile), + cmOutputConverter::SHELL)); commands.push_back(std::move(remove)); } @@ -1104,7 +1092,7 @@ void cmLocalUnixMakefileGenerator3::AppendDirectoryCleanCommand( this->Makefile->GetProperty("ADDITIONAL_CLEAN_FILES")) { cmGeneratorExpression ge; std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(prop_value); - cmSystemTools::ExpandListArgument( + cmExpandList( cge->Evaluate(this, this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE")), cleanFiles); @@ -1117,8 +1105,8 @@ void cmLocalUnixMakefileGenerator3::AppendDirectoryCleanCommand( this->GetGlobalGenerator()->GetLocalGenerators().at(0); std::string const& binaryDir = rootLG->GetCurrentBinaryDirectory(); std::string const& currentBinaryDir = this->GetCurrentBinaryDirectory(); - std::string cleanfile = currentBinaryDir; - cleanfile += "/CMakeFiles/cmake_directory_clean.cmake"; + std::string cleanfile = + cmStrCat(currentBinaryDir, "/CMakeFiles/cmake_directory_clean.cmake"); // Write clean script { std::string cleanfilePath = cmSystemTools::CollapseFullPath(cleanfile); @@ -1137,10 +1125,11 @@ void cmLocalUnixMakefileGenerator3::AppendDirectoryCleanCommand( } // Create command { - std::string remove = "$(CMAKE_COMMAND) -P "; - remove += this->ConvertToOutputFormat( - rootLG->MaybeConvertToRelativePath(binaryDir, cleanfile), - cmOutputConverter::SHELL); + std::string remove = + cmStrCat("$(CMAKE_COMMAND) -P ", + this->ConvertToOutputFormat( + rootLG->MaybeConvertToRelativePath(binaryDir, cleanfile), + cmOutputConverter::SHELL)); commands.push_back(std::move(remove)); } } @@ -1186,12 +1175,12 @@ void cmLocalUnixMakefileGenerator3::AppendEcho( std::string cmd; if (color_name.empty() && !progress) { // Use the native echo command. - cmd = "@echo "; - cmd += this->EscapeForShell(line, false, true); + cmd = cmStrCat("@echo ", this->EscapeForShell(line, false, true)); } else { // Use cmake to echo the text in color. - cmd = "@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) "; - cmd += color_name; + cmd = cmStrCat( + "@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) ", + color_name); if (progress) { cmd += "--progress-dir="; cmd += this->ConvertToOutputFormat( @@ -1227,8 +1216,7 @@ void cmLocalUnixMakefileGenerator3::AppendEcho( std::string cmLocalUnixMakefileGenerator3::CreateMakeVariable( std::string const& s, std::string const& s2) { - std::string unmodified = s; - unmodified += s2; + std::string unmodified = cmStrCat(s, s2); // if there is no restriction on the length of make variables // and there are no "." characters in the string, then return the // unmodified combination. @@ -1346,9 +1334,9 @@ bool cmLocalUnixMakefileGenerator3::UpdateDependencies( // may have changed. In this case discard all old dependencies. bool needRescanDirInfo = false; { - std::string dirInfoFile = this->GetCurrentBinaryDirectory(); - dirInfoFile += "/CMakeFiles"; - dirInfoFile += "/CMakeDirectoryInformation.cmake"; + std::string dirInfoFile = + cmStrCat(this->GetCurrentBinaryDirectory(), + "/CMakeFiles/CMakeDirectoryInformation.cmake"); int result; if (!ftc->Compare(internalDependFile, dirInfoFile, &result) || result < 0) { @@ -1390,8 +1378,8 @@ bool cmLocalUnixMakefileGenerator3::UpdateDependencies( // The dependencies must be regenerated. std::string targetName = cmSystemTools::GetFilenameName(targetDir); targetName = targetName.substr(0, targetName.length() - 4); - std::string message = "Scanning dependencies of target "; - message += targetName; + std::string message = + cmStrCat("Scanning dependencies of target ", targetName); cmSystemTools::MakefileColorEcho(cmsysTerminal_Color_ForegroundMagenta | cmsysTerminal_Color_ForegroundBold, message.c_str(), true, color); @@ -1412,9 +1400,9 @@ bool cmLocalUnixMakefileGenerator3::ScanDependencies( cmMakefile* mf = this->Makefile; bool haveDirectoryInfo = false; { - std::string dirInfoFile = this->GetCurrentBinaryDirectory(); - dirInfoFile += "/CMakeFiles"; - dirInfoFile += "/CMakeDirectoryInformation.cmake"; + std::string dirInfoFile = + cmStrCat(this->GetCurrentBinaryDirectory(), + "/CMakeFiles/CMakeDirectoryInformation.cmake"); if (mf->ReadListFile(dirInfoFile) && !cmSystemTools::GetErrorOccuredFlag()) { haveDirectoryInfo = true; @@ -1425,7 +1413,7 @@ bool cmLocalUnixMakefileGenerator3::ScanDependencies( if (haveDirectoryInfo) { // Test whether we need to force Unix paths. if (const char* force = mf->GetDefinition("CMAKE_FORCE_UNIX_PATHS")) { - if (!cmSystemTools::IsOff(force)) { + if (!cmIsOff(force)) { cmSystemTools::SetForceUnixPaths(true); } } @@ -1468,8 +1456,7 @@ bool cmLocalUnixMakefileGenerator3::ScanDependencies( // for each language we need to scan, scan it std::vector<std::string> langs; - cmSystemTools::ExpandListArgument( - mf->GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES"), langs); + cmExpandList(mf->GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES"), langs); for (std::string const& lang : langs) { // construct the checker // Create the scanner for this language @@ -1479,7 +1466,7 @@ bool cmLocalUnixMakefileGenerator3::ScanDependencies( // TODO: Handle RC (resource files) dependencies correctly. scanner = cm::make_unique<cmDependsC>(this, targetDir, lang, &validDeps); } -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP else if (lang == "Fortran") { ruleFileStream << "# Note that incremental build could trigger " << "a call to cmake_copy_f90_mod on each re-build\n"; @@ -1514,7 +1501,7 @@ void cmLocalUnixMakefileGenerator3::CheckMultipleOutputs(bool verbose) // Convert the string to a list and preserve empty entries. std::vector<std::string> pairs; - cmSystemTools::ExpandListArgument(pairs_string, pairs, true); + cmExpandList(pairs_string, pairs, true); for (std::vector<std::string>::const_iterator i = pairs.begin(); i != pairs.end() && (i + 1) != pairs.end();) { const std::string& depender = *i++; @@ -1627,8 +1614,8 @@ void cmLocalUnixMakefileGenerator3::WriteLocalAllRules( std::vector<std::string> commands; // Write the all rule. - std::string recursiveTarget = this->GetCurrentBinaryDirectory(); - recursiveTarget += "/all"; + std::string recursiveTarget = + cmStrCat(this->GetCurrentBinaryDirectory(), "/all"); bool regenerate = !this->GlobalGenerator->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION"); @@ -1636,16 +1623,15 @@ void cmLocalUnixMakefileGenerator3::WriteLocalAllRules( depends.emplace_back("cmake_check_build_system"); } - std::string progressDir = this->GetBinaryDirectory(); - progressDir += "/CMakeFiles"; + std::string progressDir = + cmStrCat(this->GetBinaryDirectory(), "/CMakeFiles"); { std::ostringstream progCmd; progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start "; progCmd << this->ConvertToOutputFormat( cmSystemTools::CollapseFullPath(progressDir), cmOutputConverter::SHELL); - std::string progressFile = "/CMakeFiles"; - progressFile += "/progress.marks"; + std::string progressFile = "/CMakeFiles/progress.marks"; std::string progressFileNameFull = this->ConvertToFullPath(progressFile); progCmd << " " << this->ConvertToOutputFormat( @@ -1653,8 +1639,7 @@ void cmLocalUnixMakefileGenerator3::WriteLocalAllRules( cmOutputConverter::SHELL); commands.push_back(progCmd.str()); } - std::string mf2Dir = "CMakeFiles/"; - mf2Dir += "Makefile2"; + std::string mf2Dir = "CMakeFiles/Makefile2"; commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget)); this->CreateCDCommand(commands, this->GetBinaryDirectory(), this->GetCurrentBinaryDirectory()); @@ -1670,8 +1655,7 @@ void cmLocalUnixMakefileGenerator3::WriteLocalAllRules( commands, true); // Write the clean rule. - recursiveTarget = this->GetCurrentBinaryDirectory(); - recursiveTarget += "/clean"; + recursiveTarget = cmStrCat(this->GetCurrentBinaryDirectory(), "/clean"); commands.clear(); depends.clear(); commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget)); @@ -1686,13 +1670,12 @@ void cmLocalUnixMakefileGenerator3::WriteLocalAllRules( depends, commands, true); // Write the preinstall rule. - recursiveTarget = this->GetCurrentBinaryDirectory(); - recursiveTarget += "/preinstall"; + recursiveTarget = cmStrCat(this->GetCurrentBinaryDirectory(), "/preinstall"); commands.clear(); depends.clear(); const char* noall = this->Makefile->GetDefinition("CMAKE_SKIP_INSTALL_ALL_DEPENDENCY"); - if (!noall || cmSystemTools::IsOff(noall)) { + if (!noall || cmIsOff(noall)) { // Drive the build before installing. depends.emplace_back("all"); } else if (regenerate) { @@ -1714,20 +1697,19 @@ void cmLocalUnixMakefileGenerator3::WriteLocalAllRules( commands.clear(); cmake* cm = this->GlobalGenerator->GetCMakeInstance(); if (cm->DoWriteGlobVerifyTarget()) { - std::string rescanRule = "$(CMAKE_COMMAND) -P "; - rescanRule += this->ConvertToOutputFormat(cm->GetGlobVerifyScript(), - cmOutputConverter::SHELL); + std::string rescanRule = + cmStrCat("$(CMAKE_COMMAND) -P ", + this->ConvertToOutputFormat(cm->GetGlobVerifyScript(), + cmOutputConverter::SHELL)); commands.push_back(rescanRule); } - std::string cmakefileName = "CMakeFiles/"; - cmakefileName += "Makefile.cmake"; + std::string cmakefileName = "CMakeFiles/Makefile.cmake"; { - std::string runRule = - "$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)"; - runRule += " --check-build-system "; - runRule += - this->ConvertToOutputFormat(cmakefileName, cmOutputConverter::SHELL); - runRule += " 1"; + std::string runRule = cmStrCat( + "$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) " + "--check-build-system ", + this->ConvertToOutputFormat(cmakefileName, cmOutputConverter::SHELL), + " 1"); commands.push_back(std::move(runRule)); } this->CreateCDCommand(commands, this->GetBinaryDirectory(), @@ -1746,7 +1728,7 @@ void cmLocalUnixMakefileGenerator3::ClearDependencies(cmMakefile* mf, return; } std::vector<std::string> files; - cmSystemTools::ExpandListArgument(infoDef, files); + cmExpandList(infoDef, files); // Each depend information file corresponds to a target. Clear the // dependencies for that target. @@ -1848,9 +1830,8 @@ void cmLocalUnixMakefileGenerator3::WriteDependLanguageInfo( cmakefileStream << " )\n"; // Tell the dependency scanner what compiler is used. - std::string cidVar = "CMAKE_"; - cidVar += implicitLang.first; - cidVar += "_COMPILER_ID"; + std::string cidVar = + cmStrCat("CMAKE_", implicitLang.first, "_COMPILER_ID"); const char* cid = this->Makefile->GetDefinition(cidVar); if (cid && *cid) { cmakefileStream << "set(CMAKE_" << implicitLang.first @@ -1914,11 +1895,11 @@ void cmLocalUnixMakefileGenerator3::WriteDependLanguageInfo( std::vector<std::string> transformRules; if (const char* xform = this->Makefile->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM")) { - cmSystemTools::ExpandListArgument(xform, transformRules); + cmExpandList(xform, transformRules); } if (const char* xform = target->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM")) { - cmSystemTools::ExpandListArgument(xform, transformRules); + cmExpandList(xform, transformRules); } if (!transformRules.empty()) { cmakefileStream << "set(CMAKE_INCLUDE_TRANSFORMS\n"; @@ -1941,10 +1922,9 @@ std::string cmLocalUnixMakefileGenerator3::GetRecursiveMakeCall( const std::string& makefile, const std::string& tgt) { // Call make on the given file. - std::string cmd; - cmd += "$(MAKE) -f "; - cmd += this->ConvertToOutputFormat(makefile, cmOutputConverter::SHELL); - cmd += " "; + std::string cmd = cmStrCat( + "$(MAKE) -f ", + this->ConvertToOutputFormat(makefile, cmOutputConverter::SHELL), ' '); cmGlobalUnixMakefileGenerator3* gg = static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator); @@ -2075,8 +2055,7 @@ std::string cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath( std::string cmLocalUnixMakefileGenerator3::GetTargetDirectory( cmGeneratorTarget const* target) const { - std::string dir = "CMakeFiles/"; - dir += target->GetName(); + std::string dir = cmStrCat("CMakeFiles/", target->GetName()); #if defined(__VMS) dir += "_dir"; #else @@ -2119,13 +2098,12 @@ void cmLocalUnixMakefileGenerator3::CreateCDCommand( // On Windows we must perform each step separately and then change // back because the shell keeps the working directory between // commands. - std::string cmd = cd_cmd; - cmd += this->ConvertToOutputForExisting(tgtDir); + std::string cmd = + cmStrCat(cd_cmd, this->ConvertToOutputForExisting(tgtDir)); commands.insert(commands.begin(), cmd); // Change back to the starting directory. - cmd = cd_cmd; - cmd += this->ConvertToOutputForExisting(relDir); + cmd = cmStrCat(cd_cmd, this->ConvertToOutputForExisting(relDir)); commands.push_back(std::move(cmd)); } else { // On UNIX we must construct a single shell command to change diff --git a/Source/cmLocalVisualStudio10Generator.cxx b/Source/cmLocalVisualStudio10Generator.cxx index d45c335..6d7b359 100644 --- a/Source/cmLocalVisualStudio10Generator.cxx +++ b/Source/cmLocalVisualStudio10Generator.cxx @@ -121,8 +121,7 @@ void cmLocalVisualStudio10Generator::ReadAndStoreExternalGUID( return; } - std::string guidStoreName = name; - guidStoreName += "_GUID_CMAKE"; + std::string guidStoreName = cmStrCat(name, "_GUID_CMAKE"); // save the GUID in the cache this->GlobalGenerator->GetCMakeInstance()->AddCacheEntry( guidStoreName.c_str(), parser.GUID.c_str(), "Stored GUID", diff --git a/Source/cmLocalVisualStudio7Generator.cxx b/Source/cmLocalVisualStudio7Generator.cxx index 8154f3e..bbee705 100644 --- a/Source/cmLocalVisualStudio7Generator.cxx +++ b/Source/cmLocalVisualStudio7Generator.cxx @@ -97,11 +97,8 @@ void cmLocalVisualStudio7Generator::FixGlobalTargets() cmCustomCommandLines force_commands; force_commands.push_back(force_command); std::string no_main_dependency; - std::string force = this->GetCurrentBinaryDirectory(); - force += "/CMakeFiles"; - force += "/"; - force += l->GetName(); - force += "_force"; + std::string force = cmStrCat(this->GetCurrentBinaryDirectory(), + "/CMakeFiles/", l->GetName(), "_force"); if (cmSourceFile* file = this->Makefile->AddCustomCommandToOutput( force.c_str(), no_depends, no_main_dependency, force_commands, " ", 0, true)) { @@ -144,11 +141,10 @@ void cmLocalVisualStudio7Generator::WriteStampFiles() { // Touch a timestamp file used to determine when the project file is // out of date. - std::string stampName = this->GetCurrentBinaryDirectory(); - stampName += "/CMakeFiles"; + std::string stampName = + cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles"); cmSystemTools::MakeDirectory(stampName.c_str()); - stampName += "/"; - stampName += "generate.stamp"; + stampName += "/generate.stamp"; cmsys::ofstream stamp(stampName.c_str()); stamp << "# CMake generation timestamp file for this directory.\n"; @@ -158,8 +154,7 @@ void cmLocalVisualStudio7Generator::WriteStampFiles() // dependencies. If any file listed in it is newer than itself then // CMake must rerun. Otherwise the project files are up to date and // the stamp file can just be touched. - std::string depName = stampName; - depName += ".depend"; + std::string depName = cmStrCat(stampName, ".depend"); cmsys::ofstream depFile(depName.c_str()); depFile << "# CMake generation dependency list for this directory.\n"; @@ -199,9 +194,7 @@ void cmLocalVisualStudio7Generator::CreateSingleVCProj( target->Target->SetProperty("GENERATOR_FILE_NAME", lname.c_str()); // create the dsp.cmake file std::string fname; - fname = this->GetCurrentBinaryDirectory(); - fname += "/"; - fname += lname; + fname = cmStrCat(this->GetCurrentBinaryDirectory(), '/', lname); if (this->FortranProject) { fname += ".vfproj"; } else { @@ -228,9 +221,8 @@ cmSourceFile* cmLocalVisualStudio7Generator::CreateVCProjBuildRule() return nullptr; } - std::string makefileIn = this->GetCurrentSourceDirectory(); - makefileIn += "/"; - makefileIn += "CMakeLists.txt"; + std::string makefileIn = + cmStrCat(this->GetCurrentSourceDirectory(), "/CMakeLists.txt"); makefileIn = cmSystemTools::CollapseFullPath(makefileIn); if (cmSourceFile* file = this->Makefile->GetSource(makefileIn)) { if (file->GetCustomCommand()) { @@ -253,20 +245,15 @@ cmSourceFile* cmLocalVisualStudio7Generator::CreateVCProjBuildRule() std::unique(listFiles.begin(), listFiles.end()); listFiles.erase(new_end, listFiles.end()); - std::string stampName = this->GetCurrentBinaryDirectory(); - stampName += "/"; - stampName += "CMakeFiles/"; - stampName += "generate.stamp"; + std::string stampName = + cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles/generate.stamp"); cmCustomCommandLine commandLine; commandLine.push_back(cmSystemTools::GetCMakeCommand()); - std::string comment = "Building Custom Rule "; - comment += makefileIn; + std::string comment = cmStrCat("Building Custom Rule ", makefileIn); std::string args; - args = "-S"; - args += this->GetSourceDirectory(); + args = cmStrCat("-S", this->GetSourceDirectory()); commandLine.push_back(args); - args = "-B"; - args += this->GetBinaryDirectory(); + args = cmStrCat("-B", this->GetBinaryDirectory()); commandLine.push_back(args); commandLine.push_back("--check-stamp-file"); commandLine.push_back(stampName); @@ -721,9 +708,7 @@ void cmLocalVisualStudio7Generator::WriteConfiguration( this->Makefile->IsOn("CMAKE_VERBOSE_MAKEFILE")); // Add a definition for the configuration name. - std::string configDefine = "CMAKE_INTDIR=\""; - configDefine += configName; - configDefine += "\""; + std::string configDefine = cmStrCat("CMAKE_INTDIR=\"", configName, '"'); targetOptions.AddDefine(configDefine); // Add the export symbol definition for shared library objects. @@ -733,9 +718,8 @@ void cmLocalVisualStudio7Generator::WriteConfiguration( // The intermediate directory name consists of a directory for the // target and a subdirectory for the configuration name. - std::string intermediateDir = this->GetTargetDirectory(target); - intermediateDir += "/"; - intermediateDir += configName; + std::string intermediateDir = + cmStrCat(this->GetTargetDirectory(target), '/', configName); if (target->GetType() < cmStateEnums::UTILITY) { std::string const& outDir = @@ -956,8 +940,7 @@ void cmLocalVisualStudio7Generator::OutputBuildTool( extraLinkOptions += targetLinkFlags; } std::string configTypeUpper = cmSystemTools::UpperCase(configName); - std::string linkFlagsConfig = "LINK_FLAGS_"; - linkFlagsConfig += configTypeUpper; + std::string linkFlagsConfig = cmStrCat("LINK_FLAGS_", configTypeUpper); targetLinkFlags = target->GetProperty(linkFlagsConfig.c_str()); if (targetLinkFlags) { extraLinkOptions += " "; @@ -989,12 +972,9 @@ void cmLocalVisualStudio7Generator::OutputBuildTool( case cmStateEnums::UNKNOWN_LIBRARY: break; case cmStateEnums::OBJECT_LIBRARY: { - std::string libpath = this->GetTargetDirectory(target); - libpath += "/"; - libpath += configName; - libpath += "/"; - libpath += target->GetName(); - libpath += ".lib"; + std::string libpath = + cmStrCat(this->GetTargetDirectory(target), '/', configName, '/', + target->GetName(), ".lib"); const char* tool = this->FortranProject ? "VFLibrarianTool" : "VCLibrarianTool"; fout << "\t\t\t<Tool\n" @@ -1005,9 +985,8 @@ void cmLocalVisualStudio7Generator::OutputBuildTool( } case cmStateEnums::STATIC_LIBRARY: { std::string targetNameFull = target->GetFullName(configName); - std::string libpath = target->GetDirectory(configName); - libpath += "/"; - libpath += targetNameFull; + std::string libpath = + cmStrCat(target->GetDirectory(configName), '/', targetNameFull); const char* tool = "VCLibrarianTool"; if (this->FortranProject) { tool = "VFLibrarianTool"; @@ -1049,9 +1028,8 @@ void cmLocalVisualStudio7Generator::OutputBuildTool( // Compute the variable name to lookup standard libraries for this // language. - std::string standardLibsVar = "CMAKE_"; - standardLibsVar += linkLanguage; - standardLibsVar += "_STANDARD_LIBRARIES"; + std::string standardLibsVar = + cmStrCat("CMAKE_", linkLanguage, "_STANDARD_LIBRARIES"); const char* tool = "VCLinkerTool"; if (this->FortranProject) { tool = "VFLinkerTool"; @@ -1071,9 +1049,8 @@ void cmLocalVisualStudio7Generator::OutputBuildTool( fout << " "; this->Internal->OutputLibraries(fout, cli.GetItems()); fout << "\"\n"; - temp = target->GetDirectory(configName); - temp += "/"; - temp += targetNames.Output; + temp = + cmStrCat(target->GetDirectory(configName), '/', targetNames.Output); fout << "\t\t\t\tOutputFile=\"" << this->ConvertToXMLOutputPathSingle(temp.c_str()) << "\"\n"; this->WriteTargetVersionAttribute(fout, target); @@ -1081,9 +1058,8 @@ void cmLocalVisualStudio7Generator::OutputBuildTool( fout << "\t\t\t\tAdditionalLibraryDirectories=\""; this->OutputLibraryDirectories(fout, cli.GetDirectories()); fout << "\"\n"; - temp = target->GetPDBDirectory(configName); - temp += "/"; - temp += targetNames.PDB; + temp = + cmStrCat(target->GetPDBDirectory(configName), '/', targetNames.PDB); fout << "\t\t\t\tProgramDatabaseFile=\"" << this->ConvertToXMLOutputPathSingle(temp.c_str()) << "\"\n"; if (targetOptions.IsDebug()) { @@ -1096,17 +1072,14 @@ void cmLocalVisualStudio7Generator::OutputBuildTool( fout << "\t\t\t\tSubSystem=\"8\"\n"; } } - std::string stackVar = "CMAKE_"; - stackVar += linkLanguage; - stackVar += "_STACK_SIZE"; + std::string stackVar = cmStrCat("CMAKE_", linkLanguage, "_STACK_SIZE"); const char* stackVal = this->Makefile->GetDefinition(stackVar.c_str()); if (stackVal) { fout << "\t\t\t\tStackReserveSize=\"" << stackVal << "\"\n"; } - temp = - target->GetDirectory(configName, cmStateEnums::ImportLibraryArtifact); - temp += "/"; - temp += targetNames.ImportLibrary; + temp = cmStrCat( + target->GetDirectory(configName, cmStateEnums::ImportLibraryArtifact), + '/', targetNames.ImportLibrary); fout << "\t\t\t\tImportLibrary=\"" << this->ConvertToXMLOutputPathSingle(temp.c_str()) << "\""; if (this->FortranProject) { @@ -1130,9 +1103,8 @@ void cmLocalVisualStudio7Generator::OutputBuildTool( // Compute the variable name to lookup standard libraries for this // language. - std::string standardLibsVar = "CMAKE_"; - standardLibsVar += linkLanguage; - standardLibsVar += "_STANDARD_LIBRARIES"; + std::string standardLibsVar = + cmStrCat("CMAKE_", linkLanguage, "_STANDARD_LIBRARIES"); const char* tool = "VCLinkerTool"; if (this->FortranProject) { tool = "VFLinkerTool"; @@ -1152,9 +1124,8 @@ void cmLocalVisualStudio7Generator::OutputBuildTool( fout << " "; this->Internal->OutputLibraries(fout, cli.GetItems()); fout << "\"\n"; - temp = target->GetDirectory(configName); - temp += "/"; - temp += targetNames.Output; + temp = + cmStrCat(target->GetDirectory(configName), '/', targetNames.Output); fout << "\t\t\t\tOutputFile=\"" << this->ConvertToXMLOutputPathSingle(temp.c_str()) << "\"\n"; this->WriteTargetVersionAttribute(fout, target); @@ -1190,17 +1161,14 @@ void cmLocalVisualStudio7Generator::OutputBuildTool( fout << "\t\t\t\tSubSystem=\"" << (isWin32Executable ? "2" : "1") << "\"\n"; } - std::string stackVar = "CMAKE_"; - stackVar += linkLanguage; - stackVar += "_STACK_SIZE"; + std::string stackVar = cmStrCat("CMAKE_", linkLanguage, "_STACK_SIZE"); const char* stackVal = this->Makefile->GetDefinition(stackVar.c_str()); if (stackVal) { fout << "\t\t\t\tStackReserveSize=\"" << stackVal << "\""; } - temp = - target->GetDirectory(configName, cmStateEnums::ImportLibraryArtifact); - temp += "/"; - temp += targetNames.ImportLibrary; + temp = cmStrCat( + target->GetDirectory(configName, cmStateEnums::ImportLibraryArtifact), + '/', targetNames.ImportLibrary); fout << "\t\t\t\tImportLibrary=\"" << this->ConvertToXMLOutputPathSingle(temp.c_str()) << "\"/>\n"; break; @@ -1509,8 +1477,7 @@ cmLocalVisualStudio7GeneratorFCInfo::cmLocalVisualStudio7GeneratorFCInfo( fc.CompileDefs = genexInterpreter.Evaluate(cdefs, COMPILE_DEFINITIONS); needfc = true; } - std::string defPropName = "COMPILE_DEFINITIONS_"; - defPropName += configUpper; + std::string defPropName = cmStrCat("COMPILE_DEFINITIONS_", configUpper); if (const char* ccdefs = sf.GetProperty(defPropName)) { fc.CompileDefsConfig = genexInterpreter.Evaluate(ccdefs, COMPILE_DEFINITIONS); @@ -1526,7 +1493,7 @@ cmLocalVisualStudio7GeneratorFCInfo::cmLocalVisualStudio7GeneratorFCInfo( // Check for extra object-file dependencies. if (const char* deps = sf.GetProperty("OBJECT_DEPENDS")) { std::vector<std::string> depends; - cmSystemTools::ExpandListArgument(deps, depends); + cmExpandList(deps, depends); const char* sep = ""; for (std::vector<std::string>::iterator j = depends.begin(); j != depends.end(); ++j) { @@ -1540,9 +1507,8 @@ cmLocalVisualStudio7GeneratorFCInfo::cmLocalVisualStudio7GeneratorFCInfo( const std::string& linkLanguage = gt->GetLinkerLanguage(config.c_str()); // If HEADER_FILE_ONLY is set, we must suppress this generation in // the project file - fc.ExcludedFromBuild = sf.GetPropertyAsBool("HEADER_FILE_ONLY") || - std::find(acs.Configs.begin(), acs.Configs.end(), ci) == - acs.Configs.end(); + fc.ExcludedFromBuild = + sf.GetPropertyAsBool("HEADER_FILE_ONLY") || !cmContains(acs.Configs, ci); if (fc.ExcludedFromBuild) { needfc = true; } @@ -1586,13 +1552,9 @@ std::string cmLocalVisualStudio7Generator::ComputeLongestObjectDirectory( // Compute the maximum length full path to the intermediate // files directory for any configuration. This is used to construct // object file names that do not produce paths that are too long. - std::string dir_max; - dir_max += this->GetCurrentBinaryDirectory(); - dir_max += "/"; - dir_max += this->GetTargetDirectory(target); - dir_max += "/"; - dir_max += config_max; - dir_max += "/"; + std::string dir_max = + cmStrCat(this->GetCurrentBinaryDirectory(), '/', + this->GetTargetDirectory(target), '/', config_max, '/'); return dir_max; } @@ -2142,8 +2104,7 @@ void cmLocalVisualStudio7Generator::ReadAndStoreExternalGUID( if (parser.GUID.empty()) { return; } - std::string guidStoreName = name; - guidStoreName += "_GUID_CMAKE"; + std::string guidStoreName = cmStrCat(name, "_GUID_CMAKE"); // save the GUID in the cache this->GlobalGenerator->GetCMakeInstance()->AddCacheEntry( guidStoreName.c_str(), parser.GUID.c_str(), "Stored GUID", @@ -2153,9 +2114,7 @@ void cmLocalVisualStudio7Generator::ReadAndStoreExternalGUID( std::string cmLocalVisualStudio7Generator::GetTargetDirectory( cmGeneratorTarget const* target) const { - std::string dir; - dir += target->GetName(); - dir += ".dir"; + std::string dir = cmStrCat(target->GetName(), ".dir"); return dir; } diff --git a/Source/cmLocalXCodeGenerator.cxx b/Source/cmLocalXCodeGenerator.cxx index 9c36627..5a06d4a 100644 --- a/Source/cmLocalXCodeGenerator.cxx +++ b/Source/cmLocalXCodeGenerator.cxx @@ -65,9 +65,8 @@ void cmLocalXCodeGenerator::ComputeObjectFilenames( std::map<std::string, int> counts; for (auto& si : mapping) { cmSourceFile const* sf = si.first; - std::string objectName = - cmSystemTools::GetFilenameWithoutLastExtension(sf->GetFullPath()); - objectName += ".o"; + std::string objectName = cmStrCat( + cmSystemTools::GetFilenameWithoutLastExtension(sf->GetFullPath()), ".o"); std::string objectNameLower = cmSystemTools::LowerCase(objectName); counts[objectNameLower] += 1; diff --git a/Source/cmMacroCommand.cxx b/Source/cmMacroCommand.cxx index 1f2b5b2..92ea9aa 100644 --- a/Source/cmMacroCommand.cxx +++ b/Source/cmMacroCommand.cxx @@ -7,9 +7,13 @@ #include <utility> #include "cm_memory.hxx" +#include "cm_static_string_view.hxx" +#include "cm_string_view.hxx" #include "cmAlgorithms.h" #include "cmExecutionStatus.h" +#include "cmFunctionBlocker.h" +#include "cmListFileCache.h" #include "cmMakefile.h" #include "cmPolicies.h" #include "cmRange.h" @@ -17,6 +21,8 @@ #include "cmStringAlgorithms.h" #include "cmSystemTools.h" +namespace { + // define the class for macro commands class cmMacroHelperCommand { @@ -48,8 +54,8 @@ bool cmMacroHelperCommand::operator()( // required by the signature if (expandedArgs.size() < this->Args.size() - 1) { std::string errorMsg = - "Macro invoked with incorrect arguments for macro named: "; - errorMsg += this->Args[0]; + cmStrCat("Macro invoked with incorrect arguments for macro named: ", + this->Args[0]); inStatus.SetError(errorMsg); return false; } @@ -136,62 +142,51 @@ bool cmMacroHelperCommand::operator()( return true; } -bool cmMacroFunctionBlocker::IsFunctionBlocked(const cmListFileFunction& lff, - cmMakefile& mf, - cmExecutionStatus&) +class cmMacroFunctionBlocker : public cmFunctionBlocker { - // record commands until we hit the ENDMACRO - // at the ENDMACRO call we shift gears and start looking for invocations - if (lff.Name.Lower == "macro") { - this->Depth++; - } else if (lff.Name.Lower == "endmacro") { - // if this is the endmacro for this macro then execute - if (!this->Depth) { - mf.AppendProperty("MACROS", this->Args[0].c_str()); - // create a new command and add it to cmake - cmMacroHelperCommand f; - f.Args = this->Args; - f.Functions = this->Functions; - f.FilePath = this->GetStartingContext().FilePath; - mf.RecordPolicies(f.Policies); - mf.GetState()->AddScriptedCommand(this->Args[0], std::move(f)); - // remove the function blocker now that the macro is defined - mf.RemoveFunctionBlocker(this, lff); - return true; - } - // decrement for each nested macro that ends - this->Depth--; - } +public: + cm::string_view StartCommandName() const override { return "macro"_s; } + cm::string_view EndCommandName() const override { return "endmacro"_s; } - // if it wasn't an endmacro and we are not executing then we must be - // recording - this->Functions.push_back(lff); - return true; -} + bool ArgumentsMatch(cmListFileFunction const&, + cmMakefile& mf) const override; + + bool Replay(std::vector<cmListFileFunction> functions, + cmExecutionStatus& status) override; + + std::vector<std::string> Args; +}; -bool cmMacroFunctionBlocker::ShouldRemove(const cmListFileFunction& lff, - cmMakefile& mf) +bool cmMacroFunctionBlocker::ArgumentsMatch(cmListFileFunction const& lff, + cmMakefile& mf) const { - if (lff.Name.Lower == "endmacro") { - std::vector<std::string> expandedArguments; - mf.ExpandArguments(lff.Arguments, expandedArguments, - this->GetStartingContext().FilePath.c_str()); - // if the endmacro has arguments make sure they - // match the arguments of the macro - if ((expandedArguments.empty() || - (expandedArguments[0] == this->Args[0]))) { - return true; - } - } + std::vector<std::string> expandedArguments; + mf.ExpandArguments(lff.Arguments, expandedArguments, + this->GetStartingContext().FilePath.c_str()); + return expandedArguments.empty() || expandedArguments[0] == this->Args[0]; +} - return false; +bool cmMacroFunctionBlocker::Replay(std::vector<cmListFileFunction> functions, + cmExecutionStatus& status) +{ + cmMakefile& mf = status.GetMakefile(); + mf.AppendProperty("MACROS", this->Args[0].c_str()); + // create a new command and add it to cmake + cmMacroHelperCommand f; + f.Args = this->Args; + f.Functions = std::move(functions); + f.FilePath = this->GetStartingContext().FilePath; + mf.RecordPolicies(f.Policies); + mf.GetState()->AddScriptedCommand(this->Args[0], std::move(f)); + return true; +} } -bool cmMacroCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus&) +bool cmMacroCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.empty()) { - this->SetError("called with incorrect number of arguments"); + status.SetError("called with incorrect number of arguments"); return false; } @@ -199,7 +194,7 @@ bool cmMacroCommand::InitialPass(std::vector<std::string> const& args, { auto fb = cm::make_unique<cmMacroFunctionBlocker>(); cmAppend(fb->Args, args); - this->Makefile->AddFunctionBlocker(std::move(fb)); + status.GetMakefile().AddFunctionBlocker(std::move(fb)); } return true; } diff --git a/Source/cmMacroCommand.h b/Source/cmMacroCommand.h index 3ebd959..25091ea 100644 --- a/Source/cmMacroCommand.h +++ b/Source/cmMacroCommand.h @@ -8,45 +8,10 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" -#include "cmFunctionBlocker.h" -#include "cmListFileCache.h" - class cmExecutionStatus; -class cmMakefile; - -class cmMacroFunctionBlocker : public cmFunctionBlocker -{ -public: - bool IsFunctionBlocked(const cmListFileFunction&, cmMakefile& mf, - cmExecutionStatus&) override; - bool ShouldRemove(const cmListFileFunction&, cmMakefile& mf) override; - - std::vector<std::string> Args; - std::vector<cmListFileFunction> Functions; - int Depth = 0; -}; /// Starts macro() ... endmacro() block -class cmMacroCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmMacroCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; -}; +bool cmMacroCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmMakeDirectoryCommand.cxx b/Source/cmMakeDirectoryCommand.cxx index aff4ca6..cdde6f9 100644 --- a/Source/cmMakeDirectoryCommand.cxx +++ b/Source/cmMakeDirectoryCommand.cxx @@ -2,23 +2,22 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmMakeDirectoryCommand.h" +#include "cmExecutionStatus.h" #include "cmMakefile.h" #include "cmSystemTools.h" -class cmExecutionStatus; - // cmMakeDirectoryCommand -bool cmMakeDirectoryCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus&) +bool cmMakeDirectoryCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() != 1) { - this->SetError("called with incorrect number of arguments"); + status.SetError("called with incorrect number of arguments"); return false; } - if (!this->Makefile->CanIWriteThisFile(args[0])) { + if (!status.GetMakefile().CanIWriteThisFile(args[0])) { std::string e = "attempted to create a directory: " + args[0] + " into a source directory."; - this->SetError(e); + status.SetError(e); cmSystemTools::SetFatalErrorOccured(); return false; } diff --git a/Source/cmMakeDirectoryCommand.h b/Source/cmMakeDirectoryCommand.h index b1fb49b..2474383 100644 --- a/Source/cmMakeDirectoryCommand.h +++ b/Source/cmMakeDirectoryCommand.h @@ -8,13 +8,9 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -/** \class cmMakeDirectoryCommand +/** * \brief Specify auxiliary source code directories. * * cmMakeDirectoryCommand specifies source code directories @@ -23,23 +19,7 @@ class cmExecutionStatus; * A side effect of this command is to create a subdirectory in the build * directory structure. */ -class cmMakeDirectoryCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmMakeDirectoryCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; -}; +bool cmMakeDirectoryCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmMakefile.cxx b/Source/cmMakefile.cxx index 8188ffa..78351c1 100644 --- a/Source/cmMakefile.cxx +++ b/Source/cmMakefile.cxx @@ -23,6 +23,7 @@ #include "cmExpandedCommandArgument.h" // IWYU pragma: keep #include "cmFileLockPool.h" #include "cmFunctionBlocker.h" +#include "cmGeneratedFileStream.h" #include "cmGeneratorExpression.h" #include "cmGeneratorExpressionEvaluationFile.h" #include "cmGlobalGenerator.h" @@ -47,7 +48,7 @@ #include "cmConfigure.h" // IWYU pragma: keep -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP # include "cmVariableWatch.h" #endif @@ -97,7 +98,7 @@ cmMakefile::cmMakefile(cmGlobalGenerator* globalGenerator, // cmListFileCache in the top level if necessary. this->CheckCMP0000 = false; -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) this->AddSourceGroup("", "^.*$"); this->AddSourceGroup("Source Files", CM_SOURCE_REGEX); this->AddSourceGroup("Header Files", CM_HEADER_REGEX); @@ -321,7 +322,13 @@ void cmMakefile::PrintCommandTrace(const cmListFileFunction& lff) const msg << " "; } msg << ")"; - cmSystemTools::Message(msg.str()); + + auto& f = this->GetCMakeInstance()->GetTraceFile(); + if (f) { + f << msg.str() << '\n'; + } else { + cmSystemTools::Message(msg.str()); + } } // Helper class to make sure the call stack is valid. @@ -353,6 +360,11 @@ private: cmMakefile* Makefile; }; +void cmMakefile::OnExecuteCommand(std::function<void()> callback) +{ + this->ExecuteCommandCallback = std::move(callback); +} + bool cmMakefile::ExecuteCommand(const cmListFileFunction& lff, cmExecutionStatus& status) { @@ -364,6 +376,10 @@ bool cmMakefile::ExecuteCommand(const cmListFileFunction& lff, return result; } + if (this->ExecuteCommandCallback) { + this->ExecuteCommandCallback(); + } + // Place this call on the call stack. cmMakefileCall stack_manager(this, lff, status); static_cast<void>(stack_manager); @@ -413,9 +429,8 @@ bool cmMakefile::ExecuteCommand(const cmListFileFunction& lff, } } else { if (!cmSystemTools::GetFatalErrorOccured()) { - std::string error = "Unknown CMake command \""; - error += lff.Name.Original; - error += "\"."; + std::string error = + cmStrCat("Unknown CMake command \"", lff.Name.Original, "\"."); this->IssueMessage(MessageType::FATAL_ERROR, error); result = false; cmSystemTools::SetFatalErrorOccured(); @@ -1172,10 +1187,8 @@ cmTarget* cmMakefile::AddUtilityCommand( // Store the custom command in the target. if (!commandLines.empty() || !depends.empty()) { - std::string force = this->GetCurrentBinaryDirectory(); - force += "/CMakeFiles"; - force += "/"; - force += utilityName; + std::string force = + cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles/", utilityName); std::vector<std::string> forced; forced.push_back(force); std::string no_main_dependency; @@ -1340,7 +1353,7 @@ bool cmMakefile::ParseDefineFlag(std::string const& def, bool remove) if (const char* cdefs = this->GetProperty("COMPILE_DEFINITIONS")) { // Expand the list. std::vector<std::string> defs; - cmSystemTools::ExpandListArgument(cdefs, defs); + cmExpandList(cdefs, defs); // Recompose the list without the definition. std::vector<std::string>::const_iterator defEnd = @@ -1381,8 +1394,8 @@ void cmMakefile::InitializeFromParent(cmMakefile* parent) std::vector<std::string> configs; this->GetConfigurations(configs); for (std::string const& config : configs) { - std::string defPropName = "COMPILE_DEFINITIONS_"; - defPropName += cmSystemTools::UpperCase(config); + std::string defPropName = + cmStrCat("COMPILE_DEFINITIONS_", cmSystemTools::UpperCase(config)); const char* prop = parent->GetProperty(defPropName); this->SetProperty(defPropName, prop); } @@ -1416,7 +1429,7 @@ void cmMakefile::PushFunctionScope(std::string const& fileName, this->PushLoopBlockBarrier(); -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) this->GetGlobalGenerator()->GetFileLockPool().PushFunctionScope(); #endif @@ -1433,7 +1446,7 @@ void cmMakefile::PopFunctionScope(bool reportError) this->PopFunctionBlockerBarrier(reportError); -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) this->GetGlobalGenerator()->GetFileLockPool().PopFunctionScope(); #endif @@ -1475,8 +1488,8 @@ public: , ReportError(true) { std::string currentStart = - this->Makefile->StateSnapshot.GetDirectory().GetCurrentSource(); - currentStart += "/CMakeLists.txt"; + cmStrCat(this->Makefile->StateSnapshot.GetDirectory().GetCurrentSource(), + "/CMakeLists.txt"); this->Makefile->StateSnapshot.SetListFile(currentStart); this->Makefile->StateSnapshot = this->Makefile->StateSnapshot.GetState()->CreatePolicyScopeSnapshot( @@ -1488,7 +1501,7 @@ public: this->Snapshot = this->GG->GetCMakeInstance()->GetCurrentSnapshot(); this->GG->GetCMakeInstance()->SetCurrentSnapshot(this->Snapshot); this->GG->SetCurrentMakefile(mf); -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) this->GG->GetFileLockPool().PushFileScope(); #endif } @@ -1497,7 +1510,7 @@ public: { this->Makefile->PopFunctionBlockerBarrier(this->ReportError); this->Makefile->PopSnapshot(this->ReportError); -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) this->GG->GetFileLockPool().PopFileScope(); #endif this->GG->SetCurrentMakefile(this->CurrentMakefile); @@ -1519,9 +1532,8 @@ private: void cmMakefile::Configure() { - std::string currentStart = - this->StateSnapshot.GetDirectory().GetCurrentSource(); - currentStart += "/CMakeLists.txt"; + std::string currentStart = cmStrCat( + this->StateSnapshot.GetDirectory().GetCurrentSource(), "/CMakeLists.txt"); // Add the bottom of all backtraces within this directory. // We will never pop this scope because it should be available @@ -1531,8 +1543,8 @@ void cmMakefile::Configure() BuildsystemFileScope scope(this); // make sure the CMakeFiles dir is there - std::string filesDir = this->StateSnapshot.GetDirectory().GetCurrentBinary(); - filesDir += "/CMakeFiles"; + std::string filesDir = cmStrCat( + this->StateSnapshot.GetDirectory().GetCurrentBinary(), "/CMakeFiles"); cmSystemTools::MakeDirectory(filesDir); assert(cmSystemTools::FileExists(currentStart, true)); @@ -1574,7 +1586,7 @@ void cmMakefile::Configure() allowedCommands.insert("message"); isProblem = false; for (cmListFileFunction const& func : listFile.Functions) { - if (allowedCommands.find(func.Name.Lower) == allowedCommands.end()) { + if (!cmContains(allowedCommands, func.Name.Lower)) { isProblem = true; break; } @@ -1643,8 +1655,7 @@ void cmMakefile::ConfigureSubDirectory(cmMakefile* mf) mf->InitializeFromParent(this); std::string currentStart = mf->GetCurrentSourceDirectory(); if (this->GetCMakeInstance()->GetDebugOutput()) { - std::string msg = " Entering "; - msg += currentStart; + std::string msg = cmStrCat(" Entering ", currentStart); cmSystemTools::Message(msg); } @@ -1686,8 +1697,8 @@ void cmMakefile::ConfigureSubDirectory(cmMakefile* mf) mf->Configure(); if (this->GetCMakeInstance()->GetDebugOutput()) { - std::string msg = " Returning to "; - msg += this->GetCurrentSourceDirectory(); + std::string msg = + cmStrCat(" Returning to ", this->GetCurrentSourceDirectory()); cmSystemTools::Message(msg); } } @@ -1791,7 +1802,7 @@ void cmMakefile::AddDefinition(const std::string& name, cm::string_view value) } this->StateSnapshot.SetDefinition(name, value); -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP cmVariableWatch* vv = this->GetVariableWatch(); if (vv) { vv->VariableAccessed(name, cmVariableWatch::VARIABLE_MODIFIED_ACCESS, @@ -1828,10 +1839,10 @@ void cmMakefile::AddCacheDefinition(const std::string& name, const char* value, std::vector<std::string> files; nvalue = value ? value : ""; - cmSystemTools::ExpandListArgument(nvalue, files); + cmExpandList(nvalue, files); nvalue.clear(); for (cc = 0; cc < files.size(); cc++) { - if (!cmSystemTools::IsOff(files[cc])) { + if (!cmIsOff(files[cc])) { files[cc] = cmSystemTools::CollapseFullPath(files[cc]); } if (cc > 0) { @@ -1894,8 +1905,7 @@ void cmMakefile::LogUnused(const char* reason, const std::string& name) const if (!this->ExecutionStatusStack.empty()) { path = this->GetExecutionContext().FilePath; } else { - path = this->GetCurrentSourceDirectory(); - path += "/CMakeLists.txt"; + path = cmStrCat(this->GetCurrentSourceDirectory(), "/CMakeLists.txt"); } if (this->CheckSystemVars || this->IsProjectFile(path.c_str())) { @@ -1912,7 +1922,7 @@ void cmMakefile::RemoveDefinition(const std::string& name) this->LogUnused("unsetting", name); } this->StateSnapshot.RemoveDefinition(name); -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP cmVariableWatch* vv = this->GetVariableWatch(); if (vv) { vv->VariableAccessed(name, cmVariableWatch::VARIABLE_REMOVED_ACCESS, @@ -1944,7 +1954,7 @@ void cmMakefile::AddGlobalLinkInformation(cmTarget& target) if (const char* linkLibsProp = this->GetProperty("LINK_LIBRARIES")) { std::vector<std::string> linkLibs; - cmSystemTools::ExpandListArgument(linkLibsProp, linkLibs); + cmExpandList(linkLibsProp, linkLibs); for (std::vector<std::string>::iterator j = linkLibs.begin(); j != linkLibs.end(); ++j) { @@ -2070,7 +2080,7 @@ cmSourceFile* cmMakefile::GetSourceFileWithOutput( return nullptr; } -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) cmSourceGroup* cmMakefile::GetSourceGroup( const std::vector<std::string>& name) const { @@ -2166,8 +2176,7 @@ cmSourceGroup* cmMakefile::GetOrCreateSourceGroup(const std::string& name) if (delimiter == nullptr) { delimiter = "\\"; } - return this->GetOrCreateSourceGroup( - cmSystemTools::tokenize(name, delimiter)); + return this->GetOrCreateSourceGroup(cmTokenize(name, delimiter)); } /** @@ -2273,7 +2282,7 @@ void cmMakefile::ExpandVariablesCMP0019() if (const char* linkLibsProp = this->GetProperty("LINK_LIBRARIES")) { std::vector<std::string> linkLibs; - cmSystemTools::ExpandListArgument(linkLibsProp, linkLibs); + cmExpandList(linkLibsProp, linkLibs); for (std::vector<std::string>::iterator l = linkLibs.begin(); l != linkLibs.end(); ++l) { @@ -2316,7 +2325,7 @@ void cmMakefile::ExpandVariablesCMP0019() bool cmMakefile::IsOn(const std::string& name) const { const char* value = this->GetDefinition(name); - return cmSystemTools::IsOn(value); + return cmIsOn(value); } bool cmMakefile::IsSet(const std::string& name) const @@ -2330,7 +2339,7 @@ bool cmMakefile::IsSet(const std::string& name) const return false; } - if (cmSystemTools::IsNOTFOUND(value)) { + if (cmIsNOTFOUND(value)) { return false; } @@ -2452,7 +2461,7 @@ bool cmMakefile::IsDefinitionSet(const std::string& name) const if (!def) { def = this->GetState()->GetInitializedCacheValue(name); } -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP if (cmVariableWatch* vv = this->GetVariableWatch()) { if (!def) { vv->VariableAccessed( @@ -2469,7 +2478,7 @@ const std::string* cmMakefile::GetDef(const std::string& name) const if (!def) { def = this->GetState()->GetInitializedCacheValue(name); } -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP cmVariableWatch* vv = this->GetVariableWatch(); if (vv && !this->SuppressSideEffects) { bool const watch_function_executed = @@ -2588,8 +2597,8 @@ const std::string& cmMakefile::ExpandVariablesInString( } // ...otherwise, see if there's a difference that needs to be warned about. else if (compareResults && (newResult != source || newError != mtype)) { - std::string msg = cmPolicies::GetPolicyWarning(cmPolicies::CMP0053); - msg += "\n"; + std::string msg = + cmStrCat(cmPolicies::GetPolicyWarning(cmPolicies::CMP0053), '\n'); std::string msg_input = original; cmSystemTools::ReplaceString(msg_input, "\n", "\n "); @@ -2659,7 +2668,7 @@ MessageType cmMakefile::ExpandVariablesInStringOld( if (const char* val = this->GetDefinition(var)) { // Store the value in the output escaping as requested. if (escapeQuotes) { - source.append(cmSystemTools::EscapeQuotes(val)); + source.append(cmEscapeQuotes(val)); } else { source.append(val); } @@ -2823,7 +2832,7 @@ MessageType cmMakefile::ExpandVariablesInStringNew( // Get the string we're meant to append to. if (value) { if (escapeQuotes) { - varresult = cmSystemTools::EscapeQuotes(value); + varresult = cmEscapeQuotes(value); } else { varresult = value; } @@ -2949,7 +2958,7 @@ MessageType cmMakefile::ExpandVariablesInStringNew( } if (escapeQuotes) { - varresult = cmSystemTools::EscapeQuotes(varresult); + varresult = cmEscapeQuotes(varresult); } // Skip over the variable. result.append(last, in - last); @@ -3042,7 +3051,7 @@ std::string cmMakefile::GetConfigurations(std::vector<std::string>& configs, if (this->GetGlobalGenerator()->IsMultiConfig()) { if (const char* configTypes = this->GetDefinition("CMAKE_CONFIGURATION_TYPES")) { - cmSystemTools::ExpandListArgument(configTypes, configs); + cmExpandList(configTypes, configs); } return ""; } @@ -3061,7 +3070,7 @@ bool cmMakefile::IsFunctionBlocked(const cmListFileFunction& lff, return false; } - return this->FunctionBlockers.top()->IsFunctionBlocked(lff, *this, status); + return this->FunctionBlockers.top()->IsFunctionBlocked(lff, status); } void cmMakefile::PushFunctionBlockerBarrier() @@ -3159,7 +3168,7 @@ bool cmMakefile::ExpandArguments(std::vector<cmListFileArgument> const& inArgs, if (i.Delim == cmListFileArgument::Quoted) { outArgs.push_back(value); } else { - cmSystemTools::ExpandListArgument(value, outArgs); + cmExpandList(value, outArgs); } } return !cmSystemTools::GetFatalErrorOccured(); @@ -3192,7 +3201,7 @@ bool cmMakefile::ExpandArguments( outArgs.emplace_back(value, true); } else { std::vector<std::string> stringArgs; - cmSystemTools::ExpandListArgument(value, stringArgs); + cmExpandList(value, stringArgs); for (std::string const& stringArg : stringArgs) { outArgs.emplace_back(stringArg, false); } @@ -3211,30 +3220,12 @@ void cmMakefile::AddFunctionBlocker(std::unique_ptr<cmFunctionBlocker> fb) this->FunctionBlockers.push(std::move(fb)); } -std::unique_ptr<cmFunctionBlocker> cmMakefile::RemoveFunctionBlocker( - cmFunctionBlocker* fb, const cmListFileFunction& lff) +std::unique_ptr<cmFunctionBlocker> cmMakefile::RemoveFunctionBlocker() { assert(!this->FunctionBlockers.empty()); - assert(this->FunctionBlockers.top().get() == fb); assert(this->FunctionBlockerBarriers.empty() || this->FunctionBlockers.size() > this->FunctionBlockerBarriers.back()); - // Warn if the arguments do not match, but always remove. - if (!fb->ShouldRemove(lff, *this)) { - cmListFileContext const& lfc = fb->GetStartingContext(); - cmListFileContext closingContext = - cmListFileContext::FromCommandContext(lff, lfc.FilePath); - std::ostringstream e; - /* clang-format off */ - e << "A logical block opening on the line\n" - << " " << lfc << "\n" - << "closes on the line\n" - << " " << closingContext << "\n" - << "with mis-matching arguments."; - /* clang-format on */ - this->IssueMessage(MessageType::AUTHOR_WARNING, e.str()); - } - auto b = std::move(this->FunctionBlockers.top()); this->FunctionBlockers.pop(); return b; @@ -3337,7 +3328,7 @@ void cmMakefile::AddTargetObject(std::string const& tgtName, cmSourceFile* sf = this->GetOrCreateSource(objFile, true); sf->SetObjectLibrary(tgtName); sf->SetProperty("EXTERNAL_OBJECT", "1"); -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) this->SourceGroups[this->ObjectLibrariesSourceGroupIndex].AddGroupFile( sf->GetFullPath()); #endif @@ -3519,7 +3510,7 @@ cmGlobalGenerator* cmMakefile::GetGlobalGenerator() const return this->GlobalGenerator; } -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP cmVariableWatch* cmMakefile::GetVariableWatch() const { if (this->GetCMakeInstance() && @@ -3568,7 +3559,7 @@ std::string cmMakefile::GetModulesFile(const std::string& filename, const char* cmakeModulePath = this->GetDefinition("CMAKE_MODULE_PATH"); if (cmakeModulePath) { std::vector<std::string> modulePath; - cmSystemTools::ExpandListArgument(cmakeModulePath, modulePath); + cmExpandList(cmakeModulePath, modulePath); // Look through the possible module directories. for (std::string itempl : modulePath) { @@ -3583,9 +3574,8 @@ std::string cmMakefile::GetModulesFile(const std::string& filename, } // Always search in the standard modules location. - moduleInCMakeRoot = cmSystemTools::GetCMakeRoot(); - moduleInCMakeRoot += "/Modules/"; - moduleInCMakeRoot += filename; + moduleInCMakeRoot = + cmStrCat(cmSystemTools::GetCMakeRoot(), "/Modules/", filename); cmSystemTools::ConvertToUnixSlashes(moduleInCMakeRoot); if (!cmSystemTools::FileExists(moduleInCMakeRoot)) { moduleInCMakeRoot.clear(); @@ -3660,7 +3650,7 @@ void cmMakefile::ConfigureString(const std::string& input, std::string& output, // Replace #cmakedefine instances. if (this->cmDefineRegex.find(line)) { const char* def = this->GetDefinition(this->cmDefineRegex.match(2)); - if (!cmSystemTools::IsOff(def)) { + if (!cmIsOff(def)) { const std::string indentation = this->cmDefineRegex.match(1); cmSystemTools::ReplaceString(line, "#" + indentation + "cmakedefine", "#" + indentation + "define"); @@ -3676,7 +3666,7 @@ void cmMakefile::ConfigureString(const std::string& input, std::string& output, cmSystemTools::ReplaceString(line, "#" + indentation + "cmakedefine01", "#" + indentation + "define"); output += line; - if (!cmSystemTools::IsOff(def)) { + if (!cmIsOff(def)) { output += " 1"; } else { output += " 0"; @@ -3751,8 +3741,7 @@ int cmMakefile::ConfigureFile(const std::string& infile, } else { newLineCharacters = "\n"; } - std::string tempOutputFile = soutfile; - tempOutputFile += ".tmp"; + std::string tempOutputFile = cmStrCat(soutfile, ".tmp"); cmsys::ofstream fout(tempOutputFile.c_str(), omode); if (!fout) { cmSystemTools::Error("Could not open file for write in copy operation " + @@ -3840,7 +3829,7 @@ const char* cmMakefile::GetProperty(const std::string& prop, bool chain) const bool cmMakefile::GetPropertyAsBool(const std::string& prop) const { - return cmSystemTools::IsOn(this->GetProperty(prop)); + return cmIsOn(this->GetProperty(prop)); } std::vector<std::string> cmMakefile::GetPropertyKeys() const @@ -3893,15 +3882,13 @@ void cmMakefile::AddCMakeDependFilesFromUser() { std::vector<std::string> deps; if (const char* deps_str = this->GetProperty("CMAKE_CONFIGURE_DEPENDS")) { - cmSystemTools::ExpandListArgument(deps_str, deps); + cmExpandList(deps_str, deps); } for (std::string const& dep : deps) { if (cmSystemTools::FileIsFullPath(dep)) { this->AddCMakeDependFile(dep); } else { - std::string f = this->GetCurrentSourceDirectory(); - f += "/"; - f += dep; + std::string f = cmStrCat(this->GetCurrentSourceDirectory(), '/', dep); this->AddCMakeDependFile(f); } } @@ -3941,14 +3928,14 @@ void cmMakefile::PushScope() this->GetState()->CreateVariableScopeSnapshot(this->StateSnapshot); this->PushLoopBlockBarrier(); -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) this->GetGlobalGenerator()->GetFileLockPool().PushFunctionScope(); #endif } void cmMakefile::PopScope() { -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) this->GetGlobalGenerator()->GetFileLockPool().PopFunctionScope(); #endif @@ -3972,7 +3959,7 @@ void cmMakefile::RaiseScope(const std::string& var, const char* varDef) return; } -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP cmVariableWatch* vv = this->GetVariableWatch(); if (vv) { vv->VariableAccessed(var, cmVariableWatch::VARIABLE_MODIFIED_ACCESS, @@ -4022,7 +4009,7 @@ cmTarget* cmMakefile::FindTargetToUse(const std::string& name, bool cmMakefile::IsAlias(const std::string& name) const { - if (this->AliasTargets.find(name) != this->AliasTargets.end()) { + if (cmContains(this->AliasTargets, name)) { return true; } return this->GetGlobalGenerator()->IsAlias(name); @@ -4230,7 +4217,7 @@ bool cmMakefile::PolicyOptionalWarningEnabled(std::string const& var) { // Check for an explicit CMAKE_POLICY_WARNING_CMP<NNNN> setting. if (const char* val = this->GetDefinition(var)) { - return cmSystemTools::IsOn(val); + return cmIsOn(val); } // Enable optional policy warnings with --debug-output, --trace, // or --trace-expand. @@ -4388,9 +4375,8 @@ bool cmMakefile::AddRequiredTargetFeature(cmTarget* target, } std::vector<std::string> availableFeatures; - cmSystemTools::ExpandListArgument(features, availableFeatures); - if (std::find(availableFeatures.begin(), availableFeatures.end(), feature) == - availableFeatures.end()) { + cmExpandList(features, availableFeatures); + if (!cmContains(availableFeatures, feature)) { std::ostringstream e; e << "The compiler feature \"" << feature << "\" is not known to " << lang << " compiler\n\"" @@ -4658,32 +4644,32 @@ void cmMakefile::CheckNeededCxxLanguage(const std::string& feature, if (const char* propCxx98 = this->GetDefinition("CMAKE_CXX98_COMPILE_FEATURES")) { std::vector<std::string> props; - cmSystemTools::ExpandListArgument(propCxx98, props); - needCxx98 = std::find(props.begin(), props.end(), feature) != props.end(); + cmExpandList(propCxx98, props); + needCxx98 = cmContains(props, feature); } if (const char* propCxx11 = this->GetDefinition("CMAKE_CXX11_COMPILE_FEATURES")) { std::vector<std::string> props; - cmSystemTools::ExpandListArgument(propCxx11, props); - needCxx11 = std::find(props.begin(), props.end(), feature) != props.end(); + cmExpandList(propCxx11, props); + needCxx11 = cmContains(props, feature); } if (const char* propCxx14 = this->GetDefinition("CMAKE_CXX14_COMPILE_FEATURES")) { std::vector<std::string> props; - cmSystemTools::ExpandListArgument(propCxx14, props); - needCxx14 = std::find(props.begin(), props.end(), feature) != props.end(); + cmExpandList(propCxx14, props); + needCxx14 = cmContains(props, feature); } if (const char* propCxx17 = this->GetDefinition("CMAKE_CXX17_COMPILE_FEATURES")) { std::vector<std::string> props; - cmSystemTools::ExpandListArgument(propCxx17, props); - needCxx17 = std::find(props.begin(), props.end(), feature) != props.end(); + cmExpandList(propCxx17, props); + needCxx17 = cmContains(props, feature); } if (const char* propCxx20 = this->GetDefinition("CMAKE_CXX20_COMPILE_FEATURES")) { std::vector<std::string> props; - cmSystemTools::ExpandListArgument(propCxx20, props); - needCxx20 = std::find(props.begin(), props.end(), feature) != props.end(); + cmExpandList(propCxx20, props); + needCxx20 = cmContains(props, feature); } } @@ -4782,20 +4768,20 @@ void cmMakefile::CheckNeededCLanguage(const std::string& feature, if (const char* propC90 = this->GetDefinition("CMAKE_C90_COMPILE_FEATURES")) { std::vector<std::string> props; - cmSystemTools::ExpandListArgument(propC90, props); - needC90 = std::find(props.begin(), props.end(), feature) != props.end(); + cmExpandList(propC90, props); + needC90 = cmContains(props, feature); } if (const char* propC99 = this->GetDefinition("CMAKE_C99_COMPILE_FEATURES")) { std::vector<std::string> props; - cmSystemTools::ExpandListArgument(propC99, props); - needC99 = std::find(props.begin(), props.end(), feature) != props.end(); + cmExpandList(propC99, props); + needC99 = cmContains(props, feature); } if (const char* propC11 = this->GetDefinition("CMAKE_C11_COMPILE_FEATURES")) { std::vector<std::string> props; - cmSystemTools::ExpandListArgument(propC11, props); - needC11 = std::find(props.begin(), props.end(), feature) != props.end(); + cmExpandList(propC11, props); + needC11 = cmContains(props, feature); } } diff --git a/Source/cmMakefile.h b/Source/cmMakefile.h index dc196ac..dcc4e77 100644 --- a/Source/cmMakefile.h +++ b/Source/cmMakefile.h @@ -30,7 +30,7 @@ #include "cmStringAlgorithms.h" #include "cmTarget.h" -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) # include "cmSourceGroup.h" #endif @@ -107,8 +107,7 @@ public: * Remove the function blocker whose scope ends with the given command. * This returns ownership of the function blocker object. */ - std::unique_ptr<cmFunctionBlocker> RemoveFunctionBlocker( - cmFunctionBlocker* fb, const cmListFileFunction& lff); + std::unique_ptr<cmFunctionBlocker> RemoveFunctionBlocker(); /** * Try running cmake and building a file. This is used for dynalically @@ -504,7 +503,7 @@ public: */ bool CanIWriteThisFile(std::string const& fileName) const; -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) /** * Get the vector source groups. */ @@ -628,6 +627,11 @@ public: void PrintCommandTrace(const cmListFileFunction& lff) const; /** + * Set a callback that is invoked whenever ExecuteCommand is called. + */ + void OnExecuteCommand(std::function<void()> callback); + + /** * Execute a single CMake command. Returns true if the command * succeeded or false if it failed. */ @@ -645,7 +649,7 @@ public: * Get the variable watch. This is used to determine when certain variables * are accessed. */ -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP cmVariableWatch* GetVariableWatch() const; #endif @@ -941,7 +945,7 @@ protected: // Track the value of the computed DEFINITIONS property. std::string DefineFlagsOrig; -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) std::vector<cmSourceGroup> SourceGroups; size_t ObjectLibrariesSourceGroupIndex; #endif @@ -964,6 +968,7 @@ private: bool EnforceUniqueDir(const std::string& srcPath, const std::string& binPath) const; + std::function<void()> ExecuteCommandCallback; using FunctionBlockerPtr = std::unique_ptr<cmFunctionBlocker>; using FunctionBlockersType = std::stack<FunctionBlockerPtr, std::vector<FunctionBlockerPtr>>; @@ -997,7 +1002,8 @@ private: cmPolicies::PolicyMap const& pm = cmPolicies::PolicyMap()); void PopPolicy(); void PopSnapshot(bool reportError = true); - friend class cmCMakePolicyCommand; + friend bool cmCMakePolicyCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); class IncludeScope; friend class IncludeScope; diff --git a/Source/cmMakefileExecutableTargetGenerator.cxx b/Source/cmMakefileExecutableTargetGenerator.cxx index a7f2a97..7bc05b1 100644 --- a/Source/cmMakefileExecutableTargetGenerator.cxx +++ b/Source/cmMakefileExecutableTargetGenerator.cxx @@ -26,6 +26,7 @@ #include "cmStateDirectory.h" #include "cmStateSnapshot.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" cmMakefileExecutableTargetGenerator::cmMakefileExecutableTargetGenerator( @@ -82,7 +83,7 @@ void cmMakefileExecutableTargetGenerator::WriteRuleFiles() void cmMakefileExecutableTargetGenerator::WriteDeviceExecutableRule( bool relink) { -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP const bool requiresDeviceLinking = requireDeviceLinking( *this->GeneratorTarget, *this->LocalGenerator, this->ConfigName); if (!requiresDeviceLinking) { @@ -110,14 +111,13 @@ void cmMakefileExecutableTargetGenerator::WriteDeviceExecutableRule( cmLocalUnixMakefileGenerator3::EchoProgress progress; this->MakeEchoProgress(progress); // Add the link message. - std::string buildEcho = "Linking "; - buildEcho += linkLanguage; - buildEcho += " device code "; - buildEcho += this->LocalGenerator->ConvertToOutputFormat( - this->LocalGenerator->MaybeConvertToRelativePath( - this->LocalGenerator->GetCurrentBinaryDirectory(), - this->DeviceLinkObject), - cmOutputConverter::SHELL); + std::string buildEcho = + cmStrCat("Linking ", linkLanguage, " device code ", + this->LocalGenerator->ConvertToOutputFormat( + this->LocalGenerator->MaybeConvertToRelativePath( + this->LocalGenerator->GetCurrentBinaryDirectory(), + this->DeviceLinkObject), + cmOutputConverter::SHELL)); this->LocalGenerator->AppendEcho( commands, buildEcho, cmLocalUnixMakefileGenerator3::EchoLink, &progress); } @@ -129,9 +129,8 @@ void cmMakefileExecutableTargetGenerator::WriteDeviceExecutableRule( // Add flags to create an executable. // Add symbol export flags if necessary. if (this->GeneratorTarget->IsExecutableWithExports()) { - std::string export_flag_var = "CMAKE_EXE_EXPORTS_"; - export_flag_var += linkLanguage; - export_flag_var += "_FLAG"; + std::string export_flag_var = + cmStrCat("CMAKE_EXE_EXPORTS_", linkLanguage, "_FLAG"); this->LocalGenerator->AppendFlags( linkFlags, this->Makefile->GetDefinition(export_flag_var)); } @@ -164,7 +163,7 @@ void cmMakefileExecutableTargetGenerator::WriteDeviceExecutableRule( const std::string linkRuleVar = "CMAKE_CUDA_DEVICE_LINK_EXECUTABLE"; const std::string linkRule = this->GetLinkRule(linkRuleVar); std::vector<std::string> commands1; - cmSystemTools::ExpandListArgument(linkRule, real_link_commands); + cmExpandList(linkRule, real_link_commands); bool useResponseFileForObjects = this->CheckUseResponseFileForObjects(linkLanguage); @@ -233,8 +232,7 @@ void cmMakefileExecutableTargetGenerator::WriteDeviceExecutableRule( const char* val = this->LocalGenerator->GetRuleLauncher( this->GeneratorTarget, "RULE_LAUNCH_LINK"); if (val && *val) { - launcher = val; - launcher += " "; + launcher = cmStrCat(val, ' '); } std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander( @@ -243,7 +241,7 @@ void cmMakefileExecutableTargetGenerator::WriteDeviceExecutableRule( // Expand placeholders in the commands. rulePlaceholderExpander->SetTargetImpLib(targetOutputReal); for (std::string& real_link_command : real_link_commands) { - real_link_command = launcher + real_link_command; + real_link_command = cmStrCat(launcher, real_link_command); rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, real_link_command, vars); } @@ -296,14 +294,13 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink) if (this->GeneratorTarget->IsAppBundleOnApple()) { this->OSXBundleGenerator->CreateAppBundle(targetNames.Output, outpath); } - outpath += "/"; + outpath += '/'; std::string outpathImp; if (relink) { - outpath = this->Makefile->GetCurrentBinaryDirectory(); - outpath += "/CMakeFiles"; - outpath += "/CMakeRelink.dir"; + outpath = cmStrCat(this->Makefile->GetCurrentBinaryDirectory(), + "/CMakeFiles/CMakeRelink.dir"); cmSystemTools::MakeDirectory(outpath); - outpath += "/"; + outpath += '/'; if (!targetNames.ImportLibrary.empty()) { outpathImp = outpath; } @@ -313,7 +310,7 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink) outpathImp = this->GeneratorTarget->GetDirectory( this->ConfigName, cmStateEnums::ImportLibraryArtifact); cmSystemTools::MakeDirectory(outpathImp); - outpathImp += "/"; + outpathImp += '/'; } } @@ -324,7 +321,7 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink) std::string pdbOutputPath = this->GeneratorTarget->GetPDBDirectory(this->ConfigName); cmSystemTools::MakeDirectory(pdbOutputPath); - pdbOutputPath += "/"; + pdbOutputPath += '/'; std::string targetFullPath = outpath + targetNames.Output; std::string targetFullPathReal = outpath + targetNames.Real; @@ -371,10 +368,8 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink) cmLocalUnixMakefileGenerator3::EchoProgress progress; this->MakeEchoProgress(progress); // Add the link message. - std::string buildEcho = "Linking "; - buildEcho += linkLanguage; - buildEcho += " executable "; - buildEcho += targetOutPath; + std::string buildEcho = + cmStrCat("Linking ", linkLanguage, " executable ", targetOutPath); this->LocalGenerator->AppendEcho( commands, buildEcho, cmLocalUnixMakefileGenerator3::EchoLink, &progress); } @@ -397,9 +392,8 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink) // Add symbol export flags if necessary. if (this->GeneratorTarget->IsExecutableWithExports()) { - std::string export_flag_var = "CMAKE_EXE_EXPORTS_"; - export_flag_var += linkLanguage; - export_flag_var += "_FLAG"; + std::string export_flag_var = + cmStrCat("CMAKE_EXE_EXPORTS_", linkLanguage, "_FLAG"); this->LocalGenerator->AppendFlags( linkFlags, this->Makefile->GetDefinition(export_flag_var)); } @@ -487,15 +481,14 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink) linkLanguage, this->ConfigName); std::string linkRule = this->GetLinkRule(linkRuleVar); std::vector<std::string> commands1; - cmSystemTools::ExpandListArgument(linkRule, real_link_commands); + cmExpandList(linkRule, real_link_commands); if (this->GeneratorTarget->IsExecutableWithExports()) { // If a separate rule for creating an import library is specified // add it now. - std::string implibRuleVar = "CMAKE_"; - implibRuleVar += linkLanguage; - implibRuleVar += "_CREATE_IMPORT_LIBRARY"; + std::string implibRuleVar = + cmStrCat("CMAKE_", linkLanguage, "_CREATE_IMPORT_LIBRARY"); if (const char* rule = this->Makefile->GetDefinition(implibRuleVar)) { - cmSystemTools::ExpandListArgument(rule, real_link_commands); + cmExpandList(rule, real_link_commands); } } @@ -590,10 +583,10 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink) vars.Manifests = manifests.c_str(); if (this->GeneratorTarget->GetPropertyAsBool("LINK_WHAT_YOU_USE")) { - std::string cmakeCommand = this->LocalGenerator->ConvertToOutputFormat( - cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL); - cmakeCommand += " -E __run_co_compile --lwyu="; - cmakeCommand += targetOutPathReal; + std::string cmakeCommand = + cmStrCat(this->LocalGenerator->ConvertToOutputFormat( + cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL), + " -E __run_co_compile --lwyu=", targetOutPathReal); real_link_commands.push_back(std::move(cmakeCommand)); } @@ -602,8 +595,7 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink) const char* val = this->LocalGenerator->GetRuleLauncher( this->GeneratorTarget, "RULE_LAUNCH_LINK"); if (val && *val) { - launcher = val; - launcher += " "; + launcher = cmStrCat(val, ' '); } std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander( @@ -612,7 +604,7 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink) // Expand placeholders in the commands. rulePlaceholderExpander->SetTargetImpLib(targetOutPathImport); for (std::string& real_link_command : real_link_commands) { - real_link_command = launcher + real_link_command; + real_link_command = cmStrCat(launcher, real_link_command); rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, real_link_command, vars); } @@ -639,10 +631,9 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink) // Add a rule to create necessary symlinks for the library. if (targetOutPath != targetOutPathReal) { - std::string symlink = "$(CMAKE_COMMAND) -E cmake_symlink_executable "; - symlink += targetOutPathReal; - symlink += " "; - symlink += targetOutPath; + std::string symlink = + cmStrCat("$(CMAKE_COMMAND) -E cmake_symlink_executable ", + targetOutPathReal, ' ', targetOutPath); commands1.push_back(std::move(symlink)); this->LocalGenerator->CreateCDCommand( commands1, this->Makefile->GetCurrentBinaryDirectory(), diff --git a/Source/cmMakefileLibraryTargetGenerator.cxx b/Source/cmMakefileLibraryTargetGenerator.cxx index bdde4b8..252279f 100644 --- a/Source/cmMakefileLibraryTargetGenerator.cxx +++ b/Source/cmMakefileLibraryTargetGenerator.cxx @@ -26,6 +26,7 @@ #include "cmStateDirectory.h" #include "cmStateSnapshot.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" cmMakefileLibraryTargetGenerator::cmMakefileLibraryTargetGenerator( @@ -162,9 +163,8 @@ void cmMakefileLibraryTargetGenerator::WriteSharedLibraryRules(bool relink) std::string linkLanguage = this->GeneratorTarget->GetLinkerLanguage(this->ConfigName); - std::string linkRuleVar = "CMAKE_"; - linkRuleVar += linkLanguage; - linkRuleVar += "_CREATE_SHARED_LIBRARY"; + std::string linkRuleVar = + cmStrCat("CMAKE_", linkLanguage, "_CREATE_SHARED_LIBRARY"); std::string extraFlags; this->GetTargetLinkFlags(extraFlags, linkLanguage); @@ -197,9 +197,8 @@ void cmMakefileLibraryTargetGenerator::WriteModuleLibraryRules(bool relink) std::string linkLanguage = this->GeneratorTarget->GetLinkerLanguage(this->ConfigName); - std::string linkRuleVar = "CMAKE_"; - linkRuleVar += linkLanguage; - linkRuleVar += "_CREATE_SHARED_MODULE"; + std::string linkRuleVar = + cmStrCat("CMAKE_", linkLanguage, "_CREATE_SHARED_MODULE"); std::string extraFlags; this->GetTargetLinkFlags(extraFlags, linkLanguage); @@ -220,9 +219,8 @@ void cmMakefileLibraryTargetGenerator::WriteFrameworkRules(bool relink) { std::string linkLanguage = this->GeneratorTarget->GetLinkerLanguage(this->ConfigName); - std::string linkRuleVar = "CMAKE_"; - linkRuleVar += linkLanguage; - linkRuleVar += "_CREATE_MACOSX_FRAMEWORK"; + std::string linkRuleVar = + cmStrCat("CMAKE_", linkLanguage, "_CREATE_MACOSX_FRAMEWORK"); std::string extraFlags; this->GetTargetLinkFlags(extraFlags, linkLanguage); @@ -235,7 +233,7 @@ void cmMakefileLibraryTargetGenerator::WriteFrameworkRules(bool relink) void cmMakefileLibraryTargetGenerator::WriteDeviceLibraryRules( const std::string& linkRuleVar, bool relink) { -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP // TODO: Merge the methods that call this method to avoid // code duplication. std::vector<std::string> commands; @@ -263,12 +261,13 @@ void cmMakefileLibraryTargetGenerator::WriteDeviceLibraryRules( cmLocalUnixMakefileGenerator3::EchoProgress progress; this->MakeEchoProgress(progress); // Add the link message. - std::string buildEcho = "Linking " + linkLanguage + " device code "; - buildEcho += this->LocalGenerator->ConvertToOutputFormat( - this->LocalGenerator->MaybeConvertToRelativePath( - this->LocalGenerator->GetCurrentBinaryDirectory(), - this->DeviceLinkObject), - cmOutputConverter::SHELL); + std::string buildEcho = + cmStrCat("Linking ", linkLanguage, " device code ", + this->LocalGenerator->ConvertToOutputFormat( + this->LocalGenerator->MaybeConvertToRelativePath( + this->LocalGenerator->GetCurrentBinaryDirectory(), + this->DeviceLinkObject), + cmOutputConverter::SHELL)); this->LocalGenerator->AppendEcho( commands, buildEcho, cmLocalUnixMakefileGenerator3::EchoLink, &progress); } @@ -359,8 +358,7 @@ void cmMakefileLibraryTargetGenerator::WriteDeviceLibraryRules( const char* val = this->LocalGenerator->GetRuleLauncher( this->GeneratorTarget, "RULE_LAUNCH_LINK"); if (val && *val) { - launcher = val; - launcher += " "; + launcher = cmStrCat(val, ' '); } std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander( @@ -369,11 +367,11 @@ void cmMakefileLibraryTargetGenerator::WriteDeviceLibraryRules( // Construct the main link rule and expand placeholders. rulePlaceholderExpander->SetTargetImpLib(targetOutputReal); std::string linkRule = this->GetLinkRule(linkRuleVar); - cmSystemTools::ExpandListArgument(linkRule, real_link_commands); + cmExpandList(linkRule, real_link_commands); // Expand placeholders. for (std::string& real_link_command : real_link_commands) { - real_link_command = launcher + real_link_command; + real_link_command = cmStrCat(launcher, real_link_command); rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, real_link_command, vars); } @@ -464,30 +462,29 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules( outpath = this->GeneratorTarget->GetDirectory(this->ConfigName); this->OSXBundleGenerator->CreateFramework(this->TargetNames.Output, outpath); - outpath += "/"; + outpath += '/'; } else if (this->GeneratorTarget->IsCFBundleOnApple()) { outpath = this->GeneratorTarget->GetDirectory(this->ConfigName); this->OSXBundleGenerator->CreateCFBundle(this->TargetNames.Output, outpath); - outpath += "/"; + outpath += '/'; } else if (relink) { - outpath = this->Makefile->GetCurrentBinaryDirectory(); - outpath += "/CMakeFiles"; - outpath += "/CMakeRelink.dir"; + outpath = cmStrCat(this->Makefile->GetCurrentBinaryDirectory(), + "/CMakeFiles/CMakeRelink.dir"); cmSystemTools::MakeDirectory(outpath); - outpath += "/"; + outpath += '/'; if (!this->TargetNames.ImportLibrary.empty()) { outpathImp = outpath; } } else { outpath = this->GeneratorTarget->GetDirectory(this->ConfigName); cmSystemTools::MakeDirectory(outpath); - outpath += "/"; + outpath += '/'; if (!this->TargetNames.ImportLibrary.empty()) { outpathImp = this->GeneratorTarget->GetDirectory( this->ConfigName, cmStateEnums::ImportLibraryArtifact); cmSystemTools::MakeDirectory(outpathImp); - outpathImp += "/"; + outpathImp += '/'; } } @@ -536,8 +533,7 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules( cmLocalUnixMakefileGenerator3::EchoProgress progress; this->MakeEchoProgress(progress); // Add the link message. - std::string buildEcho = "Linking "; - buildEcho += linkLanguage; + std::string buildEcho = cmStrCat("Linking ", linkLanguage); switch (this->GeneratorTarget->GetType()) { case cmStateEnums::STATIC_LIBRARY: buildEcho += " static library "; @@ -641,35 +637,32 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules( std::string::size_type archiveCommandLimit = std::string::npos; if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) { haveStaticLibraryRule = this->Makefile->IsDefinitionSet(linkRuleVar); - std::string arCreateVar = "CMAKE_"; - arCreateVar += linkLanguage; - arCreateVar += "_ARCHIVE_CREATE"; + std::string arCreateVar = + cmStrCat("CMAKE_", linkLanguage, "_ARCHIVE_CREATE"); arCreateVar = this->GeneratorTarget->GetFeatureSpecificLinkRuleVariable( arCreateVar, linkLanguage, this->ConfigName); if (const char* rule = this->Makefile->GetDefinition(arCreateVar)) { - cmSystemTools::ExpandListArgument(rule, archiveCreateCommands); + cmExpandList(rule, archiveCreateCommands); } - std::string arAppendVar = "CMAKE_"; - arAppendVar += linkLanguage; - arAppendVar += "_ARCHIVE_APPEND"; + std::string arAppendVar = + cmStrCat("CMAKE_", linkLanguage, "_ARCHIVE_APPEND"); arAppendVar = this->GeneratorTarget->GetFeatureSpecificLinkRuleVariable( arAppendVar, linkLanguage, this->ConfigName); if (const char* rule = this->Makefile->GetDefinition(arAppendVar)) { - cmSystemTools::ExpandListArgument(rule, archiveAppendCommands); + cmExpandList(rule, archiveAppendCommands); } - std::string arFinishVar = "CMAKE_"; - arFinishVar += linkLanguage; - arFinishVar += "_ARCHIVE_FINISH"; + std::string arFinishVar = + cmStrCat("CMAKE_", linkLanguage, "_ARCHIVE_FINISH"); arFinishVar = this->GeneratorTarget->GetFeatureSpecificLinkRuleVariable( arFinishVar, linkLanguage, this->ConfigName); if (const char* rule = this->Makefile->GetDefinition(arFinishVar)) { - cmSystemTools::ExpandListArgument(rule, archiveFinishCommands); + cmExpandList(rule, archiveFinishCommands); } } @@ -821,8 +814,7 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules( const char* val = this->LocalGenerator->GetRuleLauncher( this->GeneratorTarget, "RULE_LAUNCH_LINK"); if (val && *val) { - launcher = val; - launcher += " "; + launcher = cmStrCat(val, ' '); } std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander( @@ -879,19 +871,19 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules( } else { // Get the set of commands. std::string linkRule = this->GetLinkRule(linkRuleVar); - cmSystemTools::ExpandListArgument(linkRule, real_link_commands); + cmExpandList(linkRule, real_link_commands); if (this->GeneratorTarget->GetPropertyAsBool("LINK_WHAT_YOU_USE") && (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY)) { - std::string cmakeCommand = this->LocalGenerator->ConvertToOutputFormat( - cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL); - cmakeCommand += " -E __run_co_compile --lwyu="; - cmakeCommand += targetOutPathReal; + std::string cmakeCommand = cmStrCat( + this->LocalGenerator->ConvertToOutputFormat( + cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL), + " -E __run_co_compile --lwyu=", targetOutPathReal); real_link_commands.push_back(std::move(cmakeCommand)); } // Expand placeholders. for (std::string& real_link_command : real_link_commands) { - real_link_command = launcher + real_link_command; + real_link_command = cmStrCat(launcher, real_link_command); rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, real_link_command, vars); } @@ -921,12 +913,9 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules( // Frameworks are handled by cmOSXBundleGenerator. if (targetOutPath != targetOutPathReal && !this->GeneratorTarget->IsFrameworkOnApple()) { - std::string symlink = "$(CMAKE_COMMAND) -E cmake_symlink_library "; - symlink += targetOutPathReal; - symlink += " "; - symlink += targetOutPathSO; - symlink += " "; - symlink += targetOutPath; + std::string symlink = + cmStrCat("$(CMAKE_COMMAND) -E cmake_symlink_library ", targetOutPathReal, + ' ', targetOutPathSO, ' ', targetOutPath); commands1.push_back(std::move(symlink)); this->LocalGenerator->CreateCDCommand( commands1, this->Makefile->GetCurrentBinaryDirectory(), diff --git a/Source/cmMakefileTargetGenerator.cxx b/Source/cmMakefileTargetGenerator.cxx index 008248c..5477e48 100644 --- a/Source/cmMakefileTargetGenerator.cxx +++ b/Source/cmMakefileTargetGenerator.cxx @@ -49,7 +49,7 @@ cmMakefileTargetGenerator::cmMakefileTargetGenerator(cmGeneratorTarget* target) this->NoRuleMessages = false; if (const char* ruleStatus = cm->GetState()->GetGlobalProperty("RULE_MESSAGES")) { - this->NoRuleMessages = cmSystemTools::IsOff(ruleStatus); + this->NoRuleMessages = cmIsOff(ruleStatus); } MacOSXContentGenerator = new MacOSXContentGeneratorType(this); } @@ -90,8 +90,8 @@ void cmMakefileTargetGenerator::GetTargetLinkFlags( this->LocalGenerator->AppendFlags( flags, this->GeneratorTarget->GetProperty("LINK_FLAGS")); - std::string linkFlagsConfig = "LINK_FLAGS_"; - linkFlagsConfig += cmSystemTools::UpperCase(this->ConfigName); + std::string linkFlagsConfig = + cmStrCat("LINK_FLAGS_", cmSystemTools::UpperCase(this->ConfigName)); this->LocalGenerator->AppendFlags( flags, this->GeneratorTarget->GetProperty(linkFlagsConfig)); @@ -114,14 +114,13 @@ void cmMakefileTargetGenerator::CreateRuleFile() cmSystemTools::MakeDirectory(this->TargetBuildDirectoryFull); // Construct the rule file name. - this->BuildFileName = this->TargetBuildDirectory; - this->BuildFileName += "/build.make"; - this->BuildFileNameFull = this->TargetBuildDirectoryFull; - this->BuildFileNameFull += "/build.make"; + this->BuildFileName = cmStrCat(this->TargetBuildDirectory, "/build.make"); + this->BuildFileNameFull = + cmStrCat(this->TargetBuildDirectoryFull, "/build.make"); // Construct the rule file name. - this->ProgressFileNameFull = this->TargetBuildDirectoryFull; - this->ProgressFileNameFull += "/progress.make"; + this->ProgressFileNameFull = + cmStrCat(this->TargetBuildDirectoryFull, "/progress.make"); // reset the progress count this->NumberOfProgressActions = 0; @@ -159,10 +158,9 @@ void cmMakefileTargetGenerator::WriteTargetBuildRules() std::vector<std::string> files; cmGeneratorExpression ge; std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(prop_value); - cmSystemTools::ExpandListArgument( - cge->Evaluate(this->LocalGenerator, config, false, this->GeneratorTarget, - nullptr, nullptr), - files); + cmExpandList(cge->Evaluate(this->LocalGenerator, config, false, + this->GeneratorTarget, nullptr, nullptr), + files); return files; }; @@ -187,7 +185,7 @@ void cmMakefileTargetGenerator::WriteTargetBuildRules() // add custom commands to the clean rules? const char* clean_no_custom = this->Makefile->GetProperty("CLEAN_NO_CUSTOM"); - bool clean = cmSystemTools::IsOff(clean_no_custom); + bool clean = cmIsOff(clean_no_custom); // First generate the object rule files. Save a list of all object // files for this target. @@ -261,8 +259,8 @@ void cmMakefileTargetGenerator::WriteCommonCodeRules() : ""); // Include the dependencies for the target. - std::string dependFileNameFull = this->TargetBuildDirectoryFull; - dependFileNameFull += "/depend.make"; + std::string dependFileNameFull = + cmStrCat(this->TargetBuildDirectoryFull, "/depend.make"); *this->BuildFileStream << "# Include any dependencies generated for this target.\n" << this->GlobalGenerator->IncludeDirective << " " << root @@ -296,8 +294,8 @@ void cmMakefileTargetGenerator::WriteCommonCodeRules() // Open the flags file. This should be copy-if-different because the // rules may depend on this file itself. - this->FlagFileNameFull = this->TargetBuildDirectoryFull; - this->FlagFileNameFull += "/flags.make"; + this->FlagFileNameFull = + cmStrCat(this->TargetBuildDirectoryFull, "/flags.make"); this->FlagFileStream = new cmGeneratedFileStream(this->FlagFileNameFull, false, this->GlobalGenerator->GetMakefileEncoding()); @@ -326,9 +324,7 @@ void cmMakefileTargetGenerator::WriteTargetLanguageFlags() // put the compiler in the rules.make file so that if it changes // things rebuild for (std::string const& language : languages) { - std::string compiler = "CMAKE_"; - compiler += language; - compiler += "_COMPILER"; + std::string compiler = cmStrCat("CMAKE_", language, "_COMPILER"); *this->FlagFileStream << "# compile " << language << " with " << this->Makefile->GetSafeDefinition(compiler) << "\n"; @@ -363,9 +359,8 @@ void cmMakefileTargetGenerator::MacOSXContentGeneratorType::operator()( std::string const& input = source.GetFullPath(); // Get the output file location. - std::string output = macdir; - output += "/"; - output += cmSystemTools::GetFilenameName(input); + std::string output = + cmStrCat(macdir, '/', cmSystemTools::GetFilenameName(input)); this->Generator->CleanFiles.insert( this->Generator->LocalGenerator->MaybeConvertToRelativePath( this->Generator->LocalGenerator->GetCurrentBinaryDirectory(), output)); @@ -376,16 +371,16 @@ void cmMakefileTargetGenerator::MacOSXContentGeneratorType::operator()( std::vector<std::string> depends; std::vector<std::string> commands; depends.push_back(input); - std::string copyEcho = "Copying OS X content "; - copyEcho += output; + std::string copyEcho = cmStrCat("Copying OS X content ", output); this->Generator->LocalGenerator->AppendEcho( commands, copyEcho, cmLocalUnixMakefileGenerator3::EchoBuild); - std::string copyCommand = "$(CMAKE_COMMAND) -E copy "; - copyCommand += this->Generator->LocalGenerator->ConvertToOutputFormat( - input, cmOutputConverter::SHELL); - copyCommand += " "; - copyCommand += this->Generator->LocalGenerator->ConvertToOutputFormat( - output, cmOutputConverter::SHELL); + std::string copyCommand = + cmStrCat("$(CMAKE_COMMAND) -E copy ", + this->Generator->LocalGenerator->ConvertToOutputFormat( + input, cmOutputConverter::SHELL), + ' ', + this->Generator->LocalGenerator->ConvertToOutputFormat( + output, cmOutputConverter::SHELL)); commands.push_back(std::move(copyCommand)); this->Generator->LocalGenerator->WriteMakeRule( *this->Generator->BuildFileStream, nullptr, output, depends, commands, @@ -408,9 +403,8 @@ void cmMakefileTargetGenerator::WriteObjectRuleFiles( std::string const& objectName = this->GeneratorTarget->GetObjectName(&source); std::string obj = - this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget); - obj += "/"; - obj += objectName; + cmStrCat(this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget), + '/', objectName); // Avoid generating duplicate rules. if (this->ObjectFiles.find(obj) == this->ObjectFiles.end()) { @@ -446,9 +440,8 @@ void cmMakefileTargetGenerator::WriteObjectRuleFiles( this->WriteObjectBuildFile(obj, lang, source, depends); // The object file should be checked for dependency integrity. - std::string objFullPath = this->LocalGenerator->GetCurrentBinaryDirectory(); - objFullPath += "/"; - objFullPath += obj; + std::string objFullPath = + cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(), '/', obj); objFullPath = cmSystemTools::CollapseFullPath(objFullPath); std::string srcFullPath = cmSystemTools::CollapseFullPath(source.GetFullPath()); @@ -468,17 +461,15 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile( // generate the depend scanning rule this->WriteObjectDependRules(source, depends); - std::string relativeObj = this->LocalGenerator->GetHomeRelativeOutputPath(); - relativeObj += obj; + std::string relativeObj = + cmStrCat(this->LocalGenerator->GetHomeRelativeOutputPath(), obj); // Write the build rule. // Build the set of compiler flags. std::string flags; // Add language-specific flags. - std::string langFlags = "$("; - langFlags += lang; - langFlags += "_FLAGS)"; + std::string langFlags = cmStrCat("$(", lang, "_FLAGS)"); this->LocalGenerator->AppendFlags(flags, langFlags); std::string config = this->LocalGenerator->GetConfigName(); @@ -540,8 +531,7 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile( << "_DEFINES = " << evaluatedDefs << "\n" << "\n"; } - std::string defPropName = "COMPILE_DEFINITIONS_"; - defPropName += configUpper; + std::string defPropName = cmStrCat("COMPILE_DEFINITIONS_", configUpper); if (const char* config_compile_defs = source.GetProperty(defPropName)) { const std::string& evaluatedDefs = genexInterpreter.Evaluate(config_compile_defs, COMPILE_DEFINITIONS); @@ -565,10 +555,8 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile( if (!this->NoRuleMessages) { cmLocalUnixMakefileGenerator3::EchoProgress progress; this->MakeEchoProgress(progress); - std::string buildEcho = "Building "; - buildEcho += lang; - buildEcho += " object "; - buildEcho += relativeObj; + std::string buildEcho = + cmStrCat("Building ", lang, " object ", relativeObj); this->LocalGenerator->AppendEcho(commands, buildEcho, cmLocalUnixMakefileGenerator3::EchoBuild, &progress); @@ -588,9 +576,8 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile( targetFullPathReal = this->GeneratorTarget->GetFullPath( this->ConfigName, cmStateEnums::RuntimeBinaryArtifact, true); targetFullPathPDB = - this->GeneratorTarget->GetPDBDirectory(this->ConfigName); - targetFullPathPDB += "/"; - targetFullPathPDB += this->GeneratorTarget->GetPDBName(this->ConfigName); + cmStrCat(this->GeneratorTarget->GetPDBDirectory(this->ConfigName), '/', + this->GeneratorTarget->GetPDBName(this->ConfigName)); } targetOutPathReal = this->LocalGenerator->ConvertToOutputFormat( @@ -639,9 +626,7 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile( vars.ObjectFileDir = objectFileDir.c_str(); vars.Flags = flags.c_str(); - std::string definesString = "$("; - definesString += lang; - definesString += "_DEFINES)"; + std::string definesString = cmStrCat("$(", lang, "_DEFINES)"); this->LocalGenerator->JoinDefines(defines, definesString, lang); @@ -680,12 +665,12 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile( } const std::string& compileRule = this->Makefile->GetRequiredDefinition(cmdVar); - cmSystemTools::ExpandListArgument(compileRule, compileCommands); + cmExpandList(compileRule, compileCommands); } else { const std::string cmdVar = "CMAKE_" + lang + "_COMPILE_OBJECT"; const std::string& compileRule = this->Makefile->GetRequiredDefinition(cmdVar); - cmSystemTools::ExpandListArgument(compileRule, compileCommands); + cmExpandList(compileRule, compileCommands); } if (this->Makefile->IsOn("CMAKE_EXPORT_COMPILE_COMMANDS") && @@ -783,7 +768,7 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile( // goes to the beginning of the command line. if (!compileCommands.empty() && !compilerLauncher.empty()) { std::vector<std::string> args; - cmSystemTools::ExpandListArgument(compilerLauncher, args, true); + cmExpandList(compilerLauncher, args, true); if (!args.empty()) { args[0] = this->LocalGenerator->ConvertToOutputFormat( args[0], cmOutputConverter::SHELL); @@ -799,14 +784,13 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile( const char* val = this->LocalGenerator->GetRuleLauncher( this->GeneratorTarget, "RULE_LAUNCH_COMPILE"); if (val && *val) { - launcher = val; - launcher += " "; + launcher = cmStrCat(val, ' '); } } // Expand placeholders in the commands. for (std::string& compileCommand : compileCommands) { - compileCommand = launcher + compileCommand; + compileCommand = cmStrCat(launcher, compileCommand); rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, compileCommand, vars); } @@ -822,7 +806,7 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile( std::vector<std::string> outputs(1, relativeObj); if (const char* extra_outputs_str = source.GetProperty("OBJECT_OUTPUTS")) { // Register these as extra files to clean. - cmSystemTools::ExpandListArgument(extra_outputs_str, outputs); + cmExpandList(extra_outputs_str, outputs); this->CleanFiles.insert(outputs.begin() + 1, outputs.end()); } @@ -847,20 +831,17 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile( std::string relativeObjI = relativeObjBase + ".i"; std::string objI = objBase + ".i"; - std::string preprocessEcho = "Preprocessing "; - preprocessEcho += lang; - preprocessEcho += " source to "; - preprocessEcho += objI; + std::string preprocessEcho = + cmStrCat("Preprocessing ", lang, " source to ", objI); this->LocalGenerator->AppendEcho( commands, preprocessEcho, cmLocalUnixMakefileGenerator3::EchoBuild); - std::string preprocessRuleVar = "CMAKE_"; - preprocessRuleVar += lang; - preprocessRuleVar += "_CREATE_PREPROCESSED_SOURCE"; + std::string preprocessRuleVar = + cmStrCat("CMAKE_", lang, "_CREATE_PREPROCESSED_SOURCE"); if (const char* preprocessRule = this->Makefile->GetDefinition(preprocessRuleVar)) { std::vector<std::string> preprocessCommands; - cmSystemTools::ExpandListArgument(preprocessRule, preprocessCommands); + cmExpandList(preprocessRule, preprocessCommands); std::string shellObjI = this->LocalGenerator->ConvertToOutputFormat( objI, cmOutputConverter::SHELL); @@ -879,8 +860,9 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile( this->LocalGenerator->GetBinaryDirectory()); cmAppend(commands, preprocessCommands); } else { - std::string cmd = "$(CMAKE_COMMAND) -E cmake_unimplemented_variable "; - cmd += preprocessRuleVar; + std::string cmd = + cmStrCat("$(CMAKE_COMMAND) -E cmake_unimplemented_variable ", + preprocessRuleVar); commands.push_back(std::move(cmd)); } @@ -894,20 +876,17 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile( std::string relativeObjS = relativeObjBase + ".s"; std::string objS = objBase + ".s"; - std::string assemblyEcho = "Compiling "; - assemblyEcho += lang; - assemblyEcho += " source to assembly "; - assemblyEcho += objS; + std::string assemblyEcho = + cmStrCat("Compiling ", lang, " source to assembly ", objS); this->LocalGenerator->AppendEcho( commands, assemblyEcho, cmLocalUnixMakefileGenerator3::EchoBuild); - std::string assemblyRuleVar = "CMAKE_"; - assemblyRuleVar += lang; - assemblyRuleVar += "_CREATE_ASSEMBLY_SOURCE"; + std::string assemblyRuleVar = + cmStrCat("CMAKE_", lang, "_CREATE_ASSEMBLY_SOURCE"); if (const char* assemblyRule = this->Makefile->GetDefinition(assemblyRuleVar)) { std::vector<std::string> assemblyCommands; - cmSystemTools::ExpandListArgument(assemblyRule, assemblyCommands); + cmExpandList(assemblyRule, assemblyCommands); std::string shellObjS = this->LocalGenerator->ConvertToOutputFormat( objS, cmOutputConverter::SHELL); @@ -925,8 +904,9 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile( this->LocalGenerator->GetBinaryDirectory()); cmAppend(commands, assemblyCommands); } else { - std::string cmd = "$(CMAKE_COMMAND) -E cmake_unimplemented_variable "; - cmd += assemblyRuleVar; + std::string cmd = + cmStrCat("$(CMAKE_COMMAND) -E cmake_unimplemented_variable ", + assemblyRuleVar); commands.push_back(std::move(cmd)); } @@ -943,9 +923,9 @@ void cmMakefileTargetGenerator::WriteTargetCleanRules() std::vector<std::string> commands; // Construct the clean target name. - std::string cleanTarget = - this->LocalGenerator->GetRelativeTargetDirectory(this->GeneratorTarget); - cleanTarget += "/clean"; + std::string cleanTarget = cmStrCat( + this->LocalGenerator->GetRelativeTargetDirectory(this->GeneratorTarget), + "/clean"); // Construct the clean command. this->LocalGenerator->AppendCleanCommand(commands, this->CleanFiles, @@ -1029,8 +1009,7 @@ void cmMakefileTargetGenerator::WriteTargetDependRules() // must write the targets depend info file std::string dir = this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget); - this->InfoFileNameFull = dir; - this->InfoFileNameFull += "/DependInfo.cmake"; + this->InfoFileNameFull = cmStrCat(dir, "/DependInfo.cmake"); this->InfoFileNameFull = this->LocalGenerator->ConvertToFullPath(this->InfoFileNameFull); this->InfoFileStream = new cmGeneratedFileStream(this->InfoFileNameFull); @@ -1089,9 +1068,9 @@ void cmMakefileTargetGenerator::WriteTargetDependRules() std::vector<std::string> commands; // Construct the name of the dependency generation target. - std::string depTarget = - this->LocalGenerator->GetRelativeTargetDirectory(this->GeneratorTarget); - depTarget += "/depend"; + std::string depTarget = cmStrCat( + this->LocalGenerator->GetRelativeTargetDirectory(this->GeneratorTarget), + "/depend"); // Add a command to call CMake to scan dependencies. CMake will // touch the corresponding depends file after scanning dependencies. @@ -1182,7 +1161,7 @@ void cmMakefileTargetGenerator::WriteObjectDependRules( // shared between the object file and dependency scanning rule. depends.push_back(source.GetFullPath()); if (const char* objectDeps = source.GetProperty("OBJECT_DEPENDS")) { - cmSystemTools::ExpandListArgument(objectDeps, depends); + cmExpandList(objectDeps, depends); } } @@ -1236,8 +1215,8 @@ void cmMakefileTargetGenerator::GenerateCustomRuleFile( void cmMakefileTargetGenerator::MakeEchoProgress( cmLocalUnixMakefileGenerator3::EchoProgress& progress) const { - progress.Dir = this->LocalGenerator->GetBinaryDirectory(); - progress.Dir += "/CMakeFiles"; + progress.Dir = + cmStrCat(this->LocalGenerator->GetBinaryDirectory(), "/CMakeFiles"); std::ostringstream progressArg; progressArg << "$(CMAKE_PROGRESS_" << this->NumberOfProgressActions << ")"; progress.Arg = progressArg.str(); @@ -1371,8 +1350,8 @@ void cmMakefileTargetGenerator::WriteTargetDriverRule( // Compute the name of the driver target. std::string dir = this->LocalGenerator->GetRelativeTargetDirectory(this->GeneratorTarget); - std::string buildTargetRuleName = dir; - buildTargetRuleName += relink ? "/preinstall" : "/build"; + std::string buildTargetRuleName = + cmStrCat(dir, relink ? "/preinstall" : "/build"); buildTargetRuleName = this->LocalGenerator->MaybeConvertToRelativePath( this->LocalGenerator->GetBinaryDirectory(), buildTargetRuleName); @@ -1427,8 +1406,7 @@ void cmMakefileTargetGenerator::AppendObjectDepends( std::string const& relPath = this->LocalGenerator->GetHomeRelativeOutputPath(); for (std::string const& obj : this->Objects) { - std::string objTarget = relPath; - objTarget += obj; + std::string objTarget = cmStrCat(relPath, obj); depends.push_back(std::move(objTarget)); } @@ -1474,9 +1452,9 @@ std::string cmMakefileTargetGenerator::GetLinkRule( { std::string linkRule = this->Makefile->GetRequiredDefinition(linkRuleVar); if (this->GeneratorTarget->HasImplibGNUtoMS(this->ConfigName)) { - std::string ruleVar = "CMAKE_"; - ruleVar += this->GeneratorTarget->GetLinkerLanguage(this->ConfigName); - ruleVar += "_GNUtoMS_RULE"; + std::string ruleVar = cmStrCat( + "CMAKE_", this->GeneratorTarget->GetLinkerLanguage(this->ConfigName), + "_GNUtoMS_RULE"); if (const char* rule = this->Makefile->GetDefinition(ruleVar)) { linkRule += rule; } @@ -1497,9 +1475,8 @@ void cmMakefileTargetGenerator::CreateLinkScript( std::vector<std::string>& makefile_depends) { // Create the link script file. - std::string linkScriptName = this->TargetBuildDirectoryFull; - linkScriptName += "/"; - linkScriptName += name; + std::string linkScriptName = + cmStrCat(this->TargetBuildDirectoryFull, '/', name); cmGeneratedFileStream linkScriptStream(linkScriptName); linkScriptStream.SetCopyIfDifferent(true); for (std::string const& link_command : link_commands) { @@ -1511,12 +1488,13 @@ void cmMakefileTargetGenerator::CreateLinkScript( } // Create the makefile command to invoke the link script. - std::string link_command = "$(CMAKE_COMMAND) -E cmake_link_script "; - link_command += this->LocalGenerator->ConvertToOutputFormat( - this->LocalGenerator->MaybeConvertToRelativePath( - this->LocalGenerator->GetCurrentBinaryDirectory(), linkScriptName), - cmOutputConverter::SHELL); - link_command += " --verbose=$(VERBOSE)"; + std::string link_command = cmStrCat( + "$(CMAKE_COMMAND) -E cmake_link_script ", + this->LocalGenerator->ConvertToOutputFormat( + this->LocalGenerator->MaybeConvertToRelativePath( + this->LocalGenerator->GetCurrentBinaryDirectory(), linkScriptName), + cmOutputConverter::SHELL), + " --verbose=$(VERBOSE)"); makefile_commands.push_back(std::move(link_command)); makefile_depends.push_back(std::move(linkScriptName)); } @@ -1529,7 +1507,7 @@ bool cmMakefileTargetGenerator::CheckUseResponseFileForObjects( "CMAKE_" + l + "_USE_RESPONSE_FILE_FOR_OBJECTS"; if (const char* val = this->Makefile->GetDefinition(responseVar)) { if (*val) { - return cmSystemTools::IsOn(val); + return cmIsOn(val); } } @@ -1568,7 +1546,7 @@ bool cmMakefileTargetGenerator::CheckUseResponseFileForLibraries( "CMAKE_" + l + "_USE_RESPONSE_FILE_FOR_LIBRARIES"; if (const char* val = this->Makefile->GetDefinition(responseVar)) { if (*val) { - return cmSystemTools::IsOn(val); + return cmIsOn(val); } } @@ -1581,9 +1559,8 @@ std::string cmMakefileTargetGenerator::CreateResponseFile( std::vector<std::string>& makefile_depends) { // Create the response file. - std::string responseFileNameFull = this->TargetBuildDirectoryFull; - responseFileNameFull += "/"; - responseFileNameFull += name; + std::string responseFileNameFull = + cmStrCat(this->TargetBuildDirectoryFull, '/', name); cmGeneratedFileStream responseStream(responseFileNameFull); responseStream.SetCopyIfDifferent(true); responseStream << options << "\n"; @@ -1593,9 +1570,8 @@ std::string cmMakefileTargetGenerator::CreateResponseFile( makefile_depends.push_back(std::move(responseFileNameFull)); // Construct the name to be used on the command line. - std::string responseFileName = this->TargetBuildDirectory; - responseFileName += "/"; - responseFileName += name; + std::string responseFileName = + cmStrCat(this->TargetBuildDirectory, '/', name); return responseFileName; } @@ -1627,10 +1603,9 @@ void cmMakefileTargetGenerator::CreateLinkLibs( if (useResponseFile && linkLibs.find_first_not_of(' ') != std::string::npos) { // Lookup the response file reference flag. - std::string responseFlagVar = "CMAKE_"; - responseFlagVar += - this->GeneratorTarget->GetLinkerLanguage(this->ConfigName); - responseFlagVar += "_RESPONSE_FILE_LINK_FLAG"; + std::string responseFlagVar = cmStrCat( + "CMAKE_", this->GeneratorTarget->GetLinkerLanguage(this->ConfigName), + "_RESPONSE_FILE_LINK_FLAG"); const char* responseFlag = this->Makefile->GetDefinition(responseFlagVar); if (!responseFlag) { responseFlag = "@"; @@ -1641,9 +1616,9 @@ void cmMakefileTargetGenerator::CreateLinkLibs( this->CreateResponseFile("linklibs.rsp", linkLibs, makefile_depends); // Reference the response file. - linkLibs = responseFlag; - linkLibs += this->LocalGenerator->ConvertToOutputFormat( - link_rsp, cmOutputConverter::SHELL); + linkLibs = cmStrCat(responseFlag, + this->LocalGenerator->ConvertToOutputFormat( + link_rsp, cmOutputConverter::SHELL)); } } @@ -1665,10 +1640,9 @@ void cmMakefileTargetGenerator::CreateObjectLists( this->WriteObjectsStrings(object_strings, responseFileLimit); // Lookup the response file reference flag. - std::string responseFlagVar = "CMAKE_"; - responseFlagVar += - this->GeneratorTarget->GetLinkerLanguage(this->ConfigName); - responseFlagVar += "_RESPONSE_FILE_LINK_FLAG"; + std::string responseFlagVar = cmStrCat( + "CMAKE_", this->GeneratorTarget->GetLinkerLanguage(this->ConfigName), + "_RESPONSE_FILE_LINK_FLAG"); const char* responseFlag = this->Makefile->GetDefinition(responseFlagVar); if (!responseFlag) { responseFlag = "@"; @@ -1701,20 +1675,16 @@ void cmMakefileTargetGenerator::CreateObjectLists( buildObjs = objStrings[0]; } } else { - buildObjs = "$("; - buildObjs += variableName; - buildObjs += ") $("; - buildObjs += variableNameExternal; - buildObjs += ")"; + buildObjs = + cmStrCat("$(", variableName, ") $(", variableNameExternal, ')'); } } void cmMakefileTargetGenerator::AddIncludeFlags(std::string& flags, const std::string& lang) { - std::string responseVar = "CMAKE_"; - responseVar += lang; - responseVar += "_USE_RESPONSE_FILE_FOR_INCLUDES"; + std::string responseVar = + cmStrCat("CMAKE_", lang, "_USE_RESPONSE_FILE_FOR_INCLUDES"); bool useResponseFile = this->Makefile->IsOn(responseVar); std::vector<std::string> includes; @@ -1737,9 +1707,7 @@ void cmMakefileTargetGenerator::AddIncludeFlags(std::string& flags, if (responseFlag.empty()) { responseFlag = "@"; } - std::string name = "includes_"; - name += lang; - name += ".rsp"; + std::string name = cmStrCat("includes_", lang, ".rsp"); std::string arg = std::move(responseFlag) + this->CreateResponseFile(name.c_str(), includeFlags, this->FlagFileDepends[lang]); @@ -1758,14 +1726,14 @@ void cmMakefileTargetGenerator::GenDefFile( return; } std::string cmd = cmSystemTools::GetCMakeCommand(); - cmd = - this->LocalGenerator->ConvertToOutputFormat(cmd, cmOutputConverter::SHELL); - cmd += " -E __create_def "; - cmd += this->LocalGenerator->ConvertToOutputFormat( - this->LocalGenerator->MaybeConvertToRelativePath( - this->LocalGenerator->GetCurrentBinaryDirectory(), mdi->DefFile), - cmOutputConverter::SHELL); - cmd += " "; + cmd = cmStrCat( + this->LocalGenerator->ConvertToOutputFormat(cmd, cmOutputConverter::SHELL), + " -E __create_def ", + this->LocalGenerator->ConvertToOutputFormat( + this->LocalGenerator->MaybeConvertToRelativePath( + this->LocalGenerator->GetCurrentBinaryDirectory(), mdi->DefFile), + cmOutputConverter::SHELL), + ' '); std::string objlist_file = mdi->DefFile + ".objs"; cmd += this->LocalGenerator->ConvertToOutputFormat( this->LocalGenerator->MaybeConvertToRelativePath( diff --git a/Source/cmMarkAsAdvancedCommand.cxx b/Source/cmMarkAsAdvancedCommand.cxx index 45c59b9..ca46e14 100644 --- a/Source/cmMarkAsAdvancedCommand.cxx +++ b/Source/cmMarkAsAdvancedCommand.cxx @@ -2,20 +2,19 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmMarkAsAdvancedCommand.h" +#include "cmExecutionStatus.h" #include "cmMakefile.h" #include "cmState.h" #include "cmStateTypes.h" #include "cmSystemTools.h" #include "cmake.h" -class cmExecutionStatus; - // cmMarkAsAdvancedCommand -bool cmMarkAsAdvancedCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus&) +bool cmMarkAsAdvancedCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.empty()) { - this->SetError("called with incorrect number of arguments"); + status.SetError("called with incorrect number of arguments"); return false; } @@ -31,9 +30,9 @@ bool cmMarkAsAdvancedCommand::InitialPass(std::vector<std::string> const& args, } for (; i < args.size(); ++i) { std::string const& variable = args[i]; - cmState* state = this->Makefile->GetState(); + cmState* state = status.GetMakefile().GetState(); if (!state->GetCacheEntryValue(variable)) { - this->Makefile->GetCMakeInstance()->AddCacheEntry( + status.GetMakefile().GetCMakeInstance()->AddCacheEntry( variable, nullptr, nullptr, cmStateEnums::UNINITIALIZED); overwrite = true; } diff --git a/Source/cmMarkAsAdvancedCommand.h b/Source/cmMarkAsAdvancedCommand.h index e367c46..de7bf08 100644 --- a/Source/cmMarkAsAdvancedCommand.h +++ b/Source/cmMarkAsAdvancedCommand.h @@ -8,34 +8,14 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -/** \class cmMarkAsAdvancedCommand +/** * \brief mark_as_advanced command * * cmMarkAsAdvancedCommand implements the mark_as_advanced CMake command */ -class cmMarkAsAdvancedCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmMarkAsAdvancedCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; -}; +bool cmMarkAsAdvancedCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmMathCommand.cxx b/Source/cmMathCommand.cxx index 48b9a27..83c22aa 100644 --- a/Source/cmMathCommand.cxx +++ b/Source/cmMathCommand.cxx @@ -2,6 +2,7 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmMathCommand.h" +#include "cmExecutionStatus.h" #include "cmExprParserHelper.h" #include "cmMakefile.h" #include "cmMessageType.h" @@ -9,28 +10,33 @@ #include <stdio.h> -class cmExecutionStatus; +namespace { +bool HandleExprCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); +} -bool cmMathCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus&) +bool cmMathCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.empty()) { - this->SetError("must be called with at least one argument."); + status.SetError("must be called with at least one argument."); return false; } const std::string& subCommand = args[0]; if (subCommand == "EXPR") { - return this->HandleExprCommand(args); + return HandleExprCommand(args, status); } std::string e = "does not recognize sub-command " + subCommand; - this->SetError(e); + status.SetError(e); return false; } -bool cmMathCommand::HandleExprCommand(std::vector<std::string> const& args) +namespace { +bool HandleExprCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if ((args.size() != 3) && (args.size() != 5)) { - this->SetError("EXPR called with incorrect arguments."); + status.SetError("EXPR called with incorrect arguments."); return false; } @@ -46,7 +52,7 @@ bool cmMathCommand::HandleExprCommand(std::vector<std::string> const& args) size_t argumentIndex = 3; NumericFormat outputFormat = NumericFormat::UNINITIALIZED; - this->Makefile->AddDefinition(outputVariable, "ERROR"); + status.GetMakefile().AddDefinition(outputVariable, "ERROR"); if (argumentIndex < args.size()) { const std::string messageHint = "sub-command EXPR "; @@ -61,19 +67,19 @@ bool cmMathCommand::HandleExprCommand(std::vector<std::string> const& args) } else { std::string error = messageHint + "value \"" + argument + "\" for option \"" + option + "\" is invalid."; - this->SetError(error); + status.SetError(error); return false; } } else { std::string error = messageHint + "missing argument for option \"" + option + "\"."; - this->SetError(error); + status.SetError(error); return false; } } else { std::string error = messageHint + "option \"" + option + "\" is unknown."; - this->SetError(error); + status.SetError(error); return false; } } @@ -84,7 +90,7 @@ bool cmMathCommand::HandleExprCommand(std::vector<std::string> const& args) cmExprParserHelper helper; if (!helper.ParseString(expression.c_str(), 0)) { - this->SetError(helper.GetError()); + status.SetError(helper.GetError()); return false; } @@ -104,9 +110,10 @@ bool cmMathCommand::HandleExprCommand(std::vector<std::string> const& args) std::string const& w = helper.GetWarning(); if (!w.empty()) { - this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, w); + status.GetMakefile().IssueMessage(MessageType::AUTHOR_WARNING, w); } - this->Makefile->AddDefinition(outputVariable, buffer); + status.GetMakefile().AddDefinition(outputVariable, buffer); return true; } +} diff --git a/Source/cmMathCommand.h b/Source/cmMathCommand.h index 23633d3..ac1957c 100644 --- a/Source/cmMathCommand.h +++ b/Source/cmMathCommand.h @@ -8,33 +8,10 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; /// Mathematical expressions: math(EXPR ...) command. -class cmMathCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmMathCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; - -protected: - bool HandleExprCommand(std::vector<std::string> const& args); -}; +bool cmMathCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmMessageCommand.cxx b/Source/cmMessageCommand.cxx index 66d3c88..3f33312 100644 --- a/Source/cmMessageCommand.cxx +++ b/Source/cmMessageCommand.cxx @@ -2,6 +2,7 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmMessageCommand.h" +#include "cmExecutionStatus.h" #include "cmMakefile.h" #include "cmMessageType.h" #include "cmMessenger.h" @@ -12,14 +13,12 @@ #include <cassert> -class cmExecutionStatus; - // cmLibraryCommand -bool cmMessageCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus&) +bool cmMessageCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.empty()) { - this->SetError("called with incorrect number of arguments"); + status.SetError("called with incorrect number of arguments"); return false; } auto i = args.cbegin(); @@ -41,12 +40,13 @@ bool cmMessageCommand::InitialPass(std::vector<std::string> const& args, level = cmake::LogLevel::LOG_WARNING; ++i; } else if (*i == "AUTHOR_WARNING") { - if (this->Makefile->IsSet("CMAKE_SUPPRESS_DEVELOPER_ERRORS") && - !this->Makefile->IsOn("CMAKE_SUPPRESS_DEVELOPER_ERRORS")) { + if (status.GetMakefile().IsSet("CMAKE_SUPPRESS_DEVELOPER_ERRORS") && + !status.GetMakefile().IsOn("CMAKE_SUPPRESS_DEVELOPER_ERRORS")) { fatal = true; type = MessageType::AUTHOR_ERROR; level = cmake::LogLevel::LOG_ERROR; - } else if (!this->Makefile->IsOn("CMAKE_SUPPRESS_DEVELOPER_WARNINGS")) { + } else if (!status.GetMakefile().IsOn( + "CMAKE_SUPPRESS_DEVELOPER_WARNINGS")) { type = MessageType::AUTHOR_WARNING; level = cmake::LogLevel::LOG_WARNING; } else { @@ -66,12 +66,12 @@ bool cmMessageCommand::InitialPass(std::vector<std::string> const& args, level = cmake::LogLevel::LOG_TRACE; ++i; } else if (*i == "DEPRECATION") { - if (this->Makefile->IsOn("CMAKE_ERROR_DEPRECATED")) { + if (status.GetMakefile().IsOn("CMAKE_ERROR_DEPRECATED")) { fatal = true; type = MessageType::DEPRECATION_ERROR; level = cmake::LogLevel::LOG_ERROR; - } else if ((!this->Makefile->IsSet("CMAKE_WARN_DEPRECATED") || - this->Makefile->IsOn("CMAKE_WARN_DEPRECATED"))) { + } else if ((!status.GetMakefile().IsSet("CMAKE_WARN_DEPRECATED") || + status.GetMakefile().IsOn("CMAKE_WARN_DEPRECATED"))) { type = MessageType::DEPRECATION_WARNING; level = cmake::LogLevel::LOG_WARNING; } else { @@ -89,7 +89,7 @@ bool cmMessageCommand::InitialPass(std::vector<std::string> const& args, assert("Message log level expected to be set" && level != cmake::LogLevel::LOG_UNDEFINED); - auto desiredLevel = this->Makefile->GetCMakeInstance()->GetLogLevel(); + auto desiredLevel = status.GetMakefile().GetCMakeInstance()->GetLogLevel(); assert("Expected a valid log level here" && desiredLevel != cmake::LogLevel::LOG_UNDEFINED); @@ -104,10 +104,9 @@ bool cmMessageCommand::InitialPass(std::vector<std::string> const& args, // Check if any indentation has requested: // `CMAKE_MESSAGE_INDENT` is a list of "padding" pieces // to be joined and prepended to the message lines. - auto indent = - cmJoin(cmSystemTools::ExpandedListArgument( - this->Makefile->GetSafeDefinition("CMAKE_MESSAGE_INDENT")), - ""); + auto indent = cmJoin(cmExpandedList(status.GetMakefile().GetSafeDefinition( + "CMAKE_MESSAGE_INDENT")), + ""); // Make every line of the `message` indented // NOTE Can't reuse `cmDocumentationFormatter::PrintPreformatted` // here cuz it appends `\n` to the EOM ;-( @@ -119,8 +118,8 @@ bool cmMessageCommand::InitialPass(std::vector<std::string> const& args, case cmake::LogLevel::LOG_ERROR: case cmake::LogLevel::LOG_WARNING: // we've overridden the message type, above, so display it directly - this->Makefile->GetMessenger()->DisplayMessage( - type, message, this->Makefile->GetBacktrace()); + status.GetMakefile().GetMessenger()->DisplayMessage( + type, message, status.GetMakefile().GetBacktrace()); break; case cmake::LogLevel::LOG_NOTICE: @@ -131,7 +130,7 @@ bool cmMessageCommand::InitialPass(std::vector<std::string> const& args, case cmake::LogLevel::LOG_VERBOSE: case cmake::LogLevel::LOG_DEBUG: case cmake::LogLevel::LOG_TRACE: - this->Makefile->DisplayStatus(message, -1); + status.GetMakefile().DisplayStatus(message, -1); break; default: diff --git a/Source/cmMessageCommand.h b/Source/cmMessageCommand.h index ef89d59..7d544c4 100644 --- a/Source/cmMessageCommand.h +++ b/Source/cmMessageCommand.h @@ -8,33 +8,13 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -/** \class cmMessageCommand +/** * \brief Displays a message to the user * */ -class cmMessageCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmMessageCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; -}; +bool cmMessageCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmMessenger.cxx b/Source/cmMessenger.cxx index 07d011e..af83478 100644 --- a/Source/cmMessenger.cxx +++ b/Source/cmMessenger.cxx @@ -6,7 +6,7 @@ #include "cmStringAlgorithms.h" #include "cmSystemTools.h" -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) # include "cmsys/SystemInformation.hxx" #endif @@ -106,7 +106,7 @@ void displayMessage(MessageType t, std::ostringstream& msg) // Add a terminating blank line. msg << "\n"; -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) // Add a C++ stack trace to internal errors. if (t == MessageType::INTERNAL_ERROR) { std::string stack = cmsys::SystemInformation::GetProgramStack(0, 0); diff --git a/Source/cmNinjaNormalTargetGenerator.cxx b/Source/cmNinjaNormalTargetGenerator.cxx index cd84c03..2841245 100644 --- a/Source/cmNinjaNormalTargetGenerator.cxx +++ b/Source/cmNinjaNormalTargetGenerator.cxx @@ -218,8 +218,7 @@ void cmNinjaNormalTargetGenerator::WriteDeviceLinkRule(bool useResponseFile) const char* val = this->GetLocalGenerator()->GetRuleLauncher( this->GetGeneratorTarget(), "RULE_LAUNCH_LINK"); if (val && *val) { - launcher = val; - launcher += " "; + launcher = cmStrCat(val, ' '); } std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander( @@ -228,7 +227,7 @@ void cmNinjaNormalTargetGenerator::WriteDeviceLinkRule(bool useResponseFile) // Rule for linking library/executable. std::vector<std::string> linkCmds = this->ComputeDeviceLinkCmd(); for (std::string& linkCmd : linkCmds) { - linkCmd = launcher + linkCmd; + linkCmd = cmStrCat(launcher, linkCmd); rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), linkCmd, vars); } @@ -239,16 +238,10 @@ void cmNinjaNormalTargetGenerator::WriteDeviceLinkRule(bool useResponseFile) rule.Command = this->GetLocalGenerator()->BuildCommandLine(linkCmds); // Write the linker rule with response file if needed. - rule.Comment = "Rule for linking "; - rule.Comment += this->TargetLinkLanguage; - rule.Comment += " "; - rule.Comment += this->GetVisibleTypeName(); - rule.Comment += "."; - rule.Description = "Linking "; - rule.Description += this->TargetLinkLanguage; - rule.Description += " "; - rule.Description += this->GetVisibleTypeName(); - rule.Description += " $TARGET_FILE"; + rule.Comment = cmStrCat("Rule for linking ", this->TargetLinkLanguage, ' ', + this->GetVisibleTypeName(), '.'); + rule.Description = cmStrCat("Linking ", this->TargetLinkLanguage, ' ', + this->GetVisibleTypeName(), " $TARGET_FILE"); rule.Restat = "$RESTAT"; this->GetGlobalGenerator()->AddRule(rule); @@ -282,8 +275,7 @@ void cmNinjaNormalTargetGenerator::WriteLinkRule(bool useResponseFile) std::string responseFlag; - std::string cmakeVarLang = "CMAKE_"; - cmakeVarLang += this->TargetLinkLanguage; + std::string cmakeVarLang = cmStrCat("CMAKE_", this->TargetLinkLanguage); // build response file name std::string cmakeLinkVar = cmakeVarLang + "_RESPONSE_FILE_LINK_FLAG"; @@ -357,8 +349,7 @@ void cmNinjaNormalTargetGenerator::WriteLinkRule(bool useResponseFile) const char* val = this->GetLocalGenerator()->GetRuleLauncher( this->GetGeneratorTarget(), "RULE_LAUNCH_LINK"); if (val && *val) { - launcher = val; - launcher += " "; + launcher = cmStrCat(val, ' '); } std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander( @@ -367,7 +358,7 @@ void cmNinjaNormalTargetGenerator::WriteLinkRule(bool useResponseFile) // Rule for linking library/executable. std::vector<std::string> linkCmds = this->ComputeLinkCmd(); for (std::string& linkCmd : linkCmds) { - linkCmd = launcher + linkCmd; + linkCmd = cmStrCat(launcher, linkCmd); rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), linkCmd, vars); } @@ -380,16 +371,10 @@ void cmNinjaNormalTargetGenerator::WriteLinkRule(bool useResponseFile) rule.Command = this->GetLocalGenerator()->BuildCommandLine(linkCmds); // Write the linker rule with response file if needed. - rule.Comment = "Rule for linking "; - rule.Comment += this->TargetLinkLanguage; - rule.Comment += " "; - rule.Comment += this->GetVisibleTypeName(); - rule.Comment += "."; - rule.Description = "Linking "; - rule.Description += this->TargetLinkLanguage; - rule.Description += " "; - rule.Description += this->GetVisibleTypeName(); - rule.Description += " $TARGET_FILE"; + rule.Comment = cmStrCat("Rule for linking ", this->TargetLinkLanguage, ' ', + this->GetVisibleTypeName(), '.'); + rule.Description = cmStrCat("Linking ", this->TargetLinkLanguage, ' ', + this->GetVisibleTypeName(), " $TARGET_FILE"); rule.Restat = "$RESTAT"; this->GetGlobalGenerator()->AddRule(rule); } @@ -440,12 +425,12 @@ std::vector<std::string> cmNinjaNormalTargetGenerator::ComputeDeviceLinkCmd() case cmStateEnums::MODULE_LIBRARY: { const std::string cudaLinkCmd( this->GetMakefile()->GetDefinition("CMAKE_CUDA_DEVICE_LINK_LIBRARY")); - cmSystemTools::ExpandListArgument(cudaLinkCmd, linkCmds); + cmExpandList(cudaLinkCmd, linkCmds); } break; case cmStateEnums::EXECUTABLE: { const std::string cudaLinkCmd(this->GetMakefile()->GetDefinition( "CMAKE_CUDA_DEVICE_LINK_EXECUTABLE")); - cmSystemTools::ExpandListArgument(cudaLinkCmd, linkCmds); + cmExpandList(cudaLinkCmd, linkCmds); } break; default: break; @@ -467,19 +452,19 @@ std::vector<std::string> cmNinjaNormalTargetGenerator::ComputeLinkCmd() if (linkCmd) { std::string linkCmdStr = linkCmd; if (this->GetGeneratorTarget()->HasImplibGNUtoMS(this->ConfigName)) { - std::string ruleVar = "CMAKE_"; - ruleVar += this->GeneratorTarget->GetLinkerLanguage(this->ConfigName); - ruleVar += "_GNUtoMS_RULE"; + std::string ruleVar = cmStrCat( + "CMAKE_", this->GeneratorTarget->GetLinkerLanguage(this->ConfigName), + "_GNUtoMS_RULE"); if (const char* rule = this->Makefile->GetDefinition(ruleVar)) { linkCmdStr += rule; } } - cmSystemTools::ExpandListArgument(linkCmdStr, linkCmds); + cmExpandList(linkCmdStr, linkCmds); if (this->GetGeneratorTarget()->GetPropertyAsBool("LINK_WHAT_YOU_USE")) { - std::string cmakeCommand = + std::string cmakeCommand = cmStrCat( this->GetLocalGenerator()->ConvertToOutputFormat( - cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL); - cmakeCommand += " -E __run_co_compile --lwyu="; + cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL), + " -E __run_co_compile --lwyu="); cmGeneratorTarget& gt = *this->GetGeneratorTarget(); const std::string cfgName = this->GetConfigName(); std::string targetOutputReal = this->ConvertToNinjaPath( @@ -502,26 +487,24 @@ std::vector<std::string> cmNinjaNormalTargetGenerator::ComputeLinkCmd() } // TODO: Use ARCHIVE_APPEND for archives over a certain size. { - std::string linkCmdVar = "CMAKE_"; - linkCmdVar += this->TargetLinkLanguage; - linkCmdVar += "_ARCHIVE_CREATE"; + std::string linkCmdVar = + cmStrCat("CMAKE_", this->TargetLinkLanguage, "_ARCHIVE_CREATE"); linkCmdVar = this->GeneratorTarget->GetFeatureSpecificLinkRuleVariable( linkCmdVar, this->TargetLinkLanguage, this->GetConfigName()); std::string const& linkCmd = mf->GetRequiredDefinition(linkCmdVar); - cmSystemTools::ExpandListArgument(linkCmd, linkCmds); + cmExpandList(linkCmd, linkCmds); } { - std::string linkCmdVar = "CMAKE_"; - linkCmdVar += this->TargetLinkLanguage; - linkCmdVar += "_ARCHIVE_FINISH"; + std::string linkCmdVar = + cmStrCat("CMAKE_", this->TargetLinkLanguage, "_ARCHIVE_FINISH"); linkCmdVar = this->GeneratorTarget->GetFeatureSpecificLinkRuleVariable( linkCmdVar, this->TargetLinkLanguage, this->GetConfigName()); std::string const& linkCmd = mf->GetRequiredDefinition(linkCmdVar); - cmSystemTools::ExpandListArgument(linkCmd, linkCmds); + cmExpandList(linkCmd, linkCmds); } #ifdef __APPLE__ // On macOS ranlib truncates the fractional part of the static archive @@ -590,10 +573,8 @@ void cmNinjaNormalTargetGenerator::WriteDeviceLinkStatement() // Compute the comment. cmNinjaBuild build(this->LanguageLinkerDeviceRule()); - build.Comment = "Link the "; - build.Comment += this->GetVisibleTypeName(); - build.Comment += " "; - build.Comment += targetOutputReal; + build.Comment = + cmStrCat("Link the ", this->GetVisibleTypeName(), ' ', targetOutputReal); cmNinjaVars& vars = build.Variables; @@ -728,13 +709,9 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement() outpath); // Calculate the output path - targetOutput = outpath; - targetOutput += "/"; - targetOutput += this->TargetNames.Output; + targetOutput = cmStrCat(outpath, '/', this->TargetNames.Output); targetOutput = this->ConvertToNinjaPath(targetOutput); - targetOutputReal = outpath; - targetOutputReal += "/"; - targetOutputReal += this->TargetNames.Real; + targetOutputReal = cmStrCat(outpath, '/', this->TargetNames.Real); targetOutputReal = this->ConvertToNinjaPath(targetOutputReal); } else if (gt->IsFrameworkOnApple()) { // Create the library framework. @@ -757,10 +734,8 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement() cmNinjaVars& vars = linkBuild.Variables; // Compute the comment. - linkBuild.Comment = "Link the "; - linkBuild.Comment += this->GetVisibleTypeName(); - linkBuild.Comment += " "; - linkBuild.Comment += targetOutputReal; + linkBuild.Comment = + cmStrCat("Link the ", this->GetVisibleTypeName(), ' ', targetOutputReal); // Compute outputs. linkBuild.Outputs.push_back(targetOutputReal); @@ -967,7 +942,8 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement() >->GetPostBuildCommands() }; - std::vector<std::string> preLinkCmdLines, postBuildCmdLines; + std::vector<std::string> preLinkCmdLines; + std::vector<std::string> postBuildCmdLines; std::vector<std::string>* cmdLineLists[3] = { &preLinkCmdLines, &preLinkCmdLines, &postBuildCmdLines }; @@ -989,11 +965,11 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement() std::string cmakeCommand = this->GetLocalGenerator()->ConvertToOutputFormat( cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL); - std::string cmd = cmakeCommand; - cmd += " -E __create_def "; - cmd += this->GetLocalGenerator()->ConvertToOutputFormat( - mdi->DefFile, cmOutputConverter::SHELL); - cmd += " "; + std::string cmd = + cmStrCat(cmakeCommand, " -E __create_def ", + this->GetLocalGenerator()->ConvertToOutputFormat( + mdi->DefFile, cmOutputConverter::SHELL), + ' '); std::string obj_list_file = mdi->DefFile + ".objs"; cmd += this->GetLocalGenerator()->ConvertToOutputFormat( obj_list_file, cmOutputConverter::SHELL); @@ -1038,8 +1014,7 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement() symlinkVars["POST_BUILD"] = postBuildCmdLine; } - std::string cmakeVarLang = "CMAKE_"; - cmakeVarLang += this->TargetLinkLanguage; + std::string cmakeVarLang = cmStrCat("CMAKE_", this->TargetLinkLanguage); // build response file name std::string cmakeLinkVar = cmakeVarLang + "_RESPONSE_FILE_LINK_FLAG"; diff --git a/Source/cmNinjaTargetGenerator.cxx b/Source/cmNinjaTargetGenerator.cxx index 8b0a6ba..7b91bd4 100644 --- a/Source/cmNinjaTargetGenerator.cxx +++ b/Source/cmNinjaTargetGenerator.cxx @@ -219,8 +219,8 @@ std::string cmNinjaTargetGenerator::ComputeDefines(cmSourceFile const* source, defines, genexInterpreter.Evaluate(compile_defs, COMPILE_DEFINITIONS)); } - std::string defPropName = "COMPILE_DEFINITIONS_"; - defPropName += cmSystemTools::UpperCase(config); + std::string defPropName = + cmStrCat("COMPILE_DEFINITIONS_", cmSystemTools::UpperCase(config)); if (const char* config_compile_defs = source->GetProperty(defPropName)) { this->LocalGenerator->AppendDefines( defines, @@ -374,10 +374,10 @@ std::string cmNinjaTargetGenerator::GetDyndepFilePath( std::string cmNinjaTargetGenerator::GetTargetDependInfoPath( std::string const& lang) const { - std::string path = this->Makefile->GetCurrentBinaryDirectory(); - path += "/"; - path += this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget); - path += "/" + lang + "DependInfo.json"; + std::string path = + cmStrCat(this->Makefile->GetCurrentBinaryDirectory(), '/', + this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget), + '/', lang, "DependInfo.json"); return path; } @@ -416,9 +416,9 @@ bool cmNinjaTargetGenerator::SetMsvcTargetPdbVariable(cmNinjaVars& vars) const this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY || this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY || this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) { - pdbPath = this->GeneratorTarget->GetPDBDirectory(this->GetConfigName()); - pdbPath += "/"; - pdbPath += this->GeneratorTarget->GetPDBName(this->GetConfigName()); + pdbPath = cmStrCat( + this->GeneratorTarget->GetPDBDirectory(this->GetConfigName()), '/', + this->GeneratorTarget->GetPDBName(this->GetConfigName())); } vars["TARGET_PDB"] = this->GetLocalGenerator()->ConvertToOutputFormat( @@ -488,8 +488,7 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang) const char* val = this->GetLocalGenerator()->GetRuleLauncher( this->GetGeneratorTarget(), "RULE_LAUNCH_COMPILE"); if (val && *val) { - launcher = val; - launcher += " "; + launcher = cmStrCat(val, ' '); } std::string const cmakeCmd = @@ -529,12 +528,8 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang) // If using a response file, move defines, includes, and flags into it. if (!responseFlag.empty()) { rule.RspFile = "$RSP_FILE"; - rule.RspContent = " "; - rule.RspContent += ppVars.Defines; - rule.RspContent += " "; - rule.RspContent += ppVars.Includes; - rule.RspContent += " "; - rule.RspContent += ppFlags; + rule.RspContent = + cmStrCat(' ', ppVars.Defines, ' ', ppVars.Includes, ' ', ppFlags); ppFlags = responseFlag + rule.RspFile; ppVars.Defines = ""; ppVars.Includes = ""; @@ -546,26 +541,21 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang) std::vector<std::string> ppCmds; { // Lookup the explicit preprocessing rule. - std::string ppVar = "CMAKE_" + lang; - ppVar += "_PREPROCESS_SOURCE"; - cmSystemTools::ExpandListArgument( - this->GetMakefile()->GetRequiredDefinition(ppVar), ppCmds); + std::string ppVar = cmStrCat("CMAKE_", lang, "_PREPROCESS_SOURCE"); + cmExpandList(this->GetMakefile()->GetRequiredDefinition(ppVar), ppCmds); } for (std::string& i : ppCmds) { - i = launcher + i; + i = cmStrCat(launcher, i); rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), i, ppVars); } // Run CMake dependency scanner on preprocessed output. { - std::string ccmd = cmakeCmd; - ccmd += " -E cmake_ninja_depends --tdi="; - ccmd += tdi; - ccmd += " --lang="; - ccmd += lang; - ccmd += " --pp=$out --dep=$DEP_FILE"; + std::string ccmd = + cmStrCat(cmakeCmd, " -E cmake_ninja_depends --tdi=", tdi, + " --lang=", lang, " --pp=$out --dep=$DEP_FILE"); if (needDyndep) { ccmd += " --obj=$OBJ_FILE --ddi=$DYNDEP_INTERMEDIATE_FILE"; } @@ -574,12 +564,8 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang) rule.Command = this->GetLocalGenerator()->BuildCommandLine(ppCmds); // Write the rule for preprocessing file of the given language. - rule.Comment = "Rule for preprocessing "; - rule.Comment += lang; - rule.Comment += " files."; - rule.Description = "Building "; - rule.Description += lang; - rule.Description += " preprocessed $out"; + rule.Comment = cmStrCat("Rule for preprocessing ", lang, " files."); + rule.Description = cmStrCat("Building ", lang, " preprocessed $out"); this->GetGlobalGenerator()->AddRule(rule); } @@ -596,24 +582,16 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang) { std::vector<std::string> ddCmds; { - std::string ccmd = cmakeCmd; - ccmd += " -E cmake_ninja_dyndep --tdi="; - ccmd += tdi; - ccmd += " --lang="; - ccmd += lang; - ccmd += " --dd=$out "; - ccmd += "@"; - ccmd += rule.RspFile; + std::string ccmd = + cmStrCat(cmakeCmd, " -E cmake_ninja_dyndep --tdi=", tdi, + " --lang=", lang, " --dd=$out @", rule.RspFile); ddCmds.emplace_back(std::move(ccmd)); } rule.Command = this->GetLocalGenerator()->BuildCommandLine(ddCmds); } - rule.Comment = "Rule to generate ninja dyndep files for "; - rule.Comment += lang; - rule.Comment += "."; - rule.Description = "Generating "; - rule.Description += lang; - rule.Description += " dyndep file $out"; + rule.Comment = + cmStrCat("Rule to generate ninja dyndep files for ", lang, '.'); + rule.Description = cmStrCat("Generating ", lang, " dyndep file $out"); this->GetGlobalGenerator()->AddRule(rule); } @@ -621,12 +599,8 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang) // If using a response file, move defines, includes, and flags into it. if (!responseFlag.empty()) { rule.RspFile = "$RSP_FILE"; - rule.RspContent = " "; - rule.RspContent += vars.Defines; - rule.RspContent += " "; - rule.RspContent += vars.Includes; - rule.RspContent += " "; - rule.RspContent += flags; + rule.RspContent = + cmStrCat(' ', vars.Defines, ' ', vars.Includes, ' ', flags); flags = responseFlag + rule.RspFile; vars.Defines = ""; vars.Includes = ""; @@ -649,11 +623,10 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang) const std::string cl = mf->GetDefinition("CMAKE_C_COMPILER") ? mf->GetSafeDefinition("CMAKE_C_COMPILER") : mf->GetSafeDefinition("CMAKE_CXX_COMPILER"); - cldeps = "\""; - cldeps += cmSystemTools::GetCMClDepsCommand(); - cldeps += "\" " + lang + " " + vars.Source + " $DEP_FILE $out \""; - cldeps += mf->GetSafeDefinition("CMAKE_CL_SHOWINCLUDES_PREFIX"); - cldeps += "\" \"" + cl + "\" "; + cldeps = cmStrCat('"', cmSystemTools::GetCMClDepsCommand(), "\" ", lang, + ' ', vars.Source, " $DEP_FILE $out \"", + mf->GetSafeDefinition("CMAKE_CL_SHOWINCLUDES_PREFIX"), + "\" \"", cl, "\" "); } } else { rule.DepType = "gcc"; @@ -686,11 +659,11 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang) cmdVar = "CMAKE_CUDA_COMPILE_WHOLE_COMPILATION"; } const std::string& compileCmd = mf->GetRequiredDefinition(cmdVar); - cmSystemTools::ExpandListArgument(compileCmd, compileCmds); + cmExpandList(compileCmd, compileCmds); } else { const std::string cmdVar = "CMAKE_" + lang + "_COMPILE_OBJECT"; const std::string& compileCmd = mf->GetRequiredDefinition(cmdVar); - cmSystemTools::ExpandListArgument(compileCmd, compileCmds); + cmExpandList(compileCmd, compileCmds); } // See if we need to use a compiler launcher like ccache or distcc @@ -716,8 +689,7 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang) const char* cppcheck = this->GeneratorTarget->GetProperty(cppcheck_prop); if ((iwyu && *iwyu) || (tidy && *tidy) || (cpplint && *cpplint) || (cppcheck && *cppcheck)) { - std::string run_iwyu = cmakeCmd; - run_iwyu += " -E __run_co_compile"; + std::string run_iwyu = cmStrCat(cmakeCmd, " -E __run_co_compile"); if (!compilerLauncher.empty()) { // In __run_co_compile case the launcher command is supplied // via --launcher=<maybe-list> and consumed @@ -754,7 +726,7 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang) // goes to the beginning of the command line. if (!compileCmds.empty() && !compilerLauncher.empty()) { std::vector<std::string> args; - cmSystemTools::ExpandListArgument(compilerLauncher, args, true); + cmExpandList(compilerLauncher, args, true); if (!args.empty()) { args[0] = this->LocalGenerator->ConvertToOutputFormat( args[0], cmOutputConverter::SHELL); @@ -770,7 +742,7 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang) } for (std::string& i : compileCmds) { - i = launcher + i; + i = cmStrCat(launcher, i); rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), i, vars); } @@ -778,12 +750,8 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang) rule.Command = this->GetLocalGenerator()->BuildCommandLine(compileCmds); // Write the rule for compiling file of the given language. - rule.Comment = "Rule for compiling "; - rule.Comment += lang; - rule.Comment += " files."; - rule.Description = "Building "; - rule.Description += lang; - rule.Description += " object $out"; + rule.Comment = cmStrCat("Rule for compiling ", lang, " files."); + rule.Description = cmStrCat("Building ", lang, " object $out"); this->GetGlobalGenerator()->AddRule(rule); } @@ -865,11 +833,9 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatements() if (orderOnlyDeps.empty()) { // Any path that always exists will work here. It would be nice to // use just "." but that is not supported by Ninja < 1.7. - std::string tgtDir; - tgtDir += this->LocalGenerator->GetCurrentBinaryDirectory(); - tgtDir += "/"; - tgtDir += - this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget); + std::string tgtDir = cmStrCat( + this->LocalGenerator->GetCurrentBinaryDirectory(), '/', + this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget)); orderOnlyDeps.push_back(this->ConvertToNinjaPath(tgtDir)); } @@ -946,8 +912,7 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatement( std::string const objectFileDir = cmSystemTools::GetFilenamePath(objectFileName); - std::string cmakeVarLang = "CMAKE_"; - cmakeVarLang += language; + std::string cmakeVarLang = cmStrCat("CMAKE_", language); // build response file name std::string cmakeLinkVar = cmakeVarLang + "_RESPONSE_FILE_FLAG"; @@ -968,9 +933,8 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatement( if (!this->NeedDepTypeMSVC(language)) { bool replaceExt(false); if (!language.empty()) { - std::string repVar = "CMAKE_"; - repVar += language; - repVar += "_DEPFILE_EXTENSION_REPLACE"; + std::string repVar = + cmStrCat("CMAKE_", language, "_DEPFILE_EXTENSION_REPLACE"); replaceExt = this->Makefile->IsOn(repVar); } if (!replaceExt) { @@ -998,8 +962,7 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatement( objBuild.ExplicitDeps.push_back(sourceFileName); if (const char* objectDeps = source->GetProperty("OBJECT_DEPENDS")) { - std::vector<std::string> depList = - cmSystemTools::ExpandedListArgument(objectDeps); + std::vector<std::string> depList = cmExpandedList(objectDeps); for (std::string& odi : depList) { if (cmSystemTools::FileIsFullPath(odi)) { odi = cmSystemTools::CollapseFullPath(odi); @@ -1152,7 +1115,7 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatement( if (const char* objectOutputs = source->GetProperty("OBJECT_OUTPUTS")) { cmNinjaBuild build("phony"); build.Comment = "Additional output files."; - build.Outputs = cmSystemTools::ExpandedListArgument(objectOutputs); + build.Outputs = cmExpandedList(objectOutputs); std::transform(build.Outputs.begin(), build.Outputs.end(), build.Outputs.begin(), MapToNinjaPath()); build.ExplicitDeps = objBuild.Outputs; @@ -1301,12 +1264,12 @@ void cmNinjaTargetGenerator::ExportObjectCompileCommand( } const std::string& compileCmd = this->GetMakefile()->GetRequiredDefinition(cmdVar); - cmSystemTools::ExpandListArgument(compileCmd, compileCmds); + cmExpandList(compileCmd, compileCmds); } else { const std::string cmdVar = "CMAKE_" + language + "_COMPILE_OBJECT"; const std::string& compileCmd = this->GetMakefile()->GetRequiredDefinition(cmdVar); - cmSystemTools::ExpandListArgument(compileCmd, compileCmds); + cmExpandList(compileCmd, compileCmds); } std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander( @@ -1333,11 +1296,10 @@ void cmNinjaTargetGenerator::AdditionalCleanFiles() { cmGeneratorExpression ge; auto cge = ge.Parse(prop_value); - cmSystemTools::ExpandListArgument( - cge->Evaluate(lg, - this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"), - false, this->GeneratorTarget, nullptr, nullptr), - cleanFiles); + cmExpandList(cge->Evaluate( + lg, this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"), + false, this->GeneratorTarget, nullptr, nullptr), + cleanFiles); } std::string const& binaryDir = lg->GetCurrentBinaryDirectory(); cmGlobalNinjaGenerator* gg = lg->GetGlobalNinjaGenerator(); @@ -1386,9 +1348,8 @@ void cmNinjaTargetGenerator::MacOSXContentGeneratorType::operator()( input = this->Generator->GetGlobalGenerator()->ConvertToNinjaPath(input); // Get the output file location. - std::string output = macdir; - output += "/"; - output += cmSystemTools::GetFilenameName(input); + std::string output = + cmStrCat(macdir, '/', cmSystemTools::GetFilenameName(input)); output = this->Generator->GetGlobalGenerator()->ConvertToNinjaPath(output); // Write a build statement to copy the content into the bundle. diff --git a/Source/cmNinjaUtilityTargetGenerator.cxx b/Source/cmNinjaUtilityTargetGenerator.cxx index 1225cbd..83a9beb 100644 --- a/Source/cmNinjaUtilityTargetGenerator.cxx +++ b/Source/cmNinjaUtilityTargetGenerator.cxx @@ -13,6 +13,7 @@ #include "cmOutputConverter.h" #include "cmSourceFile.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include <algorithm> @@ -36,15 +37,15 @@ void cmNinjaUtilityTargetGenerator::Generate() cmLocalNinjaGenerator* lg = this->GetLocalGenerator(); cmGeneratorTarget* genTarget = this->GetGeneratorTarget(); - std::string utilCommandName = lg->GetCurrentBinaryDirectory(); - utilCommandName += "/CMakeFiles"; - utilCommandName += "/"; - utilCommandName += this->GetTargetName() + ".util"; + std::string utilCommandName = + cmStrCat(lg->GetCurrentBinaryDirectory(), "/CMakeFiles/", + this->GetTargetName(), ".util"); utilCommandName = this->ConvertToNinjaPath(utilCommandName); cmNinjaBuild phonyBuild("phony"); std::vector<std::string> commands; - cmNinjaDeps deps, util_outputs(1, utilCommandName); + cmNinjaDeps deps; + cmNinjaDeps util_outputs(1, utilCommandName); bool uses_terminal = false; { diff --git a/Source/cmOSXBundleGenerator.cxx b/Source/cmOSXBundleGenerator.cxx index 47a8df4..6175c1e 100644 --- a/Source/cmOSXBundleGenerator.cxx +++ b/Source/cmOSXBundleGenerator.cxx @@ -6,6 +6,7 @@ #include "cmLocalGenerator.h" #include "cmMakefile.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmTarget.h" @@ -40,20 +41,20 @@ void cmOSXBundleGenerator::CreateAppBundle(const std::string& targetName, } // Compute bundle directory names. - std::string out = outpath; - out += "/"; - out += this->GT->GetAppBundleDirectory(this->ConfigName, - cmGeneratorTarget::FullLevel); + std::string out = + cmStrCat(outpath, '/', + this->GT->GetAppBundleDirectory(this->ConfigName, + cmGeneratorTarget::FullLevel)); cmSystemTools::MakeDirectory(out); this->Makefile->AddCMakeOutputFile(out); // Configure the Info.plist file. Note that it needs the executable name // to be set. - std::string plist = outpath; - plist += "/"; - plist += this->GT->GetAppBundleDirectory(this->ConfigName, - cmGeneratorTarget::ContentLevel); - plist += "/Info.plist"; + std::string plist = + cmStrCat(outpath, '/', + this->GT->GetAppBundleDirectory(this->ConfigName, + cmGeneratorTarget::ContentLevel), + "/Info.plist"); this->LocalGenerator->GenerateAppleInfoPList(this->GT, targetName, plist); this->Makefile->AddCMakeOutputFile(plist); outpath = out; @@ -69,10 +70,11 @@ void cmOSXBundleGenerator::CreateFramework(const std::string& targetName, assert(this->MacContentFolders); // Compute the location of the top-level foo.framework directory. - std::string contentdir = outpath + "/" + - this->GT->GetFrameworkDirectory(this->ConfigName, - cmGeneratorTarget::ContentLevel); - contentdir += "/"; + std::string contentdir = + cmStrCat(outpath, '/', + this->GT->GetFrameworkDirectory(this->ConfigName, + cmGeneratorTarget::ContentLevel), + '/'); std::string newoutpath = outpath + "/" + this->GT->GetFrameworkDirectory(this->ConfigName, @@ -102,8 +104,7 @@ void cmOSXBundleGenerator::CreateFramework(const std::string& targetName, std::string newName; // Make foo.framework/Versions - std::string versions = contentdir; - versions += "Versions"; + std::string versions = cmStrCat(contentdir, "Versions"); cmSystemTools::MakeDirectory(versions); // Make foo.framework/Versions/version @@ -111,17 +112,14 @@ void cmOSXBundleGenerator::CreateFramework(const std::string& targetName, // Current -> version oldName = frameworkVersion; - newName = versions; - newName += "/Current"; + newName = cmStrCat(versions, "/Current"); cmSystemTools::RemoveFile(newName); cmSystemTools::CreateSymlink(oldName, newName); this->Makefile->AddCMakeOutputFile(newName); // foo -> Versions/Current/foo - oldName = "Versions/Current/"; - oldName += name; - newName = contentdir; - newName += name; + oldName = cmStrCat("Versions/Current/", name); + newName = cmStrCat(contentdir, name); cmSystemTools::RemoveFile(newName); cmSystemTools::CreateSymlink(oldName, newName); this->Makefile->AddCMakeOutputFile(newName); @@ -130,8 +128,7 @@ void cmOSXBundleGenerator::CreateFramework(const std::string& targetName, if (this->MacContentFolders->find("Resources") != this->MacContentFolders->end()) { oldName = "Versions/Current/Resources"; - newName = contentdir; - newName += "Resources"; + newName = cmStrCat(contentdir, "Resources"); cmSystemTools::RemoveFile(newName); cmSystemTools::CreateSymlink(oldName, newName); this->Makefile->AddCMakeOutputFile(newName); @@ -141,8 +138,7 @@ void cmOSXBundleGenerator::CreateFramework(const std::string& targetName, if (this->MacContentFolders->find("Headers") != this->MacContentFolders->end()) { oldName = "Versions/Current/Headers"; - newName = contentdir; - newName += "Headers"; + newName = cmStrCat(contentdir, "Headers"); cmSystemTools::RemoveFile(newName); cmSystemTools::CreateSymlink(oldName, newName); this->Makefile->AddCMakeOutputFile(newName); @@ -152,8 +148,7 @@ void cmOSXBundleGenerator::CreateFramework(const std::string& targetName, if (this->MacContentFolders->find("PrivateHeaders") != this->MacContentFolders->end()) { oldName = "Versions/Current/PrivateHeaders"; - newName = contentdir; - newName += "PrivateHeaders"; + newName = cmStrCat(contentdir, "PrivateHeaders"); cmSystemTools::RemoveFile(newName); cmSystemTools::CreateSymlink(oldName, newName); this->Makefile->AddCMakeOutputFile(newName); @@ -168,19 +163,20 @@ void cmOSXBundleGenerator::CreateCFBundle(const std::string& targetName, } // Compute bundle directory names. - std::string out = root; - out += "/"; - out += this->GT->GetCFBundleDirectory(this->ConfigName, - cmGeneratorTarget::FullLevel); + std::string out = + cmStrCat(root, '/', + this->GT->GetCFBundleDirectory(this->ConfigName, + cmGeneratorTarget::FullLevel)); cmSystemTools::MakeDirectory(out); this->Makefile->AddCMakeOutputFile(out); // Configure the Info.plist file. Note that it needs the executable name // to be set. - std::string plist = root + "/" + - this->GT->GetCFBundleDirectory(this->ConfigName, - cmGeneratorTarget::ContentLevel); - plist += "/Info.plist"; + std::string plist = + cmStrCat(root, '/', + this->GT->GetCFBundleDirectory(this->ConfigName, + cmGeneratorTarget::ContentLevel), + "/Info.plist"); std::string name = cmSystemTools::GetFilenameName(targetName); this->LocalGenerator->GenerateAppleInfoPList(this->GT, name, plist); this->Makefile->AddCMakeOutputFile(plist); @@ -208,10 +204,10 @@ std::string cmOSXBundleGenerator::InitMacOSXContentDirectory( { // Construct the full path to the content subdirectory. - std::string macdir = this->GT->GetMacContentDirectory( - this->ConfigName, cmStateEnums::RuntimeBinaryArtifact); - macdir += "/"; - macdir += pkgloc; + std::string macdir = + cmStrCat(this->GT->GetMacContentDirectory( + this->ConfigName, cmStateEnums::RuntimeBinaryArtifact), + '/', pkgloc); cmSystemTools::MakeDirectory(macdir); // Record use of this content location. Only the first level diff --git a/Source/cmOptionCommand.cxx b/Source/cmOptionCommand.cxx index 3724ba7..a0a0989 100644 --- a/Source/cmOptionCommand.cxx +++ b/Source/cmOptionCommand.cxx @@ -4,6 +4,7 @@ #include <sstream> +#include "cmExecutionStatus.h" #include "cmMakefile.h" #include "cmMessageType.h" #include "cmPolicies.h" @@ -11,29 +12,27 @@ #include "cmStateSnapshot.h" #include "cmStateTypes.h" #include "cmStringAlgorithms.h" -#include "cmSystemTools.h" - -class cmExecutionStatus; // cmOptionCommand -bool cmOptionCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus&) +bool cmOptionCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { const bool argError = (args.size() < 2) || (args.size() > 3); if (argError) { - std::string m = "called with incorrect number of arguments: "; - m += cmJoin(args, " "); - this->SetError(m); + std::string m = cmStrCat("called with incorrect number of arguments: ", + cmJoin(args, " ")); + status.SetError(m); return false; } // Determine the state of the option policy bool checkAndWarn = false; { - auto status = this->Makefile->GetPolicyStatus(cmPolicies::CMP0077); + auto policyStatus = + status.GetMakefile().GetPolicyStatus(cmPolicies::CMP0077); const auto* existsBeforeSet = - this->Makefile->GetStateSnapshot().GetDefinition(args[0]); - switch (status) { + status.GetMakefile().GetStateSnapshot().GetDefinition(args[0]); + switch (policyStatus) { case cmPolicies::WARN: checkAndWarn = (existsBeforeSet != nullptr); break; @@ -54,7 +53,7 @@ bool cmOptionCommand::InitialPass(std::vector<std::string> const& args, // See if a cache variable with this name already exists // If so just make sure the doc state is correct - cmState* state = this->Makefile->GetState(); + cmState* state = status.GetMakefile().GetState(); const char* existingValue = state->GetCacheEntryValue(args[0]); if (existingValue && (state->GetCacheEntryType(args[0]) != cmStateEnums::UNINITIALIZED)) { @@ -67,13 +66,13 @@ bool cmOptionCommand::InitialPass(std::vector<std::string> const& args, if (args.size() == 3) { initialValue = args[2]; } - bool init = cmSystemTools::IsOn(initialValue); - this->Makefile->AddCacheDefinition(args[0], init ? "ON" : "OFF", - args[1].c_str(), cmStateEnums::BOOL); + bool init = cmIsOn(initialValue); + status.GetMakefile().AddCacheDefinition(args[0], init ? "ON" : "OFF", + args[1].c_str(), cmStateEnums::BOOL); if (checkAndWarn) { const auto* existsAfterSet = - this->Makefile->GetStateSnapshot().GetDefinition(args[0]); + status.GetMakefile().GetStateSnapshot().GetDefinition(args[0]); if (!existsAfterSet) { std::ostringstream w; w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0077) @@ -81,7 +80,7 @@ bool cmOptionCommand::InitialPass(std::vector<std::string> const& args, "For compatibility with older versions of CMake, option " "is clearing the normal variable '" << args[0] << "'."; - this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, w.str()); + status.GetMakefile().IssueMessage(MessageType::AUTHOR_WARNING, w.str()); } } return true; diff --git a/Source/cmOptionCommand.h b/Source/cmOptionCommand.h index eddab03..cbd1cb8 100644 --- a/Source/cmOptionCommand.h +++ b/Source/cmOptionCommand.h @@ -8,34 +8,13 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -/** \class cmOptionCommand +/** * \brief Provide an option to the user * * cmOptionCommand provides an option for the user to select */ -class cmOptionCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmOptionCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; -}; - +bool cmOptionCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmOrderDirectories.cxx b/Source/cmOrderDirectories.cxx index 2d055ff..21a17e8 100644 --- a/Source/cmOrderDirectories.cxx +++ b/Source/cmOrderDirectories.cxx @@ -6,6 +6,7 @@ #include "cmGeneratorTarget.h" #include "cmGlobalGenerator.h" #include "cmMessageType.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmake.h" @@ -117,9 +118,7 @@ bool cmOrderDirectoriesConstraint::FileMayConflict(std::string const& dir, std::string const& name) { // Check if the file exists on disk. - std::string file = dir; - file += "/"; - file += name; + std::string file = cmStrCat(dir, '/', name); if (cmSystemTools::FileExists(file, true)) { // The file conflicts only if it is not the same as the original // file due to a symlink or hardlink. @@ -229,8 +228,7 @@ bool cmOrderDirectoriesConstraintLibrary::FindConflict(std::string const& dir) std::string ext = this->OD->RemoveLibraryExtension.match(2); for (std::string const& LinkExtension : this->OD->LinkExtensions) { if (LinkExtension != ext) { - std::string fname = lib; - fname += LinkExtension; + std::string fname = cmStrCat(lib, LinkExtension); if (this->FileMayConflict(dir, fname)) { return true; } diff --git a/Source/cmOutputConverter.cxx b/Source/cmOutputConverter.cxx index da7f8bc..bf516e3 100644 --- a/Source/cmOutputConverter.cxx +++ b/Source/cmOutputConverter.cxx @@ -9,6 +9,7 @@ #include <vector> #include "cmState.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" cmOutputConverter::cmOutputConverter(cmStateSnapshot const& snapshot) @@ -153,7 +154,7 @@ cmOutputConverter::FortranFormat cmOutputConverter::GetFortranFormat( { FortranFormat format = FortranFormatNone; if (!value.empty()) { - for (std::string const& fi : cmSystemTools::ExpandedListArgument(value)) { + for (std::string const& fi : cmExpandedList(value)) { if (fi == "FIXED") { format = FortranFormatFixed; } diff --git a/Source/cmOutputRequiredFilesCommand.cxx b/Source/cmOutputRequiredFilesCommand.cxx index a66af5a..38e86e3 100644 --- a/Source/cmOutputRequiredFilesCommand.cxx +++ b/Source/cmOutputRequiredFilesCommand.cxx @@ -123,7 +123,7 @@ public: incDirProp, cmGeneratorExpression::StripAllGeneratorExpressions); std::vector<std::string> includes; - cmSystemTools::ExpandListArgument(incDirs, includes); + cmExpandList(incDirs, includes); for (std::string& path : includes) { this->Makefile->ExpandVariablesInString(path); @@ -193,10 +193,8 @@ protected: // see if the include matches the regular expression if (!this->IncludeFileRegularExpression.find(includeFile)) { if (this->Verbose) { - std::string message = "Skipping "; - message += includeFile; - message += " for file "; - message += info->FullPath; + std::string message = + cmStrCat("Skipping ", includeFile, " for file ", info->FullPath); cmSystemTools::Error(message); } continue; @@ -215,10 +213,8 @@ protected: if (cmSystemTools::FileExists(cxxFile)) { found = true; } - for (std::string path : this->IncludeDirectories) { - path = path + "/"; - path = path + cxxFile; - if (cmSystemTools::FileExists(path)) { + for (std::string const& path : this->IncludeDirectories) { + if (cmSystemTools::FileExists(cmStrCat(path, "/", cxxFile))) { found = true; } } @@ -227,10 +223,8 @@ protected: if (cmSystemTools::FileExists(cxxFile)) { found = true; } - for (std::string path : this->IncludeDirectories) { - path = path + "/"; - path = path + cxxFile; - if (cmSystemTools::FileExists(path)) { + for (std::string const& path : this->IncludeDirectories) { + if (cmSystemTools::FileExists(cmStrCat(path, "/", cxxFile))) { found = true; } } @@ -240,10 +234,8 @@ protected: if (cmSystemTools::FileExists(cxxFile)) { found = true; } - for (std::string path : this->IncludeDirectories) { - path = path + "/"; - path = path + cxxFile; - if (cmSystemTools::FileExists(path)) { + for (std::string const& path : this->IncludeDirectories) { + if (cmSystemTools::FileExists(cmStrCat(path, "/", cxxFile))) { found = true; } } @@ -253,10 +245,8 @@ protected: if (cmSystemTools::FileExists(cxxFile)) { found = true; } - for (std::string path : this->IncludeDirectories) { - path = path + "/"; - path = path + cxxFile; - if (cmSystemTools::FileExists(path)) { + for (std::string const& path : this->IncludeDirectories) { + if (cmSystemTools::FileExists(cmStrCat(path, "/", cxxFile))) { found = true; } } @@ -340,9 +330,9 @@ protected: // try to guess which include path to use for (std::string incpath : this->IncludeDirectories) { if (!incpath.empty() && incpath.back() != '/') { - incpath = incpath + "/"; + incpath += "/"; } - incpath = incpath + path; + incpath += path; if (srcFile->GetFullPath() == incpath) { // set the path to the guessed path info->FullPath = incpath; @@ -421,9 +411,9 @@ protected: for (std::string path : this->IncludeDirectories) { if (!path.empty() && path.back() != '/') { - path = path + "/"; + path += "/"; } - path = path + fname; + path += fname; if (cmSystemTools::FileExists(path, true) && !cmSystemTools::FileIsDirectory(path)) { std::string fp = cmSystemTools::CollapseFullPath(path); @@ -486,9 +476,7 @@ bool cmOutputRequiredFilesCommand::InitialPass( // write them out FILE* fout = cmsys::SystemTools::Fopen(this->OutputFile, "w"); if (!fout) { - std::string err = "Can not open output file: "; - err += this->OutputFile; - this->SetError(err); + this->SetError(cmStrCat("Can not open output file: ", this->OutputFile)); return false; } std::set<cmDependInformation const*> visited; diff --git a/Source/cmParseArgumentsCommand.cxx b/Source/cmParseArgumentsCommand.cxx index 04fa0fb..2ca3c57 100644 --- a/Source/cmParseArgumentsCommand.cxx +++ b/Source/cmParseArgumentsCommand.cxx @@ -8,6 +8,7 @@ #include <utility> #include "cmArgumentParser.h" +#include "cmExecutionStatus.h" #include "cmMakefile.h" #include "cmMessageType.h" #include "cmRange.h" @@ -15,8 +16,6 @@ #include "cmSystemTools.h" #include "cm_string_view.hxx" -class cmExecutionStatus; - static std::string EscapeArg(const std::string& arg) { // replace ";" with "\;" so output argument lists will split correctly @@ -105,25 +104,25 @@ static void PassParsedArguments( } } -bool cmParseArgumentsCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus&) +bool cmParseArgumentsCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { // cmake_parse_arguments(prefix options single multi <ARGN>) // 1 2 3 4 // or // cmake_parse_arguments(PARSE_ARGV N prefix options single multi) if (args.size() < 4) { - this->SetError("must be called with at least 4 arguments."); + status.SetError("must be called with at least 4 arguments."); return false; } - std::vector<std::string>::const_iterator argIter = args.begin(), - argEnd = args.end(); + std::vector<std::string>::const_iterator argIter = args.begin(); + std::vector<std::string>::const_iterator argEnd = args.end(); bool parseFromArgV = false; unsigned long argvStart = 0; if (*argIter == "PARSE_ARGV") { if (args.size() != 6) { - this->Makefile->IssueMessage( + status.GetMakefile().IssueMessage( MessageType::FATAL_ERROR, "PARSE_ARGV must be called with exactly 6 arguments."); cmSystemTools::SetFatalErrorOccured(); @@ -131,10 +130,10 @@ bool cmParseArgumentsCommand::InitialPass(std::vector<std::string> const& args, } parseFromArgV = true; argIter++; // move past PARSE_ARGV - if (!cmSystemTools::StringToULong(argIter->c_str(), &argvStart)) { - this->Makefile->IssueMessage(MessageType::FATAL_ERROR, - "PARSE_ARGV index '" + *argIter + - "' is not an unsigned integer"); + if (!cmStrToULong(*argIter, &argvStart)) { + status.GetMakefile().IssueMessage(MessageType::FATAL_ERROR, + "PARSE_ARGV index '" + *argIter + + "' is not an unsigned integer"); cmSystemTools::SetFatalErrorOccured(); return true; } @@ -154,24 +153,24 @@ bool cmParseArgumentsCommand::InitialPass(std::vector<std::string> const& args, // anything else is put into a vector of unparsed strings std::vector<std::string> unparsed; - auto const duplicateKey = [this](std::string const& key) { - this->GetMakefile()->IssueMessage( + auto const duplicateKey = [&status](std::string const& key) { + status.GetMakefile().IssueMessage( MessageType::WARNING, "keyword defined more than once: " + key); }; // the second argument is a (cmake) list of options without argument std::vector<std::string> list; - cmSystemTools::ExpandListArgument(*argIter++, list); + cmExpandList(*argIter++, list); parser.Bind(list, options, duplicateKey); // the third argument is a (cmake) list of single argument options list.clear(); - cmSystemTools::ExpandListArgument(*argIter++, list); + cmExpandList(*argIter++, list); parser.Bind(list, singleValArgs, duplicateKey); // the fourth argument is a (cmake) list of multi argument options list.clear(); - cmSystemTools::ExpandListArgument(*argIter++, list); + cmExpandList(*argIter++, list); parser.Bind(list, multiValArgs, duplicateKey); list.clear(); @@ -179,27 +178,28 @@ bool cmParseArgumentsCommand::InitialPass(std::vector<std::string> const& args, // Flatten ;-lists in the arguments into a single list as was done // by the original function(CMAKE_PARSE_ARGUMENTS). for (; argIter != argEnd; ++argIter) { - cmSystemTools::ExpandListArgument(*argIter, list); + cmExpandList(*argIter, list); } } else { // in the PARSE_ARGV move read the arguments from ARGC and ARGV# - std::string argc = this->Makefile->GetSafeDefinition("ARGC"); + std::string argc = status.GetMakefile().GetSafeDefinition("ARGC"); unsigned long count; - if (!cmSystemTools::StringToULong(argc.c_str(), &count)) { - this->Makefile->IssueMessage(MessageType::FATAL_ERROR, - "PARSE_ARGV called with ARGC='" + argc + - "' that is not an unsigned integer"); + if (!cmStrToULong(argc, &count)) { + status.GetMakefile().IssueMessage(MessageType::FATAL_ERROR, + "PARSE_ARGV called with ARGC='" + + argc + + "' that is not an unsigned integer"); cmSystemTools::SetFatalErrorOccured(); return true; } for (unsigned long i = argvStart; i < count; ++i) { std::ostringstream argName; argName << "ARGV" << i; - const char* arg = this->Makefile->GetDefinition(argName.str()); + const char* arg = status.GetMakefile().GetDefinition(argName.str()); if (!arg) { - this->Makefile->IssueMessage(MessageType::FATAL_ERROR, - "PARSE_ARGV called with " + - argName.str() + " not set"); + status.GetMakefile().IssueMessage(MessageType::FATAL_ERROR, + "PARSE_ARGV called with " + + argName.str() + " not set"); cmSystemTools::SetFatalErrorOccured(); return true; } @@ -212,7 +212,8 @@ bool cmParseArgumentsCommand::InitialPass(std::vector<std::string> const& args, parser.Parse(list, &unparsed, &keywordsMissingValues); PassParsedArguments( - prefix, *this->Makefile, options, singleValArgs, multiValArgs, unparsed, + prefix, status.GetMakefile(), options, singleValArgs, multiValArgs, + unparsed, options_set(keywordsMissingValues.begin(), keywordsMissingValues.end()), parseFromArgV); diff --git a/Source/cmParseArgumentsCommand.h b/Source/cmParseArgumentsCommand.h index 692ea64..b2e436d 100644 --- a/Source/cmParseArgumentsCommand.h +++ b/Source/cmParseArgumentsCommand.h @@ -8,32 +8,9 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -/** \class cmParseArgumentsCommand - * - */ -class cmParseArgumentsCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmParseArgumentsCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; -}; +bool cmParseArgumentsCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmPolicies.cxx b/Source/cmPolicies.cxx index 51a61dc..d33cd32 100644 --- a/Source/cmPolicies.cxx +++ b/Source/cmPolicies.cxx @@ -34,7 +34,7 @@ static bool stringToId(const char* input, cmPolicies::PolicyID& pid) } } long id; - if (!cmSystemTools::StringToLong(input + 3, &id)) { + if (!cmStrToLong(input + 3, &id)) { return false; } if (id >= cmPolicies::CMPCOUNT) { diff --git a/Source/cmProjectCommand.cxx b/Source/cmProjectCommand.cxx index 96d9843..f8c5ada 100644 --- a/Source/cmProjectCommand.cxx +++ b/Source/cmProjectCommand.cxx @@ -102,11 +102,10 @@ bool cmProjectCommand::InitialPass(std::vector<std::string> const& args, } doing = DoingLanguages; if (!languages.empty()) { - std::string msg = + std::string msg = cmStrCat( "the following parameters must be specified after LANGUAGES " - "keyword: "; - msg += cmJoin(languages, ", "); - msg += '.'; + "keyword: ", + cmJoin(languages, ", "), '.'); this->Makefile->IssueMessage(MessageType::WARNING, msg); } } else if (args[i] == "VERSION") { @@ -368,9 +367,9 @@ bool cmProjectCommand::IncludeByVariable(const std::string& variable) return true; } - std::string m = "could not find file:\n" - " "; - m += include; + std::string m = cmStrCat("could not find file:\n" + " ", + include); this->SetError(m); return false; } diff --git a/Source/cmQTWrapCPPCommand.cxx b/Source/cmQTWrapCPPCommand.cxx index f5852a9..ba82813 100644 --- a/Source/cmQTWrapCPPCommand.cxx +++ b/Source/cmQTWrapCPPCommand.cxx @@ -6,6 +6,7 @@ #include "cmMakefile.h" #include "cmRange.h" #include "cmSourceFile.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include <utility> @@ -37,10 +38,8 @@ bool cmQTWrapCPPCommand::InitialPass(std::vector<std::string> const& args, // Compute the name of the file to generate. std::string srcName = cmSystemTools::GetFilenameWithoutLastExtension(arg); - std::string newName = this->Makefile->GetCurrentBinaryDirectory(); - newName += "/moc_"; - newName += srcName; - newName += ".cxx"; + std::string newName = cmStrCat( + this->Makefile->GetCurrentBinaryDirectory(), "/moc_", srcName, ".cxx"); cmSourceFile* sf = this->Makefile->GetOrCreateSource(newName, true); if (curr) { sf->SetProperty("ABSTRACT", curr->GetProperty("ABSTRACT")); diff --git a/Source/cmQTWrapUICommand.cxx b/Source/cmQTWrapUICommand.cxx index 361d7b3..8bc914f 100644 --- a/Source/cmQTWrapUICommand.cxx +++ b/Source/cmQTWrapUICommand.cxx @@ -6,6 +6,7 @@ #include "cmMakefile.h" #include "cmRange.h" #include "cmSourceFile.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include <utility> @@ -41,18 +42,12 @@ bool cmQTWrapUICommand::InitialPass(std::vector<std::string> const& args, // Compute the name of the files to generate. std::string srcName = cmSystemTools::GetFilenameWithoutLastExtension(arg); - std::string hName = this->Makefile->GetCurrentBinaryDirectory(); - hName += "/"; - hName += srcName; - hName += ".h"; - std::string cxxName = this->Makefile->GetCurrentBinaryDirectory(); - cxxName += "/"; - cxxName += srcName; - cxxName += ".cxx"; - std::string mocName = this->Makefile->GetCurrentBinaryDirectory(); - mocName += "/moc_"; - mocName += srcName; - mocName += ".cxx"; + std::string hName = cmStrCat(this->Makefile->GetCurrentBinaryDirectory(), + '/', srcName, ".h"); + std::string cxxName = cmStrCat( + this->Makefile->GetCurrentBinaryDirectory(), '/', srcName, ".cxx"); + std::string mocName = cmStrCat( + this->Makefile->GetCurrentBinaryDirectory(), "/moc_", srcName, ".cxx"); // Compute the name of the ui file from which to generate others. std::string uiName; diff --git a/Source/cmQtAutoGen.cxx b/Source/cmQtAutoGen.cxx index 712e22c..9d29e5c 100644 --- a/Source/cmQtAutoGen.cxx +++ b/Source/cmQtAutoGen.cxx @@ -53,9 +53,7 @@ void MergeOptions(std::vector<std::string>& baseOpts, } } // Test if this is a value option and change the existing value - if (!optName.empty() && - (std::find(valueOpts.begin(), valueOpts.end(), optName) != - valueOpts.end())) { + if (!optName.empty() && cmContains(valueOpts, optName)) { const Iter existItNext(existIt + 1); const CIter fitNext(fit + 1); if ((existItNext != baseOpts.end()) && (fitNext != fitEnd)) { @@ -294,9 +292,8 @@ static bool RccListParseOutput(std::string const& rccStdOut, std::string::size_type pos = eline.find(searchString); if (pos == std::string::npos) { - error = "rcc lists unparsable output:\n"; - error += cmQtAutoGen::Quoted(eline); - error += "\n"; + error = cmStrCat("rcc lists unparsable output:\n", + cmQtAutoGen::Quoted(eline), '\n'); return false; } pos += searchString.length(); @@ -325,9 +322,8 @@ bool cmQtAutoGen::RccLister::list(std::string const& qrcFile, error.clear(); if (!cmSystemTools::FileExists(qrcFile, true)) { - error = "The resource file "; - error += Quoted(qrcFile); - error += " does not exist."; + error = + cmStrCat("The resource file ", Quoted(qrcFile), " does not exist."); return false; } @@ -353,9 +349,8 @@ bool cmQtAutoGen::RccLister::list(std::string const& qrcFile, // Log command if (verbose) { - std::string msg = "Running command:\n"; - msg += QuotedCommand(cmd); - msg += '\n'; + std::string msg = + cmStrCat("Running command:\n", QuotedCommand(cmd), '\n'); cmSystemTools::Stdout(msg); } @@ -364,9 +359,8 @@ bool cmQtAutoGen::RccLister::list(std::string const& qrcFile, cmSystemTools::OUTPUT_NONE, cmDuration::zero(), cmProcessOutput::Auto); } if (!result || retVal) { - error = "The rcc list process failed for "; - error += Quoted(qrcFile); - error += "\n"; + error = + cmStrCat("The rcc list process failed for ", Quoted(qrcFile), '\n'); if (!rccStdOut.empty()) { error += rccStdOut; error += "\n"; @@ -392,9 +386,8 @@ bool cmQtAutoGen::RccLister::list(std::string const& qrcFile, osst << ifs.rdbuf(); qrcContents = osst.str(); } else { - error = "The resource file "; - error += Quoted(qrcFile); - error += " is not readable\n"; + error = cmStrCat("The resource file ", Quoted(qrcFile), + " is not readable\n"); return false; } } diff --git a/Source/cmQtAutoGenGlobalInitializer.cxx b/Source/cmQtAutoGenGlobalInitializer.cxx index f172b77..abc69d0 100644 --- a/Source/cmQtAutoGenGlobalInitializer.cxx +++ b/Source/cmQtAutoGenGlobalInitializer.cxx @@ -1,8 +1,6 @@ /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmQtAutoGenGlobalInitializer.h" -#include "cmQtAutoGen.h" -#include "cmQtAutoGenInitializer.h" #include "cmCustomCommandLines.h" #include "cmDuration.h" @@ -11,15 +9,18 @@ #include "cmMakefile.h" #include "cmMessageType.h" #include "cmProcessOutput.h" +#include "cmQtAutoGen.h" +#include "cmQtAutoGenInitializer.h" #include "cmState.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmTarget.h" -#include <utility> - #include "cm_memory.hxx" +#include <utility> + cmQtAutoGenGlobalInitializer::Keywords::Keywords() : AUTOMOC("AUTOMOC") , AUTOUIC("AUTOUIC") @@ -48,8 +49,7 @@ cmQtAutoGenGlobalInitializer::cmQtAutoGenGlobalInitializer( { cmMakefile* makefile = localGen->GetMakefile(); // Detect global autogen target name - if (cmSystemTools::IsOn( - makefile->GetSafeDefinition("CMAKE_GLOBAL_AUTOGEN_TARGET"))) { + if (cmIsOn(makefile->GetSafeDefinition("CMAKE_GLOBAL_AUTOGEN_TARGET"))) { std::string targetName = makefile->GetSafeDefinition("CMAKE_GLOBAL_AUTOGEN_TARGET_NAME"); if (targetName.empty()) { @@ -60,8 +60,7 @@ cmQtAutoGenGlobalInitializer::cmQtAutoGenGlobalInitializer( } // Detect global autorcc target name - if (cmSystemTools::IsOn( - makefile->GetSafeDefinition("CMAKE_GLOBAL_AUTORCC_TARGET"))) { + if (cmIsOn(makefile->GetSafeDefinition("CMAKE_GLOBAL_AUTORCC_TARGET"))) { std::string targetName = makefile->GetSafeDefinition("CMAKE_GLOBAL_AUTORCC_TARGET_NAME"); if (targetName.empty()) { @@ -119,23 +118,17 @@ cmQtAutoGenGlobalInitializer::cmQtAutoGenGlobalInitializer( bool const uicDisabled = (uic && !uicAvailable); bool const rccDisabled = (rcc && !rccAvailable); if (mocDisabled || uicDisabled || rccDisabled) { - std::string msg = "AUTOGEN: No valid Qt version found for target "; - msg += target->GetName(); - msg += ". "; - msg += cmQtAutoGen::Tools(mocDisabled, uicDisabled, rccDisabled); - msg += " disabled. Consider adding:\n"; - { - std::string version = (qtVersion.second == 0) - ? std::string("<QTVERSION>") - : std::to_string(qtVersion.second); - std::string comp = uicDisabled ? "Widgets" : "Core"; - msg += " find_package(Qt"; - msg += version; - msg += " COMPONENTS "; - msg += comp; - msg += ")\n"; - } - msg += "to your CMakeLists.txt file."; + cmAlphaNum version = (qtVersion.second == 0) + ? cmAlphaNum("<QTVERSION>") + : cmAlphaNum(qtVersion.second); + cmAlphaNum component = uicDisabled ? "Widgets" : "Core"; + + std::string const msg = cmStrCat( + "AUTOGEN: No valid Qt version found for target ", + target->GetName(), ". ", + cmQtAutoGen::Tools(mocDisabled, uicDisabled, rccDisabled), + " disabled. Consider adding:\n", " find_package(Qt", version, + " COMPONENTS ", component, ")\n", "to your CMakeLists.txt file."); target->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, msg); } if (mocIsValid || uicIsValid || rccIsValid) { @@ -218,11 +211,8 @@ cmQtAutoGenGlobalInitializer::GetCompilerFeatures( // Check if the executable exists if (!cmSystemTools::FileExists(executable, true)) { - error = "The \""; - error += generator; - error += "\" executable "; - error += cmQtAutoGen::Quoted(executable); - error += " does not exist."; + error = cmStrCat("The \"", generator, "\" executable ", + cmQtAutoGen::Quoted(executable), " does not exist."); return cmQtAutoGen::CompilerFeaturesHandle(); } @@ -238,15 +228,10 @@ cmQtAutoGenGlobalInitializer::GetCompilerFeatures( command, &stdOut, &stdErr, &retVal, nullptr, cmSystemTools::OUTPUT_NONE, cmDuration::zero(), cmProcessOutput::Auto); if (!runResult) { - error = "Test run of \""; - error += generator; - error += "\" executable "; - error += cmQtAutoGen::Quoted(executable) + " failed.\n"; - error += cmQtAutoGen::QuotedCommand(command); - error += "\n"; - error += stdOut; - error += "\n"; - error += stdErr; + error = cmStrCat("Test run of \"", generator, "\" executable ", + cmQtAutoGen::Quoted(executable), " failed.\n", + cmQtAutoGen::QuotedCommand(command), '\n', stdOut, '\n', + stdErr); return cmQtAutoGen::CompilerFeaturesHandle(); } } diff --git a/Source/cmQtAutoGenInitializer.cxx b/Source/cmQtAutoGenInitializer.cxx index da6094d..6718466 100644 --- a/Source/cmQtAutoGenInitializer.cxx +++ b/Source/cmQtAutoGenInitializer.cxx @@ -156,30 +156,27 @@ std::string cmQtAutoGenInitializer::InfoWriter::ListJoin(IT it_begin, return res; } -std::string cmQtAutoGenInitializer::InfoWriter::ConfigKey( - const char* key, std::string const& config) +inline std::string cmQtAutoGenInitializer::InfoWriter::ConfigKey( + cm::string_view key, std::string const& config) { - std::string ckey = key; - ckey += '_'; - ckey += config; - return ckey; + return cmStrCat(key, "_", config); } -void cmQtAutoGenInitializer::InfoWriter::Write(const char* key, +void cmQtAutoGenInitializer::InfoWriter::Write(cm::string_view key, std::string const& value) { Ofs_ << "set(" << key << " " << cmOutputConverter::EscapeForCMake(value) << ")\n"; }; -void cmQtAutoGenInitializer::InfoWriter::WriteUInt(const char* key, +void cmQtAutoGenInitializer::InfoWriter::WriteUInt(cm::string_view key, unsigned int value) { Ofs_ << "set(" << key << " " << value << ")\n"; }; template <class C> -void cmQtAutoGenInitializer::InfoWriter::WriteStrings(const char* key, +void cmQtAutoGenInitializer::InfoWriter::WriteStrings(cm::string_view key, C const& container) { Ofs_ << "set(" << key << " \"" @@ -187,31 +184,29 @@ void cmQtAutoGenInitializer::InfoWriter::WriteStrings(const char* key, } void cmQtAutoGenInitializer::InfoWriter::WriteConfig( - const char* key, std::map<std::string, std::string> const& map) + cm::string_view key, std::map<std::string, std::string> const& map) { for (auto const& item : map) { - Write(ConfigKey(key, item.first).c_str(), item.second); + Write(ConfigKey(key, item.first), item.second); } }; template <class C> void cmQtAutoGenInitializer::InfoWriter::WriteConfigStrings( - const char* key, std::map<std::string, C> const& map) + cm::string_view key, std::map<std::string, C> const& map) { for (auto const& item : map) { - WriteStrings(ConfigKey(key, item.first).c_str(), item.second); + WriteStrings(ConfigKey(key, item.first), item.second); } } void cmQtAutoGenInitializer::InfoWriter::WriteNestedLists( - const char* key, std::vector<std::vector<std::string>> const& lists) + cm::string_view key, std::vector<std::vector<std::string>> const& lists) { std::vector<std::string> seplist; - for (const std::vector<std::string>& list : lists) { - std::string blist = "{"; - blist += ListJoin(list.begin(), list.end()); - blist += "}"; - seplist.push_back(std::move(blist)); + seplist.reserve(lists.size()); + for (std::vector<std::string> const& list : lists) { + seplist.push_back(cmStrCat("{", ListJoin(list.begin(), list.end()), "}")); } Write(key, cmJoin(seplist, cmQtAutoGen::ListSep)); }; @@ -248,9 +243,9 @@ bool cmQtAutoGenInitializer::InitCustomTargets() this->Verbosity = makefile->GetSafeDefinition("CMAKE_AUTOGEN_VERBOSE"); if (!this->Verbosity.empty()) { unsigned long iVerb = 0; - if (!cmSystemTools::StringToULong(this->Verbosity.c_str(), &iVerb)) { + if (!cmStrToULong(this->Verbosity, &iVerb)) { // Non numeric verbosity - this->Verbosity = cmSystemTools::IsOn(this->Verbosity) ? "1" : "0"; + this->Verbosity = cmIsOn(this->Verbosity) ? "1" : "0"; } } @@ -298,21 +293,15 @@ bool cmQtAutoGenInitializer::InitCustomTargets() std::string(), makefile->GetCurrentBinaryDirectory()); // Info directory - this->Dir.Info = cbd; - this->Dir.Info += "/CMakeFiles"; - this->Dir.Info += '/'; - this->Dir.Info += this->Target->GetName(); - this->Dir.Info += "_autogen"; - this->Dir.Info += ".dir"; + this->Dir.Info = + cmStrCat(cbd, "/CMakeFiles/", this->Target->GetName(), "_autogen.dir"); cmSystemTools::ConvertToUnixSlashes(this->Dir.Info); // Build directory this->Dir.Build = this->Target->GetSafeProperty("AUTOGEN_BUILD_DIR"); if (this->Dir.Build.empty()) { - this->Dir.Build = cbd; - this->Dir.Build += '/'; - this->Dir.Build += this->Target->GetName(); - this->Dir.Build += "_autogen"; + this->Dir.Build = + cmStrCat(cbd, '/', this->Target->GetName(), "_autogen"); } cmSystemTools::ConvertToUnixSlashes(this->Dir.Build); // Cleanup build directory @@ -323,8 +312,7 @@ bool cmQtAutoGenInitializer::InitCustomTargets() cmSystemTools::ConvertToUnixSlashes(this->Dir.Work); // Include directory - this->Dir.Include = this->Dir.Build; - this->Dir.Include += "/include"; + this->Dir.Include = cmStrCat(this->Dir.Build, "/include"); if (this->MultiConfig) { this->Dir.Include += "_$<CONFIG>"; } @@ -332,9 +320,7 @@ bool cmQtAutoGenInitializer::InitCustomTargets() if (this->MultiConfig) { for (std::string const& cfg : this->ConfigsList) { std::string& dir = this->Dir.ConfigInclude[cfg]; - dir = this->Dir.Build; - dir += "/include_"; - dir += cfg; + dir = cmStrCat(this->Dir.Build, "/include_", cfg); } } } @@ -352,8 +338,7 @@ bool cmQtAutoGenInitializer::InitCustomTargets() } // Autogen target name - this->AutogenTarget.Name = this->Target->GetName(); - this->AutogenTarget.Name += "_autogen"; + this->AutogenTarget.Name = cmStrCat(this->Target->GetName(), "_autogen"); // Autogen target parallel processing this->AutogenTarget.Parallel = @@ -366,11 +351,11 @@ bool cmQtAutoGenInitializer::InitCustomTargets() // Autogen target info and settings files { - this->AutogenTarget.InfoFile = this->Dir.Info; - this->AutogenTarget.InfoFile += "/AutogenInfo.cmake"; + this->AutogenTarget.InfoFile = + cmStrCat(this->Dir.Info, "/AutogenInfo.cmake"); - this->AutogenTarget.SettingsFile = this->Dir.Info; - this->AutogenTarget.SettingsFile += "/AutogenOldSettings.txt"; + this->AutogenTarget.SettingsFile = + cmStrCat(this->Dir.Info, "/AutogenOldSettings.txt"); if (this->MultiConfig) { for (std::string const& cfg : this->ConfigsList) { @@ -383,8 +368,8 @@ bool cmQtAutoGenInitializer::InitCustomTargets() this->AddCleanFile(this->AutogenTarget.SettingsFile); } - this->AutogenTarget.ParseCacheFile = this->Dir.Info; - this->AutogenTarget.ParseCacheFile += "/ParseCache.txt"; + this->AutogenTarget.ParseCacheFile = + cmStrCat(this->Dir.Info, "/ParseCache.txt"); this->AddCleanFile(this->AutogenTarget.ParseCacheFile); } @@ -397,7 +382,7 @@ bool cmQtAutoGenInitializer::InitCustomTargets() this->Target->GetSafeProperty("AUTOGEN_TARGET_DEPENDS"); if (!deps.empty()) { std::vector<std::string> extraDeps; - cmSystemTools::ExpandListArgument(deps, extraDeps); + cmExpandList(deps, extraDeps); for (std::string const& depName : extraDeps) { // Allow target and file dependencies auto* depTarget = makefile->FindTargetToUse(depName); @@ -412,13 +397,12 @@ bool cmQtAutoGenInitializer::InitCustomTargets() // CMAKE_AUTOMOC_RELAXED_MODE deprecation warning if (this->Moc.Enabled) { - if (cmSystemTools::IsOn( - makefile->GetDefinition("CMAKE_AUTOMOC_RELAXED_MODE"))) { - std::string msg = "AUTOMOC: CMAKE_AUTOMOC_RELAXED_MODE is " - "deprecated an will be removed in the future. "; - msg += "Consider disabling it and converting the target "; - msg += this->Target->GetName(); - msg += " to regular mode."; + if (cmIsOn(makefile->GetDefinition("CMAKE_AUTOMOC_RELAXED_MODE"))) { + std::string msg = + cmStrCat("AUTOMOC: CMAKE_AUTOMOC_RELAXED_MODE is " + "deprecated an will be removed in the future. Consider " + "disabling it and converting the target ", + this->Target->GetName(), " to regular mode."); makefile->IssueMessage(MessageType::AUTHOR_WARNING, msg); } } @@ -458,8 +442,8 @@ bool cmQtAutoGenInitializer::InitMoc() cmLocalGenerator* localGen = this->Target->GetLocalGenerator(); // Mocs compilation file - this->Moc.MocsCompilation = this->Dir.Build; - this->Moc.MocsCompilation += "/mocs_compilation.cpp"; + this->Moc.MocsCompilation = + cmStrCat(this->Dir.Build, "/mocs_compilation.cpp"); // Moc predefs command if (this->Target->GetPropertyAsBool("AUTOMOC_COMPILER_PREDEFINES") && @@ -548,7 +532,7 @@ bool cmQtAutoGenInitializer::InitUic() std::string const usp = this->Target->GetSafeProperty("AUTOUIC_SEARCH_PATHS"); if (!usp.empty()) { - cmSystemTools::ExpandListArgument(usp, this->Uic.SearchPaths); + cmExpandList(usp, this->Uic.SearchPaths); std::string const& srcDir = makefile->GetCurrentSourceDirectory(); for (std::string& path : this->Uic.SearchPaths) { path = cmSystemTools::CollapseFullPath(path, srcDir); @@ -694,7 +678,7 @@ bool cmQtAutoGenInitializer::InitScanFiles() { std::string const opts = sf->GetSafeProperty(kw.AUTORCC_OPTIONS); if (!opts.empty()) { - cmSystemTools::ExpandListArgument(opts, qrc.Options); + cmExpandList(opts, qrc.Options); } } this->Rcc.Qrcs.push_back(std::move(qrc)); @@ -721,14 +705,13 @@ bool cmQtAutoGenInitializer::InitScanFiles() if (muf.MocIt || muf.UicIt) { // Search for the default header file and a private header std::string const& srcPath = muf.SF->GetFullPath(); - std::string basePath = cmQtAutoGen::SubDirPrefix(srcPath); - basePath += cmSystemTools::GetFilenameWithoutLastExtension(srcPath); + std::string basePath = + cmStrCat(cmQtAutoGen::SubDirPrefix(srcPath), + cmSystemTools::GetFilenameWithoutLastExtension(srcPath)); for (auto const& suffix : suffixes) { std::string const suffixedPath = basePath + suffix; for (auto const& ext : exts) { - std::string fullPath = suffixedPath; - fullPath += '.'; - fullPath += ext; + std::string fullPath = cmStrCat(suffixedPath, '.', ext); auto constexpr locationKind = cmSourceFileLocationKind::Known; cmSourceFile* sf = makefile->GetSource(fullPath, locationKind); @@ -814,7 +797,7 @@ bool cmQtAutoGenInitializer::InitScanFiles() if (!uicOpts.empty()) { this->Uic.FileFiles.push_back(std::move(realPath)); std::vector<std::string> optsVec; - cmSystemTools::ExpandListArgument(uicOpts, optsVec); + cmExpandList(uicOpts, optsVec); this->Uic.FileOptions.push_back(std::move(optsVec)); } } else { @@ -833,9 +816,8 @@ bool cmQtAutoGenInitializer::InitScanFiles() this->AutogenTarget.DependFiles.insert(muf->RealPath); } } else if (this->CMP0071Warn) { - std::string msg; - msg += cmPolicies::GetPolicyWarning(cmPolicies::CMP0071); - msg += '\n'; + std::string msg = + cmStrCat(cmPolicies::GetPolicyWarning(cmPolicies::CMP0071), '\n'); std::string property; if (this->Moc.Enabled && this->Uic.Enabled) { property = kw.SKIP_AUTOGEN; @@ -869,8 +851,8 @@ bool cmQtAutoGenInitializer::InitScanFiles() const bool modernQt = (this->QtVersion.Major >= 5); // Target rcc options std::vector<std::string> optionsTarget; - cmSystemTools::ExpandListArgument( - this->Target->GetSafeProperty(kw.AUTORCC_OPTIONS), optionsTarget); + cmExpandList(this->Target->GetSafeProperty(kw.AUTORCC_OPTIONS), + optionsTarget); // Check if file name is unique for (Qrc& qrc : this->Rcc.Qrcs) { @@ -888,30 +870,19 @@ bool cmQtAutoGenInitializer::InitScanFiles() for (Qrc& qrc : this->Rcc.Qrcs) { qrc.PathChecksum = fpathCheckSum.getPart(qrc.QrcFile); // RCC output file name + qrc.RccFile = cmStrCat(this->Dir.Build + "/", qrc.PathChecksum, + "/qrc_", qrc.QrcName, ".cpp"); { - std::string rccFile = this->Dir.Build + "/"; - rccFile += qrc.PathChecksum; - rccFile += "/qrc_"; - rccFile += qrc.QrcName; - rccFile += ".cpp"; - qrc.RccFile = std::move(rccFile); - } - { - std::string base = this->Dir.Info; - base += "/RCC"; - base += qrc.QrcName; + std::string base = cmStrCat(this->Dir.Info, "/RCC", qrc.QrcName); if (!qrc.Unique) { base += qrc.PathChecksum; } - qrc.LockFile = base; - qrc.LockFile += ".lock"; + qrc.LockFile = cmStrCat(base, ".lock"); - qrc.InfoFile = base; - qrc.InfoFile += "Info.cmake"; + qrc.InfoFile = cmStrCat(base, "Info.cmake"); - qrc.SettingsFile = base; - qrc.SettingsFile += "Settings.txt"; + qrc.SettingsFile = cmStrCat(base, "Settings.txt"); if (this->MultiConfig) { for (std::string const& cfg : this->ConfigsList) { @@ -932,8 +903,7 @@ bool cmQtAutoGenInitializer::InitScanFiles() // Replace '-' with '_'. The former is not valid for symbol names. std::replace(name.begin(), name.end(), '-', '_'); if (!qrc.Unique) { - name += "_"; - name += qrc.PathChecksum; + name += cmStrCat("_", qrc.PathChecksum); } std::vector<std::string> nameOpts; nameOpts.emplace_back("-name"); @@ -990,10 +960,8 @@ bool cmQtAutoGenInitializer::InitAutogenTarget() } tools += "UIC"; } - autogenComment = "Automatic "; - autogenComment += tools; - autogenComment += " for target "; - autogenComment += this->Target->GetName(); + autogenComment = + cmStrCat("Automatic ", tools, " for target ", this->Target->GetName()); } // Compose command lines @@ -1157,16 +1125,14 @@ bool cmQtAutoGenInitializer::InitRccTargets() currentLine.push_back("$<CONFIG>"); commandLines.push_back(std::move(currentLine)); } - std::string ccComment = "Automatic RCC for "; - ccComment += FileProjectRelativePath(makefile, qrc.QrcFile); + std::string ccComment = cmStrCat( + "Automatic RCC for ", FileProjectRelativePath(makefile, qrc.QrcFile)); if (qrc.Generated || this->Rcc.GlobalTarget) { // Create custom rcc target std::string ccName; { - ccName = this->Target->GetName(); - ccName += "_arcc_"; - ccName += qrc.QrcName; + ccName = cmStrCat(this->Target->GetName(), "_arcc_", qrc.QrcName); if (!qrc.Unique) { ccName += "_"; ccName += qrc.PathChecksum; @@ -1226,9 +1192,8 @@ bool cmQtAutoGenInitializer::SetupCustomTargets() { // Create info directory on demand if (!cmSystemTools::MakeDirectory(this->Dir.Info)) { - std::string emsg = ("AutoGen: Could not create directory: "); - emsg += Quoted(this->Dir.Info); - cmSystemTools::Error(emsg); + cmSystemTools::Error(cmStrCat("AutoGen: Could not create directory: ", + Quoted(this->Dir.Info))); return false; } @@ -1311,10 +1276,8 @@ bool cmQtAutoGenInitializer::SetupWriteAutogenInfo() } if (muf->MocIt || muf->UicIt) { headers.emplace_back(muf->RealPath); - std::string flags; - flags += muf->MocIt ? 'M' : 'm'; - flags += muf->UicIt ? 'U' : 'u'; - headersFlags.emplace_back(std::move(flags)); + headersFlags.emplace_back( + cmStrCat(muf->MocIt ? "M" : "m", muf->UicIt ? "U" : "u")); } } } @@ -1323,14 +1286,13 @@ bool cmQtAutoGenInitializer::SetupWriteAutogenInfo() cmFilePathChecksum const fpathCheckSum(makefile); std::unordered_set<std::string> emitted; for (std::string const& hdr : headers) { - std::string basePath = fpathCheckSum.getPart(hdr); - basePath += "/moc_"; - basePath += cmSystemTools::GetFilenameWithoutLastExtension(hdr); - for (unsigned int ii = 1; ii != 1024; ++ii) { + std::string basePath = + cmStrCat(fpathCheckSum.getPart(hdr), "/moc_", + cmSystemTools::GetFilenameWithoutLastExtension(hdr)); + for (int ii = 1; ii != 1024; ++ii) { std::string path = basePath; if (ii > 1) { - path += '_'; - path += std::to_string(ii); + path += cmStrCat("_", ii); } path += ".cpp"; if (emitted.emplace(path).second) { @@ -1369,10 +1331,8 @@ bool cmQtAutoGenInitializer::SetupWriteAutogenInfo() } if (muf->MocIt || muf->UicIt) { sources.emplace_back(muf->RealPath); - std::string flags; - flags += muf->MocIt ? 'M' : 'm'; - flags += muf->UicIt ? 'U' : 'u'; - sourcesFlags.emplace_back(std::move(flags)); + sourcesFlags.emplace_back( + cmStrCat(muf->MocIt ? "M" : "m", muf->UicIt ? "U" : "u")); } } } @@ -1426,9 +1386,8 @@ bool cmQtAutoGenInitializer::SetupWriteAutogenInfo() ofs.WriteStrings("AM_UIC_SEARCH_PATHS", this->Uic.SearchPaths); } } else { - std::string err = "AutoGen: Could not write file "; - err += this->AutogenTarget.InfoFile; - cmSystemTools::Error(err); + cmSystemTools::Error(cmStrCat("AutoGen: Could not write file ", + this->AutogenTarget.InfoFile)); return false; } @@ -1467,9 +1426,8 @@ bool cmQtAutoGenInitializer::SetupWriteRccInfo() ofs.WriteStrings("ARCC_OPTIONS", qrc.Options); ofs.WriteStrings("ARCC_INPUTS", qrc.Resources); } else { - std::string err = "AutoRcc: Could not write file "; - err += qrc.InfoFile; - cmSystemTools::Error(err); + cmSystemTools::Error( + cmStrCat("AutoRcc: Could not write file ", qrc.InfoFile)); return false; } } @@ -1524,13 +1482,10 @@ bool cmQtAutoGenInitializer::AddToSourceGroup(std::string const& fileName, if (!groupName.empty()) { sourceGroup = makefile->GetOrCreateSourceGroup(groupName); if (sourceGroup == nullptr) { - std::string err; - err += genNameUpper; - err += " error in "; - err += property; - err += ": Could not find or create the source group "; - err += cmQtAutoGen::Quoted(groupName); - cmSystemTools::Error(err); + cmSystemTools::Error( + cmStrCat(genNameUpper, " error in ", property, + ": Could not find or create the source group ", + cmQtAutoGen::Quoted(groupName))); return false; } } @@ -1550,7 +1505,7 @@ void cmQtAutoGenInitializer::AddCleanFile(std::string const& fileName) static unsigned int CharPtrToUInt(const char* const input) { unsigned long tmp = 0; - if (input != nullptr && cmSystemTools::StringToULong(input, &tmp)) { + if (input != nullptr && cmStrToULong(input, &tmp)) { return static_cast<unsigned int>(tmp); } return 0; @@ -1622,12 +1577,8 @@ bool cmQtAutoGenInitializer::GetQtExecutable(GenVarsT& genVars, bool ignoreMissingTarget) const { auto print_err = [this, &genVars](std::string const& err) { - std::string msg = genVars.GenNameUpper; - msg += " for target "; - msg += this->Target->GetName(); - msg += ": "; - msg += err; - cmSystemTools::Error(msg); + cmSystemTools::Error(cmStrCat(genVars.GenNameUpper, " for target ", + this->Target->GetName(), ": ", err)); }; // Custom executable @@ -1687,11 +1638,8 @@ bool cmQtAutoGenInitializer::GetQtExecutable(GenVarsT& genVars, std::make_shared<cmQtAutoGen::CompilerFeatures>(); return true; } - std::string err = "Could not find "; - err += executable; - err += " executable target "; - err += targetName; - print_err(err); + print_err(cmStrCat("Could not find ", executable, " executable target ", + targetName)); return false; } } diff --git a/Source/cmQtAutoGenInitializer.h b/Source/cmQtAutoGenInitializer.h index eb0d35e..7d72cad 100644 --- a/Source/cmQtAutoGenInitializer.h +++ b/Source/cmQtAutoGenInitializer.h @@ -6,6 +6,7 @@ #include "cmConfigure.h" // IWYU pragma: keep #include "cmGeneratedFileStream.h" #include "cmQtAutoGen.h" +#include "cm_string_view.hxx" #include <map> #include <memory> @@ -85,24 +86,24 @@ public: /// @return True if the file is open explicit operator bool() const { return static_cast<bool>(Ofs_); } - void Write(const char* text) { Ofs_ << text; } - void Write(const char* key, std::string const& value); - void WriteUInt(const char* key, unsigned int value); + void Write(cm::string_view text) { Ofs_ << text; } + void Write(cm::string_view, std::string const& value); + void WriteUInt(cm::string_view, unsigned int value); template <class C> - void WriteStrings(const char* key, C const& container); - void WriteConfig(const char* key, + void WriteStrings(cm::string_view, C const& container); + void WriteConfig(cm::string_view, std::map<std::string, std::string> const& map); template <class C> - void WriteConfigStrings(const char* key, + void WriteConfigStrings(cm::string_view, std::map<std::string, C> const& map); - void WriteNestedLists(const char* key, + void WriteNestedLists(cm::string_view, std::vector<std::vector<std::string>> const& lists); private: template <class IT> static std::string ListJoin(IT it_begin, IT it_end); - static std::string ConfigKey(const char* key, std::string const& config); + static std::string ConfigKey(cm::string_view, std::string const& config); private: cmGeneratedFileStream Ofs_; diff --git a/Source/cmQtAutoGenerator.cxx b/Source/cmQtAutoGenerator.cxx index 2516d84..90361a9 100644 --- a/Source/cmQtAutoGenerator.cxx +++ b/Source/cmQtAutoGenerator.cxx @@ -1,17 +1,17 @@ /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmQtAutoGenerator.h" -#include "cmQtAutoGen.h" - -#include "cmsys/FStream.hxx" #include "cm_memory.hxx" +#include "cmsys/FStream.hxx" #include "cmGlobalGenerator.h" #include "cmMakefile.h" +#include "cmQtAutoGen.h" #include "cmState.h" #include "cmStateDirectory.h" #include "cmStateSnapshot.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmake.h" @@ -22,11 +22,11 @@ cmQtAutoGenerator::Logger::Logger() std::string verbose; if (cmSystemTools::GetEnv("VERBOSE", verbose) && !verbose.empty()) { unsigned long iVerbose = 0; - if (cmSystemTools::StringToULong(verbose.c_str(), &iVerbose)) { + if (cmStrToULong(verbose, &iVerbose)) { SetVerbosity(static_cast<unsigned int>(iVerbose)); } else { // Non numeric verbosity - SetVerbose(cmSystemTools::IsOn(verbose)); + SetVerbose(cmIsOn(verbose)); } } } @@ -34,7 +34,7 @@ cmQtAutoGenerator::Logger::Logger() std::string colorEnv; cmSystemTools::GetEnv("COLOR", colorEnv); if (!colorEnv.empty()) { - SetColorOutput(cmSystemTools::IsOn(colorEnv)); + SetColorOutput(cmIsOn(colorEnv)); } else { SetColorOutput(true); } @@ -46,7 +46,7 @@ cmQtAutoGenerator::Logger::~Logger() = default; void cmQtAutoGenerator::Logger::RaiseVerbosity(std::string const& value) { unsigned long verbosity = 0; - if (cmSystemTools::StringToULong(value.c_str(), &verbosity)) { + if (cmStrToULong(value, &verbosity)) { if (this->Verbosity_ < verbosity) { this->Verbosity_ = static_cast<unsigned int>(verbosity); } @@ -60,19 +60,13 @@ void cmQtAutoGenerator::Logger::SetColorOutput(bool value) std::string cmQtAutoGenerator::Logger::HeadLine(std::string const& title) { - std::string head = title; - head += '\n'; - head.append(head.size() - 1, '-'); - head += '\n'; - return head; + return cmStrCat(title, "\n", std::string(title.size(), '-'), "\n"); } void cmQtAutoGenerator::Logger::Info(GenT genType, std::string const& message) const { - std::string msg = GeneratorName(genType); - msg += ": "; - msg += message; + std::string msg = cmStrCat(GeneratorName(genType), ": ", message); if (msg.back() != '\n') { msg.push_back('\n'); } @@ -110,19 +104,13 @@ void cmQtAutoGenerator::Logger::WarningFile(GenT genType, std::string const& filename, std::string const& message) const { - std::string msg = " "; - msg += Quoted(filename); - msg.push_back('\n'); - // Message - msg += message; - Warning(genType, msg); + Warning(genType, cmStrCat(" ", Quoted(filename), "\n", message)); } void cmQtAutoGenerator::Logger::Error(GenT genType, std::string const& message) const { - std::string msg; - msg += HeadLine(GeneratorName(genType) + " error"); + std::string msg = HeadLine(GeneratorName(genType) + " error"); // Message msg += message; if (msg.back() != '\n') { @@ -139,12 +127,7 @@ void cmQtAutoGenerator::Logger::ErrorFile(GenT genType, std::string const& filename, std::string const& message) const { - std::string emsg = " "; - emsg += Quoted(filename); - emsg += '\n'; - // Message - emsg += message; - Error(genType, emsg); + Error(genType, cmStrCat(" ", Quoted(filename), '\n', message)); } void cmQtAutoGenerator::Logger::ErrorCommand( @@ -280,10 +263,8 @@ bool cmQtAutoGenerator::Run(std::string const& infoFile, InfoFile_ = infoFile; cmSystemTools::ConvertToUnixSlashes(InfoFile_); if (!InfoFileTime_.Load(InfoFile_)) { - std::string msg = "AutoGen: The info file "; - msg += Quoted(InfoFile_); - msg += " is not readable\n"; - cmSystemTools::Stderr(msg); + cmSystemTools::Stderr(cmStrCat("AutoGen: The info file ", + Quoted(InfoFile_), " is not readable\n")); return false; } InfoDir_ = cmSystemTools::GetFilenamePath(infoFile); @@ -317,8 +298,7 @@ bool cmQtAutoGenerator::Run(std::string const& infoFile, std::string cmQtAutoGenerator::SettingsFind(std::string const& content, const char* key) { - std::string prefix(key); - prefix += ':'; + std::string prefix = cmStrCat(key, ':'); std::string::size_type pos = content.find(prefix); if (pos != std::string::npos) { pos += prefix.size(); diff --git a/Source/cmQtAutoMocUic.cxx b/Source/cmQtAutoMocUic.cxx index 0801c24..a82dd3a 100644 --- a/Source/cmQtAutoMocUic.cxx +++ b/Source/cmQtAutoMocUic.cxx @@ -302,10 +302,9 @@ void cmQtAutoMocUic::JobMocPredefsT::Process() } // Execute command if (!RunProcess(GenT::MOC, result, cmd, reason.get())) { - std::string msg = "The content generation command for "; - msg += Quoted(predefsFileRel); - msg += " failed.\n"; - msg += result.ErrorMessage; + std::string msg = + cmStrCat("The content generation command for ", + Quoted(predefsFileRel), " failed.\n", result.ErrorMessage); LogCommandError(GenT::MOC, msg, cmd, result.StdOut); return; } @@ -314,9 +313,8 @@ void cmQtAutoMocUic::JobMocPredefsT::Process() // (Re)write predefs file only on demand if (cmQtAutoGenerator::FileDiffers(predefsFileAbs, result.StdOut)) { if (!cmQtAutoGenerator::FileWrite(predefsFileAbs, result.StdOut)) { - std::string msg = "Writing "; - msg += Quoted(predefsFileRel); - msg += " failed."; + std::string msg = + cmStrCat("Writing ", Quoted(predefsFileRel), " failed."); LogFileError(GenT::MOC, predefsFileAbs, msg); return; } @@ -326,9 +324,8 @@ void cmQtAutoMocUic::JobMocPredefsT::Process() Log().Info(GenT::MOC, "Touching " + Quoted(predefsFileRel)); } if (!cmSystemTools::Touch(predefsFileAbs, false)) { - std::string msg = "Touching "; - msg += Quoted(predefsFileAbs); - msg += " failed."; + std::string msg = + cmStrCat("Touching ", Quoted(predefsFileAbs), " failed."); LogFileError(GenT::MOC, predefsFileAbs, msg); return; } @@ -347,9 +344,8 @@ bool cmQtAutoMocUic::JobMocPredefsT::Update(std::string* reason) const // Test if the file exists if (!MocEval().PredefsTime.Load(MocConst().PredefsFileAbs)) { if (reason != nullptr) { - *reason = "Generating "; - *reason += Quoted(MocConst().PredefsFileRel); - *reason += ", because it doesn't exist."; + *reason = cmStrCat("Generating ", Quoted(MocConst().PredefsFileRel), + ", because it doesn't exist."); } return true; } @@ -357,9 +353,8 @@ bool cmQtAutoMocUic::JobMocPredefsT::Update(std::string* reason) const // Test if the settings changed if (MocConst().SettingsChanged) { if (reason != nullptr) { - *reason = "Generating "; - *reason += Quoted(MocConst().PredefsFileRel); - *reason += ", because the moc settings changed."; + *reason = cmStrCat("Generating ", Quoted(MocConst().PredefsFileRel), + ", because the moc settings changed."); } return true; } @@ -371,11 +366,8 @@ bool cmQtAutoMocUic::JobMocPredefsT::Update(std::string* reason) const if (execTime.Load(exec)) { if (MocEval().PredefsTime.Older(execTime)) { if (reason != nullptr) { - *reason = "Generating "; - *reason += Quoted(MocConst().PredefsFileRel); - *reason += " because it is older than "; - *reason += Quoted(exec); - *reason += "."; + *reason = cmStrCat("Generating ", Quoted(MocConst().PredefsFileRel), + " because it is older than ", Quoted(exec), '.'); } return true; } @@ -663,13 +655,11 @@ bool cmQtAutoMocUic::JobEvaluateT::MocEvalSource( if (!sourceIncludesDotMoc && !parseData.Macro.empty() && !(relaxedMode && sourceIncludesMocUnderscore)) { { - std::string emsg = "The file contains a "; - emsg += Quoted(parseData.Macro); - emsg += " macro, but does not include "; - emsg += Quoted(sourceBase + ".moc"); - emsg += "!\nConsider to\n - add #include \""; - emsg += sourceBase; - emsg += ".moc\"\n - enable SKIP_AUTOMOC for this file"; + std::string emsg = + cmStrCat("The file contains a ", Quoted(parseData.Macro), + " macro, but does not include ", Quoted(sourceBase + ".moc"), + "!\nConsider to\n - add #include \"", sourceBase, + ".moc\"\n - enable SKIP_AUTOMOC for this file"); LogFileError(GenT::MOC, sourceFile.FileName, emsg); } return false; @@ -681,11 +671,11 @@ bool cmQtAutoMocUic::JobEvaluateT::MocEvalSource( SourceFileHandleT header = MocFindIncludedHeader(sourceDir, headerBase); if (!header) { { - std::string msg = "The file includes the moc file "; - msg += Quoted(incKey.Key); - msg += ",\nbut the header could not be found " - "in the following locations\n"; - msg += MocMessageTestHeaders(headerBase); + std::string msg = + cmStrCat("The file includes the moc file ", Quoted(incKey.Key), + ",\nbut the header could not be found " + "in the following locations\n", + MocMessageTestHeaders(headerBase)); LogFileError(GenT::MOC, sourceFile.FileName, msg); } return false; @@ -700,18 +690,14 @@ bool cmQtAutoMocUic::JobEvaluateT::MocEvalSource( // used. This is for KDE4 compatibility. { // Issue a warning - std::string msg = "The file contains a "; - msg += Quoted(parseData.Macro); - msg += " macro, but does not include "; - msg += Quoted(sourceBase + ".moc"); - msg += ".\nInstead it includes "; - msg += Quoted(incKey.Key); - msg += ".\nRunning moc on the source\n "; - msg += Quoted(sourceFile.FileName); - msg += "!\nBetter include "; - msg += Quoted(sourceBase + ".moc"); - msg += " for compatibility with regular mode.\n"; - msg += "This is a CMAKE_AUTOMOC_RELAXED_MODE warning.\n"; + std::string msg = cmStrCat( + "The file contains a ", Quoted(parseData.Macro), + " macro, but does not include ", Quoted(sourceBase + ".moc"), + ".\nInstead it includes ", Quoted(incKey.Key), + ".\nRunning moc on the source\n ", Quoted(sourceFile.FileName), + "!\nBetter include ", Quoted(sourceBase + ".moc"), + " for compatibility with regular mode.\n", + "This is a CMAKE_AUTOMOC_RELAXED_MODE warning.\n"); Log().WarningFile(GenT::MOC, sourceFile.FileName, msg); } // Create mapping @@ -749,12 +735,12 @@ bool cmQtAutoMocUic::JobEvaluateT::MocEvalSource( std::string const headerBase = incKey.Dir + incKey.Base; SourceFileHandleT header = MocFindIncludedHeader(sourceDir, headerBase); if (!header) { - std::string msg = "The file includes the moc file "; - msg += Quoted(incKey.Key); - msg += ",\nwhich seems to be the moc file from a different source " - "file.\nCMAKE_AUTOMOC_RELAXED_MODE: Also a matching header" - "could not be found in the following locations\n"; - msg += MocMessageTestHeaders(headerBase); + std::string msg = + cmStrCat("The file includes the moc file ", Quoted(incKey.Key), + ",\nwhich seems to be the moc file from a different source " + "file.\nCMAKE_AUTOMOC_RELAXED_MODE: Also a matching header" + "could not be found in the following locations\n", + MocMessageTestHeaders(headerBase)); LogFileError(GenT::MOC, sourceFile.FileName, msg); return false; } @@ -764,28 +750,22 @@ bool cmQtAutoMocUic::JobEvaluateT::MocEvalSource( } // Issue a warning if (ownMoc && parseData.Macro.empty()) { - std::string msg = "The file includes the moc file "; - msg += Quoted(incKey.Key); - msg += ", but does not contain a\n"; - msg += MocConst().MacrosString(); - msg += " macro.\nRunning moc on the header\n "; - msg += Quoted(header->FileName); - msg += "!\nBetter include "; - msg += Quoted("moc_" + incKey.Base + ".cpp"); - msg += " for a compatibility with regular mode.\n"; - msg += "This is a CMAKE_AUTOMOC_RELAXED_MODE warning.\n"; + std::string msg = cmStrCat( + "The file includes the moc file ", Quoted(incKey.Key), + ", but does not contain a\n", MocConst().MacrosString(), + " macro.\nRunning moc on the header\n ", Quoted(header->FileName), + "!\nBetter include ", Quoted("moc_" + incKey.Base + ".cpp"), + " for a compatibility with regular mode.\n", + "This is a CMAKE_AUTOMOC_RELAXED_MODE warning.\n"); Log().WarningFile(GenT::MOC, sourceFile.FileName, msg); } else { - std::string msg = "The file includes the moc file "; - msg += Quoted(incKey.Key); - msg += " instead of "; - msg += Quoted("moc_" + incKey.Base + ".cpp"); - msg += ".\nRunning moc on the header\n "; - msg += Quoted(header->FileName); - msg += "!\nBetter include "; - msg += Quoted("moc_" + incKey.Base + ".cpp"); - msg += " for compatibility with regular mode.\n"; - msg += "This is a CMAKE_AUTOMOC_RELAXED_MODE warning.\n"; + std::string msg = cmStrCat( + "The file includes the moc file ", Quoted(incKey.Key), + " instead of ", Quoted("moc_" + incKey.Base + ".cpp"), + ".\nRunning moc on the header\n ", Quoted(header->FileName), + "!\nBetter include ", Quoted("moc_" + incKey.Base + ".cpp"), + " for compatibility with regular mode.\n", + "This is a CMAKE_AUTOMOC_RELAXED_MODE warning.\n"); Log().WarningFile(GenT::MOC, sourceFile.FileName, msg); } // Create mapping @@ -800,22 +780,19 @@ bool cmQtAutoMocUic::JobEvaluateT::MocEvalSource( bool const ownMoc = (incKey.Base == sourceBase); if (!ownMoc) { // Don't allow <BASE>.moc include other than own in regular mode - std::string msg = "The file includes the moc file "; - msg += Quoted(incKey.Key); - msg += ",\nwhich seems to be the moc file from a different " - "source file.\nThis is not supported. Include "; - msg += Quoted(sourceBase + ".moc"); - msg += " to run moc on this source file."; + std::string msg = cmStrCat( + "The file includes the moc file ", Quoted(incKey.Key), + ",\nwhich seems to be the moc file from a different " + "source file.\nThis is not supported. Include ", + Quoted(sourceBase + ".moc"), " to run moc on this source file."); LogFileError(GenT::MOC, sourceFile.FileName, msg); return false; } // Accept but issue a warning if moc isn't required if (parseData.Macro.empty()) { - std::string msg = "The file includes the moc file "; - msg += Quoted(incKey.Key); - msg += ", but does not contain a "; - msg += MocConst().MacrosString(); - msg += " macro."; + std::string msg = cmStrCat( + "The file includes the moc file ", Quoted(incKey.Key), + ", but does not contain a ", MocConst().MacrosString(), " macro."); Log().WarningFile(GenT::MOC, sourceFile.FileName, msg); } // Create mapping @@ -841,9 +818,7 @@ cmQtAutoMocUic::JobEvaluateT::MocFindIncludedHeader( } // Search in include directories for (std::string const& path : MocConst().IncludePaths) { - std::string testPath = path; - testPath += '/'; - testPath += includeBase; + std::string testPath = cmStrCat(path, '/', includeBase); SourceFileHandleT res = MocFindHeader(testPath); if (res) { return res; @@ -893,10 +868,9 @@ std::string cmQtAutoMocUic::JobEvaluateT::MocMessageTestHeaders( { std::ostringstream res; { - std::string exts = ".{"; - exts += cmJoin(BaseConst().HeaderExtensions, ","); - exts += '}'; - // Compose result string + std::string exts = + cmStrCat(".{", cmJoin(BaseConst().HeaderExtensions, ","), + '}'); // Compose result string res << " " << fileBase << exts << '\n'; for (std::string const& path : MocConst().IncludePaths) { res << " " << path << '/' << fileBase << exts << '\n'; @@ -914,9 +888,8 @@ bool cmQtAutoMocUic::JobEvaluateT::MocRegisterIncluded( if (handle) { // Check if the output file would be generated from different source files if (handle->SourceFile != sourceFileHandle) { - std::string msg = "The source files\n "; - msg += Quoted(includerFileHandle->FileName); - msg += '\n'; + std::string msg = cmStrCat("The source files\n ", + Quoted(includerFileHandle->FileName), '\n'); for (auto const& item : handle->IncluderFiles) { msg += " "; msg += Quoted(item->FileName); @@ -1020,9 +993,8 @@ bool cmQtAutoMocUic::JobEvaluateT::UicRegisterMapping( MappingHandleT const& handle = it->second; if (handle->SourceFile != uiFileHandle) { // The output file already gets generated - from a different .ui file! - std::string msg = "The source files\n "; - msg += Quoted(includerFileHandle->FileName); - msg += '\n'; + std::string msg = cmStrCat("The source files\n ", + Quoted(includerFileHandle->FileName), '\n'); for (auto const& item : handle->IncluderFiles) { msg += " "; msg += Quoted(item->FileName); @@ -1063,8 +1035,7 @@ cmQtAutoMocUic::JobEvaluateT::UicFindIncludedUi( std::string const& sourceFile, std::string const& sourceDir, IncludeKeyT const& incKey) const { - std::string searchFileName = incKey.Base; - searchFileName += ".ui"; + std::string searchFileName = cmStrCat(incKey.Base, ".ui"); // Collect search paths list std::vector<std::string> testFiles; { @@ -1074,26 +1045,17 @@ cmQtAutoMocUic::JobEvaluateT::UicFindIncludedUi( // Vicinity of the source testFiles.emplace_back(sourceDir + searchFileName); if (!incKey.Dir.empty()) { - std::string path = sourceDir; - path += incKey.Dir; - path += searchFileName; - testFiles.emplace_back(path); + testFiles.emplace_back(cmStrCat(sourceDir, incKey.Dir, searchFileName)); } // AUTOUIC search paths if (!searchPaths.empty()) { for (std::string const& sPath : searchPaths) { - std::string path = sPath; - path += '/'; - path += searchFileName; - testFiles.emplace_back(std::move(path)); + testFiles.emplace_back(cmStrCat(sPath, '/', searchFileName)); } if (!incKey.Dir.empty()) { for (std::string const& sPath : searchPaths) { - std::string path = sPath; - path += '/'; - path += incKey.Dir; - path += searchFileName; - testFiles.emplace_back(std::move(path)); + testFiles.emplace_back( + cmStrCat(sPath, '/', incKey.Dir, searchFileName)); } } } @@ -1118,11 +1080,10 @@ cmQtAutoMocUic::JobEvaluateT::UicFindIncludedUi( // Log error { - std::string msg = "The file includes the uic file "; - msg += Quoted(incKey.Key); - msg += ",\nbut the user interface file "; - msg += Quoted(searchFileName); - msg += "\ncould not be found in the following locations\n"; + std::string msg = + cmStrCat("The file includes the uic file ", Quoted(incKey.Key), + ",\nbut the user interface file ", Quoted(searchFileName), + "\ncould not be found in the following locations\n"); for (std::string const& testFile : testFiles) { msg += " "; msg += Quoted(testFile); @@ -1205,10 +1166,9 @@ bool cmQtAutoMocUic::JobGenerateT::MocUpdate(MappingT const& mapping, cmFileTime outputFileTime; if (!outputFileTime.Load(outputFile)) { if (reason != nullptr) { - *reason = "Generating "; - *reason += Quoted(outputFile); - *reason += ", because it doesn't exist, from "; - *reason += Quoted(sourceFile); + *reason = + cmStrCat("Generating ", Quoted(outputFile), + ", because it doesn't exist, from ", Quoted(sourceFile)); } return true; } @@ -1216,10 +1176,9 @@ bool cmQtAutoMocUic::JobGenerateT::MocUpdate(MappingT const& mapping, // Test if any setting changed if (MocConst().SettingsChanged) { if (reason != nullptr) { - *reason = "Generating "; - *reason += Quoted(outputFile); - *reason += ", because the uic settings changed, from "; - *reason += Quoted(sourceFile); + *reason = cmStrCat("Generating ", Quoted(outputFile), + ", because the uic settings changed, from ", + Quoted(sourceFile)); } return true; } @@ -1227,10 +1186,9 @@ bool cmQtAutoMocUic::JobGenerateT::MocUpdate(MappingT const& mapping, // Test if the source file is newer if (outputFileTime.Older(mapping.SourceFile->FileTime)) { if (reason != nullptr) { - *reason = "Generating "; - *reason += Quoted(outputFile); - *reason += ", because it's older than its source file, from "; - *reason += Quoted(sourceFile); + *reason = cmStrCat("Generating ", Quoted(outputFile), + ", because it's older than its source file, from ", + Quoted(sourceFile)); } return true; } @@ -1239,12 +1197,9 @@ bool cmQtAutoMocUic::JobGenerateT::MocUpdate(MappingT const& mapping, if (!MocConst().PredefsFileAbs.empty()) { if (outputFileTime.Older(MocEval().PredefsTime)) { if (reason != nullptr) { - *reason = "Generating "; - *reason += Quoted(outputFile); - *reason += ", because it's older than "; - *reason += Quoted(MocConst().PredefsFileAbs); - *reason += ", from "; - *reason += Quoted(sourceFile); + *reason = cmStrCat( + "Generating ", Quoted(outputFile), ", because it's older than ", + Quoted(MocConst().PredefsFileAbs), ", from ", Quoted(sourceFile)); } return true; } @@ -1253,10 +1208,9 @@ bool cmQtAutoMocUic::JobGenerateT::MocUpdate(MappingT const& mapping, // Test if the moc executable is newer if (outputFileTime.Older(MocConst().ExecutableTime)) { if (reason != nullptr) { - *reason = "Generating "; - *reason += Quoted(outputFile); - *reason += ", because it's older than the moc executable, from "; - *reason += Quoted(sourceFile); + *reason = cmStrCat("Generating ", Quoted(outputFile), + ", because it's older than the moc executable, from ", + Quoted(sourceFile)); } return true; } @@ -1276,12 +1230,10 @@ bool cmQtAutoMocUic::JobGenerateT::MocUpdate(MappingT const& mapping, // Test if dependency file is older if (outputFileTime.Older(depMatch.second)) { if (reason != nullptr) { - *reason = "Generating "; - *reason += Quoted(outputFile); - *reason += ", because it's older than its dependency file "; - *reason += Quoted(depMatch.first); - *reason += ", from "; - *reason += Quoted(sourceFile); + *reason = + cmStrCat("Generating ", Quoted(outputFile), + ", because it's older than its dependency file ", + Quoted(depMatch.first), ", from ", Quoted(sourceFile)); } return true; } @@ -1346,10 +1298,9 @@ bool cmQtAutoMocUic::JobGenerateT::UicUpdate(MappingT const& mapping, cmFileTime outputFileTime; if (!outputFileTime.Load(outputFile)) { if (reason != nullptr) { - *reason = "Generating "; - *reason += Quoted(outputFile); - *reason += ", because it doesn't exist, from "; - *reason += Quoted(sourceFile); + *reason = + cmStrCat("Generating ", Quoted(outputFile), + ", because it doesn't exist, from ", Quoted(sourceFile)); } return true; } @@ -1357,10 +1308,9 @@ bool cmQtAutoMocUic::JobGenerateT::UicUpdate(MappingT const& mapping, // Test if the uic settings changed if (UicConst().SettingsChanged) { if (reason != nullptr) { - *reason = "Generating "; - *reason += Quoted(outputFile); - *reason += ", because the uic settings changed, from "; - *reason += Quoted(sourceFile); + *reason = cmStrCat("Generating ", Quoted(outputFile), + ", because the uic settings changed, from ", + Quoted(sourceFile)); } return true; } @@ -1368,10 +1318,9 @@ bool cmQtAutoMocUic::JobGenerateT::UicUpdate(MappingT const& mapping, // Test if the source file is newer if (outputFileTime.Older(mapping.SourceFile->FileTime)) { if (reason != nullptr) { - *reason = "Generating "; - *reason += Quoted(outputFile); - *reason += " because it's older than the source file "; - *reason += Quoted(sourceFile); + *reason = cmStrCat("Generating ", Quoted(outputFile), + " because it's older than the source file ", + Quoted(sourceFile)); } return true; } @@ -1379,10 +1328,9 @@ bool cmQtAutoMocUic::JobGenerateT::UicUpdate(MappingT const& mapping, // Test if the uic executable is newer if (outputFileTime.Older(UicConst().ExecutableTime)) { if (reason != nullptr) { - *reason = "Generating "; - *reason += Quoted(outputFile); - *reason += ", because it's older than the uic executable, from "; - *reason += Quoted(sourceFile); + *reason = cmStrCat("Generating ", Quoted(outputFile), + ", because it's older than the uic executable, from ", + Quoted(sourceFile)); } return true; } @@ -1418,10 +1366,9 @@ void cmQtAutoMocUic::JobMocT::Process() } } else { // Moc command failed - std::string msg = "The moc process failed to compile\n "; - msg += Quoted(sourceFile); - msg += "\ninto\n "; - msg += Quoted(outputFile); + std::string msg = + cmStrCat("The moc process failed to compile\n ", Quoted(sourceFile), + "\ninto\n ", Quoted(outputFile)); if (Mapping->IncluderFiles.empty()) { msg += ".\n"; } else { @@ -1467,11 +1414,9 @@ void cmQtAutoMocUic::JobUicT::Process() } } else { // Uic command failed - std::string msg = "The uic process failed to compile\n "; - msg += Quoted(sourceFile); - msg += "\ninto\n "; - msg += Quoted(outputFile); - msg += "\nincluded by\n"; + std::string msg = + cmStrCat("The uic process failed to compile\n ", Quoted(sourceFile), + "\ninto\n ", Quoted(outputFile), "\nincluded by\n"); for (auto const& item : Mapping->IncluderFiles) { msg += " "; msg += Quoted(item->FileName); @@ -1547,7 +1492,7 @@ bool cmQtAutoMocUic::Init(cmMakefile* makefile) }; auto InfoGetList = [makefile](const char* key) -> std::vector<std::string> { std::vector<std::string> list; - cmSystemTools::ExpandListArgument(makefile->GetSafeDefinition(key), list); + cmExpandList(makefile->GetSafeDefinition(key), list); return list; }; auto InfoGetLists = @@ -1564,12 +1509,7 @@ bool cmQtAutoMocUic::Init(cmMakefile* makefile) if (length >= 2) { std::string::const_iterator itBeg = value.begin() + (pos + 1); std::string::const_iterator itEnd = itBeg + (length - 2); - { - std::string subValue(itBeg, itEnd); - std::vector<std::string> list; - cmSystemTools::ExpandListArgument(subValue, list); - lists.push_back(std::move(list)); - } + lists.emplace_back(cmExpandedList(std::string(itBeg, itEnd))); } pos += length; pos += ListSep.size(); @@ -1580,9 +1520,7 @@ bool cmQtAutoMocUic::Init(cmMakefile* makefile) auto InfoGetConfig = [makefile, this](const char* key) -> std::string { const char* valueConf = nullptr; { - std::string keyConf = key; - keyConf += '_'; - keyConf += InfoConfig(); + std::string keyConf = cmStrCat(key, '_', InfoConfig()); valueConf = makefile->GetDefinition(keyConf); } if (valueConf == nullptr) { @@ -1593,7 +1531,7 @@ bool cmQtAutoMocUic::Init(cmMakefile* makefile) auto InfoGetConfigList = [&InfoGetConfig](const char* key) -> std::vector<std::string> { std::vector<std::string> list; - cmSystemTools::ExpandListArgument(InfoGetConfig(key), list); + cmExpandList(InfoGetConfig(key), list); return list; }; auto LogInfoError = [this](std::string const& msg) -> bool { @@ -1624,7 +1562,7 @@ bool cmQtAutoMocUic::Init(cmMakefile* makefile) BaseConst_.MultiConfig = InfoGetBool("AM_MULTI_CONFIG"); { unsigned long num = 1; - if (cmSystemTools::StringToULong(InfoGet("AM_PARALLEL").c_str(), &num)) { + if (cmStrToULong(InfoGet("AM_PARALLEL"), &num)) { num = std::max<unsigned long>(num, 1); num = std::min<unsigned long>(num, ParallelMax); } @@ -1653,9 +1591,9 @@ bool cmQtAutoMocUic::Init(cmMakefile* makefile) return LogInfoError("CMake executable file name missing."); } if (!BaseConst_.CMakeExecutableTime.Load(BaseConst_.CMakeExecutable)) { - std::string error = "The CMake executable "; - error += Quoted(BaseConst_.CMakeExecutable); - error += " does not exist."; + std::string error = + cmStrCat("The CMake executable ", Quoted(BaseConst_.CMakeExecutable), + " does not exist."); return LogInfoError(error); } BaseConst_.ParseCacheFile = InfoGetConfig("AM_PARSE_CACHE_FILE"); @@ -1672,8 +1610,7 @@ bool cmQtAutoMocUic::Init(cmMakefile* makefile) // - Qt environment { unsigned long qtv = BaseConst_.QtVersionMajor; - if (cmSystemTools::StringToULong(InfoGet("AM_QT_VERSION_MAJOR").c_str(), - &qtv)) { + if (cmStrToULong(InfoGet("AM_QT_VERSION_MAJOR"), &qtv)) { BaseConst_.QtVersionMajor = static_cast<unsigned int>(qtv); } } @@ -1684,9 +1621,9 @@ bool cmQtAutoMocUic::Init(cmMakefile* makefile) MocConst_.Enabled = true; // Load the executable file time if (!MocConst_.ExecutableTime.Load(MocConst_.Executable)) { - std::string error = "The moc executable "; - error += Quoted(MocConst_.Executable); - error += " does not exist."; + std::string error = + cmStrCat("The moc executable ", Quoted(MocConst_.Executable), + " does not exist."); return LogInfoError(error); } for (std::string& sfl : InfoGetList("AM_MOC_SKIP")) { @@ -1752,9 +1689,9 @@ bool cmQtAutoMocUic::Init(cmMakefile* makefile) UicConst_.Enabled = true; // Load the executable file time if (!UicConst_.ExecutableTime.Load(UicConst_.Executable)) { - std::string error = "The uic executable "; - error += Quoted(UicConst_.Executable); - error += " does not exist."; + std::string error = + cmStrCat("The uic executable ", Quoted(UicConst_.Executable), + " does not exist."); return LogInfoError(error); } for (std::string& sfl : InfoGetList("AM_UIC_SKIP")) { @@ -1806,7 +1743,8 @@ bool cmQtAutoMocUic::Init(cmMakefile* makefile) // Headers { // Get file lists - const char *keyFiles = "AM_HEADERS", *keyFlags = "AM_HEADERS_FLAGS"; + const char* keyFiles = "AM_HEADERS"; + const char* keyFlags = "AM_HEADERS_FLAGS"; std::vector<std::string> files = InfoGetList(keyFiles); std::vector<std::string> flags = InfoGetList(keyFlags); std::vector<std::string> builds; @@ -1841,7 +1779,8 @@ bool cmQtAutoMocUic::Init(cmMakefile* makefile) // Sources { - const char *keyFiles = "AM_SOURCES", *keyFlags = "AM_SOURCES_FLAGS"; + const char* keyFiles = "AM_SOURCES"; + const char* keyFlags = "AM_SOURCES_FLAGS"; std::vector<std::string> files = InfoGetList(keyFiles); std::vector<std::string> flags = InfoGetList(keyFlags); if (!MatchSizes(keyFiles, keyFlags, files.size(), flags.size())) { diff --git a/Source/cmQtAutoRcc.cxx b/Source/cmQtAutoRcc.cxx index 59f632d..f15634c 100644 --- a/Source/cmQtAutoRcc.cxx +++ b/Source/cmQtAutoRcc.cxx @@ -29,16 +29,14 @@ bool cmQtAutoRcc::Init(cmMakefile* makefile) auto InfoGetList = [makefile](std::string const& key) -> std::vector<std::string> { std::vector<std::string> list; - cmSystemTools::ExpandListArgument(makefile->GetSafeDefinition(key), list); + cmExpandList(makefile->GetSafeDefinition(key), list); return list; }; auto InfoGetConfig = [makefile, this](std::string const& key) -> std::string { const char* valueConf = nullptr; { - std::string keyConf = key; - keyConf += '_'; - keyConf += InfoConfig(); + std::string keyConf = cmStrCat(key, '_', InfoConfig()); valueConf = makefile->GetDefinition(keyConf); } if (valueConf == nullptr) { @@ -49,7 +47,7 @@ bool cmQtAutoRcc::Init(cmMakefile* makefile) auto InfoGetConfigList = [&InfoGetConfig](std::string const& key) -> std::vector<std::string> { std::vector<std::string> list; - cmSystemTools::ExpandListArgument(InfoGetConfig(key), list); + cmExpandList(InfoGetConfig(key), list); return list; }; auto LogInfoError = [this](std::string const& msg) -> bool { @@ -82,9 +80,8 @@ bool cmQtAutoRcc::Init(cmMakefile* makefile) // - Rcc executable RccExecutable_ = InfoGet("ARCC_RCC_EXECUTABLE"); if (!RccExecutableTime_.Load(RccExecutable_)) { - std::string error = "The rcc executable "; - error += Quoted(RccExecutable_); - error += " does not exist."; + std::string error = cmStrCat("The rcc executable ", Quoted(RccExecutable_), + " does not exist."); return LogInfoError(error); } RccListOptions_ = InfoGetList("ARCC_RCC_LIST_OPTIONS"); @@ -125,17 +122,12 @@ bool cmQtAutoRcc::Init(cmMakefile* makefile) // Init derived information // ------------------------ - RccFilePublic_ = AutogenBuildDir_; - RccFilePublic_ += '/'; - RccFilePublic_ += RccPathChecksum_; - RccFilePublic_ += '/'; - RccFilePublic_ += RccFileName_; + RccFilePublic_ = + cmStrCat(AutogenBuildDir_, '/', RccPathChecksum_, '/', RccFileName_); // Compute rcc output file name if (IsMultiConfig()) { - RccFileOutput_ = IncludeDir_; - RccFileOutput_ += '/'; - RccFileOutput_ += MultiConfigOutput(); + RccFileOutput_ = cmStrCat(IncludeDir_, '/', MultiConfigOutput()); } else { RccFileOutput_ = RccFilePublic_; } @@ -179,10 +171,8 @@ bool cmQtAutoRcc::Process() std::string cmQtAutoRcc::MultiConfigOutput() const { static std::string const suffix = "_CMAKE_"; - std::string res; - res += RccPathChecksum_; - res += '/'; - res += AppendFilenameSuffix(RccFileName_, suffix); + std::string res = cmStrCat(RccPathChecksum_, '/', + AppendFilenameSuffix(RccFileName_, suffix)); return res; } @@ -193,21 +183,10 @@ bool cmQtAutoRcc::SettingsFileRead() cmCryptoHash crypt(cmCryptoHash::AlgoSHA256); std::string const sep(" ~~~ "); { - std::string str; - str += RccExecutable_; - str += sep; - str += cmJoin(RccListOptions_, ";"); - str += sep; - str += QrcFile_; - str += sep; - str += RccPathChecksum_; - str += sep; - str += RccFileName_; - str += sep; - str += cmJoin(Options_, ";"); - str += sep; - str += cmJoin(Inputs_, ";"); - str += sep; + std::string str = + cmStrCat(RccExecutable_, sep, cmJoin(RccListOptions_, ";"), sep, + QrcFile_, sep, RccPathChecksum_, sep, RccFileName_, sep, + cmJoin(Options_, ";"), sep, cmJoin(Inputs_, ";"), sep); SettingsString_ = crypt.HashString(str); } } @@ -273,9 +252,7 @@ bool cmQtAutoRcc::SettingsFileWrite() Log().Info(GenT::RCC, "Writing settings file " + Quoted(SettingsFile_)); } // Write settings file - std::string content = "rcc:"; - content += SettingsString_; - content += '\n'; + std::string content = cmStrCat("rcc:", SettingsString_, '\n'); std::string error; if (!FileWrite(SettingsFile_, content, &error)) { Log().ErrorFile(GenT::RCC, SettingsFile_, @@ -297,9 +274,8 @@ bool cmQtAutoRcc::TestQrcRccFiles(bool& generate) // Test if the rcc input file exists if (!QrcFileTime_.Load(QrcFile_)) { std::string error; - error = "The resources file "; - error += Quoted(QrcFile_); - error += " does not exist"; + error = + cmStrCat("The resources file ", Quoted(QrcFile_), " does not exist"); Log().ErrorFile(GenT::RCC, QrcFile_, error); return false; } @@ -307,10 +283,8 @@ bool cmQtAutoRcc::TestQrcRccFiles(bool& generate) // Test if the rcc output file exists if (!RccFileTime_.Load(RccFileOutput_)) { if (Log().Verbose()) { - Reason = "Generating "; - Reason += Quoted(RccFileOutput_); - Reason += ", because it doesn't exist, from "; - Reason += Quoted(QrcFile_); + Reason = cmStrCat("Generating ", Quoted(RccFileOutput_), + ", because it doesn't exist, from ", Quoted(QrcFile_)); } generate = true; return true; @@ -319,10 +293,9 @@ bool cmQtAutoRcc::TestQrcRccFiles(bool& generate) // Test if the settings changed if (SettingsChanged_) { if (Log().Verbose()) { - Reason = "Generating "; - Reason += Quoted(RccFileOutput_); - Reason += ", because the rcc settings changed, from "; - Reason += Quoted(QrcFile_); + Reason = cmStrCat("Generating ", Quoted(RccFileOutput_), + ", because the rcc settings changed, from ", + Quoted(QrcFile_)); } generate = true; return true; @@ -331,12 +304,9 @@ bool cmQtAutoRcc::TestQrcRccFiles(bool& generate) // Test if the rcc output file is older than the .qrc file if (RccFileTime_.Older(QrcFileTime_)) { if (Log().Verbose()) { - Reason = "Generating "; - Reason += Quoted(RccFileOutput_); - Reason += ", because it is older than "; - Reason += Quoted(QrcFile_); - Reason += ", from "; - Reason += Quoted(QrcFile_); + Reason = cmStrCat("Generating ", Quoted(RccFileOutput_), + ", because it is older than ", Quoted(QrcFile_), + ", from ", Quoted(QrcFile_)); } generate = true; return true; @@ -345,10 +315,9 @@ bool cmQtAutoRcc::TestQrcRccFiles(bool& generate) // Test if the rcc output file is older than the rcc executable if (RccFileTime_.Older(RccExecutableTime_)) { if (Log().Verbose()) { - Reason = "Generating "; - Reason += Quoted(RccFileOutput_); - Reason += ", because it is older than the rcc executable, from "; - Reason += Quoted(QrcFile_); + Reason = cmStrCat("Generating ", Quoted(RccFileOutput_), + ", because it is older than the rcc executable, from ", + Quoted(QrcFile_)); } generate = true; return true; @@ -375,21 +344,17 @@ bool cmQtAutoRcc::TestResources(bool& generate) cmFileTime fileTime; if (!fileTime.Load(resFile)) { std::string error; - error = "Could not find the resource file\n "; - error += Quoted(resFile); - error += '\n'; + error = cmStrCat("Could not find the resource file\n ", Quoted(resFile), + '\n'); Log().ErrorFile(GenT::RCC, QrcFile_, error); return false; } // Check if the resource file is newer than the rcc output file if (RccFileTime_.Older(fileTime)) { if (Log().Verbose()) { - Reason = "Generating "; - Reason += Quoted(RccFileOutput_); - Reason += ", because it is older than "; - Reason += Quoted(resFile); - Reason += ", from "; - Reason += Quoted(QrcFile_); + Reason = cmStrCat("Generating ", Quoted(RccFileOutput_), + ", because it is older than ", Quoted(resFile), + ", from ", Quoted(QrcFile_)); } generate = true; break; @@ -403,10 +368,9 @@ bool cmQtAutoRcc::TestInfoFile() // Test if the rcc output file is older than the info file if (RccFileTime_.Older(InfoFileTime())) { if (Log().Verbose()) { - std::string reason = "Touching "; - reason += Quoted(RccFileOutput_); - reason += " because it is older than "; - reason += Quoted(InfoFile()); + std::string reason = + cmStrCat("Touching ", Quoted(RccFileOutput_), + " because it is older than ", Quoted(InfoFile())); Log().Info(GenT::RCC, reason); } // Touch build file @@ -457,10 +421,9 @@ bool cmQtAutoRcc::GenerateRcc() if (!result || (retVal != 0)) { // rcc process failed { - std::string err = "The rcc process failed to compile\n "; - err += Quoted(QrcFile_); - err += "\ninto\n "; - err += Quoted(RccFileOutput_); + std::string err = + cmStrCat("The rcc process failed to compile\n ", Quoted(QrcFile_), + "\ninto\n ", Quoted(RccFileOutput_)); Log().ErrorCommand(GenT::RCC, err, cmd, rccStdOut + rccStdErr); } cmSystemTools::RemoveFile(RccFileOutput_); @@ -482,12 +445,10 @@ bool cmQtAutoRcc::GenerateWrapper() // Generate a wrapper source file on demand if (IsMultiConfig()) { // Wrapper file content - std::string content; - content += "// This is an autogenerated configuration wrapper file.\n"; - content += "// Changes will be overwritten.\n"; - content += "#include <"; - content += MultiConfigOutput(); - content += ">\n"; + std::string content = + cmStrCat("// This is an autogenerated configuration wrapper file.\n", + "// Changes will be overwritten.\n", "#include <", + MultiConfigOutput(), ">\n"); // Compare with existing file content bool fileDiffers = true; diff --git a/Source/cmRST.cxx b/Source/cmRST.cxx index a329f7d..1f9aae8 100644 --- a/Source/cmRST.cxx +++ b/Source/cmRST.cxx @@ -342,7 +342,7 @@ void cmRST::OutputMarkupLines(bool inlineMarkup) { for (auto line : this->MarkupLines) { if (!line.empty()) { - line = " " + line; + line = cmStrCat(" ", line); } this->OutputLine(line, inlineMarkup); } diff --git a/Source/cmRemoveCommand.cxx b/Source/cmRemoveCommand.cxx index d0ee4d4..457b708 100644 --- a/Source/cmRemoveCommand.cxx +++ b/Source/cmRemoveCommand.cxx @@ -2,14 +2,13 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmRemoveCommand.h" +#include "cmExecutionStatus.h" #include "cmMakefile.h" -#include "cmSystemTools.h" - -class cmExecutionStatus; +#include "cmStringAlgorithms.h" // cmRemoveCommand -bool cmRemoveCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus&) +bool cmRemoveCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.empty()) { return true; @@ -17,7 +16,7 @@ bool cmRemoveCommand::InitialPass(std::vector<std::string> const& args, std::string const& variable = args[0]; // VAR is always first // get the old value - const char* cacheValue = this->Makefile->GetDefinition(variable); + const char* cacheValue = status.GetMakefile().GetDefinition(variable); // if there is no old value then return if (!cacheValue) { @@ -25,13 +24,12 @@ bool cmRemoveCommand::InitialPass(std::vector<std::string> const& args, } // expand the variable - std::vector<std::string> const varArgsExpanded = - cmSystemTools::ExpandedListArgument(cacheValue); + std::vector<std::string> const varArgsExpanded = cmExpandedList(cacheValue); // expand the args // check for REMOVE(VAR v1 v2 ... vn) std::vector<std::string> const argsExpanded = - cmSystemTools::ExpandedLists(args.begin() + 1, args.end()); + cmExpandedLists(args.begin() + 1, args.end()); // now create the new value std::string value; @@ -52,7 +50,7 @@ bool cmRemoveCommand::InitialPass(std::vector<std::string> const& args, } // add the definition - this->Makefile->AddDefinition(variable, value); + status.GetMakefile().AddDefinition(variable, value); return true; } diff --git a/Source/cmRemoveCommand.h b/Source/cmRemoveCommand.h index 088d8ad..fb72ab5 100644 --- a/Source/cmRemoveCommand.h +++ b/Source/cmRemoveCommand.h @@ -8,34 +8,14 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -/** \class cmRemoveCommand +/** * \brief remove command * * cmRemoveCommand implements the remove CMake command */ -class cmRemoveCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmRemoveCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; -}; +bool cmRemoveCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmRuntimeDependencyArchive.cxx b/Source/cmRuntimeDependencyArchive.cxx index 45aff69..1b3f387 100644 --- a/Source/cmRuntimeDependencyArchive.cxx +++ b/Source/cmRuntimeDependencyArchive.cxx @@ -6,14 +6,15 @@ #include "cmBinUtilsLinuxELFLinker.h" #include "cmBinUtilsMacOSMachOLinker.h" #include "cmBinUtilsWindowsPELinker.h" -#include "cmCommand.h" +#include "cmExecutionStatus.h" #include "cmMakefile.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #if defined(_WIN32) # include "cmGlobalGenerator.h" -# ifdef CMAKE_BUILD_WITH_CMAKE +# ifndef CMAKE_BOOTSTRAP # include "cmGlobalVisualStudioVersionedGenerator.h" # endif # include "cmVSSetupHelper.h" @@ -36,7 +37,7 @@ static void AddVisualStudioPath(std::vector<std::string>& paths, // If generating for the VS IDE, use the same instance. std::string vsloc; bool found = false; -# ifdef CMAKE_BUILD_WITH_CMAKE +# ifndef CMAKE_BOOTSTRAP if (gg->GetName().find(prefix) == 0) { cmGlobalVisualStudioVersionedGenerator* vsgen = static_cast<cmGlobalVisualStudioVersionedGenerator*>(gg); @@ -108,13 +109,13 @@ static cmsys::RegularExpression TransformCompile(const std::string& str) } cmRuntimeDependencyArchive::cmRuntimeDependencyArchive( - cmCommand* command, std::vector<std::string> searchDirectories, + cmExecutionStatus& status, std::vector<std::string> searchDirectories, std::string bundleExecutable, const std::vector<std::string>& preIncludeRegexes, const std::vector<std::string>& preExcludeRegexes, const std::vector<std::string>& postIncludeRegexes, const std::vector<std::string>& postExcludeRegexes) - : Command(command) + : Status(status) , SearchDirectories(std::move(searchDirectories)) , BundleExecutable(std::move(bundleExecutable)) , PreIncludeRegexes(preIncludeRegexes.size()) @@ -190,7 +191,7 @@ bool cmRuntimeDependencyArchive::GetRuntimeDependencies( void cmRuntimeDependencyArchive::SetError(const std::string& e) { - this->Command->SetError(e); + this->Status.SetError(e); } std::string cmRuntimeDependencyArchive::GetBundleExecutable() @@ -217,7 +218,7 @@ bool cmRuntimeDependencyArchive::GetGetRuntimeDependenciesCommand( std::string toolCommand = this->GetMakefile()->GetSafeDefinition( "CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND"); if (!toolCommand.empty()) { - cmSystemTools::ExpandListArgument(toolCommand, command); + cmExpandList(toolCommand, command); return true; } @@ -361,7 +362,7 @@ void cmRuntimeDependencyArchive::AddUnresolvedPath(const std::string& name) cmMakefile* cmRuntimeDependencyArchive::GetMakefile() { - return this->Command->GetMakefile(); + return &this->Status.GetMakefile(); } const std::map<std::string, std::set<std::string>>& diff --git a/Source/cmRuntimeDependencyArchive.h b/Source/cmRuntimeDependencyArchive.h index 67efec7..e063121 100644 --- a/Source/cmRuntimeDependencyArchive.h +++ b/Source/cmRuntimeDependencyArchive.h @@ -14,14 +14,14 @@ #include <string> #include <vector> -class cmCommand; +class cmExecutionStatus; class cmMakefile; class cmRuntimeDependencyArchive { public: explicit cmRuntimeDependencyArchive( - cmCommand* command, std::vector<std::string> searchDirectories, + cmExecutionStatus& status, std::vector<std::string> searchDirectories, std::string bundleExecutable, const std::vector<std::string>& preIncludeRegexes, const std::vector<std::string>& preExcludeRegexes, @@ -51,7 +51,7 @@ public: const std::set<std::string>& GetUnresolvedPaths(); private: - cmCommand* Command; + cmExecutionStatus& Status; std::unique_ptr<cmBinUtilsLinker> Linker; std::string GetRuntimeDependenciesTool; diff --git a/Source/cmScriptGenerator.cxx b/Source/cmScriptGenerator.cxx index 9182b41..1438f07 100644 --- a/Source/cmScriptGenerator.cxx +++ b/Source/cmScriptGenerator.cxx @@ -2,6 +2,7 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmScriptGenerator.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include <utility> @@ -51,9 +52,8 @@ static void cmScriptGeneratorEncodeConfig(const std::string& config, std::string cmScriptGenerator::CreateConfigTest(const std::string& config) { - std::string result = "\"${"; - result += this->RuntimeConfigVariable; - result += "}\" MATCHES \"^("; + std::string result = + cmStrCat("\"${", this->RuntimeConfigVariable, "}\" MATCHES \"^("); if (!config.empty()) { cmScriptGeneratorEncodeConfig(config, result); } @@ -64,9 +64,8 @@ std::string cmScriptGenerator::CreateConfigTest(const std::string& config) std::string cmScriptGenerator::CreateConfigTest( std::vector<std::string> const& configs) { - std::string result = "\"${"; - result += this->RuntimeConfigVariable; - result += "}\" MATCHES \"^("; + std::string result = + cmStrCat("\"${", this->RuntimeConfigVariable, "}\" MATCHES \"^("); const char* sep = ""; for (std::string const& config : configs) { result += sep; diff --git a/Source/cmSearchPath.cxx b/Source/cmSearchPath.cxx index 879cc95..affff54 100644 --- a/Source/cmSearchPath.cxx +++ b/Source/cmSearchPath.cxx @@ -79,7 +79,7 @@ void cmSearchPath::AddCMakePath(const std::string& variable) // Get a path from a CMake variable. if (const char* value = this->FC->Makefile->GetDefinition(variable)) { std::vector<std::string> expanded; - cmSystemTools::ExpandListArgument(value, expanded); + cmExpandList(value, expanded); for (std::string const& p : expanded) { this->AddPathInternal( @@ -104,7 +104,7 @@ void cmSearchPath::AddCMakePrefixPath(const std::string& variable) // Get a path from a CMake variable. if (const char* value = this->FC->Makefile->GetDefinition(variable)) { std::vector<std::string> expanded; - cmSystemTools::ExpandListArgument(value, expanded); + cmExpandList(value, expanded); this->AddPrefixPaths( expanded, this->FC->Makefile->GetCurrentSourceDirectory().c_str()); diff --git a/Source/cmSeparateArgumentsCommand.cxx b/Source/cmSeparateArgumentsCommand.cxx index ab4a0c7..27f45a8 100644 --- a/Source/cmSeparateArgumentsCommand.cxx +++ b/Source/cmSeparateArgumentsCommand.cxx @@ -5,17 +5,16 @@ #include <algorithm> #include <sstream> +#include "cmExecutionStatus.h" #include "cmMakefile.h" #include "cmSystemTools.h" -class cmExecutionStatus; - // cmSeparateArgumentsCommand -bool cmSeparateArgumentsCommand::InitialPass( - std::vector<std::string> const& args, cmExecutionStatus&) +bool cmSeparateArgumentsCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.empty()) { - this->SetError("must be given at least one argument."); + status.SetError("must be given at least one argument."); return false; } @@ -59,17 +58,17 @@ bool cmSeparateArgumentsCommand::InitialPass( } else { std::ostringstream e; e << "given unknown argument " << arg; - this->SetError(e.str()); + status.SetError(e.str()); return false; } } if (mode == ModeOld) { // Original space-replacement version of command. - if (const char* def = this->Makefile->GetDefinition(var)) { + if (const char* def = status.GetMakefile().GetDefinition(var)) { std::string value = def; std::replace(value.begin(), value.end(), ' ', ';'); - this->Makefile->AddDefinition(var, value); + status.GetMakefile().AddDefinition(var, value); } } else { // Parse the command line. @@ -97,7 +96,7 @@ bool cmSeparateArgumentsCommand::InitialPass( value += si; } } - this->Makefile->AddDefinition(var, value); + status.GetMakefile().AddDefinition(var, value); } return true; diff --git a/Source/cmSeparateArgumentsCommand.h b/Source/cmSeparateArgumentsCommand.h index 76e2002..e000c51 100644 --- a/Source/cmSeparateArgumentsCommand.h +++ b/Source/cmSeparateArgumentsCommand.h @@ -8,34 +8,14 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -/** \class cmSeparateArgumentsCommand +/** * \brief separate_arguments command * * cmSeparateArgumentsCommand implements the separate_arguments CMake command */ -class cmSeparateArgumentsCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmSeparateArgumentsCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; -}; +bool cmSeparateArgumentsCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmServerProtocol.cxx b/Source/cmServerProtocol.cxx index 8fcb710..670161d 100644 --- a/Source/cmServerProtocol.cxx +++ b/Source/cmServerProtocol.cxx @@ -2,6 +2,7 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmServerProtocol.h" +#include "cmAlgorithms.h" #include "cmExternalMakefileProjectGenerator.h" #include "cmFileMonitor.h" #include "cmGlobalGenerator.h" @@ -433,7 +434,7 @@ cmServerResponse cmServerProtocol1::ProcessCache( keys = allKeys; } else { for (auto const& i : keys) { - if (std::find(allKeys.begin(), allKeys.end(), i) == allKeys.end()) { + if (!cmContains(allKeys, i)) { return request.ReportError("Key \"" + i + "\" not found in cache."); } } diff --git a/Source/cmSetCommand.cxx b/Source/cmSetCommand.cxx index 1a12785..8c3a4cb 100644 --- a/Source/cmSetCommand.cxx +++ b/Source/cmSetCommand.cxx @@ -2,6 +2,7 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmSetCommand.h" +#include "cmExecutionStatus.h" #include "cmMakefile.h" #include "cmMessageType.h" #include "cmRange.h" @@ -10,14 +11,12 @@ #include "cmStringAlgorithms.h" #include "cmSystemTools.h" -class cmExecutionStatus; - // cmSetCommand -bool cmSetCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus&) +bool cmSetCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.empty()) { - this->SetError("called with incorrect number of arguments"); + status.SetError("called with incorrect number of arguments"); return false; } @@ -45,7 +44,7 @@ bool cmSetCommand::InitialPass(std::vector<std::string> const& args, std::string m = "Only the first value argument is used when setting " "an environment variable. Argument '" + args[2] + "' and later are unused."; - this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, m); + status.GetMakefile().IssueMessage(MessageType::AUTHOR_WARNING, m); } return true; } @@ -59,13 +58,13 @@ bool cmSetCommand::InitialPass(std::vector<std::string> const& args, // SET (VAR) // Removes the definition of VAR. if (args.size() == 1) { - this->Makefile->RemoveDefinition(variable); + status.GetMakefile().RemoveDefinition(variable); return true; } // SET (VAR PARENT_SCOPE) // Removes the definition of VAR // in the parent scope. if (args.size() == 2 && args.back() == "PARENT_SCOPE") { - this->Makefile->RaiseScope(variable, nullptr); + status.GetMakefile().RaiseScope(variable, nullptr); return true; } @@ -106,7 +105,7 @@ bool cmSetCommand::InitialPass(std::vector<std::string> const& args, value = cmJoin(cmMakeRange(args).advance(1).retreat(ignoreLastArgs), ";"); if (parentScope) { - this->Makefile->RaiseScope(variable, value.c_str()); + status.GetMakefile().RaiseScope(variable, value.c_str()); return true; } @@ -116,7 +115,7 @@ bool cmSetCommand::InitialPass(std::vector<std::string> const& args, if ((args.back() == "CACHE") || (args.size() > 1 && args[args.size() - 2] == "CACHE") || (force && !cache)) { - this->SetError("given invalid arguments for CACHE mode."); + status.SetError("given invalid arguments for CACHE mode."); return false; } @@ -125,7 +124,7 @@ bool cmSetCommand::InitialPass(std::vector<std::string> const& args, if (!cmState::StringToCacheEntryType(args[cacheStart + 1].c_str(), type)) { std::string m = "implicitly converting '" + args[cacheStart + 1] + "' to 'STRING' type."; - this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, m); + status.GetMakefile().IssueMessage(MessageType::AUTHOR_WARNING, m); // Setting this may not be required, since it's // initialized as a string. Keeping this here to // ensure that the type is actually converting to a string. @@ -135,7 +134,7 @@ bool cmSetCommand::InitialPass(std::vector<std::string> const& args, } // see if this is already in the cache - cmState* state = this->Makefile->GetState(); + cmState* state = status.GetMakefile().GetState(); const char* existingValue = state->GetCacheEntryValue(variable); if (existingValue && (state->GetCacheEntryType(variable) != cmStateEnums::UNINITIALIZED)) { @@ -150,11 +149,11 @@ bool cmSetCommand::InitialPass(std::vector<std::string> const& args, // if it is meant to be in the cache then define it in the cache if (cache) { - this->Makefile->AddCacheDefinition(variable, value.c_str(), docstring, - type, force); + status.GetMakefile().AddCacheDefinition(variable, value.c_str(), docstring, + type, force); } else { // add the definition - this->Makefile->AddDefinition(variable, value); + status.GetMakefile().AddDefinition(variable, value); } return true; } diff --git a/Source/cmSetCommand.h b/Source/cmSetCommand.h index 1c5a435..0973d33 100644 --- a/Source/cmSetCommand.h +++ b/Source/cmSetCommand.h @@ -8,34 +8,14 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -/** \class cmSetCommand +/** * \brief Set a CMAKE variable * * cmSetCommand sets a variable to a value with expansion. */ -class cmSetCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmSetCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; -}; +bool cmSetCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmSetDirectoryPropertiesCommand.cxx b/Source/cmSetDirectoryPropertiesCommand.cxx index 8d3961a..35daca6 100644 --- a/Source/cmSetDirectoryPropertiesCommand.cxx +++ b/Source/cmSetDirectoryPropertiesCommand.cxx @@ -2,31 +2,37 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmSetDirectoryPropertiesCommand.h" +#include "cmExecutionStatus.h" #include "cmMakefile.h" -class cmExecutionStatus; +namespace { +bool RunCommand(cmMakefile& mf, std::vector<std::string>::const_iterator ait, + std::vector<std::string>::const_iterator aitend, + std::string& errors); +} // cmSetDirectoryPropertiesCommand -bool cmSetDirectoryPropertiesCommand::InitialPass( - std::vector<std::string> const& args, cmExecutionStatus&) +bool cmSetDirectoryPropertiesCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.empty()) { - this->SetError("called with incorrect number of arguments"); + status.SetError("called with incorrect number of arguments"); return false; } std::string errors; - bool ret = cmSetDirectoryPropertiesCommand::RunCommand( - this->Makefile, args.begin() + 1, args.end(), errors); + bool ret = + RunCommand(status.GetMakefile(), args.begin() + 1, args.end(), errors); if (!ret) { - this->SetError(errors); + status.SetError(errors); } return ret; } -bool cmSetDirectoryPropertiesCommand::RunCommand( - cmMakefile* mf, std::vector<std::string>::const_iterator ait, - std::vector<std::string>::const_iterator aitend, std::string& errors) +namespace { +bool RunCommand(cmMakefile& mf, std::vector<std::string>::const_iterator ait, + std::vector<std::string>::const_iterator aitend, + std::string& errors) { for (; ait != aitend; ait += 2) { if (ait + 1 == aitend) { @@ -43,8 +49,9 @@ bool cmSetDirectoryPropertiesCommand::RunCommand( errors = "Commands and macros cannot be set using SET_CMAKE_PROPERTIES"; return false; } - mf->SetProperty(prop, value.c_str()); + mf.SetProperty(prop, value.c_str()); } return true; } +} diff --git a/Source/cmSetDirectoryPropertiesCommand.h b/Source/cmSetDirectoryPropertiesCommand.h index 5416127..c243dd7 100644 --- a/Source/cmSetDirectoryPropertiesCommand.h +++ b/Source/cmSetDirectoryPropertiesCommand.h @@ -8,35 +8,9 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -class cmMakefile; - -class cmSetDirectoryPropertiesCommand : public cmCommand -{ -public: - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmSetDirectoryPropertiesCommand>(); - } - - /** - * This is called when the command is first encountered in - * the input file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; - /** - * Static entry point for use by other commands - */ - static bool RunCommand(cmMakefile* mf, - std::vector<std::string>::const_iterator ait, - std::vector<std::string>::const_iterator aitend, - std::string& errors); -}; +bool cmSetDirectoryPropertiesCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmSetPropertyCommand.cxx b/Source/cmSetPropertyCommand.cxx index e9343c7..7e3a340 100644 --- a/Source/cmSetPropertyCommand.cxx +++ b/Source/cmSetPropertyCommand.cxx @@ -2,8 +2,10 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmSetPropertyCommand.h" +#include <set> #include <sstream> +#include "cmExecutionStatus.h" #include "cmGlobalGenerator.h" #include "cmInstalledFile.h" #include "cmMakefile.h" @@ -11,25 +13,72 @@ #include "cmRange.h" #include "cmSourceFile.h" #include "cmState.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmTarget.h" #include "cmTest.h" #include "cmake.h" -class cmExecutionStatus; - -cmSetPropertyCommand::cmSetPropertyCommand() -{ - this->AppendMode = false; - this->AppendAsString = false; - this->Remove = true; +namespace { +bool HandleGlobalMode(cmExecutionStatus& status, + const std::set<std::string>& names, + const std::string& propertyName, + const std::string& propertyValue, bool appendAsString, + bool appendMode, bool remove); +bool HandleDirectoryMode(cmExecutionStatus& status, + const std::set<std::string>& names, + const std::string& propertyName, + const std::string& propertyValue, bool appendAsString, + bool appendMode, bool remove); +bool HandleTargetMode(cmExecutionStatus& status, + const std::set<std::string>& names, + const std::string& propertyName, + const std::string& propertyValue, bool appendAsString, + bool appendMode, bool remove); +bool HandleTarget(cmTarget* target, cmMakefile& makefile, + const std::string& propertyName, + const std::string& propertyValue, bool appendAsString, + bool appendMode, bool remove); +bool HandleSourceMode(cmExecutionStatus& status, + const std::set<std::string>& names, + const std::string& propertyName, + const std::string& propertyValue, bool appendAsString, + bool appendMode, bool remove); +bool HandleSource(cmSourceFile* sf, const std::string& propertyName, + const std::string& propertyValue, bool appendAsString, + bool appendMode, bool remove); +bool HandleTestMode(cmExecutionStatus& status, std::set<std::string>& names, + const std::string& propertyName, + const std::string& propertyValue, bool appendAsString, + bool appendMode, bool remove); +bool HandleTest(cmTest* test, const std::string& propertyName, + const std::string& propertyValue, bool appendAsString, + bool appendMode, bool remove); +bool HandleCacheMode(cmExecutionStatus& status, + const std::set<std::string>& names, + const std::string& propertyName, + const std::string& propertyValue, bool appendAsString, + bool appendMode, bool remove); +bool HandleCacheEntry(std::string const& cacheKey, const cmMakefile& makefile, + const std::string& propertyName, + const std::string& propertyValue, bool appendAsString, + bool appendMode, bool remove); +bool HandleInstallMode(cmExecutionStatus& status, + const std::set<std::string>& names, + const std::string& propertyName, + const std::string& propertyValue, bool appendAsString, + bool appendMode, bool remove); +bool HandleInstall(cmInstalledFile* file, cmMakefile& makefile, + const std::string& propertyName, + const std::string& propertyValue, bool appendAsString, + bool appendMode, bool remove); } -bool cmSetPropertyCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus&) +bool cmSetPropertyCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() < 2) { - this->SetError("called with incorrect number of arguments"); + status.SetError("called with incorrect number of arguments"); return false; } @@ -55,10 +104,17 @@ bool cmSetPropertyCommand::InitialPass(std::vector<std::string> const& args, e << "given invalid scope " << scopeName << ". " << "Valid scopes are GLOBAL, DIRECTORY, " "TARGET, SOURCE, TEST, CACHE, INSTALL."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } + bool appendAsString = false; + bool appendMode = false; + bool remove = true; + std::set<std::string> names; + std::string propertyName; + std::string propertyValue; + // Parse the rest of the arguments up to the values. enum Doing { @@ -74,54 +130,61 @@ bool cmSetPropertyCommand::InitialPass(std::vector<std::string> const& args, doing = DoingProperty; } else if (arg == "APPEND") { doing = DoingNone; - this->AppendMode = true; - this->Remove = false; - this->AppendAsString = false; + appendMode = true; + remove = false; + appendAsString = false; } else if (arg == "APPEND_STRING") { doing = DoingNone; - this->AppendMode = true; - this->Remove = false; - this->AppendAsString = true; + appendMode = true; + remove = false; + appendAsString = true; } else if (doing == DoingNames) { - this->Names.insert(arg); + names.insert(arg); } else if (doing == DoingProperty) { - this->PropertyName = arg; + propertyName = arg; doing = DoingValues; } else if (doing == DoingValues) { - this->PropertyValue += sep; + propertyValue += sep; sep = ";"; - this->PropertyValue += arg; - this->Remove = false; + propertyValue += arg; + remove = false; } else { std::ostringstream e; e << "given invalid argument \"" << arg << "\"."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } } // Make sure a property name was found. - if (this->PropertyName.empty()) { - this->SetError("not given a PROPERTY <name> argument."); + if (propertyName.empty()) { + status.SetError("not given a PROPERTY <name> argument."); return false; } // Dispatch property setting. switch (scope) { case cmProperty::GLOBAL: - return this->HandleGlobalMode(); + return HandleGlobalMode(status, names, propertyName, propertyValue, + appendAsString, appendMode, remove); case cmProperty::DIRECTORY: - return this->HandleDirectoryMode(); + return HandleDirectoryMode(status, names, propertyName, propertyValue, + appendAsString, appendMode, remove); case cmProperty::TARGET: - return this->HandleTargetMode(); + return HandleTargetMode(status, names, propertyName, propertyValue, + appendAsString, appendMode, remove); case cmProperty::SOURCE_FILE: - return this->HandleSourceMode(); + return HandleSourceMode(status, names, propertyName, propertyValue, + appendAsString, appendMode, remove); case cmProperty::TEST: - return this->HandleTestMode(); + return HandleTestMode(status, names, propertyName, propertyValue, + appendAsString, appendMode, remove); case cmProperty::CACHE: - return this->HandleCacheMode(); + return HandleCacheMode(status, names, propertyName, propertyValue, + appendAsString, appendMode, remove); case cmProperty::INSTALL: - return this->HandleInstallMode(); + return HandleInstallMode(status, names, propertyName, propertyValue, + appendAsString, appendMode, remove); case cmProperty::VARIABLE: case cmProperty::CACHED_VARIABLE: @@ -130,57 +193,66 @@ bool cmSetPropertyCommand::InitialPass(std::vector<std::string> const& args, return true; } -bool cmSetPropertyCommand::HandleGlobalMode() +namespace { +bool HandleGlobalMode(cmExecutionStatus& status, + const std::set<std::string>& names, + const std::string& propertyName, + const std::string& propertyValue, + const bool appendAsString, const bool appendMode, + const bool remove) { - if (!this->Names.empty()) { - this->SetError("given names for GLOBAL scope."); + if (!names.empty()) { + status.SetError("given names for GLOBAL scope."); return false; } // Set or append the property. - cmake* cm = this->Makefile->GetCMakeInstance(); - std::string const& name = this->PropertyName; - const char* value = this->PropertyValue.c_str(); - if (this->Remove) { + cmake* cm = status.GetMakefile().GetCMakeInstance(); + const char* value = propertyValue.c_str(); + if (remove) { value = nullptr; } - if (this->AppendMode) { - cm->AppendProperty(name, value ? value : "", this->AppendAsString); + if (appendMode) { + cm->AppendProperty(propertyName, value ? value : "", appendAsString); } else { - cm->SetProperty(name, value); + cm->SetProperty(propertyName, value); } return true; } -bool cmSetPropertyCommand::HandleDirectoryMode() +bool HandleDirectoryMode(cmExecutionStatus& status, + const std::set<std::string>& names, + const std::string& propertyName, + const std::string& propertyValue, + const bool appendAsString, const bool appendMode, + const bool remove) { - if (this->Names.size() > 1) { - this->SetError("allows at most one name for DIRECTORY scope."); + if (names.size() > 1) { + status.SetError("allows at most one name for DIRECTORY scope."); return false; } // Default to the current directory. - cmMakefile* mf = this->Makefile; + cmMakefile* mf = &status.GetMakefile(); // Lookup the directory if given. - if (!this->Names.empty()) { + if (!names.empty()) { // Construct the directory name. Interpret relative paths with // respect to the current directory. - std::string dir = *this->Names.begin(); + std::string dir = *names.begin(); if (!cmSystemTools::FileIsFullPath(dir)) { - dir = this->Makefile->GetCurrentSourceDirectory(); - dir += "/"; - dir += *this->Names.begin(); + dir = cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', + *names.begin()); } // The local generators are associated with collapsed paths. dir = cmSystemTools::CollapseFullPath(dir); - mf = this->Makefile->GetGlobalGenerator()->FindMakefile(dir); + mf = status.GetMakefile().GetGlobalGenerator()->FindMakefile(dir); if (!mf) { // Could not find the directory. - this->SetError( + status.SetError( "DIRECTORY scope provided but requested directory was not found. " "This could be because the directory argument was invalid or, " "it is valid but has not been processed yet."); @@ -189,109 +261,128 @@ bool cmSetPropertyCommand::HandleDirectoryMode() } // Set or append the property. - std::string const& name = this->PropertyName; - const char* value = this->PropertyValue.c_str(); - if (this->Remove) { + const char* value = propertyValue.c_str(); + if (remove) { value = nullptr; } - if (this->AppendMode) { - mf->AppendProperty(name, value ? value : "", this->AppendAsString); + if (appendMode) { + mf->AppendProperty(propertyName, value ? value : "", appendAsString); } else { - mf->SetProperty(name, value); + mf->SetProperty(propertyName, value); } return true; } -bool cmSetPropertyCommand::HandleTargetMode() +bool HandleTargetMode(cmExecutionStatus& status, + const std::set<std::string>& names, + const std::string& propertyName, + const std::string& propertyValue, + const bool appendAsString, const bool appendMode, + const bool remove) { - for (std::string const& name : this->Names) { - if (this->Makefile->IsAlias(name)) { - this->SetError("can not be used on an ALIAS target."); + for (std::string const& name : names) { + if (status.GetMakefile().IsAlias(name)) { + status.SetError("can not be used on an ALIAS target."); return false; } - if (cmTarget* target = this->Makefile->FindTargetToUse(name)) { + if (cmTarget* target = status.GetMakefile().FindTargetToUse(name)) { // Handle the current target. - if (!this->HandleTarget(target)) { + if (!HandleTarget(target, status.GetMakefile(), propertyName, + propertyValue, appendAsString, appendMode, remove)) { return false; } } else { std::ostringstream e; e << "could not find TARGET " << name << ". Perhaps it has not yet been created."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } } return true; } -bool cmSetPropertyCommand::HandleTarget(cmTarget* target) +bool HandleTarget(cmTarget* target, cmMakefile& makefile, + const std::string& propertyName, + const std::string& propertyValue, const bool appendAsString, + const bool appendMode, const bool remove) { // Set or append the property. - std::string const& name = this->PropertyName; - const char* value = this->PropertyValue.c_str(); - if (this->Remove) { + const char* value = propertyValue.c_str(); + if (remove) { value = nullptr; } - if (this->AppendMode) { - target->AppendProperty(name, value, this->AppendAsString); + if (appendMode) { + target->AppendProperty(propertyName, value, appendAsString); } else { - target->SetProperty(name, value); + target->SetProperty(propertyName, value); } // Check the resulting value. - target->CheckProperty(name, this->Makefile); + target->CheckProperty(propertyName, &makefile); return true; } -bool cmSetPropertyCommand::HandleSourceMode() +bool HandleSourceMode(cmExecutionStatus& status, + const std::set<std::string>& names, + const std::string& propertyName, + const std::string& propertyValue, + const bool appendAsString, const bool appendMode, + const bool remove) { - for (std::string const& name : this->Names) { + for (std::string const& name : names) { // Get the source file. - if (cmSourceFile* sf = this->Makefile->GetOrCreateSource(name)) { - if (!this->HandleSource(sf)) { + if (cmSourceFile* sf = status.GetMakefile().GetOrCreateSource(name)) { + if (!HandleSource(sf, propertyName, propertyValue, appendAsString, + appendMode, remove)) { return false; } } else { std::ostringstream e; e << "given SOURCE name that could not be found or created: " << name; - this->SetError(e.str()); + status.SetError(e.str()); return false; } } return true; } -bool cmSetPropertyCommand::HandleSource(cmSourceFile* sf) +bool HandleSource(cmSourceFile* sf, const std::string& propertyName, + const std::string& propertyValue, const bool appendAsString, + const bool appendMode, const bool remove) { // Set or append the property. - std::string const& name = this->PropertyName; - const char* value = this->PropertyValue.c_str(); - if (this->Remove) { + const char* value = propertyValue.c_str(); + if (remove) { value = nullptr; } - if (this->AppendMode) { - sf->AppendProperty(name, value, this->AppendAsString); + if (appendMode) { + sf->AppendProperty(propertyName, value, appendAsString); } else { - sf->SetProperty(name, value); + sf->SetProperty(propertyName, value); } return true; } -bool cmSetPropertyCommand::HandleTestMode() +bool HandleTestMode(cmExecutionStatus& status, std::set<std::string>& names, + const std::string& propertyName, + const std::string& propertyValue, + const bool appendAsString, const bool appendMode, + const bool remove) { // Look for tests with all names given. std::set<std::string>::iterator next; - for (std::set<std::string>::iterator ni = this->Names.begin(); - ni != this->Names.end(); ni = next) { + for (std::set<std::string>::iterator ni = names.begin(); ni != names.end(); + ni = next) { next = ni; ++next; - if (cmTest* test = this->Makefile->GetTest(*ni)) { - if (this->HandleTest(test)) { - this->Names.erase(ni); + if (cmTest* test = status.GetMakefile().GetTest(*ni)) { + if (HandleTest(test, propertyName, propertyValue, appendAsString, + appendMode, remove)) { + names.erase(ni); } else { return false; } @@ -299,137 +390,151 @@ bool cmSetPropertyCommand::HandleTestMode() } // Names that are still left were not found. - if (!this->Names.empty()) { + if (!names.empty()) { std::ostringstream e; e << "given TEST names that do not exist:\n"; - for (std::string const& name : this->Names) { + for (std::string const& name : names) { e << " " << name << "\n"; } - this->SetError(e.str()); + status.SetError(e.str()); return false; } return true; } -bool cmSetPropertyCommand::HandleTest(cmTest* test) +bool HandleTest(cmTest* test, const std::string& propertyName, + const std::string& propertyValue, const bool appendAsString, + const bool appendMode, const bool remove) { // Set or append the property. - std::string const& name = this->PropertyName; - const char* value = this->PropertyValue.c_str(); - if (this->Remove) { + const char* value = propertyValue.c_str(); + if (remove) { value = nullptr; } - if (this->AppendMode) { - test->AppendProperty(name, value, this->AppendAsString); + if (appendMode) { + test->AppendProperty(propertyName, value, appendAsString); } else { - test->SetProperty(name, value); + test->SetProperty(propertyName, value); } return true; } -bool cmSetPropertyCommand::HandleCacheMode() +bool HandleCacheMode(cmExecutionStatus& status, + const std::set<std::string>& names, + const std::string& propertyName, + const std::string& propertyValue, + const bool appendAsString, const bool appendMode, + const bool remove) { - if (this->PropertyName == "ADVANCED") { - if (!this->Remove && !cmSystemTools::IsOn(this->PropertyValue) && - !cmSystemTools::IsOff(this->PropertyValue)) { + if (propertyName == "ADVANCED") { + if (!remove && !cmIsOn(propertyValue) && !cmIsOff(propertyValue)) { std::ostringstream e; - e << "given non-boolean value \"" << this->PropertyValue + e << "given non-boolean value \"" << propertyValue << R"(" for CACHE property "ADVANCED". )"; - this->SetError(e.str()); + status.SetError(e.str()); return false; } - } else if (this->PropertyName == "TYPE") { - if (!cmState::IsCacheEntryType(this->PropertyValue)) { + } else if (propertyName == "TYPE") { + if (!cmState::IsCacheEntryType(propertyValue)) { std::ostringstream e; - e << "given invalid CACHE entry TYPE \"" << this->PropertyValue << "\""; - this->SetError(e.str()); + e << "given invalid CACHE entry TYPE \"" << propertyValue << "\""; + status.SetError(e.str()); return false; } - } else if (this->PropertyName != "HELPSTRING" && - this->PropertyName != "STRINGS" && - this->PropertyName != "VALUE") { + } else if (propertyName != "HELPSTRING" && propertyName != "STRINGS" && + propertyName != "VALUE") { std::ostringstream e; - e << "given invalid CACHE property " << this->PropertyName << ". " + e << "given invalid CACHE property " << propertyName << ". " << "Settable CACHE properties are: " << "ADVANCED, HELPSTRING, STRINGS, TYPE, and VALUE."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } - for (std::string const& name : this->Names) { + for (std::string const& name : names) { // Get the source file. - cmMakefile* mf = this->GetMakefile(); - cmake* cm = mf->GetCMakeInstance(); + cmake* cm = status.GetMakefile().GetCMakeInstance(); const char* existingValue = cm->GetState()->GetCacheEntryValue(name); if (existingValue) { - if (!this->HandleCacheEntry(name)) { + if (!HandleCacheEntry(name, status.GetMakefile(), propertyName, + propertyValue, appendAsString, appendMode, + remove)) { return false; } } else { std::ostringstream e; e << "could not find CACHE variable " << name << ". Perhaps it has not yet been created."; - this->SetError(e.str()); + status.SetError(e.str()); return false; } } return true; } -bool cmSetPropertyCommand::HandleCacheEntry(std::string const& cacheKey) +bool HandleCacheEntry(std::string const& cacheKey, const cmMakefile& makefile, + const std::string& propertyName, + const std::string& propertyValue, + const bool appendAsString, const bool appendMode, + const bool remove) { // Set or append the property. - std::string const& name = this->PropertyName; - const char* value = this->PropertyValue.c_str(); - cmState* state = this->Makefile->GetState(); - if (this->Remove) { - state->RemoveCacheEntryProperty(cacheKey, name); + const char* value = propertyValue.c_str(); + cmState* state = makefile.GetState(); + if (remove) { + state->RemoveCacheEntryProperty(cacheKey, propertyName); } - if (this->AppendMode) { - state->AppendCacheEntryProperty(cacheKey, name, value, - this->AppendAsString); + if (appendMode) { + state->AppendCacheEntryProperty(cacheKey, propertyName, value, + appendAsString); } else { - state->SetCacheEntryProperty(cacheKey, name, value); + state->SetCacheEntryProperty(cacheKey, propertyName, value); } return true; } -bool cmSetPropertyCommand::HandleInstallMode() +bool HandleInstallMode(cmExecutionStatus& status, + const std::set<std::string>& names, + const std::string& propertyName, + const std::string& propertyValue, + const bool appendAsString, const bool appendMode, + const bool remove) { - cmake* cm = this->Makefile->GetCMakeInstance(); + cmake* cm = status.GetMakefile().GetCMakeInstance(); - for (std::string const& name : this->Names) { + for (std::string const& name : names) { if (cmInstalledFile* file = - cm->GetOrCreateInstalledFile(this->Makefile, name)) { - if (!this->HandleInstall(file)) { + cm->GetOrCreateInstalledFile(&status.GetMakefile(), name)) { + if (!HandleInstall(file, status.GetMakefile(), propertyName, + propertyValue, appendAsString, appendMode, remove)) { return false; } } else { std::ostringstream e; e << "given INSTALL name that could not be found or created: " << name; - this->SetError(e.str()); + status.SetError(e.str()); return false; } } return true; } -bool cmSetPropertyCommand::HandleInstall(cmInstalledFile* file) +bool HandleInstall(cmInstalledFile* file, cmMakefile& makefile, + const std::string& propertyName, + const std::string& propertyValue, const bool appendAsString, + const bool appendMode, const bool remove) { // Set or append the property. - std::string const& name = this->PropertyName; - - cmMakefile* mf = this->Makefile; - - const char* value = this->PropertyValue.c_str(); - if (this->Remove) { - file->RemoveProperty(name); - } else if (this->AppendMode) { - file->AppendProperty(mf, name, value, this->AppendAsString); + const char* value = propertyValue.c_str(); + if (remove) { + file->RemoveProperty(propertyName); + } else if (appendMode) { + file->AppendProperty(&makefile, propertyName, value, appendAsString); } else { - file->SetProperty(mf, name, value); + file->SetProperty(&makefile, propertyName, value); } return true; } +} diff --git a/Source/cmSetPropertyCommand.h b/Source/cmSetPropertyCommand.h index 4051e48..ec36f84 100644 --- a/Source/cmSetPropertyCommand.h +++ b/Source/cmSetPropertyCommand.h @@ -5,58 +5,12 @@ #include "cmConfigure.h" // IWYU pragma: keep -#include <set> #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -class cmInstalledFile; -class cmSourceFile; -class cmTarget; -class cmTest; - -class cmSetPropertyCommand : public cmCommand -{ -public: - cmSetPropertyCommand(); - - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmSetPropertyCommand>(); - } - - /** - * This is called when the command is first encountered in - * the input file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; - -private: - std::set<std::string> Names; - std::string PropertyName; - std::string PropertyValue; - bool Remove; - bool AppendMode; - bool AppendAsString; - // Implementation of each property type. - bool HandleGlobalMode(); - bool HandleDirectoryMode(); - bool HandleTargetMode(); - bool HandleTarget(cmTarget* target); - bool HandleSourceMode(); - bool HandleSource(cmSourceFile* sf); - bool HandleTestMode(); - bool HandleTest(cmTest* test); - bool HandleCacheMode(); - bool HandleCacheEntry(std::string const&); - bool HandleInstallMode(); - bool HandleInstall(cmInstalledFile* file); -}; +bool cmSetPropertyCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmSetSourceFilesPropertiesCommand.cxx b/Source/cmSetSourceFilesPropertiesCommand.cxx index 9388e7c..8e3217f 100644 --- a/Source/cmSetSourceFilesPropertiesCommand.cxx +++ b/Source/cmSetSourceFilesPropertiesCommand.cxx @@ -4,7 +4,7 @@ #include "cmMakefile.h" #include "cmSourceFile.h" -#include "cmSystemTools.h" +#include "cmStringAlgorithms.h" class cmExecutionStatus; @@ -87,7 +87,7 @@ bool cmSetSourceFilesPropertiesCommand::RunCommand( propertyPairs.push_back(*j); if (*j == "GENERATED") { ++j; - if (j != propend && cmSystemTools::IsOn(*j)) { + if (j != propend && cmIsOn(*j)) { generated = true; } } else { diff --git a/Source/cmSetTargetPropertiesCommand.cxx b/Source/cmSetTargetPropertiesCommand.cxx index 1dc7e69..b4360e4 100644 --- a/Source/cmSetTargetPropertiesCommand.cxx +++ b/Source/cmSetTargetPropertiesCommand.cxx @@ -6,6 +6,7 @@ #include "cmAlgorithms.h" #include "cmMakefile.h" +#include "cmStringAlgorithms.h" #include "cmTarget.h" class cmExecutionStatus; @@ -52,8 +53,8 @@ bool cmSetTargetPropertiesCommand::InitialPass( bool ret = cmSetTargetPropertiesCommand::SetOneTarget( args[i], propertyPairs, this->Makefile); if (!ret) { - std::string message = "Can not find target to add properties to: "; - message += args[i]; + std::string message = + cmStrCat("Can not find target to add properties to: ", args[i]); this->SetError(message); return false; } diff --git a/Source/cmSetTestsPropertiesCommand.cxx b/Source/cmSetTestsPropertiesCommand.cxx index cc9587c..ed909c6 100644 --- a/Source/cmSetTestsPropertiesCommand.cxx +++ b/Source/cmSetTestsPropertiesCommand.cxx @@ -6,6 +6,7 @@ #include "cmAlgorithms.h" #include "cmMakefile.h" +#include "cmStringAlgorithms.h" #include "cmTest.h" class cmExecutionStatus; @@ -70,8 +71,7 @@ bool cmSetTestsPropertiesCommand::SetOneTest( } } } else { - errors = "Can not find test to add properties to: "; - errors += tname; + errors = cmStrCat("Can not find test to add properties to: ", tname); return false; } diff --git a/Source/cmSiteNameCommand.cxx b/Source/cmSiteNameCommand.cxx index 9f041bc..d47f121 100644 --- a/Source/cmSiteNameCommand.cxx +++ b/Source/cmSiteNameCommand.cxx @@ -4,18 +4,18 @@ #include "cmsys/RegularExpression.hxx" +#include "cmExecutionStatus.h" #include "cmMakefile.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" -class cmExecutionStatus; - // cmSiteNameCommand -bool cmSiteNameCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus&) +bool cmSiteNameCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() != 1) { - this->SetError("called with incorrect number of arguments"); + status.SetError("called with incorrect number of arguments"); return false; } std::vector<std::string> paths; @@ -26,12 +26,12 @@ bool cmSiteNameCommand::InitialPass(std::vector<std::string> const& args, paths.emplace_back("/sbin"); paths.emplace_back("/usr/local/bin"); - const char* cacheValue = this->Makefile->GetDefinition(args[0]); + const char* cacheValue = status.GetMakefile().GetDefinition(args[0]); if (cacheValue) { return true; } - const char* temp = this->Makefile->GetDefinition("HOSTNAME"); + const char* temp = status.GetMakefile().GetDefinition("HOSTNAME"); std::string hostname_cmd; if (temp) { hostname_cmd = temp; @@ -50,7 +50,7 @@ bool cmSiteNameCommand::InitialPass(std::vector<std::string> const& args, } #else // try to find the hostname for this computer - if (!cmSystemTools::IsOff(hostname_cmd)) { + if (!cmIsOff(hostname_cmd)) { std::string host; cmSystemTools::RunSingleCommand(hostname_cmd, &host, nullptr, nullptr, nullptr, cmSystemTools::OUTPUT_NONE); @@ -71,7 +71,7 @@ bool cmSiteNameCommand::InitialPass(std::vector<std::string> const& args, } } #endif - this->Makefile->AddCacheDefinition( + status.GetMakefile().AddCacheDefinition( args[0], siteName.c_str(), "Name of the computer/site where compile is being run", cmStateEnums::STRING); diff --git a/Source/cmSiteNameCommand.h b/Source/cmSiteNameCommand.h index 0190abb..e8fc608 100644 --- a/Source/cmSiteNameCommand.h +++ b/Source/cmSiteNameCommand.h @@ -8,34 +8,14 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -/** \class cmSiteNameCommand +/** * \brief site_name command * * cmSiteNameCommand implements the site_name CMake command */ -class cmSiteNameCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmSiteNameCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; -}; +bool cmSiteNameCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmSourceFile.cxx b/Source/cmSourceFile.cxx index d05fb68..a6d2807 100644 --- a/Source/cmSourceFile.cxx +++ b/Source/cmSourceFile.cxx @@ -11,6 +11,7 @@ #include "cmMessageType.h" #include "cmProperty.h" #include "cmState.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmake.h" @@ -150,9 +151,7 @@ bool cmSourceFile::FindFullPath(std::string* error) for (auto exts : extsLists) { for (std::string const& ext : *exts) { if (!ext.empty()) { - std::string extPath = fullPath; - extPath += '.'; - extPath += ext; + std::string extPath = cmStrCat(fullPath, '.', ext); if (cmSystemTools::FileExists(extPath)) { this->FullPath = extPath; return true; @@ -177,10 +176,8 @@ bool cmSourceFile::FindFullPath(std::string* error) } // Compose error - std::string err; - err += "Cannot find source file:\n "; - err += lPath; - err += "\nTried extensions"; + std::string err = + cmStrCat("Cannot find source file:\n ", lPath, "\nTried extensions"); for (auto exts : extsLists) { for (std::string const& ext : *exts) { err += " ."; @@ -242,7 +239,7 @@ void cmSourceFile::SetProperty(const std::string& prop, const char* value) // Update IsGenerated flag if (prop == propGENERATED) { - this->IsGenerated = cmSystemTools::IsOn(value); + this->IsGenerated = cmIsOn(value); } } @@ -316,7 +313,7 @@ const char* cmSourceFile::GetSafeProperty(const std::string& prop) const bool cmSourceFile::GetPropertyAsBool(const std::string& prop) const { - return cmSystemTools::IsOn(this->GetProperty(prop)); + return cmIsOn(this->GetProperty(prop)); } cmCustomCommand* cmSourceFile::GetCustomCommand() diff --git a/Source/cmSourceFileLocation.cxx b/Source/cmSourceFileLocation.cxx index 6e2e820..0e8d09d 100644 --- a/Source/cmSourceFileLocation.cxx +++ b/Source/cmSourceFileLocation.cxx @@ -110,8 +110,7 @@ void cmSourceFileLocation::UpdateExtension(const std::string& name) // Check the source tree only because a file in the build tree should // be specified by full path at least once. We do not want this // detection to depend on whether the project has already been built. - tryPath = this->Makefile->GetCurrentSourceDirectory(); - tryPath += "/"; + tryPath = cmStrCat(this->Makefile->GetCurrentSourceDirectory(), '/'); } if (!this->Directory.empty()) { tryPath += this->Directory; diff --git a/Source/cmSourceGroup.cxx b/Source/cmSourceGroup.cxx index 7e1e836..418a40f 100644 --- a/Source/cmSourceGroup.cxx +++ b/Source/cmSourceGroup.cxx @@ -2,6 +2,8 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmSourceGroup.h" +#include "cmStringAlgorithms.h" + #include <utility> class cmSourceGroupInternals @@ -17,8 +19,7 @@ cmSourceGroup::cmSourceGroup(std::string name, const char* regex, this->Internal = new cmSourceGroupInternals; this->SetGroupRegex(regex); if (parentName) { - this->FullName = parentName; - this->FullName += "\\"; + this->FullName = cmStrCat(parentName, '\\'); } this->FullName += this->Name; } diff --git a/Source/cmSourceGroupCommand.cxx b/Source/cmSourceGroupCommand.cxx index ffdd0ce..399f1da 100644 --- a/Source/cmSourceGroupCommand.cxx +++ b/Source/cmSourceGroupCommand.cxx @@ -2,11 +2,11 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmSourceGroupCommand.h" -#include <algorithm> #include <set> #include <stddef.h> #include <utility> +#include "cmAlgorithms.h" #include "cmMakefile.h" #include "cmSourceGroup.h" #include "cmStringAlgorithms.h" @@ -21,7 +21,7 @@ const std::string kSourceGroupOptionName = "<sg_name>"; std::vector<std::string> tokenizePath(const std::string& path) { - return cmSystemTools::tokenize(path, "\\/"); + return cmTokenize(path, "\\/"); } std::string getFullFilePath(const std::string& currentPath, @@ -30,9 +30,7 @@ std::string getFullFilePath(const std::string& currentPath, std::string fullPath = path; if (!cmSystemTools::FileIsFullPath(path)) { - fullPath = currentPath; - fullPath += "/"; - fullPath += path; + fullPath = cmStrCat(currentPath, '/', path); } return cmSystemTools::CollapseFullPath(fullPath); @@ -56,7 +54,7 @@ bool rootIsPrefix(const std::string& root, { for (std::string const& file : files) { if (!cmHasPrefix(file, root)) { - error = "ROOT: " + root + " is not a prefix of file: " + file; + error = cmStrCat("ROOT: ", root, " is not a prefix of file: ", file); return false; } } @@ -94,7 +92,7 @@ bool addFilesToItsSourceGroups(const std::string& root, std::vector<std::string> tokenizedPath; if (!prefix.empty()) { - tokenizedPath = tokenizePath(prefix + '/' + sgFilesPath); + tokenizedPath = tokenizePath(cmStrCat(prefix, '/', sgFilesPath)); } else { tokenizedPath = tokenizePath(sgFilesPath); } @@ -140,8 +138,7 @@ cmSourceGroupCommand::getExpectedOptions() const bool cmSourceGroupCommand::isExpectedOption( const std::string& argument, const ExpectedOptions& expectedOptions) { - return std::find(expectedOptions.begin(), expectedOptions.end(), argument) != - expectedOptions.end(); + return cmContains(expectedOptions, argument); } void cmSourceGroupCommand::parseArguments( @@ -237,9 +234,8 @@ bool cmSourceGroupCommand::InitialPass(std::vector<std::string> const& args, for (auto const& filesArg : filesArguments) { std::string src = filesArg; if (!cmSystemTools::FileIsFullPath(src)) { - src = this->Makefile->GetCurrentSourceDirectory(); - src += "/"; - src += filesArg; + src = + cmStrCat(this->Makefile->GetCurrentSourceDirectory(), '/', filesArg); } src = cmSystemTools::CollapseFullPath(src); sg->AddGroupFile(src); diff --git a/Source/cmState.cxx b/Source/cmState.cxx index 1ea72e1..b6f1808 100644 --- a/Source/cmState.cxx +++ b/Source/cmState.cxx @@ -19,6 +19,7 @@ #include "cmGlobVerificationManager.h" #include "cmListFileCache.h" #include "cmMakefile.h" +#include "cmMessageType.h" #include "cmStatePrivate.h" #include "cmStateSnapshot.h" #include "cmStringAlgorithms.h" @@ -432,6 +433,20 @@ void cmState::AddBuiltinCommand(std::string const& name, Command command) this->BuiltinCommands.emplace(name, std::move(command)); } +static bool InvokeBuiltinCommand(cmState::BuiltinCommand command, + std::vector<cmListFileArgument> const& args, + cmExecutionStatus& status) +{ + cmMakefile& mf = status.GetMakefile(); + std::vector<std::string> expandedArguments; + if (!mf.ExpandArguments(args, expandedArguments)) { + // There was an error expanding arguments. It was already + // reported, so we can skip this command without error. + return true; + } + return command(expandedArguments, status); +} + void cmState::AddBuiltinCommand(std::string const& name, BuiltinCommand command) { @@ -439,13 +454,34 @@ void cmState::AddBuiltinCommand(std::string const& name, name, [command](const std::vector<cmListFileArgument>& args, cmExecutionStatus& status) -> bool { - std::vector<std::string> expandedArguments; - if (!status.GetMakefile().ExpandArguments(args, expandedArguments)) { - // There was an error expanding arguments. It was already - // reported, so we can skip this command without error. - return true; + return InvokeBuiltinCommand(command, args, status); + }); +} + +void cmState::AddDisallowedCommand(std::string const& name, + BuiltinCommand command, + cmPolicies::PolicyID policy, + const char* message) +{ + this->AddBuiltinCommand( + name, + [command, policy, message](const std::vector<cmListFileArgument>& args, + cmExecutionStatus& status) -> bool { + cmMakefile& mf = status.GetMakefile(); + switch (mf.GetPolicyStatus(policy)) { + case cmPolicies::WARN: + mf.IssueMessage(MessageType::AUTHOR_WARNING, + cmPolicies::GetPolicyWarning(policy)); + break; + case cmPolicies::OLD: + break; + case cmPolicies::REQUIRED_IF_USED: + case cmPolicies::REQUIRED_ALWAYS: + case cmPolicies::NEW: + mf.IssueMessage(MessageType::FATAL_ERROR, message); + return true; } - return command(expandedArguments, status); + return InvokeBuiltinCommand(command, args, status); }); } @@ -598,7 +634,7 @@ const char* cmState::GetGlobalProperty(const std::string& prop) bool cmState::GetGlobalPropertyAsBool(const std::string& prop) { - return cmSystemTools::IsOn(this->GetGlobalProperty(prop)); + return cmIsOn(this->GetGlobalProperty(prop)); } void cmState::SetSourceDirectory(std::string const& sourceDirectory) diff --git a/Source/cmState.h b/Source/cmState.h index 8847f3b..937ab61 100644 --- a/Source/cmState.h +++ b/Source/cmState.h @@ -157,6 +157,8 @@ public: std::unique_ptr<cmCommand> command); void AddBuiltinCommand(std::string const& name, Command command); void AddBuiltinCommand(std::string const& name, BuiltinCommand command); + void AddDisallowedCommand(std::string const& name, BuiltinCommand command, + cmPolicies::PolicyID policy, const char* message); void AddDisallowedCommand(std::string const& name, std::unique_ptr<cmCommand> command, cmPolicies::PolicyID policy, const char* message); diff --git a/Source/cmStateDirectory.cxx b/Source/cmStateDirectory.cxx index 3f70ed3..df96bd3 100644 --- a/Source/cmStateDirectory.cxx +++ b/Source/cmStateDirectory.cxx @@ -662,7 +662,7 @@ const char* cmStateDirectory::GetProperty(const std::string& prop, bool cmStateDirectory::GetPropertyAsBool(const std::string& prop) const { - return cmSystemTools::IsOn(this->GetProperty(prop)); + return cmIsOn(this->GetProperty(prop)); } std::vector<std::string> cmStateDirectory::GetPropertyKeys() const diff --git a/Source/cmStateSnapshot.cxx b/Source/cmStateSnapshot.cxx index 110ec56..121923d 100644 --- a/Source/cmStateSnapshot.cxx +++ b/Source/cmStateSnapshot.cxx @@ -328,7 +328,7 @@ void cmStateSnapshot::SetDefaultDefinitions() #if defined(__CYGWIN__) std::string legacy; if (cmSystemTools::GetEnv("CMAKE_LEGACY_CYGWIN_WIN32", legacy) && - cmSystemTools::IsOn(legacy.c_str())) { + cmIsOn(legacy.c_str())) { this->SetDefinition("WIN32", "1"); this->SetDefinition("CMAKE_HOST_WIN32", "1"); } diff --git a/Source/cmStringAlgorithms.cxx b/Source/cmStringAlgorithms.cxx index 5deb9b0..c686aa0 100644 --- a/Source/cmStringAlgorithms.cxx +++ b/Source/cmStringAlgorithms.cxx @@ -4,6 +4,146 @@ #include <algorithm> #include <cstdio> +#include <errno.h> +#include <stdlib.h> + +std::string cmTrimWhitespace(cm::string_view str) +{ + auto start = str.begin(); + while (start != str.end() && cmIsSpace(*start)) { + ++start; + } + if (start == str.end()) { + return std::string(); + } + auto stop = str.end() - 1; + while (cmIsSpace(*stop)) { + --stop; + } + return std::string(start, stop + 1); +} + +std::string cmRemoveQuotes(cm::string_view str) +{ + // We process only strings that have two quotes at least. + // Also front() and back() are only defined behavior on non empty strings. + if (str.size() >= 2 && // + str.front() == '"' && // + str.back() == '"') { + // Remove a quote from the front and back + str.remove_prefix(1); + str.remove_suffix(1); + } + return std::string(str); +} + +std::string cmEscapeQuotes(cm::string_view str) +{ + std::string result; + result.reserve(str.size()); + for (const char ch : str) { + if (ch == '"') { + result += '\\'; + } + result += ch; + } + return result; +} + +std::vector<std::string> cmTokenize(cm::string_view str, cm::string_view sep) +{ + std::vector<std::string> tokens; + cm::string_view::size_type tokend = 0; + + do { + cm::string_view::size_type tokstart = str.find_first_not_of(sep, tokend); + if (tokstart == cm::string_view::npos) { + break; // no more tokens + } + tokend = str.find_first_of(sep, tokstart); + if (tokend == cm::string_view::npos) { + tokens.emplace_back(str.substr(tokstart)); + } else { + tokens.emplace_back(str.substr(tokstart, tokend - tokstart)); + } + } while (tokend != cm::string_view::npos); + + if (tokens.empty()) { + tokens.emplace_back(); + } + return tokens; +} + +void cmExpandList(cm::string_view arg, std::vector<std::string>& argsOut, + bool emptyArgs) +{ + // If argument is empty, it is an empty list. + if (!emptyArgs && arg.empty()) { + return; + } + + // if there are no ; in the name then just copy the current string + if (arg.find(';') == cm::string_view::npos) { + argsOut.emplace_back(arg); + return; + } + + std::string newArg; + // Break the string at non-escaped semicolons not nested in []. + int squareNesting = 0; + cm::string_view::iterator last = arg.begin(); + cm::string_view::iterator const cend = arg.end(); + for (cm::string_view::iterator c = last; c != cend; ++c) { + switch (*c) { + case '\\': { + // We only want to allow escaping of semicolons. Other + // escapes should not be processed here. + cm::string_view::iterator cnext = c + 1; + if ((cnext != cend) && *cnext == ';') { + newArg.append(last, c); + // Skip over the escape character + last = cnext; + c = cnext; + } + } break; + case '[': { + ++squareNesting; + } break; + case ']': { + --squareNesting; + } break; + case ';': { + // Break the string here if we are not nested inside square + // brackets. + if (squareNesting == 0) { + newArg.append(last, c); + // Skip over the semicolon + last = c + 1; + if (!newArg.empty() || emptyArgs) { + // Add the last argument if the string is not empty. + argsOut.push_back(newArg); + newArg.clear(); + } + } + } break; + default: { + // Just append this character. + } break; + } + } + newArg.append(last, cend); + if (!newArg.empty() || emptyArgs) { + // Add the last argument if the string is not empty. + argsOut.push_back(std::move(newArg)); + } +} + +std::vector<std::string> cmExpandedList(cm::string_view arg, bool emptyArgs) +{ + std::vector<std::string> argsOut; + cmExpandList(arg, argsOut, emptyArgs); + return argsOut; +} namespace { template <std::size_t N, typename T> @@ -71,3 +211,114 @@ std::string cmCatViews(std::initializer_list<cm::string_view> views) } return result; } + +bool cmIsInternallyOn(cm::string_view val) +{ + return (val.size() == 4) && // + (val[0] == 'I' || val[0] == 'i') && // + (val[1] == '_') && // + (val[2] == 'O' || val[2] == 'o') && // + (val[3] == 'N' || val[3] == 'n'); +} + +bool cmIsNOTFOUND(cm::string_view val) +{ + return (val == "NOTFOUND") || cmHasLiteralSuffix(val, "-NOTFOUND"); +} + +bool cmIsOn(cm::string_view val) +{ + switch (val.size()) { + case 1: + return val[0] == '1' || val[0] == 'Y' || val[0] == 'y'; + case 2: + return // + (val[0] == 'O' || val[0] == 'o') && // + (val[1] == 'N' || val[1] == 'n'); + case 3: + return // + (val[0] == 'Y' || val[0] == 'y') && // + (val[1] == 'E' || val[1] == 'e') && // + (val[2] == 'S' || val[2] == 's'); + case 4: + return // + (val[0] == 'T' || val[0] == 't') && // + (val[1] == 'R' || val[1] == 'r') && // + (val[2] == 'U' || val[2] == 'u') && // + (val[3] == 'E' || val[3] == 'e'); + default: + break; + } + + return false; +} + +bool cmIsOff(cm::string_view val) +{ + switch (val.size()) { + case 0: + return true; + case 1: + return val[0] == '0' || val[0] == 'N' || val[0] == 'n'; + case 2: + return // + (val[0] == 'N' || val[0] == 'n') && // + (val[1] == 'O' || val[1] == 'o'); + case 3: + return // + (val[0] == 'O' || val[0] == 'o') && // + (val[1] == 'F' || val[1] == 'f') && // + (val[2] == 'F' || val[2] == 'f'); + case 5: + return // + (val[0] == 'F' || val[0] == 'f') && // + (val[1] == 'A' || val[1] == 'a') && // + (val[2] == 'L' || val[2] == 'l') && // + (val[3] == 'S' || val[3] == 's') && // + (val[4] == 'E' || val[4] == 'e'); + case 6: + return // + (val[0] == 'I' || val[0] == 'i') && // + (val[1] == 'G' || val[1] == 'g') && // + (val[2] == 'N' || val[2] == 'n') && // + (val[3] == 'O' || val[3] == 'o') && // + (val[4] == 'R' || val[4] == 'r') && // + (val[5] == 'E' || val[5] == 'e'); + default: + break; + } + + return cmIsNOTFOUND(val); +} + +bool cmStrToLong(const char* str, long* value) +{ + errno = 0; + char* endp; + *value = strtol(str, &endp, 10); + return (*endp == '\0') && (endp != str) && (errno == 0); +} + +bool cmStrToLong(std::string const& str, long* value) +{ + return cmStrToLong(str.c_str(), value); +} + +bool cmStrToULong(const char* str, unsigned long* value) +{ + errno = 0; + char* endp; + while (cmIsSpace(*str)) { + ++str; + } + if (*str == '-') { + return false; + } + *value = strtoul(str, &endp, 10); + return (*endp == '\0') && (endp != str) && (errno == 0); +} + +bool cmStrToULong(std::string const& str, unsigned long* value) +{ + return cmStrToULong(str.c_str(), value); +} diff --git a/Source/cmStringAlgorithms.h b/Source/cmStringAlgorithms.h index cdb494f..5b8b878 100644 --- a/Source/cmStringAlgorithms.h +++ b/Source/cmStringAlgorithms.h @@ -7,6 +7,7 @@ #include "cmRange.h" #include "cm_string_view.hxx" +#include <cctype> #include <initializer_list> #include <sstream> #include <string.h> @@ -31,6 +32,21 @@ private: std::string const Test_; }; +/** Returns true if the character @a ch is a whitespace character. **/ +inline bool cmIsSpace(char ch) +{ + return ((ch & 0x80) == 0) && std::isspace(ch); +} + +/** Returns a string that has whitespace removed from the start and the end. */ +std::string cmTrimWhitespace(cm::string_view str); + +/** Returns a string that has quotes removed from the start and the end. */ +std::string cmRemoveQuotes(cm::string_view str); + +/** Escape quotes in a string. */ +std::string cmEscapeQuotes(cm::string_view str); + /** Joins elements of a range with separator into a single string. */ template <typename Range> std::string cmJoin(Range const& rng, cm::string_view separator) @@ -49,6 +65,51 @@ std::string cmJoin(Range const& rng, cm::string_view separator) return os.str(); } +/** Extract tokens that are separated by any of the characters in @a sep. */ +std::vector<std::string> cmTokenize(cm::string_view str, cm::string_view sep); + +/** + * Expand the ; separated string @a arg into multiple arguments. + * All found arguments are appended to @a argsOut. + */ +void cmExpandList(cm::string_view arg, std::vector<std::string>& argsOut, + bool emptyArgs = false); + +/** + * Expand out any arguments in the string range [@a first, @a last) that have + * ; separated strings into multiple arguments. All found arguments are + * appended to @a argsOut. + */ +template <class InputIt> +void cmExpandLists(InputIt first, InputIt last, + std::vector<std::string>& argsOut) +{ + for (; first != last; ++first) { + ExpandList(*first, argsOut); + } +} + +/** + * Same as cmExpandList but a new vector is created containing + * the expanded arguments from the string @a arg. + */ +std::vector<std::string> cmExpandedList(cm::string_view arg, + bool emptyArgs = false); + +/** + * Same as cmExpandList but a new vector is created containing the expanded + * versions of all arguments in the string range [@a first, @a last). + */ +template <class InputIt> +std::vector<std::string> cmExpandedLists(InputIt first, InputIt last) +{ + std::vector<std::string> argsOut; + for (; first != last; ++first) { + cmExpandList(*first, argsOut); + } + return argsOut; +} + /** Concatenate string pieces into a single string. */ std::string cmCatViews(std::initializer_list<cm::string_view> views); @@ -119,6 +180,51 @@ std::string cmWrap(char prefix, Range const& rng, char suffix, sep); } +/** + * Does a string indicates that CMake/CPack/CTest internally + * forced this value. This is not the same as On, but this + * may be considered as "internally switched on". + */ +bool cmIsInternallyOn(cm::string_view val); +inline bool cmIsInternallyOn(const char* val) +{ + if (!val) { + return false; + } + return cmIsInternallyOn(cm::string_view(val)); +} + +/** Return true if value is NOTFOUND or ends in -NOTFOUND. */ +bool cmIsNOTFOUND(cm::string_view val); + +/** + * Does a string indicate a true or ON value? This is not the same as ifdef. + */ +bool cmIsOn(cm::string_view val); +inline bool cmIsOn(const char* val) +{ + if (!val) { + return false; + } + return cmIsOn(cm::string_view(val)); +} + +/** + * Does a string indicate a false or off value ? Note that this is + * not the same as !IsOn(...) because there are a number of + * ambiguous values such as "/usr/local/bin" a path will result in + * IsON and IsOff both returning false. Note that the special path + * NOTFOUND, *-NOTFOUND or IGNORE will cause IsOff to return true. + */ +bool cmIsOff(cm::string_view val); +inline bool cmIsOff(const char* val) +{ + if (!val) { + return true; + } + return cmIsOff(cm::string_view(val)); +} + /** Returns true if string @a str starts with the character @a prefix. */ inline bool cmHasPrefix(cm::string_view str, char prefix) { @@ -174,4 +280,13 @@ inline void cmStripSuffixIfExists(std::string& str, cm::string_view suffix) } } +/** Converts a string to long. Expects that the whole string is an integer. */ +bool cmStrToLong(const char* str, long* value); +bool cmStrToLong(std::string const& str, long* value); + +/** Converts a string to unsigned long. Expects that the whole string is an + * integer */ +bool cmStrToULong(const char* str, unsigned long* value); +bool cmStrToULong(std::string const& str, unsigned long* value); + #endif diff --git a/Source/cmStringCommand.cxx b/Source/cmStringCommand.cxx index 8b3b1e3..849a566 100644 --- a/Source/cmStringCommand.cxx +++ b/Source/cmStringCommand.cxx @@ -8,12 +8,14 @@ #include <algorithm> #include <ctype.h> #include <iterator> +#include <memory> #include <sstream> #include <stdio.h> #include <stdlib.h> #include "cmAlgorithms.h" #include "cmCryptoHash.h" +#include "cmExecutionStatus.h" #include "cmGeneratorExpression.h" #include "cmMakefile.h" #include "cmMessageType.h" @@ -24,123 +26,177 @@ #include "cmTimestamp.h" #include "cmUuid.h" -class cmExecutionStatus; +namespace { +bool HandleConfigureCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool HandleAsciiCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool HandleRegexCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool RegexMatch(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool RegexMatchAll(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool RegexReplace(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool HandleHashCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool HandleToUpperLowerCommand(std::vector<std::string> const& args, + bool toUpper, cmExecutionStatus& status); +bool HandleCompareCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool HandleReplaceCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool HandleLengthCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool HandleSubstringCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool HandleAppendCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool HandlePrependCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool HandleConcatCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool HandleJoinCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool HandleStripCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool HandleRepeatCommand(std::vector<std::string> const& args, + cmMakefile& makefile); +bool HandleRandomCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool HandleFindCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool HandleTimestampCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool HandleMakeCIdentifierCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool HandleGenexStripCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); +bool HandleUuidCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); + +bool joinImpl(std::vector<std::string> const& args, std::string const& glue, + size_t varIdx, cmMakefile& makefile); +} -bool cmStringCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus&) +bool cmStringCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.empty()) { - this->SetError("must be called with at least one argument."); + status.SetError("must be called with at least one argument."); return false; } const std::string& subCommand = args[0]; if (subCommand == "REGEX") { - return this->HandleRegexCommand(args); + return HandleRegexCommand(args, status); } if (subCommand == "REPLACE") { - return this->HandleReplaceCommand(args); + return HandleReplaceCommand(args, status); } if (subCommand == "MD5" || subCommand == "SHA1" || subCommand == "SHA224" || subCommand == "SHA256" || subCommand == "SHA384" || subCommand == "SHA512" || subCommand == "SHA3_224" || subCommand == "SHA3_256" || subCommand == "SHA3_384" || subCommand == "SHA3_512") { - return this->HandleHashCommand(args); + return HandleHashCommand(args, status); } if (subCommand == "TOLOWER") { - return this->HandleToUpperLowerCommand(args, false); + return HandleToUpperLowerCommand(args, false, status); } if (subCommand == "TOUPPER") { - return this->HandleToUpperLowerCommand(args, true); + return HandleToUpperLowerCommand(args, true, status); } if (subCommand == "COMPARE") { - return this->HandleCompareCommand(args); + return HandleCompareCommand(args, status); } if (subCommand == "ASCII") { - return this->HandleAsciiCommand(args); + return HandleAsciiCommand(args, status); } if (subCommand == "CONFIGURE") { - return this->HandleConfigureCommand(args); + return HandleConfigureCommand(args, status); } if (subCommand == "LENGTH") { - return this->HandleLengthCommand(args); + return HandleLengthCommand(args, status); } if (subCommand == "APPEND") { - return this->HandleAppendCommand(args); + return HandleAppendCommand(args, status); } if (subCommand == "PREPEND") { - return this->HandlePrependCommand(args); + return HandlePrependCommand(args, status); } if (subCommand == "CONCAT") { - return this->HandleConcatCommand(args); + return HandleConcatCommand(args, status); } if (subCommand == "JOIN") { - return this->HandleJoinCommand(args); + return HandleJoinCommand(args, status); } if (subCommand == "SUBSTRING") { - return this->HandleSubstringCommand(args); + return HandleSubstringCommand(args, status); } if (subCommand == "STRIP") { - return this->HandleStripCommand(args); + return HandleStripCommand(args, status); } if (subCommand == "REPEAT") { - return this->HandleRepeatCommand(args); + return HandleRepeatCommand(args, status.GetMakefile()); } if (subCommand == "RANDOM") { - return this->HandleRandomCommand(args); + return HandleRandomCommand(args, status); } if (subCommand == "FIND") { - return this->HandleFindCommand(args); + return HandleFindCommand(args, status); } if (subCommand == "TIMESTAMP") { - return this->HandleTimestampCommand(args); + return HandleTimestampCommand(args, status); } if (subCommand == "MAKE_C_IDENTIFIER") { - return this->HandleMakeCIdentifierCommand(args); + return HandleMakeCIdentifierCommand(args, status); } if (subCommand == "GENEX_STRIP") { - return this->HandleGenexStripCommand(args); + return HandleGenexStripCommand(args, status); } if (subCommand == "UUID") { - return this->HandleUuidCommand(args); + return HandleUuidCommand(args, status); } std::string e = "does not recognize sub-command " + subCommand; - this->SetError(e); + status.SetError(e); return false; } -bool cmStringCommand::HandleHashCommand(std::vector<std::string> const& args) +namespace { +bool HandleHashCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) if (args.size() != 3) { std::ostringstream e; e << args[0] << " requires an output variable and an input string"; - this->SetError(e.str()); + status.SetError(e.str()); return false; } - std::unique_ptr<cmCryptoHash> hash(cmCryptoHash::New(args[0].c_str())); + std::unique_ptr<cmCryptoHash> hash(cmCryptoHash::New(args[0])); if (hash) { std::string out = hash->HashString(args[2]); - this->Makefile->AddDefinition(args[1], out); + status.GetMakefile().AddDefinition(args[1], out); return true; } return false; #else std::ostringstream e; e << args[0] << " not available during bootstrap"; - this->SetError(e.str().c_str()); + status.SetError(e.str().c_str()); return false; #endif } -bool cmStringCommand::HandleToUpperLowerCommand( - std::vector<std::string> const& args, bool toUpper) +bool HandleToUpperLowerCommand(std::vector<std::string> const& args, + bool toUpper, cmExecutionStatus& status) { if (args.size() < 3) { - this->SetError("no output variable specified"); + status.SetError("no output variable specified"); return false; } @@ -154,14 +210,15 @@ bool cmStringCommand::HandleToUpperLowerCommand( } // Store the output in the provided variable. - this->Makefile->AddDefinition(outvar, output); + status.GetMakefile().AddDefinition(outvar, output); return true; } -bool cmStringCommand::HandleAsciiCommand(std::vector<std::string> const& args) +bool HandleAsciiCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() < 3) { - this->SetError("No output variable specified"); + status.SetError("No output variable specified"); return false; } std::string::size_type cc; @@ -172,27 +229,26 @@ bool cmStringCommand::HandleAsciiCommand(std::vector<std::string> const& args) if (ch > 0 && ch < 256) { output += static_cast<char>(ch); } else { - std::string error = "Character with code "; - error += args[cc]; - error += " does not exist."; - this->SetError(error); + std::string error = + cmStrCat("Character with code ", args[cc], " does not exist."); + status.SetError(error); return false; } } // Store the output in the provided variable. - this->Makefile->AddDefinition(outvar, output); + status.GetMakefile().AddDefinition(outvar, output); return true; } -bool cmStringCommand::HandleConfigureCommand( - std::vector<std::string> const& args) +bool HandleConfigureCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() < 2) { - this->SetError("No input string specified."); + status.SetError("No input string specified."); return false; } if (args.size() < 3) { - this->SetError("No output variable specified."); + status.SetError("No output variable specified."); return false; } @@ -207,73 +263,75 @@ bool cmStringCommand::HandleConfigureCommand( } else { std::ostringstream err; err << "Unrecognized argument \"" << args[i] << "\""; - this->SetError(err.str()); + status.SetError(err.str()); return false; } } // Configure the string. std::string output; - this->Makefile->ConfigureString(args[1], output, atOnly, escapeQuotes); + status.GetMakefile().ConfigureString(args[1], output, atOnly, escapeQuotes); // Store the output in the provided variable. - this->Makefile->AddDefinition(args[2], output); + status.GetMakefile().AddDefinition(args[2], output); return true; } -bool cmStringCommand::HandleRegexCommand(std::vector<std::string> const& args) +bool HandleRegexCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() < 2) { - this->SetError("sub-command REGEX requires a mode to be specified."); + status.SetError("sub-command REGEX requires a mode to be specified."); return false; } std::string const& mode = args[1]; if (mode == "MATCH") { if (args.size() < 5) { - this->SetError("sub-command REGEX, mode MATCH needs " - "at least 5 arguments total to command."); + status.SetError("sub-command REGEX, mode MATCH needs " + "at least 5 arguments total to command."); return false; } - return this->RegexMatch(args); + return RegexMatch(args, status); } if (mode == "MATCHALL") { if (args.size() < 5) { - this->SetError("sub-command REGEX, mode MATCHALL needs " - "at least 5 arguments total to command."); + status.SetError("sub-command REGEX, mode MATCHALL needs " + "at least 5 arguments total to command."); return false; } - return this->RegexMatchAll(args); + return RegexMatchAll(args, status); } if (mode == "REPLACE") { if (args.size() < 6) { - this->SetError("sub-command REGEX, mode REPLACE needs " - "at least 6 arguments total to command."); + status.SetError("sub-command REGEX, mode REPLACE needs " + "at least 6 arguments total to command."); return false; } - return this->RegexReplace(args); + return RegexReplace(args, status); } std::string e = "sub-command REGEX does not recognize mode " + mode; - this->SetError(e); + status.SetError(e); return false; } -bool cmStringCommand::RegexMatch(std::vector<std::string> const& args) +bool RegexMatch(std::vector<std::string> const& args, + cmExecutionStatus& status) { //"STRING(REGEX MATCH <regular_expression> <output variable> // <input> [<input>...])\n"; std::string const& regex = args[2]; std::string const& outvar = args[3]; - this->Makefile->ClearMatches(); + status.GetMakefile().ClearMatches(); // Compile the regular expression. cmsys::RegularExpression re; if (!re.compile(regex.c_str())) { std::string e = "sub-command REGEX, mode MATCH failed to compile regex \"" + regex + "\"."; - this->SetError(e); + status.SetError(e); return false; } @@ -283,38 +341,39 @@ bool cmStringCommand::RegexMatch(std::vector<std::string> const& args) // Scan through the input for all matches. std::string output; if (re.find(input)) { - this->Makefile->StoreMatches(re); + status.GetMakefile().StoreMatches(re); std::string::size_type l = re.start(); std::string::size_type r = re.end(); if (r - l == 0) { std::string e = "sub-command REGEX, mode MATCH regex \"" + regex + "\" matched an empty string."; - this->SetError(e); + status.SetError(e); return false; } output = input.substr(l, r - l); } // Store the output in the provided variable. - this->Makefile->AddDefinition(outvar, output); + status.GetMakefile().AddDefinition(outvar, output); return true; } -bool cmStringCommand::RegexMatchAll(std::vector<std::string> const& args) +bool RegexMatchAll(std::vector<std::string> const& args, + cmExecutionStatus& status) { //"STRING(REGEX MATCHALL <regular_expression> <output variable> <input> // [<input>...])\n"; std::string const& regex = args[2]; std::string const& outvar = args[3]; - this->Makefile->ClearMatches(); + status.GetMakefile().ClearMatches(); // Compile the regular expression. cmsys::RegularExpression re; if (!re.compile(regex.c_str())) { std::string e = "sub-command REGEX, mode MATCHALL failed to compile regex \"" + regex + "\"."; - this->SetError(e); + status.SetError(e); return false; } @@ -325,14 +384,14 @@ bool cmStringCommand::RegexMatchAll(std::vector<std::string> const& args) std::string output; const char* p = input.c_str(); while (re.find(p)) { - this->Makefile->ClearMatches(); - this->Makefile->StoreMatches(re); + status.GetMakefile().ClearMatches(); + status.GetMakefile().StoreMatches(re); std::string::size_type l = re.start(); std::string::size_type r = re.end(); if (r - l == 0) { std::string e = "sub-command REGEX, mode MATCHALL regex \"" + regex + "\" matched an empty string."; - this->SetError(e); + status.SetError(e); return false; } if (!output.empty()) { @@ -343,32 +402,33 @@ bool cmStringCommand::RegexMatchAll(std::vector<std::string> const& args) } // Store the output in the provided variable. - this->Makefile->AddDefinition(outvar, output); + status.GetMakefile().AddDefinition(outvar, output); return true; } -bool cmStringCommand::RegexReplace(std::vector<std::string> const& args) +bool RegexReplace(std::vector<std::string> const& args, + cmExecutionStatus& status) { //"STRING(REGEX REPLACE <regular_expression> <replace_expression> // <output variable> <input> [<input>...])\n" std::string const& regex = args[2]; std::string const& replace = args[3]; std::string const& outvar = args[4]; - cmStringReplaceHelper replaceHelper(regex, replace, this->Makefile); + cmStringReplaceHelper replaceHelper(regex, replace, &status.GetMakefile()); if (!replaceHelper.IsReplaceExpressionValid()) { - this->SetError( + status.SetError( "sub-command REGEX, mode REPLACE: " + replaceHelper.GetError() + "."); return false; } - this->Makefile->ClearMatches(); + status.GetMakefile().ClearMatches(); if (!replaceHelper.IsRegularExpressionValid()) { std::string e = "sub-command REGEX, mode REPLACE failed to compile regex \"" + regex + "\"."; - this->SetError(e); + status.SetError(e); return false; } @@ -378,21 +438,22 @@ bool cmStringCommand::RegexReplace(std::vector<std::string> const& args) std::string output; if (!replaceHelper.Replace(input, output)) { - this->SetError( + status.SetError( "sub-command REGEX, mode REPLACE: " + replaceHelper.GetError() + "."); return false; } // Store the output in the provided variable. - this->Makefile->AddDefinition(outvar, output); + status.GetMakefile().AddDefinition(outvar, output); return true; } -bool cmStringCommand::HandleFindCommand(std::vector<std::string> const& args) +bool HandleFindCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { // check if all required parameters were passed if (args.size() < 4 || args.size() > 5) { - this->SetError("sub-command FIND requires 3 or 4 parameters."); + status.SetError("sub-command FIND requires 3 or 4 parameters."); return false; } @@ -404,7 +465,7 @@ bool cmStringCommand::HandleFindCommand(std::vector<std::string> const& args) // if we have 5 arguments the last one must be REVERSE if (args.size() == 5 && args[4] != "REVERSE") { - this->SetError("sub-command FIND: unknown last parameter"); + status.SetError("sub-command FIND: unknown last parameter"); return false; } @@ -415,9 +476,9 @@ bool cmStringCommand::HandleFindCommand(std::vector<std::string> const& args) // ensure that the user cannot accidentally specify REVERSE as a variable if (outvar == "REVERSE") { - this->SetError("sub-command FIND does not allow one to select REVERSE as " - "the output variable. " - "Maybe you missed the actual output variable?"); + status.SetError("sub-command FIND does not allow one to select REVERSE as " + "the output variable. " + "Maybe you missed the actual output variable?"); return false; } @@ -431,20 +492,20 @@ bool cmStringCommand::HandleFindCommand(std::vector<std::string> const& args) if (std::string::npos != pos) { std::ostringstream s; s << pos; - this->Makefile->AddDefinition(outvar, s.str()); + status.GetMakefile().AddDefinition(outvar, s.str()); return true; } // the character was not found, but this is not really an error - this->Makefile->AddDefinition(outvar, "-1"); + status.GetMakefile().AddDefinition(outvar, "-1"); return true; } -bool cmStringCommand::HandleCompareCommand( - std::vector<std::string> const& args) +bool HandleCompareCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() < 2) { - this->SetError("sub-command COMPARE requires a mode to be specified."); + status.SetError("sub-command COMPARE requires a mode to be specified."); return false; } std::string const& mode = args[1]; @@ -452,10 +513,10 @@ bool cmStringCommand::HandleCompareCommand( (mode == "LESS_EQUAL") || (mode == "GREATER") || (mode == "GREATER_EQUAL")) { if (args.size() < 5) { - std::string e = "sub-command COMPARE, mode "; - e += mode; - e += " needs at least 5 arguments total to command."; - this->SetError(e); + std::string e = + cmStrCat("sub-command COMPARE, mode ", mode, + " needs at least 5 arguments total to command."); + status.SetError(e); return false; } @@ -478,22 +539,22 @@ bool cmStringCommand::HandleCompareCommand( result = !(left == right); } if (result) { - this->Makefile->AddDefinition(outvar, "1"); + status.GetMakefile().AddDefinition(outvar, "1"); } else { - this->Makefile->AddDefinition(outvar, "0"); + status.GetMakefile().AddDefinition(outvar, "0"); } return true; } std::string e = "sub-command COMPARE does not recognize mode " + mode; - this->SetError(e); + status.SetError(e); return false; } -bool cmStringCommand::HandleReplaceCommand( - std::vector<std::string> const& args) +bool HandleReplaceCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() < 5) { - this->SetError("sub-command REPLACE requires at least four arguments."); + status.SetError("sub-command REPLACE requires at least four arguments."); return false; } @@ -506,15 +567,15 @@ bool cmStringCommand::HandleReplaceCommand( cmsys::SystemTools::ReplaceString(input, matchExpression.c_str(), replaceExpression.c_str()); - this->Makefile->AddDefinition(variableName, input); + status.GetMakefile().AddDefinition(variableName, input); return true; } -bool cmStringCommand::HandleSubstringCommand( - std::vector<std::string> const& args) +bool HandleSubstringCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() != 5) { - this->SetError("sub-command SUBSTRING requires four arguments."); + status.SetError("sub-command SUBSTRING requires four arguments."); return false; } @@ -529,24 +590,26 @@ bool cmStringCommand::HandleSubstringCommand( std::ostringstream ostr; ostr << "begin index: " << begin << " is out of range 0 - " << stringLength; - this->SetError(ostr.str()); + status.SetError(ostr.str()); return false; } if (end < -1) { std::ostringstream ostr; ostr << "end index: " << end << " should be -1 or greater"; - this->SetError(ostr.str()); + status.SetError(ostr.str()); return false; } - this->Makefile->AddDefinition(variableName, stringValue.substr(begin, end)); + status.GetMakefile().AddDefinition(variableName, + stringValue.substr(begin, end)); return true; } -bool cmStringCommand::HandleLengthCommand(std::vector<std::string> const& args) +bool HandleLengthCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() != 3) { - this->SetError("sub-command LENGTH requires two arguments."); + status.SetError("sub-command LENGTH requires two arguments."); return false; } @@ -557,14 +620,15 @@ bool cmStringCommand::HandleLengthCommand(std::vector<std::string> const& args) char buffer[1024]; sprintf(buffer, "%d", static_cast<int>(length)); - this->Makefile->AddDefinition(variableName, buffer); + status.GetMakefile().AddDefinition(variableName, buffer); return true; } -bool cmStringCommand::HandleAppendCommand(std::vector<std::string> const& args) +bool HandleAppendCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() < 2) { - this->SetError("sub-command APPEND requires at least one argument."); + status.SetError("sub-command APPEND requires at least one argument."); return false; } @@ -576,20 +640,20 @@ bool cmStringCommand::HandleAppendCommand(std::vector<std::string> const& args) const std::string& variable = args[1]; std::string value; - const char* oldValue = this->Makefile->GetDefinition(variable); + const char* oldValue = status.GetMakefile().GetDefinition(variable); if (oldValue) { value = oldValue; } value += cmJoin(cmMakeRange(args).advance(2), std::string()); - this->Makefile->AddDefinition(variable, value); + status.GetMakefile().AddDefinition(variable, value); return true; } -bool cmStringCommand::HandlePrependCommand( - std::vector<std::string> const& args) +bool HandlePrependCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() < 2) { - this->SetError("sub-command PREPEND requires at least one argument."); + status.SetError("sub-command PREPEND requires at least one argument."); return false; } @@ -601,67 +665,69 @@ bool cmStringCommand::HandlePrependCommand( const std::string& variable = args[1]; std::string value = cmJoin(cmMakeRange(args).advance(2), std::string()); - const char* oldValue = this->Makefile->GetDefinition(variable); + const char* oldValue = status.GetMakefile().GetDefinition(variable); if (oldValue) { value += oldValue; } - this->Makefile->AddDefinition(variable, value); + status.GetMakefile().AddDefinition(variable, value); return true; } -bool cmStringCommand::HandleConcatCommand(std::vector<std::string> const& args) +bool HandleConcatCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() < 2) { - this->SetError("sub-command CONCAT requires at least one argument."); + status.SetError("sub-command CONCAT requires at least one argument."); return false; } - return this->joinImpl(args, std::string(), 1); + return joinImpl(args, std::string(), 1, status.GetMakefile()); } -bool cmStringCommand::HandleJoinCommand(std::vector<std::string> const& args) +bool HandleJoinCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() < 3) { - this->SetError("sub-command JOIN requires at least two arguments."); + status.SetError("sub-command JOIN requires at least two arguments."); return false; } - return this->joinImpl(args, args[1], 2); + return joinImpl(args, args[1], 2, status.GetMakefile()); } -bool cmStringCommand::joinImpl(std::vector<std::string> const& args, - std::string const& glue, const size_t varIdx) +bool joinImpl(std::vector<std::string> const& args, std::string const& glue, + const size_t varIdx, cmMakefile& makefile) { std::string const& variableName = args[varIdx]; // NOTE Items to concat/join placed right after the variable for // both `CONCAT` and `JOIN` sub-commands. std::string value = cmJoin(cmMakeRange(args).advance(varIdx + 1), glue); - this->Makefile->AddDefinition(variableName, value); + makefile.AddDefinition(variableName, value); return true; } -bool cmStringCommand::HandleMakeCIdentifierCommand( - std::vector<std::string> const& args) +bool HandleMakeCIdentifierCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() != 3) { - this->SetError("sub-command MAKE_C_IDENTIFIER requires two arguments."); + status.SetError("sub-command MAKE_C_IDENTIFIER requires two arguments."); return false; } const std::string& input = args[1]; const std::string& variableName = args[2]; - this->Makefile->AddDefinition(variableName, - cmSystemTools::MakeCidentifier(input)); + status.GetMakefile().AddDefinition(variableName, + cmSystemTools::MakeCidentifier(input)); return true; } -bool cmStringCommand::HandleGenexStripCommand( - std::vector<std::string> const& args) +bool HandleGenexStripCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() != 3) { - this->SetError("sub-command GENEX_STRIP requires two arguments."); + status.SetError("sub-command GENEX_STRIP requires two arguments."); return false; } @@ -672,14 +738,15 @@ bool cmStringCommand::HandleGenexStripCommand( const std::string& variableName = args[2]; - this->Makefile->AddDefinition(variableName, result); + status.GetMakefile().AddDefinition(variableName, result); return true; } -bool cmStringCommand::HandleStripCommand(std::vector<std::string> const& args) +bool HandleStripCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() != 3) { - this->SetError("sub-command STRIP requires two arguments."); + status.SetError("sub-command STRIP requires two arguments."); return false; } @@ -711,12 +778,13 @@ bool cmStringCommand::HandleStripCommand(std::vector<std::string> const& args) outLength = endPos - startPos + 1; } - this->Makefile->AddDefinition(variableName, - stringValue.substr(startPos, outLength)); + status.GetMakefile().AddDefinition(variableName, + stringValue.substr(startPos, outLength)); return true; } -bool cmStringCommand::HandleRepeatCommand(std::vector<std::string> const& args) +bool HandleRepeatCommand(std::vector<std::string> const& args, + cmMakefile& makefile) { // `string(REPEAT "<str>" <times> OUTPUT_VARIABLE)` enum ArgPos : std::size_t @@ -729,16 +797,15 @@ bool cmStringCommand::HandleRepeatCommand(std::vector<std::string> const& args) }; if (args.size() != ArgPos::TOTAL_ARGS) { - this->Makefile->IssueMessage( - MessageType::FATAL_ERROR, - "sub-command REPEAT requires three arguments."); + makefile.IssueMessage(MessageType::FATAL_ERROR, + "sub-command REPEAT requires three arguments."); return true; } unsigned long times; - if (!cmSystemTools::StringToULong(args[ArgPos::TIMES].c_str(), ×)) { - this->Makefile->IssueMessage(MessageType::FATAL_ERROR, - "repeat count is not a positive number."); + if (!cmStrToULong(args[ArgPos::TIMES], ×)) { + makefile.IssueMessage(MessageType::FATAL_ERROR, + "repeat count is not a positive number."); return true; } @@ -765,14 +832,15 @@ bool cmStringCommand::HandleRepeatCommand(std::vector<std::string> const& args) break; } - this->Makefile->AddDefinition(variableName, result); + makefile.AddDefinition(variableName, result); return true; } -bool cmStringCommand::HandleRandomCommand(std::vector<std::string> const& args) +bool HandleRandomCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() < 2 || args.size() == 3 || args.size() == 5) { - this->SetError("sub-command RANDOM requires at least one argument."); + status.SetError("sub-command RANDOM requires at least one argument."); return false; } @@ -809,11 +877,11 @@ bool cmStringCommand::HandleRandomCommand(std::vector<std::string> const& args) double sizeofAlphabet = static_cast<double>(alphabet.size()); if (sizeofAlphabet < 1) { - this->SetError("sub-command RANDOM invoked with bad alphabet."); + status.SetError("sub-command RANDOM invoked with bad alphabet."); return false; } if (length < 1) { - this->SetError("sub-command RANDOM invoked with bad length."); + status.SetError("sub-command RANDOM invoked with bad length."); return false; } const std::string& variableName = args.back(); @@ -832,19 +900,19 @@ bool cmStringCommand::HandleRandomCommand(std::vector<std::string> const& args) } result.push_back(0); - this->Makefile->AddDefinition(variableName, result.data()); + status.GetMakefile().AddDefinition(variableName, result.data()); return true; } -bool cmStringCommand::HandleTimestampCommand( - std::vector<std::string> const& args) +bool HandleTimestampCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() < 2) { - this->SetError("sub-command TIMESTAMP requires at least one argument."); + status.SetError("sub-command TIMESTAMP requires at least one argument."); return false; } if (args.size() > 4) { - this->SetError("sub-command TIMESTAMP takes at most three arguments."); + status.SetError("sub-command TIMESTAMP takes at most three arguments."); return false; } @@ -864,25 +932,26 @@ bool cmStringCommand::HandleTimestampCommand( } else { std::string e = " TIMESTAMP sub-command does not recognize option " + args[argsIndex] + "."; - this->SetError(e); + status.SetError(e); return false; } } cmTimestamp timestamp; std::string result = timestamp.CurrentTime(formatString, utcFlag); - this->Makefile->AddDefinition(outputVariable, result); + status.GetMakefile().AddDefinition(outputVariable, result); return true; } -bool cmStringCommand::HandleUuidCommand(std::vector<std::string> const& args) +bool HandleUuidCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) unsigned int argsIndex = 1; if (args.size() < 2) { - this->SetError("UUID sub-command requires an output variable."); + status.SetError("UUID sub-command requires an output variable."); return false; } @@ -897,21 +966,21 @@ bool cmStringCommand::HandleUuidCommand(std::vector<std::string> const& args) if (args[argsIndex] == "NAMESPACE") { ++argsIndex; if (argsIndex >= args.size()) { - this->SetError("UUID sub-command, NAMESPACE requires a value."); + status.SetError("UUID sub-command, NAMESPACE requires a value."); return false; } uuidNamespaceString = args[argsIndex++]; } else if (args[argsIndex] == "NAME") { ++argsIndex; if (argsIndex >= args.size()) { - this->SetError("UUID sub-command, NAME requires a value."); + status.SetError("UUID sub-command, NAME requires a value."); return false; } uuidName = args[argsIndex++]; } else if (args[argsIndex] == "TYPE") { ++argsIndex; if (argsIndex >= args.size()) { - this->SetError("UUID sub-command, TYPE requires a value."); + status.SetError("UUID sub-command, TYPE requires a value."); return false; } uuidType = args[argsIndex++]; @@ -921,7 +990,7 @@ bool cmStringCommand::HandleUuidCommand(std::vector<std::string> const& args) } else { std::string e = "UUID sub-command does not recognize option " + args[argsIndex] + "."; - this->SetError(e); + status.SetError(e); return false; } } @@ -931,7 +1000,7 @@ bool cmStringCommand::HandleUuidCommand(std::vector<std::string> const& args) std::vector<unsigned char> uuidNamespace; if (!uuidGenerator.StringToBinary(uuidNamespaceString, uuidNamespace)) { - this->SetError("UUID sub-command, malformed NAMESPACE UUID."); + status.SetError("UUID sub-command, malformed NAMESPACE UUID."); return false; } @@ -941,12 +1010,12 @@ bool cmStringCommand::HandleUuidCommand(std::vector<std::string> const& args) uuid = uuidGenerator.FromSha1(uuidNamespace, uuidName); } else { std::string e = "UUID sub-command, unknown TYPE '" + uuidType + "'."; - this->SetError(e); + status.SetError(e); return false; } if (uuid.empty()) { - this->SetError("UUID sub-command, generation failed."); + status.SetError("UUID sub-command, generation failed."); return false; } @@ -954,12 +1023,13 @@ bool cmStringCommand::HandleUuidCommand(std::vector<std::string> const& args) uuid = cmSystemTools::UpperCase(uuid); } - this->Makefile->AddDefinition(outputVariable, uuid); + status.GetMakefile().AddDefinition(outputVariable, uuid); return true; #else std::ostringstream e; e << args[0] << " not available during bootstrap"; - this->SetError(e.str().c_str()); + status.SetError(e.str().c_str()); return false; #endif } +} diff --git a/Source/cmStringCommand.h b/Source/cmStringCommand.h index f48ea17..bd71ba2 100644 --- a/Source/cmStringCommand.h +++ b/Source/cmStringCommand.h @@ -5,67 +5,16 @@ #include "cmConfigure.h" // IWYU pragma: keep -#include <cstddef> #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -/** \class cmStringCommand +/** * \brief Common string operations * */ -class cmStringCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmStringCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; - -protected: - bool HandleConfigureCommand(std::vector<std::string> const& args); - bool HandleAsciiCommand(std::vector<std::string> const& args); - bool HandleRegexCommand(std::vector<std::string> const& args); - bool RegexMatch(std::vector<std::string> const& args); - bool RegexMatchAll(std::vector<std::string> const& args); - bool RegexReplace(std::vector<std::string> const& args); - bool HandleHashCommand(std::vector<std::string> const& args); - bool HandleToUpperLowerCommand(std::vector<std::string> const& args, - bool toUpper); - bool HandleCompareCommand(std::vector<std::string> const& args); - bool HandleReplaceCommand(std::vector<std::string> const& args); - bool HandleLengthCommand(std::vector<std::string> const& args); - bool HandleSubstringCommand(std::vector<std::string> const& args); - bool HandleAppendCommand(std::vector<std::string> const& args); - bool HandlePrependCommand(std::vector<std::string> const& args); - bool HandleConcatCommand(std::vector<std::string> const& args); - bool HandleJoinCommand(std::vector<std::string> const& args); - bool HandleStripCommand(std::vector<std::string> const& args); - bool HandleRepeatCommand(std::vector<std::string> const& args); - bool HandleRandomCommand(std::vector<std::string> const& args); - bool HandleFindCommand(std::vector<std::string> const& args); - bool HandleTimestampCommand(std::vector<std::string> const& args); - bool HandleMakeCIdentifierCommand(std::vector<std::string> const& args); - bool HandleGenexStripCommand(std::vector<std::string> const& args); - bool HandleUuidCommand(std::vector<std::string> const& args); - - bool joinImpl(std::vector<std::string> const& args, std::string const& glue, - size_t varIdx); -}; +bool cmStringCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmSubcommandTable.cxx b/Source/cmSubcommandTable.cxx new file mode 100644 index 0000000..f6194f8 --- /dev/null +++ b/Source/cmSubcommandTable.cxx @@ -0,0 +1,31 @@ +/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying + file Copyright.txt or https://cmake.org/licensing for details. */ +#include "cmSubcommandTable.h" + +#include <algorithm> + +#include "cmExecutionStatus.h" +#include "cmStringAlgorithms.h" + +cmSubcommandTable::cmSubcommandTable(std::initializer_list<InitElem> init) + : Impl(init.begin(), init.end()) +{ + std::sort(this->Impl.begin(), this->Impl.end(), + [](Elem const& left, Elem const& right) { + return left.first < right.first; + }); +} + +bool cmSubcommandTable::operator()(cm::string_view key, + std::vector<std::string> const& args, + cmExecutionStatus& status) const +{ + auto const it = std::lower_bound( + this->Impl.begin(), this->Impl.end(), key, + [](Elem const& elem, cm::string_view k) { return elem.first < k; }); + if (it != this->Impl.end() && it->first == key) { + return it->second(args, status); + } + status.SetError(cmStrCat("does not recognize sub-command ", key)); + return false; +} diff --git a/Source/cmSubcommandTable.h b/Source/cmSubcommandTable.h new file mode 100644 index 0000000..21342bb --- /dev/null +++ b/Source/cmSubcommandTable.h @@ -0,0 +1,36 @@ +/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying + file Copyright.txt or https://cmake.org/licensing for details. */ +#ifndef cmSubcommandTable_h +#define cmSubcommandTable_h + +#include "cmConfigure.h" // IWYU pragma: keep + +#include "cm_static_string_view.hxx" +#include "cm_string_view.hxx" + +#include <initializer_list> +#include <string> +#include <utility> +#include <vector> + +class cmExecutionStatus; + +class cmSubcommandTable +{ +public: + using Command = bool (*)(std::vector<std::string> const&, + cmExecutionStatus&); + + using Elem = std::pair<cm::string_view, Command>; + using InitElem = std::pair<cm::static_string_view, Command>; + + cmSubcommandTable(std::initializer_list<InitElem> init); + + bool operator()(cm::string_view key, std::vector<std::string> const& args, + cmExecutionStatus& status) const; + +private: + std::vector<Elem> Impl; +}; + +#endif diff --git a/Source/cmSubdirCommand.cxx b/Source/cmSubdirCommand.cxx index 9d36228..07f8efe 100644 --- a/Source/cmSubdirCommand.cxx +++ b/Source/cmSubdirCommand.cxx @@ -3,6 +3,7 @@ #include "cmSubdirCommand.h" #include "cmMakefile.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" class cmExecutionStatus; @@ -44,8 +45,8 @@ bool cmSubdirCommand::InitialPass(std::vector<std::string> const& args, cmSystemTools::GetFilenameName(i); this->Makefile->AddSubDirectory(i, binPath, excludeFromAll, false); } else { - std::string error = "Incorrect SUBDIRS command. Directory: "; - error += i + " does not exist."; + std::string error = cmStrCat("Incorrect SUBDIRS command. Directory: ", i, + " does not exist."); this->SetError(error); res = false; } diff --git a/Source/cmSystemTools.cxx b/Source/cmSystemTools.cxx index 5f4e1fc..b7287d9 100644 --- a/Source/cmSystemTools.cxx +++ b/Source/cmSystemTools.cxx @@ -9,7 +9,7 @@ #include "cmStringAlgorithms.h" #include "cm_uv.h" -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) # include "cmArchiveWrite.h" # include "cmLocale.h" # include "cm_libarchive.h" @@ -21,7 +21,7 @@ # endif #endif -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) # include "cmCryptoHash.h" #endif @@ -84,11 +84,6 @@ cmSystemTools::OutputCallback s_StdoutCallback; } // namespace -static bool cm_isspace(char c) -{ - return ((c & 0x80) == 0) && isspace(c); -} - #if !defined(HAVE_ENVIRON_NOT_REQUIRE_PROTOTYPE) // For GetEnvironmentVariables # if defined(_WIN32) @@ -98,7 +93,7 @@ extern char** environ; # endif #endif -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) static std::string cm_archive_entry_pathname(struct archive_entry* entry) { # if cmsys_STL_HAS_WSTRING @@ -152,12 +147,10 @@ void cmSystemTools::ExpandRegistryValues(std::string& source, KeyWOW64 view) std::string key = regEntry.match(1); std::string val; if (ReadRegistryValue(key.c_str(), val, view)) { - std::string reg = "["; - reg += key + "]"; + std::string reg = cmStrCat('[', key, ']'); cmSystemTools::ReplaceString(source, reg.c_str(), val.c_str()); } else { - std::string reg = "["; - reg += key + "]"; + std::string reg = cmStrCat('[', key, ']'); cmSystemTools::ReplaceString(source, reg.c_str(), "/registry"); } } @@ -170,26 +163,12 @@ void cmSystemTools::ExpandRegistryValues(std::string& source, while (regEntry.find(source)) { // the arguments are the second match std::string key = regEntry.match(1); - std::string reg = "["; - reg += key + "]"; + std::string reg = cmStrCat('[', key, ']'); cmSystemTools::ReplaceString(source, reg.c_str(), "/registry"); } } #endif -std::string cmSystemTools::EscapeQuotes(cm::string_view str) -{ - std::string result; - result.reserve(str.size()); - for (const char ch : str) { - if (ch == '"') { - result += '\\'; - } - result += ch; - } - return result; -} - std::string cmSystemTools::HelpFileName(cm::string_view str) { std::string name(str); @@ -198,22 +177,6 @@ std::string cmSystemTools::HelpFileName(cm::string_view str) return name; } -std::string cmSystemTools::TrimWhitespace(cm::string_view str) -{ - auto start = str.begin(); - while (start != str.end() && cm_isspace(*start)) { - ++start; - } - if (start == str.end()) { - return std::string(); - } - auto stop = str.end() - 1; - while (cm_isspace(*stop)) { - --stop; - } - return std::string(start, stop + 1); -} - void cmSystemTools::Error(const std::string& m) { std::string message = "CMake Error: " + m; @@ -278,91 +241,11 @@ void cmSystemTools::Message(const std::string& m, const char* title) void cmSystemTools::ReportLastSystemError(const char* msg) { - std::string m = msg; - m += ": System Error: "; - m += Superclass::GetLastSystemError(); + std::string m = + cmStrCat(msg, ": System Error: ", Superclass::GetLastSystemError()); cmSystemTools::Error(m); } -bool cmSystemTools::IsInternallyOn(cm::string_view val) -{ - return (val.size() == 4) && // - (val[0] == 'I' || val[0] == 'i') && // - (val[1] == '_') && // - (val[2] == 'O' || val[2] == 'o') && // - (val[3] == 'N' || val[3] == 'n'); -} - -bool cmSystemTools::IsOn(cm::string_view val) -{ - switch (val.size()) { - case 1: - return val[0] == '1' || val[0] == 'Y' || val[0] == 'y'; - case 2: - return // - (val[0] == 'O' || val[0] == 'o') && // - (val[1] == 'N' || val[1] == 'n'); - case 3: - return // - (val[0] == 'Y' || val[0] == 'y') && // - (val[1] == 'E' || val[1] == 'e') && // - (val[2] == 'S' || val[2] == 's'); - case 4: - return // - (val[0] == 'T' || val[0] == 't') && // - (val[1] == 'R' || val[1] == 'r') && // - (val[2] == 'U' || val[2] == 'u') && // - (val[3] == 'E' || val[3] == 'e'); - default: - break; - } - - return false; -} - -bool cmSystemTools::IsNOTFOUND(cm::string_view val) -{ - return (val == "NOTFOUND") || cmHasLiteralSuffix(val, "-NOTFOUND"); -} - -bool cmSystemTools::IsOff(cm::string_view val) -{ - switch (val.size()) { - case 0: - return true; - case 1: - return val[0] == '0' || val[0] == 'N' || val[0] == 'n'; - case 2: - return // - (val[0] == 'N' || val[0] == 'n') && // - (val[1] == 'O' || val[1] == 'o'); - case 3: - return // - (val[0] == 'O' || val[0] == 'o') && // - (val[1] == 'F' || val[1] == 'f') && // - (val[2] == 'F' || val[2] == 'f'); - case 5: - return // - (val[0] == 'F' || val[0] == 'f') && // - (val[1] == 'A' || val[1] == 'a') && // - (val[2] == 'L' || val[2] == 'l') && // - (val[3] == 'S' || val[3] == 's') && // - (val[4] == 'E' || val[4] == 'e'); - case 6: - return // - (val[0] == 'I' || val[0] == 'i') && // - (val[1] == 'G' || val[1] == 'g') && // - (val[2] == 'N' || val[2] == 'n') && // - (val[3] == 'O' || val[3] == 'o') && // - (val[4] == 'R' || val[4] == 'r') && // - (val[5] == 'E' || val[5] == 'e'); - default: - break; - } - - return cmSystemTools::IsNOTFOUND(val); -} - void cmSystemTools::ParseWindowsCommandLine(const char* command, std::vector<std::string>& args) { @@ -396,7 +279,7 @@ void cmSystemTools::ParseWindowsCommandLine(const char* command, } else { arg.append(backslashes, '\\'); backslashes = 0; - if (cm_isspace(*c)) { + if (cmIsSpace(*c)) { if (in_quotes) { arg.append(1, *c); } else if (in_argument) { @@ -459,10 +342,9 @@ std::vector<std::string> cmSystemTools::HandleResponseFile( if (cmHasLiteralPrefix(arg, "@")) { cmsys::ifstream responseFile(arg.substr(1).c_str(), std::ios::in); if (!responseFile) { - std::string error = "failed to open for reading ("; - error += cmSystemTools::GetLastSystemError(); - error += "):\n "; - error += arg.substr(1); + std::string error = cmStrCat("failed to open for reading (", + cmSystemTools::GetLastSystemError(), + "):\n ", cm::string_view(arg).substr(1)); cmSystemTools::Error(error); } else { std::string line; @@ -815,9 +697,7 @@ bool cmSystemTools::DoesFileExistWithExtensions( std::string hname; for (std::string const& headerExt : headerExts) { - hname = name; - hname += "."; - hname += headerExt; + hname = cmStrCat(name, '.', headerExt); if (cmSystemTools::FileExists(hname)) { return true; } @@ -835,7 +715,7 @@ std::string cmSystemTools::FileExistsInParentDirectories( cmSystemTools::ConvertToUnixSlashes(dir); std::string prevDir; while (dir != prevDir) { - std::string path = dir + "/" + file; + std::string path = cmStrCat(dir, "/", file); if (cmSystemTools::FileExists(path)) { return path; } @@ -978,7 +858,7 @@ bool cmSystemTools::RenameFile(const std::string& oldname, std::string cmSystemTools::ComputeFileHash(const std::string& source, cmCryptoHash::Algo algo) { -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) cmCryptoHash hash(algo); return hash.HashFile(source); #else @@ -991,7 +871,7 @@ std::string cmSystemTools::ComputeFileHash(const std::string& source, std::string cmSystemTools::ComputeStringMD5(const std::string& input) { -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) cmCryptoHash md5(cmCryptoHash::AlgoMD5); return md5.HashString(input); #else @@ -1007,7 +887,7 @@ std::string cmSystemTools::ComputeCertificateThumbprint( { std::string thumbprint; -#if defined(CMAKE_BUILD_WITH_CMAKE) && defined(_WIN32) +#if !defined(CMAKE_BOOTSTRAP) && defined(_WIN32) BYTE* certData = NULL; CRYPT_INTEGER_BLOB cryptBlob; HCERTSTORE certStore = NULL; @@ -1111,9 +991,7 @@ void cmSystemTools::GlobDirs(const std::string& path, for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i) { if ((std::string(d.GetFile(i)) != ".") && (std::string(d.GetFile(i)) != "..")) { - std::string fname = startPath; - fname += "/"; - fname += d.GetFile(i); + std::string fname = cmStrCat(startPath, '/', d.GetFile(i)); if (cmSystemTools::FileIsDirectory(fname)) { fname += finishPath; cmSystemTools::GlobDirs(fname, files); @@ -1123,79 +1001,6 @@ void cmSystemTools::GlobDirs(const std::string& path, } } -void cmSystemTools::ExpandListArgument(cm::string_view arg, - std::vector<std::string>& argsOut, - bool emptyArgs) -{ - // If argument is empty, it is an empty list. - if (!emptyArgs && arg.empty()) { - return; - } - - // if there are no ; in the name then just copy the current string - if (arg.find(';') == cm::string_view::npos) { - argsOut.emplace_back(arg); - return; - } - - std::string newArg; - // Break the string at non-escaped semicolons not nested in []. - int squareNesting = 0; - cm::string_view::iterator last = arg.begin(); - cm::string_view::iterator const cend = arg.end(); - for (cm::string_view::iterator c = last; c != cend; ++c) { - switch (*c) { - case '\\': { - // We only want to allow escaping of semicolons. Other - // escapes should not be processed here. - cm::string_view::iterator cnext = c + 1; - if ((cnext != cend) && *cnext == ';') { - newArg.append(last, c); - // Skip over the escape character - last = cnext; - c = cnext; - } - } break; - case '[': { - ++squareNesting; - } break; - case ']': { - --squareNesting; - } break; - case ';': { - // Break the string here if we are not nested inside square - // brackets. - if (squareNesting == 0) { - newArg.append(last, c); - // Skip over the semicolon - last = c + 1; - if (!newArg.empty() || emptyArgs) { - // Add the last argument if the string is not empty. - argsOut.push_back(newArg); - newArg.clear(); - } - } - } break; - default: { - // Just append this character. - } break; - } - } - newArg.append(last, cend); - if (!newArg.empty() || emptyArgs) { - // Add the last argument if the string is not empty. - argsOut.push_back(std::move(newArg)); - } -} - -std::vector<std::string> cmSystemTools::ExpandedListArgument( - cm::string_view arg, bool emptyArgs) -{ - std::vector<std::string> argsOut; - ExpandListArgument(arg, argsOut, emptyArgs); - return argsOut; -} - bool cmSystemTools::SimpleGlob(const std::string& glob, std::vector<std::string>& files, int type /* = 0 */) @@ -1365,12 +1170,11 @@ std::string cmSystemTools::ForceToRelativePath(std::string const& local_path, return relative; } -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP bool cmSystemTools::UnsetEnv(const char* value) { # if !defined(HAVE_UNSETENV) - std::string var = value; - var += "="; + std::string var = cmStrCat(value, '='); return cmSystemTools::PutEnv(var.c_str()); # else unsetenv(value); @@ -1430,7 +1234,7 @@ void cmSystemTools::EnableVSConsoleOutput() // output and allow it to be captured on the fly. cmSystemTools::PutEnv("vsconsoleoutput=1"); -# ifdef CMAKE_BUILD_WITH_CMAKE +# ifndef CMAKE_BOOTSTRAP // VS sets an environment variable to tell MS tools like "cl" to report // output through a backdoor pipe instead of stdout/stderr. Unset the // environment variable to close this backdoor for any path of process @@ -1452,14 +1256,12 @@ bool cmSystemTools::CreateTar(const std::string& outFileName, std::string const& mtime, std::string const& format) { -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) std::string cwd = cmSystemTools::GetCurrentWorkingDirectory(); cmsys::ofstream fout(outFileName.c_str(), std::ios::out | std::ios::binary); if (!fout) { - std::string e = "Cannot open output file \""; - e += outFileName; - e += "\": "; - e += cmSystemTools::GetLastSystemError(); + std::string e = cmStrCat("Cannot open output file \"", outFileName, + "\": ", cmSystemTools::GetLastSystemError()); cmSystemTools::Error(e); return false; } @@ -1506,7 +1308,7 @@ bool cmSystemTools::CreateTar(const std::string& outFileName, #endif } -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) namespace { # define BSDTAR_FILESIZE_PRINTF "%lu" # define BSDTAR_FILESIZE_TYPE unsigned long @@ -1802,7 +1604,7 @@ bool cmSystemTools::ExtractTar(const std::string& outFileName, const std::vector<std::string>& files, bool verbose) { -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) return extract_tar(outFileName, files, verbose, true); #else (void)outFileName; @@ -1816,7 +1618,7 @@ bool cmSystemTools::ListTar(const std::string& outFileName, const std::vector<std::string>& files, bool verbose) { -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) return extract_tar(outFileName, files, verbose, false); #else (void)outFileName; @@ -2142,40 +1944,34 @@ void cmSystemTools::FindCMakeResources(const char* argv0) } #endif exe_dir = cmSystemTools::GetActualCaseForPath(exe_dir); - cmSystemToolsCMakeCommand = exe_dir; - cmSystemToolsCMakeCommand += "/cmake"; - cmSystemToolsCMakeCommand += cmSystemTools::GetExecutableExtension(); -#ifndef CMAKE_BUILD_WITH_CMAKE + cmSystemToolsCMakeCommand = + cmStrCat(exe_dir, "/cmake", cmSystemTools::GetExecutableExtension()); +#ifdef CMAKE_BOOTSTRAP // The bootstrap cmake does not provide the other tools, // so use the directory where they are about to be built. exe_dir = CMAKE_BOOTSTRAP_BINARY_DIR "/bin"; #endif - cmSystemToolsCTestCommand = exe_dir; - cmSystemToolsCTestCommand += "/ctest"; - cmSystemToolsCTestCommand += cmSystemTools::GetExecutableExtension(); - cmSystemToolsCPackCommand = exe_dir; - cmSystemToolsCPackCommand += "/cpack"; - cmSystemToolsCPackCommand += cmSystemTools::GetExecutableExtension(); - cmSystemToolsCMakeGUICommand = exe_dir; - cmSystemToolsCMakeGUICommand += "/cmake-gui"; - cmSystemToolsCMakeGUICommand += cmSystemTools::GetExecutableExtension(); + cmSystemToolsCTestCommand = + cmStrCat(exe_dir, "/ctest", cmSystemTools::GetExecutableExtension()); + cmSystemToolsCPackCommand = + cmStrCat(exe_dir, "/cpack", cmSystemTools::GetExecutableExtension()); + cmSystemToolsCMakeGUICommand = + cmStrCat(exe_dir, "/cmake-gui", cmSystemTools::GetExecutableExtension()); if (!cmSystemTools::FileExists(cmSystemToolsCMakeGUICommand)) { cmSystemToolsCMakeGUICommand.clear(); } - cmSystemToolsCMakeCursesCommand = exe_dir; - cmSystemToolsCMakeCursesCommand += "/ccmake"; - cmSystemToolsCMakeCursesCommand += cmSystemTools::GetExecutableExtension(); + cmSystemToolsCMakeCursesCommand = + cmStrCat(exe_dir, "/ccmake", cmSystemTools::GetExecutableExtension()); if (!cmSystemTools::FileExists(cmSystemToolsCMakeCursesCommand)) { cmSystemToolsCMakeCursesCommand.clear(); } - cmSystemToolsCMClDepsCommand = exe_dir; - cmSystemToolsCMClDepsCommand += "/cmcldeps"; - cmSystemToolsCMClDepsCommand += cmSystemTools::GetExecutableExtension(); + cmSystemToolsCMClDepsCommand = + cmStrCat(exe_dir, "/cmcldeps", cmSystemTools::GetExecutableExtension()); if (!cmSystemTools::FileExists(cmSystemToolsCMClDepsCommand)) { cmSystemToolsCMClDepsCommand.clear(); } -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP // Install tree has // - "<prefix><CMAKE_BIN_DIR>/cmake" // - "<prefix><CMAKE_DATA_DIR>" @@ -2408,8 +2204,9 @@ bool cmSystemTools::ChangeRPath(std::string const& file, return true; } if (emsg) { - *emsg = "No valid ELF RPATH or RUNPATH entry exists in the file; "; - *emsg += elf.GetErrorMessage(); + *emsg = + cmStrCat("No valid ELF RPATH or RUNPATH entry exists in the file; ", + elf.GetErrorMessage()); } return false; } @@ -2475,9 +2272,8 @@ bool cmSystemTools::ChangeRPath(std::string const& file, // least one null terminator. if (rp[rp_count].Size < rp[rp_count].Value.length() + 1) { if (emsg) { - *emsg = "The replacement path is too long for the "; - *emsg += se_name[i]; - *emsg += " entry."; + *emsg = cmStrCat("The replacement path is too long for the ", + se_name[i], " entry."); } return false; } @@ -2513,9 +2309,7 @@ bool cmSystemTools::ChangeRPath(std::string const& file, // Seek to the RPATH position. if (!f.seekp(rp[i].Position)) { if (emsg) { - *emsg = "Error seeking to "; - *emsg += rp[i].Name; - *emsg += " position."; + *emsg = cmStrCat("Error seeking to ", rp[i].Name, " position."); } return false; } @@ -2530,9 +2324,8 @@ bool cmSystemTools::ChangeRPath(std::string const& file, // Make sure it wrote correctly. if (!f) { if (emsg) { - *emsg = "Error writing the new "; - *emsg += rp[i].Name; - *emsg += " string to the file."; + *emsg = cmStrCat("Error writing the new ", rp[i].Name, + " string to the file."); } return false; } @@ -2561,7 +2354,8 @@ bool cmSystemTools::VersionCompare(cmSystemTools::CompareOp op, { const char* endl = lhss; const char* endr = rhss; - unsigned long lhs, rhs; + unsigned long lhs; + unsigned long rhs; while (((*endl >= '0') && (*endl <= '9')) || ((*endr >= '0') && (*endr <= '9'))) { @@ -2872,61 +2666,20 @@ bool cmSystemTools::CheckRPath(std::string const& file, bool cmSystemTools::RepeatedRemoveDirectory(const std::string& dir) { +#ifdef _WIN32 // Windows sometimes locks files temporarily so try a few times. - for (int i = 0; i < 10; ++i) { + WindowsFileRetry retry = cmSystemTools::GetWindowsFileRetry(); + + for (unsigned int i = 0; i < retry.Count; ++i) { if (cmSystemTools::RemoveADirectory(dir)) { return true; } - cmSystemTools::Delay(100); + cmSystemTools::Delay(retry.Delay); } return false; -} - -std::vector<std::string> cmSystemTools::tokenize(const std::string& str, - const std::string& sep) -{ - std::vector<std::string> tokens; - std::string::size_type tokend = 0; - - do { - std::string::size_type tokstart = str.find_first_not_of(sep, tokend); - if (tokstart == std::string::npos) { - break; // no more tokens - } - tokend = str.find_first_of(sep, tokstart); - if (tokend == std::string::npos) { - tokens.push_back(str.substr(tokstart)); - } else { - tokens.push_back(str.substr(tokstart, tokend - tokstart)); - } - } while (tokend != std::string::npos); - - if (tokens.empty()) { - tokens.emplace_back(); - } - return tokens; -} - -bool cmSystemTools::StringToLong(const char* str, long* value) -{ - errno = 0; - char* endp; - *value = strtol(str, &endp, 10); - return (*endp == '\0') && (endp != str) && (errno == 0); -} - -bool cmSystemTools::StringToULong(const char* str, unsigned long* value) -{ - errno = 0; - char* endp; - while (isspace(*str)) { - ++str; - } - if (*str == '-') { - return false; - } - *value = strtoul(str, &endp, 10); - return (*endp == '\0') && (endp != str) && (errno == 0); +#else + return cmSystemTools::RemoveADirectory(dir); +#endif } std::string cmSystemTools::EncodeURL(std::string const& in, bool escapeSlashes) diff --git a/Source/cmSystemTools.h b/Source/cmSystemTools.h index ac1aa80..953a358 100644 --- a/Source/cmSystemTools.h +++ b/Source/cmSystemTools.h @@ -29,65 +29,14 @@ public: typedef cmProcessOutput::Encoding Encoding; /** - * Expand the ; separated string @a arg into multiple arguments. - * All found arguments are appended to @a argsOut. - */ - static void ExpandListArgument(cm::string_view arg, - std::vector<std::string>& argsOut, - bool emptyArgs = false); - - /** - * Expand out any arguments in the string range [@a first, @a last) that have - * ; separated strings into multiple arguments. All found arguments are - * appended to @a argsOut. - */ - template <class InputIt> - static void ExpandLists(InputIt first, InputIt last, - std::vector<std::string>& argsOut) - { - for (; first != last; ++first) { - cmSystemTools::ExpandListArgument(*first, argsOut); - } - } - - /** - * Same as ExpandListArgument but a new vector is created containing - * the expanded arguments from the string @a arg. - */ - static std::vector<std::string> ExpandedListArgument(cm::string_view arg, - bool emptyArgs = false); - - /** - * Same as ExpandList but a new vector is created containing the expanded - * versions of all arguments in the string range [@a first, @a last). - */ - template <class InputIt> - static std::vector<std::string> ExpandedLists(InputIt first, InputIt last) - { - std::vector<std::string> argsOut; - for (; first != last; ++first) { - cmSystemTools::ExpandListArgument(*first, argsOut); - } - return argsOut; - } - - /** * Look for and replace registry values in a string */ static void ExpandRegistryValues(std::string& source, KeyWOW64 view = KeyWOW64_Default); - //! Escape quotes in a string. - static std::string EscapeQuotes(cm::string_view str); - /** Map help document name to file name. */ static std::string HelpFileName(cm::string_view); - /** - * Returns a string that has whitespace removed from the start and the end. - */ - static std::string TrimWhitespace(cm::string_view str); - using MessageCallback = std::function<void(const std::string&, const char*)>; /** * Set the function used by GUIs to display error messages @@ -145,50 +94,6 @@ public: cmSystemTools::s_ErrorOccured = false; } - /** - * Does a string indicates that CMake/CPack/CTest internally - * forced this value. This is not the same as On, but this - * may be considered as "internally switched on". - */ - static bool IsInternallyOn(cm::string_view val); - static inline bool IsInternallyOn(const char* val) - { - if (!val) { - return false; - } - return IsInternallyOn(cm::string_view(val)); - } - - /** - * Does a string indicate a true or on value? This is not the same as ifdef. - */ - static bool IsOn(cm::string_view val); - inline static bool IsOn(const char* val) - { - if (!val) { - return false; - } - return IsOn(cm::string_view(val)); - } - - /** - * Does a string indicate a false or off value ? Note that this is - * not the same as !IsOn(...) because there are a number of - * ambiguous values such as "/usr/local/bin" a path will result in - * IsON and IsOff both returning false. Note that the special path - * NOTFOUND, *-NOTFOUND or IGNORE will cause IsOff to return true. - */ - static bool IsOff(cm::string_view val); - inline static bool IsOff(const char* val) - { - if (!val) { - return true; - } - return IsOff(cm::string_view(val)); - } - - //! Return true if value is NOTFOUND or ends in -NOTFOUND. - static bool IsNOTFOUND(cm::string_view val); //! Return true if the path is a framework static bool IsPathToFramework(const std::string& value); @@ -395,7 +300,7 @@ public: static std::string ForceToRelativePath(std::string const& local_path, std::string const& remote_path); -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP /** Remove an environment variable */ static bool UnsetEnv(const char* value); @@ -508,14 +413,6 @@ public: /** Remove a directory; repeat a few times in case of locked files. */ static bool RepeatedRemoveDirectory(const std::string& dir); - /** Tokenize a string */ - static std::vector<std::string> tokenize(const std::string& str, - const std::string& sep); - - /** Convert string to long. Expected that the whole string is an integer */ - static bool StringToLong(const char* str, long* value); - static bool StringToULong(const char* str, unsigned long* value); - /** Encode a string as a URL. */ static std::string EncodeURL(std::string const& in, bool escapeSlashes = true); diff --git a/Source/cmTarget.cxx b/Source/cmTarget.cxx index beccfce..bc1b9de 100644 --- a/Source/cmTarget.cxx +++ b/Source/cmTarget.cxx @@ -89,7 +89,7 @@ const char* cmTargetPropertyComputer::GetSources<cmTarget>( const char* sep = ""; for (std::string const& entry : entries) { std::vector<std::string> files; - cmSystemTools::ExpandListArgument(entry, files); + cmExpandList(entry, files); for (std::string const& file : files) { if (cmHasLiteralPrefix(file, "$<TARGET_OBJECTS:") && file.back() == '>') { @@ -180,6 +180,7 @@ public: std::vector<cmCustomCommand> PreBuildCommands; std::vector<cmCustomCommand> PreLinkCommands; std::vector<cmCustomCommand> PostBuildCommands; + std::vector<cmInstallTargetGenerator*> InstallGenerators; std::set<std::string> SystemIncludeDirectories; cmTarget::LinkLibraryVectorType OriginalLinkLibraries; std::vector<std::string> IncludeDirectoriesEntries; @@ -342,6 +343,7 @@ cmTarget::cmTarget(std::string const& name, cmStateEnums::TargetType type, initProp("CUDA_EXTENSIONS"); initProp("CUDA_COMPILER_LAUNCHER"); initProp("CUDA_SEPARABLE_COMPILATION"); + initProp("CUDA_RESOLVE_DEVICE_SYMBOLS"); initProp("LINK_SEARCH_START_STATIC"); initProp("LINK_SEARCH_END_STATIC"); initProp("FOLDER"); @@ -390,8 +392,7 @@ cmTarget::cmTarget(std::string const& name, cmStateEnums::TargetType type, strcmp(prop, "MAP_IMPORTED_CONFIG_") != 0) { continue; } - std::string property = prop; - property += configUpper; + std::string property = cmStrCat(prop, configUpper); initProp(property); } @@ -402,8 +403,8 @@ cmTarget::cmTarget(std::string const& name, cmStateEnums::TargetType type, // property directly. if (impl->TargetType != cmStateEnums::EXECUTABLE && impl->TargetType != cmStateEnums::INTERFACE_LIBRARY) { - std::string property = cmSystemTools::UpperCase(configName); - property += "_POSTFIX"; + std::string property = + cmStrCat(cmSystemTools::UpperCase(configName), "_POSTFIX"); initProp(property); } } @@ -499,7 +500,7 @@ cmTarget::cmTarget(std::string const& name, cmStateEnums::TargetType type, const std::string genName = mf->GetGlobalGenerator()->GetName(); if (cmHasLiteralPrefix(genName, "Visual Studio")) { std::vector<std::string> props; - cmSystemTools::ExpandListArgument(globals, props); + cmExpandList(globals, props); const std::string vsGlobal = "VS_GLOBAL_"; for (const std::string& i : props) { // split NAME=VALUE @@ -742,7 +743,7 @@ public: bool operator()(std::string const& entry) { std::vector<std::string> files; - cmSystemTools::ExpandListArgument(entry, files); + cmExpandList(entry, files); std::vector<cmSourceFileLocation> locations; locations.reserve(files.size()); std::transform(files.begin(), files.end(), std::back_inserter(locations), @@ -776,8 +777,7 @@ cmSourceFile* cmTarget::AddSource(const std::string& src, bool before) void cmTarget::ClearDependencyInformation(cmMakefile& mf) { - std::string depname = this->GetName(); - depname += "_LIB_DEPENDS"; + std::string depname = cmStrCat(this->GetName(), "_LIB_DEPENDS"); mf.RemoveCacheDefinition(depname); } @@ -873,6 +873,17 @@ void cmTarget::SetHaveInstallRule(bool hir) impl->HaveInstallRule = hir; } +void cmTarget::AddInstallGenerator(cmInstallTargetGenerator* g) +{ + impl->InstallGenerators.emplace_back(g); +} + +std::vector<cmInstallTargetGenerator*> const& cmTarget::GetInstallGenerators() + const +{ + return impl->InstallGenerators; +} + bool cmTarget::GetIsGeneratorProvided() const { return impl->IsGeneratorProvided; @@ -934,8 +945,7 @@ void cmTarget::AddLinkLibrary(cmMakefile& mf, std::string const& lib, impl->TargetType <= cmStateEnums::MODULE_LIBRARY && (this->GetPolicyStatusCMP0073() == cmPolicies::OLD || this->GetPolicyStatusCMP0073() == cmPolicies::WARN)) { - std::string targetEntry = impl->Name; - targetEntry += "_LIB_DEPENDS"; + std::string targetEntry = cmStrCat(impl->Name, "_LIB_DEPENDS"); std::string dependencies; const char* old_val = mf.GetDefinition(targetEntry); if (old_val) { @@ -1178,7 +1188,7 @@ void cmTarget::SetProperty(const std::string& prop, const char* value) impl->SourceBacktraces.push_back(lfbt); } } else if (prop == propIMPORTED_GLOBAL) { - if (!cmSystemTools::IsOn(value)) { + if (!cmIsOn(value)) { std::ostringstream e; e << "IMPORTED_GLOBAL property can't be set to FALSE on targets (\"" << impl->Name << "\")\n"; @@ -1658,7 +1668,7 @@ const char* cmTarget::GetSafeProperty(const std::string& prop) const bool cmTarget::GetPropertyAsBool(const std::string& prop) const { - return cmSystemTools::IsOn(this->GetProperty(prop)); + return cmIsOn(this->GetProperty(prop)); } cmPropertyMap const& cmTarget::GetProperties() const @@ -1793,8 +1803,7 @@ std::string cmTarget::ImportedGetFullPath( if (loc) { result = loc; } else { - std::string impProp = "IMPORTED_LOCATION"; - impProp += suffix; + std::string impProp = cmStrCat("IMPORTED_LOCATION", suffix); if (const char* config_location = this->GetProperty(impProp)) { result = config_location; } else if (const char* location = @@ -1809,8 +1818,7 @@ std::string cmTarget::ImportedGetFullPath( result = imp; } else if (this->GetType() == cmStateEnums::SHARED_LIBRARY || this->IsExecutableWithExports()) { - std::string impProp = "IMPORTED_IMPLIB"; - impProp += suffix; + std::string impProp = cmStrCat("IMPORTED_IMPLIB", suffix); if (const char* config_implib = this->GetProperty(impProp)) { result = config_implib; } else if (const char* implib = @@ -1823,8 +1831,7 @@ std::string cmTarget::ImportedGetFullPath( } if (result.empty()) { - result = this->GetName(); - result += "-NOTFOUND"; + result = cmStrCat(this->GetName(), "-NOTFOUND"); } return result; } @@ -1878,15 +1885,13 @@ bool cmTarget::GetMappedConfig(std::string const& desired_config, } // Track the configuration-specific property suffix. - suffix = "_"; - suffix += config_upper; + suffix = cmStrCat('_', config_upper); std::vector<std::string> mappedConfigs; { - std::string mapProp = "MAP_IMPORTED_CONFIG_"; - mapProp += config_upper; + std::string mapProp = cmStrCat("MAP_IMPORTED_CONFIG_", config_upper); if (const char* mapValue = this->GetProperty(mapProp)) { - cmSystemTools::ExpandListArgument(mapValue, mappedConfigs, true); + cmExpandList(mapValue, mappedConfigs, true); } } @@ -1915,19 +1920,16 @@ bool cmTarget::GetMappedConfig(std::string const& desired_config, } } else { std::string mcUpper = cmSystemTools::UpperCase(*mci); - std::string locProp = locPropBase + "_"; - locProp += mcUpper; + std::string locProp = cmStrCat(locPropBase, '_', mcUpper); *loc = this->GetProperty(locProp); if (allowImp) { - std::string impProp = "IMPORTED_IMPLIB_"; - impProp += mcUpper; + std::string impProp = cmStrCat("IMPORTED_IMPLIB_", mcUpper); *imp = this->GetProperty(impProp); } // If it was found, use it for all properties below. if (*loc || *imp) { - suffix = "_"; - suffix += mcUpper; + suffix = cmStrCat('_', mcUpper); } } } @@ -1944,12 +1946,10 @@ bool cmTarget::GetMappedConfig(std::string const& desired_config, // If we have not yet found it then there are no mapped // configurations. Look for an exact-match. if (!*loc && !*imp) { - std::string locProp = locPropBase; - locProp += suffix; + std::string locProp = cmStrCat(locPropBase, suffix); *loc = this->GetProperty(locProp); if (allowImp) { - std::string impProp = "IMPORTED_IMPLIB"; - impProp += suffix; + std::string impProp = cmStrCat("IMPORTED_IMPLIB", suffix); *imp = this->GetProperty(impProp); } } @@ -1973,19 +1973,16 @@ bool cmTarget::GetMappedConfig(std::string const& desired_config, if (!*loc && !*imp) { std::vector<std::string> availableConfigs; if (const char* iconfigs = this->GetProperty("IMPORTED_CONFIGURATIONS")) { - cmSystemTools::ExpandListArgument(iconfigs, availableConfigs); + cmExpandList(iconfigs, availableConfigs); } for (std::vector<std::string>::const_iterator aci = availableConfigs.begin(); !*loc && !*imp && aci != availableConfigs.end(); ++aci) { - suffix = "_"; - suffix += cmSystemTools::UpperCase(*aci); - std::string locProp = locPropBase; - locProp += suffix; + suffix = cmStrCat('_', cmSystemTools::UpperCase(*aci)); + std::string locProp = cmStrCat(locPropBase, suffix); *loc = this->GetProperty(locProp); if (allowImp) { - std::string impProp = "IMPORTED_IMPLIB"; - impProp += suffix; + std::string impProp = cmStrCat("IMPORTED_IMPLIB", suffix); *imp = this->GetProperty(impProp); } } diff --git a/Source/cmTarget.h b/Source/cmTarget.h index 4e5141b..2b75879 100644 --- a/Source/cmTarget.h +++ b/Source/cmTarget.h @@ -21,6 +21,7 @@ class cmCustomCommand; class cmGlobalGenerator; +class cmInstallTargetGenerator; class cmMakefile; class cmMessenger; class cmPropertyMap; @@ -147,6 +148,9 @@ public: bool GetHaveInstallRule() const; void SetHaveInstallRule(bool hir); + void AddInstallGenerator(cmInstallTargetGenerator* g); + std::vector<cmInstallTargetGenerator*> const& GetInstallGenerators() const; + /** * Get/Set whether this target was auto-created by a generator. */ diff --git a/Source/cmTargetIncludeDirectoriesCommand.cxx b/Source/cmTargetIncludeDirectoriesCommand.cxx index d6918c0..d099349 100644 --- a/Source/cmTargetIncludeDirectoriesCommand.cxx +++ b/Source/cmTargetIncludeDirectoriesCommand.cxx @@ -9,6 +9,7 @@ #include "cmListFileCache.h" #include "cmMakefile.h" #include "cmMessageType.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmTarget.h" @@ -39,9 +40,9 @@ std::string cmTargetIncludeDirectoriesCommand::Join( for (std::string const& it : content) { if (cmSystemTools::FileIsFullPath(it) || cmGeneratorExpression::Find(it) == 0) { - dirs += sep + it; + dirs += cmStrCat(sep, it); } else { - dirs += sep + prefix + it; + dirs += cmStrCat(sep, prefix, it); } sep = ";"; } diff --git a/Source/cmTargetLinkLibrariesCommand.cxx b/Source/cmTargetLinkLibrariesCommand.cxx index 3883b52..4fbec90 100644 --- a/Source/cmTargetLinkLibrariesCommand.cxx +++ b/Source/cmTargetLinkLibrariesCommand.cxx @@ -12,6 +12,7 @@ #include "cmPolicies.h" #include "cmState.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmTarget.h" #include "cmake.h" @@ -237,8 +238,7 @@ bool cmTargetLinkLibrariesCommand::InitialPass( // only there for backwards compatibility when mixing projects built // with old versions of CMake and new) llt = GENERAL_LibraryType; - std::string linkType = args[0]; - linkType += "_LINK_TYPE"; + std::string linkType = cmStrCat(args[0], "_LINK_TYPE"); const char* linkTypeString = this->Makefile->GetDefinition(linkType); if (linkTypeString) { if (strcmp(linkTypeString, "debug") == 0) { @@ -502,8 +502,7 @@ bool cmTargetLinkLibrariesCommand::HandleLibrary(const std::string& lib, if (llt == DEBUG_LibraryType || llt == GENERAL_LibraryType) { // Put in the DEBUG configuration interfaces. for (std::string const& dc : debugConfigs) { - prop = "LINK_INTERFACE_LIBRARIES_"; - prop += dc; + prop = cmStrCat("LINK_INTERFACE_LIBRARIES_", dc); this->Target->AppendProperty(prop, libRef.c_str()); } } @@ -514,8 +513,7 @@ bool cmTargetLinkLibrariesCommand::HandleLibrary(const std::string& lib, // Make sure the DEBUG configuration interfaces exist so that the // general one will not be used as a fall-back. for (std::string const& dc : debugConfigs) { - prop = "LINK_INTERFACE_LIBRARIES_"; - prop += dc; + prop = cmStrCat("LINK_INTERFACE_LIBRARIES_", dc); if (!this->Target->GetProperty(prop)) { this->Target->SetProperty(prop, ""); } diff --git a/Source/cmTargetSourcesCommand.cxx b/Source/cmTargetSourcesCommand.cxx index eb5f37c..2251a65 100644 --- a/Source/cmTargetSourcesCommand.cxx +++ b/Source/cmTargetSourcesCommand.cxx @@ -75,9 +75,8 @@ std::vector<std::string> cmTargetSourcesCommand::ConvertToAbsoluteContent( absoluteSrc = src; } else { changedPath = true; - absoluteSrc = this->Makefile->GetCurrentSourceDirectory(); - absoluteSrc += "/"; - absoluteSrc += src; + absoluteSrc = + cmStrCat(this->Makefile->GetCurrentSourceDirectory(), '/', src); } absoluteContent.push_back(absoluteSrc); } diff --git a/Source/cmTest.cxx b/Source/cmTest.cxx index 01f2b96..d5c61c1 100644 --- a/Source/cmTest.cxx +++ b/Source/cmTest.cxx @@ -5,7 +5,7 @@ #include "cmMakefile.h" #include "cmProperty.h" #include "cmState.h" -#include "cmSystemTools.h" +#include "cmStringAlgorithms.h" cmTest::cmTest(cmMakefile* mf) : CommandExpandLists(false) @@ -47,7 +47,7 @@ const char* cmTest::GetProperty(const std::string& prop) const bool cmTest::GetPropertyAsBool(const std::string& prop) const { - return cmSystemTools::IsOn(this->GetProperty(prop)); + return cmIsOn(this->GetProperty(prop)); } void cmTest::SetProperty(const std::string& prop, const char* value) diff --git a/Source/cmTestGenerator.cxx b/Source/cmTestGenerator.cxx index 916784c..75cb413 100644 --- a/Source/cmTestGenerator.cxx +++ b/Source/cmTestGenerator.cxx @@ -15,6 +15,7 @@ #include "cmPropertyMap.h" #include "cmRange.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmTest.h" @@ -83,7 +84,7 @@ void cmTestGenerator::GenerateScriptForConfig(std::ostream& os, // Expand arguments if COMMAND_EXPAND_LISTS is set if (this->Test->GetCommandExpandLists()) { - argv = cmSystemTools::ExpandedLists(argv.begin(), argv.end()); + argv = cmExpandedLists(argv.begin(), argv.end()); // Expanding lists on an empty command may have left it empty if (argv.empty()) { argv.emplace_back(); @@ -102,7 +103,7 @@ void cmTestGenerator::GenerateScriptForConfig(std::ostream& os, const char* emulator = target->GetProperty("CROSSCOMPILING_EMULATOR"); if (emulator != nullptr && *emulator) { std::vector<std::string> emulatorWithArgs; - cmSystemTools::ExpandListArgument(emulator, emulatorWithArgs); + cmExpandList(emulator, emulatorWithArgs); std::string emulatorExe(emulatorWithArgs[0]); cmSystemTools::ConvertToUnixSlashes(emulatorExe); os << cmOutputConverter::EscapeForCMake(emulatorExe) << " "; diff --git a/Source/cmTimestamp.cxx b/Source/cmTimestamp.cxx index da5d21e..9e32226 100644 --- a/Source/cmTimestamp.cxx +++ b/Source/cmTimestamp.cxx @@ -6,6 +6,7 @@ #include <sstream> #include <stdlib.h> +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" std::string cmTimestamp::CurrentTime(const std::string& formatString, @@ -109,7 +110,7 @@ time_t cmTimestamp::CreateUtcTimeTFromTm(struct tm& tm) const time_t result = mktime(&tm); -# ifdef CMAKE_BUILD_WITH_CMAKE +# ifndef CMAKE_BOOTSTRAP if (tz_was_set) { cmSystemTools::PutEnv(tz_old); } else { @@ -131,8 +132,7 @@ std::string cmTimestamp::AddTimestampComponent(char flag, struct tm& timeStruct, const time_t timeT) const { - std::string formatString = "%"; - formatString += flag; + std::string formatString = cmStrCat('%', flag); switch (flag) { case 'a': diff --git a/Source/cmTryRunCommand.cxx b/Source/cmTryRunCommand.cxx index ed944ac..1c892c7 100644 --- a/Source/cmTryRunCommand.cxx +++ b/Source/cmTryRunCommand.cxx @@ -11,6 +11,7 @@ #include "cmRange.h" #include "cmState.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmake.h" @@ -170,7 +171,7 @@ void cmTryRunCommand::RunExecutable(const std::string& runArgs, this->Makefile->GetSafeDefinition("CMAKE_CROSSCOMPILING_EMULATOR"); if (!emulator.empty()) { std::vector<std::string> emulatorWithArgs; - cmSystemTools::ExpandListArgument(emulator, emulatorWithArgs); + cmExpandList(emulator, emulatorWithArgs); finalCommand += cmSystemTools::ConvertToRunCommandPath(emulatorWithArgs[0]); finalCommand += " "; @@ -213,20 +214,17 @@ void cmTryRunCommand::DoNotRunExecutable(const std::string& runArgs, // copy the executable out of the CMakeFiles/ directory, so it is not // removed at the end of TRY_RUN and the user can run it manually // on the target platform. - std::string copyDest = this->Makefile->GetHomeOutputDirectory(); - copyDest += "/CMakeFiles"; - copyDest += "/"; - copyDest += cmSystemTools::GetFilenameWithoutExtension(this->OutputFile); - copyDest += "-"; - copyDest += this->RunResultVariable; - copyDest += cmSystemTools::GetFilenameExtension(this->OutputFile); + std::string copyDest = + cmStrCat(this->Makefile->GetHomeOutputDirectory(), "/CMakeFiles/", + cmSystemTools::GetFilenameWithoutExtension(this->OutputFile), '-', + this->RunResultVariable, + cmSystemTools::GetFilenameExtension(this->OutputFile)); cmSystemTools::CopyFileAlways(this->OutputFile, copyDest); - std::string resultFileName = this->Makefile->GetHomeOutputDirectory(); - resultFileName += "/TryRunResults.cmake"; + std::string resultFileName = + cmStrCat(this->Makefile->GetHomeOutputDirectory(), "/TryRunResults.cmake"); - std::string detailsString = "For details see "; - detailsString += resultFileName; + std::string detailsString = cmStrCat("For details see ", resultFileName); std::string internalRunOutputName = this->RunResultVariable + "__TRYRUN_OUTPUT"; @@ -235,10 +233,10 @@ void cmTryRunCommand::DoNotRunExecutable(const std::string& runArgs, if (!this->Makefile->GetDefinition(this->RunResultVariable)) { // if the variables doesn't exist, create it with a helpful error text // and mark it as advanced - std::string comment; - comment += "Run result of TRY_RUN(), indicates whether the executable " - "would have been able to run on its target platform.\n"; - comment += detailsString; + std::string comment = + cmStrCat("Run result of TRY_RUN(), indicates whether the executable " + "would have been able to run on its target platform.\n", + detailsString); this->Makefile->AddCacheDefinition(this->RunResultVariable, "PLEASE_FILL_OUT-FAILED_TO_RUN", comment.c_str(), cmStateEnums::STRING); @@ -258,11 +256,10 @@ void cmTryRunCommand::DoNotRunExecutable(const std::string& runArgs, if (!this->Makefile->GetDefinition(internalRunOutputName)) { // if the variables doesn't exist, create it with a helpful error text // and mark it as advanced - std::string comment; - comment += + std::string comment = cmStrCat( "Output of TRY_RUN(), contains the text, which the executable " - "would have printed on stdout and stderr on its target platform.\n"; - comment += detailsString; + "would have printed on stdout and stderr on its target platform.\n", + detailsString); this->Makefile->AddCacheDefinition( internalRunOutputName, "PLEASE_FILL_OUT-NOTFOUND", comment.c_str(), @@ -294,15 +291,15 @@ void cmTryRunCommand::DoNotRunExecutable(const std::string& runArgs, /* clang-format on */ } - std::string comment = "\n"; - comment += this->RunResultVariable; - comment += "\n indicates whether the executable would have been able " + std::string comment = + cmStrCat('\n', this->RunResultVariable, + "\n indicates whether the executable would have been able " "to run on its\n" - " target platform. If so, set "; - comment += this->RunResultVariable; - comment += " to\n" + " target platform. If so, set ", + this->RunResultVariable, + " to\n" " the exit code (in many cases 0 for success), otherwise " - "enter \"FAILED_TO_RUN\".\n"; + "enter \"FAILED_TO_RUN\".\n"); if (out) { comment += internalRunOutputName; comment += @@ -343,10 +340,11 @@ void cmTryRunCommand::DoNotRunExecutable(const std::string& runArgs, } firstTryRun = false; - std::string errorMessage = "TRY_RUN() invoked in cross-compiling mode, " - "please set the following cache variables " - "appropriately:\n"; - errorMessage += " " + this->RunResultVariable + " (advanced)\n"; + std::string errorMessage = + cmStrCat("TRY_RUN() invoked in cross-compiling mode, " + "please set the following cache variables " + "appropriately:\n ", + this->RunResultVariable, " (advanced)\n"); if (out) { errorMessage += " " + internalRunOutputName + " (advanced)\n"; } diff --git a/Source/cmUVHandlePtr.cxx b/Source/cmUVHandlePtr.cxx index db67463..97c27cb 100644 --- a/Source/cmUVHandlePtr.cxx +++ b/Source/cmUVHandlePtr.cxx @@ -122,7 +122,7 @@ uv_handle_ptr_<T>::operator T*() const return this->handle.get(); } -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP template <> struct uv_handle_deleter<uv_async_t> { @@ -230,7 +230,7 @@ int uv_timer_ptr::start(uv_timer_cb cb, uint64_t timeout, uint64_t repeat) return uv_timer_start(*this, cb, timeout, repeat); } -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP uv_tty_ptr::operator uv_stream_t*() const { return reinterpret_cast<uv_stream_t*>(handle.get()); @@ -259,7 +259,7 @@ UV_HANDLE_PTR_INSTANTIATE_EXPLICIT(process) UV_HANDLE_PTR_INSTANTIATE_EXPLICIT(timer) -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP UV_HANDLE_PTR_INSTANTIATE_EXPLICIT(async) UV_HANDLE_PTR_INSTANTIATE_EXPLICIT(tty) diff --git a/Source/cmUnsetCommand.cxx b/Source/cmUnsetCommand.cxx index 0e903c7..3ba95e9 100644 --- a/Source/cmUnsetCommand.cxx +++ b/Source/cmUnsetCommand.cxx @@ -2,18 +2,17 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmUnsetCommand.h" +#include "cmExecutionStatus.h" #include "cmMakefile.h" #include "cmStringAlgorithms.h" #include "cmSystemTools.h" -class cmExecutionStatus; - // cmUnsetCommand -bool cmUnsetCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus&) +bool cmUnsetCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.empty() || args.size() > 2) { - this->SetError("called with incorrect number of arguments"); + status.SetError("called with incorrect number of arguments"); return false; } @@ -24,27 +23,27 @@ bool cmUnsetCommand::InitialPass(std::vector<std::string> const& args, // what is the variable name auto const& envVarName = variable.substr(4, variable.size() - 5); -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP cmSystemTools::UnsetEnv(envVarName.c_str()); #endif return true; } // unset(VAR) if (args.size() == 1) { - this->Makefile->RemoveDefinition(variable); + status.GetMakefile().RemoveDefinition(variable); return true; } // unset(VAR CACHE) if ((args.size() == 2) && (args[1] == "CACHE")) { - this->Makefile->RemoveCacheDefinition(variable); + status.GetMakefile().RemoveCacheDefinition(variable); return true; } // unset(VAR PARENT_SCOPE) if ((args.size() == 2) && (args[1] == "PARENT_SCOPE")) { - this->Makefile->RaiseScope(variable, nullptr); + status.GetMakefile().RaiseScope(variable, nullptr); return true; } // ERROR: second argument isn't CACHE or PARENT_SCOPE - this->SetError("called with an invalid second argument"); + status.SetError("called with an invalid second argument"); return false; } diff --git a/Source/cmUnsetCommand.h b/Source/cmUnsetCommand.h index 9b78d44..be4c166 100644 --- a/Source/cmUnsetCommand.h +++ b/Source/cmUnsetCommand.h @@ -8,34 +8,14 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -/** \class cmUnsetCommand +/** * \brief Unset a CMAKE variable * * cmUnsetCommand unsets or removes a variable. */ -class cmUnsetCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmUnsetCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; -}; +bool cmUnsetCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmUseMangledMesaCommand.cxx b/Source/cmUseMangledMesaCommand.cxx index 4358194..3d83760 100644 --- a/Source/cmUseMangledMesaCommand.cxx +++ b/Source/cmUseMangledMesaCommand.cxx @@ -5,6 +5,7 @@ #include "cmsys/FStream.hxx" #include "cmsys/RegularExpression.hxx" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" class cmExecutionStatus; @@ -20,13 +21,9 @@ bool cmUseMangledMesaCommand::InitialPass(std::vector<std::string> const& args, return false; } const std::string& inputDir = args[0]; - std::string glh = inputDir; - glh += "/"; - glh += "gl.h"; + std::string glh = cmStrCat(inputDir, "/gl.h"); if (!cmSystemTools::FileExists(glh)) { - std::string e = "Bad path to Mesa, could not find: "; - e += glh; - e += " "; + std::string e = cmStrCat("Bad path to Mesa, could not find: ", glh, ' '); this->SetError(e); return false; } @@ -39,9 +36,7 @@ bool cmUseMangledMesaCommand::InitialPass(std::vector<std::string> const& args, } cmSystemTools::MakeDirectory(destDir); for (std::string const& f : files) { - std::string path = inputDir; - path += "/"; - path += f; + std::string path = cmStrCat(inputDir, '/', f); this->CopyAndFullPathMesaHeader(path, destDir); } @@ -51,13 +46,11 @@ bool cmUseMangledMesaCommand::InitialPass(std::vector<std::string> const& args, void cmUseMangledMesaCommand::CopyAndFullPathMesaHeader( const std::string& source, const std::string& outdir) { - std::string dir, file; + std::string dir; + std::string file; cmSystemTools::SplitProgramPath(source, dir, file); - std::string outFile = outdir; - outFile += "/"; - outFile += file; - std::string tempOutputFile = outFile; - tempOutputFile += ".tmp"; + std::string outFile = cmStrCat(outdir, '/', file); + std::string tempOutputFile = cmStrCat(outFile, ".tmp"); cmsys::ofstream fout(tempOutputFile.c_str()); if (!fout) { cmSystemTools::Error("Could not open file for write in copy operation: " + diff --git a/Source/cmUtilitySourceCommand.cxx b/Source/cmUtilitySourceCommand.cxx index b59a587..d255b67 100644 --- a/Source/cmUtilitySourceCommand.cxx +++ b/Source/cmUtilitySourceCommand.cxx @@ -7,6 +7,7 @@ #include "cmMakefile.h" #include "cmState.h" #include "cmStateTypes.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" class cmExecutionStatus; @@ -35,11 +36,11 @@ bool cmUtilitySourceCommand::InitialPass(std::vector<std::string> const& args, if (this->Makefile->IsOn("CMAKE_CROSSCOMPILING")) { haveCacheValue = (cacheValue != nullptr); if (!haveCacheValue) { - std::string msg = "UTILITY_SOURCE is used in cross compiling mode for "; - msg += cacheEntry; - msg += ". If your intention is to run this executable, you need to " - "preload the cache with the full path to a version of that " - "program, which runs on this build machine."; + std::string msg = cmStrCat( + "UTILITY_SOURCE is used in cross compiling mode for ", cacheEntry, + ". If your intention is to run this executable, you need to " + "preload the cache with the full path to a version of that " + "program, which runs on this build machine."); cmSystemTools::Message(msg, "Warning"); } } else { diff --git a/Source/cmUuid.cxx b/Source/cmUuid.cxx index 51ecbd1..0dc6ca7 100644 --- a/Source/cmUuid.cxx +++ b/Source/cmUuid.cxx @@ -114,14 +114,12 @@ std::string cmUuid::BinaryToString(const unsigned char* input) const std::string cmUuid::ByteToHex(unsigned char byte) const { - std::string result; + std::string result(" "); for (int i = 0; i < 2; ++i) { unsigned char rest = byte % 16; byte /= 16; - char c = (rest < 0xA) ? char('0' + rest) : char('a' + (rest - 0xA)); - - result = c + result; + result.at(1 - i) = c; } return result; diff --git a/Source/cmVSSetupHelper.cxx b/Source/cmVSSetupHelper.cxx index c78361e..707ceac 100644 --- a/Source/cmVSSetupHelper.cxx +++ b/Source/cmVSSetupHelper.cxx @@ -2,6 +2,7 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmVSSetupHelper.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmsys/Encoding.hxx" #include "cmsys/FStream.hxx" @@ -195,7 +196,7 @@ bool cmVSSetupAPIHelper::GetVSInstanceInfo( if (!fin || !cmSystemTools::GetLineFromStream(fin, vcToolsVersion)) { return false; } - vcToolsVersion = cmSystemTools::TrimWhitespace(vcToolsVersion); + vcToolsVersion = cmTrimWhitespace(vcToolsVersion); std::string const vcToolsDir = vcRoot + "/VC/Tools/MSVC/" + vcToolsVersion; if (!cmSystemTools::FileIsDirectory(vcToolsDir)) { return false; @@ -364,8 +365,8 @@ bool cmVSSetupAPIHelper::EnumerateAndChooseVSInstance() // We are not looking for a specific instance. // If we've been given a hint then use it. if (!envVSCommonToolsDir.empty()) { - std::string currentVSLocation = instanceInfo.GetInstallLocation(); - currentVSLocation += "/Common7/Tools"; + std::string currentVSLocation = + cmStrCat(instanceInfo.GetInstallLocation(), "/Common7/Tools"); if (cmSystemTools::ComparePath(currentVSLocation, envVSCommonToolsDir)) { chosenInstanceInfo = instanceInfo; diff --git a/Source/cmVariableRequiresCommand.cxx b/Source/cmVariableRequiresCommand.cxx index 9878ff1..c44eeca 100644 --- a/Source/cmVariableRequiresCommand.cxx +++ b/Source/cmVariableRequiresCommand.cxx @@ -4,6 +4,7 @@ #include "cmMakefile.h" #include "cmState.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" class cmExecutionStatus; @@ -46,12 +47,11 @@ bool cmVariableRequiresCommand::InitialPass( } if (!requirementsMet) { - std::string message = "Variable assertion failed:\n"; - message += - testVariable + " Requires that the following unset variables are set:\n"; - message += notSet; - message += "\nPlease set them, or set "; - message += testVariable + " to false, and re-configure.\n"; + std::string message = + cmStrCat("Variable assertion failed:\n", testVariable, + " Requires that the following unset variables are set:\n", + notSet, "\nPlease set them, or set ", testVariable, + " to false, and re-configure.\n"); if (hasAdvanced) { message += "One or more of the required variables is advanced." diff --git a/Source/cmVariableWatchCommand.cxx b/Source/cmVariableWatchCommand.cxx index 83a774d..db23efd 100644 --- a/Source/cmVariableWatchCommand.cxx +++ b/Source/cmVariableWatchCommand.cxx @@ -2,6 +2,7 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmVariableWatchCommand.h" +#include <memory> #include <sstream> #include <utility> @@ -119,11 +120,11 @@ private: std::shared_ptr<Impl const> Action; }; -bool cmVariableWatchCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus&) +bool cmVariableWatchCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.empty()) { - this->SetError("must be called with at least one argument."); + status.SetError("must be called with at least one argument."); return false; } std::string const& variable = args[0]; @@ -134,7 +135,7 @@ bool cmVariableWatchCommand::InitialPass(std::vector<std::string> const& args, if (variable == "CMAKE_CURRENT_LIST_FILE") { std::ostringstream ostr; ostr << "cannot be set on the variable: " << variable; - this->SetError(ostr.str()); + status.SetError(ostr.str()); return false; } @@ -143,13 +144,14 @@ bool cmVariableWatchCommand::InitialPass(std::vector<std::string> const& args, data->InCallback = false; data->Command = command; - if (!this->Makefile->GetCMakeInstance()->GetVariableWatch()->AddWatch( + if (!status.GetMakefile().GetCMakeInstance()->GetVariableWatch()->AddWatch( variable, cmVariableWatchCommandVariableAccessed, data, deleteVariableWatchCallbackData)) { deleteVariableWatchCallbackData(data); return false; } - this->Makefile->AddFinalAction(FinalAction(this->Makefile, variable)); + status.GetMakefile().AddFinalAction( + FinalAction(&status.GetMakefile(), variable)); return true; } diff --git a/Source/cmVariableWatchCommand.h b/Source/cmVariableWatchCommand.h index 221269f..3f9f244 100644 --- a/Source/cmVariableWatchCommand.h +++ b/Source/cmVariableWatchCommand.h @@ -8,33 +8,13 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -/** \class cmVariableWatchCommand +/** * \brief Watch when the variable changes and invoke command * */ -class cmVariableWatchCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmVariableWatchCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; -}; +bool cmVariableWatchCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmVisualStudio10TargetGenerator.cxx b/Source/cmVisualStudio10TargetGenerator.cxx index ed6e4d9..c5cf9a7 100644 --- a/Source/cmVisualStudio10TargetGenerator.cxx +++ b/Source/cmVisualStudio10TargetGenerator.cxx @@ -364,10 +364,9 @@ void cmVisualStudio10TargetGenerator::Generate() return; } } - std::string path = this->LocalGenerator->GetCurrentBinaryDirectory(); - path += "/"; - path += this->Name; - path += ProjectFileExtension; + std::string path = + cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(), '/', + this->Name, ProjectFileExtension); cmGeneratedFileStream BuildFileStream(path); const std::string PathToProjectFile = path; BuildFileStream.SetCopyIfDifferent(true); @@ -628,9 +627,8 @@ void cmVisualStudio10TargetGenerator::Generate() std::string propsTemplate = GetCMakeFilePath("Templates/MSBuild/nasm.props.in"); - std::string propsLocal; - propsLocal += this->DefaultArtifactDir; - propsLocal += "\\nasm.props"; + std::string propsLocal = + cmStrCat(this->DefaultArtifactDir, "\\nasm.props"); ConvertToWindowsSlash(propsLocal); this->Makefile->ConfigureFile(propsTemplate, propsLocal, false, true, true); @@ -750,7 +748,7 @@ void cmVisualStudio10TargetGenerator::WritePackageReferences(Elem& e0) std::vector<std::string> packageReferences; if (const char* vsPackageReferences = this->GeneratorTarget->GetProperty("VS_PACKAGE_REFERENCES")) { - cmSystemTools::ExpandListArgument(vsPackageReferences, packageReferences); + cmExpandList(vsPackageReferences, packageReferences); } if (!packageReferences.empty()) { Elem e1(e0, "ItemGroup"); @@ -777,7 +775,7 @@ void cmVisualStudio10TargetGenerator::WriteDotNetReferences(Elem& e0) std::vector<std::string> references; if (const char* vsDotNetReferences = this->GeneratorTarget->GetProperty("VS_DOTNET_REFERENCES")) { - cmSystemTools::ExpandListArgument(vsDotNetReferences, references); + cmExpandList(vsDotNetReferences, references); } cmPropertyMap const& props = this->GeneratorTarget->Target->GetProperties(); for (auto const& i : props.GetList()) { @@ -838,7 +836,7 @@ void cmVisualStudio10TargetGenerator::WriteDotNetReference( const char* privateReference = "True"; if (const char* value = this->GeneratorTarget->GetProperty( "VS_DOTNET_REFERENCES_COPY_LOCAL")) { - if (cmSystemTools::IsOff(value)) { + if (cmIsOff(value)) { privateReference = "False"; } } @@ -854,7 +852,7 @@ void cmVisualStudio10TargetGenerator::WriteImports(Elem& e0) this->GeneratorTarget->Target->GetProperty("VS_PROJECT_IMPORT"); if (imports) { std::vector<std::string> argsSplit; - cmSystemTools::ExpandListArgument(std::string(imports), argsSplit, false); + cmExpandList(std::string(imports), argsSplit, false); for (auto& path : argsSplit) { if (!cmsys::SystemTools::FileIsFullPath(path)) { path = this->Makefile->GetCurrentSourceDirectory() + "/" + path; @@ -1074,7 +1072,7 @@ void cmVisualStudio10TargetGenerator::WriteWinRTReferences(Elem& e0) std::vector<std::string> references; if (const char* vsWinRTReferences = this->GeneratorTarget->GetProperty("VS_WINRT_REFERENCES")) { - cmSystemTools::ExpandListArgument(vsWinRTReferences, references); + cmExpandList(vsWinRTReferences, references); } if (this->GlobalGenerator->TargetsWindowsPhone() && @@ -1272,8 +1270,8 @@ void cmVisualStudio10TargetGenerator::WriteMSToolConfigurationValuesManaged( e1.Element("PlatformToolset", toolset); } - std::string postfixName = cmSystemTools::UpperCase(config); - postfixName += "_POSTFIX"; + std::string postfixName = + cmStrCat(cmSystemTools::UpperCase(config), "_POSTFIX"); std::string assemblyName = this->GeneratorTarget->GetOutputName( config, cmStateEnums::RuntimeBinaryArtifact); if (const char* postfix = this->GeneratorTarget->GetProperty(postfixName)) { @@ -1378,9 +1376,8 @@ void cmVisualStudio10TargetGenerator::WriteCustomRule( // preventing dependent rebuilds. this->ForceOld(sourcePath); } else { - std::string error = "Could not create file: ["; - error += sourcePath; - error += "] "; + std::string error = + cmStrCat("Could not create file: [", sourcePath, "] "); cmSystemTools::Error(error + cmSystemTools::GetLastSystemError()); } } @@ -1549,11 +1546,9 @@ void cmVisualStudio10TargetGenerator::WriteGroups() this->AddMissingSourceGroups(groupsUsed, sourceGroups); // Write out group file - std::string path = this->LocalGenerator->GetCurrentBinaryDirectory(); - path += "/"; - path += this->Name; - path += computeProjectFileExtension(this->GeneratorTarget); - path += ".filters"; + std::string path = cmStrCat( + this->LocalGenerator->GetCurrentBinaryDirectory(), '/', this->Name, + computeProjectFileExtension(this->GeneratorTarget), ".filters"); cmGeneratedFileStream fout(path); fout.SetCopyIfDifferent(true); char magic[] = { char(0xEF), char(0xBB), char(0xBF) }; @@ -1948,11 +1943,11 @@ void cmVisualStudio10TargetGenerator::WriteExtraSource(Elem& e1, const std::string& enableDebug = cge->Evaluate(this->LocalGenerator, this->Configurations[i]); if (!enableDebug.empty()) { - e2.WritePlatformConfigTag( - "EnableDebuggingInformation", - "'$(Configuration)|$(Platform)'=='" + this->Configurations[i] + - "|" + this->Platform + "'", - cmSystemTools::IsOn(enableDebug) ? "true" : "false"); + e2.WritePlatformConfigTag("EnableDebuggingInformation", + "'$(Configuration)|$(Platform)'=='" + + this->Configurations[i] + "|" + + this->Platform + "'", + cmIsOn(enableDebug) ? "true" : "false"); } } } @@ -1969,7 +1964,7 @@ void cmVisualStudio10TargetGenerator::WriteExtraSource(Elem& e1, "DisableOptimizations", "'$(Configuration)|$(Platform)'=='" + this->Configurations[i] + "|" + this->Platform + "'", - (cmSystemTools::IsOn(disableOptimizations) ? "true" : "false")); + (cmIsOn(disableOptimizations) ? "true" : "false")); } } } @@ -2234,8 +2229,7 @@ void cmVisualStudio10TargetGenerator::OutputSourceSpecificFlags( for (std::string const& config : this->Configurations) { std::string configUpper = cmSystemTools::UpperCase(config); std::string configDefines = defines; - std::string defPropName = "COMPILE_DEFINITIONS_"; - defPropName += configUpper; + std::string defPropName = cmStrCat("COMPILE_DEFINITIONS_", configUpper); if (const char* ccdefs = sf.GetProperty(defPropName)) { if (!configDefines.empty()) { configDefines += ";"; @@ -2425,17 +2419,14 @@ void cmVisualStudio10TargetGenerator::WritePathAndIncrementalLinkOptions( e1.WritePlatformConfigTag( "IntDir", cond, "$(Platform)\\$(Configuration)\\$(ProjectName)\\"); } else { - std::string intermediateDir = - this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget); - intermediateDir += "/"; - intermediateDir += config; - intermediateDir += "/"; + std::string intermediateDir = cmStrCat( + this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget), '/', + config, '/'); std::string outDir; std::string targetNameFull; if (ttype == cmStateEnums::OBJECT_LIBRARY) { outDir = intermediateDir; - targetNameFull = this->GeneratorTarget->GetName(); - targetNameFull += ".lib"; + targetNameFull = cmStrCat(this->GeneratorTarget->GetName(), ".lib"); } else { outDir = this->GeneratorTarget->GetDirectory(config) + "/"; targetNameFull = this->GeneratorTarget->GetFullName(config); @@ -2603,8 +2594,7 @@ bool cmVisualStudio10TargetGenerator::ComputeClOptions( std::string langForClCompile; if (this->ProjectType == csproj) { langForClCompile = "CSharp"; - } else if (std::find(cm::cbegin(clLangs), cm::cend(clLangs), linkLanguage) != - cm::cend(clLangs)) { + } else if (cmContains(clLangs, linkLanguage)) { langForClCompile = linkLanguage; } else { std::set<std::string> languages; @@ -2716,9 +2706,7 @@ bool cmVisualStudio10TargetGenerator::ComputeClOptions( } // Add a definition for the configuration name. - std::string configDefine = "CMAKE_INTDIR=\""; - configDefine += configName; - configDefine += "\""; + std::string configDefine = cmStrCat("CMAKE_INTDIR=\"", configName, '"'); clOptions.AddDefine(configDefine); if (const std::string* exportMacro = this->GeneratorTarget->GetExportMacro()) { @@ -2743,7 +2731,7 @@ bool cmVisualStudio10TargetGenerator::ComputeClOptions( } } if (const char* winRT = clOptions.GetFlag("CompileAsWinRT")) { - if (cmSystemTools::IsOn(winRT)) { + if (cmIsOn(winRT)) { this->TargetCompileAsWinRT = true; } } @@ -3013,9 +3001,7 @@ bool cmVisualStudio10TargetGenerator::ComputeCudaOptions( cudaOptions.AddDefines(targetDefines); // Add a definition for the configuration name. - std::string configDefine = "CMAKE_INTDIR=\""; - configDefine += configName; - configDefine += "\""; + std::string configDefine = cmStrCat("CMAKE_INTDIR=\"", configName, '"'); cudaOptions.AddDefine(configDefine); if (const std::string* exportMacro = this->GeneratorTarget->GetExportMacro()) { @@ -3273,9 +3259,9 @@ void cmVisualStudio10TargetGenerator::WriteManifestOptions( if (dpiAware) { if (!strcmp(dpiAware, "PerMonitor")) { e2.Element("EnableDpiAwareness", "PerMonitorHighDPIAware"); - } else if (cmSystemTools::IsOn(dpiAware)) { + } else if (cmIsOn(dpiAware)) { e2.Element("EnableDpiAwareness", "true"); - } else if (cmSystemTools::IsOff(dpiAware)) { + } else if (cmIsOff(dpiAware)) { e2.Element("EnableDpiAwareness", "false"); } else { cmSystemTools::Error("Bad parameter for VS_DPI_AWARE: " + @@ -3430,9 +3416,7 @@ bool cmVisualStudio10TargetGenerator::ComputeLinkOptions( linkType = "EXE"; } std::string flags; - std::string linkFlagVarBase = "CMAKE_"; - linkFlagVarBase += linkType; - linkFlagVarBase += "_LINKER_FLAGS"; + std::string linkFlagVarBase = cmStrCat("CMAKE_", linkType, "_LINKER_FLAGS"); flags += " "; flags += this->Makefile->GetRequiredDefinition(linkFlagVarBase); std::string linkFlagVar = linkFlagVarBase + "_" + CONFIG; @@ -3444,8 +3428,7 @@ bool cmVisualStudio10TargetGenerator::ComputeLinkOptions( flags += " "; flags += targetLinkFlags; } - std::string flagsProp = "LINK_FLAGS_"; - flagsProp += CONFIG; + std::string flagsProp = cmStrCat("LINK_FLAGS_", CONFIG); if (const char* flagsConfig = this->GeneratorTarget->GetProperty(flagsProp)) { flags += " "; @@ -3470,8 +3453,7 @@ bool cmVisualStudio10TargetGenerator::ComputeLinkOptions( std::vector<std::string> libVec; std::vector<std::string> vsTargetVec; this->AddLibraries(cli, libVec, vsTargetVec, config); - if (std::find(linkClosure->Languages.begin(), linkClosure->Languages.end(), - "CUDA") != linkClosure->Languages.end() && + if (cmContains(linkClosure->Languages, "CUDA") && this->CudaOptions[config] != nullptr) { switch (this->CudaOptions[config]->GetCudaRuntime()) { case cmVisualStudioGeneratorOptions::CudaRuntimeStatic: @@ -3486,9 +3468,8 @@ bool cmVisualStudio10TargetGenerator::ComputeLinkOptions( break; } } - std::string standardLibsVar = "CMAKE_"; - standardLibsVar += linkLanguage; - standardLibsVar += "_STANDARD_LIBRARIES"; + std::string standardLibsVar = + cmStrCat("CMAKE_", linkLanguage, "_STANDARD_LIBRARIES"); std::string const& libs = this->Makefile->GetSafeDefinition(standardLibsVar); cmSystemTools::ParseWindowsCommandLine(libs.c_str(), libVec); linkOptions.AddFlag("AdditionalDependencies", libVec); @@ -3552,13 +3533,12 @@ bool cmVisualStudio10TargetGenerator::ComputeLinkOptions( linkOptions.AddFlag("GenerateDebugInformation", "false"); - std::string pdb = this->GeneratorTarget->GetPDBDirectory(config); - pdb += "/"; - pdb += targetNames.PDB; - std::string imLib = this->GeneratorTarget->GetDirectory( - config, cmStateEnums::ImportLibraryArtifact); - imLib += "/"; - imLib += targetNames.ImportLibrary; + std::string pdb = cmStrCat(this->GeneratorTarget->GetPDBDirectory(config), + '/', targetNames.PDB); + std::string imLib = + cmStrCat(this->GeneratorTarget->GetDirectory( + config, cmStateEnums::ImportLibraryArtifact), + '/', targetNames.ImportLibrary); linkOptions.AddFlag("ImportLibrary", imLib); linkOptions.AddFlag("ProgramDataBaseFile", pdb); @@ -3758,8 +3738,7 @@ void cmVisualStudio10TargetGenerator::AddTargetsFileAndConfigPair( { for (TargetsFileAndConfigs& i : this->TargetsFileAndConfigsVec) { if (cmSystemTools::ComparePath(targetsFile, i.File)) { - if (std::find(i.Configs.begin(), i.Configs.end(), config) == - i.Configs.end()) { + if (!cmContains(i.Configs, config)) { i.Configs.push_back(config); } return; @@ -3941,10 +3920,8 @@ void cmVisualStudio10TargetGenerator::WriteProjectReferences(Elem& e0) if (p) { path = p; } else { - path = lg->GetCurrentBinaryDirectory(); - path += "/"; - path += dt->GetName(); - path += computeProjectFileExtension(dt); + path = cmStrCat(lg->GetCurrentBinaryDirectory(), '/', dt->GetName(), + computeProjectFileExtension(dt)); } ConvertToWindowsSlash(path); Elem e2(e1, "ProjectReference"); @@ -4027,7 +4004,7 @@ void cmVisualStudio10TargetGenerator::WriteSDKReferences(Elem& e0) std::unique_ptr<Elem> spe1; if (const char* vsSDKReferences = this->GeneratorTarget->GetProperty("VS_SDK_REFERENCES")) { - cmSystemTools::ExpandListArgument(vsSDKReferences, sdkReferences); + cmExpandList(vsSDKReferences, sdkReferences); spe1 = cm::make_unique<Elem>(e0, "ItemGroup"); for (std::string const& ri : sdkReferences) { Elem(*spe1, "SDKReference").Attribute("Include", ri); @@ -4751,8 +4728,8 @@ std::string cmVisualStudio10TargetGenerator::GetCMakeFilePath( const char* relativeFilePath) const { // Always search in the standard modules location. - std::string path = cmSystemTools::GetCMakeRoot() + "/"; - path += relativeFilePath; + std::string path = + cmStrCat(cmSystemTools::GetCMakeRoot(), '/', relativeFilePath); ConvertToWindowsSlash(path); return path; diff --git a/Source/cmVisualStudioGeneratorOptions.cxx b/Source/cmVisualStudioGeneratorOptions.cxx index e1b0c70..3e423e9 100644 --- a/Source/cmVisualStudioGeneratorOptions.cxx +++ b/Source/cmVisualStudioGeneratorOptions.cxx @@ -193,7 +193,7 @@ void cmVisualStudioGeneratorOptions::FixCudaCodeGeneration() std::string arch_name = arch[0]; std::vector<std::string> codes; if (!code.empty()) { - codes = cmSystemTools::tokenize(code[0], ","); + codes = cmTokenize(code[0], ","); } if (codes.empty()) { codes.push_back(arch_name); @@ -220,7 +220,7 @@ void cmVisualStudioGeneratorOptions::FixCudaCodeGeneration() cmSystemTools::ReplaceString(entry, "]", ""); cmSystemTools::ReplaceString(entry, "\"", ""); - std::vector<std::string> codes = cmSystemTools::tokenize(entry, ","); + std::vector<std::string> codes = cmTokenize(entry, ","); if (codes.size() >= 2) { auto gencode_arch = cm::cbegin(codes); for (auto ci = gencode_arch + 1; ci != cm::cend(codes); ++ci) { @@ -325,9 +325,9 @@ void cmVisualStudioGeneratorOptions::ParseFinish() // "rtSingleThreadedDLL", "10", /libs:dll // "rtSingleThreadedDebug", "5", /dbglibs /libs:static // "rtSingleThreadedDebugDLL", "11", /dbglibs /libs:dll - std::string rl = "rtMultiThreaded"; - rl += this->FortranRuntimeDebug ? "Debug" : ""; - rl += this->FortranRuntimeDLL ? "DLL" : ""; + std::string rl = + cmStrCat("rtMultiThreaded", this->FortranRuntimeDebug ? "Debug" : "", + this->FortranRuntimeDLL ? "DLL" : ""); this->FlagMap["RuntimeLibrary"] = rl; } diff --git a/Source/cmVisualStudioSlnParser.cxx b/Source/cmVisualStudioSlnParser.cxx index 3e7e142..9eaee11 100644 --- a/Source/cmVisualStudioSlnParser.cxx +++ b/Source/cmVisualStudioSlnParser.cxx @@ -463,7 +463,7 @@ bool cmVisualStudioSlnParser::ParseImpl(std::istream& input, cmSlnData& output, if (!this->ParseBOM(input, line, state)) return false; do { - line = cmSystemTools::TrimWhitespace(line); + line = cmTrimWhitespace(line); if (line.empty()) continue; ParsedLine parsedLine; @@ -579,9 +579,9 @@ bool cmVisualStudioSlnParser::ParseKeyValuePair(const std::string& line, return true; } const std::string& key = line.substr(0, idxEqualSign); - parsedLine.SetTag(cmSystemTools::TrimWhitespace(key)); + parsedLine.SetTag(cmTrimWhitespace(key)); const std::string& value = line.substr(idxEqualSign + 1); - parsedLine.AddValue(cmSystemTools::TrimWhitespace(value)); + parsedLine.AddValue(cmTrimWhitespace(value)); return true; } @@ -590,18 +590,17 @@ bool cmVisualStudioSlnParser::ParseTag(const std::string& fullTag, { size_t idxLeftParen = fullTag.find('('); if (idxLeftParen == fullTag.npos) { - parsedLine.SetTag(cmSystemTools::TrimWhitespace(fullTag)); + parsedLine.SetTag(cmTrimWhitespace(fullTag)); return true; } - parsedLine.SetTag( - cmSystemTools::TrimWhitespace(fullTag.substr(0, idxLeftParen))); + parsedLine.SetTag(cmTrimWhitespace(fullTag.substr(0, idxLeftParen))); size_t idxRightParen = fullTag.rfind(')'); if (idxRightParen == fullTag.npos) { this->LastResult.SetError(ResultErrorInputStructure, state.GetCurrentLine()); return false; } - const std::string& arg = cmSystemTools::TrimWhitespace( + const std::string& arg = cmTrimWhitespace( fullTag.substr(idxLeftParen + 1, idxRightParen - idxLeftParen - 1)); if (arg.front() == '"') { if (arg.back() != '"') { @@ -618,7 +617,7 @@ bool cmVisualStudioSlnParser::ParseTag(const std::string& fullTag, bool cmVisualStudioSlnParser::ParseValue(const std::string& value, ParsedLine& parsedLine) { - const std::string& trimmed = cmSystemTools::TrimWhitespace(value); + const std::string& trimmed = cmTrimWhitespace(value); if (trimmed.empty()) parsedLine.AddValue(trimmed); else if (trimmed.front() == '"' && trimmed.back() == '"') diff --git a/Source/cmWhileCommand.cxx b/Source/cmWhileCommand.cxx index 37d1c74..a396852 100644 --- a/Source/cmWhileCommand.cxx +++ b/Source/cmWhileCommand.cxx @@ -3,10 +3,14 @@ #include "cmWhileCommand.h" #include "cm_memory.hxx" +#include "cm_static_string_view.hxx" +#include "cm_string_view.hxx" #include "cmConditionEvaluator.h" #include "cmExecutionStatus.h" #include "cmExpandedCommandArgument.h" +#include "cmFunctionBlocker.h" +#include "cmListFileCache.h" #include "cmMakefile.h" #include "cmMessageType.h" #include "cmSystemTools.h" @@ -14,9 +18,29 @@ #include <string> #include <utility> +class cmWhileFunctionBlocker : public cmFunctionBlocker +{ +public: + cmWhileFunctionBlocker(cmMakefile* mf); + ~cmWhileFunctionBlocker() override; + + cm::string_view StartCommandName() const override { return "while"_s; } + cm::string_view EndCommandName() const override { return "endwhile"_s; } + + bool ArgumentsMatch(cmListFileFunction const& lff, + cmMakefile& mf) const override; + + bool Replay(std::vector<cmListFileFunction> functions, + cmExecutionStatus& inStatus) override; + + std::vector<cmListFileArgument> Args; + +private: + cmMakefile* Makefile; +}; + cmWhileFunctionBlocker::cmWhileFunctionBlocker(cmMakefile* mf) : Makefile(mf) - , Depth(0) { this->Makefile->PushLoopBlock(); } @@ -26,108 +50,77 @@ cmWhileFunctionBlocker::~cmWhileFunctionBlocker() this->Makefile->PopLoopBlock(); } -bool cmWhileFunctionBlocker::IsFunctionBlocked(const cmListFileFunction& lff, - cmMakefile& mf, - cmExecutionStatus& inStatus) +bool cmWhileFunctionBlocker::ArgumentsMatch(cmListFileFunction const& lff, + cmMakefile&) const { - // at end of for each execute recorded commands - if (lff.Name.Lower == "while") { - // record the number of while commands past this one - this->Depth++; - } else if (lff.Name.Lower == "endwhile") { - // if this is the endwhile for this while loop then execute - if (!this->Depth) { - // Remove the function blocker for this scope or bail. - std::unique_ptr<cmFunctionBlocker> fb( - mf.RemoveFunctionBlocker(this, lff)); - if (!fb) { - return false; - } + return lff.Arguments.empty() || lff.Arguments == this->Args; +} - std::string errorString; - - std::vector<cmExpandedCommandArgument> expandedArguments; - mf.ExpandArguments(this->Args, expandedArguments); - MessageType messageType; - - cmListFileContext execContext = this->GetStartingContext(); - - cmCommandContext commandContext; - commandContext.Line = execContext.Line; - commandContext.Name = execContext.Name; - - cmConditionEvaluator conditionEvaluator(mf, this->GetStartingContext(), - mf.GetBacktrace(commandContext)); - - bool isTrue = - conditionEvaluator.IsTrue(expandedArguments, errorString, messageType); - - while (isTrue) { - if (!errorString.empty()) { - std::string err = "had incorrect arguments: "; - for (cmListFileArgument const& arg : this->Args) { - err += (arg.Delim ? "\"" : ""); - err += arg.Value; - err += (arg.Delim ? "\"" : ""); - err += " "; - } - err += "("; - err += errorString; - err += ")."; - mf.IssueMessage(messageType, err); - if (messageType == MessageType::FATAL_ERROR) { - cmSystemTools::SetFatalErrorOccured(); - return true; - } - } - - // Invoke all the functions that were collected in the block. - for (cmListFileFunction const& fn : this->Functions) { - cmExecutionStatus status(mf); - mf.ExecuteCommand(fn, status); - if (status.GetReturnInvoked()) { - inStatus.SetReturnInvoked(); - return true; - } - if (status.GetBreakInvoked()) { - return true; - } - if (status.GetContinueInvoked()) { - break; - } - if (cmSystemTools::GetFatalErrorOccured()) { - return true; - } - } - expandedArguments.clear(); - mf.ExpandArguments(this->Args, expandedArguments); - isTrue = conditionEvaluator.IsTrue(expandedArguments, errorString, - messageType); - } - return true; - } - // decrement for each nested while that ends - this->Depth--; - } +bool cmWhileFunctionBlocker::Replay(std::vector<cmListFileFunction> functions, + cmExecutionStatus& inStatus) +{ + cmMakefile& mf = inStatus.GetMakefile(); + std::string errorString; - // record the command - this->Functions.push_back(lff); + std::vector<cmExpandedCommandArgument> expandedArguments; + mf.ExpandArguments(this->Args, expandedArguments); + MessageType messageType; - // always return true - return true; -} + cmListFileContext execContext = this->GetStartingContext(); -bool cmWhileFunctionBlocker::ShouldRemove(const cmListFileFunction& lff, - cmMakefile&) -{ - if (lff.Name.Lower == "endwhile") { - // if the endwhile has arguments, then make sure - // they match the arguments of the matching while - if (lff.Arguments.empty() || lff.Arguments == this->Args) { - return true; + cmCommandContext commandContext; + commandContext.Line = execContext.Line; + commandContext.Name = execContext.Name; + + cmConditionEvaluator conditionEvaluator(mf, this->GetStartingContext(), + mf.GetBacktrace(commandContext)); + + bool isTrue = + conditionEvaluator.IsTrue(expandedArguments, errorString, messageType); + + while (isTrue) { + if (!errorString.empty()) { + std::string err = "had incorrect arguments: "; + for (cmListFileArgument const& arg : this->Args) { + err += (arg.Delim ? "\"" : ""); + err += arg.Value; + err += (arg.Delim ? "\"" : ""); + err += " "; + } + err += "("; + err += errorString; + err += ")."; + mf.IssueMessage(messageType, err); + if (messageType == MessageType::FATAL_ERROR) { + cmSystemTools::SetFatalErrorOccured(); + return true; + } } + + // Invoke all the functions that were collected in the block. + for (cmListFileFunction const& fn : functions) { + cmExecutionStatus status(mf); + mf.ExecuteCommand(fn, status); + if (status.GetReturnInvoked()) { + inStatus.SetReturnInvoked(); + return true; + } + if (status.GetBreakInvoked()) { + return true; + } + if (status.GetContinueInvoked()) { + break; + } + if (cmSystemTools::GetFatalErrorOccured()) { + return true; + } + } + expandedArguments.clear(); + mf.ExpandArguments(this->Args, expandedArguments); + isTrue = + conditionEvaluator.IsTrue(expandedArguments, errorString, messageType); } - return false; + return true; } bool cmWhileCommand(std::vector<cmListFileArgument> const& args, diff --git a/Source/cmWhileCommand.h b/Source/cmWhileCommand.h index 2257799..beca652 100644 --- a/Source/cmWhileCommand.h +++ b/Source/cmWhileCommand.h @@ -7,28 +7,8 @@ #include <vector> -#include "cmFunctionBlocker.h" -#include "cmListFileCache.h" - class cmExecutionStatus; -class cmMakefile; - -class cmWhileFunctionBlocker : public cmFunctionBlocker -{ -public: - cmWhileFunctionBlocker(cmMakefile* mf); - ~cmWhileFunctionBlocker() override; - bool IsFunctionBlocked(const cmListFileFunction& lff, cmMakefile& mf, - cmExecutionStatus&) override; - bool ShouldRemove(const cmListFileFunction& lff, cmMakefile& mf) override; - - std::vector<cmListFileArgument> Args; - std::vector<cmListFileFunction> Functions; - -private: - cmMakefile* Makefile; - int Depth; -}; +struct cmListFileArgument; /// \brief Starts a while loop bool cmWhileCommand(std::vector<cmListFileArgument> const& args, diff --git a/Source/cmWorkerPool.cxx b/Source/cmWorkerPool.cxx index 974100b..baf326a 100644 --- a/Source/cmWorkerPool.cxx +++ b/Source/cmWorkerPool.cxx @@ -3,6 +3,7 @@ #include "cmWorkerPool.h" #include "cmRange.h" +#include "cmStringAlgorithms.h" #include "cmUVHandlePtr.h" #include "cmUVSignalHackRAII.h" // IWYU pragma: keep #include "cm_uv.h" @@ -306,13 +307,11 @@ void cmUVReadOnlyProcess::UVExit(uv_process_t* handle, int64_t exitStatus, proc.Result()->TermSignal = termSignal; if (!proc.Result()->error()) { if (termSignal != 0) { - proc.Result()->ErrorMessage = "Process was terminated by signal "; - proc.Result()->ErrorMessage += - std::to_string(proc.Result()->TermSignal); + proc.Result()->ErrorMessage = cmStrCat( + "Process was terminated by signal ", proc.Result()->TermSignal); } else if (exitStatus != 0) { - proc.Result()->ErrorMessage = "Process failed with return value "; - proc.Result()->ErrorMessage += - std::to_string(proc.Result()->ExitStatus); + proc.Result()->ErrorMessage = cmStrCat( + "Process failed with return value ", proc.Result()->ExitStatus); } } @@ -332,9 +331,8 @@ void cmUVReadOnlyProcess::UVPipeOutEnd(ssize_t error) { // Process pipe error if ((error != 0) && !Result()->error()) { - Result()->ErrorMessage = - "Reading from stdout pipe failed with libuv error code "; - Result()->ErrorMessage += std::to_string(error); + Result()->ErrorMessage = cmStrCat( + "Reading from stdout pipe failed with libuv error code ", error); } // Try finish UVTryFinish(); @@ -351,9 +349,8 @@ void cmUVReadOnlyProcess::UVPipeErrEnd(ssize_t error) { // Process pipe error if ((error != 0) && !Result()->error()) { - Result()->ErrorMessage = - "Reading from stderr pipe failed with libuv error code "; - Result()->ErrorMessage += std::to_string(error); + Result()->ErrorMessage = cmStrCat( + "Reading from stderr pipe failed with libuv error code ", error); } // Try finish UVTryFinish(); diff --git a/Source/cmWriteFileCommand.cxx b/Source/cmWriteFileCommand.cxx index 49dbf1a..5009b16 100644 --- a/Source/cmWriteFileCommand.cxx +++ b/Source/cmWriteFileCommand.cxx @@ -4,18 +4,18 @@ #include "cmsys/FStream.hxx" +#include "cmExecutionStatus.h" #include "cmMakefile.h" +#include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cm_sys_stat.h" -class cmExecutionStatus; - // cmLibraryCommand -bool cmWriteFileCommand::InitialPass(std::vector<std::string> const& args, - cmExecutionStatus&) +bool cmWriteFileCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) { if (args.size() < 2) { - this->SetError("called with incorrect number of arguments"); + status.SetError("called with incorrect number of arguments"); return false; } std::string message; @@ -33,10 +33,10 @@ bool cmWriteFileCommand::InitialPass(std::vector<std::string> const& args, } } - if (!this->Makefile->CanIWriteThisFile(fileName)) { + if (!status.GetMakefile().CanIWriteThisFile(fileName)) { std::string e = "attempted to write a file: " + fileName + " into a source directory."; - this->SetError(e); + status.SetError(e); cmSystemTools::SetFatalErrorOccured(); return false; } @@ -65,10 +65,10 @@ bool cmWriteFileCommand::InitialPass(std::vector<std::string> const& args, cmsys::ofstream file(fileName.c_str(), overwrite ? std::ios::out : std::ios::app); if (!file) { - std::string error = "Internal CMake error when trying to open file: "; - error += fileName; - error += " for writing."; - this->SetError(error); + std::string error = + cmStrCat("Internal CMake error when trying to open file: ", fileName, + " for writing."); + status.SetError(error); return false; } file << message << std::endl; diff --git a/Source/cmWriteFileCommand.h b/Source/cmWriteFileCommand.h index 3961898..3e0e043 100644 --- a/Source/cmWriteFileCommand.h +++ b/Source/cmWriteFileCommand.h @@ -8,33 +8,13 @@ #include <string> #include <vector> -#include "cm_memory.hxx" - -#include "cmCommand.h" - class cmExecutionStatus; -/** \class cmWriteFileCommand +/** * \brief Writes a message to a file * */ -class cmWriteFileCommand : public cmCommand -{ -public: - /** - * This is a virtual constructor for the command. - */ - std::unique_ptr<cmCommand> Clone() override - { - return cm::make_unique<cmWriteFileCommand>(); - } - - /** - * This is called when the command is first encountered in - * the CMakeLists.txt file. - */ - bool InitialPass(std::vector<std::string> const& args, - cmExecutionStatus& status) override; -}; +bool cmWriteFileCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); #endif diff --git a/Source/cmXCodeObject.h b/Source/cmXCodeObject.h index 51e5d36..0552676 100644 --- a/Source/cmXCodeObject.h +++ b/Source/cmXCodeObject.h @@ -12,6 +12,8 @@ #include <utility> #include <vector> +#include "cmAlgorithms.h" + class cmGeneratorTarget; class cmXCodeObject @@ -80,15 +82,10 @@ public: void SetObject(cmXCodeObject* value) { this->Object = value; } cmXCodeObject* GetObject() { return this->Object; } void AddObject(cmXCodeObject* value) { this->List.push_back(value); } - bool HasObject(cmXCodeObject* o) const - { - return !(std::find(this->List.begin(), this->List.end(), o) == - this->List.end()); - } + bool HasObject(cmXCodeObject* o) const { return cmContains(this->List, o); } void AddUniqueObject(cmXCodeObject* value) { - if (std::find(this->List.begin(), this->List.end(), value) == - this->List.end()) { + if (!cmContains(this->List, value)) { this->List.push_back(value); } } diff --git a/Source/cmXCodeScheme.cxx b/Source/cmXCodeScheme.cxx index c33bb7e..0b3962e 100644 --- a/Source/cmXCodeScheme.cxx +++ b/Source/cmXCodeScheme.cxx @@ -27,14 +27,11 @@ void cmXCodeScheme::WriteXCodeSharedScheme(const std::string& xcProjDir, { // Create shared scheme sub-directory tree // - std::string xcodeSchemeDir = xcProjDir; - xcodeSchemeDir += "/xcshareddata/xcschemes"; + std::string xcodeSchemeDir = cmStrCat(xcProjDir, "/xcshareddata/xcschemes"); cmSystemTools::MakeDirectory(xcodeSchemeDir.c_str()); - std::string xcodeSchemeFile = xcodeSchemeDir; - xcodeSchemeFile += "/"; - xcodeSchemeFile += this->TargetName; - xcodeSchemeFile += ".xcscheme"; + std::string xcodeSchemeFile = + cmStrCat(xcodeSchemeDir, '/', this->TargetName, ".xcscheme"); cmGeneratedFileStream fout(xcodeSchemeFile); fout.SetCopyIfDifferent(true); @@ -218,7 +215,7 @@ void cmXCodeScheme::WriteLaunchAction(cmXMLWriter& xout, if (const char* argList = this->Target->GetTarget()->GetProperty("XCODE_SCHEME_ARGUMENTS")) { std::vector<std::string> arguments; - cmSystemTools::ExpandListArgument(argList, arguments); + cmExpandList(argList, arguments); if (!arguments.empty()) { xout.StartElement("CommandLineArguments"); @@ -239,7 +236,7 @@ void cmXCodeScheme::WriteLaunchAction(cmXMLWriter& xout, if (const char* envList = this->Target->GetTarget()->GetProperty("XCODE_SCHEME_ENVIRONMENT")) { std::vector<std::string> envs; - cmSystemTools::ExpandListArgument(envList, envs); + cmExpandList(envList, envs); if (!envs.empty()) { xout.StartElement("EnvironmentVariables"); @@ -393,9 +390,7 @@ std::string cmXCodeScheme::FindConfiguration(const std::string& name) // Try to find the desired configuration by name, // and if it's not found return first from the list // - if (std::find(this->ConfigList.begin(), this->ConfigList.end(), name) == - this->ConfigList.end() && - !this->ConfigList.empty()) { + if (!cmContains(this->ConfigList, name) && !this->ConfigList.empty()) { return this->ConfigList[0]; } diff --git a/Source/cm_codecvt.hxx b/Source/cm_codecvt.hxx index 2df3961..2060584 100644 --- a/Source/cm_codecvt.hxx +++ b/Source/cm_codecvt.hxx @@ -18,7 +18,7 @@ public: ANSI }; -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP codecvt(Encoding e); diff --git a/Source/cmake.cxx b/Source/cmake.cxx index 309efd3..a5c8d46 100644 --- a/Source/cmake.cxx +++ b/Source/cmake.cxx @@ -28,9 +28,10 @@ #include "cmUtils.hxx" #include "cmVersionConfig.h" #include "cmWorkingDirectory.h" +#include "cm_string_view.hxx" #include "cm_sys_stat.h" -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) # include "cm_jsoncpp_writer.h" # include "cmFileAPI.h" @@ -39,11 +40,11 @@ # include <unordered_map> #endif -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) # define CMAKE_USE_ECLIPSE #endif -#if defined(__MINGW32__) && !defined(CMAKE_BUILD_WITH_CMAKE) +#if defined(__MINGW32__) && defined(CMAKE_BOOTSTRAP) # define CMAKE_BOOT_MINGW #endif @@ -71,7 +72,7 @@ # include "cmGlobalWatcomWMakeGenerator.h" #endif #include "cmGlobalUnixMakefileGenerator3.h" -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) # include "cmGlobalNinjaGenerator.h" #endif #include "cmExtraCodeLiteGenerator.h" @@ -91,7 +92,7 @@ #endif #if defined(__APPLE__) -# if defined(CMAKE_BUILD_WITH_CMAKE) +# if !defined(CMAKE_BOOTSTRAP) # include "cmGlobalXCodeGenerator.h" # define CMAKE_USE_XCODE 1 @@ -114,7 +115,7 @@ namespace { -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) typedef std::unordered_map<std::string, Json::Value> JsonValueMapType; #endif @@ -132,22 +133,16 @@ static void cmWarnUnusedCliWarning(const std::string& variable, int /*unused*/, } cmake::cmake(Role role, cmState::Mode mode) + : FileTimeCache(cm::make_unique<cmFileTimeCache>()) +#ifndef CMAKE_BOOTSTRAP + , VariableWatch(cm::make_unique<cmVariableWatch>()) +#endif + , State(cm::make_unique<cmState>()) + , Messenger(cm::make_unique<cmMessenger>()) { - this->Trace = false; - this->TraceExpand = false; - this->WarnUninitialized = false; - this->WarnUnused = false; - this->WarnUnusedCli = true; - this->CheckSystemVars = false; - this->DebugOutput = false; - this->DebugTryCompile = false; - this->ClearBuildSystem = false; - this->FileTimeCache = cm::make_unique<cmFileTimeCache>(); - - this->State = cm::make_unique<cmState>(); + this->TraceFile.close(); this->State->SetMode(mode); this->CurrentSnapshot = this->State->CreateBaseSnapshot(); - this->Messenger = cm::make_unique<cmMessenger>(); #ifdef __APPLE__ struct rlimit rlp; @@ -159,16 +154,6 @@ cmake::cmake(Role role, cmState::Mode mode) } #endif - this->GlobalGenerator = nullptr; - this->GeneratorInstanceSet = false; - this->GeneratorPlatformSet = false; - this->GeneratorToolsetSet = false; - this->CurrentWorkingMode = NORMAL_MODE; - -#ifdef CMAKE_BUILD_WITH_CMAKE - this->VariableWatch = cm::make_unique<cmVariableWatch>(); -#endif - this->AddDefaultGenerators(); this->AddDefaultExtraGenerators(); if (role == RoleScript || role == RoleProject) { @@ -188,32 +173,25 @@ cmake::cmake(Role role, cmState::Mode mode) // Set up a list of source and header extensions. // These are used to find files when the extension is not given. { - auto fillExts = [](FileExtensions& exts, - std::initializer_list<const char*> extList) { + auto setupExts = [](FileExtensions& exts, + std::initializer_list<cm::string_view> extList) { // Fill ordered vector exts.ordered.reserve(extList.size()); - for (const char* ext : extList) { + for (cm::string_view ext : extList) { exts.ordered.emplace_back(ext); }; // Fill unordered set exts.unordered.insert(exts.ordered.begin(), exts.ordered.end()); }; - // Source extensions // The "c" extension MUST precede the "C" extension. - fillExts(this->SourceFileExtensions, - { "c", "C", "c++", "cc", "cpp", "cxx", "cu", "m", "M", "mm" }); - - // Header extensions - fillExts(this->HeaderFileExtensions, - { "h", "hh", "h++", "hm", "hpp", "hxx", "in", "txx" }); - - // Cuda extensions - fillExts(this->CudaFileExtensions, { "cu" }); - - // Fortran extensions - fillExts(this->FortranFileExtensions, - { "f", "F", "for", "f77", "f90", "f95", "f03" }); + setupExts(this->SourceFileExtensions, + { "c", "C", "c++", "cc", "cpp", "cxx", "cu", "m", "M", "mm" }); + setupExts(this->HeaderFileExtensions, + { "h", "hh", "h++", "hm", "hpp", "hxx", "in", "txx" }); + setupExts(this->CudaFileExtensions, { "cu" }); + setupExts(this->FortranFileExtensions, + { "f", "F", "for", "f77", "f90", "f95", "f03" }); } } @@ -226,7 +204,7 @@ cmake::~cmake() cmDeleteAll(this->Generators); } -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) Json::Value cmake::ReportVersionJson() const { Json::Value version = Json::objectValue; @@ -285,7 +263,7 @@ Json::Value cmake::ReportCapabilitiesJson() const std::string cmake::ReportCapabilities() const { std::string result; -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) Json::FastWriter writer; result = writer.write(this->ReportCapabilitiesJson()); #else @@ -318,7 +296,8 @@ bool cmake::SetCacheArgs(const std::vector<std::string>& args) return false; } } - std::string var, value; + std::string var; + std::string value; cmStateEnums::CacheEntryType type = cmStateEnums::UNINITIALIZED; if (cmState::ParseCacheEntry(entry, var, value, type)) { // The value is transformed if it is a filepath for example, so @@ -553,7 +532,7 @@ bool cmake::FindPackage(const std::vector<std::string>& args) } else if (mode == "COMPILE") { std::string includes = mf->GetSafeDefinition("PACKAGE_INCLUDE_DIRS"); std::vector<std::string> includeDirs; - cmSystemTools::ExpandListArgument(includes, includeDirs); + cmExpandList(includes, includeDirs); gg->CreateGenerationObjects(); cmLocalGenerator* lg = gg->LocalGenerators[0]; @@ -570,7 +549,7 @@ bool cmake::FindPackage(const std::vector<std::string>& args) std::string libs = mf->GetSafeDefinition("PACKAGE_LIBRARIES"); std::vector<std::string> libList; - cmSystemTools::ExpandListArgument(libs, libList); + cmExpandList(libs, libList); for (std::string const& lib : libList) { tgt->AddLinkLibrary(*mf, lib, GENERAL_LibraryType); } @@ -626,10 +605,9 @@ void cmake::LoadEnvironmentPresets() if (hasEnvironmentGenerator) { key = varValue; } else if (!this->GetIsInTryCompile()) { - std::string message = "Warning: Environment variable "; - message += name; - message += " will be ignored, because CMAKE_GENERATOR "; - message += "is not set."; + std::string message = + cmStrCat("Warning: Environment variable ", name, + " will be ignored, because CMAKE_GENERATOR is not set."); cmSystemTools::Message(message, "Warning"); } } @@ -763,6 +741,11 @@ void cmake::SetArgs(const std::vector<std::string>& args) cmSystemTools::ConvertToUnixSlashes(file); this->AddTraceSource(file); this->SetTrace(true); + } else if (arg.find("--trace-redirect=", 0) == 0) { + std::string file = arg.substr(strlen("--trace-redirect=")); + cmSystemTools::ConvertToUnixSlashes(file); + this->SetTraceFile(file); + this->SetTrace(true); } else if (arg.find("--trace", 0) == 0) { std::cout << "Running with trace output on.\n"; this->SetTrace(true); @@ -831,8 +814,8 @@ void cmake::SetArgs(const std::vector<std::string>& args) kdevError = "\nThe KDevelop3 generator is not supported anymore."; } - cmSystemTools::Error("Could not create named generator " + value + - kdevError); + cmSystemTools::Error( + cmStrCat("Could not create named generator ", value, kdevError)); this->PrintGeneratorList(); return; } @@ -893,6 +876,20 @@ cmake::LogLevel cmake::StringToLogLevel(const std::string& levelStr) return (it != levels.cend()) ? it->second : LogLevel::LOG_UNDEFINED; } +void cmake::SetTraceFile(const std::string& file) +{ + this->TraceFile.close(); + this->TraceFile.open(file.c_str()); + if (!this->TraceFile) { + std::stringstream ss; + ss << "Error opening trace file " << file << ": " + << cmSystemTools::GetLastSystemError(); + cmSystemTools::Error(ss.str()); + return; + } + std::cout << "Trace will be written to " << file << "\n"; +} + void cmake::SetDirectoriesFromFile(const std::string& arg) { // Check if the argument refers to a CMakeCache.txt or @@ -903,10 +900,8 @@ void cmake::SetDirectoriesFromFile(const std::string& arg) if (cmSystemTools::FileIsDirectory(arg)) { std::string path = cmSystemTools::CollapseFullPath(arg); cmSystemTools::ConvertToUnixSlashes(path); - std::string cacheFile = path; - cacheFile += "/CMakeCache.txt"; - std::string listFile = path; - listFile += "/CMakeLists.txt"; + std::string cacheFile = cmStrCat(path, "/CMakeCache.txt"); + std::string listFile = cmStrCat(path, "/CMakeLists.txt"); if (cmSystemTools::FileExists(cacheFile)) { cachePath = path; } @@ -991,7 +986,7 @@ int cmake::AddCMakePaths() this->AddCacheEntry("CMAKE_COMMAND", cmSystemTools::GetCMakeCommand().c_str(), "Path to CMake executable.", cmStateEnums::INTERNAL); -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP this->AddCacheEntry( "CMAKE_CTEST_COMMAND", cmSystemTools::GetCTestCommand().c_str(), "Path to ctest program executable.", cmStateEnums::INTERNAL); @@ -1017,7 +1012,7 @@ int cmake::AddCMakePaths() void cmake::AddDefaultExtraGenerators() { -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) this->ExtraGenerators.push_back(cmExtraCodeBlocksGenerator::GetFactory()); this->ExtraGenerators.push_back(cmExtraCodeLiteGenerator::GetFactory()); this->ExtraGenerators.push_back(cmExtraSublimeTextGenerator::GetFactory()); @@ -1161,12 +1156,10 @@ std::string cmake::FindCacheFile(const std::string& binaryDir) { std::string cachePath = binaryDir; cmSystemTools::ConvertToUnixSlashes(cachePath); - std::string cacheFile = cachePath; - cacheFile += "/CMakeCache.txt"; + std::string cacheFile = cmStrCat(cachePath, "/CMakeCache.txt"); if (!cmSystemTools::FileExists(cacheFile)) { // search in parent directories for cache - std::string cmakeFiles = cachePath; - cmakeFiles += "/CMakeFiles"; + std::string cmakeFiles = cmStrCat(cachePath, "/CMakeFiles"); if (cmSystemTools::FileExists(cmakeFiles)) { std::string cachePathFound = cmSystemTools::FileExistsInParentDirectories("CMakeCache.txt", @@ -1221,8 +1214,7 @@ void cmake::SetGlobalGenerator(cmGlobalGenerator* gg) int cmake::DoPreConfigureChecks() { // Make sure the Source directory contains a CMakeLists.txt file. - std::string srcList = this->GetHomeDirectory(); - srcList += "/CMakeLists.txt"; + std::string srcList = cmStrCat(this->GetHomeDirectory(), "/CMakeLists.txt"); if (!cmSystemTools::FileExists(srcList)) { std::ostringstream err; if (cmSystemTools::FileIsDirectory(this->GetHomeDirectory())) { @@ -1244,17 +1236,16 @@ int cmake::DoPreConfigureChecks() // do a sanity check on some values if (this->State->GetInitializedCacheValue("CMAKE_HOME_DIRECTORY")) { std::string cacheStart = - *this->State->GetInitializedCacheValue("CMAKE_HOME_DIRECTORY"); - cacheStart += "/CMakeLists.txt"; - std::string currentStart = this->GetHomeDirectory(); - currentStart += "/CMakeLists.txt"; + cmStrCat(*this->State->GetInitializedCacheValue("CMAKE_HOME_DIRECTORY"), + "/CMakeLists.txt"); + std::string currentStart = + cmStrCat(this->GetHomeDirectory(), "/CMakeLists.txt"); if (!cmSystemTools::SameFile(cacheStart, currentStart)) { - std::string message = "The source \""; - message += currentStart; - message += "\" does not match the source \""; - message += cacheStart; - message += "\" used to generate cache. "; - message += "Re-run cmake with a different source directory."; + std::string message = + cmStrCat("The source \"", currentStart, + "\" does not match the source \"", cacheStart, + "\" used to generate cache. Re-run cmake with a different " + "source directory."); cmSystemTools::Error(message); return -2; } @@ -1274,7 +1265,7 @@ struct SaveCacheEntry int cmake::HandleDeleteCacheVariables(const std::string& var) { std::vector<std::string> argsSplit; - cmSystemTools::ExpandListArgument(std::string(var), argsSplit, true); + cmExpandList(std::string(var), argsSplit, true); // erase the property to avoid infinite recursion this->State->SetGlobalProperty("__CMAKE_DELETE_CACHE_CHANGE_VARS_", ""); if (this->State->GetIsInTryCompile()) { @@ -1388,18 +1379,16 @@ int cmake::Configure() // so we cannot rely on command line options alone. Always ensure our // messenger is in sync with the cache. const char* value = this->State->GetCacheEntryValue("CMAKE_WARN_DEPRECATED"); - this->Messenger->SetSuppressDeprecatedWarnings(value && - cmSystemTools::IsOff(value)); + this->Messenger->SetSuppressDeprecatedWarnings(value && cmIsOff(value)); value = this->State->GetCacheEntryValue("CMAKE_ERROR_DEPRECATED"); - this->Messenger->SetDeprecatedWarningsAsErrors(cmSystemTools::IsOn(value)); + this->Messenger->SetDeprecatedWarningsAsErrors(cmIsOn(value)); value = this->State->GetCacheEntryValue("CMAKE_SUPPRESS_DEVELOPER_WARNINGS"); - this->Messenger->SetSuppressDevWarnings(cmSystemTools::IsOn(value)); + this->Messenger->SetSuppressDevWarnings(cmIsOn(value)); value = this->State->GetCacheEntryValue("CMAKE_SUPPRESS_DEVELOPER_ERRORS"); - this->Messenger->SetDevWarningsAsErrors(value && - cmSystemTools::IsOff(value)); + this->Messenger->SetDevWarningsAsErrors(value && cmIsOff(value)); int ret = this->ActualConfigure(); const char* delCacheVars = @@ -1459,12 +1448,11 @@ int cmake::ActualConfigure() this->State->GetInitializedCacheValue("CMAKE_GENERATOR"); if (genName) { if (!this->GlobalGenerator->MatchesGeneratorName(*genName)) { - std::string message = "Error: generator : "; - message += this->GlobalGenerator->GetName(); - message += "\nDoes not match the generator used previously: "; - message += *genName; - message += "\nEither remove the CMakeCache.txt file and CMakeFiles " - "directory or choose a different binary directory."; + std::string message = + cmStrCat("Error: generator : ", this->GlobalGenerator->GetName(), + "\nDoes not match the generator used previously: ", *genName, + "\nEither remove the CMakeCache.txt file and CMakeFiles " + "directory or choose a different binary directory."); cmSystemTools::Error(message); return -2; } @@ -1482,12 +1470,11 @@ int cmake::ActualConfigure() if (const std::string* instance = this->State->GetInitializedCacheValue("CMAKE_GENERATOR_INSTANCE")) { if (this->GeneratorInstanceSet && this->GeneratorInstance != *instance) { - std::string message = "Error: generator instance: "; - message += this->GeneratorInstance; - message += "\nDoes not match the instance used previously: "; - message += *instance; - message += "\nEither remove the CMakeCache.txt file and CMakeFiles " - "directory or choose a different binary directory."; + std::string message = + cmStrCat("Error: generator instance: ", this->GeneratorInstance, + "\nDoes not match the instance used previously: ", *instance, + "\nEither remove the CMakeCache.txt file and CMakeFiles " + "directory or choose a different binary directory."); cmSystemTools::Error(message); return -2; } @@ -1501,12 +1488,11 @@ int cmake::ActualConfigure() this->State->GetInitializedCacheValue("CMAKE_GENERATOR_PLATFORM")) { if (this->GeneratorPlatformSet && this->GeneratorPlatform != *platformName) { - std::string message = "Error: generator platform: "; - message += this->GeneratorPlatform; - message += "\nDoes not match the platform used previously: "; - message += *platformName; - message += "\nEither remove the CMakeCache.txt file and CMakeFiles " - "directory or choose a different binary directory."; + std::string message = cmStrCat( + "Error: generator platform: ", this->GeneratorPlatform, + "\nDoes not match the platform used previously: ", *platformName, + "\nEither remove the CMakeCache.txt file and CMakeFiles " + "directory or choose a different binary directory."); cmSystemTools::Error(message); return -2; } @@ -1519,12 +1505,11 @@ int cmake::ActualConfigure() if (const std::string* tsName = this->State->GetInitializedCacheValue("CMAKE_GENERATOR_TOOLSET")) { if (this->GeneratorToolsetSet && this->GeneratorToolset != *tsName) { - std::string message = "Error: generator toolset: "; - message += this->GeneratorToolset; - message += "\nDoes not match the toolset used previously: "; - message += *tsName; - message += "\nEither remove the CMakeCache.txt file and CMakeFiles " - "directory or choose a different binary directory."; + std::string message = + cmStrCat("Error: generator toolset: ", this->GeneratorToolset, + "\nDoes not match the toolset used previously: ", *tsName, + "\nEither remove the CMakeCache.txt file and CMakeFiles " + "directory or choose a different binary directory."); cmSystemTools::Error(message); return -2; } @@ -1544,7 +1529,7 @@ int cmake::ActualConfigure() this->TruncateOutputLog("CMakeError.log"); } -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) this->FileAPI = cm::make_unique<cmFileAPI>(this); this->FileAPI->ReadQueries(); #endif @@ -1782,8 +1767,8 @@ int cmake::Run(const std::vector<std::string>& args, bool noconfigure) "Build files cannot be regenerated correctly."); return ret; } - std::string message = "Build files have been written to: "; - message += this->GetHomeOutputDirectory(); + std::string message = cmStrCat("Build files have been written to: ", + this->GetHomeOutputDirectory()); this->UpdateProgress(message, -1); return ret; } @@ -1812,7 +1797,7 @@ int cmake::Generate() // for the Visual Studio and Xcode generators.) this->SaveCache(this->GetHomeOutputDirectory()); -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) this->FileAPI->WriteReplies(); #endif @@ -1827,15 +1812,13 @@ void cmake::AddCacheEntry(const std::string& key, const char* value, this->UnwatchUnusedCli(key); if (key == "CMAKE_WARN_DEPRECATED") { - this->Messenger->SetSuppressDeprecatedWarnings( - value && cmSystemTools::IsOff(value)); + this->Messenger->SetSuppressDeprecatedWarnings(value && cmIsOff(value)); } else if (key == "CMAKE_ERROR_DEPRECATED") { - this->Messenger->SetDeprecatedWarningsAsErrors(cmSystemTools::IsOn(value)); + this->Messenger->SetDeprecatedWarningsAsErrors(cmIsOn(value)); } else if (key == "CMAKE_SUPPRESS_DEVELOPER_WARNINGS") { - this->Messenger->SetSuppressDevWarnings(cmSystemTools::IsOn(value)); + this->Messenger->SetSuppressDevWarnings(cmIsOn(value)); } else if (key == "CMAKE_SUPPRESS_DEVELOPER_ERRORS") { - this->Messenger->SetDevWarningsAsErrors(value && - cmSystemTools::IsOff(value)); + this->Messenger->SetDevWarningsAsErrors(value && cmIsOff(value)); } } @@ -1918,7 +1901,7 @@ void cmake::AddDefaultGenerators() this->Generators.push_back(cmGlobalMinGWMakefileGenerator::NewFactory()); #endif this->Generators.push_back(cmGlobalUnixMakefileGenerator3::NewFactory()); -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) # if defined(__linux__) || defined(_WIN32) this->Generators.push_back(cmGlobalGhsMultiGenerator::NewFactory()); # endif @@ -1944,8 +1927,8 @@ int cmake::LoadCache() // could we not read the cache if (!this->LoadCache(this->GetHomeOutputDirectory())) { // if it does exist, but isn't readable then warn the user - std::string cacheFile = this->GetHomeOutputDirectory(); - cacheFile += "/CMakeCache.txt"; + std::string cacheFile = + cmStrCat(this->GetHomeOutputDirectory(), "/CMakeCache.txt"); if (cmSystemTools::FileExists(cacheFile)) { cmSystemTools::Error( "There is a CMakeCache.txt file for the current binary tree but " @@ -2077,7 +2060,7 @@ std::vector<cmDocumentationEntry> cmake::GetGeneratorsDocumentation() void cmake::PrintGeneratorList() { -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP cmDocumentation doc; auto generators = this->GetGeneratorsDocumentation(); doc.AppendSection("Generators", generators); @@ -2099,7 +2082,8 @@ void cmake::UpdateConversionPathTable() ". CMake can not open file."); cmSystemTools::ReportLastSystemError("CMake can not open file."); } else { - std::string a, b; + std::string a; + std::string b; while (!table.eof()) { // two entries per line table >> a; @@ -2182,7 +2166,7 @@ int cmake::CheckBuildSystem() // If any byproduct of makefile generation is missing we must re-run. std::vector<std::string> products; if (const char* productStr = mf.GetDefinition("CMAKE_MAKEFILE_PRODUCTS")) { - cmSystemTools::ExpandListArgument(productStr, products); + cmExpandList(productStr, products); } for (std::string const& p : products) { if (!(cmSystemTools::FileExists(p) || cmSystemTools::FileIsSymlink(p))) { @@ -2201,8 +2185,8 @@ int cmake::CheckBuildSystem() const char* dependsStr = mf.GetDefinition("CMAKE_MAKEFILE_DEPENDS"); const char* outputsStr = mf.GetDefinition("CMAKE_MAKEFILE_OUTPUTS"); if (dependsStr && outputsStr) { - cmSystemTools::ExpandListArgument(dependsStr, depends); - cmSystemTools::ExpandListArgument(outputsStr, outputs); + cmExpandList(dependsStr, depends); + cmExpandList(outputsStr, outputs); } if (depends.empty() || outputs.empty()) { // Not enough information was provided to do the test. Just rerun. @@ -2274,9 +2258,7 @@ int cmake::CheckBuildSystem() void cmake::TruncateOutputLog(const char* fname) { - std::string fullPath = this->GetHomeOutputDirectory(); - fullPath += "/"; - fullPath += fname; + std::string fullPath = cmStrCat(this->GetHomeOutputDirectory(), '/', fname); struct stat st; if (::stat(fullPath.c_str(), &st)) { return; @@ -2293,14 +2275,6 @@ void cmake::TruncateOutputLog(const char* fname) } } -inline std::string removeQuotes(const std::string& s) -{ - if (s.front() == '\"' && s.back() == '\"') { - return s.substr(1, s.size() - 2); - } - return s; -} - void cmake::MarkCliAsUsed(const std::string& variable) { this->UsedCliVariables[variable] = true; @@ -2308,13 +2282,13 @@ void cmake::MarkCliAsUsed(const std::string& variable) void cmake::GenerateGraphViz(const std::string& fileName) const { -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP cmGraphVizWriter gvWriter(this->GetGlobalGenerator()); - std::string settingsFile = this->GetHomeOutputDirectory(); - settingsFile += "/CMakeGraphVizOptions.cmake"; - std::string fallbackSettingsFile = this->GetHomeDirectory(); - fallbackSettingsFile += "/CMakeGraphVizOptions.cmake"; + std::string settingsFile = + cmStrCat(this->GetHomeOutputDirectory(), "/CMakeGraphVizOptions.cmake"); + std::string fallbackSettingsFile = + cmStrCat(this->GetHomeDirectory(), "/CMakeGraphVizOptions.cmake"); gvWriter.ReadSettings(settingsFile, fallbackSettingsFile); gvWriter.WritePerTargetFiles(fileName); @@ -2411,8 +2385,7 @@ int cmake::GetSystemInformation(std::vector<std::string>& args) // no option assume it is the output file else { if (!cmSystemTools::FileIsFullPath(arg)) { - resultFile = cwd; - resultFile += "/"; + resultFile = cmStrCat(cwd, '/'); } resultFile += arg; writeToStdout = false; @@ -2421,12 +2394,10 @@ int cmake::GetSystemInformation(std::vector<std::string>& args) // we have to find the module directory, so we can copy the files this->AddCMakePaths(); - std::string modulesPath = cmSystemTools::GetCMakeRoot(); - modulesPath += "/Modules"; - std::string inFile = modulesPath; - inFile += "/SystemInformation.cmake"; - std::string outFile = destPath; - outFile += "/CMakeLists.txt"; + std::string modulesPath = + cmStrCat(cmSystemTools::GetCMakeRoot(), "/Modules"); + std::string inFile = cmStrCat(modulesPath, "/SystemInformation.cmake"); + std::string outFile = cmStrCat(destPath, "/CMakeLists.txt"); // Copy file if (!cmsys::SystemTools::CopyFileAlways(inFile, outFile)) { @@ -2437,8 +2408,7 @@ int cmake::GetSystemInformation(std::vector<std::string>& args) // do we write to a file or to stdout? if (resultFile.empty()) { - resultFile = cwd; - resultFile += "/__cmake_systeminformation/results.txt"; + resultFile = cmStrCat(cwd, "/__cmake_systeminformation/results.txt"); } { @@ -2494,8 +2464,7 @@ static bool cmakeCheckStampFile(const std::string& stampName) // conjunction with cmLocalVisualStudio7Generator to avoid // repeatedly re-running CMake when the user rebuilds the entire // solution. - std::string stampDepends = stampName; - stampDepends += ".depend"; + std::string stampDepends = cmStrCat(stampName, ".depend"); #if defined(_WIN32) || defined(__CYGWIN__) cmsys::ifstream fin(stampDepends.c_str(), std::ios::in | std::ios::binary); #else @@ -2586,7 +2555,7 @@ std::vector<std::string> cmake::GetDebugConfigs() if (const char* config_list = this->State->GetGlobalProperty("DEBUG_CONFIGURATIONS")) { // Expand the specified list and convert to upper-case. - cmSystemTools::ExpandListArgument(config_list, configs); + cmExpandList(config_list, configs); std::transform(configs.begin(), configs.end(), configs.begin(), cmSystemTools::UpperCase); } @@ -2657,7 +2626,7 @@ int cmake::Build(int jobs, const std::string& dir, const char* cachedVerbose = this->State->GetCacheEntryValue("CMAKE_VERBOSE_MAKEFILE"); - if (cmSystemTools::IsOn(cachedVerbose)) { + if (cmIsOn(cachedVerbose)) { verbose = true; } @@ -2705,8 +2674,8 @@ int cmake::Build(int jobs, const std::string& dir, "Build files cannot be regenerated correctly."); return ret; } - std::string message = "Build files have been written to: "; - message += this->GetHomeOutputDirectory(); + std::string message = cmStrCat("Build files have been written to: ", + this->GetHomeOutputDirectory()); this->UpdateProgress(message, -1); // Restore the previously set directories to their original value. @@ -2767,9 +2736,9 @@ bool cmake::Open(const std::string& dir, bool dryRun) void cmake::WatchUnusedCli(const std::string& var) { -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP this->VariableWatch->AddWatch(var, cmWarnUnusedCliWarning, this); - if (this->UsedCliVariables.find(var) == this->UsedCliVariables.end()) { + if (!cmContains(this->UsedCliVariables, var)) { this->UsedCliVariables[var] = false; } #endif @@ -2777,7 +2746,7 @@ void cmake::WatchUnusedCli(const std::string& var) void cmake::UnwatchUnusedCli(const std::string& var) { -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP this->VariableWatch->RemoveWatch(var, cmWarnUnusedCliWarning); this->UsedCliVariables.erase(var); #endif @@ -2785,7 +2754,7 @@ void cmake::UnwatchUnusedCli(const std::string& var) void cmake::RunCheckForUnusedVariables() { -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP bool haveUnused = false; std::ostringstream msg; msg << "Manually-specified variables were not used by the project:"; diff --git a/Source/cmake.h b/Source/cmake.h index 6aa00e1..081e120 100644 --- a/Source/cmake.h +++ b/Source/cmake.h @@ -13,6 +13,7 @@ #include <unordered_set> #include <vector> +#include "cmGeneratedFileStream.h" #include "cmInstalledFile.h" #include "cmListFileCache.h" #include "cmMessageType.h" @@ -20,7 +21,7 @@ #include "cmStateSnapshot.h" #include "cmStateTypes.h" -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) # include "cm_jsoncpp_value.h" #endif @@ -145,7 +146,7 @@ public: cmake(cmake const&) = delete; cmake& operator=(cmake const&) = delete; -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) Json::Value ReportVersionJson() const; Json::Value ReportCapabilitiesJson() const; #endif @@ -334,7 +335,7 @@ public: //! this is called by generators to update the progress void UpdateProgress(const std::string& msg, float prog); -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) //! Get the variable watch object cmVariableWatch* GetVariableWatch() { return this->VariableWatch.get(); } #endif @@ -401,6 +402,9 @@ public: { return this->TraceOnlyThisSources; } + cmGeneratedFileStream& GetTraceFile() { return this->TraceFile; } + void SetTraceFile(std::string const& file); + bool GetWarnUninitialized() { return this->WarnUninitialized; } void SetWarnUninitialized(bool b) { this->WarnUninitialized = b; } bool GetWarnUnused() { return this->WarnUnused; } @@ -509,14 +513,14 @@ protected: void AddDefaultGenerators(); void AddDefaultExtraGenerators(); - cmGlobalGenerator* GlobalGenerator; + cmGlobalGenerator* GlobalGenerator = nullptr; std::map<std::string, DiagLevel> DiagLevels; std::string GeneratorInstance; std::string GeneratorPlatform; std::string GeneratorToolset; - bool GeneratorInstanceSet; - bool GeneratorPlatformSet; - bool GeneratorToolsetSet; + bool GeneratorInstanceSet = false; + bool GeneratorPlatformSet = false; + bool GeneratorToolsetSet = false; //! read in a cmake list file to initialize the cache void ReadListFile(const std::vector<std::string>& args, @@ -543,14 +547,15 @@ protected: private: ProgressCallbackType ProgressCallback; - WorkingMode CurrentWorkingMode; - bool DebugOutput; - bool Trace; - bool TraceExpand; - bool WarnUninitialized; - bool WarnUnused; - bool WarnUnusedCli; - bool CheckSystemVars; + WorkingMode CurrentWorkingMode = NORMAL_MODE; + bool DebugOutput = false; + bool Trace = false; + bool TraceExpand = false; + cmGeneratedFileStream TraceFile; + bool WarnUninitialized = false; + bool WarnUnused = false; + bool WarnUnusedCli = true; + bool CheckSystemVars = false; std::map<std::string, bool> UsedCliVariables; std::string CMakeEditCommand; std::string CXXEnvironment; @@ -564,13 +569,13 @@ private: FileExtensions HeaderFileExtensions; FileExtensions CudaFileExtensions; FileExtensions FortranFileExtensions; - bool ClearBuildSystem; - bool DebugTryCompile; + bool ClearBuildSystem = false; + bool DebugTryCompile = false; std::unique_ptr<cmFileTimeCache> FileTimeCache; std::string GraphVizFile; InstalledFilesMap InstalledFiles; -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) std::unique_ptr<cmVariableWatch> VariableWatch; std::unique_ptr<cmFileAPI> FileAPI; #endif diff --git a/Source/cmakemain.cxx b/Source/cmakemain.cxx index 10a6825..2b51a2a 100644 --- a/Source/cmakemain.cxx +++ b/Source/cmakemain.cxx @@ -12,7 +12,7 @@ #include "cmake.h" #include "cmcmd.h" -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP # include "cmDocumentation.h" # include "cmDynamicLoader.h" #endif @@ -20,7 +20,7 @@ #include "cm_uv.h" #include "cmsys/Encoding.hxx" -#if defined(_WIN32) && defined(CMAKE_BUILD_WITH_CMAKE) +#if defined(_WIN32) && !defined(CMAKE_BOOTSTRAP) # include "cmsys/ConsoleBuf.hxx" #endif @@ -33,7 +33,7 @@ #include <vector> namespace { -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP const char* cmDocumentationName[][2] = { { nullptr, " cmake - Cross-Platform Makefile Generator." }, { nullptr, nullptr } @@ -80,6 +80,8 @@ const char* cmDocumentationOptions[][2] = { { "--trace-expand", "Put cmake in trace mode with variable expansion." }, { "--trace-source=<file>", "Trace only this CMake file/module. Multiple options allowed." }, + { "--trace-redirect=<file>", + "Redirect trace output to a file instead of stderr." }, { "--warn-uninitialized", "Warn about uninitialized values." }, { "--warn-unused-vars", "Warn about unused variables." }, { "--no-warn-unused-cli", "Don't warn about command line options." }, @@ -136,11 +138,9 @@ void cmakemainProgressCallback(const std::string& m, float prog, cmake* cm) cmMakefile* mf = cmakemainGetMakefile(cm); std::string dir; if (mf && cmHasLiteralPrefix(m, "Configuring") && (prog < 0)) { - dir = " "; - dir += mf->GetCurrentSourceDirectory(); + dir = cmStrCat(' ', mf->GetCurrentSourceDirectory()); } else if (mf && cmHasLiteralPrefix(m, "Generating")) { - dir = " "; - dir += mf->GetCurrentBinaryDirectory(); + dir = cmStrCat(' ', mf->GetCurrentBinaryDirectory()); } if ((prog < 0) || (!dir.empty())) { @@ -156,7 +156,7 @@ int do_cmake(int ac, char const* const* av) return 1; } -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP cmDocumentation doc; doc.addCMakeStandardDocSections(); if (doc.CheckOptions(ac, av)) { @@ -321,7 +321,7 @@ int extract_job_number(int& index, char const* current, char const* next, unsigned long numJobs = 0; if (jobString.empty()) { jobs = cmake::DEFAULT_BUILD_PARALLEL_LEVEL; - } else if (cmSystemTools::StringToULong(jobString.c_str(), &numJobs)) { + } else if (cmStrToULong(jobString, &numJobs)) { if (numJobs == 0) { std::cerr << "The <jobs> value requires a positive integer argument.\n\n"; @@ -339,7 +339,7 @@ int extract_job_number(int& index, char const* current, char const* next, int do_build(int ac, char const* const* av) { -#ifndef CMAKE_BUILD_WITH_CMAKE +#ifdef CMAKE_BOOTSTRAP std::cerr << "This cmake does not support --build\n"; return -1; #else @@ -439,7 +439,7 @@ int do_build(int ac, char const* const* av) jobs = cmake::DEFAULT_BUILD_PARALLEL_LEVEL; } else { unsigned long numJobs = 0; - if (cmSystemTools::StringToULong(parallel.c_str(), &numJobs)) { + if (cmStrToULong(parallel, &numJobs)) { if (numJobs == 0) { std::cerr << "The CMAKE_BUILD_PARALLEL_LEVEL environment variable " "requires a positive integer argument.\n\n"; @@ -503,7 +503,7 @@ int do_build(int ac, char const* const* av) int do_install(int ac, char const* const* av) { -#ifndef CMAKE_BUILD_WITH_CMAKE +#ifdef CMAKE_BOOTSTRAP std::cerr << "This cmake does not support --install\n"; return -1; #else @@ -624,7 +624,7 @@ int do_install(int ac, char const* const* av) int do_open(int ac, char const* const* av) { -#ifndef CMAKE_BUILD_WITH_CMAKE +#ifdef CMAKE_BOOTSTRAP std::cerr << "This cmake does not support --open\n"; return -1; #else @@ -669,7 +669,7 @@ int do_open(int ac, char const* const* av) int main(int ac, char const* const* av) { cmSystemTools::EnsureStdPipes(); -#if defined(_WIN32) && defined(CMAKE_BUILD_WITH_CMAKE) +#if defined(_WIN32) && !defined(CMAKE_BOOTSTRAP) // Replace streambuf so we can output Unicode to console cmsys::ConsoleBuf::Manager consoleOut(std::cout); consoleOut.SetUTF8Pipes(); @@ -699,7 +699,7 @@ int main(int ac, char const* const* av) } } int ret = do_cmake(ac, av); -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP cmDynamicLoader::FlushCache(); #endif uv_loop_close(uv_default_loop()); diff --git a/Source/cmcmd.cxx b/Source/cmcmd.cxx index aecc978..0832e2f 100644 --- a/Source/cmcmd.cxx +++ b/Source/cmcmd.cxx @@ -19,18 +19,18 @@ #include "cmVersion.h" #include "cmake.h" -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) # include "cmDependsFortran.h" // For -E cmake_copy_f90_mod callback. # include "cmServer.h" # include "cmServerConnection.h" #endif -#if defined(CMAKE_BUILD_WITH_CMAKE) && defined(_WIN32) +#if !defined(CMAKE_BOOTSTRAP) && defined(_WIN32) # include "bindexplib.h" # include "cmsys/ConsoleBuf.hxx" #endif -#if defined(CMAKE_BUILD_WITH_CMAKE) && defined(_WIN32) && !defined(__CYGWIN__) +#if !defined(CMAKE_BOOTSTRAP) && defined(_WIN32) && !defined(__CYGWIN__) # include "cmVisualStudioWCEPlatformParser.h" #endif @@ -38,10 +38,8 @@ #include "cmsys/FStream.hxx" #include "cmsys/Process.h" #include "cmsys/Terminal.h" -#include <algorithm> #include <array> #include <iostream> -#include <iterator> #include <memory> #include <sstream> #include <stdio.h> @@ -61,7 +59,7 @@ void CMakeCommandUsage(const char* program) { std::ostringstream errorStream; -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP /* clang-format off */ errorStream << "cmake version " << cmVersion::GetCMakeVersion() << "\n"; @@ -175,7 +173,7 @@ static int HandleIWYU(const std::string& runCmd, // Construct the iwyu command line by taking what was given // and adding all the arguments we give to the compiler. std::vector<std::string> iwyu_cmd; - cmSystemTools::ExpandListArgument(runCmd, iwyu_cmd, true); + cmExpandList(runCmd, iwyu_cmd, true); cmAppend(iwyu_cmd, orig_cmd.begin() + 1, orig_cmd.end()); // Run the iwyu command line. Capture its stderr and hide its stdout. // Ignore its return code because the tool always returns non-zero. @@ -204,8 +202,7 @@ static int HandleTidy(const std::string& runCmd, const std::string& sourceFile, // automatically skip over the compiler itself and extract the // options. int ret; - std::vector<std::string> tidy_cmd = - cmSystemTools::ExpandedListArgument(runCmd, true); + std::vector<std::string> tidy_cmd = cmExpandedList(runCmd, true); tidy_cmd.push_back(sourceFile); tidy_cmd.emplace_back("--"); cmAppend(tidy_cmd, orig_cmd); @@ -266,7 +263,7 @@ static int HandleCppLint(const std::string& runCmd, { // Construct the cpplint command line. std::vector<std::string> cpplint_cmd; - cmSystemTools::ExpandListArgument(runCmd, cpplint_cmd, true); + cmExpandList(runCmd, cpplint_cmd, true); cpplint_cmd.push_back(sourceFile); // Run the cpplint command line. Capture its output. @@ -295,7 +292,7 @@ static int HandleCppCheck(const std::string& runCmd, { // Construct the cpplint command line. std::vector<std::string> cppcheck_cmd; - cmSystemTools::ExpandListArgument(runCmd, cppcheck_cmd, true); + cmExpandList(runCmd, cppcheck_cmd, true); // extract all the -D, -U, and -I options from the compile line for (auto const& opt : orig_cmd) { if (opt.size() > 2) { @@ -408,7 +405,7 @@ int cmcmd::HandleCoCompileCommands(std::vector<std::string> const& args) if (cmHasLiteralPrefix(arg, "--source=")) { sourceFile = arg.substr(9); } else if (cmHasLiteralPrefix(arg, "--launcher=")) { - cmSystemTools::ExpandListArgument(arg.substr(11), launchers, true); + cmExpandList(arg.substr(11), launchers, true); } else { // if it was not a co-compiler or --source/--launcher then error std::cerr << "__run_co_compile given unknown argument: " << arg @@ -561,7 +558,7 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string> const& args) return 0; } -#if defined(_WIN32) && defined(CMAKE_BUILD_WITH_CMAKE) +#if defined(_WIN32) && !defined(CMAKE_BOOTSTRAP) else if (args[1] == "__create_def") { if (args.size() < 4) { std::cerr @@ -654,7 +651,7 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string> const& args) return 1; } -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) if (args[1] == "environment") { for (auto const& env : cmSystemTools::GetEnvironmentVariables()) { std::cout << env << std::endl; @@ -766,8 +763,10 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string> const& args) if (args[1] == "time" && args.size() > 2) { std::vector<std::string> command(args.begin() + 2, args.end()); - clock_t clock_start, clock_finish; - time_t time_start, time_finish; + clock_t clock_start; + clock_t clock_finish; + time_t time_start; + time_t time_finish; time(&time_start); clock_start = clock(); @@ -838,8 +837,7 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string> const& args) // Command to start progress for a build if (args[1] == "cmake_progress_start" && args.size() == 4) { // basically remove the directory - std::string dirName = args[2]; - dirName += "/Progress"; + std::string dirName = cmStrCat(args[2], "/Progress"); cmSystemTools::RemoveADirectory(dirName); // is the last argument a filename that exists? @@ -856,8 +854,7 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string> const& args) if (count) { cmSystemTools::MakeDirectory(dirName); // write the count into the directory - std::string fName = dirName; - fName += "/count.txt"; + std::string fName = cmStrCat(dirName, "/count.txt"); FILE* progFile = cmsys::SystemTools::Fopen(fName, "w"); if (progFile) { fprintf(progFile, "%i\n", count); @@ -946,8 +943,7 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string> const& args) if (args.size() >= 9 && args[8].length() >= 8 && args[8].substr(0, 8) == "--color=") { // Enable or disable color based on the switch value. - color = - (args[8].size() == 8 || cmSystemTools::IsOn(args[8].substr(8))); + color = (args[8].size() == 8 || cmIsOn(args[8].substr(8))); } } else { // Support older signature for existing makefiles: @@ -994,7 +990,7 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string> const& args) return cmcmd::ExecuteLinkScript(args); } -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP // Internal CMake ninja dependency scanning support. if (args[1] == "cmake_ninja_depends") { return cmcmd_cmake_ninja_depends(args.begin() + 2, args.end()); @@ -1029,7 +1025,7 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string> const& args) return cmcmd::ExecuteEchoColor(args); } -#ifdef CMAKE_BUILD_WITH_CMAKE +#ifndef CMAKE_BOOTSTRAP if ((args[1] == "cmake_autogen") && (args.size() >= 4)) { cmQtAutoMocUic autoGen; std::string const& infoDir = args[2]; @@ -1076,11 +1072,7 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string> const& args) } } else if (cmHasLiteralPrefix(arg, "--format=")) { format = arg.substr(9); - bool isKnown = - std::find(cm::cbegin(knownFormats), cm::cend(knownFormats), - format) != cm::cend(knownFormats); - - if (!isKnown) { + if (!cmContains(knownFormats, format)) { cmSystemTools::Error("Unknown -E tar --format= argument: " + format); return 1; @@ -1210,7 +1202,7 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string> const& args) return 1; } } -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) cmConnection* conn; if (isDebug) { conn = new cmServerStdIoConnection; @@ -1231,7 +1223,7 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string> const& args) return 1; } -#if defined(CMAKE_BUILD_WITH_CMAKE) +#if !defined(CMAKE_BOOTSTRAP) // Internal CMake Fortran module support. if (args[1] == "cmake_copy_f90_mod" && args.size() >= 4) { return cmDependsFortran::CopyModule(args) ? 0 : 1; @@ -1352,14 +1344,12 @@ bool cmcmd::SymlinkInternal(std::string const& file, std::string const& link) static void cmcmdProgressReport(std::string const& dir, std::string const& num) { - std::string dirName = dir; - dirName += "/Progress"; + std::string dirName = cmStrCat(dir, "/Progress"); std::string fName; FILE* progFile; // read the count - fName = dirName; - fName += "/count.txt"; + fName = cmStrCat(dirName, "/count.txt"); progFile = cmsys::SystemTools::Fopen(fName, "r"); int count = 0; if (!progFile) { @@ -1374,8 +1364,7 @@ static void cmcmdProgressReport(std::string const& dir, std::string const& num) for (const char* c = last;; ++c) { if (*c == ',' || *c == '\0') { if (c != last) { - fName = dirName; - fName += "/"; + fName = cmStrCat(dirName, '/'); fName.append(last, c - last); progFile = cmsys::SystemTools::Fopen(fName, "w"); if (progFile) { @@ -1412,7 +1401,7 @@ int cmcmd::ExecuteEchoColor(std::vector<std::string> const& args) // Enable or disable color based on the switch value. std::string value = arg.substr(9); if (!value.empty()) { - enabled = cmSystemTools::IsOn(value); + enabled = cmIsOn(value); } } else if (cmHasLiteralPrefix(arg, "--progress-dir=")) { progressDir = arg.substr(15); @@ -1464,7 +1453,7 @@ int cmcmd::ExecuteLinkScript(std::vector<std::string> const& args) bool verbose = false; if (args.size() >= 4) { if (args[3].find("--verbose=") == 0) { - if (!cmSystemTools::IsOff(args[3].substr(10))) { + if (!cmIsOff(args[3].substr(10))) { verbose = true; } } @@ -1547,7 +1536,7 @@ int cmcmd::ExecuteLinkScript(std::vector<std::string> const& args) int cmcmd::WindowsCEEnvironment(const char* version, const std::string& name) { -#if defined(CMAKE_BUILD_WITH_CMAKE) && defined(_WIN32) && !defined(__CYGWIN__) +#if !defined(CMAKE_BOOTSTRAP) && defined(_WIN32) && !defined(__CYGWIN__) cmVisualStudioWCEPlatformParser parser(name.c_str()); parser.ParseVersion(version); if (parser.Found()) { @@ -1605,7 +1594,7 @@ private: // still works. int cmcmd::VisualStudioLink(std::vector<std::string> const& args, int type) { -#if defined(_WIN32) && defined(CMAKE_BUILD_WITH_CMAKE) +#if defined(_WIN32) && !defined(CMAKE_BOOTSTRAP) // Replace streambuf so we output in the system codepage. CMake is set up // to output in Unicode (see SetUTF8Pipes) but the Visual Studio linker // outputs using the system codepage so we need to change behavior when diff --git a/Source/ctest.cxx b/Source/ctest.cxx index 3b3630f..77a84fd 100644 --- a/Source/ctest.cxx +++ b/Source/ctest.cxx @@ -8,7 +8,7 @@ #include "cmSystemTools.h" #include "cmsys/Encoding.hxx" -#if defined(_WIN32) && defined(CMAKE_BUILD_WITH_CMAKE) +#if defined(_WIN32) && !defined(CMAKE_BOOTSTRAP) # include "cmsys/ConsoleBuf.hxx" #endif #include <iostream> @@ -144,7 +144,7 @@ static const char* cmDocumentationOptions[][2] = { int main(int argc, char const* const* argv) { cmSystemTools::EnsureStdPipes(); -#if defined(_WIN32) && defined(CMAKE_BUILD_WITH_CMAKE) +#if defined(_WIN32) && !defined(CMAKE_BOOTSTRAP) // Replace streambuf so we can output Unicode to console cmsys::ConsoleBuf::Manager consoleOut(std::cout); consoleOut.SetUTF8Pipes(); |