diff options
Diffstat (limited to 'Source')
274 files changed, 9559 insertions, 4945 deletions
diff --git a/Source/CMakeLists.txt b/Source/CMakeLists.txt index 621ac3e..7722c19 100644 --- a/Source/CMakeLists.txt +++ b/Source/CMakeLists.txt @@ -111,6 +111,8 @@ ENDIF(CMAKE_USE_ELF_PARSER) # Sources for CMakeLib # SET(SRCS + cmStandardIncludes.cxx + cmArchiveWrite.cxx cmBootstrapCommands.cxx cmCacheManager.cxx cmCacheManager.h @@ -129,6 +131,8 @@ SET(SRCS cmComputeTargetDepends.cxx cmCustomCommand.cxx cmCustomCommand.h + cmCustomCommandGenerator.cxx + cmCustomCommandGenerator.h cmDefinitions.cxx cmDefinitions.h cmDepends.cxx @@ -154,6 +158,8 @@ SET(SRCS cmDocumentationFormatterText.cxx cmDocumentationFormatterUsage.cxx cmDocumentationSection.cxx + cmDocumentCompileDefinitions.h + cmDocumentGeneratorExpressions.h cmDocumentVariables.cxx cmDynamicLoader.cxx cmDynamicLoader.h @@ -167,6 +173,8 @@ SET(SRCS cmExportFileGenerator.cxx cmExportInstallFileGenerator.h cmExportInstallFileGenerator.cxx + cmExtraCodeBlocksGenerator.cxx + cmExtraCodeBlocksGenerator.h cmExtraEclipseCDT4Generator.cxx cmExtraEclipseCDT4Generator.h cmFileTimeComparison.cxx @@ -179,6 +187,8 @@ SET(SRCS cmGlobalUnixMakefileGenerator3.cxx cmGlobalUnixMakefileGenerator3.h cmGraphAdjacencyList.h + cmGraphVizWriter.cxx + cmGraphVizWriter.h cmInstallGenerator.h cmInstallGenerator.cxx cmInstallExportGenerator.cxx @@ -256,10 +266,6 @@ IF(UNIX) SET(SRCS ${SRCS} cmGlobalKdevelopGenerator.cxx) ENDIF(UNIX) -IF(NOT CYGWIN) - SET(SRCS ${SRCS} cmExtraCodeBlocksGenerator.cxx) -ENDIF(NOT CYGWIN) - # XCode only works on apple IF(APPLE) SET(SRCS ${SRCS} @@ -332,7 +338,7 @@ ENDIF (WIN32) # create a library used by the command line and the GUI ADD_LIBRARY(CMakeLib ${SRCS}) -TARGET_LINK_LIBRARIES(CMakeLib cmsys +TARGET_LINK_LIBRARIES(CMakeLib cmsys ${CMAKE_EXPAT_LIBRARIES} ${CMAKE_ZLIB_LIBRARIES} ${CMAKE_TAR_LIBRARIES} ${CMAKE_COMPRESS_LIBRARIES} ${CMAKE_CURL_LIBRARIES} ) @@ -351,7 +357,7 @@ ENDIF(CMAKE_BUILD_ON_VISUAL_STUDIO OR MINGW) # CTestLib # INCLUDE_DIRECTORIES( - "${CMAKE_SOURCE_DIR}/Source/CTest" + "${CMake_SOURCE_DIR}/Source/CTest" ${CMAKE_XMLRPC_INCLUDES} ${CMAKE_CURL_INCLUDES} ) @@ -368,6 +374,7 @@ SET(CTEST_SRCS cmCTest.cxx CTest/cmCTestConfigureHandler.cxx CTest/cmCTestCoverageCommand.cxx CTest/cmCTestCoverageHandler.cxx + CTest/cmParsePHPCoverage.cxx CTest/cmCTestEmptyBinaryDirectoryCommand.cxx CTest/cmCTestGenericHandler.cxx CTest/cmCTestHandlerCommand.cxx @@ -425,13 +432,13 @@ SET(CPACK_SRCS CPack/cmCPackZIPGenerator.cxx ) -IF(WIN32 AND UNIX) +IF(CYGWIN) SET(CPACK_SRCS ${CPACK_SRCS} CPack/cmCPackCygwinBinaryGenerator.cxx CPack/cmCPackCygwinSourceGenerator.cxx ) -ENDIF(WIN32 AND UNIX) - +ENDIF(CYGWIN) + IF(UNIX) SET(CPACK_SRCS ${CPACK_SRCS} CPack/cmCPackDebGenerator.cxx @@ -493,8 +500,8 @@ IF(BUILD_QtDialog) SUBDIRS(QtDialog) ENDIF(BUILD_QtDialog) -INCLUDE (${CMAKE_BINARY_DIR}/Source/LocalUserOptions.cmake OPTIONAL) -INCLUDE (${CMAKE_SOURCE_DIR}/Source/LocalUserOptions.cmake OPTIONAL) +INCLUDE (${CMake_BINARY_DIR}/Source/LocalUserOptions.cmake OPTIONAL) +INCLUDE (${CMake_SOURCE_DIR}/Source/LocalUserOptions.cmake OPTIONAL) INSTALL_TARGETS(/bin cmake) INSTALL_TARGETS(/bin ctest) @@ -504,4 +511,3 @@ IF(APPLE) ENDIF(APPLE) INSTALL_FILES(${CMAKE_DATA_DIR}/include cmCPluginAPI.h) - diff --git a/Source/CMakeVersionSource.cmake b/Source/CMakeVersionSource.cmake new file mode 100644 index 0000000..05e265c --- /dev/null +++ b/Source/CMakeVersionSource.cmake @@ -0,0 +1,37 @@ +# Try to identify the current development source version. +set(CMake_VERSION_SOURCE "") +if(EXISTS ${CMake_SOURCE_DIR}/.git/HEAD) + find_program(GIT_EXECUTABLE NAMES git git.cmd) + mark_as_advanced(GIT_EXECUTABLE) + if(GIT_EXECUTABLE) + execute_process( + COMMAND ${GIT_EXECUTABLE} rev-parse --verify -q --short=4 HEAD + OUTPUT_VARIABLE head + OUTPUT_STRIP_TRAILING_WHITESPACE + WORKING_DIRECTORY ${CMake_SOURCE_DIR} + ) + if(head) + set(CMake_VERSION_SOURCE "g${head}") + execute_process( + COMMAND ${GIT_EXECUTABLE} update-index -q --refresh + WORKING_DIRECTORY ${CMake_SOURCE_DIR} + ) + execute_process( + COMMAND ${GIT_EXECUTABLE} diff-index --name-only HEAD -- + OUTPUT_VARIABLE dirty + OUTPUT_STRIP_TRAILING_WHITESPACE + WORKING_DIRECTORY ${CMake_SOURCE_DIR} + ) + if(dirty) + set(CMake_VERSION_SOURCE "${CMake_VERSION_SOURCE}-dirty") + endif() + endif() + endif() +elseif(EXISTS ${CMake_SOURCE_DIR}/CVS/Repository) + file(READ ${CMake_SOURCE_DIR}/CVS/Repository repo) + set(branch "") + if("${repo}" MATCHES "\\.git/") + string(REGEX REPLACE ".*\\.git/([^\r\n]*).*" "-\\1" branch "${repo}") + endif() + set(CMake_VERSION_SOURCE "cvs${branch}") +endif() diff --git a/Source/CPack/cmCPackArchiveGenerator.cxx b/Source/CPack/cmCPackArchiveGenerator.cxx index ba221a3..46be99b 100644 --- a/Source/CPack/cmCPackArchiveGenerator.cxx +++ b/Source/CPack/cmCPackArchiveGenerator.cxx @@ -22,13 +22,12 @@ #include <errno.h> #include <cmsys/SystemTools.hxx> -#include <cmlibarchive/libarchive/archive.h> -#include <cmlibarchive/libarchive/archive_entry.h> - +#include <cmsys/Directory.hxx> +#include <cm_libarchive.h> //---------------------------------------------------------------------- -cmCPackArchiveGenerator::cmCPackArchiveGenerator(CompressType t, - ArchiveType at) +cmCPackArchiveGenerator::cmCPackArchiveGenerator(cmArchiveWrite::Compress t, + cmArchiveWrite::Type at) { this->Compress = t; this->Archive = at; @@ -39,221 +38,240 @@ cmCPackArchiveGenerator::~cmCPackArchiveGenerator() { } -static const size_t cmCPackTGZ_Data_BlockSize = 16384; - -// make this an anonymous namespace so that archive.h does not -// have to be included in the .h file for this class -namespace +//---------------------------------------------------------------------- +int cmCPackArchiveGenerator::InitializeInternal() { -bool SetArchiveType(struct archive* a, - cmCPackArchiveGenerator::CompressType ct, - cmCPackArchiveGenerator::ArchiveType at) + this->SetOptionIfNotSet("CPACK_INCLUDE_TOPLEVEL_DIRECTORY", "1"); + return this->Superclass::InitializeInternal(); +} +//---------------------------------------------------------------------- +int cmCPackArchiveGenerator::addOneComponentToArchive(cmArchiveWrite& archive, + cmCPackComponent* component) { - int res = 0; - // pick the archive type - switch(at) - { - case cmCPackArchiveGenerator::TAR: - // maybe this: - res = archive_write_set_format_pax_restricted(a); - break; - case cmCPackArchiveGenerator::ZIP: - res = archive_write_set_format_zip(a); - break; - } - if(res != ARCHIVE_OK) - { - return false; - } - - // pick a compression type - switch(ct) - { - case cmCPackArchiveGenerator::GZIP: - res = archive_write_set_compression_gzip(a); - break; - case cmCPackArchiveGenerator::BZIP2: - res = archive_write_set_compression_bzip2(a); - break; - case cmCPackArchiveGenerator::COMPRESS: - res = archive_write_set_compression_compress(a); - break; - case cmCPackArchiveGenerator::LZMA: - res = archive_write_set_compression_lzma(a); - break; - case cmCPackArchiveGenerator::NONE: - default: - res = archive_write_set_compression_none(a); - } - if(res != ARCHIVE_OK) - { - return false; - } - // do not pad the last block!! - res = archive_write_set_bytes_in_last_block(a, 1); - if(res != ARCHIVE_OK) + cmCPackLogger(cmCPackLog::LOG_VERBOSE, " - packaging component: " + << component->Name + << std::endl); + // Add the files of this component to the archive + std::string localToplevel(this->GetOption("CPACK_TEMPORARY_DIRECTORY")); + localToplevel += "/"+ component->Name; + std::string dir = cmSystemTools::GetCurrentWorkingDirectory(); + // Change to local toplevel + cmSystemTools::ChangeDirectory(localToplevel.c_str()); + std::vector<std::string>::const_iterator fileIt; + for (fileIt = component->Files.begin(); fileIt != component->Files.end(); + ++fileIt ) { - return false; + cmCPackLogger(cmCPackLog::LOG_DEBUG,"Adding file: " + << (*fileIt) << std::endl); + archive.Add(*fileIt); + if (!archive) + { + cmCPackLogger(cmCPackLog::LOG_ERROR, "ERROR while packaging files: " + << archive.GetError() + << std::endl); + return 0; + } } - - return true; + // Go back to previous dir + cmSystemTools::ChangeDirectory(dir.c_str()); + return 1; } - -struct StreamData -{ - StreamData(cmGeneratedFileStream* gfs, - cmCPackArchiveGenerator* ag) - { - this->GeneratedFileStream = gfs; - this->Generator = ag; - } - cmGeneratedFileStream* GeneratedFileStream; - cmCPackArchiveGenerator* Generator; -}; +/* + * The macro will open/create a file 'filename' + * an declare and open the associated + * cmArchiveWrite 'archive' object. + */ +#define DECLARE_AND_OPEN_ARCHIVE(filename,archive) \ +cmGeneratedFileStream gf; \ +gf.Open(filename.c_str(), false, true); \ +if (!GenerateHeader(&gf)) \ + { \ + cmCPackLogger(cmCPackLog::LOG_ERROR, \ + "Problem to generate Header for archive < " \ + << filename \ + << ">." << std::endl); \ + return 0; \ + } \ +cmArchiveWrite archive(gf,this->Compress, this->Archive); \ +if (!archive) \ + { \ + cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem to create archive < " \ + << filename \ + << ">. ERROR =" \ + << archive.GetError() \ + << std::endl); \ + return 0; \ + } -extern "C" -{ -int OpenArchive(struct archive *, void *client_data) +//---------------------------------------------------------------------- +int cmCPackArchiveGenerator::PackageComponents(bool ignoreGroup) { - struct StreamData *data = (StreamData*)client_data; - if(data->GeneratedFileStream && - *data->GeneratedFileStream) + packageFileNames.clear(); + // The default behavior is to have one package by component group + // unless CPACK_COMPONENTS_IGNORE_GROUP is specified. + if (!ignoreGroup) { - if(data->Generator-> - GenerateHeader(data->GeneratedFileStream)) + std::map<std::string, cmCPackComponentGroup>::iterator compGIt; + for (compGIt=this->ComponentGroups.begin(); + compGIt!=this->ComponentGroups.end(); ++compGIt) + { + cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Packaging component group: " + << compGIt->first + << std::endl); + // Begin the archive for this group + std::string packageFileName= std::string(toplevel); + packageFileName += "/" + +std::string(this->GetOption("CPACK_PACKAGE_FILE_NAME")) + +"-"+compGIt->first + this->GetOutputExtension(); + // open a block in order to automatically close archive + // at the end of the block { - return ARCHIVE_OK; + DECLARE_AND_OPEN_ARCHIVE(packageFileName,archive); + // now iterate over the component of this group + std::vector<cmCPackComponent*>::iterator compIt; + for (compIt=(compGIt->second).Components.begin(); + compIt!=(compGIt->second).Components.end(); + ++compIt) + { + // Add the files of this component to the archive + addOneComponentToArchive(archive,*compIt); + } + } + // add the generated package to package file names list + packageFileNames.push_back(packageFileName); } } - return (ARCHIVE_FATAL); -} - -__LA_SSIZE_T WriteArchive(struct archive *, - void *client_data, - const void *buff, - size_t n) -{ - struct StreamData *data = (StreamData*)client_data; - data->GeneratedFileStream-> - write(reinterpret_cast<const char*>(buff),n); - if(!data->GeneratedFileStream->bad()) + // CPACK_COMPONENTS_IGNORE_GROUPS is set + // We build 1 package per component + else { - return n; + std::map<std::string, cmCPackComponent>::iterator compIt; + for (compIt=this->Components.begin(); + compIt!=this->Components.end(); ++compIt ) + { + std::string localToplevel(this->GetOption("CPACK_TEMPORARY_DIRECTORY")); + std::string packageFileName = std::string(toplevel); + + localToplevel += "/"+ compIt->first; + packageFileName += "/" + +std::string(this->GetOption("CPACK_PACKAGE_FILE_NAME")) + +"-"+compIt->first + this->GetOutputExtension(); + { + DECLARE_AND_OPEN_ARCHIVE(packageFileName,archive); + // Add the files of this component to the archive + addOneComponentToArchive(archive,&(compIt->second)); + } + // add the generated package to package file names list + packageFileNames.push_back(packageFileName); + } } - return 0; + return 1; } - -int CloseArchive(struct archive *, void *client_data) +//---------------------------------------------------------------------- +int cmCPackArchiveGenerator::PackageComponentsAllInOne(bool allComponent) { - struct StreamData *data = (StreamData*)client_data; - if(data->GeneratedFileStream->Close()) + // reset the package file names + packageFileNames.clear(); + packageFileNames.push_back(std::string(toplevel)); + packageFileNames[0] += "/" + +std::string(this->GetOption("CPACK_PACKAGE_FILE_NAME")) + +"-ALL" + this->GetOutputExtension(); + cmCPackLogger(cmCPackLog::LOG_VERBOSE, + "Packaging all groups in one package..." + "(CPACK_COMPONENTS_ALL_GROUPS_IN_ONE_PACKAGE is set)" + << std::endl); + DECLARE_AND_OPEN_ARCHIVE(packageFileNames[0],archive); + + // The ALL GROUP in ONE package case + if (! allComponent) { + // iterate over the component groups + std::map<std::string, cmCPackComponentGroup>::iterator compGIt; + for (compGIt=this->ComponentGroups.begin(); + compGIt!=this->ComponentGroups.end(); ++compGIt) + { + cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Packaging component group: " + << compGIt->first + << std::endl); + // now iterate over the component of this group + std::vector<cmCPackComponent*>::iterator compIt; + for (compIt=(compGIt->second).Components.begin(); + compIt!=(compGIt->second).Components.end(); + ++compIt) + { + // Add the files of this component to the archive + addOneComponentToArchive(archive,*compIt); + } + } + } + // The ALL COMPONENT in ONE package case + else { - delete data->GeneratedFileStream; - return ARCHIVE_OK; + std::map<std::string, cmCPackComponent>::iterator compIt; + for (compIt=this->Components.begin();compIt!=this->Components.end(); + ++compIt ) + { + // Add the files of this component to the archive + addOneComponentToArchive(archive,&(compIt->second)); + } } - return ARCHIVE_FATAL; + // archive goes out of scope so it will finalized and closed. + return 1; } -} //extern C -} // anon name space - //---------------------------------------------------------------------- -int cmCPackArchiveGenerator::InitializeInternal() -{ - this->SetOptionIfNotSet("CPACK_INCLUDE_TOPLEVEL_DIRECTORY", "1"); - return this->Superclass::InitializeInternal(); -} - -int cmCPackArchiveGenerator::CompressFiles(const char* outFileName, - const char* toplevel, const std::vector<std::string>& files) +int cmCPackArchiveGenerator::PackageFiles() { - int res = ARCHIVE_OK; -#define CHECK_ARCHIVE_ERROR(res, msg) \ - if(res != ARCHIVE_OK) \ - {\ - cmCPackLogger(cmCPackLog::LOG_ERROR, msg \ - << archive_error_string(a) \ - << cmSystemTools::GetLastSystemError() \ - << " " << res \ - << "\n"); \ - } cmCPackLogger(cmCPackLog::LOG_DEBUG, "Toplevel: " - << (toplevel ? toplevel : "(NULL)") << std::endl); - // create a new archive - struct archive* a = archive_write_new(); - // Set the compress and archive types for the archive - SetArchiveType(a, this->Compress, this->Archive); - // Open binary stream - cmGeneratedFileStream* gf = new cmGeneratedFileStream; - gf->Open(outFileName, false, true); - StreamData data(gf, this); - // pass callbacks to archive_write_open to handle stream - res = archive_write_open(a, - &data, - OpenArchive, - WriteArchive, - CloseArchive); - CHECK_ARCHIVE_ERROR(res, "archive_write_open:"); - // create a new disk struct - struct archive* disk = archive_read_disk_new(); -#if !defined(_WIN32) || defined(__CYGWIN__) - res = archive_read_disk_set_standard_lookup(disk); -#endif - CHECK_ARCHIVE_ERROR(res, "archive_read_disk_set_standard_lookup:"); + << toplevel << std::endl); + + PrepareGroupingKind(); + + if (SupportsComponentInstallation()) { + // CASE 1 : COMPONENT ALL-IN-ONE package + // If ALL GROUPS or ALL COMPONENTS in ONE package has been requested + // then the package file is unique and should be open here. + if (allComponentInOne || + (allGroupInOne && (!this->ComponentGroups.empty())) + ) + { + return PackageComponentsAllInOne(allComponentInOne); + } + // CASE 2 : COMPONENT CLASSICAL package(s) (i.e. not all-in-one) + // There will be 1 package for each component group + // however one may require to ignore component group and + // in this case you'll get 1 package for each component. + else if ((!this->ComponentGroups.empty()) || (ignoreComponentGroup)) + { + return PackageComponents(ignoreComponentGroup); + } + } + + // CASE 3 : NON COMPONENT package. + DECLARE_AND_OPEN_ARCHIVE(packageFileNames[0],archive); std::vector<std::string>::const_iterator fileIt; std::string dir = cmSystemTools::GetCurrentWorkingDirectory(); - cmSystemTools::ChangeDirectory(toplevel); + cmSystemTools::ChangeDirectory(toplevel.c_str()); for ( fileIt = files.begin(); fileIt != files.end(); ++ fileIt ) { - // create a new entry for each file - struct archive_entry *entry = archive_entry_new(); // Get the relative path to the file - std::string rp = cmSystemTools::RelativePath(toplevel, fileIt->c_str()); - // Set the name of the entry to the file name - archive_entry_set_pathname(entry, rp.c_str()); - res = archive_read_disk_entry_from_file(disk, entry, -1, 0); - CHECK_ARCHIVE_ERROR(res, "archive_read_disk_entry_from_file:"); - // write entry header - res = archive_write_header(a, entry); - CHECK_ARCHIVE_ERROR(res, "archive_write_header:"); - // the entry size can be 0 if it is a symlink - if(archive_entry_size(entry) > 0) + std::string rp = cmSystemTools::RelativePath(toplevel.c_str(), + fileIt->c_str()); + archive.Add(rp); + if(!archive) { - // now copy contents of file into archive a - FILE* file = fopen(fileIt->c_str(), "rb"); - if(!file) - { - cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem with fopen(): " - << fileIt->c_str() - << strerror(errno) - << std::endl); - return 0; - } - char buff[cmCPackTGZ_Data_BlockSize]; - size_t len = fread(buff, 1, sizeof(buff), file); - while (len > 0) - { - size_t wlen = archive_write_data(a, buff, len); - if(wlen != len) - { - cmCPackLogger(cmCPackLog::LOG_ERROR, "archive_write_data(): " - << "tried to write " << len << "\n" - << "write " << wlen << "\n"); - return 0; - } - len = fread(buff, 1, sizeof(buff), file); - } - // close the file and free the entry - fclose(file); + cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem while adding file< " + << *fileIt + << "> to archive <" + << packageFileNames[0] << "> .ERROR =" + << archive.GetError() + << std::endl); + return 0; } - archive_entry_free(entry); } cmSystemTools::ChangeDirectory(dir.c_str()); - // close the archive and finish the write - archive_write_close(a); - archive_write_finish(a); + // The destructor of cmArchiveWrite will close and finish the write return 1; } @@ -262,3 +280,17 @@ int cmCPackArchiveGenerator::GenerateHeader(std::ostream*) { return 1; } + +bool cmCPackArchiveGenerator::SupportsComponentInstallation() const { + // The Component installation support should only + // be activated if explicitly requested by the user + // (for backward compatibility reason) + if (IsOn("CPACK_ARCHIVE_COMPONENT_INSTALL")) + { + return true; + } + else + { + return false; + } +} diff --git a/Source/CPack/cmCPackArchiveGenerator.h b/Source/CPack/cmCPackArchiveGenerator.h index 486db8e..dc17257 100644 --- a/Source/CPack/cmCPackArchiveGenerator.h +++ b/Source/CPack/cmCPackArchiveGenerator.h @@ -13,35 +13,62 @@ #ifndef cmCPackArchiveGenerator_h #define cmCPackArchiveGenerator_h +#include "cmArchiveWrite.h" #include "cmCPackGenerator.h" /** \class cmCPackArchiveGenerator - * \brief A generator base for libarchive generation + * \brief A generator base for libarchive generation. + * The generator itself uses the libarchive wrapper + * \ref cmArchiveWrite. * */ class cmCPackArchiveGenerator : public cmCPackGenerator -{ + { public: - enum CompressType{ GZIP, BZIP2, COMPRESS, LZMA, NONE}; - enum ArchiveType{ TAR, ZIP}; cmTypeMacro(cmCPackArchiveGenerator, cmCPackGenerator); /** * Construct generator */ - cmCPackArchiveGenerator(CompressType, ArchiveType); + cmCPackArchiveGenerator(cmArchiveWrite::Compress, cmArchiveWrite::Type); virtual ~cmCPackArchiveGenerator(); // Used to add a header to the archive virtual int GenerateHeader(std::ostream* os); - + // component support + virtual bool SupportsComponentInstallation() const; protected: virtual int InitializeInternal(); - int CompressFiles(const char* outFileName, const char* toplevel, - const std::vector<std::string>& files); + /** + * Add the files belonging to the specified component + * to the provided (already opened) archive. + * @param[in,out] archive the archive object + * @param[in] component the component whose file will be added to archive + */ + int addOneComponentToArchive(cmArchiveWrite& archive, + cmCPackComponent* component); + + /** + * The main package file method. + * If component install was required this + * method will call either PackageComponents or + * PackageComponentsAllInOne. + */ + int PackageFiles(); + /** + * The method used to package files when component + * install is used. This will create one + * archive for each component group. + */ + int PackageComponents(bool ignoreGroup); + /** + * Special case of component install where all + * components will be put in a single installer. + */ + int PackageComponentsAllInOne(bool allComponent); virtual const char* GetOutputExtension() = 0; - CompressType Compress; - ArchiveType Archive; -}; + cmArchiveWrite::Compress Compress; + cmArchiveWrite::Type Archive; + }; #endif diff --git a/Source/CPack/cmCPackBundleGenerator.cxx b/Source/CPack/cmCPackBundleGenerator.cxx index 247a043..06a0509 100644 --- a/Source/CPack/cmCPackBundleGenerator.cxx +++ b/Source/CPack/cmCPackBundleGenerator.cxx @@ -53,10 +53,8 @@ const char* cmCPackBundleGenerator::GetPackagingInstallPrefix() } //---------------------------------------------------------------------- -int cmCPackBundleGenerator::CompressFiles(const char* outFileName, - const char* toplevel, const std::vector<std::string>& files) +int cmCPackBundleGenerator::PackageFiles() { - (void) files; // Get required arguments ... const std::string cpack_bundle_name = this->GetOption("CPACK_BUNDLE_NAME") @@ -167,5 +165,5 @@ int cmCPackBundleGenerator::CompressFiles(const char* outFileName, cmSystemTools::SetPermissions(command_target.str().c_str(), 0777); } - return this->CreateDMG(toplevel, outFileName); + return this->CreateDMG(); } diff --git a/Source/CPack/cmCPackBundleGenerator.h b/Source/CPack/cmCPackBundleGenerator.h index ce05541..82814b0 100644 --- a/Source/CPack/cmCPackBundleGenerator.h +++ b/Source/CPack/cmCPackBundleGenerator.h @@ -31,8 +31,7 @@ public: protected: virtual int InitializeInternal(); virtual const char* GetPackagingInstallPrefix(); - int CompressFiles(const char* outFileName, const char* toplevel, - const std::vector<std::string>& files); + int PackageFiles(); std::string InstallPrefix; }; diff --git a/Source/CPack/cmCPackCygwinBinaryGenerator.cxx b/Source/CPack/cmCPackCygwinBinaryGenerator.cxx index 853a1be..6c8fc54 100644 --- a/Source/CPack/cmCPackCygwinBinaryGenerator.cxx +++ b/Source/CPack/cmCPackCygwinBinaryGenerator.cxx @@ -41,8 +41,7 @@ int cmCPackCygwinBinaryGenerator::InitializeInternal() } //---------------------------------------------------------------------- -int cmCPackCygwinBinaryGenerator::CompressFiles(const char* outFileName, - const char* toplevel, const std::vector<std::string>& files) +int cmCPackCygwinBinaryGenerator::PackageFiles() { std::string packageName = this->GetOption("CPACK_PACKAGE_NAME"); packageName += "-"; @@ -70,12 +69,10 @@ int cmCPackCygwinBinaryGenerator::CompressFiles(const char* outFileName, ofs << manifest << "\n"; } // add the manifest file to the list of all files - std::vector<std::string> filesWithManifest = files; - filesWithManifest.push_back(manifestFile); + files.push_back(manifestFile); // create the bzip2 tar file - return this->Superclass::CompressFiles(outFileName, toplevel, - filesWithManifest); + return this->Superclass::PackageFiles(); } const char* cmCPackCygwinBinaryGenerator::GetOutputExtension() diff --git a/Source/CPack/cmCPackCygwinBinaryGenerator.h b/Source/CPack/cmCPackCygwinBinaryGenerator.h index 19b09f0..38f6df1 100644 --- a/Source/CPack/cmCPackCygwinBinaryGenerator.h +++ b/Source/CPack/cmCPackCygwinBinaryGenerator.h @@ -30,8 +30,7 @@ public: virtual ~cmCPackCygwinBinaryGenerator(); protected: virtual int InitializeInternal(); - int CompressFiles(const char* outFileName, const char* toplevel, - const std::vector<std::string>& files); + int PackageFiles(); virtual const char* GetOutputExtension(); std::string OutputExtension; }; diff --git a/Source/CPack/cmCPackCygwinSourceGenerator.cxx b/Source/CPack/cmCPackCygwinSourceGenerator.cxx index cca8338..5979729 100644 --- a/Source/CPack/cmCPackCygwinSourceGenerator.cxx +++ b/Source/CPack/cmCPackCygwinSourceGenerator.cxx @@ -48,21 +48,19 @@ int cmCPackCygwinSourceGenerator::InitializeInternal() } //---------------------------------------------------------------------- -int cmCPackCygwinSourceGenerator::CompressFiles(const char* outFileName, - const char* toplevel, const std::vector<std::string>& files) +int cmCPackCygwinSourceGenerator::PackageFiles() { // Create a tar file of the sources std::string packageDirFileName = this->GetOption("CPACK_TEMPORARY_DIRECTORY"); packageDirFileName += ".tar.bz2"; + packageFileNames[0] = packageDirFileName; std::string output; // skip one parent up to the cmCPackTarBZip2Generator // to create tar.bz2 file with the list of source // files - this->Compress = BZIP2; - if ( !this->cmCPackTarBZip2Generator:: - CompressFiles(packageDirFileName.c_str(), - toplevel, files) ) + this->Compress = cmArchiveWrite::CompressBZip2; + if ( !this->cmCPackTarBZip2Generator::PackageFiles() ) { return 0; } @@ -135,21 +133,25 @@ int cmCPackCygwinSourceGenerator::CompressFiles(const char* outFileName, patchFile += "/"; patchFile += cmSystemTools::GetFilenameName( this->GetOption("CPACK_CYGWIN_PATCH_FILE")); - std::vector<std::string> outerFiles; + std::string file = cmSystemTools::GetFilenameName(compressOutFile); std::string sourceTar = cmSystemTools::GetFilenamePath(compressOutFile); sourceTar += "/"; sourceTar += file; + /* reset list of file to be packaged */ + files.clear(); // a source release in cygwin should have the build script used // to build the package, the patch file that is different from the // regular upstream version of the sources, and a bziped tar file // of the original sources - outerFiles.push_back(buildScript); - outerFiles.push_back(patchFile); - outerFiles.push_back(sourceTar); - if ( !this->cmCPackTarBZip2Generator:: - CompressFiles(outerTarFile.c_str(), - tmpDir.c_str(), outerFiles) ) + files.push_back(buildScript); + files.push_back(patchFile); + files.push_back(sourceTar); + /* update the name of the produced package */ + packageFileNames[0] = outerTarFile; + /* update the toplevel dir */ + toplevel = tmpDir; + if ( !this->cmCPackTarBZip2Generator::PackageFiles() ) { return 0; } diff --git a/Source/CPack/cmCPackCygwinSourceGenerator.h b/Source/CPack/cmCPackCygwinSourceGenerator.h index 9817cf9..9d98a9b 100644 --- a/Source/CPack/cmCPackCygwinSourceGenerator.h +++ b/Source/CPack/cmCPackCygwinSourceGenerator.h @@ -31,8 +31,7 @@ public: protected: const char* GetPackagingInstallPrefix(); virtual int InitializeInternal(); - int CompressFiles(const char* outFileName, const char* toplevel, - const std::vector<std::string>& files); + int PackageFiles(); virtual const char* GetOutputExtension(); std::string InstallPrefix; std::string OutputExtension; diff --git a/Source/CPack/cmCPackDebGenerator.cxx b/Source/CPack/cmCPackDebGenerator.cxx index 9c77cc1..47a1ff6 100644 --- a/Source/CPack/cmCPackDebGenerator.cxx +++ b/Source/CPack/cmCPackDebGenerator.cxx @@ -43,14 +43,15 @@ cmCPackDebGenerator::~cmCPackDebGenerator() int cmCPackDebGenerator::InitializeInternal() { this->SetOptionIfNotSet("CPACK_PACKAGING_INSTALL_PREFIX", "/usr"); - + if (cmSystemTools::IsOff(this->GetOption("CPACK_SET_DESTDIR"))) + { + this->SetOption("CPACK_SET_DESTDIR", "I_ON"); + } return this->Superclass::InitializeInternal(); } //---------------------------------------------------------------------- -int cmCPackDebGenerator::CompressFiles(const char* outFileName, - const char* toplevel, - const std::vector<std::string>& files) +int cmCPackDebGenerator::PackageFiles() { this->ReadListFile("CPackDeb.cmake"); const char* cmakeExecutable = this->GetOption("CMAKE_COMMAND"); @@ -87,10 +88,24 @@ int cmCPackDebGenerator::CompressFiles(const char* outFileName, // optional entries const char* debian_pkg_dep = this->GetOption("CPACK_DEBIAN_PACKAGE_DEPENDS"); - const char* debian_pkg_rec = + const char* debian_pkg_rec = this->GetOption("CPACK_DEBIAN_PACKAGE_RECOMMENDS"); - const char* debian_pkg_sug = + const char* debian_pkg_sug = this->GetOption("CPACK_DEBIAN_PACKAGE_SUGGESTS"); + const char* debian_pkg_url = + this->GetOption("CPACK_DEBIAN_PACKAGE_HOMEPAGE"); + const char* debian_pkg_predep = + this->GetOption("CPACK_DEBIAN_PACKAGE_PREDEPENDS"); + const char* debian_pkg_enhances = + this->GetOption("CPACK_DEBIAN_PACKAGE_ENHANCES"); + const char* debian_pkg_breaks = + this->GetOption("CPACK_DEBIAN_PACKAGE_BREAKS"); + const char* debian_pkg_conflicts = + this->GetOption("CPACK_DEBIAN_PACKAGE_CONFLICTS"); + const char* debian_pkg_provides = + this->GetOption("CPACK_DEBIAN_PACKAGE_PROVIDES"); + const char* debian_pkg_replaces = + this->GetOption("CPACK_DEBIAN_PACKAGE_REPLACES"); { // the scope is needed for cmGeneratedFileStream cmGeneratedFileStream out(ctlfilename.c_str()); @@ -99,18 +114,46 @@ int cmCPackDebGenerator::CompressFiles(const char* outFileName, out << "Section: " << debian_pkg_section << "\n"; out << "Priority: " << debian_pkg_priority << "\n"; out << "Architecture: " << debian_pkg_arch << "\n"; - if(debian_pkg_dep) + if(debian_pkg_dep && *debian_pkg_dep) { out << "Depends: " << debian_pkg_dep << "\n"; } - if(debian_pkg_rec) + if(debian_pkg_rec && *debian_pkg_rec) { out << "Recommends: " << debian_pkg_rec << "\n"; } - if(debian_pkg_sug) + if(debian_pkg_sug && *debian_pkg_sug) { out << "Suggests: " << debian_pkg_sug << "\n"; } + if(debian_pkg_url && *debian_pkg_url) + { + out << "Homepage: " << debian_pkg_url << "\n"; + } + if (debian_pkg_predep && *debian_pkg_predep) + { + out << "Pre-Depends: " << debian_pkg_predep << "\n"; + } + if (debian_pkg_enhances && *debian_pkg_enhances) + { + out << "Enhances: " << debian_pkg_enhances << "\n"; + } + if (debian_pkg_breaks && *debian_pkg_breaks) + { + out << "Breaks: " << debian_pkg_breaks << "\n"; + } + if (debian_pkg_conflicts && *debian_pkg_conflicts) + { + out << "Conflicts: " << debian_pkg_conflicts << "\n"; + } + if (debian_pkg_provides && *debian_pkg_provides) + { + out << "Provides: " << debian_pkg_provides << "\n"; + } + if (debian_pkg_replaces && *debian_pkg_replaces) + { + out << "Replaces: " << debian_pkg_replaces << "\n"; + } unsigned long totalSize = 0; { std::string dirName = this->GetOption("CPACK_TEMPORARY_DIRECTORY"); @@ -121,7 +164,7 @@ int cmCPackDebGenerator::CompressFiles(const char* outFileName, totalSize += cmSystemTools::FileLength(fileIt->c_str()); } } - out << "Installed-Size: " << totalSize << "\n"; + out << "Installed-Size: " << (totalSize + 1023) / 1024 << "\n"; out << "Maintainer: " << maintainer << "\n"; out << "Description: " << desc << "\n"; out << std::endl; @@ -135,7 +178,7 @@ int cmCPackDebGenerator::CompressFiles(const char* outFileName, // now add all directories which have to be compressed // collect all top level install dirs for that // e.g. /opt/bin/foo, /usr/bin/bar and /usr/bin/baz would give /usr and /opt - int topLevelLength = strlen(toplevel); + size_t topLevelLength = toplevel.length(); std::set<std::string> installDirs; for (std::vector<std::string>::const_iterator fileIt = files.begin(); fileIt != files.end(); ++ fileIt ) @@ -154,7 +197,7 @@ int cmCPackDebGenerator::CompressFiles(const char* outFileName, std::string output; int retVal = -1; int res = cmSystemTools::RunSingleCommand(cmd.c_str(), &output, - &retVal, toplevel, this->GeneratorVerbose, 0); + &retVal, toplevel.c_str(), this->GeneratorVerbose, 0); if ( !res || retVal ) { @@ -190,7 +233,7 @@ int cmCPackDebGenerator::CompressFiles(const char* outFileName, //std::string output; //int retVal = -1; res = cmSystemTools::RunSingleCommand(cmd.c_str(), &output, - &retVal, toplevel, this->GeneratorVerbose, 0); + &retVal, toplevel.c_str(), this->GeneratorVerbose, 0); // debian md5sums entries are like this: // 014f3604694729f3bf19263bac599765 usr/bin/ccmake // thus strip the full path (with the trailing slash) @@ -231,7 +274,7 @@ int cmCPackDebGenerator::CompressFiles(const char* outFileName, } } res = cmSystemTools::RunSingleCommand(cmd.c_str(), &output, - &retVal, toplevel, this->GeneratorVerbose, 0); + &retVal, toplevel.c_str(), this->GeneratorVerbose, 0); if ( !res || retVal ) { @@ -257,7 +300,7 @@ int cmCPackDebGenerator::CompressFiles(const char* outFileName, arFiles.push_back(topLevelString + "debian-binary"); arFiles.push_back(topLevelString + "control.tar.gz"); arFiles.push_back(topLevelString + "data.tar.gz"); - res = ar_append(outFileName, arFiles); + res = ar_append(packageFileNames[0].c_str(), arFiles); if ( res!=0 ) { std::string tmpFile = this->GetOption("CPACK_TOPLEVEL_DIRECTORY"); @@ -371,7 +414,7 @@ static const char * ar_rname(const char *path) typedef struct ar_hdr HDR; static char ar_hb[sizeof(HDR) + 1]; /* real header */ -static int ar_already_written; +static size_t ar_already_written; /* copy_ar -- * Copy size bytes from one file to another - taking care to handle the @@ -431,7 +474,7 @@ static int put_arobj(CF *cfp, struct stat *sb) /* If not truncating names and the name is too long or contains * a space, use extended format 1. */ - unsigned int lname = strlen(name); + size_t lname = strlen(name); uid_t uid = sb->st_uid; gid_t gid = sb->st_gid; if (uid > USHRT_MAX) { @@ -441,7 +484,7 @@ static int put_arobj(CF *cfp, struct stat *sb) gid = USHRT_MAX; } if (lname > sizeof(hdr->ar_name) || strchr(name, ' ')) - (void)sprintf(ar_hb, HDR1, AR_EFMT1, lname, + (void)sprintf(ar_hb, HDR1, AR_EFMT1, (int)lname, (long int)sb->st_mtime, uid, gid, sb->st_mode, (long long)sb->st_size + lname, ARFMAG); else { diff --git a/Source/CPack/cmCPackDebGenerator.h b/Source/CPack/cmCPackDebGenerator.h index d229944..4a357d1 100644 --- a/Source/CPack/cmCPackDebGenerator.h +++ b/Source/CPack/cmCPackDebGenerator.h @@ -33,8 +33,7 @@ public: protected: virtual int InitializeInternal(); - virtual int CompressFiles(const char* outFileName, const char* toplevel, - const std::vector<std::string>& files); + virtual int PackageFiles(); virtual const char* GetOutputExtension() { return ".deb"; } }; diff --git a/Source/CPack/cmCPackDragNDropGenerator.cxx b/Source/CPack/cmCPackDragNDropGenerator.cxx index 95324cf..e9ce76c 100644 --- a/Source/CPack/cmCPackDragNDropGenerator.cxx +++ b/Source/CPack/cmCPackDragNDropGenerator.cxx @@ -104,12 +104,10 @@ const char* cmCPackDragNDropGenerator::GetOutputExtension() } //---------------------------------------------------------------------- -int cmCPackDragNDropGenerator::CompressFiles(const char* outFileName, - const char* toplevel, const std::vector<std::string>& files) +int cmCPackDragNDropGenerator::PackageFiles() { - (void) files; - return this->CreateDMG(toplevel, outFileName); + return this->CreateDMG(); } //---------------------------------------------------------------------- @@ -161,8 +159,7 @@ bool cmCPackDragNDropGenerator::RunCommand(cmOStringStream& command, } //---------------------------------------------------------------------- -int cmCPackDragNDropGenerator::CreateDMG(const std::string& toplevel, - const std::string& outFileName) +int cmCPackDragNDropGenerator::CreateDMG() { // Get optional arguments ... const std::string cpack_package_icon = this->GetOption("CPACK_PACKAGE_ICON") @@ -475,7 +472,7 @@ int cmCPackDragNDropGenerator::CreateDMG(const std::string& toplevel, final_image_command << cpack_dmg_format; final_image_command << " -imagekey"; final_image_command << " zlib-level=9"; - final_image_command << " -o \"" << outFileName << "\""; + final_image_command << " -o \"" << packageFileNames[0] << "\""; if(!this->RunCommand(final_image_command)) { diff --git a/Source/CPack/cmCPackDragNDropGenerator.h b/Source/CPack/cmCPackDragNDropGenerator.h index 43a9617..dcef7fb 100644 --- a/Source/CPack/cmCPackDragNDropGenerator.h +++ b/Source/CPack/cmCPackDragNDropGenerator.h @@ -29,14 +29,12 @@ public: protected: virtual int InitializeInternal(); virtual const char* GetOutputExtension(); - int CompressFiles(const char* outFileName, const char* toplevel, - const std::vector<std::string>& files); + int PackageFiles(); bool CopyFile(cmOStringStream& source, cmOStringStream& target); bool RunCommand(cmOStringStream& command, std::string* output = 0); - virtual int CreateDMG(const std::string& installdir, - const std::string& outdmg); + int CreateDMG(); std::string InstallPrefix; }; diff --git a/Source/CPack/cmCPackGenerator.cxx b/Source/CPack/cmCPackGenerator.cxx index 6224b40..feda52c 100644 --- a/Source/CPack/cmCPackGenerator.cxx +++ b/Source/CPack/cmCPackGenerator.cxx @@ -35,6 +35,9 @@ cmCPackGenerator::cmCPackGenerator() this->GeneratorVerbose = false; this->MakefileMap = 0; this->Logger = 0; + this->allGroupInOne = false; + this->allComponentInOne = false; + this->ignoreComponentGroup = false; } //---------------------------------------------------------------------- @@ -100,6 +103,7 @@ int cmCPackGenerator::PrepareNames() } std::string destFile = pdir; + this->SetOptionIfNotSet("CPACK_OUTPUT_FILE_PREFIX", destFile.c_str()); destFile += "/" + outName; std::string outFile = topDirectory + "/" + outName; this->SetOptionIfNotSet("CPACK_TOPLEVEL_DIRECTORY", topDirectory.c_str()); @@ -170,7 +174,9 @@ 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")); + bool setDestDir = cmSystemTools::IsOn(this->GetOption("CPACK_SET_DESTDIR")) + | cmSystemTools::IsInternallyOn( + this->GetOption("CPACK_SET_DESTDIR")); if (!setDestDir) { tempInstallDirectoryStr += this->GetPackagingInstallPrefix(); @@ -217,7 +223,7 @@ int cmCPackGenerator::InstallProject() // If the CPackConfig file sets CPACK_INSTALLED_DIRECTORIES // then glob it and copy it to CPACK_TEMPORARY_DIRECTORY - // This is used in Source packageing + // This is used in Source packaging if ( !this->InstallProjectViaInstalledDirectories( setDestDir, tempInstallDirectory) ) { @@ -328,15 +334,16 @@ int cmCPackGenerator::InstallProjectViaInstalledDirectories( it != installDirectoriesVector.end(); ++it ) { + std::list<std::pair<std::string,std::string> > symlinkedFiles; cmCPackLogger(cmCPackLog::LOG_DEBUG, "Find files" << std::endl); cmsys::Glob gl; - std::string toplevel = it->c_str(); + std::string top = it->c_str(); it ++; std::string subdir = it->c_str(); - std::string findExpr = toplevel; + std::string findExpr = top; findExpr += "/*"; cmCPackLogger(cmCPackLog::LOG_OUTPUT, - "- Install directory: " << toplevel << std::endl); + "- Install directory: " << top << std::endl); gl.RecurseOn(); if ( !gl.FindFiles(findExpr) ) { @@ -344,7 +351,7 @@ int cmCPackGenerator::InstallProjectViaInstalledDirectories( "Cannot find any files in the installed directory" << std::endl); return 0; } - std::vector<std::string>& files = gl.GetFiles(); + files = gl.GetFiles(); std::vector<std::string>::iterator gfit; std::vector<cmsys::RegularExpression>::iterator regIt; for ( gfit = files.begin(); gfit != files.end(); ++ gfit ) @@ -368,10 +375,21 @@ int cmCPackGenerator::InstallProjectViaInstalledDirectories( } std::string filePath = tempDir; filePath += "/" + subdir + "/" - + cmSystemTools::RelativePath(toplevel.c_str(), gfit->c_str()); + + cmSystemTools::RelativePath(top.c_str(), gfit->c_str()); cmCPackLogger(cmCPackLog::LOG_DEBUG, "Copy file: " << inFile.c_str() << " -> " << filePath.c_str() << std::endl); - if ( !cmSystemTools::CopyFileIfDifferent(inFile.c_str(), + /* If the file is a symlink we will have to re-create it */ + if ( cmSystemTools::FileIsSymlink(inFile.c_str())) + { + std::string targetFile; + std::string inFileRelative = + cmSystemTools::RelativePath(top.c_str(),inFile.c_str()); + cmSystemTools::ReadSymlink(inFile.c_str(),targetFile); + symlinkedFiles.push_back(std::pair<std::string, + std::string>(targetFile,inFileRelative)); + } + /* If it is not a symlink then do a plain copy */ + else if ( !cmSystemTools::CopyFileIfDifferent(inFile.c_str(), filePath.c_str()) ) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem copying file: " @@ -379,6 +397,36 @@ int cmCPackGenerator::InstallProjectViaInstalledDirectories( return 0; } } + /* rebuild symlinks in the installed tree */ + if (symlinkedFiles.size()>0) + { + std::list< std::pair<std::string,std::string> >::iterator symlinkedIt; + std::string curDir = cmSystemTools::GetCurrentWorkingDirectory(); + std::string goToDir = tempDir; + goToDir += "/"+subdir; + cmCPackLogger(cmCPackLog::LOG_DEBUG, + "Change dir to: " << goToDir <<std::endl); + cmSystemTools::ChangeDirectory(goToDir.c_str()); + for (symlinkedIt=symlinkedFiles.begin(); + symlinkedIt != symlinkedFiles.end(); + ++symlinkedIt) + { + cmCPackLogger(cmCPackLog::LOG_DEBUG, "Will create a symlink: " + << symlinkedIt->second << "--> " + << symlinkedIt->first << std::endl); + if (!cmSystemTools::CreateSymlink((symlinkedIt->first).c_str(), + (symlinkedIt->second).c_str())) + { + cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot create symlink: " + << symlinkedIt->second << "--> " + << symlinkedIt->first << std::endl); + return 0; + } + } + cmCPackLogger(cmCPackLog::LOG_DEBUG, "Going back to: " + << curDir <<std::endl); + cmSystemTools::ChangeDirectory(curDir.c_str()); + } } } return 1; @@ -413,7 +461,8 @@ int cmCPackGenerator::InstallProjectViaInstallScript( // underneath the tempInstallDirectory. The value of the project's // CMAKE_INSTALL_PREFIX is sent in here as the value of the // CPACK_INSTALL_PREFIX variable. - std::string dir; + + std::string dir; if (this->GetOption("CPACK_INSTALL_PREFIX")) { dir += this->GetOption("CPACK_INSTALL_PREFIX"); @@ -458,6 +507,7 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects( = this->GetOption("CPACK_INSTALL_CMAKE_PROJECTS"); const char* cmakeGenerator = this->GetOption("CPACK_CMAKE_GENERATOR"); + std::string absoluteDestFiles; if ( cmakeProjects && *cmakeProjects ) { if ( !cmakeGenerator ) @@ -501,7 +551,14 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects( std::vector<std::string> componentsVector; bool componentInstall = false; - if (this->SupportsComponentInstallation()) + /* + * We do a component install iff + * - the CPack generator support component + * - the user did not request Monolithic install + * (this works at CPack time too) + */ + if (this->SupportsComponentInstallation() & + !(this->IsSet("CPACK_MONOLITHIC_INSTALL"))) { // Determine the installation types for this project (if provided). std::string installTypesVar = "CPACK_" @@ -642,6 +699,18 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects( // value of the project's CMAKE_INSTALL_PREFIX is sent in here as // the value of the CPACK_INSTALL_PREFIX variable. // + // If DESTDIR has been 'internally set ON' this means that + // the underlying CPack specific generator did ask for that + // In this case we may override CPACK_INSTALL_PREFIX with + // 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"))) + { + this->SetOption("CPACK_INSTALL_PREFIX", + this->GetOption("CPACK_PACKAGING_INSTALL_PREFIX")); + } std::string dir; if (this->GetOption("CPACK_INSTALL_PREFIX")) { @@ -668,7 +737,20 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects( { dir = tempInstallDirectory + "/" + dir; } - + /* + * We must re-set DESTDIR for each component + * We must not add the CPACK_INSTALL_PREFIX part because + * it will be added using the override of CMAKE_INSTALL_PREFIX + * The main reason for this awkward trick is that + * are using DESTDIR for 2 different reasons: + * - Because it was asked by the CPack Generator or the user + * using CPACK_SET_DESTDIR + * - Because it was already used for component install + * in order to put things in subdirs... + */ + cmSystemTools::PutEnv( + (std::string("DESTDIR=")+tempInstallDirectory).c_str() + ); cmCPackLogger(cmCPackLog::LOG_DEBUG, "- Creating directory: '" << dir << "'" << std::endl); @@ -722,6 +804,16 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects( mf->AddDefinition("CMAKE_INSTALL_DO_STRIP", "1"); } int res = mf->ReadListFile(0, installFile.c_str()); + if (NULL !=mf->GetDefinition("CPACK_ABSOLUTE_DESTINATION_FILES")) { + if (absoluteDestFiles.length()>0) { + absoluteDestFiles +=";"; + } + absoluteDestFiles += + mf->GetDefinition("CPACK_ABSOLUTE_DESTINATION_FILES"); + cmCPackLogger(cmCPackLog::LOG_DEBUG, + "Got some ABSOLUTE DESTINATION FILES: " + << absoluteDestFiles << std::endl); + } if ( cmSystemTools::GetErrorOccuredFlag() || !res ) { return 0; @@ -729,6 +821,8 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects( } } } + this->SetOption("CPACK_ABSOLUTE_DESTINATION_FILES", + absoluteDestFiles.c_str()); return 1; } @@ -789,7 +883,7 @@ int cmCPackGenerator::DoPackage() cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Remove toplevel directory: " << toplevelDirectory << std::endl); - if ( !cmSystemTools::RemoveADirectory(toplevelDirectory) ) + if ( !cmSystemTools::RepeatedRemoveDirectory(toplevelDirectory) ) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem removing toplevel directory: " @@ -827,8 +921,8 @@ int cmCPackGenerator::DoPackage() return 0; } - cmCPackLogger(cmCPackLog::LOG_OUTPUT, "Compress package" << std::endl); - cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Compress files to: " + cmCPackLogger(cmCPackLog::LOG_OUTPUT, "Create package" << std::endl); + cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Package files to: " << (tempPackageFileName ? tempPackageFileName : "(NULL)") << std::endl); if ( cmSystemTools::FileExists(tempPackageFileName) ) { @@ -843,7 +937,7 @@ int cmCPackGenerator::DoPackage() } // The files to be installed - std::vector<std::string> files = gl.GetFiles(); + files = gl.GetFiles(); // For component installations, determine which files go into which // components. @@ -852,8 +946,12 @@ int cmCPackGenerator::DoPackage() std::vector<std::string>::const_iterator it; for ( it = files.begin(); it != files.end(); ++ it ) { - std::string fileN = cmSystemTools::RelativePath(tempDirectory, - it->c_str()); + // beware we cannot just use tempDirectory as before + // because some generator will "CPACK_INCLUDE_TOPLEVEL_DIRECTORY" + // we really want "CPACK_TEMPORARY_DIRECTORY" + std::string fileN = + cmSystemTools::RelativePath( + this->GetOption("CPACK_TEMPORARY_DIRECTORY"), it->c_str()); // Determine which component we are in. std::string componentName = fileN.substr(0, fileN.find('/')); @@ -863,37 +961,65 @@ int cmCPackGenerator::DoPackage() // Add this file to the list of files for the component. this->Components[componentName].Files.push_back(fileN); + cmCPackLogger(cmCPackLog::LOG_DEBUG, "Adding file <" + <<fileN<<"> to component <" + <<componentName<<">"<<std::endl); } } - if ( !this->CompressFiles(tempPackageFileName, - tempDirectory, files) || cmSystemTools::GetErrorOccuredFlag()) + + packageFileNames.clear(); + /* Put at least one file name into the list of + * wanted packageFileNames. The specific generator + * may update this during PackageFiles. + * (either putting several names or updating the provided one) + */ + packageFileNames.push_back(tempPackageFileName); + toplevel = tempDirectory; + if ( !this->PackageFiles() || cmSystemTools::GetErrorOccuredFlag()) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem compressing the directory" << std::endl); return 0; } - cmCPackLogger(cmCPackLog::LOG_OUTPUT, "Finalize package" << std::endl); - cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Copy final package: " - << (tempPackageFileName ? tempPackageFileName : "(NULL)" ) - << " to " - << (packageFileName ? packageFileName : "(NULL)") - << std::endl); - if ( !cmSystemTools::CopyFileIfDifferent(tempPackageFileName, - packageFileName) ) + /* + * Copy the generated packages to final destination + * - there may be several of them + * - the initially provided name may have changed + * (because the specific generator did 'normalize' it) + */ + cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Copying final package(s) [" + <<packageFileNames.size() + <<"]:"<<std::endl); + std::vector<std::string>::iterator it; + /* now copy package one by one */ + for (it=packageFileNames.begin();it!=packageFileNames.end();++it) { - cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem copying the package: " - << (tempPackageFileName ? tempPackageFileName : "(NULL)" ) - << " to " - << (packageFileName ? packageFileName : "(NULL)") - << std::endl); - return 0; + std::string tmpPF(this->GetOption("CPACK_OUTPUT_FILE_PREFIX")); + tempPackageFileName = it->c_str(); + tmpPF += "/"+cmSystemTools::GetFilenameName(*it); + packageFileName = tmpPF.c_str(); + cmCPackLogger(cmCPackLog::LOG_DEBUG, "Copy final package(s): " + << (tempPackageFileName ? tempPackageFileName : "(NULL)" ) + << " to " + << (packageFileName ? packageFileName : "(NULL)") + << std::endl); + if ( !cmSystemTools::CopyFileIfDifferent(tempPackageFileName, + packageFileName) ) + { + cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem copying the package: " + << (tempPackageFileName ? tempPackageFileName : "(NULL)" ) + << " to " + << (packageFileName ? packageFileName : "(NULL)") + << std::endl); + return 0; + } + cmCPackLogger(cmCPackLog::LOG_OUTPUT, "- package: " + << packageFileName + << " generated." << std::endl); } - cmCPackLogger(cmCPackLog::LOG_OUTPUT, "Package " - << (packageFileName ? packageFileName : "(NULL)") - << " generated." << std::endl); return 1; } @@ -944,7 +1070,13 @@ bool cmCPackGenerator::IsSet(const char* name) const } //---------------------------------------------------------------------- -const char* cmCPackGenerator::GetOption(const char* op) +bool cmCPackGenerator::IsOn(const char* name) const +{ + return cmSystemTools::IsOn(GetOption(name)); +} + +//---------------------------------------------------------------------- +const char* cmCPackGenerator::GetOption(const char* op) const { const char* ret = this->MakefileMap->GetDefinition(op); if(!ret) @@ -984,12 +1116,8 @@ int cmCPackGenerator::SetCMakeRoot() } //---------------------------------------------------------------------- -int cmCPackGenerator::CompressFiles(const char* outFileName, - const char* toplevel, const std::vector<std::string>& files) +int cmCPackGenerator::PackageFiles() { - (void)outFileName; - (void)toplevel; - (void)files; return 0; } @@ -1084,7 +1212,7 @@ int cmCPackGenerator::CleanTemporaryDirectory() cmCPackLogger(cmCPackLog::LOG_OUTPUT, "- Clean temporary : " << tempInstallDirectory << std::endl); - if(!cmsys::SystemTools::RemoveADirectory(tempInstallDirectory)) + if(!cmSystemTools::RepeatedRemoveDirectory(tempInstallDirectory)) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem removing temporary directory: " << @@ -1097,6 +1225,70 @@ int cmCPackGenerator::CleanTemporaryDirectory() } //---------------------------------------------------------------------- +int cmCPackGenerator::PrepareGroupingKind() +{ + // The default behavior is to create 1 package by component group + // unless the user asked to put all COMPONENTS in a single package + allGroupInOne = (NULL != + (this->GetOption( + "CPACK_COMPONENTS_ALL_GROUPS_IN_ONE_PACKAGE"))); + allComponentInOne = (NULL != + (this->GetOption( + "CPACK_COMPONENTS_ALL_IN_ONE_PACKAGE"))); + ignoreComponentGroup = (NULL != + (this->GetOption( + "CPACK_COMPONENTS_IGNORE_GROUPS"))); + + std::string groupingType; + + // Second way to specify grouping + if (NULL != this->GetOption("CPACK_COMPONENTS_GROUPING")) { + groupingType = this->GetOption("CPACK_COMPONENTS_GROUPING"); + } + + if (groupingType.length()>0) + { + cmCPackLogger(cmCPackLog::LOG_VERBOSE, "[" + << this->Name << "]" + << " requested component grouping = "<< groupingType <<std::endl); + if (groupingType == "ALL_GROUP_IN_ONE") + { + allGroupInOne = true; + } + else if (groupingType == "ALL_COMPONENT_IN_ONE") + { + allComponentInOne = true; + } + else if (groupingType == "IGNORE") + { + ignoreComponentGroup = true; + } + else + { + cmCPackLogger(cmCPackLog::LOG_WARNING, "[" + << this->Name << "]" + << " requested component grouping type <"<< groupingType + << "> UNKNOWN not in (ALL_GROUP_IN_ONE," + "ALL_COMPONENT_IN_ONE,IGNORE)" <<std::endl); + } + } + + // Some components were defined but NO group + // force ignoreGroups + if (this->ComponentGroups.empty() && (!this->Components.empty()) + && (!ignoreComponentGroup)) { + cmCPackLogger(cmCPackLog::LOG_WARNING, "[" + << this->Name << "]" + << " Some Components defined but NO component group:" + << " Ignoring component group." + << std::endl); + ignoreComponentGroup = true; + } + + return 1; +} + +//---------------------------------------------------------------------- bool cmCPackGenerator::SupportsComponentInstallation() const { return false; diff --git a/Source/CPack/cmCPackGenerator.h b/Source/CPack/cmCPackGenerator.h index 45188fe..f44a334 100644 --- a/Source/CPack/cmCPackGenerator.h +++ b/Source/CPack/cmCPackGenerator.h @@ -55,13 +55,22 @@ class cmCPackGenerator : public cmObject public: cmTypeMacro(cmCPackGenerator, cmObject); /** - * If verbose then more informaiton is printed out + * If verbose then more information is printed out */ void SetVerbose(bool val) { this->GeneratorVerbose = val; } /** - * Do the actual processing. Subclass has to override it. - * Return 0 if error. + * Do the actual whole package processing. + * Subclass may redefine it but its usually enough + * to redefine @ref PackageFiles, because in fact + * this method do call: + * - PrepareName + * - clean-up temp dirs + * - InstallProject (with the appropriate method) + * - prepare list of files and/or components to be package + * - PackageFiles + * - Copy produced packages at the expected place + * @return 0 if error. */ virtual int DoPackage(); @@ -79,8 +88,9 @@ public: //! Set and get the options void SetOption(const char* op, const char* value); void SetOptionIfNotSet(const char* op, const char* value); - const char* GetOption(const char* op); + const char* GetOption(const char* op) const; bool IsSet(const char* name) const; + bool IsOn(const char* name) const; //! Set all the variables int SetCMakeRoot(); @@ -94,13 +104,43 @@ public: bool ReadListFile(const char* moduleName); protected: + /** + * Prepare common used names by inspecting + * several CPACK_xxx var values. + */ int PrepareNames(); + + /** + * Install the project using appropriate method. + */ int InstallProject(); + int CleanTemporaryDirectory(); + virtual const char* GetOutputExtension() { return ".cpack"; } virtual const char* GetOutputPostfix() { return 0; } - virtual int CompressFiles(const char* outFileName, const char* toplevel, - const std::vector<std::string>& files); + + /** + * Prepare requested grouping kind from CPACK_xxx vars + * CPACK_COMPONENTS_ALL_GROUPS_IN_ONE_PACKAGE + * CPACK_COMPONENTS_ALL_IN_ONE_PACKAGE + * CPACK_COMPONENTS_IGNORE_GROUPS + * or + * CPACK_COMPONENTS_GROUPING + * @return 1 on success 0 on failure. + */ + virtual int PrepareGroupingKind(); + + /** + * Package the list of files and/or components which + * has been prepared by the beginning of DoPackage. + * @pre @ref toplevel has been filled-in + * @pre the list of file @ref files has been populated + * @pre packageFileNames contains at least 1 entry + * @post packageFileNames may have been updated and contains + * the list of packages generated by the specific generator. + */ + virtual int PackageFiles(); virtual const char* GetInstallPath(); virtual const char* GetPackagingInstallPrefix(); @@ -134,13 +174,58 @@ protected: std::string InstallPath; + /** + * The list of package file names. + * At beginning of DoPackage the (generic) generator will populate + * the list of desired package file names then it will + * call the redefined method PackageFiles which is may + * either use this set of names (usually on entry there should be + * only a single name) or update the vector with the list + * of created package file names. + */ + std::vector<std::string> packageFileNames; + + /** + * The directory where all the files to be packaged reside. + * If the installer support components there will be one + * sub-directory for each component. In those directories + * one will find the file belonging to the specified component. + */ + std::string toplevel; + + /** + * The complete list of files to be packaged. + * This list will be populated by DoPackage before + * PackageFiles is called. + */ + std::vector<std::string> files; + std::string CPackSelf; std::string CMakeSelf; std::string CMakeRoot; std::map<std::string, cmCPackInstallationType> InstallationTypes; + /** + * The set of components. + * If component installation is supported then this map + * contains the component specified in CPACK_COMPONENTS_ALL + */ std::map<std::string, cmCPackComponent> Components; std::map<std::string, cmCPackComponentGroup> ComponentGroups; + /** + * If true All component groups will be put in a single package. + */ + bool allGroupInOne; + /** + * If true All component will be put in a single package. + */ + bool allComponentInOne; + /** + * If true component grouping will be ignored. + * You will still get 1 package for each component unless + * allComponentInOne is true. + */ + bool ignoreComponentGroup; cmCPackLog* Logger; private: diff --git a/Source/CPack/cmCPackNSISGenerator.cxx b/Source/CPack/cmCPackNSISGenerator.cxx index ad77386..e5fe575 100644 --- a/Source/CPack/cmCPackNSISGenerator.cxx +++ b/Source/CPack/cmCPackNSISGenerator.cxx @@ -43,11 +43,10 @@ cmCPackNSISGenerator::~cmCPackNSISGenerator() } //---------------------------------------------------------------------- -int cmCPackNSISGenerator::CompressFiles(const char* outFileName, - const char* toplevel, const std::vector<std::string>& files) +int cmCPackNSISGenerator::PackageFiles() { - (void)outFileName; // TODO: Fix nsis to force out file name - (void)toplevel; + // TODO: Fix nsis to force out file name + std::string nsisInFileName = this->FindTemplate("NSIS.template.in"); if ( nsisInFileName.size() == 0 ) { @@ -74,7 +73,7 @@ int cmCPackNSISGenerator::CompressFiles(const char* outFileName, std::vector<std::string>::const_iterator it; for ( it = files.begin(); it != files.end(); ++ it ) { - std::string fileN = cmSystemTools::RelativePath(toplevel, + std::string fileN = cmSystemTools::RelativePath(toplevel.c_str(), it->c_str()); if (!this->Components.empty()) { @@ -88,13 +87,14 @@ int cmCPackNSISGenerator::CompressFiles(const char* outFileName, << str.str().c_str() << std::endl); this->SetOptionIfNotSet("CPACK_NSIS_DELETE_FILES", str.str().c_str()); std::vector<std::string> dirs; - this->GetListOfSubdirectories(toplevel, dirs); + this->GetListOfSubdirectories(toplevel.c_str(), dirs); std::vector<std::string>::const_iterator sit; cmOStringStream dstr; for ( sit = dirs.begin(); sit != dirs.end(); ++ sit ) { std::string componentName; - std::string fileN = cmSystemTools::RelativePath(toplevel, sit->c_str()); + std::string fileN = cmSystemTools::RelativePath(toplevel.c_str(), + sit->c_str()); if ( fileN.empty() ) { continue; @@ -129,14 +129,21 @@ int cmCPackNSISGenerator::CompressFiles(const char* outFileName, cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Configure file: " << nsisInFileName << " to " << nsisFileName << std::endl); if(this->IsSet("CPACK_NSIS_MUI_ICON") - && this->IsSet("CPACK_NSIS_MUI_UNIICON")) + || this->IsSet("CPACK_NSIS_MUI_UNIICON")) { - std::string installerIconCode="!define MUI_ICON \""; - installerIconCode += this->GetOption("CPACK_NSIS_MUI_ICON"); - installerIconCode += "\"\n"; - installerIconCode += "!define MUI_UNICON \""; - installerIconCode += this->GetOption("CPACK_NSIS_MUI_UNIICON"); - installerIconCode += "\"\n"; + std::string installerIconCode; + if(this->IsSet("CPACK_NSIS_MUI_ICON")) + { + installerIconCode += "!define MUI_ICON \""; + installerIconCode += this->GetOption("CPACK_NSIS_MUI_ICON"); + installerIconCode += "\"\n"; + } + if(this->IsSet("CPACK_NSIS_MUI_UNIICON")) + { + installerIconCode += "!define MUI_UNICON \""; + installerIconCode += this->GetOption("CPACK_NSIS_MUI_UNIICON"); + installerIconCode += "\"\n"; + } this->SetOptionIfNotSet("CPACK_NSIS_INSTALLER_MUI_ICON_CODE", installerIconCode.c_str()); } @@ -149,6 +156,17 @@ int cmCPackNSISGenerator::CompressFiles(const char* outFileName, installerIconCode.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"; + this->SetOptionIfNotSet("CPACK_NSIS_INSTALLER_MUI_FINISHPAGE_RUN_CODE", + installerRunCode.c_str()); + } + // Setup all of the component sections if (this->Components.empty()) { @@ -337,6 +355,7 @@ int cmCPackNSISGenerator::InitializeInternal() << std::endl); std::vector<std::string> path; std::string nsisPath; + bool gotRegValue = true; #ifdef _WIN32 if ( !cmsys::SystemTools::ReadRegistryValue( @@ -346,24 +365,37 @@ int cmCPackNSISGenerator::InitializeInternal() if ( !cmsys::SystemTools::ReadRegistryValue( "HKEY_LOCAL_MACHINE\\SOFTWARE\\NSIS", nsisPath) ) { - cmCPackLogger - (cmCPackLog::LOG_ERROR, - "Cannot find NSIS registry value. This is usually caused by NSIS " - "not being installed. Please install NSIS from " - "http://nsis.sourceforge.net" - << std::endl); - return 0; + gotRegValue = false; } } - path.push_back(nsisPath); + + if (gotRegValue) + { + path.push_back(nsisPath); + } #endif + nsisPath = cmSystemTools::FindProgram("makensis", path, false); + if ( nsisPath.empty() ) { - cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot find NSIS compiler" + cmCPackLogger(cmCPackLog::LOG_ERROR, + "Cannot find NSIS compiler makensis: likely it is not installed, " + "or not in your PATH" << std::endl); + + if (!gotRegValue) + { + cmCPackLogger(cmCPackLog::LOG_ERROR, + "Could not read NSIS registry value. This is usually caused by " + "NSIS not being installed. Please install NSIS from " + "http://nsis.sourceforge.net" + << std::endl); + } + return 0; } + std::string nsisCmd = "\"" + nsisPath + "\" " NSIS_OPT "VERSION"; cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Test NSIS version: " << nsisCmd.c_str() << std::endl); @@ -400,10 +432,13 @@ int cmCPackNSISGenerator::InitializeInternal() return 0; } this->SetOptionIfNotSet("CPACK_INSTALLER_PROGRAM", nsisPath.c_str()); + this->SetOptionIfNotSet("CPACK_NSIS_EXECUTABLES_DIRECTORY", "bin"); const char* cpackPackageExecutables = this->GetOption("CPACK_PACKAGE_EXECUTABLES"); const char* cpackPackageDeskTopLinks = this->GetOption("CPACK_CREATE_DESKTOP_LINKS"); + const char* cpackNsisExecutablesDirectory + = this->GetOption("CPACK_NSIS_EXECUTABLES_DIRECTORY"); std::vector<std::string> cpackPackageDesktopLinksVector; if(cpackPackageDeskTopLinks) { @@ -426,12 +461,14 @@ int cmCPackNSISGenerator::InitializeInternal() cmCPackLogger(cmCPackLog::LOG_DEBUG, "CPACK_CREATE_DESKTOP_LINKS: " << "not set" << std::endl); } + + cmOStringStream str; + cmOStringStream deleteStr; + if ( cpackPackageExecutables ) { cmCPackLogger(cmCPackLog::LOG_DEBUG, "The cpackPackageExecutables: " << cpackPackageExecutables << "." << std::endl); - cmOStringStream str; - cmOStringStream deleteStr; std::vector<std::string> cpackPackageExecutablesVector; cmSystemTools::ExpandListArgument(cpackPackageExecutables, cpackPackageExecutablesVector); @@ -451,7 +488,8 @@ int cmCPackNSISGenerator::InitializeInternal() ++ it; std::string linkName = *it; str << " CreateShortCut \"$SMPROGRAMS\\$STARTMENU_FOLDER\\" - << linkName << ".lnk\" \"$INSTDIR\\bin\\" << execName << ".exe\"" + << linkName << ".lnk\" \"$INSTDIR\\" + << cpackNsisExecutablesDirectory << "\\" << execName << ".exe\"" << std::endl; deleteStr << " Delete \"$SMPROGRAMS\\$MUI_TEMP\\" << linkName << ".lnk\"" << std::endl; @@ -465,18 +503,21 @@ int cmCPackNSISGenerator::InitializeInternal() { str << " StrCmp \"$INSTALL_DESKTOP\" \"1\" 0 +2\n"; str << " CreateShortCut \"$DESKTOP\\" - << linkName << ".lnk\" \"$INSTDIR\\bin\\" << execName << ".exe\"" + << linkName << ".lnk\" \"$INSTDIR\\" + << cpackNsisExecutablesDirectory << "\\" << execName << ".exe\"" << std::endl; deleteStr << " StrCmp \"$INSTALL_DESKTOP\" \"1\" 0 +2\n"; deleteStr << " Delete \"$DESKTOP\\" << linkName << ".lnk\"" << std::endl; } } - this->CreateMenuLinks(str, deleteStr); - this->SetOptionIfNotSet("CPACK_NSIS_CREATE_ICONS", str.str().c_str()); - this->SetOptionIfNotSet("CPACK_NSIS_DELETE_ICONS", - deleteStr.str().c_str()); } + + this->CreateMenuLinks(str, deleteStr); + this->SetOptionIfNotSet("CPACK_NSIS_CREATE_ICONS", str.str().c_str()); + this->SetOptionIfNotSet("CPACK_NSIS_DELETE_ICONS", + deleteStr.str().c_str()); + this->SetOptionIfNotSet("CPACK_NSIS_COMPRESSOR", "lzma"); return this->Superclass::InitializeInternal(); @@ -505,22 +546,25 @@ void cmCPackNSISGenerator::CreateMenuLinks( cmOStringStream& str, "<icon name>." << std::endl); return; } + + cmsys::RegularExpression urlRegex; + urlRegex.compile("^(mailto:|(ftps?|https?|news)://).*$"); + std::vector<std::string>::iterator it; for ( it = cpackMenuLinksVector.begin(); it != cpackMenuLinksVector.end(); ++it ) { std::string sourceName = *it; - bool url = false; - if(sourceName.find("http:") == 0) - { - url = true; - } - /* convert / to \\ */ + const bool url = urlRegex.find(sourceName); + + // Convert / to \ in filenames, but not in urls: + // if(!url) { cmSystemTools::ReplaceString(sourceName, "/", "\\"); } + ++ it; std::string linkName = *it; if(!url) @@ -758,7 +802,7 @@ CreateComponentDescription(cmCPackComponent *component, } // Create the NSIS code to download this file on-the-fly. - unsigned totalSizeInKbytes = (totalSize + 512) / 1024; + unsigned long totalSizeInKbytes = (totalSize + 512) / 1024; if (totalSizeInKbytes == 0) { totalSizeInKbytes = 1; diff --git a/Source/CPack/cmCPackNSISGenerator.h b/Source/CPack/cmCPackNSISGenerator.h index dff5b8f..6ad103f 100644 --- a/Source/CPack/cmCPackNSISGenerator.h +++ b/Source/CPack/cmCPackNSISGenerator.h @@ -37,8 +37,7 @@ protected: virtual int InitializeInternal(); void CreateMenuLinks( cmOStringStream& str, cmOStringStream& deleteStr); - int CompressFiles(const char* outFileName, const char* toplevel, - const std::vector<std::string>& files); + int PackageFiles(); virtual const char* GetOutputExtension() { return ".exe"; } virtual const char* GetOutputPostfix() { return "win32"; } diff --git a/Source/CPack/cmCPackOSXX11Generator.cxx b/Source/CPack/cmCPackOSXX11Generator.cxx index a3b5759..2d4bb97 100644 --- a/Source/CPack/cmCPackOSXX11Generator.cxx +++ b/Source/CPack/cmCPackOSXX11Generator.cxx @@ -33,12 +33,10 @@ cmCPackOSXX11Generator::~cmCPackOSXX11Generator() } //---------------------------------------------------------------------- -int cmCPackOSXX11Generator::CompressFiles(const char* outFileName, - const char* toplevel, - const std::vector<std::string>& files) +int cmCPackOSXX11Generator::PackageFiles() { - (void) files; // TODO: Fix api to not need files. - (void) toplevel; // TODO: Use toplevel + // TODO: Use toplevel ? + // It is used! Is this an obsolete comment? const char* cpackPackageExecutables = this->GetOption("CPACK_PACKAGE_EXECUTABLES"); @@ -144,7 +142,7 @@ int cmCPackOSXX11Generator::CompressFiles(const char* outFileName, dmgCmd << "\"" << this->GetOption("CPACK_INSTALLER_PROGRAM_DISK_IMAGE") << "\" create -ov -format UDZO -srcfolder \"" << diskImageDirectory.c_str() - << "\" \"" << outFileName << "\""; + << "\" \"" << packageFileNames[0] << "\""; int retVal = 1; cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Compress disk image using command: " diff --git a/Source/CPack/cmCPackOSXX11Generator.h b/Source/CPack/cmCPackOSXX11Generator.h index 7fd60b4..b7bd243 100644 --- a/Source/CPack/cmCPackOSXX11Generator.h +++ b/Source/CPack/cmCPackOSXX11Generator.h @@ -33,8 +33,7 @@ public: protected: virtual int InitializeInternal(); - int CompressFiles(const char* outFileName, const char* toplevel, - const std::vector<std::string>& files); + int PackageFiles(); virtual const char* GetPackagingInstallPrefix(); virtual const char* GetOutputExtension() { return ".dmg"; } diff --git a/Source/CPack/cmCPackPackageMakerGenerator.cxx b/Source/CPack/cmCPackPackageMakerGenerator.cxx index 9333131..ef81da8 100644 --- a/Source/CPack/cmCPackPackageMakerGenerator.cxx +++ b/Source/CPack/cmCPackPackageMakerGenerator.cxx @@ -59,12 +59,10 @@ int cmCPackPackageMakerGenerator::CopyInstallScript(const char* resdir, } //---------------------------------------------------------------------- -int cmCPackPackageMakerGenerator::CompressFiles(const char* outFileName, - const char* toplevel, - const std::vector<std::string>& files) +int cmCPackPackageMakerGenerator::PackageFiles() { - (void) files; // TODO: Fix api to not need files. - (void) toplevel; // TODO: Use toplevel + // TODO: Use toplevel + // It is used! Is this an obsolete comment? std::string resDir; // Where this package's resources will go. std::string packageDirFileName @@ -318,7 +316,7 @@ int cmCPackPackageMakerGenerator::CompressFiles(const char* outFileName, cmOStringStream dmgCmd; dmgCmd << "\"" << this->GetOption("CPACK_INSTALLER_PROGRAM_DISK_IMAGE") << "\" create -ov -format UDZO -srcfolder \"" << packageDirFileName - << "\" \"" << outFileName << "\""; + << "\" \"" << packageFileNames[0] << "\""; std::string output; int retVal = 1; int numTries = 4; diff --git a/Source/CPack/cmCPackPackageMakerGenerator.h b/Source/CPack/cmCPackPackageMakerGenerator.h index 36cd594..2bab947 100644 --- a/Source/CPack/cmCPackPackageMakerGenerator.h +++ b/Source/CPack/cmCPackPackageMakerGenerator.h @@ -42,8 +42,7 @@ protected: const char* script, const char* name); virtual int InitializeInternal(); - int CompressFiles(const char* outFileName, const char* toplevel, - const std::vector<std::string>& files); + int PackageFiles(); virtual const char* GetOutputExtension() { return ".dmg"; } virtual const char* GetOutputPostfix() { return "darwin"; } diff --git a/Source/CPack/cmCPackRPMGenerator.cxx b/Source/CPack/cmCPackRPMGenerator.cxx index fb85581..a5db78f 100644 --- a/Source/CPack/cmCPackRPMGenerator.cxx +++ b/Source/CPack/cmCPackRPMGenerator.cxx @@ -11,6 +11,7 @@ ============================================================================*/ #include "cmCPackRPMGenerator.h" #include "cmCPackLog.h" +#include "cmSystemTools.h" //---------------------------------------------------------------------- cmCPackRPMGenerator::cmCPackRPMGenerator() @@ -26,22 +27,94 @@ cmCPackRPMGenerator::~cmCPackRPMGenerator() int cmCPackRPMGenerator::InitializeInternal() { this->SetOptionIfNotSet("CPACK_PACKAGING_INSTALL_PREFIX", "/usr"); - + if (cmSystemTools::IsOff(this->GetOption("CPACK_SET_DESTDIR"))) + { + this->SetOption("CPACK_SET_DESTDIR", "I_ON"); + } return this->Superclass::InitializeInternal(); } //---------------------------------------------------------------------- -int cmCPackRPMGenerator::CompressFiles(const char* /*outFileName*/, - const char* /*toplevel*/, - const std::vector<std::string>& /*files*/) +int cmCPackRPMGenerator::PackageFiles() { - this->ReadListFile("CPackRPM.cmake"); + int retval = 1; + /* Digest Component grouping specification */ + retval = PrepareGroupingKind(); + cmCPackLogger(cmCPackLog::LOG_DEBUG, "Toplevel: " + << toplevel << std::endl); + + /* Are we in the component packaging case */ + if (SupportsComponentInstallation() & (!this->ComponentGroups.empty())) + { + /* Reset package file name list it will be populated during the + * component packaging run*/ + packageFileNames.clear(); + std::string initialTopLevel(this->GetOption("CPACK_TEMPORARY_DIRECTORY")); + /* One Package per component CASE */ + /* Iterate over components */ + std::map<std::string, cmCPackComponent>::iterator compIt; + for (compIt=this->Components.begin(); + compIt!=this->Components.end(); ++compIt ) + { + std::string localToplevel(initialTopLevel); + std::string packageFileName( + cmSystemTools::GetParentDirectory(toplevel.c_str()) + ); + std::string outputFileName( + std::string(this->GetOption("CPACK_PACKAGE_FILE_NAME") + ) + +"-"+compIt->first + this->GetOutputExtension()); + + localToplevel += "/"+ compIt->first; + /* replace the TEMP DIRECTORY with the component one */ + this->SetOption("CPACK_TEMPORARY_DIRECTORY",localToplevel.c_str()); + packageFileName += "/"+ outputFileName; + /* replace proposed CPACK_OUTPUT_FILE_NAME */ + this->SetOption("CPACK_OUTPUT_FILE_NAME",outputFileName.c_str()); + /* replace the TEMPORARY package file name */ + this->SetOption("CPACK_TEMPORARY_PACKAGE_FILE_NAME", + packageFileName.c_str()); + + this->SetOption("CPACK_RPM_PACKAGE_COMPONENT",compIt->first.c_str()); + if (!this->ReadListFile("CPackRPM.cmake")) + { + cmCPackLogger(cmCPackLog::LOG_ERROR, + "Error while execution CPackRPM.cmake" << std::endl); + retval = 0; + } + + // add the generated package to package file names list + packageFileNames.push_back(packageFileName); + } + } + /* This is the non component case */ + else + { + if (!this->ReadListFile("CPackRPM.cmake")) + { + cmCPackLogger(cmCPackLog::LOG_ERROR, + "Error while execution CPackRPM.cmake" << std::endl); + retval = 0; + } + } + if (!this->IsSet("RPMBUILD_EXECUTABLE")) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot find rpmbuild" << std::endl); - return 0; + retval = 0; } - return 1; + return retval; } +bool cmCPackRPMGenerator::SupportsComponentInstallation() const + { + if (IsOn("CPACK_RPM_COMPONENT_INSTALL")) + { + return true; + } + else + { + return false; + } + } diff --git a/Source/CPack/cmCPackRPMGenerator.h b/Source/CPack/cmCPackRPMGenerator.h index c607f35..57d5cca 100644 --- a/Source/CPack/cmCPackRPMGenerator.h +++ b/Source/CPack/cmCPackRPMGenerator.h @@ -37,9 +37,9 @@ public: protected: virtual int InitializeInternal(); - virtual int CompressFiles(const char* outFileName, const char* toplevel, - const std::vector<std::string>& files); + virtual int PackageFiles(); virtual const char* GetOutputExtension() { return ".rpm"; } + virtual bool SupportsComponentInstallation() const; }; diff --git a/Source/CPack/cmCPackSTGZGenerator.cxx b/Source/CPack/cmCPackSTGZGenerator.cxx index a687e0d..184c557 100644 --- a/Source/CPack/cmCPackSTGZGenerator.cxx +++ b/Source/CPack/cmCPackSTGZGenerator.cxx @@ -52,14 +52,13 @@ int cmCPackSTGZGenerator::InitializeInternal() } //---------------------------------------------------------------------- -int cmCPackSTGZGenerator::CompressFiles(const char* outFileName, - const char* toplevel, const std::vector<std::string>& files) +int cmCPackSTGZGenerator::PackageFiles() { - if ( !this->Superclass::CompressFiles(outFileName, toplevel, files) ) + if ( !this->Superclass::PackageFiles() ) { return 0; } - return cmSystemTools::SetPermissions(outFileName, + return cmSystemTools::SetPermissions(packageFileNames[0].c_str(), #if defined( _MSC_VER ) || defined( __MINGW32__ ) S_IREAD | S_IWRITE | S_IEXEC #elif defined( __BORLANDC__ ) diff --git a/Source/CPack/cmCPackSTGZGenerator.h b/Source/CPack/cmCPackSTGZGenerator.h index fc51e4d..ccceec8 100644 --- a/Source/CPack/cmCPackSTGZGenerator.h +++ b/Source/CPack/cmCPackSTGZGenerator.h @@ -32,8 +32,7 @@ public: virtual ~cmCPackSTGZGenerator(); protected: - int CompressFiles(const char* outFileName, const char* toplevel, - const std::vector<std::string>& files); + int PackageFiles(); virtual int InitializeInternal(); int GenerateHeader(std::ostream* os); virtual const char* GetOutputExtension() { return ".sh"; } diff --git a/Source/CPack/cmCPackTGZGenerator.cxx b/Source/CPack/cmCPackTGZGenerator.cxx index c6ef8ae..509c7f8 100644 --- a/Source/CPack/cmCPackTGZGenerator.cxx +++ b/Source/CPack/cmCPackTGZGenerator.cxx @@ -14,8 +14,8 @@ //---------------------------------------------------------------------- cmCPackTGZGenerator::cmCPackTGZGenerator() - :cmCPackArchiveGenerator(cmCPackArchiveGenerator::GZIP, - cmCPackArchiveGenerator::TAR) + :cmCPackArchiveGenerator(cmArchiveWrite::CompressGZip, + cmArchiveWrite::TypeTAR) { } diff --git a/Source/CPack/cmCPackTarBZip2Generator.cxx b/Source/CPack/cmCPackTarBZip2Generator.cxx index 52826dc..971d166 100644 --- a/Source/CPack/cmCPackTarBZip2Generator.cxx +++ b/Source/CPack/cmCPackTarBZip2Generator.cxx @@ -13,8 +13,8 @@ #include "cmCPackTarBZip2Generator.h" //---------------------------------------------------------------------- cmCPackTarBZip2Generator::cmCPackTarBZip2Generator() - :cmCPackArchiveGenerator(cmCPackArchiveGenerator::BZIP2, - cmCPackArchiveGenerator::TAR) + :cmCPackArchiveGenerator(cmArchiveWrite::CompressBZip2, + cmArchiveWrite::TypeTAR) { } diff --git a/Source/CPack/cmCPackTarCompressGenerator.cxx b/Source/CPack/cmCPackTarCompressGenerator.cxx index e9b5e2e..7a8f697 100644 --- a/Source/CPack/cmCPackTarCompressGenerator.cxx +++ b/Source/CPack/cmCPackTarCompressGenerator.cxx @@ -14,8 +14,8 @@ //---------------------------------------------------------------------- cmCPackTarCompressGenerator::cmCPackTarCompressGenerator() - :cmCPackArchiveGenerator(cmCPackArchiveGenerator::COMPRESS, - cmCPackArchiveGenerator::TAR) + :cmCPackArchiveGenerator(cmArchiveWrite::CompressCompress, + cmArchiveWrite::TypeTAR) { } diff --git a/Source/CPack/cmCPackZIPGenerator.cxx b/Source/CPack/cmCPackZIPGenerator.cxx index e195f83..e6e4e77 100644 --- a/Source/CPack/cmCPackZIPGenerator.cxx +++ b/Source/CPack/cmCPackZIPGenerator.cxx @@ -14,8 +14,8 @@ //---------------------------------------------------------------------- cmCPackZIPGenerator::cmCPackZIPGenerator() - :cmCPackArchiveGenerator(cmCPackArchiveGenerator::NONE, - cmCPackArchiveGenerator::ZIP) + :cmCPackArchiveGenerator(cmArchiveWrite::CompressNone, + cmArchiveWrite::TypeZIP) { } diff --git a/Source/CPack/cpack.cxx b/Source/CPack/cpack.cxx index 243d9c9..9163af81 100644 --- a/Source/CPack/cpack.cxx +++ b/Source/CPack/cpack.cxx @@ -203,7 +203,7 @@ int main (int argc, char *argv[]) if ( verbose ) { log.SetVerbose(verbose); - cmCPack_Log(&log, cmCPackLog::LOG_OUTPUT, "Enable Verbse" << std::endl); + cmCPack_Log(&log, cmCPackLog::LOG_OUTPUT, "Enable Verbose" << std::endl); } if ( debug ) { diff --git a/Source/CTest/cmCTestBZR.cxx b/Source/CTest/cmCTestBZR.cxx index d8ec9cd..36302df 100644 --- a/Source/CTest/cmCTestBZR.cxx +++ b/Source/CTest/cmCTestBZR.cxx @@ -276,12 +276,14 @@ private: && !this->CData.empty()) { this->CurChange.Path.assign(&this->CData[0], this->CData.size()); + cmSystemTools::ConvertToUnixSlashes(this->CurChange.Path); this->Changes.push_back(this->CurChange); } else if(strcmp(name, "symlink") == 0 && !this->CData.empty()) { // symlinks have an arobase at the end in the log this->CurChange.Path.assign(&this->CData[0], this->CData.size()-1); + cmSystemTools::ConvertToUnixSlashes(this->CurChange.Path); this->Changes.push_back(this->CurChange); } else if(strcmp(name, "committer") == 0 && !this->CData.empty()) @@ -290,7 +292,7 @@ private: if(this->EmailRegex.find(this->Rev.Author)) { this->Rev.Author = this->EmailRegex.match(1); - //email = email_regex.match(2); + this->Rev.EMail = this->EmailRegex.match(2); } } else if(strcmp(name, "timestamp") == 0 && !this->CData.empty()) @@ -377,9 +379,10 @@ private: return true; } - void DoPath(char c0, char c1, char c2, std::string const& path) + void DoPath(char c0, char c1, char c2, std::string path) { if(path.empty()) return; + cmSystemTools::ConvertToUnixSlashes(path); const std::string dir = cmSystemTools::GetFilenamePath(path); const std::string name = cmSystemTools::GetFilenameName(path); @@ -488,9 +491,10 @@ private: return true; } - void DoPath(char c0, char c1, char c2, std::string const& path) + void DoPath(char c0, char c1, char c2, std::string path) { if(path.empty()) return; + cmSystemTools::ConvertToUnixSlashes(path); if ( c0=='C' ) { diff --git a/Source/CTest/cmCTestBuildCommand.cxx b/Source/CTest/cmCTestBuildCommand.cxx index 7a4d877..b984e85 100644 --- a/Source/CTest/cmCTestBuildCommand.cxx +++ b/Source/CTest/cmCTestBuildCommand.cxx @@ -144,10 +144,17 @@ cmCTestGenericHandler* cmCTestBuildCommand::InitializeHandler() else { cmOStringStream ostr; - ostr << "CTEST_BUILD_COMMAND or CTEST_CMAKE_GENERATOR not specified. " - "Please specify the CTEST_CMAKE_GENERATOR and CTEST_PROJECT_NAME if " - "this is a CMake project, or specify the CTEST_BUILD_COMMAND for " - "cmake or any other project."; + ostr << "has no project to build. If this is a " + "\"built with CMake\" project, verify that CTEST_CMAKE_GENERATOR " + "and CTEST_PROJECT_NAME are set." + "\n" + "CTEST_PROJECT_NAME is usually set in CTestConfig.cmake. Verify " + "that CTestConfig.cmake exists, or CTEST_PROJECT_NAME " + "is set in the script, or PROJECT_NAME is passed as an argument " + "to ctest_build." + "\n" + "Alternatively, set CTEST_BUILD_COMMAND to build the project " + "with a custom command line."; this->SetError(ostr.str().c_str()); return 0; } diff --git a/Source/CTest/cmCTestBuildCommand.h b/Source/CTest/cmCTestBuildCommand.h index 228067e..9eb4907 100644 --- a/Source/CTest/cmCTestBuildCommand.h +++ b/Source/CTest/cmCTestBuildCommand.h @@ -60,10 +60,12 @@ public: virtual const char* GetFullDocumentation() { return - " ctest_build([BUILD build_dir] [RETURN_VALUE res] [APPEND]\n" - " [NUMBER_ERRORS val] [NUMBER_WARNINGS val])\n" + " ctest_build([BUILD build_dir] [TARGET target] [RETURN_VALUE res]\n" + " [APPEND][NUMBER_ERRORS val] [NUMBER_WARNINGS val])\n" "Builds the given build directory and stores results in Build.xml. " - "If no BUILD is given, the CTEST_BINARY_DIRECTORY variable is used. " + "If no BUILD is given, the CTEST_BINARY_DIRECTORY variable is used.\n" + "The TARGET variable can be used to specify a build target. If none " + "is specified, the \"all\" target will be built.\n" "The RETURN_VALUE option specifies a variable in which to store the " "return value of the native build tool. " "The NUMBER_ERRORS and NUMBER_WARNINGS options specify variables in " diff --git a/Source/CTest/cmCTestBuildHandler.cxx b/Source/CTest/cmCTestBuildHandler.cxx index a125459..9678ac4 100644 --- a/Source/CTest/cmCTestBuildHandler.cxx +++ b/Source/CTest/cmCTestBuildHandler.cxx @@ -43,6 +43,7 @@ static const char* cmCTestErrorMatches[] = { "^[Bb]us [Ee]rror", "^[Ss]egmentation [Vv]iolation", "^[Ss]egmentation [Ff]ault", + ":.*[Pp]ermission [Dd]enied", "([^ :]+):([0-9]+): ([^ \\t])", "([^:]+): error[ \\t]*[0-9]+[ \\t]*:", "^Error ([0-9]+):", @@ -61,11 +62,11 @@ static const char* cmCTestErrorMatches[] = { ": syntax error ", "^collect2: ld returned 1 exit status", "ld terminated with signal", - "Unsatisfied symbols:", + "Unsatisfied symbol", "^Unresolved:", - "Undefined symbols:", + "Undefined symbol", "^Undefined[ \\t]+first referenced", - "^CMake Error:", + "^CMake Error.*:", ":[ \\t]cannot find", ":[ \\t]can't find", ": \\*\\*\\* No rule to make target \\`.*\\'. Stop", @@ -129,6 +130,7 @@ static const char* cmCTestWarningMatches[] = { "\\([0-9]*\\): remark #[0-9]*", "\".*\", line [0-9]+: remark\\([0-9]*\\):", "cc-[0-9]* CC: REMARK File = .*, Line = [0-9]*", + "^CMake Warning.*:", 0 }; @@ -174,8 +176,8 @@ cmCTestWarningErrorFileLine[] = { //---------------------------------------------------------------------- cmCTestBuildHandler::cmCTestBuildHandler() { - this->MaxPreContext = 6; - this->MaxPostContext = 6; + this->MaxPreContext = 10; + this->MaxPostContext = 10; this->MaxErrors = 50; this->MaxWarnings = 50; @@ -214,8 +216,8 @@ void cmCTestBuildHandler::Initialize() this->ErrorsAndWarnings.clear(); this->LastErrorOrWarning = this->ErrorsAndWarnings.end(); this->PostContextCount = 0; - this->MaxPreContext = 6; - this->MaxPostContext = 6; + this->MaxPreContext = 10; + this->MaxPostContext = 10; this->PreContext.clear(); this->TotalErrors = 0; @@ -249,6 +251,20 @@ void cmCTestBuildHandler::PopulateCustomVectors(cmMakefile *mf) "CTEST_CUSTOM_MAXIMUM_NUMBER_OF_WARNINGS", this->MaxWarnings); + int n = -1; + this->CTest->PopulateCustomInteger(mf, "CTEST_CUSTOM_ERROR_PRE_CONTEXT", n); + if (n != -1) + { + this->MaxPreContext = static_cast<size_t>(n); + } + + n = -1; + this->CTest->PopulateCustomInteger(mf, "CTEST_CUSTOM_ERROR_POST_CONTEXT", n); + if (n != -1) + { + this->MaxPostContext = static_cast<size_t>(n); + } + // Record the user-specified custom warning rules. if(const char* customWarningMatchers = mf->GetDefinition("CTEST_CUSTOM_WARNING_MATCH")) @@ -551,6 +567,7 @@ class cmCTestBuildHandler::FragmentCompare { public: FragmentCompare(cmFileTimeComparison* ftc): FTC(ftc) {} + FragmentCompare(): FTC(0) {} bool operator()(std::string const& l, std::string const& r) { // Order files by modification time. Use lexicographic order @@ -958,7 +975,7 @@ int cmCTestBuildHandler::RunMakeCommand(const char* command, this->ProcessBuffer(0, 0, tick, tick_len, ofs, &this->BuildProcessingErrorQueue); cmCTestLog(this->CTest, OUTPUT, " Size of output: " - << int(this->BuildOutputLogSize / 1024.0) << "K" << std::endl); + << ((this->BuildOutputLogSize + 512) / 1024) << "K" << std::endl); // Properly handle output of the build command cmsysProcess_WaitForExit(cp, 0); @@ -1170,7 +1187,7 @@ void cmCTestBuildHandler::ProcessBuffer(const char* data, int length, if ( tick % tick_line_len == 0 && tick > 0 ) { cmCTestLog(this->CTest, HANDLER_OUTPUT, " Size: " - << int((this->BuildOutputLogSize / 1024.0) + 1) << "K" << std::endl + << ((this->BuildOutputLogSize + 512) / 1024) << "K" << std::endl << " "); } } diff --git a/Source/CTest/cmCTestConfigureCommand.cxx b/Source/CTest/cmCTestConfigureCommand.cxx index 1ad4e24..9a668bc 100644 --- a/Source/CTest/cmCTestConfigureCommand.cxx +++ b/Source/CTest/cmCTestConfigureCommand.cxx @@ -89,6 +89,16 @@ cmCTestGenericHandler* cmCTestConfigureCommand::InitializeHandler() return 0; } + const std::string cmakelists_file = source_dir + "/CMakeLists.txt"; + if ( !cmSystemTools::FileExists(cmakelists_file.c_str()) ) + { + cmOStringStream e; + e << "CMakeLists.txt file does not exist [" + << cmakelists_file << "]"; + this->SetError(e.str().c_str()); + return 0; + } + bool multiConfig = false; bool cmakeBuildTypeInOptions = false; @@ -122,7 +132,8 @@ cmCTestGenericHandler* cmCTestConfigureCommand::InitializeHandler() } } - if (!multiConfig && !cmakeBuildTypeInOptions) + if (!multiConfig && !cmakeBuildTypeInOptions && + !this->CTest->GetConfigType().empty()) { cmakeConfigureCommand += " \"-DCMAKE_BUILD_TYPE:STRING="; cmakeConfigureCommand += this->CTest->GetConfigType(); diff --git a/Source/CTest/cmCTestCoverageHandler.cxx b/Source/CTest/cmCTestCoverageHandler.cxx index 1076886..6863adc 100644 --- a/Source/CTest/cmCTestCoverageHandler.cxx +++ b/Source/CTest/cmCTestCoverageHandler.cxx @@ -10,6 +10,7 @@ See the License for more information. ============================================================================*/ #include "cmCTestCoverageHandler.h" +#include "cmParsePHPCoverage.h" #include "cmCTest.h" #include "cmake.h" #include "cmMakefile.h" @@ -126,20 +127,6 @@ private: //---------------------------------------------------------------------- -//********************************************************************** -class cmCTestCoverageHandlerContainer -{ -public: - int Error; - std::string SourceDir; - std::string BinaryDir; - typedef std::vector<int> SingleFileCoverageVector; - typedef std::map<std::string, SingleFileCoverageVector> TotalCoverageMap; - TotalCoverageMap TotalCoverage; - std::ostream* OFS; -}; -//********************************************************************** -//---------------------------------------------------------------------- //---------------------------------------------------------------------- cmCTestCoverageHandler::cmCTestCoverageHandler() @@ -380,7 +367,6 @@ int cmCTestCoverageHandler::ProcessHandler() cmsys::RegularExpression(rexIt->c_str())); } - if(this->HandleBullseyeCoverage(&cont)) { return cont.Error; @@ -396,8 +382,14 @@ int cmCTestCoverageHandler::ProcessHandler() { return error; } + file_count += this->HandlePHPCoverage(&cont); + if ( file_count < 0 ) + { + return error; + } error = cont.Error; + std::set<std::string> uncovered = this->FindUncoveredFiles(&cont); if ( file_count == 0 ) { @@ -437,7 +429,7 @@ int cmCTestCoverageHandler::ProcessHandler() //std::string fullBinaryDir = binaryDir + "/"; cmCTestLog(this->CTest, HANDLER_OUTPUT, std::endl); cmCTestLog(this->CTest, HANDLER_OUTPUT, - " Acumulating results (each . represents one file):" << std::endl); + " Accumulating results (each . represents one file):" << std::endl); cmCTestLog(this->CTest, HANDLER_OUTPUT, " "); std::vector<std::string> errorsWhileAccumulating; @@ -516,7 +508,7 @@ int cmCTestCoverageHandler::ProcessHandler() cmCTestCoverageHandlerContainer::SingleFileCoverageVector::size_type cc; std::string line; cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, - "Actually perfoming coverage for: " << fullFileName << std::endl); + "Actually performing coverage for: " << fullFileName << std::endl); for ( cc= 0; cc < fcov.size(); cc ++ ) { if ( !cmSystemTools::GetLineFromStream(ifs, line) && @@ -524,7 +516,7 @@ int cmCTestCoverageHandler::ProcessHandler() { cmOStringStream ostr; ostr << "Problem reading source file: " << fullFileName.c_str() - << " line:" << cc; + << " line:" << cc << " out total: " << fcov.size()-1; errorsWhileAccumulating.push_back(ostr.str()); error ++; break; @@ -577,13 +569,58 @@ int cmCTestCoverageHandler::ProcessHandler() this->WriteXMLLabels(covSumFile, shortFileName); covSumFile << "\t</File>" << std::endl; } + + //Handle all the files in the extra coverage globs that have no cov data + for(std::set<std::string>::iterator i = uncovered.begin(); + i != uncovered.end(); ++i) + { + std::string fileName = cmSystemTools::GetFilenameName(*i); + std::string fullPath = cont.SourceDir + "/" + *i; + + covLogFile << "\t<File Name=\"" << cmXMLSafe(fileName) + << "\" FullPath=\"" << cmXMLSafe(*i) << "\">\n" + << "\t\t<Report>" << std::endl; + + std::ifstream ifs(fullPath.c_str()); + if (!ifs) + { + cmOStringStream ostr; + ostr << "Cannot open source file: " << fullPath.c_str(); + errorsWhileAccumulating.push_back(ostr.str()); + error ++; + continue; + } + int untested = 0; + std::string line; + cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, + "Actually performing coverage for: " << i->c_str() << std::endl); + while (cmSystemTools::GetLineFromStream(ifs, line)) + { + covLogFile << "\t\t<Line Number=\"" << untested << "\" Count=\"0\">" + << cmXMLSafe(line) << "</Line>" << std::endl; + untested ++; + } + covLogFile << "\t\t</Report>\n\t</File>" << std::endl; + + total_untested += untested; + covSumFile << "\t<File Name=\"" << cmXMLSafe(fileName) + << "\" FullPath=\"" << cmXMLSafe(i->c_str()) + << "\" Covered=\"true\">\n" + << "\t\t<LOCTested>0</LOCTested>\n" + << "\t\t<LOCUnTested>" << untested << "</LOCUnTested>\n" + << "\t\t<PercentCoverage>0</PercentCoverage>\n" + << "\t\t<CoverageMetric>0</CoverageMetric>\n"; + this->WriteXMLLabels(covSumFile, *i); + covSumFile << "\t</File>" << std::endl; + } + this->EndCoverageLogFile(covLogFile, logFileCount); if ( errorsWhileAccumulating.size() > 0 ) { cmCTestLog(this->CTest, ERROR_MESSAGE, std::endl); cmCTestLog(this->CTest, ERROR_MESSAGE, - "Error(s) while acumulating results:" << std::endl); + "Error(s) while accumulating results:" << std::endl); std::vector<std::string>::iterator erIt; for ( erIt = errorsWhileAccumulating.begin(); erIt != errorsWhileAccumulating.end(); @@ -654,6 +691,8 @@ void cmCTestCoverageHandler::PopulateCustomVectors(cmMakefile *mf) " Add coverage exclude regular expressions." << std::endl); this->CTest->PopulateCustomVector(mf, "CTEST_CUSTOM_COVERAGE_EXCLUDE", this->CustomCoverageExclude); + this->CTest->PopulateCustomVector(mf, "CTEST_EXTRA_COVERAGE_GLOB", + this->ExtraCoverageGlobs); std::vector<cmStdString>::iterator it; for ( it = this->CustomCoverageExclude.begin(); it != this->CustomCoverageExclude.end(); @@ -662,6 +701,12 @@ void cmCTestCoverageHandler::PopulateCustomVectors(cmMakefile *mf) cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, " Add coverage exclude: " << it->c_str() << std::endl); } + for ( it = this->ExtraCoverageGlobs.begin(); + it != this->ExtraCoverageGlobs.end(); ++it) + { + cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, " Add coverage glob: " + << it->c_str() << std::endl); + } } //---------------------------------------------------------------------- @@ -695,6 +740,18 @@ bool IsFileInDir(const std::string &infile, const std::string &indir) } //---------------------------------------------------------------------- +int cmCTestCoverageHandler::HandlePHPCoverage( + cmCTestCoverageHandlerContainer* cont) +{ + cmParsePHPCoverage cov(*cont, this->CTest); + std::string coverageDir = this->CTest->GetBinaryDir() + "/xdebugCoverage"; + if(cmSystemTools::FileIsDirectory(coverageDir.c_str())) + { + cov.ReadPHPCoverageDirectory(coverageDir.c_str()); + } + return static_cast<int>(cont->TotalCoverage.size()); +} +//---------------------------------------------------------------------- int cmCTestCoverageHandler::HandleGCovCoverage( cmCTestCoverageHandlerContainer* cont) { @@ -1703,6 +1760,7 @@ int cmCTestCoverageHandler::RunBullseyeSourceSummary( << "</ElapsedMinutes>" << "</Coverage>" << std::endl; this->CTest->EndXML(covSumFile); + // Now create the coverage information for each file return this->RunBullseyeCoverageBranch(cont, coveredFileNames, @@ -1961,3 +2019,43 @@ bool cmCTestCoverageHandler::IsFilteredOut(std::string const& source) } return true; } + +//---------------------------------------------------------------------- +std::set<std::string> cmCTestCoverageHandler::FindUncoveredFiles( + cmCTestCoverageHandlerContainer* cont) +{ + std::set<std::string> extraMatches; + + for(std::vector<cmStdString>::iterator i = this->ExtraCoverageGlobs.begin(); + i != this->ExtraCoverageGlobs.end(); ++i) + { + cmsys::Glob gl; + gl.RecurseOn(); + gl.RecurseThroughSymlinksOff(); + std::string glob = cont->SourceDir + "/" + *i; + gl.FindFiles(glob); + std::vector<std::string> files = gl.GetFiles(); + for(std::vector<std::string>::iterator f = files.begin(); + f != files.end(); ++f) + { + if(this->ShouldIDoCoverage(f->c_str(), + cont->SourceDir.c_str(), cont->BinaryDir.c_str())) + { + extraMatches.insert(this->CTest->GetShortPathToFile( + f->c_str())); + } + } + } + + if(extraMatches.size()) + { + for(cmCTestCoverageHandlerContainer::TotalCoverageMap::iterator i = + cont->TotalCoverage.begin(); i != cont->TotalCoverage.end(); ++i) + { + std::string shortPath = this->CTest->GetShortPathToFile( + i->first.c_str()); + extraMatches.erase(shortPath); + } + } + return extraMatches; +} diff --git a/Source/CTest/cmCTestCoverageHandler.h b/Source/CTest/cmCTestCoverageHandler.h index b3e4db6..d3e8503 100644 --- a/Source/CTest/cmCTestCoverageHandler.h +++ b/Source/CTest/cmCTestCoverageHandler.h @@ -20,8 +20,17 @@ #include <cmsys/RegularExpression.hxx> class cmGeneratedFileStream; -class cmCTestCoverageHandlerContainer; - +class cmCTestCoverageHandlerContainer +{ +public: + int Error; + std::string SourceDir; + std::string BinaryDir; + typedef std::vector<int> SingleFileCoverageVector; + typedef std::map<std::string, SingleFileCoverageVector> TotalCoverageMap; + TotalCoverageMap TotalCoverage; + std::ostream* OFS; +}; /** \class cmCTestCoverageHandler * \brief A class that handles coverage computaiton for ctest * @@ -59,6 +68,9 @@ private: int HandleGCovCoverage(cmCTestCoverageHandlerContainer* cont); void FindGCovFiles(std::vector<std::string>& files); + //! Handle coverage using xdebug php coverage + int HandlePHPCoverage(cmCTestCoverageHandlerContainer* cont); + //! Handle coverage using Bullseye int HandleBullseyeCoverage(cmCTestCoverageHandlerContainer* cont); int RunBullseyeSourceSummary(cmCTestCoverageHandlerContainer* cont); @@ -66,6 +78,7 @@ private: std::set<cmStdString>& coveredFileNames, std::vector<std::string>& files, std::vector<std::string>& filesFullPath); + int RunBullseyeCommand( cmCTestCoverageHandlerContainer* cont, const char* cmd, @@ -91,52 +104,12 @@ private: std::string FindFile(cmCTestCoverageHandlerContainer* cont, std::string fileName); - struct cmCTestCoverage - { - cmCTestCoverage() - { - this->AbsolutePath = ""; - this->FullPath = ""; - this->Covered = false; - this->Tested = 0; - this->UnTested = 0; - this->Lines.clear(); - this->Show = false; - } - cmCTestCoverage(const cmCTestCoverage& rhs) : - AbsolutePath(rhs.AbsolutePath), - FullPath(rhs.FullPath), - Covered(rhs.Covered), - Tested(rhs.Tested), - UnTested(rhs.UnTested), - Lines(rhs.Lines), - Show(rhs.Show) - { - } - cmCTestCoverage& operator=(const cmCTestCoverage& rhs) - { - this->AbsolutePath = rhs.AbsolutePath; - this->FullPath = rhs.FullPath; - this->Covered = rhs.Covered; - this->Tested = rhs.Tested; - this->UnTested = rhs.UnTested; - this->Lines = rhs.Lines; - this->Show = rhs.Show; - return *this; - } - std::string AbsolutePath; - std::string FullPath; - bool Covered; - int Tested; - int UnTested; - std::vector<int> Lines; - bool Show; - }; - + std::set<std::string> FindUncoveredFiles( + cmCTestCoverageHandlerContainer* cont); std::vector<cmStdString> CustomCoverageExclude; std::vector<cmsys::RegularExpression> CustomCoverageExcludeRegex; + std::vector<cmStdString> ExtraCoverageGlobs; - typedef std::map<std::string, cmCTestCoverage> CoverageMap; // Map from source file to label ids. class LabelSet: public std::set<int> {}; diff --git a/Source/CTest/cmCTestGIT.cxx b/Source/CTest/cmCTestGIT.cxx index 5b0e8ff..aa9e55b 100644 --- a/Source/CTest/cmCTestGIT.cxx +++ b/Source/CTest/cmCTestGIT.cxx @@ -19,6 +19,8 @@ #include <cmsys/ios/sstream> #include <cmsys/Process.h> +#include <sys/types.h> +#include <time.h> #include <ctype.h> //---------------------------------------------------------------------------- @@ -83,14 +85,83 @@ void cmCTestGIT::NoteNewRevision() } //---------------------------------------------------------------------------- -bool cmCTestGIT::UpdateImpl() +std::string cmCTestGIT::FindGitDir() +{ + std::string git_dir; + + // Run "git rev-parse --git-dir" to locate the real .git directory. + const char* git = this->CommandLineTool.c_str(); + char const* git_rev_parse[] = {git, "rev-parse", "--git-dir", 0}; + std::string git_dir_line; + OneLineParser rev_parse_out(this, "rev-parse-out> ", git_dir_line); + OutputLogger rev_parse_err(this->Log, "rev-parse-err> "); + if(this->RunChild(git_rev_parse, &rev_parse_out, &rev_parse_err)) + { + git_dir = git_dir_line; + } + if(git_dir.empty()) + { + git_dir = ".git"; + } + + // Git reports a relative path only when the .git directory is in + // the current directory. + if(git_dir[0] == '.') + { + git_dir = this->SourceDirectory + "/" + git_dir; + } +#if defined(_WIN32) && !defined(__CYGWIN__) + 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"; + if(cmSystemTools::FileExists(cygpath_exe.c_str())) + { + char const* cygpath[] = {cygpath_exe.c_str(), "-w", git_dir.c_str(), 0}; + OneLineParser cygpath_out(this, "cygpath-out> ", git_dir_line); + OutputLogger cygpath_err(this->Log, "cygpath-err> "); + if(this->RunChild(cygpath, &cygpath_out, &cygpath_err)) + { + git_dir = git_dir_line; + } + } + } +#endif + return git_dir; +} + +//---------------------------------------------------------------------------- +std::string cmCTestGIT::FindTopDir() +{ + std::string top_dir = this->SourceDirectory; + + // Run "git rev-parse --show-cdup" to locate the top of the tree. + const char* git = this->CommandLineTool.c_str(); + char const* git_rev_parse[] = {git, "rev-parse", "--show-cdup", 0}; + std::string cdup; + OneLineParser rev_parse_out(this, "rev-parse-out> ", cdup); + OutputLogger rev_parse_err(this->Log, "rev-parse-err> "); + if(this->RunChild(git_rev_parse, &rev_parse_out, &rev_parse_err) && + !cdup.empty()) + { + top_dir += "/"; + top_dir += cdup; + top_dir = cmSystemTools::CollapseFullPath(top_dir.c_str()); + } + return top_dir; +} + +//---------------------------------------------------------------------------- +bool cmCTestGIT::UpdateByFetchAndReset() { - // Use "git pull" to update the working tree. - std::vector<char const*> git_pull; - git_pull.push_back(this->CommandLineTool.c_str()); - git_pull.push_back("pull"); + const char* git = this->CommandLineTool.c_str(); - // TODO: if(this->CTest->GetTestModel() == cmCTest::NIGHTLY) + // Use "git fetch" to get remote commits. + std::vector<char const*> git_fetch; + git_fetch.push_back(git); + git_fetch.push_back("fetch"); // Add user-specified update options. std::string opts = this->CTest->GetCTestConfiguration("UpdateOptions"); @@ -102,15 +173,101 @@ bool cmCTestGIT::UpdateImpl() for(std::vector<cmStdString>::const_iterator ai = args.begin(); ai != args.end(); ++ai) { - git_pull.push_back(ai->c_str()); + git_fetch.push_back(ai->c_str()); } // Sentinel argument. - git_pull.push_back(0); + git_fetch.push_back(0); + + // Fetch upstream refs. + OutputLogger fetch_out(this->Log, "fetch-out> "); + OutputLogger fetch_err(this->Log, "fetch-err> "); + if(!this->RunUpdateCommand(&git_fetch[0], &fetch_out, &fetch_err)) + { + return false; + } + + // Identify the merge head that would be used by "git pull". + std::string sha1; + { + std::string fetch_head = this->FindGitDir() + "/FETCH_HEAD"; + std::ifstream fin(fetch_head.c_str(), std::ios::in | std::ios::binary); + if(!fin) + { + this->Log << "Unable to open " << fetch_head << "\n"; + return false; + } + std::string line; + while(sha1.empty() && cmSystemTools::GetLineFromStream(fin, line)) + { + this->Log << "FETCH_HEAD> " << line << "\n"; + if(line.find("\tnot-for-merge\t") == line.npos) + { + std::string::size_type pos = line.find('\t'); + if(pos != line.npos) + { + sha1 = line.substr(0, pos); + } + } + } + if(sha1.empty()) + { + this->Log << "FETCH_HEAD has no upstream branch candidate!\n"; + return false; + } + } + + // Reset the local branch to point at that tracked from upstream. + char const* git_reset[] = {git, "reset", "--hard", sha1.c_str(), 0}; + OutputLogger reset_out(this->Log, "reset-out> "); + OutputLogger reset_err(this->Log, "reset-err> "); + return this->RunChild(&git_reset[0], &reset_out, &reset_err); +} + +//---------------------------------------------------------------------------- +bool cmCTestGIT::UpdateByCustom(std::string const& custom) +{ + std::vector<std::string> git_custom_command; + cmSystemTools::ExpandListArgument(custom, git_custom_command, true); + std::vector<char const*> git_custom; + for(std::vector<std::string>::const_iterator + i = git_custom_command.begin(); i != git_custom_command.end(); ++i) + { + git_custom.push_back(i->c_str()); + } + git_custom.push_back(0); + + OutputLogger custom_out(this->Log, "custom-out> "); + OutputLogger custom_err(this->Log, "custom-err> "); + return this->RunUpdateCommand(&git_custom[0], &custom_out, &custom_err); +} + +//---------------------------------------------------------------------------- +bool cmCTestGIT::UpdateInternal() +{ + std::string custom = this->CTest->GetCTestConfiguration("GITUpdateCustom"); + if(!custom.empty()) + { + return this->UpdateByCustom(custom); + } + return this->UpdateByFetchAndReset(); +} + +//---------------------------------------------------------------------------- +bool cmCTestGIT::UpdateImpl() +{ + if(!this->UpdateInternal()) + { + return false; + } - OutputLogger out(this->Log, "pull-out> "); - OutputLogger err(this->Log, "pull-err> "); - return this->RunUpdateCommand(&git_pull[0], &out, &err); + std::string top_dir = this->FindTopDir(); + const char* git = this->CommandLineTool.c_str(); + char const* git_submodule[] = {git, "submodule", "update", 0}; + OutputLogger submodule_out(this->Log, "submodule-out> "); + OutputLogger submodule_err(this->Log, "submodule-err> "); + return this->RunChild(git_submodule, &submodule_out, &submodule_err, + top_dir.c_str()); } //---------------------------------------------------------------------------- @@ -242,8 +399,12 @@ protected: \n Log message indented by (4) spaces\n (even blank lines have the spaces)\n + [[ \n [Diff format] + OR + \0 + ]] The header may have more fields. See 'git help diff-tree'. */ @@ -297,6 +458,11 @@ private: { if(this->Line.empty()) { + if(this->Section == SectionBody && this->LineEnd == '\0') + { + // Skip SectionDiff + this->NextSection(); + } this->NextSection(); } else @@ -336,16 +502,16 @@ private: Person author; this->ParsePerson(this->Line.c_str()+7, author); this->Rev.Author = author.Name; - char buf[1024]; - if(author.TimeZone >= 0) - { - sprintf(buf, "%lu +%04ld", author.Time, author.TimeZone); - } - else - { - sprintf(buf, "%lu -%04ld", author.Time, -author.TimeZone); - } - this->Rev.Date = buf; + this->Rev.EMail = author.EMail; + this->Rev.Date = this->FormatDateTime(author); + } + else if(strncmp(this->Line.c_str(), "committer ", 10) == 0) + { + Person committer; + this->ParsePerson(this->Line.c_str()+10, committer); + this->Rev.Committer = committer.Name; + this->Rev.CommitterEMail = committer.EMail; + this->Rev.CommitDate = this->FormatDateTime(committer); } } @@ -358,6 +524,32 @@ private: } this->Rev.Log += "\n"; } + + std::string FormatDateTime(Person const& person) + { + // Convert the time to a human-readable format that is also easy + // to machine-parse: "CCYY-MM-DD hh:mm:ss". + time_t seconds = static_cast<time_t>(person.Time); + struct tm* t = gmtime(&seconds); + char dt[1024]; + sprintf(dt, "%04d-%02d-%02d %02d:%02d:%02d", + t->tm_year+1900, t->tm_mon+1, t->tm_mday, + t->tm_hour, t->tm_min, t->tm_sec); + std::string out = dt; + + // Add the time-zone field "+zone" or "-zone". + char tz[32]; + if(person.TimeZone >= 0) + { + sprintf(tz, " +%04ld", person.TimeZone); + } + else + { + sprintf(tz, " -%04ld", -person.TimeZone); + } + out += tz; + return out; + } }; char const cmCTestGIT::CommitParser::SectionSep[SectionCount] = @@ -395,10 +587,16 @@ void cmCTestGIT::LoadRevisions() //---------------------------------------------------------------------------- void cmCTestGIT::LoadModifications() { - // Use 'git diff-index' to get modified files. const char* git = this->CommandLineTool.c_str(); - const char* git_diff_index[] = {git, "diff-index", "-z", "HEAD", 0}; + // Use 'git update-index' to refresh the index w.r.t. the work tree. + const char* git_update_index[] = {git, "update-index", "--refresh", 0}; + OutputLogger ui_out(this->Log, "ui-out> "); + OutputLogger ui_err(this->Log, "ui-err> "); + this->RunChild(git_update_index, &ui_out, &ui_err); + + // Use 'git diff-index' to get modified files. + const char* git_diff_index[] = {git, "diff-index", "-z", "HEAD", 0}; DiffParser out(this, "di-out> "); OutputLogger err(this->Log, "di-err> "); this->RunChild(git_diff_index, &out, &err); diff --git a/Source/CTest/cmCTestGIT.h b/Source/CTest/cmCTestGIT.h index 2561ed4..1765340 100644 --- a/Source/CTest/cmCTestGIT.h +++ b/Source/CTest/cmCTestGIT.h @@ -32,9 +32,17 @@ private: virtual void NoteNewRevision(); virtual bool UpdateImpl(); + std::string FindGitDir(); + std::string FindTopDir(); + + bool UpdateByFetchAndReset(); + bool UpdateByCustom(std::string const& custom); + bool UpdateInternal(); + void LoadRevisions(); void LoadModifications(); +public: // needed by older Sun compilers // Parsing helper classes. class OneLineParser; class DiffParser; diff --git a/Source/CTest/cmCTestGlobalVC.cxx b/Source/CTest/cmCTestGlobalVC.cxx index 73a36da..8c51102 100644 --- a/Source/CTest/cmCTestGlobalVC.cxx +++ b/Source/CTest/cmCTestGlobalVC.cxx @@ -107,6 +107,19 @@ void cmCTestGlobalVC::WriteXMLDirectory(std::ostream& xml, } //---------------------------------------------------------------------------- +void cmCTestGlobalVC::WriteXMLGlobal(std::ostream& xml) +{ + if(!this->NewRevision.empty()) + { + xml << "\t<Revision>" << this->NewRevision << "</Revision>\n"; + } + if(!this->OldRevision.empty() && this->OldRevision != this->NewRevision) + { + xml << "\t<PriorRevision>" << this->OldRevision << "</PriorRevision>\n"; + } +} + +//---------------------------------------------------------------------------- bool cmCTestGlobalVC::WriteXMLUpdates(std::ostream& xml) { cmCTestLog(this->CTest, HANDLER_OUTPUT, @@ -117,6 +130,8 @@ bool cmCTestGlobalVC::WriteXMLUpdates(std::ostream& xml) this->LoadModifications(); + this->WriteXMLGlobal(xml); + for(std::map<cmStdString, Directory>::const_iterator di = this->Dirs.begin(); di != this->Dirs.end(); ++di) { diff --git a/Source/CTest/cmCTestGlobalVC.h b/Source/CTest/cmCTestGlobalVC.h index d88016b..a648a59 100644 --- a/Source/CTest/cmCTestGlobalVC.h +++ b/Source/CTest/cmCTestGlobalVC.h @@ -60,6 +60,7 @@ protected: virtual void LoadModifications() = 0; virtual void LoadRevisions() = 0; + virtual void WriteXMLGlobal(std::ostream& xml); void WriteXMLDirectory(std::ostream& xml, std::string const& path, Directory const& dir); }; diff --git a/Source/CTest/cmCTestHG.cxx b/Source/CTest/cmCTestHG.cxx index b263677..86a7617 100644 --- a/Source/CTest/cmCTestHG.cxx +++ b/Source/CTest/cmCTestHG.cxx @@ -220,7 +220,7 @@ private: } else if ( strcmp(name, "email") == 0 && !this->CData.empty()) { - // this->Rev.Email.assign(&this->CData[0], this->CData.size()); + this->Rev.EMail.assign(&this->CData[0], this->CData.size()); } else if(strcmp(name, "date") == 0 && !this->CData.empty()) { diff --git a/Source/CTest/cmCTestLaunch.cxx b/Source/CTest/cmCTestLaunch.cxx index 8e305b7..9831d02 100644 --- a/Source/CTest/cmCTestLaunch.cxx +++ b/Source/CTest/cmCTestLaunch.cxx @@ -220,6 +220,13 @@ void cmCTestLaunch::ComputeFileNames() //---------------------------------------------------------------------------- void cmCTestLaunch::RunChild() { + // Ignore noopt make rules + if(this->RealArgs.empty() || this->RealArgs[0] == ":") + { + this->ExitCode = 0; + return; + } + // Prepare to run the real command. cmsysProcess* cp = this->Process; cmsysProcess_SetCommand(cp, this->RealArgV); diff --git a/Source/CTest/cmCTestMemCheckHandler.cxx b/Source/CTest/cmCTestMemCheckHandler.cxx index 0d15ddc..13a25cb 100644 --- a/Source/CTest/cmCTestMemCheckHandler.cxx +++ b/Source/CTest/cmCTestMemCheckHandler.cxx @@ -201,8 +201,7 @@ void cmCTestMemCheckHandler::Initialize() this->CustomMaximumPassedTestOutputSize = 0; this->CustomMaximumFailedTestOutputSize = 0; this->MemoryTester = ""; - this->MemoryTesterOptionsParsed.clear(); - this->MemoryTesterOptions = ""; + this->MemoryTesterOptions.clear(); this->MemoryTesterStyle = UNKNOWN; this->MemoryTesterOutputFile = ""; int cc; @@ -249,12 +248,12 @@ void cmCTestMemCheckHandler::GenerateTestCommand( std::vector<cmStdString>::size_type pp; std::string memcheckcommand = ""; memcheckcommand = this->MemoryTester; - for ( pp = 0; pp < this->MemoryTesterOptionsParsed.size(); pp ++ ) + for ( pp = 0; pp < this->MemoryTesterOptions.size(); pp ++ ) { - args.push_back(this->MemoryTesterOptionsParsed[pp]); - memcheckcommand += " "; - memcheckcommand += cmSystemTools::EscapeSpaces( - this->MemoryTesterOptionsParsed[pp].c_str()); + args.push_back(this->MemoryTesterOptions[pp]); + memcheckcommand += " \""; + memcheckcommand += this->MemoryTesterOptions[pp]; + memcheckcommand += "\""; } cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Memory check command: " << memcheckcommand << std::endl); @@ -440,18 +439,21 @@ bool cmCTestMemCheckHandler::InitializeMemoryChecking() } // Setup the options + std::string memoryTesterOptions; if ( this->CTest->GetCTestConfiguration( "MemoryCheckCommandOptions").size() ) { - this->MemoryTesterOptions = this->CTest->GetCTestConfiguration( + memoryTesterOptions = this->CTest->GetCTestConfiguration( "MemoryCheckCommandOptions"); } else if ( this->CTest->GetCTestConfiguration( "ValgrindCommandOptions").size() ) { - this->MemoryTesterOptions = this->CTest->GetCTestConfiguration( + memoryTesterOptions = this->CTest->GetCTestConfiguration( "ValgrindCommandOptions"); } + this->MemoryTesterOptions + = cmSystemTools::ParseArguments(memoryTesterOptions.c_str()); this->MemoryTesterOutputFile = this->CTest->GetBinaryDir() + "/Testing/Temporary/MemoryChecker.log"; @@ -459,10 +461,14 @@ bool cmCTestMemCheckHandler::InitializeMemoryChecking() if ( this->MemoryTester.find("valgrind") != std::string::npos ) { this->MemoryTesterStyle = cmCTestMemCheckHandler::VALGRIND; - if ( !this->MemoryTesterOptions.size() ) + if ( this->MemoryTesterOptions.empty() ) { - this->MemoryTesterOptions = "-q --tool=memcheck --leak-check=yes " - "--show-reachable=yes --workaround-gcc296-bugs=yes --num-callers=50"; + this->MemoryTesterOptions.push_back("-q"); + this->MemoryTesterOptions.push_back("--tool=memcheck"); + this->MemoryTesterOptions.push_back("--leak-check=yes"); + this->MemoryTesterOptions.push_back("--show-reachable=yes"); + this->MemoryTesterOptions.push_back("--workaround-gcc296-bugs=yes"); + this->MemoryTesterOptions.push_back("--num-callers=50"); } if ( this->CTest->GetCTestConfiguration( "MemoryCheckSuppressionFile").size() ) @@ -476,17 +482,15 @@ bool cmCTestMemCheckHandler::InitializeMemoryChecking() "MemoryCheckSuppressionFile").c_str() << std::endl); return false; } - this->MemoryTesterOptions += " --suppressions=" + - cmSystemTools::EscapeSpaces(this->CTest->GetCTestConfiguration( - "MemoryCheckSuppressionFile").c_str()) + ""; + std::string suppressions = "--suppressions=" + + this->CTest->GetCTestConfiguration("MemoryCheckSuppressionFile"); + this->MemoryTesterOptions.push_back(suppressions); } } else if ( this->MemoryTester.find("purify") != std::string::npos ) { this->MemoryTesterStyle = cmCTestMemCheckHandler::PURIFY; - std::string outputFile = - cmSystemTools::EscapeSpaces(this->MemoryTesterOutputFile.c_str()); - + std::string outputFile; #ifdef _WIN32 if( this->CTest->GetCTestConfiguration( "MemoryCheckSuppressionFile").size() ) @@ -500,31 +504,29 @@ bool cmCTestMemCheckHandler::InitializeMemoryChecking() "MemoryCheckSuppressionFile").c_str() << std::endl); return false; } - this->MemoryTesterOptions += " /FilterFiles=" + - cmSystemTools::EscapeSpaces(this->CTest->GetCTestConfiguration( - "MemoryCheckSuppressionFile").c_str()); + std::string filterFiles = "/FilterFiles=" + + this->CTest->GetCTestConfiguration("MemoryCheckSuppressionFile"); + this->MemoryTesterOptions.push_back(filterFiles); } - this->MemoryTesterOptions += " /SAVETEXTDATA=" + outputFile; + outputFile = "/SAVETEXTDATA="; #else - this->MemoryTesterOptions += " -log-file=" + outputFile; + outputFile = "-log-file="; #endif + outputFile += this->MemoryTesterOutputFile; + this->MemoryTesterOptions.push_back(outputFile); } else if ( this->MemoryTester.find("BC") != std::string::npos ) { this->BoundsCheckerXMLFile = this->MemoryTesterOutputFile; - std::string outputFile = - cmSystemTools::EscapeSpaces(this->MemoryTesterOutputFile.c_str()); std::string dpbdFile = this->CTest->GetBinaryDir() + "/Testing/Temporary/MemoryChecker.DPbd"; - std::string errorFile = this->CTest->GetBinaryDir() - + "/Testing/Temporary/MemoryChecker.error"; - errorFile = cmSystemTools::EscapeSpaces(errorFile.c_str()); this->BoundsCheckerDPBDFile = dpbdFile; - dpbdFile = cmSystemTools::EscapeSpaces(dpbdFile.c_str()); this->MemoryTesterStyle = cmCTestMemCheckHandler::BOUNDS_CHECKER; - this->MemoryTesterOptions += " /B " + dpbdFile; - this->MemoryTesterOptions += " /X " + outputFile; - this->MemoryTesterOptions += " /M "; + this->MemoryTesterOptions.push_back("/B"); + this->MemoryTesterOptions.push_back(dpbdFile); + this->MemoryTesterOptions.push_back("/X"); + this->MemoryTesterOptions.push_back(this->MemoryTesterOutputFile); + this->MemoryTesterOptions.push_back("/M"); } else { @@ -534,8 +536,6 @@ bool cmCTestMemCheckHandler::InitializeMemoryChecking() return false; } - this->MemoryTesterOptionsParsed - = cmSystemTools::ParseArguments(this->MemoryTesterOptions.c_str()); std::vector<cmStdString>::size_type cc; for ( cc = 0; cmCTestMemCheckResultStrings[cc]; cc ++ ) { diff --git a/Source/CTest/cmCTestMemCheckHandler.h b/Source/CTest/cmCTestMemCheckHandler.h index db426f0..427d471 100644 --- a/Source/CTest/cmCTestMemCheckHandler.h +++ b/Source/CTest/cmCTestMemCheckHandler.h @@ -89,8 +89,7 @@ private: std::string BoundsCheckerDPBDFile; std::string BoundsCheckerXMLFile; std::string MemoryTester; - std::vector<cmStdString> MemoryTesterOptionsParsed; - std::string MemoryTesterOptions; + std::vector<cmStdString> MemoryTesterOptions; int MemoryTesterStyle; std::string MemoryTesterOutputFile; int MemoryTesterGlobalResults[NO_MEMORY_FAULT]; diff --git a/Source/CTest/cmCTestMultiProcessHandler.cxx b/Source/CTest/cmCTestMultiProcessHandler.cxx index a79f131..f3a4457 100644 --- a/Source/CTest/cmCTestMultiProcessHandler.cxx +++ b/Source/CTest/cmCTestMultiProcessHandler.cxx @@ -16,12 +16,31 @@ #include "cmSystemTools.h" #include <stdlib.h> #include <stack> +#include <float.h> + +class TestComparator +{ +public: + TestComparator(cmCTestMultiProcessHandler* handler) : Handler(handler) {} + ~TestComparator() {} + + // Sorts tests in descending order of cost + bool operator() (int index1, int index2) const + { + return Handler->Properties[index1]->Cost > + Handler->Properties[index2]->Cost; + } + +private: + cmCTestMultiProcessHandler* Handler; +}; cmCTestMultiProcessHandler::cmCTestMultiProcessHandler() { this->ParallelLevel = 1; this->Completed = 0; this->RunningCount = 0; + this->StopTimePassed = false; } cmCTestMultiProcessHandler::~cmCTestMultiProcessHandler() @@ -68,6 +87,10 @@ void cmCTestMultiProcessHandler::RunTests() this->StartNextTests(); while(this->Tests.size() != 0) { + if(this->StopTimePassed) + { + return; + } this->CheckOutput(); this->StartNextTests(); } @@ -76,6 +99,7 @@ void cmCTestMultiProcessHandler::RunTests() { } this->MarkFinished(); + this->UpdateCostData(); } //--------------------------------------------------------- @@ -85,6 +109,7 @@ void cmCTestMultiProcessHandler::StartTestProcess(int test) this->TestRunningMap[test] = true; // mark the test as running // now remove the test itself this->EraseTest(test); + this->RunningCount += GetProcessorsUsed(test); cmCTestRunTest* testRun = new cmCTestRunTest(this->TestHandler); testRun->SetIndex(test); @@ -93,12 +118,22 @@ void cmCTestMultiProcessHandler::StartTestProcess(int test) std::string current_dir = cmSystemTools::GetCurrentWorkingDirectory(); cmSystemTools::ChangeDirectory(this->Properties[test]->Directory.c_str()); + // Lock the resources we'll be using + this->LockResources(test); + if(testRun->StartTest(this->Total)) { this->RunningTests.insert(testRun); } + else if(testRun->IsStopTimePassed()) + { + this->StopTimePassed = true; + delete testRun; + return; + } else { + this->UnlockResources(test); this->Completed++; this->TestFinishMap[test] = true; this->TestRunningMap[test] = false; @@ -111,21 +146,36 @@ void cmCTestMultiProcessHandler::StartTestProcess(int test) } //--------------------------------------------------------- -void cmCTestMultiProcessHandler::EraseTest(int test) +void cmCTestMultiProcessHandler::LockResources(int index) { - this->Tests.erase(test); - for(TestCostMap::iterator i = this->TestCosts.begin(); - i != this->TestCosts.end(); ++i) + for(std::set<std::string>::iterator i = + this->Properties[index]->LockedResources.begin(); + i != this->Properties[index]->LockedResources.end(); ++i) { - if(i->second.find(test) != i->second.end()) - { - i->second.erase(test); - return; - } + this->LockedResources.insert(*i); } } //--------------------------------------------------------- +void cmCTestMultiProcessHandler::UnlockResources(int index) +{ + for(std::set<std::string>::iterator i = + this->Properties[index]->LockedResources.begin(); + i != this->Properties[index]->LockedResources.end(); ++i) + { + this->LockedResources.erase(*i); + } +} + +//--------------------------------------------------------- +void cmCTestMultiProcessHandler::EraseTest(int test) +{ + this->Tests.erase(test); + this->SortedTests.erase( + std::find(this->SortedTests.begin(), this->SortedTests.end(), test)); +} + +//--------------------------------------------------------- inline size_t cmCTestMultiProcessHandler::GetProcessorsUsed(int test) { size_t processors = @@ -144,6 +194,17 @@ inline size_t cmCTestMultiProcessHandler::GetProcessorsUsed(int test) //--------------------------------------------------------- bool cmCTestMultiProcessHandler::StartTest(int test) { + //Check for locked resources + for(std::set<std::string>::iterator i = + this->Properties[test]->LockedResources.begin(); + i != this->Properties[test]->LockedResources.end(); ++i) + { + if(this->LockedResources.find(*i) != this->LockedResources.end()) + { + return false; + } + } + // copy the depend tests locally because when // a test is finished it will be removed from the depend list // and we don't want to be iterating a list while removing from it @@ -193,38 +254,30 @@ void cmCTestMultiProcessHandler::StartNextTests() return; } - for(TestCostMap::reverse_iterator i = this->TestCosts.rbegin(); - i != this->TestCosts.rend(); ++i) + TestList copy = this->SortedTests; + for(TestList::iterator test = copy.begin(); test != copy.end(); ++test) { - TestSet tests = i->second; //copy the test set - for(TestSet::iterator test = tests.begin(); - test != tests.end(); ++test) + //in case this test has already been started due to dependency + if(this->TestRunningMap[*test] || this->TestFinishMap[*test]) { - //in case this test has already been started due to dependency - if(this->TestRunningMap[*test] || this->TestFinishMap[*test]) - { - continue; - } - size_t processors = GetProcessorsUsed(*test); - if(processors > numToStart) - { - return; - } - if(this->StartTest(*test)) - { - numToStart -= processors; - this->RunningCount += processors; - } - else - { - cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, std::endl - << "Test did not start waiting on depends to finish: " - << *test << "\n"); - } - if(numToStart == 0) + continue; + } + size_t processors = GetProcessorsUsed(*test); + if(processors > numToStart) + { + return; + } + if(this->StartTest(*test)) + { + if(this->StopTimePassed) { return; } + numToStart -= processors; + } + if(numToStart == 0) + { + return; } } } @@ -272,8 +325,7 @@ bool cmCTestMultiProcessHandler::CheckOutput() this->TestRunningMap[test] = false; this->RunningTests.erase(p); this->WriteCheckpoint(test); - this->WriteCostData(test, static_cast<float>( - p->GetTestResults().ExecutionTime)); + this->UnlockResources(test); this->RunningCount -= GetProcessorsUsed(test); delete p; } @@ -281,53 +333,158 @@ bool cmCTestMultiProcessHandler::CheckOutput() } //--------------------------------------------------------- -void cmCTestMultiProcessHandler::ReadCostData() +void cmCTestMultiProcessHandler::UpdateCostData() { - std::string fname = this->CTest->GetBinaryDir() - + "/Testing/Temporary/CTestCostData.txt"; + std::string fname = this->CTest->GetCostDataFile(); + std::string tmpout = fname + ".tmp"; + std::fstream fout; + fout.open(tmpout.c_str(), std::ios::out); - if(cmSystemTools::FileExists(fname.c_str(), true) - && this->ParallelLevel > 1) - { + PropertiesMap temp = this->Properties; + + if(cmSystemTools::FileExists(fname.c_str())) + { std::ifstream fin; fin.open(fname.c_str()); + std::string line; while(std::getline(fin, line)) { + if(line == "---") break; std::vector<cmsys::String> parts = cmSystemTools::SplitString(line.c_str(), ' '); + //Format: <name> <previous_runs> <avg_cost> + if(parts.size() < 3) break; + + std::string name = parts[0]; + int prev = atoi(parts[1].c_str()); + float cost = static_cast<float>(atof(parts[2].c_str())); + + int index = this->SearchByName(name); + if(index == -1) + { + // This test is not in memory. We just rewrite the entry + fout << name << " " << prev << " " << cost << "\n"; + } + else + { + // Update with our new average cost + fout << name << " " << this->Properties[index]->PreviousRuns << " " + << this->Properties[index]->Cost << "\n"; + temp.erase(index); + } + } + fin.close(); + cmSystemTools::RemoveFile(fname.c_str()); + } + + // Add all tests not previously listed in the file + for(PropertiesMap::iterator i = temp.begin(); i != temp.end(); ++i) + { + fout << i->second->Name << " " << i->second->PreviousRuns << " " + << i->second->Cost << "\n"; + } + + // Write list of failed tests + fout << "---\n"; + for(std::vector<cmStdString>::iterator i = this->Failed->begin(); + i != this->Failed->end(); ++i) + { + fout << i->c_str() << "\n"; + } + fout.close(); + cmSystemTools::RenameFile(tmpout.c_str(), fname.c_str()); +} + +//--------------------------------------------------------- +void cmCTestMultiProcessHandler::ReadCostData() +{ + std::string fname = this->CTest->GetCostDataFile(); + + if(cmSystemTools::FileExists(fname.c_str(), true)) + { + std::ifstream fin; + fin.open(fname.c_str()); + std::string line; + while(std::getline(fin, line)) + { + if(line == "---") break; + + std::vector<cmsys::String> parts = + cmSystemTools::SplitString(line.c_str(), ' '); + + // Probably an older version of the file, will be fixed next run + if(parts.size() < 3) + { + fin.close(); + return; + } + + std::string name = parts[0]; + int prev = atoi(parts[1].c_str()); + float cost = static_cast<float>(atof(parts[2].c_str())); - int index = atoi(parts[0].c_str()); - float cost = static_cast<float>(atof(parts[1].c_str())); - if(this->Properties[index] && this->Properties[index]->Cost == 0) + int index = this->SearchByName(name); + if(index == -1) continue; + + this->Properties[index]->PreviousRuns = prev; + // When not running in parallel mode, don't use cost data + if(this->ParallelLevel > 1 && + this->Properties[index] && + this->Properties[index]->Cost == 0) { this->Properties[index]->Cost = cost; } } + // Next part of the file is the failed tests + while(std::getline(fin, line)) + { + if(line != "") + { + this->LastTestsFailed.push_back(line); + } + } fin.close(); } - cmSystemTools::RemoveFile(fname.c_str()); } //--------------------------------------------------------- -void cmCTestMultiProcessHandler::CreateTestCostList() +int cmCTestMultiProcessHandler::SearchByName(std::string name) { - for(TestMap::iterator i = this->Tests.begin(); - i != this->Tests.end(); ++i) + int index = -1; + + for(PropertiesMap::iterator i = this->Properties.begin(); + i != this->Properties.end(); ++i) { - this->TestCosts[this->Properties[i->first]->Cost].insert(i->first); + if(i->second->Name == name) + { + index = i->first; + } } + return index; } //--------------------------------------------------------- -void cmCTestMultiProcessHandler::WriteCostData(int index, float cost) +void cmCTestMultiProcessHandler::CreateTestCostList() { - std::string fname = this->CTest->GetBinaryDir() - + "/Testing/Temporary/CTestCostData.txt"; - std::fstream fout; - fout.open(fname.c_str(), std::ios::app); - fout << index << " " << cost << "\n"; - fout.close(); + for(TestMap::iterator i = this->Tests.begin(); + i != this->Tests.end(); ++i) + { + SortedTests.push_back(i->first); + + //If the test failed last time, it should be run first, so max the cost. + //Only do this for parallel runs; in non-parallel runs, avoid clobbering + //the test's explicitly set cost. + if(this->ParallelLevel > 1 && + std::find(this->LastTestsFailed.begin(), this->LastTestsFailed.end(), + this->Properties[i->first]->Name) != this->LastTestsFailed.end()) + { + this->Properties[i->first]->Cost = FLT_MAX; + } + } + + TestComparator comp(this); + std::sort(SortedTests.begin(), SortedTests.end(), comp); } //--------------------------------------------------------- @@ -336,7 +493,7 @@ void cmCTestMultiProcessHandler::WriteCheckpoint(int index) std::string fname = this->CTest->GetBinaryDir() + "/Testing/Temporary/CTestCheckpoint.txt"; std::fstream fout; - fout.open(fname.c_str(), std::ios::app); + fout.open(fname.c_str(), std::ios::app | std::ios::out); fout << index << "\n"; fout.close(); } @@ -355,11 +512,13 @@ void cmCTestMultiProcessHandler::PrintTestList() { this->TestHandler->SetMaxIndex(this->FindMaxIndex()); int count = 0; + for (PropertiesMap::iterator it = this->Properties.begin(); it != this->Properties.end(); ++it) { count++; cmCTestTestHandler::cmCTestTestProperties& p = *it->second; + //push working dir std::string current_dir = cmSystemTools::GetCurrentWorkingDirectory(); cmSystemTools::ChangeDirectory(p.Directory.c_str()); @@ -369,6 +528,20 @@ void cmCTestMultiProcessHandler::PrintTestList() testRun.SetTestProperties(&p); testRun.ComputeArguments(); //logs the command in verbose mode + if(p.Labels.size()) //print the labels + { + cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Labels:"); + } + for(std::vector<std::string>::iterator label = p.Labels.begin(); + label != p.Labels.end(); ++label) + { + cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, " " << *label); + } + if(p.Labels.size()) //print the labels + { + cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, std::endl); + } + if (this->TestHandler->MemCheck) { cmCTestLog(this->CTest, HANDLER_OUTPUT, " Memory Check"); @@ -387,10 +560,36 @@ void cmCTestMultiProcessHandler::PrintTestList() //pop working dir cmSystemTools::ChangeDirectory(current_dir.c_str()); } + cmCTestLog(this->CTest, HANDLER_OUTPUT, std::endl << "Total Tests: " << this->Total << std::endl); } +void cmCTestMultiProcessHandler::PrintLabels() +{ + std::set<std::string> allLabels; + for (PropertiesMap::iterator it = this->Properties.begin(); + it != this->Properties.end(); ++it) + { + cmCTestTestHandler::cmCTestTestProperties& p = *it->second; + allLabels.insert(p.Labels.begin(), p.Labels.end()); + } + + if(allLabels.size()) + { + cmCTestLog(this->CTest, HANDLER_OUTPUT, "All Labels:" << std::endl); + } + else + { + cmCTestLog(this->CTest, HANDLER_OUTPUT, "No Labels Exist" << std::endl); + } + for(std::set<std::string>::iterator label = allLabels.begin(); + label != allLabels.end(); ++label) + { + cmCTestLog(this->CTest, HANDLER_OUTPUT, " " << *label << std::endl); + } +} + //--------------------------------------------------------- void cmCTestMultiProcessHandler::CheckResume() { @@ -450,43 +649,43 @@ int cmCTestMultiProcessHandler::FindMaxIndex() //Returns true if no cycles exist in the dependency graph bool cmCTestMultiProcessHandler::CheckCycles() { - cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, + cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Checking test dependency graph..." << std::endl); for(TestMap::iterator it = this->Tests.begin(); it != this->Tests.end(); ++it) { //DFS from each element to itself + int root = it->first; + std::set<int> visited; std::stack<int> s; - std::vector<int> visited; - s.push(it->first); - visited.push_back(it->first); - + s.push(root); while(!s.empty()) { int test = s.top(); s.pop(); - - for(TestSet::iterator d = this->Tests[test].begin(); - d != this->Tests[test].end(); ++d) + if(visited.insert(test).second) { - s.push(*d); - for(std::vector<int>::iterator v = visited.begin(); - v != visited.end(); ++v) + for(TestSet::iterator d = this->Tests[test].begin(); + d != this->Tests[test].end(); ++d) { - if(*v == *d) + if(*d == root) { //cycle exists - cmCTestLog(this->CTest, ERROR_MESSAGE, "Error: a cycle exists in " - "the test dependency graph for the test \"" - << this->Properties[*d]->Name << "\"." << std::endl - << "Please fix the cycle and run ctest again." << std::endl); + cmCTestLog(this->CTest, ERROR_MESSAGE, + "Error: a cycle exists in the test dependency graph " + "for the test \"" << this->Properties[root]->Name << + "\".\nPlease fix the cycle and run ctest again.\n"); return false; } + else + { + s.push(*d); + } } - visited.push_back(*d); } - visited.pop_back(); } } + cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, + "Checking test dependency graph end" << std::endl); return true; } diff --git a/Source/CTest/cmCTestMultiProcessHandler.h b/Source/CTest/cmCTestMultiProcessHandler.h index 16591b0..1483440 100644 --- a/Source/CTest/cmCTestMultiProcessHandler.h +++ b/Source/CTest/cmCTestMultiProcessHandler.h @@ -23,10 +23,11 @@ */ class cmCTestMultiProcessHandler { + friend class TestComparator; public: struct TestSet : public std::set<int> {}; struct TestMap : public std::map<int, TestSet> {}; - struct TestCostMap : public std::map<float, TestSet> {}; + struct TestList : public std::vector<int> {}; struct PropertiesMap : public std::map<int, cmCTestTestHandler::cmCTestTestProperties*> {}; @@ -38,6 +39,7 @@ public: void SetParallelLevel(size_t); virtual void RunTests(); void PrintTestList(); + void PrintLabels(); void SetPassFailVectors(std::vector<cmStdString>* passed, std::vector<cmStdString>* failed) @@ -55,8 +57,7 @@ public: cmCTestTestHandler * GetTestHandler() { return this->TestHandler; } -protected: - cmCTest* CTest; +protected: // Start the next test or tests as many as are allowed by // ParallelLevel void StartNextTests(); @@ -64,8 +65,12 @@ protected: bool StartTest(int test); // Mark the checkpoint for the given test void WriteCheckpoint(int index); - void WriteCostData(int index, float cost); + + void UpdateCostData(); void ReadCostData(); + // Return index of a test based on its name + int SearchByName(std::string name); + void CreateTestCostList(); // Removes the checkpoint file void MarkFinished(); @@ -80,14 +85,18 @@ protected: bool CheckCycles(); int FindMaxIndex(); inline size_t GetProcessorsUsed(int index); + + void LockResources(int index); + void UnlockResources(int index); // map from test number to set of depend tests TestMap Tests; - TestCostMap TestCosts; + TestList SortedTests; //Total number of tests we'll be running size_t Total; //Number of tests that are complete size_t Completed; size_t RunningCount; + bool StopTimePassed; //list of test properties (indices concurrent to the test map) PropertiesMap Properties; std::map<int, bool> TestRunningMap; @@ -95,10 +104,13 @@ protected: std::map<int, cmStdString> TestOutput; std::vector<cmStdString>* Passed; std::vector<cmStdString>* Failed; + std::vector<std::string> LastTestsFailed; + std::set<std::string> LockedResources; std::vector<cmCTestTestHandler::cmCTestTestResult>* TestResults; size_t ParallelLevel; // max number of process that can be run at once std::set<cmCTestRunTest*> RunningTests; // current running tests cmCTestTestHandler * TestHandler; + cmCTest* CTest; }; #endif diff --git a/Source/CTest/cmCTestRunScriptCommand.h b/Source/CTest/cmCTestRunScriptCommand.h index c2cda66..5765150 100644 --- a/Source/CTest/cmCTestRunScriptCommand.h +++ b/Source/CTest/cmCTestRunScriptCommand.h @@ -68,7 +68,7 @@ public: "Runs a script or scripts much like if it was run from ctest -S. " "If no argument is provided then the current script is run using " "the current settings of the variables. If NEW_PROCESS is specified " - "then each script will be run in a seperate process." + "then each script will be run in a separate process." "If RETURN_VALUE is specified the return value of the last script " "run will be put into var."; } diff --git a/Source/CTest/cmCTestRunTest.cxx b/Source/CTest/cmCTestRunTest.cxx index abeea47..42a4cff 100644 --- a/Source/CTest/cmCTestRunTest.cxx +++ b/Source/CTest/cmCTestRunTest.cxx @@ -14,6 +14,7 @@ #include "cmCTestMemCheckHandler.h" #include "cmCTest.h" #include "cmSystemTools.h" +#include "cm_curl.h" #include <cm_zlib.h> #include <cmsys/Base64.h> @@ -22,16 +23,16 @@ cmCTestRunTest::cmCTestRunTest(cmCTestTestHandler* handler) { this->CTest = handler->CTest; this->TestHandler = handler; - this->ModifyEnv = false; this->TestProcess = 0; this->TestResult.ExecutionTime =0; this->TestResult.ReturnValue = 0; - this->TestResult.Status = 0; + this->TestResult.Status = cmCTestTestHandler::NOT_RUN; this->TestResult.TestCount = 0; this->TestResult.Properties = 0; this->ProcessOutput = ""; this->CompressedOutput = ""; this->CompressionRatio = 2; + this->StopTimePassed = false; } cmCTestRunTest::~cmCTestRunTest() @@ -82,7 +83,8 @@ void cmCTestRunTest::CompressOutput() reinterpret_cast<unsigned char*>( const_cast<char*>(this->ProcessOutput.c_str())); //zlib makes the guarantee that this is the maximum output size - int outSize = static_cast<int>(this->ProcessOutput.size() * 1.001 + 13); + int outSize = static_cast<int>( + static_cast<double>(this->ProcessOutput.size()) * 1.001 + 13.0); unsigned char* out = new unsigned char[outSize]; strm.zalloc = Z_NULL; @@ -94,7 +96,7 @@ void cmCTestRunTest::CompressOutput() return; } - strm.avail_in = this->ProcessOutput.size(); + strm.avail_in = static_cast<uInt>(this->ProcessOutput.size()); strm.next_in = in; strm.avail_out = outSize; strm.next_out = out; @@ -108,20 +110,23 @@ void cmCTestRunTest::CompressOutput() } (void)deflateEnd(&strm); - + unsigned char *encoded_buffer = new unsigned char[static_cast<int>(outSize * 1.5)]; unsigned long rlen = cmsysBase64_Encode(out, strm.total_out, encoded_buffer, 1); - + for(unsigned long i = 0; i < rlen; i++) { this->CompressedOutput += encoded_buffer[i]; } - this->CompressionRatio = static_cast<double>(strm.total_out) / - static_cast<double>(strm.total_in); + if(strm.total_in) + { + this->CompressionRatio = static_cast<double>(strm.total_out) / + static_cast<double>(strm.total_in); + } delete [] encoded_buffer; delete [] out; @@ -135,11 +140,6 @@ bool cmCTestRunTest::EndTest(size_t completed, size_t total, bool started) this->CompressOutput(); } - //restore the old environment - if (this->ModifyEnv) - { - cmSystemTools::RestoreEnv(this->OrigEnv); - } this->WriteLogOutputTop(completed, total); std::string reason; bool passed = true; @@ -222,7 +222,7 @@ bool cmCTestRunTest::EndTest(size_t completed, size_t total, bool started) { outputTestErrorsToConsole = this->CTest->OutputTestOutputOnTestFailure; cmCTestLog(this->CTest, HANDLER_OUTPUT, "***Exception: "); - switch ( retVal ) + switch(this->TestProcess->GetExitException()) { case cmsysProcess_Exception_Fault: cmCTestLog(this->CTest, HANDLER_OUTPUT, "SegFault"); @@ -264,23 +264,26 @@ bool cmCTestRunTest::EndTest(size_t completed, size_t total, bool started) { *this->TestHandler->LogFile << "Test time = " << buf << std::endl; } + + // Set the working directory to the tests directory + std::string oldpath = cmSystemTools::GetCurrentWorkingDirectory(); + cmSystemTools::ChangeDirectory(this->TestProperties->Directory.c_str()); + this->DartProcessing(); + + // restore working directory + cmSystemTools::ChangeDirectory(oldpath.c_str()); + + // if this is doing MemCheck then all the output needs to be put into // Output since that is what is parsed by cmCTestMemCheckHandler if(!this->TestHandler->MemCheck && started) { - if (this->TestResult.Status == cmCTestTestHandler::COMPLETED) - { this->TestHandler->CleanTestOutput(this->ProcessOutput, static_cast<size_t> - (this->TestHandler->CustomMaximumPassedTestOutputSize)); - } - else - { - this->TestHandler->CleanTestOutput(this->ProcessOutput, - static_cast<size_t> - (this->TestHandler->CustomMaximumFailedTestOutputSize)); - } + (this->TestResult.Status == cmCTestTestHandler::COMPLETED ? + this->TestHandler->CustomMaximumPassedTestOutputSize : + this->TestHandler->CustomMaximumFailedTestOutputSize)); } this->TestResult.Reason = reason; if (this->TestHandler->LogFile) @@ -325,7 +328,7 @@ bool cmCTestRunTest::EndTest(size_t completed, size_t total, bool started) << "----------------------------------------------------------" << std::endl << std::endl; } - // if the test actually stared and ran + // if the test actually started and ran // record the results in TestResult if(started) { @@ -338,6 +341,7 @@ bool cmCTestRunTest::EndTest(size_t completed, size_t total, bool started) this->TestResult.CompletionStatus = "Completed"; this->TestResult.ExecutionTime = this->TestProcess->GetTotalTime(); this->MemCheckPostProcess(); + this->ComputeWeightedCost(); } // Always push the current TestResult onto the // TestHandler vector @@ -346,7 +350,22 @@ bool cmCTestRunTest::EndTest(size_t completed, size_t total, bool started) return passed; } -//-------------------------------------------------------------- +//---------------------------------------------------------------------- +void cmCTestRunTest::ComputeWeightedCost() +{ + double prev = static_cast<double>(this->TestProperties->PreviousRuns); + double avgcost = static_cast<double>(this->TestProperties->Cost); + double current = this->TestResult.ExecutionTime; + + if(this->TestResult.Status == cmCTestTestHandler::COMPLETED) + { + this->TestProperties->Cost = + static_cast<float>(((prev * avgcost) + current) / (prev + 1.0)); + this->TestProperties->PreviousRuns++; + } +} + +//---------------------------------------------------------------------- void cmCTestRunTest::MemCheckPostProcess() { if(!this->TestHandler->MemCheck) @@ -430,13 +449,20 @@ bool cmCTestRunTest::StartTest(size_t total) } this->StartTime = this->CTest->CurrentTime(); - return this->CreateProcess(this->TestProperties->Timeout, - &this->TestProperties->Environment); + double timeout = this->ResolveTimeout(); + + if(this->StopTimePassed) + { + return false; + } + return this->ForkProcess(timeout, this->TestProperties->ExplicitTimeout, + &this->TestProperties->Environment); } +//---------------------------------------------------------------------- void cmCTestRunTest::ComputeArguments() { - std::vector<std::string>::const_iterator j = + std::vector<std::string>::const_iterator j = this->TestProperties->Args.begin(); ++j; // skip test name @@ -446,15 +472,17 @@ void cmCTestRunTest::ComputeArguments() cmCTestMemCheckHandler * handler = static_cast<cmCTestMemCheckHandler*> (this->TestHandler); this->ActualCommand = handler->MemoryTester.c_str(); + this->TestProperties->Args[1] = this->TestHandler->FindTheExecutable( + this->TestProperties->Args[1].c_str()); } else { - this->ActualCommand = + this->ActualCommand = this->TestHandler->FindTheExecutable( this->TestProperties->Args[1].c_str()); ++j; //skip the executable (it will be actualCommand) } - this->TestCommand + std::string testCommand = cmSystemTools::ConvertToOutputPath(this->ActualCommand.c_str()); //Prepends memcheck args to our command string @@ -462,22 +490,24 @@ void cmCTestRunTest::ComputeArguments() for(std::vector<std::string>::iterator i = this->Arguments.begin(); i != this->Arguments.end(); ++i) { - this->TestCommand += " "; - this->TestCommand += cmSystemTools::EscapeSpaces(j->c_str()); + testCommand += " \""; + testCommand += *i; + testCommand += "\""; } for(;j != this->TestProperties->Args.end(); ++j) { - this->TestCommand += " "; - this->TestCommand += cmSystemTools::EscapeSpaces(j->c_str()); + testCommand += " \""; + testCommand += *j; + testCommand += "\""; this->Arguments.push_back(*j); } - this->TestResult.FullCommandLine = this->TestCommand; + this->TestResult.FullCommandLine = testCommand; cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, std::endl << this->Index << ": " << (this->TestHandler->MemCheck?"MemCheck":"Test") - << " command: " << this->TestCommand + << " command: " << testCommand << std::endl); } @@ -504,7 +534,72 @@ void cmCTestRunTest::DartProcessing() } //---------------------------------------------------------------------- -bool cmCTestRunTest::CreateProcess(double testTimeOut, +double cmCTestRunTest::ResolveTimeout() +{ + double timeout = this->TestProperties->Timeout; + + if(this->CTest->GetStopTime() == "") + { + return timeout; + } + struct tm* lctime; + time_t current_time = time(0); + lctime = gmtime(¤t_time); + int gm_hour = lctime->tm_hour; + time_t gm_time = mktime(lctime); + lctime = localtime(¤t_time); + int local_hour = lctime->tm_hour; + + int tzone_offset = local_hour - gm_hour; + if(gm_time > current_time && gm_hour < local_hour) + { + // this means gm_time is on the next day + tzone_offset -= 24; + } + else if(gm_time < current_time && gm_hour > local_hour) + { + // this means gm_time is on the previous day + tzone_offset += 24; + } + + tzone_offset *= 100; + char buf[1024]; + // add todays year day and month to the time in str because + // curl_getdate no longer assumes the day is today + sprintf(buf, "%d%02d%02d %s %+05i", + lctime->tm_year + 1900, + lctime->tm_mon + 1, + lctime->tm_mday, + this->CTest->GetStopTime().c_str(), + tzone_offset); + + time_t stop_time = curl_getdate(buf, ¤t_time); + if(stop_time == -1) + { + return timeout; + } + + //the stop time refers to the next day + if(this->CTest->NextDayStopTime) + { + stop_time += 24*60*60; + } + int stop_timeout = static_cast<int>(stop_time - current_time) % (24*60*60); + this->CTest->LastStopTimeout = stop_timeout; + + if(stop_timeout <= 0 || stop_timeout > this->CTest->LastStopTimeout) + { + cmCTestLog(this->CTest, ERROR_MESSAGE, "The stop time has been passed. " + "Stopping all tests." << std::endl); + this->StopTimePassed = true; + return 0; + } + return timeout == 0 ? stop_timeout : + (timeout < stop_timeout ? timeout : stop_timeout); +} + +//---------------------------------------------------------------------- +bool cmCTestRunTest::ForkProcess(double testTimeOut, bool explicitTimeout, std::vector<std::string>* environment) { this->TestProcess = new cmProcess; @@ -514,9 +609,6 @@ bool cmCTestRunTest::CreateProcess(double testTimeOut, this->TestProcess->SetCommand(this->ActualCommand.c_str()); this->TestProcess->SetCommandArguments(this->Arguments); - std::vector<std::string> origEnv; - this->ModifyEnv = (environment && environment->size()>0); - // determine how much time we have double timeout = this->CTest->GetRemainingTimeAllowed() - 120; if (this->CTest->GetTimeOut() > 0 && this->CTest->GetTimeOut() < timeout) @@ -528,20 +620,28 @@ bool cmCTestRunTest::CreateProcess(double testTimeOut, { timeout = testTimeOut; } - // always have at least 1 second if we got to here if (timeout <= 0) { timeout = 1; } + // handle timeout explicitly set to 0 + if (testTimeOut == 0 && explicitTimeout) + { + timeout = 0; + } cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, this->Index << ": " << "Test timeout computed to be: " << timeout << "\n"); this->TestProcess->SetTimeout(timeout); - if (this->ModifyEnv) +#ifdef CMAKE_BUILD_WITH_CMAKE + cmSystemTools::SaveRestoreEnvironment sre; +#endif + + if (environment && environment->size()>0) { - this->OrigEnv = cmSystemTools::AppendEnv(environment); + cmSystemTools::AppendEnv(environment); } return this->TestProcess->StartProcess(); diff --git a/Source/CTest/cmCTestRunTest.h b/Source/CTest/cmCTestRunTest.h index 1084643..89456d5 100644 --- a/Source/CTest/cmCTestRunTest.h +++ b/Source/CTest/cmCTestRunTest.h @@ -39,6 +39,8 @@ public: std::string GetProcessOutput() { return this->ProcessOutput; } + bool IsStopTimePassed() { return this->StopTimePassed; } + cmCTestTestHandler::cmCTestTestResult GetTestResults() { return this->TestResult; } @@ -54,11 +56,15 @@ public: bool EndTest(size_t completed, size_t total, bool started); //Called by ctest -N to log the command string void ComputeArguments(); + + void ComputeWeightedCost(); private: void DartProcessing(); void ExeNotFound(std::string exe); - bool CreateProcess(double testTimeOut, - std::vector<std::string>* environment); + // Figures out a final timeout which is min(STOP_TIME, NOW+TIMEOUT) + double ResolveTimeout(); + bool ForkProcess(double testTimeOut, bool explicitTimeout, + std::vector<std::string>* environment); void WriteLogOutputTop(size_t completed, size_t total); //Run post processing of the process output for MemCheck void MemCheckPostProcess(); @@ -73,14 +79,9 @@ private: //if this option is set to false.) //bool OptimizeForCTest; - //flag for whether the env was modified for this run - bool ModifyEnv; - bool UsePrefixCommand; std::string PrefixCommand; - //stores the original environment if we are modifying it - std::vector<std::string> OrigEnv; std::string ProcessOutput; std::string CompressedOutput; double CompressionRatio; @@ -88,9 +89,9 @@ private: cmCTestTestHandler::cmCTestTestResult TestResult; int Index; std::string StartTime; - std::string TestCommand; std::string ActualCommand; std::vector<std::string> Arguments; + bool StopTimePassed; }; inline int getNumWidth(size_t n) diff --git a/Source/CTest/cmCTestSVN.cxx b/Source/CTest/cmCTestSVN.cxx index 82e5845..fab9a8c 100644 --- a/Source/CTest/cmCTestSVN.cxx +++ b/Source/CTest/cmCTestSVN.cxx @@ -440,3 +440,11 @@ void cmCTestSVN::LoadModifications() OutputLogger err(this->Log, "status-err> "); this->RunChild(svn_status, &out, &err); } + +//---------------------------------------------------------------------------- +void cmCTestSVN::WriteXMLGlobal(std::ostream& xml) +{ + this->cmCTestGlobalVC::WriteXMLGlobal(xml); + + xml << "\t<SVNPath>" << this->Base << "</SVNPath>\n"; +} diff --git a/Source/CTest/cmCTestSVN.h b/Source/CTest/cmCTestSVN.h index ff9ff0f..f72c58f 100644 --- a/Source/CTest/cmCTestSVN.h +++ b/Source/CTest/cmCTestSVN.h @@ -52,6 +52,8 @@ private: void DoRevision(Revision const& revision, std::vector<Change> const& changes); + void WriteXMLGlobal(std::ostream& xml); + // Parsing helper classes. class InfoParser; class LogParser; diff --git a/Source/CTest/cmCTestScriptHandler.cxx b/Source/CTest/cmCTestScriptHandler.cxx index 5983e68..fdf17e0 100644 --- a/Source/CTest/cmCTestScriptHandler.cxx +++ b/Source/CTest/cmCTestScriptHandler.cxx @@ -583,6 +583,10 @@ void cmCTestScriptHandler::SleepInSeconds(unsigned int secondsToWait) int cmCTestScriptHandler::RunConfigurationScript (const std::string& total_script_arg, bool pscope) { +#ifdef CMAKE_BUILD_WITH_CMAKE + cmSystemTools::SaveRestoreEnvironment sre; +#endif + int result; this->ScriptStartTime = diff --git a/Source/CTest/cmCTestSleepCommand.h b/Source/CTest/cmCTestSleepCommand.h index 411eb01..468cd85 100644 --- a/Source/CTest/cmCTestSleepCommand.h +++ b/Source/CTest/cmCTestSleepCommand.h @@ -63,11 +63,10 @@ public: virtual const char* GetFullDocumentation() { return - " ctest_sleep( seconds )\n" - " ctest_sleep( time1 duration time2 )\n" - "With one argument it will sleep for a given number of seconds. " - "With three arguments it will wait for time2 - time1 - duration " - "seconds."; + " ctest_sleep(<seconds>)\n" + "Sleep for given number of seconds.\n" + " ctest_sleep(<time1> <duration> <time2>)\n" + "Sleep for t=(time1 + duration - time2) seconds if t > 0."; } cmTypeMacro(cmCTestSleepCommand, cmCTestCommand); diff --git a/Source/CTest/cmCTestStartCommand.cxx b/Source/CTest/cmCTestStartCommand.cxx index 606fbbe..228a173 100644 --- a/Source/CTest/cmCTestStartCommand.cxx +++ b/Source/CTest/cmCTestStartCommand.cxx @@ -17,6 +17,11 @@ #include "cmCTestVC.h" #include "cmGeneratedFileStream.h" +cmCTestStartCommand::cmCTestStartCommand() +{ + this->CreateNewTag = true; +} + bool cmCTestStartCommand ::InitialPass(std::vector<std::string> const& args, cmExecutionStatus &) { @@ -44,6 +49,15 @@ bool cmCTestStartCommand } } + if (cnt < args.size()) + { + if (args[cnt] == "APPEND") + { + cnt ++; + this->CreateNewTag = false; + } + } + if ( cnt < args.size() ) { src_dir = args[cnt].c_str(); diff --git a/Source/CTest/cmCTestStartCommand.h b/Source/CTest/cmCTestStartCommand.h index ae2f26b..afbc77b 100644 --- a/Source/CTest/cmCTestStartCommand.h +++ b/Source/CTest/cmCTestStartCommand.h @@ -23,7 +23,7 @@ class cmCTestStartCommand : public cmCTestCommand { public: - cmCTestStartCommand() {} + cmCTestStartCommand(); /** * This is a virtual constructor for the command. @@ -33,6 +33,7 @@ public: cmCTestStartCommand* ni = new cmCTestStartCommand; ni->CTest = this->CTest; ni->CTestScriptHandler = this->CTestScriptHandler; + ni->CreateNewTag = this->CreateNewTag; return ni; } @@ -44,6 +45,14 @@ public: cmExecutionStatus &status); /** + * Will this invocation of ctest_start create a new TAG file? + */ + bool ShouldCreateNewTag() + { + return this->CreateNewTag; + } + + /** * The name of the command as specified in CMakeList.txt. */ virtual const char* GetName() { return "ctest_start";} @@ -62,18 +71,21 @@ public: virtual const char* GetFullDocumentation() { return - " ctest_start(Model [TRACK <track>] [source [binary]])\n" + " ctest_start(Model [TRACK <track>] [APPEND] [source [binary]])\n" "Starts the testing for a given model. The command should be called " "after the binary directory is initialized. If the 'source' and " "'binary' directory are not specified, it reads the " "CTEST_SOURCE_DIRECTORY and CTEST_BINARY_DIRECTORY. If the track is " - "specified, the submissions will go to the specified track."; + "specified, the submissions will go to the specified track. " + "If APPEND is used, the existing TAG is used rather than " + "creating a new one based on the current time stamp."; } cmTypeMacro(cmCTestStartCommand, cmCTestCommand); private: bool InitialCheckout(std::ostream& ofs, std::string const& sourceDir); + bool CreateNewTag; }; diff --git a/Source/CTest/cmCTestSubmitCommand.cxx b/Source/CTest/cmCTestSubmitCommand.cxx index d1226da..24974e3 100644 --- a/Source/CTest/cmCTestSubmitCommand.cxx +++ b/Source/CTest/cmCTestSubmitCommand.cxx @@ -147,6 +147,13 @@ cmCTestGenericHandler* cmCTestSubmitCommand::InitializeHandler() static_cast<cmCTestSubmitHandler*>(handler)->SelectParts(this->Parts); } + static_cast<cmCTestSubmitHandler*>(handler)->SetOption("RetryDelay", + this->RetryDelay.c_str()); + static_cast<cmCTestSubmitHandler*>(handler)->SetOption("RetryCount", + this->RetryCount.c_str()); + static_cast<cmCTestSubmitHandler*>(handler)->SetOption("InternalTest", + this->InternalTest ? "ON" : "OFF"); + return handler; } @@ -169,6 +176,24 @@ bool cmCTestSubmitCommand::CheckArgumentKeyword(std::string const& arg) return true; } + if(arg == "RETRY_COUNT") + { + this->ArgumentDoing = ArgumentDoingRetryCount; + return true; + } + + if(arg == "RETRY_DELAY") + { + this->ArgumentDoing = ArgumentDoingRetryDelay; + return true; + } + + if(arg == "INTERNAL_TEST_CHECKSUM") + { + this->InternalTest = true; + return true; + } + // Look for other arguments. return this->Superclass::CheckArgumentKeyword(arg); } @@ -213,6 +238,18 @@ bool cmCTestSubmitCommand::CheckArgumentValue(std::string const& arg) return true; } + if(this->ArgumentDoing == ArgumentDoingRetryCount) + { + this->RetryCount = arg; + return true; + } + + if(this->ArgumentDoing == ArgumentDoingRetryDelay) + { + this->RetryDelay = arg; + return true; + } + // Look for other arguments. return this->Superclass::CheckArgumentValue(arg); } diff --git a/Source/CTest/cmCTestSubmitCommand.h b/Source/CTest/cmCTestSubmitCommand.h index ccaef7e..edc9c65 100644 --- a/Source/CTest/cmCTestSubmitCommand.h +++ b/Source/CTest/cmCTestSubmitCommand.h @@ -29,6 +29,9 @@ public: { this->PartsMentioned = false; this->FilesMentioned = false; + this->InternalTest = false; + this->RetryCount = ""; + this->RetryDelay = ""; } /** @@ -61,7 +64,8 @@ public: virtual const char* GetFullDocumentation() { return - " ctest_submit([PARTS ...] [FILES ...] [RETURN_VALUE res])\n" + " ctest_submit([PARTS ...] [FILES ...] [RETRY_COUNT count] " + " [RETRY_DELAY delay][RETURN_VALUE res])\n" "By default all available parts are submitted if no PARTS or FILES " "are specified. " "The PARTS option lists a subset of parts to be submitted. " @@ -77,7 +81,11 @@ public: " ExtraFiles = Files listed by CTEST_EXTRA_SUBMIT_FILES\n" " Submit = nothing\n" "The FILES option explicitly lists specific files to be submitted. " - "Each individual file must exist at the time of the call.\n"; + "Each individual file must exist at the time of the call.\n" + "The RETRY_DELAY option specifies how long in seconds to wait after " + "a timed-out submission before attempting to re-submit.\n" + "The RETRY_COUNT option specifies how many times to retry a timed-out " + "submission.\n"; } cmTypeMacro(cmCTestSubmitCommand, cmCTestHandlerCommand); @@ -92,13 +100,18 @@ protected: { ArgumentDoingParts = Superclass::ArgumentDoingLast1, ArgumentDoingFiles, + ArgumentDoingRetryDelay, + ArgumentDoingRetryCount, ArgumentDoingLast2 }; bool PartsMentioned; std::set<cmCTest::Part> Parts; bool FilesMentioned; + bool InternalTest; cmCTest::SetOfStrings Files; + std::string RetryCount; + std::string RetryDelay; }; diff --git a/Source/CTest/cmCTestSubmitHandler.cxx b/Source/CTest/cmCTestSubmitHandler.cxx index 7b4f38b..9f9f85a 100644 --- a/Source/CTest/cmCTestSubmitHandler.cxx +++ b/Source/CTest/cmCTestSubmitHandler.cxx @@ -15,6 +15,7 @@ #include "cmVersion.h" #include "cmGeneratedFileStream.h" #include "cmCTest.h" +#include "cmXMLParser.h" #include <cmsys/Process.h> #include <cmsys/Base64.h> @@ -31,6 +32,90 @@ typedef std::vector<char> cmCTestSubmitHandlerVectorOfChar; +//---------------------------------------------------------------------------- +class cmCTestSubmitHandler::ResponseParser: public cmXMLParser +{ +public: + ResponseParser() { this->Status = STATUS_OK; } + ~ResponseParser() {} + +public: + + enum StatusType + { + STATUS_OK, + STATUS_WARNING, + STATUS_ERROR + }; + + StatusType Status; + std::string CDashVersion; + std::string Filename; + std::string MD5; + std::string Message; + +private: + + std::vector<char> CurrentValue; + + std::string GetCurrentValue() + { + std::string val; + if(this->CurrentValue.size()) + { + val.assign(&this->CurrentValue[0], this->CurrentValue.size()); + } + return val; + } + + virtual void StartElement(const char* name, const char** atts) + { + this->CurrentValue.clear(); + if(strcmp(name, "cdash") == 0) + { + this->CDashVersion = this->FindAttribute(atts, "version"); + } + } + + virtual void CharacterDataHandler(const char* data, int length) + { + this->CurrentValue.insert(this->CurrentValue.end(), data, data+length); + } + + virtual void EndElement(const char* name) + { + if(strcmp(name, "status") == 0) + { + std::string status = cmSystemTools::UpperCase(this->GetCurrentValue()); + if(status == "OK" || status == "SUCCESS") + { + this->Status = STATUS_OK; + } + else if(status == "WARNING") + { + this->Status = STATUS_WARNING; + } + else + { + this->Status = STATUS_ERROR; + } + } + else if(strcmp(name, "filename") == 0) + { + this->Filename = this->GetCurrentValue(); + } + else if(strcmp(name, "md5") == 0) + { + this->MD5 = this->GetCurrentValue(); + } + else if(strcmp(name, "message") == 0) + { + this->Message = this->GetCurrentValue(); + } + } +}; + + static size_t cmCTestSubmitHandlerWriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data) @@ -367,6 +452,20 @@ bool cmCTestSubmitHandler::SubmitUsingHTTP(const cmStdString& localprefix, = url + ((url.find("?",0) == cmStdString::npos) ? "?" : "&") + "FileName=" + ofile; + upload_as += "&MD5="; + + if(cmSystemTools::IsOn(this->GetOption("InternalTest"))) + { + upload_as += "bad_md5sum"; + } + else + { + char md5[33]; + cmSystemTools::ComputeFileMD5(local_file.c_str(), md5); + md5[32] = 0; + upload_as += md5; + } + struct stat st; if ( ::stat(local_file.c_str(), &st) ) { @@ -382,7 +481,6 @@ bool cmCTestSubmitHandler::SubmitUsingHTTP(const cmStdString& localprefix, << local_file.c_str() << " to " << upload_as.c_str() << " Size: " << st.st_size << std::endl); - // specify target ::curl_easy_setopt(curl,CURLOPT_URL, upload_as.c_str()); @@ -411,6 +509,19 @@ bool cmCTestSubmitHandler::SubmitUsingHTTP(const cmStdString& localprefix, // Now run off and do what you've been told! res = ::curl_easy_perform(curl); + if(cmSystemTools::IsOn(this->GetOption("InternalTest")) && + cmSystemTools::VersionCompare(cmSystemTools::OP_LESS, + this->CTest->GetCDashVersion().c_str(), "1.7")) + { + // mock failure output for internal test case + std::string mock_output = "<cdash version=\"1.7.0\">\n" + " <status>ERROR</status>\n" + " <message>Checksum failed for file.</message>\n" + "</cdash>\n"; + chunk.clear(); + chunk.assign(mock_output.begin(), mock_output.end()); + } + if ( chunk.size() > 0 ) { cmCTestLog(this->CTest, DEBUG, "CURL output: [" @@ -425,6 +536,60 @@ bool cmCTestSubmitHandler::SubmitUsingHTTP(const cmStdString& localprefix, << std::endl); } + // If curl failed for any reason, or checksum fails, wait and retry + // + if(res != CURLE_OK || this->HasErrors) + { + std::string retryDelay = this->GetOption("RetryDelay") == NULL ? + "" : this->GetOption("RetryDelay"); + std::string retryCount = this->GetOption("RetryCount") == NULL ? + "" : this->GetOption("RetryCount"); + + int delay = retryDelay == "" ? atoi(this->CTest->GetCTestConfiguration( + "CTestSubmitRetryDelay").c_str()) : atoi(retryDelay.c_str()); + int count = retryCount == "" ? atoi(this->CTest->GetCTestConfiguration( + "CTestSubmitRetryCount").c_str()) : atoi(retryCount.c_str()); + + for(int i = 0; i < count; i++) + { + cmCTestLog(this->CTest, HANDLER_OUTPUT, + " Submit failed, waiting " << delay << " seconds...\n"); + + double stop = cmSystemTools::GetTime() + delay; + while(cmSystemTools::GetTime() < stop) + { + cmSystemTools::Delay(100); + } + + cmCTestLog(this->CTest, HANDLER_OUTPUT, + " Retry submission: Attempt " << (i + 1) << " of " + << count << std::endl); + + ::fclose(ftpfile); + ftpfile = ::fopen(local_file.c_str(), "rb"); + ::curl_easy_setopt(curl, CURLOPT_INFILE, ftpfile); + + chunk.clear(); + chunkDebug.clear(); + this->HasErrors = false; + + res = ::curl_easy_perform(curl); + + if ( chunk.size() > 0 ) + { + cmCTestLog(this->CTest, DEBUG, "CURL output: [" + << cmCTestLogWrite(&*chunk.begin(), chunk.size()) << "]" + << std::endl); + this->ParseResponse(chunk); + } + + if(res == CURLE_OK && !this->HasErrors) + { + break; + } + } + } + fclose(ftpfile); if ( res ) { @@ -467,14 +632,22 @@ void cmCTestSubmitHandler ::ParseResponse(cmCTestSubmitHandlerVectorOfChar chunk) { std::string output = ""; + output.append(chunk.begin(), chunk.end()); - for(cmCTestSubmitHandlerVectorOfChar::iterator i = chunk.begin(); - i != chunk.end(); ++i) + if(output.find("<cdash") != output.npos) { - output += *i; + ResponseParser parser; + parser.Parse(output.c_str()); + + if(parser.Status != ResponseParser::STATUS_OK) + { + this->HasErrors = true; + cmCTestLog(this->CTest, HANDLER_OUTPUT, " Submission failed: " << + parser.Message << std::endl); + return; + } } output = cmSystemTools::UpperCase(output); - if(output.find("WARNING") != std::string::npos) { this->HasWarnings = true; @@ -483,13 +656,12 @@ void cmCTestSubmitHandler { this->HasErrors = true; } - + if(this->HasWarnings || this->HasErrors) { cmCTestLog(this->CTest, HANDLER_OUTPUT, " Server Response:\n" << cmCTestLogWrite(&*chunk.begin(), chunk.size()) << "\n"); } - } //---------------------------------------------------------------------------- @@ -589,7 +761,7 @@ bool cmCTestSubmitHandler::TriggerUsingHTTP( << turl.c_str() << std::endl); cmCTestLog(this->CTest, ERROR_MESSAGE, " Error message was: " << error_buffer << std::endl); - *this->LogFile << "\tTrigerring failed with error: " << error_buffer + *this->LogFile << "\tTriggering failed with error: " << error_buffer << std::endl << " Error message was: " << error_buffer << std::endl; diff --git a/Source/CTest/cmCTestSubmitHandler.h b/Source/CTest/cmCTestSubmitHandler.h index 8b011ea..e7755b1 100644 --- a/Source/CTest/cmCTestSubmitHandler.h +++ b/Source/CTest/cmCTestSubmitHandler.h @@ -79,6 +79,7 @@ private: std::string GetSubmitResultsPrefix(); + class ResponseParser; cmStdString HTTPProxy; int HTTPProxyType; cmStdString HTTPProxyAuth; diff --git a/Source/CTest/cmCTestTestCommand.cxx b/Source/CTest/cmCTestTestCommand.cxx index b0adf22..5aee035 100644 --- a/Source/CTest/cmCTestTestCommand.cxx +++ b/Source/CTest/cmCTestTestCommand.cxx @@ -25,6 +25,7 @@ cmCTestTestCommand::cmCTestTestCommand() this->Arguments[ctt_INCLUDE_LABEL] = "INCLUDE_LABEL"; this->Arguments[ctt_PARALLEL_LEVEL] = "PARALLEL_LEVEL"; this->Arguments[ctt_SCHEDULE_RANDOM] = "SCHEDULE_RANDOM"; + this->Arguments[ctt_STOP_TIME] = "STOP_TIME"; this->Arguments[ctt_LAST] = 0; this->Last = ctt_LAST; } @@ -98,6 +99,10 @@ cmCTestGenericHandler* cmCTestTestCommand::InitializeHandler() handler->SetOption("ScheduleRandom", this->Values[ctt_SCHEDULE_RANDOM]); } + if(this->Values[ctt_STOP_TIME]) + { + this->CTest->SetStopTime(this->Values[ctt_STOP_TIME]); + } return handler; } diff --git a/Source/CTest/cmCTestTestCommand.h b/Source/CTest/cmCTestTestCommand.h index 12314df..c6fd631 100644 --- a/Source/CTest/cmCTestTestCommand.h +++ b/Source/CTest/cmCTestTestCommand.h @@ -62,7 +62,8 @@ public: " [EXCLUDE_LABEL exclude regex] \n" " [INCLUDE_LABEL label regex] \n" " [PARALLEL_LEVEL level] \n" - " [SCHEDULE_RANDOM on]) \n" + " [SCHEDULE_RANDOM on] \n" + " [STOP_TIME time of day]) \n" "Tests the given build directory and stores results in Test.xml. The " "second argument is a variable that will hold value. Optionally, " "you can specify the starting test number START, the ending test number " @@ -73,7 +74,8 @@ public: "property LABEL. PARALLEL_LEVEL should be set to a positive number " "representing the number of tests to be run in parallel. " "SCHEDULE_RANDOM will launch tests in a random order, and is " - "typically used to detect implicit test dependencies." + "typically used to detect implicit test dependencies. STOP_TIME is the " + "time of day at which the tests should all stop running." "\n" CTEST_COMMAND_APPEND_OPTION_DOCS; } @@ -96,6 +98,7 @@ protected: ctt_INCLUDE_LABEL, ctt_PARALLEL_LEVEL, ctt_SCHEDULE_RANDOM, + ctt_STOP_TIME, ctt_LAST }; }; diff --git a/Source/CTest/cmCTestTestHandler.cxx b/Source/CTest/cmCTestTestHandler.cxx index 8af2815..87c75eb 100644 --- a/Source/CTest/cmCTestTestHandler.cxx +++ b/Source/CTest/cmCTestTestHandler.cxx @@ -26,6 +26,7 @@ #include "cmCommand.h" #include "cmSystemTools.h" #include "cmXMLSafe.h" +#include "cm_utf8.h" #include <stdlib.h> #include <math.h> @@ -438,6 +439,8 @@ void cmCTestTestHandler::Initialize() this->TestsToRun.clear(); + this->UseIncludeLabelRegExpFlag = false; + this->UseExcludeLabelRegExpFlag = false; this->UseIncludeRegExpFlag = false; this->UseExcludeRegExpFlag = false; this->UseExcludeRegExpFirst = false; @@ -567,7 +570,7 @@ int cmCTestTestHandler::ProcessHandler() if (total == 0) { - if ( !this->CTest->GetShowOnly() ) + if ( !this->CTest->GetShowOnly() && !this->CTest->ShouldPrintLabels() ) { cmCTestLog(this->CTest, ERROR_MESSAGE, "No tests were found!!!" << std::endl); @@ -1036,9 +1039,9 @@ void cmCTestTestHandler::ProcessDirectory(std::vector<cmStdString> &passed, bool randomSchedule = this->CTest->GetScheduleType() == "Random"; if(randomSchedule) - { + { srand((unsigned)time(0)); - } + } for (ListOfTests::iterator it = this->TestList.begin(); it != this->TestList.end(); ++it) @@ -1048,7 +1051,7 @@ void cmCTestTestHandler::ProcessDirectory(std::vector<cmStdString> &passed, if(randomSchedule) { - p.Cost = rand(); + p.Cost = static_cast<float>(rand()); } if(p.Timeout == 0 && this->CTest->GetGlobalTimeout() != 0) @@ -1079,7 +1082,12 @@ void cmCTestTestHandler::ProcessDirectory(std::vector<cmStdString> &passed, parallel->SetPassFailVectors(&passed, &failed); this->TestResults.clear(); parallel->SetTestResults(&this->TestResults); - if(this->CTest->GetShowOnly()) + + if(this->CTest->ShouldPrintLabels()) + { + parallel->PrintLabels(); + } + else if(this->CTest->GetShowOnly()) { parallel->PrintTestList(); } @@ -1309,7 +1317,8 @@ std::string cmCTestTestHandler::EncodeFile(std::string file) cmSystemTools::RemoveFile(tarFile.c_str()); unsigned char *encoded_buffer - = new unsigned char [ static_cast<int>(len * 1.5 + 5) ]; + = new unsigned char [ static_cast<int>( + static_cast<double>(len) * 1.5 + 5.0) ]; unsigned long rlen = cmsysBase64_Encode(file_buffer, len, encoded_buffer, 1); @@ -1881,7 +1890,8 @@ std::string cmCTestTestHandler::GenerateRegressionImages( unsigned char *file_buffer = new unsigned char [ len + 1 ]; ifs.read(reinterpret_cast<char*>(file_buffer), len); unsigned char *encoded_buffer - = new unsigned char [ static_cast<int>(len * 1.5 + 5) ]; + = new unsigned char [ static_cast<int>( + static_cast<double>(len) * 1.5 + 5.0) ]; unsigned long rlen = cmsysBase64_Encode(file_buffer, len, encoded_buffer, 1); @@ -1971,65 +1981,45 @@ void cmCTestTestHandler::SetTestsToRunInformation(const char* in) } } -//---------------------------------------------------------------------- -bool cmCTestTestHandler::CleanTestOutput(std::string& output, - size_t remove_threshold) +//---------------------------------------------------------------------------- +bool cmCTestTestHandler::CleanTestOutput(std::string& output, size_t length) { - if ( remove_threshold == 0 ) + if(!length || length >= output.size() || + output.find("CTEST_FULL_OUTPUT") != output.npos) { return true; } - if ( output.find("CTEST_FULL_OUTPUT") != output.npos ) + + // Truncate at given length but do not break in the middle of a multi-byte + // UTF-8 encoding. + char const* const begin = output.c_str(); + char const* const end = begin + output.size(); + char const* const truncate = begin + length; + char const* current = begin; + while(current < truncate) { - return true; - } - cmOStringStream ostr; - std::string::size_type cc; - std::string::size_type skipsize = 0; - int inTag = 0; - int skipped = 0; - for ( cc = 0; cc < output.size(); cc ++ ) - { - int ch = output[cc]; - if ( ch < 0 || ch > 255 ) - { - break; - } - if ( ch == '<' ) + unsigned int ch; + if(const char* next = cm_utf8_decode_character(current, end, &ch)) { - inTag = 1; - } - if ( !inTag ) - { - int notskip = 0; - // Skip - if ( skipsize < remove_threshold ) - { - ostr << static_cast<char>(ch); - notskip = 1; - } - skipsize ++; - if ( notskip && skipsize >= remove_threshold ) + if(next > truncate) { - skipped = 1; + break; } + current = next; } - else + else // Bad byte will be handled by cmXMLSafe. { - ostr << static_cast<char>(ch); - } - if ( ch == '>' ) - { - inTag = 0; + ++current; } } - if ( skipped ) - { - ostr << "..." << std::endl << "The rest of the test output was removed " - "since it exceeds the threshold of " - << remove_threshold << " characters." << std::endl; - } - output = ostr.str(); + output = output.substr(0, current - begin); + + // Append truncation message. + cmOStringStream msg; + msg << "...\n" + "The rest of the test output was removed since it exceeds the threshold " + "of " << length << " bytes.\n"; + output += msg.str(); return true; } @@ -2099,9 +2089,21 @@ bool cmCTestTestHandler::SetTestsProperties( rtit->AttachOnFail.push_back(*f); } } + if ( key == "RESOURCE_LOCK" ) + { + std::vector<std::string> lval; + cmSystemTools::ExpandListArgument(val.c_str(), lval); + + for(std::vector<std::string>::iterator f = lval.begin(); + f != lval.end(); ++f) + { + rtit->LockedResources.insert(*f); + } + } if ( key == "TIMEOUT" ) { rtit->Timeout = atof(val.c_str()); + rtit->ExplicitTimeout = true; } if ( key == "COST" ) { @@ -2172,7 +2174,6 @@ bool cmCTestTestHandler::SetTestsProperties( { rtit->Labels.push_back(*crit); } - } if ( key == "MEASUREMENT" ) { @@ -2201,6 +2202,10 @@ bool cmCTestTestHandler::SetTestsProperties( std::string(crit->c_str()))); } } + if ( key == "WORKING_DIRECTORY" ) + { + rtit->Directory = val; + } } } } @@ -2272,8 +2277,10 @@ bool cmCTestTestHandler::AddTest(const std::vector<std::string>& args) test.WillFail = false; test.RunSerial = false; test.Timeout = 0; + test.ExplicitTimeout = false; test.Cost = 0; test.Processors = 1; + test.PreviousRuns = 0; if (this->UseIncludeRegExpFlag && !this->IncludeTestsRegularExpression.find(testname.c_str())) { diff --git a/Source/CTest/cmCTestTestHandler.h b/Source/CTest/cmCTestTestHandler.h index 1513410..7aa8522 100644 --- a/Source/CTest/cmCTestTestHandler.h +++ b/Source/CTest/cmCTestTestHandler.h @@ -96,13 +96,16 @@ public: bool IsInBasedOnREOptions; bool WillFail; float Cost; + int PreviousRuns; bool RunSerial; double Timeout; + bool ExplicitTimeout; int Index; //Requested number of process slots int Processors; std::vector<std::string> Environment; std::vector<std::string> Labels; + std::set<std::string> LockedResources; }; struct cmCTestTestResult diff --git a/Source/CTest/cmCTestUpdateCommand.cxx b/Source/CTest/cmCTestUpdateCommand.cxx index 571745d..8414349 100644 --- a/Source/CTest/cmCTestUpdateCommand.cxx +++ b/Source/CTest/cmCTestUpdateCommand.cxx @@ -52,6 +52,8 @@ cmCTestGenericHandler* cmCTestUpdateCommand::InitializeHandler() this->CTest->SetCTestConfigurationFromCMakeVariable(this->Makefile, "GITUpdateOptions", "CTEST_GIT_UPDATE_OPTIONS"); this->CTest->SetCTestConfigurationFromCMakeVariable(this->Makefile, + "GITUpdateCustom", "CTEST_GIT_UPDATE_CUSTOM"); + this->CTest->SetCTestConfigurationFromCMakeVariable(this->Makefile, "HGCommand", "CTEST_HG_COMMAND"); this->CTest->SetCTestConfigurationFromCMakeVariable(this->Makefile, "HGUpdateOptions", "CTEST_HG_UPDATE_OPTIONS"); diff --git a/Source/CTest/cmCTestUpdateHandler.cxx b/Source/CTest/cmCTestUpdateHandler.cxx index 4111357..9eae3f3 100644 --- a/Source/CTest/cmCTestUpdateHandler.cxx +++ b/Source/CTest/cmCTestUpdateHandler.cxx @@ -258,7 +258,8 @@ int cmCTestUpdateHandler::ProcessHandler() << this->CTest->GetTestModelString() << "</BuildStamp>" << std::endl; os << "\t<StartDateTime>" << start_time << "</StartDateTime>\n" << "\t<StartTime>" << start_time_time << "</StartTime>\n" - << "\t<UpdateCommand>" << cmXMLSafe(vc->GetUpdateCommandLine()) + << "\t<UpdateCommand>" + << cmXMLSafe(vc->GetUpdateCommandLine()).Quotes(false) << "</UpdateCommand>\n" << "\t<UpdateType>" << cmXMLSafe( cmCTestUpdateHandlerUpdateToString(this->UpdateType)) @@ -305,6 +306,7 @@ int cmCTestUpdateHandler::ProcessHandler() } if(!updated) { + os << "Update command failed:\n" << vc->GetUpdateCommandLine(); cmCTestLog(this->CTest, ERROR_MESSAGE, " Update command failed: " << vc->GetUpdateCommandLine() << "\n"); } diff --git a/Source/CTest/cmCTestVC.cxx b/Source/CTest/cmCTestVC.cxx index 35f567a..fbee227 100644 --- a/Source/CTest/cmCTestVC.cxx +++ b/Source/CTest/cmCTestVC.cxx @@ -227,6 +227,12 @@ void cmCTestVC::WriteXMLEntry(std::ostream& xml, << "\t\t\t<FullName>" << cmXMLSafe(full) << "</FullName>\n" << "\t\t\t<CheckinDate>" << cmXMLSafe(rev.Date) << "</CheckinDate>\n" << "\t\t\t<Author>" << cmXMLSafe(rev.Author) << "</Author>\n" + << "\t\t\t<Email>" << cmXMLSafe(rev.EMail) << "</Email>\n" + << "\t\t\t<Committer>" << cmXMLSafe(rev.Committer) << "</Committer>\n" + << "\t\t\t<CommitterEmail>" << cmXMLSafe(rev.CommitterEMail) + << "</CommitterEmail>\n" + << "\t\t\t<CommitDate>" << cmXMLSafe(rev.CommitDate) + << "</CommitDate>\n" << "\t\t\t<Log>" << cmXMLSafe(rev.Log) << "</Log>\n" << "\t\t\t<Revision>" << cmXMLSafe(rev.Rev) << "</Revision>\n" << "\t\t\t<PriorRevision>" << cmXMLSafe(prior) << "</PriorRevision>\n" diff --git a/Source/CTest/cmCTestVC.h b/Source/CTest/cmCTestVC.h index e6ea76d..44e1dac 100644 --- a/Source/CTest/cmCTestVC.h +++ b/Source/CTest/cmCTestVC.h @@ -73,6 +73,10 @@ protected: std::string Rev; std::string Date; std::string Author; + std::string EMail; + std::string Committer; + std::string CommitterEMail; + std::string CommitDate; std::string Log; }; diff --git a/Source/CTest/cmParsePHPCoverage.cxx b/Source/CTest/cmParsePHPCoverage.cxx new file mode 100644 index 0000000..32c1ec1 --- /dev/null +++ b/Source/CTest/cmParsePHPCoverage.cxx @@ -0,0 +1,252 @@ +#include "cmStandardIncludes.h" +#include "cmSystemTools.h" +#include "cmParsePHPCoverage.h" +#include <cmsys/Directory.hxx> + +/* + To setup coverage for php. + + - edit php.ini to add auto prepend and append php files from phpunit + auto_prepend_file = + auto_append_file = + - run the tests + - run this program on all the files in c:/tmp + +*/ + +cmParsePHPCoverage::cmParsePHPCoverage(cmCTestCoverageHandlerContainer& cont, + cmCTest* ctest) + :Coverage(cont), CTest(ctest) +{ +} + +bool cmParsePHPCoverage::ReadUntil(std::ifstream& in, char until) +{ + char c = 0; + while(in.get(c) && c != until) + { + } + if(c != until) + { + return false; + } + return true; +} +bool cmParsePHPCoverage::ReadCoverageArray(std::ifstream& in, + cmStdString const& fileName) +{ + cmCTestCoverageHandlerContainer::SingleFileCoverageVector& coverageVector + = this->Coverage.TotalCoverage[fileName]; + + char c; + char buf[4]; + in.read(buf, 3); + buf[3] = 0; + if(strcmp(buf, ";a:") != 0) + { + cmCTestLog(this->CTest, ERROR_MESSAGE, + "failed to read start of coverage array, found : " + << buf << "\n"); + return false; + } + int size = 0; + if(!this->ReadInt(in, size)) + { + cmCTestLog(this->CTest, ERROR_MESSAGE, + "failed to read size "); + return false; + } + if(!in.get(c) && c == '{') + { + cmCTestLog(this->CTest, ERROR_MESSAGE, + "failed to read open {\n"); + return false; + } + for(int i =0; i < size; i++) + { + this->ReadUntil(in, ':'); + int line = 0; + this->ReadInt(in, line); + // ok xdebug may have a bug here + // it seems to be 1 based but often times + // seems to have a 0'th line. + line--; + if(line < 0) + { + line = 0; + } + this->ReadUntil(in, ':'); + int value = 0; + this->ReadInt(in, value); + // make sure the vector is the right size and is + // initialized with -1 for each line + while(coverageVector.size() <= static_cast<size_t>(line) ) + { + coverageVector.push_back(-1); + } + // if value is less than 0, set it to zero + // TODO figure out the difference between + // -1 and -2 in xdebug coverage?? For now + // assume less than 0 is just not covered + // CDash expects -1 for non executable code (like comments) + // and 0 for uncovered code, and a positive value + // for number of times a line was executed + if(value < 0) + { + value = 0; + } + // if unset then set it to value + if(coverageVector[line] == -1) + { + coverageVector[line] = value; + } + // otherwise increment by value + else + { + coverageVector[line] += value; + } + } + return true; +} + +bool cmParsePHPCoverage::ReadInt(std::ifstream& in, int& v) +{ + std::string s; + char c = 0; + while(in.get(c) && c != ':' && c != ';') + { + s += c; + } + v = atoi(s.c_str()); + return true; +} + +bool cmParsePHPCoverage::ReadArraySize(std::ifstream& in, int& size) +{ + char c = 0; + in.get(c); + if(c != 'a') + { + return false; + } + if(in.get(c) && c == ':') + { + if(this->ReadInt(in, size)) + { + return true; + } + } + return false; +} + +bool cmParsePHPCoverage::ReadFileInformation(std::ifstream& in) +{ + char buf[4]; + in.read(buf, 2); + buf[2] = 0; + if(strcmp(buf, "s:") != 0) + { + cmCTestLog(this->CTest, ERROR_MESSAGE, + "failed to read start of file info found: [" << buf << "]\n"); + return false; + } + char c; + int size = 0; + if(this->ReadInt(in, size)) + { + size++; // add one for null termination + char* s = new char[size+1]; + // read open quote + if(in.get(c) && c != '"') + { + return false; + } + // read the string data + in.read(s, size-1); + s[size-1] = 0; + cmStdString fileName = s; + delete [] s; + // read close quote + if(in.get(c) && c != '"') + { + cmCTestLog(this->CTest, ERROR_MESSAGE, + "failed to read close quote\n" + << "read [" << c << "]\n"); + return false; + } + if(!this->ReadCoverageArray(in, fileName) ) + { + cmCTestLog(this->CTest, ERROR_MESSAGE, + "failed to read coverage array for file: " + << fileName << "\n"); + return false; + } + return true; + } + return false; +} + + +bool cmParsePHPCoverage::ReadPHPData(const char* file) +{ + std::ifstream in(file); + if(!in) + { + return false; + } + int size = 0; + this->ReadArraySize(in, size); + char c = 0; + in.get(c); + if(c != '{') + { + cmCTestLog(this->CTest, ERROR_MESSAGE, + "failed to read open array\n"); + return false; + } + for(int i =0; i < size; i++) + { + if(!this->ReadFileInformation(in)) + { + cmCTestLog(this->CTest, ERROR_MESSAGE, + "Failed to read file #" << i << "\n"); + return false; + } + in.get(c); + if(c != '}') + { + cmCTestLog(this->CTest, ERROR_MESSAGE, + "failed to read close array\n"); + return false; + } + } + return true; +} + +bool cmParsePHPCoverage::ReadPHPCoverageDirectory(const char* d) +{ + cmsys::Directory dir; + if(!dir.Load(d)) + { + return false; + } + size_t numf; + unsigned int i; + numf = dir.GetNumberOfFiles(); + for (i = 0; i < numf; i++) + { + std::string file = dir.GetFile(i); + if(file != "." && file != ".." + && !cmSystemTools::FileIsDirectory(file.c_str())) + { + std::string path = d; + path += "/"; + path += file; + if(!this->ReadPHPData(path.c_str())) + { + return false; + } + } + } + return true; +} diff --git a/Source/CTest/cmParsePHPCoverage.h b/Source/CTest/cmParsePHPCoverage.h new file mode 100644 index 0000000..ce5741d --- /dev/null +++ b/Source/CTest/cmParsePHPCoverage.h @@ -0,0 +1,48 @@ +/*============================================================================ + CMake - Cross Platform Makefile Generator + Copyright 2000-2009 Kitware, Inc. + + Distributed under the OSI-approved BSD License (the "License"); + see accompanying file Copyright.txt for details. + + This software is distributed WITHOUT ANY WARRANTY; without even the + implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the License for more information. +============================================================================*/ + +#ifndef cmParsePHPCoverage_h +#define cmParsePHPCoverage_h + +#include "cmStandardIncludes.h" +#include "cmCTestCoverageHandler.h" + +/** \class cmParsePHPCoverage + * \brief Parse xdebug PHP coverage information + * + * This class is used to parse php coverage information produced + * by xdebug. The data is stored as a php dump of the array + * return by xdebug coverage. It is an array of arrays. + */ +class cmParsePHPCoverage +{ +public: + cmParsePHPCoverage(cmCTestCoverageHandlerContainer& cont, + cmCTest* ctest); + bool ReadPHPCoverageDirectory(const char* dir); + void PrintCoverage(); +private: + bool ReadPHPData(const char* file); + bool ReadArraySize(std::ifstream& in, int& size); + bool ReadFileInformation(std::ifstream& in); + bool ReadInt(std::ifstream& in, int& v); + bool ReadCoverageArray(std::ifstream& in, cmStdString const&); + bool ReadUntil(std::ifstream& in, char until); + typedef std::map<int, int> FileLineCoverage; + std::map<cmStdString, FileLineCoverage> FileToCoverage; + std::map<int, int> FileCoverage; + cmCTestCoverageHandlerContainer& Coverage; + cmCTest* CTest; +}; + + +#endif diff --git a/Source/CTest/cmProcess.cxx b/Source/CTest/cmProcess.cxx index b028cc0..0ee631f 100644 --- a/Source/CTest/cmProcess.cxx +++ b/Source/CTest/cmProcess.cxx @@ -61,7 +61,6 @@ bool cmProcess::StartProcess() cmsysProcess_SetWorkingDirectory(this->Process, this->WorkingDirectory.c_str()); } - cmsysProcess_SetOption(this->Process, cmsysProcess_Option_HideWindow, 1); cmsysProcess_SetTimeout(this->Process, this->Timeout); cmsysProcess_Execute(this->Process); return (cmsysProcess_GetState(this->Process) @@ -265,3 +264,9 @@ int cmProcess::ReportStatus() return result; } + + +int cmProcess::GetExitException() +{ + return cmsysProcess_GetExitException(this->Process); +} diff --git a/Source/CTest/cmProcess.h b/Source/CTest/cmProcess.h index 01dacf9..ff99ca2 100644 --- a/Source/CTest/cmProcess.h +++ b/Source/CTest/cmProcess.h @@ -43,7 +43,7 @@ public: void SetId(int id) { this->Id = id;} int GetExitValue() { return this->ExitValue;} double GetTotalTime() { return this->TotalTime;} - + int GetExitException(); /** * Read one line of output but block for no more than timeout. * Returns: diff --git a/Source/CursesDialog/cmCursesLongMessageForm.cxx b/Source/CursesDialog/cmCursesLongMessageForm.cxx index c66147b..1c48d8c 100644 --- a/Source/CursesDialog/cmCursesLongMessageForm.cxx +++ b/Source/CursesDialog/cmCursesLongMessageForm.cxx @@ -53,13 +53,13 @@ void cmCursesLongMessageForm::UpdateStatusBar() getmaxyx(stdscr, y, x); char bar[cmCursesMainForm::MAX_WIDTH]; - int size = strlen(this->Title.c_str()); + size_t size = strlen(this->Title.c_str()); if ( size >= cmCursesMainForm::MAX_WIDTH ) { size = cmCursesMainForm::MAX_WIDTH-1; } strncpy(bar, this->Title.c_str(), size); - for(int i=size-1; i<cmCursesMainForm::MAX_WIDTH; i++) bar[i] = ' '; + for(size_t i=size-1; i<cmCursesMainForm::MAX_WIDTH; i++) bar[i] = ' '; int width; if (x < cmCursesMainForm::MAX_WIDTH ) @@ -76,8 +76,8 @@ void cmCursesLongMessageForm::UpdateStatusBar() char version[cmCursesMainForm::MAX_WIDTH]; char vertmp[128]; sprintf(vertmp,"CMake Version %s", cmVersion::GetCMakeVersion()); - int sideSpace = (width-strlen(vertmp)); - for(int i=0; i<sideSpace; i++) { version[i] = ' '; } + size_t sideSpace = (width-strlen(vertmp)); + for(size_t i=0; i<sideSpace; i++) { version[i] = ' '; } sprintf(version+sideSpace, "%s", vertmp); version[width] = '\0'; diff --git a/Source/CursesDialog/cmCursesMainForm.cxx b/Source/CursesDialog/cmCursesMainForm.cxx index cd231ad..c93f353 100644 --- a/Source/CursesDialog/cmCursesMainForm.cxx +++ b/Source/CursesDialog/cmCursesMainForm.cxx @@ -242,7 +242,7 @@ void cmCursesMainForm::RePost() // Assign the fields: 3 for each entry: label, new entry marker // ('*' or ' ') and entry widget this->Fields = new FIELD*[3*this->NumberOfVisibleEntries+1]; - int cc; + size_t cc; for ( cc = 0; cc < 3 * this->NumberOfVisibleEntries+1; cc ++ ) { this->Fields[cc] = 0; @@ -334,32 +334,35 @@ void cmCursesMainForm::Render(int left, int top, int width, int height) } // Re-adjust the fields according to their place - bool isNewPage; - int i=0; this->NumberOfPages = 1; - std::vector<cmCursesCacheEntryComposite*>::iterator it; - for (it = this->Entries->begin(); it != this->Entries->end(); ++it) + if (height > 0) { - cmCacheManager::CacheIterator mit = - this->CMakeInstance->GetCacheManager()->GetCacheIterator((*it)->GetValue()); - if (mit.IsAtEnd() || - (!this->AdvancedMode && mit.GetPropertyAsBool("ADVANCED"))) + bool isNewPage; + int i=0; + std::vector<cmCursesCacheEntryComposite*>::iterator it; + for (it = this->Entries->begin(); it != this->Entries->end(); ++it) { - continue; - } - int row = (i % height) + 1; - int page = (i / height) + 1; - isNewPage = ( page > 1 ) && ( row == 1 ); + cmCacheManager::CacheIterator mit = + this->CMakeInstance->GetCacheManager()->GetCacheIterator((*it)->GetValue()); + if (mit.IsAtEnd() || + (!this->AdvancedMode && mit.GetPropertyAsBool("ADVANCED"))) + { + continue; + } + int row = (i % height) + 1; + int page = (i / height) + 1; + isNewPage = ( page > 1 ) && ( row == 1 ); - if (isNewPage) - { - this->NumberOfPages++; + if (isNewPage) + { + this->NumberOfPages++; + } + (*it)->Label->Move(left, top+row-1, isNewPage); + (*it)->IsNewLabel->Move(left+32, top+row-1, false); + (*it)->Entry->Move(left+33, top+row-1, false); + (*it)->Entry->SetPage(this->NumberOfPages); + i++; } - (*it)->Label->Move(left, top+row-1, isNewPage); - (*it)->IsNewLabel->Move(left+32, top+row-1, false); - (*it)->Entry->Move(left+33, top+row-1, false); - (*it)->Entry->SetPage(this->NumberOfPages); - i++; } // Post the form @@ -454,7 +457,7 @@ void cmCursesMainForm::PrintKeys(int process /* = 0 */) if (cw) { sprintf(firstLine, "Page %d of %d", cw->GetPage(), this->NumberOfPages); - curses_move(0,65-strlen(firstLine)-1); + curses_move(0,65-static_cast<unsigned int>(strlen(firstLine))-1); printw(firstLine); } // } @@ -526,10 +529,10 @@ void cmCursesMainForm::UpdateStatusBar(const char* message) // Join the key, help string and pad with spaces // (or truncate) as necessary char bar[cmCursesMainForm::MAX_WIDTH]; - int i, curFieldLen = strlen(curField); - int helpLen = strlen(help); + size_t i, curFieldLen = strlen(curField); + size_t helpLen = strlen(help); - int width; + size_t width; if (x < cmCursesMainForm::MAX_WIDTH ) { width = x; @@ -592,7 +595,7 @@ void cmCursesMainForm::UpdateStatusBar(const char* message) char version[cmCursesMainForm::MAX_WIDTH]; char vertmp[128]; sprintf(vertmp,"CMake Version %s", cmVersion::GetCMakeVersion()); - int sideSpace = (width-strlen(vertmp)); + size_t sideSpace = (width-strlen(vertmp)); for(i=0; i<sideSpace; i++) { version[i] = ' '; } sprintf(version+sideSpace, "%s", vertmp); version[width] = '\0'; @@ -795,8 +798,8 @@ void cmCursesMainForm::RemoveEntry(const char* value) // copy from the list box to the cache manager void cmCursesMainForm::FillCacheManagerFromUI() { - int size = this->Entries->size(); - for(int i=0; i < size; i++) + size_t size = this->Entries->size(); + for(size_t i=0; i < size; i++) { cmCacheManager::CacheIterator it = this->CMakeInstance->GetCacheManager()->GetCacheIterator( @@ -866,7 +869,7 @@ void cmCursesMainForm::HandleInput() std::string searchstr = "Search: " + this->SearchString; this->UpdateStatusBar( searchstr.c_str() ); this->PrintKeys(1); - curses_move(y-5,searchstr.size()); + curses_move(y-5,static_cast<unsigned int>(searchstr.size())); //curses_move(1,1); touchwin(stdscr); refresh(); @@ -902,7 +905,7 @@ void cmCursesMainForm::HandleInput() this->SearchMode = false; if ( this->SearchString.size() > 0 ) { - this->JumpToCacheEntry(-1, this->SearchString.c_str()); + this->JumpToCacheEntry(this->SearchString.c_str()); this->OldSearchString = this->SearchString; } this->SearchString = ""; @@ -961,7 +964,7 @@ void cmCursesMainForm::HandleInput() else if ( key == KEY_DOWN || key == ctrl('n') ) { FIELD* cur = current_field(this->Form); - int findex = field_index(cur); + size_t findex = field_index(cur); if ( findex == 3*this->NumberOfVisibleEntries-1 ) { continue; @@ -1076,7 +1079,7 @@ void cmCursesMainForm::HandleInput() { if ( this->OldSearchString.size() > 0 ) { - this->JumpToCacheEntry(-1, this->OldSearchString.c_str()); + this->JumpToCacheEntry(this->OldSearchString.c_str()); } } // switch advanced on/off @@ -1108,7 +1111,7 @@ void cmCursesMainForm::HandleInput() { this->OkToGenerate = false; FIELD* cur = current_field(this->Form); - int findex = field_index(cur); + size_t findex = field_index(cur); // make the next or prev. current field after deletion // each entry consists of fields: label, isnew, value @@ -1191,7 +1194,7 @@ int cmCursesMainForm::LoadCache(const char *) return r; } -void cmCursesMainForm::JumpToCacheEntry(int idx, const char* astr) +void cmCursesMainForm::JumpToCacheEntry(const char* astr) { std::string str; if ( astr ) @@ -1199,18 +1202,14 @@ void cmCursesMainForm::JumpToCacheEntry(int idx, const char* astr) str = cmSystemTools::LowerCase(astr); } - if ( idx > this->NumberOfVisibleEntries ) - { - return; - } - if ( idx < 0 && str.size() == 0) + if(str.empty()) { return; } FIELD* cur = current_field(this->Form); int start_index = field_index(cur); int findex = start_index; - while ( (findex / 3) != idx ) + for(;;) { if ( str.size() > 0 ) { @@ -1232,7 +1231,7 @@ void cmCursesMainForm::JumpToCacheEntry(int idx, const char* astr) } } } - if ( findex >= 3* this->NumberOfVisibleEntries-1 ) + if ( size_t(findex) >= 3* this->NumberOfVisibleEntries-1 ) { set_current_field(this->Form, this->Fields[2]); } diff --git a/Source/CursesDialog/cmCursesMainForm.h b/Source/CursesDialog/cmCursesMainForm.h index 9751999..3e191b4 100644 --- a/Source/CursesDialog/cmCursesMainForm.h +++ b/Source/CursesDialog/cmCursesMainForm.h @@ -122,9 +122,8 @@ protected: // Remove an entry from the interface and the cache. void RemoveEntry(const char* value); - // Jump to the cache value with index idx. If string str is - // specified, it will stop on widget that contain that string. - void JumpToCacheEntry(int idx, const char* str); + // Jump to the cache entry whose name matches the string. + void JumpToCacheEntry(const char* str); // Copies of cache entries stored in the user interface std::vector<cmCursesCacheEntryComposite*>* Entries; @@ -147,7 +146,7 @@ protected: // Where is cmake executable std::string WhereCMake; // Number of entries shown (depends on mode -normal or advanced-) - int NumberOfVisibleEntries; + size_t NumberOfVisibleEntries; bool AdvancedMode; // Did the iteration converge (no new entries) ? bool OkToGenerate; diff --git a/Source/CursesDialog/form/fld_info.c b/Source/CursesDialog/form/fld_info.c index 7c50b1d..1ba92c8 100644 --- a/Source/CursesDialog/form/fld_info.c +++ b/Source/CursesDialog/form/fld_info.c @@ -69,7 +69,7 @@ int field_info(const FIELD *field, | int *drows, int *dcols, | int *maxgrow) | -| Description : Retrieve informations about a dynamic fields current +| Description : Retrieve information about a dynamic fields current | dynamic parameters. | | Return Values : E_OK - success diff --git a/Source/CursesDialog/form/fld_user.c b/Source/CursesDialog/form/fld_user.c index 7ffca9c..3287b5b 100644 --- a/Source/CursesDialog/form/fld_user.c +++ b/Source/CursesDialog/form/fld_user.c @@ -39,7 +39,7 @@ MODULE_ID("$Id$") | Function : int set_field_userptr(FIELD *field, void *usrptr) | | Description : Set the pointer that is reserved in any field to store -| application relevant informations +| application relevant information | | Return Values : E_OK - on success +--------------------------------------------------------------------------*/ @@ -54,7 +54,7 @@ int set_field_userptr(FIELD * field, void *usrptr) | Function : void *field_userptr(const FIELD *field) | | Description : Return the pointer that is reserved in any field to -| store application relevant informations. +| store application relevant information. | | Return Values : Value of pointer. If no such pointer has been set, | NULL is returned diff --git a/Source/CursesDialog/form/frm_driver.c b/Source/CursesDialog/form/frm_driver.c index 0b53b5a..03896c2 100644 --- a/Source/CursesDialog/form/frm_driver.c +++ b/Source/CursesDialog/form/frm_driver.c @@ -357,8 +357,12 @@ static void Buffer_To_Window(const FIELD * field, WINDOW * win) assert(win && field); +#if defined(__LSB_VERSION__) + getmaxyx(win, height, width); +#else width = getmaxx(win); height = getmaxy(win); +#endif for(row=0, pBuffer=field->buf; row < height; @@ -396,7 +400,11 @@ static void Window_To_Buffer(WINDOW * win, FIELD * field) pad = field->pad; p = field->buf; +#if defined(__LSB_VERSION__) + { int width; getmaxyx(win, height, width); } +#else height = getmaxy(win); +#endif for(row=0; (row < height) && (row < field->drows); row++ ) { @@ -871,7 +879,17 @@ static int Display_Or_Erase_Field(FIELD * field, bool bEraseFlag) if (field->opts & O_VISIBLE) Set_Field_Window_Attributes(field,win); else + { +#if defined(__LSB_VERSION__) + /* getattrs() would be handy, but it is not part of LSB 4.0 */ + attr_t fwinAttrs; + short fwinPair; + wattr_get(fwin, &fwinAttrs, &fwinPair, 0); + wattr_set(win, fwinAttrs, fwinPair, 0); +#else wattrset(win,getattrs(fwin)); +#endif + } werase(win); } diff --git a/Source/CursesDialog/form/frm_post.c b/Source/CursesDialog/form/frm_post.c index 5ead942..3c63de7 100644 --- a/Source/CursesDialog/form/frm_post.c +++ b/Source/CursesDialog/form/frm_post.c @@ -51,6 +51,7 @@ int post_form(FORM * form) WINDOW *formwin; int err; int page; + int height, width; if (!form) RETURN(E_BAD_ARGUMENT); @@ -62,7 +63,13 @@ int post_form(FORM * form) RETURN(E_NOT_CONNECTED); formwin = Get_Form_Window(form); - if ((form->cols > getmaxx(formwin)) || (form->rows > getmaxy(formwin))) +#if defined(__LSB_VERSION__) + getmaxyx(formwin, height, width); +#else + width = getmaxx(formwin); + height = getmaxy(formwin); +#endif + if ((form->cols > width) || (form->rows > height)) RETURN(E_NO_ROOM); /* reset form->curpage to an invald value. This forces Set_Form_Page diff --git a/Source/CursesDialog/form/frm_user.c b/Source/CursesDialog/form/frm_user.c index 8f0edbc..f38bbbb 100644 --- a/Source/CursesDialog/form/frm_user.c +++ b/Source/CursesDialog/form/frm_user.c @@ -39,7 +39,7 @@ MODULE_ID("$Id$") | Function : int set_form_userptr(FORM *form, void *usrptr) | | Description : Set the pointer that is reserved in any form to store -| application relevant informations +| application relevant information | | Return Values : E_OK - on success +--------------------------------------------------------------------------*/ @@ -54,7 +54,7 @@ int set_form_userptr(FORM * form, void *usrptr) | Function : void *form_userptr(const FORM *form) | | Description : Return the pointer that is reserved in any form to -| store application relevant informations. +| store application relevant information. | | Return Values : Value of pointer. If no such pointer has been set, | NULL is returned diff --git a/Source/QtDialog/CMakeIngestOSXBundleLibraries.cmake b/Source/QtDialog/CMakeIngestOSXBundleLibraries.cmake deleted file mode 100644 index 9f5cf00..0000000 --- a/Source/QtDialog/CMakeIngestOSXBundleLibraries.cmake +++ /dev/null @@ -1,347 +0,0 @@ -# -# CMakeIngestOSXBundleLibraries.cmake -# -# Only for the Mac build. -# -# Depends on OS tools: -# otool -# install_name_tool -# -# This script ingests libraries and frameworks into an existing .app bundle and -# then uses install_name_tool to fixup the references to the newly embedded -# libraries so that they all refer to each other via "@executable_path." -# -# The main intent (and simplifying assumption used for developing the script) -# is to have a single executable .app bundle that becomes "self-contained" by -# copying all non-system libs that it depends on into itself. The further -# assumption is that all such dependencies are simple .dylib shared library -# files or Mac Framework libraries. -# -# This script can be used as part of the build via ADD_CUSTOM_COMMAND, or used -# only during make install via INSTALL SCRIPT. -# -if(NOT DEFINED input_file) - message(FATAL_ERROR " -${CMAKE_CURRENT_LIST_FILE}(${CMAKE_CURRENT_LIST_LINE}): error: Variable input_file is not defined. - -Use a command line like this to use this script: - cmake \"-Dinput_file=filename\" \"-Dextra_libs=/path/to/lib1;/path/to/lib2\" \"-Dlib_path=/path/to/unqualified/libs\" -P \"${CMAKE_CURRENT_LIST_FILE}\" - -'input_file' should be the main executable inside a Mac bundle directory structure. -For example, use 'bin/paraview.app/Contents/MacOS/paraview' from a ParaView binary dir. - -'extra_libs' should be a semi-colon separated list of full path names to extra libraries -to copy into the bundle that cannot be derived from otool -L output. For example, you may -also want to fixup dynamically loaded plugins from your build tree and copy them into the -bundle. - -'lib_path' should be the path where to find libraries referenced without a path name in -otool -L output. - -") -endif(NOT DEFINED input_file) -message("ingest ${input_file}") -set(eol_char "E") - -if(APPLE) - set(dep_tool "otool") - set(dep_cmd_args "-L") - set(dep_regex "^\t([^\t]+) \\(compatibility version ([0-9]+.[0-9]+.[0-9]+), current version ([0-9]+.[0-9]+.[0-9]+)\\)${eol_char}$") -endif(APPLE) - -message("") -message("# Script \"${CMAKE_CURRENT_LIST_FILE}\" running...") -message("") -message("input_file: '${input_file}'") -message("extra_libs: '${extra_libs}'") -message("lib_path: '${lib_path}'") -message("") - -get_filename_component(input_file_full "${input_file}" ABSOLUTE) -message("input_file_full: '${input_file_full}'") - -get_filename_component(bundle "${input_file_full}/../../.." ABSOLUTE) -message("bundle: '${bundle}'") - - -find_program(dep_cmd ${dep_tool}) - -# find the full path to the framework in path set the result -# in pathout -macro(find_framework_full_path path pathout) - set(${pathout} "${path}") - if(NOT EXISTS "${path}") - set(FRAMEWORK_SEARCH "/Library/Frameworks" - "/System/Library/Frameworks" ) - set(__FOUND FALSE) - foreach(f ${FRAMEWORK_SEARCH}) - set(newd "${f}/${path}") - if(EXISTS "${newd}" AND NOT __FOUND) - set(${pathout} "${newd}") - set(__FOUND TRUE) - endif(EXISTS "${newd}" AND NOT __FOUND) - endforeach(f) - endif(NOT EXISTS "${path}") -endmacro(find_framework_full_path) - - -macro(append_unique au_list_var au_value) - set(${au_list_var} ${${au_list_var}} "${au_value}") -endmacro(append_unique) - - -macro(gather_dependents gd_target gd_dependents_var) - execute_process( - COMMAND ${dep_cmd} ${dep_cmd_args} ${gd_target} - OUTPUT_VARIABLE dep_tool_ov - ) - - string(REGEX REPLACE ";" "\\\\;" dep_candidates "${dep_tool_ov}") - string(REGEX REPLACE "\n" "${eol_char};" dep_candidates "${dep_candidates}") - - set(${gd_dependents_var} "") - - foreach(candidate ${dep_candidates}) - if("${candidate}" MATCHES "${dep_regex}") - string(REGEX REPLACE "${dep_regex}" "\\1" raw_item "${candidate}") - string(REGEX REPLACE "${dep_regex}" "\\2" raw_compat_version "${candidate}") - string(REGEX REPLACE "${dep_regex}" "\\3" raw_current_version "${candidate}") - - set(item "${raw_item}") - - string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+)$" "\\1" compat_major_version "${raw_compat_version}") - string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+)$" "\\2" compat_minor_version "${raw_compat_version}") - string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+)$" "\\3" compat_patch_version "${raw_compat_version}") - - string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+)$" "\\1" current_major_version "${raw_current_version}") - string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+)$" "\\2" current_minor_version "${raw_current_version}") - string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+)$" "\\3" current_patch_version "${raw_current_version}") - - #message("${raw_item} - compat ${raw_compat_version} - current ${raw_current_version}") - append_unique("${gd_dependents_var}" "${item}") - else("${candidate}" MATCHES "${dep_regex}") - if("${candidate}" STREQUAL "${gd_target}:${eol_char}") - #message("info: ignoring target name...") - else("${candidate}" STREQUAL "${gd_target}:${eol_char}") - message("error: candidate='${candidate}'") - endif("${candidate}" STREQUAL "${gd_target}:${eol_char}") - endif("${candidate}" MATCHES "${dep_regex}") - endforeach(candidate) -endmacro(gather_dependents) - - -message("Gathering dependent libraries for '${input_file_full}'...") -gather_dependents("${input_file_full}" deps) -message("") - - -# Order lexicographically: -# -list(SORT deps) - - -# Split into separate lists, "system" "embedded" and "nonsystem" libraries. -# System libs are assumed to be available on all target runtime Macs and do not -# need to be copied/fixed-up by this script. Embedded libraries are assumed to -# be in the bundle and fixed-up already. Only non-system, non-embedded libs -# need copying and fixing up... -# -set(system_deps "") -set(embedded_deps "") -set(nonsystem_deps "") - -foreach(d ${deps}) - set(d_is_embedded_lib 0) - set(d_is_system_lib 0) - - if("${d}" MATCHES "^(/System/Library|/usr/lib)") - set(d_is_system_lib 1) - else("${d}" MATCHES "^(/System/Library|/usr/lib)") - if("${d}" MATCHES "^@executable_path") - set(d_is_embedded_lib 1) - endif("${d}" MATCHES "^@executable_path") - endif("${d}" MATCHES "^(/System/Library|/usr/lib)") - - if(d_is_system_lib) - set(system_deps ${system_deps} "${d}") - else(d_is_system_lib) - if(d_is_embedded_lib) - set(embedded_deps ${embedded_deps} "${d}") - else(d_is_embedded_lib) - set(nonsystem_deps ${nonsystem_deps} "${d}") - endif(d_is_embedded_lib) - endif(d_is_system_lib) -endforeach(d) - -message("") -message("system_deps:") -foreach(d ${system_deps}) - message("${d}") -endforeach(d ${system_deps}) - -message("") -message("embedded_deps:") -foreach(d ${embedded_deps}) - message("${d}") -endforeach(d ${embedded_deps}) - -message("") -message("nonsystem_deps:") -foreach(d ${nonsystem_deps}) - message("${d}") -endforeach(d ${nonsystem_deps}) - -message("") - - -macro(copy_library_into_bundle clib_bundle clib_libsrc clib_dstlibs clib_fixups) - # - # If the source library is a framework, copy just the shared lib bit of the framework - # into the bundle under "${clib_bundle}/Contents/Frameworks" - if it is just a dylib - # copy it into the same directory with the main bundle executable under - # "${clib_bundle}/Contents/MacOS" - # - if("${clib_libsrc}" MATCHES ".framework/.*/.*/.*") - # make sure clib_libsrc is a full path to the framework as a framework - # maybe linked in with relative paths in some cases - find_framework_full_path("${clib_libsrc}" fw_full_src) - get_filename_component(fw_src "${fw_full_src}" ABSOLUTE) - get_filename_component(fw_srcdir "${clib_libsrc}/../../.." ABSOLUTE) - get_filename_component(fwdirname "${fw_srcdir}" NAME) - string(REGEX REPLACE "^(.*)\\.framework$" "\\1" fwname "${fwdirname}") - string(REGEX REPLACE "^.*/${fwname}\\.framework/(.*)$" "\\1" fwlibname "${clib_libsrc}") - set(fw_dstdir "${clib_bundle}/Contents/Frameworks") - -# message("") -# message("fwdirname: '${fwdirname}'") -# message("fwname: '${fwname}'") -# message("fwlibname: '${fwlibname}'") -# message("fw_src: '${fw_src}'") -# message("fw_srcdir: '${fw_srcdir}'") -# message("fw_dstdir: '${fw_dstdir}'") -# message("new_name: '@executable_path/../Frameworks/${fwdirname}/${fwlibname}'") -# message("") - - message("Copying ${fw_srcdir} into bundle...") - - # This command copies the *entire* framework recursively: - # -# execute_process(COMMAND ${CMAKE_COMMAND} -E copy_directory -# "${fw_srcdir}" "${fw_dstdir}" -# ) - - # This command copies just the main shared lib of the framework: - # (This technique will not work for frameworks that have necessary - # resource or auxiliary files...) - # - message("fw_src = [${fw_src}] fw_full_src = [${fw_full_src}]") - message("Copy: ${CMAKE_COMMAND} -E copy \"${fw_src}\" \"${fw_dstdir}/${fwlibname}\"") - execute_process(COMMAND ${CMAKE_COMMAND} -E copy - "${fw_src}" "${fw_dstdir}/${fwlibname}" - ) - - get_filename_component(fw_src_path "${fw_src}" PATH) - message("Checking ${fw_src_path}/Resources") - if(EXISTS "${fw_src_path}/Resources") - message("Copy: ${CMAKE_COMMAND} -E copy_directory \"${fw_src_path}/Resources/\" \"${fw_dstdir}/Resources/\"") - execute_process(COMMAND ${CMAKE_COMMAND} -E copy_directory - "${fw_src_path}/Resources/" "${fw_dstdir}/${fwdirname}/Resources/") - endif(EXISTS "${fw_src_path}/Resources") - - execute_process(COMMAND install_name_tool - -id "@executable_path/../Frameworks/${fwlibname}" - "${clib_bundle}/Contents/Frameworks/${fwlibname}" - ) - set(${clib_dstlibs} ${${clib_dstlibs}} - "${clib_bundle}/Contents/Frameworks/${fwlibname}" - ) - set(${clib_fixups} ${${clib_fixups}} - "-change" - "${clib_libsrc}" - "@executable_path/../Frameworks/${fwlibname}" - ) - else("${clib_libsrc}" MATCHES ".framework/.*/.*/.*") - if("${clib_libsrc}" MATCHES "/") - set(clib_libsrcfull "${clib_libsrc}") - else("${clib_libsrc}" MATCHES "/") - set(clib_libsrcfull "${lib_path}/${clib_libsrc}") - if(NOT EXISTS "${clib_libsrcfull}") - message(FATAL_ERROR "error: '${clib_libsrcfull}' does not exist...") - endif(NOT EXISTS "${clib_libsrcfull}") - endif("${clib_libsrc}" MATCHES "/") - - get_filename_component(dylib_src "${clib_libsrcfull}" ABSOLUTE) - get_filename_component(dylib_name "${dylib_src}" NAME) - set(dylib_dst "${clib_bundle}/Contents/MacOS/${dylib_name}") - -# message("dylib_src: ${dylib_src}") -# message("dylib_dst: ${dylib_dst}") -# message("new_name: '@executable_path/${dylib_name}'") - - message("Copying ${dylib_src} into bundle...") - execute_process(COMMAND ${CMAKE_COMMAND} -E copy - "${dylib_src}" "${dylib_dst}") - execute_process(COMMAND install_name_tool - -id "@executable_path/${dylib_name}" - "${dylib_dst}" - ) - set(${clib_dstlibs} ${${clib_dstlibs}} - "${dylib_dst}" - ) - set(${clib_fixups} ${${clib_fixups}} - "-change" - "${clib_libsrc}" - "@executable_path/${dylib_name}" - ) - endif("${clib_libsrc}" MATCHES ".framework/.*/.*/.*") -endmacro(copy_library_into_bundle) - - -# Copy dependent "nonsystem" libraries into the bundle: -# -message("Copying dependent libraries into bundle...") -set(srclibs ${nonsystem_deps} ${extra_libs}) -set(dstlibs "") -set(fixups "") -foreach(d ${srclibs}) - message("copy it --- ${d}") - copy_library_into_bundle("${bundle}" "${d}" dstlibs fixups) -endforeach(d) - -message("") -message("dstlibs='${dstlibs}'") -message("") -message("fixups='${fixups}'") -message("") - - -# Fixup references to copied libraries in the main bundle executable and in the -# copied libraries themselves: -# -if(NOT "${fixups}" STREQUAL "") - message("Fixing up references...") - foreach(d ${dstlibs} "${input_file_full}") - message("fixing up references in: '${d}'") - execute_process(COMMAND install_name_tool ${fixups} "${d}") - endforeach(d) - message("") -endif(NOT "${fixups}" STREQUAL "") - - -# List all references to eyeball them and make sure they look right: -# -message("Listing references...") -foreach(d ${dstlibs} "${input_file_full}") - execute_process(COMMAND otool -L "${d}") - message("") -endforeach(d) -message("") - - -# Output file: -# -#get_filename_component(script_name "${CMAKE_CURRENT_LIST_FILE}" NAME) -#file(WRITE "${input_file_full}_${script_name}" "# Script \"${CMAKE_CURRENT_LIST_FILE}\" completed.\n") -message("") -message("# Script \"${CMAKE_CURRENT_LIST_FILE}\" completed.") -message("") diff --git a/Source/QtDialog/CMakeLists.txt b/Source/QtDialog/CMakeLists.txt index 405c952..4785188 100644 --- a/Source/QtDialog/CMakeLists.txt +++ b/Source/QtDialog/CMakeLists.txt @@ -19,13 +19,6 @@ ELSE(NOT QT4_FOUND) INCLUDE(${QT_USE_FILE}) SET(CMAKE_PACKAGE_QTGUI TRUE) - # i don't want to install or package the qt gui on windows - # unless qt is static - IF(WIN32 AND NOT QT_CONFIG MATCHES "static") - SET(CMAKE_PACKAGE_QTGUI FALSE) - MESSAGE(STATUS - "WARNING: QtDialog requires a static built qt for installation.") - ENDIF(WIN32 AND NOT QT_CONFIG MATCHES "static") SET(SRCS AddCacheEntry.cxx AddCacheEntry.h @@ -86,12 +79,8 @@ ELSE(NOT QT4_FOUND) SET(CMAKE_INSTALL_DESTINATION_ARGS BUNDLE DESTINATION "${CMAKE_BUNDLE_LOCATION}") ENDIF(${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION} GREATER 2.4) - # if qt is not static and we are on windows then skip the install - # I don't want to distribute qt dlls - IF(CMAKE_PACKAGE_QTGUI) - INSTALL(TARGETS cmake-gui RUNTIME DESTINATION bin - ${CMAKE_INSTALL_DESTINATION_ARGS}) - ENDIF(CMAKE_PACKAGE_QTGUI) + + INSTALL(TARGETS cmake-gui RUNTIME DESTINATION bin ${CMAKE_INSTALL_DESTINATION_ARGS}) IF(UNIX) # install a desktop file so CMake appears in the application start menu @@ -112,10 +101,21 @@ ELSE(NOT QT4_FOUND) "${CMake_BINARY_DIR}/Source/QtDialog/postupgrade.sh") INSTALL(CODE "execute_process(COMMAND ln -s \"../MacOS/${CMAKE_BUNDLE_NAME}\" cmake-gui WORKING_DIRECTORY \$ENV{DESTDIR}\${CMAKE_INSTALL_PREFIX}/bin)") - INSTALL(CODE "set(input_file - \"\$ENV{DESTDIR}\${CMAKE_INSTALL_PREFIX}/MacOS/${CMAKE_BUNDLE_NAME}\")") - INSTALL(SCRIPT "${CMake_SOURCE_DIR}/Source/QtDialog/CMakeIngestOSXBundleLibraries.cmake") ENDIF(APPLE) + + if(APPLE OR WIN32) + # install rules for including 3rd party libs such as Qt + # if a system Qt is used (e.g. installed in /usr/lib/), it will not be included in the installation + set(fixup_exe "\$ENV{DESTDIR}\${CMAKE_INSTALL_PREFIX}/bin/cmake-gui${CMAKE_EXECUTABLE_SUFFIX}") + if(APPLE) + set(fixup_exe "\$ENV{DESTDIR}\${CMAKE_INSTALL_PREFIX}/MacOS/${CMAKE_BUNDLE_NAME}") + endif(APPLE) + install(CODE " + include(\"${CMake_SOURCE_DIR}/Modules/BundleUtilities.cmake\") + fixup_bundle(\"${fixup_exe}\" \"\" \"${QT_LIBRARY_DIR};${QT_BINARY_DIR}\") + ") + endif(APPLE OR WIN32) + CONFIGURE_FILE("${QtDialog_SOURCE_DIR}/QtDialogCPack.cmake.in" "${QtDialog_BINARY_DIR}/QtDialogCPack.cmake" @ONLY) ENDIF(NOT QT4_FOUND) diff --git a/Source/QtDialog/CMakeSetup.cxx b/Source/QtDialog/CMakeSetup.cxx index e613a78..7ba7f51 100644 --- a/Source/QtDialog/CMakeSetup.cxx +++ b/Source/QtDialog/CMakeSetup.cxx @@ -11,7 +11,6 @@ ============================================================================*/ #include "QCMake.h" // include to disable MS warnings #include <QApplication> -#include <QFileInfo> #include <QDir> #include <QTranslator> #include <QLocale> @@ -21,6 +20,7 @@ #include "cmake.h" #include "cmVersion.h" #include <cmsys/CommandLineArguments.hxx> +#include <cmsys/SystemTools.hxx> //---------------------------------------------------------------------------- static const char * cmDocumentationName[][3] = @@ -164,16 +164,31 @@ int main(int argc, char** argv) QStringList args = app.arguments(); if(args.count() == 2) { - QFileInfo buildFileInfo(args[1], "CMakeCache.txt"); - QFileInfo srcFileInfo(args[1], "CMakeLists.txt"); - if(buildFileInfo.exists()) + cmsys_stl::string filePath = cmSystemTools::CollapseFullPath(args[1].toAscii().data()); + + // check if argument is a directory containing CMakeCache.txt + cmsys_stl::string buildFilePath = + cmSystemTools::CollapseFullPath("CMakeCache.txt", filePath.c_str()); + + // check if argument is a CMakeCache.txt file + if(cmSystemTools::GetFilenameName(filePath) == "CMakeCache.txt" && + cmSystemTools::FileExists(filePath.c_str())) + { + buildFilePath = filePath; + } + + // check if argument is a directory containing CMakeLists.txt + cmsys_stl::string srcFilePath = + cmSystemTools::CollapseFullPath("CMakeLists.txt", filePath.c_str()); + + if(cmSystemTools::FileExists(buildFilePath.c_str())) { - dialog.setBinaryDirectory(buildFileInfo.absolutePath()); + dialog.setBinaryDirectory(cmSystemTools::GetFilenamePath(buildFilePath).c_str()); } - else if(srcFileInfo.exists()) + else if(cmSystemTools::FileExists(srcFilePath.c_str())) { - dialog.setSourceDirectory(srcFileInfo.absolutePath()); - dialog.setBinaryDirectory(QDir::currentPath()); + dialog.setSourceDirectory(filePath.c_str()); + dialog.setBinaryDirectory(cmSystemTools::CollapseFullPath(".").c_str()); } } } diff --git a/Source/QtDialog/CMakeSetupDialog.cxx b/Source/QtDialog/CMakeSetupDialog.cxx index eb82f2a..408dbac 100644 --- a/Source/QtDialog/CMakeSetupDialog.cxx +++ b/Source/QtDialog/CMakeSetupDialog.cxx @@ -34,7 +34,7 @@ #include "FirstConfigure.h" #include "cmVersion.h" -QCMakeThread::QCMakeThread(QObject* p) +QCMakeThread::QCMakeThread(QObject* p) : QThread(p), CMakeInstance(NULL) { } @@ -55,7 +55,7 @@ void QCMakeThread::run() } CMakeSetupDialog::CMakeSetupDialog() - : ExitAfterGenerate(true), CacheModified(false), CurrentState(Interrupting) + : ExitAfterGenerate(true), CacheModified(false), ConfigureNeeded(true), CurrentState(Interrupting) { QString title = QString(tr("CMake %1")); title = title.arg(cmVersion::GetCMakeVersion()); @@ -76,61 +76,62 @@ CMakeSetupDialog::CMakeSetupDialog() this->ProgressBar->reset(); this->RemoveEntry->setEnabled(false); this->AddEntry->setEnabled(false); - + QByteArray p = settings.value("SplitterSizes").toByteArray(); this->Splitter->restoreState(p); bool groupView = settings.value("GroupView", false).toBool(); - if(groupView) - { - this->setViewType(2); - this->ViewType->setCurrentIndex(2); - } + this->setGroupedView(groupView); + this->groupedCheck->setCheckState(groupView ? Qt::Checked : Qt::Unchecked); + + bool advancedView = settings.value("AdvancedView", false).toBool(); + this->setAdvancedView(advancedView); + this->advancedCheck->setCheckState(advancedView?Qt::Checked : Qt::Unchecked); QMenu* FileMenu = this->menuBar()->addMenu(tr("&File")); this->ReloadCacheAction = FileMenu->addAction(tr("&Reload Cache")); - QObject::connect(this->ReloadCacheAction, SIGNAL(triggered(bool)), + QObject::connect(this->ReloadCacheAction, SIGNAL(triggered(bool)), this, SLOT(doReloadCache())); this->DeleteCacheAction = FileMenu->addAction(tr("&Delete Cache")); - QObject::connect(this->DeleteCacheAction, SIGNAL(triggered(bool)), + QObject::connect(this->DeleteCacheAction, SIGNAL(triggered(bool)), this, SLOT(doDeleteCache())); this->ExitAction = FileMenu->addAction(tr("E&xit")); - QObject::connect(this->ExitAction, SIGNAL(triggered(bool)), + QObject::connect(this->ExitAction, SIGNAL(triggered(bool)), this, SLOT(close())); QMenu* ToolsMenu = this->menuBar()->addMenu(tr("&Tools")); this->ConfigureAction = ToolsMenu->addAction(tr("&Configure")); // prevent merging with Preferences menu item on Mac OS X this->ConfigureAction->setMenuRole(QAction::NoRole); - QObject::connect(this->ConfigureAction, SIGNAL(triggered(bool)), + QObject::connect(this->ConfigureAction, SIGNAL(triggered(bool)), this, SLOT(doConfigure())); this->GenerateAction = ToolsMenu->addAction(tr("&Generate")); - QObject::connect(this->GenerateAction, SIGNAL(triggered(bool)), + QObject::connect(this->GenerateAction, SIGNAL(triggered(bool)), this, SLOT(doGenerate())); QAction* showChangesAction = ToolsMenu->addAction(tr("&Show My Changes")); - QObject::connect(showChangesAction, SIGNAL(triggered(bool)), + QObject::connect(showChangesAction, SIGNAL(triggered(bool)), this, SLOT(showUserChanges())); #if defined(Q_WS_MAC) - this->InstallForCommandLineAction + this->InstallForCommandLineAction = ToolsMenu->addAction(tr("&Install For Command Line Use")); - QObject::connect(this->InstallForCommandLineAction, SIGNAL(triggered(bool)), + QObject::connect(this->InstallForCommandLineAction, SIGNAL(triggered(bool)), this, SLOT(doInstallForCommandLine())); -#endif +#endif QMenu* OptionsMenu = this->menuBar()->addMenu(tr("&Options")); this->SuppressDevWarningsAction = OptionsMenu->addAction(tr("&Suppress dev Warnings (-Wno-dev)")); this->SuppressDevWarningsAction->setCheckable(true); QAction* debugAction = OptionsMenu->addAction(tr("&Debug Output")); debugAction->setCheckable(true); - QObject::connect(debugAction, SIGNAL(toggled(bool)), + QObject::connect(debugAction, SIGNAL(toggled(bool)), this, SLOT(setDebugOutput(bool))); - + OptionsMenu->addSeparator(); QAction* expandAction = OptionsMenu->addAction(tr("&Expand Grouped Entries")); - QObject::connect(expandAction, SIGNAL(triggered(bool)), + QObject::connect(expandAction, SIGNAL(triggered(bool)), this->CacheValues, SLOT(expandAll())); QAction* collapseAction = OptionsMenu->addAction(tr("&Collapse Grouped Entries")); - QObject::connect(collapseAction, SIGNAL(triggered(bool)), + QObject::connect(collapseAction, SIGNAL(triggered(bool)), this->CacheValues, SLOT(collapseAll())); QMenu* HelpMenu = this->menuBar()->addMenu(tr("&Help")); @@ -140,17 +141,17 @@ CMakeSetupDialog::CMakeSetupDialog() a = HelpMenu->addAction(tr("Help")); QObject::connect(a, SIGNAL(triggered(bool)), this, SLOT(doHelp())); - + QShortcut* filterShortcut = new QShortcut(QKeySequence::Find, this); - QObject::connect(filterShortcut, SIGNAL(activated()), + QObject::connect(filterShortcut, SIGNAL(activated()), this, SLOT(startSearch())); - + this->setAcceptDrops(true); - + // get the saved binary directories QStringList buildPaths = this->loadBuildPaths(); this->BinaryDirectory->addItems(buildPaths); - + this->BinaryDirectory->setCompleter(new QCMakeFileCompleter(this, true)); this->SourceDirectory->setCompleter(new QCMakeFileCompleter(this, true)); @@ -162,37 +163,39 @@ CMakeSetupDialog::CMakeSetupDialog() // start the cmake worker thread this->CMakeThread = new QCMakeThread(this); QObject::connect(this->CMakeThread, SIGNAL(cmakeInitialized()), - this, SLOT(initialize()), Qt::QueuedConnection); + this, SLOT(initialize()), Qt::QueuedConnection); this->CMakeThread->start(); - + this->enterState(ReadyConfigure); + + ProgressOffset = 0.0; + ProgressFactor = 1.0; } void CMakeSetupDialog::initialize() { // now the cmake worker thread is running, lets make our connections to it - QObject::connect(this->CMakeThread->cmakeInstance(), + QObject::connect(this->CMakeThread->cmakeInstance(), SIGNAL(propertiesChanged(const QCMakePropertyList&)), this->CacheValues->cacheModel(), SLOT(setProperties(const QCMakePropertyList&))); QObject::connect(this->ConfigureButton, SIGNAL(clicked(bool)), this, SLOT(doConfigure())); - QObject::connect(this->CMakeThread->cmakeInstance(), - SIGNAL(configureDone(int)), - this, SLOT(finishConfigure(int))); - QObject::connect(this->CMakeThread->cmakeInstance(), - SIGNAL(generateDone(int)), - this, SLOT(finishGenerate(int))); + + QObject::connect(this->CMakeThread->cmakeInstance(), SIGNAL(configureDone(int)), + this, SLOT(exitLoop(int))); + QObject::connect(this->CMakeThread->cmakeInstance(), SIGNAL(generateDone(int)), + this, SLOT(exitLoop(int))); QObject::connect(this->GenerateButton, SIGNAL(clicked(bool)), this, SLOT(doGenerate())); - + QObject::connect(this->BrowseSourceDirectoryButton, SIGNAL(clicked(bool)), this, SLOT(doSourceBrowse())); QObject::connect(this->BrowseBinaryDirectoryButton, SIGNAL(clicked(bool)), this, SLOT(doBinaryBrowse())); - + QObject::connect(this->BinaryDirectory, SIGNAL(editTextChanged(QString)), this, SLOT(onBinaryDirectoryChanged(QString))); QObject::connect(this->SourceDirectory, SIGNAL(textChanged(QString)), @@ -204,11 +207,11 @@ void CMakeSetupDialog::initialize() QObject::connect(this->CMakeThread->cmakeInstance(), SIGNAL(binaryDirChanged(QString)), this, SLOT(updateBinaryDirectory(QString))); - + QObject::connect(this->CMakeThread->cmakeInstance(), SIGNAL(progressChanged(QString, float)), this, SLOT(showProgress(QString,float))); - + QObject::connect(this->CMakeThread->cmakeInstance(), SIGNAL(errorMessage(QString)), this, SLOT(error(QString))); @@ -217,31 +220,33 @@ void CMakeSetupDialog::initialize() SIGNAL(outputMessage(QString)), this, SLOT(message(QString))); - QObject::connect(this->ViewType, SIGNAL(currentIndexChanged(int)), - this, SLOT(setViewType(int))); - QObject::connect(this->Search, SIGNAL(textChanged(QString)), + QObject::connect(this->groupedCheck, SIGNAL(toggled(bool)), + this, SLOT(setGroupedView(bool))); + QObject::connect(this->advancedCheck, SIGNAL(toggled(bool)), + this, SLOT(setAdvancedView(bool))); + QObject::connect(this->Search, SIGNAL(textChanged(QString)), this, SLOT(setSearchFilter(QString))); - + QObject::connect(this->CMakeThread->cmakeInstance(), SIGNAL(generatorChanged(QString)), this, SLOT(updateGeneratorLabel(QString))); this->updateGeneratorLabel(QString()); - + QObject::connect(this->CacheValues->cacheModel(), - SIGNAL(dataChanged(QModelIndex,QModelIndex)), + SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(setCacheModified())); - + QObject::connect(this->CacheValues->selectionModel(), - SIGNAL(selectionChanged(QItemSelection,QItemSelection)), + SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(selectionChanged())); - QObject::connect(this->RemoveEntry, SIGNAL(clicked(bool)), + QObject::connect(this->RemoveEntry, SIGNAL(clicked(bool)), this, SLOT(removeSelectedCacheEntries())); - QObject::connect(this->AddEntry, SIGNAL(clicked(bool)), + QObject::connect(this->AddEntry, SIGNAL(clicked(bool)), this, SLOT(addCacheEntry())); - QObject::connect(this->SuppressDevWarningsAction, SIGNAL(triggered(bool)), + QObject::connect(this->SuppressDevWarningsAction, SIGNAL(triggered(bool)), this->CMakeThread->cmakeInstance(), SLOT(setSuppressDevWarnings(bool))); - + if(!this->SourceDirectory->text().isEmpty() || !this->BinaryDirectory->lineEdit()->text().isEmpty()) { @@ -266,16 +271,9 @@ CMakeSetupDialog::~CMakeSetupDialog() this->CMakeThread->quit(); this->CMakeThread->wait(2000); } - -void CMakeSetupDialog::doConfigure() -{ - if(this->CurrentState == Configuring) - { - // stop configure - doInterrupt(); - return; - } +bool CMakeSetupDialog::prepareConfigure() +{ // make sure build directory exists QString bindir = this->CMakeThread->cmakeInstance()->binaryDirectory(); QDir dir(bindir); @@ -288,19 +286,19 @@ void CMakeSetupDialog::doConfigure() msg += bindir; QString title = tr("Create Directory"); QMessageBox::StandardButton btn; - btn = QMessageBox::information(this, title, msg, + btn = QMessageBox::information(this, title, msg, QMessageBox::Yes | QMessageBox::No); if(btn == QMessageBox::No) { - return; + return false; } if(!dir.mkpath(".")) { - QMessageBox::information(this, tr("Create Directory Failed"), - QString(tr("Failed to create directory %1")).arg(dir.path()), + QMessageBox::information(this, tr("Create Directory Failed"), + QString(tr("Failed to create directory %1")).arg(dir.path()), QMessageBox::Ok); - return; + return false; } } @@ -309,27 +307,45 @@ void CMakeSetupDialog::doConfigure() { if(!this->setupFirstConfigure()) { - return; + return false; } } // remember path this->addBinaryPath(dir.absolutePath()); - - this->enterState(Configuring); - this->CacheValues->selectionModel()->clear(); - QMetaObject::invokeMethod(this->CMakeThread->cmakeInstance(), - "setProperties", Qt::QueuedConnection, - Q_ARG(QCMakePropertyList, - this->CacheValues->cacheModel()->properties())); - QMetaObject::invokeMethod(this->CMakeThread->cmakeInstance(), - "configure", Qt::QueuedConnection); + return true; } -void CMakeSetupDialog::finishConfigure(int err) +void CMakeSetupDialog::exitLoop(int err) { - if(0 == err && !this->CacheValues->cacheModel()->newPropertyCount()) + this->LocalLoop.exit(err); +} + +void CMakeSetupDialog::doConfigure() +{ + if(this->CurrentState == Configuring) + { + // stop configure + doInterrupt(); + return; + } + + if(!prepareConfigure()) + { + return; + } + + this->enterState(Configuring); + + bool ret = doConfigureInternal(); + + if(ret) + { + this->ConfigureNeeded = false; + } + + if(ret && !this->CacheValues->cacheModel()->newPropertyCount()) { this->enterState(ReadyGenerate); } @@ -338,24 +354,31 @@ void CMakeSetupDialog::finishConfigure(int err) this->enterState(ReadyConfigure); this->CacheValues->scrollToTop(); } - - if(err != 0) - { - QMessageBox::critical(this, tr("Error"), - tr("Error in configuration process, project files may be invalid"), - QMessageBox::Ok); - } + this->ProgressBar->reset(); } -void CMakeSetupDialog::finishGenerate(int err) +bool CMakeSetupDialog::doConfigureInternal() { - this->enterState(ReadyConfigure); + this->Output->clear(); + this->CacheValues->selectionModel()->clear(); + + QMetaObject::invokeMethod(this->CMakeThread->cmakeInstance(), + "setProperties", Qt::QueuedConnection, + Q_ARG(QCMakePropertyList, + this->CacheValues->cacheModel()->properties())); + QMetaObject::invokeMethod(this->CMakeThread->cmakeInstance(), + "configure", Qt::QueuedConnection); + + int err = this->LocalLoop.exec(); + if(err != 0) { - QMessageBox::critical(this, tr("Error"), - tr("Error in generation process, project files may be invalid"), + QMessageBox::critical(this, tr("Error"), + tr("Error in configuration process, project files may be invalid"), QMessageBox::Ok); } + + return 0 == err; } void CMakeSetupDialog::doInstallForCommandLine() @@ -364,6 +387,23 @@ void CMakeSetupDialog::doInstallForCommandLine() setupdialog.exec(); } +bool CMakeSetupDialog::doGenerateInternal() +{ + QMetaObject::invokeMethod(this->CMakeThread->cmakeInstance(), + "generate", Qt::QueuedConnection); + + int err = this->LocalLoop.exec(); + + if(err != 0) + { + QMessageBox::critical(this, tr("Error"), + tr("Error in generation process, project files may be invalid"), + QMessageBox::Ok); + } + + return 0 == err; +} + void CMakeSetupDialog::doGenerate() { if(this->CurrentState == Generating) @@ -372,11 +412,45 @@ void CMakeSetupDialog::doGenerate() doInterrupt(); return; } + + // see if we need to configure + // we'll need to configure if: + // the configure step hasn't been done yet + // generate was the last step done + if(this->ConfigureNeeded) + { + if(!prepareConfigure()) + { + return; + } + } + this->enterState(Generating); - QMetaObject::invokeMethod(this->CMakeThread->cmakeInstance(), - "generate", Qt::QueuedConnection); + + bool config_passed = true; + if(this->ConfigureNeeded) + { + this->CacheValues->cacheModel()->setShowNewProperties(false); + this->ProgressFactor = 0.5; + config_passed = doConfigureInternal(); + this->ProgressOffset = 0.5; + } + + if(config_passed) + { + doGenerateInternal(); + } + + this->ProgressOffset = 0.0; + this->ProgressFactor = 1.0; + this->CacheValues->cacheModel()->setShowNewProperties(true); + + this->enterState(ReadyConfigure); + this->ProgressBar->reset(); + + this->ConfigureNeeded = true; } - + void CMakeSetupDialog::closeEvent(QCloseEvent* e) { // prompt for close if there are unsaved changes, and we're not busy @@ -467,7 +541,7 @@ void CMakeSetupDialog::doInterrupt() void CMakeSetupDialog::doSourceBrowse() { - QString dir = QFileDialog::getExistingDirectory(this, + QString dir = QFileDialog::getExistingDirectory(this, tr("Enter Path to Source"), this->SourceDirectory->text()); if(!dir.isEmpty()) { @@ -497,7 +571,7 @@ void CMakeSetupDialog::updateBinaryDirectory(const QString& dir) void CMakeSetupDialog::doBinaryBrowse() { - QString dir = QFileDialog::getExistingDirectory(this, + QString dir = QFileDialog::getExistingDirectory(this, tr("Enter Path to Build"), this->BinaryDirectory->currentText()); if(!dir.isEmpty() && dir != this->BinaryDirectory->currentText()) { @@ -539,6 +613,7 @@ void CMakeSetupDialog::setSourceDirectory(const QString& dir) void CMakeSetupDialog::showProgress(const QString& /*msg*/, float percent) { + percent = (percent * ProgressFactor) + ProgressOffset; this->ProgressBar->setValue(qRound(percent * 100)); } @@ -586,7 +661,7 @@ bool CMakeSetupDialog::setupFirstConfigure() { dialog.saveToSettings(); this->CMakeThread->cmakeInstance()->setGenerator(dialog.getGenerator()); - + QCMakeCacheModel* m = this->CacheValues->cacheModel(); if(dialog.compilerSetup()) @@ -594,20 +669,20 @@ bool CMakeSetupDialog::setupFirstConfigure() QString fortranCompiler = dialog.getFortranCompiler(); if(!fortranCompiler.isEmpty()) { - m->insertProperty(QCMakeProperty::FILEPATH, "CMAKE_Fortran_COMPILER", + m->insertProperty(QCMakeProperty::FILEPATH, "CMAKE_Fortran_COMPILER", "Fortran compiler.", fortranCompiler, false); } QString cxxCompiler = dialog.getCXXCompiler(); if(!cxxCompiler.isEmpty()) { - m->insertProperty(QCMakeProperty::FILEPATH, "CMAKE_CXX_COMPILER", + m->insertProperty(QCMakeProperty::FILEPATH, "CMAKE_CXX_COMPILER", "CXX compiler.", cxxCompiler, false); } - + QString cCompiler = dialog.getCCompiler(); if(!cCompiler.isEmpty()) { - m->insertProperty(QCMakeProperty::FILEPATH, "CMAKE_C_COMPILER", + m->insertProperty(QCMakeProperty::FILEPATH, "CMAKE_C_COMPILER", "C compiler.", cCompiler, false); } } @@ -616,38 +691,38 @@ bool CMakeSetupDialog::setupFirstConfigure() QString fortranCompiler = dialog.getFortranCompiler(); if(!fortranCompiler.isEmpty()) { - m->insertProperty(QCMakeProperty::FILEPATH, "CMAKE_Fortran_COMPILER", + m->insertProperty(QCMakeProperty::FILEPATH, "CMAKE_Fortran_COMPILER", "Fortran compiler.", fortranCompiler, false); } QString mode = dialog.getCrossIncludeMode(); - m->insertProperty(QCMakeProperty::STRING, "CMAKE_FIND_ROOT_PATH_MODE_INCLUDE", + m->insertProperty(QCMakeProperty::STRING, "CMAKE_FIND_ROOT_PATH_MODE_INCLUDE", "CMake Find Include Mode", mode, false); mode = dialog.getCrossLibraryMode(); - m->insertProperty(QCMakeProperty::STRING, "CMAKE_FIND_ROOT_PATH_MODE_LIBRARY", + m->insertProperty(QCMakeProperty::STRING, "CMAKE_FIND_ROOT_PATH_MODE_LIBRARY", "CMake Find Library Mode", mode, false); mode = dialog.getCrossProgramMode(); - m->insertProperty(QCMakeProperty::STRING, "CMAKE_FIND_ROOT_PATH_MODE_PROGRAM", + m->insertProperty(QCMakeProperty::STRING, "CMAKE_FIND_ROOT_PATH_MODE_PROGRAM", "CMake Find Program Mode", mode, false); - + QString rootPath = dialog.getCrossRoot(); - m->insertProperty(QCMakeProperty::PATH, "CMAKE_FIND_ROOT_PATH", + m->insertProperty(QCMakeProperty::PATH, "CMAKE_FIND_ROOT_PATH", "CMake Find Root Path", rootPath, false); QString systemName = dialog.getSystemName(); - m->insertProperty(QCMakeProperty::STRING, "CMAKE_SYSTEM_NAME", + m->insertProperty(QCMakeProperty::STRING, "CMAKE_SYSTEM_NAME", "CMake System Name", systemName, false); QString cxxCompiler = dialog.getCXXCompiler(); - m->insertProperty(QCMakeProperty::FILEPATH, "CMAKE_CXX_COMPILER", + m->insertProperty(QCMakeProperty::FILEPATH, "CMAKE_CXX_COMPILER", "CXX compiler.", cxxCompiler, false); QString cCompiler = dialog.getCCompiler(); - m->insertProperty(QCMakeProperty::FILEPATH, "CMAKE_C_COMPILER", + m->insertProperty(QCMakeProperty::FILEPATH, "CMAKE_C_COMPILER", "C compiler.", cCompiler, false); } else if(dialog.crossCompilerToolChainFile()) { QString toolchainFile = dialog.getCrossCompilerToolChainFile(); - m->insertProperty(QCMakeProperty::FILEPATH, "CMAKE_TOOLCHAIN_FILE", + m->insertProperty(QCMakeProperty::FILEPATH, "CMAKE_TOOLCHAIN_FILE", "Cross Compile ToolChain File", toolchainFile, false); } return true; @@ -677,11 +752,11 @@ void CMakeSetupDialog::doReloadCache() } void CMakeSetupDialog::doDeleteCache() -{ +{ QString title = tr("Delete Cache"); QString msg = "Are you sure you want to delete the cache?"; QMessageBox::StandardButton btn; - btn = QMessageBox::information(this, title, msg, + btn = QMessageBox::information(this, title, msg, QMessageBox::Yes | QMessageBox::No); if(btn == QMessageBox::No) { @@ -722,7 +797,7 @@ void CMakeSetupDialog::setExitAfterGenerate(bool b) void CMakeSetupDialog::addBinaryPath(const QString& path) { QString cleanpath = QDir::cleanPath(path); - + // update UI this->BinaryDirectory->blockSignals(true); int idx = this->BinaryDirectory->findText(cleanpath); @@ -733,7 +808,7 @@ void CMakeSetupDialog::addBinaryPath(const QString& path) this->BinaryDirectory->insertItem(0, cleanpath); this->BinaryDirectory->setCurrentIndex(0); this->BinaryDirectory->blockSignals(false); - + // save to registry QStringList buildPaths = this->loadBuildPaths(); buildPaths.removeAll(cleanpath); @@ -743,7 +818,7 @@ void CMakeSetupDialog::addBinaryPath(const QString& path) void CMakeSetupDialog::dragEnterEvent(QDragEnterEvent* e) { - if(!(this->CurrentState == ReadyConfigure || + if(!(this->CurrentState == ReadyConfigure || this->CurrentState == ReadyGenerate)) { e->ignore(); @@ -753,7 +828,7 @@ void CMakeSetupDialog::dragEnterEvent(QDragEnterEvent* e) const QMimeData* dat = e->mimeData(); QList<QUrl> urls = dat->urls(); QString file = urls.count() ? urls[0].toLocalFile() : QString(); - if(!file.isEmpty() && + if(!file.isEmpty() && (file.endsWith("CMakeCache.txt", Qt::CaseInsensitive) || file.endsWith("CMakeLists.txt", Qt::CaseInsensitive) ) ) { @@ -767,7 +842,7 @@ void CMakeSetupDialog::dragEnterEvent(QDragEnterEvent* e) void CMakeSetupDialog::dropEvent(QDropEvent* e) { - if(!(this->CurrentState == ReadyConfigure || + if(!(this->CurrentState == ReadyConfigure || this->CurrentState == ReadyGenerate)) { return; @@ -802,7 +877,7 @@ QStringList CMakeSetupDialog::loadBuildPaths() QStringList buildPaths; for(int i=0; i<10; i++) - { + { QString p = settings.value(QString("WhereBuild%1").arg(i)).toString(); if(!p.isEmpty()) { @@ -824,11 +899,11 @@ void CMakeSetupDialog::saveBuildPaths(const QStringList& paths) } for(int i=0; i<num; i++) - { + { settings.setValue(QString("WhereBuild%1").arg(i), paths[i]); } } - + void CMakeSetupDialog::setCacheModified() { this->CacheModified = true; @@ -852,8 +927,8 @@ void CMakeSetupDialog::removeSelectedCacheEntries() void CMakeSetupDialog::selectionChanged() { QModelIndexList idxs = this->CacheValues->selectionModel()->selectedRows(); - if(idxs.count() && - (this->CurrentState == ReadyConfigure || + if(idxs.count() && + (this->CurrentState == ReadyConfigure || this->CurrentState == ReadyGenerate) ) { this->RemoveEntry->setEnabled(true); @@ -863,7 +938,7 @@ void CMakeSetupDialog::selectionChanged() this->RemoveEntry->setEnabled(false); } } - + void CMakeSetupDialog::enterState(CMakeSetupDialog::State s) { if(s == this->CurrentState) @@ -880,7 +955,6 @@ void CMakeSetupDialog::enterState(CMakeSetupDialog::State s) } else if(s == Configuring) { - this->Output->clear(); this->setEnabledState(false); this->GenerateButton->setEnabled(false); this->GenerateAction->setEnabled(false); @@ -896,17 +970,15 @@ void CMakeSetupDialog::enterState(CMakeSetupDialog::State s) } else if(s == ReadyConfigure) { - this->ProgressBar->reset(); this->setEnabledState(true); - this->GenerateButton->setEnabled(false); - this->GenerateAction->setEnabled(false); + this->GenerateButton->setEnabled(true); + this->GenerateAction->setEnabled(true); this->ConfigureButton->setEnabled(true); this->ConfigureButton->setText(tr("&Configure")); this->GenerateButton->setText(tr("&Generate")); } else if(s == ReadyGenerate) { - this->ProgressBar->reset(); this->setEnabledState(true); this->GenerateButton->setEnabled(true); this->GenerateAction->setEnabled(true); @@ -950,31 +1022,23 @@ void CMakeSetupDialog::setDebugOutput(bool flag) "setDebugOutput", Qt::QueuedConnection, Q_ARG(bool, flag)); } -void CMakeSetupDialog::setViewType(int v) +void CMakeSetupDialog::setGroupedView(bool v) { - if(v == 0) // simple view - { - this->CacheValues->cacheModel()->setViewType(QCMakeCacheModel::FlatView); - this->CacheValues->setRootIsDecorated(false); - this->CacheValues->setShowAdvanced(false); - } - else if(v == 1) // advanced view - { - this->CacheValues->cacheModel()->setViewType(QCMakeCacheModel::FlatView); - this->CacheValues->setRootIsDecorated(false); - this->CacheValues->setShowAdvanced(true); - } - else if(v == 2) // grouped view - { - this->CacheValues->cacheModel()->setViewType(QCMakeCacheModel::GroupView); - this->CacheValues->setRootIsDecorated(true); - this->CacheValues->setShowAdvanced(true); - } - + this->CacheValues->cacheModel()->setViewType(v ? QCMakeCacheModel::GroupView : QCMakeCacheModel::FlatView); + this->CacheValues->setRootIsDecorated(v); + QSettings settings; settings.beginGroup("Settings/StartPath"); - settings.setValue("GroupView", v == 2); - + settings.setValue("GroupView", v); + +} + +void CMakeSetupDialog::setAdvancedView(bool v) +{ + this->CacheValues->setShowAdvanced(v); + QSettings settings; + settings.beginGroup("Settings/StartPath"); + settings.setValue("AdvancedView", v); } void CMakeSetupDialog::showUserChanges() @@ -996,7 +1060,7 @@ void CMakeSetupDialog::showUserChanges() QString command; QString cache; - + foreach(QCMakeProperty prop, changes) { QString type; @@ -1032,13 +1096,13 @@ void CMakeSetupDialog::showUserChanges() command += QString("-D%1\"%2\" ").arg(line).arg(value); cache += QString("%1%2\n").arg(line).arg(value); } - + textedit->append(tr("Commandline options:")); textedit->append(command); textedit->append("\n"); textedit->append(tr("Cache file:")); textedit->append(cache); - + dialog.exec(); } diff --git a/Source/QtDialog/CMakeSetupDialog.h b/Source/QtDialog/CMakeSetupDialog.h index de7922a..1934795 100644 --- a/Source/QtDialog/CMakeSetupDialog.h +++ b/Source/QtDialog/CMakeSetupDialog.h @@ -16,6 +16,7 @@ #include "QCMake.h" #include <QMainWindow> #include <QThread> +#include <QEventLoop> #include "ui_CMakeSetupDialog.h" class QCMakeThread; @@ -43,8 +44,6 @@ protected slots: void doHelp(); void doAbout(); void doInterrupt(); - void finishConfigure(int error); - void finishGenerate(int error); void error(const QString& message); void message(const QString& message); @@ -70,9 +69,14 @@ protected slots: void addCacheEntry(); void startSearch(); void setDebugOutput(bool); - void setViewType(int); + void setAdvancedView(bool); + void setGroupedView(bool); void showUserChanges(); void setSearchFilter(const QString& str); + bool prepareConfigure(); + bool doConfigureInternal(); + bool doGenerateInternal(); + void exitLoop(int); protected: @@ -86,6 +90,7 @@ protected: QCMakeThread* CMakeThread; bool ExitAfterGenerate; bool CacheModified; + bool ConfigureNeeded; QAction* ReloadCacheAction; QAction* DeleteCacheAction; QAction* ExitAction; @@ -98,6 +103,10 @@ protected: QTextCharFormat ErrorFormat; QTextCharFormat MessageFormat; + QEventLoop LocalLoop; + + float ProgressOffset; + float ProgressFactor; }; // QCMake instance on a thread diff --git a/Source/QtDialog/CMakeSetupDialog.ui b/Source/QtDialog/CMakeSetupDialog.ui index ae0dca2..dc8ee3f 100644 --- a/Source/QtDialog/CMakeSetupDialog.ui +++ b/Source/QtDialog/CMakeSetupDialog.ui @@ -1,7 +1,8 @@ -<ui version="4.0" > +<?xml version="1.0" encoding="UTF-8"?> +<ui version="4.0"> <class>CMakeSetupDialog</class> - <widget class="QWidget" name="CMakeSetupDialog" > - <property name="geometry" > + <widget class="QWidget" name="CMakeSetupDialog"> + <property name="geometry"> <rect> <x>0</x> <y>0</y> @@ -9,115 +10,111 @@ <height>582</height> </rect> </property> - <layout class="QGridLayout" > - <property name="margin" > + <layout class="QGridLayout"> + <property name="margin"> <number>9</number> </property> - <property name="spacing" > + <property name="spacing"> <number>6</number> </property> - <item row="0" column="0" > - <layout class="QGridLayout" > - <property name="margin" > + <item row="0" column="0"> + <layout class="QGridLayout"> + <property name="margin"> <number>0</number> </property> - <property name="spacing" > + <property name="spacing"> <number>6</number> </property> - <item row="0" column="0" > - <widget class="QLabel" name="label" > - <property name="text" > + <item row="0" column="0"> + <widget class="QLabel" name="label"> + <property name="text"> <string>Where is the source code:</string> </property> </widget> </item> - <item row="0" column="1" > - <widget class="QLineEdit" name="SourceDirectory" /> + <item row="0" column="1"> + <widget class="QLineEdit" name="SourceDirectory"/> </item> - <item row="0" column="2" > - <widget class="QPushButton" name="BrowseSourceDirectoryButton" > - <property name="text" > + <item row="0" column="2"> + <widget class="QPushButton" name="BrowseSourceDirectoryButton"> + <property name="text"> <string>Browse &Source...</string> </property> </widget> </item> - <item row="1" column="0" > - <widget class="QLabel" name="label_2" > - <property name="text" > + <item row="1" column="0"> + <widget class="QLabel" name="label_2"> + <property name="text"> <string>Where to build the binaries:</string> </property> </widget> </item> - <item row="1" column="1" > - <widget class="QComboBox" name="BinaryDirectory" > - <property name="sizePolicy" > - <sizepolicy vsizetype="Fixed" hsizetype="Ignored" > + <item row="1" column="1"> + <widget class="QComboBox" name="BinaryDirectory"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Ignored" vsizetype="Fixed"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> - <property name="editable" > + <property name="editable"> <bool>true</bool> </property> </widget> </item> - <item row="1" column="2" > - <widget class="QPushButton" name="BrowseBinaryDirectoryButton" > - <property name="text" > + <item row="1" column="2"> + <widget class="QPushButton" name="BrowseBinaryDirectoryButton"> + <property name="text"> <string>Browse &Build...</string> </property> </widget> </item> </layout> </item> - <item row="1" column="0" > - <widget class="QSplitter" name="Splitter" > - <property name="orientation" > + <item row="1" column="0"> + <widget class="QSplitter" name="Splitter"> + <property name="orientation"> <enum>Qt::Vertical</enum> </property> - <widget class="QFrame" name="frame" > - <property name="frameShape" > + <widget class="QFrame" name="frame"> + <property name="frameShape"> <enum>QFrame::NoFrame</enum> </property> - <property name="frameShadow" > + <property name="frameShadow"> <enum>QFrame::Raised</enum> </property> - <layout class="QVBoxLayout" > - <property name="margin" > - <number>0</number> - </property> - <property name="spacing" > + <layout class="QVBoxLayout"> + <property name="spacing"> <number>6</number> </property> + <property name="margin"> + <number>0</number> + </property> <item> - <layout class="QHBoxLayout" > - <property name="margin" > - <number>0</number> - </property> - <property name="spacing" > + <layout class="QHBoxLayout"> + <property name="spacing"> <number>6</number> </property> + <property name="margin"> + <number>0</number> + </property> <item> - <widget class="QLabel" name="label_4" > - <property name="sizePolicy" > - <sizepolicy> - <hsizetype>0</hsizetype> - <vsizetype>0</vsizetype> + <widget class="QLabel" name="label_4"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Fixed" vsizetype="Fixed"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> - <property name="text" > + <property name="text"> <string>Search:</string> </property> </widget> </item> <item> - <widget class="QLineEdit" name="Search" > - <property name="sizePolicy" > - <sizepolicy> - <hsizetype>7</hsizetype> - <vsizetype>0</vsizetype> + <widget class="QLineEdit" name="Search"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Expanding" vsizetype="Fixed"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> @@ -125,33 +122,14 @@ </widget> </item> <item> - <widget class="QComboBox" name="ViewType" > - <item> - <property name="text" > - <string>Simple View</string> - </property> - </item> - <item> - <property name="text" > - <string>Advanced View</string> - </property> - </item> - <item> - <property name="text" > - <string>Grouped View</string> - </property> - </item> - </widget> - </item> - <item> <spacer> - <property name="orientation" > + <property name="orientation"> <enum>Qt::Horizontal</enum> </property> - <property name="sizeType" > + <property name="sizeType"> <enum>QSizePolicy::Minimum</enum> </property> - <property name="sizeHint" > + <property name="sizeHint" stdset="0"> <size> <width>40</width> <height>23</height> @@ -160,33 +138,49 @@ </spacer> </item> <item> - <widget class="QToolButton" name="AddEntry" > - <property name="toolTip" > + <widget class="QCheckBox" name="groupedCheck"> + <property name="text"> + <string>Grouped</string> + </property> + </widget> + </item> + <item> + <widget class="QCheckBox" name="advancedCheck"> + <property name="text"> + <string>Advanced</string> + </property> + </widget> + </item> + <item> + <widget class="QToolButton" name="AddEntry"> + <property name="toolTip"> <string>Add New Entry</string> </property> - <property name="text" > + <property name="text"> <string>&Add Entry</string> </property> - <property name="icon" > - <iconset resource="CMakeSetup.qrc" >:/Icons/Plus16.png</iconset> + <property name="icon"> + <iconset resource="CMakeSetup.qrc"> + <normaloff>:/Icons/Plus16.png</normaloff>:/Icons/Plus16.png</iconset> </property> - <property name="toolButtonStyle" > + <property name="toolButtonStyle"> <enum>Qt::ToolButtonTextBesideIcon</enum> </property> </widget> </item> <item> - <widget class="QToolButton" name="RemoveEntry" > - <property name="toolTip" > + <widget class="QToolButton" name="RemoveEntry"> + <property name="toolTip"> <string>Remove Selected Entries</string> </property> - <property name="text" > + <property name="text"> <string>&Remove Entry</string> </property> - <property name="icon" > - <iconset resource="CMakeSetup.qrc" >:/Icons/Delete16.png</iconset> + <property name="icon"> + <iconset resource="CMakeSetup.qrc"> + <normaloff>:/Icons/Delete16.png</normaloff>:/Icons/Delete16.png</iconset> </property> - <property name="toolButtonStyle" > + <property name="toolButtonStyle"> <enum>Qt::ToolButtonTextBesideIcon</enum> </property> </widget> @@ -194,69 +188,69 @@ </layout> </item> <item> - <widget class="QCMakeCacheView" name="CacheValues" > - <property name="alternatingRowColors" > + <widget class="QCMakeCacheView" name="CacheValues"> + <property name="alternatingRowColors"> <bool>true</bool> </property> - <property name="selectionMode" > + <property name="selectionMode"> <enum>QAbstractItemView::ExtendedSelection</enum> </property> - <property name="selectionBehavior" > + <property name="selectionBehavior"> <enum>QAbstractItemView::SelectRows</enum> </property> </widget> </item> <item> - <widget class="QLabel" name="label_3" > - <property name="text" > + <widget class="QLabel" name="label_3"> + <property name="text"> <string>Press Configure to update and display new values in red, then press Generate to generate selected build files.</string> </property> - <property name="alignment" > + <property name="alignment"> <set>Qt::AlignCenter</set> </property> - <property name="wordWrap" > + <property name="wordWrap"> <bool>true</bool> </property> </widget> </item> <item> - <layout class="QHBoxLayout" > - <property name="margin" > - <number>0</number> - </property> - <property name="spacing" > + <layout class="QHBoxLayout"> + <property name="spacing"> <number>6</number> </property> + <property name="margin"> + <number>0</number> + </property> <item> - <widget class="QPushButton" name="ConfigureButton" > - <property name="text" > + <widget class="QPushButton" name="ConfigureButton"> + <property name="text"> <string>&Configure</string> </property> </widget> </item> <item> - <widget class="QPushButton" name="GenerateButton" > - <property name="text" > + <widget class="QPushButton" name="GenerateButton"> + <property name="text"> <string>&Generate</string> </property> </widget> </item> <item> - <widget class="QLabel" name="Generator" > - <property name="text" > + <widget class="QLabel" name="Generator"> + <property name="text"> <string>Current Generator:</string> </property> </widget> </item> <item> <spacer> - <property name="orientation" > + <property name="orientation"> <enum>Qt::Horizontal</enum> </property> - <property name="sizeType" > + <property name="sizeType"> <enum>QSizePolicy::Expanding</enum> </property> - <property name="sizeHint" > + <property name="sizeHint" stdset="0"> <size> <width>121</width> <height>27</height> @@ -265,23 +259,23 @@ </spacer> </item> <item> - <widget class="QProgressBar" name="ProgressBar" > - <property name="minimum" > + <widget class="QProgressBar" name="ProgressBar"> + <property name="minimum"> <number>0</number> </property> - <property name="maximum" > + <property name="maximum"> <number>100</number> </property> - <property name="value" > + <property name="value"> <number>0</number> </property> - <property name="textVisible" > + <property name="textVisible"> <bool>false</bool> </property> - <property name="orientation" > + <property name="orientation"> <enum>Qt::Horizontal</enum> </property> - <property name="textDirection" > + <property name="textDirection"> <enum>QProgressBar::BottomToTop</enum> </property> </widget> @@ -290,11 +284,11 @@ </item> </layout> </widget> - <widget class="QTextEdit" name="Output" > - <property name="lineWrapMode" > + <widget class="QTextEdit" name="Output"> + <property name="lineWrapMode"> <enum>QTextEdit::NoWrap</enum> </property> - <property name="readOnly" > + <property name="readOnly"> <bool>true</bool> </property> </widget> @@ -310,7 +304,7 @@ </customwidget> </customwidgets> <resources> - <include location="CMakeSetup.qrc" /> + <include location="CMakeSetup.qrc"/> </resources> <connections/> </ui> diff --git a/Source/QtDialog/QCMakeCacheView.cxx b/Source/QtDialog/QCMakeCacheView.cxx index d90307a..562396d 100644 --- a/Source/QtDialog/QCMakeCacheView.cxx +++ b/Source/QtDialog/QCMakeCacheView.cxx @@ -200,6 +200,7 @@ QCMakeCacheModel::QCMakeCacheModel(QObject* p) NewPropertyCount(0), View(FlatView) { + this->ShowNewProperties = true; QStringList labels; labels << tr("Name") << tr("Value"); this->setHorizontalHeaderLabels(labels); @@ -214,6 +215,11 @@ static uint qHash(const QCMakeProperty& p) return qHash(p.Key); } +void QCMakeCacheModel::setShowNewProperties(bool f) +{ + this->ShowNewProperties = f; +} + void QCMakeCacheModel::clear() { this->QStandardItemModel::clear(); @@ -226,13 +232,21 @@ void QCMakeCacheModel::clear() void QCMakeCacheModel::setProperties(const QCMakePropertyList& props) { - QSet<QCMakeProperty> newProps = props.toSet(); - QSet<QCMakeProperty> newProps2 = newProps; - QSet<QCMakeProperty> oldProps = this->properties().toSet(); - - oldProps.intersect(newProps); - newProps.subtract(oldProps); - newProps2.subtract(newProps); + QSet<QCMakeProperty> newProps, newProps2; + + if(this->ShowNewProperties) + { + newProps = props.toSet(); + newProps2 = newProps; + QSet<QCMakeProperty> oldProps = this->properties().toSet(); + oldProps.intersect(newProps); + newProps.subtract(oldProps); + newProps2.subtract(newProps); + } + else + { + newProps2 = props.toSet(); + } bool b = this->blockSignals(true); diff --git a/Source/QtDialog/QCMakeCacheView.h b/Source/QtDialog/QCMakeCacheView.h index 401e07e..58bbd2d 100644 --- a/Source/QtDialog/QCMakeCacheView.h +++ b/Source/QtDialog/QCMakeCacheView.h @@ -78,6 +78,9 @@ public slots: // become new properties and be marked red. void setProperties(const QCMakePropertyList& props); + // set whether to show new properties in red + void setShowNewProperties(bool); + // clear everything from the model void clear(); @@ -115,6 +118,7 @@ public: protected: bool EditEnabled; int NewPropertyCount; + bool ShowNewProperties; ViewType View; // set the data in the model for this property diff --git a/Source/cmAddCustomCommandCommand.cxx b/Source/cmAddCustomCommandCommand.cxx index f6b3234..7af6ec8 100644 --- a/Source/cmAddCustomCommandCommand.cxx +++ b/Source/cmAddCustomCommandCommand.cxx @@ -161,6 +161,7 @@ bool cmAddCustomCommandCommand filename += "/"; } filename += copy; + cmSystemTools::ConvertToUnixSlashes(filename); break; case doing_source: // We do not want to convert the argument to SOURCE because diff --git a/Source/cmAddCustomCommandCommand.h b/Source/cmAddCustomCommandCommand.h index c67caa5..490e043 100644 --- a/Source/cmAddCustomCommandCommand.h +++ b/Source/cmAddCustomCommandCommand.h @@ -13,6 +13,7 @@ #define cmAddCustomCommandCommand_h #include "cmCommand.h" +#include "cmDocumentGeneratorExpressions.h" /** \class cmAddCustomCommandCommand * \brief @@ -146,12 +147,22 @@ public: "target-level dependency will be added so that the executable target " "will be built before any target using this custom command. However " "this does NOT add a file-level dependency that would cause the " - "custom command to re-run whenever the executable is recompiled.\n" - + "custom command to re-run whenever the executable is recompiled." + "\n" + "Arguments to COMMAND may use \"generator expressions\" with the " + "syntax \"$<...>\". " + CM_DOCUMENT_COMMAND_GENERATOR_EXPRESSIONS + "References to target names in generator expressions imply " + "target-level dependencies, but NOT file-level dependencies. " + "List target names with the DEPENDS option to add file dependencies." + "\n" "The DEPENDS option specifies files on which the command depends. " "If any dependency is an OUTPUT of another custom command in the " "same directory (CMakeLists.txt file) CMake automatically brings the " "other custom command into the target in which this command is built. " + "If DEPENDS is not specified the command will run whenever the OUTPUT " + "is missing; if the command does not actually create the OUTPUT then " + "the rule will always run. " "If DEPENDS specifies any target (created by an ADD_* command) " "a target-level dependency is created to make sure the target is " "built before any target using this custom command. Additionally, " diff --git a/Source/cmAddDependenciesCommand.cxx b/Source/cmAddDependenciesCommand.cxx index 1205f07..a77140d 100644 --- a/Source/cmAddDependenciesCommand.cxx +++ b/Source/cmAddDependenciesCommand.cxx @@ -24,11 +24,7 @@ bool cmAddDependenciesCommand } std::string target_name = args[0]; - - cmTarget* target = - this->GetMakefile()->GetLocalGenerator()-> - GetGlobalGenerator()->FindTarget(0, target_name.c_str()); - if(target) + if(cmTarget* target = this->Makefile->FindTargetToUse(target_name.c_str())) { std::vector<std::string>::const_iterator s = args.begin(); ++s; // skip over target_name diff --git a/Source/cmAddDependenciesCommand.h b/Source/cmAddDependenciesCommand.h index 6a981c3..fee011c 100644 --- a/Source/cmAddDependenciesCommand.h +++ b/Source/cmAddDependenciesCommand.h @@ -62,6 +62,8 @@ public: "top-level target is one created by ADD_EXECUTABLE, ADD_LIBRARY, " "or ADD_CUSTOM_TARGET. Adding dependencies with this command " "can be used to make sure one target is built before another target. " + "Dependencies added to an IMPORTED target are followed transitively " + "in its place since the target itself does not build. " "See the DEPENDS option of ADD_CUSTOM_TARGET " "and ADD_CUSTOM_COMMAND for adding file-level dependencies in custom " "rules. See the OBJECT_DEPENDS option in " diff --git a/Source/cmAddTestCommand.cxx b/Source/cmAddTestCommand.cxx index 923206d..11ca9e7 100644 --- a/Source/cmAddTestCommand.cxx +++ b/Source/cmAddTestCommand.cxx @@ -74,6 +74,7 @@ bool cmAddTestCommand::HandleNameMode(std::vector<std::string> const& args) { std::string name; std::vector<std::string> configurations; + std::string working_directory; std::vector<std::string> command; // Read the arguments. @@ -81,6 +82,7 @@ bool cmAddTestCommand::HandleNameMode(std::vector<std::string> const& args) DoingName, DoingCommand, DoingConfigs, + DoingWorkingDirectory, DoingNone }; Doing doing = DoingName; @@ -104,6 +106,15 @@ bool cmAddTestCommand::HandleNameMode(std::vector<std::string> const& args) } doing = DoingConfigs; } + else if(args[i] == "WORKING_DIRECTORY") + { + if(!working_directory.empty()) + { + this->SetError(" may be given at most one WORKING_DIRECTORY."); + return false; + } + doing = DoingWorkingDirectory; + } else if(doing == DoingName) { name = args[i]; @@ -117,6 +128,11 @@ bool cmAddTestCommand::HandleNameMode(std::vector<std::string> const& args) { configurations.push_back(args[i]); } + else if(doing == DoingWorkingDirectory) + { + working_directory = args[i]; + doing = DoingNone; + } else { cmOStringStream e; @@ -154,6 +170,7 @@ bool cmAddTestCommand::HandleNameMode(std::vector<std::string> const& args) cmTest* test = this->Makefile->CreateTest(name.c_str()); test->SetOldStyle(false); test->SetCommand(command); + test->SetProperty("WORKING_DIRECTORY", working_directory.c_str()); this->Makefile->AddTestGenerator(new cmTestGenerator(test, configurations)); return true; diff --git a/Source/cmAddTestCommand.h b/Source/cmAddTestCommand.h index 79fb481..edaf12c 100644 --- a/Source/cmAddTestCommand.h +++ b/Source/cmAddTestCommand.h @@ -13,6 +13,7 @@ #define cmAddTestCommand_h #include "cmCommand.h" +#include "cmDocumentGeneratorExpressions.h" /** \class cmAddTestCommand * \brief Add a test to the lists of tests to run. @@ -68,28 +69,19 @@ public: "in the binary tree.\n" "\n" " add_test(NAME <name> [CONFIGURATIONS [Debug|Release|...]]\n" + " [WORKING_DIRECTORY dir]\n" " COMMAND <command> [arg1 [arg2 ...]])\n" "If COMMAND specifies an executable target (created by " "add_executable) it will automatically be replaced by the location " "of the executable created at build time. " "If a CONFIGURATIONS option is given then the test will be executed " - "only when testing under one of the named configurations." + "only when testing under one of the named configurations. " + "If a WORKING_DIRECTORY option is given then the test will be executed " + "in the given directory." "\n" "Arguments after COMMAND may use \"generator expressions\" with the " "syntax \"$<...>\". " - "These expressions are evaluted during build system generation and " - "produce information specific to each generated build configuration. " - "Valid expressions are:\n" - " $<CONFIGURATION> = configuration name\n" - " $<TARGET_FILE:tgt> = main file (.exe, .so.1.2, .a)\n" - " $<TARGET_LINKER_FILE:tgt> = file used to link (.a, .lib, .so)\n" - " $<TARGET_SONAME_FILE:tgt> = file with soname (.so.3)\n" - "where \"tgt\" is the name of a target. " - "Target file expressions produce a full path, but _DIR and _NAME " - "versions can produce the directory and file name components:\n" - " $<TARGET_FILE_DIR:tgt>/$<TARGET_FILE_NAME:tgt>\n" - " $<TARGET_LINKER_FILE_DIR:tgt>/$<TARGET_LINKER_FILE_NAME:tgt>\n" - " $<TARGET_SONAME_FILE_DIR:tgt>/$<TARGET_SONAME_FILE_NAME:tgt>\n" + CM_DOCUMENT_COMMAND_GENERATOR_EXPRESSIONS "Example usage:\n" " add_test(NAME mytest\n" " COMMAND testDriver --config $<CONFIGURATION>\n" diff --git a/Source/cmArchiveWrite.cxx b/Source/cmArchiveWrite.cxx new file mode 100644 index 0000000..d9e4742 --- /dev/null +++ b/Source/cmArchiveWrite.cxx @@ -0,0 +1,299 @@ +/*============================================================================ + CMake - Cross Platform Makefile Generator + Copyright 2000-2010 Kitware, Inc., Insight Software Consortium + + Distributed under the OSI-approved BSD License (the "License"); + see accompanying file Copyright.txt for details. + + This software is distributed WITHOUT ANY WARRANTY; without even the + implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the License for more information. +============================================================================*/ +#include "cmArchiveWrite.h" + +#include "cmSystemTools.h" +#include <cmsys/ios/iostream> +#include <cmsys/Directory.hxx> +#include <cm_libarchive.h> + +//---------------------------------------------------------------------------- +class cmArchiveWrite::Entry +{ + struct archive_entry* Object; +public: + Entry(): Object(archive_entry_new()) {} + ~Entry() { archive_entry_free(this->Object); } + operator struct archive_entry*() { return this->Object; } +}; + +//---------------------------------------------------------------------------- +struct cmArchiveWrite::Callback +{ + // archive_write_callback + static __LA_SSIZE_T Write(struct archive*, void *cd, + const void *b, size_t n) + { + cmArchiveWrite* self = static_cast<cmArchiveWrite*>(cd); + if(self->Stream.write(static_cast<const char*>(b), + static_cast<cmsys_ios::streamsize>(n))) + { + return static_cast<__LA_SSIZE_T>(n); + } + else + { + return static_cast<__LA_SSIZE_T>(-1); + } + } +}; + +//---------------------------------------------------------------------------- +cmArchiveWrite::cmArchiveWrite(std::ostream& os, Compress c, Type t): + Stream(os), + Archive(archive_write_new()), + Disk(archive_read_disk_new()), + Verbose(false) +{ + switch (c) + { + case CompressNone: + if(archive_write_set_compression_none(this->Archive) != ARCHIVE_OK) + { + this->Error = "archive_write_set_compression_none: "; + this->Error += archive_error_string(this->Archive); + return; + } + break; + case CompressCompress: + if(archive_write_set_compression_compress(this->Archive) != ARCHIVE_OK) + { + this->Error = "archive_write_set_compression_compress: "; + this->Error += archive_error_string(this->Archive); + return; + } + break; + case CompressGZip: + if(archive_write_set_compression_gzip(this->Archive) != ARCHIVE_OK) + { + this->Error = "archive_write_set_compression_gzip: "; + this->Error += archive_error_string(this->Archive); + return; + } + break; + case CompressBZip2: + if(archive_write_set_compression_bzip2(this->Archive) != ARCHIVE_OK) + { + this->Error = "archive_write_set_compression_bzip2: "; + this->Error += archive_error_string(this->Archive); + return; + } + break; + case CompressLZMA: + if(archive_write_set_compression_lzma(this->Archive) != ARCHIVE_OK) + { + this->Error = "archive_write_set_compression_lzma: "; + this->Error += archive_error_string(this->Archive); + return; + } + break; + case CompressXZ: + if(archive_write_set_compression_xz(this->Archive) != ARCHIVE_OK) + { + this->Error = "archive_write_set_compression_xz: "; + this->Error += 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 += archive_error_string(this->Archive); + return;; + } +#endif + switch (t) + { + case TypeZIP: + if(archive_write_set_format_zip(this->Archive) != ARCHIVE_OK) + { + this->Error = "archive_write_set_format_zip: "; + this->Error += archive_error_string(this->Archive); + return; + } + break; + case TypeTAR: + if(archive_write_set_format_pax_restricted(this->Archive) != ARCHIVE_OK) + { + this->Error = "archive_write_set_format_pax_restricted: "; + this->Error += archive_error_string(this->Archive); + return; + } + break; + } + + // 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 += archive_error_string(this->Archive); + return; + } + + if(archive_write_open( + this->Archive, this, 0, + reinterpret_cast<archive_write_callback*>(&Callback::Write), + 0) != ARCHIVE_OK) + { + this->Error = "archive_write_open: "; + this->Error += archive_error_string(this->Archive); + return; + } +} + +//---------------------------------------------------------------------------- +cmArchiveWrite::~cmArchiveWrite() +{ + archive_read_finish(this->Disk); + archive_write_finish(this->Archive); +} + +//---------------------------------------------------------------------------- +bool cmArchiveWrite::Add(std::string path, size_t skip, const char* prefix) +{ + if(this->Okay()) + { + if(!path.empty() && path[path.size()-1] == '/') + { + path.erase(path.size()-1); + } + this->AddPath(path.c_str(), skip, prefix); + } + return this->Okay(); +} + +//---------------------------------------------------------------------------- +bool cmArchiveWrite::AddPath(const char* path, + size_t skip, const char* prefix) +{ + if(!this->AddFile(path, skip, prefix)) + { + return false; + } + if(!cmSystemTools::FileIsDirectory(path)) + { + return true; + } + cmsys::Directory d; + if(d.Load(path)) + { + std::string next = path; + next += "/"; + std::string::size_type end = next.size(); + unsigned long n = d.GetNumberOfFiles(); + for(unsigned long i = 0; i < n; ++i) + { + const char* file = d.GetFile(i); + if(strcmp(file, ".") != 0 && strcmp(file, "..") != 0) + { + next.erase(end); + next += file; + if(!this->AddPath(next.c_str(), skip, prefix)) + { + return false; + } + } + } + } + return true; +} + +//---------------------------------------------------------------------------- +bool cmArchiveWrite::AddFile(const char* file, + size_t skip, const char* prefix) +{ + // Skip the file if we have no name for it. This may happen on a + // top-level directory, which does not need to be included anyway. + if(skip >= strlen(file)) + { + return true; + } + const char* out = file + skip; + + // Meta-data. + std::string dest = prefix? prefix : ""; + dest += out; + if(this->Verbose) + { + std::cout << dest << "\n"; + } + Entry e; + archive_entry_copy_sourcepath(e, file); + archive_entry_set_pathname(e, dest.c_str()); + if(archive_read_disk_entry_from_file(this->Disk, e, -1, 0) != ARCHIVE_OK) + { + this->Error = "archive_read_disk_entry_from_file: "; + this->Error += archive_error_string(this->Disk); + return false; + } + if(archive_write_header(this->Archive, e) != ARCHIVE_OK) + { + this->Error = "archive_write_header: "; + this->Error += archive_error_string(this->Archive); + return false; + } + + // Content. + if(size_t size = static_cast<size_t>(archive_entry_size(e))) + { + return this->AddData(file, size); + } + return true; +} + +//---------------------------------------------------------------------------- +bool cmArchiveWrite::AddData(const char* file, size_t size) +{ + std::ifstream fin(file, std::ios::in | cmsys_ios_binary); + if(!fin) + { + this->Error = "Error opening \""; + this->Error += file; + this->Error += "\": "; + this->Error += cmSystemTools::GetLastSystemError(); + return false; + } + + char buffer[16384]; + size_t nleft = size; + while(nleft > 0) + { + typedef cmsys_ios::streamsize ssize_type; + size_t const nnext = nleft > sizeof(buffer)? sizeof(buffer) : nleft; + ssize_type const nnext_s = static_cast<ssize_type>(nnext); + fin.read(buffer, nnext_s); + // Some stream libraries (older HPUX) return failure at end of + // file on the last read even if some data were read. Check + // gcount instead of trusting the stream error status. + if(static_cast<size_t>(fin.gcount()) != nnext) + { + break; + } + if(archive_write_data(this->Archive, buffer, nnext) != nnext_s) + { + this->Error = "archive_write_data: "; + this->Error += 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(); + return false; + } + return true; +} diff --git a/Source/cmArchiveWrite.h b/Source/cmArchiveWrite.h new file mode 100644 index 0000000..3e3b2f0 --- /dev/null +++ b/Source/cmArchiveWrite.h @@ -0,0 +1,94 @@ +/*============================================================================ + CMake - Cross Platform Makefile Generator + Copyright 2000-2010 Kitware, Inc., Insight Software Consortium + + Distributed under the OSI-approved BSD License (the "License"); + see accompanying file Copyright.txt for details. + + This software is distributed WITHOUT ANY WARRANTY; without even the + implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the License for more information. +============================================================================*/ +#ifndef cmArchiveWrite_h +#define cmArchiveWrite_h + +#include "cmStandardIncludes.h" + +#if !defined(CMAKE_BUILD_WITH_CMAKE) +# error "cmArchiveWrite not allowed during bootstrap build!" +#endif + +/** \class cmArchiveWrite + * \brief Wrapper around libarchive for writing. + * + */ +class cmArchiveWrite +{ + typedef void (cmArchiveWrite::* safe_bool)(); + void safe_bool_true() {} +public: + /** Compression type. */ + enum Compress + { + CompressNone, + CompressCompress, + CompressGZip, + CompressBZip2, + CompressLZMA, + CompressXZ + }; + + /** Archive Type */ + enum Type + { + TypeTAR, + TypeZIP + }; + + /** Construct with output stream to which to write archive. */ + cmArchiveWrite(std::ostream& os, Compress c = CompressNone, Type = TypeTAR); + ~cmArchiveWrite(); + + /** + * Add a path (file or directory) to the archive. Directories are + * added recursively. The "path" must be readable on disk, either + * full path or relative to current working directory. The "skip" + * value indicates how many leading bytes from the input path to + * skip. The remaining part of the input path is appended to the + * "prefix" value to construct the final name in the archive. + */ + bool Add(std::string path, size_t skip = 0, const char* prefix = 0); + + /** Returns true if there has been no error. */ + operator safe_bool() const + { return this->Okay()? &cmArchiveWrite::safe_bool_true : 0; } + + /** Returns true if there has been an error. */ + bool operator!() const { return !this->Okay(); } + + /** Return the error string; empty if none. */ + std::string GetError() const { return this->Error; } + + // TODO: More general callback instead of hard-coding calls to + // std::cout. + void SetVerbose(bool v) { this->Verbose = v; } + +private: + bool Okay() const { return this->Error.empty(); } + bool AddPath(const char* path, size_t skip, const char* prefix); + bool AddFile(const char* file, size_t skip, const char* prefix); + bool AddData(const char* file, size_t size); + + struct Callback; + friend struct Callback; + + class Entry; + + std::ostream& Stream; + struct archive* Archive; + struct archive* Disk; + bool Verbose; + std::string Error; +}; + +#endif diff --git a/Source/cmBootstrapCommands.cxx b/Source/cmBootstrapCommands.cxx index db01688..554f452 100644 --- a/Source/cmBootstrapCommands.cxx +++ b/Source/cmBootstrapCommands.cxx @@ -32,6 +32,7 @@ #include "cmCreateTestSourceList.cxx" #include "cmDefinePropertyCommand.cxx" #include "cmElseCommand.cxx" +#include "cmEnableLanguageCommand.cxx" #include "cmEnableTestingCommand.cxx" #include "cmEndForEachCommand.cxx" #include "cmEndFunctionCommand.cxx" @@ -109,6 +110,7 @@ void GetBootstrapCommands(std::list<cmCommand*>& commands) commands.push_back(new cmCreateTestSourceList); commands.push_back(new cmDefinePropertyCommand); commands.push_back(new cmElseCommand); + commands.push_back(new cmEnableLanguageCommand); commands.push_back(new cmEnableTestingCommand); commands.push_back(new cmEndForEachCommand); commands.push_back(new cmEndFunctionCommand); diff --git a/Source/cmCMakeMinimumRequired.cxx b/Source/cmCMakeMinimumRequired.cxx index b7e939e..126934c 100644 --- a/Source/cmCMakeMinimumRequired.cxx +++ b/Source/cmCMakeMinimumRequired.cxx @@ -66,14 +66,17 @@ bool cmCMakeMinimumRequired int current_major = cmVersion::GetMajorVersion(); int current_minor = cmVersion::GetMinorVersion(); int current_patch = cmVersion::GetPatchVersion(); + int current_tweak = cmVersion::GetTweakVersion(); - // Parse the required version number. If no patch-level is given - // use zero. + // Parse at least two components of the version number. + // Use zero for those not specified. int required_major = 0; int required_minor = 0; int required_patch = 0; - if(sscanf(version_string.c_str(), "%d.%d.%d", - &required_major, &required_minor, &required_patch) < 2) + int required_tweak = 0; + if(sscanf(version_string.c_str(), "%u.%u.%u.%u", + &required_major, &required_minor, + &required_patch, &required_tweak) < 2) { cmOStringStream e; e << "could not parse VERSION \"" << version_string.c_str() << "\"."; @@ -87,13 +90,17 @@ bool cmCMakeMinimumRequired current_minor < required_minor) || (current_major == required_major && current_minor == required_minor && - current_patch < required_patch)) + current_patch < required_patch) || + (current_major == required_major && + current_minor == required_minor && + current_patch == required_patch && + current_tweak < required_tweak)) { // The current version is too low. cmOStringStream e; e << "CMake " << version_string.c_str() << " or higher is required. You are running version " - << current_major << "." << current_minor << "." << current_patch; + << cmVersion::GetCMakeVersion(); this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str()); cmSystemTools::SetFatalErrorOccured(); return true; diff --git a/Source/cmCMakeMinimumRequired.h b/Source/cmCMakeMinimumRequired.h index 05c2505..9bf7ef8 100644 --- a/Source/cmCMakeMinimumRequired.h +++ b/Source/cmCMakeMinimumRequired.h @@ -61,13 +61,13 @@ public: virtual const char* GetFullDocumentation() { return - " cmake_minimum_required(VERSION major[.minor[.patch]]\n" + " cmake_minimum_required(VERSION major[.minor[.patch[.tweak]]]\n" " [FATAL_ERROR])\n" "If the current version of CMake is lower than that required " "it will stop processing the project and report an error. " "When a version higher than 2.4 is specified the command implicitly " "invokes\n" - " cmake_policy(VERSION major[.minor[.patch]])\n" + " cmake_policy(VERSION major[.minor[.patch[.tweak]]])\n" "which sets the cmake policy version level to the version specified. " "When version 2.4 or lower is given the command implicitly invokes\n" " cmake_policy(VERSION 2.4)\n" diff --git a/Source/cmCMakePolicyCommand.h b/Source/cmCMakePolicyCommand.h index ffd0f44..afd3001 100644 --- a/Source/cmCMakePolicyCommand.h +++ b/Source/cmCMakePolicyCommand.h @@ -80,12 +80,13 @@ public: "behavior. " "While setting policies individually is supported, we encourage " "projects to set policies based on CMake versions.\n" - " cmake_policy(VERSION major.minor[.patch])\n" + " cmake_policy(VERSION major.minor[.patch[.tweak]])\n" "Specify that the current CMake list file is written for the " "given version of CMake. " "All policies introduced in the specified version or earlier " "will be set to use NEW behavior. " - "All policies introduced after the specified version will be unset. " + "All policies introduced after the specified version will be unset " + "(unless variable CMAKE_POLICY_DEFAULT_CMP<NNNN> sets a default). " "This effectively requests behavior preferred as of a given CMake " "version and tells newer CMake versions to warn about their new " "policies. " diff --git a/Source/cmCTest.cxx b/Source/cmCTest.cxx index 25a80ff..2e05883 100644 --- a/Source/cmCTest.cxx +++ b/Source/cmCTest.cxx @@ -155,6 +155,89 @@ std::string cmCTest::CurrentTime() } //---------------------------------------------------------------------- +std::string cmCTest::GetCostDataFile() +{ + std::string fname = this->GetCTestConfiguration("CostDataFile"); + if(fname == "") + { + fname= this->GetBinaryDir() + "/Testing/Temporary/CTestCostData.txt"; + } + return fname; +} + +#ifdef CMAKE_BUILD_WITH_CMAKE +//---------------------------------------------------------------------------- +static size_t +HTTPResponseCallback(void *ptr, size_t size, size_t nmemb, void *data) +{ + register int realsize = (int)(size * nmemb); + + std::string *response + = static_cast<std::string*>(data); + const char* chPtr = static_cast<char*>(ptr); + *response += chPtr; + + return realsize; +} + +//---------------------------------------------------------------------------- +int cmCTest::HTTPRequest(std::string url, HTTPMethod method, + std::string& response, + std::string fields, + std::string putFile, int timeout) +{ + CURL* curl; + FILE* file; + ::curl_global_init(CURL_GLOBAL_ALL); + curl = ::curl_easy_init(); + + //set request options based on method + switch(method) + { + case cmCTest::HTTP_POST: + ::curl_easy_setopt(curl, CURLOPT_POST, 1); + ::curl_easy_setopt(curl, CURLOPT_POSTFIELDS, fields.c_str()); + break; + case cmCTest::HTTP_PUT: + if(!cmSystemTools::FileExists(putFile.c_str())) + { + response = "Error: File "; + response += putFile + " does not exist.\n"; + return -1; + } + ::curl_easy_setopt(curl, CURLOPT_PUT, 1); + file = ::fopen(putFile.c_str(), "rb"); + ::curl_easy_setopt(curl, CURLOPT_INFILE, file); + //fall through to append GET fields + case cmCTest::HTTP_GET: + if(fields.size()) + { + url += "?" + fields; + } + break; + default: + break; + } + + ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); + ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout); + ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); + + //set response options + ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, HTTPResponseCallback); + ::curl_easy_setopt(curl, CURLOPT_FILE, (void *)&response); + ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1); + + CURLcode res = ::curl_easy_perform(curl); + + ::curl_easy_cleanup(curl); + ::curl_global_cleanup(); + + return static_cast<int>(res); +} +#endif + +//---------------------------------------------------------------------- std::string cmCTest::MakeURLSafe(const std::string& str) { cmOStringStream ost; @@ -221,15 +304,20 @@ cmCTest::cmCTest() this->ShowOnly = false; this->RunConfigurationScript = false; this->UseHTTP10 = false; + this->PrintLabels = false; this->CompressTestOutput = true; + this->ComputedCompressOutput = false; this->TestModel = cmCTest::EXPERIMENTAL; this->MaxTestNameWidth = 30; this->InteractiveDebugMode = true; this->TimeOut = 0; this->GlobalTimeout = 0; + this->LastStopTimeout = 24 * 60 * 60; this->CompressXMLFiles = false; this->CTestConfigFile = ""; this->ScheduleType = ""; + this->StopTime = ""; + this->NextDayStopTime = false; this->OutputLogFile = 0; this->OutputLogFileLastTag = -1; this->SuppressUpdatingCTestConfiguration = false; @@ -300,6 +388,44 @@ void cmCTest::SetParallelLevel(int level) } //---------------------------------------------------------------------------- +bool cmCTest::ShouldCompressTestOutput() +{ + if(!this->ComputedCompressOutput) + { + std::string cdashVersion = this->GetCDashVersion(); + //version >= 1.6? + bool cdashSupportsGzip = cmSystemTools::VersionCompare( + cmSystemTools::OP_GREATER, cdashVersion.c_str(), "1.6") || + cmSystemTools::VersionCompare(cmSystemTools::OP_EQUAL, + cdashVersion.c_str(), "1.6"); + this->CompressTestOutput &= cdashSupportsGzip; + this->ComputedCompressOutput = true; + } + return this->CompressTestOutput; +} + +//---------------------------------------------------------------------------- +std::string cmCTest::GetCDashVersion() +{ +#ifdef CMAKE_BUILD_WITH_CMAKE + //First query the server. If that fails, fall back to the local setting + std::string response; + std::string url = "http://"; + url += this->GetCTestConfiguration("DropSite"); + + std::string cdashUri = this->GetCTestConfiguration("DropLocation"); + cdashUri = cdashUri.substr(0, cdashUri.find("/submit.php")); + + url += cdashUri + "/api/getversion.php"; + int res = cmCTest::HTTPRequest(url, cmCTest::HTTP_GET, response, "", "", 3); + + return res ? this->GetCTestConfiguration("CDashVersion") : response; +#else + return this->GetCTestConfiguration("CDashVersion"); +#endif +} + +//---------------------------------------------------------------------------- cmCTest::Part cmCTest::GetPartFromName(const char* name) { // Look up by lower-case to make names case-insensitive. @@ -315,7 +441,7 @@ cmCTest::Part cmCTest::GetPartFromName(const char* name) } //---------------------------------------------------------------------- -int cmCTest::Initialize(const char* binary_dir, bool script) +int cmCTest::Initialize(const char* binary_dir, cmCTestStartCommand* command) { cmCTestLog(this, DEBUG, "Here: " << __LINE__ << std::endl); if(!this->InteractiveDebugMode) @@ -366,6 +492,8 @@ int cmCTest::Initialize(const char* binary_dir, bool script) if ( this->ProduceXML ) { + // Verify "Testing" directory exists: + // std::string testingDir = this->BinaryDir + "/Testing"; if ( cmSystemTools::FileExists(testingDir.c_str()) ) { @@ -385,73 +513,108 @@ int cmCTest::Initialize(const char* binary_dir, bool script) return 0; } } + + // Create new "TAG" file or read existing one: + // + bool createNewTag = true; + if (command) + { + createNewTag = command->ShouldCreateNewTag(); + } + std::string tagfile = testingDir + "/TAG"; std::ifstream tfin(tagfile.c_str()); std::string tag; - time_t tctime = time(0); - if ( this->TomorrowTag ) - { - tctime += ( 24 * 60 * 60 ); - } - struct tm *lctime = gmtime(&tctime); - if ( tfin && cmSystemTools::GetLineFromStream(tfin, tag) ) - { - int year = 0; - int mon = 0; - int day = 0; - int hour = 0; - int min = 0; - sscanf(tag.c_str(), "%04d%02d%02d-%02d%02d", - &year, &mon, &day, &hour, &min); - if ( year != lctime->tm_year + 1900 || - mon != lctime->tm_mon+1 || - day != lctime->tm_mday ) + + if (createNewTag) + { + time_t tctime = time(0); + if ( this->TomorrowTag ) { - tag = ""; + tctime += ( 24 * 60 * 60 ); } - std::string tagmode; - if ( cmSystemTools::GetLineFromStream(tfin, tagmode) ) + struct tm *lctime = gmtime(&tctime); + if ( tfin && cmSystemTools::GetLineFromStream(tfin, tag) ) { - if (tagmode.size() > 4 && !this->Parts[PartStart]) + int year = 0; + int mon = 0; + int day = 0; + int hour = 0; + int min = 0; + sscanf(tag.c_str(), "%04d%02d%02d-%02d%02d", + &year, &mon, &day, &hour, &min); + if ( year != lctime->tm_year + 1900 || + mon != lctime->tm_mon+1 || + day != lctime->tm_mday ) { - this->TestModel = cmCTest::GetTestModelFromString(tagmode.c_str()); + tag = ""; } + std::string tagmode; + if ( cmSystemTools::GetLineFromStream(tfin, tagmode) ) + { + if (tagmode.size() > 4 && !this->Parts[PartStart]) + { + this->TestModel = cmCTest::GetTestModelFromString(tagmode.c_str()); + } + } + tfin.close(); } - tfin.close(); - } - if (tag.size() == 0 || script || this->Parts[PartStart]) - { - cmCTestLog(this, DEBUG, "TestModel: " << this->GetTestModelString() - << std::endl); - cmCTestLog(this, DEBUG, "TestModel: " << this->TestModel << std::endl); - if ( this->TestModel == cmCTest::NIGHTLY ) + if (tag.size() == 0 || (0 != command) || this->Parts[PartStart]) { - lctime = this->GetNightlyTime( - this->GetCTestConfiguration("NightlyStartTime"), this->TomorrowTag); + cmCTestLog(this, DEBUG, "TestModel: " << this->GetTestModelString() + << std::endl); + cmCTestLog(this, DEBUG, "TestModel: " << this->TestModel << std::endl); + if ( this->TestModel == cmCTest::NIGHTLY ) + { + lctime = this->GetNightlyTime( + this->GetCTestConfiguration("NightlyStartTime"), + this->TomorrowTag); + } + char datestring[100]; + sprintf(datestring, "%04d%02d%02d-%02d%02d", + lctime->tm_year + 1900, + lctime->tm_mon+1, + lctime->tm_mday, + lctime->tm_hour, + lctime->tm_min); + tag = datestring; + std::ofstream ofs(tagfile.c_str()); + if ( ofs ) + { + ofs << tag << std::endl; + ofs << this->GetTestModelString() << std::endl; + } + ofs.close(); + if ( 0 == command ) + { + cmCTestLog(this, OUTPUT, "Create new tag: " << tag << " - " + << this->GetTestModelString() << std::endl); + } } - char datestring[100]; - sprintf(datestring, "%04d%02d%02d-%02d%02d", - lctime->tm_year + 1900, - lctime->tm_mon+1, - lctime->tm_mday, - lctime->tm_hour, - lctime->tm_min); - tag = datestring; - std::ofstream ofs(tagfile.c_str()); - if ( ofs ) + } + else + { + if ( tfin ) { - ofs << tag << std::endl; - ofs << this->GetTestModelString() << std::endl; + cmSystemTools::GetLineFromStream(tfin, tag); + tfin.close(); } - ofs.close(); - if ( !script ) + + if ( tag.empty() ) { - cmCTestLog(this, OUTPUT, "Create new tag: " << tag << " - " - << this->GetTestModelString() << std::endl); + cmCTestLog(this, ERROR_MESSAGE, + "Cannot read existing TAG file in " << testingDir + << std::endl); + return 0; } + + cmCTestLog(this, OUTPUT, " Use existing tag: " << tag << " - " + << this->GetTestModelString() << std::endl); } + this->CurrentTag = tag; } + return 1; } @@ -509,7 +672,7 @@ bool cmCTest::InitializeFromCommand(cmCTestStartCommand* command) } } - if ( !this->Initialize(bld_dir.c_str(), true) ) + if ( !this->Initialize(bld_dir.c_str(), command) ) { return false; } @@ -1007,7 +1170,7 @@ int cmCTest::RunMakeCommand(const char* command, std::string* output, if ( tick % tick_line_len == 0 && tick > 0 ) { cmCTestLog(this, HANDLER_OUTPUT, " Size: " - << int((output->size() / 1024.0) + 1) << "K" << std::endl + << int((double(output->size()) / 1024.0) + 1) << "K" << std::endl << " " << std::flush); } } @@ -1019,7 +1182,7 @@ int cmCTest::RunMakeCommand(const char* command, std::string* output, } } cmCTestLog(this, OUTPUT, " Size of output: " - << int(output->size() / 1024.0) << "K" << std::endl); + << int(double(output->size()) / 1024.0) << "K" << std::endl); cmsysProcess_WaitForExit(cp, 0); @@ -1711,6 +1874,11 @@ void cmCTest::HandleCommandLineArguments(size_t &i, this->CompressTestOutput = false; } + if(this->CheckArgument(arg, "--print-labels")) + { + this->PrintLabels = true; + } + if(this->CheckArgument(arg, "--http1.0")) { this->UseHTTP10 = true; @@ -1722,6 +1890,12 @@ void cmCTest::HandleCommandLineArguments(size_t &i, double timeout = (double)atof(args[i].c_str()); this->GlobalTimeout = timeout; } + + if(this->CheckArgument(arg, "--stop-time") && i < args.size() - 1) + { + i++; + this->SetStopTime(args[i]); + } if(this->CheckArgument(arg, "-C", "--build-config") && i < args.size() - 1) @@ -1953,7 +2127,7 @@ int cmCTest::Run(std::vector<std::string> &args, std::string* output) i++; std::string targ = args[i]; // AddTestsForDashboard parses the dashborad type and converts it - // into the seperate stages + // into the separate stages if (!this->AddTestsForDashboardType(targ)) { performSomeTest = false; @@ -2119,7 +2293,7 @@ int cmCTest::Run(std::vector<std::string> &args, std::string* output) it->second->SetSubmitIndex(this->SubmitIndex); } std::string cwd = cmSystemTools::GetCurrentWorkingDirectory(); - if(!this->Initialize(cwd.c_str(), false)) + if(!this->Initialize(cwd.c_str(), 0)) { res = 12; cmCTestLog(this, ERROR_MESSAGE, "Problem initializing the dashboard." @@ -2176,6 +2350,13 @@ void cmCTest::SetNotesFiles(const char* notes) } //---------------------------------------------------------------------- +void cmCTest::SetStopTime(std::string time) +{ + this->StopTime = time; + this->DetermineNextDayStop(); +} + +//---------------------------------------------------------------------- int cmCTest::ReadCustomConfigurationFileTree(const char* dir, cmMakefile* mf) { bool found = false; @@ -2377,6 +2558,46 @@ void cmCTest::EmptyCTestConfiguration() } //---------------------------------------------------------------------- +void cmCTest::DetermineNextDayStop() +{ + struct tm* lctime; + time_t current_time = time(0); + lctime = gmtime(¤t_time); + int gm_hour = lctime->tm_hour; + time_t gm_time = mktime(lctime); + lctime = localtime(¤t_time); + int local_hour = lctime->tm_hour; + + int tzone_offset = local_hour - gm_hour; + if(gm_time > current_time && gm_hour < local_hour) + { + // this means gm_time is on the next day + tzone_offset -= 24; + } + else if(gm_time < current_time && gm_hour > local_hour) + { + // this means gm_time is on the previous day + tzone_offset += 24; + } + + tzone_offset *= 100; + char buf[1024]; + sprintf(buf, "%d%02d%02d %s %+05i", + lctime->tm_year + 1900, + lctime->tm_mon + 1, + lctime->tm_mday, + this->StopTime.c_str(), + tzone_offset); + + time_t stop_time = curl_getdate(buf, ¤t_time); + + if(stop_time < current_time) + { + this->NextDayStopTime = true; + } +} + +//---------------------------------------------------------------------- void cmCTest::SetCTestConfiguration(const char *name, const char* value) { cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, "SetCTestConfiguration:" diff --git a/Source/cmCTest.h b/Source/cmCTest.h index 6fe1eb3..e54a205 100644 --- a/Source/cmCTest.h +++ b/Source/cmCTest.h @@ -80,6 +80,21 @@ public: bool Enabled; std::string Name; }; +#ifdef CMAKE_BUILD_WITH_CMAKE + enum HTTPMethod { + HTTP_GET, + HTTP_POST, + HTTP_PUT + }; + + /** + * Perform an HTTP request. + */ + static int HTTPRequest(std::string url, HTTPMethod method, + std::string& response, + std::string fields = "", + std::string putFile = "", int timeout = 0); +#endif /** Get a testing part id from its string name. Returns PartCount if the string does not name a valid part. */ @@ -195,7 +210,14 @@ public: bool ShouldUseHTTP10() { return this->UseHTTP10; } - bool ShouldCompressTestOutput() { return this->CompressTestOutput; } + bool ShouldPrintLabels() { return this->PrintLabels; } + + bool ShouldCompressTestOutput(); + + std::string GetCDashVersion(); + + std::string GetStopTime() { return this->StopTime; } + void SetStopTime(std::string time); //Used for parallel ctest job scheduling std::string GetScheduleType() { return this->ScheduleType; } @@ -381,14 +403,19 @@ public: { this->StreamOut = out; this->StreamErr = err; } void AddSiteProperties(std::ostream& ); bool GetLabelSummary() { return this->LabelSummary;} + + std::string GetCostDataFile(); private: std::string ConfigType; std::string ScheduleType; + std::string StopTime; + bool NextDayStopTime; bool Verbose; bool ExtraVerbose; bool ProduceXML; bool LabelSummary; bool UseHTTP10; + bool PrintLabels; bool Failover; bool BatchJobs; @@ -396,8 +423,13 @@ private: bool RunConfigurationScript; + //flag for lazy getter (optimization) + bool ComputedCompressOutput; + int GenerateNotesFile(const char* files); + void DetermineNextDayStop(); + // these are helper classes typedef std::map<cmStdString,cmCTestGenericHandler*> t_TestingHandlers; t_TestingHandlers TestingHandlers; @@ -428,6 +460,8 @@ private: double GlobalTimeout; + int LastStopTimeout; + int MaxTestNameWidth; int ParallelLevel; @@ -457,14 +491,14 @@ private: void BlockTestErrorDiagnostics(); /** - * Initialize a dashboard run in the given build tree. The "script" - * argument is true when running from a command-driven (ctest_start) - * dashboard script, and false when running from the CTest command + * Initialize a dashboard run in the given build tree. The "command" + * argument is non-NULL when running from a command-driven (ctest_start) + * dashboard script, and NULL when running from the CTest command * line. Note that a declarative dashboard script does not actually * call this method because it sets CTEST_COMMAND to drive a build * through the ctest command line. */ - int Initialize(const char* binary_dir, bool script); + int Initialize(const char* binary_dir, cmCTestStartCommand* command); //! parse the option after -D and convert it into the appropriate steps bool AddTestsForDashboardType(std::string &targ); diff --git a/Source/cmCacheManager.cxx b/Source/cmCacheManager.cxx index e1a1076..c8374db 100644 --- a/Source/cmCacheManager.cxx +++ b/Source/cmCacheManager.cxx @@ -22,10 +22,6 @@ #include <cmsys/RegularExpression.hxx> -#if defined(_WIN32) || defined(__CYGWIN__) -# include <windows.h> -#endif // _WIN32 - const char* cmCacheManagerTypes[] = { "BOOL", "PATH", @@ -97,14 +93,14 @@ bool cmCacheManager::LoadCache(const char* path, return this->LoadCache(path, internal, emptySet, emptySet); } -bool cmCacheManager::ParseEntry(const char* entry, - std::string& var, - std::string& value) +static bool ParseEntryWithoutType(const char* entry, + std::string& var, + std::string& value) { - // input line is: key:type=value + // input line is: key=value static cmsys::RegularExpression reg( - "^([^:]*)=(.*[^\r\t ]|[\r\t ]*)[\r\t ]*$"); - // input line is: "key":type=value + "^([^=]*)=(.*[^\r\t ]|[\r\t ]*)[\r\t ]*$"); + // input line is: "key"=value static cmsys::RegularExpression regQuoted( "^\"([^\"]*)\"=(.*[^\r\t ]|[\r\t ]*)[\r\t ]*$"); bool flag = false; @@ -173,6 +169,11 @@ bool cmCacheManager::ParseEntry(const char* entry, value.size() - 2); } + if (!flag) + { + return ParseEntryWithoutType(entry, var, value); + } + return flag; } @@ -340,7 +341,7 @@ bool cmCacheManager::LoadCache(const char* path, std::string("The current CMakeCache.txt directory ") + currentcwd + std::string(" is different than the directory ") + std::string(this->GetCacheValue("CMAKE_CACHEFILE_DIR")) + - std::string(" where CMackeCache.txt was created. This may result " + std::string(" where CMakeCache.txt was created. This may result " "in binaries being created in the wrong place. If you " "are not sure, reedit the CMakeCache.txt"); cmSystemTools::Error(message.c_str()); diff --git a/Source/cmCacheManager.h b/Source/cmCacheManager.h index da14966..314017b 100644 --- a/Source/cmCacheManager.h +++ b/Source/cmCacheManager.h @@ -139,10 +139,6 @@ public: std::string& value, CacheEntryType& type); - static bool ParseEntry(const char* entry, - std::string& var, - std::string& value); - ///! Get a value from the cache given a key const char* GetCacheValue(const char* key) const; diff --git a/Source/cmCommands.cxx b/Source/cmCommands.cxx index 1950871..bb1e4e2 100644 --- a/Source/cmCommands.cxx +++ b/Source/cmCommands.cxx @@ -14,7 +14,6 @@ #include "cmAuxSourceDirectoryCommand.cxx" #include "cmBuildNameCommand.cxx" #include "cmElseIfCommand.cxx" -#include "cmEnableLanguageCommand.cxx" #include "cmEndWhileCommand.cxx" #include "cmExportCommand.cxx" #include "cmExportLibraryDependencies.cxx" @@ -54,7 +53,6 @@ void GetPredefinedCommands(std::list<cmCommand*>& commands.push_back(new cmAuxSourceDirectoryCommand); commands.push_back(new cmBuildNameCommand); commands.push_back(new cmElseIfCommand); - commands.push_back(new cmEnableLanguageCommand); commands.push_back(new cmEndWhileCommand); commands.push_back(new cmExportCommand); commands.push_back(new cmExportLibraryDependenciesCommand); diff --git a/Source/cmComputeComponentGraph.cxx b/Source/cmComputeComponentGraph.cxx index 3f2a361..5bec6a1 100644 --- a/Source/cmComputeComponentGraph.cxx +++ b/Source/cmComputeComponentGraph.cxx @@ -71,8 +71,8 @@ void cmComputeComponentGraph::TarjanVisit(int i) this->TarjanStack.push(i); // Follow outgoing edges. - NodeList const& nl = this->InputGraph[i]; - for(NodeList::const_iterator ni = nl.begin(); ni != nl.end(); ++ni) + EdgeList const& nl = this->InputGraph[i]; + for(EdgeList::const_iterator ni = nl.begin(); ni != nl.end(); ++ni) { int j = *ni; @@ -142,14 +142,17 @@ void cmComputeComponentGraph::TransferEdges() for(int i=0; i < n; ++i) { int i_component = this->TarjanComponents[i]; - NodeList const& nl = this->InputGraph[i]; - for(NodeList::const_iterator ni = nl.begin(); ni != nl.end(); ++ni) + EdgeList const& nl = this->InputGraph[i]; + for(EdgeList::const_iterator ni = nl.begin(); ni != nl.end(); ++ni) { int j = *ni; int j_component = this->TarjanComponents[j]; if(i_component != j_component) { - this->ComponentGraph[i_component].push_back(j_component); + // We do not attempt to combine duplicate edges, but instead + // store the inter-component edges with suitable multiplicity. + this->ComponentGraph[i_component].push_back( + cmGraphEdge(j_component, ni->IsStrong())); } } } diff --git a/Source/cmComputeComponentGraph.h b/Source/cmComputeComponentGraph.h index 855a141..a2ce946 100644 --- a/Source/cmComputeComponentGraph.h +++ b/Source/cmComputeComponentGraph.h @@ -33,6 +33,7 @@ class cmComputeComponentGraph public: // Represent the graph with an adjacency list. typedef cmGraphNodeList NodeList; + typedef cmGraphEdgeList EdgeList; typedef cmGraphAdjacencyList Graph; cmComputeComponentGraph(Graph const& input); @@ -41,7 +42,7 @@ public: /** Get the adjacency list of the component graph. */ Graph const& GetComponentGraph() const { return this->ComponentGraph; } - NodeList const& GetComponentGraphEdges(int c) const + EdgeList const& GetComponentGraphEdges(int c) const { return this->ComponentGraph[c]; } /** Get map from component index to original node indices. */ diff --git a/Source/cmComputeLinkDepends.cxx b/Source/cmComputeLinkDepends.cxx index 24410ec..342c217 100644 --- a/Source/cmComputeLinkDepends.cxx +++ b/Source/cmComputeLinkDepends.cxx @@ -285,7 +285,7 @@ cmComputeLinkDepends::AllocateLinkEntry(std::string const& item) lei = this->LinkEntryIndex.insert(index_entry).first; this->EntryList.push_back(LinkEntry()); this->InferredDependSets.push_back(0); - this->EntryConstraintGraph.push_back(NodeList()); + this->EntryConstraintGraph.push_back(EdgeList()); return lei; } @@ -669,7 +669,7 @@ void cmComputeLinkDepends::CleanConstraintGraph() cmsys_stl::sort(i->begin(), i->end()); // Make the edge list unique. - NodeList::iterator last = cmsys_stl::unique(i->begin(), i->end()); + EdgeList::iterator last = cmsys_stl::unique(i->begin(), i->end()); i->erase(last, i->end()); } } @@ -681,9 +681,9 @@ void cmComputeLinkDepends::DisplayConstraintGraph() cmOStringStream e; for(unsigned int i=0; i < this->EntryConstraintGraph.size(); ++i) { - NodeList const& nl = this->EntryConstraintGraph[i]; + EdgeList const& nl = this->EntryConstraintGraph[i]; e << "item " << i << " is [" << this->EntryList[i].Item << "]\n"; - for(NodeList::const_iterator j = nl.begin(); j != nl.end(); ++j) + for(EdgeList::const_iterator j = nl.begin(); j != nl.end(); ++j) { e << " item " << *j << " must follow it\n"; } @@ -758,10 +758,11 @@ cmComputeLinkDepends::DisplayComponents() fprintf(stderr, " item %d [%s]\n", i, this->EntryList[i].Item.c_str()); } - NodeList const& ol = this->CCG->GetComponentGraphEdges(c); - for(NodeList::const_iterator oi = ol.begin(); oi != ol.end(); ++oi) + EdgeList const& ol = this->CCG->GetComponentGraphEdges(c); + for(EdgeList::const_iterator oi = ol.begin(); oi != ol.end(); ++oi) { - fprintf(stderr, " followed by Component (%d)\n", *oi); + int i = *oi; + fprintf(stderr, " followed by Component (%d)\n", i); } fprintf(stderr, " topo order index %d\n", this->ComponentOrder[c]); @@ -784,8 +785,8 @@ void cmComputeLinkDepends::VisitComponent(unsigned int c) // Visit the neighbors of the component first. // Run in reverse order so the topological order will preserve the // original order where there are no constraints. - NodeList const& nl = this->CCG->GetComponentGraphEdges(c); - for(NodeList::const_reverse_iterator ni = nl.rbegin(); + EdgeList const& nl = this->CCG->GetComponentGraphEdges(c); + for(EdgeList::const_reverse_iterator ni = nl.rbegin(); ni != nl.rend(); ++ni) { this->VisitComponent(*ni); @@ -856,8 +857,8 @@ void cmComputeLinkDepends::VisitEntry(int index) // are now pending. if(completed) { - NodeList const& ol = this->CCG->GetComponentGraphEdges(component); - for(NodeList::const_iterator oi = ol.begin(); oi != ol.end(); ++oi) + EdgeList const& ol = this->CCG->GetComponentGraphEdges(component); + for(EdgeList::const_iterator oi = ol.begin(); oi != ol.end(); ++oi) { // This entire component is now pending no matter whether it has // been partially seen already. diff --git a/Source/cmComputeLinkDepends.h b/Source/cmComputeLinkDepends.h index a08afb6..e196e00 100644 --- a/Source/cmComputeLinkDepends.h +++ b/Source/cmComputeLinkDepends.h @@ -117,6 +117,7 @@ private: // Ordering constraint graph adjacency list. typedef cmGraphNodeList NodeList; + typedef cmGraphEdgeList EdgeList; typedef cmGraphAdjacencyList Graph; Graph EntryConstraintGraph; void CleanConstraintGraph(); diff --git a/Source/cmComputeLinkInformation.cxx b/Source/cmComputeLinkInformation.cxx index 69a4d22..d53200c 100644 --- a/Source/cmComputeLinkInformation.cxx +++ b/Source/cmComputeLinkInformation.cxx @@ -376,6 +376,8 @@ cmComputeLinkInformation { this->OrderDependentRPath ->SetImplicitDirectories(this->ImplicitLinkDirs); + this->OrderDependentRPath + ->AddLanguageDirectories(this->RuntimeLinkDirs); } // Decide whether to enable compatible library search path mode. @@ -921,7 +923,7 @@ void cmComputeLinkInformation::ComputeItemParserInfo() //---------------------------------------------------------------------------- void cmComputeLinkInformation::AddLinkPrefix(const char* p) { - if(p) + if(p && *p) { this->LinkPrefixes.insert(p); } @@ -1324,13 +1326,12 @@ void cmComputeLinkInformation::AddFrameworkItem(std::string const& item) //---------------------------------------------------------------------------- void cmComputeLinkInformation::AddDirectoryItem(std::string const& item) { -#ifdef __APPLE__ - if(cmSystemTools::IsPathToFramework(item.c_str())) + if(this->Makefile->IsOn("APPLE") + && cmSystemTools::IsPathToFramework(item.c_str())) { this->AddFrameworkItem(item); } else -#endif { this->DropDirectoryItem(item); } @@ -1642,6 +1643,14 @@ void cmComputeLinkInformation::LoadImplicitLinkInfo() this->ImplicitLinkLibs.insert(item); } } + + // Get platform specific rpath link directories + if(const char *rpathDirs = + (this->Makefile->GetDefinition + ("CMAKE_PLATFORM_RUNTIME_PATH"))) + { + cmSystemTools::ExpandListArgument(rpathDirs, this->RuntimeLinkDirs); + } } //---------------------------------------------------------------------------- diff --git a/Source/cmComputeLinkInformation.h b/Source/cmComputeLinkInformation.h index ad2026b..bbeed68 100644 --- a/Source/cmComputeLinkInformation.h +++ b/Source/cmComputeLinkInformation.h @@ -163,6 +163,9 @@ private: std::set<cmStdString> ImplicitLinkDirs; std::set<cmStdString> ImplicitLinkLibs; + // Additional paths configured by the runtime linker + std::vector<std::string> RuntimeLinkDirs; + // Linker search path compatibility mode. std::set<cmStdString> OldLinkDirMask; std::vector<std::string> OldLinkDirItems; diff --git a/Source/cmComputeTargetDepends.cxx b/Source/cmComputeTargetDepends.cxx index 94b8527..a4ca363 100644 --- a/Source/cmComputeTargetDepends.cxx +++ b/Source/cmComputeTargetDepends.cxx @@ -129,7 +129,10 @@ bool cmComputeTargetDepends::Compute() } // Compute the final dependency graph. - this->ComputeFinalDepends(ccg); + if(!this->ComputeFinalDepends(ccg)) + { + return false; + } if(this->DebugMode) { this->DisplayGraph(this->FinalGraph, "final"); @@ -141,7 +144,7 @@ bool cmComputeTargetDepends::Compute() //---------------------------------------------------------------------------- void cmComputeTargetDepends::GetTargetDirectDepends(cmTarget* t, - std::set<cmTarget*>& deps) + cmTargetDependSet& deps) { // Lookup the index for this target. All targets should be known by // this point. @@ -150,10 +153,12 @@ cmComputeTargetDepends::GetTargetDirectDepends(cmTarget* t, int i = tii->second; // Get its final dependencies. - NodeList const& nl = this->FinalGraph[i]; - for(NodeList::const_iterator ni = nl.begin(); ni != nl.end(); ++ni) + EdgeList const& nl = this->FinalGraph[i]; + for(EdgeList::const_iterator ni = nl.begin(); ni != nl.end(); ++ni) { - deps.insert(this->Targets[*ni]); + cmTarget* dep = this->Targets[*ni]; + cmTargetDependSet::iterator di = deps.insert(dep).first; + di->SetType(ni->IsStrong()); } } @@ -195,15 +200,13 @@ void cmComputeTargetDepends::CollectTargetDepends(int depender_index) // Get the depender. cmTarget* depender = this->Targets[depender_index]; - // Keep track of dependencies already listed. - std::set<cmStdString> emitted; - - // A target should not depend on itself. - emitted.insert(depender->GetName()); - // Loop over all targets linked directly. + { cmTarget::LinkLibraryVectorType const& tlibs = depender->GetOriginalLinkLibraries(); + std::set<cmStdString> emitted; + // A target should not depend on itself. + emitted.insert(depender->GetName()); for(cmTarget::LinkLibraryVectorType::const_iterator lib = tlibs.begin(); lib != tlibs.end(); ++lib) { @@ -213,9 +216,14 @@ void cmComputeTargetDepends::CollectTargetDepends(int depender_index) this->AddTargetDepend(depender_index, lib->first.c_str(), true); } } + } // Loop over all utility dependencies. + { std::set<cmStdString> const& tutils = depender->GetUtilities(); + std::set<cmStdString> emitted; + // A target should not depend on itself. + emitted.insert(depender->GetName()); for(std::set<cmStdString>::const_iterator util = tutils.begin(); util != tutils.end(); ++util) { @@ -225,6 +233,7 @@ void cmComputeTargetDepends::CollectTargetDepends(int depender_index) this->AddTargetDepend(depender_index, util->c_str(), false); } } + } } //---------------------------------------------------------------------------- @@ -237,13 +246,7 @@ void cmComputeTargetDepends::AddTargetDepend(int depender_index, // Check the target's makefile first. cmTarget* dependee = - depender->GetMakefile()->FindTarget(dependee_name); - - // Then search globally. - if(!dependee) - { - dependee = this->GlobalGenerator->FindTarget(0, dependee_name); - } + depender->GetMakefile()->FindTargetToUse(dependee_name); // Skip targets that will not really be linked. This is probably a // name conflict between an external library and an executable @@ -255,24 +258,42 @@ void cmComputeTargetDepends::AddTargetDepend(int depender_index, dependee = 0; } - // If not found then skip then the dependee. - if(!dependee) + if(dependee) { - return; + this->AddTargetDepend(depender_index, dependee, linking); } +} - // No imported targets should have been found. - assert(!dependee->IsImported()); - - // Lookup the index for this target. All targets should be known by - // this point. - std::map<cmTarget*, int>::const_iterator tii = - this->TargetIndex.find(dependee); - assert(tii != this->TargetIndex.end()); - int dependee_index = tii->second; - - // Add this entry to the dependency graph. - this->InitialGraph[depender_index].push_back(dependee_index); +//---------------------------------------------------------------------------- +void cmComputeTargetDepends::AddTargetDepend(int depender_index, + cmTarget* dependee, + bool linking) +{ + if(dependee->IsImported()) + { + // Skip imported targets but follow their utility dependencies. + std::set<cmStdString> const& utils = dependee->GetUtilities(); + for(std::set<cmStdString>::const_iterator i = utils.begin(); + i != utils.end(); ++i) + { + cmTarget* transitive_dependee = + dependee->GetMakefile()->FindTargetToUse(i->c_str()); + this->AddTargetDepend(depender_index, transitive_dependee, false); + } + } + else + { + // Lookup the index for this target. All targets should be known by + // this point. + std::map<cmTarget*, int>::const_iterator tii = + this->TargetIndex.find(dependee); + assert(tii != this->TargetIndex.end()); + int dependee_index = tii->second; + + // Add this entry to the dependency graph. + this->InitialGraph[depender_index].push_back( + cmGraphEdge(dependee_index, !linking)); + } } //---------------------------------------------------------------------------- @@ -283,16 +304,16 @@ cmComputeTargetDepends::DisplayGraph(Graph const& graph, const char* name) int n = static_cast<int>(graph.size()); for(int depender_index = 0; depender_index < n; ++depender_index) { - NodeList const& nl = graph[depender_index]; + EdgeList const& nl = graph[depender_index]; cmTarget* depender = this->Targets[depender_index]; fprintf(stderr, "target %d is [%s]\n", depender_index, depender->GetName()); - for(NodeList::const_iterator ni = nl.begin(); ni != nl.end(); ++ni) + for(EdgeList::const_iterator ni = nl.begin(); ni != nl.end(); ++ni) { int dependee_index = *ni; cmTarget* dependee = this->Targets[dependee_index]; - fprintf(stderr, " depends on target %d [%s]\n", dependee_index, - dependee->GetName()); + fprintf(stderr, " depends on target %d [%s] (%s)\n", dependee_index, + dependee->GetName(), ni->IsStrong()? "strong" : "weak"); } } fprintf(stderr, "\n"); @@ -363,7 +384,8 @@ cmComputeTargetDepends //---------------------------------------------------------------------------- void cmComputeTargetDepends -::ComplainAboutBadComponent(cmComputeComponentGraph const& ccg, int c) +::ComplainAboutBadComponent(cmComputeComponentGraph const& ccg, int c, + bool strong) { // Construct the error message. cmOStringStream e; @@ -383,18 +405,27 @@ cmComputeTargetDepends << cmTarget::TargetTypeNames[depender->GetType()] << "\n"; // List its dependencies that are inside the component. - NodeList const& nl = this->InitialGraph[i]; - for(NodeList::const_iterator ni = nl.begin(); ni != nl.end(); ++ni) + EdgeList const& nl = this->InitialGraph[i]; + for(EdgeList::const_iterator ni = nl.begin(); ni != nl.end(); ++ni) { int j = *ni; if(cmap[j] == c) { cmTarget* dependee = this->Targets[j]; - e << " depends on \"" << dependee->GetName() << "\"\n"; + e << " depends on \"" << dependee->GetName() << "\"" + << " (" << (ni->IsStrong()? "strong" : "weak") << ")\n"; } } } - if(this->NoCycles) + if(strong) + { + // Custom command executable dependencies cannot occur within a + // component of static libraries. The cycle must appear in calls + // to add_dependencies. + e << "The component contains at least one cycle consisting of strong " + << "dependencies (created by add_dependencies) that cannot be broken."; + } + else if(this->NoCycles) { e << "The GLOBAL_DEPENDS_NO_CYCLES global property is enabled, so " << "cyclic dependencies are not allowed even among static libraries."; @@ -408,7 +439,49 @@ cmComputeTargetDepends } //---------------------------------------------------------------------------- -void +bool +cmComputeTargetDepends +::IntraComponent(std::vector<int> const& cmap, int c, int i, int* head, + std::set<int>& emitted, std::set<int>& visited) +{ + if(!visited.insert(i).second) + { + // Cycle in utility depends! + return false; + } + if(emitted.insert(i).second) + { + // Honor strong intra-component edges in the final order. + EdgeList const& el = this->InitialGraph[i]; + for(EdgeList::const_iterator ei = el.begin(); ei != el.end(); ++ei) + { + int j = *ei; + if(cmap[j] == c && ei->IsStrong()) + { + this->FinalGraph[i].push_back(cmGraphEdge(j, true)); + if(!this->IntraComponent(cmap, c, j, head, emitted, visited)) + { + return false; + } + } + } + + // Prepend to a linear linked-list of intra-component edges. + if(*head >= 0) + { + this->FinalGraph[i].push_back(cmGraphEdge(*head, false)); + } + else + { + this->ComponentTail[c] = i; + } + *head = i; + } + return true; +} + +//---------------------------------------------------------------------------- +bool cmComputeTargetDepends ::ComputeFinalDepends(cmComputeComponentGraph const& ccg) { @@ -420,34 +493,43 @@ cmComputeTargetDepends this->FinalGraph.resize(0); this->FinalGraph.resize(this->InitialGraph.size()); - // Convert inter-component edges to connect component tails to heads. - int n = static_cast<int>(cgraph.size()); - for(int depender_component=0; depender_component < n; ++depender_component) + // Choose intra-component edges to linearize dependencies. + std::vector<int> const& cmap = ccg.GetComponentMap(); + this->ComponentHead.resize(components.size()); + this->ComponentTail.resize(components.size()); + int nc = static_cast<int>(components.size()); + for(int c=0; c < nc; ++c) { - int depender_component_tail = components[depender_component].back(); - NodeList const& nl = cgraph[depender_component]; - for(NodeList::const_iterator ni = nl.begin(); ni != nl.end(); ++ni) + int head = -1; + std::set<int> emitted; + NodeList const& nl = components[c]; + for(NodeList::const_reverse_iterator ni = nl.rbegin(); + ni != nl.rend(); ++ni) { - int dependee_component = *ni; - int dependee_component_head = components[dependee_component].front(); - this->FinalGraph[depender_component_tail] - .push_back(dependee_component_head); + std::set<int> visited; + if(!this->IntraComponent(cmap, c, *ni, &head, emitted, visited)) + { + // Cycle in add_dependencies within component! + this->ComplainAboutBadComponent(ccg, c, true); + return false; + } } + this->ComponentHead[c] = head; } - // Compute intra-component edges. - int nc = static_cast<int>(components.size()); - for(int c=0; c < nc; ++c) + // Convert inter-component edges to connect component tails to heads. + int n = static_cast<int>(cgraph.size()); + for(int depender_component=0; depender_component < n; ++depender_component) { - // Within the component each target depends on that following it. - NodeList const& nl = components[c]; - NodeList::const_iterator ni = nl.begin(); - int last_i = *ni; - for(++ni; ni != nl.end(); ++ni) + int depender_component_tail = this->ComponentTail[depender_component]; + EdgeList const& nl = cgraph[depender_component]; + for(EdgeList::const_iterator ni = nl.begin(); ni != nl.end(); ++ni) { - int i = *ni; - this->FinalGraph[last_i].push_back(i); - last_i = i; + int dependee_component = *ni; + int dependee_component_head = this->ComponentHead[dependee_component]; + this->FinalGraph[depender_component_tail] + .push_back(cmGraphEdge(dependee_component_head, ni->IsStrong())); } } + return true; } diff --git a/Source/cmComputeTargetDepends.h b/Source/cmComputeTargetDepends.h index 68e3e47..67bce72 100644 --- a/Source/cmComputeTargetDepends.h +++ b/Source/cmComputeTargetDepends.h @@ -21,6 +21,7 @@ class cmComputeComponentGraph; class cmGlobalGenerator; class cmTarget; +class cmTargetDependSet; /** \class cmComputeTargetDepends * \brief Compute global interdependencies among targets. @@ -38,14 +39,15 @@ public: bool Compute(); std::vector<cmTarget*> const& GetTargets() const { return this->Targets; } - void GetTargetDirectDepends(cmTarget* t, std::set<cmTarget*>& deps); + void GetTargetDirectDepends(cmTarget* t, cmTargetDependSet& deps); private: void CollectTargets(); void CollectDepends(); void CollectTargetDepends(int depender_index); void AddTargetDepend(int depender_index, const char* dependee_name, bool linking); - void ComputeFinalDepends(cmComputeComponentGraph const& ccg); + void AddTargetDepend(int depender_index, cmTarget* dependee, bool linking); + bool ComputeFinalDepends(cmComputeComponentGraph const& ccg); cmGlobalGenerator* GlobalGenerator; bool DebugMode; @@ -59,6 +61,7 @@ private: // top-level index corresponds to a depender whose dependencies are // listed. typedef cmGraphNodeList NodeList; + typedef cmGraphEdgeList EdgeList; typedef cmGraphAdjacencyList Graph; Graph InitialGraph; Graph FinalGraph; @@ -67,7 +70,13 @@ private: // Deal with connected components. void DisplayComponents(cmComputeComponentGraph const& ccg); bool CheckComponents(cmComputeComponentGraph const& ccg); - void ComplainAboutBadComponent(cmComputeComponentGraph const& ccg, int c); + void ComplainAboutBadComponent(cmComputeComponentGraph const& ccg, int c, + bool strong = false); + + std::vector<int> ComponentHead; + std::vector<int> ComponentTail; + bool IntraComponent(std::vector<int> const& cmap, int c, int i, int* head, + std::set<int>& emitted, std::set<int>& visited); }; #endif diff --git a/Source/cmCoreTryCompile.cxx b/Source/cmCoreTryCompile.cxx index d636cb8..25b3216 100644 --- a/Source/cmCoreTryCompile.cxx +++ b/Source/cmCoreTryCompile.cxx @@ -173,12 +173,30 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv) const char* lang =(this->Makefile->GetCMakeInstance()->GetGlobalGenerator() ->GetLanguageFromExtension(ext.c_str())); const char* def = this->Makefile->GetDefinition("CMAKE_MODULE_PATH"); - fprintf(fout, "cmake_minimum_required(VERSION %u.%u)\n", - cmVersion::GetMajorVersion(), cmVersion::GetMinorVersion()); + fprintf(fout, "cmake_minimum_required(VERSION %u.%u.%u.%u)\n", + cmVersion::GetMajorVersion(), cmVersion::GetMinorVersion(), + cmVersion::GetPatchVersion(), cmVersion::GetTweakVersion()); if(def) { fprintf(fout, "SET(CMAKE_MODULE_PATH %s)\n", def); } + + const char* rulesOverrideBase = "CMAKE_USER_MAKE_RULES_OVERRIDE"; + std::string rulesOverrideLang = + rulesOverrideBase + (lang ? std::string("_") + lang : std::string("")); + if(const char* rulesOverridePath = + this->Makefile->GetDefinition(rulesOverrideLang.c_str())) + { + fprintf(fout, "SET(%s \"%s\")\n", + rulesOverrideLang.c_str(), rulesOverridePath); + } + else if(const char* rulesOverridePath2 = + this->Makefile->GetDefinition(rulesOverrideBase)) + { + fprintf(fout, "SET(%s \"%s\")\n", + rulesOverrideBase, rulesOverridePath2); + } + if(lang) { fprintf(fout, "PROJECT(CMAKE_TRY_COMPILE %s)\n", lang); @@ -382,28 +400,18 @@ void cmCoreTryCompile::CleanupFiles(const char* binDir) } else { - if(!cmSystemTools::RemoveFile(fullPath.c_str())) + // Sometimes anti-virus software hangs on to new files so we + // cannot delete them immediately. Try a few times. + int tries = 5; + while(!cmSystemTools::RemoveFile(fullPath.c_str()) && + --tries && cmSystemTools::FileExists(fullPath.c_str())) + { + cmSystemTools::Delay(500); + } + if(tries == 0) { - bool removed = false; - int numAttempts = 0; - // sometimes anti-virus software hangs on to - // new files and we can not delete them, so try - // 5 times with .5 second delay between tries. - while(!removed && numAttempts < 5) - { - cmSystemTools::Delay(500); - if(cmSystemTools::RemoveFile(fullPath.c_str())) - { - removed = true; - } - numAttempts++; - } - if(!removed) - { - std::string m = "Remove failed on file: "; - m += fullPath; - cmSystemTools::ReportLastSystemError(m.c_str()); - } + std::string m = "Remove failed on file: " + fullPath; + cmSystemTools::ReportLastSystemError(m.c_str()); } } } diff --git a/Source/cmCustomCommand.cxx b/Source/cmCustomCommand.cxx index 5db88fa..bd860ee 100644 --- a/Source/cmCustomCommand.cxx +++ b/Source/cmCustomCommand.cxx @@ -11,6 +11,8 @@ ============================================================================*/ #include "cmCustomCommand.h" +#include "cmMakefile.h" + //---------------------------------------------------------------------------- cmCustomCommand::cmCustomCommand() { @@ -28,12 +30,14 @@ cmCustomCommand::cmCustomCommand(const cmCustomCommand& r): Comment(r.Comment), WorkingDirectory(r.WorkingDirectory), EscapeAllowMakeVars(r.EscapeAllowMakeVars), - EscapeOldStyle(r.EscapeOldStyle) + EscapeOldStyle(r.EscapeOldStyle), + Backtrace(new cmListFileBacktrace(*r.Backtrace)) { } //---------------------------------------------------------------------------- -cmCustomCommand::cmCustomCommand(const std::vector<std::string>& outputs, +cmCustomCommand::cmCustomCommand(cmMakefile* mf, + const std::vector<std::string>& outputs, const std::vector<std::string>& depends, const cmCustomCommandLines& commandLines, const char* comment, @@ -45,10 +49,21 @@ cmCustomCommand::cmCustomCommand(const std::vector<std::string>& outputs, Comment(comment?comment:""), WorkingDirectory(workingDirectory?workingDirectory:""), EscapeAllowMakeVars(false), - EscapeOldStyle(true) + EscapeOldStyle(true), + Backtrace(new cmListFileBacktrace) { this->EscapeOldStyle = true; this->EscapeAllowMakeVars = false; + if(mf) + { + mf->GetBacktrace(*this->Backtrace); + } +} + +//---------------------------------------------------------------------------- +cmCustomCommand::~cmCustomCommand() +{ + delete this->Backtrace; } //---------------------------------------------------------------------------- @@ -131,6 +146,12 @@ void cmCustomCommand::SetEscapeAllowMakeVars(bool b) } //---------------------------------------------------------------------------- +cmListFileBacktrace const& cmCustomCommand::GetBacktrace() const +{ + return *this->Backtrace; +} + +//---------------------------------------------------------------------------- cmCustomCommand::ImplicitDependsList const& cmCustomCommand::GetImplicitDepends() const { diff --git a/Source/cmCustomCommand.h b/Source/cmCustomCommand.h index c9adddf..dd92e34 100644 --- a/Source/cmCustomCommand.h +++ b/Source/cmCustomCommand.h @@ -13,6 +13,8 @@ #define cmCustomCommand_h #include "cmStandardIncludes.h" +class cmMakefile; +class cmListFileBacktrace; /** \class cmCustomCommand * \brief A class to encapsulate a custom command @@ -27,12 +29,15 @@ public: cmCustomCommand(const cmCustomCommand& r); /** Main constructor specifies all information for the command. */ - cmCustomCommand(const std::vector<std::string>& outputs, + cmCustomCommand(cmMakefile* mf, + const std::vector<std::string>& outputs, const std::vector<std::string>& depends, const cmCustomCommandLines& commandLines, const char* comment, const char* workingDirectory); + ~cmCustomCommand(); + /** Get the output file produced by the command. */ const std::vector<std::string>& GetOutputs() const; @@ -63,6 +68,9 @@ public: bool GetEscapeAllowMakeVars() const; void SetEscapeAllowMakeVars(bool b); + /** Backtrace of the command that created this custom command. */ + cmListFileBacktrace const& GetBacktrace() const; + typedef std::pair<cmStdString, cmStdString> ImplicitDependsPair; class ImplicitDependsList: public std::vector<ImplicitDependsPair> {}; void SetImplicitDepends(ImplicitDependsList const&); @@ -78,6 +86,7 @@ private: std::string WorkingDirectory; bool EscapeAllowMakeVars; bool EscapeOldStyle; + cmListFileBacktrace* Backtrace; ImplicitDependsList ImplicitDepends; }; diff --git a/Source/cmCustomCommandGenerator.cxx b/Source/cmCustomCommandGenerator.cxx new file mode 100644 index 0000000..a650129 --- /dev/null +++ b/Source/cmCustomCommandGenerator.cxx @@ -0,0 +1,72 @@ +/*============================================================================ + CMake - Cross Platform Makefile Generator + Copyright 2000-2010 Kitware, Inc., Insight Software Consortium + + Distributed under the OSI-approved BSD License (the "License"); + see accompanying file Copyright.txt for details. + + This software is distributed WITHOUT ANY WARRANTY; without even the + implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the License for more information. +============================================================================*/ +#include "cmCustomCommandGenerator.h" + +#include "cmMakefile.h" +#include "cmCustomCommand.h" +#include "cmLocalGenerator.h" +#include "cmGeneratorExpression.h" + +//---------------------------------------------------------------------------- +cmCustomCommandGenerator::cmCustomCommandGenerator( + cmCustomCommand const& cc, const char* config, cmMakefile* mf): + CC(cc), Config(config), Makefile(mf), LG(mf->GetLocalGenerator()), + OldStyle(cc.GetEscapeOldStyle()), MakeVars(cc.GetEscapeAllowMakeVars()), + GE(new cmGeneratorExpression(mf, config, cc.GetBacktrace())) +{ +} + +//---------------------------------------------------------------------------- +cmCustomCommandGenerator::~cmCustomCommandGenerator() +{ + delete this->GE; +} + +//---------------------------------------------------------------------------- +unsigned int cmCustomCommandGenerator::GetNumberOfCommands() const +{ + return static_cast<unsigned int>(this->CC.GetCommandLines().size()); +} + +//---------------------------------------------------------------------------- +std::string cmCustomCommandGenerator::GetCommand(unsigned int c) const +{ + std::string const& argv0 = this->CC.GetCommandLines()[c][0]; + cmTarget* target = this->Makefile->FindTargetToUse(argv0.c_str()); + if(target && target->GetType() == cmTarget::EXECUTABLE && + (target->IsImported() || !this->Makefile->IsOn("CMAKE_CROSSCOMPILING"))) + { + return target->GetLocation(this->Config); + } + return this->GE->Process(argv0); +} + +//---------------------------------------------------------------------------- +void +cmCustomCommandGenerator +::AppendArguments(unsigned int c, std::string& cmd) const +{ + cmCustomCommandLine const& commandLine = this->CC.GetCommandLines()[c]; + for(unsigned int j=1;j < commandLine.size(); ++j) + { + std::string arg = this->GE->Process(commandLine[j]); + cmd += " "; + if(this->OldStyle) + { + cmd += this->LG->EscapeForShellOldStyle(arg.c_str()); + } + else + { + cmd += this->LG->EscapeForShell(arg.c_str(), this->MakeVars); + } + } +} diff --git a/Source/cmCustomCommandGenerator.h b/Source/cmCustomCommandGenerator.h new file mode 100644 index 0000000..4e89f27 --- /dev/null +++ b/Source/cmCustomCommandGenerator.h @@ -0,0 +1,40 @@ +/*============================================================================ + CMake - Cross Platform Makefile Generator + Copyright 2000-2010 Kitware, Inc., Insight Software Consortium + + Distributed under the OSI-approved BSD License (the "License"); + see accompanying file Copyright.txt for details. + + This software is distributed WITHOUT ANY WARRANTY; without even the + implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the License for more information. +============================================================================*/ +#ifndef cmCustomCommandGenerator_h +#define cmCustomCommandGenerator_h + +#include "cmStandardIncludes.h" + +class cmCustomCommand; +class cmMakefile; +class cmLocalGenerator; +class cmGeneratorExpression; + +class cmCustomCommandGenerator +{ + cmCustomCommand const& CC; + const char* Config; + cmMakefile* Makefile; + cmLocalGenerator* LG; + bool OldStyle; + bool MakeVars; + cmGeneratorExpression* GE; +public: + cmCustomCommandGenerator(cmCustomCommand const& cc, const char* config, + cmMakefile* mf); + ~cmCustomCommandGenerator(); + unsigned int GetNumberOfCommands() const; + std::string GetCommand(unsigned int c) const; + void AppendArguments(unsigned int c, std::string& cmd) const; +}; + +#endif diff --git a/Source/cmData.h b/Source/cmData.h deleted file mode 100644 index 3ae32f5..0000000 --- a/Source/cmData.h +++ /dev/null @@ -1,38 +0,0 @@ -/*============================================================================ - CMake - Cross Platform Makefile Generator - Copyright 2000-2009 Kitware, Inc., Insight Software Consortium - - Distributed under the OSI-approved BSD License (the "License"); - see accompanying file Copyright.txt for details. - - This software is distributed WITHOUT ANY WARRANTY; without even the - implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - See the License for more information. -============================================================================*/ -#ifndef cmData_h -#define cmData_h - -#include "cmStandardIncludes.h" - -/** \class cmData - * \brief Hold extra data on a cmMakefile instance for a command. - * - * When CMake commands need to store extra information in a cmMakefile - * instance, but the information is not needed by the makefile generators, - * it can be held in a subclass of cmData. The cmMakefile class has a map - * from std::string to cmData*. On its destruction, it destroys all the - * extra data through the virtual destructor of cmData. - */ -class cmData -{ -public: - cmData(const char* name): Name(name) {} - virtual ~cmData() {} - - const std::string& GetName() const - { return this->Name; } -protected: - std::string Name; -}; - -#endif diff --git a/Source/cmDepends.cxx b/Source/cmDepends.cxx index 69ff858..19558fa 100644 --- a/Source/cmDepends.cxx +++ b/Source/cmDepends.cxx @@ -25,7 +25,7 @@ cmDepends::cmDepends(cmLocalGenerator* lg, const char* targetDir): Verbose(false), FileComparison(0), TargetDirectory(targetDir), - MaxPath(cmSystemTools::GetMaximumFilePathLength()), + MaxPath(16384), Dependee(new char[MaxPath]), Depender(new char[MaxPath]) { diff --git a/Source/cmDependsC.cxx b/Source/cmDependsC.cxx index 942cb3f..a76b3af 100644 --- a/Source/cmDependsC.cxx +++ b/Source/cmDependsC.cxx @@ -448,6 +448,7 @@ void cmDependsC::Scan(std::istream& is, const char* directory, // Get the file being included. UnscannedEntry entry; entry.FileName = this->IncludeRegexLine.match(2); + cmSystemTools::ConvertToUnixSlashes(entry.FileName); if(this->IncludeRegexLine.match(3) == "\"" && !cmSystemTools::FileIsFullPath(entry.FileName.c_str())) { diff --git a/Source/cmDependsFortran.cxx b/Source/cmDependsFortran.cxx index 961d291..9e4726c 100644 --- a/Source/cmDependsFortran.cxx +++ b/Source/cmDependsFortran.cxx @@ -442,9 +442,11 @@ cmDependsFortran for(std::set<cmStdString>::const_iterator i = info.Includes.begin(); i != info.Includes.end(); ++i) { - makeDepends << obj << ": " - << cmSystemTools::ConvertToOutputPath(i->c_str()).c_str() - << std::endl; + makeDepends << obj << ": " << + this->LocalGenerator->Convert(i->c_str(), + cmLocalGenerator::HOME_OUTPUT, + cmLocalGenerator::MAKEFILE) + << std::endl; internalDepends << " " << i->c_str() << std::endl; } makeDepends << std::endl; @@ -491,7 +493,7 @@ cmDependsFortran std::string stampFile = this->LocalGenerator->Convert(required->second.c_str(), cmLocalGenerator::HOME_OUTPUT, - cmLocalGenerator::SHELL); + cmLocalGenerator::MAKEFILE); makeDepends << obj << ": " << stampFile << "\n"; } else @@ -504,7 +506,7 @@ cmDependsFortran module = this->LocalGenerator->Convert(module.c_str(), cmLocalGenerator::HOME_OUTPUT, - cmLocalGenerator::SHELL); + cmLocalGenerator::MAKEFILE); makeDepends << obj << ": " << module << "\n"; } } diff --git a/Source/cmDocumentCompileDefinitions.h b/Source/cmDocumentCompileDefinitions.h new file mode 100644 index 0000000..ef3b3e7 --- /dev/null +++ b/Source/cmDocumentCompileDefinitions.h @@ -0,0 +1,34 @@ +/*============================================================================ + CMake - Cross Platform Makefile Generator + Copyright 2000-2011 Kitware, Inc., Insight Software Consortium + + Distributed under the OSI-approved BSD License (the "License"); + see accompanying file Copyright.txt for details. + + This software is distributed WITHOUT ANY WARRANTY; without even the + implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the License for more information. +============================================================================*/ +#ifndef cmDocumentCompileDefinitions_h +#define cmDocumentCompileDefinitions_h + +#define CM_DOCUMENT_COMPILE_DEFINITIONS_DISCLAIMER \ + "Disclaimer: Most native build tools have poor support for escaping " \ + "certain values. CMake has work-arounds for many cases but some " \ + "values may just not be possible to pass correctly. If a value " \ + "does not seem to be escaped correctly, do not attempt to " \ + "work-around the problem by adding escape sequences to the value. " \ + "Your work-around may break in a future version of CMake that " \ + "has improved escape support. Instead consider defining the macro " \ + "in a (configured) header file. Then report the limitation. " \ + "Known limitations include:\n" \ + " # - broken almost everywhere\n" \ + " ; - broken in VS IDE and Borland Makefiles\n" \ + " , - broken in VS IDE\n" \ + " % - broken in some cases in NMake\n" \ + " & | - broken in some cases on MinGW\n" \ + " ^ < > \\\" - broken in most Make tools on Windows\n" \ + "CMake does not reject these values outright because they do work " \ + "in some cases. Use with caution. " + +#endif diff --git a/Source/cmDocumentGeneratorExpressions.h b/Source/cmDocumentGeneratorExpressions.h new file mode 100644 index 0000000..5359013 --- /dev/null +++ b/Source/cmDocumentGeneratorExpressions.h @@ -0,0 +1,30 @@ +/*============================================================================ + CMake - Cross Platform Makefile Generator + Copyright 2000-2010 Kitware, Inc., Insight Software Consortium + + Distributed under the OSI-approved BSD License (the "License"); + see accompanying file Copyright.txt for details. + + This software is distributed WITHOUT ANY WARRANTY; without even the + implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the License for more information. +============================================================================*/ +#ifndef cmDocumentGeneratorExpressions_h +#define cmDocumentGeneratorExpressions_h + +#define CM_DOCUMENT_COMMAND_GENERATOR_EXPRESSIONS \ + "Generator expressions are evaluted during build system generation " \ + "to produce information specific to each build configuration. " \ + "Valid expressions are:\n" \ + " $<CONFIGURATION> = configuration name\n" \ + " $<TARGET_FILE:tgt> = main file (.exe, .so.1.2, .a)\n" \ + " $<TARGET_LINKER_FILE:tgt> = file used to link (.a, .lib, .so)\n" \ + " $<TARGET_SONAME_FILE:tgt> = file with soname (.so.3)\n" \ + "where \"tgt\" is the name of a target. " \ + "Target file expressions produce a full path, but _DIR and _NAME " \ + "versions can produce the directory and file name components:\n" \ + " $<TARGET_FILE_DIR:tgt>/$<TARGET_FILE_NAME:tgt>\n" \ + " $<TARGET_LINKER_FILE_DIR:tgt>/$<TARGET_LINKER_FILE_NAME:tgt>\n" \ + " $<TARGET_SONAME_FILE_DIR:tgt>/$<TARGET_SONAME_FILE_NAME:tgt>\n" + +#endif diff --git a/Source/cmDocumentVariables.cxx b/Source/cmDocumentVariables.cxx index 091d688..e9b54d8 100644 --- a/Source/cmDocumentVariables.cxx +++ b/Source/cmDocumentVariables.cxx @@ -2,7 +2,7 @@ #include "cmake.h" void cmDocumentVariables::DefineVariables(cmake* cm) -{ +{ // Subsection: variables defined by cmake, that give // information about the project, and cmake cm->DefineProperty @@ -18,21 +18,21 @@ void cmDocumentVariables::DefineVariables(cmake* cm) "This is the full path to the CMake executable cmake which is " "useful from custom commands that want to use the cmake -E " "option for portable system commands. " - "(e.g. /usr/local/bin/cmake", false, + "(e.g. /usr/local/bin/cmake", false, "Variables that Provide Information"); cm->DefineProperty ("CMAKE_BINARY_DIR", cmProperty::VARIABLE, "The path to the top level of the build tree.", "This is the full path to the top level of the current CMake " "build tree. For an in-source build, this would be the same " - "as CMAKE_SOURCE_DIR. ", false, + "as CMAKE_SOURCE_DIR. ", false, "Variables that Provide Information"); cm->DefineProperty ("CMAKE_SOURCE_DIR", cmProperty::VARIABLE, "The path to the top level of the source tree.", "This is the full path to the top level of the current CMake " "source tree. For an in-source build, this would be the same " - "as CMAKE_BINARY_DIR. ", false, + "as CMAKE_BINARY_DIR. ", false, "Variables that Provide Information"); cm->DefineProperty ("CMAKE_CURRENT_BINARY_DIR", cmProperty::VARIABLE, @@ -42,13 +42,13 @@ void cmDocumentVariables::DefineVariables(cmake* cm) "add_subdirectory will create a binary directory in the build " "tree, and as it is being processed this variable will be set. " "For in-source builds this is the current source directory " - "being processed.", false, + "being processed.", false, "Variables that Provide Information"); cm->DefineProperty ("CMAKE_CURRENT_SOURCE_DIR", cmProperty::VARIABLE, "The path to the source directory currently being processed.", "This the full path to the source directory that is currently " - "being processed by cmake. ", false, + "being processed by cmake. ", false, "Variables that Provide Information"); cm->DefineProperty @@ -74,8 +74,28 @@ void cmDocumentVariables::DefineVariables(cmake* cm) ("CMAKE_CURRENT_LIST_LINE", cmProperty::VARIABLE, "The line number of the current file being processed.", "This is the line number of the file currently being" - " processed by cmake.", false, + " processed by cmake.", false, "Variables that Provide Information"); + + cm->DefineProperty + ("CMAKE_CURRENT_LIST_DIR", cmProperty::VARIABLE, + "Full directory of the listfile currently being processed.", + "As CMake processes the listfiles in your project this " + "variable will always be set to the directory where the listfile which " + "is currently being processed (CMAKE_CURRENT_LIST_FILE) is located. " + "The value has dynamic scope. " + "When CMake starts processing commands in a source file " + "it sets this variable to the directory where this file is located. " + "When CMake finishes processing commands from the file it " + "restores the previous value. " + "Therefore the value of the variable inside a macro or " + "function is the directory of the file invoking the bottom-most entry on " + "the call stack, not the directory of the file containing the macro or " + "function definition." + "\n" + "See also CMAKE_CURRENT_LIST_FILE.",false, + "Variables that Provide Information"); + cm->DefineProperty ("CMAKE_BUILD_TOOL", cmProperty::VARIABLE, "Tool used for the actual build process.", @@ -87,7 +107,7 @@ void cmDocumentVariables::DefineVariables(cmake* cm) "and for Visual Studio 7 it set to devenv. For " "Nmake Makefiles the value is nmake. This can be " "useful for adding special flags and commands based" - " on the final build environment. ", false, + " on the final build environment. ", false, "Variables that Provide Information"); cm->DefineProperty ("CMAKE_CROSSCOMPILING", cmProperty::VARIABLE, @@ -101,7 +121,7 @@ void cmDocumentVariables::DefineVariables(cmake* cm) "The directory with the CMakeCache.txt file.", "This is the full path to the directory that has the " "CMakeCache.txt file in it. This is the same as " - "CMAKE_BINARY_DIR.", false, + "CMAKE_BINARY_DIR.", false, "Variables that Provide Information"); cm->DefineProperty ("CMAKE_CACHE_MAJOR_VERSION", cmProperty::VARIABLE, @@ -109,7 +129,7 @@ void cmDocumentVariables::DefineVariables(cmake* cm) "This is stores the major version of CMake used to " "write a CMake cache file. It is only different when " "a different version of CMake is run on a previously " - "created cache file.", false, + "created cache file.", false, "Variables that Provide Information"); cm->DefineProperty ("CMAKE_CACHE_MINOR_VERSION", cmProperty::VARIABLE, @@ -117,18 +137,18 @@ void cmDocumentVariables::DefineVariables(cmake* cm) "This is stores the minor version of CMake used to " "write a CMake cache file. It is only different when " "a different version of CMake is run on a previously " - "created cache file.", false, + "created cache file.", false, "Variables that Provide Information"); - + cm->DefineProperty ("CMAKE_CACHE_PATCH_VERSION", cmProperty::VARIABLE, "Patch version of CMake used to create the CMakeCache.txt file", "This is stores the patch version of CMake used to " "write a CMake cache file. It is only different when " "a different version of CMake is run on a previously " - "created cache file.", false, + "created cache file.", false, "Variables that Provide Information"); - + cm->DefineProperty ("CMAKE_CFG_INTDIR", cmProperty::VARIABLE, "Build-time reference to per-configuration output subdirectory.", @@ -168,7 +188,7 @@ void cmDocumentVariables::DefineVariables(cmake* cm) "is passed as the value of preprocessor symbol \"CMAKE_INTDIR\" to " "the compilation of all source files.",false, "Variables that Provide Information"); - + cm->DefineProperty ("CMAKE_CTEST_COMMAND", cmProperty::VARIABLE, "Full path to ctest command installed with cmake.", @@ -251,12 +271,22 @@ void cmDocumentVariables::DefineVariables(cmake* cm) " executable being run.",false, "Variables that Provide Information"); cm->DefineProperty + ("CMAKE_TWEAK_VERSION", cmProperty::VARIABLE, + "The tweak version of cmake (i.e. the 1 in X.X.X.1).", + "This specifies the tweak version of the CMake executable being run. " + "Releases use tweak < 20000000 and development versions use the date " + "format CCYYMMDD for the tweak level." + ,false, "Variables that Provide Information"); + cm->DefineProperty ("CMAKE_VERSION", cmProperty::VARIABLE, - "The full version of cmake in major.minor.patch format.", + "The full version of cmake in major.minor.patch[.tweak[-id]] format.", "This specifies the full version of the CMake executable being run. " "This variable is defined by versions 2.6.3 and higher. " - "See variables CMAKE_MAJOR_VERSION, CMAKE_MINOR_VERSION, and " - "CMAKE_PATCH_VERSION for individual version components.", false, + "See variables CMAKE_MAJOR_VERSION, CMAKE_MINOR_VERSION, " + "CMAKE_PATCH_VERSION, and CMAKE_TWEAK_VERSION " + "for individual version components. " + "The [-id] component appears in non-release versions " + "and may be arbitrary text.", false, "Variables that Provide Information"); cm->DefineProperty @@ -432,8 +462,27 @@ void cmDocumentVariables::DefineVariables(cmake* cm) "Variables that Provide Information"); - // Variables defined by cmake, that change the behavior + // Variables defined by cmake, that change the behavior // of cmake + + cm->DefineProperty + ("CMAKE_POLICY_DEFAULT_CMP<NNNN>", cmProperty::VARIABLE, + "Default for CMake Policy CMP<NNNN> when it is otherwise left unset.", + "Commands cmake_minimum_required(VERSION) and cmake_policy(VERSION) " + "by default leave policies introduced after the given version unset. " + "Set CMAKE_POLICY_DEFAULT_CMP<NNNN> to OLD or NEW to specify the " + "default for policy CMP<NNNN>, where <NNNN> is the policy number." + "\n" + "This variable should not be set by a project in CMake code; " + "use cmake_policy(SET) instead. " + "Users running CMake may set this variable in the cache " + "(e.g. -DCMAKE_POLICY_DEFAULT_CMP<NNNN>=<OLD|NEW>) " + "to set a policy not otherwise set by the project. " + "Set to OLD to quiet a policy warning while using old behavior " + "or to NEW to try building the project with new behavior.", + false, + "Variables That Change Behavior"); + cm->DefineProperty ("CMAKE_FIND_LIBRARY_PREFIXES", cmProperty::VARIABLE, "Prefixes to prepend when looking for libraries.", @@ -515,10 +564,10 @@ void cmDocumentVariables::DefineVariables(cmake* cm) cm->DefineProperty ("CMAKE_MODULE_PATH", cmProperty::VARIABLE, - "Path to look for cmake modules to load.", - "Specifies a path to override the default search path for " - "CMake modules. For example include commands will look " - "in this path first for modules to include.", + "List of directories to search for CMake modules.", + "Commands like include() and find_package() search for files in " + "directories listed by this variable before checking the default " + "modules that come with CMake.", false, "Variables That Change Behavior"); @@ -577,7 +626,39 @@ void cmDocumentVariables::DefineVariables(cmake* cm) "directories for the current system. It is NOT intended " "to be modified by the project, use CMAKE_PREFIX_PATH for this. See also " "CMAKE_SYSTEM_INCLUDE_PATH, CMAKE_SYSTEM_LIBRARY_PATH, " - "CMAKE_SYSTEM_PROGRAM_PATH.", false, + "CMAKE_SYSTEM_PROGRAM_PATH, and CMAKE_SYSTEM_IGNORE_PATH.", false, + "Variables That Change Behavior"); + + cm->DefineProperty + ("CMAKE_SYSTEM_IGNORE_PATH", cmProperty::VARIABLE, + "Path to be ignored by FIND_XXX() commands.", + "Specifies directories to be ignored by searches in FIND_XXX() commands " + "This is useful in cross-compiled environments where some system " + "directories contain incompatible but possibly linkable libraries. For " + "example, on cross-compiled cluster environments, this allows a user to " + "ignore directories containing libraries meant for the front-end " + "machine that modules like FindX11 (and others) would normally search. " + "By default this contains a list of directories containing incompatible " + "binaries for the host system. " + "See also CMAKE_SYSTEM_PREFIX_PATH, CMAKE_SYSTEM_LIBRARY_PATH, " + "CMAKE_SYSTEM_INCLUDE_PATH, and CMAKE_SYSTEM_PROGRAM_PATH.", false, + "Variables That Change Behavior"); + + cm->DefineProperty + ("CMAKE_IGNORE_PATH", cmProperty::VARIABLE, + "Path to be ignored by FIND_XXX() commands.", + "Specifies directories to be ignored by searches in FIND_XXX() commands " + "This is useful in cross-compiled environments where some system " + "directories contain incompatible but possibly linkable libraries. For " + "example, on cross-compiled cluster environments, this allows a user to " + "ignore directories containing libraries meant for the front-end " + "machine that modules like FindX11 (and others) would normally search. " + "By default this is empty; it is intended to be set by the project. " + "Note that CMAKE_IGNORE_PATH takes a list of directory names, NOT a " + "list of prefixes. If you want to ignore paths under prefixes (bin, " + "include, lib, etc.), you'll need to specify them explicitly. " + "See also CMAKE_PREFIX_PATH, CMAKE_LIBRARY_PATH, CMAKE_INCLUDE_PATH, " + "CMAKE_PROGRAM_PATH.", false, "Variables That Change Behavior"); cm->DefineProperty @@ -598,7 +679,7 @@ void cmDocumentVariables::DefineVariables(cmake* cm) "will check each of the contained directories for the existence of the " "library which is currently searched. By default it contains the " "standard directories for the current system. It is NOT intended to be " - "modified by the project, use CMAKE_SYSTEM_LIBRARY_PATH for this. See " + "modified by the project, use CMAKE_LIBRARY_PATH for this. See " "also CMAKE_SYSTEM_PREFIX_PATH.", false, "Variables That Change Behavior"); @@ -623,7 +704,7 @@ void cmDocumentVariables::DefineVariables(cmake* cm) "to override any variables that need to be changed " "for some special project. ",false, "Variables That Change Behavior"); - + cm->DefineProperty ("BUILD_SHARED_LIBS", cmProperty::VARIABLE, "Global flag to cause add_library to create shared libraries if on.", @@ -634,14 +715,14 @@ void cmDocumentVariables::DefineVariables(cmake* cm) "they want to build the project using shared or static " "libraries.",false, "Variables That Change Behavior"); - + cm->DefineProperty ("CMAKE_NOT_USING_CONFIG_FLAGS", cmProperty::VARIABLE, "Skip _BUILD_TYPE flags if true.", "This is an internal flag used by the generators in " "CMake to tell CMake to skip the _BUILD_TYPE flags.",false, "Variables That Change Behavior"); - + cm->DefineProperty ("CMAKE_MFC_FLAG", cmProperty::VARIABLE, "Tell cmake to use MFC for an executable or dll.", @@ -732,19 +813,19 @@ void cmDocumentVariables::DefineVariables(cmake* cm) "True if running on Mac OSX.", "Set to true on Mac OSX.",false, "Variables That Describe the System"); - + cm->DefineProperty ("BORLAND", cmProperty::VARIABLE, "True of the borland compiler is being used.", "This is set to true if the Borland compiler is being used.",false, "Variables That Describe the System"); - + cm->DefineProperty ("CYGWIN", cmProperty::VARIABLE, "True for cygwin.", "Set to true when using CYGWIN.",false, "Variables That Describe the System"); - + cm->DefineProperty ("MSVC", cmProperty::VARIABLE, "True when using Microsoft Visual C", @@ -796,7 +877,7 @@ void cmDocumentVariables::DefineVariables(cmake* cm) "Set to true when the target system is UNIX or UNIX like " "(i.e. APPLE and CYGWIN).",false, "Variables That Describe the System"); - + cm->DefineProperty ("WIN32", cmProperty::VARIABLE, "True on windows systems, including win64.", @@ -823,7 +904,7 @@ void cmDocumentVariables::DefineVariables(cmake* cm) "Set to true when the host system is UNIX or UNIX like " "(i.e. APPLE and CYGWIN).",false, "Variables That Describe the System"); - + cm->DefineProperty ("CMAKE_HOST_WIN32", cmProperty::VARIABLE, "True on windows systems, including win64.", @@ -848,7 +929,7 @@ void cmDocumentVariables::DefineVariables(cmake* cm) "The value must be an integer no less than 128.",false, "Variables That Describe the System"); - // Variables that affect the building of object files and + // Variables that affect the building of object files and // targets. // cm->DefineProperty @@ -1040,6 +1121,14 @@ void cmDocumentVariables::DefineVariables(cmake* cm) "this variable for a target if they are set. " "Library targets are otherwise placed in this directory.",false, "Variables that Control the Build"); + cm->DefineProperty + ("CMAKE_TRY_COMPILE_CONFIGURATION", cmProperty::VARIABLE, + "Build configuration used for try_compile and try_run projects.", + "Projects built by try_compile and try_run are built " + "synchronously during the CMake configuration step. " + "Therefore a specific build configuration must be chosen even " + "if the generated build system supports multiple configurations.",false, + "Variables that Control the Build"); // Variables defined when the a language is enabled These variables will @@ -1064,7 +1153,7 @@ void cmDocumentVariables::DefineVariables(cmake* cm) "This is the command that will be used as the <LANG> compiler. " "Once set, you can not change this variable.",false, "Variables for Languages"); - + cm->DefineProperty ("CMAKE_<LANG>_COMPILER_ID", cmProperty::VARIABLE, "An internal variable subject to change.", @@ -1108,54 +1197,54 @@ void cmDocumentVariables::DefineVariables(cmake* cm) "If the selected <LANG> compiler is the GNU " "compiler then this is TRUE, if not it is FALSE.",false, "Variables for Languages"); - + cm->DefineProperty ("CMAKE_<LANG>_FLAGS_DEBUG", cmProperty::VARIABLE, "Flags for Debug build type or configuration.", "<LANG> flags used when CMAKE_BUILD_TYPE is Debug.",false, "Variables for Languages"); - + cm->DefineProperty ("CMAKE_<LANG>_FLAGS_MINSIZEREL", cmProperty::VARIABLE, "Flags for MinSizeRel build type or configuration.", "<LANG> flags used when CMAKE_BUILD_TYPE is MinSizeRel." "Short for minimum size release.",false, "Variables for Languages"); - + cm->DefineProperty ("CMAKE_<LANG>_FLAGS_RELEASE", cmProperty::VARIABLE, "Flags for Release build type or configuration.", "<LANG> flags used when CMAKE_BUILD_TYPE is Release",false, "Variables for Languages"); - + cm->DefineProperty ("CMAKE_<LANG>_FLAGS_RELWITHDEBINFO", cmProperty::VARIABLE, "Flags for RelWithDebInfo type or configuration.", "<LANG> flags used when CMAKE_BUILD_TYPE is RelWithDebInfo. " "Short for Release With Debug Information.",false, "Variables for Languages"); - + cm->DefineProperty ("CMAKE_<LANG>_COMPILE_OBJECT", cmProperty::VARIABLE, "Rule variable to compile a single object file.", "This is a rule variable that tells CMake how to " "compile a single object file for for the language <LANG>.",false, "Variables for Languages"); - + cm->DefineProperty ("CMAKE_<LANG>_CREATE_SHARED_LIBRARY", cmProperty::VARIABLE, "Rule variable to create a shared library.", "This is a rule variable that tells CMake how to " "create a shared library for the language <LANG>.",false, "Variables for Languages"); - + cm->DefineProperty ("CMAKE_<LANG>_CREATE_SHARED_MODULE", cmProperty::VARIABLE, "Rule variable to create a shared module.", "This is a rule variable that tells CMake how to " "create a shared library for the language <LANG>.",false, "Variables for Languages"); - + cm->DefineProperty ("CMAKE_<LANG>_CREATE_STATIC_LIBRARY", cmProperty::VARIABLE, "Rule variable to create a static library.", @@ -1247,20 +1336,20 @@ void cmDocumentVariables::DefineVariables(cmake* cm) "See also the CMAKE_<LANG>_LINKER_PREFERENCE_PROPAGATES variable.", false, "Variables for Languages"); - + cm->DefineProperty ("CMAKE_<LANG>_LINK_EXECUTABLE ", cmProperty::VARIABLE, "Rule variable to link and executable.", "Rule variable to link and executable for the given language.",false, "Variables for Languages"); - + cm->DefineProperty ("CMAKE_<LANG>_OUTPUT_EXTENSION", cmProperty::VARIABLE, "Extension for the output of a compile for a single file.", "This is the extension for an object file for " "the given <LANG>. For example .obj for C on Windows.",false, "Variables for Languages"); - + cm->DefineProperty ("CMAKE_<LANG>_SOURCE_FILE_EXTENSIONS", cmProperty::VARIABLE, "Extensions of source files for the given language.", @@ -1274,17 +1363,40 @@ void cmDocumentVariables::DefineVariables(cmake* cm) "this variable is defined to 1.", false,"Variables for Languages"); + cm->DefineProperty( + "CMAKE_Fortran_MODDIR_FLAG", cmProperty::VARIABLE, + "Fortran flag for module output directory.", + "This stores the flag needed to pass the value of the " + "Fortran_MODULE_DIRECTORY target property to the compiler.", + false,"Variables for Languages"); + + cm->DefineProperty( + "CMAKE_Fortran_MODDIR_DEFAULT", cmProperty::VARIABLE, + "Fortran default module output directory.", + "Most Fortran compilers write .mod files to the current working " + "directory. " + "For those that do not, this is set to \".\" and used when the " + "Fortran_MODULE_DIRECTORY target property is not set.", + false,"Variables for Languages"); + + cm->DefineProperty( + "CMAKE_Fortran_MODOUT_FLAG", cmProperty::VARIABLE, + "Fortran flag to enable module output.", + "Most Fortran compilers write .mod files out by default. " + "For others, this stores the flag needed to enable module output.", + false,"Variables for Languages"); + // variables that are used by cmake but not to be documented - cm->DefineProperty("CMAKE_MATCH_0", cmProperty::VARIABLE,0,0); - cm->DefineProperty("CMAKE_MATCH_1", cmProperty::VARIABLE,0,0); - cm->DefineProperty("CMAKE_MATCH_2", cmProperty::VARIABLE,0,0); - cm->DefineProperty("CMAKE_MATCH_3", cmProperty::VARIABLE,0,0); - cm->DefineProperty("CMAKE_MATCH_4", cmProperty::VARIABLE,0,0); - cm->DefineProperty("CMAKE_MATCH_5", cmProperty::VARIABLE,0,0); - cm->DefineProperty("CMAKE_MATCH_6", cmProperty::VARIABLE,0,0); - cm->DefineProperty("CMAKE_MATCH_7", cmProperty::VARIABLE,0,0); - cm->DefineProperty("CMAKE_MATCH_8", cmProperty::VARIABLE,0,0); - cm->DefineProperty("CMAKE_MATCH_9", cmProperty::VARIABLE,0,0); + cm->DefineProperty("CMAKE_MATCH_0", cmProperty::VARIABLE,0,0); + cm->DefineProperty("CMAKE_MATCH_1", cmProperty::VARIABLE,0,0); + cm->DefineProperty("CMAKE_MATCH_2", cmProperty::VARIABLE,0,0); + cm->DefineProperty("CMAKE_MATCH_3", cmProperty::VARIABLE,0,0); + cm->DefineProperty("CMAKE_MATCH_4", cmProperty::VARIABLE,0,0); + cm->DefineProperty("CMAKE_MATCH_5", cmProperty::VARIABLE,0,0); + cm->DefineProperty("CMAKE_MATCH_6", cmProperty::VARIABLE,0,0); + cm->DefineProperty("CMAKE_MATCH_7", cmProperty::VARIABLE,0,0); + cm->DefineProperty("CMAKE_MATCH_8", cmProperty::VARIABLE,0,0); + cm->DefineProperty("CMAKE_MATCH_9", cmProperty::VARIABLE,0,0); cm->DefineProperty("CMAKE_<LANG>_COMPILER_ARG1", cmProperty::VARIABLE,0,0); @@ -1314,6 +1426,8 @@ void cmDocumentVariables::DefineVariables(cmake* cm) cmProperty::VARIABLE,0,0); cm->DefineProperty("CMAKE_<LANG>_LINK_FLAGS", cmProperty::VARIABLE,0,0); + cm->DefineProperty("CMAKE_<LANG>_RESPONSE_FILE_LINK_FLAG", + cmProperty::VARIABLE,0,0); cm->DefineProperty("CMAKE_<LANG>_STANDARD_LIBRARIES", cmProperty::VARIABLE,0,0); cm->DefineProperty("CMAKE_<LANG>_STANDARD_LIBRARIES_INIT", @@ -1388,4 +1502,6 @@ void cmDocumentVariables::DefineVariables(cmake* cm) cmProperty::VARIABLE,0,0); cm->DefineProperty("CMAKE_LINK_DEPENDENT_LIBRARY_DIRS", cmProperty::VARIABLE,0,0); + cm->DefineProperty("CMAKE_MAKE_INCLUDE_FROM_ROOT", + cmProperty::VARIABLE,0,0); } diff --git a/Source/cmDocumentation.cxx b/Source/cmDocumentation.cxx index fc2fb14..bfe11c1 100644 --- a/Source/cmDocumentation.cxx +++ b/Source/cmDocumentation.cxx @@ -606,20 +606,22 @@ bool cmDocumentation::CreateSingleModule(const char* fname, } else { - if(text.length() < 2 && brief.length() == 1) - { - return false; - } - char* pname = strcpy(new char[strlen(moduleName)+1], moduleName); - char* ptext = strcpy(new char[text.length()+1], text.c_str()); - this->ModuleStrings.push_back(pname); - this->ModuleStrings.push_back(ptext); - char* pbrief = strcpy(new char[brief.length()+1], brief.c_str()); - this->ModuleStrings.push_back(pbrief); - moduleSection.Append(pname, pbrief, ptext); - return true; + break; } } + + if(text.length() < 2 && brief.length() == 1) + { + return false; + } + + char* pname = strcpy(new char[strlen(moduleName)+1], moduleName); + char* ptext = strcpy(new char[text.length()+1], text.c_str()); + this->ModuleStrings.push_back(pname); + this->ModuleStrings.push_back(ptext); + char* pbrief = strcpy(new char[brief.length()+1], brief.c_str()); + this->ModuleStrings.push_back(pbrief); + moduleSection.Append(pname, pbrief, ptext); return true; } @@ -1177,11 +1179,18 @@ bool cmDocumentation::PrintDocumentationSingleModule(std::ostream& os) this->CurrentArgument.c_str(), *this->AllSections["Modules"])) { - this->PrintDocumentationCommand - (os, this->AllSections["Modules"]->GetEntries()[0]); - os << "\n Defined in: "; - os << moduleName << "\n"; - return true; + if(this->AllSections["Modules"]->GetEntries().size()) + { + this->PrintDocumentationCommand + (os, this->AllSections["Modules"]->GetEntries()[0]); + os << "\n Defined in: "; + os << moduleName << "\n"; + return true; + } + else + { + return false; + } } } diff --git a/Source/cmDocumentationFormatterHTML.cxx b/Source/cmDocumentationFormatterHTML.cxx index 09aff8d..6ced1e4 100644 --- a/Source/cmDocumentationFormatterHTML.cxx +++ b/Source/cmDocumentationFormatterHTML.cxx @@ -39,7 +39,7 @@ static void cmDocumentationPrintHTMLChar(std::ostream& os, char c) os << "&"; break; case '\n': - os << "<br>"; + os << "<br />"; break; default: os << c; @@ -125,23 +125,33 @@ void cmDocumentationFormatterHTML { if (name) { - os << "<h2><a name=\"section_" << name << "\"/>" << name << "</h2>\n"; + os << "<h2><a name=\"section_"; + cmDocumentationPrintHTMLId(os, name); + os << "\"/>" << name << "</h2>\n"; } - os << "<ul>\n"; + // Is a list needed? for(std::vector<cmDocumentationEntry>::const_iterator op = entries.begin(); op != entries.end(); ++ op ) { - if(op->Name.size()) - { - os << " <li><a href=\"#" << prefix << ":"; - cmDocumentationPrintHTMLId(os, op->Name.c_str()); - os << "\"><b><code>"; - this->PrintHTMLEscapes(os, op->Name.c_str()); - os << "</code></b></a></li>"; - } + if (op->Name.size()) + { + os << "<ul>\n"; + for(;op != entries.end() && op->Name.size(); ++op) + { + if(op->Name.size()) + { + os << " <li><a href=\"#" << prefix << ":"; + cmDocumentationPrintHTMLId(os, op->Name.c_str()); + os << "\"><b><code>"; + this->PrintHTMLEscapes(os, op->Name.c_str()); + os << "</code></b></a></li>"; + } + } + os << "</ul>\n" ; + break; // Skip outer loop termination test + } } - os << "</ul>\n" ; } for(std::vector<cmDocumentationEntry>::const_iterator op = entries.begin(); @@ -164,7 +174,7 @@ void cmDocumentationFormatterHTML this->PrintHTMLEscapes(os, op->Brief.c_str()); if(op->Full.size()) { - os << "<br>\n "; + os << "<br />\n "; this->PrintFormatted(os, op->Full.c_str()); } os << "\n"; @@ -194,6 +204,7 @@ void cmDocumentationFormatterHTML::PrintParagraph(std::ostream& os, { os << "<p>"; this->PrintHTMLEscapes(os, text); + os << "</p>\n"; } //---------------------------------------------------------------------------- @@ -201,7 +212,12 @@ void cmDocumentationFormatterHTML::PrintHeader(const char* docname, const char* appname, std::ostream& os) { - os << "<html><head><title>"; + os << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"" + << " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n"; + os << "<html xmlns=\"http://www.w3.org/1999/xhtml\"" + << " xml:lang=\"en\" lang=\"en\">\n"; + os << "<head><meta http-equiv=\"Content-Type\" " + << "content=\"text/html;charset=utf-8\" /><title>"; os << docname << " - " << appname; os << "</title></head><body>\n"; } @@ -253,16 +269,20 @@ void cmDocumentationFormatterHTML return; } - os << "<h2><a name=\"section_Index\"/>Master Index " + os << "<h2><a name=\"section_Index\">Master Index " << "CMake " << cmVersion::GetCMakeVersion() - << "</h2>\n"; - os << "<ul>\n"; - for(unsigned int i=0; i < sections.size(); ++i) + << "</a></h2>\n"; + + if (!sections.empty()) { - std::string name = sections[i]-> - GetName((this->GetForm())); - os << " <li><a href=\"#section_" - << name << "\"<b>" << name << "</b></a></li>\n"; + os << "<ul>\n"; + for(unsigned int i=0; i < sections.size(); ++i) + { + std::string name = sections[i]->GetName((this->GetForm())); + os << " <li><a href=\"#section_"; + cmDocumentationPrintHTMLId(os, name.c_str()); + os << "\"><b>" << name << "</b></a></li>\n"; + } + os << "</ul>\n"; } - os << "</ul>\n"; } diff --git a/Source/cmDocumentationFormatterText.cxx b/Source/cmDocumentationFormatterText.cxx index 078b890..0b04b73 100644 --- a/Source/cmDocumentationFormatterText.cxx +++ b/Source/cmDocumentationFormatterText.cxx @@ -96,7 +96,7 @@ void cmDocumentationFormatterText::PrintColumn(std::ostream& os, { // Print text arranged in an indented column of fixed witdh. const char* l = text; - int column = 0; + long column = 0; bool newSentence = false; bool firstLine = true; int width = this->TextWidth - static_cast<int>(strlen(this->TextIndent)); diff --git a/Source/cmELF.cxx b/Source/cmELF.cxx index 763fdd8..1158fc0 100644 --- a/Source/cmELF.cxx +++ b/Source/cmELF.cxx @@ -576,7 +576,7 @@ unsigned int cmELFInternalImpl<Types>::GetDynamicEntryCount() return i; } } - return this->DynamicSectionEntries.size(); + return static_cast<unsigned int>(this->DynamicSectionEntries.size()); } //---------------------------------------------------------------------------- @@ -687,7 +687,8 @@ cmELFInternalImpl<Types>::GetDynamicSectionString(int tag) // The value has been read successfully. Report it. se.Position = static_cast<unsigned long>(strtab.sh_offset + first); se.Size = last - first; - se.IndexInSection = di - this->DynamicSectionEntries.begin(); + se.IndexInSection = + static_cast<int>(di - this->DynamicSectionEntries.begin()); return &se; } } diff --git a/Source/cmExportCommand.cxx b/Source/cmExportCommand.cxx index 48c5c6e..cb614d4 100644 --- a/Source/cmExportCommand.cxx +++ b/Source/cmExportCommand.cxx @@ -152,11 +152,10 @@ bool cmExportCommand ebfg.SetCommand(this); // Compute the set of configurations exported. - if(const char* types = - this->Makefile->GetDefinition("CMAKE_CONFIGURATION_TYPES")) + std::vector<std::string> configurationTypes; + this->Makefile->GetConfigurations(configurationTypes); + if(!configurationTypes.empty()) { - std::vector<std::string> configurationTypes; - cmSystemTools::ExpandListArgument(types, configurationTypes); for(std::vector<std::string>::const_iterator ci = configurationTypes.begin(); ci != configurationTypes.end(); ++ci) @@ -164,11 +163,6 @@ bool cmExportCommand ebfg.AddConfiguration(ci->c_str()); } } - else if(const char* config = - this->Makefile->GetDefinition("CMAKE_BUILD_TYPE")) - { - ebfg.AddConfiguration(config); - } else { ebfg.AddConfiguration(""); diff --git a/Source/cmExtraCodeBlocksGenerator.cxx b/Source/cmExtraCodeBlocksGenerator.cxx index 4bedea3..a5650d4 100644 --- a/Source/cmExtraCodeBlocksGenerator.cxx +++ b/Source/cmExtraCodeBlocksGenerator.cxx @@ -23,7 +23,7 @@ #include <cmsys/SystemTools.hxx> /* Some useful URLs: -Homepage: +Homepage: http://www.codeblocks.org File format docs: @@ -63,16 +63,6 @@ cmExtraCodeBlocksGenerator::cmExtraCodeBlocksGenerator() } -void cmExtraCodeBlocksGenerator::SetGlobalGenerator( - cmGlobalGenerator* generator) -{ - cmExternalMakefileProjectGenerator::SetGlobalGenerator(generator); - cmGlobalUnixMakefileGenerator3* mf = (cmGlobalUnixMakefileGenerator3*) - generator; - mf->SetToolSupportsColor(false); - mf->SetForceVerboseMakefiles(true); -} - void cmExtraCodeBlocksGenerator::Generate() { // for each sub project in the project create a codeblocks project @@ -107,7 +97,7 @@ void cmExtraCodeBlocksGenerator::CreateProjectFile( /* Tree is used to create a "Virtual Folder" in CodeBlocks, in which all CMake files this project depends on will be put. This means additionally to the "Sources" and "Headers" virtual folders of CodeBlocks, there will - now also be a "CMake Files" virtual folder. + now also be a "CMake Files" virtual folder. Patch by Daniel Teske <daniel.teske AT nokia.com> (which use C::B project files in QtCreator).*/ struct Tree @@ -115,24 +105,24 @@ struct Tree std::string path; //only one component of the path std::vector<Tree> folders; std::vector<std::string> files; - void InsertPath(const std::vector<std::string>& splitted, - std::vector<std::string>::size_type start, + void InsertPath(const std::vector<std::string>& splitted, + std::vector<std::string>::size_type start, const std::string& fileName); void BuildVirtualFolder(std::string& virtualFolders) const; - void BuildVirtualFolderImpl(std::string& virtualFolders, + void BuildVirtualFolderImpl(std::string& virtualFolders, const std::string& prefix) const; void BuildUnit(std::string& unitString, const std::string& fsPath) const; - void BuildUnitImpl(std::string& unitString, - const std::string& virtualFolderPath, + void BuildUnitImpl(std::string& unitString, + const std::string& virtualFolderPath, const std::string& fsPath) const; }; -void Tree::InsertPath(const std::vector<std::string>& splitted, - std::vector<std::string>::size_type start, +void Tree::InsertPath(const std::vector<std::string>& splitted, + std::vector<std::string>::size_type start, const std::string& fileName) { - if (start == splitted.size()) + if (start == splitted.size()) { files.push_back(fileName); return; @@ -289,14 +279,10 @@ void cmExtraCodeBlocksGenerator std::string fileName = *(splitted.end()-1); splitted.erase(splitted.end() - 1, splitted.end()); - // We don't want paths with ".." in them - // reasons are that we don't want files outside the project - // TODO: the path should be normalized first though // We don't want paths with CMakeFiles in them // or do we? // In speedcrunch those where purely internal if (splitted.size() >= 1 - && relative.find("..") == std::string::npos && relative.find("CMakeFiles") == std::string::npos) { tree.InsertPath(splitted, 1, fileName); @@ -305,7 +291,7 @@ void cmExtraCodeBlocksGenerator } // Now build a virtual tree string - std::string virtualFolders; + std::string virtualFolders; tree.BuildVirtualFolder(virtualFolders); // And one for <Unit> std::string unitFiles; @@ -327,7 +313,7 @@ void cmExtraCodeBlocksGenerator this->AppendTarget(fout, "all", 0, make.c_str(), mf, compiler.c_str()); - // add all executable and library targets and some of the GLOBAL + // add all executable and library targets and some of the GLOBAL // and UTILITY targets for (std::vector<cmLocalGenerator*>::const_iterator lg=lgs.begin(); lg!=lgs.end(); lg++) @@ -342,9 +328,9 @@ void cmExtraCodeBlocksGenerator case cmTarget::GLOBAL_TARGET: { bool insertTarget = false; - // Only add the global targets from CMAKE_BINARY_DIR, + // Only add the global targets from CMAKE_BINARY_DIR, // not from the subdirs - if (strcmp(makefile->GetStartOutputDirectory(), + if (strcmp(makefile->GetStartOutputDirectory(), makefile->GetHomeOutputDirectory())==0) { insertTarget = true; @@ -366,7 +352,7 @@ void cmExtraCodeBlocksGenerator } if (insertTarget) { - this->AppendTarget(fout, ti->first.c_str(), 0, + this->AppendTarget(fout, ti->first.c_str(), 0, make.c_str(), makefile, compiler.c_str()); } } @@ -376,13 +362,13 @@ void cmExtraCodeBlocksGenerator // Experimental-"sub"targets as e.g. NightlyStart if (((ti->first.find("Nightly")==0) &&(ti->first!="Nightly")) || ((ti->first.find("Continuous")==0)&&(ti->first!="Continuous")) - || ((ti->first.find("Experimental")==0) + || ((ti->first.find("Experimental")==0) && (ti->first!="Experimental"))) { break; } - this->AppendTarget(fout, ti->first.c_str(), 0, + this->AppendTarget(fout, ti->first.c_str(), 0, make.c_str(), makefile, compiler.c_str()); break; case cmTarget::EXECUTABLE: @@ -390,11 +376,11 @@ void cmExtraCodeBlocksGenerator case cmTarget::SHARED_LIBRARY: case cmTarget::MODULE_LIBRARY: { - this->AppendTarget(fout, ti->first.c_str(), &ti->second, + this->AppendTarget(fout, ti->first.c_str(), &ti->second, make.c_str(), makefile, compiler.c_str()); std::string fastTarget = ti->first; fastTarget += "/fast"; - this->AppendTarget(fout, fastTarget.c_str(), &ti->second, + this->AppendTarget(fout, fastTarget.c_str(), &ti->second, make.c_str(), makefile, compiler.c_str()); } break; @@ -441,7 +427,7 @@ void cmExtraCodeBlocksGenerator { for(std::vector<std::string>::const_iterator ext = mf->GetSourceExtensions().begin(); - ext != mf->GetSourceExtensions().end(); + ext != mf->GetSourceExtensions().end(); ++ext) { if ((*si)->GetExtension() == *ext) @@ -471,11 +457,11 @@ void cmExtraCodeBlocksGenerator // The following loop tries to add header files matching to implementation // files to the project. It does that by iterating over all source files, - // replacing the file name extension with ".h" and checks whether such a + // replacing the file name extension with ".h" and checks whether such a // file exists. If it does, it is inserted into the map of files. // A very similar version of that code exists also in the kdevelop // project generator. - for (std::map<std::string, cmSourceFile*>::const_iterator + for (std::map<std::string, cmSourceFile*>::const_iterator sit=cFiles.begin(); sit!=cFiles.end(); ++sit) @@ -487,7 +473,7 @@ void cmExtraCodeBlocksGenerator // check if there's a matching header around for(std::vector<std::string>::const_iterator ext = mf->GetHeaderExtensions().begin(); - ext != mf->GetHeaderExtensions().end(); + ext != mf->GetHeaderExtensions().end(); ++ext) { std::string hname=headerBasename; @@ -510,7 +496,7 @@ void cmExtraCodeBlocksGenerator // insert all source files in the CodeBlocks project // first the C/C++ implementation files, then all others - for (std::map<std::string, cmSourceFile*>::const_iterator + for (std::map<std::string, cmSourceFile*>::const_iterator sit=cFiles.begin(); sit!=cFiles.end(); ++sit) @@ -518,7 +504,7 @@ void cmExtraCodeBlocksGenerator fout<<" <Unit filename=\""<< sit->first <<"\">\n" " </Unit>\n"; } - for (std::set<std::string>::const_iterator + for (std::set<std::string>::const_iterator sit=otherFiles.begin(); sit!=otherFiles.end(); ++sit) @@ -545,7 +531,6 @@ void cmExtraCodeBlocksGenerator::AppendTarget(cmGeneratedFileStream& fout, { std::string makefileName = makefile->GetStartOutputDirectory(); makefileName += "/Makefile"; - makefileName = cmSystemTools::ConvertToOutputPath(makefileName.c_str()); fout<<" <Target title=\"" << targetName << "\">\n"; if (target!=0) @@ -582,7 +567,7 @@ void cmExtraCodeBlocksGenerator::AppendTarget(cmGeneratedFileStream& fout, " <Option compiler=\"" << compiler << "\" />\n" " <Compiler>\n"; // the include directories for this target - const std::vector<std::string>& incDirs = + const std::vector<std::string>& incDirs = target->GetMakefile()->GetIncludeDirectories(); for(std::vector<std::string>::const_iterator dirIt=incDirs.begin(); dirIt != incDirs.end(); @@ -594,27 +579,27 @@ void cmExtraCodeBlocksGenerator::AppendTarget(cmGeneratedFileStream& fout, } else // e.g. all and the GLOBAL and UTILITY targets { - fout<<" <Option working_dir=\"" + fout<<" <Option working_dir=\"" << makefile->GetStartOutputDirectory() << "\" />\n" <<" <Option type=\"" << 4 << "\" />\n"; } fout<<" <MakeCommands>\n" - " <Build command=\"" + " <Build command=\"" << this->BuildMakeCommand(make, makefileName.c_str(), targetName) << "\" />\n" - " <CompileFile command=\"" + " <CompileFile command=\"" << this->BuildMakeCommand(make, makefileName.c_str(),""$file"") << "\" />\n" - " <Clean command=\"" - << this->BuildMakeCommand(make, makefileName.c_str(), "clean") + " <Clean command=\"" + << this->BuildMakeCommand(make, makefileName.c_str(), "clean") << "\" />\n" - " <DistClean command=\"" - << this->BuildMakeCommand(make, makefileName.c_str(), "clean") + " <DistClean command=\"" + << this->BuildMakeCommand(make, makefileName.c_str(), "clean") << "\" />\n" " </MakeCommands>\n" " </Target>\n"; - + } @@ -631,8 +616,8 @@ std::string cmExtraCodeBlocksGenerator::GetCBCompilerId(const cmMakefile* mf) std::string hostSystemName = mf->GetSafeDefinition("CMAKE_HOST_SYSTEM_NAME"); std::string systemName = mf->GetSafeDefinition("CMAKE_SYSTEM_NAME"); - std::string compilerId = mf->GetRequiredDefinition(compilerIdVar.c_str()); - std::string compiler = "gcc"; + std::string compilerId = mf->GetSafeDefinition(compilerIdVar.c_str()); + std::string compiler = "gcc"; // default to gcc if (compilerId == "MSVC") { compiler = "msvc8"; @@ -680,7 +665,7 @@ int cmExtraCodeBlocksGenerator::GetCBTargetType(cmTarget* target) { return 2; } - else if ((target->GetType()==cmTarget::SHARED_LIBRARY) + else if ((target->GetType()==cmTarget::SHARED_LIBRARY) || (target->GetType()==cmTarget::MODULE_LIBRARY)) { return 3; @@ -696,23 +681,31 @@ std::string cmExtraCodeBlocksGenerator::BuildMakeCommand( std::string command = make; if (strcmp(this->GlobalGenerator->GetName(), "NMake Makefiles")==0) { + std::string makefileName = cmSystemTools::ConvertToOutputPath(makefile); command += " /NOLOGO /f ""; - command += makefile; + command += makefileName; command += "" "; + command += " VERBOSE=1 "; command += target; } else if (strcmp(this->GlobalGenerator->GetName(), "MinGW Makefiles")==0) { - command += " -f "; - command += makefile; - command += " "; + // no escaping of spaces in this case, see + // http://public.kitware.com/Bug/view.php?id=10014 + std::string makefileName = makefile; + command += " -f ""; + command += makefileName; + command += "" "; + command += " VERBOSE=1 "; command += target; } else { + std::string makefileName = cmSystemTools::ConvertToOutputPath(makefile); command += " -f ""; - command += makefile; + command += makefileName; command += "" "; + command += " VERBOSE=1 "; command += target; } return command; diff --git a/Source/cmExtraCodeBlocksGenerator.h b/Source/cmExtraCodeBlocksGenerator.h index 97a2d24..57751fc 100644 --- a/Source/cmExtraCodeBlocksGenerator.h +++ b/Source/cmExtraCodeBlocksGenerator.h @@ -22,22 +22,19 @@ class cmGeneratedFileStream; /** \class cmExtraCodeBlocksGenerator * \brief Write CodeBlocks project files for Makefile based projects - * - * This generator is in early alpha stage. */ class cmExtraCodeBlocksGenerator : public cmExternalMakefileProjectGenerator { public: cmExtraCodeBlocksGenerator(); - virtual void SetGlobalGenerator(cmGlobalGenerator* generator); virtual const char* GetName() const { return cmExtraCodeBlocksGenerator::GetActualName();} static const char* GetActualName() { return "CodeBlocks";} - static cmExternalMakefileProjectGenerator* New() + static cmExternalMakefileProjectGenerator* New() { return new cmExtraCodeBlocksGenerator; } /** Get the documentation entry for this generator. */ - virtual void GetDocumentation(cmDocumentationEntry& entry, + virtual void GetDocumentation(cmDocumentationEntry& entry, const char* fullName) const; virtual void Generate(); @@ -49,7 +46,7 @@ private: const std::string& filename); std::string GetCBCompilerId(const cmMakefile* mf); int GetCBTargetType(cmTarget* target); - std::string BuildMakeCommand(const std::string& make, const char* makefile, + std::string BuildMakeCommand(const std::string& make, const char* makefile, const char* target); void AppendTarget(cmGeneratedFileStream& fout, const char* targetName, diff --git a/Source/cmExtraEclipseCDT4Generator.cxx b/Source/cmExtraEclipseCDT4Generator.cxx index 8703853..0ef771f 100644 --- a/Source/cmExtraEclipseCDT4Generator.cxx +++ b/Source/cmExtraEclipseCDT4Generator.cxx @@ -43,25 +43,15 @@ void cmExtraEclipseCDT4Generator entry.Name = this->GetName(); entry.Brief = "Generates Eclipse CDT 4.0 project files."; entry.Full = - "Project files for Eclipse will be created in the top directory " - "and will have a linked resource to every subdirectory which " - "features a CMakeLists.txt file containing a PROJECT() call." + "Project files for Eclipse will be created in the top directory. " + "In out of source builds, a linked resource to the top level source " + "directory will be created." "Additionally a hierarchy of makefiles is generated into the " "build tree. The appropriate make program can build the project through " "the default make target. A \"make install\" target is also provided."; } //---------------------------------------------------------------------------- -void cmExtraEclipseCDT4Generator -::SetGlobalGenerator(cmGlobalGenerator* generator) -{ - cmExternalMakefileProjectGenerator::SetGlobalGenerator(generator); - cmGlobalUnixMakefileGenerator3* mf - = static_cast<cmGlobalUnixMakefileGenerator3*>(generator); - mf->SetToolSupportsColor(true); -} - -//---------------------------------------------------------------------------- void cmExtraEclipseCDT4Generator::Generate() { const cmMakefile* mf @@ -73,7 +63,7 @@ void cmExtraEclipseCDT4Generator::Generate() this->IsOutOfSourceBuild = (this->HomeDirectory!=this->HomeOutputDirectory); - this->GenerateSourceProject = (this->IsOutOfSourceBuild && + this->GenerateSourceProject = (this->IsOutOfSourceBuild && mf->IsOn("ECLIPSE_CDT4_GENERATE_SOURCE_PROJECT")); // NOTE: This is not good, since it pollutes the source tree. However, @@ -109,7 +99,7 @@ void cmExtraEclipseCDT4Generator::CreateSourceProjectFile() const return; } - fout << + fout << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<projectDescription>\n" "\t<name>" << name << "</name>\n" @@ -124,10 +114,72 @@ void cmExtraEclipseCDT4Generator::CreateSourceProjectFile() const ; } + +//---------------------------------------------------------------------------- +void cmExtraEclipseCDT4Generator::AddEnvVar(cmGeneratedFileStream& fout, + const char* envVar, cmMakefile* mf) +{ + // get the variables from the environment and from the cache and then + // figure out which one to use: + + const char* envVarValue = getenv(envVar); + + std::string cacheEntryName = "CMAKE_ECLIPSE_ENVVAR_"; + cacheEntryName += envVar; + const char* cacheValue = mf->GetCacheManager()->GetCacheValue( + cacheEntryName.c_str()); + + // now we have both, decide which one to use + std::string valueToUse; + if (envVarValue==0 && cacheValue==0) + { + // nothing known, do nothing + valueToUse = ""; + } + else if (envVarValue!=0 && cacheValue==0) + { + // The variable is in the env, but not in the cache. Use it and put it + // in the cache + valueToUse = envVarValue; + mf->AddCacheDefinition(cacheEntryName.c_str(), valueToUse.c_str(), + cacheEntryName.c_str(), cmCacheManager::STRING, + true); + mf->GetCacheManager()->SaveCache(mf->GetHomeOutputDirectory()); + } + else if (envVarValue==0 && cacheValue!=0) + { + // It is already in the cache, but not in the env, so use it from the cache + valueToUse = cacheValue; + } + else + { + // It is both in the cache and in the env. + // Use the version from the env. except if the value from the env is + // completely contained in the value from the cache (for the case that we + // now have a PATH without MSVC dirs in the env. but had the full PATH with + // all MSVC dirs during the cmake run which stored the var in the cache: + valueToUse = cacheValue; + if (valueToUse.find(envVarValue) == std::string::npos) + { + valueToUse = envVarValue; + mf->AddCacheDefinition(cacheEntryName.c_str(), valueToUse.c_str(), + cacheEntryName.c_str(), cmCacheManager::STRING, + true); + mf->GetCacheManager()->SaveCache(mf->GetHomeOutputDirectory()); + } + } + + if (!valueToUse.empty()) + { + fout << envVar << "=" << valueToUse << "|"; + } +} + + //---------------------------------------------------------------------------- void cmExtraEclipseCDT4Generator::CreateProjectFile() { - const cmMakefile* mf + cmMakefile* mf = this->GlobalGenerator->GetLocalGenerators()[0]->GetMakefile(); const std::string filename = this->HomeOutputDirectory + "/.project"; @@ -138,12 +190,18 @@ void cmExtraEclipseCDT4Generator::CreateProjectFile() return; } - fout << + std::string compilerId = mf->GetSafeDefinition("CMAKE_C_COMPILER_ID"); + if (compilerId.empty()) // no C compiler, try the C++ compiler: + { + compilerId = mf->GetSafeDefinition("CMAKE_CXX_COMPILER_ID"); + } + + fout << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<projectDescription>\n" "\t<name>" << this->GenerateProjectName(mf->GetProjectName(), - mf->GetDefinition("CMAKE_BUILD_TYPE"), + mf->GetSafeDefinition("CMAKE_BUILD_TYPE"), this->GetPathBasename(this->HomeOutputDirectory)) << "</name>\n" "\t<comment></comment>\n" @@ -157,7 +215,7 @@ void cmExtraEclipseCDT4Generator::CreateProjectFile() ; // use clean target - fout << + fout << "\t\t\t\t<dictionary>\n" "\t\t\t\t\t<key>org.eclipse.cdt.make.core.cleanBuildTarget</key>\n" "\t\t\t\t\t<value>clean</value>\n" @@ -178,7 +236,7 @@ void cmExtraEclipseCDT4Generator::CreateProjectFile() // set the make command std::string make = mf->GetRequiredDefinition("CMAKE_MAKE_PROGRAM"); - fout << + fout << "\t\t\t\t<dictionary>\n" "\t\t\t\t\t<key>org.eclipse.cdt.make.core.enabledIncrementalBuild</key>\n" "\t\t\t\t\t<value>true</value>\n" @@ -214,29 +272,23 @@ void cmExtraEclipseCDT4Generator::CreateProjectFile() fout << "\t\t\t\t<dictionary>\n" "\t\t\t\t\t<key>org.eclipse.cdt.make.core.environment</key>\n" - "\t\t\t\t\t<value>VERBOSE=1|</value>\n" // enforce VERBOSE Makefile output - "\t\t\t\t\t<value>" + "\t\t\t\t\t<value>VERBOSE=1|CMAKE_NO_VERBOSE=1|" //verbose Makefile output ; // set vsvars32.bat environment available at CMake time, // but not necessarily when eclipse is open - if (make.find("nmake") != std::string::npos) + if (compilerId == "MSVC") { - if (getenv("PATH")) - { - fout << "PATH=" << getenv("PATH") << "|"; - } - if (getenv("INCLUDE")) - { - fout << "INCLUDE=" << getenv("INCLUDE") << "|"; - } - if (getenv("LIB")) - { - fout << "LIB=" << getenv("LIB") << "|"; - } - if (getenv("LIBPATH")) - { - fout << "LIBPATH=" << getenv("LIBPATH") << "|"; - } + AddEnvVar(fout, "PATH", mf); + AddEnvVar(fout, "INCLUDE", mf); + AddEnvVar(fout, "LIB", mf); + AddEnvVar(fout, "LIBPATH", mf); + } + else if (compilerId == "Intel") + { + // if the env.var is set, use this one and put it in the cache + // if the env.var is not set, but the value is in the cache, + // use it from the cache: + AddEnvVar(fout, "INTEL_LICENSE_FILE", mf); } fout << "</value>\n" @@ -285,11 +337,6 @@ void cmExtraEclipseCDT4Generator::CreateProjectFile() "\t\t\t\t\t<key>org.eclipse.cdt.core.errorOutputParser</key>\n" "\t\t\t\t\t<value>" ; - std::string compilerId = mf->GetSafeDefinition("CMAKE_C_COMPILER_ID"); - if (compilerId.empty()) // no C compiler, try the C++ compiler: - { - compilerId = mf->GetSafeDefinition("CMAKE_CXX_COMPILER_ID"); - } if (compilerId == "MSVC") { fout << "org.eclipse.cdt.core.VCErrorParser;"; @@ -334,24 +381,24 @@ void cmExtraEclipseCDT4Generator::CreateProjectFile() if (this->IsOutOfSourceBuild) { fout << "\t<linkedResources>\n"; - // for each sub project create a linked resource to the source dir - // - only if it is an out-of-source build - for (std::map<cmStdString, std::vector<cmLocalGenerator*> >::const_iterator - it = this->GlobalGenerator->GetProjectMap().begin(); - it != this->GlobalGenerator->GetProjectMap().end(); - ++it) - { - std::string linkSourceDirectory = this->GetEclipsePath( - it->second[0]->GetMakefile()->GetStartDirectory()); - // .project dir can't be subdir of a linked resource dir - if (!cmSystemTools::IsSubDirectory(this->HomeOutputDirectory.c_str(), + // create a linked resource to CMAKE_SOURCE_DIR + // (this is not done anymore for each project because of + // http://public.kitware.com/Bug/view.php?id=9978 and because I found it + // actually quite confusing in bigger projects with many directories and + // projects, Alex + + std::string sourceLinkedResourceName = "[Source directory]"; + std::string linkSourceDirectory = this->GetEclipsePath( + mf->GetStartDirectory()); + // .project dir can't be subdir of a linked resource dir + if (!cmSystemTools::IsSubDirectory(this->HomeOutputDirectory.c_str(), linkSourceDirectory.c_str())) - { - this->AppendLinkedResource(fout, it->first, - this->GetEclipsePath(linkSourceDirectory)); - this->SrcLinkedResources.push_back(it->first); - } + { + this->AppendLinkedResource(fout, sourceLinkedResourceName, + this->GetEclipsePath(linkSourceDirectory)); + this->SrcLinkedResources.push_back(sourceLinkedResourceName); } + // for EXECUTABLE_OUTPUT_PATH when not in binary dir this->AppendOutLinkedResource(fout, mf->GetSafeDefinition("CMAKE_RUNTIME_OUTPUT_DIRECTORY"), @@ -383,7 +430,7 @@ void cmExtraEclipseCDT4Generator::AppendIncludeDirectories( if(emittedDirs.find(dir) == emittedDirs.end()) { emittedDirs.insert(dir); - fout << "<pathentry include=\"" + fout << "<pathentry include=\"" << cmExtraEclipseCDT4Generator::GetEclipsePath(dir) << "\" kind=\"inc\" path=\"\" system=\"true\"/>\n"; } @@ -395,7 +442,7 @@ void cmExtraEclipseCDT4Generator::AppendIncludeDirectories( void cmExtraEclipseCDT4Generator::CreateCProjectFile() const { std::set<std::string> emmited; - + const cmMakefile* mf = this->GlobalGenerator->GetLocalGenerators()[0]->GetMakefile(); @@ -408,7 +455,7 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const } // add header - fout << + fout << "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" "<?fileVersion 4.0.0?>\n\n" "<cproject>\n" @@ -418,7 +465,7 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const fout << "<cconfiguration id=\"org.eclipse.cdt.core.default.config.1\">\n"; // Configuration settings... - fout << + fout << "<storageModule" " buildSystemId=\"org.eclipse.cdt.core.defaultConfigDataProvider\"" " id=\"org.eclipse.cdt.core.default.config.1\"" @@ -479,9 +526,9 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const fout << "</extensions>\n" "</storageModule>\n" ; - + // ??? - fout << + fout << "<storageModule moduleId=\"org.eclipse.cdt.core.language.mapping\">\n" "<project-mappings/>\n" "</storageModule>\n" @@ -562,13 +609,13 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const // we have -DFOO def = *di; } - + // insert the definition if not already added. if(emmited.find(def) == emmited.end()) { emmited.insert(def); fout << "<pathentry kind=\"mac\" name=\"" << def - << "\" path=\"\" value=\"" << this->EscapeForXML(val) + << "\" path=\"\" value=\"" << this->EscapeForXML(val) << "\"/>\n"; } } @@ -655,8 +702,8 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const = (*it)->GetMakefile()->GetIncludeDirectories(); this->AppendIncludeDirectories(fout, includeDirs, emmited); } - // now also the system include directories, in case we found them in - // CMakeSystemSpecificInformation.cmake. This makes Eclipse find the + // now also the system include directories, in case we found them in + // CMakeSystemSpecificInformation.cmake. This makes Eclipse find the // standard headers. mf->GetDefinition("CMAKE_ECLIPSE_C_SYSTEM_INCLUDE_DIRS"); std::string compiler = mf->GetSafeDefinition("CMAKE_C_COMPILER"); @@ -681,15 +728,17 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const fout << "</storageModule>\n"; // add build targets - fout << + fout << "<storageModule moduleId=\"org.eclipse.cdt.make.core.buildtargets\">\n" "<buildTargets>\n" ; emmited.clear(); const std::string make = mf->GetRequiredDefinition("CMAKE_MAKE_PROGRAM"); + const std::string makeArgs = mf->GetSafeDefinition( + "CMAKE_ECLIPSE_MAKE_ARGUMENTS"); cmGlobalGenerator* generator = const_cast<cmGlobalGenerator*>(this->GlobalGenerator); - + std::string allTarget; std::string cleanTarget; if (generator->GetAllTargetName()) @@ -701,7 +750,7 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const cleanTarget = generator->GetCleanTargetName(); } - // add all executable and library targets and some of the GLOBAL + // add all executable and library targets and some of the GLOBAL // and UTILITY targets for (std::vector<cmLocalGenerator*>::const_iterator it = this->GlobalGenerator->GetLocalGenerators().begin(); @@ -724,7 +773,7 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const case cmTarget::GLOBAL_TARGET: { bool insertTarget = false; - // Only add the global targets from CMAKE_BINARY_DIR, + // Only add the global targets from CMAKE_BINARY_DIR, // not from the subdirs if (subdir.empty()) { @@ -747,7 +796,7 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const } if (insertTarget) { - this->AppendTarget(fout, ti->first, make, subdir, ": "); + this->AppendTarget(fout, ti->first, make, makeArgs, subdir, ": "); } } break; @@ -756,13 +805,13 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const // Experimental-"sub"targets as e.g. NightlyStart if (((ti->first.find("Nightly")==0) &&(ti->first!="Nightly")) || ((ti->first.find("Continuous")==0)&&(ti->first!="Continuous")) - || ((ti->first.find("Experimental")==0) + || ((ti->first.find("Experimental")==0) && (ti->first!="Experimental"))) { break; } - this->AppendTarget(fout, ti->first, make, subdir, ": "); + this->AppendTarget(fout, ti->first, make, makeArgs, subdir, ": "); break; case cmTarget::EXECUTABLE: case cmTarget::STATIC_LIBRARY: @@ -771,10 +820,10 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const { const char* prefix = (ti->second.GetType()==cmTarget::EXECUTABLE ? "[exe] " : "[lib] "); - this->AppendTarget(fout, ti->first, make, subdir, prefix); + this->AppendTarget(fout, ti->first, make, makeArgs, subdir, prefix); std::string fastTarget = ti->first; fastTarget += "/fast"; - this->AppendTarget(fout, fastTarget, make, subdir, prefix); + this->AppendTarget(fout, fastTarget, make, makeArgs, subdir, prefix); } break; // ignore these: @@ -785,15 +834,15 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const break; } } - + // insert the all and clean targets in every subdir if (!allTarget.empty()) { - this->AppendTarget(fout, allTarget, make, subdir, ": "); + this->AppendTarget(fout, allTarget, make, makeArgs, subdir, ": "); } if (!cleanTarget.empty()) { - this->AppendTarget(fout, cleanTarget, make, subdir, ": "); + this->AppendTarget(fout, cleanTarget, make, makeArgs, subdir, ": "); } //insert rules for compiling, preprocessing and assembling individual files @@ -813,7 +862,7 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const { prefix = "[pre] "; } - this->AppendTarget(fout, *fit, make, subdir, prefix); + this->AppendTarget(fout, *fit, make, makeArgs, subdir, prefix); } } @@ -898,7 +947,7 @@ std::string cmExtraEclipseCDT4Generator::EscapeForXML(const std::string& value) // Helper functions //---------------------------------------------------------------------------- void cmExtraEclipseCDT4Generator -::AppendStorageScanners(cmGeneratedFileStream& fout, +::AppendStorageScanners(cmGeneratedFileStream& fout, const cmMakefile& makefile) { // we need the "make" and the C (or C++) compiler which are used, Alex @@ -915,7 +964,7 @@ void cmExtraEclipseCDT4Generator // the following right now hardcodes gcc behaviour :-/ - fout << + fout << "<storageModule moduleId=\"scannerConfiguration\">\n" "<autodiscovery enabled=\"true\" problemReportingEnabled=\"true\"" " selectedProfileId=" @@ -939,24 +988,25 @@ void cmExtraEclipseCDT4Generator // of that is to sort the targets in the view of Eclipse, so that at first // the global/utility/all/clean targets appear ": ", then the executable // targets "[exe] ", then the libraries "[lib]", then the rules for the -// object files "[obj]", then for preprocessing only "[pre] " and -// finally the assembly files "[to asm] ". Note the "to" in "to asm", +// object files "[obj]", then for preprocessing only "[pre] " and +// finally the assembly files "[to asm] ". Note the "to" in "to asm", // without it, "asm" would be the first targets in the list, with the "to" // they are the last targets, which makes more sense. void cmExtraEclipseCDT4Generator::AppendTarget(cmGeneratedFileStream& fout, const std::string& target, const std::string& make, + const std::string& makeArgs, const std::string& path, const char* prefix) { - fout << + fout << "<target name=\"" << prefix << target << "\"" " path=\"" << path.c_str() << "\"" " targetID=\"org.eclipse.cdt.make.MakeTargetBuilder\">\n" "<buildCommand>" << cmExtraEclipseCDT4Generator::GetEclipsePath(make) << "</buildCommand>\n" - "<buildArguments/>\n" + "<buildArguments>" << makeArgs << "</buildArguments>\n" "<buildTarget>" << target << "</buildTarget>\n" "<stopOnError>true</stopOnError>\n" "<useDefaultCommand>false</useDefaultCommand>\n" @@ -976,7 +1026,7 @@ void cmExtraEclipseCDT4Generator bool runActionUseDefault, bool sipParserEnabled) { - fout << + fout << "<profile id=\"" << profileID << "\">\n" "<buildOutputProvider>\n" "<openAction enabled=\"" << (openActionEnabled ? "true" : "false") diff --git a/Source/cmExtraEclipseCDT4Generator.h b/Source/cmExtraEclipseCDT4Generator.h index f7ddad9..99e69c4 100644 --- a/Source/cmExtraEclipseCDT4Generator.h +++ b/Source/cmExtraEclipseCDT4Generator.h @@ -21,8 +21,6 @@ class cmGeneratedFileStream; /** \class cmExtraEclipseCDT4Generator * \brief Write Eclipse project files for Makefile based projects - * - * This generator is in early alpha stage. */ class cmExtraEclipseCDT4Generator : public cmExternalMakefileProjectGenerator { @@ -42,8 +40,6 @@ public: virtual void GetDocumentation(cmDocumentationEntry& entry, const char* fullName) const; - virtual void SetGlobalGenerator(cmGlobalGenerator* generator); - virtual void Generate(); private: @@ -70,11 +66,12 @@ private: static std::string EscapeForXML(const std::string& value); // Helper functions - static void AppendStorageScanners(cmGeneratedFileStream& fout, + static void AppendStorageScanners(cmGeneratedFileStream& fout, const cmMakefile& makefile); static void AppendTarget (cmGeneratedFileStream& fout, const std::string& target, const std::string& make, + const std::string& makeArguments, const std::string& path, const char* prefix = ""); static void AppendScannerProfile (cmGeneratedFileStream& fout, @@ -100,6 +97,9 @@ private: const std::vector<std::string>& includeDirs, std::set<std::string>& emittedDirs); + static void AddEnvVar(cmGeneratedFileStream& fout, const char* envVar, + cmMakefile* mf); + std::vector<std::string> SrcLinkedResources; std::vector<std::string> OutLinkedResources; std::string HomeDirectory; diff --git a/Source/cmFileCommand.cxx b/Source/cmFileCommand.cxx index bce4137..8ebd41f 100644 --- a/Source/cmFileCommand.cxx +++ b/Source/cmFileCommand.cxx @@ -183,26 +183,18 @@ bool cmFileCommand::HandleWriteCommand(std::vector<std::string> const& args, std::string dir = cmSystemTools::GetFilenamePath(fileName); cmSystemTools::MakeDirectory(dir.c_str()); - mode_t mode = -#if defined( _MSC_VER ) || defined( __MINGW32__ ) - S_IREAD | S_IWRITE -#elif defined( __BORLANDC__ ) - S_IRUSR | S_IWUSR -#else - S_IRUSR | S_IWUSR | - S_IRGRP | - S_IROTH -#endif - ; + mode_t mode = 0; // Set permissions to writable if ( cmSystemTools::GetPermissions(fileName.c_str(), mode) ) { cmSystemTools::SetPermissions(fileName.c_str(), #if defined( _MSC_VER ) || defined( __MINGW32__ ) - S_IREAD | S_IWRITE + mode | S_IWRITE +#elif defined( __BORLANDC__ ) + mode | S_IWUSR #else - S_IRUSR | S_IWUSR + mode | S_IWUSR | S_IWGRP #endif ); } @@ -219,7 +211,10 @@ bool cmFileCommand::HandleWriteCommand(std::vector<std::string> const& args, } file << message; file.close(); - cmSystemTools::SetPermissions(fileName.c_str(), mode); + if(mode) + { + cmSystemTools::SetPermissions(fileName.c_str(), mode); + } return true; } @@ -531,13 +526,6 @@ bool cmFileCommand::HandleStringsCommand(std::vector<std::string> const& args) return false; } - // At least one compiler (Portland Group Fortran) produces binaries - // with some extra characters in strings. - char extra[256]; // = {}; // some compilers do not like this - memset(extra, 0, sizeof(extra)); - extra[0x0c] = 1; // FF (form feed) - extra[0x14] = 1; // DC4 (device control 4) - // Parse strings out of the file. int output_size = 0; std::vector<std::string> strings; @@ -547,28 +535,7 @@ bool cmFileCommand::HandleStringsCommand(std::vector<std::string> const& args) (limit_input < 0 || static_cast<int>(fin.tellg()) < limit_input) && (c = fin.get(), fin)) { - if(c == '\0') - { - // A terminating null character has been found. Check if the - // current string matches the requirements. Since it was - // terminated by a null character, we require that the length be - // at least one no matter what the user specified. - if(s.length() >= minlen && s.length() >= 1 && - (!have_regex || regex.find(s.c_str()))) - { - output_size += static_cast<int>(s.size()) + 1; - if(limit_output >= 0 && output_size >= limit_output) - { - s = ""; - break; - } - strings.push_back(s); - } - - // Reset the string to empty. - s = ""; - } - else if(c == '\n' && !newline_consume) + if(c == '\n' && !newline_consume) { // The current line has been terminated. Check if the current // string matches the requirements. The length may now be as @@ -592,7 +559,7 @@ bool cmFileCommand::HandleStringsCommand(std::vector<std::string> const& args) { // Ignore CR character to make output always have UNIX newlines. } - else if((c >= 0x20 && c < 0x7F) || c == '\t' || extra[c] || + else if((c >= 0x20 && c < 0x7F) || c == '\t' || (c == '\n' && newline_consume)) { // This is an ASCII character that may be part of a string. @@ -602,7 +569,23 @@ bool cmFileCommand::HandleStringsCommand(std::vector<std::string> const& args) } else { - // This is a non-string character. Reset the string to emtpy. + // TODO: Support ENCODING option. See issue #10519. + // A non-string character has been found. Check if the current + // string matches the requirements. We require that the length + // be at least one no matter what the user specified. + if(s.length() >= minlen && s.length() >= 1 && + (!have_regex || regex.find(s.c_str()))) + { + output_size += static_cast<int>(s.size()) + 1; + if(limit_output >= 0 && output_size >= limit_output) + { + s = ""; + break; + } + strings.push_back(s); + } + + // Reset the string to empty. s = ""; } @@ -1521,7 +1504,7 @@ bool cmFileCopier::InstallFile(const char* fromFile, const char* toFile, this->ReportCopy(toFile, TypeFile, copy); // Copy the file. - if(copy && !cmSystemTools::CopyAFile(fromFile, toFile, true, false)) + if(copy && !cmSystemTools::CopyAFile(fromFile, toFile, true)) { cmOStringStream e; e << this->Name << " cannot copy file \"" << fromFile @@ -1533,6 +1516,13 @@ bool cmFileCopier::InstallFile(const char* fromFile, const char* toFile, // Set the file modification time of the destination file. if(copy && !this->Always) { + // Add write permission so we can set the file time. + // Permissions are set unconditionally below anyway. + mode_t perm = 0; + if(cmSystemTools::GetPermissions(toFile, perm)) + { + cmSystemTools::SetPermissions(toFile, perm | mode_owner_write); + } if (!cmSystemTools::CopyFileTime(fromFile, toFile)) { cmOStringStream e; @@ -2457,7 +2447,8 @@ namespace{ fout->write(chPtr, realsize); return realsize; } - + + static size_t cmFileCommandCurlDebugCallback(CURL *, curl_infotype, char *chPtr, size_t size, void *data) @@ -2470,6 +2461,72 @@ namespace{ } + class cURLProgressHelper + { + public: + cURLProgressHelper(cmFileCommand *fc) + { + this->CurrentPercentage = -1; + this->FileCommand = fc; + } + + bool UpdatePercentage(double value, double total, std::string &status) + { + int OldPercentage = this->CurrentPercentage; + + if (0.0 == total) + { + this->CurrentPercentage = 100; + } + else + { + this->CurrentPercentage = static_cast<int>(value/total*100.0 + 0.5); + } + + bool updated = (OldPercentage != this->CurrentPercentage); + + if (updated) + { + cmOStringStream oss; + oss << "[download " << this->CurrentPercentage << "% complete]"; + status = oss.str(); + } + + return updated; + } + + cmFileCommand *GetFileCommand() + { + return this->FileCommand; + } + + private: + int CurrentPercentage; + cmFileCommand *FileCommand; + }; + + + static int + cmFileCommandCurlProgressCallback(void *clientp, + double dltotal, double dlnow, + double ultotal, double ulnow) + { + cURLProgressHelper *helper = + reinterpret_cast<cURLProgressHelper *>(clientp); + + static_cast<void>(ultotal); + static_cast<void>(ulnow); + + std::string status; + if (helper->UpdatePercentage(dlnow, dltotal, status)) + { + cmFileCommand *fc = helper->GetFileCommand(); + cmMakefile *mf = fc->GetMakefile(); + mf->DisplayStatus(status.c_str(), -1); + } + + return 0; + } } #endif @@ -2483,8 +2540,8 @@ namespace { cURLEasyGuard(CURL * easy) : Easy(easy) {} - - ~cURLEasyGuard(void) + + ~cURLEasyGuard(void) { if (this->Easy) { @@ -2505,6 +2562,7 @@ namespace { } #endif + bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args) @@ -2513,8 +2571,7 @@ cmFileCommand::HandleDownloadCommand(std::vector<std::string> std::vector<std::string>::const_iterator i = args.begin(); if(args.size() < 3) { - this->SetError("FILE(DOWNLOAD url file) must be called with " - "at least three arguments."); + this->SetError("DOWNLOAD must be called with at least three arguments."); return false; } ++i; // Get rid of subcommand @@ -2522,9 +2579,13 @@ cmFileCommand::HandleDownloadCommand(std::vector<std::string> ++i; std::string file = *i; ++i; + long timeout = 0; std::string verboseLog; std::string statusVar; + std::string expectedMD5sum; + bool showProgress = false; + while(i != args.end()) { if(*i == "TIMEOUT") @@ -2536,8 +2597,7 @@ cmFileCommand::HandleDownloadCommand(std::vector<std::string> } else { - this->SetError("FILE(DOWNLOAD url file TIMEOUT time) missing " - "time for TIMEOUT."); + this->SetError("DOWNLOAD missing time for TIMEOUT."); return false; } } @@ -2546,8 +2606,7 @@ cmFileCommand::HandleDownloadCommand(std::vector<std::string> ++i; if( i == args.end()) { - this->SetError("FILE(DOWNLOAD url file LOG VAR) missing " - "VAR for LOG."); + this->SetError("DOWNLOAD missing VAR for LOG."); return false; } verboseLog = *i; @@ -2557,15 +2616,68 @@ cmFileCommand::HandleDownloadCommand(std::vector<std::string> ++i; if( i == args.end()) { - this->SetError("FILE(DOWNLOAD url file STATUS VAR) missing " - "VAR for STATUS."); + this->SetError("DOWNLOAD missing VAR for STATUS."); return false; } statusVar = *i; } + else if(*i == "EXPECTED_MD5") + { + ++i; + if( i == args.end()) + { + this->SetError("DOWNLOAD missing sum value for EXPECTED_MD5."); + return false; + } + expectedMD5sum = cmSystemTools::LowerCase(*i); + } + else if(*i == "SHOW_PROGRESS") + { + showProgress = true; + } ++i; } + // If file exists already, and caller specified an expected md5 sum, + // and the existing file already has the expected md5 sum, then simply + // return. + // + if(cmSystemTools::FileExists(file.c_str()) && + !expectedMD5sum.empty()) + { + char computedMD5[32]; + + if (!cmSystemTools::ComputeFileMD5(file.c_str(), computedMD5)) + { + this->SetError("DOWNLOAD cannot compute MD5 sum on pre-existing file"); + return false; + } + + std::string actualMD5sum = cmSystemTools::LowerCase( + std::string(computedMD5, 32)); + + if (expectedMD5sum == actualMD5sum) + { + this->Makefile->DisplayStatus( + "FILE(DOWNLOAD) returning early: file already exists with " + "expected MD5 sum", -1); + + if(statusVar.size()) + { + cmOStringStream result; + result << (int)0 << ";\"" + "returning early: file already exists with expected MD5 sum\""; + this->Makefile->AddDefinition(statusVar.c_str(), + result.str().c_str()); + } + + return true; + } + } + + // Make sure parent directory exists so we can write to the file + // as we receive downloaded bits from curl... + // std::string dir = cmSystemTools::GetFilenamePath(file.c_str()); if(!cmSystemTools::FileExists(dir.c_str()) && !cmSystemTools::MakeDirectory(dir.c_str())) @@ -2580,17 +2692,16 @@ cmFileCommand::HandleDownloadCommand(std::vector<std::string> std::ofstream fout(file.c_str(), std::ios::binary); if(!fout) { - this->SetError("FILE(DOWNLOAD url file TIMEOUT time) can not open " - "file for write."); + this->SetError("DOWNLOAD cannot open file for write."); return false; } + ::CURL *curl; ::curl_global_init(CURL_GLOBAL_DEFAULT); curl = ::curl_easy_init(); if(!curl) { - this->SetError("FILE(DOWNLOAD ) error " - "initializing curl."); + this->SetError("DOWNLOAD error initializing curl."); return false; } @@ -2599,28 +2710,29 @@ cmFileCommand::HandleDownloadCommand(std::vector<std::string> ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); if (res != CURLE_OK) { - std::string errstring = "FILE(DOWNLOAD ) error; cannot set url: "; - errstring += ::curl_easy_strerror(res); + std::string e = "DOWNLOAD cannot set url: "; + e += ::curl_easy_strerror(res); + this->SetError(e.c_str()); return false; } res = ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, - cmFileCommandWriteMemoryCallback); + cmFileCommandWriteMemoryCallback); if (res != CURLE_OK) - { - std::string errstring = - "FILE(DOWNLOAD ) error; cannot set write function: "; - errstring += ::curl_easy_strerror(res); + { + std::string e = "DOWNLOAD cannot set write function: "; + e += ::curl_easy_strerror(res); + this->SetError(e.c_str()); return false; } res = ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, - cmFileCommandCurlDebugCallback); + cmFileCommandCurlDebugCallback); if (res != CURLE_OK) { - std::string errstring = - "FILE(DOWNLOAD ) error; cannot set debug function: "; - errstring += ::curl_easy_strerror(res); + std::string e = "DOWNLOAD cannot set debug function: "; + e += ::curl_easy_strerror(res); + this->SetError(e.c_str()); return false; } @@ -2630,16 +2742,27 @@ cmFileCommand::HandleDownloadCommand(std::vector<std::string> if (res != CURLE_OK) { - std::string errstring = "FILE(DOWNLOAD ) error; cannot set write data: "; - errstring += ::curl_easy_strerror(res); + std::string e = "DOWNLOAD cannot set write data: "; + e += ::curl_easy_strerror(res); + this->SetError(e.c_str()); return false; } res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)&chunkDebug); if (res != CURLE_OK) { - std::string errstring = "FILE(DOWNLOAD ) error; cannot set write data: "; - errstring += ::curl_easy_strerror(res); + std::string e = "DOWNLOAD cannot set debug data: "; + e += ::curl_easy_strerror(res); + this->SetError(e.c_str()); + return false; + } + + res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); + if (res != CURLE_OK) + { + std::string e = "DOWNLOAD cannot set follow-redirect option: "; + e += ::curl_easy_strerror(res); + this->SetError(e.c_str()); return false; } @@ -2649,26 +2772,72 @@ cmFileCommand::HandleDownloadCommand(std::vector<std::string> if (res != CURLE_OK) { - std::string errstring = "FILE(DOWNLOAD ) error; cannot set verbose: "; - errstring += ::curl_easy_strerror(res); + std::string e = "DOWNLOAD cannot set verbose: "; + e += ::curl_easy_strerror(res); + this->SetError(e.c_str()); return false; } } + if(timeout > 0) { res = ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout ); if (res != CURLE_OK) { - std::string errstring = "FILE(DOWNLOAD ) error; cannot set verbose: "; - errstring += ::curl_easy_strerror(res); + std::string e = "DOWNLOAD cannot set timeout: "; + e += ::curl_easy_strerror(res); + this->SetError(e.c_str()); + return false; + } + } + + // Need the progress helper's scope to last through the duration of + // the curl_easy_perform call... so this object is declared at function + // scope intentionally, rather than inside the "if(showProgress)" + // block... + // + cURLProgressHelper helper(this); + + if(showProgress) + { + res = ::curl_easy_setopt(curl, + CURLOPT_NOPROGRESS, 0); + if (res != CURLE_OK) + { + std::string e = "DOWNLOAD cannot set noprogress value: "; + e += ::curl_easy_strerror(res); + this->SetError(e.c_str()); + return false; + } + + res = ::curl_easy_setopt(curl, + CURLOPT_PROGRESSFUNCTION, cmFileCommandCurlProgressCallback); + if (res != CURLE_OK) + { + std::string e = "DOWNLOAD cannot set progress function: "; + e += ::curl_easy_strerror(res); + this->SetError(e.c_str()); + return false; + } + + res = ::curl_easy_setopt(curl, + CURLOPT_PROGRESSDATA, reinterpret_cast<void*>(&helper)); + if (res != CURLE_OK) + { + std::string e = "DOWNLOAD cannot set progress data: "; + e += ::curl_easy_strerror(res); + this->SetError(e.c_str()); return false; } } + res = ::curl_easy_perform(curl); + /* always cleanup */ g_curl.release(); ::curl_easy_cleanup(curl); + if(statusVar.size()) { cmOStringStream result; @@ -2676,7 +2845,42 @@ cmFileCommand::HandleDownloadCommand(std::vector<std::string> this->Makefile->AddDefinition(statusVar.c_str(), result.str().c_str()); } + ::curl_global_cleanup(); + + // Explicitly flush/close so we can measure the md5 accurately. + // + fout.flush(); + fout.close(); + + // Verify MD5 sum if requested: + // + if (!expectedMD5sum.empty()) + { + char computedMD5[32]; + + if (!cmSystemTools::ComputeFileMD5(file.c_str(), computedMD5)) + { + this->SetError("DOWNLOAD cannot compute MD5 sum on downloaded file"); + return false; + } + + std::string actualMD5sum = cmSystemTools::LowerCase( + std::string(computedMD5, 32)); + + if (expectedMD5sum != actualMD5sum) + { + cmOStringStream oss; + oss << "DOWNLOAD MD5 mismatch" << std::endl + << " for file: [" << file << "]" << std::endl + << " expected MD5 sum: [" << expectedMD5sum << "]" << std::endl + << " actual MD5 sum: [" << actualMD5sum << "]" << std::endl + ; + this->SetError(oss.str().c_str()); + return false; + } + } + if(chunkDebug.size()) { chunkDebug.push_back(0); @@ -2694,10 +2898,10 @@ cmFileCommand::HandleDownloadCommand(std::vector<std::string> this->Makefile->AddDefinition(verboseLog.c_str(), &*chunkDebug.begin()); } + return true; #else - this->SetError("FILE(DOWNLOAD ) " - "not supported in bootstrap cmake "); + this->SetError("DOWNLOAD not supported by bootstrap cmake."); return false; #endif } diff --git a/Source/cmFileCommand.h b/Source/cmFileCommand.h index c6da301..b11dcde 100644 --- a/Source/cmFileCommand.h +++ b/Source/cmFileCommand.h @@ -80,7 +80,8 @@ public: " file(RELATIVE_PATH variable directory file)\n" " file(TO_CMAKE_PATH path result)\n" " file(TO_NATIVE_PATH path result)\n" - " file(DOWNLOAD url file [TIMEOUT timeout] [STATUS status] [LOG log])\n" + " file(DOWNLOAD url file [TIMEOUT timeout] [STATUS status] [LOG log]\n" + " [EXPECTED_MD5 sum] [SHOW_PROGRESS])\n" "WRITE will write a message into a file called 'filename'. It " "overwrites the file if it already exists, and creates the file " "if it does not exist.\n" @@ -115,7 +116,12 @@ public: "expressions and store it into the variable. Globbing expressions " "are similar to regular expressions, but much simpler. If RELATIVE " "flag is specified for an expression, the results will be returned " - "as a relative path to the given path.\n" + "as a relative path to the given path. " + "(We do not recommend using GLOB to collect a list of source files " + "from your source tree. If no CMakeLists.txt file changes when a " + "source is added or removed then the generated build system cannot " + "know when to ask CMake to regenerate.)" + "\n" "Examples of globbing expressions include:\n" " *.cxx - match all files with extension cxx\n" " *.vt? - match all files with extension vta,...,vtz\n" @@ -152,7 +158,12 @@ public: "and the second element is a string value for the error. A 0 " "numeric error means no error in the operation. " "If TIMEOUT time is specified, the operation will " - "timeout after time seconds, time should be specified as an integer." + "timeout after time seconds, time should be specified as an integer. " + "If EXPECTED_MD5 sum is specified, the operation will verify that the " + "downloaded file's actual md5 sum matches the expected value. If it " + "does not match, the operation fails with an error. " + "If SHOW_PROGRESS is specified, progress information will be printed " + "as status messages until the operation is complete." "\n" "The file() command also provides COPY and INSTALL signatures:\n" " file(<COPY|INSTALL> files... DESTINATION <dir>\n" diff --git a/Source/cmFindBase.cxx b/Source/cmFindBase.cxx index a54ad7a..d0fe99f 100644 --- a/Source/cmFindBase.cxx +++ b/Source/cmFindBase.cxx @@ -13,11 +13,17 @@ cmFindBase::cmFindBase() { - cmSystemTools::ReplaceString(this->GenericDocumentationPathsOrder, - "FIND_ARGS_XXX", "<VAR> NAMES name"); this->AlreadyInCache = false; this->AlreadyInCacheWithoutMetaInfo = false; - this->GenericDocumentation = +} + +//---------------------------------------------------------------------------- +void cmFindBase::GenerateDocumentation() +{ + this->cmFindCommon::GenerateDocumentation(); + cmSystemTools::ReplaceString(this->GenericDocumentationPathsOrder, + "FIND_ARGS_XXX", "<VAR> NAMES name"); + this->GenericDocumentation = " FIND_XXX(<VAR> name1 [path1 path2 ...])\n" "This is the short-hand signature for the command that " "is sufficient in many cases. It is the same " @@ -97,7 +103,18 @@ cmFindBase::cmFindBase() this->GenericDocumentation += this->GenericDocumentationRootPath; this->GenericDocumentation += this->GenericDocumentationPathsOrder; } - + +//---------------------------------------------------------------------------- +const char* cmFindBase::GetFullDocumentation() +{ + if(this->GenericDocumentation.empty()) + { + this->GenerateDocumentation(); + } + return this->GenericDocumentation.c_str(); +} + +//---------------------------------------------------------------------------- bool cmFindBase::ParseArguments(std::vector<std::string> const& argsIn) { if(argsIn.size() < 2 ) @@ -147,6 +164,11 @@ bool cmFindBase::ParseArguments(std::vector<std::string> const& argsIn) } } } + if(args.size() < 2 ) + { + this->SetError("called with incorrect number of arguments"); + return false; + } this->VariableName = args[0]; if(this->CheckForVariableInCache()) { @@ -269,6 +291,11 @@ bool cmFindBase::ParseArguments(std::vector<std::string> const& argsIn) } this->ExpandPaths(); + // Filter out ignored paths from the prefix list + std::set<std::string> ignored; + this->GetIgnoredPaths(ignored); + this->FilterPaths(this->SearchPaths, ignored); + // Handle search root stuff. this->RerootPaths(this->SearchPaths); diff --git a/Source/cmFindBase.h b/Source/cmFindBase.h index 2f1727e..de319b1 100644 --- a/Source/cmFindBase.h +++ b/Source/cmFindBase.h @@ -31,10 +31,10 @@ public: virtual bool ParseArguments(std::vector<std::string> const& args); cmTypeMacro(cmFindBase, cmFindCommon); - virtual const char* GetFullDocumentation() - {return this->GenericDocumentation.c_str();} + virtual const char* GetFullDocumentation(); protected: + virtual void GenerateDocumentation(); void PrintFindStuff(); void ExpandPaths(); void AddPathSuffixes(); diff --git a/Source/cmFindCommon.cxx b/Source/cmFindCommon.cxx index f4c0064..a05e337 100644 --- a/Source/cmFindCommon.cxx +++ b/Source/cmFindCommon.cxx @@ -34,7 +34,11 @@ cmFindCommon::cmFindCommon() this->SearchFrameworkLast = false; this->SearchAppBundleOnly = false; this->SearchAppBundleLast = false; +} +//---------------------------------------------------------------------------- +void cmFindCommon::GenerateDocumentation() +{ // Documentation components. this->GenericDocumentationMacPolicy = "On Darwin or systems supporting OS X Frameworks, the cmake variable" @@ -241,6 +245,63 @@ void cmFindCommon::RerootPaths(std::vector<std::string>& paths) } //---------------------------------------------------------------------------- +void cmFindCommon::FilterPaths(std::vector<std::string>& paths, + const std::set<std::string>& ignore) +{ + // Now filter out anything that's in the ignore set. + std::vector<std::string> unfiltered; + unfiltered.swap(paths); + + for(std::vector<std::string>::iterator pi = unfiltered.begin(); + pi != unfiltered.end(); ++pi) + { + if (ignore.count(*pi) == 0) + { + paths.push_back(*pi); + } + } +} + + +//---------------------------------------------------------------------------- +void cmFindCommon::GetIgnoredPaths(std::vector<std::string>& ignore) +{ + // null-terminated list of paths. + static const char *paths[] = + { "CMAKE_SYSTEM_IGNORE_PATH", "CMAKE_IGNORE_PATH", 0 }; + + // Construct the list of path roots with no trailing slashes. + for(const char **pathName = paths; *pathName; ++pathName) + { + // Get the list of paths to ignore from the variable. + const char* ignorePath = this->Makefile->GetDefinition(*pathName); + if((ignorePath == 0) || (strlen(ignorePath) == 0)) + { + continue; + } + + cmSystemTools::ExpandListArgument(ignorePath, ignore); + } + + for(std::vector<std::string>::iterator i = ignore.begin(); + i != ignore.end(); ++i) + { + cmSystemTools::ConvertToUnixSlashes(*i); + } +} + + +//---------------------------------------------------------------------------- +void cmFindCommon::GetIgnoredPaths(std::set<std::string>& ignore) +{ + std::vector<std::string> ignoreVec; + GetIgnoredPaths(ignoreVec); + ignore.insert(ignoreVec.begin(), ignoreVec.end()); +} + + + +//---------------------------------------------------------------------------- bool cmFindCommon::CheckCommonArgument(std::string const& arg) { if(arg == "NO_DEFAULT_PATH") @@ -423,3 +484,17 @@ void cmFindCommon::AddTrailingSlashes(std::vector<std::string>& paths) } } } + +//---------------------------------------------------------------------------- +void cmFindCommon::SetMakefile(cmMakefile* makefile) +{ + cmCommand::SetMakefile(makefile); + + // If we are building for Apple (OSX or also iphone), make sure + // that frameworks and bundles are searched first. + if(this->Makefile->IsOn("APPLE")) + { + this->SearchFrameworkFirst = true; + this->SearchAppBundleFirst = true; + } +} diff --git a/Source/cmFindCommon.h b/Source/cmFindCommon.h index 08d2158..875c223 100644 --- a/Source/cmFindCommon.h +++ b/Source/cmFindCommon.h @@ -39,6 +39,14 @@ protected: /** Place a set of search paths under the search roots. */ void RerootPaths(std::vector<std::string>& paths); + /** Get ignored paths from CMAKE_[SYSTEM_]IGNORE_path variables. */ + void GetIgnoredPaths(std::vector<std::string>& ignore); + void GetIgnoredPaths(std::set<std::string>& ignore); + + /** Remove paths in the ignore set from the supplied vector. */ + void FilterPaths(std::vector<std::string>& paths, + const std::set<std::string>& ignore); + /** Add trailing slashes to all search paths. */ void AddTrailingSlashes(std::vector<std::string>& paths); @@ -48,6 +56,8 @@ protected: /** Compute the current default bundle/framework search policy. */ void SelectDefaultMacMode(); + virtual void GenerateDocumentation(); + cmStdString CMakePathName; RootPathMode FindRootPathMode; @@ -61,6 +71,8 @@ protected: PathType pathType); void AddPathInternal(std::string const& in_path, PathType pathType); + void SetMakefile(cmMakefile* makefile); + bool NoDefaultPath; bool NoCMakePath; bool NoCMakeEnvironmentPath; diff --git a/Source/cmFindFileCommand.cxx b/Source/cmFindFileCommand.cxx index 897b4bb..fa66fa1 100644 --- a/Source/cmFindFileCommand.cxx +++ b/Source/cmFindFileCommand.cxx @@ -15,11 +15,16 @@ cmFindFileCommand::cmFindFileCommand() { this->IncludeFileInPath = true; +} + +void cmFindFileCommand::GenerateDocumentation() +{ + this->cmFindPathCommand::GenerateDocumentation(); cmSystemTools::ReplaceString(this->GenericDocumentation, "find_path", "find_file"); cmSystemTools::ReplaceString(this->GenericDocumentation, - "directory containing the named file", + "directory containing the named file", "full path to named file"); cmSystemTools::ReplaceString(this->GenericDocumentation, - "file in a directory", "full path to a file"); + "file in a directory", "full path to a file"); } diff --git a/Source/cmFindFileCommand.h b/Source/cmFindFileCommand.h index aa0d25e..dd2e01d 100644 --- a/Source/cmFindFileCommand.h +++ b/Source/cmFindFileCommand.h @@ -44,6 +44,8 @@ public: } cmTypeMacro(cmFindFileCommand, cmFindPathCommand); +protected: + virtual void GenerateDocumentation(); }; diff --git a/Source/cmFindLibraryCommand.cxx b/Source/cmFindLibraryCommand.cxx index 9077c8e..b309376 100644 --- a/Source/cmFindLibraryCommand.cxx +++ b/Source/cmFindLibraryCommand.cxx @@ -16,6 +16,13 @@ cmFindLibraryCommand::cmFindLibraryCommand() { + this->EnvironmentPath = "LIB"; +} + +//---------------------------------------------------------------------------- +void cmFindLibraryCommand::GenerateDocumentation() +{ + this->cmFindBase::GenerateDocumentation(); cmSystemTools::ReplaceString(this->GenericDocumentation, "FIND_XXX", "find_library"); cmSystemTools::ReplaceString(this->GenericDocumentation, @@ -29,7 +36,7 @@ cmFindLibraryCommand::cmFindLibraryCommand() cmSystemTools::ReplaceString(this->GenericDocumentation, "XXX_SYSTEM", "LIB"); cmSystemTools::ReplaceString(this->GenericDocumentation, - "CMAKE_SYSTEM_XXX_PATH", + "CMAKE_SYSTEM_XXX_PATH", "CMAKE_SYSTEM_LIBRARY_PATH"); cmSystemTools::ReplaceString(this->GenericDocumentation, "SEARCH_XXX_DESC", "library"); @@ -38,11 +45,9 @@ cmFindLibraryCommand::cmFindLibraryCommand() cmSystemTools::ReplaceString(this->GenericDocumentation, "XXX_SUBDIR", "lib"); cmSystemTools::ReplaceString(this->GenericDocumentation, - "CMAKE_FIND_ROOT_PATH_MODE_XXX", + "CMAKE_FIND_ROOT_PATH_MODE_XXX", "CMAKE_FIND_ROOT_PATH_MODE_LIBRARY"); - - this->EnvironmentPath = "LIB"; - this->GenericDocumentation += + this->GenericDocumentation += "\n" "If the library found is a framework, then VAR will be set to " "the full path to the framework <fullPath>/A.framework. " diff --git a/Source/cmFindLibraryCommand.h b/Source/cmFindLibraryCommand.h index 486c2cf..7930f52 100644 --- a/Source/cmFindLibraryCommand.h +++ b/Source/cmFindLibraryCommand.h @@ -64,6 +64,7 @@ protected: void AddArchitecturePaths(const char* suffix); void AddLib64Paths(); std::string FindLibrary(); + virtual void GenerateDocumentation(); private: std::string FindNormalLibrary(); std::string FindFrameworkLibrary(); diff --git a/Source/cmFindPackageCommand.cxx b/Source/cmFindPackageCommand.cxx index bd58f56..fdc1a01 100644 --- a/Source/cmFindPackageCommand.cxx +++ b/Source/cmFindPackageCommand.cxx @@ -51,13 +51,6 @@ void cmFindPackageNeedBackwardsCompatibility(const std::string& variable, //---------------------------------------------------------------------------- cmFindPackageCommand::cmFindPackageCommand() { - cmSystemTools::ReplaceString(this->GenericDocumentationRootPath, - "CMAKE_FIND_ROOT_PATH_MODE_XXX", - "CMAKE_FIND_ROOT_PATH_MODE_PACKAGE"); - cmSystemTools::ReplaceString(this->GenericDocumentationPathsOrder, - "FIND_ARGS_XXX", "<package>"); - cmSystemTools::ReplaceString(this->GenericDocumentationPathsOrder, - "FIND_XXX", "find_package"); this->CMakePathName = "PACKAGE"; this->Quiet = false; this->Required = false; @@ -78,6 +71,19 @@ cmFindPackageCommand::cmFindPackageCommand() this->VersionFoundPatch = 0; this->VersionFoundTweak = 0; this->VersionFoundCount = 0; +} + +//---------------------------------------------------------------------------- +void cmFindPackageCommand::GenerateDocumentation() +{ + this->cmFindCommon::GenerateDocumentation(); + cmSystemTools::ReplaceString(this->GenericDocumentationRootPath, + "CMAKE_FIND_ROOT_PATH_MODE_XXX", + "CMAKE_FIND_ROOT_PATH_MODE_PACKAGE"); + cmSystemTools::ReplaceString(this->GenericDocumentationPathsOrder, + "FIND_ARGS_XXX", "<package>"); + cmSystemTools::ReplaceString(this->GenericDocumentationPathsOrder, + "FIND_XXX", "find_package"); this->CommandDocumentation = " find_package(<package> [version] [EXACT] [QUIET]\n" " [[REQUIRED|COMPONENTS] [components...]]\n" @@ -156,6 +162,11 @@ cmFindPackageCommand::cmFindPackageCommand() "The full path to the configuration file is stored in the cmake " "variable <package>_CONFIG." "\n" + "All configuration files which have been considered by CMake while " + "searching for an installation of the package with an appropriate " + "version are stored in the cmake variable <package>_CONSIDERED_CONFIGS, " + "the associated versions in <package>_CONSIDERED_VERSIONS. " + "\n" "If the package configuration file cannot be found CMake " "will generate an error describing the problem unless the QUIET " "argument is specified. If REQUIRED is specified and the package " @@ -313,6 +324,10 @@ cmFindPackageCommand::cmFindPackageCommand() //---------------------------------------------------------------------------- const char* cmFindPackageCommand::GetFullDocumentation() { + if(this->CommandDocumentation.empty()) + { + this->GenerateDocumentation(); + } return this->CommandDocumentation.c_str(); } @@ -596,6 +611,15 @@ bool cmFindPackageCommand } } + // get igonored paths from vars and reroot them. + std::vector<std::string> ignored; + this->GetIgnoredPaths(ignored); + this->RerootPaths(ignored); + + // Construct a set of ignored paths + this->IgnoredPaths.clear(); + this->IgnoredPaths.insert(ignored.begin(), ignored.end()); + // Find and load the package. bool result = this->HandlePackageMode(); this->AppendSuccessInformation(); @@ -609,7 +633,7 @@ void cmFindPackageCommand::SetModuleVariables(const std::string& components) // Store the list of components. std::string components_var = this->Name + "_FIND_COMPONENTS"; this->AddFindDefinition(components_var.c_str(), components.c_str()); - + if(this->Quiet) { // Tell the module that is about to be read that it should find @@ -712,6 +736,8 @@ bool cmFindPackageCommand::FindModule(bool& found) //---------------------------------------------------------------------------- bool cmFindPackageCommand::HandlePackageMode() { + this->ConsideredConfigs.clear(); + // Support old capitalization behavior. std::string upperDir = cmSystemTools::UpperCase(this->Name); std::string upperFound = cmSystemTools::UpperCase(this->Name); @@ -800,36 +826,58 @@ bool cmFindPackageCommand::HandlePackageMode() { // The variable is not set. cmOStringStream e; - e << "Could not find "; - if(!this->NoModule) - { - e << "module Find" << this->Name << ".cmake or "; - } - e << "a configuration file for package " << this->Name << ".\n"; - if(!this->NoModule) - { - e << "Adjust CMAKE_MODULE_PATH to find Find" - << this->Name << ".cmake or set "; - } - else - { - e << "Set "; - } - e << this->Variable << " to the directory containing a CMake " - << "configuration file for " << this->Name << ". "; - if(this->Configs.size() == 1) - { - e << "The file will be called " << this->Configs[0]; + // If there are files in ConsideredConfigs, it means that FooConfig.cmake + // have been found, but they didn't have appropriate versions. + if (this->ConsideredConfigs.size() > 0) + { + e << "Could not find a configuration file for package \"" + << this->Name << "\" that " + << (this->VersionExact? "exactly matches" : "is compatible with") + << " requested version \"" << this->Version << "\".\n" + << "The following configuration files were considered but not " + "accepted:\n"; + for(std::vector<ConfigFileInfo>::size_type i=0; + i<this->ConsideredConfigs.size(); i++) + { + e << " " << this->ConsideredConfigs[i].filename + << ", version: " << this->ConsideredConfigs[i].version << "\n"; + } } else { - e << "The file will have one of the following names:\n"; - for(std::vector<std::string>::const_iterator ci = this->Configs.begin(); - ci != this->Configs.end(); ++ci) + e << "Could not find "; + if(!this->NoModule) + { + e << "module Find" << this->Name << ".cmake or "; + } + e << "a configuration file for package " << this->Name << ".\n"; + if(!this->NoModule) { - e << " " << *ci << "\n"; + e << "Adjust CMAKE_MODULE_PATH to find Find" + << this->Name << ".cmake or set "; + } + else + { + e << "Set "; + } + e << this->Variable << " to the directory containing a CMake " + << "configuration file for " << this->Name << ". "; + if(this->Configs.size() == 1) + { + e << "The file will be called " << this->Configs[0]; + } + else + { + e << "The file will have one of the following names:\n"; + for(std::vector<std::string>::const_iterator ci=this->Configs.begin(); + ci != this->Configs.end(); ++ci) + { + e << " " << *ci << "\n"; + } } } + + this->Makefile->IssueMessage( this->Required? cmake::FATAL_ERROR : cmake::WARNING, e.str()); } @@ -888,6 +936,31 @@ bool cmFindPackageCommand::HandlePackageMode() } #endif + std::string consideredConfigsVar = this->Name; + consideredConfigsVar += "_CONSIDERED_CONFIGS"; + std::string consideredVersionsVar = this->Name; + consideredVersionsVar += "_CONSIDERED_VERSIONS"; + + std::string consideredConfigFiles; + std::string consideredVersions; + + const char* sep = ""; + for(std::vector<ConfigFileInfo>::size_type i=0; + i<this->ConsideredConfigs.size(); i++) + { + consideredConfigFiles += sep; + consideredVersions += sep; + consideredConfigFiles += this->ConsideredConfigs[i].filename; + consideredVersions += this->ConsideredConfigs[i].version; + sep = ";"; + } + + this->Makefile->AddDefinition(consideredConfigsVar.c_str(), + consideredConfigFiles.c_str()); + + this->Makefile->AddDefinition(consideredVersionsVar.c_str(), + consideredVersions.c_str()); + return result; } @@ -1074,6 +1147,20 @@ void cmFindPackageCommand::AppendSuccessInformation() } } + // set a global property to record the required version of this package + std::string versionInfoPropName = "_CMAKE_"; + versionInfoPropName += this->Name; + versionInfoPropName += "_REQUIRED_VERSION"; + std::string versionInfo; + if(!this->Version.empty()) + { + versionInfo = this->VersionExact ? "==" : ">="; + versionInfo += " "; + versionInfo += this->Version; + } + this->Makefile->GetCMakeInstance()->SetProperty(versionInfoPropName.c_str(), + versionInfo.c_str()); + // Restore original state of "_FIND_" variables we set. this->RestoreFindDefinitions(); } @@ -1431,6 +1518,11 @@ bool cmFindPackageCommand::CheckDirectory(std::string const& dir) bool cmFindPackageCommand::FindConfigFile(std::string const& dir, std::string& file) { + if (this->IgnoredPaths.count(dir)) + { + return false; + } + for(std::vector<std::string>::const_iterator ci = this->Configs.begin(); ci != this->Configs.end(); ++ci) { @@ -1453,6 +1545,10 @@ bool cmFindPackageCommand::FindConfigFile(std::string const& dir, //---------------------------------------------------------------------------- bool cmFindPackageCommand::CheckVersion(std::string const& config_file) { + bool result = false; // by default, assume the version is not ok. + bool haveResult = false; + std::string version = "unknown"; + // Get the filename without the .cmake extension. std::string::size_type pos = config_file.rfind('.'); std::string version_file_base = config_file.substr(0, pos); @@ -1460,31 +1556,42 @@ bool cmFindPackageCommand::CheckVersion(std::string const& config_file) // Look for foo-config-version.cmake std::string version_file = version_file_base; version_file += "-version.cmake"; - if(cmSystemTools::FileExists(version_file.c_str(), true)) + if ((haveResult == false) + && (cmSystemTools::FileExists(version_file.c_str(), true))) { - return this->CheckVersionFile(version_file); + result = this->CheckVersionFile(version_file, version); + haveResult = true; } // Look for fooConfigVersion.cmake version_file = version_file_base; version_file += "Version.cmake"; - if(cmSystemTools::FileExists(version_file.c_str(), true)) + if ((haveResult == false) + && (cmSystemTools::FileExists(version_file.c_str(), true))) { - return this->CheckVersionFile(version_file); + result = this->CheckVersionFile(version_file, version); + haveResult = true; } + // If no version was requested a versionless package is acceptable. - if(this->Version.empty()) + if ((haveResult == false) && (this->Version.empty())) { - return true; + result = true; + haveResult = true; } - // No version file found. Assume the version is incompatible. - return false; + ConfigFileInfo configFileInfo; + configFileInfo.filename = config_file; + configFileInfo.version = version; + this->ConsideredConfigs.push_back(configFileInfo); + + return result; } //---------------------------------------------------------------------------- -bool cmFindPackageCommand::CheckVersionFile(std::string const& version_file) +bool cmFindPackageCommand::CheckVersionFile(std::string const& version_file, + std::string& result_version) { // The version file will be loaded in an isolated scope. cmMakefile::ScopePushPop varScope(this->Makefile); @@ -1557,6 +1664,12 @@ bool cmFindPackageCommand::CheckVersionFile(std::string const& version_file) } } + result_version = this->Makefile->GetSafeDefinition("PACKAGE_VERSION"); + if (result_version.empty()) + { + result_version = "unknown"; + } + // Succeed if the version is suitable. return suitable; } diff --git a/Source/cmFindPackageCommand.h b/Source/cmFindPackageCommand.h index 63f4111..19d2b10 100644 --- a/Source/cmFindPackageCommand.h +++ b/Source/cmFindPackageCommand.h @@ -65,6 +65,8 @@ public: virtual const char* GetFullDocumentation(); cmTypeMacro(cmFindPackageCommand, cmFindCommon); +protected: + virtual void GenerateDocumentation(); private: void AppendSuccessInformation(); void AppendToProperty(const char* propertyName); @@ -98,7 +100,8 @@ private: bool CheckDirectory(std::string const& dir); bool FindConfigFile(std::string const& dir, std::string& file); bool CheckVersion(std::string const& config_file); - bool CheckVersionFile(std::string const& version_file); + bool CheckVersionFile(std::string const& version_file, + std::string& result_version); bool SearchPrefix(std::string const& prefix); bool SearchFrameworkPrefix(std::string const& prefix_in); bool SearchAppBundlePrefix(std::string const& prefix_in); @@ -136,6 +139,10 @@ private: bool PolicyScope; std::vector<std::string> Names; std::vector<std::string> Configs; + std::set<std::string> IgnoredPaths; + + struct ConfigFileInfo { std::string filename; std::string version; }; + std::vector<ConfigFileInfo> ConsideredConfigs; }; #endif diff --git a/Source/cmFindPathCommand.cxx b/Source/cmFindPathCommand.cxx index cca243a..83b651b 100644 --- a/Source/cmFindPathCommand.cxx +++ b/Source/cmFindPathCommand.cxx @@ -18,6 +18,11 @@ cmFindPathCommand::cmFindPathCommand() { this->EnvironmentPath = "INCLUDE"; this->IncludeFileInPath = false; +} + +void cmFindPathCommand::GenerateDocumentation() +{ + this->cmFindBase::GenerateDocumentation(); cmSystemTools::ReplaceString(this->GenericDocumentation, "FIND_XXX", "find_path"); cmSystemTools::ReplaceString(this->GenericDocumentation, @@ -31,27 +36,21 @@ cmFindPathCommand::cmFindPathCommand() cmSystemTools::ReplaceString(this->GenericDocumentation, "XXX_SYSTEM", "INCLUDE"); cmSystemTools::ReplaceString(this->GenericDocumentation, - "CMAKE_SYSTEM_XXX_PATH", - "CMAKE_SYSTEM_INCLUDE_PATH"); + "CMAKE_SYSTEM_XXX_PATH", + "CMAKE_SYSTEM_INCLUDE_PATH"); cmSystemTools::ReplaceString(this->GenericDocumentation, - "SEARCH_XXX_DESC", + "SEARCH_XXX_DESC", "directory containing the named file"); cmSystemTools::ReplaceString(this->GenericDocumentation, "SEARCH_XXX", "file in a directory"); cmSystemTools::ReplaceString(this->GenericDocumentation, "XXX_SUBDIR", "include"); cmSystemTools::ReplaceString(this->GenericDocumentation, - "CMAKE_FIND_ROOT_PATH_MODE_XXX", + "CMAKE_FIND_ROOT_PATH_MODE_XXX", "CMAKE_FIND_ROOT_PATH_MODE_INCLUDE"); - - this->ExtraDocAdded = false; -} - -const char* cmFindPathCommand::GetFullDocumentation() -{ - if(!this->ExtraDocAdded && !this->IncludeFileInPath) + if(!this->IncludeFileInPath) { - this->GenericDocumentation += + this->GenericDocumentation += "\n" "When searching for frameworks, if the file is specified as " "A/b.h, then the framework search will look for " @@ -59,9 +58,7 @@ const char* cmFindPathCommand::GetFullDocumentation() "If that is found the path will be set to the path to the framework. " "CMake will convert this to the correct -F option to include the " "file. "; - this->ExtraDocAdded = true; } - return this->GenericDocumentation.c_str(); } // cmFindPathCommand diff --git a/Source/cmFindPathCommand.h b/Source/cmFindPathCommand.h index 3c04343..bd94779 100644 --- a/Source/cmFindPathCommand.h +++ b/Source/cmFindPathCommand.h @@ -59,10 +59,10 @@ public: return "Find the directory containing a file."; } - virtual const char* GetFullDocumentation(); cmTypeMacro(cmFindPathCommand, cmFindBase); bool IncludeFileInPath; - bool ExtraDocAdded; +protected: + virtual void GenerateDocumentation(); private: std::string FindHeaderInFramework(std::string const& file, std::string const& dir); diff --git a/Source/cmFindProgramCommand.cxx b/Source/cmFindProgramCommand.cxx index 519f862..71cfdcb 100644 --- a/Source/cmFindProgramCommand.cxx +++ b/Source/cmFindProgramCommand.cxx @@ -16,9 +16,10 @@ #if defined(__APPLE__) #include <CoreFoundation/CoreFoundation.h> #endif - -cmFindProgramCommand::cmFindProgramCommand() + +void cmFindProgramCommand::GenerateDocumentation() { + this->cmFindBase::GenerateDocumentation(); cmSystemTools::ReplaceString(this->GenericDocumentation, "FIND_XXX", "find_program"); cmSystemTools::ReplaceString(this->GenericDocumentation, @@ -32,8 +33,8 @@ cmFindProgramCommand::cmFindProgramCommand() cmSystemTools::ReplaceString(this->GenericDocumentation, "XXX_SYSTEM", ""); cmSystemTools::ReplaceString(this->GenericDocumentation, - "CMAKE_SYSTEM_XXX_PATH", - "CMAKE_SYSTEM_PROGRAM_PATH"); + "CMAKE_SYSTEM_XXX_PATH", + "CMAKE_SYSTEM_PROGRAM_PATH"); cmSystemTools::ReplaceString(this->GenericDocumentation, "SEARCH_XXX_DESC", "program"); cmSystemTools::ReplaceString(this->GenericDocumentation, @@ -41,7 +42,7 @@ cmFindProgramCommand::cmFindProgramCommand() cmSystemTools::ReplaceString(this->GenericDocumentation, "XXX_SUBDIR", "[s]bin"); cmSystemTools::ReplaceString(this->GenericDocumentation, - "CMAKE_FIND_ROOT_PATH_MODE_XXX", + "CMAKE_FIND_ROOT_PATH_MODE_XXX", "CMAKE_FIND_ROOT_PATH_MODE_PROGRAM"); } diff --git a/Source/cmFindProgramCommand.h b/Source/cmFindProgramCommand.h index ae790a3..654e834 100644 --- a/Source/cmFindProgramCommand.h +++ b/Source/cmFindProgramCommand.h @@ -25,7 +25,6 @@ class cmFindProgramCommand : public cmFindBase { public: - cmFindProgramCommand(); /** * This is a virtual constructor for the command. */ @@ -63,6 +62,7 @@ public: protected: std::string FindProgram(std::vector<std::string> names); + virtual void GenerateDocumentation(); private: std::string FindAppBundle(std::vector<std::string> names); diff --git a/Source/cmGeneratorExpression.cxx b/Source/cmGeneratorExpression.cxx index a61880f..8710dfc 100644 --- a/Source/cmGeneratorExpression.cxx +++ b/Source/cmGeneratorExpression.cxx @@ -17,8 +17,8 @@ //---------------------------------------------------------------------------- cmGeneratorExpression::cmGeneratorExpression( cmMakefile* mf, const char* config, - cmListFileBacktrace const& backtrace): - Makefile(mf), Config(config), Backtrace(backtrace) + cmListFileBacktrace const& backtrace, bool quiet): + Makefile(mf), Config(config), Backtrace(backtrace), Quiet(quiet) { this->TargetInfo.compile("^\\$<TARGET" "(|_SONAME|_LINKER)" // File with what purpose? @@ -87,7 +87,7 @@ bool cmGeneratorExpression::Evaluate() this->Data.insert(this->Data.end(), result.begin(), result.end()); return true; } - else + else if(!this->Quiet) { // Failure. Report the error message. cmOStringStream e; @@ -99,6 +99,7 @@ bool cmGeneratorExpression::Evaluate() this->Backtrace); return false; } + return true; } //---------------------------------------------------------------------------- @@ -140,6 +141,7 @@ bool cmGeneratorExpression::EvaluateTargetInfo(std::string& result) result = "Target \"" + name + "\" is not an executable or library."; return false; } + this->Targets.insert(target); // Lookup the target file with the given purpose. std::string purpose = this->TargetInfo.match(1); diff --git a/Source/cmGeneratorExpression.h b/Source/cmGeneratorExpression.h index aa36055..1a9d4c6 100644 --- a/Source/cmGeneratorExpression.h +++ b/Source/cmGeneratorExpression.h @@ -15,6 +15,7 @@ #include <cmsys/RegularExpression.hxx> +class cmTarget; class cmMakefile; class cmListFileBacktrace; @@ -32,18 +33,25 @@ class cmGeneratorExpression public: /** Construct with an evaluation context and configuration. */ cmGeneratorExpression(cmMakefile* mf, const char* config, - cmListFileBacktrace const& backtrace); + cmListFileBacktrace const& backtrace, + bool quiet = false); /** Evaluate generator expressions in a string. */ const char* Process(std::string const& input); const char* Process(const char* input); + + /** Get set of targets found during evaluations. */ + std::set<cmTarget*> const& GetTargets() const + { return this->Targets; } private: cmMakefile* Makefile; const char* Config; cmListFileBacktrace const& Backtrace; + bool Quiet; std::vector<char> Data; std::stack<size_t> Barriers; cmsys::RegularExpression TargetInfo; + std::set<cmTarget*> Targets; bool Evaluate(); bool Evaluate(const char* expr, std::string& result); bool EvaluateTargetInfo(std::string& result); diff --git a/Source/cmGetCMakePropertyCommand.h b/Source/cmGetCMakePropertyCommand.h index c78671e..d82be70 100644 --- a/Source/cmGetCMakePropertyCommand.h +++ b/Source/cmGetCMakePropertyCommand.h @@ -54,11 +54,14 @@ public: { return " get_cmake_property(VAR property)\n" - "Get a property from the CMake instance. The value of the " - "property is stored in the variable VAR. If the property is " - "not found, CMake will report an error. Some supported properties " + "Get a property from the CMake instance. " + "The value of the property is stored in the variable VAR. " + "If the property is not found, VAR will be set to \"NOTFOUND\". " + "Some supported properties " "include: VARIABLES, CACHE_VARIABLES, COMMANDS, MACROS, and " - "COMPONENTS."; + "COMPONENTS." + "\n" + "See also the more general get_property() command."; } cmTypeMacro(cmGetCMakePropertyCommand, cmCommand); diff --git a/Source/cmGetDirectoryPropertyCommand.h b/Source/cmGetDirectoryPropertyCommand.h index c3a23a3..b7a5f71 100644 --- a/Source/cmGetDirectoryPropertyCommand.h +++ b/Source/cmGetDirectoryPropertyCommand.h @@ -66,7 +66,8 @@ public: "Get a variable definition from a directory. " "This form is useful to get a variable definition from another " "directory." - ; + "\n" + "See also the more general get_property() command."; } cmTypeMacro(cmGetDirectoryPropertyCommand, cmCommand); diff --git a/Source/cmGetFilenameComponentCommand.h b/Source/cmGetFilenameComponentCommand.h index c85b296..aff4d7e 100644 --- a/Source/cmGetFilenameComponentCommand.h +++ b/Source/cmGetFilenameComponentCommand.h @@ -62,10 +62,10 @@ public: virtual const char* GetFullDocumentation() { return - " get_filename_component(VarName FileName\n" + " get_filename_component(<VAR> FileName\n" " PATH|ABSOLUTE|NAME|EXT|NAME_WE|REALPATH\n" " [CACHE])\n" - "Set VarName to be the path (PATH), file name (NAME), file " + "Set <VAR> to be the path (PATH), file name (NAME), file " "extension (EXT), file name without extension (NAME_WE) of FileName, " "the full path (ABSOLUTE), or the full path with all symlinks " "resolved (REALPATH). " @@ -73,14 +73,14 @@ public: "trailing slashes. The longest file extension is always considered. " "If the optional CACHE argument is specified, the result variable is " "added to the cache.\n" - " get_filename_component(VarName FileName\n" - " PROGRAM [PROGRAM_ARGS ArgVar]\n" + " get_filename_component(<VAR> FileName\n" + " PROGRAM [PROGRAM_ARGS <ARG_VAR>]\n" " [CACHE])\n" "The program in FileName will be found in the system search path or " "left as a full path. If PROGRAM_ARGS is present with PROGRAM, then " "any command-line arguments present in the FileName string are split " - "from the program name and stored in ArgVar. This is used to separate " - "a program name from its arguments in a command line string."; + "from the program name and stored in <ARG_VAR>. This is used to " + "separate a program name from its arguments in a command line string."; } cmTypeMacro(cmGetFilenameComponentCommand, cmCommand); diff --git a/Source/cmGetSourceFilePropertyCommand.h b/Source/cmGetSourceFilePropertyCommand.h index c1d5e11..56469f8 100644 --- a/Source/cmGetSourceFilePropertyCommand.h +++ b/Source/cmGetSourceFilePropertyCommand.h @@ -53,7 +53,9 @@ public: "stored in the variable VAR. If the property is not found, VAR " "will be set to \"NOTFOUND\". Use set_source_files_properties to set " "property values. Source file properties usually control how the " - "file is built. One property that is always there is LOCATION"; + "file is built. One property that is always there is LOCATION" + "\n" + "See also the more general get_property() command."; } cmTypeMacro(cmGetSourceFilePropertyCommand, cmCommand); diff --git a/Source/cmGetTargetPropertyCommand.h b/Source/cmGetTargetPropertyCommand.h index e1984c3..71c75ef 100644 --- a/Source/cmGetTargetPropertyCommand.h +++ b/Source/cmGetTargetPropertyCommand.h @@ -55,7 +55,9 @@ public: "property values. Properties are usually used to control how " "a target is built, but some query the target instead. " "This command can get properties for any target so far created. " - "The targets do not need to be in the current CMakeLists.txt file."; + "The targets do not need to be in the current CMakeLists.txt file." + "\n" + "See also the more general get_property() command."; } cmTypeMacro(cmGetTargetPropertyCommand, cmCommand); diff --git a/Source/cmGetTestPropertyCommand.h b/Source/cmGetTestPropertyCommand.h index 956cf55..d9f5d9b 100644 --- a/Source/cmGetTestPropertyCommand.h +++ b/Source/cmGetTestPropertyCommand.h @@ -48,11 +48,13 @@ public: virtual const char* GetFullDocumentation() { return - " get_test_property(test VAR property)\n" - "Get a property from the Test. The value of the property is " - "stored in the variable VAR. If the property is not found, " - "CMake will report an error. For a list of standard properties " - "you can type cmake --help-property-list"; + " get_test_property(test property VAR)\n" + "Get a property from the Test. The value of the property is " + "stored in the variable VAR. If the property is not found, VAR " + "will be set to \"NOTFOUND\". For a list of standard properties " + "you can type cmake --help-property-list" + "\n" + "See also the more general get_property() command."; } cmTypeMacro(cmGetTestPropertyCommand, cmCommand); diff --git a/Source/cmGlobalGenerator.cxx b/Source/cmGlobalGenerator.cxx index 1cbd423..123ab5e 100644 --- a/Source/cmGlobalGenerator.cxx +++ b/Source/cmGlobalGenerator.cxx @@ -699,9 +699,8 @@ bool cmGlobalGenerator::IsDependedOn(const char* project, l != targets.end(); l++) { cmTarget& target = l->second; - std::set<cmStdString>::const_iterator pos = - target.GetUtilities().find(targetIn->GetName()); - if(pos != target.GetUtilities().end()) + TargetDependSet const& tgtdeps = this->GetTargetDirectDepends(target); + if(tgtdeps.count(targetIn)) { return true; } @@ -815,24 +814,11 @@ void cmGlobalGenerator::Generate() // For each existing cmLocalGenerator unsigned int i; - // Consolidate global targets + // Put a copy of each global target in every directory. cmTargets globalTargets; this->CreateDefaultGlobalTargets(&globalTargets); for (i = 0; i < this->LocalGenerators.size(); ++i) { - cmTargets* targets = - &(this->LocalGenerators[i]->GetMakefile()->GetTargets()); - cmTargets::iterator tarIt; - for ( tarIt = targets->begin(); tarIt != targets->end(); ++ tarIt ) - { - if ( tarIt->second.GetType() == cmTarget::GLOBAL_TARGET ) - { - globalTargets[tarIt->first] = tarIt->second; - } - } - } - for (i = 0; i < this->LocalGenerators.size(); ++i) - { cmMakefile* mf = this->LocalGenerators[i]->GetMakefile(); cmTargets* targets = &(mf->GetTargets()); cmTargets::iterator tit; @@ -863,19 +849,10 @@ void cmGlobalGenerator::Generate() } // Compute the inter-target dependencies. - { - cmComputeTargetDepends ctd(this); - if(!ctd.Compute()) + if(!this->ComputeTargetDepends()) { return; } - std::vector<cmTarget*> const& targets = ctd.GetTargets(); - for(std::vector<cmTarget*>::const_iterator ti = targets.begin(); - ti != targets.end(); ++ti) - { - ctd.GetTargetDirectDepends(*ti, this->TargetDependencies[*ti]); - } - } // Create a map from local generator to the complete set of targets // it builds by default. @@ -908,6 +885,23 @@ void cmGlobalGenerator::Generate() } //---------------------------------------------------------------------------- +bool cmGlobalGenerator::ComputeTargetDepends() +{ + cmComputeTargetDepends ctd(this); + if(!ctd.Compute()) + { + return false; + } + std::vector<cmTarget*> const& targets = ctd.GetTargets(); + for(std::vector<cmTarget*>::const_iterator ti = targets.begin(); + ti != targets.end(); ++ti) + { + ctd.GetTargetDirectDepends(*ti, this->TargetDependencies[*ti]); + } + return true; +} + +//---------------------------------------------------------------------------- bool cmGlobalGenerator::CheckTargets() { // Make sure all targets can find their source files. @@ -1487,7 +1481,7 @@ void cmGlobalGenerator::FillLocalGeneratorToTargetMap() // Add dependencies of the included target. An excluded // target may still be included if it is a dependency of a // non-excluded target. - TargetDependSet & tgtdeps = this->GetTargetDirectDepends(target); + TargetDependSet const& tgtdeps = this->GetTargetDirectDepends(target); for(TargetDependSet::const_iterator ti = tgtdeps.begin(); ti != tgtdeps.end(); ++ti) { @@ -1837,12 +1831,44 @@ void cmGlobalGenerator::CreateDefaultGlobalTargets(cmTargets* targets) } } +//---------------------------------------------------------------------------- +const char* cmGlobalGenerator::GetPredefinedTargetsFolder() +{ + const char* prop = + this->GetCMakeInstance()->GetProperty("PREDEFINED_TARGETS_FOLDER"); + + if (prop) + { + return prop; + } + + return "CMakePredefinedTargets"; +} + +//---------------------------------------------------------------------------- +bool cmGlobalGenerator::UseFolderProperty() +{ + const char* prop = this->GetCMakeInstance()->GetProperty("USE_FOLDERS"); + + // If this property is defined, let the setter turn this on or off... + // + if (prop) + { + return cmSystemTools::IsOn(prop); + } + + // By default, this feature is OFF, since it is not supported in the + // Visual Studio Express editions: + // + return false; +} + +//---------------------------------------------------------------------------- cmTarget cmGlobalGenerator::CreateGlobalTarget( const char* name, const char* message, const cmCustomCommandLines* commandLines, std::vector<std::string> depends, - const char* workingDirectory, - bool depends_on_all /* = false */) + const char* workingDirectory) { // Package cmTarget target; @@ -1853,19 +1879,23 @@ cmTarget cmGlobalGenerator::CreateGlobalTarget( std::vector<std::string> no_outputs; std::vector<std::string> no_depends; // Store the custom command in the target. - cmCustomCommand cc(no_outputs, no_depends, *commandLines, 0, + cmCustomCommand cc(0, no_outputs, no_depends, *commandLines, 0, workingDirectory); target.GetPostBuildCommands().push_back(cc); target.SetProperty("EchoString", message); - if ( depends_on_all ) - { - target.AddUtility("all"); - } std::vector<std::string>::iterator dit; for ( dit = depends.begin(); dit != depends.end(); ++ dit ) { target.AddUtility(dit->c_str()); } + + // Organize in the "predefined targets" folder: + // + if (this->UseFolderProperty()) + { + target.SetProperty("FOLDER", this->GetPredefinedTargetsFolder()); + } + return target; } @@ -1879,7 +1909,7 @@ void cmGlobalGenerator::AppendDirectoryForConfig(const char*, const char*, } //---------------------------------------------------------------------------- -cmGlobalGenerator::TargetDependSet & +cmGlobalGenerator::TargetDependSet const& cmGlobalGenerator::GetTargetDirectDepends(cmTarget & target) { return this->TargetDependencies[&target]; @@ -2068,20 +2098,27 @@ void cmGlobalGenerator::CheckRuleHashes() std::string pfile = home; pfile += this->GetCMakeInstance()->GetCMakeFilesDirectory(); pfile += "/CMakeRuleHashes.txt"; + this->CheckRuleHashes(pfile, home); + this->WriteRuleHashes(pfile); +#endif +} +//---------------------------------------------------------------------------- +void cmGlobalGenerator::CheckRuleHashes(std::string const& pfile, + std::string const& home) +{ #if defined(_WIN32) || defined(__CYGWIN__) std::ifstream fin(pfile.c_str(), std::ios::in | std::ios::binary); #else std::ifstream fin(pfile.c_str(), std::ios::in); #endif - bool goodStream = true; if(!fin) { - goodStream = false; + return; } std::string line; std::string fname; - while(goodStream && cmSystemTools::GetLineFromStream(fin, line)) + while(cmSystemTools::GetLineFromStream(fin, line)) { // Line format is a 32-byte hex string followed by a space // followed by a file name (with no escaping). @@ -2127,7 +2164,11 @@ void cmGlobalGenerator::CheckRuleHashes() } } } +} +//---------------------------------------------------------------------------- +void cmGlobalGenerator::WriteRuleHashes(std::string const& pfile) +{ // Now generate a new persistence file with the current hashes. if(this->RuleHashes.empty()) { @@ -2144,7 +2185,6 @@ void cmGlobalGenerator::CheckRuleHashes() fout << " " << rhi->first << "\n"; } } -#endif } //---------------------------------------------------------------------------- diff --git a/Source/cmGlobalGenerator.h b/Source/cmGlobalGenerator.h index b7b4324..6a1aa53 100644 --- a/Source/cmGlobalGenerator.h +++ b/Source/cmGlobalGenerator.h @@ -16,6 +16,7 @@ #include "cmStandardIncludes.h" #include "cmTarget.h" // For cmTargets +#include "cmTargetDepend.h" // For cmTargetDependSet class cmake; class cmMakefile; @@ -38,31 +39,31 @@ public: ///! Free any memory allocated with the GlobalGenerator cmGlobalGenerator(); virtual ~cmGlobalGenerator(); - + ///! Create a local generator appropriate to this Global Generator virtual cmLocalGenerator *CreateLocalGenerator(); ///! Get the name for this generator virtual const char *GetName() const { return "Generic"; }; - + /** Get the documentation entry for this generator. */ virtual void GetDocumentation(cmDocumentationEntry& entry) const; - + /** * Create LocalGenerators and process the CMakeLists files. This does not - * actually produce any makefiles, DSPs, etc. + * actually produce any makefiles, DSPs, etc. */ virtual void Configure(); /** * Generate the all required files for building this project/tree. This * basically creates a series of LocalGenerators for each directory and - * requests that they Generate. + * requests that they Generate. */ virtual void Generate(); /** - * Set/Get and Clear the enabled languages. + * Set/Get and Clear the enabled languages. */ void SetLanguageEnabled(const char*, cmMakefile* mf); bool GetLanguageEnabled(const char*) const; @@ -70,7 +71,7 @@ public: void GetEnabledLanguages(std::vector<std::string>& lang); /** * Try to determine system infomation such as shared library - * extension, pthreads, byte order etc. + * extension, pthreads, byte order etc. */ virtual void EnableLanguage(std::vector<std::string>const& languages, cmMakefile *, bool optional); @@ -88,7 +89,7 @@ public: const char *projectName, const char *targetName, bool fast, std::string *output, cmMakefile* mf); - + /** * Build a file given the following information. This is a more direct call * that is used by both CTest and TryCompile. If target name is NULL or @@ -104,28 +105,28 @@ public: const char* extraOptions = 0, std::vector<std::string> const& nativeOptions = std::vector<std::string>()); - + virtual std::string GenerateBuildCommand( const char* makeProgram, - const char *projectName, const char* additionalOptions, + const char *projectName, const char* additionalOptions, const char *targetName, const char* config, bool ignoreErrors, bool fast); - + ///! Set the CMake instance void SetCMakeInstance(cmake *cm); - + ///! Get the CMake instance cmake *GetCMakeInstance() { return this->CMakeInstance; }; void SetConfiguredFilesPath(cmGlobalGenerator* gen); - const std::vector<cmLocalGenerator *>& GetLocalGenerators() const { + const std::vector<cmLocalGenerator *>& GetLocalGenerators() const { return this->LocalGenerators;} - cmLocalGenerator* GetCurrentLocalGenerator() + cmLocalGenerator* GetCurrentLocalGenerator() {return this->CurrentLocalGenerator;} - void SetCurrentLocalGenerator(cmLocalGenerator* lg) + void SetCurrentLocalGenerator(cmLocalGenerator* lg) {this->CurrentLocalGenerator = lg;} void AddLocalGenerator(cmLocalGenerator *lg); @@ -138,11 +139,11 @@ public: void AddInstallComponent(const char* component); - const std::set<cmStdString>* GetInstallComponents() const + const std::set<cmStdString>* GetInstallComponents() const { return &InstallComponents; } ///! Add one installed target to the sets of the exports - void AddTargetToExports(const char* exportSet, cmTarget* target, + void AddTargetToExports(const char* exportSet, cmTarget* target, cmInstallTargetGenerator* archive, cmInstallTargetGenerator* runTime, cmInstallTargetGenerator* library, @@ -158,10 +159,9 @@ public: void EnableInstallTarget(); int TryCompileTimeout; - + bool GetForceUnixPaths() {return this->ForceUnixPaths;} bool GetToolSupportsColor() { return this->ToolSupportsColor; } - void SetToolSupportsColor(bool enable) { this->ToolSupportsColor = enable; } ///! return the language for the given extension const char* GetLanguageFromExtension(const char* ext); @@ -234,11 +234,11 @@ public: virtual const char* GetCleanTargetName() { return 0; } // Class to track a set of dependencies. - class TargetDependSet: public std::set<cmTarget*> {}; + typedef cmTargetDependSet TargetDependSet; // what targets does the specified target depend on directly // via a target_link_libraries or add_dependencies - TargetDependSet & GetTargetDirectDepends(cmTarget & target); + TargetDependSet const& GetTargetDirectDepends(cmTarget & target); const std::map<cmStdString, std::vector<cmLocalGenerator*> >& GetProjectMap() const {return this->ProjectMap;} @@ -254,7 +254,7 @@ public: bool BinaryDirectoryIsNew(const char* dir) { return this->BinaryDirectories.insert(dir).second; - } + } /** Supported systems creates a GUID for the given name */ virtual void CreateGUID(const char*) {} @@ -275,11 +275,13 @@ protected: void SetLanguageEnabledMaps(const char* l, cmMakefile* mf); void FillExtensionToLanguageMap(const char* l, cmMakefile* mf); + virtual bool ComputeTargetDepends(); + virtual bool CheckALLOW_DUPLICATE_CUSTOM_TARGETS(); bool CheckTargets(); - // Fill the ProjectMap, this must be called after LocalGenerators + // Fill the ProjectMap, this must be called after LocalGenerators // has been populated. void FillProjectMap(); void CheckLocalGenerators(); @@ -289,8 +291,7 @@ protected: void CreateDefaultGlobalTargets(cmTargets* targets); cmTarget CreateGlobalTarget(const char* name, const char* message, const cmCustomCommandLines* commandLines, - std::vector<std::string> depends, const char* workingDir, - bool depends_on_all = false); + std::vector<std::string> depends, const char* workingDir); bool NeedSymbolicMark; bool UseLinkScript; @@ -320,21 +321,26 @@ protected: // All targets in the entire project. std::map<cmStdString,cmTarget *> TotalTargets; + virtual const char* GetPredefinedTargetsFolder(); + virtual bool UseFolderProperty(); + private: float FirstTimeProgress; // If you add a new map here, make sure it is copied - // in EnableLanguagesFromGenerator + // in EnableLanguagesFromGenerator std::map<cmStdString, bool> IgnoreExtensions; std::map<cmStdString, bool> LanguageEnabled; std::map<cmStdString, cmStdString> OutputExtensions; std::map<cmStdString, cmStdString> LanguageToOutputExtension; std::map<cmStdString, cmStdString> ExtensionToLanguage; - std::map<cmStdString, int> LanguageToLinkerPreference; + std::map<cmStdString, int> LanguageToLinkerPreference; // Record hashes for rules and outputs. struct RuleHash { char Data[32]; }; std::map<cmStdString, RuleHash> RuleHashes; void CheckRuleHashes(); + void CheckRuleHashes(std::string const& pfile, std::string const& home); + void WriteRuleHashes(std::string const& pfile); void WriteSummary(); void WriteSummary(cmTarget* target); diff --git a/Source/cmGlobalJOMMakefileGenerator.h b/Source/cmGlobalJOMMakefileGenerator.h index 98df5f5..08be4b4 100644 --- a/Source/cmGlobalJOMMakefileGenerator.h +++ b/Source/cmGlobalJOMMakefileGenerator.h @@ -28,7 +28,9 @@ public: ///! Get the name for the generator. virtual const char* GetName() const { return cmGlobalJOMMakefileGenerator::GetActualName();} - static const char* GetActualName() {return "JOM Makefiles";} + // use NMake Makefiles in the name so that scripts/tests that depend on the + // name NMake Makefiles will work + static const char* GetActualName() {return "NMake Makefiles JOM";} /** Get the documentation entry for this generator. */ virtual void GetDocumentation(cmDocumentationEntry& entry) const; diff --git a/Source/cmGlobalKdevelopGenerator.cxx b/Source/cmGlobalKdevelopGenerator.cxx index 6ceec48..56b9e9c 100644 --- a/Source/cmGlobalKdevelopGenerator.cxx +++ b/Source/cmGlobalKdevelopGenerator.cxx @@ -475,6 +475,7 @@ void cmGlobalKdevelopGenerator " <environments>\n" " <default>\n" " <envvar value=\"1\" name=\"VERBOSE\" />\n" + " <envvar value=\"1\" name=\"CMAKE_NO_VERBOSE\" />\n" " </default>\n" " </environments>\n" " </make>\n"; diff --git a/Source/cmGlobalMSYSMakefileGenerator.cxx b/Source/cmGlobalMSYSMakefileGenerator.cxx index d324e59..820e7e6 100644 --- a/Source/cmGlobalMSYSMakefileGenerator.cxx +++ b/Source/cmGlobalMSYSMakefileGenerator.cxx @@ -69,9 +69,16 @@ void cmGlobalMSYSMakefileGenerator { gxx = tgxx; } + std::string trc = cmSystemTools::FindProgram("windres", locations); + std::string rc = "windres.exe"; + if(trc.size()) + { + rc = trc; + } mf->AddDefinition("MSYS", "1"); mf->AddDefinition("CMAKE_GENERATOR_CC", gcc.c_str()); mf->AddDefinition("CMAKE_GENERATOR_CXX", gxx.c_str()); + mf->AddDefinition("CMAKE_GENERATOR_RC", rc.c_str()); this->cmGlobalUnixMakefileGenerator3::EnableLanguage(l, mf, optional); if(!mf->IsSet("CMAKE_AR") && diff --git a/Source/cmGlobalMinGWMakefileGenerator.cxx b/Source/cmGlobalMinGWMakefileGenerator.cxx index 9f9d1be..2f558dc 100644 --- a/Source/cmGlobalMinGWMakefileGenerator.cxx +++ b/Source/cmGlobalMinGWMakefileGenerator.cxx @@ -44,8 +44,15 @@ void cmGlobalMinGWMakefileGenerator { gxx = tgxx; } + std::string trc = cmSystemTools::FindProgram("windres", locations); + std::string rc = "windres.exe"; + if(trc.size()) + { + rc = trc; + } mf->AddDefinition("CMAKE_GENERATOR_CC", gcc.c_str()); mf->AddDefinition("CMAKE_GENERATOR_CXX", gxx.c_str()); + mf->AddDefinition("CMAKE_GENERATOR_RC", rc.c_str()); this->cmGlobalUnixMakefileGenerator3::EnableLanguage(l, mf, optional); } diff --git a/Source/cmGlobalUnixMakefileGenerator3.cxx b/Source/cmGlobalUnixMakefileGenerator3.cxx index b687fe1..d9a341c 100644 --- a/Source/cmGlobalUnixMakefileGenerator3.cxx +++ b/Source/cmGlobalUnixMakefileGenerator3.cxx @@ -24,7 +24,7 @@ cmGlobalUnixMakefileGenerator3::cmGlobalUnixMakefileGenerator3() this->ForceUnixPaths = true; this->FindMakeProgramFile = "CMakeUnixFindMake.cmake"; this->ToolSupportsColor = true; - this->ForceVerboseMakefiles = false; + this->NoRuleMessages = false; #if defined(_WIN32) || defined(__VMS) this->UseLinkScript = false; @@ -34,8 +34,8 @@ cmGlobalUnixMakefileGenerator3::cmGlobalUnixMakefileGenerator3() } void cmGlobalUnixMakefileGenerator3 -::EnableLanguage(std::vector<std::string>const& languages, - cmMakefile *mf, +::EnableLanguage(std::vector<std::string>const& languages, + cmMakefile *mf, bool optional) { this->cmGlobalGenerator::EnableLanguage(languages, mf, optional); @@ -51,17 +51,17 @@ void cmGlobalUnixMakefileGenerator3 std::string langComp = "CMAKE_"; langComp += lang; langComp += "_COMPILER"; - + if(!mf->GetDefinition(langComp.c_str())) { if(!optional) { - cmSystemTools::Error(langComp.c_str(), + cmSystemTools::Error(langComp.c_str(), " not set, after EnableLanguage"); } continue; } - const char* name = mf->GetRequiredDefinition(langComp.c_str()); + const char* name = mf->GetRequiredDefinition(langComp.c_str()); if(!cmSystemTools::FileIsFullPath(name)) { path = cmSystemTools::FindProgram(name); @@ -70,7 +70,7 @@ void cmGlobalUnixMakefileGenerator3 { path = name; } - if((path.size() == 0 || !cmSystemTools::FileExists(path.c_str())) + if((path.size() == 0 || !cmSystemTools::FileExists(path.c_str())) && (optional==false)) { std::string message = "your "; @@ -96,8 +96,8 @@ void cmGlobalUnixMakefileGenerator3 cmSystemTools::ConvertToUnixSlashes(cnameString); cmSystemTools::ConvertToUnixSlashes(pathString); if (cnameString != pathString) - { - const char* cvars = + { + const char* cvars = this->GetCMakeInstance()->GetProperty( "__CMAKE_DELETE_CACHE_CHANGE_VARS_"); if(cvars) @@ -139,44 +139,53 @@ void cmGlobalUnixMakefileGenerator3 } //---------------------------------------------------------------------------- -void cmGlobalUnixMakefileGenerator3::Generate() +void cmGlobalUnixMakefileGenerator3::Generate() { // first do superclass method this->cmGlobalGenerator::Generate(); - // initialize progress - unsigned long total = 0; - for(ProgressMapType::const_iterator pmi = this->ProgressMap.begin(); - pmi != this->ProgressMap.end(); ++pmi) + cmake* cm = this->GetCMakeInstance(); + if(const char* ruleStatus = cm->GetProperty("RULE_MESSAGES")) { - total += pmi->second.NumberOfActions; + this->NoRuleMessages = cmSystemTools::IsOff(ruleStatus); } - // write each target's progress.make this loop is done twice. Bascially the - // Generate pass counts all the actions, the first loop below determines - // how many actions have progress updates for each target and writes to - // corrrect variable values for everything except the all targets. The - // second loop actually writes out correct values for the all targets as - // well. This is because the all targets require more information that is - // computed in the first loop. - unsigned long current = 0; - for(ProgressMapType::iterator pmi = this->ProgressMap.begin(); - pmi != this->ProgressMap.end(); ++pmi) + if(!this->NoRuleMessages) { - pmi->second.WriteProgressVariables(total, current); - } - for(unsigned int i = 0; i < this->LocalGenerators.size(); ++i) - { - cmLocalUnixMakefileGenerator3 *lg = - static_cast<cmLocalUnixMakefileGenerator3 *>(this->LocalGenerators[i]); - std::string markFileName = lg->GetMakefile()->GetStartOutputDirectory(); - markFileName += "/"; - markFileName += cmake::GetCMakeFilesDirectory(); - markFileName += "/progress.marks"; - cmGeneratedFileStream markFile(markFileName.c_str()); - markFile << this->CountProgressMarksInAll(lg) << "\n"; + // initialize progress + unsigned long total = 0; + for(ProgressMapType::const_iterator pmi = this->ProgressMap.begin(); + pmi != this->ProgressMap.end(); ++pmi) + { + total += pmi->second.NumberOfActions; + } + + // write each target's progress.make this loop is done twice. Bascially the + // Generate pass counts all the actions, the first loop below determines + // how many actions have progress updates for each target and writes to + // corrrect variable values for everything except the all targets. The + // second loop actually writes out correct values for the all targets as + // well. This is because the all targets require more information that is + // computed in the first loop. + unsigned long current = 0; + for(ProgressMapType::iterator pmi = this->ProgressMap.begin(); + pmi != this->ProgressMap.end(); ++pmi) + { + pmi->second.WriteProgressVariables(total, current); + } + for(unsigned int i = 0; i < this->LocalGenerators.size(); ++i) + { + cmLocalUnixMakefileGenerator3 *lg = + static_cast<cmLocalUnixMakefileGenerator3 *>(this->LocalGenerators[i]); + std::string markFileName = lg->GetMakefile()->GetStartOutputDirectory(); + markFileName += "/"; + markFileName += cmake::GetCMakeFilesDirectory(); + markFileName += "/progress.marks"; + cmGeneratedFileStream markFile(markFileName.c_str()); + markFile << this->CountProgressMarksInAll(lg) << "\n"; + } } - + // write the main makefile this->WriteMainMakefile2(); this->WriteMainCMakefile(); @@ -187,7 +196,7 @@ void cmGlobalUnixMakefileGenerator3::WriteMainMakefile2() // Open the output file. This should not be copy-if-different // because the check-build-system step compares the makefile time to // see if the build system must be regenerated. - std::string makefileName = + std::string makefileName = this->GetCMakeInstance()->GetHomeOutputDirectory(); makefileName += cmake::GetCMakeFilesDirectory(); makefileName += "/Makefile2"; @@ -196,11 +205,11 @@ void cmGlobalUnixMakefileGenerator3::WriteMainMakefile2() { return; } - + // get a local generator for some useful methods - cmLocalUnixMakefileGenerator3 *lg = + cmLocalUnixMakefileGenerator3 *lg = static_cast<cmLocalUnixMakefileGenerator3 *>(this->LocalGenerators[0]); - + // Write the do not edit header. lg->WriteDisclaimer(makefileStream); @@ -229,8 +238,8 @@ void cmGlobalUnixMakefileGenerator3::WriteMainMakefile2() } // Write and empty all: - lg->WriteMakeRule(makefileStream, - "The main recursive all target", "all", + lg->WriteMakeRule(makefileStream, + "The main recursive all target", "all", depends, no_commands, true); // Write an empty preinstall: @@ -240,12 +249,12 @@ void cmGlobalUnixMakefileGenerator3::WriteMainMakefile2() // Write out the "special" stuff lg->WriteSpecialTargetsTop(makefileStream); - + // write the target convenience rules unsigned int i; for (i = 0; i < this->LocalGenerators.size(); ++i) { - lg = + lg = static_cast<cmLocalUnixMakefileGenerator3 *>(this->LocalGenerators[i]); this->WriteConvenienceRules2(makefileStream,lg); } @@ -261,7 +270,7 @@ void cmGlobalUnixMakefileGenerator3::WriteMainCMakefile() // Open the output file. This should not be copy-if-different // because the check-build-system step compares the makefile time to // see if the build system must be regenerated. - std::string cmakefileName = + std::string cmakefileName = this->GetCMakeInstance()->GetHomeOutputDirectory(); cmakefileName += cmake::GetCMakeFilesDirectory(); cmakefileName += "/Makefile.cmake"; @@ -271,14 +280,14 @@ void cmGlobalUnixMakefileGenerator3::WriteMainCMakefile() return; } - std::string makefileName = + std::string makefileName = this->GetCMakeInstance()->GetHomeOutputDirectory(); makefileName += "/Makefile"; - + // get a local generator for some useful methods - cmLocalUnixMakefileGenerator3 *lg = + cmLocalUnixMakefileGenerator3 *lg = static_cast<cmLocalUnixMakefileGenerator3 *>(this->LocalGenerators[0]); - + // Write the do not edit header. lg->WriteDisclaimer(cmakefileStream); @@ -291,9 +300,9 @@ void cmGlobalUnixMakefileGenerator3::WriteMainCMakefile() std::vector<std::string> lfiles; for (unsigned int i = 0; i < this->LocalGenerators.size(); ++i) { - lg = + lg = static_cast<cmLocalUnixMakefileGenerator3 *>(this->LocalGenerators[i]); - + // Get the list of files contributing to this generation step. lfiles.insert(lfiles.end(),lg->GetMakefile()->GetListFiles().begin(), lg->GetMakefile()->GetListFiles().end()); @@ -301,7 +310,7 @@ void cmGlobalUnixMakefileGenerator3::WriteMainCMakefile() // Sort the list and remove duplicates. std::sort(lfiles.begin(), lfiles.end(), std::less<std::string>()); #if !defined(__VMS) // The Compaq STL on VMS crashes, so accept duplicates. - std::vector<std::string>::iterator new_end = + std::vector<std::string>::iterator new_end = std::unique(lfiles.begin(),lfiles.end()); lfiles.erase(new_end, lfiles.end()); #endif @@ -317,14 +326,14 @@ void cmGlobalUnixMakefileGenerator3::WriteMainCMakefile() cmakefileStream << "# The top level Makefile was generated from the following files:\n" << "SET(CMAKE_MAKEFILE_DEPENDS\n" - << " \"" + << " \"" << lg->Convert(cache.c_str(), cmLocalGenerator::START_OUTPUT).c_str() << "\"\n"; for(std::vector<std::string>::const_iterator i = lfiles.begin(); i != lfiles.end(); ++i) { cmakefileStream - << " \"" + << " \"" << lg->Convert(i->c_str(), cmLocalGenerator::START_OUTPUT).c_str() << "\"\n"; } @@ -340,10 +349,10 @@ void cmGlobalUnixMakefileGenerator3::WriteMainCMakefile() cmakefileStream << "# The corresponding makefile is:\n" << "SET(CMAKE_MAKEFILE_OUTPUTS\n" - << " \"" + << " \"" << lg->Convert(makefileName.c_str(), cmLocalGenerator::START_OUTPUT).c_str() << "\"\n" - << " \"" + << " \"" << lg->Convert(check.c_str(), cmLocalGenerator::START_OUTPUT).c_str() << "\"\n"; cmakefileStream << " )\n\n"; @@ -367,19 +376,19 @@ void cmGlobalUnixMakefileGenerator3::WriteMainCMakefile() std::string tmpStr; for (unsigned int i = 0; i < this->LocalGenerators.size(); ++i) { - lg = + lg = static_cast<cmLocalUnixMakefileGenerator3 *>(this->LocalGenerators[i]); tmpStr = lg->GetMakefile()->GetStartOutputDirectory(); tmpStr += cmake::GetCMakeFilesDirectory(); tmpStr += "/CMakeDirectoryInformation.cmake"; - cmakefileStream << " \"" << - lg->Convert(tmpStr.c_str(),cmLocalGenerator::HOME_OUTPUT).c_str() + cmakefileStream << " \"" << + lg->Convert(tmpStr.c_str(),cmLocalGenerator::HOME_OUTPUT).c_str() << "\"\n"; } cmakefileStream << " )\n\n"; } - this->WriteMainCMakefileLanguageRules(cmakefileStream, + this->WriteMainCMakefileLanguageRules(cmakefileStream, this->LocalGenerators); } @@ -458,7 +467,7 @@ cmGlobalUnixMakefileGenerator3 // The directory-level rule should depend on the directory-level // rules of the subdirectories. - for(std::vector<cmLocalGenerator*>::iterator sdi = + for(std::vector<cmLocalGenerator*>::iterator sdi = lg->GetChildren().begin(); sdi != lg->GetChildren().end(); ++sdi) { cmLocalUnixMakefileGenerator3* slg = @@ -518,7 +527,7 @@ cmGlobalUnixMakefileGenerator3 std::string cmGlobalUnixMakefileGenerator3 -::GenerateBuildCommand(const char* makeProgram, const char *projectName, +::GenerateBuildCommand(const char* makeProgram, const char *projectName, const char* additionalOptions, const char *targetName, const char* config, bool ignoreErrors, bool fast) { @@ -526,9 +535,9 @@ std::string cmGlobalUnixMakefileGenerator3 (void)projectName; (void)config; - std::string makeCommand = + std::string makeCommand = cmSystemTools::ConvertToUnixOutputPath(makeProgram); - + // Since we have full control over the invocation of nmake, let us // make it quiet. if ( strcmp(this->GetName(), "NMake Makefiles") == 0 ) @@ -563,7 +572,7 @@ std::string cmGlobalUnixMakefileGenerator3 (this->CMakeInstance->GetStartOutputDirectory()); lg->GetMakefile()->MakeStartDirectoriesCurrent(); } - + makeCommand += " \""; std::string tname = targetName; if(fast) @@ -585,14 +594,14 @@ std::string cmGlobalUnixMakefileGenerator3 //---------------------------------------------------------------------------- void cmGlobalUnixMakefileGenerator3 -::WriteConvenienceRules(std::ostream& ruleFileStream, +::WriteConvenienceRules(std::ostream& ruleFileStream, std::set<cmStdString> &emitted) { - std::vector<std::string> depends; + std::vector<std::string> depends; std::vector<std::string> commands; depends.push_back("cmake_check_build_system"); - + // write the target convenience rules unsigned int i; cmLocalUnixMakefileGenerator3 *lg; @@ -622,7 +631,7 @@ cmGlobalUnixMakefileGenerator3 ruleFileStream << "# Target rules for targets named " << t->second.GetName() << "\n\n"; - + // Write the rule. commands.clear(); std::string tmp = cmake::GetCMakeFilesDirectoryPostSlash(); @@ -631,16 +640,16 @@ cmGlobalUnixMakefileGenerator3 (tmp.c_str(),t->second.GetName())); depends.clear(); depends.push_back("cmake_check_build_system"); - lg->WriteMakeRule(ruleFileStream, + lg->WriteMakeRule(ruleFileStream, "Build rule for target.", t->second.GetName(), depends, commands, true); - + // Add a fast rule to build the target std::string localName = lg->GetRelativeTargetDirectory(t->second); std::string makefileName; makefileName = localName; - makefileName += "/build.make"; + makefileName += "/build.make"; depends.clear(); commands.clear(); std::string makeTargetName = localName; @@ -677,10 +686,10 @@ cmGlobalUnixMakefileGenerator3 //---------------------------------------------------------------------------- void cmGlobalUnixMakefileGenerator3 -::WriteConvenienceRules2(std::ostream& ruleFileStream, +::WriteConvenienceRules2(std::ostream& ruleFileStream, cmLocalUnixMakefileGenerator3 *lg) { - std::vector<std::string> depends; + std::vector<std::string> depends; std::vector<std::string> commands; std::string localName; std::string makeTargetName; @@ -688,7 +697,7 @@ cmGlobalUnixMakefileGenerator3 // write the directory level rules for this local gen this->WriteDirectoryRules2(ruleFileStream,lg); - + depends.push_back("cmake_check_build_system"); // for each target Generate the rule files for each target. @@ -708,15 +717,15 @@ cmGlobalUnixMakefileGenerator3 localName = lg->GetRelativeTargetDirectory(t->second); makefileName = localName; makefileName += "/build.make"; - + bool needRequiresStep = this->NeedRequiresStep(t->second); - + lg->WriteDivider(ruleFileStream); ruleFileStream << "# Target rules for target " << localName << "\n\n"; - - commands.clear(); + + commands.clear(); makeTargetName = localName; makeTargetName += "/depend"; commands.push_back(lg->GetRecursiveMakeCall @@ -734,38 +743,43 @@ cmGlobalUnixMakefileGenerator3 makeTargetName += "/build"; commands.push_back(lg->GetRecursiveMakeCall (makefileName.c_str(),makeTargetName.c_str())); - + // Write the rule. localName += "/all"; depends.clear(); + std::string progressDir; - std::string progressDir = - lg->GetMakefile()->GetHomeOutputDirectory(); - progressDir += cmake::GetCMakeFilesDirectory(); + if(!this->NoRuleMessages) { - cmOStringStream progCmd; - progCmd << "$(CMAKE_COMMAND) -E cmake_progress_report "; - // all target counts - progCmd << lg->Convert(progressDir.c_str(), - cmLocalGenerator::FULL, - cmLocalGenerator::SHELL); - progCmd << " "; - std::vector<int> &progFiles = this->ProgressMap[&t->second].Marks; - for (std::vector<int>::iterator i = progFiles.begin(); - i != progFiles.end(); ++i) + progressDir = + lg->GetMakefile()->GetHomeOutputDirectory(); + progressDir += cmake::GetCMakeFilesDirectory(); { - progCmd << " " << *i; + cmOStringStream progCmd; + progCmd << "$(CMAKE_COMMAND) -E cmake_progress_report "; + // all target counts + progCmd << lg->Convert(progressDir.c_str(), + cmLocalGenerator::FULL, + cmLocalGenerator::SHELL); + progCmd << " "; + std::vector<unsigned long>& progFiles = + this->ProgressMap[&t->second].Marks; + for (std::vector<unsigned long>::iterator i = progFiles.begin(); + i != progFiles.end(); ++i) + { + progCmd << " " << *i; + } + commands.push_back(progCmd.str()); } - commands.push_back(progCmd.str()); + progressDir = "Built target "; + progressDir += t->first; + lg->AppendEcho(commands,progressDir.c_str()); } - progressDir = "Built target "; - progressDir += t->first; - lg->AppendEcho(commands,progressDir.c_str()); - + this->AppendGlobalTargetDepends(depends,t->second); lg->WriteMakeRule(ruleFileStream, "All Build rule for target.", localName.c_str(), depends, commands, true); - + // add the all/all dependency if(!this->IsExcluded(this->LocalGenerators[0], t->second)) { @@ -775,54 +789,58 @@ cmGlobalUnixMakefileGenerator3 lg->WriteMakeRule(ruleFileStream, "Include target in all.", "all", depends, commands, true); } - - // Write the rule. - commands.clear(); - progressDir = lg->GetMakefile()->GetHomeOutputDirectory(); - progressDir += cmake::GetCMakeFilesDirectory(); - - { - // TODO: Convert the total progress count to a make variable. - cmOStringStream progCmd; - progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start "; - // # in target - progCmd << lg->Convert(progressDir.c_str(), - cmLocalGenerator::FULL, - cmLocalGenerator::SHELL); - // - std::set<cmTarget *> emitted; - progCmd << " " - << this->CountProgressMarksInTarget(&t->second, emitted); - commands.push_back(progCmd.str()); - } + + if(!this->NoRuleMessages) + { + // Write the rule. + commands.clear(); + progressDir = lg->GetMakefile()->GetHomeOutputDirectory(); + progressDir += cmake::GetCMakeFilesDirectory(); + + { + // TODO: Convert the total progress count to a make variable. + cmOStringStream progCmd; + progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start "; + // # in target + progCmd << lg->Convert(progressDir.c_str(), + cmLocalGenerator::FULL, + cmLocalGenerator::SHELL); + // + std::set<cmTarget *> emitted; + progCmd << " " + << this->CountProgressMarksInTarget(&t->second, emitted); + commands.push_back(progCmd.str()); + } + } std::string tmp = cmake::GetCMakeFilesDirectoryPostSlash(); tmp += "Makefile2"; commands.push_back(lg->GetRecursiveMakeCall (tmp.c_str(),localName.c_str())); - { - cmOStringStream progCmd; - progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start "; // # 0 - progCmd << lg->Convert(progressDir.c_str(), - cmLocalGenerator::FULL, - cmLocalGenerator::SHELL); - progCmd << " 0"; - commands.push_back(progCmd.str()); - } + if(!this->NoRuleMessages) + { + cmOStringStream progCmd; + progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start "; // # 0 + progCmd << lg->Convert(progressDir.c_str(), + cmLocalGenerator::FULL, + cmLocalGenerator::SHELL); + progCmd << " 0"; + commands.push_back(progCmd.str()); + } depends.clear(); depends.push_back("cmake_check_build_system"); localName = lg->GetRelativeTargetDirectory(t->second); localName += "/rule"; - lg->WriteMakeRule(ruleFileStream, + lg->WriteMakeRule(ruleFileStream, "Build rule for subdir invocation for target.", localName.c_str(), depends, commands, true); - + // Add a target with the canonical name (no prefix, suffix or path). commands.clear(); depends.clear(); depends.push_back(localName); lg->WriteMakeRule(ruleFileStream, "Convenience name for target.", t->second.GetName(), depends, commands, true); - + // Add rules to prepare the target for installation. if(t->second.NeedRelinkBeforeInstall(lg->ConfigurationName.c_str())) { @@ -832,7 +850,7 @@ cmGlobalUnixMakefileGenerator3 commands.clear(); commands.push_back(lg->GetRecursiveMakeCall (makefileName.c_str(), localName.c_str())); - lg->WriteMakeRule(ruleFileStream, + lg->WriteMakeRule(ruleFileStream, "Pre-install relink rule for target.", localName.c_str(), depends, commands, true); @@ -845,7 +863,7 @@ cmGlobalUnixMakefileGenerator3 "preinstall", depends, commands, true); } } - + // add the clean rule localName = lg->GetRelativeTargetDirectory(t->second); makeTargetName = localName; @@ -986,7 +1004,7 @@ void cmGlobalUnixMakefileGenerator3::WriteHelpRule lg->AppendEcho(commands,"... all (the default if no target is provided)"); lg->AppendEcho(commands,"... clean"); lg->AppendEcho(commands,"... depend"); - + // Keep track of targets already listed. std::set<cmStdString> emittedTargets; @@ -995,7 +1013,7 @@ void cmGlobalUnixMakefileGenerator3::WriteHelpRule cmLocalUnixMakefileGenerator3 *lg2; for (i = 0; i < this->LocalGenerators.size(); ++i) { - lg2 = + lg2 = static_cast<cmLocalUnixMakefileGenerator3 *>(this->LocalGenerators[i]); // for the passed in makefile or if this is the top Makefile wripte out // the targets diff --git a/Source/cmGlobalUnixMakefileGenerator3.h b/Source/cmGlobalUnixMakefileGenerator3.h index 401888f..cdc9460 100644 --- a/Source/cmGlobalUnixMakefileGenerator3.h +++ b/Source/cmGlobalUnixMakefileGenerator3.h @@ -22,19 +22,19 @@ class cmLocalUnixMakefileGenerator3; * \brief Write a Unix makefiles. * * cmGlobalUnixMakefileGenerator3 manages UNIX build process for a tree - - + + The basic approach of this generator is to produce Makefiles that will all be run with the current working directory set to the Home Output directory. The one exception to this is the subdirectory Makefiles which are created as a convenience and just cd up to the Home Output directory and - invoke the main Makefiles. - + invoke the main Makefiles. + The make process starts with Makefile. Makefile should only contain the targets the user is likely to invoke directly from a make command line. No internal targets should be in this file. Makefile2 contains the internal targets that are required to make the process work. - + Makefile2 in turn will recursively make targets in the correct order. Each target has its own directory <target>.dir and its own makefile build.make in that directory. Also in that directory is a couple makefiles per source file @@ -47,7 +47,7 @@ class cmLocalUnixMakefileGenerator3; rescanned. Rules for custom commands follow the same model as rules for source files. - + */ class cmGlobalUnixMakefileGenerator3 : public cmGlobalGenerator @@ -64,13 +64,13 @@ public: /** Get the documentation entry for this generator. */ virtual void GetDocumentation(cmDocumentationEntry& entry) const; - + ///! Create a local generator appropriate to this Global Generator3 virtual cmLocalGenerator *CreateLocalGenerator(); /** * Try to determine system infomation such as shared library - * extension, pthreads, byte order etc. + * extension, pthreads, byte order etc. */ virtual void EnableLanguage(std::vector<std::string>const& languages, cmMakefile *, bool optional); @@ -78,11 +78,11 @@ public: /** * Generate the all required files for building this project/tree. This * basically creates a series of LocalGenerators for each directory and - * requests that they Generate. + * requests that they Generate. */ virtual void Generate(); - - + + void WriteMainCMakefileLanguageRules(cmGeneratedFileStream& cmakefileStream, std::vector<cmLocalGenerator *> &); @@ -91,7 +91,7 @@ public: cmLocalUnixMakefileGenerator3 *); // write the top lvel target rules - void WriteConvenienceRules(std::ostream& ruleFileStream, + void WriteConvenienceRules(std::ostream& ruleFileStream, std::set<cmStdString> &emitted); /** Get the command to use for a target that has no rule. This is @@ -105,23 +105,13 @@ public: // change the build command for speed virtual std::string GenerateBuildCommand (const char* makeProgram, - const char *projectName, const char* additionalOptions, + const char *projectName, const char* additionalOptions, const char *targetName, const char* config, bool ignoreErrors, bool fast); /** Record per-target progress information. */ void RecordTargetProgress(cmMakefileTargetGenerator* tg); - /** - * If true, the CMake variable CMAKE_VERBOSE_MAKEFILES doesn't have effect - * anymore. Set it to true when writing a generator where short output - * doesn't make sense, e.g. because the full output is parsed by an - * IDE/editor. - */ - bool GetForceVerboseMakefiles() { return this->ForceVerboseMakefiles; } - void SetForceVerboseMakefiles(bool enable) - {this->ForceVerboseMakefiles=enable;} - protected: void WriteMainMakefile2(); void WriteMainCMakefile(); @@ -169,7 +159,7 @@ protected: // in the rule to satisfy the make program. std::string EmptyRuleHackCommand; - bool ForceVerboseMakefiles; + bool NoRuleMessages; // Store per-target progress counters. struct TargetProgress @@ -177,7 +167,7 @@ protected: TargetProgress(): NumberOfActions(0) {} unsigned long NumberOfActions; std::string VariableFile; - std::vector<int> Marks; + std::vector<unsigned long> Marks; void WriteProgressVariables(unsigned long total, unsigned long& current); }; struct ProgressMapCompare { bool operator()(cmTarget*,cmTarget*) const; }; diff --git a/Source/cmGlobalVisualStudio10Generator.cxx b/Source/cmGlobalVisualStudio10Generator.cxx index 691502f..0b939af 100644 --- a/Source/cmGlobalVisualStudio10Generator.cxx +++ b/Source/cmGlobalVisualStudio10Generator.cxx @@ -19,6 +19,10 @@ cmGlobalVisualStudio10Generator::cmGlobalVisualStudio10Generator() { this->FindMakeProgramFile = "CMakeVS10FindMake.cmake"; + std::string vc10Express; + this->ExpressEdition = cmSystemTools::ReadRegistryValue( + "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VCExpress\\10.0\\Setup\\VC;" + "ProductDir", vc10Express, cmSystemTools::KeyWOW64_32); } //---------------------------------------------------------------------------- @@ -40,7 +44,7 @@ void cmGlobalVisualStudio10Generator::WriteSLNHeader(std::ostream& fout) cmLocalGenerator *cmGlobalVisualStudio10Generator::CreateLocalGenerator() { cmLocalVisualStudio10Generator* lg = new cmLocalVisualStudio10Generator; - lg->SetPlatformName(this->PlatformName.c_str()); + lg->SetPlatformName(this->GetPlatformName()); lg->SetGlobalGenerator(this); return lg; } @@ -63,6 +67,16 @@ void cmGlobalVisualStudio10Generator } //---------------------------------------------------------------------------- +const char* cmGlobalVisualStudio10Generator::GetPlatformToolset() +{ + if(!this->PlatformToolset.empty()) + { + return this->PlatformToolset.c_str(); + } + return 0; +} + +//---------------------------------------------------------------------------- std::string cmGlobalVisualStudio10Generator::GetUserMacrosDirectory() { std::string base; diff --git a/Source/cmGlobalVisualStudio10Generator.h b/Source/cmGlobalVisualStudio10Generator.h index 219c36e..bef5642 100644 --- a/Source/cmGlobalVisualStudio10Generator.h +++ b/Source/cmGlobalVisualStudio10Generator.h @@ -54,6 +54,12 @@ public: cmMakefile *, bool optional); virtual void WriteSLNHeader(std::ostream& fout); + /** Is the installed VS an Express edition? */ + bool IsExpressEdition() const { return this->ExpressEdition; } + + /** The toolset name for the target platform. */ + const char* GetPlatformToolset(); + /** * Where does this version of Visual Studio look for macros for the * current user? Returns the empty string if this version of Visual @@ -70,5 +76,9 @@ public: { return "$(Configuration)";} protected: virtual const char* GetIDEVersion() { return "10.0"; } + + std::string PlatformToolset; +private: + bool ExpressEdition; }; #endif diff --git a/Source/cmGlobalVisualStudio10Win64Generator.cxx b/Source/cmGlobalVisualStudio10Win64Generator.cxx index 1004fa9..8600777 100644 --- a/Source/cmGlobalVisualStudio10Win64Generator.cxx +++ b/Source/cmGlobalVisualStudio10Win64Generator.cxx @@ -16,7 +16,6 @@ //---------------------------------------------------------------------------- cmGlobalVisualStudio10Win64Generator::cmGlobalVisualStudio10Win64Generator() { - this->PlatformName = "x64"; } //---------------------------------------------------------------------------- @@ -37,3 +36,52 @@ void cmGlobalVisualStudio10Win64Generator mf->AddDefinition("MSVC_C_ARCHITECTURE_ID", "x64"); mf->AddDefinition("MSVC_CXX_ARCHITECTURE_ID", "x64"); } + +//---------------------------------------------------------------------------- +bool cmGlobalVisualStudio10Win64Generator::Find64BitTools(cmMakefile* mf) +{ + if(!this->PlatformToolset.empty()) + { + return true; + } + // This edition does not come with 64-bit tools. Look for them. + // + // TODO: Detect available tools? x64\v100 exists but does not work? + // KHLM\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\4.0;VCTargetsPath + // c:/Program Files (x86)/MSBuild/Microsoft.Cpp/v4.0/Platforms/ + // {Itanium,Win32,x64}/PlatformToolsets/{v100,v90,Windows7.1SDK} + std::string winSDK_7_1; + if(cmSystemTools::ReadRegistryValue( + "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SDKs\\" + "Windows\\v7.1;InstallationFolder", winSDK_7_1)) + { + cmOStringStream m; + m << "Found Windows SDK v7.1: " << winSDK_7_1; + mf->DisplayStatus(m.str().c_str(), -1); + this->PlatformToolset = "Windows7.1SDK"; + return true; + } + else + { + cmOStringStream e; + e << "Cannot enable 64-bit tools with Visual Studio 2010 Express.\n" + << "Install the Microsoft Windows SDK v7.1 to get 64-bit tools:\n" + << " http://msdn.microsoft.com/en-us/windows/bb980924.aspx"; + mf->IssueMessage(cmake::FATAL_ERROR, e.str().c_str()); + cmSystemTools::SetFatalErrorOccured(); + return false; + } +} + +//---------------------------------------------------------------------------- +void cmGlobalVisualStudio10Win64Generator +::EnableLanguage(std::vector<std::string> const& languages, + cmMakefile* mf, bool optional) +{ + if(this->IsExpressEdition() && !this->Find64BitTools(mf)) + { + return; + } + this->cmGlobalVisualStudio10Generator + ::EnableLanguage(languages, mf, optional); +} diff --git a/Source/cmGlobalVisualStudio10Win64Generator.h b/Source/cmGlobalVisualStudio10Win64Generator.h index 98ba03c..e6d3dc5 100644 --- a/Source/cmGlobalVisualStudio10Win64Generator.h +++ b/Source/cmGlobalVisualStudio10Win64Generator.h @@ -27,10 +27,15 @@ public: return cmGlobalVisualStudio10Win64Generator::GetActualName();} static const char* GetActualName() {return "Visual Studio 10 Win64";} + virtual const char* GetPlatformName() const {return "x64";} + /** Get the documentation entry for this generator. */ virtual void GetDocumentation(cmDocumentationEntry& entry) const; virtual void AddPlatformDefinitions(cmMakefile* mf); + bool Find64BitTools(cmMakefile* mf); + virtual void EnableLanguage(std::vector<std::string>const& languages, + cmMakefile *, bool optional); }; #endif diff --git a/Source/cmGlobalVisualStudio6Generator.cxx b/Source/cmGlobalVisualStudio6Generator.cxx index d053ca2..fe44e20 100644 --- a/Source/cmGlobalVisualStudio6Generator.cxx +++ b/Source/cmGlobalVisualStudio6Generator.cxx @@ -13,6 +13,7 @@ #include "cmLocalVisualStudio6Generator.h" #include "cmMakefile.h" #include "cmake.h" +#include "cmGeneratedFileStream.h" // Utility function to make a valid VS6 *.dsp filename out // of a CMake target name: @@ -196,8 +197,6 @@ void cmGlobalVisualStudio6Generator this->GetTargetSets(projectTargets, originalTargets, root, generators); OrderedTargetDependSet orderedProjectTargets(projectTargets); - std::string rootdir = root->GetMakefile()->GetStartOutputDirectory(); - rootdir += "/"; for(OrderedTargetDependSet::const_iterator tt = orderedProjectTargets.begin(); tt != orderedProjectTargets.end(); ++tt) @@ -274,44 +273,33 @@ void cmGlobalVisualStudio6Generator::WriteProject(std::ostream& fout, fout << "Package=<5>\n{{{\n}}}\n\n"; fout << "Package=<4>\n"; fout << "{{{\n"; - - // insert Begin Project Dependency Project_Dep_Name project stuff here - if (target.GetType() != cmTarget::STATIC_LIBRARY) + VSDependSet const& depends = this->VSTargetDepends[&target]; + for(VSDependSet::const_iterator di = depends.begin(); + di != depends.end(); ++di) { - cmTarget::LinkLibraryVectorType::const_iterator j, jend; - j = target.GetLinkLibraries().begin(); - jend = target.GetLinkLibraries().end(); - for(;j!= jend; ++j) - { - if(j->first != dspname) - { - // is the library part of this DSW ? If so add dependency - if(this->FindTarget(0, j->first.c_str())) - { - fout << "Begin Project Dependency\n"; - fout << "Project_Dep_Name " - << GetVS6TargetName(j->first.c_str()) << "\n"; - fout << "End Project Dependency\n"; - } - } - } + const char* name = di->c_str(); + fout << "Begin Project Dependency\n"; + fout << "Project_Dep_Name " << GetVS6TargetName(name) << "\n"; + fout << "End Project Dependency\n"; } + fout << "}}}\n\n"; - std::set<cmStdString>::const_iterator i, end; - // write utility dependencies. - i = target.GetUtilities().begin(); - end = target.GetUtilities().end(); - for(;i!= end; ++i) + UtilityDependsMap::iterator ui = this->UtilityDepends.find(&target); + if(ui != this->UtilityDepends.end()) { - if(*i != dspname) - { - std::string depName = this->GetUtilityForTarget(target, i->c_str()); - fout << "Begin Project Dependency\n"; - fout << "Project_Dep_Name " << GetVS6TargetName(depName) << "\n"; - fout << "End Project Dependency\n"; - } + const char* uname = ui->second.c_str(); + fout << "Project: \"" << uname << "\"=" + << dir << "\\" << uname << ".dsp - Package Owner=<4>\n\n"; + fout << + "Package=<5>\n{{{\n}}}\n\n" + "Package=<4>\n" + "{{{\n" + "Begin Project Dependency\n" + "Project_Dep_Name " << dspname << "\n" + "End Project Dependency\n" + "}}}\n\n"; + ; } - fout << "}}}\n\n"; } @@ -368,6 +356,49 @@ void cmGlobalVisualStudio6Generator::WriteDSWHeader(std::ostream& fout) } //---------------------------------------------------------------------------- +std::string +cmGlobalVisualStudio6Generator::WriteUtilityDepend(cmTarget* target) +{ + std::string pname = target->GetName(); + pname += "_UTILITY"; + pname = GetVS6TargetName(pname.c_str()); + std::string fname = target->GetMakefile()->GetStartOutputDirectory(); + fname += "/"; + fname += pname; + fname += ".dsp"; + cmGeneratedFileStream fout(fname.c_str()); + fout.SetCopyIfDifferent(true); + fout << + "# Microsoft Developer Studio Project File - Name=\"" + << pname << "\" - Package Owner=<4>\n" + "# Microsoft Developer Studio Generated Build File, Format Version 6.00\n" + "# ** DO NOT EDIT **\n" + "\n" + "# TARGTYPE \"Win32 (x86) Generic Project\" 0x010a\n" + "\n" + "CFG=" << pname << " - Win32 Debug\n" + "!MESSAGE \"" << pname << " - Win32 Debug\"" + " (based on \"Win32 (x86) Generic Project\")\n" + "!MESSAGE \"" << pname << " - Win32 Release\" " + "(based on \"Win32 (x86) Generic Project\")\n" + "!MESSAGE \"" << pname << " - Win32 MinSizeRel\" " + "(based on \"Win32 (x86) Generic Project\")\n" + "!MESSAGE \"" << pname << " - Win32 RelWithDebInfo\" " + "(based on \"Win32 (x86) Generic Project\")\n" + "\n" + "# Begin Project\n" + "# Begin Target\n" + "# Name \"" << pname << " - Win32 Debug\"\n" + "# Name \"" << pname << " - Win32 Release\"\n" + "# Name \"" << pname << " - Win32 MinSizeRel\"\n" + "# Name \"" << pname << " - Win32 RelWithDebInfo\"\n" + "# End Target\n" + "# End Project\n" + ; + return pname; +} + +//---------------------------------------------------------------------------- void cmGlobalVisualStudio6Generator ::GetDocumentation(cmDocumentationEntry& entry) const { diff --git a/Source/cmGlobalVisualStudio6Generator.h b/Source/cmGlobalVisualStudio6Generator.h index 553c7be..77d5370 100644 --- a/Source/cmGlobalVisualStudio6Generator.h +++ b/Source/cmGlobalVisualStudio6Generator.h @@ -96,6 +96,7 @@ private: const char* name, const char* path, const std::set<cmStdString>& dependencies); void WriteDSWFooter(std::ostream& fout); + virtual std::string WriteUtilityDepend(cmTarget* target); }; #endif diff --git a/Source/cmGlobalVisualStudio71Generator.cxx b/Source/cmGlobalVisualStudio71Generator.cxx index d608aac..adb5f2f 100644 --- a/Source/cmGlobalVisualStudio71Generator.cxx +++ b/Source/cmGlobalVisualStudio71Generator.cxx @@ -37,6 +37,7 @@ cmLocalGenerator *cmGlobalVisualStudio71Generator::CreateLocalGenerator() void cmGlobalVisualStudio71Generator::AddPlatformDefinitions(cmMakefile* mf) { this->cmGlobalVisualStudio7Generator::AddPlatformDefinitions(mf); + mf->RemoveDefinition("MSVC70"); mf->AddDefinition("MSVC71", "1"); } @@ -110,6 +111,13 @@ void cmGlobalVisualStudio71Generator OrderedTargetDependSet orderedProjectTargets(projectTargets); this->WriteTargetsToSolution(fout, root, orderedProjectTargets); + + bool useFolderProperty = this->UseFolderProperty(); + if (useFolderProperty) + { + this->WriteFolders(fout); + } + // Write out the configurations information for the solution fout << "Global\n"; // Write out the configurations for the solution @@ -119,6 +127,15 @@ void cmGlobalVisualStudio71Generator // Write out the configurations for all the targets in the project this->WriteTargetConfigurations(fout, root, orderedProjectTargets); fout << "\tEndGlobalSection\n"; + + if (useFolderProperty) + { + // Write out project folders + fout << "\tGlobalSection(NestedProjects) = preSolution\n"; + this->WriteFoldersContent(fout); + fout << "\tEndGlobalSection\n"; + } + // Write the footer for the SLN file this->WriteSLNFooter(fout); } @@ -162,16 +179,31 @@ cmGlobalVisualStudio71Generator::WriteProject(std::ostream& fout, ext = targetExt; } + std::string guid = this->GetGUID(dspname); fout << project << dspname << "\", \"" - << this->ConvertToSolutionPath(dir) - << "\\" << dspname << ext << "\", \"{" - << this->GetGUID(dspname) << "}\"\n"; + << this->ConvertToSolutionPath(dir) << (dir[0]? "\\":"") + << dspname << ext << "\", \"{" << guid << "}\"\n"; fout << "\tProjectSection(ProjectDependencies) = postProject\n"; this->WriteProjectDepends(fout, dspname, dir, t); fout << "\tEndProjectSection\n"; fout <<"EndProject\n"; + + UtilityDependsMap::iterator ui = this->UtilityDepends.find(&t); + if(ui != this->UtilityDepends.end()) + { + const char* uname = ui->second.c_str(); + fout << "Project(\"{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}\") = \"" + << uname << "\", \"" + << this->ConvertToSolutionPath(dir) << (dir[0]? "\\":"") + << uname << ".vcproj" << "\", \"{" + << this->GetGUID(uname) << "}\"\n" + << "\tProjectSection(ProjectDependencies) = postProject\n" + << "\t\t{" << guid << "} = {" << guid << "}\n" + << "\tEndProjectSection\n" + << "EndProject\n"; + } } //---------------------------------------------------------------------------- @@ -181,62 +213,24 @@ cmGlobalVisualStudio71Generator::WriteProject(std::ostream& fout, void cmGlobalVisualStudio71Generator ::WriteProjectDepends(std::ostream& fout, - const char* dspname, + const char*, const char*, cmTarget& target) { -#if 0 - // Create inter-target dependencies in the solution file. For VS - // 7.1 and below we cannot let static libraries depend directly on - // targets to which they "link" because the librarian tool will copy - // the targets into the static library. See - // cmGlobalVisualStudioGenerator::FixUtilityDependsForTarget for a - // work-around. VS 8 and above do not have this problem. - if (!this->VSLinksDependencies() || - target.GetType() != cmTarget::STATIC_LIBRARY); -#else - if (target.GetType() != cmTarget::STATIC_LIBRARY) -#endif + VSDependSet const& depends = this->VSTargetDepends[&target]; + for(VSDependSet::const_iterator di = depends.begin(); + di != depends.end(); ++di) { - cmTarget::LinkLibraryVectorType::const_iterator j, jend; - j = target.GetLinkLibraries().begin(); - jend = target.GetLinkLibraries().end(); - for(;j!= jend; ++j) + const char* name = di->c_str(); + std::string guid = this->GetGUID(name); + if(guid.size() == 0) { - if(j->first != dspname) - { - // is the library part of this SLN ? If so add dependency - // find target anywhere because all depend libraries are - // brought in as well - if(this->FindTarget(0, j->first.c_str())) - { - fout << "\t\t{" << this->GetGUID(j->first.c_str()) << "} = {" - << this->GetGUID(j->first.c_str()) << "}\n"; - } - } - } - } - - std::set<cmStdString>::const_iterator i, end; - // write utility dependencies. - i = target.GetUtilities().begin(); - end = target.GetUtilities().end(); - for(;i!= end; ++i) - { - if(*i != dspname) - { - std::string name = this->GetUtilityForTarget(target, i->c_str()); - std::string guid = this->GetGUID(name.c_str()); - if(guid.size() == 0) - { - std::string m = "Target: "; - m += target.GetName(); - m += " depends on unknown target: "; - m += name; - cmSystemTools::Error(m.c_str()); - } - - fout << "\t\t{" << guid << "} = {" << guid << "}\n"; + std::string m = "Target: "; + m += target.GetName(); + m += " depends on unknown target: "; + m += name; + cmSystemTools::Error(m.c_str()); } + fout << "\t\t{" << guid << "} = {" << guid << "}\n"; } } diff --git a/Source/cmGlobalVisualStudio7Generator.cxx b/Source/cmGlobalVisualStudio7Generator.cxx index 9631e9a..51b8918 100644 --- a/Source/cmGlobalVisualStudio7Generator.cxx +++ b/Source/cmGlobalVisualStudio7Generator.cxx @@ -273,12 +273,12 @@ void cmGlobalVisualStudio7Generator::WriteTargetsToSolution( cmLocalGenerator* root, OrderedTargetDependSet const& projectTargets) { - std::string rootdir = root->GetMakefile()->GetStartOutputDirectory(); - rootdir += "/"; for(OrderedTargetDependSet::const_iterator tt = projectTargets.begin(); tt != projectTargets.end(); ++tt) { cmTarget* target = *tt; + bool written = false; + // handle external vc project files const char* expath = target->GetProperty("EXTERNAL_MSPROJECT"); if(expath) @@ -287,6 +287,7 @@ void cmGlobalVisualStudio7Generator::WriteTargetsToSolution( std::string location = expath; this->WriteExternalProject(fout, project.c_str(), location.c_str(), target->GetUtilities()); + written = true; } else { @@ -298,8 +299,55 @@ void cmGlobalVisualStudio7Generator::WriteTargetsToSolution( std::string dir = tmf->GetStartOutputDirectory(); dir = root->Convert(dir.c_str(), cmLocalGenerator::START_OUTPUT); + if(dir == ".") + { + dir = ""; // msbuild cannot handle ".\" prefix + } this->WriteProject(fout, vcprojName, dir.c_str(), *target); + written = true; + } + } + + // Create "solution folder" information from FOLDER target property + // + if (written && this->UseFolderProperty()) + { + const char *targetFolder = target->GetProperty("FOLDER"); + if (targetFolder) + { + std::vector<cmsys::String> tokens = + cmSystemTools::SplitString(targetFolder, '/', false); + + std::string cumulativePath = ""; + + for(std::vector<cmsys::String>::iterator iter = tokens.begin(); + iter != tokens.end(); ++iter) + { + if(!iter->size()) + { + continue; + } + + if (cumulativePath.empty()) + { + cumulativePath = "CMAKE_FOLDER_GUID_" + *iter; + } + else + { + VisualStudioFolders[cumulativePath].insert( + cumulativePath + "/" + *iter); + + cumulativePath = cumulativePath + "/" + *iter; + } + + this->CreateGUID(cumulativePath.c_str()); + } + + if (!cumulativePath.empty()) + { + VisualStudioFolders[cumulativePath].insert(target->GetName()); + } } } } @@ -327,6 +375,7 @@ void cmGlobalVisualStudio7Generator::WriteTargetDepends( } } +//---------------------------------------------------------------------------- // Write a SLN file to the stream void cmGlobalVisualStudio7Generator ::WriteSLNFile(std::ostream& fout, @@ -344,6 +393,13 @@ void cmGlobalVisualStudio7Generator OrderedTargetDependSet orderedProjectTargets(projectTargets); this->WriteTargetsToSolution(fout, root, orderedProjectTargets); + + bool useFolderProperty = this->UseFolderProperty(); + if (useFolderProperty) + { + this->WriteFolders(fout); + } + // Write out the configurations information for the solution fout << "Global\n" << "\tGlobalSection(SolutionConfiguration) = preSolution\n"; @@ -361,6 +417,14 @@ void cmGlobalVisualStudio7Generator this->WriteTargetDepends(fout, orderedProjectTargets); fout << "\tEndGlobalSection\n"; + if (useFolderProperty) + { + // Write out project folders + fout << "\tGlobalSection(NestedProjects) = preSolution\n"; + this->WriteFoldersContent(fout); + fout << "\tEndGlobalSection\n"; + } + // Write out the configurations for all the targets in the project fout << "\tGlobalSection(ProjectConfiguration) = postSolution\n"; this->WriteTargetConfigurations(fout, root, orderedProjectTargets); @@ -371,6 +435,55 @@ void cmGlobalVisualStudio7Generator } //---------------------------------------------------------------------------- +void cmGlobalVisualStudio7Generator::WriteFolders(std::ostream& fout) +{ + const char *prefix = "CMAKE_FOLDER_GUID_"; + const std::string::size_type skip_prefix = strlen(prefix); + std::string guidProjectTypeFolder = "2150E333-8FDC-42A3-9474-1A3956D46DE8"; + for(std::map<std::string,std::set<std::string> >::iterator iter = + VisualStudioFolders.begin(); iter != VisualStudioFolders.end(); ++iter) + { + std::string fullName = iter->first; + std::string guid = this->GetGUID(fullName.c_str()); + + cmSystemTools::ReplaceString(fullName, "/", "\\"); + if (cmSystemTools::StringStartsWith(fullName.c_str(), prefix)) + { + fullName = fullName.substr(skip_prefix); + } + + std::string nameOnly = cmSystemTools::GetFilenameName(fullName); + + fout << "Project(\"{" << + guidProjectTypeFolder << "}\") = \"" << + nameOnly << "\", \"" << + fullName << "\", \"{" << + guid << + "}\"\nEndProject\n"; + } +} + +//---------------------------------------------------------------------------- +void cmGlobalVisualStudio7Generator::WriteFoldersContent(std::ostream& fout) +{ + for(std::map<std::string,std::set<std::string> >::iterator iter = + VisualStudioFolders.begin(); iter != VisualStudioFolders.end(); ++iter) + { + std::string key(iter->first); + std::string guidParent(this->GetGUID(key.c_str())); + + for(std::set<std::string>::iterator it = iter->second.begin(); + it != iter->second.end(); ++it) + { + std::string value(*it); + std::string guid(this->GetGUID(value.c_str())); + + fout << "\t\t{" << guid << "} = {" << guidParent << "}\n"; + } + } +} + +//---------------------------------------------------------------------------- std::string cmGlobalVisualStudio7Generator::ConvertToSolutionPath(const char* path) { @@ -405,9 +518,21 @@ void cmGlobalVisualStudio7Generator::WriteProject(std::ostream& fout, fout << project << dspname << "\", \"" - << this->ConvertToSolutionPath(dir) - << "\\" << dspname << ext << "\", \"{" + << this->ConvertToSolutionPath(dir) << (dir[0]? "\\":"") + << dspname << ext << "\", \"{" << this->GetGUID(dspname) << "}\"\nEndProject\n"; + + UtilityDependsMap::iterator ui = this->UtilityDepends.find(&target); + if(ui != this->UtilityDepends.end()) + { + const char* uname = ui->second.c_str(); + fout << "Project(\"{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}\") = \"" + << uname << "\", \"" + << this->ConvertToSolutionPath(dir) << (dir[0]? "\\":"") + << uname << ".vcproj" << "\", \"{" + << this->GetGUID(uname) << "}\"\n" + << "EndProject\n"; + } } @@ -422,59 +547,30 @@ cmGlobalVisualStudio7Generator const char*, cmTarget& target) { int depcount = 0; - // insert Begin Project Dependency Project_Dep_Name project stuff here - if (target.GetType() != cmTarget::STATIC_LIBRARY) - { - cmTarget::LinkLibraryVectorType::const_iterator j, jend; - j = target.GetLinkLibraries().begin(); - jend = target.GetLinkLibraries().end(); - for(;j!= jend; ++j) + std::string dspguid = this->GetGUID(dspname); + VSDependSet const& depends = this->VSTargetDepends[&target]; + for(VSDependSet::const_iterator di = depends.begin(); + di != depends.end(); ++di) + { + const char* name = di->c_str(); + std::string guid = this->GetGUID(name); + if(guid.size() == 0) { - if(j->first != dspname) - { - // is the library part of this SLN ? If so add dependency - if(this->FindTarget(0, j->first.c_str())) - { - std::string guid = this->GetGUID(j->first.c_str()); - if(guid.size() == 0) - { - std::string m = "Target: "; - m += dspname; - m += " depends on unknown target: "; - m += j->first.c_str(); - cmSystemTools::Error(m.c_str()); - } - fout << "\t\t{" << this->GetGUID(dspname) << "}." - << depcount << " = {" << guid << "}\n"; - depcount++; - } - } + std::string m = "Target: "; + m += target.GetName(); + m += " depends on unknown target: "; + m += name; + cmSystemTools::Error(m.c_str()); } + fout << "\t\t{" << dspguid << "}." << depcount << " = {" << guid << "}\n"; + depcount++; } - std::set<cmStdString>::const_iterator i, end; - // write utility dependencies. - i = target.GetUtilities().begin(); - end = target.GetUtilities().end(); - for(;i!= end; ++i) + UtilityDependsMap::iterator ui = this->UtilityDepends.find(&target); + if(ui != this->UtilityDepends.end()) { - if(*i != dspname) - { - std::string name = this->GetUtilityForTarget(target, i->c_str()); - std::string guid = this->GetGUID(name.c_str()); - if(guid.size() == 0) - { - std::string m = "Target: "; - m += dspname; - m += " depends on unknown target: "; - m += name.c_str(); - cmSystemTools::Error(m.c_str()); - } - - fout << "\t\t{" << this->GetGUID(dspname) << "}." << depcount << " = {" - << guid << "}\n"; - depcount++; - } + const char* uname = ui->second.c_str(); + fout << "\t\t{" << this->GetGUID(uname) << "}.0 = {" << dspguid << "}\n"; } } @@ -537,6 +633,61 @@ void cmGlobalVisualStudio7Generator::WriteSLNHeader(std::ostream& fout) fout << "Microsoft Visual Studio Solution File, Format Version 7.00\n"; } +//---------------------------------------------------------------------------- +std::string +cmGlobalVisualStudio7Generator::WriteUtilityDepend(cmTarget* target) +{ + std::string pname = target->GetName(); + pname += "_UTILITY"; + std::string fname = target->GetMakefile()->GetStartOutputDirectory(); + fname += "/"; + fname += pname; + fname += ".vcproj"; + cmGeneratedFileStream fout(fname.c_str()); + fout.SetCopyIfDifferent(true); + this->CreateGUID(pname.c_str()); + std::string guid = this->GetGUID(pname.c_str()); + + fout << + "<?xml version=\"1.0\" encoding = \"Windows-1252\"?>\n" + "<VisualStudioProject\n" + "\tProjectType=\"Visual C++\"\n" + "\tVersion=\"" << this->GetIDEVersion() << "0\"\n" + "\tName=\"" << pname << "\"\n" + "\tProjectGUID=\"{" << guid << "}\"\n" + "\tKeyword=\"Win32Proj\">\n" + "\t<Platforms><Platform Name=\"Win32\"/></Platforms>\n" + "\t<Configurations>\n" + ; + for(std::vector<std::string>::iterator i = this->Configurations.begin(); + i != this->Configurations.end(); ++i) + { + fout << + "\t\t<Configuration\n" + "\t\t\tName=\"" << *i << "|Win32\"\n" + "\t\t\tOutputDirectory=\"" << *i << "\"\n" + "\t\t\tIntermediateDirectory=\"" << pname << ".dir\\" << *i << "\"\n" + "\t\t\tConfigurationType=\"10\"\n" + "\t\t\tUseOfMFC=\"0\"\n" + "\t\t\tATLMinimizesCRunTimeLibraryUsage=\"FALSE\"\n" + "\t\t\tCharacterSet=\"2\">\n" + "\t\t</Configuration>\n" + ; + } + fout << + "\t</Configurations>\n" + "\t<Files></Files>\n" + "\t<Globals></Globals>\n" + "</VisualStudioProject>\n" + ; + + if(fout.Close()) + { + this->FileReplacedDuringGenerate(fname); + } + return pname; +} + std::string cmGlobalVisualStudio7Generator::GetGUID(const char* name) { std::string guidStoreName = name; diff --git a/Source/cmGlobalVisualStudio7Generator.h b/Source/cmGlobalVisualStudio7Generator.h index 85ba244..b6c84e8 100644 --- a/Source/cmGlobalVisualStudio7Generator.h +++ b/Source/cmGlobalVisualStudio7Generator.h @@ -113,6 +113,7 @@ protected: bool partOfDefaultBuild); virtual void WriteSLNFooter(std::ostream& fout); virtual void WriteSLNHeader(std::ostream& fout); + virtual std::string WriteUtilityDepend(cmTarget* target); virtual void AddPlatformDefinitions(cmMakefile* mf); virtual void WriteTargetsToSolution( @@ -142,6 +143,10 @@ protected: std::vector<std::string> Configurations; std::map<cmStdString, cmStdString> GUIDMap; + virtual void WriteFolders(std::ostream& fout); + virtual void WriteFoldersContent(std::ostream& fout); + std::map<std::string,std::set<std::string> > VisualStudioFolders; + // Set during OutputSLNFile with the name of the current project. // There is one SLN file per project. std::string CurrentProject; diff --git a/Source/cmGlobalVisualStudio8Generator.cxx b/Source/cmGlobalVisualStudio8Generator.cxx index e423174..2d080df 100644 --- a/Source/cmGlobalVisualStudio8Generator.cxx +++ b/Source/cmGlobalVisualStudio8Generator.cxx @@ -21,7 +21,7 @@ cmGlobalVisualStudio8Generator::cmGlobalVisualStudio8Generator() { this->FindMakeProgramFile = "CMakeVS8FindMake.cmake"; this->ProjectConfigurationSectionName = "ProjectConfigurationPlatforms"; - this->PlatformName = "Win32"; + this->ArchitectureId = "X86"; } //---------------------------------------------------------------------------- @@ -30,6 +30,7 @@ cmLocalGenerator *cmGlobalVisualStudio8Generator::CreateLocalGenerator() { cmLocalVisualStudio7Generator *lg = new cmLocalVisualStudio7Generator; lg->SetVersion8(); + lg->SetPlatformName(this->GetPlatformName()); lg->SetExtraFlagTable(this->GetExtraFlagTableVS8()); lg->SetGlobalGenerator(this); return lg; @@ -55,8 +56,8 @@ void cmGlobalVisualStudio8Generator //---------------------------------------------------------------------------- void cmGlobalVisualStudio8Generator::AddPlatformDefinitions(cmMakefile* mf) { - mf->AddDefinition("MSVC_C_ARCHITECTURE_ID", "X86"); - mf->AddDefinition("MSVC_CXX_ARCHITECTURE_ID", "X86"); + mf->AddDefinition("MSVC_C_ARCHITECTURE_ID", this->ArchitectureId); + mf->AddDefinition("MSVC_CXX_ARCHITECTURE_ID", this->ArchitectureId); mf->AddDefinition("MSVC80", "1"); } @@ -136,6 +137,13 @@ void cmGlobalVisualStudio8Generator::AddCheckTarget() no_working_directory, no_depends, noCommandLines); + // Organize in the "predefined targets" folder: + // + if (this->UseFolderProperty()) + { + tgt->SetProperty("FOLDER", this->GetPredefinedTargetsFolder()); + } + // Create a list of all stamp files for this project. std::vector<std::string> stamps; std::string stampList = cmake::GetCMakeFilesDirectoryPostSlash(); @@ -154,8 +162,6 @@ void cmGlobalVisualStudio8Generator::AddCheckTarget() stampFile += "/"; stampFile += cmake::GetCMakeFilesDirectoryPostSlash(); stampFile += "generate.stamp"; - stampFile = generators[0]->Convert(stampFile.c_str(), - cmLocalGenerator::START_OUTPUT); fout << stampFile << "\n"; stamps.push_back(stampFile); } @@ -254,8 +260,8 @@ cmGlobalVisualStudio8Generator for(std::vector<std::string>::iterator i = this->Configurations.begin(); i != this->Configurations.end(); ++i) { - fout << "\t\t" << *i << "|" << this->PlatformName << " = " << *i << "|" - << this->PlatformName << "\n"; + fout << "\t\t" << *i << "|" << this->GetPlatformName() + << " = " << *i << "|" << this->GetPlatformName() << "\n"; } fout << "\tEndGlobalSection\n"; } @@ -271,18 +277,40 @@ cmGlobalVisualStudio8Generator i != this->Configurations.end(); ++i) { fout << "\t\t{" << guid << "}." << *i - << "|" << this->PlatformName << ".ActiveCfg = " - << *i << "|" << this->PlatformName << "\n"; + << "|" << this->GetPlatformName() << ".ActiveCfg = " + << *i << "|" << this->GetPlatformName() << "\n"; if(partOfDefaultBuild) { fout << "\t\t{" << guid << "}." << *i - << "|" << this->PlatformName << ".Build.0 = " - << *i << "|" << this->PlatformName << "\n"; + << "|" << this->GetPlatformName() << ".Build.0 = " + << *i << "|" << this->GetPlatformName() << "\n"; } } } //---------------------------------------------------------------------------- +bool cmGlobalVisualStudio8Generator::ComputeTargetDepends() +{ + // Skip over the cmGlobalVisualStudioGenerator implementation! + // We do not need the support that VS <= 7.1 needs. + return this->cmGlobalGenerator::ComputeTargetDepends(); +} + +//---------------------------------------------------------------------------- +void cmGlobalVisualStudio8Generator::WriteProjectDepends( + std::ostream& fout, const char*, const char*, cmTarget& t) +{ + TargetDependSet const& unordered = this->GetTargetDirectDepends(t); + OrderedTargetDependSet depends(unordered); + for(OrderedTargetDependSet::const_iterator i = depends.begin(); + i != depends.end(); ++i) + { + std::string guid = this->GetGUID((*i)->GetName()); + fout << "\t\t{" << guid << "} = {" << guid << "}\n"; + } +} + +//---------------------------------------------------------------------------- bool cmGlobalVisualStudio8Generator::NeedLinkLibraryDependencies( cmTarget& target) { diff --git a/Source/cmGlobalVisualStudio8Generator.h b/Source/cmGlobalVisualStudio8Generator.h index 9d836bd..e0913ed 100644 --- a/Source/cmGlobalVisualStudio8Generator.h +++ b/Source/cmGlobalVisualStudio8Generator.h @@ -32,14 +32,14 @@ public: return cmGlobalVisualStudio8Generator::GetActualName();} static const char* GetActualName() {return "Visual Studio 8 2005";} + virtual const char* GetPlatformName() const {return "Win32";} + /** Get the documentation entry for this generator. */ virtual void GetDocumentation(cmDocumentationEntry& entry) const; ///! Create a local generator appropriate to this Global Generator virtual cmLocalGenerator *CreateLocalGenerator(); - std::string const& GetPlatformName() const { return this->PlatformName; } - /** * Override Configure and Generate to add the build-system check * target. @@ -78,6 +78,10 @@ protected: virtual void WriteProjectConfigurations(std::ostream& fout, const char* name, bool partOfDefaultBuild); - std::string PlatformName; // Win32 or x64 + virtual bool ComputeTargetDepends(); + virtual void WriteProjectDepends(std::ostream& fout, const char* name, + const char* path, cmTarget &t); + + const char* ArchitectureId; }; #endif diff --git a/Source/cmGlobalVisualStudio8Win64Generator.cxx b/Source/cmGlobalVisualStudio8Win64Generator.cxx index d5558bb..3469b17 100644 --- a/Source/cmGlobalVisualStudio8Win64Generator.cxx +++ b/Source/cmGlobalVisualStudio8Win64Generator.cxx @@ -19,7 +19,7 @@ cmGlobalVisualStudio8Win64Generator::cmGlobalVisualStudio8Win64Generator() { - this->PlatformName = "x64"; + this->ArchitectureId = "x64"; } ///! Create a local generator appropriate to this Global Generator @@ -27,7 +27,7 @@ cmLocalGenerator *cmGlobalVisualStudio8Win64Generator::CreateLocalGenerator() { cmLocalVisualStudio7Generator *lg = new cmLocalVisualStudio7Generator; lg->SetVersion8(); - lg->SetPlatformName(this->PlatformName.c_str()); + lg->SetPlatformName(this->GetPlatformName()); lg->SetExtraFlagTable(this->GetExtraFlagTableVS8()); lg->SetGlobalGenerator(this); return lg; @@ -48,6 +48,4 @@ void cmGlobalVisualStudio8Win64Generator { this->cmGlobalVisualStudio8Generator::AddPlatformDefinitions(mf); mf->AddDefinition("CMAKE_FORCE_WIN64", "TRUE"); - mf->AddDefinition("MSVC_C_ARCHITECTURE_ID", "x64"); - mf->AddDefinition("MSVC_CXX_ARCHITECTURE_ID", "x64"); } diff --git a/Source/cmGlobalVisualStudio8Win64Generator.h b/Source/cmGlobalVisualStudio8Win64Generator.h index 44c237c..084ba69 100644 --- a/Source/cmGlobalVisualStudio8Win64Generator.h +++ b/Source/cmGlobalVisualStudio8Win64Generator.h @@ -33,6 +33,8 @@ public: return cmGlobalVisualStudio8Win64Generator::GetActualName();} static const char* GetActualName() {return "Visual Studio 8 2005 Win64";} + virtual const char* GetPlatformName() const {return "x64";} + /** Get the documentation entry for this generator. */ virtual void GetDocumentation(cmDocumentationEntry& entry) const; diff --git a/Source/cmGlobalVisualStudio9Generator.cxx b/Source/cmGlobalVisualStudio9Generator.cxx index f6ae705..f8ceea0 100644 --- a/Source/cmGlobalVisualStudio9Generator.cxx +++ b/Source/cmGlobalVisualStudio9Generator.cxx @@ -25,8 +25,8 @@ cmGlobalVisualStudio9Generator::cmGlobalVisualStudio9Generator() //---------------------------------------------------------------------------- void cmGlobalVisualStudio9Generator::AddPlatformDefinitions(cmMakefile* mf) { - mf->AddDefinition("MSVC_C_ARCHITECTURE_ID", "X86"); - mf->AddDefinition("MSVC_CXX_ARCHITECTURE_ID", "X86"); + mf->AddDefinition("MSVC_C_ARCHITECTURE_ID", this->ArchitectureId); + mf->AddDefinition("MSVC_CXX_ARCHITECTURE_ID", this->ArchitectureId); mf->AddDefinition("MSVC90", "1"); } @@ -42,6 +42,7 @@ cmLocalGenerator *cmGlobalVisualStudio9Generator::CreateLocalGenerator() { cmLocalVisualStudio7Generator *lg = new cmLocalVisualStudio7Generator; lg->SetVersion9(); + lg->SetPlatformName(this->GetPlatformName()); lg->SetExtraFlagTable(this->GetExtraFlagTableVS8()); lg->SetGlobalGenerator(this); return lg; diff --git a/Source/cmGlobalVisualStudio9Win64Generator.cxx b/Source/cmGlobalVisualStudio9Win64Generator.cxx index c5b9bab..ff4fd4f 100644 --- a/Source/cmGlobalVisualStudio9Win64Generator.cxx +++ b/Source/cmGlobalVisualStudio9Win64Generator.cxx @@ -16,7 +16,7 @@ cmGlobalVisualStudio9Win64Generator::cmGlobalVisualStudio9Win64Generator() { - this->PlatformName = "x64"; + this->ArchitectureId = "x64"; } ///! Create a local generator appropriate to this Global Generator @@ -24,7 +24,7 @@ cmLocalGenerator *cmGlobalVisualStudio9Win64Generator::CreateLocalGenerator() { cmLocalVisualStudio7Generator *lg = new cmLocalVisualStudio7Generator; lg->SetVersion9(); - lg->SetPlatformName(this->PlatformName.c_str()); + lg->SetPlatformName(this->GetPlatformName()); lg->SetExtraFlagTable(this->GetExtraFlagTableVS8()); lg->SetGlobalGenerator(this); return lg; @@ -45,6 +45,4 @@ void cmGlobalVisualStudio9Win64Generator { cmGlobalVisualStudio9Generator::AddPlatformDefinitions(mf); mf->AddDefinition("CMAKE_FORCE_WIN64", "TRUE"); - mf->AddDefinition("MSVC_C_ARCHITECTURE_ID", "x64"); - mf->AddDefinition("MSVC_CXX_ARCHITECTURE_ID", "x64"); } diff --git a/Source/cmGlobalVisualStudio9Win64Generator.h b/Source/cmGlobalVisualStudio9Win64Generator.h index 55abcfc..f6dcc03 100644 --- a/Source/cmGlobalVisualStudio9Win64Generator.h +++ b/Source/cmGlobalVisualStudio9Win64Generator.h @@ -33,6 +33,8 @@ public: return cmGlobalVisualStudio9Win64Generator::GetActualName();} static const char* GetActualName() {return "Visual Studio 9 2008 Win64";} + virtual const char* GetPlatformName() const {return "x64";} + /** Get the documentation entry for this generator. */ virtual void GetDocumentation(cmDocumentationEntry& entry) const; diff --git a/Source/cmGlobalVisualStudioGenerator.cxx b/Source/cmGlobalVisualStudioGenerator.cxx index 85b4a71..449d090 100644 --- a/Source/cmGlobalVisualStudioGenerator.cxx +++ b/Source/cmGlobalVisualStudioGenerator.cxx @@ -56,6 +56,21 @@ void cmGlobalVisualStudioGenerator::Generate() AddUtilityCommand("ALL_BUILD", true, no_working_dir, no_depends, no_commands, false, "Build all projects"); + +#if 0 + // Can't activate this code because we want ALL_BUILD + // selected as the default "startup project" when first + // opened in Visual Studio... And if it's nested in a + // folder, then that doesn't happen. + // + // Organize in the "predefined targets" folder: + // + if (this->UseFolderProperty()) + { + allBuild->SetProperty("FOLDER", this->GetPredefinedTargetsFolder()); + } +#endif + // Now make all targets depend on the ALL_BUILD target cmTargets targets; for(std::vector<cmLocalGenerator*>::iterator i = gen.begin(); @@ -74,9 +89,6 @@ void cmGlobalVisualStudioGenerator::Generate() } } - // Fix utility dependencies to avoid linking to libraries. - this->FixUtilityDepends(); - // Configure CMake Visual Studio macros, for this user on this version // of Visual Studio. this->ConfigureCMakeVisualStudioMacros(); @@ -225,211 +237,192 @@ std::string cmGlobalVisualStudioGenerator::GetUserMacrosRegKeyBase() } //---------------------------------------------------------------------------- -void cmGlobalVisualStudioGenerator::FixUtilityDepends() +void cmGlobalVisualStudioGenerator::FillLinkClosure(cmTarget* target, + TargetSet& linked) { - // Skip for VS versions 8 and above. - if(!this->VSLinksDependencies()) + if(linked.insert(target).second) { - return; - } - - // For VS versions before 8: - // - // When a target that links contains a project-level dependency on a - // library target that library is automatically linked. In order to - // allow utility-style project-level dependencies that do not - // actually link we need to automatically insert an intermediate - // custom target. - // - // Here we edit the utility dependencies of a target to add the - // intermediate custom target when necessary. - for(unsigned i = 0; i < this->LocalGenerators.size(); ++i) - { - cmTargets* targets = - &(this->LocalGenerators[i]->GetMakefile()->GetTargets()); - for(cmTargets::iterator tarIt = targets->begin(); - tarIt != targets->end(); ++tarIt) + TargetDependSet const& depends = this->GetTargetDirectDepends(*target); + for(TargetDependSet::const_iterator di = depends.begin(); + di != depends.end(); ++di) { - this->FixUtilityDependsForTarget(tarIt->second); + if(di->IsLink()) + { + this->FillLinkClosure(*di, linked); + } } } } //---------------------------------------------------------------------------- -void -cmGlobalVisualStudioGenerator::FixUtilityDependsForTarget(cmTarget& target) +cmGlobalVisualStudioGenerator::TargetSet const& +cmGlobalVisualStudioGenerator::GetTargetLinkClosure(cmTarget* target) { - // Only targets that link need to be fixed. - if(target.GetType() != cmTarget::STATIC_LIBRARY && - target.GetType() != cmTarget::SHARED_LIBRARY && - target.GetType() != cmTarget::MODULE_LIBRARY && - target.GetType() != cmTarget::EXECUTABLE) + TargetSetMap::iterator i = this->TargetLinkClosure.find(target); + if(i == this->TargetLinkClosure.end()) { - return; + TargetSetMap::value_type entry(target, TargetSet()); + i = this->TargetLinkClosure.insert(entry).first; + this->FillLinkClosure(target, i->second); } + return i->second; +} -#if 0 - // This feature makes a mess in SLN files for VS 7.1 and below. It - // creates an extra target for every target that is "linked" by a - // static library. Without this feature static libraries do not - // wait until their "link" dependencies are built to build. This is - // not a problem 99.9% of the time, and projects that do have the - // problem can enable this work-around by using add_dependencies. - - // Static libraries cannot depend directly on the targets to which - // they link because VS will copy those targets into the library - // (for VS < 8). To work around the problem we copy the - // dependencies to be utility dependencies so that the work-around - // below is used. - if(target.GetType() == cmTarget::STATIC_LIBRARY) +//---------------------------------------------------------------------------- +void cmGlobalVisualStudioGenerator::FollowLinkDepends( + cmTarget* target, std::set<cmTarget*>& linked) +{ + if(linked.insert(target).second && + target->GetType() == cmTarget::STATIC_LIBRARY) { - cmTarget::LinkLibraryVectorType const& libs = target.GetLinkLibraries(); - for(cmTarget::LinkLibraryVectorType::const_iterator i = libs.begin(); - i != libs.end(); ++i) + // Static library targets do not list their link dependencies so + // we must follow them transitively now. + TargetDependSet const& depends = this->GetTargetDirectDepends(*target); + for(TargetDependSet::const_iterator di = depends.begin(); + di != depends.end(); ++di) { - if(cmTarget* depTarget = this->FindTarget(0, i->first.c_str(), false)) + if(di->IsLink()) { - target.AddUtility(depTarget->GetName()); + this->FollowLinkDepends(*di, linked); } } } -#endif +} - // Look at each utility dependency. - for(std::set<cmStdString>::const_iterator ui = - target.GetUtilities().begin(); - ui != target.GetUtilities().end(); ++ui) +//---------------------------------------------------------------------------- +bool cmGlobalVisualStudioGenerator::ComputeTargetDepends() +{ + if(!this->cmGlobalGenerator::ComputeTargetDepends()) + { + return false; + } + std::map<cmStdString, std::vector<cmLocalGenerator*> >::iterator it; + for(it = this->ProjectMap.begin(); it!= this->ProjectMap.end(); ++it) { - if(cmTarget* depTarget = this->FindTarget(0, ui->c_str())) + std::vector<cmLocalGenerator*>& gen = it->second; + for(std::vector<cmLocalGenerator*>::iterator i = gen.begin(); + i != gen.end(); ++i) { - if(depTarget->GetType() == cmTarget::STATIC_LIBRARY || - depTarget->GetType() == cmTarget::SHARED_LIBRARY || - depTarget->GetType() == cmTarget::MODULE_LIBRARY) + cmTargets& targets = (*i)->GetMakefile()->GetTargets(); + for(cmTargets::iterator ti = targets.begin(); + ti != targets.end(); ++ti) { - // This utility dependency will cause an attempt to link. If - // the depender does not already link the dependee we need an - // intermediate target. - if(!this->CheckTargetLinks(target, ui->c_str())) - { - this->CreateUtilityDependTarget(*depTarget); - } + this->ComputeVSTargetDepends(ti->second); } } } + return true; } //---------------------------------------------------------------------------- -void -cmGlobalVisualStudioGenerator::CreateUtilityDependTarget(cmTarget& target) +void cmGlobalVisualStudioGenerator::ComputeVSTargetDepends(cmTarget& target) { - // This target is a library on which a utility dependency exists. - // We need to create an intermediate custom target to hook up the - // dependency without causing a link. - const char* altName = target.GetProperty("ALTERNATIVE_DEPENDENCY_NAME"); - if(!altName) + if(this->VSTargetDepends.find(&target) != this->VSTargetDepends.end()) + { + return; + } + VSDependSet& vsTargetDepend = this->VSTargetDepends[&target]; + // VS <= 7.1 has two behaviors that affect solution dependencies. + // + // (1) Solution-level dependencies between a linkable target and a + // library cause that library to be linked. We use an intermedite + // empty utility target to express the dependency. (VS 8 and above + // provide a project file "LinkLibraryDependencies" setting to + // choose whether to activate this behavior. We disable it except + // when linking external project files.) + // + // (2) We cannot let static libraries depend directly on targets to + // which they "link" because the librarian tool will copy the + // targets into the static library. While the work-around for + // behavior (1) would also avoid this, it would create a large + // number of extra utility targets for little gain. Instead, use + // the above work-around only for dependencies explicitly added by + // the add_dependencies() command. Approximate link dependencies by + // leaving them out for the static library itself but following them + // transitively for other targets. + + bool allowLinkable = (target.GetType() != cmTarget::STATIC_LIBRARY && + target.GetType() != cmTarget::SHARED_LIBRARY && + target.GetType() != cmTarget::MODULE_LIBRARY && + target.GetType() != cmTarget::EXECUTABLE); + + TargetDependSet const& depends = this->GetTargetDirectDepends(target); + + // Collect implicit link dependencies (target_link_libraries). + // Static libraries cannot depend on their link implementation + // due to behavior (2), but they do not really need to. + std::set<cmTarget*> linkDepends; + if(target.GetType() != cmTarget::STATIC_LIBRARY) { - // Create the intermediate utility target. - std::string altNameStr = target.GetName(); - altNameStr += "_UTILITY"; - const std::vector<std::string> no_depends; - cmCustomCommandLines no_commands; - const char* no_working_dir = 0; - const char* no_comment = 0; - target.GetMakefile()->AddUtilityCommand(altNameStr.c_str(), true, - no_working_dir, no_depends, - no_commands, false, no_comment); - target.SetProperty("ALTERNATIVE_DEPENDENCY_NAME", altNameStr.c_str()); - - // Most targets have a GUID created in ConfigureFinalPass. Since - // that has already been called, create one for this target now. - this->CreateGUID(altNameStr.c_str()); - - // The intermediate target should depend on the original target. - if(cmTarget* alt = this->FindTarget(0, altNameStr.c_str())) + for(TargetDependSet::const_iterator di = depends.begin(); + di != depends.end(); ++di) { - alt->AddUtility(target.GetName()); + cmTargetDepend dep = *di; + if(dep.IsLink()) + { + this->FollowLinkDepends(dep, linkDepends); + } } } -} -//---------------------------------------------------------------------------- -bool cmGlobalVisualStudioGenerator::CheckTargetLinks(cmTarget& target, - const char* name) -{ - // Return whether the given target links to a target with the given name. - if(target.GetType() == cmTarget::STATIC_LIBRARY) + // Collext explicit util dependencies (add_dependencies). + std::set<cmTarget*> utilDepends; + for(TargetDependSet::const_iterator di = depends.begin(); + di != depends.end(); ++di) { - // Static libraries never link to anything. - return false; - } - cmTarget::LinkLibraryVectorType const& libs = target.GetLinkLibraries(); - for(cmTarget::LinkLibraryVectorType::const_iterator i = libs.begin(); - i != libs.end(); ++i) - { - if(i->first == name) + cmTargetDepend dep = *di; + if(dep.IsUtil()) { - return true; + this->FollowLinkDepends(dep, utilDepends); } } - return false; -} -//---------------------------------------------------------------------------- -const char* -cmGlobalVisualStudioGenerator::GetUtilityForTarget(cmTarget& target, - const char* name) -{ - // Possibly depend on an intermediate utility target to avoid - // linking. - if(target.GetType() == cmTarget::STATIC_LIBRARY || - target.GetType() == cmTarget::SHARED_LIBRARY || - target.GetType() == cmTarget::MODULE_LIBRARY || - target.GetType() == cmTarget::EXECUTABLE) + // Collect all targets linked by this target so we can avoid + // intermediate targets below. + TargetSet linked; + if(target.GetType() != cmTarget::STATIC_LIBRARY) + { + linked = this->GetTargetLinkClosure(&target); + } + + // Emit link dependencies. + for(std::set<cmTarget*>::iterator di = linkDepends.begin(); + di != linkDepends.end(); ++di) { - // The depender is a target that links. Lookup the dependee to - // see if it provides an alternative dependency name. - if(cmTarget* depTarget = this->FindTarget(0, name)) + cmTarget* dep = *di; + vsTargetDepend.insert(dep->GetName()); + } + + // Emit util dependencies. Possibly use intermediate targets. + for(std::set<cmTarget*>::iterator di = utilDepends.begin(); + di != utilDepends.end(); ++di) + { + cmTarget* dep = *di; + if(allowLinkable || !dep->IsLinkable() || linked.count(dep)) { - // Check for an alternative name created by FixUtilityDepends. - if(const char* altName = - depTarget->GetProperty("ALTERNATIVE_DEPENDENCY_NAME")) - { - // The alternative name is needed only if the depender does - // not really link to the dependee. - if(!this->CheckTargetLinks(target, name)) - { - return altName; - } - } + // Direct dependency allowed. + vsTargetDepend.insert(dep->GetName()); + } + else + { + // Direct dependency on linkable target not allowed. + // Use an intermediate utility target. + vsTargetDepend.insert(this->GetUtilityDepend(dep)); } } - - // No special case. Just use the original dependency name. - return name; } //---------------------------------------------------------------------------- -void cmGlobalVisualStudioGenerator::GetTargetSets( - TargetDependSet& projectTargets, TargetDependSet& originalTargets, - cmLocalGenerator* root, GeneratorVector const& generators - ) +std::string cmGlobalVisualStudioGenerator::GetUtilityDepend(cmTarget* target) { - this->cmGlobalGenerator::GetTargetSets(projectTargets, originalTargets, - root, generators); - - // Add alternative dependency targets created by FixUtilityDepends. - for(TargetDependSet::iterator ti = projectTargets.begin(); - ti != projectTargets.end(); ++ti) + UtilityDependsMap::iterator i = this->UtilityDepends.find(target); + if(i == this->UtilityDepends.end()) { - cmTarget* tgt = *ti; - if(const char* altName = tgt->GetProperty("ALTERNATIVE_DEPENDENCY_NAME")) - { - if(cmTarget* alt = tgt->GetMakefile()->FindTarget(altName)) - { - projectTargets.insert(alt); - } - } + std::string name = this->WriteUtilityDepend(target); + UtilityDependsMap::value_type entry(target, name); + i = this->UtilityDepends.insert(entry).first; } + return i->second; } //---------------------------------------------------------------------------- @@ -618,8 +611,9 @@ void WriteVSMacrosFileRegistryEntry( { // Create the subkey and set the values of interest: HKEY hsubkey = NULL; - result = RegCreateKeyEx(hkey, nextAvailableSubKeyName.c_str(), 0, "", 0, - KEY_READ|KEY_WRITE, 0, &hsubkey, 0); + char lpClass[] = ""; + result = RegCreateKeyEx(hkey, nextAvailableSubKeyName.c_str(), 0, + lpClass, 0, KEY_READ|KEY_WRITE, 0, &hsubkey, 0); if (ERROR_SUCCESS == result) { DWORD dw = 0; @@ -770,11 +764,22 @@ cmGlobalVisualStudioGenerator::TargetCompare //---------------------------------------------------------------------------- cmGlobalVisualStudioGenerator::OrderedTargetDependSet -::OrderedTargetDependSet(cmGlobalGenerator::TargetDependSet const& targets) +::OrderedTargetDependSet(TargetDependSet const& targets) { - for(cmGlobalGenerator::TargetDependSet::const_iterator ti = + for(TargetDependSet::const_iterator ti = targets.begin(); ti != targets.end(); ++ti) { this->insert(*ti); } } + +//---------------------------------------------------------------------------- +cmGlobalVisualStudioGenerator::OrderedTargetDependSet +::OrderedTargetDependSet(TargetSet const& targets) +{ + for(TargetSet::const_iterator ti = targets.begin(); + ti != targets.end(); ++ti) + { + this->insert(*ti); + } +} diff --git a/Source/cmGlobalVisualStudioGenerator.h b/Source/cmGlobalVisualStudioGenerator.h index b0be087..bc96f4e 100644 --- a/Source/cmGlobalVisualStudioGenerator.h +++ b/Source/cmGlobalVisualStudioGenerator.h @@ -61,7 +61,6 @@ public: // return true if target is fortran only bool TargetIsFortranOnly(cmTarget& t); - const char* GetUtilityForTarget(cmTarget& target, const char*); /** Get the top-level registry key for this VS version. */ std::string GetRegistryBase(); @@ -70,9 +69,14 @@ public: i.e. "Can I build Debug and Release in the same tree?" */ virtual bool IsMultiConfig() { return true; } -protected: - void FixUtilityDepends(); + class TargetSet: public std::set<cmTarget*> {}; + struct TargetCompare + { + bool operator()(cmTarget const* l, cmTarget const* r) const; + }; + class OrderedTargetDependSet; +protected: // Does this VS version link targets to each other if there are // dependencies in the SLN file? This was done for VS versions // below 8. @@ -80,24 +84,36 @@ protected: virtual const char* GetIDEVersion() = 0; - struct TargetCompare - { - bool operator()(cmTarget const* l, cmTarget const* r) const; - }; - class OrderedTargetDependSet: public std::multiset<cmTarget*, TargetCompare> - { - public: - OrderedTargetDependSet(cmGlobalGenerator::TargetDependSet const&); - }; - - virtual void GetTargetSets(TargetDependSet& projectTargets, - TargetDependSet& originalTargets, - cmLocalGenerator* root, GeneratorVector const&); + virtual bool ComputeTargetDepends(); + class VSDependSet: public std::set<cmStdString> {}; + class VSDependMap: public std::map<cmTarget*, VSDependSet> {}; + VSDependMap VSTargetDepends; + void ComputeVSTargetDepends(cmTarget&); bool CheckTargetLinks(cmTarget& target, const char* name); + std::string GetUtilityForTarget(cmTarget& target, const char*); + virtual std::string WriteUtilityDepend(cmTarget*) = 0; + std::string GetUtilityDepend(cmTarget* target); + typedef std::map<cmTarget*, cmStdString> UtilityDependsMap; + UtilityDependsMap UtilityDepends; private: - void FixUtilityDependsForTarget(cmTarget& target); - void CreateUtilityDependTarget(cmTarget& target); + void FollowLinkDepends(cmTarget* target, std::set<cmTarget*>& linked); + + class TargetSetMap: public std::map<cmTarget*, TargetSet> {}; + TargetSetMap TargetLinkClosure; + void FillLinkClosure(cmTarget* target, TargetSet& linked); + TargetSet const& GetTargetLinkClosure(cmTarget* target); +}; + +class cmGlobalVisualStudioGenerator::OrderedTargetDependSet: + public std::multiset<cmTargetDepend, + cmGlobalVisualStudioGenerator::TargetCompare> +{ +public: + typedef cmGlobalGenerator::TargetDependSet TargetDependSet; + typedef cmGlobalVisualStudioGenerator::TargetSet TargetSet; + OrderedTargetDependSet(TargetDependSet const&); + OrderedTargetDependSet(TargetSet const&); }; #endif diff --git a/Source/cmGlobalXCodeGenerator.cxx b/Source/cmGlobalXCodeGenerator.cxx index 05c6848..1395865 100644 --- a/Source/cmGlobalXCodeGenerator.cxx +++ b/Source/cmGlobalXCodeGenerator.cxx @@ -18,6 +18,7 @@ #include "cmGeneratedFileStream.h" #include "cmComputeLinkInformation.h" #include "cmSourceFile.h" +#include "cmCustomCommandGenerator.h" #include <cmsys/auto_ptr.hxx> @@ -131,8 +132,8 @@ cmGlobalXCodeGenerator::cmGlobalXCodeGenerator(std::string const& version) //---------------------------------------------------------------------------- cmGlobalGenerator* cmGlobalXCodeGenerator::New() -{ -#if defined(CMAKE_BUILD_WITH_CMAKE) +{ +#if defined(CMAKE_BUILD_WITH_CMAKE) cmXcodeVersionParser parser; parser.ParseFile ("/Developer/Applications/Xcode.app/Contents/version.plist"); @@ -156,7 +157,7 @@ cmGlobalGenerator* cmGlobalXCodeGenerator::New() void cmGlobalXCodeGenerator::EnableLanguage(std::vector<std::string>const& lang, cmMakefile * mf, bool optional) -{ +{ mf->AddDefinition("XCODE","1"); mf->AddDefinition("XCODE_VERSION", this->VersionString.c_str()); if(this->XcodeVersion == 15) @@ -175,12 +176,12 @@ void cmGlobalXCodeGenerator::EnableLanguage(std::vector<std::string>const& mf->AddDefinition("CMAKE_GENERATOR_CC", "gcc"); mf->AddDefinition("CMAKE_GENERATOR_CXX", "g++"); mf->AddDefinition("CMAKE_GENERATOR_NO_COMPILER_ENV", "1"); - // initialize Architectures so it can be used by + // initialize Architectures so it can be used by // GetTargetObjectFileDirectories this->cmGlobalGenerator::EnableLanguage(lang, mf, optional); - const char* osxArch = + const char* osxArch = mf->GetDefinition("CMAKE_OSX_ARCHITECTURES"); - const char* sysroot = + const char* sysroot = mf->GetDefinition("CMAKE_OSX_SYSROOT"); if(osxArch && sysroot) { @@ -193,10 +194,10 @@ void cmGlobalXCodeGenerator::EnableLanguage(std::vector<std::string>const& //---------------------------------------------------------------------------- std::string cmGlobalXCodeGenerator ::GenerateBuildCommand(const char* makeProgram, - const char *projectName, - const char* additionalOptions, + const char *projectName, + const char* additionalOptions, const char *targetName, - const char* config, + const char* config, bool ignoreErrors, bool) { @@ -210,7 +211,7 @@ std::string cmGlobalXCodeGenerator "Generator cannot find the appropriate make command."); return ""; } - std::string makeCommand = + std::string makeCommand = cmSystemTools::ConvertToOutputPath(makeProgram); std::string lowerCaseCommand = makeCommand; cmSystemTools::LowerCase(lowerCaseCommand); @@ -284,7 +285,7 @@ void cmGlobalXCodeGenerator::Generate() // make sure extra targets are added before calling // the parent generate which will call trace depends for(it = this->ProjectMap.begin(); it!= this->ProjectMap.end(); ++it) - { + { cmLocalGenerator* root = it->second[0]; this->SetGenerationRoot(root); // add ALL_BUILD, INSTALL, etc @@ -293,7 +294,7 @@ void cmGlobalXCodeGenerator::Generate() this->ForceLinkerLanguages(); this->cmGlobalGenerator::Generate(); for(it = this->ProjectMap.begin(); it!= this->ProjectMap.end(); ++it) - { + { cmLocalGenerator* root = it->second[0]; this->SetGenerationRoot(root); // now create the project @@ -319,8 +320,8 @@ void cmGlobalXCodeGenerator::SetGenerationRoot(cmLocalGenerator* root) } //---------------------------------------------------------------------------- -void -cmGlobalXCodeGenerator::AddExtraTargets(cmLocalGenerator* root, +void +cmGlobalXCodeGenerator::AddExtraTargets(cmLocalGenerator* root, std::vector<cmLocalGenerator*>& gens) { cmMakefile* mf = root->GetMakefile(); @@ -339,7 +340,7 @@ cmGlobalXCodeGenerator::AddExtraTargets(cmLocalGenerator* root, listfile += "CMakeLists.txt"; allbuild->AddSource(listfile.c_str()); - // Add XCODE depend helper + // Add XCODE depend helper std::string dir = mf->GetCurrentOutputDirectory(); cmCustomCommandLine makecommand; makecommand.push_back("make"); @@ -354,14 +355,14 @@ cmGlobalXCodeGenerator::AddExtraTargets(cmLocalGenerator* root, cmCustomCommandLines commandLines; commandLines.push_back(makecommand); // Add Re-Run CMake rules - this->CreateReRunCMakeFile(root); + this->CreateReRunCMakeFile(root, gens); // now make the allbuild depend on all the non-utility targets // in the project for(std::vector<cmLocalGenerator*>::iterator i = gens.begin(); i != gens.end(); ++i) { - cmLocalGenerator* lg = *i; + cmLocalGenerator* lg = *i; if(this->IsExcluded(root, *i)) { continue; @@ -370,7 +371,7 @@ cmGlobalXCodeGenerator::AddExtraTargets(cmLocalGenerator* root, for(cmTargets::iterator l = tgts.begin(); l != tgts.end(); l++) { cmTarget& target = l->second; - // make all exe, shared libs and modules + // make all exe, shared libs and modules // run the depend check makefile as a post build rule // this will make sure that when the next target is built // things are up-to-date @@ -385,7 +386,7 @@ cmGlobalXCodeGenerator::AddExtraTargets(cmLocalGenerator* root, cmTarget::POST_BUILD, "Depend check for xcode", dir.c_str()); - + } if(!target.GetPropertyAsBool("EXCLUDE_FROM_ALL")) { @@ -402,13 +403,21 @@ cmGlobalXCodeGenerator::AddExtraTargets(cmLocalGenerator* root, } //---------------------------------------------------------------------------- -void cmGlobalXCodeGenerator::CreateReRunCMakeFile(cmLocalGenerator* root) +void cmGlobalXCodeGenerator::CreateReRunCMakeFile( + cmLocalGenerator* root, std::vector<cmLocalGenerator*> const& gens) { cmMakefile* mf = root->GetMakefile(); - std::vector<std::string> lfiles = mf->GetListFiles(); + std::vector<std::string> lfiles; + for(std::vector<cmLocalGenerator*>::const_iterator gi = gens.begin(); + gi != gens.end(); ++gi) + { + std::vector<std::string> const& lf = (*gi)->GetMakefile()->GetListFiles(); + lfiles.insert(lfiles.end(), lf.begin(), lf.end()); + } + // sort the array - std::sort(lfiles.begin(), lfiles.end(), std::less<std::string>()); - std::vector<std::string>::iterator new_end = + std::sort(lfiles.begin(), lfiles.end(), std::less<std::string>()); + std::vector<std::string>::iterator new_end = std::unique(lfiles.begin(), lfiles.end()); lfiles.erase(new_end, lfiles.end()); std::string dir = mf->GetHomeOutputDirectory(); @@ -428,7 +437,7 @@ void cmGlobalXCodeGenerator::CreateReRunCMakeFile(cmLocalGenerator* root) makefileStream << "\\\n" << this->ConvertToRelativeForMake(i->c_str()); } std::string cmake = mf->GetRequiredDefinition("CMAKE_COMMAND"); - makefileStream << "\n\t" << this->ConvertToRelativeForMake(cmake.c_str()) + makefileStream << "\n\t" << this->ConvertToRelativeForMake(cmake.c_str()) << " -H" << this->ConvertToRelativeForMake( mf->GetHomeDirectory()) << " -B" << this->ConvertToRelativeForMake( @@ -451,7 +460,7 @@ void cmGlobalXCodeGenerator::ClearXCodeObjects() } //---------------------------------------------------------------------------- -cmXCodeObject* +cmXCodeObject* cmGlobalXCodeGenerator::CreateObject(cmXCodeObject::PBXType ptype) { cmXCodeObject* obj; @@ -468,7 +477,7 @@ cmGlobalXCodeGenerator::CreateObject(cmXCodeObject::PBXType ptype) } //---------------------------------------------------------------------------- -cmXCodeObject* +cmXCodeObject* cmGlobalXCodeGenerator::CreateObject(cmXCodeObject::Type type) { cmXCodeObject* obj = new cmXCodeObject(cmXCodeObject::None, type); @@ -539,7 +548,7 @@ cmGlobalXCodeGenerator::CreateXCodeSourceFile(cmLocalGenerator* lg, buildFile->SetComment(fileRef->GetComment()); buildFile->AddAttribute("fileRef", this->CreateObjectReference(fileRef)); - cmXCodeObject* settings = + cmXCodeObject* settings = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP); settings->AddAttribute("COMPILER_FLAGS", this->CreateString(flags.c_str())); @@ -608,7 +617,7 @@ cmGlobalXCodeGenerator::CreateXCodeFileReference(cmSourceFile* sf, } fileRef->AddAttribute("fileEncoding", this->CreateString("4")); - const char* lang = + const char* lang = this->CurrentLocalGenerator->GetSourceFileLanguage(*sf); std::string sourcecode = "sourcecode"; std::string ext = sf->GetExtension(); @@ -643,7 +652,7 @@ cmGlobalXCodeGenerator::CreateXCodeFileReference(cmSourceFile* sf, sourcecode += ".c.h"; } else if(ext == "hxx" || ext == "hpp" || ext == "txx" - || ext == "pch") + || ext == "pch" || ext == "hh") { sourcecode += ".cpp.h"; } @@ -675,7 +684,7 @@ cmGlobalXCodeGenerator::CreateXCodeFileReference(cmSourceFile* sf, // // valid lastKnownFileType value. // } - fileRef->AddAttribute("lastKnownFileType", + fileRef->AddAttribute("lastKnownFileType", this->CreateString(sourcecode.c_str())); // Store the file path relative to the top of the source tree. @@ -717,31 +726,15 @@ void cmGlobalXCodeGenerator::SetCurrentLocalGenerator(cmLocalGenerator* gen) std::string outdir = cmSystemTools::CollapseFullPath(this->CurrentMakefile-> GetCurrentOutputDirectory()); - cmSystemTools::SplitPath(outdir.c_str(), + cmSystemTools::SplitPath(outdir.c_str(), this->CurrentOutputDirectoryComponents); // Select the current set of configuration types. this->CurrentConfigurationTypes.clear(); - if(this->XcodeVersion > 20) - { - if(const char* types = - this->CurrentMakefile->GetDefinition("CMAKE_CONFIGURATION_TYPES")) - { - cmSystemTools::ExpandListArgument(types, - this->CurrentConfigurationTypes); - } - } + this->CurrentMakefile->GetConfigurations(this->CurrentConfigurationTypes); if(this->CurrentConfigurationTypes.empty()) { - if(const char* buildType = - this->CurrentMakefile->GetDefinition("CMAKE_BUILD_TYPE")) - { - this->CurrentConfigurationTypes.push_back(buildType); - } - else - { - this->CurrentConfigurationTypes.push_back(""); - } + this->CurrentConfigurationTypes.push_back(""); } } @@ -783,7 +776,7 @@ cmGlobalXCodeGenerator::CreateXCodeTargets(cmLocalGenerator* gen, this->CreateXCodeSourceFile(this->CurrentLocalGenerator, *i, cmtarget); cmXCodeObject* fr = xsf->GetObject("fileRef"); - cmXCodeObject* filetype = + cmXCodeObject* filetype = fr->GetObject()->GetObject("lastKnownFileType"); cmTarget::SourceFileFlags tsFlags = @@ -829,7 +822,7 @@ cmGlobalXCodeGenerator::CreateXCodeTargets(cmLocalGenerator* gen, sourceBuildPhase = this->CreateObject(cmXCodeObject::PBXSourcesBuildPhase); sourceBuildPhase->SetComment("Sources"); - sourceBuildPhase->AddAttribute("buildActionMask", + sourceBuildPhase->AddAttribute("buildActionMask", this->CreateString("2147483647")); buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST); for(std::vector<cmXCodeObject*>::iterator i = sourceFiles.begin(); @@ -838,7 +831,7 @@ cmGlobalXCodeGenerator::CreateXCodeTargets(cmLocalGenerator* gen, buildFiles->AddObject(*i); } sourceBuildPhase->AddAttribute("files", buildFiles); - sourceBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing", + sourceBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing", this->CreateString("0")); } @@ -931,7 +924,7 @@ cmGlobalXCodeGenerator::CreateXCodeTargets(cmLocalGenerator* gen, for ( sfIt = mit->second.begin(); sfIt != mit->second.end(); ++ sfIt ) { cmXCodeObject* xsf = - this->CreateXCodeSourceFile(this->CurrentLocalGenerator, + this->CreateXCodeSourceFile(this->CurrentLocalGenerator, *sfIt, cmtarget); buildFiles->AddObject(xsf); } @@ -955,12 +948,12 @@ cmGlobalXCodeGenerator::CreateXCodeTargets(cmLocalGenerator* gen, { buildFiles->AddObject(*i); } - frameworkBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing", + frameworkBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing", this->CreateString("0")); } // create list of build phases and create the XCode target - cmXCodeObject* buildPhases = + cmXCodeObject* buildPhases = this->CreateObject(cmXCodeObject::OBJECT_LIST); this->CreateCustomCommands(buildPhases, sourceBuildPhase, @@ -1049,15 +1042,15 @@ cmGlobalXCodeGenerator::CreateBuildPhase(const char* name, { return 0; } - cmXCodeObject* buildPhase = + cmXCodeObject* buildPhase = this->CreateObject(cmXCodeObject::PBXShellScriptBuildPhase); buildPhase->AddAttribute("buildActionMask", this->CreateString("2147483647")); cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST); buildPhase->AddAttribute("files", buildFiles); - buildPhase->AddAttribute("name", + buildPhase->AddAttribute("name", this->CreateString(name)); - buildPhase->AddAttribute("runOnlyForDeploymentPostprocessing", + buildPhase->AddAttribute("runOnlyForDeploymentPostprocessing", this->CreateString("0")); buildPhase->AddAttribute("shellPath", this->CreateString("/bin/sh")); @@ -1080,16 +1073,16 @@ void cmGlobalXCodeGenerator::CreateCustomCommands(cmXCodeObject* buildPhases, frameworkBuildPhase, cmTarget& cmtarget) { - std::vector<cmCustomCommand> const & prebuild + std::vector<cmCustomCommand> const & prebuild = cmtarget.GetPreBuildCommands(); - std::vector<cmCustomCommand> const & prelink + std::vector<cmCustomCommand> const & prelink = cmtarget.GetPreLinkCommands(); - std::vector<cmCustomCommand> const & postbuild + std::vector<cmCustomCommand> const & postbuild = cmtarget.GetPostBuildCommands(); std::vector<cmSourceFile*>const &classes = cmtarget.GetSourceFiles(); // add all the sources std::vector<cmCustomCommand> commands; - for(std::vector<cmSourceFile*>::const_iterator i = classes.begin(); + for(std::vector<cmSourceFile*>::const_iterator i = classes.begin(); i != classes.end(); ++i) { if((*i)->GetCustomCommand()) @@ -1098,7 +1091,7 @@ void cmGlobalXCodeGenerator::CreateCustomCommands(cmXCodeObject* buildPhases, } } std::vector<cmCustomCommand> reruncom; - cmXCodeObject* cmakeReRunPhase = + cmXCodeObject* cmakeReRunPhase = this->CreateBuildPhase("CMake ReRun", "cmakeReRunPhase", cmtarget, reruncom); buildPhases->AddObject(cmakeReRunPhase); @@ -1108,15 +1101,15 @@ void cmGlobalXCodeGenerator::CreateCustomCommands(cmXCodeObject* buildPhases, "cmakeRulesBuildPhase", cmtarget, commands); // create prebuild phase - cmXCodeObject* preBuildPhase = + cmXCodeObject* preBuildPhase = this->CreateBuildPhase("CMake PreBuild Rules", "preBuildCommands", cmtarget, prebuild); // create prelink phase - cmXCodeObject* preLinkPhase = + cmXCodeObject* preLinkPhase = this->CreateBuildPhase("CMake PreLink Rules", "preLinkCommands", cmtarget, prelink); // create postbuild phase - cmXCodeObject* postBuildPhase = + cmXCodeObject* postBuildPhase = this->CreateBuildPhase("CMake PostBuild Rules", "postBuildPhase", cmtarget, postbuild); @@ -1183,10 +1176,10 @@ std::string cmGlobalXCodeGenerator::ExtractFlag(const char* flag, } //---------------------------------------------------------------------------- -void +void cmGlobalXCodeGenerator::AddCommandsToBuildPhase(cmXCodeObject* buildphase, cmTarget& target, - std::vector<cmCustomCommand> + std::vector<cmCustomCommand> const & commands, const char* name) { @@ -1197,7 +1190,7 @@ cmGlobalXCodeGenerator::AddCommandsToBuildPhase(cmXCodeObject* buildphase, std::string makecmd = "make -C "; makecmd += cdir; makecmd += " -f "; - makecmd += + makecmd += this->ConvertToRelativeForMake(this->CurrentReRunCMakeMakefile.c_str()); cmSystemTools::ReplaceString(makecmd, "\\ ", "\\\\ "); buildphase->AddAttribute("shellScript", @@ -1211,7 +1204,7 @@ cmGlobalXCodeGenerator::AddCommandsToBuildPhase(cmXCodeObject* buildphase, for(std::vector<cmCustomCommand>::const_iterator i = commands.begin(); i != commands.end(); ++i) { - cmCustomCommand const& cc = *i; + cmCustomCommand const& cc = *i; if(!cc.GetCommandLines().empty()) { const std::vector<std::string>& outputs = cc.GetOutputs(); @@ -1229,7 +1222,7 @@ cmGlobalXCodeGenerator::AddCommandsToBuildPhase(cmXCodeObject* buildphase, } } } - + std::string dir = this->CurrentMakefile->GetCurrentOutputDirectory(); dir += "/CMakeScripts"; cmSystemTools::MakeDirectory(dir.c_str()); @@ -1239,19 +1232,19 @@ cmGlobalXCodeGenerator::AddCommandsToBuildPhase(cmXCodeObject* buildphase, makefile += "_"; makefile += name; makefile += ".make"; - - for (std::vector<std::string>::const_iterator currentConfig= + + for (std::vector<std::string>::const_iterator currentConfig= this->CurrentConfigurationTypes.begin(); currentConfig!=this->CurrentConfigurationTypes.end(); currentConfig++ ) { - this->CreateCustomRulesMakefile(makefile.c_str(), - target, - commands, + this->CreateCustomRulesMakefile(makefile.c_str(), + target, + commands, currentConfig->c_str(), multipleOutputPairs); } - + std::string cdir = this->CurrentMakefile->GetCurrentOutputDirectory(); cdir = this->ConvertToRelativeForXCode(cdir.c_str()); std::string makecmd = "make -C "; @@ -1265,18 +1258,18 @@ cmGlobalXCodeGenerator::AddCommandsToBuildPhase(cmXCodeObject* buildphase, } makecmd += " all"; cmSystemTools::ReplaceString(makecmd, "\\ ", "\\\\ "); - buildphase->AddAttribute("shellScript", + buildphase->AddAttribute("shellScript", this->CreateString(makecmd.c_str())); } //---------------------------------------------------------------------------- void cmGlobalXCodeGenerator -::CreateCustomRulesMakefile(const char* makefileBasename, - cmTarget& target, - std::vector<cmCustomCommand> +::CreateCustomRulesMakefile(const char* makefileBasename, + cmTarget& target, + std::vector<cmCustomCommand> const & commands, const char* configName, - const std::map<cmStdString, + const std::map<cmStdString, cmStdString>& multipleOutputPairs ) { @@ -1293,7 +1286,10 @@ void cmGlobalXCodeGenerator makefileStream.SetCopyIfDifferent(true); makefileStream << "# Generated by CMake, DO NOT EDIT\n"; makefileStream << "# Custom rules for " << target.GetName() << "\n"; - + + // disable the implicit rules + makefileStream << ".SUFFIXES: " << "\n"; + // have all depend on all outputs makefileStream << "all: "; std::map<const cmCustomCommand*, cmStdString> tname; @@ -1301,7 +1297,7 @@ void cmGlobalXCodeGenerator for(std::vector<cmCustomCommand>::const_iterator i = commands.begin(); i != commands.end(); ++i) { - cmCustomCommand const& cc = *i; + cmCustomCommand const& cc = *i; if(!cc.GetCommandLines().empty()) { const std::vector<std::string>& outputs = cc.GetOutputs(); @@ -1315,10 +1311,10 @@ void cmGlobalXCodeGenerator } } else - { + { cmOStringStream str; str << "_buildpart_" << count++ ; - tname[&cc] = std::string(target.GetName()) + str.str(); + tname[&cc] = std::string(target.GetName()) + str.str(); makefileStream << "\\\n\t" << tname[&cc]; } } @@ -1327,11 +1323,10 @@ void cmGlobalXCodeGenerator for(std::vector<cmCustomCommand>::const_iterator i = commands.begin(); i != commands.end(); ++i) { - cmCustomCommand const& cc = *i; + cmCustomCommand const& cc = *i; if(!cc.GetCommandLines().empty()) { - bool escapeOldStyle = cc.GetEscapeOldStyle(); - bool escapeAllowMakeVars = cc.GetEscapeAllowMakeVars(); + cmCustomCommandGenerator ccg(cc, configName, this->CurrentMakefile); makefileStream << "\n"; const std::vector<std::string>& outputs = cc.GetOutputs(); if(!outputs.empty()) @@ -1346,15 +1341,17 @@ void cmGlobalXCodeGenerator // There are no outputs. Use the generated force rule name. makefileStream << tname[&cc] << ": "; } - for(std::vector<std::string>::const_iterator d = + for(std::vector<std::string>::const_iterator d = cc.GetDepends().begin(); d != cc.GetDepends().end(); ++d) { - std::string dep = - this->CurrentLocalGenerator->GetRealDependency(d->c_str(), - configName); - makefileStream << "\\\n" << this - ->ConvertToRelativeForMake(dep.c_str()); + std::string dep; + if(this->CurrentLocalGenerator + ->GetRealDependency(d->c_str(), configName, dep)) + { + makefileStream << "\\\n" << + this->ConvertToRelativeForMake(dep.c_str()); + } } makefileStream << "\n"; @@ -1362,20 +1359,15 @@ void cmGlobalXCodeGenerator { std::string echo_cmd = "echo "; echo_cmd += (this->CurrentLocalGenerator-> - EscapeForShell(comment, escapeAllowMakeVars)); + EscapeForShell(comment, cc.GetEscapeAllowMakeVars())); makefileStream << "\t" << echo_cmd.c_str() << "\n"; } // Add each command line to the set of commands. - for(cmCustomCommandLines::const_iterator cl = - cc.GetCommandLines().begin(); - cl != cc.GetCommandLines().end(); ++cl) + for(unsigned int c = 0; c < ccg.GetNumberOfCommands(); ++c) { // Build the command line in a single string. - const cmCustomCommandLine& commandLine = *cl; - std::string cmd2 = this->CurrentLocalGenerator - ->GetRealLocation(commandLine[0].c_str(), configName); - + std::string cmd2 = ccg.GetCommand(c); cmSystemTools::ReplaceString(cmd2, "/./", "/"); cmd2 = this->ConvertToRelativeForMake(cmd2.c_str()); std::string cmd; @@ -1386,21 +1378,7 @@ void cmGlobalXCodeGenerator cmd += " && "; } cmd += cmd2; - for(unsigned int j=1; j < commandLine.size(); ++j) - { - cmd += " "; - if(escapeOldStyle) - { - cmd += (this->CurrentLocalGenerator - ->EscapeForShellOldStyle(commandLine[j].c_str())); - } - else - { - cmd += (this->CurrentLocalGenerator-> - EscapeForShell(commandLine[j].c_str(), - escapeAllowMakeVars)); - } - } + ccg.AppendArguments(c, cmd); makefileStream << "\t" << cmd.c_str() << "\n"; } } @@ -1409,7 +1387,7 @@ void cmGlobalXCodeGenerator // Add rules to deal with multiple outputs of custom commands. if(!multipleOutputPairs.empty()) { - makefileStream << + makefileStream << "\n# Dependencies of multiple outputs to their primary outputs \n"; for(std::map<cmStdString, cmStdString>::const_iterator o = @@ -1440,6 +1418,9 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmTarget& target, std::string defFlags; bool shared = ((target.GetType() == cmTarget::SHARED_LIBRARY) || (target.GetType() == cmTarget::MODULE_LIBRARY)); + bool binary = ((target.GetType() == cmTarget::STATIC_LIBRARY) || + (target.GetType() == cmTarget::EXECUTABLE) || + shared); const char* lang = target.GetLinkerLanguage(configName); std::string cflags; @@ -1454,10 +1435,17 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmTarget& target, // Add language-specific flags. this->CurrentLocalGenerator->AddLanguageFlags(flags, lang, configName); - + // Add shared-library flags if needed. this->CurrentLocalGenerator->AddSharedFlags(flags, lang, shared); } + else if(binary) + { + cmSystemTools::Error + ("CMake can not determine linker language for target:", + target.GetName()); + return; + } // Add define flags this->CurrentLocalGenerator-> @@ -1492,11 +1480,11 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmTarget& target, std::string extraLinkOptions; if(target.GetType() == cmTarget::EXECUTABLE) { - extraLinkOptions = + extraLinkOptions = this->CurrentMakefile->GetRequiredDefinition("CMAKE_EXE_LINKER_FLAGS"); std::string var = "CMAKE_EXE_LINKER_FLAGS_"; var += cmSystemTools::UpperCase(configName); - std::string val = + std::string val = this->CurrentMakefile->GetSafeDefinition(var.c_str()); if(val.size()) { @@ -1514,8 +1502,13 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmTarget& target, extraLinkOptions = this->CurrentMakefile-> GetRequiredDefinition("CMAKE_MODULE_LINKER_FLAGS"); } - - const char* targetLinkFlags = target.GetProperty("LINK_FLAGS"); + + const char* linkFlagsProp = "LINK_FLAGS"; + if(target.GetType() == cmTarget::STATIC_LIBRARY) + { + linkFlagsProp = "STATIC_LIBRARY_FLAGS"; + } + const char* targetLinkFlags = target.GetProperty(linkFlagsProp); if(targetLinkFlags) { extraLinkOptions += " "; @@ -1523,7 +1516,8 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmTarget& target, } if(configName && *configName) { - std::string linkFlagsVar = "LINK_FLAGS_"; + std::string linkFlagsVar = linkFlagsProp; + linkFlagsVar += "_"; linkFlagsVar += cmSystemTools::UpperCase(configName); if(const char* linkFlags = target.GetProperty(linkFlagsVar.c_str())) { @@ -1589,9 +1583,9 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmTarget& target, this->CreateString(pndir.c_str())); pndir = target.GetDirectory(configName); } - buildSettings->AddAttribute("EXECUTABLE_PREFIX", + buildSettings->AddAttribute("EXECUTABLE_PREFIX", this->CreateString(pnprefix.c_str())); - buildSettings->AddAttribute("EXECUTABLE_SUFFIX", + buildSettings->AddAttribute("EXECUTABLE_SUFFIX", this->CreateString(pnsuffix.c_str())); } buildSettings->AddAttribute("SYMROOT", @@ -1602,20 +1596,20 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmTarget& target, { case cmTarget::STATIC_LIBRARY: { - buildSettings->AddAttribute("LIBRARY_STYLE", + buildSettings->AddAttribute("LIBRARY_STYLE", this->CreateString("STATIC")); break; } - + case cmTarget::MODULE_LIBRARY: { - buildSettings->AddAttribute("LIBRARY_STYLE", + buildSettings->AddAttribute("LIBRARY_STYLE", this->CreateString("BUNDLE")); if(this->XcodeVersion >= 22) { - buildSettings->AddAttribute("MACH_O_TYPE", + buildSettings->AddAttribute("MACH_O_TYPE", this->CreateString("mh_bundle")); - buildSettings->AddAttribute("GCC_DYNAMIC_NO_PIC", + buildSettings->AddAttribute("GCC_DYNAMIC_NO_PIC", this->CreateString("NO")); // Add the flags to create an executable. std::string createFlags = @@ -1700,7 +1694,7 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmTarget& target, plist.c_str()); std::string path = this->ConvertToRelativeForXCode(plist.c_str()); - buildSettings->AddAttribute("INFOPLIST_FILE", + buildSettings->AddAttribute("INFOPLIST_FILE", this->CreateString(path.c_str())); } @@ -1711,7 +1705,7 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmTarget& target, } if(this->XcodeVersion >= 22) { - buildSettings->AddAttribute("PREBINDING", + buildSettings->AddAttribute("PREBINDING", this->CreateString("NO")); } @@ -1736,7 +1730,7 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmTarget& target, } else { - std::string incpath = + std::string incpath = this->XCodeEscapePath(i->c_str()); dirs.Add(incpath.c_str()); } @@ -1755,12 +1749,12 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmTarget& target, } if(!fdirs.IsEmpty()) { - buildSettings->AddAttribute("FRAMEWORK_SEARCH_PATHS", + buildSettings->AddAttribute("FRAMEWORK_SEARCH_PATHS", fdirs.CreateList()); } if(!dirs.IsEmpty()) { - buildSettings->AddAttribute("HEADER_SEARCH_PATHS", + buildSettings->AddAttribute("HEADER_SEARCH_PATHS", dirs.CreateList()); } std::string oflagc = this->ExtractFlag("-O", cflags); @@ -1802,11 +1796,11 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmTarget& target, if(gflagc.size() ==0 && gflag.size() == 0) { debugStr = "NO"; - } + } buildSettings->AddAttribute("GCC_GENERATE_DEBUGGING_SYMBOLS", this->CreateString(debugStr)); - buildSettings->AddAttribute("GCC_OPTIMIZATION_LEVEL", + buildSettings->AddAttribute("GCC_OPTIMIZATION_LEVEL", this->CreateString(optLevel)); buildSettings->AddAttribute("GCC_SYMBOLS_PRIVATE_EXTERN", this->CreateString("NO")); @@ -1816,11 +1810,11 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmTarget& target, { flags += " "; flags += defFlags; - buildSettings->AddAttribute("OTHER_CPLUSPLUSFLAGS", + buildSettings->AddAttribute("OTHER_CPLUSPLUSFLAGS", this->CreateString(flags.c_str())); cflags += " "; cflags += defFlags; - buildSettings->AddAttribute("OTHER_CFLAGS", + buildSettings->AddAttribute("OTHER_CFLAGS", this->CreateString(cflags.c_str())); } @@ -1828,7 +1822,7 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmTarget& target, { flags += " "; flags += defFlags; - buildSettings->AddAttribute("OTHER_CFLAGS", + buildSettings->AddAttribute("OTHER_CFLAGS", this->CreateString(flags.c_str())); } @@ -1856,9 +1850,9 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmTarget& target, buildSettings->AddAttribute("INSTALL_PATH", this->CreateString(install_name_dir.c_str())); - buildSettings->AddAttribute("OTHER_LDFLAGS", + buildSettings->AddAttribute("OTHER_LDFLAGS", this->CreateString(extraLinkOptions.c_str())); - buildSettings->AddAttribute("OTHER_REZFLAGS", + buildSettings->AddAttribute("OTHER_REZFLAGS", this->CreateString("")); buildSettings->AddAttribute("SECTORDER_FLAGS", this->CreateString("")); @@ -1928,12 +1922,12 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmTarget& target, } //---------------------------------------------------------------------------- -cmXCodeObject* +cmXCodeObject* cmGlobalXCodeGenerator::CreateUtilityTarget(cmTarget& cmtarget) { cmXCodeObject* shellBuildPhase = this->CreateObject(cmXCodeObject::PBXShellScriptBuildPhase); - shellBuildPhase->AddAttribute("buildActionMask", + shellBuildPhase->AddAttribute("buildActionMask", this->CreateString("2147483647")); cmXCodeObject* buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST); shellBuildPhase->AddAttribute("files", buildFiles); @@ -1948,10 +1942,10 @@ cmGlobalXCodeGenerator::CreateUtilityTarget(cmTarget& cmtarget) shellBuildPhase->AddAttribute("shellScript", this->CreateString( "# shell script goes here\nexit 0")); - cmXCodeObject* target = + cmXCodeObject* target = this->CreateObject(cmXCodeObject::PBXAggregateTarget); target->SetComment(cmtarget.GetName()); - cmXCodeObject* buildPhases = + cmXCodeObject* buildPhases = this->CreateObject(cmXCodeObject::OBJECT_LIST); std::vector<cmXCodeObject*> emptyContentVector; this->CreateCustomCommands(buildPhases, 0, 0, 0, emptyContentVector, 0, @@ -1970,7 +1964,7 @@ cmGlobalXCodeGenerator::CreateUtilityTarget(cmTarget& cmtarget) this->CreateBuildSettings(cmtarget, buildSettings, theConfig); target->AddAttribute("buildSettings", buildSettings); } - cmXCodeObject* dependencies = + cmXCodeObject* dependencies = this->CreateObject(cmXCodeObject::OBJECT_LIST); target->AddAttribute("dependencies", dependencies); target->AddAttribute("name", this->CreateString(cmtarget.GetName())); @@ -1998,13 +1992,13 @@ cmGlobalXCodeGenerator::CreateUtilityTarget(cmTarget& cmtarget) std::string cmGlobalXCodeGenerator::AddConfigurations(cmXCodeObject* target, cmTarget& cmtarget) { - std::string configTypes = + std::string configTypes = this->CurrentMakefile->GetRequiredDefinition("CMAKE_CONFIGURATION_TYPES"); std::vector<std::string> configVectorIn; std::vector<std::string> configVector; configVectorIn.push_back(configTypes); cmSystemTools::ExpandList(configVectorIn, configVector); - cmXCodeObject* configlist = + cmXCodeObject* configlist = this->CreateObject(cmXCodeObject::XCConfigurationList); cmXCodeObject* buildConfigurations = this->CreateObject(cmXCodeObject::OBJECT_LIST); @@ -2015,11 +2009,11 @@ std::string cmGlobalXCodeGenerator::AddConfigurations(cmXCodeObject* target, comment += cmtarget.GetName(); comment += "\""; configlist->SetComment(comment.c_str()); - target->AddAttribute("buildConfigurationList", + target->AddAttribute("buildConfigurationList", this->CreateObjectReference(configlist)); for(unsigned int i = 0; i < configVector.size(); ++i) { - cmXCodeObject* config = + cmXCodeObject* config = this->CreateObject(cmXCodeObject::XCBuildConfiguration); buildConfigurations->AddObject(config); cmXCodeObject* buildSettings = @@ -2032,9 +2026,9 @@ std::string cmGlobalXCodeGenerator::AddConfigurations(cmXCodeObject* target, } if(configVector.size()) { - configlist->AddAttribute("defaultConfigurationName", + configlist->AddAttribute("defaultConfigurationName", this->CreateString(configVector[0].c_str())); - configlist->AddAttribute("defaultConfigurationIsVisible", + configlist->AddAttribute("defaultConfigurationIsVisible", this->CreateString("0")); return configVector[0]; } @@ -2089,7 +2083,7 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeTarget(cmTarget& cmtarget, cmXCodeObject* buildPhases) { - cmXCodeObject* target = + cmXCodeObject* target = this->CreateObject(cmXCodeObject::PBXNativeTarget); target->AddAttribute("buildPhases", buildPhases); cmXCodeObject* buildRules = this->CreateObject(cmXCodeObject::OBJECT_LIST); @@ -2107,13 +2101,13 @@ cmGlobalXCodeGenerator::CreateXCodeTarget(cmTarget& cmtarget, this->CreateBuildSettings(cmtarget, buildSettings, defConfig.c_str()); target->AddAttribute("buildSettings", buildSettings); } - cmXCodeObject* dependencies = + cmXCodeObject* dependencies = this->CreateObject(cmXCodeObject::OBJECT_LIST); target->AddAttribute("dependencies", dependencies); target->AddAttribute("name", this->CreateString(cmtarget.GetName())); target->AddAttribute("productName",this->CreateString(cmtarget.GetName())); - cmXCodeObject* fileRef = + cmXCodeObject* fileRef = this->CreateObject(cmXCodeObject::PBXFileReference); if(const char* fileType = this->GetTargetFileType(cmtarget)) { @@ -2125,7 +2119,7 @@ cmGlobalXCodeGenerator::CreateXCodeTarget(cmTarget& cmtarget, fileRef->AddAttribute("sourceTree", this->CreateString("BUILT_PRODUCTS_DIR")); fileRef->SetComment(cmtarget.GetName()); - target->AddAttribute("productReference", + target->AddAttribute("productReference", this->CreateObjectReference(fileRef)); if(const char* productType = this->GetTargetProductType(cmtarget)) { @@ -2166,20 +2160,20 @@ void cmGlobalXCodeGenerator::AddDependTarget(cmXCodeObject* target, // now avoid circular references if dependTarget already // depends on target then skip it. Circular references crashes // xcode - cmXCodeObject* dependTargetDepends = + cmXCodeObject* dependTargetDepends = dependTarget->GetObject("dependencies"); if(dependTargetDepends) { if(dependTargetDepends->HasObject(target->GetPBXTargetDependency())) - { + { return; } } - + cmXCodeObject* targetdep = dependTarget->GetPBXTargetDependency(); if(!targetdep) { - cmXCodeObject* container = + cmXCodeObject* container = this->CreateObject(cmXCodeObject::PBXContainerItemProxy); container->SetComment("PBXContainerItemProxy"); container->AddAttribute("containerPortal", @@ -2187,25 +2181,25 @@ void cmGlobalXCodeGenerator::AddDependTarget(cmXCodeObject* target, container->AddAttribute("proxyType", this->CreateString("1")); container->AddAttribute("remoteGlobalIDString", this->CreateObjectReference(dependTarget)); - container->AddAttribute("remoteInfo", + container->AddAttribute("remoteInfo", this->CreateString( dependTarget->GetTarget()->GetName())); - targetdep = + targetdep = this->CreateObject(cmXCodeObject::PBXTargetDependency); targetdep->SetComment("PBXTargetDependency"); targetdep->AddAttribute("target", this->CreateObjectReference(dependTarget)); - targetdep->AddAttribute("targetProxy", + targetdep->AddAttribute("targetProxy", this->CreateObjectReference(container)); dependTarget->SetPBXTargetDependency(targetdep); } - + cmXCodeObject* depends = target->GetObject("dependencies"); if(!depends) { cmSystemTools:: Error("target does not have dependencies attribute error.."); - + } else { @@ -2253,14 +2247,14 @@ void cmGlobalXCodeGenerator { // There are multiple configurations. Add the setting to the // buildSettings of the configuration name given. - cmXCodeObject* configurationList = + cmXCodeObject* configurationList = target->GetObject("buildConfigurationList")->GetObject(); - cmXCodeObject* buildConfigs = + cmXCodeObject* buildConfigs = configurationList->GetObject("buildConfigurations"); std::vector<cmXCodeObject*> list = buildConfigs->GetObjectList(); - // each configuration and the target itself has a buildSettings in it + // each configuration and the target itself has a buildSettings in it //list.push_back(target); - for(std::vector<cmXCodeObject*>::iterator i = list.begin(); + for(std::vector<cmXCodeObject*>::iterator i = list.begin(); i != list.end(); ++i) { if(configName) @@ -2422,7 +2416,7 @@ void cmGlobalXCodeGenerator::CreateGroups(cmLocalGenerator* root, std::vector<cmSourceGroup> sourceGroups = mf->GetSourceGroups(); cmTargets &tgts = mf->GetTargets(); for(cmTargets::iterator l = tgts.begin(); l != tgts.end(); l++) - { + { cmTarget& cmtarget = l->second; // Same skipping logic here as in CreateXCodeTargets so that we do not @@ -2445,21 +2439,21 @@ void cmGlobalXCodeGenerator::CreateGroups(cmLocalGenerator* root, std::vector<cmSourceFile*> classes = cmtarget.GetSourceFiles(); - for(std::vector<cmSourceFile*>::const_iterator s = classes.begin(); + for(std::vector<cmSourceFile*>::const_iterator s = classes.begin(); s != classes.end(); s++) { cmSourceFile* sf = *s; // Add the file to the list of sources. std::string const& source = sf->GetFullPath(); - cmSourceGroup& sourceGroup = + cmSourceGroup& sourceGroup = mf->FindSourceGroup(source.c_str(), sourceGroups); - cmXCodeObject* pbxgroup = + cmXCodeObject* pbxgroup = this->CreateOrGetPBXGroup(cmtarget, &sourceGroup); cmStdString key = GetGroupMapKey(cmtarget, sf); this->GroupMap[key] = pbxgroup; } } - } + } } //---------------------------------------------------------------------------- @@ -2485,7 +2479,7 @@ cmXCodeObject* cmGlobalXCodeGenerator { tgroup = this->CreateObject(cmXCodeObject::PBXGroup); this->TargetGroup[cmtarget.GetName()] = tgroup; - cmXCodeObject* tgroupChildren = + cmXCodeObject* tgroupChildren = this->CreateObject(cmXCodeObject::OBJECT_LIST); tgroup->AddAttribute("name", this->CreateString(cmtarget.GetName())); tgroup->AddAttribute("children", tgroupChildren); @@ -2508,7 +2502,7 @@ cmXCodeObject* cmGlobalXCodeGenerator cmXCodeObject* tgroupChildren = tgroup->GetObject("children"); cmXCodeObject* group = this->CreateObject(cmXCodeObject::PBXGroup); - cmXCodeObject* groupChildren = + cmXCodeObject* groupChildren = this->CreateObject(cmXCodeObject::OBJECT_LIST); group->AddAttribute("name", this->CreateString(sg->GetName())); group->AddAttribute("children", groupChildren); @@ -2528,19 +2522,19 @@ void cmGlobalXCodeGenerator std::vector<cmLocalGenerator*>& generators) { - this->ClearXCodeObjects(); + this->ClearXCodeObjects(); this->RootObject = 0; this->SourcesGroupChildren = 0; this->ResourcesGroupChildren = 0; this->MainGroupChildren = 0; cmXCodeObject* group = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP); group->AddAttribute("COPY_PHASE_STRIP", this->CreateString("NO")); - cmXCodeObject* developBuildStyle = + cmXCodeObject* developBuildStyle = this->CreateObject(cmXCodeObject::PBXBuildStyle); cmXCodeObject* listObjs = this->CreateObject(cmXCodeObject::OBJECT_LIST); if(this->XcodeVersion == 15) { - developBuildStyle->AddAttribute("name", + developBuildStyle->AddAttribute("name", this->CreateString("Development")); developBuildStyle->AddAttribute("buildSettings", group); listObjs->AddObject(developBuildStyle); @@ -2556,7 +2550,7 @@ void cmGlobalXCodeGenerator { for(unsigned int i = 0; i < this->CurrentConfigurationTypes.size(); ++i) { - cmXCodeObject* buildStyle = + cmXCodeObject* buildStyle = this->CreateObject(cmXCodeObject::PBXBuildStyle); const char* name = this->CurrentConfigurationTypes[i].c_str(); buildStyle->AddAttribute("name", this->CreateString(name)); @@ -2570,7 +2564,7 @@ void cmGlobalXCodeGenerator } cmXCodeObject* mainGroup = this->CreateObject(cmXCodeObject::PBXGroup); - this->MainGroupChildren = + this->MainGroupChildren = this->CreateObject(cmXCodeObject::OBJECT_LIST); mainGroup->AddAttribute("children", this->MainGroupChildren); if(this->XcodeVersion == 15) @@ -2580,7 +2574,7 @@ void cmGlobalXCodeGenerator mainGroup->AddAttribute("sourceTree", this->CreateString("<group>")); cmXCodeObject* sourcesGroup = this->CreateObject(cmXCodeObject::PBXGroup); - this->SourcesGroupChildren = + this->SourcesGroupChildren = this->CreateObject(cmXCodeObject::OBJECT_LIST); sourcesGroup->AddAttribute("name", this->CreateString("Sources")); sourcesGroup->AddAttribute("children", this->SourcesGroupChildren); @@ -2603,7 +2597,7 @@ void cmGlobalXCodeGenerator resourcesGroup->AddAttribute("sourceTree", this->CreateString("<group>")); this->MainGroupChildren->AddObject(resourcesGroup); - // now create the cmake groups + // now create the cmake groups this->CreateGroups(root, generators); cmXCodeObject* productGroup = this->CreateObject(cmXCodeObject::PBXGroup); @@ -2613,16 +2607,16 @@ void cmGlobalXCodeGenerator productGroup->AddAttribute("refType", this->CreateString("4")); } productGroup->AddAttribute("sourceTree", this->CreateString("<group>")); - cmXCodeObject* productGroupChildren = + cmXCodeObject* productGroupChildren = this->CreateObject(cmXCodeObject::OBJECT_LIST); productGroup->AddAttribute("children", productGroupChildren); this->MainGroupChildren->AddObject(productGroup); - - + + this->RootObject = this->CreateObject(cmXCodeObject::PBXProject); this->RootObject->SetComment("Project object"); group = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP); - this->RootObject->AddAttribute("mainGroup", + this->RootObject->AddAttribute("mainGroup", this->CreateObjectReference(mainGroup)); this->RootObject->AddAttribute("buildSettings", group); this->RootObject->AddAttribute("buildStyles", listObjs); @@ -2634,7 +2628,10 @@ void cmGlobalXCodeGenerator group->AddAttribute("BuildIndependentTargetsInParallel", this->CreateString("YES")); this->RootObject->AddAttribute("attributes", group); - if (this->XcodeVersion >= 31) + if (this->XcodeVersion >= 32) + this->RootObject->AddAttribute("compatibilityVersion", + this->CreateString("Xcode 3.2")); + else if (this->XcodeVersion >= 31) this->RootObject->AddAttribute("compatibilityVersion", this->CreateString("Xcode 3.1")); else @@ -2649,18 +2646,18 @@ void cmGlobalXCodeGenerator this->CreateString(pdir.c_str())); this->RootObject->AddAttribute("projectRoot", this->CreateString("")); } - cmXCodeObject* configlist = + cmXCodeObject* configlist = this->CreateObject(cmXCodeObject::XCConfigurationList); cmXCodeObject* buildConfigurations = this->CreateObject(cmXCodeObject::OBJECT_LIST); std::vector<cmXCodeObject*> configs; if(this->XcodeVersion == 15) { - cmXCodeObject* configDebug = + cmXCodeObject* configDebug = this->CreateObject(cmXCodeObject::XCBuildConfiguration); configDebug->AddAttribute("name", this->CreateString("Debug")); configs.push_back(configDebug); - cmXCodeObject* configRelease = + cmXCodeObject* configRelease = this->CreateObject(cmXCodeObject::XCBuildConfiguration); configRelease->AddAttribute("name", this->CreateString("Release")); configs.push_back(configRelease); @@ -2670,7 +2667,7 @@ void cmGlobalXCodeGenerator for(unsigned int i = 0; i < this->CurrentConfigurationTypes.size(); ++i) { const char* name = this->CurrentConfigurationTypes[i].c_str(); - cmXCodeObject* config = + cmXCodeObject* config = this->CreateObject(cmXCodeObject::XCBuildConfiguration); config->AddAttribute("name", this->CreateString(name)); configs.push_back(config); @@ -2688,13 +2685,13 @@ void cmGlobalXCodeGenerator comment += this->CurrentProject; comment += "\""; configlist->SetComment(comment.c_str()); - configlist->AddAttribute("defaultConfigurationIsVisible", + configlist->AddAttribute("defaultConfigurationIsVisible", this->CreateString("0")); - configlist->AddAttribute("defaultConfigurationName", + configlist->AddAttribute("defaultConfigurationName", this->CreateString("Debug")); cmXCodeObject* buildSettings = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP); - const char* osxArch = + const char* osxArch = this->CurrentMakefile->GetDefinition("CMAKE_OSX_ARCHITECTURES"); if(strlen(osxArch) == 0) { @@ -2719,11 +2716,11 @@ void cmGlobalXCodeGenerator this->CreateString("YES")); } - const char* sysroot = + const char* sysroot = this->CurrentMakefile->GetDefinition("CMAKE_OSX_SYSROOT"); - const char* sysrootDefault = + const char* sysrootDefault = this->CurrentMakefile->GetDefinition("CMAKE_OSX_SYSROOT_DEFAULT"); - const char* deploymentTarget = + const char* deploymentTarget = this->CurrentMakefile->GetDefinition("CMAKE_OSX_DEPLOYMENT_TARGET"); if(osxArch && sysroot) { @@ -2733,22 +2730,24 @@ void cmGlobalXCodeGenerator cmSystemTools::ExpandListArgument(std::string(osxArch), this->Architectures); flagsUsed = true; - buildSettings->AddAttribute("SDKROOT", + buildSettings->AddAttribute("SDKROOT", this->CreateString(sysroot)); std::string archString; - for( std::vector<std::string>::iterator i = + const char* sep = ""; + for( std::vector<std::string>::iterator i = this->Architectures.begin(); i != this->Architectures.end(); ++i) { + archString += sep; archString += *i; - archString += " "; + sep = " "; } - buildSettings->AddAttribute("ARCHS", + buildSettings->AddAttribute("ARCHS", this->CreateString(archString.c_str())); if(!flagsUsed && sysrootDefault && strcmp(sysroot, sysrootDefault) != 0) { - buildSettings->AddAttribute("SDKROOT", + buildSettings->AddAttribute("SDKROOT", this->CreateString(sysroot)); } } @@ -2758,6 +2757,22 @@ void cmGlobalXCodeGenerator this->CreateString(deploymentTarget)); } + // Put this last so it can override existing settings + // Convert "CMAKE_XCODE_ATTRIBUTE_*" variables directly. + { + std::vector<std::string> vars = this->CurrentMakefile->GetDefinitions(); + for(std::vector<std::string>::const_iterator i = vars.begin(); + i != vars.end(); ++i) + { + if(i->find("CMAKE_XCODE_ATTRIBUTE_") == 0) + { + buildSettings->AddAttribute(i->substr(22).c_str(), + this->CreateString( + this->CurrentMakefile->GetDefinition(i->c_str()))); + } + } + } + std::string symroot = root->GetMakefile()->GetCurrentOutputDirectory(); symroot += "/build"; buildSettings->AddAttribute("SYMROOT", this->CreateString(symroot.c_str())); @@ -2768,7 +2783,7 @@ void cmGlobalXCodeGenerator (*i)->AddAttribute("buildSettings", buildSettings); } - this->RootObject->AddAttribute("buildConfigurationList", + this->RootObject->AddAttribute("buildConfigurationList", this->CreateObjectReference(configlist)); std::vector<cmXCodeObject*> targets; @@ -2793,7 +2808,7 @@ void cmGlobalXCodeGenerator cmXCodeObject* allTargets = this->CreateObject(cmXCodeObject::OBJECT_LIST); for(std::vector<cmXCodeObject*>::iterator i = targets.begin(); i != targets.end(); ++i) - { + { cmXCodeObject* t = *i; allTargets->AddObject(t); cmXCodeObject* productRef = t->GetObject("productReference"); @@ -2806,11 +2821,11 @@ void cmGlobalXCodeGenerator } //---------------------------------------------------------------------------- -void +void cmGlobalXCodeGenerator::CreateXCodeDependHackTarget( std::vector<cmXCodeObject*>& targets) -{ - cmGeneratedFileStream +{ + cmGeneratedFileStream makefileStream(this->CurrentXCodeHackMakefile.c_str()); if(!makefileStream) { @@ -2856,9 +2871,9 @@ cmGlobalXCodeGenerator::CreateXCodeDependHackTarget( this->ConvertToRelativeForMake(tfull.c_str()); } } - makefileStream << "\n\n"; + makefileStream << "\n\n"; } - makefileStream + makefileStream << "# For each target create a dummy rule " "so the target does not have to exist\n"; std::set<cmStdString> emitted; @@ -2868,7 +2883,7 @@ cmGlobalXCodeGenerator::CreateXCodeDependHackTarget( cmXCodeObject* target = *i; std::map<cmStdString, cmXCodeObject::StringVec> const& deplibs = target->GetDependLibraries(); - for(std::map<cmStdString, cmXCodeObject::StringVec>::const_iterator ci + for(std::map<cmStdString, cmXCodeObject::StringVec>::const_iterator ci = deplibs.begin(); ci != deplibs.end(); ++ci) { for(cmXCodeObject::StringVec::const_iterator d = ci->second.begin(); @@ -2876,7 +2891,7 @@ cmGlobalXCodeGenerator::CreateXCodeDependHackTarget( { if(emitted.insert(*d).second) { - makefileStream << + makefileStream << this->ConvertToRelativeForMake(d->c_str()) << ":\n"; } } @@ -2885,10 +2900,10 @@ cmGlobalXCodeGenerator::CreateXCodeDependHackTarget( makefileStream << "\n\n"; // Write rules to help Xcode relink things at the right time. - makefileStream << + makefileStream << "# Rules to remove targets that are older than anything to which they\n" "# link. This forces Xcode to relink the targets from scratch. It\n" - "# does not seem to check these dependencies itself.\n"; + "# does not seem to check these dependencies itself.\n"; for(std::vector<std::string>::const_iterator ct = this->CurrentConfigurationTypes.begin(); ct != this->CurrentConfigurationTypes.end(); ++ct) @@ -2909,7 +2924,7 @@ cmGlobalXCodeGenerator::CreateXCodeDependHackTarget( { // Create a rule for this target. std::string tfull = t->GetFullPath(configName); - makefileStream << this->ConvertToRelativeForMake(tfull.c_str()) + makefileStream << this->ConvertToRelativeForMake(tfull.c_str()) << ":"; // List dependencies if any exist. @@ -2921,7 +2936,7 @@ cmGlobalXCodeGenerator::CreateXCodeDependHackTarget( for(std::vector<cmStdString>::const_iterator d = deplibs.begin(); d != deplibs.end(); ++d) { - makefileStream << "\\\n\t" << + makefileStream << "\\\n\t" << this->ConvertToRelativeForMake(d->c_str()); } } @@ -2943,7 +2958,7 @@ cmGlobalXCodeGenerator::CreateXCodeDependHackTarget( universal += "/"; universal += t->GetName(); universal += ".build/Objects-normal/"; - for( std::vector<std::string>::iterator arch = + for( std::vector<std::string>::iterator arch = this->Architectures.begin(); arch != this->Architectures.end(); ++arch) { @@ -2952,7 +2967,7 @@ cmGlobalXCodeGenerator::CreateXCodeDependHackTarget( universalFile += "/"; universalFile += t->GetFullName(configName); makefileStream << "\t/bin/rm -f " - << + << this->ConvertToRelativeForMake(universalFile.c_str()) << "\n"; } @@ -2966,7 +2981,7 @@ cmGlobalXCodeGenerator::CreateXCodeDependHackTarget( //---------------------------------------------------------------------------- void cmGlobalXCodeGenerator::OutputXCodeProject(cmLocalGenerator* root, - std::vector<cmLocalGenerator*>& + std::vector<cmLocalGenerator*>& generators) { if(generators.size() == 0) @@ -3006,7 +3021,7 @@ cmGlobalXCodeGenerator::OutputXCodeProject(cmLocalGenerator* root, } //---------------------------------------------------------------------------- -void +void cmGlobalXCodeGenerator::WriteXCodePBXProj(std::ostream& fout, cmLocalGenerator* , std::vector<cmLocalGenerator*>& ) @@ -3022,7 +3037,9 @@ cmGlobalXCodeGenerator::WriteXCodePBXProj(std::ostream& fout, cmXCodeObject::Indent(1, fout); if(this->XcodeVersion >= 21) { - if (this->XcodeVersion >= 31) + if (this->XcodeVersion >= 32) + fout << "objectVersion = 46;\n"; + else if (this->XcodeVersion >= 31) fout << "objectVersion = 45;\n"; else if (this->XcodeVersion >= 30) fout << "objectVersion = 44;\n"; @@ -3064,7 +3081,7 @@ std::string cmGlobalXCodeGenerator::ConvertToRelativeForMake(const char* p) } else { - std::string ret = + std::string ret = this->CurrentLocalGenerator-> ConvertToRelativePath(this->CurrentOutputDirectoryComponents, p); return cmSystemTools::ConvertToOutputPath(ret.c_str()); @@ -3080,7 +3097,7 @@ std::string cmGlobalXCodeGenerator::ConvertToRelativeForXCode(const char* p) } else { - std::string ret = + std::string ret = this->CurrentLocalGenerator-> ConvertToRelativePath(this->ProjectOutputDirectoryComponents, p); return cmSystemTools::ConvertToOutputPath(ret.c_str()); @@ -3120,7 +3137,7 @@ std::string cmGlobalXCodeGenerator::XCodeEscapePath(const char* p) //---------------------------------------------------------------------------- void cmGlobalXCodeGenerator:: GetTargetObjectFileDirectories(cmTarget* target, - std::vector<std::string>& + std::vector<std::string>& dirs) { std::string dir = this->CurrentMakefile->GetCurrentOutputDirectory(); @@ -3134,7 +3151,7 @@ GetTargetObjectFileDirectories(cmTarget* target, std::string dirsave = dir; if(this->Architectures.size()) { - for(std::vector<std::string>::iterator i = this->Architectures.begin(); + for(std::vector<std::string>::iterator i = this->Architectures.begin(); i != this->Architectures.end(); ++i) { dir += *i; diff --git a/Source/cmGlobalXCodeGenerator.h b/Source/cmGlobalXCodeGenerator.h index b4de805..290532a 100644 --- a/Source/cmGlobalXCodeGenerator.h +++ b/Source/cmGlobalXCodeGenerator.h @@ -171,7 +171,8 @@ private: const char* name2, cmTarget& cmtarget, const std::vector<cmCustomCommand>&); - void CreateReRunCMakeFile(cmLocalGenerator* root); + void CreateReRunCMakeFile(cmLocalGenerator* root, + std::vector<cmLocalGenerator*> const& gens); std::string LookupFlags(const char* varNamePrefix, const char* varNameLang, diff --git a/Source/cmGraphAdjacencyList.h b/Source/cmGraphAdjacencyList.h index 7794840..0149d33 100644 --- a/Source/cmGraphAdjacencyList.h +++ b/Source/cmGraphAdjacencyList.h @@ -14,7 +14,27 @@ #include "cmStandardIncludes.h" +/** + * Graph edge representation. Most use cases just need the + * destination vertex, so we support conversion to/from an int. We + * also store boolean to indicate whether an edge is "strong". + */ +class cmGraphEdge +{ +public: + cmGraphEdge(): Dest(0), Strong(true) {} + cmGraphEdge(int n): Dest(n), Strong(true) {} + cmGraphEdge(int n, bool s): Dest(n), Strong(s) {} + cmGraphEdge(cmGraphEdge const& r): Dest(r.Dest), Strong(r.Strong) {} + operator int() const { return this->Dest; } + + bool IsStrong() const { return this->Strong; } +private: + int Dest; + bool Strong; +}; +struct cmGraphEdgeList: public std::vector<cmGraphEdge> {}; struct cmGraphNodeList: public std::vector<int> {}; -struct cmGraphAdjacencyList: public std::vector<cmGraphNodeList> {}; +struct cmGraphAdjacencyList: public std::vector<cmGraphEdgeList> {}; #endif diff --git a/Source/cmGraphVizWriter.cxx b/Source/cmGraphVizWriter.cxx new file mode 100644 index 0000000..bdb33bc --- /dev/null +++ b/Source/cmGraphVizWriter.cxx @@ -0,0 +1,435 @@ +/*============================================================================ + CMake - Cross Platform Makefile Generator + Copyright 2000-2009 Kitware, Inc., Insight Software Consortium + + Distributed under the OSI-approved BSD License (the "License"); + see accompanying file Copyright.txt for details. + + This software is distributed WITHOUT ANY WARRANTY; without even the + implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the License for more information. +============================================================================*/ +#include "cmGraphVizWriter.h" +#include "cmMakefile.h" +#include "cmLocalGenerator.h" +#include "cmGlobalGenerator.h" +#include "cmGeneratedFileStream.h" + +#include <memory> + + + +static const char* getShapeForTarget(const cmTarget* target) +{ + if (!target) + { + return "ellipse"; + } + + switch ( target->GetType() ) + { + case cmTarget::EXECUTABLE: + return "house"; + case cmTarget::STATIC_LIBRARY: + return "diamond"; + case cmTarget::SHARED_LIBRARY: + return "polygon"; + case cmTarget::MODULE_LIBRARY: + return "octagon"; + default: + break; + } + + return "box"; +} + + +cmGraphVizWriter::cmGraphVizWriter(const std::vector<cmLocalGenerator*>& + localGenerators) +:GraphType("digraph") +,GraphName("GG") +,GraphHeader("node [\n fontsize = \"12\"\n];") +,GraphNodePrefix("node") +,GenerateForExecutables(true) +,GenerateForStaticLibs(true) +,GenerateForSharedLibs(true) +,GenerateForModuleLibs(true) +,LocalGenerators(localGenerators) +,HaveTargetsAndLibs(false) +{ +} + + +void cmGraphVizWriter::ReadSettings(const char* settingsFileName, + const char* fallbackSettingsFileName) +{ + cmake cm; + cmGlobalGenerator ggi; + ggi.SetCMakeInstance(&cm); + std::auto_ptr<cmLocalGenerator> lg(ggi.CreateLocalGenerator()); + cmMakefile *mf = lg->GetMakefile(); + + const char* inFileName = settingsFileName; + + if ( !cmSystemTools::FileExists(inFileName) ) + { + inFileName = fallbackSettingsFileName; + if ( !cmSystemTools::FileExists(inFileName) ) + { + return; + } + } + + if ( !mf->ReadListFile(0, inFileName) ) + { + cmSystemTools::Error("Problem opening GraphViz options file: ", + inFileName); + return; + } + + std::cout << "Reading GraphViz options file: " << inFileName << std::endl; + +#define __set_if_set(var, cmakeDefinition) \ + { \ + const char* value = mf->GetDefinition(cmakeDefinition); \ + if ( value ) \ + { \ + var = value; \ + } \ + } + + __set_if_set(this->GraphType, "GRAPHVIZ_GRAPH_TYPE"); + __set_if_set(this->GraphName, "GRAPHVIZ_GRAPH_NAME"); + __set_if_set(this->GraphHeader, "GRAPHVIZ_GRAPH_HEADER"); + __set_if_set(this->GraphNodePrefix, "GRAPHVIZ_NODE_PREFIX"); + +#define __set_bool_if_set(var, cmakeDefinition) \ + { \ + const char* value = mf->GetDefinition(cmakeDefinition); \ + if ( value ) \ + { \ + var = mf->IsOn(cmakeDefinition); \ + } \ + } + + __set_bool_if_set(this->GenerateForExecutables, "GRAPHVIZ_EXECUTABLES"); + __set_bool_if_set(this->GenerateForStaticLibs, "GRAPHVIZ_STATIC_LIBS"); + __set_bool_if_set(this->GenerateForSharedLibs, "GRAPHVIZ_SHARED_LIBS"); + __set_bool_if_set(this->GenerateForModuleLibs , "GRAPHVIZ_MODULE_LIBS"); + + cmStdString tmpRegexString; + __set_if_set(tmpRegexString, "GRAPHVIZ_TARGET_IGNORE_REGEX"); + if (tmpRegexString.size() > 0) + { + if (!this->TargetIgnoreRegex.compile(tmpRegexString.c_str())) + { + std::cerr << "Could not compile bad regex \"" << tmpRegexString << "\"" + << std::endl; + } + } + + this->TargetsToIgnore.clear(); + const char* ignoreTargets = mf->GetDefinition("GRAPHVIZ_IGNORE_TARGETS"); + if ( ignoreTargets ) + { + std::vector<std::string> ignoreTargetsVector; + cmSystemTools::ExpandListArgument(ignoreTargets,ignoreTargetsVector); + for(std::vector<std::string>::iterator itvIt = ignoreTargetsVector.begin(); + itvIt != ignoreTargetsVector.end(); + ++ itvIt ) + { + this->TargetsToIgnore.insert(itvIt->c_str()); + } + } + +} + + +void cmGraphVizWriter::WritePerTargetFiles(const char* fileName) +{ + this->CollectTargetsAndLibs(); + + for(std::map<cmStdString, const cmTarget*>::const_iterator ptrIt = + this->TargetPtrs.begin(); + ptrIt != this->TargetPtrs.end(); + ++ptrIt) + { + if (ptrIt->second == NULL) + { + continue; + } + + if (this->GenerateForTargetType(ptrIt->second->GetType()) == false) + { + continue; + } + + std::set<std::string> insertedConnections; + std::set<std::string> insertedNodes; + + std::string currentFilename = fileName; + currentFilename += "."; + currentFilename += ptrIt->first; + cmGeneratedFileStream str(currentFilename.c_str()); + if ( !str ) + { + return; + } + + std::cout << "Writing " << currentFilename << "..." << std::endl; + this->WriteHeader(str); + + this->WriteConnections(ptrIt->first.c_str(), + insertedNodes, insertedConnections, str); + this->WriteFooter(str); + } + +} + + +void cmGraphVizWriter::WriteGlobalFile(const char* fileName) +{ + this->CollectTargetsAndLibs(); + + cmGeneratedFileStream str(fileName); + if ( !str ) + { + return; + } + this->WriteHeader(str); + + std::cout << "Writing " << fileName << "..." << std::endl; + + std::set<std::string> insertedConnections; + std::set<std::string> insertedNodes; + + for(std::map<cmStdString, const cmTarget*>::const_iterator ptrIt = + this->TargetPtrs.begin(); + ptrIt != this->TargetPtrs.end(); + ++ptrIt) + { + if (ptrIt->second == NULL) + { + continue; + } + + if (this->GenerateForTargetType(ptrIt->second->GetType()) == false) + { + continue; + } + + this->WriteConnections(ptrIt->first.c_str(), + insertedNodes, insertedConnections, str); + } + this->WriteFooter(str); +} + + +void cmGraphVizWriter::WriteHeader(cmGeneratedFileStream& str) const +{ + str << this->GraphType << " " << this->GraphName << " {" << std::endl; + str << this->GraphHeader << std::endl; +} + + +void cmGraphVizWriter::WriteFooter(cmGeneratedFileStream& str) const +{ + str << "}" << std::endl; +} + + +void cmGraphVizWriter::WriteConnections(const char* targetName, + std::set<std::string>& insertedNodes, + std::set<std::string>& insertedConnections, + cmGeneratedFileStream& str) const +{ + std::map<cmStdString, const cmTarget* >::const_iterator targetPtrIt = + this->TargetPtrs.find(targetName); + + if (targetPtrIt == this->TargetPtrs.end()) // not found at all + { + return; + } + + this->WriteNode(targetName, targetPtrIt->second, insertedNodes, str); + + if (targetPtrIt->second == NULL) // it's an external library + { + return; + } + + + std::string myNodeName = this->TargetNamesNodes.find(targetName)->second; + + const cmTarget::LinkLibraryVectorType* ll = + &(targetPtrIt->second->GetOriginalLinkLibraries()); + + for (cmTarget::LinkLibraryVectorType::const_iterator llit = ll->begin(); + llit != ll->end(); + ++ llit ) + { + const char* libName = llit->first.c_str(); + std::map<cmStdString, cmStdString>::const_iterator libNameIt = + this->TargetNamesNodes.find(libName); + + std::string connectionName = myNodeName; + connectionName += "-"; + connectionName += libNameIt->second; + if (insertedConnections.find(connectionName) == insertedConnections.end()) + { + insertedConnections.insert(connectionName); + this->WriteNode(libName, this->TargetPtrs.find(libName)->second, + insertedNodes, str); + + str << " \"" << myNodeName.c_str() << "\" -> \"" + << libNameIt->second.c_str() << "\""; + str << " // " << targetName << " -> " << libName << std::endl; + this->WriteConnections(libName, insertedNodes, insertedConnections, str); + } + } + +} + + +void cmGraphVizWriter::WriteNode(const char* targetName, + const cmTarget* target, + std::set<std::string>& insertedNodes, + cmGeneratedFileStream& str) const +{ + if (insertedNodes.find(targetName) == insertedNodes.end()) + { + insertedNodes.insert(targetName); + std::map<cmStdString, cmStdString>::const_iterator nameIt = + this->TargetNamesNodes.find(targetName); + + str << " \"" << nameIt->second.c_str() << "\" [ label=\"" + << targetName << "\" shape=\"" << getShapeForTarget(target) + << "\"];" << std::endl; + } +} + + +void cmGraphVizWriter::CollectTargetsAndLibs() +{ + if (this->HaveTargetsAndLibs == false) + { + this->HaveTargetsAndLibs = true; + int cnt = this->CollectAllTargets(); + this->CollectAllExternalLibs(cnt); + } +} + + +int cmGraphVizWriter::CollectAllTargets() +{ + int cnt = 0; + // First pass get the list of all cmake targets + for (std::vector<cmLocalGenerator*>::const_iterator lit = + this->LocalGenerators.begin(); + lit != this->LocalGenerators.end(); + ++ lit ) + { + const cmTargets* targets = &((*lit)->GetMakefile()->GetTargets()); + for ( cmTargets::const_iterator tit = targets->begin(); + tit != targets->end(); + ++ tit ) + { + const char* realTargetName = tit->first.c_str(); + if(this->IgnoreThisTarget(realTargetName)) + { + // Skip ignored targets + continue; + } + //std::cout << "Found target: " << tit->first.c_str() << std::endl; + cmOStringStream ostr; + ostr << this->GraphNodePrefix << cnt++; + this->TargetNamesNodes[realTargetName] = ostr.str(); + this->TargetPtrs[realTargetName] = &tit->second; + } + } + + return cnt; +} + + +int cmGraphVizWriter::CollectAllExternalLibs(int cnt) +{ + // Ok, now find all the stuff we link to that is not in cmake + for (std::vector<cmLocalGenerator*>::const_iterator lit = + this->LocalGenerators.begin(); + lit != this->LocalGenerators.end(); + ++ lit ) + { + const cmTargets* targets = &((*lit)->GetMakefile()->GetTargets()); + for ( cmTargets::const_iterator tit = targets->begin(); + tit != targets->end(); + ++ tit ) + { + const char* realTargetName = tit->first.c_str(); + if (this->IgnoreThisTarget(realTargetName)) + { + // Skip ignored targets + continue; + } + const cmTarget::LinkLibraryVectorType* ll = + &(tit->second.GetOriginalLinkLibraries()); + for (cmTarget::LinkLibraryVectorType::const_iterator llit = ll->begin(); + llit != ll->end(); + ++ llit ) + { + const char* libName = llit->first.c_str(); + if (this->IgnoreThisTarget(libName)) + { + // Skip ignored targets + continue; + } + + std::map<cmStdString, const cmTarget*>::const_iterator tarIt = + this->TargetPtrs.find(libName); + if ( tarIt == this->TargetPtrs.end() ) + { + cmOStringStream ostr; + ostr << this->GraphNodePrefix << cnt++; + this->TargetNamesNodes[libName] = ostr.str(); + this->TargetPtrs[libName] = NULL; + //str << " \"" << ostr.c_str() << "\" [ label=\"" << libName + //<< "\" shape=\"ellipse\"];" << std::endl; + } + } + } + } + return cnt; +} + + +bool cmGraphVizWriter::IgnoreThisTarget(const char* name) +{ + if (this->TargetIgnoreRegex.is_valid()) + { + if (this->TargetIgnoreRegex.find(name)) + { + return true; + } + } + return (this->TargetsToIgnore.find(name) != this->TargetsToIgnore.end()); +} + + +bool cmGraphVizWriter::GenerateForTargetType(cmTarget::TargetType targetType) + const +{ + switch (targetType) + { + case cmTarget::EXECUTABLE: + return this->GenerateForExecutables; + case cmTarget::STATIC_LIBRARY: + return this->GenerateForStaticLibs; + case cmTarget::SHARED_LIBRARY: + return this->GenerateForSharedLibs; + case cmTarget::MODULE_LIBRARY: + return this->GenerateForModuleLibs; + default: + break; + } + return false; +} diff --git a/Source/cmGraphVizWriter.h b/Source/cmGraphVizWriter.h new file mode 100644 index 0000000..105eb96 --- /dev/null +++ b/Source/cmGraphVizWriter.h @@ -0,0 +1,84 @@ +#ifndef CMGRAPHVIZWRITER_H +#define CMGRAPHVIZWRITER_H +/*============================================================================ + CMake - Cross Platform Makefile Generator + Copyright 2000-2009 Kitware, Inc., Insight Software Consortium + + Distributed under the OSI-approved BSD License (the "License"); + see accompanying file Copyright.txt for details. + + This software is distributed WITHOUT ANY WARRANTY; without even the + implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the License for more information. +============================================================================*/ +#include "cmStandardIncludes.h" +#include "cmLocalGenerator.h" +#include "cmGeneratedFileStream.h" +#include "cmTarget.h" +#include <cmsys/RegularExpression.hxx> + + +/** This class implements writing files for graphviz (dot) for graphs + * representing the dependencies between the targets in the project. */ +class cmGraphVizWriter +{ +public: + + cmGraphVizWriter(const std::vector<cmLocalGenerator*>& localGenerators); + + void ReadSettings(const char* settingsFileName, + const char* fallbackSettingsFileName); + + void WritePerTargetFiles(const char* fileName); + + void WriteGlobalFile(const char* fileName); + +protected: + + void CollectTargetsAndLibs(); + + int CollectAllTargets(); + + int CollectAllExternalLibs(int cnt); + + void WriteHeader(cmGeneratedFileStream& str) const; + + void WriteConnections(const char* targetName, + std::set<std::string>& insertedNodes, + std::set<std::string>& insertedConnections, + cmGeneratedFileStream& str) const; + + void WriteNode(const char* targetName, const cmTarget* target, + std::set<std::string>& insertedNodes, + cmGeneratedFileStream& str) const; + + void WriteFooter(cmGeneratedFileStream& str) const; + + bool IgnoreThisTarget(const char* name); + + bool GenerateForTargetType(cmTarget::TargetType targetType) const; + + cmStdString GraphType; + cmStdString GraphName; + cmStdString GraphHeader; + cmStdString GraphNodePrefix; + + bool GenerateForExecutables; + bool GenerateForStaticLibs; + bool GenerateForSharedLibs; + bool GenerateForModuleLibs; + + cmsys::RegularExpression TargetIgnoreRegex; + + std::set<cmStdString> TargetsToIgnore; + + const std::vector<cmLocalGenerator*>& LocalGenerators; + + std::map<cmStdString, const cmTarget*> TargetPtrs; + // maps from the actual target names to node names in dot: + std::map<cmStdString, cmStdString> TargetNamesNodes; + + bool HaveTargetsAndLibs; +}; + +#endif diff --git a/Source/cmIfCommand.h b/Source/cmIfCommand.h index 107a892..4996bc4 100644 --- a/Source/cmIfCommand.h +++ b/Source/cmIfCommand.h @@ -125,10 +125,13 @@ public: "True if the constant is 1, ON, YES, TRUE, Y, or a non-zero number. " "False if the constant is 0, OFF, NO, FALSE, N, IGNORE, \"\", " "or ends in the suffix '-NOTFOUND'. " - "Named boolean constants are case-insensitive." + "Named boolean constants are case-insensitive. " + "If the argument is not one of these constants, " + "it is treated as a variable:" "\n" " if(<variable>)\n" - "True if the variable's value is not a false constant." + "True if the variable is defined to a value that is not a false " + "constant. False otherwise. " "\n" " if(NOT <expression>)\n" "True if the expression is not true." @@ -163,32 +166,25 @@ public: "Behavior is well-defined only for full paths.\n" " if(IS_ABSOLUTE path)\n" "True if the given path is an absolute path.\n" - " if(variable MATCHES regex)\n" - " if(string MATCHES regex)\n" + " if(<variable|string> MATCHES regex)\n" "True if the given string or variable's value matches the given " "regular expression.\n" - " if(variable LESS number)\n" - " if(string LESS number)\n" - " if(variable GREATER number)\n" - " if(string GREATER number)\n" - " if(variable EQUAL number)\n" - " if(string EQUAL number)\n" + " if(<variable|string> LESS <variable|string>)\n" + " if(<variable|string> GREATER <variable|string>)\n" + " if(<variable|string> EQUAL <variable|string>)\n" "True if the given string or variable's value is a valid number and " "the inequality or equality is true.\n" - " if(variable STRLESS string)\n" - " if(string STRLESS string)\n" - " if(variable STRGREATER string)\n" - " if(string STRGREATER string)\n" - " if(variable STREQUAL string)\n" - " if(string STREQUAL string)\n" + " if(<variable|string> STRLESS <variable|string>)\n" + " if(<variable|string> STRGREATER <variable|string>)\n" + " if(<variable|string> STREQUAL <variable|string>)\n" "True if the given string or variable's value is lexicographically " "less (or greater, or equal) than the string or variable on the right.\n" - " if(version1 VERSION_LESS version2)\n" - " if(version1 VERSION_EQUAL version2)\n" - " if(version1 VERSION_GREATER version2)\n" + " if(<variable|string> VERSION_LESS <variable|string>)\n" + " if(<variable|string> VERSION_EQUAL <variable|string>)\n" + " if(<variable|string> VERSION_GREATER <variable|string>)\n" "Component-wise integer version number comparison (version format is " "major[.minor[.patch[.tweak]]]).\n" - " if(DEFINED variable)\n" + " if(DEFINED <variable>)\n" "True if the given variable is defined. It does not matter if the " "variable is true or false just if it has been set.\n" " if((expression) AND (expression OR (expression)))\n" @@ -199,38 +195,27 @@ public: "that contains them." "\n" - "The if statement was written fairly early in CMake's history " - "and it has some convenience features that are worth covering. " - "The if statement reduces operations until there is " - "a single remaining value, at that point if the case " - "insensitive value is: ON, 1, YES, TRUE, Y it returns true, if " - "it is OFF, 0, NO, FALSE, N, NOTFOUND, *-NOTFOUND, IGNORE it " - "will return false. \n" - - "This is fairly reasonable. The convenience feature that sometimes " - "throws new authors is how CMake handles values that do not " - "match the true or false list. Those values are treated as " - "variables and are dereferenced even though they do not have " - "the required ${} syntax. This means that if you write\n" - - " if (boobah)\n" - - "CMake will treat it as if you wrote \n" - - " if (${boobah})\n" - - "likewise if you write \n" - - " if (fubar AND sol)\n" - - "CMake will conveniently treat it as \n" - - " if (\"${fubar}\" AND \"${sol}\")\n" - - "The later is really the correct way to write it, but the " - "former will work as well. Only some operations in the if " - "statement have this special handling of arguments. The " - "specific details follow: \n" + "The if command was written very early in CMake's history, predating " + "the ${} variable evaluation syntax, and for convenience evaluates " + "variables named by its arguments as shown in the above signatures. " + "Note that normal variable evaluation with ${} applies before the " + "if command even receives the arguments. " + "Therefore code like\n" + " set(var1 OFF)\n" + " set(var2 \"var1\")\n" + " if(${var2})\n" + "appears to the if command as\n" + " if(var1)\n" + "and is evaluated according to the if(<variable>) case " + "documented above. " + "The result is OFF which is false. " + "However, if we remove the ${} from the example then the command sees\n" + " if(var2)\n" + "which is true because var2 is defined to \"var1\" which is not " + "a false constant." + "\n" + "Automatic evaluation applies in the other cases whenever the " + "above-documented signature accepts <variable|string>:\n" "1) The left hand argument to MATCHES is first checked to see " "if it is a defined variable, if so the variable's value is " diff --git a/Source/cmIncludeCommand.cxx b/Source/cmIncludeCommand.cxx index c9b14a1..0ac6df4 100644 --- a/Source/cmIncludeCommand.cxx +++ b/Source/cmIncludeCommand.cxx @@ -26,10 +26,10 @@ bool cmIncludeCommand bool noPolicyScope = false; std::string fname = args[0]; std::string resultVarName; - + for (unsigned int i=1; i<args.size(); i++) { - if (args[i] == "OPTIONAL") + if (args[i] == "OPTIONAL") { if (optional) { @@ -60,10 +60,10 @@ bool cmIncludeCommand { noPolicyScope = true; } - else if(i > 1) // compat.: in previous cmake versions the second + else if(i > 1) // compat.: in previous cmake versions the second // parameter was ignore if it wasn't "OPTIONAL" { - std::string errorText = "called with invalid argument: "; + std::string errorText = "called with invalid argument: "; errorText += args[i]; this->SetError(errorText.c_str()); return false; @@ -82,15 +82,15 @@ bool cmIncludeCommand } } std::string fullFilePath; - bool readit = - this->Makefile->ReadListFile( this->Makefile->GetCurrentListFile(), + bool readit = + this->Makefile->ReadListFile( this->Makefile->GetCurrentListFile(), fname.c_str(), &fullFilePath, noPolicyScope); - + // add the location of the included file if a result variable was given if (resultVarName.size()) { - this->Makefile->AddDefinition(resultVarName.c_str(), + this->Makefile->AddDefinition(resultVarName.c_str(), readit?fullFilePath.c_str():"NOTFOUND"); } diff --git a/Source/cmIncludeCommand.h b/Source/cmIncludeCommand.h index a215275..d933ef3 100644 --- a/Source/cmIncludeCommand.h +++ b/Source/cmIncludeCommand.h @@ -15,7 +15,7 @@ #include "cmCommand.h" /** \class cmIncludeCommand - * \brief + * \brief * * cmIncludeCommand defines a list of distant * files that can be "included" in the current list file. @@ -28,7 +28,7 @@ public: /** * This is a virtual constructor for the command. */ - virtual cmCommand* Clone() + virtual cmCommand* Clone() { return new cmIncludeCommand; } @@ -49,15 +49,15 @@ public: * The name of the command as specified in CMakeList.txt. */ virtual const char* GetName() {return "include";} - + /** * Succinct documentation. */ - virtual const char* GetTerseDocumentation() + virtual const char* GetTerseDocumentation() { return "Read CMake listfile code from the given file."; } - + /** * More documentation. */ @@ -73,13 +73,17 @@ public: "the variable will be set to the full filename which " "has been included or NOTFOUND if it failed.\n" "If a module is specified instead of a file, the file with name " - "<modulename>.cmake is searched in the CMAKE_MODULE_PATH." + "<modulename>.cmake is searched first in CMAKE_MODULE_PATH, then in the " + "CMake module directory. There is one exception to this: if the file " + "which calls include() is located itself in the CMake module directory, " + "then first the CMake module directory is searched and " + "CMAKE_MODULE_PATH afterwards. See also policy CMP0017." "\n" "See the cmake_policy() command documentation for discussion of the " "NO_POLICY_SCOPE option." ; } - + cmTypeMacro(cmIncludeCommand, cmCommand); }; diff --git a/Source/cmIncludeDirectoryCommand.cxx b/Source/cmIncludeDirectoryCommand.cxx index 1c1444b..9e6f4b6 100644 --- a/Source/cmIncludeDirectoryCommand.cxx +++ b/Source/cmIncludeDirectoryCommand.cxx @@ -63,7 +63,7 @@ bool cmIncludeDirectoryCommand // " /foo/bar // /boo/hoo /dingle/berry " // -// ideally that should be three seperate arguments but when sucking the +// ideally that should be three separate arguments but when sucking the // output from a program and passing it into a command the cleanup doesn't // always happen // diff --git a/Source/cmIncludeExternalMSProjectCommand.h b/Source/cmIncludeExternalMSProjectCommand.h index d14d564..5269041 100644 --- a/Source/cmIncludeExternalMSProjectCommand.h +++ b/Source/cmIncludeExternalMSProjectCommand.h @@ -62,9 +62,8 @@ public: " dep1 dep2 ...)\n" "Includes an external Microsoft project in the generated workspace " "file. Currently does nothing on UNIX. This will create a " - "target named INCLUDE_EXTERNAL_MSPROJECT_[projectname]. This can " - "be used in the add_dependencies command to make things depend " - "on the external project."; + "target named [projectname]. This can be used in the add_dependencies " + "command to make things depend on the external project."; } cmTypeMacro(cmIncludeExternalMSProjectCommand, cmCommand); diff --git a/Source/cmInstallCommand.h b/Source/cmInstallCommand.h index ea0a1ec..8f62322 100644 --- a/Source/cmInstallCommand.h +++ b/Source/cmInstallCommand.h @@ -175,6 +175,7 @@ public: "The EXPORT option associates the installed target files with an " "export called <export-name>. " "It must appear before any RUNTIME, LIBRARY, or ARCHIVE options. " + "To actually install the export file itself, call install(EXPORT). " "See documentation of the install(EXPORT ...) signature below for " "details." "\n" diff --git a/Source/cmInstallGenerator.cxx b/Source/cmInstallGenerator.cxx index 47ca769..d7505dc 100644 --- a/Source/cmInstallGenerator.cxx +++ b/Source/cmInstallGenerator.cxx @@ -60,6 +60,29 @@ void cmInstallGenerator } os << indent; std::string dest = this->GetInstallDestination(); + if (cmSystemTools::FileIsFullPath(dest.c_str())) + { + os << "list(APPEND CPACK_ABSOLUTE_DESTINATION_FILES\n"; + os << indent << " \""; + for(std::vector<std::string>::const_iterator fi = files.begin(); + fi != files.end(); ++fi) + { + if (fi!=files.begin()) + { + os << ";"; + } + os << dest << "/"; + if (rename && *rename) + { + os << rename; + } + else + { + os << cmSystemTools::GetFilenameName(*fi); + } + } + os << "\")\n"; + } os << "FILE(INSTALL DESTINATION \"" << dest << "\" TYPE " << stype.c_str(); if(optional) { diff --git a/Source/cmLoadCacheCommand.cxx b/Source/cmLoadCacheCommand.cxx index d2a07dc..a239e55 100644 --- a/Source/cmLoadCacheCommand.cxx +++ b/Source/cmLoadCacheCommand.cxx @@ -174,7 +174,8 @@ void cmLoadCacheCommand::CheckLine(const char* line) // Check one line of the cache file. std::string var; std::string value; - if(this->ParseEntry(line, var, value)) + cmCacheManager::CacheEntryType type = cmCacheManager::UNINITIALIZED; + if(cmCacheManager::ParseEntry(line, var, value, type)) { // Found a real entry. See if this one was requested. if(this->VariablesToRead.find(var) != this->VariablesToRead.end()) @@ -193,38 +194,3 @@ void cmLoadCacheCommand::CheckLine(const char* line) } } } - -//---------------------------------------------------------------------------- -bool cmLoadCacheCommand::ParseEntry(const char* entry, std::string& var, - std::string& value) -{ - // input line is: key:type=value - cmsys::RegularExpression reg("^([^:]*):([^=]*)=(.*[^\t ]|[\t ]*)[\t ]*$"); - // input line is: "key":type=value - cmsys::RegularExpression - regQuoted("^\"([^\"]*)\":([^=]*)=(.*[^\t ]|[\t ]*)[\t ]*$"); - bool flag = false; - if(regQuoted.find(entry)) - { - var = regQuoted.match(1); - value = regQuoted.match(3); - flag = true; - } - else if (reg.find(entry)) - { - var = reg.match(1); - value = reg.match(3); - flag = true; - } - - // if value is enclosed in single quotes ('foo') then remove them - // it is used to enclose trailing space or tab - if (flag && - value.size() >= 2 && - value[0] == '\'' && - value[value.size() - 1] == '\'') - { - value = value.substr(1, value.size() - 2); - } - return flag; -} diff --git a/Source/cmLoadCacheCommand.h b/Source/cmLoadCacheCommand.h index b06d94d..8ecee4a 100644 --- a/Source/cmLoadCacheCommand.h +++ b/Source/cmLoadCacheCommand.h @@ -83,7 +83,6 @@ protected: bool ReadWithPrefix(std::vector<std::string> const& args); void CheckLine(const char* line); - bool ParseEntry(const char* entry, std::string& var, std::string& value); }; diff --git a/Source/cmLocalGenerator.cxx b/Source/cmLocalGenerator.cxx index 3339ee4..d3cbc1f 100644 --- a/Source/cmLocalGenerator.cxx +++ b/Source/cmLocalGenerator.cxx @@ -278,16 +278,8 @@ void cmLocalGenerator::GenerateTestFiles() // Compute the set of configurations. std::vector<std::string> configurationTypes; - if(const char* types = - this->Makefile->GetDefinition("CMAKE_CONFIGURATION_TYPES")) - { - cmSystemTools::ExpandListArgument(types, configurationTypes); - } - const char* config = 0; - if(configurationTypes.empty()) - { - config = this->Makefile->GetDefinition("CMAKE_BUILD_TYPE"); - } + const char* config = + this->Makefile->GetConfigurations(configurationTypes, false); std::string file = this->Makefile->GetStartOutputDirectory(); file += "/"; @@ -383,16 +375,8 @@ void cmLocalGenerator::GenerateInstallRules() // Compute the set of configurations. std::vector<std::string> configurationTypes; - if(const char* types = - this->Makefile->GetDefinition("CMAKE_CONFIGURATION_TYPES")) - { - cmSystemTools::ExpandListArgument(types, configurationTypes); - } - const char* config = 0; - if(configurationTypes.empty()) - { - config = this->Makefile->GetDefinition("CMAKE_BUILD_TYPE"); - } + const char* config = + this->Makefile->GetConfigurations(configurationTypes, false); // Choose a default install configuration. const char* default_config = config; @@ -546,19 +530,7 @@ void cmLocalGenerator::GenerateTargetManifest() { // Collect the set of configuration types. std::vector<std::string> configNames; - if(const char* configurationTypes = - this->Makefile->GetDefinition("CMAKE_CONFIGURATION_TYPES")) - { - cmSystemTools::ExpandListArgument(configurationTypes, configNames); - } - else if(const char* buildType = - this->Makefile->GetDefinition("CMAKE_BUILD_TYPE")) - { - if(*buildType) - { - configNames.push_back(buildType); - } - } + this->Makefile->GetConfigurations(configNames); // Add our targets to the manifest for each configuration. cmTargets& targets = this->Makefile->GetTargets(); @@ -712,9 +684,7 @@ void cmLocalGenerator::AddBuildTargetRule(const char* llang, cmTarget& target) std::string langFlags; this->AddLanguageFlags(langFlags, llang, 0); -#ifdef __APPLE__ this->AddArchitectureFlags(langFlags, &target, llang, 0); -#endif /* __APPLE__ */ vars.LanguageCompileFlags = langFlags.c_str(); cmCustomCommandLines commandLines; @@ -1272,8 +1242,8 @@ const char* cmLocalGenerator::GetIncludeFlags(const char* lang) #endif for(i = includes.begin(); i != includes.end(); ++i) { -#ifdef __APPLE__ - if(cmSystemTools::IsPathToFramework(i->c_str())) + if(this->Makefile->IsOn("APPLE") + && cmSystemTools::IsPathToFramework(i->c_str())) { std::string frameworkDir = *i; frameworkDir += "/../"; @@ -1288,7 +1258,7 @@ const char* cmLocalGenerator::GetIncludeFlags(const char* lang) } continue; } -#endif + std::string include = *i; if(!flagUsed || repeatFlag) { @@ -1766,12 +1736,17 @@ void cmLocalGenerator::OutputLinkLibraries(std::ostream& fout, //---------------------------------------------------------------------------- -#ifdef __APPLE__ void cmLocalGenerator::AddArchitectureFlags(std::string& flags, cmTarget* target, const char *lang, const char* config) { + // Only add Mac OS X specific flags on Darwin platforms (OSX and iphone): + if(!this->Makefile->IsOn("APPLE")) + { + return; + } + if(this->EmitUniversalBinaryFlags) { std::vector<std::string> archs; @@ -1784,6 +1759,10 @@ void cmLocalGenerator::AddArchitectureFlags(std::string& flags, this->Makefile->GetDefinition("CMAKE_OSX_DEPLOYMENT_TARGET"); std::string isysrootVar = std::string("CMAKE_") + lang + "_HAS_ISYSROOT"; bool hasIsysroot = this->Makefile->IsOn(isysrootVar.c_str()); + std::string deploymentTargetFlagVar = + std::string("CMAKE_") + lang + "_OSX_DEPLOYMENT_TARGET_FLAG"; + const char* deploymentTargetFlag = + this->Makefile->GetDefinition(deploymentTargetFlagVar.c_str()); bool flagsUsed = false; if(!archs.empty() && sysroot && lang && (lang[0] =='C' || lang[0] == 'F')) { @@ -1815,15 +1794,15 @@ void cmLocalGenerator::AddArchitectureFlags(std::string& flags, flags += sysroot; } - if (deploymentTarget && *deploymentTarget && - lang && (lang[0] =='C' || lang[0] == 'F')) + if (deploymentTargetFlag && *deploymentTargetFlag && + deploymentTarget && *deploymentTarget) { - flags += " -mmacosx-version-min="; + flags += " "; + flags += deploymentTargetFlag; flags += deploymentTarget; } } } -#endif /* __APPLE__ */ //---------------------------------------------------------------------------- @@ -1839,8 +1818,9 @@ void cmLocalGenerator::AddLanguageFlags(std::string& flags, } //---------------------------------------------------------------------------- -std::string cmLocalGenerator::GetRealDependency(const char* inName, - const char* config) +bool cmLocalGenerator::GetRealDependency(const char* inName, + const char* config, + std::string& dep) { // Older CMake code may specify the dependency using the target // output file rather than the target name. Such code would have @@ -1876,7 +1856,8 @@ std::string cmLocalGenerator::GetRealDependency(const char* inName, // it is a full path to a depend that has the same name // as a target but is in a different location so do not use // the target as the depend - return inName; + dep = inName; + return true; } } switch (target->GetType()) @@ -1890,15 +1871,16 @@ std::string cmLocalGenerator::GetRealDependency(const char* inName, // Get the location of the target's output file and depend on it. if(const char* location = target->GetLocation(config)) { - return location; + dep = location; + return true; } } break; case cmTarget::UTILITY: case cmTarget::GLOBAL_TARGET: - // Depending on a utility target may not work but just trust - // the user to have given a valid name. - return inName; + // A utility target has no file on which to depend. This was listed + // only to get the target-level dependency. + return false; case cmTarget::INSTALL_FILES: case cmTarget::INSTALL_PROGRAMS: case cmTarget::INSTALL_DIRECTORY: @@ -1910,41 +1892,24 @@ std::string cmLocalGenerator::GetRealDependency(const char* inName, if(cmSystemTools::FileIsFullPath(inName)) { // This is a full path. Return it as given. - return inName; + dep = inName; + return true; } // Check for a source file in this directory that matches the // dependency. if(cmSourceFile* sf = this->Makefile->GetSource(inName)) { - name = sf->GetFullPath(); - return name; + dep = sf->GetFullPath(); + return true; } // Treat the name as relative to the source directory in which it // was given. - name = this->Makefile->GetCurrentDirectory(); - name += "/"; - name += inName; - return name; -} - -//---------------------------------------------------------------------------- -std::string cmLocalGenerator::GetRealLocation(const char* inName, - const char* config) -{ - std::string outName=inName; - // Look for a CMake target with the given name, which is an executable - // and which can be run - cmTarget* target = this->Makefile->FindTargetToUse(inName); - if ((target != 0) - && (target->GetType() == cmTarget::EXECUTABLE) - && ((this->Makefile->IsOn("CMAKE_CROSSCOMPILING") == false) - || (target->IsImported() == true))) - { - outName = target->GetLocation( config ); - } - return outName; + dep = this->Makefile->GetCurrentDirectory(); + dep += "/"; + dep += inName; + return true; } //---------------------------------------------------------------------------- @@ -2242,6 +2207,10 @@ std::string cmLocalGenerator::ConvertToOutputFormat(const char* source, } result = this->EscapeForShell(result.c_str(), true, false); } + else if(output == RESPONSE) + { + result = this->EscapeForShell(result.c_str(), false, false); + } return result; } @@ -2799,17 +2768,29 @@ cmLocalGenerator std::string cmLocalGenerator::EscapeForShellOldStyle(const char* str) { std::string result; - bool forceOn = cmSystemTools::GetForceUnixPaths(); - if(forceOn && this->WindowsShell) +#if defined(_WIN32) && !defined(__CYGWIN__) + // if there are spaces + std::string temp = str; + if (temp.find(" ") != std::string::npos && + temp.find("\"")==std::string::npos) { - cmSystemTools::SetForceUnixPaths(false); + result = "\""; + result += str; + result += "\""; + return result; } - result = cmSystemTools::EscapeSpaces(str); - if(forceOn && this->WindowsShell) + return str; +#else + for(const char* ch = str; *ch != '\0'; ++ch) { - cmSystemTools::SetForceUnixPaths(true); + if(*ch == ' ') + { + result += '\\'; + } + result += *ch; } return result; +#endif } //---------------------------------------------------------------------------- @@ -3034,7 +3015,7 @@ bool cmLocalGenerator::CheckDefinition(std::string const& define) const if(define.find_first_of("#") != define.npos) { cmOStringStream e; - e << "WARNING: Peprocessor definitions containing '#' may not be " + e << "WARNING: Preprocessor definitions containing '#' may not be " << "passed on the compiler command line because many compilers " << "do not support it.\n" << "CMake is dropping a preprocessor definition: " << define << "\n" diff --git a/Source/cmLocalGenerator.h b/Source/cmLocalGenerator.h index becdfff..35aab99 100644 --- a/Source/cmLocalGenerator.h +++ b/Source/cmLocalGenerator.h @@ -102,7 +102,7 @@ public: * path setting */ enum RelativeRoot { NONE, FULL, HOME, START, HOME_OUTPUT, START_OUTPUT }; - enum OutputFormat { UNCHANGED, MAKEFILE, SHELL }; + enum OutputFormat { UNCHANGED, MAKEFILE, SHELL, RESPONSE }; std::string ConvertToOutputFormat(const char* source, OutputFormat output); std::string Convert(const char* remote, RelativeRoot local, OutputFormat output = UNCHANGED, @@ -133,10 +133,8 @@ public: std::vector<cmLocalGenerator*>& GetChildren() { return this->Children; }; -#ifdef __APPLE__ void AddArchitectureFlags(std::string& flags, cmTarget* target, const char *lang, const char* config); -#endif /* __APPLE__ */ void AddLanguageFlags(std::string& flags, const char* lang, const char* config); @@ -160,18 +158,15 @@ public: /** Translate a dependency as given in CMake code to the name to appear in a generated build file. If the given name is that of + a utility target, returns false. If the given name is that of a CMake target it will be transformed to the real output location of that target for the given configuration. If the given name is the full path to a file it will be returned. Otherwise the name is treated as a relative path with respect to the source directory of this generator. This should only be used for dependencies of custom commands. */ - std::string GetRealDependency(const char* name, const char* config); - - /** Translate a command as given in CMake code to the location of the - executable if the command is the name of a CMake executable target. - If that's not the case, just return the original name. */ - std::string GetRealLocation(const char* inName, const char* config); + bool GetRealDependency(const char* name, const char* config, + std::string& dep); ///! for existing files convert to output path and short path if spaces std::string ConvertToOutputForExisting(const char* remote, diff --git a/Source/cmLocalUnixMakefileGenerator3.cxx b/Source/cmLocalUnixMakefileGenerator3.cxx index fce5a9c..ff48009 100644 --- a/Source/cmLocalUnixMakefileGenerator3.cxx +++ b/Source/cmLocalUnixMakefileGenerator3.cxx @@ -19,6 +19,7 @@ #include "cmake.h" #include "cmVersion.h" #include "cmFileTimeComparison.h" +#include "cmCustomCommandGenerator.h" // Include dependency scanners for supported languages. Only the // C/C++ scanner is needed for bootstrapping CMake. @@ -140,7 +141,7 @@ void cmLocalUnixMakefileGenerator3::Generate() // write the local Makefile this->WriteLocalMakefile(); - + // Write the cmake file with information for this directory. this->WriteDirectoryInformationFile(); } @@ -149,7 +150,7 @@ void cmLocalUnixMakefileGenerator3::Generate() void cmLocalUnixMakefileGenerator3::GetIndividualFileTargets (std::vector<std::string>& targets) { - for (std::map<cmStdString, LocalObjectInfo>::iterator lo = + for (std::map<cmStdString, LocalObjectInfo>::iterator lo = this->LocalObjectFiles.begin(); lo != this->LocalObjectFiles.end(); ++lo) { @@ -188,10 +189,10 @@ void cmLocalUnixMakefileGenerator3::WriteLocalMakefile() { ruleFileStream.SetCopyIfDifferent(true); } - + // write the all rules this->WriteLocalAllRules(ruleFileStream); - + // only write local targets unless at the top Keep track of targets already // listed. std::set<cmStdString> emittedTargets; @@ -203,7 +204,7 @@ void cmLocalUnixMakefileGenerator3::WriteLocalMakefile() } else { - cmGlobalUnixMakefileGenerator3 *gg = + cmGlobalUnixMakefileGenerator3 *gg = static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator); gg->WriteConvenienceRules(ruleFileStream,emittedTargets); } @@ -215,7 +216,7 @@ void cmLocalUnixMakefileGenerator3::WriteLocalMakefile() // now write out the object rules // for each object file name - for (std::map<cmStdString, LocalObjectInfo>::iterator lo = + for (std::map<cmStdString, LocalObjectInfo>::iterator lo = this->LocalObjectFiles.begin(); lo != this->LocalObjectFiles.end(); ++lo) { @@ -261,7 +262,7 @@ void cmLocalUnixMakefileGenerator3::WriteLocalMakefile() // add a help target as long as there isn;t a real target named help if(emittedTargets.insert("help").second) { - cmGlobalUnixMakefileGenerator3 *gg = + cmGlobalUnixMakefileGenerator3 *gg = static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator); gg->WriteHelpRule(ruleFileStream,this); } @@ -353,7 +354,7 @@ void cmLocalUnixMakefileGenerator3 localName += "/rule"; commands.clear(); depends.clear(); - + // Build the target for this pass. std::string makefile2 = cmake::GetCMakeFilesDirectoryPostSlash(); makefile2 += "Makefile2"; @@ -364,7 +365,7 @@ void cmLocalUnixMakefileGenerator3 cmLocalGenerator::START_OUTPUT); this->WriteMakeRule(ruleFileStream, "Convenience name for target.", localName.c_str(), depends, commands, true); - + // Add a target with the canonical name (no prefix, suffix or path). if(localName != t->second.GetName()) { @@ -378,7 +379,7 @@ void cmLocalUnixMakefileGenerator3 std::string makefileName = this->GetRelativeTargetDirectory(t->second); makefileName += "/build.make"; // make sure the makefile name is suitable for a makefile - std::string makeTargetName = + std::string makeTargetName = this->GetRelativeTargetDirectory(t->second); makeTargetName += "/build"; localName = t->second.GetName(); @@ -647,7 +648,7 @@ cmLocalUnixMakefileGenerator3 makefileStream << "# The CMake executable.\n" << "CMAKE_COMMAND = " - << this->Convert(cmakecommand.c_str(), FULL, SHELL).c_str() + << this->Convert(cmakecommand.c_str(), FULL, SHELL).c_str() << "\n" << "\n"; makefileStream @@ -656,7 +657,7 @@ cmLocalUnixMakefileGenerator3 << this->Convert(cmakecommand.c_str(),FULL,SHELL).c_str() << " -E remove -f\n" << "\n"; - + if(const char* edit_cmd = this->Makefile->GetDefinition("CMAKE_EDIT_COMMAND")) { @@ -722,8 +723,7 @@ cmLocalUnixMakefileGenerator3 // "VERBOSE=1" to be added as a make variable which will change the // name of this special target. This gives a make-time choice to // the user. - if((this->Makefile->IsOn("CMAKE_VERBOSE_MAKEFILE")) - || (gg->GetForceVerboseMakefiles())) + if(this->Makefile->IsOn("CMAKE_VERBOSE_MAKEFILE")) { makefileStream << "# Produce verbose output by default.\n" @@ -872,7 +872,7 @@ cmLocalUnixMakefileGenerator3 { // Add a dependency on the rule file itself unless an option to skip // it is specifically enabled by the user or project. - const char* nodep = + const char* nodep = this->Makefile->GetDefinition("CMAKE_SKIP_RULE_DEPENDENCY"); if(!nodep || cmSystemTools::IsOff(nodep)) { @@ -903,9 +903,12 @@ cmLocalUnixMakefileGenerator3 d != cc.GetDepends().end(); ++d) { // Lookup the real name of the dependency in case it is a CMake target. - std::string dep = this->GetRealDependency - (d->c_str(), this->ConfigurationName.c_str()); - depends.push_back(dep); + std::string dep; + if(this->GetRealDependency(d->c_str(), this->ConfigurationName.c_str(), + dep)) + { + depends.push_back(dep); + } } } @@ -959,20 +962,35 @@ cmLocalUnixMakefileGenerator3 { *content << dir; } - bool escapeOldStyle = cc.GetEscapeOldStyle(); - bool escapeAllowMakeVars = cc.GetEscapeAllowMakeVars(); + cmCustomCommandGenerator ccg(cc, this->ConfigurationName.c_str(), + this->Makefile); // Add each command line to the set of commands. std::vector<std::string> commands1; - for(cmCustomCommandLines::const_iterator cl = cc.GetCommandLines().begin(); - cl != cc.GetCommandLines().end(); ++cl) + for(unsigned int c = 0; c < ccg.GetNumberOfCommands(); ++c) { // Build the command line in a single string. - const cmCustomCommandLine& commandLine = *cl; - std::string cmd = GetRealLocation(commandLine[0].c_str(), - this->ConfigurationName.c_str()); + std::string cmd = ccg.GetCommand(c); if (cmd.size()) { + // Use "call " before any invocations of .bat or .cmd files + // invoked as custom commands in the WindowsShell. + // + bool useCall = false; + + if (this->WindowsShell) + { + std::string suffix; + if (cmd.size() > 4) + { + suffix = cmSystemTools::LowerCase(cmd.substr(cmd.size()-4)); + if (suffix == ".bat" || suffix == ".cmd") + { + useCall = true; + } + } + } + cmSystemTools::ReplaceString(cmd, "/./", "/"); // Convert the command to a relative path only if the current // working directory will be the start-output directory. @@ -1005,19 +1023,8 @@ cmLocalUnixMakefileGenerator3 std::string launcher = this->MakeLauncher(cc, target, workingDir? NONE : START_OUTPUT); cmd = launcher + this->Convert(cmd.c_str(),NONE,SHELL); - for(unsigned int j=1; j < commandLine.size(); ++j) - { - cmd += " "; - if(escapeOldStyle) - { - cmd += this->EscapeForShellOldStyle(commandLine[j].c_str()); - } - else - { - cmd += this->EscapeForShell(commandLine[j].c_str(), - escapeAllowMakeVars); - } - } + + ccg.AppendArguments(c, cmd); if(content) { // Rule content does not include the launcher. @@ -1044,6 +1051,17 @@ cmLocalUnixMakefileGenerator3 } } } + if (launcher.empty()) + { + if (useCall) + { + cmd = "call " + cmd; + } + else if (this->NMake && cmd[0]=='"') + { + cmd = "echo >nul && " + cmd; + } + } commands1.push_back(cmd); } } @@ -1254,7 +1272,7 @@ cmLocalUnixMakefileGenerator3 // see if the variable has been defined before and return // the modified version of the variable - std::map<cmStdString, cmStdString>::iterator i = + std::map<cmStdString, cmStdString>::iterator i = this->MakeVariableMap.find(unmodified); if(i != this->MakeVariableMap.end()) { @@ -1375,7 +1393,7 @@ bool cmLocalUnixMakefileGenerator3::UpdateDependencies(const char* tgtInfo, dirInfoFile += "/CMakeDirectoryInformation.cmake"; { int result; - if(!ftc->FileTimeCompare(internalDependFile.c_str(), + if(!ftc->FileTimeCompare(internalDependFile.c_str(), dirInfoFile.c_str(), &result) || result < 0) { if(verbose) @@ -1389,7 +1407,7 @@ bool cmLocalUnixMakefileGenerator3::UpdateDependencies(const char* tgtInfo, needRescanDirInfo = true; } } - + // Check the implicit dependencies to see if they are up to date. // The build.make file may have explicit dependencies for the object // files but these will not affect the scanning process so they need @@ -1404,11 +1422,11 @@ bool cmLocalUnixMakefileGenerator3::UpdateDependencies(const char* tgtInfo, // cmDependsC::Check() fills the vector validDependencies() with the // dependencies for those files where they are still valid, i.e. neither // the files themselves nor any files they depend on have changed. - // We don't do that if the CMakeDirectoryInformation.cmake file has + // We don't do that if the CMakeDirectoryInformation.cmake file has // changed, because then potentially all dependencies have changed. // This information is given later on to cmDependsC, which then only // rescans the files where it did not get valid dependencies via this - // dependency vector. This means that in the normal case, when only + // dependency vector. This means that in the normal case, when only // few or one file have been edited, then also only this one file is // actually scanned again, instead of all files for this target. needRescanDependencies = !checker.Check(dependFile.c_str(), @@ -1456,7 +1474,7 @@ cmLocalUnixMakefileGenerator3 { haveDirectoryInfo = true; } - + // Lookup useful directory information. if(haveDirectoryInfo) { @@ -1516,11 +1534,11 @@ cmLocalUnixMakefileGenerator3 this->WriteDisclaimer(ruleFileStream); this->WriteDisclaimer(internalRuleFileStream); - // for each language we need to scan, scan it + // for each language we need to scan, scan it const char *langStr = mf->GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES"); std::vector<std::string> langs; cmSystemTools::ExpandListArgument(langStr, langs); - for (std::vector<std::string>::iterator li = + for (std::vector<std::string>::iterator li = langs.begin(); li != langs.end(); ++li) { // construct the checker @@ -1543,7 +1561,7 @@ cmLocalUnixMakefileGenerator3 scanner = new cmDependsJava(); } #endif - + if (scanner) { scanner->SetLocalGenerator(this); @@ -1657,25 +1675,25 @@ void cmLocalUnixMakefileGenerator3 cmLocalUnixMakefileGenerator3::EchoGlobal); // Global targets store their rules in pre- and post-build commands. - this->AppendCustomDepends(depends, + this->AppendCustomDepends(depends, glIt->second.GetPreBuildCommands()); - this->AppendCustomDepends(depends, + this->AppendCustomDepends(depends, glIt->second.GetPostBuildCommands()); - this->AppendCustomCommands(commands, + this->AppendCustomCommands(commands, glIt->second.GetPreBuildCommands(), &glIt->second, cmLocalGenerator::START_OUTPUT); - this->AppendCustomCommands(commands, + this->AppendCustomCommands(commands, glIt->second.GetPostBuildCommands(), &glIt->second, cmLocalGenerator::START_OUTPUT); std::string targetName = glIt->second.GetName(); - this->WriteMakeRule(ruleFileStream, targetString.c_str(), + this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName.c_str(), depends, commands, true); // Provide a "/fast" version of the target. depends.clear(); - if((targetName == "install") + if((targetName == "install") || (targetName == "install_local") || (targetName == "install_strip")) { @@ -1709,7 +1727,7 @@ void cmLocalUnixMakefileGenerator3 progressDir += cmake::GetCMakeFilesDirectory(); { cmOStringStream progCmd; - progCmd << + progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start "; progCmd << this->Convert(progressDir.c_str(), cmLocalGenerator::FULL, @@ -1804,8 +1822,8 @@ void cmLocalUnixMakefileGenerator3 this->CreateCDCommand(commands, this->Makefile->GetHomeOutputDirectory(), cmLocalGenerator::START_OUTPUT); - this->WriteMakeRule(ruleFileStream, "clear depends", - "depend", + this->WriteMakeRule(ruleFileStream, "clear depends", + "depend", depends, commands, true); } @@ -2019,7 +2037,7 @@ cmLocalUnixMakefileGenerator3 cmd += "$(MAKE) -f "; cmd += this->Convert(makefile,NONE,SHELL); cmd += " "; - + // Pass down verbosity level. if(this->GetMakeSilentFlag().size()) { @@ -2096,7 +2114,7 @@ cmLocalUnixMakefileGenerator3 std::string cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath(const char* p) { - + // Split the path into its components. std::vector<std::string> components; cmSystemTools::SplitPath(p, components); @@ -2195,7 +2213,7 @@ void cmLocalUnixMakefileGenerator3 { return; } - + if(!this->UnixCD) { // On Windows we must perform each step separately and then change diff --git a/Source/cmLocalVisualStudio10Generator.cxx b/Source/cmLocalVisualStudio10Generator.cxx index 8df0ffa..de2a837 100644 --- a/Source/cmLocalVisualStudio10Generator.cxx +++ b/Source/cmLocalVisualStudio10Generator.cxx @@ -37,7 +37,7 @@ class cmVS10XMLParser : public cmXMLParser { return; } - if(strcmp("ProjectGUID", name) == 0) + if(strcmp("ProjectGUID", name) == 0 || strcmp("ProjectGuid", name) == 0) { this->DoGUID = true; } @@ -117,3 +117,9 @@ void cmLocalVisualStudio10Generator "Stored GUID", cmCacheManager::INTERNAL); } + +//---------------------------------------------------------------------------- +std::string cmLocalVisualStudio10Generator::CheckForErrorLine() +{ + return "if errorlevel 1 goto :VCEnd"; +} diff --git a/Source/cmLocalVisualStudio10Generator.h b/Source/cmLocalVisualStudio10Generator.h index 5694220..06b8b09 100644 --- a/Source/cmLocalVisualStudio10Generator.h +++ b/Source/cmLocalVisualStudio10Generator.h @@ -36,6 +36,10 @@ public: virtual void Generate(); virtual void ReadAndStoreExternalGUID(const char* name, const char* path); + +protected: + virtual std::string CheckForErrorLine(); + private: }; #endif diff --git a/Source/cmLocalVisualStudio6Generator.cxx b/Source/cmLocalVisualStudio6Generator.cxx index 2cf840d..7aabf4d 100644 --- a/Source/cmLocalVisualStudio6Generator.cxx +++ b/Source/cmLocalVisualStudio6Generator.cxx @@ -65,13 +65,7 @@ public: { this->Code += "\\\n\t"; } - this->Code += - this->LG->ConstructScript(cc.GetCommandLines(), - cc.GetWorkingDirectory(), - this->Config, - cc.GetEscapeOldStyle(), - cc.GetEscapeAllowMakeVars(), - "\\\n\t"); + this->Code += this->LG->ConstructScript(cc, this->Config, "\\\n\t"); } private: cmLocalVisualStudio6Generator* LG; @@ -659,12 +653,7 @@ cmLocalVisualStudio6Generator { std::string config = this->GetConfigName(*i); std::string script = - this->ConstructScript(command.GetCommandLines(), - command.GetWorkingDirectory(), - config.c_str(), - command.GetEscapeOldStyle(), - command.GetEscapeAllowMakeVars(), - "\\\n\t"); + this->ConstructScript(command, config.c_str(), "\\\n\t"); if (i == this->Configurations.begin()) { @@ -686,10 +675,12 @@ cmLocalVisualStudio6Generator ++d) { // Lookup the real name of the dependency in case it is a CMake target. - std::string dep = this->GetRealDependency(d->c_str(), - config.c_str()); - fout << "\\\n\t" << - this->ConvertToOptionallyRelativeOutputPath(dep.c_str()); + std::string dep; + if(this->GetRealDependency(d->c_str(), config.c_str(), dep)) + { + fout << "\\\n\t" << + this->ConvertToOptionallyRelativeOutputPath(dep.c_str()); + } } fout << "\n"; @@ -847,7 +838,7 @@ cmLocalVisualStudio6Generator::MaybeCreateOutputDir(cmTarget& target, std::vector<std::string> no_depends; cmCustomCommandLines commands; commands.push_back(command); - pcc.reset(new cmCustomCommand(no_output, no_depends, commands, 0, 0)); + pcc.reset(new cmCustomCommand(0, no_output, no_depends, commands, 0, 0)); pcc->SetEscapeOldStyle(false); pcc->SetEscapeAllowMakeVars(true); return pcc; @@ -1142,6 +1133,10 @@ void cmLocalVisualStudio6Generator // Get extra linker options for this target type. std::string extraLinkOptions; + std::string extraLinkOptionsDebug; + std::string extraLinkOptionsRelease; + std::string extraLinkOptionsMinSizeRel; + std::string extraLinkOptionsRelWithDebInfo; if(target.GetType() == cmTarget::EXECUTABLE) { extraLinkOptions = @@ -1165,6 +1160,34 @@ void cmLocalVisualStudio6Generator extraLinkOptions += targetLinkFlags; } + if(const char* targetLinkFlags = target.GetProperty("LINK_FLAGS_DEBUG")) + { + extraLinkOptionsDebug += " "; + extraLinkOptionsDebug += targetLinkFlags; + } + + if(const char* targetLinkFlags = target.GetProperty("LINK_FLAGS_RELEASE")) + { + extraLinkOptionsRelease += " "; + extraLinkOptionsRelease += targetLinkFlags; + } + + if(const char* targetLinkFlags = target.GetProperty("LINK_FLAGS_MINSIZEREL")) + { + extraLinkOptionsMinSizeRel += " "; + extraLinkOptionsMinSizeRel += targetLinkFlags; + } + + if(const char* targetLinkFlags = + target.GetProperty("LINK_FLAGS_RELWITHDEBINFO")) + { + extraLinkOptionsRelWithDebInfo += " "; + extraLinkOptionsRelWithDebInfo += targetLinkFlags; + } + + + + // Get standard libraries for this language. if(targetBuilds) { @@ -1259,13 +1282,22 @@ void cmLocalVisualStudio6Generator target.GetType() == cmTarget::SHARED_LIBRARY || target.GetType() == cmTarget::MODULE_LIBRARY) { - this->ComputeLinkOptions(target, "Debug", extraLinkOptions, + extraLinkOptionsDebug = + extraLinkOptions + " " + extraLinkOptionsDebug; + extraLinkOptionsRelease = + extraLinkOptions + " " + extraLinkOptionsRelease; + extraLinkOptionsMinSizeRel = + extraLinkOptions + " " + extraLinkOptionsMinSizeRel; + extraLinkOptionsRelWithDebInfo = + extraLinkOptions + " " + extraLinkOptionsRelWithDebInfo; + this->ComputeLinkOptions(target, "Debug", extraLinkOptionsDebug, optionsDebug); - this->ComputeLinkOptions(target, "Release", extraLinkOptions, + this->ComputeLinkOptions(target, "Release", extraLinkOptionsRelease, optionsRelease); - this->ComputeLinkOptions(target, "MinSizeRel", extraLinkOptions, + this->ComputeLinkOptions(target, "MinSizeRel", extraLinkOptionsMinSizeRel, optionsMinSizeRel); - this->ComputeLinkOptions(target, "RelWithDebInfo", extraLinkOptions, + this->ComputeLinkOptions(target, "RelWithDebInfo", + extraLinkOptionsRelWithDebInfo, optionsRelWithDebInfo); } @@ -1342,11 +1374,43 @@ void cmLocalVisualStudio6Generator cmSystemTools::Error("Error Reading ", this->DSPHeaderTemplate.c_str()); } std::string staticLibOptions; + std::string staticLibOptionsDebug; + std::string staticLibOptionsRelease; + std::string staticLibOptionsMinSizeRel; + std::string staticLibOptionsRelWithDebInfo; if(target.GetType() == cmTarget::STATIC_LIBRARY ) { if(const char* libflags = target.GetProperty("STATIC_LIBRARY_FLAGS")) { staticLibOptions = libflags; + staticLibOptionsDebug = libflags; + staticLibOptionsRelease = libflags; + staticLibOptionsMinSizeRel = libflags; + staticLibOptionsRelWithDebInfo = libflags; + } + if(const char* libflagsDebug = + target.GetProperty("STATIC_LIBRARY_FLAGS_DEBUG")) + { + staticLibOptionsDebug += " "; + staticLibOptionsDebug = libflagsDebug; + } + if(const char* libflagsRelease = + target.GetProperty("STATIC_LIBRARY_FLAGS_RELEASE")) + { + staticLibOptionsRelease += " "; + staticLibOptionsRelease = libflagsRelease; + } + if(const char* libflagsMinSizeRel = + target.GetProperty("STATIC_LIBRARY_FLAGS_MINSIZEREL")) + { + staticLibOptionsMinSizeRel += " "; + staticLibOptionsMinSizeRel = libflagsMinSizeRel; + } + if(const char* libflagsRelWithDebInfo = + target.GetProperty("STATIC_LIBRARY_FLAGS_RELWITHDEBINFO")) + { + staticLibOptionsRelWithDebInfo += " "; + staticLibOptionsRelWithDebInfo = libflagsRelWithDebInfo; } } @@ -1378,6 +1442,14 @@ void cmLocalVisualStudio6Generator mfcFlag); if(target.GetType() == cmTarget::STATIC_LIBRARY ) { + cmSystemTools::ReplaceString(line, "CM_STATIC_LIB_ARGS_DEBUG", + staticLibOptionsDebug.c_str()); + cmSystemTools::ReplaceString(line, "CM_STATIC_LIB_ARGS_RELEASE", + staticLibOptionsRelease.c_str()); + cmSystemTools::ReplaceString(line, "CM_STATIC_LIB_ARGS_MINSIZEREL", + staticLibOptionsMinSizeRel.c_str()); + cmSystemTools::ReplaceString(line, "CM_STATIC_LIB_ARGS_RELWITHDEBINFO", + staticLibOptionsRelWithDebInfo.c_str()); cmSystemTools::ReplaceString(line, "CM_STATIC_LIB_ARGS", staticLibOptions.c_str()); } @@ -1420,7 +1492,7 @@ void cmLocalVisualStudio6Generator outputNameDebug.c_str()); cmSystemTools::ReplaceString(line, "OUTPUT_NAME_RELEASE", outputNameRelease.c_str()); - cmSystemTools::ReplaceString(line, "OUTPUT_NAME_MINSIZEREL", + cmSystemTools::ReplaceString(line, "OUTPUT_NAME_MINSIZEREL", outputNameMinSizeRel.c_str()); cmSystemTools::ReplaceString(line, "OUTPUT_NAME_RELWITHDEBINFO", outputNameRelWithDebInfo.c_str()); @@ -1431,7 +1503,7 @@ void cmLocalVisualStudio6Generator optionsDebug.c_str()); cmSystemTools::ReplaceString(line, "CM_MULTILINE_OPTIONS_RELEASE", optionsRelease.c_str()); - cmSystemTools::ReplaceString(line, "CM_MULTILINE_OPTIONS_MINSIZEREL", + cmSystemTools::ReplaceString(line, "CM_MULTILINE_OPTIONS_MINSIZEREL", optionsMinSizeRel.c_str()); cmSystemTools::ReplaceString(line, "CM_MULTILINE_OPTIONS_RELWITHDEBINFO", optionsRelWithDebInfo.c_str()); @@ -1519,41 +1591,18 @@ void cmLocalVisualStudio6Generator std::string flagVar = baseFlagVar + "_RELEASE"; flagsRelease = this->Makefile->GetSafeDefinition(flagVar.c_str()); flagsRelease += " -DCMAKE_INTDIR=\\\"Release\\\" "; - if(const char* targetLinkFlags = - target.GetProperty("LINK_FLAGS_RELEASE")) - { - flagsRelease += targetLinkFlags; - flagsRelease += " "; - } + flagVar = baseFlagVar + "_MINSIZEREL"; flagsMinSize = this->Makefile->GetSafeDefinition(flagVar.c_str()); flagsMinSize += " -DCMAKE_INTDIR=\\\"MinSizeRel\\\" "; - if(const char* targetLinkFlags = - target.GetProperty("LINK_FLAGS_MINSIZEREL")) - { - flagsMinSize += targetLinkFlags; - flagsMinSize += " "; - } - + flagVar = baseFlagVar + "_DEBUG"; flagsDebug = this->Makefile->GetSafeDefinition(flagVar.c_str()); flagsDebug += " -DCMAKE_INTDIR=\\\"Debug\\\" "; - if(const char* targetLinkFlags = target.GetProperty("LINK_FLAGS_DEBUG")) - { - flagsDebug += targetLinkFlags; - flagsDebug += " "; - } flagVar = baseFlagVar + "_RELWITHDEBINFO"; flagsDebugRel = this->Makefile->GetSafeDefinition(flagVar.c_str()); flagsDebugRel += " -DCMAKE_INTDIR=\\\"RelWithDebInfo\\\" "; - if(const char* targetLinkFlags = - target.GetProperty("LINK_FLAGS_RELWITHDEBINFO")) - { - flagsDebugRel += targetLinkFlags; - flagsDebugRel += " "; - } - } // if unicode is not found, then add -D_MBCS @@ -1619,7 +1668,7 @@ void cmLocalVisualStudio6Generator // There are not separate CXX and C template files, so we use the same // variable names. The previous code sets up flags* variables to contain // the correct C or CXX flags - cmSystemTools::ReplaceString(line, "CMAKE_CXX_FLAGS_MINSIZEREL", + cmSystemTools::ReplaceString(line, "CMAKE_CXX_FLAGS_MINSIZEREL", flagsMinSize.c_str()); cmSystemTools::ReplaceString(line, "CMAKE_CXX_FLAGS_DEBUG", flagsDebug.c_str()); @@ -1629,7 +1678,7 @@ void cmLocalVisualStudio6Generator flagsRelease.c_str()); cmSystemTools::ReplaceString(line, "CMAKE_CXX_FLAGS", flags.c_str()); - cmSystemTools::ReplaceString(line, "COMPILE_DEFINITIONS_MINSIZE", + cmSystemTools::ReplaceString(line, "COMPILE_DEFINITIONS_MINSIZEREL", minsizeDefines.c_str()); cmSystemTools::ReplaceString(line, "COMPILE_DEFINITIONS_DEBUG", debugDefines.c_str()); diff --git a/Source/cmLocalVisualStudio7Generator.cxx b/Source/cmLocalVisualStudio7Generator.cxx index c9b9722..34756d8 100644 --- a/Source/cmLocalVisualStudio7Generator.cxx +++ b/Source/cmLocalVisualStudio7Generator.cxx @@ -234,9 +234,11 @@ void cmLocalVisualStudio7Generator //---------------------------------------------------------------------------- cmSourceFile* cmLocalVisualStudio7Generator::CreateVCProjBuildRule() { - std::string stampName = cmake::GetCMakeFilesDirectoryPostSlash(); + std::string stampName = this->Makefile->GetCurrentOutputDirectory(); + stampName += "/"; + stampName += cmake::GetCMakeFilesDirectoryPostSlash(); stampName += "generate.stamp"; - const char* dsprule = + const char* dsprule = this->Makefile->GetRequiredDefinition("CMAKE_COMMAND"); cmCustomCommandLine commandLine; commandLine.push_back(dsprule); @@ -261,16 +263,20 @@ cmSourceFile* cmLocalVisualStudio7Generator::CreateVCProjBuildRule() START_OUTPUT, UNCHANGED, true); commandLine.push_back(args); commandLine.push_back("--check-stamp-file"); - commandLine.push_back(stampName.c_str()); + std::string stampFilename = this->Convert(stampName.c_str(), FULL, + SHELL); + commandLine.push_back(stampFilename.c_str()); std::vector<std::string> const& listFiles = this->Makefile->GetListFiles(); cmCustomCommandLines commandLines; commandLines.push_back(commandLine); const char* no_working_directory = 0; - this->Makefile->AddCustomCommandToOutput(stampName.c_str(), listFiles, - makefileIn.c_str(), commandLines, - comment.c_str(), + std::string fullpathStampName = this->Convert(stampName.c_str(), FULL, + UNCHANGED); + this->Makefile->AddCustomCommandToOutput(fullpathStampName.c_str(), + listFiles, makefileIn.c_str(), + commandLines, comment.c_str(), no_working_directory, true); if(cmSourceFile* file = this->Makefile->GetSource(makefileIn.c_str())) { @@ -421,7 +427,7 @@ cmVS7FlagTable cmLocalVisualStudio7GeneratorFlagTable[] = // The YX and Yu options are in a per-global-generator table because // their values differ based on the VS IDE version. {"ForcedIncludeFiles", "FI", "Forced include files", "", - cmVS7FlagTable::UserValueRequired}, + cmVS7FlagTable::UserValueRequired | cmVS7FlagTable::SemicolonAppendable}, // boolean flags {"BufferSecurityCheck", "GS", "Buffer security check", "TRUE", 0}, @@ -460,6 +466,8 @@ cmVS7FlagTable cmLocalVisualStudio7GeneratorLinkFlagTable[] = {"GenerateManifest", "MANIFEST", "enable manifest generation", "TRUE", 0}, {"LinkIncremental", "INCREMENTAL:NO", "link incremental", "1", 0}, {"LinkIncremental", "INCREMENTAL:YES", "link incremental", "2", 0}, + {"EntryPointSymbol", "ENTRY:", "sets the starting address", "", + cmVS7FlagTable::UserValue}, {"IgnoreDefaultLibraryNames", "NODEFAULTLIB:", "default libs to ignore", "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable}, {"IgnoreAllDefaultLibraries", "NODEFAULTLIB", "ignore all default libs", @@ -474,6 +482,21 @@ cmVS7FlagTable cmLocalVisualStudio7GeneratorLinkFlagTable[] = {"OptimizeReferences", "OPT:REF", "Eliminate unreferenced data", "2", 0}, {"TargetMachine", "MACHINE:I386", "Machine x86", "1", 0}, {"TargetMachine", "MACHINE:X86", "Machine x86", "1", 0}, + {"TargetMachine", "MACHINE:AM33", "Machine AM33", "2", 0}, + {"TargetMachine", "MACHINE:ARM", "Machine ARM", "3", 0}, + {"TargetMachine", "MACHINE:EBC", "Machine EBC", "4", 0}, + {"TargetMachine", "MACHINE:IA64", "Machine IA64", "5", 0}, + {"TargetMachine", "MACHINE:M32R", "Machine M32R", "6", 0}, + {"TargetMachine", "MACHINE:MIPS", "Machine MIPS", "7", 0}, + {"TargetMachine", "MACHINE:MIPS16", "Machine MIPS16", "8", 0}, + {"TargetMachine", "MACHINE:MIPSFPU)", "Machine MIPSFPU", "9", 0}, + {"TargetMachine", "MACHINE:MIPSFPU16", "Machine MIPSFPU16", "10", 0}, + {"TargetMachine", "MACHINE:MIPSR41XX", "Machine MIPSR41XX", "11", 0}, + {"TargetMachine", "MACHINE:SH3", "Machine SH3", "12", 0}, + {"TargetMachine", "MACHINE:SH3DSP", "Machine SH3DSP", "13", 0}, + {"TargetMachine", "MACHINE:SH4", "Machine SH4", "14", 0}, + {"TargetMachine", "MACHINE:SH5", "Machine SH5", "15", 0}, + {"TargetMachine", "MACHINE:THUMB", "Machine THUMB", "16", 0}, {"TargetMachine", "MACHINE:X64", "Machine x64", "17", 0}, {"ModuleDefinitionFile", "DEF:", "add an export def file", "", cmVS7FlagTable::UserValue}, @@ -523,12 +546,7 @@ public: { this->Stream << this->LG->EscapeForXML("\n"); } - std::string script = - this->LG->ConstructScript(cc.GetCommandLines(), - cc.GetWorkingDirectory(), - this->Config, - cc.GetEscapeOldStyle(), - cc.GetEscapeAllowMakeVars()); + std::string script = this->LG->ConstructScript(cc, this->Config); this->Stream << this->LG->EscapeForXML(script.c_str()); } private: @@ -646,6 +664,7 @@ void cmLocalVisualStudio7Generator::WriteConfiguration(std::ostream& fout, targetOptions.FixExceptionHandlingDefault(); targetOptions.Parse(flags.c_str()); targetOptions.Parse(defineFlags.c_str()); + targetOptions.ParseFinish(); targetOptions.AddDefines (this->Makefile->GetProperty("COMPILE_DEFINITIONS")); targetOptions.AddDefines(target.GetProperty("COMPILE_DEFINITIONS")); @@ -744,7 +763,9 @@ void cmLocalVisualStudio7Generator::WriteConfiguration(std::ostream& fout, // We need to specify a program database file name even for // non-debug configurations because VS still creates .idb files. fout << "\t\t\t\tProgramDataBaseFileName=\"" - << target.GetDirectory(configName) << "/" + << this->ConvertToXMLOutputPathSingle( + target.GetDirectory(configName).c_str()) + << "/" << target.GetPDBName(configName) << "\"\n"; } fout << "/>\n"; // end of <Tool Name=VCCLCompilerTool @@ -776,7 +797,6 @@ void cmLocalVisualStudio7Generator::WriteConfiguration(std::ostream& fout, tool = "VFMIDLTool"; } fout << "\t\t\t<Tool\n\t\t\t\tName=\"" << tool << "\"\n"; - targetOptions.OutputPreprocessorDefinitions(fout, "\t\t\t\t", "\n"); fout << "\t\t\t\tMkTypLibCompatible=\"FALSE\"\n"; if( this->PlatformName == "x64" ) { @@ -911,7 +931,20 @@ void cmLocalVisualStudio7Generator::OutputBuildTool(std::ostream& fout, } fout << "\t\t\t<Tool\n" << "\t\t\t\tName=\"" << tool << "\"\n"; - if(const char* libflags = target.GetProperty("STATIC_LIBRARY_FLAGS")) + + std::string libflags; + if(const char* flags = target.GetProperty("STATIC_LIBRARY_FLAGS")) + { + libflags += flags; + } + std::string libFlagsConfig = "STATIC_LIBRARY_FLAGS_"; + libFlagsConfig += configTypeUpper; + if(const char* flagsConfig = target.GetProperty(libFlagsConfig.c_str())) + { + libflags += " "; + libflags += flagsConfig; + } + if(!libflags.empty()) { fout << "\t\t\t\tAdditionalOptions=\"" << libflags << "\"\n"; } @@ -976,7 +1009,7 @@ void cmLocalVisualStudio7Generator::OutputBuildTool(std::ostream& fout, temp = target.GetDirectory(configName); temp += "/"; temp += targetNamePDB; - fout << "\t\t\t\tProgramDataBaseFile=\"" << + fout << "\t\t\t\tProgramDatabaseFile=\"" << this->ConvertToXMLOutputPathSingle(temp.c_str()) << "\"\n"; if(isDebug) { @@ -994,7 +1027,12 @@ void cmLocalVisualStudio7Generator::OutputBuildTool(std::ostream& fout, temp += "/"; temp += targetNameImport; fout << "\t\t\t\tImportLibrary=\"" - << this->ConvertToXMLOutputPathSingle(temp.c_str()) << "\"/>\n"; + << this->ConvertToXMLOutputPathSingle(temp.c_str()) << "\""; + if(this->FortranProject) + { + fout << "\n\t\t\t\tLinkDLL=\"true\""; + } + fout << "/>\n"; } break; case cmTarget::EXECUTABLE: @@ -1049,8 +1087,10 @@ void cmLocalVisualStudio7Generator::OutputBuildTool(std::ostream& fout, fout << "\t\t\t\tAdditionalLibraryDirectories=\""; this->OutputLibraryDirectories(fout, cli.GetDirectories()); fout << "\"\n"; - fout << "\t\t\t\tProgramDataBaseFile=\"" - << target.GetDirectory(configName) << "/" << targetNamePDB + std::string path = this->ConvertToXMLOutputPathSingle( + target.GetDirectory(configName).c_str()); + fout << "\t\t\t\tProgramDatabaseFile=\"" + << path << "/" << targetNamePDB << "\"\n"; if(isDebug) { @@ -1058,11 +1098,13 @@ void cmLocalVisualStudio7Generator::OutputBuildTool(std::ostream& fout, } if ( target.GetPropertyAsBool("WIN32_EXECUTABLE") ) { - fout << "\t\t\t\tSubSystem=\"2\"\n"; + fout << "\t\t\t\tSubSystem=\"" + << (this->FortranProject? "subSystemWindows" : "2") << "\"\n"; } else { - fout << "\t\t\t\tSubSystem=\"1\"\n"; + fout << "\t\t\t\tSubSystem=\"" + << (this->FortranProject? "subSystemConsole" : "1") << "\"\n"; } std::string stackVar = "CMAKE_"; stackVar += linkLanguage; @@ -1548,12 +1590,7 @@ WriteCustomRule(std::ostream& fout, << this->EscapeForXML(fc.CompileFlags.c_str()) << "\"/>\n"; } - std::string script = - this->ConstructScript(command.GetCommandLines(), - command.GetWorkingDirectory(), - i->c_str(), - command.GetEscapeOldStyle(), - command.GetEscapeAllowMakeVars()); + std::string script = this->ConstructScript(command, i->c_str()); fout << "\t\t\t\t\t<Tool\n" << "\t\t\t\t\tName=\"" << customTool << "\"\n" << "\t\t\t\t\tDescription=\"" @@ -1581,9 +1618,12 @@ WriteCustomRule(std::ostream& fout, ++d) { // Get the real name of the dependency in case it is a CMake target. - std::string dep = this->GetRealDependency(d->c_str(), i->c_str()); - fout << this->ConvertToXMLOutputPath(dep.c_str()) - << ";"; + std::string dep; + if(this->GetRealDependency(d->c_str(), i->c_str(), dep)) + { + fout << this->ConvertToXMLOutputPath(dep.c_str()) + << ";"; + } } } fout << "\"\n"; @@ -1666,6 +1706,22 @@ void cmLocalVisualStudio7Generator event.Finish(); } +void cmLocalVisualStudio7Generator::WriteProjectSCC(std::ostream& fout, + cmTarget& target) +{ + // if we have all the required Source code control tags + // then add that to the project + const char* vsProjectname = target.GetProperty("VS_SCC_PROJECTNAME"); + const char* vsLocalpath = target.GetProperty("VS_SCC_LOCALPATH"); + const char* vsProvider = target.GetProperty("VS_SCC_PROVIDER"); + if(vsProvider && vsLocalpath && vsProjectname) + { + fout << "\tSccProjectName=\"" << vsProjectname << "\"\n" + << "\tSccLocalPath=\"" << vsLocalpath << "\"\n" + << "\tSccProvider=\"" << vsProvider << "\"\n"; + } +} + void cmLocalVisualStudio7Generator ::WriteProjectStartFortran(std::ostream& fout, @@ -1733,6 +1789,7 @@ cmLocalVisualStudio7Generator { fout << "\tProjectType=\"" << projectType << "\"\n"; } + this->WriteProjectSCC(fout, target); fout<< "\tKeyword=\"" << keyword << "\">\n" << "\tProjectGUID=\"{" << gg->GetGUID(libName) << "}\">\n" << "\t<Platforms>\n" @@ -1773,9 +1830,6 @@ cmLocalVisualStudio7Generator::WriteProjectStart(std::ostream& fout, { keyword = "Win32Proj"; } - const char* vsProjectname = target.GetProperty("VS_SCC_PROJECTNAME"); - const char* vsLocalpath = target.GetProperty("VS_SCC_LOCALPATH"); - const char* vsProvider = target.GetProperty("VS_SCC_PROVIDER"); cmGlobalVisualStudio7Generator* gg = static_cast<cmGlobalVisualStudio7Generator *>(this->GlobalGenerator); fout << "\tName=\"" << projLabel << "\"\n"; @@ -1783,14 +1837,7 @@ cmLocalVisualStudio7Generator::WriteProjectStart(std::ostream& fout, { fout << "\tProjectGUID=\"{" << gg->GetGUID(libName) << "}\"\n"; } - // if we have all the required Source code control tags - // then add that to the project - if(vsProvider && vsLocalpath && vsProjectname) - { - fout << "\tSccProjectName=\"" << vsProjectname << "\"\n" - << "\tSccLocalPath=\"" << vsLocalpath << "\"\n" - << "\tSccProvider=\"" << vsProvider << "\"\n"; - } + this->WriteProjectSCC(fout, target); fout << "\tKeyword=\"" << keyword << "\">\n" << "\t<Platforms>\n" << "\t\t<Platform\n\t\t\tName=\"" << this->PlatformName << "\"/>\n" diff --git a/Source/cmLocalVisualStudio7Generator.h b/Source/cmLocalVisualStudio7Generator.h index 19f7b97..160e2d4 100644 --- a/Source/cmLocalVisualStudio7Generator.h +++ b/Source/cmLocalVisualStudio7Generator.h @@ -102,6 +102,7 @@ private: cmTarget& t, bool debug); void OutputLibraryDirectories(std::ostream& fout, std::vector<std::string> const& dirs); + void WriteProjectSCC(std::ostream& fout, cmTarget& target); void WriteProjectStart(std::ostream& fout, const char *libName, cmTarget &tgt, std::vector<cmSourceGroup> &sgs); void WriteProjectStartFortran(std::ostream& fout, const char *libName, diff --git a/Source/cmLocalVisualStudioGenerator.cxx b/Source/cmLocalVisualStudioGenerator.cxx index 83d8dec..9164beb 100644 --- a/Source/cmLocalVisualStudioGenerator.cxx +++ b/Source/cmLocalVisualStudioGenerator.cxx @@ -14,6 +14,7 @@ #include "cmMakefile.h" #include "cmSourceFile.h" #include "cmSystemTools.h" +#include "cmCustomCommandGenerator.h" #include "windows.h" //---------------------------------------------------------------------------- @@ -52,7 +53,7 @@ cmLocalVisualStudioGenerator::MaybeCreateImplibDir(cmTarget& target, std::vector<std::string> no_depends; cmCustomCommandLines commands; commands.push_back(command); - pcc.reset(new cmCustomCommand(no_output, no_depends, commands, 0, 0)); + pcc.reset(new cmCustomCommand(0, no_output, no_depends, commands, 0, 0)); pcc->SetEscapeOldStyle(false); pcc->SetEscapeAllowMakeVars(true); return pcc; @@ -149,15 +150,29 @@ void cmLocalVisualStudioGenerator::ComputeObjectNameRequirements } //---------------------------------------------------------------------------- +std::string cmLocalVisualStudioGenerator::CheckForErrorLine() +{ + return "if errorlevel 1 goto :VCReportError"; +} + +//---------------------------------------------------------------------------- +std::string cmLocalVisualStudioGenerator::GetCheckForErrorLine() +{ + return this->CheckForErrorLine(); +} + +//---------------------------------------------------------------------------- std::string cmLocalVisualStudioGenerator -::ConstructScript(const cmCustomCommandLines& commandLines, - const char* workingDirectory, +::ConstructScript(cmCustomCommand const& cc, const char* configName, - bool escapeOldStyle, - bool escapeAllowMakeVars, const char* newline_text) { + const cmCustomCommandLines& commandLines = cc.GetCommandLines(); + const char* workingDirectory = cc.GetWorkingDirectory(); + cmCustomCommandGenerator ccg(cc, configName, this->Makefile); + RelativeRoot relativeRoot = workingDirectory? NONE : START_OUTPUT; + // Avoid leading or trailing newlines. const char* newline = ""; @@ -169,7 +184,7 @@ cmLocalVisualStudioGenerator script += newline; newline = newline_text; script += "cd "; - script += this->Convert(workingDirectory, START_OUTPUT, SHELL); + script += this->Convert(workingDirectory, FULL, SHELL); // Change the working drive. if(workingDirectory[0] && workingDirectory[1] == ':') @@ -196,41 +211,25 @@ cmLocalVisualStudioGenerator } } // Write each command on a single line. - for(cmCustomCommandLines::const_iterator cl = commandLines.begin(); - cl != commandLines.end(); ++cl) + for(unsigned int c = 0; c < ccg.GetNumberOfCommands(); ++c) { // Start a new line. script += newline; newline = newline_text; - // Start with the command name. - const cmCustomCommandLine& commandLine = *cl; - std::string commandName = this->GetRealLocation(commandLine[0].c_str(), - configName); - if(!workingDirectory) - { - script += this->Convert(commandName.c_str(),START_OUTPUT,SHELL); - } - else - { - script += this->Convert(commandName.c_str(),NONE,SHELL); - } - - // Add the arguments. - for(unsigned int j=1;j < commandLine.size(); ++j) - { - script += " "; - if(escapeOldStyle) - { - script += this->EscapeForShellOldStyle(commandLine[j].c_str()); - } - else - { - script += this->EscapeForShell(commandLine[j].c_str(), - escapeAllowMakeVars); - } - } + // Add this command line. + std::string cmd = ccg.GetCommand(c); + script += this->Convert(cmd.c_str(), relativeRoot, SHELL); + ccg.AppendArguments(c, script); + + // After each custom command, check for an error result. + // If there was an error, jump to the VCReportError label, + // skipping the run of any subsequent commands in this + // sequence. + // + script += newline_text; + script += this->GetCheckForErrorLine(); } + return script; } - diff --git a/Source/cmLocalVisualStudioGenerator.h b/Source/cmLocalVisualStudioGenerator.h index 6034b22..1954ac5 100644 --- a/Source/cmLocalVisualStudioGenerator.h +++ b/Source/cmLocalVisualStudioGenerator.h @@ -18,6 +18,7 @@ class cmSourceFile; class cmSourceGroup; +class cmCustomCommand; /** \class cmLocalVisualStudioGenerator * \brief Base class for Visual Studio generators. @@ -30,15 +31,19 @@ class cmLocalVisualStudioGenerator : public cmLocalGenerator public: cmLocalVisualStudioGenerator(); virtual ~cmLocalVisualStudioGenerator(); + /** Construct a script from the given list of command lines. */ - std::string ConstructScript(const cmCustomCommandLines& commandLines, - const char* workingDirectory, + std::string ConstructScript(cmCustomCommand const& cc, const char* configName, - bool escapeOldStyle, - bool escapeAllowMakeVars, const char* newline = "\n"); + /** Line of batch file text that skips to the end after + * a failed step in a sequence of custom commands. + */ + std::string GetCheckForErrorLine(); + protected: + virtual std::string CheckForErrorLine(); /** Construct a custom command to make exe import lib dir. */ cmsys::auto_ptr<cmCustomCommand> diff --git a/Source/cmMakefile.cxx b/Source/cmMakefile.cxx index d09188a..e1cea22 100644 --- a/Source/cmMakefile.cxx +++ b/Source/cmMakefile.cxx @@ -22,6 +22,7 @@ #include "cmFunctionBlocker.h" #include "cmListFileCache.h" #include "cmCommandArgumentParserHelper.h" +#include "cmDocumentCompileDefinitions.h" #include "cmTest.h" #ifdef CMAKE_BUILD_WITH_CMAKE # include "cmVariableWatch.h" @@ -124,7 +125,6 @@ cmMakefile::cmMakefile(const cmMakefile& mf): Internal(new Internals) this->LocalGenerator = mf.LocalGenerator; this->FunctionBlockers = mf.FunctionBlockers; - this->DataMap = mf.DataMap; this->MacrosMap = mf.MacrosMap; this->SubDirectoryOrder = mf.SubDirectoryOrder; this->Properties = mf.Properties; @@ -200,14 +200,6 @@ cmMakefile::~cmMakefile() { delete this->UsedCommands[i]; } - for(DataMapType::const_iterator d = this->DataMap.begin(); - d != this->DataMap.end(); ++d) - { - if(d->second) - { - delete d->second; - } - } std::vector<cmFunctionBlocker*>::iterator pos; for (pos = this->FunctionBlockers.begin(); pos != this->FunctionBlockers.end(); ++pos) @@ -362,7 +354,7 @@ bool cmMakefile::ExecuteCommand(const cmListFileFunction& lff, // No error. return result; } - + std::string name = lff.Name; // Place this call on the call stack. @@ -386,7 +378,7 @@ bool cmMakefile::ExecuteCommand(const cmListFileFunction& lff, cmOStringStream msg; msg << lff.FilePath << "(" << lff.Line << "): "; msg << lff.Name << "("; - for(std::vector<cmListFileArgument>::const_iterator i = + for(std::vector<cmListFileArgument>::const_iterator i = lff.Arguments.begin(); i != lff.Arguments.end(); ++i) { msg << i->Value; @@ -619,6 +611,8 @@ bool cmMakefile::ReadListFile(const char* filename_in, } this->AddDefinition("CMAKE_CURRENT_LIST_FILE", filenametoread); + this->AddDefinition("CMAKE_CURRENT_LIST_DIR", + cmSystemTools::GetFilenamePath(filenametoread).c_str()); // try to see if the list file is the top most // list file for a project, and if it is, then it @@ -652,6 +646,8 @@ bool cmMakefile::ReadListFile(const char* filename_in, } this->AddDefinition("CMAKE_PARENT_LIST_FILE", currentParentFile.c_str()); this->AddDefinition("CMAKE_CURRENT_LIST_FILE", currentFile.c_str()); + this->AddDefinition("CMAKE_CURRENT_LIST_DIR", + cmSystemTools::GetFilenamePath(currentFile).c_str()); return false; } // add this list file to the list of dependencies @@ -692,6 +688,8 @@ bool cmMakefile::ReadListFile(const char* filename_in, this->AddDefinition("CMAKE_PARENT_LIST_FILE", currentParentFile.c_str()); this->AddDefinition("CMAKE_CURRENT_LIST_FILE", currentFile.c_str()); + this->AddDefinition("CMAKE_CURRENT_LIST_DIR", + cmSystemTools::GetFilenamePath(currentFile).c_str()); // pop the listfile off the stack this->ListFileStack.pop_back(); @@ -830,7 +828,8 @@ cmMakefile::AddCustomCommandToTarget(const char* target, { // Add the command to the appropriate build step for the target. std::vector<std::string> no_output; - cmCustomCommand cc(no_output, depends, commandLines, comment, workingDir); + cmCustomCommand cc(this, no_output, depends, + commandLines, comment, workingDir); cc.SetEscapeOldStyle(escapeOldStyle); cc.SetEscapeAllowMakeVars(true); switch(type) @@ -903,6 +902,14 @@ cmMakefile::AddCustomCommandToOutput(const std::vector<std::string>& outputs, // Construct a rule file associated with the first output produced. std::string outName = outputs[0]; outName += ".rule"; + const char* dir = + this->LocalGenerator->GetGlobalGenerator()-> + GetCMakeCFGInitDirectory(); + if(dir && dir[0] == '$') + { + cmSystemTools::ReplaceString(outName, dir, + cmake::GetCMakeFilesDirectory()); + } // Check if the rule file already exists. file = this->GetSource(outName.c_str()); if(file && file->GetCustomCommand() && !replace) @@ -942,7 +949,7 @@ cmMakefile::AddCustomCommandToOutput(const std::vector<std::string>& outputs, if(file) { cmCustomCommand* cc = - new cmCustomCommand(outputs, depends2, commandLines, + new cmCustomCommand(this, outputs, depends2, commandLines, comment, workingDir); cc->SetEscapeOldStyle(escapeOldStyle); cc->SetEscapeAllowMakeVars(true); @@ -1359,8 +1366,8 @@ void cmMakefile::AddLinkLibraryForTarget(const char *target, cmOStringStream e; e << "Attempt to add link library \"" << lib << "\" to target \"" - << target << "\" which is not built by this project."; - cmSystemTools::Error(e.str().c_str()); + << target << "\" which is not built in this directory."; + this->IssueMessage(cmake::FATAL_ERROR, e.str().c_str()); } } @@ -1445,16 +1452,7 @@ void cmMakefile::InitializeFromParent() this->SetProperty("COMPILE_DEFINITIONS", parent->GetProperty("COMPILE_DEFINITIONS")); std::vector<std::string> configs; - if(const char* configTypes = - this->GetDefinition("CMAKE_CONFIGURATION_TYPES")) - { - cmSystemTools::ExpandListArgument(configTypes, configs); - } - else if(const char* buildType = - this->GetDefinition("CMAKE_BUILD_TYPE")) - { - configs.push_back(buildType); - } + this->GetConfigurations(configs); for(std::vector<std::string>::const_iterator ci = configs.begin(); ci != configs.end(); ++ci) { @@ -1752,8 +1750,8 @@ void cmMakefile::AddLibrary(const char* lname, cmTarget::TargetType type, bool excludeFromAll) { // wrong type ? default to STATIC - if ( (type != cmTarget::STATIC_LIBRARY) - && (type != cmTarget::SHARED_LIBRARY) + if ( (type != cmTarget::STATIC_LIBRARY) + && (type != cmTarget::SHARED_LIBRARY) && (type != cmTarget::MODULE_LIBRARY)) { type = cmTarget::STATIC_LIBRARY; @@ -2335,26 +2333,28 @@ void cmMakefile::AddDefaultDefinitions() { /* Up to CMake 2.4 here only WIN32, UNIX and APPLE were set. With CMake must separate between target and host platform. In most cases - the tests for WIN32, UNIX and APPLE will be for the target system, so an + the tests for WIN32, UNIX and APPLE will be for the target system, so an additional set of variables for the host system is required -> CMAKE_HOST_WIN32, CMAKE_HOST_UNIX, CMAKE_HOST_APPLE. - WIN32, UNIX and APPLE are now set in the platform files in + WIN32, UNIX and APPLE are now set in the platform files in Modules/Platforms/. To keep cmake scripts (-P) and custom language and compiler modules working, these variables are still also set here in this place, but they - will be reset in CMakeSystemSpecificInformation.cmake before the platform + will be reset in CMakeSystemSpecificInformation.cmake before the platform files are executed. */ -#if defined(_WIN32) || defined(__CYGWIN__) +#if defined(_WIN32) this->AddDefinition("WIN32", "1"); this->AddDefinition("CMAKE_HOST_WIN32", "1"); #else this->AddDefinition("UNIX", "1"); this->AddDefinition("CMAKE_HOST_UNIX", "1"); #endif - // Cygwin is more like unix so enable the unix commands #if defined(__CYGWIN__) - this->AddDefinition("UNIX", "1"); - this->AddDefinition("CMAKE_HOST_UNIX", "1"); + if(cmSystemTools::IsOn(cmSystemTools::GetEnv("CMAKE_LEGACY_CYGWIN_WIN32"))) + { + this->AddDefinition("WIN32", "1"); + this->AddDefinition("CMAKE_HOST_WIN32", "1"); + } #endif #if defined(__APPLE__) this->AddDefinition("APPLE", "1"); @@ -2368,16 +2368,39 @@ void cmMakefile::AddDefaultDefinitions() this->AddDefinition("CMAKE_MAJOR_VERSION", temp); sprintf(temp, "%d", cmVersion::GetPatchVersion()); this->AddDefinition("CMAKE_PATCH_VERSION", temp); - sprintf(temp, "%u.%u.%u", - cmVersion::GetMajorVersion(), - cmVersion::GetMinorVersion(), - cmVersion::GetPatchVersion()); - this->AddDefinition("CMAKE_VERSION", temp); + sprintf(temp, "%d", cmVersion::GetTweakVersion()); + this->AddDefinition("CMAKE_TWEAK_VERSION", temp); + this->AddDefinition("CMAKE_VERSION", cmVersion::GetCMakeVersion()); this->AddDefinition("CMAKE_FILES_DIRECTORY", cmake::GetCMakeFilesDirectory()); } +//---------------------------------------------------------------------------- +const char* +cmMakefile::GetConfigurations(std::vector<std::string>& configs, + bool single) const +{ + if(this->LocalGenerator->GetGlobalGenerator()->IsMultiConfig()) + { + if(const char* configTypes = + this->GetDefinition("CMAKE_CONFIGURATION_TYPES")) + { + cmSystemTools::ExpandListArgument(configTypes, configs); + } + return 0; + } + else + { + const char* buildType = this->GetDefinition("CMAKE_BUILD_TYPE"); + if(single && buildType && *buildType) + { + configs.push_back(buildType); + } + return buildType; + } +} + #if defined(CMAKE_BUILD_WITH_CMAKE) /** * Find a source group whose regular expression matches the filename @@ -2593,54 +2616,6 @@ void cmMakefile::SetHomeOutputDirectory(const char* lib) } } - -/** - * Register the given cmData instance with its own name. - */ -void cmMakefile::RegisterData(cmData* data) -{ - std::string name = data->GetName(); - DataMapType::const_iterator d = this->DataMap.find(name); - if((d != this->DataMap.end()) && (d->second != 0) && (d->second != data)) - { - delete d->second; - } - this->DataMap[name] = data; -} - - -/** - * Register the given cmData instance with the given name. This can be used - * to register a NULL pointer. - */ -void cmMakefile::RegisterData(const char* name, cmData* data) -{ - DataMapType::const_iterator d = this->DataMap.find(name); - if((d != this->DataMap.end()) && (d->second != 0) && (d->second != data)) - { - delete d->second; - } - this->DataMap[name] = data; -} - - -/** - * Lookup a cmData instance previously registered with the given name. If - * the instance cannot be found, return NULL. - */ -cmData* cmMakefile::LookupData(const char* name) const -{ - DataMapType::const_iterator d = this->DataMap.find(name); - if(d != this->DataMap.end()) - { - return d->second; - } - else - { - return 0; - } -} - //---------------------------------------------------------------------------- cmSourceFile* cmMakefile::GetSource(const char* sourceName) { @@ -2678,13 +2653,13 @@ cmSourceFile* cmMakefile::GetOrCreateSource(const char* sourceName, } } -void cmMakefile::EnableLanguage(std::vector<std::string> const & lang, +void cmMakefile::EnableLanguage(std::vector<std::string> const & lang, bool optional) { this->AddDefinition("CMAKE_CFG_INTDIR", this->LocalGenerator->GetGlobalGenerator() ->GetCMakeCFGInitDirectory()); - this->LocalGenerator->GetGlobalGenerator()->EnableLanguage(lang, this, + this->LocalGenerator->GetGlobalGenerator()->EnableLanguage(lang, this, optional); } @@ -2743,6 +2718,18 @@ int cmMakefile::TryCompile(const char *srcdir, const char *bindir, cm.SetStartOutputDirectory(bindir); cm.SetCMakeCommand(cmakeCommand.c_str()); cm.LoadCache(); + if(!gg->IsMultiConfig()) + { + if(const char* config = + this->GetDefinition("CMAKE_TRY_COMPILE_CONFIGURATION")) + { + // Tell the single-configuration generator which one to use. + // Add this before the user-provided CMake arguments in case + // one of the arguments is -DCMAKE_BUILD_TYPE=... + cm.AddCacheEntry("CMAKE_BUILD_TYPE", config, + "Build configuration", cmCacheManager::STRING); + } + } // if cmake args were provided then pass them in if (cmakeArgs) { @@ -2760,7 +2747,7 @@ int cmMakefile::TryCompile(const char *srcdir, const char *bindir, { cm.AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", "FALSE", "", cmCacheManager::INTERNAL); - } + } if (cm.Configure() != 0) { cmSystemTools::Error( @@ -2851,35 +2838,100 @@ void cmMakefile::DisplayStatus(const char* message, float s) std::string cmMakefile::GetModulesFile(const char* filename) { - std::vector<std::string> modulePath; - const char* def = this->GetDefinition("CMAKE_MODULE_PATH"); - if(def) + std::string result; + + // We search the module always in CMAKE_ROOT and in CMAKE_MODULE_PATH, + // and then decide based on the policy setting which one to return. + // See CMP0017 for more details. + // The specific problem was that KDE 4.5.0 installs a + // FindPackageHandleStandardArgs.cmake which doesn't have the new features + // of FPHSA.cmake introduced in CMake 2.8.3 yet, and by setting + // CMAKE_MODULE_PATH also e.g. FindZLIB.cmake from cmake included + // FPHSA.cmake from kdelibs and not from CMake, and tried to use the + // new features, which were not there in the version from kdelibs, and so + // failed (" + std::string moduleInCMakeRoot; + std::string moduleInCMakeModulePath; + + // Always search in CMAKE_MODULE_PATH: + const char* cmakeModulePath = this->GetDefinition("CMAKE_MODULE_PATH"); + if(cmakeModulePath) + { + std::vector<std::string> modulePath; + cmSystemTools::ExpandListArgument(cmakeModulePath, modulePath); + + //Look through the possible module directories. + for(std::vector<std::string>::iterator i = modulePath.begin(); + i != modulePath.end(); ++i) + { + std::string itempl = *i; + cmSystemTools::ConvertToUnixSlashes(itempl); + itempl += "/"; + itempl += filename; + if(cmSystemTools::FileExists(itempl.c_str())) + { + moduleInCMakeModulePath = itempl; + break; + } + } + } + + // Always search in the standard modules location. + const char* cmakeRoot = this->GetDefinition("CMAKE_ROOT"); + if(cmakeRoot) { - cmSystemTools::ExpandListArgument(def, modulePath); + moduleInCMakeRoot = cmakeRoot; + moduleInCMakeRoot += "/Modules/"; + moduleInCMakeRoot += filename; + cmSystemTools::ConvertToUnixSlashes(moduleInCMakeRoot); + if(!cmSystemTools::FileExists(moduleInCMakeRoot.c_str())) + { + moduleInCMakeRoot = ""; + } } - // Also search in the standard modules location. - def = this->GetDefinition("CMAKE_ROOT"); - if(def) + // Normally, prefer the files found in CMAKE_MODULE_PATH. Only when the file + // from which we are being called is located itself in CMAKE_ROOT, then + // prefer results from CMAKE_ROOT depending on the policy setting. + result = moduleInCMakeModulePath; + if (result.size() == 0) { - std::string rootModules = def; - rootModules += "/Modules"; - modulePath.push_back(rootModules); + result = moduleInCMakeRoot; } - //std::string Look through the possible module directories. - for(std::vector<std::string>::iterator i = modulePath.begin(); - i != modulePath.end(); ++i) + + if ((moduleInCMakeModulePath.size()>0) && (moduleInCMakeRoot.size()>0)) { - std::string itempl = *i; - cmSystemTools::ConvertToUnixSlashes(itempl); - itempl += "/"; - itempl += filename; - if(cmSystemTools::FileExists(itempl.c_str())) + const char* currentFile = this->GetDefinition("CMAKE_CURRENT_LIST_FILE"); + if (currentFile && (strstr(currentFile, cmakeRoot) == currentFile)) { - return itempl; + switch (this->GetPolicyStatus(cmPolicies::CMP0017)) + { + case cmPolicies::WARN: + { + cmOStringStream e; + e << "File " << currentFile << " includes " + << moduleInCMakeModulePath + << " (found via CMAKE_MODULE_PATH) which shadows " + << moduleInCMakeRoot << ". This may cause errors later on .\n" + << this->GetPolicies()->GetPolicyWarning(cmPolicies::CMP0017); + + this->IssueMessage(cmake::AUTHOR_WARNING, e.str()); + // break; // fall through to OLD behaviour + } + case cmPolicies::OLD: + result = moduleInCMakeModulePath; + break; + case cmPolicies::REQUIRED_IF_USED: + case cmPolicies::REQUIRED_ALWAYS: + case cmPolicies::NEW: + default: + result = moduleInCMakeRoot; + break; + } } } - return ""; + + return result; } void cmMakefile::ConfigureString(const std::string& input, @@ -3048,7 +3100,7 @@ void cmMakefile::SetProperty(const char* prop, const char* value) { return; } - + // handle special props std::string propname = prop; if ( propname == "INCLUDE_DIRECTORIES" ) @@ -3072,7 +3124,7 @@ void cmMakefile::SetProperty(const char* prop, const char* value) this->SetLinkDirectories(varArgsExpanded); return; } - + if ( propname == "INCLUDE_REGULAR_EXPRESSION" ) { this->SetIncludeRegularExpression(value); @@ -3082,7 +3134,7 @@ void cmMakefile::SetProperty(const char* prop, const char* value) if ( propname == "ADDITIONAL_MAKE_CLEAN_FILES" ) { // This property is not inherrited - if ( strcmp(this->GetCurrentDirectory(), + if ( strcmp(this->GetCurrentDirectory(), this->GetStartDirectory()) != 0 ) { return; @@ -3203,14 +3255,14 @@ const char *cmMakefile::GetProperty(const char* prop, return output.c_str(); } else if (!strcmp("DEFINITIONS",prop)) - { + { output += this->DefineFlagsOrig; return output.c_str(); } else if (!strcmp("INCLUDE_DIRECTORIES",prop) ) { cmOStringStream str; - for (std::vector<std::string>::const_iterator + for (std::vector<std::string>::const_iterator it = this->GetIncludeDirectories().begin(); it != this->GetIncludeDirectories().end(); ++ it ) @@ -3227,7 +3279,7 @@ const char *cmMakefile::GetProperty(const char* prop, else if (!strcmp("LINK_DIRECTORIES",prop)) { cmOStringStream str; - for (std::vector<std::string>::const_iterator + for (std::vector<std::string>::const_iterator it = this->GetLinkDirectories().begin(); it != this->GetLinkDirectories().end(); ++ it ) @@ -3453,14 +3505,7 @@ void cmMakefile::DefineProperties(cmake *cm) "are not supported by the native build tool. " "The VS6 IDE does not support definition values with spaces " "(but NMake does).\n" - "Dislaimer: Most native build tools have poor support for escaping " - "certain values. CMake has work-arounds for many cases but some " - "values may just not be possible to pass correctly. If a value " - "does not seem to be escaped correctly, do not attempt to " - "work-around the problem by adding escape sequences to the value. " - "Your work-around may break in a future version of CMake that " - "has improved escape support. Instead consider defining the macro " - "in a (configured) header file. Then report the limitation."); + CM_DOCUMENT_COMPILE_DEFINITIONS_DISCLAIMER); cm->DefineProperty ("COMPILE_DEFINITIONS_<CONFIG>", cmProperty::DIRECTORY, @@ -3619,6 +3664,12 @@ cmTarget* cmMakefile::FindTargetToUse(const char* name) return imported->second; } + // Look for a target built in this directory. + if(cmTarget* t = this->FindTarget(name)) + { + return t; + } + // Look for a target built in this project. return this->LocalGenerator->GetGlobalGenerator()->FindTarget(0, name); } @@ -3641,7 +3692,7 @@ bool cmMakefile::EnforceUniqueName(std::string const& name, std::string& msg, msg = e.str(); return false; } - else + else { // target names must be globally unique switch (this->GetPolicyStatus(cmPolicies::CMP0002)) @@ -3660,7 +3711,7 @@ bool cmMakefile::EnforceUniqueName(std::string const& name, std::string& msg, case cmPolicies::NEW: break; } - + // The conflict is with a non-imported target. // Allow this if the user has requested support. cmake* cm = @@ -3809,7 +3860,7 @@ cmMakefile::GetPolicyStatusInternal(cmPolicies::PolicyID id) return this->GetPolicies()->GetPolicyStatus(id); } -bool cmMakefile::SetPolicy(const char *id, +bool cmMakefile::SetPolicy(const char *id, cmPolicies::PolicyStatus status) { cmPolicies::PolicyID pid; @@ -3939,7 +3990,7 @@ bool cmMakefile::SetPolicyVersion(const char *version) } cmPolicies *cmMakefile::GetPolicies() -{ +{ if (!this->GetCMakeInstance()) { return 0; diff --git a/Source/cmMakefile.h b/Source/cmMakefile.h index 63f81b8..8b8a3f8 100644 --- a/Source/cmMakefile.h +++ b/Source/cmMakefile.h @@ -13,7 +13,6 @@ #define cmMakefile_h #include "cmCacheManager.h" -#include "cmData.h" #include "cmExecutionStatus.h" #include "cmListFileCache.h" #include "cmPolicies.h" @@ -310,7 +309,11 @@ public: { return this->ProjectName.c_str(); } - + + /** Get the configurations to be generated. */ + const char* GetConfigurations(std::vector<std::string>& configs, + bool single = true) const; + /** * Set the name of the library. */ @@ -692,10 +695,6 @@ public: std::vector<cmSourceGroup> &groups); #endif - void RegisterData(cmData*); - void RegisterData(const char*, cmData*); - cmData* LookupData(const char*) const; - /** * Execute a single CMake command. Returns true if the command * succeeded or false if it failed. @@ -916,9 +915,6 @@ private: void PushFunctionBlockerBarrier(); void PopFunctionBlockerBarrier(bool reportError = true); - typedef std::map<cmStdString, cmData*> DataMapType; - DataMapType DataMap; - typedef std::map<cmStdString, cmStdString> StringStringMap; StringStringMap MacrosMap; diff --git a/Source/cmMakefileExecutableTargetGenerator.cxx b/Source/cmMakefileExecutableTargetGenerator.cxx index e7c4a7d..4426241 100644 --- a/Source/cmMakefileExecutableTargetGenerator.cxx +++ b/Source/cmMakefileExecutableTargetGenerator.cxx @@ -82,34 +82,9 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink) { std::vector<std::string> commands; - std::string relPath = this->LocalGenerator->GetHomeRelativeOutputPath(); - std::string objTarget; - // Build list of dependencies. std::vector<std::string> depends; - for(std::vector<std::string>::const_iterator obj = this->Objects.begin(); - obj != this->Objects.end(); ++obj) - { - objTarget = relPath; - objTarget += *obj; - depends.push_back(objTarget); - } - - // Add dependencies on targets that must be built first. - this->AppendTargetDepends(depends); - - // Add a dependency on the rule file itself. - this->LocalGenerator->AppendRuleDepend(depends, - this->BuildFileNameFull.c_str()); - - for(std::vector<std::string>::const_iterator obj = - this->ExternalObjects.begin(); - obj != this->ExternalObjects.end(); ++obj) - { - depends.push_back(*obj); - } - - // from here up is the same for exe or lib + this->AppendLinkDepends(depends); // Get the name of the executable to generate. std::string targetName; @@ -229,10 +204,8 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink) // Add language feature flags. this->AddFeatureFlags(flags, linkLanguage); -#ifdef __APPLE__ this->LocalGenerator->AddArchitectureFlags(flags, this->Target, linkLanguage, this->ConfigName); -#endif /* __APPLE__ */ // Add target-specific linker flags. this->LocalGenerator->AppendFlags @@ -347,6 +320,13 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink) vars.CMTarget = this->Target; vars.Language = linkLanguage; vars.Objects = buildObjs.c_str(); + std::string objdir = cmake::GetCMakeFilesDirectoryPostSlash(); + objdir += this->Target->GetName(); + objdir += ".dir"; + objdir = this->Convert(objdir.c_str(), + cmLocalGenerator::START_OUTPUT, + cmLocalGenerator::SHELL); + vars.ObjectDir = objdir.c_str(); vars.Target = targetOutPathReal.c_str(); vars.TargetPDB = targetOutPathPDB.c_str(); diff --git a/Source/cmMakefileLibraryTargetGenerator.cxx b/Source/cmMakefileLibraryTargetGenerator.cxx index f351174..049a338 100644 --- a/Source/cmMakefileLibraryTargetGenerator.cxx +++ b/Source/cmMakefileLibraryTargetGenerator.cxx @@ -122,6 +122,10 @@ void cmMakefileLibraryTargetGenerator::WriteStaticLibraryRules() std::string extraFlags; this->LocalGenerator->AppendFlags (extraFlags,this->Target->GetProperty("STATIC_LIBRARY_FLAGS")); + std::string staticLibraryFlagsConfig = "STATIC_LIBRARY_FLAGS_"; + staticLibraryFlagsConfig += cmSystemTools::UpperCase(this->ConfigName); + this->LocalGenerator->AppendFlags + (extraFlags, this->Target->GetProperty(staticLibraryFlagsConfig.c_str())); this->WriteLibraryRules(linkRuleVar.c_str(), extraFlags.c_str(), false); } @@ -304,33 +308,10 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules // code duplication. std::vector<std::string> commands; - std::string relPath = this->LocalGenerator->GetHomeRelativeOutputPath(); - std::string objTarget; - // Build list of dependencies. std::vector<std::string> depends; - for(std::vector<std::string>::const_iterator obj = this->Objects.begin(); - obj != this->Objects.end(); ++obj) - { - objTarget = relPath; - objTarget += *obj; - depends.push_back(objTarget); - } + this->AppendLinkDepends(depends); - // Add dependencies on targets that must be built first. - this->AppendTargetDepends(depends); - - // Add a dependency on the rule file itself. - this->LocalGenerator->AppendRuleDepend(depends, - this->BuildFileNameFull.c_str()); - - for(std::vector<std::string>::const_iterator obj - = this->ExternalObjects.begin(); - obj != this->ExternalObjects.end(); ++obj) - { - depends.push_back(*obj); - } - // Get the language to use for linking this library. const char* linkLanguage = this->Target->GetLinkerLanguage(this->ConfigName); @@ -682,10 +663,8 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules std::string langFlags; this->AddFeatureFlags(langFlags, linkLanguage); -#ifdef __APPLE__ this->LocalGenerator->AddArchitectureFlags(langFlags, this->Target, linkLanguage, this->ConfigName); -#endif /* __APPLE__ */ // remove any language flags that might not work with the // particular os diff --git a/Source/cmMakefileTargetGenerator.cxx b/Source/cmMakefileTargetGenerator.cxx index dd45950..9dcd8f1 100644 --- a/Source/cmMakefileTargetGenerator.cxx +++ b/Source/cmMakefileTargetGenerator.cxx @@ -189,12 +189,15 @@ void cmMakefileTargetGenerator::WriteTargetBuildRules() //---------------------------------------------------------------------------- void cmMakefileTargetGenerator::WriteCommonCodeRules() { + const char* root = (this->Makefile->IsOn("CMAKE_MAKE_INCLUDE_FROM_ROOT")? + "$(CMAKE_BINARY_DIR)/" : ""); + // Include the dependencies for the target. std::string dependFileNameFull = this->TargetBuildDirectoryFull; dependFileNameFull += "/depend.make"; *this->BuildFileStream << "# Include any dependencies generated for this target.\n" - << this->LocalGenerator->IncludeDirective << " " + << this->LocalGenerator->IncludeDirective << " " << root << this->Convert(dependFileNameFull.c_str(), cmLocalGenerator::HOME_OUTPUT, cmLocalGenerator::MAKEFILE) @@ -205,7 +208,7 @@ void cmMakefileTargetGenerator::WriteCommonCodeRules() // Include the progress variables for the target. *this->BuildFileStream << "# Include the progress variables for this target.\n" - << this->LocalGenerator->IncludeDirective << " " + << this->LocalGenerator->IncludeDirective << " " << root << this->Convert(this->ProgressFileNameFull.c_str(), cmLocalGenerator::HOME_OUTPUT, cmLocalGenerator::MAKEFILE) @@ -238,7 +241,7 @@ void cmMakefileTargetGenerator::WriteCommonCodeRules() // Include the flags for the target. *this->BuildFileStream << "# Include the compile flags for this target's objects.\n" - << this->LocalGenerator->IncludeDirective << " " + << this->LocalGenerator->IncludeDirective << " " << root << this->Convert(this->FlagFileNameFull.c_str(), cmLocalGenerator::HOME_OUTPUT, cmLocalGenerator::MAKEFILE) @@ -294,10 +297,8 @@ void cmMakefileTargetGenerator::WriteTargetLanguageFlags() // Add language feature flags. this->AddFeatureFlags(flags, lang); -#ifdef __APPLE__ this->LocalGenerator->AddArchitectureFlags(flags, this->Target, lang, this->ConfigName); -#endif /* __APPLE__ */ // Fortran-specific flags computed for this target. if(*l == "Fortran") @@ -848,7 +849,7 @@ cmMakefileTargetGenerator p_depends.push_back(relativeObj); this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, 0, temp.c_str(), p_depends, no_commands, - true); + false); } //---------------------------------------------------------------------------- @@ -1329,7 +1330,7 @@ public: this->NextObject = this->LocalGenerator->Convert(obj.c_str(), cmLocalGenerator::START_OUTPUT, - cmLocalGenerator::SHELL); + cmLocalGenerator::RESPONSE); // Roll over to next string if the limit will be exceeded. if(this->LengthLimit != std::string::npos && @@ -1439,11 +1440,15 @@ void cmMakefileTargetGenerator::WriteTargetDriverRule(const char* main_output, //---------------------------------------------------------------------------- std::string cmMakefileTargetGenerator::GetFrameworkFlags() { -#ifndef __APPLE__ - return std::string(); -#else - std::set<cmStdString> emitted; + if(!this->Makefile->IsOn("APPLE")) + { + return std::string(); + } + + std::set<cmStdString> emitted; +#ifdef __APPLE__ /* don't insert this when crosscompiling e.g. to iphone */ emitted.insert("/System/Library/Frameworks"); +#endif std::vector<std::string> includes; this->LocalGenerator->GetIncludeDirectories(includes); std::vector<std::string>::iterator i; @@ -1475,7 +1480,6 @@ std::string cmMakefileTargetGenerator::GetFrameworkFlags() } } return flags; -#endif } //---------------------------------------------------------------------------- @@ -1503,6 +1507,50 @@ void cmMakefileTargetGenerator //---------------------------------------------------------------------------- void cmMakefileTargetGenerator +::AppendLinkDepends(std::vector<std::string>& depends) +{ + // Add dependencies on the compiled object files. + std::string relPath = this->LocalGenerator->GetHomeRelativeOutputPath(); + std::string objTarget; + for(std::vector<std::string>::const_iterator obj = this->Objects.begin(); + obj != this->Objects.end(); ++obj) + { + objTarget = relPath; + objTarget += *obj; + depends.push_back(objTarget); + } + + // Add dependencies on targets that must be built first. + this->AppendTargetDepends(depends); + + // Add a dependency on the rule file itself. + this->LocalGenerator->AppendRuleDepend(depends, + this->BuildFileNameFull.c_str()); + + // Add a dependency on the link definitions file, if any. + if(!this->ModuleDefinitionFile.empty()) + { + depends.push_back(this->ModuleDefinitionFile); + } + + // Add dependencies on the external object files. + for(std::vector<std::string>::const_iterator obj + = this->ExternalObjects.begin(); + obj != this->ExternalObjects.end(); ++obj) + { + depends.push_back(*obj); + } + + // Add user-specified dependencies. + if(const char* linkDepends = + this->Target->GetProperty("LINK_DEPENDS")) + { + cmSystemTools::ExpandListArgument(linkDepends, depends); + } +} + +//---------------------------------------------------------------------------- +void cmMakefileTargetGenerator ::CloseFileStreams() { delete this->BuildFileStream; @@ -1620,6 +1668,17 @@ cmMakefileTargetGenerator std::vector<std::string> object_strings; this->WriteObjectsStrings(object_strings, responseFileLimit); + // Lookup the response file reference flag. + std::string responseFlagVar = "CMAKE_"; + responseFlagVar += this->Target->GetLinkerLanguage(this->ConfigName); + responseFlagVar += "_RESPONSE_FILE_LINK_FLAG"; + const char* responseFlag = + this->Makefile->GetDefinition(responseFlagVar.c_str()); + if(!responseFlag) + { + responseFlag = "@"; + } + // Write a response file for each string. const char* sep = ""; for(unsigned int i = 0; i < object_strings.size(); ++i) @@ -1637,7 +1696,7 @@ cmMakefileTargetGenerator sep = " "; // Reference the response file. - buildObjs += "@"; + buildObjs += responseFlag; buildObjs += this->Convert(objects_rsp.c_str(), cmLocalGenerator::NONE, cmLocalGenerator::SHELL); @@ -1707,8 +1766,20 @@ const char* cmMakefileTargetGenerator::GetFortranModuleDirectory() //---------------------------------------------------------------------------- void cmMakefileTargetGenerator::AddFortranFlags(std::string& flags) { + // Enable module output if necessary. + if(const char* modout_flag = + this->Makefile->GetDefinition("CMAKE_Fortran_MODOUT_FLAG")) + { + this->LocalGenerator->AppendFlags(flags, modout_flag); + } + // Add a module output directory flag if necessary. - if(const char* mod_dir = this->GetFortranModuleDirectory()) + const char* mod_dir = this->GetFortranModuleDirectory(); + if(!mod_dir) + { + mod_dir = this->Makefile->GetDefinition("CMAKE_Fortran_MODDIR_DEFAULT"); + } + if(mod_dir) { const char* moddir_flag = this->Makefile->GetRequiredDefinition("CMAKE_Fortran_MODDIR_FLAG"); diff --git a/Source/cmMakefileTargetGenerator.h b/Source/cmMakefileTargetGenerator.h index 4ee2b39..c9aede2 100644 --- a/Source/cmMakefileTargetGenerator.h +++ b/Source/cmMakefileTargetGenerator.h @@ -115,6 +115,9 @@ protected: // append intertarget dependencies void AppendTargetDepends(std::vector<std::string>& depends); + // Append link rule dependencies (objects, etc.). + void AppendLinkDepends(std::vector<std::string>& depends); + /** In order to support parallel builds for custom commands with multiple outputs the outputs are given a serial order, and only the first output actually has the build rule. Other outputs diff --git a/Source/cmOptionCommand.h b/Source/cmOptionCommand.h index 8670fc4..fa5abd8 100644 --- a/Source/cmOptionCommand.h +++ b/Source/cmOptionCommand.h @@ -59,7 +59,10 @@ public: " option(<option_variable> \"help string describing option\"\n" " [initial value])\n" "Provide an option for the user to select as ON or OFF. If no " - "initial value is provided, OFF is used."; + "initial value is provided, OFF is used.\n" + "If you have options that depend on the values of other " + "options, see the module help for CMakeDependentOption." + ; } /** diff --git a/Source/cmPolicies.cxx b/Source/cmPolicies.cxx index 2d41d40..2d1f792 100644 --- a/Source/cmPolicies.cxx +++ b/Source/cmPolicies.cxx @@ -3,6 +3,7 @@ #include "cmMakefile.h" #include "cmSourceFile.h" #include "cmVersion.h" +#include "cmVersionMacros.h" #include <map> #include <set> #include <queue> @@ -14,14 +15,15 @@ const char* cmPolicies::PolicyStatusNames[] = { class cmPolicy { -public: - cmPolicy(cmPolicies::PolicyID iD, +public: + cmPolicy(cmPolicies::PolicyID iD, const char *idString, const char *shortDescription, const char *longDescription, unsigned int majorVersionIntroduced, unsigned int minorVersionIntroduced, unsigned int patchVersionIntroduced, + unsigned int tweakVersionIntroduced, cmPolicies::PolicyStatus status) { if (!idString || !shortDescription || ! longDescription) @@ -37,21 +39,26 @@ public: this->MajorVersionIntroduced = majorVersionIntroduced; this->MinorVersionIntroduced = minorVersionIntroduced; this->PatchVersionIntroduced = patchVersionIntroduced; + this->TweakVersionIntroduced = tweakVersionIntroduced; this->Status = status; } std::string GetVersionString() { - cmOStringStream error; - error << this->MajorVersionIntroduced << "." << - this->MinorVersionIntroduced << "." << - this->PatchVersionIntroduced; - return error.str(); + cmOStringStream v; + v << this->MajorVersionIntroduced << "." << this->MinorVersionIntroduced; + v << "." << this->PatchVersionIntroduced; + if(this->TweakVersionIntroduced > 0) + { + v << "." << this->TweakVersionIntroduced; + } + return v.str(); } - bool IsPolicyNewerThan(unsigned int majorV, + bool IsPolicyNewerThan(unsigned int majorV, unsigned int minorV, - unsigned int patchV) + unsigned int patchV, + unsigned int tweakV) { if (majorV < this->MajorVersionIntroduced) { @@ -69,9 +76,17 @@ public: { return false; } - return (patchV < this->PatchVersionIntroduced); + if (patchV < this->PatchVersionIntroduced) + { + return true; + } + if (patchV > this->PatchVersionIntroduced) + { + return false; + } + return (tweakV < this->TweakVersionIntroduced); } - + cmPolicies::PolicyID ID; std::string IDString; std::string ShortDescription; @@ -79,6 +94,7 @@ public: unsigned int MajorVersionIntroduced; unsigned int MinorVersionIntroduced; unsigned int PatchVersionIntroduced; + unsigned int TweakVersionIntroduced; cmPolicies::PolicyStatus Status; }; @@ -110,7 +126,7 @@ cmPolicies::cmPolicies() "The NEW behavior is to issue an error instead of a warning. " "An included file may set CMP0000 explicitly to affect how this " "policy is enforced for the main CMakeLists.txt file.", - 2,6,0, cmPolicies::WARN + 2,6,0,0, cmPolicies::WARN ); this->DefinePolicy( @@ -126,7 +142,7 @@ cmPolicies::cmPolicies() "and the cmake_policy command. " "However, CMake must still check CMAKE_BACKWARDS_COMPATIBILITY for " "projects written for CMake 2.4 and below.", - 2,6,0, cmPolicies::WARN + 2,6,0,0, cmPolicies::WARN ); this->DefinePolicy( @@ -148,7 +164,7 @@ cmPolicies::cmPolicies() "Custom targets must simply have globally unique names (unless one " "uses the global property ALLOW_DUPLICATE_CUSTOM_TARGETS with a " "Makefiles generator).", - 2,6,0, cmPolicies::WARN + 2,6,0,0, cmPolicies::WARN ); this->DefinePolicy( @@ -213,7 +229,7 @@ cmPolicies::cmPolicies() "Note that the warning for this policy will be issued for at most " "one target. This avoids flooding users with messages for every " "target when setting the policy once will probably fix all targets.", - 2,6,0, cmPolicies::WARN); + 2,6,0,0, cmPolicies::WARN); this->DefinePolicy( CMP0004, "CMP0004", @@ -229,7 +245,7 @@ cmPolicies::cmPolicies() "The setting for this policy used when checking the library names is " "that in effect when the target is created by an add_executable or " "add_library command.", - 2,6,0, cmPolicies::WARN); + 2,6,0,0, cmPolicies::WARN); this->DefinePolicy( CMP0005, "CMP0005", @@ -250,7 +266,7 @@ cmPolicies::cmPolicies() "for all native build tools automatically. " "See documentation of the COMPILE_DEFINITIONS target property for " "limitations of the escaping implementation.", - 2,6,0, cmPolicies::WARN); + 2,6,0,0, cmPolicies::WARN); this->DefinePolicy( CMP0006, "CMP0006", @@ -268,19 +284,19 @@ cmPolicies::cmPolicies() "DESTINATION if a BUNDLE DESTINATION is not given. " "The NEW behavior for this policy is to produce an error if a bundle " "target is installed without a BUNDLE DESTINATION.", - 2,6,0, cmPolicies::WARN); - + 2,6,0,0, cmPolicies::WARN); + this->DefinePolicy( CMP0007, "CMP0007", "list command no longer ignores empty elements.", "This policy determines whether the list command will " - "ignore empty elements in the list. " + "ignore empty elements in the list. " "CMake 2.4 and below list commands ignored all empty elements" " in the list. For example, a;b;;c would have length 3 and not 4. " "The OLD behavior for this policy is to ignore empty list elements. " "The NEW behavior for this policy is to correctly count empty " "elements in a list. ", - 2,6,0, cmPolicies::WARN); + 2,6,0,0, cmPolicies::WARN); this->DefinePolicy( CMP0008, "CMP0008", @@ -306,7 +322,7 @@ cmPolicies::cmPolicies() "path and ask the linker to search for it. " "The NEW behavior for this policy is to trust the given path and " "pass it directly to the native build tool unchanged.", - 2,6,1, cmPolicies::WARN); + 2,6,1,0, cmPolicies::WARN); this->DefinePolicy( CMP0009, "CMP0009", @@ -322,7 +338,7 @@ cmPolicies::cmPolicies() "The NEW behavior for this policy is not to follow the symlinks " "by default, but only if FOLLOW_SYMLINKS is given as an additional " "argument to the FILE command.", - 2,6,2, cmPolicies::WARN); + 2,6,2,0, cmPolicies::WARN); this->DefinePolicy( CMP0010, "CMP0010", @@ -334,7 +350,7 @@ cmPolicies::cmPolicies() "The OLD behavior for this policy is to warn about the error, leave " "the string untouched, and continue. " "The NEW behavior for this policy is to report an error.", - 2,6,3, cmPolicies::WARN); + 2,6,3,0, cmPolicies::WARN); this->DefinePolicy( CMP0011, "CMP0011", @@ -354,7 +370,7 @@ cmPolicies::cmPolicies() "include() and find_package() commands. " "The NEW behavior for this policy is to allow the commands to do their " "default cmake_policy PUSH and POP.", - 2,6,3, cmPolicies::WARN); + 2,6,3,0, cmPolicies::WARN); this->DefinePolicy( CMP0012, "CMP0012", @@ -376,7 +392,7 @@ cmPolicies::cmPolicies() "named like numbers and boolean constants. " "The NEW behavior for this policy is to recognize numbers and " "boolean constants without dereferencing variables with such names.", - 2,8,0, cmPolicies::WARN); + 2,8,0,0, cmPolicies::WARN); this->DefinePolicy( CMP0013, "CMP0013", @@ -393,7 +409,7 @@ cmPolicies::cmPolicies() "directories. " "The NEW behavior for this policy is to disallow duplicate binary " "directories with an error.", - 2,8,0, cmPolicies::WARN); + 2,8,0,0, cmPolicies::WARN); this->DefinePolicy( CMP0014, "CMP0014", @@ -405,12 +421,12 @@ cmPolicies::cmPolicies() "the case is an error. " "The OLD behavior for this policy is to silently ignore the problem. " "The NEW behavior for this policy is to report an error.", - 2,8,0, cmPolicies::WARN); + 2,8,0,0, cmPolicies::WARN); this->DefinePolicy( CMP0015, "CMP0015", "link_directories() treats paths relative to the source dir.", - "In CMake 2.6.4 and lower the link_directories() command passed relative " + "In CMake 2.8.0 and lower the link_directories() command passed relative " "paths unchanged to the linker. " "In CMake 2.8.1 and above the link_directories() command prefers to " "interpret relative paths with respect to CMAKE_CURRENT_SOURCE_DIR, " @@ -420,13 +436,39 @@ cmPolicies::cmPolicies() "The NEW behavior for this policy is to convert relative paths to " "absolute paths by appending the relative path to " "CMAKE_CURRENT_SOURCE_DIR.", - 2,8,1, cmPolicies::WARN); + 2,8,1,0, cmPolicies::WARN); + + this->DefinePolicy( + CMP0016, "CMP0016", + "target_link_libraries() reports error if only argument is not a target.", + "In CMake 2.8.2 and lower the target_link_libraries() command silently " + "ignored if it was called with only one argument, and this argument " + "wasn't a valid target. " + "In CMake 2.8.3 and above it reports an error in this case.", + 2,8,3,0, cmPolicies::WARN); + + this->DefinePolicy( + CMP0017, "CMP0017", + "Prefer files from the CMake module directory when including from there.", + "Starting with CMake 2.8.4, if a cmake-module shipped with CMake (i.e. " + "located in the CMake module directory) calls include() or " + "find_package(), the files located in the the CMake module directory are " + "prefered over the files in CMAKE_MODULE_PATH. " + "This makes sure that the modules belonging to " + "CMake always get those files included which they expect, and against " + "which they were developed and tested. " + "In call other cases, the files found in " + "CMAKE_MODULE_PATH still take precedence over the ones in " + "the CMake module directory. " + "The OLD behaviour is to always prefer files from CMAKE_MODULE_PATH over " + "files from the CMake modules directory.", + 2,8,4,0, cmPolicies::WARN); } cmPolicies::~cmPolicies() { // free the policies - std::map<cmPolicies::PolicyID,cmPolicy *>::iterator i + std::map<cmPolicies::PolicyID,cmPolicy *>::iterator i = this->Policies.begin(); for (;i != this->Policies.end(); ++i) { @@ -435,12 +477,13 @@ cmPolicies::~cmPolicies() } void cmPolicies::DefinePolicy(cmPolicies::PolicyID iD, - const char *idString, + const char *idString, const char *shortDescription, const char *longDescription, unsigned int majorVersionIntroduced, unsigned int minorVersionIntroduced, unsigned int patchVersionIntroduced, + unsigned int tweakVersionIntroduced, cmPolicies::PolicyStatus status) { // a policy must be unique and can only be defined once @@ -450,43 +493,45 @@ void cmPolicies::DefinePolicy(cmPolicies::PolicyID iD, "ID ", this->GetPolicyIDString(iD).c_str()); return; } - + this->Policies[iD] = new cmPolicy(iD, idString, shortDescription, longDescription, majorVersionIntroduced, minorVersionIntroduced, patchVersionIntroduced, + tweakVersionIntroduced, status); this->PolicyStringMap[idString] = iD; } //---------------------------------------------------------------------------- -bool cmPolicies::ApplyPolicyVersion(cmMakefile *mf, +bool cmPolicies::ApplyPolicyVersion(cmMakefile *mf, const char *version) { std::string ver = "2.4.0"; if (version && strlen(version) > 0) - { + { ver = version; - } + } unsigned int majorVer = 2; unsigned int minorVer = 0; unsigned int patchVer = 0; + unsigned int tweakVer = 0; // parse the string - if(sscanf(ver.c_str(), "%u.%u.%u", - &majorVer, &minorVer, &patchVer) < 2) + if(sscanf(ver.c_str(), "%u.%u.%u.%u", + &majorVer, &minorVer, &patchVer, &tweakVer) < 2) { cmOStringStream e; e << "Invalid policy version value \"" << ver << "\". " - << "A numeric major.minor[.patch] must be given."; + << "A numeric major.minor[.patch[.tweak]] must be given."; mf->IssueMessage(cmake::FATAL_ERROR, e.str()); return false; } - + // it is an error if the policy version is less than 2.4 if (majorVer < 2 || (majorVer == 2 && minorVer < 4)) { @@ -510,7 +555,11 @@ bool cmPolicies::ApplyPolicyVersion(cmMakefile *mf, minorVer > cmVersion::GetMinorVersion()) || (majorVer == cmVersion::GetMajorVersion() && minorVer == cmVersion::GetMinorVersion() && - patchVer > cmVersion::GetPatchVersion())) + patchVer > cmVersion::GetPatchVersion()) || + (majorVer == cmVersion::GetMajorVersion() && + minorVer == cmVersion::GetMinorVersion() && + patchVer == cmVersion::GetPatchVersion() && + tweakVer > cmVersion::GetTweakVersion())) { cmOStringStream e; e << "An attempt was made to set the policy version of CMake to \"" @@ -524,29 +573,33 @@ bool cmPolicies::ApplyPolicyVersion(cmMakefile *mf, // now loop over all the policies and set them as appropriate std::vector<cmPolicies::PolicyID> ancientPolicies; - std::map<cmPolicies::PolicyID,cmPolicy *>::iterator i - = this->Policies.begin(); - for (;i != this->Policies.end(); ++i) - { - if (i->second->IsPolicyNewerThan(majorVer,minorVer,patchVer)) + for(std::map<cmPolicies::PolicyID,cmPolicy *>::iterator i + = this->Policies.begin(); i != this->Policies.end(); ++i) { - if(i->second->Status == cmPolicies::REQUIRED_ALWAYS) + if (i->second->IsPolicyNewerThan(majorVer,minorVer,patchVer,tweakVer)) { + if(i->second->Status == cmPolicies::REQUIRED_ALWAYS) + { ancientPolicies.push_back(i->first); + } + else + { + cmPolicies::PolicyStatus status = cmPolicies::WARN; + if(!this->GetPolicyDefault(mf, i->second->IDString, &status) || + !mf->SetPolicy(i->second->ID, status)) + { + return false; + } + } } - else if (!mf->SetPolicy(i->second->ID, cmPolicies::WARN)) - { - return false; - } - } else - { - if (!mf->SetPolicy(i->second->ID, cmPolicies::NEW)) { + if (!mf->SetPolicy(i->second->ID, cmPolicies::NEW)) + { return false; + } } } - } // Make sure the project does not use any ancient policies. if(!ancientPolicies.empty()) @@ -560,13 +613,43 @@ bool cmPolicies::ApplyPolicyVersion(cmMakefile *mf, return true; } +//---------------------------------------------------------------------------- +bool cmPolicies::GetPolicyDefault(cmMakefile* mf, std::string const& policy, + cmPolicies::PolicyStatus* defaultSetting) +{ + std::string defaultVar = "CMAKE_POLICY_DEFAULT_" + policy; + std::string defaultValue = mf->GetSafeDefinition(defaultVar.c_str()); + if(defaultValue == "NEW") + { + *defaultSetting = cmPolicies::NEW; + } + else if(defaultValue == "OLD") + { + *defaultSetting = cmPolicies::OLD; + } + else if(defaultValue == "") + { + *defaultSetting = cmPolicies::WARN; + } + else + { + cmOStringStream e; + e << defaultVar << " has value \"" << defaultValue + << "\" but must be \"OLD\", \"NEW\", or \"\" (empty)."; + mf->IssueMessage(cmake::FATAL_ERROR, e.str().c_str()); + return false; + } + + return true; +} + bool cmPolicies::GetPolicyID(const char *id, cmPolicies::PolicyID &pid) { if (!id || strlen(id) < 1) { return false; } - std::map<std::string,cmPolicies::PolicyID>::iterator pos = + std::map<std::string,cmPolicies::PolicyID>::iterator pos = this->PolicyStringMap.find(id); if (pos == this->PolicyStringMap.end()) { @@ -578,7 +661,7 @@ bool cmPolicies::GetPolicyID(const char *id, cmPolicies::PolicyID &pid) std::string cmPolicies::GetPolicyIDString(cmPolicies::PolicyID pid) { - std::map<cmPolicies::PolicyID,cmPolicy *>::iterator pos = + std::map<cmPolicies::PolicyID,cmPolicy *>::iterator pos = this->Policies.find(pid); if (pos == this->Policies.end()) { @@ -591,7 +674,7 @@ std::string cmPolicies::GetPolicyIDString(cmPolicies::PolicyID pid) ///! return a warning string for a given policy std::string cmPolicies::GetPolicyWarning(cmPolicies::PolicyID id) { - std::map<cmPolicies::PolicyID,cmPolicy *>::iterator pos = + std::map<cmPolicies::PolicyID,cmPolicy *>::iterator pos = this->Policies.find(id); if (pos == this->Policies.end()) { @@ -610,12 +693,12 @@ std::string cmPolicies::GetPolicyWarning(cmPolicies::PolicyID id) "and suppress this warning."; return msg.str(); } - - + + ///! return an error string for when a required policy is unspecified std::string cmPolicies::GetRequiredPolicyError(cmPolicies::PolicyID id) { - std::map<cmPolicies::PolicyID,cmPolicy *>::iterator pos = + std::map<cmPolicies::PolicyID,cmPolicy *>::iterator pos = this->Policies.find(id); if (pos == this->Policies.end()) { @@ -641,25 +724,25 @@ std::string cmPolicies::GetRequiredPolicyError(cmPolicies::PolicyID id) } ///! Get the default status for a policy -cmPolicies::PolicyStatus +cmPolicies::PolicyStatus cmPolicies::GetPolicyStatus(cmPolicies::PolicyID id) { // if the policy is not know then what? - std::map<cmPolicies::PolicyID,cmPolicy *>::iterator pos = + std::map<cmPolicies::PolicyID,cmPolicy *>::iterator pos = this->Policies.find(id); if (pos == this->Policies.end()) { // TODO is this right? return cmPolicies::WARN; } - + return pos->second->Status; } void cmPolicies::GetDocumentation(std::vector<cmDocumentationEntry>& v) { // now loop over all the policies and set them as appropriate - std::map<cmPolicies::PolicyID,cmPolicy *>::iterator i + std::map<cmPolicies::PolicyID,cmPolicy *>::iterator i = this->Policies.begin(); for (;i != this->Policies.end(); ++i) { diff --git a/Source/cmPolicies.h b/Source/cmPolicies.h index aaa3ac0..2160f37 100644 --- a/Source/cmPolicies.h +++ b/Source/cmPolicies.h @@ -51,6 +51,8 @@ public: CMP0013, // Duplicate binary directories not allowed CMP0014, // Input directories must have CMakeLists.txt CMP0015, // link_directories() treats paths relative to source dir + CMP0016, // target_link_libraries() fails if only argument is not a target + CMP0017, // Prefer files in CMAKE_ROOT when including from CMAKE_ROOT // Always the last entry. Useful mostly to avoid adding a comma // the last policy when adding a new one. @@ -60,10 +62,10 @@ public: ///! convert a string policy ID into a number bool GetPolicyID(const char *id, /* out */ cmPolicies::PolicyID &pid); std::string GetPolicyIDString(cmPolicies::PolicyID pid); - + ///! Get the default status for a policy cmPolicies::PolicyStatus GetPolicyStatus(cmPolicies::PolicyID id); - + ///! Define a Policy for CMake void DefinePolicy(cmPolicies::PolicyID id, const char *stringID, @@ -72,6 +74,7 @@ public: unsigned int majorVersionIntroduced, unsigned int minorVersionIntroduced, unsigned int patchVersionIntroduced, + unsigned int tweakVersionIntroduced, cmPolicies::PolicyStatus status); ///! Set a policy level for this listfile @@ -79,7 +82,7 @@ public: ///! return a warning string for a given policy std::string GetPolicyWarning(cmPolicies::PolicyID id); - + ///! return an error string for when a required policy is unspecified std::string GetRequiredPolicyError(cmPolicies::PolicyID id); @@ -100,6 +103,10 @@ public: void DiagnoseAncientPolicies(std::vector<PolicyID> const& ancient, unsigned int majorVer, unsigned int minorVer, unsigned int patchVer, cmMakefile* mf); + + bool GetPolicyDefault(cmMakefile* mf, std::string const& policy, + cmPolicies::PolicyStatus* defaultStatus); + }; #endif diff --git a/Source/cmProcessTools.cxx b/Source/cmProcessTools.cxx index cacd766..d2f7bf3 100644 --- a/Source/cmProcessTools.cxx +++ b/Source/cmProcessTools.cxx @@ -44,7 +44,7 @@ void cmProcessTools::RunProcess(struct cmsysProcess_s* cp, //---------------------------------------------------------------------------- cmProcessTools::LineParser::LineParser(char sep, bool ignoreCR): - Separator(sep), IgnoreCR(ignoreCR), Log(0), Prefix(0) + Separator(sep), IgnoreCR(ignoreCR), Log(0), Prefix(0), LineEnd('\0') { } @@ -61,8 +61,10 @@ bool cmProcessTools::LineParser::ProcessChunk(const char* first, int length) const char* last = first + length; for(const char* c = first; c != last; ++c) { - if(*c == this->Separator) + if(*c == this->Separator || *c == '\0') { + this->LineEnd = *c; + // Log this line. if(this->Log && this->Prefix) { diff --git a/Source/cmProcessTools.h b/Source/cmProcessTools.h index 0b210af..439726d 100644 --- a/Source/cmProcessTools.h +++ b/Source/cmProcessTools.h @@ -55,6 +55,7 @@ public: bool IgnoreCR; std::ostream* Log; const char* Prefix; + char LineEnd; std::string Line; virtual bool ProcessChunk(const char* data, int length); diff --git a/Source/cmProjectCommand.h b/Source/cmProjectCommand.h index fca5f1f..fc2b7a2 100644 --- a/Source/cmProjectCommand.h +++ b/Source/cmProjectCommand.h @@ -66,7 +66,7 @@ public: "Optionally you can specify which languages your project supports. " "Example languages are CXX (i.e. C++), C, Fortran, etc. " "By default C and CXX are enabled. E.g. if you do not have a " - "C++ compiler, you can disable the check for it by explicitely listing " + "C++ compiler, you can disable the check for it by explicitly listing " "the languages you want to support, e.g. C. By using the special " "language \"NONE\" all checks for any language can be disabled."; } diff --git a/Source/cmSetCommand.cxx b/Source/cmSetCommand.cxx index 5fcbdba..d00fc86 100644 --- a/Source/cmSetCommand.cxx +++ b/Source/cmSetCommand.cxx @@ -99,7 +99,7 @@ bool cmSetCommand } } - // collect any values into a single semi-colon seperated value list + // collect any values into a single semi-colon separated value list if(static_cast<unsigned short>(args.size()) > static_cast<unsigned short>(1 + ignoreLastArgs)) { diff --git a/Source/cmSetPropertyCommand.h b/Source/cmSetPropertyCommand.h index 853e7ba..c477bb7 100644 --- a/Source/cmSetPropertyCommand.h +++ b/Source/cmSetPropertyCommand.h @@ -66,7 +66,9 @@ public: "directory (already processed by CMake) may be named by full or " "relative path.\n" "TARGET scope may name zero or more existing targets.\n" - "SOURCE scope may name zero or more source files.\n" + "SOURCE scope may name zero or more source files. " + "Note that source file properties are visible only to targets " + "added in the same directory (CMakeLists.txt).\n" "TEST scope may name zero or more existing tests.\n" "CACHE scope must name zero or more cache existing entries.\n" "The required PROPERTY option is immediately followed by the name " diff --git a/Source/cmSetSourceFilesPropertiesCommand.h b/Source/cmSetSourceFilesPropertiesCommand.h index 7182152..392f168 100644 --- a/Source/cmSetSourceFilesPropertiesCommand.h +++ b/Source/cmSetSourceFilesPropertiesCommand.h @@ -48,35 +48,15 @@ public: virtual const char* GetFullDocumentation() { return - " set_source_files_properties(file1 file2 ...\n" + " set_source_files_properties([file1 [file2 [...]]]\n" " PROPERTIES prop1 value1\n" - " prop2 value2 ...)\n" - "Set properties on a file. The syntax for the command is to list all " - "the files you want " - "to change, and then provide the values you want to set next. You " - "can make up your own properties as well. " - "The following are used by CMake. " - "The ABSTRACT flag (boolean) is used by some class wrapping " - "commands. " - "If WRAP_EXCLUDE (boolean) is true then many wrapping commands " - "will ignore this file. If GENERATED (boolean) is true then it " - "is not an error if this source file does not exist when it is " - "added to a target. Obviously, " - "it must be created (presumably by a custom command) before the " - "target is built. " - "If the HEADER_FILE_ONLY (boolean) property is true then the " - "file is not compiled. This is useful if you want to add extra " - "non build files to an IDE. " - "OBJECT_DEPENDS (string) adds dependencies to the object file. " - "COMPILE_FLAGS (string) is passed to the compiler as additional " - "command line arguments when the source file is compiled. " - "LANGUAGE (string) CXX|C will change the default compiler used " - "to compile the source file. The languages used need to be enabled " - "in the PROJECT command. " - "If SYMBOLIC (boolean) is set to true the build system will be " - "informed that the source file is not actually created on disk but " - "instead used as a symbolic name for a build rule."; - + " [prop2 value2 [...]])\n" + "Set properties associated with source files using a key/value " + "paired list. " + "See properties documentation for those known to CMake. " + "Unrecognized properties are ignored. " + "Source file properties are visible only to targets " + "added in the same directory (CMakeLists.txt)."; } cmTypeMacro(cmSetSourceFilesPropertiesCommand, cmCommand); diff --git a/Source/cmSourceFile.cxx b/Source/cmSourceFile.cxx index 3704d6a..ed1da7b 100644 --- a/Source/cmSourceFile.cxx +++ b/Source/cmSourceFile.cxx @@ -16,6 +16,7 @@ #include "cmMakefile.h" #include "cmSystemTools.h" #include "cmake.h" +#include "cmDocumentCompileDefinitions.h" //---------------------------------------------------------------------------- cmSourceFile::cmSourceFile(cmMakefile* mf, const char* name): @@ -101,11 +102,11 @@ cmSourceFileLocation const& cmSourceFile::GetLocation() const } //---------------------------------------------------------------------------- -std::string const& cmSourceFile::GetFullPath() +std::string const& cmSourceFile::GetFullPath(std::string* error) { if(this->FullPath.empty()) { - if(this->FindFullPath()) + if(this->FindFullPath(error)) { this->CheckExtension(); } @@ -120,7 +121,7 @@ std::string const& cmSourceFile::GetFullPath() const } //---------------------------------------------------------------------------- -bool cmSourceFile::FindFullPath() +bool cmSourceFile::FindFullPath(std::string* error) { // If thie method has already failed once do not try again. if(this->FindFullPathFailed) @@ -187,8 +188,13 @@ bool cmSourceFile::FindFullPath() } cmOStringStream e; - e << "Cannot find source file \"" << this->Location.GetName() << "\""; - e << ". Tried extensions"; + std::string missing = this->Location.GetDirectory(); + if(!missing.empty()) + { + missing += "/"; + } + missing += this->Location.GetName(); + e << "Cannot find source file:\n " << missing << "\nTried extensions"; for(std::vector<std::string>::const_iterator ext = srcExts.begin(); ext != srcExts.end(); ++ext) { @@ -199,7 +205,14 @@ bool cmSourceFile::FindFullPath() { e << " ." << *ext; } - this->Location.GetMakefile()->IssueMessage(cmake::FATAL_ERROR, e.str()); + if(error) + { + *error = e.str(); + } + else + { + this->Location.GetMakefile()->IssueMessage(cmake::FATAL_ERROR, e.str()); + } this->FindFullPathFailed = true; return false; } @@ -404,15 +417,7 @@ void cmSourceFile::DefineProperties(cmake *cm) "The VS6 IDE does not support definition values with spaces " "(but NMake does). Xcode does not support per-configuration " "definitions on source files.\n" - "Dislaimer: Most native build tools have poor support for escaping " - "certain values. CMake has work-arounds for many cases but some " - "values may just not be possible to pass correctly. If a value " - "does not seem to be escaped correctly, do not attempt to " - "work-around the problem by adding escape sequences to the value. " - "Your work-around may break in a future version of CMake that " - "has improved escape support. Instead consider defining the macro " - "in a (configured) header file. Then report the limitation."); - + CM_DOCUMENT_COMPILE_DEFINITIONS_DISCLAIMER); cm->DefineProperty ("COMPILE_DEFINITIONS_<CONFIG>", cmProperty::SOURCE_FILE, @@ -433,7 +438,7 @@ void cmSourceFile::DefineProperties(cmake *cm) ("GENERATED", cmProperty::SOURCE_FILE, "Is this source file generated as part of the build process.", "If a source file is generated by the build process CMake will " - "handle it differently in temrs of dependency checking etc. " + "handle it differently in terms of dependency checking etc. " "Otherwise having a non-existent source file could create problems."); cm->DefineProperty @@ -465,7 +470,9 @@ void cmSourceFile::DefineProperties(cmake *cm) "What programming language is the file.", "A property that can be set to indicate what programming language " "the source file is. If it is not set the language is determined " - "based on the file extension. Typical values are CXX C etc."); + "based on the file extension. Typical values are CXX C etc. Setting " + "this property for a file means this file will be compiled. " + "Do not set this for header or files that should not be compiled."); cm->DefineProperty ("LOCATION", cmProperty::SOURCE_FILE, @@ -487,7 +494,7 @@ void cmSourceFile::DefineProperties(cmake *cm) "For frameworks the content folder is " "\"<name>.framework/Versions/<version>\". " "See the PUBLIC_HEADER, PRIVATE_HEADER, and RESOURCE target " - "properties for specifying files meant for Headers, PrivateHeadres, " + "properties for specifying files meant for Headers, PrivateHeaders, " "or Resources directories."); cm->DefineProperty diff --git a/Source/cmSourceFile.h b/Source/cmSourceFile.h index 937e4b7..2dc8488 100644 --- a/Source/cmSourceFile.h +++ b/Source/cmSourceFile.h @@ -60,7 +60,7 @@ public: * horrible interface, but is necessary for backwards * compatibility). */ - std::string const& GetFullPath(); + std::string const& GetFullPath(std::string* error = 0); std::string const& GetFullPath() const; /** @@ -108,7 +108,7 @@ private: std::string FullPath; bool FindFullPathFailed; - bool FindFullPath(); + bool FindFullPath(std::string* error); bool TryFullPath(const char* tryPath, const char* ext); void CheckExtension(); void CheckLanguage(std::string const& ext); diff --git a/Source/cmStandardIncludes.cxx b/Source/cmStandardIncludes.cxx new file mode 100644 index 0000000..a4bdb2e --- /dev/null +++ b/Source/cmStandardIncludes.cxx @@ -0,0 +1,16 @@ +/*============================================================================ + CMake - Cross Platform Makefile Generator + Copyright 2000-2010 Kitware, Inc., Insight Software Consortium + + Distributed under the OSI-approved BSD License (the "License"); + see accompanying file Copyright.txt for details. + + This software is distributed WITHOUT ANY WARRANTY; without even the + implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the License for more information. +============================================================================*/ +#include "cmStandardIncludes.h" +#if !defined(CMAKE_NO_ANSI_STRING_STREAM) +cmOStringStream::cmOStringStream() {} +cmOStringStream::~cmOStringStream() {} +#endif diff --git a/Source/cmStandardIncludes.h b/Source/cmStandardIncludes.h index 5db0200..e8decbb 100644 --- a/Source/cmStandardIncludes.h +++ b/Source/cmStandardIncludes.h @@ -45,6 +45,7 @@ // This is a hack to prevent warnings about these functions being // declared but not referenced. #if defined(__sgi) && !defined(__GNUC__) +# pragma set woff 3970 /* conversion from pointer to same-sized */ # include <sys/termios.h> class cmStandardIncludesHack { @@ -240,7 +241,8 @@ typedef cmsys::String cmStdString; class cmOStringStream: public std::ostringstream { public: - cmOStringStream() {} + cmOStringStream(); + ~cmOStringStream(); private: cmOStringStream(const cmOStringStream&); void operator=(const cmOStringStream&); diff --git a/Source/cmStringCommand.cxx b/Source/cmStringCommand.cxx index 3bd47a4..2b4414d 100644 --- a/Source/cmStringCommand.cxx +++ b/Source/cmStringCommand.cxx @@ -606,7 +606,7 @@ bool cmStringCommand::HandleSubstringCommand(std::vector<std::string> const& return false; } int leftOverLength = intStringLength - begin; - if ( end < 0 || end > leftOverLength ) + if ( end < -1 || end > leftOverLength ) { cmOStringStream ostr; ostr << "end index: " << end << " is out of range " << 0 << " - " @@ -739,7 +739,7 @@ bool cmStringCommand alphabet = cmStringCommandDefaultAlphabet; } - double sizeofAlphabet = alphabet.size(); + double sizeofAlphabet = static_cast<double>(alphabet.size()); if ( sizeofAlphabet < 1 ) { this->SetError("sub-command RANDOM invoked with bad alphabet."); diff --git a/Source/cmSystemTools.cxx b/Source/cmSystemTools.cxx index f5fba5c..7bc89a4 100644 --- a/Source/cmSystemTools.cxx +++ b/Source/cmSystemTools.cxx @@ -23,8 +23,8 @@ #include <cmsys/Directory.hxx> #include <cmsys/System.h> #if defined(CMAKE_BUILD_WITH_CMAKE) -#include <cmlibarchive/libarchive/archive.h> -#include <cmlibarchive/libarchive/archive_entry.h> +# include "cmArchiveWrite.h" +# include <cm_libarchive.h> # include <cmsys/Terminal.h> #endif #include <cmsys/stl/algorithm> @@ -191,49 +191,6 @@ std::string cmSystemTools::EscapeQuotes(const char* str) return result; } -std::string cmSystemTools::EscapeSpaces(const char* str) -{ -#if defined(_WIN32) && !defined(__CYGWIN__) - bool useDoubleQ = true; -#else - bool useDoubleQ = false; -#endif - if(cmSystemTools::s_ForceUnixPaths) - { - useDoubleQ = false; - } - - if(useDoubleQ) - { - std::string result; - - // if there are spaces - std::string temp = str; - if (temp.find(" ") != std::string::npos && - temp.find("\"")==std::string::npos) - { - result = "\""; - result += str; - result += "\""; - return result; - } - return str; - } - else - { - std::string result = ""; - for(const char* ch = str; *ch != '\0'; ++ch) - { - if(*ch == ' ') - { - result += '\\'; - } - result += *ch; - } - return result; - } -} - void cmSystemTools::Error(const char* m1, const char* m2, const char* m3, const char* m4) { @@ -326,7 +283,22 @@ void cmSystemTools::ReportLastSystemError(const char* msg) cmSystemTools::Error(m.c_str()); } - +bool cmSystemTools::IsInternallyOn(const char* val) +{ + if (!val) + { + return false; + } + std::basic_string<char> v = val; + + for(std::basic_string<char>::iterator c = v.begin(); + c != v.end(); c++) + { + *c = static_cast<char>(toupper(*c)); + } + return (v == "I_ON" || v == "i_on"); +} + bool cmSystemTools::IsOn(const char* val) { if (!val) @@ -1204,6 +1176,8 @@ bool cmSystemTools::ComputeFileMD5(const char* source, char* md5out) // Should be efficient enough on most system: const int bufferSize = 4096; char buffer[bufferSize]; + unsigned char const* buffer_uc = + reinterpret_cast<unsigned char const*>(buffer); // This copy loop is very sensitive on certain platforms with // slightly broken stream libraries (like HPUX). Normally, it is // incorrect to not check the error condition on the fin.read() @@ -1212,10 +1186,9 @@ bool cmSystemTools::ComputeFileMD5(const char* source, char* md5out) while(fin) { fin.read(buffer, bufferSize); - if(fin.gcount()) + if(int gcount = static_cast<int>(fin.gcount())) { - cmsysMD5_Append(md5, reinterpret_cast<unsigned char const*>(buffer), - fin.gcount()); + cmsysMD5_Append(md5, buffer_uc, gcount); } } cmsysMD5_FinalizeHex(md5, md5out); @@ -1673,6 +1646,18 @@ void cmSystemTools::RestoreEnv(const std::vector<std::string>& env) PutEnv(eit->c_str()); } } + +//---------------------------------------------------------------------- +cmSystemTools::SaveRestoreEnvironment::SaveRestoreEnvironment() +{ + this->Env = cmSystemTools::GetEnvironmentVariables(); +} + +//---------------------------------------------------------------------- +cmSystemTools::SaveRestoreEnvironment::~SaveRestoreEnvironment() +{ + cmSystemTools::RestoreEnv(this->Env); +} #endif void cmSystemTools::EnableVSConsoleOutput() @@ -1707,142 +1692,41 @@ bool cmSystemTools::CreateTar(const char* outFileName, bool gzip, bool bzip2, bool verbose) { #if defined(CMAKE_BUILD_WITH_CMAKE) - - // Create a macro to handle return from libarchive - // functions -#define CHECK_ARCHIVE_ERROR(res, msg)\ - if(res != ARCHIVE_OK)\ - {\ - cmSystemTools::Error(msg, \ - archive_error_string(a));\ - return false;\ - } - std::string cwd = cmSystemTools::GetCurrentWorkingDirectory(); - // recursively expand all directories in files so that we have a list - // of files - std::vector<std::string> expandedFiles; + std::ofstream fout(outFileName, std::ios::out | cmsys_ios_binary); + if(!fout) + { + std::string e = "Cannot open output file \""; + e += outFileName; + e += "\": "; + e += cmSystemTools::GetLastSystemError(); + cmSystemTools::Error(e.c_str()); + return false; + } + cmArchiveWrite a(fout, (gzip? cmArchiveWrite::CompressGZip : + (bzip2? cmArchiveWrite::CompressBZip2 : + cmArchiveWrite::CompressNone)), + cmArchiveWrite::TypeTAR); + a.SetVerbose(verbose); for(std::vector<cmStdString>::const_iterator i = files.begin(); i != files.end(); ++i) { - if(cmSystemTools::FileIsDirectory(i->c_str())) + std::string path = *i; + if(cmSystemTools::FileIsFullPath(path.c_str())) { - cmsys::Glob gl; - std::string findExpr = *i; - if ( findExpr[findExpr.size()-1] != '/' ) - { - findExpr +="/"; - } - findExpr += "*"; - gl.RecurseOn(); - if ( gl.FindFiles(findExpr) ) - { - std::vector<std::string> dirfiles = gl.GetFiles(); - std::copy(dirfiles.begin(), dirfiles.end(), - std::back_inserter(expandedFiles)); - } + // Get the relative path to the file. + path = cmSystemTools::RelativePath(cwd.c_str(), path.c_str()); } - else + if(!a.Add(path)) { - if(!cmSystemTools::FileIsFullPath(i->c_str())) - { - std::string fullp = cwd + "/" + *i; - expandedFiles.push_back(fullp); - } - else - { - expandedFiles.push_back(*i); - } + break; } } - int res; - // create a new archive - struct archive* a = archive_write_new(); if(!a) { - cmSystemTools::Error("Unable to use create archive"); + cmSystemTools::Error(a.GetError().c_str()); return false; } - - if(gzip) - { - res = archive_write_set_compression_gzip(a); - CHECK_ARCHIVE_ERROR(res, "Can not set gzip:"); - } - if(bzip2) - { - res = archive_write_set_compression_bzip2(a); - CHECK_ARCHIVE_ERROR(res, "Can not set bzip2:"); - } - if(!bzip2 && !gzip) - { - res = archive_write_set_compression_none(a); - CHECK_ARCHIVE_ERROR(res, "Can not set none:"); - } - res = archive_write_set_format_pax_restricted(a); - CHECK_ARCHIVE_ERROR(res, "Can not set tar format:"); - res = archive_write_open_file(a, outFileName); - CHECK_ARCHIVE_ERROR(res, "write open:"); - // create a new disk struct - struct archive* disk = archive_read_disk_new(); - archive_read_disk_set_standard_lookup(disk); - std::vector<std::string>::const_iterator fileIt; - for ( fileIt = expandedFiles.begin(); - fileIt != expandedFiles.end(); ++ fileIt ) - { - // create a new entry for each file - struct archive_entry *entry = archive_entry_new(); - // Get the relative path to the file - std::string rp = cmSystemTools::RelativePath(cwd.c_str(), - fileIt->c_str()); - if(verbose) - { - std::cout << rp << "\n"; - } - // Set the name of the entry to the file name - archive_entry_set_pathname(entry, rp.c_str()); - archive_read_disk_entry_from_file(disk, entry, -1, 0); - CHECK_ARCHIVE_ERROR(res, "read disk entry:"); - - // write entry header - res = archive_write_header(a, entry); - CHECK_ARCHIVE_ERROR(res, "write header: "); - if(archive_entry_size(entry) > 0) - { - // now copy contents of file into archive a - FILE* file = fopen(fileIt->c_str(), "rb"); - if(!file) - { - cmSystemTools::Error("Problem with fopen(): ", - fileIt->c_str()); - return false; - } - char buff[16384]; - size_t len = fread(buff, 1, sizeof(buff), file); - while (len > 0) - { - size_t wlen = archive_write_data(a, buff, len); - if(wlen != len) - { - cmOStringStream error; - error << "Problem with archive_write_data\n" - << "Tried to write [" << len << "] bytes.\n" - << "archive_write_data wrote [" << wlen << "] bytes.\n"; - cmSystemTools::Error(error.str().c_str(), - archive_error_string(a) - ); - return false; - } - len = fread(buff, 1, sizeof(buff), file); - } - // close the file and free the entry - fclose(file); - } - archive_entry_free(entry); - } - // close the archive and finish the write - archive_write_close(a); - archive_write_finish(a); return true; #else (void)outFileName; @@ -1977,9 +1861,9 @@ namespace{ # pragma warn -8066 /* unreachable code */ #endif -int copy_data(struct archive *ar, struct archive *aw) +long copy_data(struct archive *ar, struct archive *aw) { - int r; + long r; const void *buff; size_t size; off_t offset; @@ -2036,23 +1920,32 @@ bool extract_tar(const char* outFileName, bool verbose, if (verbose && extract) { cmSystemTools::Stdout("x "); + cmSystemTools::Stdout(archive_entry_pathname(entry)); } if(verbose && !extract) { list_item_verbose(stdout, entry); } - else + else if(!extract) { cmSystemTools::Stdout(archive_entry_pathname(entry)); } if(extract) { + r = archive_write_disk_set_options(ext, ARCHIVE_EXTRACT_TIME); + if (r != ARCHIVE_OK) + { + cmSystemTools::Error( + "Problem with archive_write_disk_set_options(): ", + archive_error_string(ext)); + } + r = archive_write_header(ext, entry); if (r != ARCHIVE_OK) { cmSystemTools::Error("Problem with archive_write_header(): ", - archive_error_string(a)); - cmSystemTools::Error("Curren file:", + archive_error_string(ext)); + cmSystemTools::Error("Current file:", archive_entry_pathname(entry)); } else @@ -2123,7 +2016,7 @@ int cmSystemTools::WaitForLine(cmsysProcess* process, std::string& line, } else if(*outiter == '\n' || *outiter == '\0') { - int length = outiter-out.begin(); + std::vector<char>::size_type length = outiter-out.begin(); if(length > 1 && *(outiter-1) == '\r') { --length; @@ -2146,7 +2039,7 @@ int cmSystemTools::WaitForLine(cmsysProcess* process, std::string& line, } else if(*erriter == '\n' || *erriter == '\0') { - int length = erriter-err.begin(); + std::vector<char>::size_type length = erriter-err.begin(); if(length > 1 && *(erriter-1) == '\r') { --length; @@ -2691,6 +2584,33 @@ bool cmSystemTools::ChangeRPath(std::string const& file, } //---------------------------------------------------------------------------- +bool cmSystemTools::VersionCompare(cmSystemTools::CompareOp op, + const char* lhss, const char* rhss) +{ + unsigned int lhs[4] = {0,0,0,0}; + unsigned int rhs[4] = {0,0,0,0}; + sscanf(lhss, "%u.%u.%u.%u", &lhs[0], &lhs[1], &lhs[2], &lhs[3]); + sscanf(rhss, "%u.%u.%u.%u", &rhs[0], &rhs[1], &rhs[2], &rhs[3]); + + // Do component-wise comparison. + for(unsigned int i=0; i < 4; ++i) + { + if(lhs[i] < rhs[i]) + { + // lhs < rhs, so true if operation is LESS + return op == cmSystemTools::OP_LESS; + } + else if(lhs[i] > rhs[i]) + { + // lhs > rhs, so true if operation is GREATER + return op == cmSystemTools::OP_GREATER; + } + } + // lhs == rhs, so true if operation is EQUAL + return op == cmSystemTools::OP_EQUAL; +} + +//---------------------------------------------------------------------------- bool cmSystemTools::RemoveRPath(std::string const& file, std::string* emsg, bool* removed) { @@ -2898,3 +2818,18 @@ bool cmSystemTools::CheckRPath(std::string const& file, return false; #endif } + +//---------------------------------------------------------------------------- +bool cmSystemTools::RepeatedRemoveDirectory(const char* dir) +{ + // Windows sometimes locks files temporarily so try a few times. + for(int i = 0; i < 10; ++i) + { + if(cmSystemTools::RemoveADirectory(dir)) + { + return true; + } + cmSystemTools::Delay(100); + } + return false; +} diff --git a/Source/cmSystemTools.h b/Source/cmSystemTools.h index 6364870..6f9147c 100644 --- a/Source/cmSystemTools.h +++ b/Source/cmSystemTools.h @@ -46,12 +46,6 @@ public: static void ExpandRegistryValues(std::string& source, KeyWOW64 view = KeyWOW64_Default); - /** - * Platform independent escape spaces, unix uses backslash, - * windows double quotes the string. - */ - static std::string EscapeSpaces(const char* str); - ///! Escape quotes in a string. static std::string EscapeQuotes(const char* str); @@ -109,6 +103,12 @@ 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(const char* val); /** * does a string indicate a true or on value ? This is not the same * as ifdef. @@ -268,6 +268,17 @@ public: UNKNOWN_FILE_FORMAT }; + enum CompareOp { + OP_LESS, + OP_GREATER, + OP_EQUAL + }; + + /** + * Compare versions + */ + static bool VersionCompare(CompareOp op, const char* lhs, const char* rhs); + /** * Determine the file type based on the extension */ @@ -347,6 +358,20 @@ public: AppendEnv to put the environment back to the way it was. */ static void RestoreEnv(const std::vector<std::string>& env); + + /** Helper class to save and restore the environment. + Instantiate this class as an automatic variable on + the stack. Its constructor saves a copy of the current + environment and then its destructor restores the + original environment. */ + class SaveRestoreEnvironment + { + public: + SaveRestoreEnvironment(); + virtual ~SaveRestoreEnvironment(); + private: + std::vector<std::string> Env; + }; #endif /** Setup the environment to enable VS 8 IDE output. */ @@ -411,6 +436,9 @@ public: static bool CheckRPath(std::string const& file, std::string const& newRPath); + /** Remove a directory; repeat a few times in case of locked files. */ + static bool RepeatedRemoveDirectory(const char* dir); + private: static bool s_ForceUnixPaths; static bool s_RunCommandHideConsole; diff --git a/Source/cmTarget.cxx b/Source/cmTarget.cxx index 0c8f14a..72efce3 100644 --- a/Source/cmTarget.cxx +++ b/Source/cmTarget.cxx @@ -16,7 +16,9 @@ #include "cmLocalGenerator.h" #include "cmGlobalGenerator.h" #include "cmComputeLinkInformation.h" +#include "cmDocumentCompileDefinitions.h" #include "cmListFileCache.h" +#include "cmGeneratorExpression.h" #include <cmsys/RegularExpression.hxx> #include <map> #include <set> @@ -145,14 +147,7 @@ void cmTarget::DefineProperties(cmake *cm) "are not supported by the native build tool. " "The VS6 IDE does not support definition values with spaces " "(but NMake does).\n" - "Dislaimer: Most native build tools have poor support for escaping " - "certain values. CMake has work-arounds for many cases but some " - "values may just not be possible to pass correctly. If a value " - "does not seem to be escaped correctly, do not attempt to " - "work-around the problem by adding escape sequences to the value. " - "Your work-around may break in a future version of CMake that " - "has improved escape support. Instead consider defining the macro " - "in a (configured) header file. Then report the limitation."); + CM_DOCUMENT_COMPILE_DEFINITIONS_DISCLAIMER); cm->DefineProperty ("COMPILE_DEFINITIONS_<CONFIG>", cmProperty::TARGET, @@ -202,7 +197,7 @@ void cmTarget::DefineProperties(cmake *cm) cm->DefineProperty ("HAS_CXX", cmProperty::TARGET, - "Link the target using the C++ linker tool (obselete).", + "Link the target using the C++ linker tool (obsolete).", "This is equivalent to setting the LINKER_LANGUAGE property to CXX. " "See that property's documentation for details."); @@ -393,6 +388,24 @@ void cmTarget::DefineProperties(cmake *cm) "from which the target is imported."); cm->DefineProperty + ("IMPORTED_NO_SONAME", cmProperty::TARGET, + "Specifies that an IMPORTED shared library target has no \"soname\". ", + "Set this property to true for an imported shared library file that " + "has no \"soname\" field. " + "CMake may adjust generated link commands for some platforms to prevent " + "the linker from using the path to the library in place of its missing " + "soname. " + "Ignored for non-imported targets."); + + cm->DefineProperty + ("IMPORTED_NO_SONAME_<CONFIG>", cmProperty::TARGET, + "Per-configuration version of IMPORTED_NO_SONAME property.", + "This property is used when loading settings for the <CONFIG> " + "configuration of an imported target. " + "Configuration names correspond to those provided by the project " + "from which the target is imported."); + + cm->DefineProperty ("EXCLUDE_FROM_ALL", cmProperty::TARGET, "Exclude the target from the all target.", "A property on a target that indicates if the target is excluded " @@ -482,6 +495,15 @@ void cmTarget::DefineProperties(cmake *cm) "value is the default. " "See documentation of CMAKE_<LANG>_LINKER_PREFERENCE variables."); +#define CM_LOCATION_UNDEFINED_BEHAVIOR \ + "\n" \ + "Do not set properties that affect the location of the target after " \ + "reading this property. These include properties whose names match " \ + "\"(RUNTIME|LIBRARY|ARCHIVE)_OUTPUT_(NAME|DIRECTORY)(_<CONFIG>)?\" " \ + "or \"(IMPLIB_)?(PREFIX|SUFFIX)\". " \ + "Failure to follow this rule is not diagnosed and leaves the location " \ + "of the target undefined." + cm->DefineProperty ("LOCATION", cmProperty::TARGET, "Read-only location of a target on disk.", @@ -498,7 +520,10 @@ void cmTarget::DefineProperties(cmake *cm) "In CMake 2.6 and above add_custom_command automatically recognizes a " "target name in its COMMAND and DEPENDS options and computes the " "target location. " - "Therefore this property is not needed for creating custom commands."); + "In CMake 2.8.4 and above add_custom_command recognizes generator " + "expressions to refer to target locations anywhere in the command. " + "Therefore this property is not needed for creating custom commands." + CM_LOCATION_UNDEFINED_BEHAVIOR); cm->DefineProperty ("LOCATION_<CONFIG>", cmProperty::TARGET, @@ -511,7 +536,20 @@ void cmTarget::DefineProperties(cmake *cm) "By default CMake looks for an exact-match but otherwise uses an " "arbitrary available configuration. " "Use the MAP_IMPORTED_CONFIG_<CONFIG> property to map imported " - "configurations explicitly."); + "configurations explicitly." + CM_LOCATION_UNDEFINED_BEHAVIOR); + + cm->DefineProperty + ("LINK_DEPENDS", cmProperty::TARGET, + "Additional files on which a target binary depends for linking.", + "Specifies a semicolon-separated list of full-paths to files on which " + "the link rule for this target depends. " + "The target binary will be linked if any of the named files is newer " + "than it." + "\n" + "This property is ignored by non-Makefile generators. " + "It is intended to specify dependencies on \"linker scripts\" for " + "custom Makefile link rules."); cm->DefineProperty ("LINK_INTERFACE_LIBRARIES", cmProperty::TARGET, @@ -708,6 +746,11 @@ void cmTarget::DefineProperties(cmake *cm) "Extra flags to use when linking a static library."); cm->DefineProperty + ("STATIC_LIBRARY_FLAGS_<CONFIG>", cmProperty::TARGET, + "Per-configuration flags for creating a static library.", + "This is the configuration-specific version of STATIC_LIBRARY_FLAGS."); + + cm->DefineProperty ("SUFFIX", cmProperty::TARGET, "What comes after the library name.", "A target property that can be set to override the suffix " @@ -811,12 +854,16 @@ void cmTarget::DefineProperties(cmake *cm) "executable with the TARGET_LINK_LIBRARIES command. " "On all platforms a target-level dependency on the executable is " "created for targets that link to it. " - "For non-DLL platforms the link rule is simply ignored since " - "the dynamic loader will automatically bind symbols when the " - "module is loaded. " "For DLL platforms an import library will be created for the " "exported symbols and then used for linking. " - "All Windows-based systems including Cygwin are DLL platforms."); + "All Windows-based systems including Cygwin are DLL platforms. " + "For non-DLL platforms that require all symbols to be resolved at " + "link time, such as Mac OS X, the module will \"link\" to the " + "executable using a flag like \"-bundle_loader\". " + "For other non-DLL platforms the link rule is simply ignored since " + "the dynamic loader will automatically bind symbols when the " + "module is loaded. " + ); cm->DefineProperty ("Fortran_MODULE_DIRECTORY", cmProperty::TARGET, @@ -849,10 +896,19 @@ void cmTarget::DefineProperties(cmake *cm) "set_source_files_properties command."); cm->DefineProperty + ("FOLDER", cmProperty::TARGET, + "Set the folder name. Use to organize targets in an IDE.", + "Targets with no FOLDER property will appear as top level " + "entities in IDEs like Visual Studio. Targets with the same " + "FOLDER property value will appear next to each other in a " + "folder of that name. To nest folders, use FOLDER values such " + "as 'GUI/Dialogs' with '/' characters separating folder levels."); + + cm->DefineProperty ("PROJECT_LABEL", cmProperty::TARGET, "Change the name of a target in an IDE.", "Can be used to change the name of the target in an IDE " - "like visual stuido. "); + "like Visual Studio. "); cm->DefineProperty ("VS_KEYWORD", cmProperty::TARGET, "Visual Studio project keyword.", @@ -1026,18 +1082,7 @@ void cmTarget::SetMakefile(cmMakefile* mf) // Collect the set of configuration types. std::vector<std::string> configNames; - if(const char* configurationTypes = - mf->GetDefinition("CMAKE_CONFIGURATION_TYPES")) - { - cmSystemTools::ExpandListArgument(configurationTypes, configNames); - } - else if(const char* buildType = mf->GetDefinition("CMAKE_BUILD_TYPE")) - { - if(*buildType) - { - configNames.push_back(buildType); - } - } + mf->GetConfigurations(configNames); // Setup per-configuration property default values. const char* configProps[] = { @@ -1320,8 +1365,8 @@ bool cmTargetTraceDependencies::IsUtility(std::string const& dep) util = cmSystemTools::GetFilenameWithoutLastExtension(util); } - // Check for a non-imported target with this name. - if(cmTarget* t = this->GlobalGenerator->FindTarget(0, util.c_str())) + // Check for a target with this name. + if(cmTarget* t = this->Makefile->FindTargetToUse(util.c_str())) { // If we find the target and the dep was given as a full path, // then make sure it was not a full path to something else, and @@ -1365,12 +1410,13 @@ cmTargetTraceDependencies { // Transform command names that reference targets built in this // project to corresponding target-level dependencies. + cmGeneratorExpression ge(this->Makefile, 0, cc.GetBacktrace(), true); for(cmCustomCommandLines::const_iterator cit = cc.GetCommandLines().begin(); cit != cc.GetCommandLines().end(); ++cit) { std::string const& command = *cit->begin(); - // Look for a non-imported target with this name. - if(cmTarget* t = this->GlobalGenerator->FindTarget(0, command.c_str())) + // Check for a target with this name. + if(cmTarget* t = this->Makefile->FindTargetToUse(command.c_str())) { if(t->GetType() == cmTarget::EXECUTABLE) { @@ -1381,6 +1427,21 @@ cmTargetTraceDependencies this->Target->AddUtility(command.c_str()); } } + + // Check for target references in generator expressions. + for(cmCustomCommandLine::const_iterator cli = cit->begin(); + cli != cit->end(); ++cli) + { + ge.Process(*cli); + } + } + + // Add target-level dependencies referenced by generator expressions. + std::set<cmTarget*> targets = ge.GetTargets(); + for(std::set<cmTarget*>::iterator ti = targets.begin(); + ti != targets.end(); ++ti) + { + this->Target->AddUtility((*ti)->GetName()); } // Queue the custom command dependencies. @@ -1413,6 +1474,15 @@ cmTargetTraceDependencies //---------------------------------------------------------------------------- void cmTarget::TraceDependencies(const char* vsProjectFile) { + // CMake-generated targets have no dependencies to trace. Normally tracing + // would find nothing anyway, but when building CMake itself the "install" + // target command ends up referencing the "cmake" target but we do not + // really want the dependency because "install" depend on "all" anyway. + if(this->GetType() == cmTarget::GLOBAL_TARGET) + { + return; + } + // Use a helper object to trace the dependencies. cmTargetTraceDependencies tracer(this, this->Internal.Get(), vsProjectFile); tracer.Trace(); @@ -1425,8 +1495,15 @@ bool cmTarget::FindSourceFiles() si = this->SourceFiles.begin(); si != this->SourceFiles.end(); ++si) { - if((*si)->GetFullPath().empty()) + std::string e; + if((*si)->GetFullPath(&e).empty()) { + if(!e.empty()) + { + cmake* cm = this->Makefile->GetCMakeInstance(); + cm->IssueMessage(cmake::FATAL_ERROR, e, + this->GetBacktrace()); + } return false; } } @@ -3089,13 +3166,13 @@ void cmTarget::GetFullNameInternal(const char* config, outBase += configPostfix?configPostfix:""; // Name shared libraries with their version number on some platforms. - if(const char* version = this->GetProperty("VERSION")) + if(const char* soversion = this->GetProperty("SOVERSION")) { if(this->GetType() == cmTarget::SHARED_LIBRARY && !implib && this->Makefile->IsOn("CMAKE_SHARED_LIBRARY_NAME_WITH_VERSION")) { outBase += "-"; - outBase += version; + outBase += soversion; } } @@ -3152,6 +3229,7 @@ void cmTarget::GetLibraryNames(std::string& name, // the library version as the soversion. soversion = version; } + bool isApple = this->Makefile->IsOn("APPLE"); // Get the components of the library name. std::string prefix; @@ -3163,26 +3241,33 @@ void cmTarget::GetLibraryNames(std::string& name, name = prefix+base+suffix; // The library's soname. -#if defined(__APPLE__) - soName = prefix+base; -#else - soName = name; -#endif + if(isApple) + { + soName = prefix+base; + } + else + { + soName = name; + } if(soversion) { soName += "."; soName += soversion; } -#if defined(__APPLE__) - soName += suffix; -#endif + if(isApple) + { + soName += suffix; + } // The library's real name on disk. -#if defined(__APPLE__) - realName = prefix+base; -#else + if(isApple) + { + realName = prefix+base; + } + else + { realName = name; -#endif + } if(version) { realName += "."; @@ -3193,9 +3278,10 @@ void cmTarget::GetLibraryNames(std::string& name, realName += "."; realName += soversion; } -#if defined(__APPLE__) - realName += suffix; -#endif + if(isApple) + { + realName += suffix; + } // The import library name. if(this->GetType() == cmTarget::SHARED_LIBRARY || diff --git a/Source/cmTargetDepend.h b/Source/cmTargetDepend.h new file mode 100644 index 0000000..258bacd --- /dev/null +++ b/Source/cmTargetDepend.h @@ -0,0 +1,48 @@ +/*============================================================================ + CMake - Cross Platform Makefile Generator + Copyright 2000-2010 Kitware, Inc., Insight Software Consortium + + Distributed under the OSI-approved BSD License (the "License"); + see accompanying file Copyright.txt for details. + + This software is distributed WITHOUT ANY WARRANTY; without even the + implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the License for more information. +============================================================================*/ +#ifndef cmTargetDepend_h +#define cmTargetDepend_h + +#include "cmStandardIncludes.h" + +class cmTarget; + +/** One edge in the global target dependency graph. + It may be marked as a 'link' or 'util' edge or both. */ +class cmTargetDepend +{ + cmTarget* Target; + + // The set order depends only on the Target, so we use + // mutable members to acheive a map with set syntax. + mutable bool Link; + mutable bool Util; +public: + cmTargetDepend(cmTarget* t): Target(t), Link(false), Util(false) {} + operator cmTarget*() const { return this->Target; } + cmTarget* operator->() const { return this->Target; } + cmTarget& operator*() const { return *this->Target; } + friend bool operator < (cmTargetDepend const& l, cmTargetDepend const& r) + { return l.Target < r.Target; } + void SetType(bool strong) const + { + if(strong) { this->Util = true; } + else { this->Link = true; } + } + bool IsLink() const { return this->Link; } + bool IsUtil() const { return this->Util; } +}; + +/** Unordered set of (direct) dependencies of a target. */ +class cmTargetDependSet: public std::set<cmTargetDepend> {}; + +#endif diff --git a/Source/cmTargetLinkLibrariesCommand.cxx b/Source/cmTargetLinkLibrariesCommand.cxx index f1f76c8..805959d 100644 --- a/Source/cmTargetLinkLibrariesCommand.cxx +++ b/Source/cmTargetLinkLibrariesCommand.cxx @@ -29,23 +29,64 @@ bool cmTargetLinkLibrariesCommand return false; } - // but we might not have any libs after variable expansion - if(args.size() < 2) - { - return true; - } - // Lookup the target for which libraries are specified. this->Target = this->Makefile->GetCMakeInstance() ->GetGlobalGenerator()->FindTarget(0, args[0].c_str()); if(!this->Target) { + cmake::MessageType t = cmake::FATAL_ERROR; // fail by default cmOStringStream e; e << "Cannot specify link libraries for target \"" << args[0] << "\" " << "which is not built by this project."; - this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str()); - cmSystemTools::SetFatalErrorOccured(); + // The bad target is the only argument. Check how policy CMP0016 is set, + // and accept, warn or fail respectively: + if (args.size() < 2) + { + switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0016)) + { + case cmPolicies::WARN: + t = cmake::AUTHOR_WARNING; + // Print the warning. + e << "\n" + << "CMake does not support this but it used to work accidentally " + << "and is being allowed for compatibility." + << "\n" << this->Makefile->GetPolicies()-> + GetPolicyWarning(cmPolicies::CMP0016); + break; + case cmPolicies::OLD: // OLD behavior does not warn. + t = cmake::MESSAGE; + break; + case cmPolicies::REQUIRED_IF_USED: + case cmPolicies::REQUIRED_ALWAYS: + e << "\n" << this->Makefile->GetPolicies()-> + GetRequiredPolicyError(cmPolicies::CMP0016); + break; + case cmPolicies::NEW: // NEW behavior prints the error. + default: + break; + } + } + + // now actually print the message + switch(t) + { + case cmake::AUTHOR_WARNING: + this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, e.str()); + break; + case cmake::FATAL_ERROR: + this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str()); + cmSystemTools::SetFatalErrorOccured(); + break; + default: + break; + } + return true; + } + + // but we might not have any libs after variable expansion + if(args.size() < 2) + { return true; } @@ -57,7 +98,7 @@ bool cmTargetLinkLibrariesCommand // specification when the keyword is encountered. this->DoingInterface = false; - // add libraries, nothe that there is an optional prefix + // add libraries, nothe that there is an optional prefix // of debug and optimized than can be used for(unsigned int i=1; i < args.size(); ++i) { @@ -118,7 +159,7 @@ bool cmTargetLinkLibrariesCommand llt = cmTarget::GENERAL; std::string linkType = args[0]; linkType += "_LINK_TYPE"; - const char* linkTypeString = + const char* linkTypeString = this->Makefile->GetDefinition( linkType.c_str() ); if(linkTypeString) { @@ -133,7 +174,7 @@ bool cmTargetLinkLibrariesCommand } this->HandleLibrary(args[i].c_str(), llt); } - } + } // Make sure the last argument was not a library type specifier. if(haveLLT) diff --git a/Source/cmTargetLinkLibrariesCommand.h b/Source/cmTargetLinkLibrariesCommand.h index 43a0d7c..ce57df7 100644 --- a/Source/cmTargetLinkLibrariesCommand.h +++ b/Source/cmTargetLinkLibrariesCommand.h @@ -62,6 +62,10 @@ public: " target_link_libraries(<target> [item1 [item2 [...]]]\n" " [[debug|optimized|general] <item>] ...)\n" "Specify libraries or flags to use when linking a given target. " + "The named <target> must have been created in the current directory " + "by a command such as add_executable or add_library. " + "The remaining arguments specify library names or flags." + "\n" "If a library name matches that of another target in the project " "a dependency will automatically be added in the build system to make " "sure the library being linked is up-to-date before the target links. " diff --git a/Source/cmTest.cxx b/Source/cmTest.cxx index b52bc19..c25a8b6 100644 --- a/Source/cmTest.cxx +++ b/Source/cmTest.cxx @@ -143,6 +143,12 @@ void cmTest::DefineProperties(cmake *cm) "The list is reported in dashboard submissions."); cm->DefineProperty + ("RESOURCE_LOCK", cmProperty::TEST, + "Specify a list of resources that are locked by this test.", + "If multiple tests specify the same resource lock, they are guaranteed " + "not to run concurrently."); + + cm->DefineProperty ("MEASUREMENT", cmProperty::TEST, "Specify a CDASH measurement and value to be reported for a test.", "If set to a name then that name will be reported to CDASH as a " @@ -190,4 +196,10 @@ void cmTest::DefineProperties(cmake *cm) "If set to true, this will invert the pass/fail flag of the test.", "This property can be used for tests that are expected to fail and " "return a non zero return code."); + + cm->DefineProperty + ("WORKING_DIRECTORY", cmProperty::TEST, + "The directory from which the test executable will be called.", + "If this is not set it is called from the directory the test executable " + "is located in."); } diff --git a/Source/cmTryCompileCommand.h b/Source/cmTryCompileCommand.h index 3a30e4c..0c67a8b 100644 --- a/Source/cmTryCompileCommand.h +++ b/Source/cmTryCompileCommand.h @@ -47,7 +47,7 @@ public: */ virtual const char* GetTerseDocumentation() { - return "Try compiling some code."; + return "Try building some code."; } /** @@ -55,23 +55,28 @@ public: virtual const char* GetFullDocumentation() { return - " try_compile(RESULT_VAR bindir srcdir\n" - " projectName <targetname> [CMAKE_FLAGS <Flags>]\n" - " [OUTPUT_VARIABLE var])\n" - "Try compiling a program. In this form, srcdir should contain a " - "complete CMake project with a CMakeLists.txt file and all sources. The " - "bindir and srcdir will not be deleted after this command is run. " - "If <target name> is specified then build just that target " - "otherwise the all or ALL_BUILD target is built.\n" - " try_compile(RESULT_VAR bindir srcfile\n" - " [CMAKE_FLAGS <Flags>]\n" - " [COMPILE_DEFINITIONS <flags> ...]\n" - " [OUTPUT_VARIABLE var]\n" - " [COPY_FILE <filename> )\n" - "Try compiling a srcfile. In this case, the user need only supply a " - "source file. CMake will create the appropriate CMakeLists.txt file " - "to build the source. If COPY_FILE is used, the compiled file will be " - "copied to the given file.\n" + " try_compile(RESULT_VAR <bindir> <srcdir>\n" + " <projectName> [targetName] [CMAKE_FLAGS flags...]\n" + " [OUTPUT_VARIABLE <var>])\n" + "Try building a project. In this form, srcdir should contain a " + "complete CMake project with a CMakeLists.txt file and all sources. " + "The bindir and srcdir will not be deleted after this command is run. " + "Specify targetName to build a specific target instead of the 'all' or " + "'ALL_BUILD' target." + "\n" + " try_compile(RESULT_VAR <bindir> <srcfile>\n" + " [CMAKE_FLAGS flags...]\n" + " [COMPILE_DEFINITIONS flags...]\n" + " [OUTPUT_VARIABLE <var>]\n" + " [COPY_FILE <fileName>])\n" + "Try building a source file into an executable. " + "In this form the user need only supply a source file that defines " + "a 'main'. " + "CMake will create a CMakeLists.txt file to build the source " + "as an executable. " + "Specify COPY_FILE to get a copy of the linked executable at the " + "given fileName." + "\n" "In this version all files in bindir/CMakeFiles/CMakeTmp, " "will be cleaned automatically, for debugging a --debug-trycompile can " "be passed to cmake to avoid the clean. Some extra flags that " @@ -94,7 +99,9 @@ public: "Return the success or failure in " "RESULT_VAR. CMAKE_FLAGS can be used to pass -DVAR:TYPE=VALUE flags " "to the cmake that is run during the build. " - ""; + "Set variable CMAKE_TRY_COMPILE_CONFIGURATION to choose a build " + "configuration." + ; } cmTypeMacro(cmTryCompileCommand, cmCoreTryCompile); diff --git a/Source/cmTryRunCommand.cxx b/Source/cmTryRunCommand.cxx index 3010fc9..4d31a14 100644 --- a/Source/cmTryRunCommand.cxx +++ b/Source/cmTryRunCommand.cxx @@ -361,7 +361,7 @@ void cmTryRunCommand::DoNotRunExecutable(const std::string& runArgs, std::string errorMessage = "TRY_RUN() invoked in cross-compiling mode, " "please set the following cache variables " - "appropriatly:\n"; + "appropriately:\n"; errorMessage += " " + this->RunResultVariable + " (advanced)\n"; if (out!=0) { diff --git a/Source/cmTryRunCommand.h b/Source/cmTryRunCommand.h index ca48e90..f86d863 100644 --- a/Source/cmTryRunCommand.h +++ b/Source/cmTryRunCommand.h @@ -93,7 +93,10 @@ public: "that when crosscompiling, the cache variables will have to be set " "manually to the output of the executable. You can also \"guard\" the " "calls to try_run with if(CMAKE_CROSSCOMPILING) and provide an " - "easy-to-preset alternative for this case.\n"; + "easy-to-preset alternative for this case.\n" + "Set variable CMAKE_TRY_COMPILE_CONFIGURATION to choose a build " + "configuration." + ; } cmTypeMacro(cmTryRunCommand, cmCoreTryCompile); diff --git a/Source/cmVersion.cxx b/Source/cmVersion.cxx index bde5f98..047d24d 100644 --- a/Source/cmVersion.cxx +++ b/Source/cmVersion.cxx @@ -16,8 +16,9 @@ unsigned int cmVersion::GetMajorVersion() { return CMake_VERSION_MAJOR; } unsigned int cmVersion::GetMinorVersion() { return CMake_VERSION_MINOR; } unsigned int cmVersion::GetPatchVersion() { return CMake_VERSION_PATCH; } +unsigned int cmVersion::GetTweakVersion() { return CMake_VERSION_TWEAK; } const char* cmVersion::GetCMakeVersion() { - return CMake_VERSION_FULL CMake_VERSION_RC_SUFFIX; + return CMake_VERSION; } diff --git a/Source/cmVersion.h b/Source/cmVersion.h index f267ab6..e313524 100644 --- a/Source/cmVersion.h +++ b/Source/cmVersion.h @@ -28,6 +28,7 @@ public: static unsigned int GetMajorVersion(); static unsigned int GetMinorVersion(); static unsigned int GetPatchVersion(); + static unsigned int GetTweakVersion(); static const char* GetCMakeVersion(); }; diff --git a/Source/cmVersionConfig.h.in b/Source/cmVersionConfig.h.in index ee6eca7..76bc8fe 100644 --- a/Source/cmVersionConfig.h.in +++ b/Source/cmVersionConfig.h.in @@ -12,4 +12,5 @@ #define CMake_VERSION_MAJOR @CMake_VERSION_MAJOR@ #define CMake_VERSION_MINOR @CMake_VERSION_MINOR@ #define CMake_VERSION_PATCH @CMake_VERSION_PATCH@ -#cmakedefine CMake_VERSION_RC @CMake_VERSION_RC@ +#define CMake_VERSION_TWEAK @CMake_VERSION_TWEAK@ +#define CMake_VERSION "@CMake_VERSION@" diff --git a/Source/cmVersionMacros.h b/Source/cmVersionMacros.h index 412db6d..67f58ca 100644 --- a/Source/cmVersionMacros.h +++ b/Source/cmVersionMacros.h @@ -14,22 +14,9 @@ #include "cmVersionConfig.h" -#define CMAKE_TO_STRING(x) CMAKE_TO_STRING0(x) -#define CMAKE_TO_STRING0(x) #x - -#define CMake_VERSION \ - CMAKE_TO_STRING(CMake_VERSION_MAJOR) "." \ - CMAKE_TO_STRING(CMake_VERSION_MINOR) - -#define CMake_VERSION_FULL \ - CMAKE_TO_STRING(CMake_VERSION_MAJOR) "." \ - CMAKE_TO_STRING(CMake_VERSION_MINOR) "." \ - CMAKE_TO_STRING(CMake_VERSION_PATCH) - -#if !(CMake_VERSION_MINOR & 1) && defined(CMake_VERSION_RC) -# define CMake_VERSION_RC_SUFFIX "-rc" CMAKE_TO_STRING(CMake_VERSION_RC) -#else -# define CMake_VERSION_RC_SUFFIX "" +#define CMake_VERSION_TWEAK_IS_RELEASE(tweak) ((tweak) < 20000000) +#if CMake_VERSION_TWEAK_IS_RELEASE(CMake_VERSION_TWEAK) +# define CMake_VERSION_IS_RELEASE 1 #endif #endif diff --git a/Source/cmVisualStudio10TargetGenerator.cxx b/Source/cmVisualStudio10TargetGenerator.cxx index 4a8e161..ab282b0 100644 --- a/Source/cmVisualStudio10TargetGenerator.cxx +++ b/Source/cmVisualStudio10TargetGenerator.cxx @@ -32,6 +32,30 @@ static std::string cmVS10EscapeXML(std::string arg) return arg; } +static std::string cmVS10EscapeComment(std::string comment) +{ + // MSBuild takes the CDATA of a <Message></Message> element and just + // does "echo $CDATA" with no escapes. We must encode the string. + // http://technet.microsoft.com/en-us/library/cc772462%28WS.10%29.aspx + std::string echoable; + for(std::string::iterator c = comment.begin(); c != comment.end(); ++c) + { + switch (*c) + { + case '\r': break; + case '\n': echoable += '\t'; break; + case '"': /* no break */ + case '|': /* no break */ + case '&': /* no break */ + case '<': /* no break */ + case '>': /* no break */ + case '^': echoable += '^'; /* no break */ + default: echoable += *c; break; + } + } + return echoable; +} + cmVisualStudio10TargetGenerator:: cmVisualStudio10TargetGenerator(cmTarget* target, cmGlobalVisualStudio10Generator* gg) @@ -125,7 +149,10 @@ void cmVisualStudio10TargetGenerator::Generate() ".vcxproj"); if(this->Target->GetType() <= cmTarget::MODULE_LIBRARY) { - this->ComputeClOptions(); + if(!this->ComputeClOptions()) + { + return; + } } cmMakefile* mf = this->Target->GetMakefile(); std::string path = mf->GetStartOutputDirectory(); @@ -155,6 +182,13 @@ void cmVisualStudio10TargetGenerator::Generate() this->WriteString("<Keyword>Win32Proj</Keyword>\n", 2); this->WriteString("<Platform>", 2); (*this->BuildFileStream) << this->Platform << "</Platform>\n"; + const char* projLabel = this->Target->GetProperty("PROJECT_LABEL"); + if(!projLabel) + { + projLabel = this->Name.c_str(); + } + this->WriteString("<ProjectName>", 2); + (*this->BuildFileStream) << projLabel << "</ProjectName>\n"; this->WriteString("</PropertyGroup>\n", 1); this->WriteString("<Import Project=" "\"$(VCTargetsPath)\\Microsoft.Cpp.Default.props\" />\n", @@ -210,6 +244,8 @@ void cmVisualStudio10TargetGenerator::WriteProjectConfigurations() void cmVisualStudio10TargetGenerator::WriteProjectConfigurationValues() { + cmGlobalVisualStudio10Generator* gg = + static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator); std::vector<std::string> *configs = static_cast<cmGlobalVisualStudio7Generator *> (this->GlobalGenerator)->GetConfigurations(); @@ -257,6 +293,13 @@ void cmVisualStudio10TargetGenerator::WriteProjectConfigurationValues() { this->WriteString("<CharacterSet>MultiByte</CharacterSet>\n", 2); } + if(const char* toolset = gg->GetPlatformToolset()) + { + std::string pts = "<PlatformToolset>"; + pts += toolset; + pts += "</PlatformToolset>\n"; + this->WriteString(pts.c_str(), 2); + } this->WriteString("</PropertyGroup>\n", 1); } } @@ -318,6 +361,7 @@ cmVisualStudio10TargetGenerator::WriteCustomRule(cmSourceFile* source, } cmLocalVisualStudio7Generator* lg = this->LocalGenerator; std::string comment = lg->ConstructComment(command); + comment = cmVS10EscapeComment(comment); std::vector<std::string> *configs = static_cast<cmGlobalVisualStudio7Generator *> (this->GlobalGenerator)->GetConfigurations(); @@ -332,15 +376,9 @@ cmVisualStudio10TargetGenerator::WriteCustomRule(cmSourceFile* source, i != configs->end(); ++i) { std::string script = - cmVS10EscapeXML( - lg->ConstructScript(command.GetCommandLines(), - command.GetWorkingDirectory(), - i->c_str(), - command.GetEscapeOldStyle(), - command.GetEscapeAllowMakeVars()) - ); + cmVS10EscapeXML(lg->ConstructScript(command, i->c_str())); this->WritePlatformConfigTag("Message",i->c_str(), 3); - (*this->BuildFileStream ) << comment << "</Message>\n"; + (*this->BuildFileStream ) << cmVS10EscapeXML(comment) << "</Message>\n"; this->WritePlatformConfigTag("Command", i->c_str(), 3); (*this->BuildFileStream ) << script << "</Command>\n"; this->WritePlatformConfigTag("AdditionalInputs", i->c_str(), 3); @@ -351,10 +389,12 @@ cmVisualStudio10TargetGenerator::WriteCustomRule(cmSourceFile* source, d != command.GetDepends().end(); ++d) { - std::string dep = this->LocalGenerator-> - GetRealDependency(d->c_str(), i->c_str()); - this->ConvertToWindowsSlash(dep); - (*this->BuildFileStream ) << ";" << dep; + std::string dep; + if(this->LocalGenerator->GetRealDependency(d->c_str(), i->c_str(), dep)) + { + this->ConvertToWindowsSlash(dep); + (*this->BuildFileStream ) << ";" << dep; + } } (*this->BuildFileStream ) << ";%(AdditionalInputs)</AdditionalInputs>\n"; this->WritePlatformConfigTag("Outputs", i->c_str(), 3); @@ -396,6 +436,7 @@ void cmVisualStudio10TargetGenerator::WriteGroups() std::vector<cmSourceFile*> customBuild; std::vector<cmSourceFile*> none; std::vector<cmSourceFile*> headers; + std::vector<cmSourceFile*> idls; std::vector<cmSourceFile*> resource; for(std::vector<cmSourceFile*>::const_iterator s = classes.begin(); @@ -418,7 +459,7 @@ void cmVisualStudio10TargetGenerator::WriteGroups() { clCompile.push_back(sf); } - if(strcmp(lang, "RC") == 0) + else if(strcmp(lang, "RC") == 0) { resource.push_back(sf); } @@ -430,17 +471,25 @@ void cmVisualStudio10TargetGenerator::WriteGroups() { headers.push_back(sf); } + else if(sf->GetExtension() == "idl") + { + idls.push_back(sf); + } else { none.push_back(sf); } } + + this->AddMissingSourceGroups(groupsUsed, sourceGroups); + // Write out group file std::string path = this->Makefile->GetStartOutputDirectory(); path += "/"; path += this->Name; path += ".vcxproj.filters"; cmGeneratedFileStream fout(path.c_str()); + fout.SetCopyIfDifferent(true); char magic[] = {0xEF,0xBB, 0xBF}; fout.write(magic, 3); cmGeneratedFileStream* save = this->BuildFileStream; @@ -454,6 +503,7 @@ void cmVisualStudio10TargetGenerator::WriteGroups() this->WriteGroupSources("ClCompile", clCompile, sourceGroups); this->WriteGroupSources("ClInclude", headers, sourceGroups); this->WriteGroupSources("ResourceCompile", resource, sourceGroups); + this->WriteGroupSources("Midl", idls, sourceGroups); this->WriteGroupSources("CustomBuild", customBuild, sourceGroups); this->WriteString("<ItemGroup>\n", 1); @@ -484,9 +534,60 @@ void cmVisualStudio10TargetGenerator::WriteGroups() this->WriteString("</Project>\n", 0); // restore stream pointer this->BuildFileStream = save; + + if (fout.Close()) + { + this->GlobalGenerator->FileReplacedDuringGenerate(path); + } } -void +// Add to groupsUsed empty source groups that have non-empty children. +void +cmVisualStudio10TargetGenerator::AddMissingSourceGroups( + std::set<cmSourceGroup*>& groupsUsed, + const std::vector<cmSourceGroup>& allGroups + ) +{ + for(std::vector<cmSourceGroup>::const_iterator current = allGroups.begin(); + current != allGroups.end(); ++current) + { + std::vector<cmSourceGroup> const& children = current->GetGroupChildren(); + if(children.empty()) + { + continue; // the group is really empty + } + + this->AddMissingSourceGroups(groupsUsed, children); + + cmSourceGroup* current_ptr = const_cast<cmSourceGroup*>(&(*current)); + if(groupsUsed.find(current_ptr) != groupsUsed.end()) + { + continue; // group has already been added to set + } + + // check if it least one of the group's descendants is not empty + // (at least one child must already have been added) + std::vector<cmSourceGroup>::const_iterator child_it = children.begin(); + while(child_it != children.end()) + { + cmSourceGroup* child_ptr = const_cast<cmSourceGroup*>(&(*child_it)); + if(groupsUsed.find(child_ptr) != groupsUsed.end()) + { + break; // found a child that was already added => add current group too + } + child_it++; + } + + if(child_it == children.end()) + { + continue; // no descendants have source files => ignore this group + } + + groupsUsed.insert(current_ptr); + } +} + +void cmVisualStudio10TargetGenerator:: WriteGroupSources(const char* name, std::vector<cmSourceFile*> const& sources, @@ -556,7 +657,7 @@ void cmVisualStudio10TargetGenerator::WriteObjSources() void cmVisualStudio10TargetGenerator::WriteCLSources() { - if(this->Target->GetType() > cmTarget::MODULE_LIBRARY) + if(this->Target->GetType() > cmTarget::UTILITY) { return; } @@ -575,6 +676,7 @@ void cmVisualStudio10TargetGenerator::WriteCLSources() const char* lang = (*source)->GetLanguage(); bool cl = lang && (strcmp(lang, "C") == 0 || strcmp(lang, "CXX") ==0); bool rc = lang && (strcmp(lang, "RC") == 0); + bool idl = (*source)->GetExtension() == "idl"; std::string sourceFile = (*source)->GetFullPath(); sourceFile = cmSystemTools::RelativePath( this->Makefile->GetCurrentOutputDirectory(), @@ -593,13 +695,17 @@ void cmVisualStudio10TargetGenerator::WriteCLSources() { this->WriteString("<ResourceCompile Include=\"", 2); } + else if(idl) + { + this->WriteString("<Midl Include=\"", 2); + } else { this->WriteString("<None Include=\"", 2); } (*this->BuildFileStream ) << sourceFile << "\""; // ouput any flags specific to this source file - if(cl && this->OutputSourceSpecificFlags(*source)) + if(!header && cl && this->OutputSourceSpecificFlags(*source)) { // if the source file has specific flags the tag // is ended on a new line @@ -705,7 +811,7 @@ bool cmVisualStudio10TargetGenerator::OutputSourceSpecificFlags( hasFlags = true; this->WriteString("<ObjectFileName>", 3); (*this->BuildFileStream ) - << "$(Configuration)/" << objectName << "</ObjectFileName>\n"; + << "$(IntDir)/" << objectName << "</ObjectFileName>\n"; } std::vector<std::string> *configs = static_cast<cmGlobalVisualStudio7Generator *> @@ -752,10 +858,12 @@ bool cmVisualStudio10TargetGenerator::OutputSourceSpecificFlags( void cmVisualStudio10TargetGenerator::WritePathAndIncrementalLinkOptions() { - if(this->Target->GetType() > cmTarget::MODULE_LIBRARY) + cmTarget::TargetType ttype = this->Target->GetType(); + if(ttype > cmTarget::GLOBAL_TARGET) { return; } + this->WriteString("<PropertyGroup>\n", 2); this->WriteString("<_ProjectFileVersion>10.0.20506.1" "</_ProjectFileVersion>\n", 3); @@ -765,36 +873,50 @@ void cmVisualStudio10TargetGenerator::WritePathAndIncrementalLinkOptions() for(std::vector<std::string>::iterator config = configs->begin(); config != configs->end(); ++config) { - std::string targetNameFull = - this->Target->GetFullName(config->c_str()); - std::string intermediateDir = this->LocalGenerator-> - GetTargetDirectory(*this->Target); - intermediateDir += "/"; - intermediateDir += *config; - intermediateDir += "/"; - this->ConvertToWindowsSlash(intermediateDir); - std::string outDir = this->Target->GetDirectory(config->c_str()); - this->ConvertToWindowsSlash(outDir); - this->WritePlatformConfigTag("OutDir", config->c_str(), 3); - *this->BuildFileStream << outDir - << "\\" - << "</OutDir>\n"; - this->WritePlatformConfigTag("IntDir", config->c_str(), 3); - *this->BuildFileStream << intermediateDir - << "</IntDir>\n"; - this->WritePlatformConfigTag("TargetName", config->c_str(), 3); - *this->BuildFileStream << cmSystemTools::GetFilenameWithoutExtension( - targetNameFull.c_str()) - << "</TargetName>\n"; - - this->WritePlatformConfigTag("TargetExt", config->c_str(), 3); - *this->BuildFileStream << cmSystemTools::GetFilenameLastExtension( - targetNameFull.c_str()) - << "</TargetExt>\n"; - this->OutputLinkIncremental(*config); + if(ttype >= cmTarget::UTILITY) + { + this->WritePlatformConfigTag("IntDir", config->c_str(), 3); + *this->BuildFileStream + << "$(Platform)\\$(Configuration)\\$(ProjectName)\\" + << "</IntDir>\n"; + } + else + { + std::string targetNameFull = + this->Target->GetFullName(config->c_str()); + std::string intermediateDir = this->LocalGenerator-> + GetTargetDirectory(*this->Target); + intermediateDir += "/"; + intermediateDir += *config; + intermediateDir += "/"; + this->ConvertToWindowsSlash(intermediateDir); + std::string outDir = this->Target->GetDirectory(config->c_str()); + this->ConvertToWindowsSlash(outDir); + + this->WritePlatformConfigTag("OutDir", config->c_str(), 3); + *this->BuildFileStream << outDir + << "\\" + << "</OutDir>\n"; + + this->WritePlatformConfigTag("IntDir", config->c_str(), 3); + *this->BuildFileStream << intermediateDir + << "</IntDir>\n"; + + this->WritePlatformConfigTag("TargetName", config->c_str(), 3); + *this->BuildFileStream + << cmSystemTools::GetFilenameWithoutLastExtension( + targetNameFull.c_str()) + << "</TargetName>\n"; + + this->WritePlatformConfigTag("TargetExt", config->c_str(), 3); + *this->BuildFileStream + << cmSystemTools::GetFilenameLastExtension(targetNameFull.c_str()) + << "</TargetExt>\n"; + + this->OutputLinkIncremental(*config); + } } this->WriteString("</PropertyGroup>\n", 2); - } @@ -854,6 +976,13 @@ OutputLinkIncremental(std::string const& configName) flags += " "; flags += targetLinkFlags; } + std::string flagsProp = "LINK_FLAGS_"; + flagsProp += CONFIG; + if(const char* flagsConfig = this->Target->GetProperty(flagsProp.c_str())) + { + flags += " "; + flags += flagsConfig; + } if(flags.find("INCREMENTAL:NO") != flags.npos) { incremental = "false"; @@ -864,19 +993,23 @@ OutputLinkIncremental(std::string const& configName) } //---------------------------------------------------------------------------- -void cmVisualStudio10TargetGenerator::ComputeClOptions() +bool cmVisualStudio10TargetGenerator::ComputeClOptions() { std::vector<std::string> const* configs = this->GlobalGenerator->GetConfigurations(); for(std::vector<std::string>::const_iterator i = configs->begin(); i != configs->end(); ++i) { - this->ComputeClOptions(*i); + if(!this->ComputeClOptions(*i)) + { + return false; + } } + return true; } //---------------------------------------------------------------------------- -void cmVisualStudio10TargetGenerator::ComputeClOptions( +bool cmVisualStudio10TargetGenerator::ComputeClOptions( std::string const& configName) { // much of this was copied from here: @@ -899,7 +1032,7 @@ void cmVisualStudio10TargetGenerator::ComputeClOptions( cmSystemTools::Error ("CMake can not determine linker language for target:", this->Name.c_str()); - return; + return false; } if(strcmp(linkLanguage, "C") == 0 || strcmp(linkLanguage, "CXX") == 0 || strcmp(linkLanguage, "Fortran") == 0) @@ -959,6 +1092,7 @@ void cmVisualStudio10TargetGenerator::ComputeClOptions( } this->ClOptions[configName] = pOptions.release(); + return true; } //---------------------------------------------------------------------------- @@ -971,6 +1105,15 @@ void cmVisualStudio10TargetGenerator::WriteClOptions( clOptions.OutputAdditionalOptions(*this->BuildFileStream, " ", ""); this->OutputIncludes(includes); clOptions.OutputFlagMap(*this->BuildFileStream, " "); + + // If not in debug mode, write the DebugInformationFormat field + // without value so PDBs don't get generated uselessly. + if(!clOptions.IsDebug()) + { + this->WriteString("<DebugInformationFormat>" + "</DebugInformationFormat>\n", 3); + } + clOptions.OutputPreprocessorDefinitions(*this->BuildFileStream, " ", "\n"); this->WriteString("<AssemblerListingLocation>", 3); @@ -1001,31 +1144,39 @@ OutputIncludes(std::vector<std::string> const & includes) void cmVisualStudio10TargetGenerator:: -WriteRCOptions(std::string const& , +WriteRCOptions(std::string const& configName, std::vector<std::string> const & includes) { this->WriteString("<ResourceCompile>\n", 2); + Options& clOptions = *(this->ClOptions[configName]); + clOptions.OutputPreprocessorDefinitions(*this->BuildFileStream, " ", + "\n"); this->OutputIncludes(includes); this->WriteString("</ResourceCompile>\n", 2); } -void cmVisualStudio10TargetGenerator::WriteLibOptions(std::string const& - ) +void +cmVisualStudio10TargetGenerator::WriteLibOptions(std::string const& config) { if(this->Target->GetType() != cmTarget::STATIC_LIBRARY) { return; } - if(const char* libflags = this->Target - ->GetProperty("STATIC_LIBRARY_FLAGS")) + const char* libflags = this->Target->GetProperty("STATIC_LIBRARY_FLAGS"); + std::string flagsConfigVar = "STATIC_LIBRARY_FLAGS_"; + flagsConfigVar += cmSystemTools::UpperCase(config); + const char* libflagsConfig = + this->Target->GetProperty(flagsConfigVar.c_str()); + if(libflags || libflagsConfig) { this->WriteString("<Lib>\n", 2); cmVisualStudioGeneratorOptions libOptions(this->LocalGenerator, 10, cmVisualStudioGeneratorOptions::Linker, cmVS10LibFlagTable, 0, this); - libOptions.Parse(libflags); + libOptions.Parse(libflags?libflags:""); + libOptions.Parse(libflagsConfig?libflagsConfig:""); libOptions.OutputAdditionalOptions(*this->BuildFileStream, " ", ""); libOptions.OutputFlagMap(*this->BuildFileStream, " "); this->WriteString("</Lib>\n", 2); @@ -1093,6 +1244,13 @@ void cmVisualStudio10TargetGenerator::WriteLinkOptions(std::string const& flags += " "; flags += targetLinkFlags; } + std::string flagsProp = "LINK_FLAGS_"; + flagsProp += CONFIG; + if(const char* flagsConfig = this->Target->GetProperty(flagsProp.c_str())) + { + flags += " "; + flags += flagsConfig; + } cmVisualStudioGeneratorOptions linkOptions(this->LocalGenerator, 10, cmVisualStudioGeneratorOptions::Linker, @@ -1250,11 +1408,20 @@ WriteMidlOptions(std::string const& /*config*/, { this->WriteString("<Midl>\n", 2); this->OutputIncludes(includes); + this->WriteString("<OutputDirectory>$(IntDir)</OutputDirectory>\n", 3); + this->WriteString("<HeaderFileName>%(Filename).h</HeaderFileName>\n", 3); + this->WriteString( + "<TypeLibraryName>%(Filename).tlb</TypeLibraryName>\n", 3); + this->WriteString( + "<InterfaceIdentifierFileName>" + "%(Filename)_i.c</InterfaceIdentifierFileName>\n", 3); + this->WriteString("<ProxyFileName>%(Filename)_p.c</ProxyFileName>\n",3); this->WriteString("</Midl>\n", 2); } - + + void cmVisualStudio10TargetGenerator::WriteItemDefinitionGroups() -{ +{ std::vector<std::string> *configs = static_cast<cmGlobalVisualStudio7Generator *> (this->GlobalGenerator)->GetConfigurations(); @@ -1319,16 +1486,11 @@ void cmVisualStudio10TargetGenerator::WriteEvent( script += pre; pre = "\n"; script += - cmVS10EscapeXML( - lg->ConstructScript(command.GetCommandLines(), - command.GetWorkingDirectory(), - configName.c_str(), - command.GetEscapeOldStyle(), - command.GetEscapeAllowMakeVars()) - ); + cmVS10EscapeXML(lg->ConstructScript(command, configName.c_str())); } + comment = cmVS10EscapeComment(comment); this->WriteString("<Message>",3); - (*this->BuildFileStream ) << comment << "</Message>\n"; + (*this->BuildFileStream ) << cmVS10EscapeXML(comment) << "</Message>\n"; this->WriteString("<Command>", 3); (*this->BuildFileStream ) << script; (*this->BuildFileStream ) << "</Command>" << "\n"; @@ -1339,10 +1501,13 @@ void cmVisualStudio10TargetGenerator::WriteEvent( void cmVisualStudio10TargetGenerator::WriteProjectReferences() { - cmGlobalGenerator::TargetDependSet& depends + cmGlobalGenerator::TargetDependSet const& unordered = this->GlobalGenerator->GetTargetDirectDepends(*this->Target); + typedef cmGlobalVisualStudioGenerator::OrderedTargetDependSet + OrderedTargetDependSet; + OrderedTargetDependSet depends(unordered); this->WriteString("<ItemGroup>\n", 1); - for( cmGlobalGenerator::TargetDependSet::const_iterator i = depends.begin(); + for( OrderedTargetDependSet::const_iterator i = depends.begin(); i != depends.end(); ++i) { cmTarget* dt = *i; diff --git a/Source/cmVisualStudio10TargetGenerator.h b/Source/cmVisualStudio10TargetGenerator.h index 989db71..c3c27f4 100644 --- a/Source/cmVisualStudio10TargetGenerator.h +++ b/Source/cmVisualStudio10TargetGenerator.h @@ -50,8 +50,8 @@ private: void WriteObjSources(); void WritePathAndIncrementalLinkOptions(); void WriteItemDefinitionGroups(); - void ComputeClOptions(); - void ComputeClOptions(std::string const& configName); + bool ComputeClOptions(); + bool ComputeClOptions(std::string const& configName); void WriteClOptions(std::string const& config, std::vector<std::string> const & includes); void WriteRCOptions(std::string const& config, @@ -77,6 +77,10 @@ private: void WriteGroupSources(const char* name, std::vector<cmSourceFile*> const& sources, std::vector<cmSourceGroup>& ); + void AddMissingSourceGroups(std::set<cmSourceGroup*>& groupsUsed, + const std::vector<cmSourceGroup>& allGroups); + + private: typedef cmVisualStudioGeneratorOptions Options; typedef std::map<cmStdString, Options*> OptionsMap; diff --git a/Source/cmVisualStudioGeneratorOptions.cxx b/Source/cmVisualStudioGeneratorOptions.cxx index 051cc1f..9acae0d 100644 --- a/Source/cmVisualStudioGeneratorOptions.cxx +++ b/Source/cmVisualStudioGeneratorOptions.cxx @@ -45,6 +45,10 @@ cmVisualStudioGeneratorOptions // Slash options are allowed for VS. this->AllowSlash = true; + + this->FortranRuntimeDebug = false; + this->FortranRuntimeDLL = false; + this->FortranRuntimeMT = false; } //---------------------------------------------------------------------------- @@ -81,17 +85,15 @@ void cmVisualStudioGeneratorOptions::SetVerboseMakefile(bool verbose) // was not given explicitly in the flags we want to add an attribute // to the generated project to disable logo suppression. Otherwise // the GUI default is to enable suppression. + // + // Avoid this on Visual Studio 10 (and later!) because it results in: + // "cl ... warning D9035: option 'nologo-' has been deprecated" + // if(verbose && + this->Version != 10 && this->FlagMap.find("SuppressStartupBanner") == this->FlagMap.end()) { - if(this->Version == 10) - { - this->FlagMap["SuppressStartupBanner"] = "false"; - } - else - { - this->FlagMap["SuppressStartupBanner"] = "FALSE"; - } + this->FlagMap["SuppressStartupBanner"] = "FALSE"; } } @@ -133,8 +135,55 @@ void cmVisualStudioGeneratorOptions::Parse(const char* flags) } //---------------------------------------------------------------------------- +void cmVisualStudioGeneratorOptions::ParseFinish() +{ + if(this->CurrentTool == FortranCompiler) + { + // "RuntimeLibrary" attribute values: + // "rtMultiThreaded", "0", /threads /libs:static + // "rtMultiThreadedDLL", "2", /threads /libs:dll + // "rtMultiThreadedDebug", "1", /threads /dbglibs /libs:static + // "rtMultiThreadedDebugDLL", "3", /threads /dbglibs /libs:dll + // These seem unimplemented by the IDE: + // "rtSingleThreaded", "4", /libs:static + // "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" : ""; + this->FlagMap["RuntimeLibrary"] = rl; + } +} + +//---------------------------------------------------------------------------- void cmVisualStudioGeneratorOptions::StoreUnknownFlag(const char* flag) { + // Look for Intel Fortran flags that do not map well in the flag table. + if(this->CurrentTool == FortranCompiler) + { + if(strcmp(flag, "/dbglibs") == 0) + { + this->FortranRuntimeDebug = true; + return; + } + if(strcmp(flag, "/threads") == 0) + { + this->FortranRuntimeMT = true; + return; + } + if(strcmp(flag, "/libs:dll") == 0) + { + this->FortranRuntimeDLL = true; + return; + } + if(strcmp(flag, "/libs:static") == 0) + { + this->FortranRuntimeDLL = false; + return; + } + } + // This option is not known. Store it in the output flags. this->FlagString += " "; this->FlagString += @@ -183,7 +232,7 @@ cmVisualStudioGeneratorOptions { fout << prefix << "PreprocessorDefinitions=\""; } - const char* comma = ""; + const char* sep = ""; for(std::vector<std::string>::const_iterator di = this->Defines.begin(); di != this->Defines.end(); ++di) { @@ -208,15 +257,8 @@ cmVisualStudioGeneratorOptions define = cmVisualStudioGeneratorOptionsEscapeForXML(define.c_str()); } // Store the flag in the project file. - fout << comma << define; - if(this->Version == 10) - { - comma = ";"; - } - else - { - comma = ","; - } + fout << sep << define; + sep = ";"; } if(this->Version == 10) { diff --git a/Source/cmVisualStudioGeneratorOptions.h b/Source/cmVisualStudioGeneratorOptions.h index f7d1a02..8619ba0 100644 --- a/Source/cmVisualStudioGeneratorOptions.h +++ b/Source/cmVisualStudioGeneratorOptions.h @@ -39,6 +39,7 @@ public: // Store options from command line flags. void Parse(const char* flags); + void ParseFinish(); // Fix the ExceptionHandling option to default to off. void FixExceptionHandlingDefault(); @@ -67,6 +68,10 @@ private: Tool CurrentTool; cmVisualStudio10TargetGenerator* TargetGenerator; + bool FortranRuntimeDebug; + bool FortranRuntimeDLL; + bool FortranRuntimeMT; + virtual void StoreUnknownFlag(const char* flag); }; diff --git a/Source/cmWin32ProcessExecution.cxx b/Source/cmWin32ProcessExecution.cxx index c8b4ae4..f37e0ff 100644 --- a/Source/cmWin32ProcessExecution.cxx +++ b/Source/cmWin32ProcessExecution.cxx @@ -22,7 +22,8 @@ #if defined(__BORLANDC__) # define STRICMP stricmp # define TO_INTPTR(x) ((long)(x)) -#else // Visual studio +#endif // Borland +#if defined(_MSC_VER) // Visual studio # if ( _MSC_VER >= 1300 ) # include <stddef.h> # define TO_INTPTR(x) ((intptr_t)(x)) @@ -30,7 +31,12 @@ # define TO_INTPTR(x) ((long)(x)) # endif // Visual studio .NET # define STRICMP _stricmp -#endif // Borland +#endif // Visual Studio +#if defined(__MINGW32__) +# include <stdint.h> +# define TO_INTPTR(x) ((intptr_t)(x)) +# define STRICMP _stricmp +#endif // MinGW #define POPEN_1 1 #define POPEN_2 2 @@ -284,7 +290,8 @@ static BOOL RealPopenCreateProcess(const char *cmdstring, { PROCESS_INFORMATION piProcInfo; STARTUPINFO siStartInfo; - char *s1=0,*s2=0, *s3 = " /c "; + char *s1=0,*s2=0; + const char *s3 = " /c "; int i = GetEnvironmentVariable("COMSPEC",NULL,0); if (i) { diff --git a/Source/cmWriteFileCommand.cxx b/Source/cmWriteFileCommand.cxx index 5c5ad2e..b2acb2b 100644 --- a/Source/cmWriteFileCommand.cxx +++ b/Source/cmWriteFileCommand.cxx @@ -54,26 +54,18 @@ bool cmWriteFileCommand std::string dir = cmSystemTools::GetFilenamePath(fileName); cmSystemTools::MakeDirectory(dir.c_str()); - mode_t mode = -#if defined( _MSC_VER ) || defined( __MINGW32__ ) - S_IREAD | S_IWRITE -#elif defined( __BORLANDC__ ) - S_IRUSR | S_IWUSR -#else - S_IRUSR | S_IWUSR | - S_IRGRP | - S_IROTH -#endif - ; + mode_t mode = 0; // Set permissions to writable if ( cmSystemTools::GetPermissions(fileName.c_str(), mode) ) { cmSystemTools::SetPermissions(fileName.c_str(), #if defined( _MSC_VER ) || defined( __MINGW32__ ) - S_IREAD | S_IWRITE + mode | S_IWRITE +#elif defined( __BORLANDC__ ) + mode | S_IWUSR #else - S_IRUSR | S_IWUSR + mode | S_IWUSR | S_IWGRP #endif ); } @@ -91,7 +83,10 @@ bool cmWriteFileCommand } file << message << std::endl; file.close(); - cmSystemTools::SetPermissions(fileName.c_str(), mode); + if(mode) + { + cmSystemTools::SetPermissions(fileName.c_str(), mode); + } return true; } diff --git a/Source/cmXCodeObject.cxx b/Source/cmXCodeObject.cxx index 07c7b8c..5920470 100644 --- a/Source/cmXCodeObject.cxx +++ b/Source/cmXCodeObject.cxx @@ -236,7 +236,7 @@ void cmXCodeObject::PrintString(std::ostream& os) const // considered special by the Xcode project file parser. bool needQuote = (this->String.empty() || - this->String.find_first_of(" <>.+-=@") != this->String.npos); + this->String.find_first_of(" <>.+-=@$") != this->String.npos); const char* quote = needQuote? "\"" : ""; // Print the string, quoted and escaped as necessary. diff --git a/Source/cm_utf8.c b/Source/cm_utf8.c index 3d4ca16..c9bf259 100644 --- a/Source/cm_utf8.c +++ b/Source/cm_utf8.c @@ -50,7 +50,7 @@ const char* cm_utf8_decode_character(const char* first, const char* last, unsigned int* pc) { /* Count leading ones in the first byte. */ - unsigned char c = *first++; + unsigned char c = (unsigned char)*first++; unsigned char const ones = cm_utf8_ones[c]; switch(ones) { @@ -62,10 +62,10 @@ const char* cm_utf8_decode_character(const char* first, const char* last, /* Extract bits from this multi-byte character. */ { unsigned int uc = c & cm_utf8_mask[ones]; - unsigned char left; + int left; for(left = ones-1; left && first != last; --left) { - c = *first++; + c = (unsigned char)*first++; if(cm_utf8_ones[c] != 1) { return 0; diff --git a/Source/cmake.cxx b/Source/cmake.cxx index a01e0e0..1b49837 100644 --- a/Source/cmake.cxx +++ b/Source/cmake.cxx @@ -26,6 +26,7 @@ #include "cmDocumentationFormatterText.h" #if defined(CMAKE_BUILD_WITH_CMAKE) +# include "cmGraphVizWriter.h" # include "cmDependsFortran.h" // For -E cmake_copy_f90_mod callback. # include "cmVariableWatch.h" # include <cmsys/Terminal.h> @@ -82,7 +83,7 @@ #include "cmCallVisualStudioMacro.h" #endif -#if !defined(__CYGWIN__) && !defined(CMAKE_BOOT_MINGW) +#if !defined(CMAKE_BOOT_MINGW) # include "cmExtraCodeBlocksGenerator.h" #endif @@ -162,16 +163,6 @@ cmake::cmake() } #endif - // If MAKEFLAGS are given in the environment, remove the environment - // variable. This will prevent try-compile from succeeding when it - // should fail (if "-i" is an option). We cannot simply test - // whether "-i" is given and remove it because some make programs - // encode the MAKEFLAGS variable in a strange way. - if(getenv("MAKEFLAGS")) - { - cmSystemTools::PutEnv("MAKEFLAGS="); - } - this->Verbose = false; this->InTryCompile = false; this->CacheManager = new cmCacheManager(this); @@ -179,7 +170,7 @@ cmake::cmake() this->ProgressCallback = 0; this->ProgressCallbackClientData = 0; this->ScriptMode = false; - + #ifdef CMAKE_BUILD_WITH_CMAKE this->VariableWatch = new cmVariableWatch; this->VariableWatch->AddWatch("CMAKE_WORDS_BIGENDIAN", @@ -372,8 +363,7 @@ bool cmake::SetCacheArgs(const std::vector<std::string>& args) } std::string var, value; cmCacheManager::CacheEntryType type = cmCacheManager::UNINITIALIZED; - if(cmCacheManager::ParseEntry(entry.c_str(), var, value, type) || - cmCacheManager::ParseEntry(entry.c_str(), var, value)) + if(cmCacheManager::ParseEntry(entry.c_str(), var, value, type)) { this->CacheManager->AddCacheEntry(var.c_str(), value.c_str(), "No help, variable specified on the command line.", type); @@ -392,7 +382,7 @@ bool cmake::SetCacheArgs(const std::vector<std::string>& args) this->DoSuppressDevWarnings = true; } else if(arg.find("-Wdev",0) == 0) - { + { this->SuppressDevWarnings = false; this->DoSuppressDevWarnings = true; } @@ -416,7 +406,7 @@ bool cmake::SetCacheArgs(const std::vector<std::string>& args) cmsys::Glob::PatternToRegex(entryPattern.c_str(), true, true).c_str()); //go through all cache entries and collect the vars which will be removed std::vector<std::string> entriesToDelete; - cmCacheManager::CacheIterator it = + cmCacheManager::CacheIterator it = this->CacheManager->GetCacheIterator(); for ( it.Begin(); !it.IsAtEnd(); it.Next() ) { @@ -432,8 +422,8 @@ bool cmake::SetCacheArgs(const std::vector<std::string>& args) } // now remove them from the cache - for(std::vector<std::string>::const_iterator currentEntry = - entriesToDelete.begin(); + for(std::vector<std::string>::const_iterator currentEntry = + entriesToDelete.begin(); currentEntry != entriesToDelete.end(); ++currentEntry) { @@ -801,7 +791,7 @@ int cmake::AddCMakePaths() cMakeSelf += "/cmake"; std::cerr << cMakeSelf.c_str() << "\n"; } -#endif +#endif if(!cmSystemTools::FileExists(cMakeSelf.c_str())) { cmSystemTools::Error("CMake executable cannot be found at ", @@ -812,12 +802,12 @@ int cmake::AddCMakePaths() this->CacheManager->AddCacheEntry ("CMAKE_COMMAND",cMakeSelf.c_str(), "Path to CMake executable.", cmCacheManager::INTERNAL); - // if the edit command is not yet in the cache, + // if the edit command is not yet in the cache, // or if CMakeEditCommand has been set on this object, // then set the CMAKE_EDIT_COMMAND in the cache // This will mean that the last gui to edit the cache // will be the one that make edit_cache uses. - if(!this->GetCacheDefinition("CMAKE_EDIT_COMMAND") + if(!this->GetCacheDefinition("CMAKE_EDIT_COMMAND") || !this->CMakeEditCommand.empty()) { // Find and save the command to edit the cache @@ -825,8 +815,8 @@ int cmake::AddCMakePaths() if(!this->CMakeEditCommand.empty()) { editCacheCommand = cmSystemTools::GetFilenamePath(cMakeSelf) - + std::string("/") - + this->CMakeEditCommand + + std::string("/") + + this->CMakeEditCommand + cmSystemTools::GetFilenameExtension(cMakeSelf); } if( !cmSystemTools::FileExists(editCacheCommand.c_str())) @@ -946,7 +936,7 @@ void CMakeCommandUsage(const char* program) errorStream << "cmake bootstrap\n"; #endif - // If you add new commands, change here, + // If you add new commands, change here, // and in cmakemain.cxx in the options table errorStream << "Usage: " << program << " -E [command] [arguments ...]\n" @@ -964,7 +954,7 @@ void CMakeCommandUsage(const char* program) << " echo [string]... - displays arguments as text\n" << " echo_append [string]... - displays arguments as text but no new " "line\n" - << " environment - display the current enviroment\n" + << " environment - display the current environment\n" << " make_directory dir - create a directory\n" << " md5sum file1 [...] - compute md5sum of files\n" << " remove_directory dir - remove a directory and its contents\n" @@ -1101,7 +1091,7 @@ int cmake::ExecuteCMakeCommand(std::vector<std::string>& args) return 0; } #endif - + else if (args[1] == "make_directory" && args.size() == 3) { if(!cmSystemTools::MakeDirectory(args[2].c_str())) @@ -1352,7 +1342,7 @@ int cmake::ExecuteCMakeCommand(std::vector<std::string>& args) } return 0; } - + // Command to create a symbolic link. Fails on platforms not // supporting them. else if (args[1] == "create_symlink" && args.size() == 4) @@ -1418,8 +1408,10 @@ int cmake::ExecuteCMakeCommand(std::vector<std::string>& args) else if (args[1] == "cmake_depends" && args.size() >= 6) { // Use the make system's VERBOSE environment variable to enable - // verbose output. - bool verbose = cmSystemTools::GetEnv("VERBOSE") != 0; + // verbose output. This can be skipped by also setting CMAKE_NO_VERBOSE + // (which is set by the Eclipse and KDevelop generators). + bool verbose = ((cmSystemTools::GetEnv("VERBOSE") != 0) + && (cmSystemTools::GetEnv("CMAKE_NO_VERBOSE") == 0)); // Create a cmake object instance to process dependencies. cmake cm; @@ -1582,6 +1574,24 @@ int cmake::ExecuteCMakeCommand(std::vector<std::string>& args) cmSystemTools::Error("Problem extracting tar: ", outFile.c_str()); return 1; } +#ifdef WIN32 + // OK, on windows 7 after we untar some files, + // sometimes we can not rename the directory after + // the untar is done. This breaks the external project + // untar and rename code. So, by default we will wait + // 1/10th of a second after the untar. If CMAKE_UNTAR_DELAY + // is set in the env, its value will be used instead of 100. + int delay = 100; + const char* delayVar = cmSystemTools::GetEnv("CMAKE_UNTAR_DELAY"); + if(delayVar) + { + delay = atoi(delayVar); + } + if(delay) + { + cmSystemTools::Delay(delay); + } +#endif } return 0; } @@ -1625,14 +1635,14 @@ int cmake::ExecuteCMakeCommand(std::vector<std::string>& args) return 1; } -void cmake::AddExtraGenerator(const char* name, +void cmake::AddExtraGenerator(const char* name, CreateExtraGeneratorFunctionType newFunction) { cmExternalMakefileProjectGenerator* extraGenerator = newFunction(); const std::vector<std::string>& supportedGlobalGenerators = extraGenerator->GetSupportedGlobalGenerators(); - for(std::vector<std::string>::const_iterator + for(std::vector<std::string>::const_iterator it = supportedGlobalGenerators.begin(); it != supportedGlobalGenerators.end(); ++it ) @@ -1651,10 +1661,8 @@ void cmake::AddDefaultExtraGenerators() // e.g. kdevelop4 ? #endif -#if !defined(__CYGWIN__) this->AddExtraGenerator(cmExtraCodeBlocksGenerator::GetActualName(), &cmExtraCodeBlocksGenerator::New); -#endif #ifdef CMAKE_USE_ECLIPSE this->AddExtraGenerator(cmExtraEclipseCDT4Generator::GetActualName(), @@ -1662,11 +1670,11 @@ void cmake::AddDefaultExtraGenerators() #endif #ifdef CMAKE_USE_KDEVELOP - this->AddExtraGenerator(cmGlobalKdevelopGenerator::GetActualName(), + this->AddExtraGenerator(cmGlobalKdevelopGenerator::GetActualName(), &cmGlobalKdevelopGenerator::New); - // for kdevelop also add the generator with just the name of the + // for kdevelop also add the generator with just the name of the // extra generator, since it was this way since cmake 2.2 - this->ExtraGenerators[cmGlobalKdevelopGenerator::GetActualName()] + this->ExtraGenerators[cmGlobalKdevelopGenerator::GetActualName()] = &cmGlobalKdevelopGenerator::New; #endif @@ -1682,7 +1690,7 @@ void cmake::GetRegisteredGenerators(std::vector<std::string>& names) { names.push_back(i->first); } - for(RegisteredExtraGeneratorsMap::const_iterator + for(RegisteredExtraGeneratorsMap::const_iterator i = this->ExtraGenerators.begin(); i != this->ExtraGenerators.end(); ++i) { @@ -1820,7 +1828,7 @@ int cmake::DoPreConfigureChecks() // do a sanity check on some values if(this->CacheManager->GetCacheValue("CMAKE_HOME_DIRECTORY")) { - std::string cacheStart = + std::string cacheStart = this->CacheManager->GetCacheValue("CMAKE_HOME_DIRECTORY"); cacheStart += "/CMakeLists.txt"; std::string currentStart = this->GetHomeDirectory(); @@ -1864,13 +1872,13 @@ int cmake::HandleDeleteCacheVariables(const char* var) cmCacheManager::CacheIterator ci = this->CacheManager->NewIterator(); std::vector<SaveCacheEntry> saved; cmOStringStream warning; - warning + warning << "You have changed variables that require your cache to be deleted.\n" << "Configure will be re-run and you may have to reset some variables.\n" << "The following variables have changed:\n"; for(std::vector<std::string>::iterator i = argsSplit.begin(); i != argsSplit.end(); ++i) - { + { SaveCacheEntry save; save.key = *i; warning << *i << "= "; @@ -1884,7 +1892,7 @@ int cmake::HandleDeleteCacheVariables(const char* var) } saved.push_back(save); } - + // remove the cache this->CacheManager->DeleteCache(this->GetStartOutputDirectory()); // load the empty cache @@ -1956,7 +1964,7 @@ int cmake::ActualConfigure() if ( !res ) { this->CacheManager->AddCacheEntry - ("CMAKE_HOME_DIRECTORY", + ("CMAKE_HOME_DIRECTORY", this->GetHomeDirectory(), "Start directory with the top level CMakeLists.txt file for this " "project", @@ -1966,9 +1974,9 @@ int cmake::ActualConfigure() // no generator specified on the command line if(!this->GlobalGenerator) { - const char* genName = + const char* genName = this->CacheManager->GetCacheValue("CMAKE_GENERATOR"); - const char* extraGenName = + const char* extraGenName = this->CacheManager->GetCacheValue("CMAKE_EXTRA_GENERATOR"); if(genName) { @@ -1990,7 +1998,7 @@ int cmake::ActualConfigure() this->SetGlobalGenerator(new cmGlobalBorlandMakefileGenerator); #elif defined(_WIN32) && !defined(__CYGWIN__) && !defined(CMAKE_BOOT_MINGW) std::string installedCompiler; - // Try to find the newest VS installed on the computer and + // Try to find the newest VS installed on the computer and // use that as a default if -G is not specified std::string vsregBase = "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\"; @@ -2054,11 +2062,11 @@ int cmake::ActualConfigure() } if(!this->CacheManager->GetCacheValue("CMAKE_GENERATOR")) { - this->CacheManager->AddCacheEntry("CMAKE_GENERATOR", + this->CacheManager->AddCacheEntry("CMAKE_GENERATOR", this->GlobalGenerator->GetName(), "Name of generator.", cmCacheManager::INTERNAL); - this->CacheManager->AddCacheEntry("CMAKE_EXTRA_GENERATOR", + this->CacheManager->AddCacheEntry("CMAKE_EXTRA_GENERATOR", this->GlobalGenerator->GetExtraGeneratorName(), "Name of external makefile project generator.", cmCacheManager::INTERNAL); @@ -2197,7 +2205,7 @@ int cmake::Run(const std::vector<std::string>& args, bool noconfigure) // set the cmake command this->CMakeCommand = args[0]; - + if ( !this->ScriptMode ) { // load the cache @@ -2231,6 +2239,16 @@ int cmake::Run(const std::vector<std::string>& args, bool noconfigure) } } + // If MAKEFLAGS are given in the environment, remove the environment + // variable. This will prevent try-compile from succeeding when it + // should fail (if "-i" is an option). We cannot simply test + // whether "-i" is given and remove it because some make programs + // encode the MAKEFLAGS variable in a strange way. + if(getenv("MAKEFLAGS")) + { + cmSystemTools::PutEnv("MAKEFLAGS="); + } + this->PreLoadCMakeFiles(); std::string systemFile = this->GetHomeOutputDirectory(); @@ -2312,7 +2330,7 @@ void cmake::AddCacheEntry(const char* key, const char* value, const char* helpString, int type) { - this->CacheManager->AddCacheEntry(key, value, + this->CacheManager->AddCacheEntry(key, value, helpString, cmCacheManager::CacheEntryType(type)); } @@ -2427,8 +2445,8 @@ void cmake::UpdateProgress(const char *msg, float prog) } } -void cmake::GetCommandDocumentation(std::vector<cmDocumentationEntry>& v, - bool withCurrentCommands, +void cmake::GetCommandDocumentation(std::vector<cmDocumentationEntry>& v, + bool withCurrentCommands, bool withCompatCommands) const { for(RegisteredCommandsMap::const_iterator j = this->Commands.begin(); @@ -2439,7 +2457,7 @@ void cmake::GetCommandDocumentation(std::vector<cmDocumentationEntry>& v, { continue; } - + cmDocumentationEntry e((*j).second->GetName(), (*j).second->GetTerseDocumentation(), (*j).second->GetFullDocumentation()); @@ -2475,7 +2493,7 @@ void cmake::GetGeneratorDocumentation(std::vector<cmDocumentationEntry>& v) delete generator; v.push_back(e); } - for(RegisteredExtraGeneratorsMap::const_iterator + for(RegisteredExtraGeneratorsMap::const_iterator i = this->ExtraGenerators.begin(); i != this->ExtraGenerators.end(); ++i) { cmDocumentationEntry e; @@ -2490,7 +2508,7 @@ void cmake::GetGeneratorDocumentation(std::vector<cmDocumentationEntry>& v) void cmake::UpdateConversionPathTable() { // Update the path conversion table with any specified file: - const char* tablepath = + const char* tablepath = this->CacheManager->GetCacheValue("CMAKE_PATH_TRANSLATION_FILE"); if(tablepath) @@ -2520,16 +2538,18 @@ int cmake::CheckBuildSystem() { // We do not need to rerun CMake. Check dependency integrity. Use // the make system's VERBOSE environment variable to enable verbose - // output. - bool verbose = cmSystemTools::GetEnv("VERBOSE") != 0; - + // output. This can be skipped by setting CMAKE_NO_VERBOSE (which is set + // by the Eclipse and KDevelop generators). + bool verbose = ((cmSystemTools::GetEnv("VERBOSE") != 0) + && (cmSystemTools::GetEnv("CMAKE_NO_VERBOSE") == 0)); + // This method will check the integrity of the build system if the // option was given on the command line. It reads the given file to // determine whether CMake should rerun. // If no file is provided for the check, we have to rerun. if(this->CheckBuildSystemArgument.size() == 0) - { + { if(verbose) { cmOStringStream msg; @@ -2545,7 +2565,7 @@ int cmake::CheckBuildSystem() if(verbose) { cmOStringStream msg; - msg << "Re-run cmake missing file: " + msg << "Re-run cmake missing file: " << this->CheckBuildSystemArgument.c_str() << "\n"; cmSystemTools::Stdout(msg.str().c_str()); } @@ -2565,7 +2585,7 @@ int cmake::CheckBuildSystem() if(verbose) { cmOStringStream msg; - msg << "Re-run cmake error reading : " + msg << "Re-run cmake error reading : " << this->CheckBuildSystemArgument.c_str() << "\n"; cmSystemTools::Stdout(msg.str().c_str()); } @@ -2815,253 +2835,27 @@ const char* cmake::GetCPackCommand() return this->CPackCommand.c_str(); } + void cmake::GenerateGraphViz(const char* fileName) const { - cmGeneratedFileStream str(fileName); - if ( !str ) - { - return; - } - cmake cm; - cmGlobalGenerator ggi; - ggi.SetCMakeInstance(&cm); - std::auto_ptr<cmLocalGenerator> lg(ggi.CreateLocalGenerator()); - cmMakefile *mf = lg->GetMakefile(); - - std::string infile = this->GetHomeOutputDirectory(); - infile += "/CMakeGraphVizOptions.cmake"; - if ( !cmSystemTools::FileExists(infile.c_str()) ) - { - infile = this->GetHomeDirectory(); - infile += "/CMakeGraphVizOptions.cmake"; - if ( !cmSystemTools::FileExists(infile.c_str()) ) - { - infile = ""; - } - } - - if ( !infile.empty() ) - { - if ( !mf->ReadListFile(0, infile.c_str()) ) - { - cmSystemTools::Error("Problem opening GraphViz options file: ", - infile.c_str()); - return; - } - std::cout << "Read GraphViz options file: " << infile.c_str() - << std::endl; - } - -#define __set_if_not_set(var, value, cmakeDefinition) \ - const char* var = mf->GetDefinition(cmakeDefinition); \ - if ( !var ) \ - { \ - var = value; \ - } - __set_if_not_set(graphType, "digraph", "GRAPHVIZ_GRAPH_TYPE"); - __set_if_not_set(graphName, "GG", "GRAPHVIZ_GRAPH_NAME"); - __set_if_not_set(graphHeader, "node [\n fontsize = \"12\"\n];", - "GRAPHVIZ_GRAPH_HEADER"); - __set_if_not_set(graphNodePrefix, "node", "GRAPHVIZ_NODE_PREFIX"); - const char* ignoreTargets = mf->GetDefinition("GRAPHVIZ_IGNORE_TARGETS"); - std::set<cmStdString> ignoreTargetsSet; - if ( ignoreTargets ) - { - std::vector<std::string> ignoreTargetsVector; - cmSystemTools::ExpandListArgument(ignoreTargets,ignoreTargetsVector); - std::vector<std::string>::iterator itvIt; - for ( itvIt = ignoreTargetsVector.begin(); - itvIt != ignoreTargetsVector.end(); - ++ itvIt ) - { - ignoreTargetsSet.insert(itvIt->c_str()); - } - } - - str << graphType << " " << graphName << " {" << std::endl; - str << graphHeader << std::endl; - - const cmGlobalGenerator* gg = this->GetGlobalGenerator(); - const std::vector<cmLocalGenerator*>& localGenerators = - gg->GetLocalGenerators(); - std::vector<cmLocalGenerator*>::const_iterator lit; - // for target deps - // 1 - cmake target - // 2 - external target - // 0 - no deps - std::map<cmStdString, int> targetDeps; - std::map<cmStdString, const cmTarget*> targetPtrs; - std::map<cmStdString, cmStdString> targetNamesNodes; - int cnt = 0; - // First pass get the list of all cmake targets - for ( lit = localGenerators.begin(); lit != localGenerators.end(); ++ lit ) - { - const cmTargets* targets = &((*lit)->GetMakefile()->GetTargets()); - cmTargets::const_iterator tit; - for ( tit = targets->begin(); tit != targets->end(); ++ tit ) - { - const char* realTargetName = tit->first.c_str(); - if ( ignoreTargetsSet.find(realTargetName) != ignoreTargetsSet.end() ) - { - // Skip ignored targets - continue; - } - //std::cout << "Found target: " << tit->first.c_str() << std::endl; - cmOStringStream ostr; - ostr << graphNodePrefix << cnt++; - targetNamesNodes[realTargetName] = ostr.str(); - targetPtrs[realTargetName] = &tit->second; - } - } - // Ok, now find all the stuff we link to that is not in cmake - for ( lit = localGenerators.begin(); lit != localGenerators.end(); ++ lit ) - { - const cmTargets* targets = &((*lit)->GetMakefile()->GetTargets()); - cmTargets::const_iterator tit; - for ( tit = targets->begin(); tit != targets->end(); ++ tit ) - { - const cmTarget::LinkLibraryVectorType* ll - = &(tit->second.GetOriginalLinkLibraries()); - cmTarget::LinkLibraryVectorType::const_iterator llit; - const char* realTargetName = tit->first.c_str(); - if ( ignoreTargetsSet.find(realTargetName) != ignoreTargetsSet.end() ) - { - // Skip ignored targets - continue; - } - if ( ll->size() > 0 ) - { - targetDeps[realTargetName] = 1; - } - for ( llit = ll->begin(); llit != ll->end(); ++ llit ) - { - const char* libName = llit->first.c_str(); - std::map<cmStdString, cmStdString>::const_iterator tarIt - = targetNamesNodes.find(libName); - if ( ignoreTargetsSet.find(libName) != ignoreTargetsSet.end() ) - { - // Skip ignored targets - continue; - } - if ( tarIt == targetNamesNodes.end() ) - { - cmOStringStream ostr; - ostr << graphNodePrefix << cnt++; - targetDeps[libName] = 2; - targetNamesNodes[libName] = ostr.str(); - //str << " \"" << ostr.c_str() << "\" [ label=\"" << libName - //<< "\" shape=\"ellipse\"];" << std::endl; - } - else - { - std::map<cmStdString, int>::const_iterator depIt - = targetDeps.find(libName); - if ( depIt == targetDeps.end() ) - { - targetDeps[libName] = 1; - } - } - } - } - } +#ifdef CMAKE_BUILD_WITH_CMAKE + std::auto_ptr<cmGraphVizWriter> gvWriter( + new cmGraphVizWriter(this->GetGlobalGenerator()->GetLocalGenerators())); - // Write out nodes - std::map<cmStdString, int>::const_iterator depIt; - for ( depIt = targetDeps.begin(); depIt != targetDeps.end(); ++ depIt ) - { - const char* newTargetName = depIt->first.c_str(); - std::map<cmStdString, cmStdString>::const_iterator tarIt - = targetNamesNodes.find(newTargetName); - if ( tarIt == targetNamesNodes.end() ) - { - // We should not be here. - std::cout << __LINE__ << " Cannot find library: " << newTargetName - << " even though it was added in the previous pass" << std::endl; - abort(); - } + std::string settingsFile = this->GetHomeOutputDirectory(); + settingsFile += "/CMakeGraphVizOptions.cmake"; + std::string fallbackSettingsFile = this->GetHomeDirectory(); + fallbackSettingsFile += "/CMakeGraphVizOptions.cmake"; - str << " \"" << tarIt->second.c_str() << "\" [ label=\"" - << newTargetName << "\" shape=\""; - if ( depIt->second == 1 ) - { - std::map<cmStdString, const cmTarget*>::const_iterator tarTypeIt = - targetPtrs.find(newTargetName); - if ( tarTypeIt == targetPtrs.end() ) - { - // We should not be here. - std::cout << __LINE__ << " Cannot find library: " << newTargetName - << " even though it was added in the previous pass" << std::endl; - abort(); - } - const cmTarget* tg = tarTypeIt->second; - switch ( tg->GetType() ) - { - case cmTarget::EXECUTABLE: - str << "house"; - break; - case cmTarget::STATIC_LIBRARY: - str << "diamond"; - break; - case cmTarget::SHARED_LIBRARY: - str << "polygon"; - break; - case cmTarget::MODULE_LIBRARY: - str << "octagon"; - break; - default: - str << "box"; - } - } - else - { - str << "ellipse"; - } - str << "\"];" << std::endl; - } + gvWriter->ReadSettings(settingsFile.c_str(), fallbackSettingsFile.c_str()); - // Now generate the connectivity - for ( lit = localGenerators.begin(); lit != localGenerators.end(); ++ lit ) - { - const cmTargets* targets = &((*lit)->GetMakefile()->GetTargets()); - cmTargets::const_iterator tit; - for ( tit = targets->begin(); tit != targets->end(); ++ tit ) - { - std::map<cmStdString, int>::iterator dependIt - = targetDeps.find(tit->first.c_str()); - if ( dependIt == targetDeps.end() ) - { - continue; - } - std::map<cmStdString, cmStdString>::iterator cmakeTarIt - = targetNamesNodes.find(tit->first.c_str()); - const cmTarget::LinkLibraryVectorType* ll - = &(tit->second.GetOriginalLinkLibraries()); - cmTarget::LinkLibraryVectorType::const_iterator llit; - for ( llit = ll->begin(); llit != ll->end(); ++ llit ) - { - const char* libName = llit->first.c_str(); - std::map<cmStdString, cmStdString>::const_iterator tarIt - = targetNamesNodes.find(libName); - if ( tarIt == targetNamesNodes.end() ) - { - // We should not be here. - std::cout << __LINE__ << " Cannot find library: " << libName - << " even though it was added in the previous pass" << std::endl; - abort(); - } - str << " \"" << cmakeTarIt->second.c_str() << "\" -> \"" - << tarIt->second.c_str() << "\"" << std::endl; - } - } - } + gvWriter->WritePerTargetFiles(fileName); + gvWriter->WriteGlobalFile(fileName); - // TODO: Use dotted or something for external libraries - //str << " \"node0\":f4 -> \"node12\"[color=\"#0000ff\" style=dotted]" - //<< std::endl; - // - str << "}" << std::endl; +#endif } + //---------------------------------------------------------------------------- int cmake::SymlinkLibrary(std::vector<std::string>& args) { @@ -3316,7 +3110,7 @@ int cmake::ExecuteLinkScript(std::vector<std::string>& args) void cmake::DefineProperties(cmake *cm) { cm->DefineProperty - ("REPORT_UNDEFINED_PROPERTIES", cmProperty::GLOBAL, + ("REPORT_UNDEFINED_PROPERTIES", cmProperty::GLOBAL, "If set, report any undefined properties to this file.", "If this property is set to a filename then when CMake runs " "it will report any properties or variables that were accessed " @@ -3324,7 +3118,7 @@ void cmake::DefineProperties(cmake *cm) ); cm->DefineProperty - ("TARGET_SUPPORTS_SHARED_LIBS", cmProperty::GLOBAL, + ("TARGET_SUPPORTS_SHARED_LIBS", cmProperty::GLOBAL, "Does the target platform support shared libraries.", "TARGET_SUPPORTS_SHARED_LIBS is a boolean specifying whether the target " "platform supports shared libraries. Basically all current general " @@ -3361,7 +3155,7 @@ void cmake::DefineProperties(cmake *cm) "this list.This property is used by the macros in FeatureSummary.cmake."); cm->DefineProperty ("DISABLED_FEATURES", cmProperty::GLOBAL, - "List of features which are disabled during the CMake run.", + "List of features which are disabled during the CMake run.", "List of features which are disabled during the CMake run. Be default " "it contains the names of all packages which were not found. This is " "determined using the <NAME>_FOUND variables. Packages which are " @@ -3481,6 +3275,23 @@ void cmake::DefineProperties(cmake *cm) "the value of this property. " "Non-Makefile generators currently ignore this property."); + cm->DefineProperty + ("USE_FOLDERS", cmProperty::GLOBAL, + "Use the FOLDER target property to organize targets into folders.", + "If not set, CMake treats this property as OFF by default. " + "CMake generators that are capable of organizing into a " + "hierarchy of folders use the values of the FOLDER target " + "property to name those folders. See also the documentation " + "for the FOLDER target property."); + + cm->DefineProperty + ("PREDEFINED_TARGETS_FOLDER", cmProperty::GLOBAL, + "Name of FOLDER for targets that are added automatically by CMake.", + "If not set, CMake uses \"CMakePredefinedTargets\" as a default " + "value for this property. Targets such as INSTALL, PACKAGE and " + "RUN_TESTS will be organized into this FOLDER. See also the " + "documentation for the FOLDER target property."); + // ================================================================ // define variables as well // ================================================================ @@ -3494,13 +3305,13 @@ void cmake::DefineProperty(const char *name, cmProperty::ScopeType scope, bool chained, const char *docSection) { this->PropertyDefinitions[scope].DefineProperty(name,scope,ShortDescription, - FullDescription, + FullDescription, docSection, chained); } cmPropertyDefinition *cmake -::GetPropertyDefinition(const char *name, +::GetPropertyDefinition(const char *name, cmProperty::ScopeType scope) { if (this->IsPropertyDefined(name,scope)) @@ -3510,7 +3321,7 @@ cmPropertyDefinition *cmake return 0; } -void cmake::RecordPropertyAccess(const char *name, +void cmake::RecordPropertyAccess(const char *name, cmProperty::ScopeType scope) { this->AccessedProperties.insert @@ -3582,13 +3393,13 @@ void cmake::ReportUndefinedPropertyAccesses(const char *filename) { if (!this->IsPropertyDefined(ap->first.c_str(),ap->second) && aliasedProperties.find(std::pair<cmStdString,cmProperty::ScopeType> - (ap->first,ap->second)) == + (ap->first,ap->second)) == aliasedProperties.end()) { const char *scopeStr = ""; switch (ap->second) { - case cmProperty::TARGET: + case cmProperty::TARGET: scopeStr = "TARGET"; break; case cmProperty::SOURCE_FILE: @@ -3690,7 +3501,7 @@ const char *cmake::GetProperty(const char* prop, cmProperty::ScopeType scope) } else if ( propname == "COMMANDS" ) { - cmake::RegisteredCommandsMap::iterator cmds + cmake::RegisteredCommandsMap::iterator cmds = this->GetCommands()->begin(); for (unsigned int cc=0 ; cmds != this->GetCommands()->end(); ++ cmds ) { @@ -3798,14 +3609,14 @@ 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 = + std::string modulesPath = this->CacheManager->GetCacheValue("CMAKE_ROOT"); modulesPath += "/Modules"; std::string inFile = modulesPath; inFile += "/SystemInformation.cmake"; std::string outFile = destPath; outFile += "/CMakeLists.txt"; - + // Copy file if(!cmSystemTools::cmCopyFile(inFile.c_str(), outFile.c_str())) { @@ -3813,7 +3624,7 @@ int cmake::GetSystemInformation(std::vector<std::string>& args) << "\" to \"" << outFile.c_str() << "\".\n"; return 1; } - + // do we write to a file or to stdout? if (resultFile.size() == 0) { @@ -3839,7 +3650,7 @@ int cmake::GetSystemInformation(std::vector<std::string>& args) // change back to the original directory cmSystemTools::ChangeDirectory(cwd.c_str()); - + // echo results to stdout if needed if (writeToStdout) { @@ -3860,7 +3671,7 @@ int cmake::GetSystemInformation(std::vector<std::string>& args) fclose(fin); } } - + // clean up the directory cmSystemTools::RemoveADirectory(destPath.c_str()); return 0; @@ -3904,6 +3715,9 @@ static bool cmakeCheckStampFile(const char* stampName) // build system is really out of date. std::cout << "CMake is re-running because " << stampName << " is out-of-date.\n"; + std::cout << " the file '" << dep << "'\n"; + std::cout << " is newer than '" << stampDepends << "'\n"; + std::cout << " result='" << result << "'\n"; return false; } } @@ -3976,7 +3790,7 @@ int cmake::VisualStudioLink(std::vector<std::string>& args, int type) for(std::vector<std::string>::iterator i = args.begin(); i != args.end(); ++i) { - // check for nmake temporary files + // check for nmake temporary files if((*i)[0] == '@' && i->find("@CMakeFiles") != 0 ) { std::ifstream fin(i->substr(1).c_str()); @@ -4001,6 +3815,10 @@ int cmake::VisualStudioLink(std::vector<std::string>& args, int type) { hasIncremental = true; } + if(cmSystemTools::Strucmp(i->c_str(), "/INCREMENTAL") == 0) + { + hasIncremental = true; + } if(cmSystemTools::Strucmp(i->c_str(), "/MANIFEST:NO") == 0) { hasManifest = false; @@ -4029,7 +3847,7 @@ int cmake::VisualStudioLink(std::vector<std::string>& args, int type) type, hasManifest, verbose); } -int cmake::ParseVisualStudioLinkCommand(std::vector<std::string>& args, +int cmake::ParseVisualStudioLinkCommand(std::vector<std::string>& args, std::vector<cmStdString>& command, std::string& targetName) { @@ -4080,7 +3898,7 @@ bool cmake::RunCommand(const char* comment, &retCode, 0, false); // always print the output of the command, unless // it is the dumb rc command banner, but if the command - // returned an error code then print the output anyway as + // returned an error code then print the output anyway as // the banner may be mixed with some other important information. if(output.find("Resource Compiler Version") == output.npos || retCode !=0) @@ -4101,12 +3919,12 @@ bool cmake::RunCommand(const char* comment, return retCode == 0; } -int cmake::VisualStudioLinkIncremental(std::vector<std::string>& args, +int cmake::VisualStudioLinkIncremental(std::vector<std::string>& args, int type, bool verbose) { // This follows the steps listed here: // http://blogs.msdn.com/zakramer/archive/2006/05/22/603558.aspx - + // 1. Compiler compiles the application and generates the *.obj files. // 2. An empty manifest file is generated if this is a clean build and if // not the previous one is reused. @@ -4118,10 +3936,10 @@ int cmake::VisualStudioLinkIncremental(std::vector<std::string>& args, // on. // 5. The manifest tool (mt.exe) is then used to generate the final // manifest. - + // If the final manifest is changed, then 6 and 7 are run, if not // they are skipped, and it is done. - + // 6. The resource compiler is invoked one more time. // 7. Finally, the Linker does another incremental link, but since the // only thing that has changed is the *.res file that contains the @@ -4180,7 +3998,7 @@ int cmake::VisualStudioLinkIncremental(std::vector<std::string>& args, outputOpt += resourceFile; rcCommand.push_back(outputOpt); rcCommand.push_back(resourceInputFile); - // Run rc command to create resource + // Run rc command to create resource if(!cmake::RunCommand("RC Pass 1", rcCommand, verbose)) { return -1; @@ -4190,7 +4008,7 @@ int cmake::VisualStudioLinkIncremental(std::vector<std::string>& args, { return -1; } - // create mt command + // create mt command std::string outArg("/out:"); outArg+= manifestFile; mtCommand.push_back("/nologo"); @@ -4241,7 +4059,7 @@ int cmake::VisualStudioLinkNonIncremental(std::vector<std::string>& args, { return -1; } - // Run the link command as given + // Run the link command as given linkCommand.push_back("/MANIFEST"); if(!cmake::RunCommand("LINK", linkCommand, verbose)) { @@ -4393,7 +4211,7 @@ int cmake::Build(const std::string& dir, const std::string& config, const std::vector<std::string>& nativeOptions, bool clean) -{ +{ if(!cmSystemTools::FileIsDirectory(dir.c_str())) { std::cerr << "Error: " << dir << " is not a directory\n"; @@ -4413,8 +4231,8 @@ int cmake::Build(const std::string& dir, std::cerr << "Error: could find generator in Cache\n"; return 1; } - cmGlobalGenerator* gen = - this->CreateGlobalGenerator(it.GetValue()); + std::auto_ptr<cmGlobalGenerator> gen( + this->CreateGlobalGenerator(it.GetValue())); std::string output; std::string projName; std::string makeProgram; @@ -4432,7 +4250,7 @@ int cmake::Build(const std::string& dir, makeProgram = it.GetValue(); return gen->Build(0, dir.c_str(), projName.c_str(), target.c_str(), - &output, + &output, makeProgram.c_str(), config.c_str(), clean, false, 0, true, 0, nativeOptions); diff --git a/Source/cmake.h b/Source/cmake.h index 8312795..435d38b 100644 --- a/Source/cmake.h +++ b/Source/cmake.h @@ -21,14 +21,14 @@ // command line arguments. // 3) Load the cache by calling LoadCache (duh) // 4) if you are using command line arguments with -D or -C flags then -// call SetCacheArgs (or if for some other reason you want to modify the +// call SetCacheArgs (or if for some other reason you want to modify the // cache, do it now. // 5) Finally call Configure // 6) Let the user change values and go back to step 5 // 7) call Generate // // If your GUI allows the user to change the start & home directories then -// you must at a minimum redo steps 2 through 7. +// you must at a minimum redo steps 2 through 7. // @@ -50,6 +50,8 @@ class cmExternalMakefileProjectGenerator; class cmDocumentationSection; class cmPolicies; class cmListFileBacktrace; +class cmTarget; +class cmGeneratedFileStream; class cmake { @@ -73,14 +75,14 @@ class cmake static const char *GetCMakeFilesDirectory() {return "/CMakeFiles";}; static const char *GetCMakeFilesDirectoryPostSlash() { return "CMakeFiles/";}; - + //@{ /** * Set/Get the home directory (or output directory) in the project. The * home directory is the top directory of the project. It is where * cmake was run. Remember that CMake processes * CMakeLists files by recursing up the tree starting at the StartDirectory - * and going up until it reaches the HomeDirectory. + * and going up until it reaches the HomeDirectory. */ void SetHomeDirectory(const char* dir); const char* GetHomeDirectory() const @@ -100,9 +102,9 @@ class cmake * is the directory of the CMakeLists.txt file that started the current * round of processing. Remember that CMake processes CMakeLists files by * recursing up the tree starting at the StartDirectory and going up until - * it reaches the HomeDirectory. + * it reaches the HomeDirectory. */ - void SetStartDirectory(const char* dir) + void SetStartDirectory(const char* dir) { this->cmStartDirectory = dir; cmSystemTools::ConvertToUnixSlashes(this->cmStartDirectory); @@ -158,7 +160,7 @@ class cmake ///! Return the global generator assigned to this instance of cmake cmGlobalGenerator* GetGlobalGenerator() { return this->GlobalGenerator; } ///! Return the global generator assigned to this instance of cmake, const - const cmGlobalGenerator* GetGlobalGenerator() const + const cmGlobalGenerator* GetGlobalGenerator() const { return this->GlobalGenerator; } ///! Return the global generator assigned to this instance of cmake @@ -169,25 +171,25 @@ class cmake ///! get the cmCachemManager used by this invocation of cmake cmCacheManager *GetCacheManager() { return this->CacheManager; } - + ///! set the cmake command this instance of cmake should use void SetCMakeCommand(const char* cmd) { this->CMakeCommand = cmd; } - + /** * Given a variable name, return its value (as a string). */ const char* GetCacheDefinition(const char*) const; ///! Add an entry into the cache - void AddCacheEntry(const char* key, const char* value, - const char* helpString, + void AddCacheEntry(const char* key, const char* value, + const char* helpString, int type); - /** + /** * Execute commands during the build process. Supports options such * as echo, remove file etc. */ static int ExecuteCMakeCommand(std::vector<std::string>&); - /** + /** * Get the system information and write it to the file specified */ int GetSystemInformation(std::vector<std::string>&); @@ -210,16 +212,16 @@ class cmake /** Check if a command exists. */ bool CommandExists(const char* name) const; - + ///! Parse command line arguments void SetArgs(const std::vector<std::string>&); ///! Is this cmake running as a result of a TRY_COMPILE command bool GetIsInTryCompile() { return this->InTryCompile; } - + ///! Is this cmake running as a result of a TRY_COMPILE command void SetIsInTryCompile(bool i) { this->InTryCompile = i; } - + ///! Parse command line arguments that might set cache values bool SetCacheArgs(const std::vector<std::string>&); @@ -227,9 +229,9 @@ class cmake (const char*msg, float progress, void *); /** * Set the function used by GUI's to receive progress updates - * Function gets passed: message as a const char*, a progress + * Function gets passed: message as a const char*, a progress * amount ranging from 0 to 1.0 and client data. The progress - * number provided may be negative in cases where a message is + * number provided may be negative in cases where a message is * to be displayed without any progress percentage. */ void SetProgressCallback(ProgressCallbackType f, void* clientData=0); @@ -244,14 +246,14 @@ class cmake cmVariableWatch* GetVariableWatch() { return this->VariableWatch; } /** Get the documentation entries for the supported commands. - * If withCurrentCommands is true, the documentation for the + * If withCurrentCommands is true, the documentation for the * recommended set of commands is included. * If withCompatCommands is true, the documentation for discouraged * (compatibility) commands is included. * You probably don't want to set both to false. */ - void GetCommandDocumentation(std::vector<cmDocumentationEntry>& entries, - bool withCurrentCommands = true, + void GetCommandDocumentation(std::vector<cmDocumentationEntry>& entries, + bool withCurrentCommands = true, bool withCompatCommands = true) const; void GetPropertiesDocumentation(std::map<std::string, cmDocumentationSection *>&); @@ -278,7 +280,7 @@ class cmake */ void SetScriptMode(bool mode) { this->ScriptMode = mode; } bool GetScriptMode() { return this->ScriptMode; } - + ///! Debug the try compile stuff by not delelting the files bool GetDebugTryCompile(){return this->DebugTryCompile;} void DebugTryCompileOn(){this->DebugTryCompile = true;} @@ -310,7 +312,7 @@ class cmake void DefineProperty(const char *name, cmProperty::ScopeType scope, const char *ShortDescription, const char *FullDescription, - bool chain = false, + bool chain = false, const char *variableGroup = 0); // get property definition @@ -338,7 +340,7 @@ class cmake } void SetSuppressDevWarnings(bool v) { - this->SuppressDevWarnings = v; + this->SuppressDevWarnings = v; this->DoSuppressDevWarnings = true; } @@ -357,10 +359,10 @@ protected: cmPropertyMap Properties; std::set<std::pair<cmStdString,cmProperty::ScopeType> > AccessedProperties; - std::map<cmProperty::ScopeType, cmPropertyDefinitionMap> + std::map<cmProperty::ScopeType, cmPropertyDefinitionMap> PropertyDefinitions; - typedef + typedef cmExternalMakefileProjectGenerator* (*CreateExtraGeneratorFunctionType)(); typedef std::map<cmStdString, CreateExtraGeneratorFunctionType> RegisteredExtraGeneratorsMap; @@ -374,15 +376,15 @@ protected: void AddDefaultCommands(); void AddDefaultGenerators(); void AddDefaultExtraGenerators(); - void AddExtraGenerator(const char* name, + void AddExtraGenerator(const char* name, CreateExtraGeneratorFunctionType newFunction); - cmPolicies *Policies; + cmPolicies *Policies; cmGlobalGenerator *GlobalGenerator; cmCacheManager *CacheManager; - std::string cmHomeDirectory; + std::string cmHomeDirectory; std::string HomeOutputDirectory; - std::string cmStartDirectory; + std::string cmStartDirectory; std::string StartOutputDirectory; bool SuppressDevWarnings; bool DoSuppressDevWarnings; @@ -393,7 +395,7 @@ protected: ///! Check if CMAKE_CACHEFILE_DIR is set. If it is not, delete the log file. /// If it is set, truncate it to 50kb void TruncateOutputLog(const char* fname); - + /** * Method called to check build system integrity at build time. * Returns 1 if CMake should rerun and 0 otherwise. @@ -416,24 +418,24 @@ protected: static int ExecuteLinkScript(std::vector<std::string>& args); static int VisualStudioLink(std::vector<std::string>& args, int type); static int VisualStudioLinkIncremental(std::vector<std::string>& args, - int type, + int type, bool verbose); static int VisualStudioLinkNonIncremental(std::vector<std::string>& args, int type, bool hasManifest, bool verbose); - static int ParseVisualStudioLinkCommand(std::vector<std::string>& args, - std::vector<cmStdString>& command, + static int ParseVisualStudioLinkCommand(std::vector<std::string>& args, + std::vector<cmStdString>& command, std::string& targetName); static bool RunCommand(const char* comment, std::vector<cmStdString>& command, bool verbose, int* retCodeOut = 0); cmVariableWatch* VariableWatch; - + ///! Find the full path to one of the cmake programs like ctest, cpack, etc. std::string FindCMakeProgram(const char* name) const; -private: +private: cmake(const cmake&); // Not implemented. void operator=(const cmake&); // Not implemented. ProgressCallbackType ProgressCallback; @@ -458,7 +460,7 @@ private: cmFileTimeComparison* FileComparison; std::string GraphVizFile; std::vector<std::string> DebugConfigs; - + void UpdateConversionPathTable(); }; diff --git a/Source/ctest.cxx b/Source/ctest.cxx index c9b875d..3937d8d 100644 --- a/Source/ctest.cxx +++ b/Source/ctest.cxx @@ -152,7 +152,7 @@ static const char * cmDocumentationOptions[][3] = "popups and interactive " "debugging."}, {"--no-label-summary", "Disable timing summary information for labels.", - "This option tells ctest to not print summary information for each label " + "This option tells ctest not to print summary information for each label " "associated with the tests run. If there are no labels on the " "tests, nothing extra is printed."}, {"--build-and-test", "Configure, build and run a test.", @@ -218,6 +218,10 @@ static const char * cmDocumentationOptions[][3] = {"--timeout <seconds>", "Set a global timeout on all tests.", "This option will set a global timeout on all tests that do not already " "have a timeout set on them."}, + {"--stop-time <time>", "Set a time at which all tests should stop running.", + "Set a real time of day at which all tests should timeout. Example: " + "7:00:00 -0400. Any time format understood by the curl date parser is " + "accepted. Local time is assumed if no timezone is specified."}, {"--http1.0", "Submit using HTTP 1.0.", "This option will force CTest to use HTTP 1.0 to submit files to the " "dashboard, instead of HTTP 1.1."}, @@ -225,6 +229,9 @@ static const char * cmDocumentationOptions[][3] = "This flag will turn off automatic compression of test output. Use this " "to maintain compatibility with an older version of CDash which doesn't " "support compressed test output."}, + {"--print-labels", "Print all available test labels.", + "This option will not run any tests, it will simply print the list of " + "all labels associated with the test set."}, {"--help-command <cmd> [<file>]", "Show help for a single command and exit.", "Prints the help for the command to stdout or to the specified file." }, {"--help-command-list [<file>]", "List available commands and exit.", diff --git a/Source/kwsys/CMakeLists.txt b/Source/kwsys/CMakeLists.txt index 62042e8..a35a01f 100644 --- a/Source/kwsys/CMakeLists.txt +++ b/Source/kwsys/CMakeLists.txt @@ -61,6 +61,8 @@ # If not given the install rules # will not be in any component. # +# KWSYS_INSTALL_EXPORT_NAME = The EXPORT option value for install(TARGETS) calls. +# # Example: # # SET(KWSYS_INSTALL_BIN_DIR bin) @@ -141,12 +143,6 @@ IF(COMMAND SET_PROPERTY) "KWSYS_HEADER(%)=<${KWSYS_NAMESPACE}/%>" ) ENDIF(COMMAND SET_PROPERTY) -# add option to disable memory cleanup at exit of putenv memory -IF(DEFINED KWSYS_DO_NOT_CLEAN_PUTENV) - SET(KWSYS_DO_NOT_CLEAN_PUTENV 1) -ELSE(DEFINED KWSYS_DO_NOT_CLEAN_PUTENV) - SET(KWSYS_DO_NOT_CLEAN_PUTENV 0) -ENDIF(DEFINED KWSYS_DO_NOT_CLEAN_PUTENV) # Select library components. IF(KWSYS_STANDALONE OR CMake_SOURCE_DIR) @@ -242,6 +238,9 @@ IF(COMMAND INSTALL) # Setup library install rules. SET(KWSYS_INSTALL_LIBRARY_RULE) IF(KWSYS_INSTALL_LIB_DIR) + IF(KWSYS_INSTALL_EXPORT_NAME) + LIST(APPEND KWSYS_INSTALL_LIBRARY_RULE EXPORT ${KWSYS_INSTALL_EXPORT_NAME}) + ENDIF() # Install the shared library to the lib directory. SET(KWSYS_INSTALL_LIBRARY_RULE ${KWSYS_INSTALL_LIBRARY_RULE} LIBRARY DESTINATION ${KWSYS_INSTALL_LIB_DIR} @@ -309,6 +308,14 @@ IF(NOT KWSYS_IN_SOURCE_BUILD) ${PROJECT_BINARY_DIR}/kwsysPrivate.h COPY_ONLY IMMEDIATE) ENDIF(NOT KWSYS_IN_SOURCE_BUILD) +# Select plugin module file name convention. +IF(NOT KWSYS_DynamicLoader_PREFIX) + SET(KWSYS_DynamicLoader_PREFIX ${CMAKE_SHARED_MODULE_PREFIX}) +ENDIF() +IF(NOT KWSYS_DynamicLoader_SUFFIX) + SET(KWSYS_DynamicLoader_SUFFIX ${CMAKE_SHARED_MODULE_SUFFIX}) +ENDIF() + #----------------------------------------------------------------------------- # We require ANSI support from the C compiler. Add any needed flags. IF(CMAKE_ANSI_CFLAGS) @@ -597,6 +604,23 @@ ELSE(KWSYS_BUILD_SHARED) ENDIF(KWSYS_BUILD_SHARED) #----------------------------------------------------------------------------- +# Configure some implementation details. + +KWSYS_PLATFORM_C_TEST(KWSYS_C_HAS_PTRDIFF_T + "Checking whether C compiler has ptrdiff_t in stddef.h" DIRECT) +KWSYS_PLATFORM_C_TEST(KWSYS_C_HAS_SSIZE_T + "Checking whether C compiler has ssize_t in unistd.h" DIRECT) +SET_SOURCE_FILES_PROPERTIES(ProcessUNIX.c System.c PROPERTIES + COMPILE_FLAGS "-DKWSYS_C_HAS_PTRDIFF_T=${KWSYS_C_HAS_PTRDIFF_T} -DKWSYS_C_HAS_SSIZE_T=${KWSYS_C_HAS_SSIZE_T}" + ) + +IF(KWSYS_DO_NOT_CLEAN_PUTENV) + # Disable cleanup of putenv memory for issues with GCOV. + SET_SOURCE_FILES_PROPERTIES(SystemTools.cxx PROPERTIES + COMPILE_FLAGS -DKWSYS_DO_NOT_CLEAN_PUTENV=1) +ENDIF(KWSYS_DO_NOT_CLEAN_PUTENV) + +#----------------------------------------------------------------------------- # Choose a directory for the generated headers. IF(NOT KWSYS_HEADER_ROOT) SET(KWSYS_HEADER_ROOT "${PROJECT_BINARY_DIR}") @@ -774,15 +798,6 @@ IF(KWSYS_USE_Process) ELSE(NOT UNIX) # Use the UNIX implementation. SET(KWSYS_C_SRCS ${KWSYS_C_SRCS} ProcessUNIX.c) - - # Help ProcessUNIX.c compile properly on all platforms. - KWSYS_PLATFORM_C_TEST(KWSYS_C_HAS_PTRDIFF_T - "Checking whether C compiler has ptrdiff_t in stddef.h" DIRECT) - KWSYS_PLATFORM_C_TEST(KWSYS_C_HAS_SSIZE_T - "Checking whether C compiler has ssize_t in unistd.h" DIRECT) - SET_SOURCE_FILES_PROPERTIES(ProcessUNIX.c PROPERTIES - COMPILE_FLAGS "-DKWSYS_C_HAS_PTRDIFF_T=${KWSYS_C_HAS_PTRDIFF_T} -DKWSYS_C_HAS_SSIZE_T=${KWSYS_C_HAS_SSIZE_T}" - ) ENDIF(NOT UNIX) ENDIF(KWSYS_USE_Process) @@ -1087,6 +1102,7 @@ IF(KWSYS_STANDALONE OR CMake_SOURCE_DIR) FOREACH(n 1 2 3 4 5 6 ${KWSYS_TEST_PROCESS_7}) ADD_TEST(kwsys.testProcess-${n} ${EXEC_DIR}/${KWSYS_NAMESPACE}TestProcess ${n}) KWSYS_SET_PROPERTY(TEST kwsys.testProcess-${n} PROPERTY LABELS ${KWSYS_LABELS_TEST}) + SET_TESTS_PROPERTIES(kwsys.testProcess-${n} PROPERTIES TIMEOUT 120) ENDFOREACH(n) # Some Apple compilers produce bad optimizations in this source. @@ -1114,5 +1130,11 @@ IF(KWSYS_STANDALONE OR CMake_SOURCE_DIR) SET_TESTS_PROPERTIES(kwsys.testFail PROPERTIES MEASUREMENT "Some Key=Some Value") MESSAGE(STATUS "GET_TEST_PROPERTY returned: ${wfv}") ENDIF(COMMAND SET_TESTS_PROPERTIES AND COMMAND GET_TEST_PROPERTY AND KWSYS_STANDALONE) + + # Suppress known consistent failures on buggy systems. + IF(KWSYS_TEST_BOGUS_FAILURES) + SET_TESTS_PROPERTIES(${KWSYS_TEST_BOGUS_FAILURES} PROPERTIES WILL_FAIL ON) + ENDIF() + ENDIF(BUILD_TESTING) ENDIF(KWSYS_STANDALONE OR CMake_SOURCE_DIR) diff --git a/Source/kwsys/Configure.h.in b/Source/kwsys/Configure.h.in index b57b698..15986cf 100644 --- a/Source/kwsys/Configure.h.in +++ b/Source/kwsys/Configure.h.in @@ -28,6 +28,10 @@ # if defined(__INTEL_COMPILER) # pragma warning (disable: 1572) /* floating-point equality test */ # endif +# if defined(__sgi) && !defined(__GNUC__) +# pragma set woff 3970 /* pointer to int conversion */ +# pragma set woff 3968 /* 64 bit conversion */ +# endif #endif /* Whether kwsys namespace is "kwsys". */ @@ -88,11 +92,17 @@ #endif /* Setup the export macro. */ -#if defined(_WIN32) && @KWSYS_BUILD_SHARED@ -# if defined(@KWSYS_NAMESPACE@_EXPORTS) -# define @KWSYS_NAMESPACE@_EXPORT __declspec(dllexport) +#if @KWSYS_BUILD_SHARED@ +# if defined(_WIN32) || defined(__CYGWIN__) +# if defined(@KWSYS_NAMESPACE@_EXPORTS) +# define @KWSYS_NAMESPACE@_EXPORT __declspec(dllexport) +# else +# define @KWSYS_NAMESPACE@_EXPORT __declspec(dllimport) +# endif +# elif __GNUC__ >= 4 +# define @KWSYS_NAMESPACE@_EXPORT __attribute__ ((visibility("default"))) # else -# define @KWSYS_NAMESPACE@_EXPORT __declspec(dllimport) +# define @KWSYS_NAMESPACE@_EXPORT # endif #else # define @KWSYS_NAMESPACE@_EXPORT diff --git a/Source/kwsys/Configure.hxx.in b/Source/kwsys/Configure.hxx.in index 9310d94..716b84f 100644 --- a/Source/kwsys/Configure.hxx.in +++ b/Source/kwsys/Configure.hxx.in @@ -15,15 +15,6 @@ /* Include C configuration. */ #include <@KWSYS_NAMESPACE@/Configure.h> -/* Disable cleanup of putenv memory for issues with GCOV */ -#if @KWSYS_DO_NOT_CLEAN_PUTENV@ -#define KWSYS_DO_NOT_CLEAN_PUTENV -#else -#undef KWSYS_DO_NOT_CLEAN_PUTENV -#endif - - - /* Whether ANSI C++ stream headers are to be used. */ #define @KWSYS_NAMESPACE@_IOS_USE_ANSI @KWSYS_IOS_USE_ANSI@ diff --git a/Source/kwsys/DynamicLoader.cxx b/Source/kwsys/DynamicLoader.cxx index a337031..c4ee095 100644 --- a/Source/kwsys/DynamicLoader.cxx +++ b/Source/kwsys/DynamicLoader.cxx @@ -69,19 +69,6 @@ DynamicLoader::GetSymbolAddress(DynamicLoader::LibraryHandle lib, const char* sy return *reinterpret_cast<DynamicLoader::SymbolPointer*>(&result); } -//---------------------------------------------------------------------------- -const char* DynamicLoader::LibPrefix() -{ - return "lib"; -} - -//---------------------------------------------------------------------------- -const char* DynamicLoader::LibExtension() -{ - return ".sl"; -} - -//---------------------------------------------------------------------------- const char* DynamicLoader::LastError() { // TODO: Need implementation with errno/strerror @@ -176,21 +163,6 @@ DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress( } //---------------------------------------------------------------------------- -const char* DynamicLoader::LibPrefix() -{ - return "lib"; -} - -//---------------------------------------------------------------------------- -const char* DynamicLoader::LibExtension() -{ - // NSCreateObjectFileImageFromFile fail when dealing with dylib image - // it returns NSObjectFileImageInappropriateFile - //return ".dylib"; - return ".so"; -} - -//---------------------------------------------------------------------------- const char* DynamicLoader::LastError() { return 0; @@ -285,22 +257,6 @@ DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress( } //---------------------------------------------------------------------------- -const char* DynamicLoader::LibPrefix() -{ -#ifdef __MINGW32__ - return "lib"; -#else - return ""; -#endif -} - -//---------------------------------------------------------------------------- -const char* DynamicLoader::LibExtension() -{ - return ".dll"; -} - -//---------------------------------------------------------------------------- const char* DynamicLoader::LastError() { LPVOID lpMsgBuf=NULL; @@ -418,18 +374,6 @@ DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress( } //---------------------------------------------------------------------------- -const char* DynamicLoader::LibPrefix() -{ - return "lib"; -} - -//---------------------------------------------------------------------------- -const char* DynamicLoader::LibExtension() -{ - return ".so"; -} - -//---------------------------------------------------------------------------- const char* DynamicLoader::LastError() { const char *retval = strerror(last_dynamic_err); @@ -444,7 +388,7 @@ const char* DynamicLoader::LastError() // 5. Implementation for systems without dynamic libs // __gnu_blrts__ is IBM BlueGene/L // __LIBCATAMOUNT__ is defined on Catamount on Cray compute nodes -#if defined(__gnu_blrts__) || defined(__LIBCATAMOUNT__) +#if defined(__gnu_blrts__) || defined(__LIBCATAMOUNT__) || defined(__CRAYXT_COMPUTE_LINUX_TARGET) #include <string.h> // for strerror() #define DYNAMICLOADER_DEFINED 1 @@ -476,18 +420,6 @@ DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress( } //---------------------------------------------------------------------------- -const char* DynamicLoader::LibPrefix() - { - return "lib"; - } - -//---------------------------------------------------------------------------- -const char* DynamicLoader::LibExtension() - { - return ".a"; - } - -//---------------------------------------------------------------------------- const char* DynamicLoader::LastError() { return "General error"; @@ -540,22 +472,6 @@ DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress( } //---------------------------------------------------------------------------- -const char* DynamicLoader::LibPrefix() -{ - return "lib"; -} - -//---------------------------------------------------------------------------- -const char* DynamicLoader::LibExtension() -{ -#ifdef __CYGWIN__ - return ".dll"; -#else - return ".so"; -#endif -} - -//---------------------------------------------------------------------------- const char* DynamicLoader::LastError() { return dlerror(); diff --git a/Source/kwsys/DynamicLoader.hxx.in b/Source/kwsys/DynamicLoader.hxx.in index 325e956..64468ec 100644 --- a/Source/kwsys/DynamicLoader.hxx.in +++ b/Source/kwsys/DynamicLoader.hxx.in @@ -86,11 +86,11 @@ public: /** Find the address of the symbol in the given library. */ static SymbolPointer GetSymbolAddress(LibraryHandle, const char*); - /** Return the library prefix for the given architecture */ - static const char* LibPrefix(); + /** Return the default module prefix for the current platform. */ + static const char* LibPrefix() { return "@KWSYS_DynamicLoader_PREFIX@"; } - /** Return the library extension for the given architecture. */ - static const char* LibExtension(); + /** Return the default module suffix for the current platform. */ + static const char* LibExtension() { return "@KWSYS_DynamicLoader_SUFFIX@"; } /** Return the last error produced from a calls made on this class. */ static const char* LastError(); diff --git a/Source/kwsys/MD5.c b/Source/kwsys/MD5.c index f2e2019..56776a3 100644 --- a/Source/kwsys/MD5.c +++ b/Source/kwsys/MD5.c @@ -29,6 +29,11 @@ it in a single source file instead of a separate header and implementation file. */ +#if defined(__clang__) +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wcast-align" +#endif + /* Copyright (C) 1999, 2000, 2002 Aladdin Enterprises. All rights reserved. @@ -52,7 +57,6 @@ ghost@aladdin.com */ -/* $Id$ */ /* Independent implementation of MD5 (RFC 1321). @@ -429,6 +433,10 @@ static void md5_finish(md5_state_t *pms, md5_byte_t digest[16]) digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3)); } +#if defined(__clang__) +# pragma clang diagnostic pop +#endif + /*--------------------------------------------------------------------------*/ /* Wrap up the MD5 state in our opaque structure. */ struct kwsysMD5_s diff --git a/Source/kwsys/ProcessUNIX.c b/Source/kwsys/ProcessUNIX.c index 79716a1..9c66a44 100644 --- a/Source/kwsys/ProcessUNIX.c +++ b/Source/kwsys/ProcessUNIX.c @@ -720,6 +720,14 @@ void kwsysProcess_Execute(kwsysProcess* cp) return; } + /* Make sure we have something to run. */ + if(cp->NumberOfCommands < 1) + { + strcpy(cp->ErrorMessage, "No command"); + cp->State = kwsysProcess_State_Error; + return; + } + /* Initialize the control structure for a new process. */ if(!kwsysProcessInitialize(cp)) { @@ -1875,9 +1883,8 @@ static int kwsysProcessSetupOutputPipeFile(int* p, const char* name) /* Close the existing descriptor. */ kwsysProcessCleanupDescriptor(p); - /* Open a file for the pipe to write (permissions 644). */ - if((fout = open(name, O_WRONLY | O_CREAT | O_TRUNC, - S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0) + /* Open a file for the pipe to write. */ + if((fout = open(name, O_WRONLY | O_CREAT | O_TRUNC, 0666)) < 0) { return 0; } @@ -2374,9 +2381,13 @@ static pid_t kwsysProcessFork(kwsysProcess* cp, Here we define the command to call on each platform and the corresponding parsing format string. The parsing format should have two integers to store: the pid and then the ppid. */ -#if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) +#if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) \ + || defined(__OpenBSD__) || defined(__GLIBC__) || defined(__GNU__) # define KWSYSPE_PS_COMMAND "ps axo pid,ppid" # define KWSYSPE_PS_FORMAT "%d %d\n" +#elif defined(__sun) && (defined(__SVR4) || defined(__svr4__)) /* Solaris */ +# define KWSYSPE_PS_COMMAND "ps -e -o pid,ppid" +# define KWSYSPE_PS_FORMAT "%d %d\n" #elif defined(__hpux) || defined(__sun__) || defined(__sgi) || defined(_AIX) \ || defined(__sparc) # define KWSYSPE_PS_COMMAND "ps -ef" diff --git a/Source/kwsys/ProcessWin32.c b/Source/kwsys/ProcessWin32.c index c5ea6db..5aa4d8b 100644 --- a/Source/kwsys/ProcessWin32.c +++ b/Source/kwsys/ProcessWin32.c @@ -987,6 +987,14 @@ void kwsysProcess_Execute(kwsysProcess* cp) return; } + /* Make sure we have something to run. */ + if(cp->NumberOfCommands < 1) + { + strcpy(cp->ErrorMessage, "No command"); + cp->State = kwsysProcess_State_Error; + return; + } + /* Initialize the control structure for a new process. */ if(!kwsysProcessInitialize(cp)) { diff --git a/Source/kwsys/Registry.cxx b/Source/kwsys/Registry.cxx index 284e8ad..cd521c9 100644 --- a/Source/kwsys/Registry.cxx +++ b/Source/kwsys/Registry.cxx @@ -401,8 +401,9 @@ bool RegistryHelper::Open(const char *toplevel, const char *subkey, } else { + char lpClass[] = ""; res = ( RegCreateKeyEx(scope, str.str().c_str(), - 0, "", REG_OPTION_NON_VOLATILE, KEY_READ|KEY_WRITE, + 0, lpClass, REG_OPTION_NON_VOLATILE, KEY_READ|KEY_WRITE, NULL, &this->HKey, &dwDummy) == ERROR_SUCCESS ); } if ( res != 0 ) diff --git a/Source/kwsys/SharedForward.h.in b/Source/kwsys/SharedForward.h.in index a5f3a4d..8521099 100644 --- a/Source/kwsys/SharedForward.h.in +++ b/Source/kwsys/SharedForward.h.in @@ -201,6 +201,12 @@ static const char kwsys_shared_forward_path_slash[2] = {KWSYS_SHARED_FORWARD_PAT # define KWSYS_SHARED_FORWARD_LDD_N 1 # define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH" +/* OpenBSD */ +#elif defined(__OpenBSD__) +# define KWSYS_SHARED_FORWARD_LDD "ldd" +# define KWSYS_SHARED_FORWARD_LDD_N 1 +# define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH" + /* OSX */ #elif defined(__APPLE__) # define KWSYS_SHARED_FORWARD_LDD "otool", "-L" @@ -246,12 +252,14 @@ static const char kwsys_shared_forward_path_slash[2] = {KWSYS_SHARED_FORWARD_PAT # define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY64_PATH" # endif +/* Cygwin */ +#elif defined(__CYGWIN__) +# define KWSYS_SHARED_FORWARD_LDD "cygcheck" /* TODO: cygwin 1.7 has ldd */ +# define KWSYS_SHARED_FORWARD_LDD_N 1 +# define KWSYS_SHARED_FORWARD_LDPATH "PATH" + /* Windows */ #elif defined(_WIN32) -# if defined(__CYGWIN__) -# define KWSYS_SHARED_FORWARD_LDD "cygcheck" -# define KWSYS_SHARED_FORWARD_LDD_N 1 -# endif # define KWSYS_SHARED_FORWARD_LDPATH "PATH" /* Guess on this unknown system. */ diff --git a/Source/kwsys/String.hxx.in b/Source/kwsys/String.hxx.in index 424f61d..4386c9e 100644 --- a/Source/kwsys/String.hxx.in +++ b/Source/kwsys/String.hxx.in @@ -25,7 +25,7 @@ namespace @KWSYS_NAMESPACE@ * simply a subclass of this type with the same interface so that the * name is shorter in debugging symbols and error messages. */ -class @KWSYS_NAMESPACE@_EXPORT String: public @KWSYS_NAMESPACE@_stl::string +class String: public @KWSYS_NAMESPACE@_stl::string { /** The original string type. */ typedef @KWSYS_NAMESPACE@_stl::string stl_string; diff --git a/Source/kwsys/SystemInformation.cxx b/Source/kwsys/SystemInformation.cxx index 7041d38..9bc659e 100644 --- a/Source/kwsys/SystemInformation.cxx +++ b/Source/kwsys/SystemInformation.cxx @@ -66,7 +66,6 @@ #endif #ifdef __linux -# include <sys/procfs.h> # include <sys/types.h> # include <unistd.h> # include <fcntl.h> @@ -151,10 +150,6 @@ public: void RunMemoryCheck(); public: -#define VENDOR_STRING_LENGTH (12 + 1) -#define CHIPNAME_STRING_LENGTH (48 + 1) -#define SERIALNUMBER_STRING_LENGTH (29 + 1) - typedef struct tagID { int Type; @@ -163,9 +158,9 @@ public: int Revision; int ExtendedFamily; int ExtendedModel; - char ProcessorName[CHIPNAME_STRING_LENGTH]; - char Vendor[VENDOR_STRING_LENGTH]; - char SerialNumber[SERIALNUMBER_STRING_LENGTH]; + kwsys_stl::string ProcessorName; + kwsys_stl::string Vendor; + kwsys_stl::string SerialNumber; } ID; typedef struct tagCPUPowerManagement @@ -269,6 +264,10 @@ protected: //For Haiku OS bool QueryHaikuInfo(); + //For QNX + bool QueryQNXMemory(); + bool QueryQNXProcessor(); + // Evaluate the memory information. int QueryMemory(); size_t TotalVirtualMemory; @@ -530,7 +529,12 @@ SystemInformationImplementation::SystemInformationImplementation() this->CurrentPositionInFile = 0; this->ChipManufacturer = UnknownManufacturer; memset(&this->Features, 0, sizeof(CPUFeatures)); - memset(&this->ChipID, 0, sizeof(ID)); + this->ChipID.Type = 0; + this->ChipID.Family = 0; + this->ChipID.Model = 0; + this->ChipID.Revision = 0; + this->ChipID.ExtendedFamily = 0; + this->ChipID.ExtendedModel = 0; this->CPUSpeedInMHz = 0; this->NumberOfLogicalCPU = 0; this->NumberOfPhysicalCPU = 0; @@ -597,6 +601,8 @@ void SystemInformationImplementation::RunCPUCheck() this->QuerySolarisInfo(); #elif defined(__HAIKU__) this->QueryHaikuInfo(); +#elif defined(__QNX__) + this->QueryQNXProcessor(); #else this->RetreiveInformationFromCpuInfoFile(); #endif @@ -615,6 +621,8 @@ void SystemInformationImplementation::RunMemoryCheck() this->QuerySolarisInfo(); #elif defined(__HAIKU__) this->QueryHaikuInfo(); +#elif defined(__QNX__) + this->QueryQNXMemory(); #else this->QueryMemory(); #endif @@ -623,7 +631,7 @@ void SystemInformationImplementation::RunMemoryCheck() /** Get the vendor string */ const char * SystemInformationImplementation::GetVendorString() { - return this->ChipID.Vendor; + return this->ChipID.Vendor.c_str(); } /** Get the OS Name */ @@ -726,14 +734,14 @@ kwsys_stl::string SystemInformationImplementation::GetSteppingCode() /** Return the stepping code of the CPU present. */ const char * SystemInformationImplementation::GetExtendedProcessorName() { - return this->ChipID.ProcessorName; + return this->ChipID.ProcessorName.c_str(); } /** Return the serial number of the processor * in hexadecimal: xxxx-xxxx-xxxx-xxxx-xxxx-xxxx. */ const char * SystemInformationImplementation::GetProcessorSerialNumber() { - return this->ChipID.SerialNumber; + return this->ChipID.SerialNumber.c_str(); } /** Return the logical processors per physical */ @@ -1022,21 +1030,21 @@ bool SystemInformationImplementation::RetrieveCPUFeatures() /** Find the manufacturer given the vendor id */ void SystemInformationImplementation::FindManufacturer() { - if (strcmp (this->ChipID.Vendor, "GenuineIntel") == 0) this->ChipManufacturer = Intel; // Intel Corp. - else if (strcmp (this->ChipID.Vendor, "UMC UMC UMC ") == 0) this->ChipManufacturer = UMC; // United Microelectronics Corp. - else if (strcmp (this->ChipID.Vendor, "AuthenticAMD") == 0) this->ChipManufacturer = AMD; // Advanced Micro Devices - else if (strcmp (this->ChipID.Vendor, "AMD ISBETTER") == 0) this->ChipManufacturer = AMD; // Advanced Micro Devices (1994) - else if (strcmp (this->ChipID.Vendor, "CyrixInstead") == 0) this->ChipManufacturer = Cyrix; // Cyrix Corp., VIA Inc. - else if (strcmp (this->ChipID.Vendor, "NexGenDriven") == 0) this->ChipManufacturer = NexGen; // NexGen Inc. (now AMD) - else if (strcmp (this->ChipID.Vendor, "CentaurHauls") == 0) this->ChipManufacturer = IDT; // IDT/Centaur (now VIA) - else if (strcmp (this->ChipID.Vendor, "RiseRiseRise") == 0) this->ChipManufacturer = Rise; // Rise - else if (strcmp (this->ChipID.Vendor, "GenuineTMx86") == 0) this->ChipManufacturer = Transmeta; // Transmeta - else if (strcmp (this->ChipID.Vendor, "TransmetaCPU") == 0) this->ChipManufacturer = Transmeta; // Transmeta - else if (strcmp (this->ChipID.Vendor, "Geode By NSC") == 0) this->ChipManufacturer = NSC; // National Semiconductor - else if (strcmp (this->ChipID.Vendor, "Sun") == 0) this->ChipManufacturer = Sun; // Sun Microelectronics - else if (strcmp (this->ChipID.Vendor, "IBM") == 0) this->ChipManufacturer = IBM; // IBM Microelectronics - else if (strcmp (this->ChipID.Vendor, "Motorola") == 0) this->ChipManufacturer = Motorola; // Motorola Microelectronics - else this->ChipManufacturer = UnknownManufacturer; // Unknown manufacturer + if (this->ChipID.Vendor == "GenuineIntel") this->ChipManufacturer = Intel; // Intel Corp. + else if (this->ChipID.Vendor == "UMC UMC UMC ") this->ChipManufacturer = UMC; // United Microelectronics Corp. + else if (this->ChipID.Vendor == "AuthenticAMD") this->ChipManufacturer = AMD; // Advanced Micro Devices + else if (this->ChipID.Vendor == "AMD ISBETTER") this->ChipManufacturer = AMD; // Advanced Micro Devices (1994) + else if (this->ChipID.Vendor == "CyrixInstead") this->ChipManufacturer = Cyrix; // Cyrix Corp., VIA Inc. + else if (this->ChipID.Vendor == "NexGenDriven") this->ChipManufacturer = NexGen; // NexGen Inc. (now AMD) + else if (this->ChipID.Vendor == "CentaurHauls") this->ChipManufacturer = IDT; // IDT/Centaur (now VIA) + else if (this->ChipID.Vendor == "RiseRiseRise") this->ChipManufacturer = Rise; // Rise + else if (this->ChipID.Vendor == "GenuineTMx86") this->ChipManufacturer = Transmeta; // Transmeta + else if (this->ChipID.Vendor == "TransmetaCPU") this->ChipManufacturer = Transmeta; // Transmeta + else if (this->ChipID.Vendor == "Geode By NSC") this->ChipManufacturer = NSC; // National Semiconductor + else if (this->ChipID.Vendor == "Sun") this->ChipManufacturer = Sun; // Sun Microelectronics + else if (this->ChipID.Vendor == "IBM") this->ChipManufacturer = IBM; // IBM Microelectronics + else if (this->ChipID.Vendor == "Motorola") this->ChipManufacturer = Motorola; // Motorola Microelectronics + else this->ChipManufacturer = UnknownManufacturer; // Unknown manufacturer } @@ -1094,10 +1102,12 @@ bool SystemInformationImplementation::RetrieveCPUIdentity() } // Process the returned information. - memcpy (this->ChipID.Vendor, &(localCPUVendor[0]), sizeof (int)); - memcpy (&(this->ChipID.Vendor[4]), &(localCPUVendor[1]), sizeof (int)); - memcpy (&(this->ChipID.Vendor[8]), &(localCPUVendor[2]), sizeof (int)); - this->ChipID.Vendor[12] = '\0'; + char vbuf[13]; + memcpy (&(vbuf[0]), &(localCPUVendor[0]), sizeof (int)); + memcpy (&(vbuf[4]), &(localCPUVendor[1]), sizeof (int)); + memcpy (&(vbuf[8]), &(localCPUVendor[2]), sizeof (int)); + vbuf[12] = '\0'; + this->ChipID.Vendor = vbuf; this->FindManufacturer(); @@ -1546,17 +1556,17 @@ bool SystemInformationImplementation::RetrieveClassicalCPUClockSpeed() if (this->ChipID.Family == 3) { // 80386 processors.... Loop time is 115 cycles! - dFrequency = (((CLASSICAL_CPU_FREQ_LOOP * 115) / dDifference) / 1048576); + dFrequency = (((CLASSICAL_CPU_FREQ_LOOP * 115) / dDifference) / 1000000); } else if (this->ChipID.Family == 4) { // 80486 processors.... Loop time is 47 cycles! - dFrequency = (((CLASSICAL_CPU_FREQ_LOOP * 47) / dDifference) / 1048576); + dFrequency = (((CLASSICAL_CPU_FREQ_LOOP * 47) / dDifference) / 1000000); } else if (this->ChipID.Family == 5) { // Pentium processors.... Loop time is 43 cycles! - dFrequency = (((CLASSICAL_CPU_FREQ_LOOP * 43) / dDifference) / 1048576); + dFrequency = (((CLASSICAL_CPU_FREQ_LOOP * 43) / dDifference) / 1000000); } // Save the clock speed. @@ -1792,7 +1802,8 @@ bool SystemInformationImplementation::RetrieveProcessorSerialNumber() } // Process the returned information. - sprintf (this->ChipID.SerialNumber, "%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x", + char sn[128]; + sprintf (sn, "%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x", ((SerialNumber[0] & 0xff000000) >> 24), ((SerialNumber[0] & 0x00ff0000) >> 16), ((SerialNumber[0] & 0x0000ff00) >> 8), @@ -1805,7 +1816,7 @@ bool SystemInformationImplementation::RetrieveProcessorSerialNumber() ((SerialNumber[2] & 0x00ff0000) >> 16), ((SerialNumber[2] & 0x0000ff00) >> 8), ((SerialNumber[2] & 0x000000ff) >> 0)); - + this->ChipID.SerialNumber = sn; return true; #else @@ -1873,6 +1884,15 @@ bool SystemInformationImplementation::RetrieveCPUPowerManagement() #endif } +void SystemInformationStripLeadingSpace(kwsys_stl::string& str) +{ + // Because some manufacturers have leading white space - we have to post-process the name. + kwsys_stl::string::size_type pos = str.find_first_not_of(" "); + if(pos != kwsys_stl::string::npos) + { + str = str.substr(pos); + } +} /** */ bool SystemInformationImplementation::RetrieveExtendedCPUIdentity() @@ -1886,7 +1906,6 @@ bool SystemInformationImplementation::RetrieveExtendedCPUIdentity() return false; #if USE_ASM_INSTRUCTIONS - int ProcessorNameStartPos = 0; int CPUExtendedIdentity[12]; // Use assembly to detect CPUID information... @@ -1942,47 +1961,25 @@ bool SystemInformationImplementation::RetrieveExtendedCPUIdentity() } // Process the returned information. - memcpy (this->ChipID.ProcessorName, &(CPUExtendedIdentity[0]), sizeof (int)); - memcpy (&(this->ChipID.ProcessorName[4]), &(CPUExtendedIdentity[1]), sizeof (int)); - memcpy (&(this->ChipID.ProcessorName[8]), &(CPUExtendedIdentity[2]), sizeof (int)); - memcpy (&(this->ChipID.ProcessorName[12]), &(CPUExtendedIdentity[3]), sizeof (int)); - memcpy (&(this->ChipID.ProcessorName[16]), &(CPUExtendedIdentity[4]), sizeof (int)); - memcpy (&(this->ChipID.ProcessorName[20]), &(CPUExtendedIdentity[5]), sizeof (int)); - memcpy (&(this->ChipID.ProcessorName[24]), &(CPUExtendedIdentity[6]), sizeof (int)); - memcpy (&(this->ChipID.ProcessorName[28]), &(CPUExtendedIdentity[7]), sizeof (int)); - memcpy (&(this->ChipID.ProcessorName[32]), &(CPUExtendedIdentity[8]), sizeof (int)); - memcpy (&(this->ChipID.ProcessorName[36]), &(CPUExtendedIdentity[9]), sizeof (int)); - memcpy (&(this->ChipID.ProcessorName[40]), &(CPUExtendedIdentity[10]), sizeof (int)); - memcpy (&(this->ChipID.ProcessorName[44]), &(CPUExtendedIdentity[11]), sizeof (int)); - this->ChipID.ProcessorName[48] = '\0'; + char nbuf[49]; + memcpy (&(nbuf[0]), &(CPUExtendedIdentity[0]), sizeof (int)); + memcpy (&(nbuf[4]), &(CPUExtendedIdentity[1]), sizeof (int)); + memcpy (&(nbuf[8]), &(CPUExtendedIdentity[2]), sizeof (int)); + memcpy (&(nbuf[12]), &(CPUExtendedIdentity[3]), sizeof (int)); + memcpy (&(nbuf[16]), &(CPUExtendedIdentity[4]), sizeof (int)); + memcpy (&(nbuf[20]), &(CPUExtendedIdentity[5]), sizeof (int)); + memcpy (&(nbuf[24]), &(CPUExtendedIdentity[6]), sizeof (int)); + memcpy (&(nbuf[28]), &(CPUExtendedIdentity[7]), sizeof (int)); + memcpy (&(nbuf[32]), &(CPUExtendedIdentity[8]), sizeof (int)); + memcpy (&(nbuf[36]), &(CPUExtendedIdentity[9]), sizeof (int)); + memcpy (&(nbuf[40]), &(CPUExtendedIdentity[10]), sizeof (int)); + memcpy (&(nbuf[44]), &(CPUExtendedIdentity[11]), sizeof (int)); + nbuf[48] = '\0'; + this->ChipID.ProcessorName = nbuf; // Because some manufacturers have leading white space - we have to post-process the name. - if (this->ChipManufacturer == Intel) - { - for (int nCounter = 0; nCounter < CHIPNAME_STRING_LENGTH; nCounter ++) - { - // There will either be NULL (\0) or spaces ( ) as the leading characters. - if ((this->ChipID.ProcessorName[nCounter] != '\0') && (this->ChipID.ProcessorName[nCounter] != ' ')) - { - // We have found the starting position of the name. - ProcessorNameStartPos = nCounter; - // Terminate the loop. - break; - } - } - - // Check to see if there is any white space at the start. - if (ProcessorNameStartPos == 0) - { - return true; - } - - // Now move the name forward so that there is no white space. - memmove(this->ChipID.ProcessorName, &(this->ChipID.ProcessorName[ProcessorNameStartPos]), (CHIPNAME_STRING_LENGTH - ProcessorNameStartPos)); - } - + SystemInformationStripLeadingSpace(this->ChipID.ProcessorName); return true; - #else return false; #endif @@ -1999,53 +1996,53 @@ bool SystemInformationImplementation::RetrieveClassicalCPUIdentity() // Check the family / model / revision to determine the CPU ID. switch (this->ChipID.Family) { case 3: - sprintf (this->ChipID.ProcessorName, "Newer i80386 family"); + this->ChipID.ProcessorName = "Newer i80386 family"; break; case 4: switch (this->ChipID.Model) { - case 0: sprintf (this->ChipID.ProcessorName,"i80486DX-25/33"); break; - case 1: sprintf (this->ChipID.ProcessorName,"i80486DX-50"); break; - case 2: sprintf (this->ChipID.ProcessorName,"i80486SX"); break; - case 3: sprintf (this->ChipID.ProcessorName,"i80486DX2"); break; - case 4: sprintf (this->ChipID.ProcessorName,"i80486SL"); break; - case 5: sprintf (this->ChipID.ProcessorName,"i80486SX2"); break; - case 7: sprintf (this->ChipID.ProcessorName,"i80486DX2 WriteBack"); break; - case 8: sprintf (this->ChipID.ProcessorName,"i80486DX4"); break; - case 9: sprintf (this->ChipID.ProcessorName,"i80486DX4 WriteBack"); break; - default: sprintf (this->ChipID.ProcessorName,"Unknown 80486 family"); return false; + case 0: this->ChipID.ProcessorName = "i80486DX-25/33"; break; + case 1: this->ChipID.ProcessorName = "i80486DX-50"; break; + case 2: this->ChipID.ProcessorName = "i80486SX"; break; + case 3: this->ChipID.ProcessorName = "i80486DX2"; break; + case 4: this->ChipID.ProcessorName = "i80486SL"; break; + case 5: this->ChipID.ProcessorName = "i80486SX2"; break; + case 7: this->ChipID.ProcessorName = "i80486DX2 WriteBack"; break; + case 8: this->ChipID.ProcessorName = "i80486DX4"; break; + case 9: this->ChipID.ProcessorName = "i80486DX4 WriteBack"; break; + default: this->ChipID.ProcessorName = "Unknown 80486 family"; return false; } break; case 5: switch (this->ChipID.Model) { - case 0: sprintf (this->ChipID.ProcessorName,"P5 A-Step"); break; - case 1: sprintf (this->ChipID.ProcessorName,"P5"); break; - case 2: sprintf (this->ChipID.ProcessorName,"P54C"); break; - case 3: sprintf (this->ChipID.ProcessorName,"P24T OverDrive"); break; - case 4: sprintf (this->ChipID.ProcessorName,"P55C"); break; - case 7: sprintf (this->ChipID.ProcessorName,"P54C"); break; - case 8: sprintf (this->ChipID.ProcessorName,"P55C (0.25micron)"); break; - default: sprintf (this->ChipID.ProcessorName,"Unknown Pentium family"); return false; + case 0: this->ChipID.ProcessorName = "P5 A-Step"; break; + case 1: this->ChipID.ProcessorName = "P5"; break; + case 2: this->ChipID.ProcessorName = "P54C"; break; + case 3: this->ChipID.ProcessorName = "P24T OverDrive"; break; + case 4: this->ChipID.ProcessorName = "P55C"; break; + case 7: this->ChipID.ProcessorName = "P54C"; break; + case 8: this->ChipID.ProcessorName = "P55C (0.25micron)"; break; + default: this->ChipID.ProcessorName = "Unknown Pentium family"; return false; } break; case 6: switch (this->ChipID.Model) { - case 0: sprintf (this->ChipID.ProcessorName,"P6 A-Step"); break; - case 1: sprintf (this->ChipID.ProcessorName,"P6"); break; - case 3: sprintf (this->ChipID.ProcessorName,"Pentium II (0.28 micron)"); break; - case 5: sprintf (this->ChipID.ProcessorName,"Pentium II (0.25 micron)"); break; - case 6: sprintf (this->ChipID.ProcessorName,"Pentium II With On-Die L2 Cache"); break; - case 7: sprintf (this->ChipID.ProcessorName,"Pentium III (0.25 micron)"); break; - case 8: sprintf (this->ChipID.ProcessorName,"Pentium III (0.18 micron) With 256 KB On-Die L2 Cache "); break; - case 0xa: sprintf (this->ChipID.ProcessorName,"Pentium III (0.18 micron) With 1 Or 2 MB On-Die L2 Cache "); break; - case 0xb: sprintf (this->ChipID.ProcessorName,"Pentium III (0.13 micron) With 256 Or 512 KB On-Die L2 Cache "); break; - case 23: sprintf (this->ChipID.ProcessorName, "Intel(R) Core(TM)2 Duo CPU T9500 @ 2.60GHz"); break; - default: sprintf (this->ChipID.ProcessorName,"Unknown P6 family"); return false; + case 0: this->ChipID.ProcessorName = "P6 A-Step"; break; + case 1: this->ChipID.ProcessorName = "P6"; break; + case 3: this->ChipID.ProcessorName = "Pentium II (0.28 micron)"; break; + case 5: this->ChipID.ProcessorName = "Pentium II (0.25 micron)"; break; + case 6: this->ChipID.ProcessorName = "Pentium II With On-Die L2 Cache"; break; + case 7: this->ChipID.ProcessorName = "Pentium III (0.25 micron)"; break; + case 8: this->ChipID.ProcessorName = "Pentium III (0.18 micron) With 256 KB On-Die L2 Cache "; break; + case 0xa: this->ChipID.ProcessorName = "Pentium III (0.18 micron) With 1 Or 2 MB On-Die L2 Cache "; break; + case 0xb: this->ChipID.ProcessorName = "Pentium III (0.13 micron) With 256 Or 512 KB On-Die L2 Cache "; break; + case 23: this->ChipID.ProcessorName = "Intel(R) Core(TM)2 Duo CPU T9500 @ 2.60GHz"; break; + default: this->ChipID.ProcessorName = "Unknown P6 family"; return false; } break; case 7: - sprintf (this->ChipID.ProcessorName,"Intel Merced (IA-64)"); + this->ChipID.ProcessorName = "Intel Merced (IA-64)"; break; case 0xf: // Check the extended family bits... @@ -2054,21 +2051,21 @@ bool SystemInformationImplementation::RetrieveClassicalCPUIdentity() case 0: switch (this->ChipID.Model) { - case 0: sprintf (this->ChipID.ProcessorName,"Pentium IV (0.18 micron)"); break; - case 1: sprintf (this->ChipID.ProcessorName,"Pentium IV (0.18 micron)"); break; - case 2: sprintf (this->ChipID.ProcessorName,"Pentium IV (0.13 micron)"); break; - default: sprintf (this->ChipID.ProcessorName,"Unknown Pentium 4 family"); return false; + case 0: this->ChipID.ProcessorName = "Pentium IV (0.18 micron)"; break; + case 1: this->ChipID.ProcessorName = "Pentium IV (0.18 micron)"; break; + case 2: this->ChipID.ProcessorName = "Pentium IV (0.13 micron)"; break; + default: this->ChipID.ProcessorName = "Unknown Pentium 4 family"; return false; } break; case 1: - sprintf (this->ChipID.ProcessorName,"Intel McKinley (IA-64)"); + this->ChipID.ProcessorName = "Intel McKinley (IA-64)"; break; default: - sprintf (this->ChipID.ProcessorName,"Pentium"); + this->ChipID.ProcessorName = "Pentium"; } break; default: - sprintf (this->ChipID.ProcessorName,"Unknown Intel family"); + this->ChipID.ProcessorName = "Unknown Intel family"; return false; } break; @@ -2080,49 +2077,49 @@ bool SystemInformationImplementation::RetrieveClassicalCPUIdentity() case 4: switch (this->ChipID.Model) { - case 3: sprintf (this->ChipID.ProcessorName,"80486DX2"); break; - case 7: sprintf (this->ChipID.ProcessorName,"80486DX2 WriteBack"); break; - case 8: sprintf (this->ChipID.ProcessorName,"80486DX4"); break; - case 9: sprintf (this->ChipID.ProcessorName,"80486DX4 WriteBack"); break; - case 0xe: sprintf (this->ChipID.ProcessorName,"5x86"); break; - case 0xf: sprintf (this->ChipID.ProcessorName,"5x86WB"); break; - default: sprintf (this->ChipID.ProcessorName,"Unknown 80486 family"); return false; + case 3: this->ChipID.ProcessorName = "80486DX2"; break; + case 7: this->ChipID.ProcessorName = "80486DX2 WriteBack"; break; + case 8: this->ChipID.ProcessorName = "80486DX4"; break; + case 9: this->ChipID.ProcessorName = "80486DX4 WriteBack"; break; + case 0xe: this->ChipID.ProcessorName = "5x86"; break; + case 0xf: this->ChipID.ProcessorName = "5x86WB"; break; + default: this->ChipID.ProcessorName = "Unknown 80486 family"; return false; } break; case 5: switch (this->ChipID.Model) { - case 0: sprintf (this->ChipID.ProcessorName,"SSA5 (PR75, PR90, PR100)"); break; - case 1: sprintf (this->ChipID.ProcessorName,"5k86 (PR120, PR133)"); break; - case 2: sprintf (this->ChipID.ProcessorName,"5k86 (PR166)"); break; - case 3: sprintf (this->ChipID.ProcessorName,"5k86 (PR200)"); break; - case 6: sprintf (this->ChipID.ProcessorName,"K6 (0.30 micron)"); break; - case 7: sprintf (this->ChipID.ProcessorName,"K6 (0.25 micron)"); break; - case 8: sprintf (this->ChipID.ProcessorName,"K6-2"); break; - case 9: sprintf (this->ChipID.ProcessorName,"K6-III"); break; - case 0xd: sprintf (this->ChipID.ProcessorName,"K6-2+ or K6-III+ (0.18 micron)"); break; - default: sprintf (this->ChipID.ProcessorName,"Unknown 80586 family"); return false; + case 0: this->ChipID.ProcessorName = "SSA5 (PR75, PR90 = PR100)"; break; + case 1: this->ChipID.ProcessorName = "5k86 (PR120 = PR133)"; break; + case 2: this->ChipID.ProcessorName = "5k86 (PR166)"; break; + case 3: this->ChipID.ProcessorName = "5k86 (PR200)"; break; + case 6: this->ChipID.ProcessorName = "K6 (0.30 micron)"; break; + case 7: this->ChipID.ProcessorName = "K6 (0.25 micron)"; break; + case 8: this->ChipID.ProcessorName = "K6-2"; break; + case 9: this->ChipID.ProcessorName = "K6-III"; break; + case 0xd: this->ChipID.ProcessorName = "K6-2+ or K6-III+ (0.18 micron)"; break; + default: this->ChipID.ProcessorName = "Unknown 80586 family"; return false; } break; case 6: switch (this->ChipID.Model) { - case 1: sprintf (this->ChipID.ProcessorName,"Athlon- (0.25 micron)"); break; - case 2: sprintf (this->ChipID.ProcessorName,"Athlon- (0.18 micron)"); break; - case 3: sprintf (this->ChipID.ProcessorName,"Duron- (SF core)"); break; - case 4: sprintf (this->ChipID.ProcessorName,"Athlon- (Thunderbird core)"); break; - case 6: sprintf (this->ChipID.ProcessorName,"Athlon- (Palomino core)"); break; - case 7: sprintf (this->ChipID.ProcessorName,"Duron- (Morgan core)"); break; + case 1: this->ChipID.ProcessorName = "Athlon- (0.25 micron)"; break; + case 2: this->ChipID.ProcessorName = "Athlon- (0.18 micron)"; break; + case 3: this->ChipID.ProcessorName = "Duron- (SF core)"; break; + case 4: this->ChipID.ProcessorName = "Athlon- (Thunderbird core)"; break; + case 6: this->ChipID.ProcessorName = "Athlon- (Palomino core)"; break; + case 7: this->ChipID.ProcessorName = "Duron- (Morgan core)"; break; case 8: if (this->Features.ExtendedFeatures.SupportsMP) - sprintf (this->ChipID.ProcessorName,"Athlon - MP (Thoroughbred core)"); - else sprintf (this->ChipID.ProcessorName,"Athlon - XP (Thoroughbred core)"); + this->ChipID.ProcessorName = "Athlon - MP (Thoroughbred core)"; + else this->ChipID.ProcessorName = "Athlon - XP (Thoroughbred core)"; break; - default: sprintf (this->ChipID.ProcessorName,"Unknown K7 family"); return false; + default: this->ChipID.ProcessorName = "Unknown K7 family"; return false; } break; default: - sprintf (this->ChipID.ProcessorName,"Unknown AMD family"); + this->ChipID.ProcessorName = "Unknown AMD family"; return false; } break; @@ -2133,12 +2130,12 @@ bool SystemInformationImplementation::RetrieveClassicalCPUIdentity() case 5: switch (this->ChipID.Model) { - case 4: sprintf (this->ChipID.ProcessorName,"Crusoe TM3x00 and TM5x00"); break; - default: sprintf (this->ChipID.ProcessorName,"Unknown Crusoe family"); return false; + case 4: this->ChipID.ProcessorName = "Crusoe TM3x00 and TM5x00"; break; + default: this->ChipID.ProcessorName = "Unknown Crusoe family"; return false; } break; default: - sprintf (this->ChipID.ProcessorName,"Unknown Transmeta family"); + this->ChipID.ProcessorName = "Unknown Transmeta family"; return false; } break; @@ -2149,13 +2146,13 @@ bool SystemInformationImplementation::RetrieveClassicalCPUIdentity() case 5: switch (this->ChipID.Model) { - case 0: sprintf (this->ChipID.ProcessorName,"mP6 (0.25 micron)"); break; - case 2: sprintf (this->ChipID.ProcessorName,"mP6 (0.18 micron)"); break; - default: sprintf (this->ChipID.ProcessorName,"Unknown Rise family"); return false; + case 0: this->ChipID.ProcessorName = "mP6 (0.25 micron)"; break; + case 2: this->ChipID.ProcessorName = "mP6 (0.18 micron)"; break; + default: this->ChipID.ProcessorName = "Unknown Rise family"; return false; } break; default: - sprintf (this->ChipID.ProcessorName,"Unknown Rise family"); + this->ChipID.ProcessorName = "Unknown Rise family"; return false; } break; @@ -2166,13 +2163,13 @@ bool SystemInformationImplementation::RetrieveClassicalCPUIdentity() case 4: switch (this->ChipID.Model) { - case 1: sprintf (this->ChipID.ProcessorName,"U5D"); break; - case 2: sprintf (this->ChipID.ProcessorName,"U5S"); break; - default: sprintf (this->ChipID.ProcessorName,"Unknown UMC family"); return false; + case 1: this->ChipID.ProcessorName = "U5D"; break; + case 2: this->ChipID.ProcessorName = "U5S"; break; + default: this->ChipID.ProcessorName = "Unknown UMC family"; return false; } break; default: - sprintf (this->ChipID.ProcessorName,"Unknown UMC family"); + this->ChipID.ProcessorName = "Unknown UMC family"; return false; } break; @@ -2183,21 +2180,21 @@ bool SystemInformationImplementation::RetrieveClassicalCPUIdentity() case 5: switch (this->ChipID.Model) { - case 4: sprintf (this->ChipID.ProcessorName,"C6"); break; - case 8: sprintf (this->ChipID.ProcessorName,"C2"); break; - case 9: sprintf (this->ChipID.ProcessorName,"C3"); break; - default: sprintf (this->ChipID.ProcessorName,"Unknown IDT\\Centaur family"); return false; + case 4: this->ChipID.ProcessorName = "C6"; break; + case 8: this->ChipID.ProcessorName = "C2"; break; + case 9: this->ChipID.ProcessorName = "C3"; break; + default: this->ChipID.ProcessorName = "Unknown IDT\\Centaur family"; return false; } break; case 6: switch (this->ChipID.Model) { - case 6: sprintf (this->ChipID.ProcessorName,"VIA Cyrix III - Samuel"); break; - default: sprintf (this->ChipID.ProcessorName,"Unknown IDT\\Centaur family"); return false; + case 6: this->ChipID.ProcessorName = "VIA Cyrix III - Samuel"; break; + default: this->ChipID.ProcessorName = "Unknown IDT\\Centaur family"; return false; } break; default: - sprintf (this->ChipID.ProcessorName,"Unknown IDT\\Centaur family"); + this->ChipID.ProcessorName = "Unknown IDT\\Centaur family"; return false; } break; @@ -2208,32 +2205,32 @@ bool SystemInformationImplementation::RetrieveClassicalCPUIdentity() case 4: switch (this->ChipID.Model) { - case 4: sprintf (this->ChipID.ProcessorName,"MediaGX GX, GXm"); break; - case 9: sprintf (this->ChipID.ProcessorName,"5x86"); break; - default: sprintf (this->ChipID.ProcessorName,"Unknown Cx5x86 family"); return false; + case 4: this->ChipID.ProcessorName = "MediaGX GX = GXm"; break; + case 9: this->ChipID.ProcessorName = "5x86"; break; + default: this->ChipID.ProcessorName = "Unknown Cx5x86 family"; return false; } break; case 5: switch (this->ChipID.Model) { - case 2: sprintf (this->ChipID.ProcessorName,"Cx6x86"); break; - case 4: sprintf (this->ChipID.ProcessorName,"MediaGX GXm"); break; - default: sprintf (this->ChipID.ProcessorName,"Unknown Cx6x86 family"); return false; + case 2: this->ChipID.ProcessorName = "Cx6x86"; break; + case 4: this->ChipID.ProcessorName = "MediaGX GXm"; break; + default: this->ChipID.ProcessorName = "Unknown Cx6x86 family"; return false; } break; case 6: switch (this->ChipID.Model) { - case 0: sprintf (this->ChipID.ProcessorName,"6x86MX"); break; - case 5: sprintf (this->ChipID.ProcessorName,"Cyrix M2 Core"); break; - case 6: sprintf (this->ChipID.ProcessorName,"WinChip C5A Core"); break; - case 7: sprintf (this->ChipID.ProcessorName,"WinChip C5B\\C5C Core"); break; - case 8: sprintf (this->ChipID.ProcessorName,"WinChip C5C-T Core"); break; - default: sprintf (this->ChipID.ProcessorName,"Unknown 6x86MX\\Cyrix III family"); return false; + case 0: this->ChipID.ProcessorName = "6x86MX"; break; + case 5: this->ChipID.ProcessorName = "Cyrix M2 Core"; break; + case 6: this->ChipID.ProcessorName = "WinChip C5A Core"; break; + case 7: this->ChipID.ProcessorName = "WinChip C5B\\C5C Core"; break; + case 8: this->ChipID.ProcessorName = "WinChip C5C-T Core"; break; + default: this->ChipID.ProcessorName = "Unknown 6x86MX\\Cyrix III family"; return false; } break; default: - sprintf (this->ChipID.ProcessorName,"Unknown Cyrix family"); + this->ChipID.ProcessorName = "Unknown Cyrix family"; return false; } break; @@ -2244,21 +2241,21 @@ bool SystemInformationImplementation::RetrieveClassicalCPUIdentity() case 5: switch (this->ChipID.Model) { - case 0: sprintf (this->ChipID.ProcessorName,"Nx586 or Nx586FPU"); break; - default: sprintf (this->ChipID.ProcessorName,"Unknown NexGen family"); return false; + case 0: this->ChipID.ProcessorName = "Nx586 or Nx586FPU"; break; + default: this->ChipID.ProcessorName = "Unknown NexGen family"; return false; } break; default: - sprintf (this->ChipID.ProcessorName,"Unknown NexGen family"); + this->ChipID.ProcessorName = "Unknown NexGen family"; return false; } break; case NSC: - sprintf (this->ChipID.ProcessorName,"Cx486SLC \\ DLC \\ Cx486S A-Step"); + this->ChipID.ProcessorName = "Cx486SLC \\ DLC \\ Cx486S A-Step"; break; default: - sprintf (this->ChipID.ProcessorName,"Unknown family"); // We cannot identify the processor. + this->ChipID.ProcessorName = "Unknown family"; // We cannot identify the processor. return false; } @@ -2365,7 +2362,7 @@ int SystemInformationImplementation::RetreiveInformationFromCpuInfoFile() this->ChipID.Family = atoi(this->ExtractValueFromCpuInfoFile(buffer,"cpu family").c_str()); // Chip Vendor - strcpy(this->ChipID.Vendor,this->ExtractValueFromCpuInfoFile(buffer,"vendor_id").c_str()); + this->ChipID.Vendor = this->ExtractValueFromCpuInfoFile(buffer,"vendor_id"); this->FindManufacturer(); // Chip Model @@ -2395,11 +2392,13 @@ int SystemInformationImplementation::QueryMemory() #elif _WIN32 #if _MSC_VER < 1300 MEMORYSTATUS ms; + unsigned long tv, tp, av, ap; ms.dwLength = sizeof(ms); GlobalMemoryStatus(&ms); -#define MEM_VAL(value) dw##value + #define MEM_VAL(value) dw##value #else MEMORYSTATUSEX ms; + DWORDLONG tv, tp, av, ap; ms.dwLength = sizeof(ms); if (0 == GlobalMemoryStatusEx(&ms)) { @@ -2407,10 +2406,10 @@ int SystemInformationImplementation::QueryMemory() } #define MEM_VAL(value) ull##value #endif - unsigned long tv = ms.MEM_VAL(TotalVirtual); - unsigned long tp = ms.MEM_VAL(TotalPhys); - unsigned long av = ms.MEM_VAL(AvailVirtual); - unsigned long ap = ms.MEM_VAL(AvailPhys); + tv = ms.MEM_VAL(TotalVirtual); + tp = ms.MEM_VAL(TotalPhys); + av = ms.MEM_VAL(AvailVirtual); + ap = ms.MEM_VAL(AvailPhys); this->TotalVirtualMemory = tv>>10>>10; this->TotalPhysicalMemory = tp>>10>>10; this->AvailableVirtualMemory = av>>10>>10; @@ -2943,7 +2942,7 @@ bool SystemInformationImplementation::ParseSysCtl() len = sizeof(value); sysctlbyname("hw.cpufrequency", &value, &len, NULL, 0); - this->CPUSpeedInMHz = static_cast< float >( value )/ 1048576; + this->CPUSpeedInMHz = static_cast< float >( value )/ 1000000; // Chip family @@ -2962,7 +2961,7 @@ bool SystemInformationImplementation::ParseSysCtl() kwsys_stl::string machineBuf(retBuf); if (machineBuf.find_first_of("Power") != kwsys_stl::string::npos) { - strcpy(this->ChipID.Vendor, "IBM"); + this->ChipID.Vendor = "IBM"; len = 4; err = sysctlbyname("hw.cputype", &this->ChipID.Family, &len, NULL, 0); err = sysctlbyname("hw.cpusubtype", &this->ChipID.Model, &len, NULL, 0); @@ -2980,13 +2979,14 @@ bool SystemInformationImplementation::ParseSysCtl() len = 128; err = sysctlbyname("machdep.cpu.vendor", retBuf, &len, NULL, 0); // Chip Vendor - strcpy(this->ChipID.Vendor,retBuf); + this->ChipID.Vendor = retBuf; this->FindManufacturer(); - len=CHIPNAME_STRING_LENGTH; + ::memset(retBuf, 0, 128); err = sysctlbyname("machdep.cpu.brand_string", - this->ChipID.ProcessorName, &len, NULL, 0); + retBuf, &len, NULL, 0); + this->ChipID.ProcessorName = retBuf; // Chip Model len = sizeof(value); @@ -3173,11 +3173,11 @@ bool SystemInformationImplementation::QuerySolarisInfo() this->ChipID.Family = 0; // Chip Vendor - strcpy(this->ChipID.Vendor,"Sun"); + this->ChipID.Vendor = "Sun"; this->FindManufacturer(); // Chip Model - sprintf(this->ChipID.ProcessorName,"%s",this->ParseValueFromKStat("-s cpu_type").c_str()); + this->ChipID.ProcessorName = this->ParseValueFromKStat("-s cpu_type"); this->ChipID.Model = 0; // Cache size @@ -3231,7 +3231,7 @@ bool SystemInformationImplementation::QueryHaikuInfo() char vbuf[13]; strncpy(vbuf, cpu_info.eax_0.vendor_id, 12); vbuf[12] = '\0'; - strcpy(this->ChipID.Vendor,vbuf); + this->ChipID.Vendor = vbuf; this->FindManufacturer(); @@ -3272,6 +3272,89 @@ bool SystemInformationImplementation::QueryHaikuInfo() #endif } +bool SystemInformationImplementation::QueryQNXMemory() +{ +#if defined(__QNX__) + kwsys_stl::string buffer; + kwsys_stl::vector<const char*> args; + args.clear(); + + args.push_back("showmem"); + args.push_back("-S"); + args.push_back(0); + buffer = this->RunProcess(args); + args.clear(); + + size_t pos = buffer.find("System RAM:"); + if (pos == buffer.npos) + return false; + pos = buffer.find(":", pos); + size_t pos2 = buffer.find("M (", pos); + if (pos2 == buffer.npos) + return false; + + pos++; + while (buffer[pos] == ' ') + pos++; + + this->TotalPhysicalMemory = atoi(buffer.substr(pos, pos2 - pos).c_str()); + return true; +#endif + return false; +} + +bool SystemInformationImplementation::QueryQNXProcessor() +{ +#if defined(__QNX__) + // the output on my QNX 6.4.1 looks like this: + // Processor1: 686 Pentium II Stepping 3 2175MHz FPU + kwsys_stl::string buffer; + kwsys_stl::vector<const char*> args; + args.clear(); + + args.push_back("pidin"); + args.push_back("info"); + args.push_back(0); + buffer = this->RunProcess(args); + args.clear(); + + size_t pos = buffer.find("Processor1:"); + if (pos == buffer.npos) + return false; + + size_t pos2 = buffer.find("MHz", pos); + if (pos2 == buffer.npos) + return false; + + size_t pos3 = pos2; + while (buffer[pos3] != ' ') + --pos3; + + this->CPUSpeedInMHz = atoi(buffer.substr(pos3 + 1, pos2 - pos3 - 1).c_str()); + + pos2 = buffer.find(" Stepping", pos); + if (pos2 != buffer.npos) + { + pos2 = buffer.find(" ", pos2 + 1); + if (pos2 != buffer.npos && pos2 < pos3) + { + this->ChipID.Revision = atoi(buffer.substr(pos2 + 1, pos3 - pos2).c_str()); + } + } + + this->NumberOfPhysicalCPU = 0; + do + { + pos = buffer.find("\nProcessor", pos + 1); + ++this->NumberOfPhysicalCPU; + } while (pos != buffer.npos); + this->NumberOfLogicalCPU = 1; + + return true; +#else + return false; +#endif +} /** Query the operating system information */ bool SystemInformationImplementation::QueryOSInformation() @@ -3302,28 +3385,37 @@ bool SystemInformationImplementation::QueryOSInformation() { case VER_PLATFORM_WIN32_NT: // Test for the product. - if (osvi.dwMajorVersion <= 4) + if (osvi.dwMajorVersion <= 4) { this->OSRelease = "NT"; } - if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0) + if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0) { this->OSRelease = "2000"; } - if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1) + if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1) + { + this->OSRelease = "XP"; + } + // XP Professional x64 + if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2) { this->OSRelease = "XP"; } #ifdef VER_NT_WORKSTATION // Test for product type. - if (bOsVersionInfoEx) + if (bOsVersionInfoEx) { - if (osvi.wProductType == VER_NT_WORKSTATION) + if (osvi.wProductType == VER_NT_WORKSTATION) { - if (osvi.dwMajorVersion == 6) + if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 0) { this->OSRelease = "Vista"; } + if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 1) + { + this->OSRelease = "7"; + } // VER_SUITE_PERSONAL may not be defined #ifdef VER_SUITE_PERSONAL else diff --git a/Source/kwsys/SystemTools.cxx b/Source/kwsys/SystemTools.cxx index 1c00621..eefa7f5 100644 --- a/Source/kwsys/SystemTools.cxx +++ b/Source/kwsys/SystemTools.cxx @@ -9,6 +9,13 @@ implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the License for more information. ============================================================================*/ + +#ifdef __osf__ +# define _OSF_SOURCE +# define _POSIX_C_SOURCE 199506L +# define _XOPEN_SOURCE_EXTENDED +#endif + #include "kwsysPrivate.h" #include KWSYS_HEADER(RegularExpression.hxx) #include KWSYS_HEADER(SystemTools.hxx) @@ -371,9 +378,7 @@ void SystemTools::GetPath(kwsys_stl::vector<kwsys_stl::string>& path, const char kwsys_stl::string::size_type endpos = pathEnv.find(pathSep, start); if(endpos != kwsys_stl::string::npos) { - kwsys_stl::string convertedPath; - Realpath(pathEnv.substr(start, endpos-start).c_str(), convertedPath); - path.push_back(convertedPath); + path.push_back(pathEnv.substr(start, endpos-start)); start = endpos+1; } else @@ -558,6 +563,14 @@ void SystemTools::ReplaceString(kwsys_stl::string& source, static DWORD SystemToolsMakeRegistryMode(DWORD mode, SystemTools::KeyWOW64 view) { + // only add the modes when on a system that supports Wow64. + static FARPROC wow64p = GetProcAddress(GetModuleHandle("kernel32"), + "IsWow64Process"); + if(wow64p == NULL) + { + return mode; + } + if(view == SystemTools::KeyWOW64_32) { return mode | KWSYS_ST_KEY_WOW64_32KEY; @@ -729,10 +742,11 @@ bool SystemTools::WriteRegistryValue(const char *key, const char *value, HKEY hKey; DWORD dwDummy; + char lpClass[] = ""; if(RegCreateKeyEx(primaryKey, second.c_str(), 0, - "", + lpClass, REG_OPTION_NON_VOLATILE, SystemToolsMakeRegistryMode(KEY_WRITE, view), NULL, @@ -1398,6 +1412,10 @@ kwsys_stl::vector<kwsys::String> SystemTools::SplitString(const char* p, char se { kwsys_stl::string path = p; kwsys_stl::vector<kwsys::String> paths; + if(path.empty()) + { + return paths; + } if(isPath && path[0] == '/') { path.erase(path.begin()); @@ -1631,7 +1649,7 @@ kwsys_stl::string SystemTools::ConvertToUnixOutputPath(const char* path) kwsys_stl::string ret = path; // remove // except at the beginning might be a cygwin drive - kwsys_stl::string::size_type pos=0; + kwsys_stl::string::size_type pos=1; while((pos = ret.find("//", pos)) != kwsys_stl::string::npos) { ret.erase(pos, 1); @@ -1715,8 +1733,7 @@ kwsys_stl::string SystemTools::ConvertToWindowsOutputPath(const char* path) } bool SystemTools::CopyFileIfDifferent(const char* source, - const char* destination, - bool copyPermissions) + const char* destination) { // special check for a destination that is a directory // FilesDiffer does not handle file to directory compare @@ -1729,8 +1746,7 @@ bool SystemTools::CopyFileIfDifferent(const char* source, new_destination += SystemTools::GetFilenameName(source_name); if(SystemTools::FilesDiffer(source, new_destination.c_str())) { - return SystemTools::CopyFileAlways(source, destination, - copyPermissions); + return SystemTools::CopyFileAlways(source, destination); } else { @@ -1743,7 +1759,7 @@ bool SystemTools::CopyFileIfDifferent(const char* source, // are different if(SystemTools::FilesDiffer(source, destination)) { - return SystemTools::CopyFileAlways(source, destination, copyPermissions); + return SystemTools::CopyFileAlways(source, destination); } // at this point the files must be the same so return true return true; @@ -1829,8 +1845,7 @@ bool SystemTools::FilesDiffer(const char* source, /** * Copy a file named by "source" to the file named by "destination". */ -bool SystemTools::CopyFileAlways(const char* source, const char* destination, - bool copyPermissions) +bool SystemTools::CopyFileAlways(const char* source, const char* destination) { // If files are the same do not copy if ( SystemTools::SameFile(source, destination) ) @@ -1917,23 +1932,11 @@ bool SystemTools::CopyFileAlways(const char* source, const char* destination, fin.close(); fout.close(); - // More checks. - struct stat statSource, statDestination; - statSource.st_size = 12345; - statDestination.st_size = 12345; - if(stat(source, &statSource) != 0) - { - return false; - } - else if(stat(destination, &statDestination) != 0) + if(!fout) { return false; } - else if(statSource.st_size != statDestination.st_size) - { - return false; - } - if ( copyPermissions && perms ) + if ( perms ) { if ( !SystemTools::SetPermissions(destination, perm) ) { @@ -1945,15 +1948,15 @@ bool SystemTools::CopyFileAlways(const char* source, const char* destination, //---------------------------------------------------------------------------- bool SystemTools::CopyAFile(const char* source, const char* destination, - bool always, bool copyPermissions) + bool always) { if(always) { - return SystemTools::CopyFileAlways(source, destination, copyPermissions); + return SystemTools::CopyFileAlways(source, destination); } else { - return SystemTools::CopyFileIfDifferent(source, destination, copyPermissions); + return SystemTools::CopyFileIfDifferent(source, destination); } } @@ -1962,7 +1965,7 @@ bool SystemTools::CopyAFile(const char* source, const char* destination, * "destination". */ bool SystemTools::CopyADirectory(const char* source, const char* destination, - bool always, bool copyPermissions) + bool always) { Directory dir; dir.Load(source); @@ -1986,16 +1989,14 @@ bool SystemTools::CopyADirectory(const char* source, const char* destination, fullDestPath += dir.GetFile(static_cast<unsigned long>(fileNum)); if (!SystemTools::CopyADirectory(fullPath.c_str(), fullDestPath.c_str(), - always, - copyPermissions)) + always)) { return false; } } else { - if(!SystemTools::CopyAFile(fullPath.c_str(), destination, always, - copyPermissions)) + if(!SystemTools::CopyAFile(fullPath.c_str(), destination, always)) { return false; } @@ -3065,76 +3066,56 @@ kwsys_stl::string SystemTools::RelativePath(const char* local, const char* remot return relativePath; } -// OK, some fun stuff to get the actual case of a given path. -// Basically, you just need to call ShortPath, then GetLongPathName, -// However, GetLongPathName is not implemented on windows NT and 95, -// so we have to simulate it on those versions #ifdef _WIN32 -int OldWindowsGetLongPath(kwsys_stl::string const& shortPath, - kwsys_stl::string& longPath ) +static int GetCasePathName(const kwsys_stl::string & pathIn, + kwsys_stl::string & casePath) { - kwsys_stl::string::size_type iFound = shortPath.rfind('/'); - if (iFound > 1 && iFound != shortPath.npos) + kwsys_stl::vector<kwsys_stl::string> path_components; + SystemTools::SplitPath(pathIn.c_str(), path_components); + if(path_components[0].empty()) // First component always exists. { - // recurse to peel off components - // - if (OldWindowsGetLongPath(shortPath.substr(0, iFound), longPath) > 0) - { - longPath += '/'; - if (shortPath[1] != '/') - { - WIN32_FIND_DATA findData; - - // append the long component name to the path - // - if (INVALID_HANDLE_VALUE != ::FindFirstFile - (shortPath.c_str(), &findData)) - { - longPath += findData.cFileName; - } - else - { - // if FindFirstFile fails, return the error code - // - longPath = ""; - return 0; - } - } - } + // Relative paths cannot be converted. + casePath = ""; + return 0; } - else + + // Start with root component. + kwsys_stl::vector<kwsys_stl::string>::size_type idx = 0; + casePath = path_components[idx++]; + const char* sep = ""; + + // If network path, fill casePath with server/share so FindFirstFile + // will work after that. Maybe someday call other APIs to get + // actual case of servers and shares. + if(path_components.size() > 2 && path_components[0] == "//") { - longPath = shortPath; + casePath += path_components[idx++]; + casePath += "/"; + casePath += path_components[idx++]; + sep = "/"; } - return (int)longPath.size(); -} - -int PortableGetLongPathName(const char* pathIn, - kwsys_stl::string & longPath) -{ - HMODULE lh = LoadLibrary("Kernel32.dll"); - if(lh) + for(; idx < path_components.size(); idx++) { - FARPROC proc = GetProcAddress(lh, "GetLongPathNameA"); - if(proc) + casePath += sep; + sep = "/"; + kwsys_stl::string test_str = casePath; + test_str += path_components[idx]; + + WIN32_FIND_DATA findData; + HANDLE hFind = ::FindFirstFile(test_str.c_str(), &findData); + if (INVALID_HANDLE_VALUE != hFind) { - typedef DWORD (WINAPI * GetLongFunctionPtr) (LPCSTR,LPSTR,DWORD); - GetLongFunctionPtr func = (GetLongFunctionPtr)proc; - char buffer[MAX_PATH+1]; - int len = (*func)(pathIn, buffer, MAX_PATH+1); - if(len == 0 || len > MAX_PATH+1) - { - FreeLibrary(lh); - return 0; - } - longPath = buffer; - FreeLibrary(lh); - return len; + casePath += findData.cFileName; + ::FindClose(hFind); + } + else + { + casePath = ""; + return 0; } - FreeLibrary(lh); } - return OldWindowsGetLongPath(pathIn, longPath); + return (int)casePath.size(); } #endif @@ -3145,38 +3126,29 @@ kwsys_stl::string SystemTools::GetActualCaseForPath(const char* p) #ifndef _WIN32 return p; #else + kwsys_stl::string casePath = p; + // make sure drive letter is always upper case + if(casePath.size() > 1 && casePath[1] == ':') + { + casePath[0] = toupper(casePath[0]); + } + // Check to see if actual case has already been called // for this path, and the result is stored in the LongPathMap - SystemToolsTranslationMap::iterator i = - SystemTools::LongPathMap->find(p); + SystemToolsTranslationMap::iterator i = + SystemTools::LongPathMap->find(casePath); if(i != SystemTools::LongPathMap->end()) { return i->second; } - kwsys_stl::string shortPath; - if(!SystemTools::GetShortPath(p, shortPath)) - { - return p; - } - kwsys_stl::string longPath; - int len = PortableGetLongPathName(shortPath.c_str(), longPath); + int len = GetCasePathName(p, casePath); if(len == 0 || len > MAX_PATH+1) { return p; } - // Use original path if conversion back to a long path failed. - if(longPath == shortPath) - { - longPath = p; - } - // make sure drive letter is always upper case - if(longPath.size() > 1 && longPath[1] == ':') - { - longPath[0] = toupper(longPath[0]); - } - (*SystemTools::LongPathMap)[p] = longPath; - return longPath; -#endif + (*SystemTools::LongPathMap)[p] = casePath; + return casePath; +#endif } //---------------------------------------------------------------------------- @@ -3194,9 +3166,9 @@ const char* SystemTools::SplitPathRootComponent(const char* p, } c += 2; } - else if(c[0] == '/') + else if(c[0] == '/' || c[0] == '\\') { - // Unix path. + // Unix path (or Windows path w/out drive letter). if(root) { *root = "/"; diff --git a/Source/kwsys/SystemTools.hxx.in b/Source/kwsys/SystemTools.hxx.in index fd35742..cf47923 100644 --- a/Source/kwsys/SystemTools.hxx.in +++ b/Source/kwsys/SystemTools.hxx.in @@ -372,8 +372,8 @@ public: * "c:/" = Windows full path (can be any drive letter) * "c:" = Windows drive-letter relative path (can be any drive letter) * "//" = Network path - * "~" = Home path for current user - * "~u" = Home path for user 'u' + * "~/" = Home path for current user + * "~u/" = Home path for user 'u' * "" = Relative path * * A pointer to the rest of the path after the root component is @@ -385,7 +385,7 @@ public: /** * Split a path name into its basic components. The first component - * is one of the roots returned by SplitPathRootComponent. + * always exists and is the root returned by SplitPathRootComponent. * The remaining components form the path. If there is a trailing * slash then the last component is the empty string. The * components can be recombined as "c[0]c[1]/c[2]/.../c[n]" to @@ -500,14 +500,10 @@ public: /** * Copy the source file to the destination file only - * if the two files differ. If the "copyPermissions" - * argument is true, the permissions of the copy are - * set to be the same as the permissions of the - * original. + * if the two files differ. */ static bool CopyFileIfDifferent(const char* source, - const char* destination, - bool copyPermissions = true); + const char* destination); /** * Compare the contents of two files. Return true if different @@ -520,22 +516,17 @@ public: static bool SameFile(const char* file1, const char* file2); /** - * Copy a file. If the "copyPermissions" argument is true, the - * permissions of the copy are set to be the same as the permissions - * of the original. + * Copy a file. */ - static bool CopyFileAlways(const char* source, const char* destination, - bool copyPermissions = true); + static bool CopyFileAlways(const char* source, const char* destination); /** * Copy a file. If the "always" argument is true the file is always * copied. If it is false, the file is copied only if it is new or - * has changed. If the "copyPermissions" argument is true, the - * permissions of the copy are set to be the same as the permissions - * of the original. + * has changed. */ static bool CopyAFile(const char* source, const char* destination, - bool always = true, bool copyPermissions = true); + bool always = true); /** * Copy content directory to another directory with all files and @@ -544,7 +535,7 @@ public: * are new are copied. */ static bool CopyADirectory(const char* source, const char* destination, - bool always = true, bool copyPermissions = true); + bool always = true); /** * Remove a file diff --git a/Source/kwsys/hashtable.hxx.in b/Source/kwsys/hashtable.hxx.in index b36c975..db52fc8 100644 --- a/Source/kwsys/hashtable.hxx.in +++ b/Source/kwsys/hashtable.hxx.in @@ -38,6 +38,7 @@ # pragma warn -8027 /* 'for' not inlined. */ # pragma warn -8026 /* 'exception' not inlined. */ #endif + #ifndef @KWSYS_NAMESPACE@_hashtable_hxx #define @KWSYS_NAMESPACE@_hashtable_hxx @@ -57,6 +58,9 @@ # pragma warning (disable:4786) # pragma warning (disable:4512) /* no assignment operator for class */ #endif +#if defined(__sgi) && !defined(__GNUC__) +# pragma set woff 3970 /* pointer to int conversion */ 3321 3968 +#endif #if @KWSYS_NAMESPACE@_STL_HAS_ALLOCATOR_TEMPLATE # define @KWSYS_NAMESPACE@_HASH_DEFAULT_ALLOCATOR(T) @KWSYS_NAMESPACE@_stl::allocator< T > @@ -388,6 +392,10 @@ struct _Hashtable_const_iterator { // Note: assumes long is at least 32 bits. enum { _stl_num_primes = 31 }; +// create a function with a static local to that function that returns +// the static +inline const unsigned long* get_stl_prime_list() { + static const unsigned long _stl_prime_list[_stl_num_primes] = { 5ul, 11ul, 23ul, @@ -399,10 +407,12 @@ static const unsigned long _stl_prime_list[_stl_num_primes] = 1610612741ul, 3221225473ul, 4294967291ul }; +return &_stl_prime_list[0]; } + inline size_t _stl_next_prime(size_t __n) { - const unsigned long* __first = _stl_prime_list; - const unsigned long* __last = _stl_prime_list + (int)_stl_num_primes; + const unsigned long* __first = get_stl_prime_list(); + const unsigned long* __last = get_stl_prime_list() + (int)_stl_num_primes; const unsigned long* pos = @KWSYS_NAMESPACE@_stl::lower_bound(__first, __last, __n); return pos == __last ? *(__last - 1) : *pos; } @@ -587,7 +597,7 @@ public: size_type bucket_count() const { return _M_buckets.size(); } size_type max_bucket_count() const - { return _stl_prime_list[(int)_stl_num_primes - 1]; } + { return get_stl_prime_list()[(int)_stl_num_primes - 1]; } size_type elems_in_bucket(size_type __bucket) const { diff --git a/Source/kwsys/kwsysDateStamp.cmake b/Source/kwsys/kwsysDateStamp.cmake index be8d66f..d16795a 100644 --- a/Source/kwsys/kwsysDateStamp.cmake +++ b/Source/kwsys/kwsysDateStamp.cmake @@ -12,10 +12,10 @@ #============================================================================= # KWSys version date year component. Format is CCYY. -SET(KWSYS_DATE_STAMP_YEAR 2009) +SET(KWSYS_DATE_STAMP_YEAR 2011) # KWSys version date month component. Format is MM. -SET(KWSYS_DATE_STAMP_MONTH 12) +SET(KWSYS_DATE_STAMP_MONTH 01) # KWSys version date day component. Format is DD. -SET(KWSYS_DATE_STAMP_DAY 17) +SET(KWSYS_DATE_STAMP_DAY 26) diff --git a/Source/kwsys/kwsysPlatformTests.cmake b/Source/kwsys/kwsysPlatformTests.cmake index 994b7e7..d042450 100644 --- a/Source/kwsys/kwsysPlatformTests.cmake +++ b/Source/kwsys/kwsysPlatformTests.cmake @@ -177,7 +177,7 @@ MACRO(KWSYS_PLATFORM_INFO_TEST lang var description) ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_FILES_DIRECTORY}/${var}.bin) # Compile the test binary. - IF(NOT DEFINED ${var}_COMPILED) + IF(NOT EXISTS ${KWSYS_PLATFORM_INFO_FILE}) MESSAGE(STATUS "${description}") TRY_COMPILE(${var}_COMPILED ${CMAKE_CURRENT_BINARY_DIR} diff --git a/Source/kwsys/testAutoPtr.cxx b/Source/kwsys/testAutoPtr.cxx index 747d869..ed75ff4 100644 --- a/Source/kwsys/testAutoPtr.cxx +++ b/Source/kwsys/testAutoPtr.cxx @@ -25,7 +25,7 @@ #define ASSERT(x,y) if (!(x)) { printf("FAIL: " y "\n"); status = 1; } -static int instances = 0; +int instances = 0; // don't declare as static struct A { diff --git a/Source/kwsys/testProcess.c b/Source/kwsys/testProcess.c index 0060c4d..877002a 100644 --- a/Source/kwsys/testProcess.c +++ b/Source/kwsys/testProcess.c @@ -94,7 +94,11 @@ int test4(int argc, const char* argv[]) fprintf(stderr, "Output before crash on stderr from crash test.\n"); fflush(stdout); fflush(stderr); +#if defined(__clang__) + *(int*)1 = 0; /* Clang warns about 0-ptr; undefined behavior. */ +#else *(int*)0 = 0; +#endif fprintf(stdout, "Output after crash on stdout from crash test.\n"); fprintf(stderr, "Output after crash on stderr from crash test.\n"); return 0; diff --git a/Source/kwsys/testSystemTools.cxx b/Source/kwsys/testSystemTools.cxx index ad35c34..c0e74af 100644 --- a/Source/kwsys/testSystemTools.cxx +++ b/Source/kwsys/testSystemTools.cxx @@ -297,7 +297,7 @@ bool CheckStringOperations() if (kwsys::SystemTools::ConvertToUnixOutputPath ("//Local Mojo/Hex Power Pack/Iffy Voodoo") != - "/Local\\ Mojo/Hex\\ Power\\ Pack/Iffy\\ Voodoo") + "//Local\\ Mojo/Hex\\ Power\\ Pack/Iffy\\ Voodoo") { kwsys_ios::cerr << "Problem with ConvertToUnixOutputPath " |