Revise C++ coding style using clang-format

Run the `Utilities/Scripts/clang-format.bash` script to update
all our C++ code to a new style defined by `.clang-format`.
Use `clang-format` version 3.8.

* If you reached this commit for a line in `git blame`, re-run the blame
  operation starting at the parent of this commit to see older history
  for the content.

* See the parent commit for instructions to rebase a change across this
  style transition commit.
This commit is contained in:
Kitware Robot authored and Brad King committed 2016-05-16 16:05:19 -04:00
1 parent 82df6deaaf
commit d9fd2f5402
1450 files changed
+62404 -83728

No files matched your search

+5 -6
View File
@@ -1,19 +1,18 @@
#ifdef __cplusplus
# error "A C++ compiler has been selected for C."
#error "A C++ compiler has been selected for C."
#endif
#ifdef __CLASSIC_C__
# define const
#define const
#endif
#include "CMakeCompilerABI.h"
#ifdef __CLASSIC_C__
int main(argc, argv) int argc; char *argv[];
int main(argc, argv) int argc;
char* argv[];
#else
int main(int argc, char *argv[])
int main(int argc, char* argv[])
#endif
{
int require = 0;
+1 -3
View File
@@ -1,11 +1,9 @@
#ifndef __cplusplus
# error "A C compiler has been selected for C++."
#error "A C compiler has been selected for C++."
#endif
#include "CMakeCompilerABI.h"
int main(int argc, char* argv[])
{
int require = 0;
+11 -13
View File
@@ -1,34 +1,32 @@
/* Size of a pointer-to-data in bytes. */
#define SIZEOF_DPTR (sizeof(void*))
const char info_sizeof_dptr[] = {
'I', 'N', 'F', 'O', ':', 's', 'i', 'z', 'e', 'o', 'f', '_', 'd', 'p', 't', 'r', '[',
('0' + ((SIZEOF_DPTR / 10)%10)),
('0' + (SIZEOF_DPTR % 10)),
']','\0'
const char info_sizeof_dptr[] = {
'I', 'N', 'F', 'O', ':', 's', 'i', 'z', 'e', 'o', 'f', '_', 'd', 'p', 't',
'r', '[', ('0' + ((SIZEOF_DPTR / 10) % 10)), ('0' + (SIZEOF_DPTR % 10)), ']',
'\0'
/* clang-format needs this comment to break after the opening brace */
};
/* Application Binary Interface. */
#if defined(__sgi) && defined(_ABIO32)
# define ABI_ID "ELF O32"
#define ABI_ID "ELF O32"
#elif defined(__sgi) && defined(_ABIN32)
# define ABI_ID "ELF N32"
#define ABI_ID "ELF N32"
#elif defined(__sgi) && defined(_ABI64)
# define ABI_ID "ELF 64"
#define ABI_ID "ELF 64"
/* Check for (some) ARM ABIs.
* See e.g. http://wiki.debian.org/ArmEabiPort for some information on this. */
#elif defined(__GNU__) && defined(__ELF__) && defined(__ARM_EABI__)
# define ABI_ID "ELF ARMEABI"
#define ABI_ID "ELF ARMEABI"
#elif defined(__GNU__) && defined(__ELF__) && defined(__ARMEB__)
# define ABI_ID "ELF ARM"
#define ABI_ID "ELF ARM"
#elif defined(__GNU__) && defined(__ELF__) && defined(__ARMEL__)
# define ABI_ID "ELF ARM"
#define ABI_ID "ELF ARM"
#elif defined(__ELF__)
# define ABI_ID "ELF"
#define ABI_ID "ELF"
#endif
#if defined(ABI_ID)
+11 -8
View File
@@ -6,11 +6,13 @@ void* runner(void*);
int res = 0;
#ifdef __CLASSIC_C__
int main(){
int main()
{
int ac;
char*av[];
char* av[];
#else
int main(int ac, char*av[]){
int main(int ac, char* av[])
{
#endif
pthread_t tid[2];
pthread_create(&tid[0], 0, runner, (void*)1);
@@ -22,17 +24,18 @@ int main(int ac, char*av[]){
pthread_join(tid[0], 0);
pthread_join(tid[1], 0);
if(ac > 1000){return *av[0];}
if (ac > 1000) {
return *av[0];
}
return res;
}
void* runner(void* args)
{
int cc;
for ( cc = 0; cc < 10; cc ++ )
{
for (cc = 0; cc < 10; cc++) {
printf("%p CC: %d\n", args, cc);
}
res ++;
}
res++;
return 0;
}
+11 -9
View File
@@ -3,24 +3,26 @@
#ifdef __cplusplus
extern "C"
#endif
char CHECK_FUNCTION_EXISTS();
char
CHECK_FUNCTION_EXISTS();
#ifdef __CLASSIC_C__
int main(){
int main()
{
int ac;
char*av[];
char* av[];
#else
int main(int ac, char*av[]){
int main(int ac, char* av[])
{
#endif
CHECK_FUNCTION_EXISTS();
if(ac > 1000)
{
if (ac > 1000) {
return *av[0];
}
}
return 0;
}
#else /* CHECK_FUNCTION_EXISTS */
#else /* CHECK_FUNCTION_EXISTS */
# error "CHECK_FUNCTION_EXISTS has to specify the function"
#error "CHECK_FUNCTION_EXISTS has to specify the function"
#endif /* CHECK_FUNCTION_EXISTS */
+10 -6
View File
@@ -3,18 +3,22 @@
extern int CHECK_VARIABLE_EXISTS;
#ifdef __CLASSIC_C__
int main(){
int main()
{
int ac;
char*av[];
char* av[];
#else
int main(int ac, char*av[]){
int main(int ac, char* av[])
{
#endif
if(ac > 1000){return *av[0];}
if (ac > 1000) {
return *av[0];
}
return CHECK_VARIABLE_EXISTS;
}
#else /* CHECK_VARIABLE_EXISTS */
#else /* CHECK_VARIABLE_EXISTS */
# error "CHECK_VARIABLE_EXISTS has to specify the variable"
#error "CHECK_VARIABLE_EXISTS has to specify the variable"
#endif /* CHECK_VARIABLE_EXISTS */
+3 -1
View File
@@ -1 +1,3 @@
void my_module_(void) {}
void my_module_(void)
{
}
+3 -1
View File
@@ -1 +1,3 @@
void mymodule_(void) {}
void mymodule_(void)
{
}
+1 -1
View File
@@ -1,6 +1,6 @@
#include <iostream>
int main(int,char *[])
int main(int, char* [])
{
return 0;
}
+3 -2
View File
@@ -1,7 +1,8 @@
int main(int, char*[])
int main(int, char* [])
{
int i;
for(int i=0; i < 1; ++i);
for (int i = 0; i < 1; ++i)
;
(void)i;
return 0;
}
+3 -4
View File
@@ -1,11 +1,10 @@
#include <sstream>
int main(int, char*[])
int main(int, char* [])
{
std::ostringstream os;
os << "12345";
if(os.str().size() == 5)
{
if (os.str().size() == 5) {
return 0;
}
}
return -1;
}
+1 -1
View File
@@ -1,5 +1,5 @@
#include <list>
int main(int, char*[])
int main(int, char* [])
{
std::list<int>();
return 0;
+210 -295
View File
@@ -39,22 +39,22 @@ cmCPackIFWGenerator::~cmCPackIFWGenerator()
{
}
bool cmCPackIFWGenerator::IsVersionLess(const char *version)
bool cmCPackIFWGenerator::IsVersionLess(const char* version)
{
return cmSystemTools::VersionCompare(cmSystemTools::OP_LESS,
FrameworkVersion.data(), version);
FrameworkVersion.data(), version);
}
bool cmCPackIFWGenerator::IsVersionGreater(const char *version)
bool cmCPackIFWGenerator::IsVersionGreater(const char* version)
{
return cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER,
FrameworkVersion.data(), version);
FrameworkVersion.data(), version);
}
bool cmCPackIFWGenerator::IsVersionEqual(const char *version)
bool cmCPackIFWGenerator::IsVersionEqual(const char* version)
{
return cmSystemTools::VersionCompare(cmSystemTools::OP_EQUAL,
FrameworkVersion.data(), version);
FrameworkVersion.data(), version);
}
int cmCPackIFWGenerator::PackageFiles()
@@ -72,168 +72,141 @@ int cmCPackIFWGenerator::PackageFiles()
ifwTmpFile += "/IFWOutput.log";
// Run repogen
if (!Installer.Repositories.empty())
{
if (!Installer.Repositories.empty()) {
std::string ifwCmd = RepoGen;
if(IsVersionLess("2.0.0"))
{
if (IsVersionLess("2.0.0")) {
ifwCmd += " -c " + this->toplevel + "/config/config.xml";
}
}
ifwCmd += " -p " + this->toplevel + "/packages";
if(!PkgsDirsVector.empty())
{
for(std::vector<std::string>::iterator it = PkgsDirsVector.begin();
it != PkgsDirsVector.end(); ++it)
{
if (!PkgsDirsVector.empty()) {
for (std::vector<std::string>::iterator it = PkgsDirsVector.begin();
it != PkgsDirsVector.end(); ++it) {
ifwCmd += " -p " + *it;
}
}
}
if (!OnlineOnly && !DownloadedPackages.empty())
{
if (!OnlineOnly && !DownloadedPackages.empty()) {
ifwCmd += " -i ";
std::set<cmCPackIFWPackage*>::iterator it
= DownloadedPackages.begin();
std::set<cmCPackIFWPackage*>::iterator it = DownloadedPackages.begin();
ifwCmd += (*it)->Name;
++it;
while(it != DownloadedPackages.end())
{
while (it != DownloadedPackages.end()) {
ifwCmd += "," + (*it)->Name;
++it;
}
}
}
ifwCmd += " " + this->toplevel + "/repository";
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Execute: " << ifwCmd
<< std::endl);
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Execute: " << ifwCmd << std::endl);
std::string output;
int retVal = 1;
cmCPackLogger(cmCPackLog::LOG_OUTPUT,
"- Generate repository" << std::endl);
cmCPackLogger(cmCPackLog::LOG_OUTPUT, "- Generate repository"
<< std::endl);
bool res = cmSystemTools::RunSingleCommand(
ifwCmd.c_str(), &output, &output,
&retVal, 0, this->GeneratorVerbose, 0);
if ( !res || retVal )
{
ifwCmd.c_str(), &output, &output, &retVal, 0, this->GeneratorVerbose, 0);
if (!res || retVal) {
cmGeneratedFileStream ofs(ifwTmpFile.c_str());
ofs << "# Run command: " << ifwCmd << std::endl
<< "# Output:" << std::endl
<< output << std::endl;
cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem running IFW command: "
<< ifwCmd << std::endl
<< "Please check " << ifwTmpFile << " for errors"
<< std::endl);
<< ifwCmd << std::endl
<< "Please check " << ifwTmpFile << " for errors"
<< std::endl);
return 0;
}
cmCPackLogger(cmCPackLog::LOG_OUTPUT, "- repository: " << this->toplevel
<< "/repository generated" << std::endl);
}
cmCPackLogger(cmCPackLog::LOG_OUTPUT, "- repository: "
<< this->toplevel << "/repository generated" << std::endl);
}
// Run binary creator
{
std::string ifwCmd = BinCreator;
ifwCmd += " -c " + this->toplevel + "/config/config.xml";
ifwCmd += " -p " + this->toplevel + "/packages";
std::string ifwCmd = BinCreator;
ifwCmd += " -c " + this->toplevel + "/config/config.xml";
ifwCmd += " -p " + this->toplevel + "/packages";
if(!PkgsDirsVector.empty())
{
for(std::vector<std::string>::iterator it = PkgsDirsVector.begin();
it != PkgsDirsVector.end(); ++it)
{
ifwCmd += " -p " + *it;
if (!PkgsDirsVector.empty()) {
for (std::vector<std::string>::iterator it = PkgsDirsVector.begin();
it != PkgsDirsVector.end(); ++it) {
ifwCmd += " -p " + *it;
}
}
if (OnlineOnly)
{
ifwCmd += " --online-only";
}
else if (!DownloadedPackages.empty() && !Installer.Repositories.empty())
{
ifwCmd += " -e ";
std::set<cmCPackIFWPackage*>::iterator it
= DownloadedPackages.begin();
ifwCmd += (*it)->Name;
++it;
while(it != DownloadedPackages.end())
{
ifwCmd += "," + (*it)->Name;
if (OnlineOnly) {
ifwCmd += " --online-only";
} else if (!DownloadedPackages.empty() &&
!Installer.Repositories.empty()) {
ifwCmd += " -e ";
std::set<cmCPackIFWPackage*>::iterator it = DownloadedPackages.begin();
ifwCmd += (*it)->Name;
++it;
while (it != DownloadedPackages.end()) {
ifwCmd += "," + (*it)->Name;
++it;
}
}
else if (!DependentPackages.empty())
{
ifwCmd += " -i ";
// Binary
std::set<cmCPackIFWPackage*>::iterator bit = BinaryPackages.begin();
while(bit != BinaryPackages.end())
{
ifwCmd += (*bit)->Name + ",";
++bit;
} else if (!DependentPackages.empty()) {
ifwCmd += " -i ";
// Binary
std::set<cmCPackIFWPackage*>::iterator bit = BinaryPackages.begin();
while (bit != BinaryPackages.end()) {
ifwCmd += (*bit)->Name + ",";
++bit;
}
// Depend
DependenceMap::iterator it = DependentPackages.begin();
ifwCmd += it->second.Name;
++it;
while(it != DependentPackages.end())
{
ifwCmd += "," + it->second.Name;
// Depend
DependenceMap::iterator it = DependentPackages.begin();
ifwCmd += it->second.Name;
++it;
while (it != DependentPackages.end()) {
ifwCmd += "," + it->second.Name;
++it;
}
}
// TODO: set correct name for multipackages
if (!this->packageFileNames.empty())
{
ifwCmd += " " + packageFileNames[0];
// TODO: set correct name for multipackages
if (!this->packageFileNames.empty()) {
ifwCmd += " " + packageFileNames[0];
} else {
ifwCmd += " installer";
}
else
{
ifwCmd += " installer";
}
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Execute: " << ifwCmd
<< std::endl);
std::string output;
int retVal = 1;
cmCPackLogger(cmCPackLog::LOG_OUTPUT, "- Generate package" << std::endl);
bool res = cmSystemTools::RunSingleCommand(
ifwCmd.c_str(), &output, &output,
&retVal, 0, this->GeneratorVerbose, 0);
if ( !res || retVal )
{
cmGeneratedFileStream ofs(ifwTmpFile.c_str());
ofs << "# Run command: " << ifwCmd << std::endl
<< "# Output:" << std::endl
<< output << std::endl;
cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem running IFW command: "
<< ifwCmd << std::endl
<< "Please check " << ifwTmpFile << " for errors"
<< std::endl);
return 0;
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Execute: " << ifwCmd << std::endl);
std::string output;
int retVal = 1;
cmCPackLogger(cmCPackLog::LOG_OUTPUT, "- Generate package" << std::endl);
bool res = cmSystemTools::RunSingleCommand(
ifwCmd.c_str(), &output, &output, &retVal, 0, this->GeneratorVerbose, 0);
if (!res || retVal) {
cmGeneratedFileStream ofs(ifwTmpFile.c_str());
ofs << "# Run command: " << ifwCmd << std::endl
<< "# Output:" << std::endl
<< output << std::endl;
cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem running IFW command: "
<< ifwCmd << std::endl
<< "Please check " << ifwTmpFile << " for errors"
<< std::endl);
return 0;
}
}
return 1;
}
const char *cmCPackIFWGenerator::GetPackagingInstallPrefix()
const char* cmCPackIFWGenerator::GetPackagingInstallPrefix()
{
const char *defPrefix = cmCPackGenerator::GetPackagingInstallPrefix();
const char* defPrefix = cmCPackGenerator::GetPackagingInstallPrefix();
std::string tmpPref = defPrefix ? defPrefix : "";
if(this->Components.empty())
{
if (this->Components.empty()) {
tmpPref += "packages/" + GetRootPackageName() + "/data";
}
}
this->SetOption("CPACK_IFW_PACKAGING_INSTALL_PREFIX", tmpPref.c_str());
return this->GetOption("CPACK_IFW_PACKAGING_INSTALL_PREFIX");
}
const char *cmCPackIFWGenerator::GetOutputExtension()
const char* cmCPackIFWGenerator::GetOutputExtension()
{
return ExecutableSuffix.c_str();
}
@@ -246,56 +219,43 @@ int cmCPackIFWGenerator::InitializeInternal()
const std::string RepoGenOpt = "CPACK_IFW_REPOGEN_EXECUTABLE";
const std::string FrameworkVersionOpt = "CPACK_IFW_FRAMEWORK_VERSION";
if(!this->IsSet(BinCreatorOpt) ||
!this->IsSet(RepoGenOpt) ||
!this->IsSet(FrameworkVersionOpt))
{
if (!this->IsSet(BinCreatorOpt) || !this->IsSet(RepoGenOpt) ||
!this->IsSet(FrameworkVersionOpt)) {
this->ReadListFile("CPackIFW.cmake");
}
}
// Look 'binarycreator' executable (needs)
const char *BinCreatorStr = this->GetOption(BinCreatorOpt);
if(!BinCreatorStr || cmSystemTools::IsNOTFOUND(BinCreatorStr))
{
const char* BinCreatorStr = this->GetOption(BinCreatorOpt);
if (!BinCreatorStr || cmSystemTools::IsNOTFOUND(BinCreatorStr)) {
BinCreator = "";
}
else
{
} else {
BinCreator = BinCreatorStr;
}
}
if (BinCreator.empty())
{
if (BinCreator.empty()) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Cannot find QtIFW compiler \"binarycreator\": "
"likely it is not installed, or not in your PATH"
<< std::endl);
<< std::endl);
return 0;
}
}
// Look 'repogen' executable (optional)
const char *RepoGenStr = this->GetOption(RepoGenOpt);
if(!RepoGenStr || cmSystemTools::IsNOTFOUND(RepoGenStr))
{
const char* RepoGenStr = this->GetOption(RepoGenOpt);
if (!RepoGenStr || cmSystemTools::IsNOTFOUND(RepoGenStr)) {
RepoGen = "";
}
else
{
} else {
RepoGen = RepoGenStr;
}
}
// Framework version
if(const char* FrameworkVersionSrt =
this->GetOption(FrameworkVersionOpt))
{
if (const char* FrameworkVersionSrt = this->GetOption(FrameworkVersionOpt)) {
FrameworkVersion = FrameworkVersionSrt;
}
else
{
} else {
FrameworkVersion = "1.9.9";
}
}
// Variables that Change Behavior
@@ -304,158 +264,130 @@ int cmCPackIFWGenerator::InitializeInternal()
// Additional packages dirs
PkgsDirsVector.clear();
if(const char* dirs = this->GetOption("CPACK_IFW_PACKAGES_DIRECTORIES"))
{
cmSystemTools::ExpandListArgument(dirs,
PkgsDirsVector);
}
if (const char* dirs = this->GetOption("CPACK_IFW_PACKAGES_DIRECTORIES")) {
cmSystemTools::ExpandListArgument(dirs, PkgsDirsVector);
}
// Installer
Installer.Generator = this;
Installer.ConfigureFromOptions();
if (const char* ifwDownloadAll =
this->GetOption("CPACK_IFW_DOWNLOAD_ALL"))
{
if (const char* ifwDownloadAll = this->GetOption("CPACK_IFW_DOWNLOAD_ALL")) {
OnlineOnly = cmSystemTools::IsOn(ifwDownloadAll);
}
else if (const char* cpackDownloadAll =
this->GetOption("CPACK_DOWNLOAD_ALL"))
{
} else if (const char* cpackDownloadAll =
this->GetOption("CPACK_DOWNLOAD_ALL")) {
OnlineOnly = cmSystemTools::IsOn(cpackDownloadAll);
}
else
{
} else {
OnlineOnly = false;
}
}
if (!Installer.Repositories.empty() && RepoGen.empty()) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Cannot find QtIFW repository generator \"repogen\": "
"likely it is not installed, or not in your PATH"
<< std::endl);
return 0;
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Cannot find QtIFW repository generator \"repogen\": "
"likely it is not installed, or not in your PATH"
<< std::endl);
return 0;
}
// Executable suffix
if(const char *optExeSuffix = this->GetOption("CMAKE_EXECUTABLE_SUFFIX"))
{
if (const char* optExeSuffix = this->GetOption("CMAKE_EXECUTABLE_SUFFIX")) {
ExecutableSuffix = optExeSuffix;
if(ExecutableSuffix.empty())
{
if (ExecutableSuffix.empty()) {
std::string sysName(this->GetOption("CMAKE_SYSTEM_NAME"));
if(sysName == "Linux")
{
if (sysName == "Linux") {
ExecutableSuffix = ".run";
}
}
}
else
{
} else {
ExecutableSuffix = cmCPackGenerator::GetOutputExtension();
}
}
return this->Superclass::InitializeInternal();
}
std::string
cmCPackIFWGenerator::GetComponentInstallDirNameSuffix(
std::string cmCPackIFWGenerator::GetComponentInstallDirNameSuffix(
const std::string& componentName)
{
const std::string prefix = "packages/";
const std::string suffix = "/data";
if (componentPackageMethod == ONE_PACKAGE) {
return std::string(prefix + GetRootPackageName() + suffix);
return std::string(prefix + GetRootPackageName() + suffix);
}
return prefix
+ GetComponentPackageName(&Components[componentName])
+ suffix;
return prefix + GetComponentPackageName(&Components[componentName]) + suffix;
}
cmCPackComponent*
cmCPackIFWGenerator::GetComponent(const std::string &projectName,
const std::string &componentName)
cmCPackComponent* cmCPackIFWGenerator::GetComponent(
const std::string& projectName, const std::string& componentName)
{
ComponentsMap::iterator cit = Components.find(componentName);
if ( cit != Components.end() ) return &(cit->second);
if (cit != Components.end())
return &(cit->second);
cmCPackComponent* component
= cmCPackGenerator::GetComponent(projectName, componentName);
if(!component) return component;
cmCPackComponent* component =
cmCPackGenerator::GetComponent(projectName, componentName);
if (!component)
return component;
std::string name = GetComponentPackageName(component);
PackagesMap::iterator pit = Packages.find(name);
if(pit != Packages.end()) return component;
if (pit != Packages.end())
return component;
cmCPackIFWPackage *package = &Packages[name];
cmCPackIFWPackage* package = &Packages[name];
package->Name = name;
package->Generator = this;
if(package->ConfigureFromComponent(component))
{
if (package->ConfigureFromComponent(component)) {
package->Installer = &Installer;
Installer.Packages.insert(
std::pair<std::string, cmCPackIFWPackage*>(
name, package));
std::pair<std::string, cmCPackIFWPackage*>(name, package));
ComponentPackages.insert(
std::pair<cmCPackComponent*, cmCPackIFWPackage*>(
component, package));
if(component->IsDownloaded)
{
std::pair<cmCPackComponent*, cmCPackIFWPackage*>(component, package));
if (component->IsDownloaded) {
DownloadedPackages.insert(package);
}
else
{
} else {
BinaryPackages.insert(package);
}
}
else
{
} else {
Packages.erase(name);
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Cannot configure package \"" << name <<
"\" for component \"" << component->Name << "\""
<< std::endl);
}
cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot configure package \""
<< name << "\" for component \"" << component->Name << "\""
<< std::endl);
}
return component;
}
cmCPackComponentGroup*
cmCPackIFWGenerator::GetComponentGroup(const std::string &projectName,
const std::string &groupName)
cmCPackComponentGroup* cmCPackIFWGenerator::GetComponentGroup(
const std::string& projectName, const std::string& groupName)
{
cmCPackComponentGroup* group
= cmCPackGenerator::GetComponentGroup(projectName, groupName);
if(!group) return group;
cmCPackComponentGroup* group =
cmCPackGenerator::GetComponentGroup(projectName, groupName);
if (!group)
return group;
std::string name = GetGroupPackageName(group);
PackagesMap::iterator pit = Packages.find(name);
if(pit != Packages.end()) return group;
if (pit != Packages.end())
return group;
cmCPackIFWPackage *package = &Packages[name];
cmCPackIFWPackage* package = &Packages[name];
package->Name = name;
package->Generator = this;
if(package->ConfigureFromGroup(group))
{
if (package->ConfigureFromGroup(group)) {
package->Installer = &Installer;
Installer.Packages.insert(
std::pair<std::string, cmCPackIFWPackage*>(
name, package));
std::pair<std::string, cmCPackIFWPackage*>(name, package));
GroupPackages.insert(
std::pair<cmCPackComponentGroup*, cmCPackIFWPackage*>(
group, package));
std::pair<cmCPackComponentGroup*, cmCPackIFWPackage*>(group, package));
BinaryPackages.insert(package);
}
else
{
} else {
Packages.erase(name);
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Cannot configure package \"" << name <<
"\" for component group \"" << group->Name << "\""
<< std::endl);
}
cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot configure package \""
<< name << "\" for component group \"" << group->Name
<< "\"" << std::endl);
}
return group;
}
@@ -485,123 +417,106 @@ std::string cmCPackIFWGenerator::GetRootPackageName()
// Default value
std::string name = "root";
if (const char* optIFW_PACKAGE_GROUP =
this->GetOption("CPACK_IFW_PACKAGE_GROUP"))
{
this->GetOption("CPACK_IFW_PACKAGE_GROUP")) {
// Configure from root group
cmCPackIFWPackage package;
package.Generator = this;
package.ConfigureFromGroup(optIFW_PACKAGE_GROUP);
name = package.Name;
}
else if (const char* optIFW_PACKAGE_NAME =
this->GetOption("CPACK_IFW_PACKAGE_NAME"))
{
} else if (const char* optIFW_PACKAGE_NAME =
this->GetOption("CPACK_IFW_PACKAGE_NAME")) {
// Configure from root package name
name = optIFW_PACKAGE_NAME;
}
else if (const char* optPACKAGE_NAME =
this->GetOption("CPACK_PACKAGE_NAME"))
{
} else if (const char* optPACKAGE_NAME =
this->GetOption("CPACK_PACKAGE_NAME")) {
// Configure from package name
name = optPACKAGE_NAME;
}
}
return name;
}
std::string
cmCPackIFWGenerator::GetGroupPackageName(cmCPackComponentGroup *group) const
std::string cmCPackIFWGenerator::GetGroupPackageName(
cmCPackComponentGroup* group) const
{
std::string name;
if (!group) return name;
if (cmCPackIFWPackage* package = GetGroupPackage(group))
{
if (!group)
return name;
if (cmCPackIFWPackage* package = GetGroupPackage(group)) {
return package->Name;
}
const char* option = GetOption(
"CPACK_IFW_COMPONENT_GROUP_"
+ cmsys::SystemTools::UpperCase(group->Name)
+ "_NAME");
}
const char* option =
GetOption("CPACK_IFW_COMPONENT_GROUP_" +
cmsys::SystemTools::UpperCase(group->Name) + "_NAME");
name = option ? option : group->Name;
if(group->ParentGroup)
{
if (group->ParentGroup) {
cmCPackIFWPackage* package = GetGroupPackage(group->ParentGroup);
bool dot = !ResolveDuplicateNames;
if(dot && name.substr(0, package->Name.size()) == package->Name)
{
if (dot && name.substr(0, package->Name.size()) == package->Name) {
dot = false;
}
if(dot)
{
name = package->Name + "." + name;
}
}
if (dot) {
name = package->Name + "." + name;
}
}
return name;
}
std::string cmCPackIFWGenerator::GetComponentPackageName(
cmCPackComponent *component) const
cmCPackComponent* component) const
{
std::string name;
if (!component) return name;
if (cmCPackIFWPackage* package = GetComponentPackage(component))
{
if (!component)
return name;
if (cmCPackIFWPackage* package = GetComponentPackage(component)) {
return package->Name;
}
std::string prefix = "CPACK_IFW_COMPONENT_"
+ cmsys::SystemTools::UpperCase(component->Name)
+ "_";
}
std::string prefix = "CPACK_IFW_COMPONENT_" +
cmsys::SystemTools::UpperCase(component->Name) + "_";
const char* option = GetOption(prefix + "NAME");
name = option ? option : component->Name;
if(component->Group)
{
if (component->Group) {
cmCPackIFWPackage* package = GetGroupPackage(component->Group);
if((componentPackageMethod == ONE_PACKAGE_PER_GROUP)
|| IsOn(prefix + "COMMON"))
{
if ((componentPackageMethod == ONE_PACKAGE_PER_GROUP) ||
IsOn(prefix + "COMMON")) {
return package->Name;
}
bool dot = !ResolveDuplicateNames;
if(dot && name.substr(0, package->Name.size()) == package->Name)
{
dot = false;
}
if(dot)
{
name = package->Name + "." + name;
}
}
bool dot = !ResolveDuplicateNames;
if (dot && name.substr(0, package->Name.size()) == package->Name) {
dot = false;
}
if (dot) {
name = package->Name + "." + name;
}
}
return name;
}
cmCPackIFWPackage* cmCPackIFWGenerator::GetGroupPackage(
cmCPackComponentGroup *group) const
cmCPackComponentGroup* group) const
{
std::map<cmCPackComponentGroup*, cmCPackIFWPackage*>::const_iterator pit
= GroupPackages.find(group);
std::map<cmCPackComponentGroup*, cmCPackIFWPackage*>::const_iterator pit =
GroupPackages.find(group);
return pit != GroupPackages.end() ? pit->second : 0;
}
cmCPackIFWPackage* cmCPackIFWGenerator::GetComponentPackage(
cmCPackComponent *component) const
cmCPackComponent* component) const
{
std::map<cmCPackComponent*, cmCPackIFWPackage*>::const_iterator pit
= ComponentPackages.find(component);
std::map<cmCPackComponent*, cmCPackIFWPackage*>::const_iterator pit =
ComponentPackages.find(component);
return pit != ComponentPackages.end() ? pit->second : 0;
}
void cmCPackIFWGenerator::WriteGeneratedByToStrim(cmXMLWriter &xout)
void cmCPackIFWGenerator::WriteGeneratedByToStrim(cmXMLWriter& xout)
{
std::stringstream comment;
comment << "Generated by CPack " << CMake_VERSION << " IFW generator "
<< "for QtIFW ";
if(IsVersionLess("2.0"))
{
<< "for QtIFW ";
if (IsVersionLess("2.0")) {
comment << "less 2.0";
}
else
{
} else {
comment << FrameworkVersion;
}
}
comment << " tools at " << cmTimestamp().CurrentTime("", true);
xout.Comment(comment.str().c_str());
}
+10 -12
View File
@@ -49,17 +49,17 @@ public:
/**
* Compare \a version with QtIFW framework version
*/
bool IsVersionLess(const char *version);
bool IsVersionLess(const char* version);
/**
* Compare \a version with QtIFW framework version
*/
bool IsVersionGreater(const char *version);
bool IsVersionGreater(const char* version);
/**
* Compare \a version with QtIFW framework version
*/
bool IsVersionEqual(const char *version);
bool IsVersionEqual(const char* version);
protected:
// cmCPackGenerator reimplementation
@@ -90,9 +90,8 @@ protected:
*
* @return Pointer to component
*/
virtual cmCPackComponent* GetComponent(
const std::string& projectName,
const std::string& componentName);
virtual cmCPackComponent* GetComponent(const std::string& projectName,
const std::string& componentName);
/**
* @brief Get group of component
@@ -104,8 +103,7 @@ protected:
* @return Pointer to component group
*/
virtual cmCPackComponentGroup* GetComponentGroup(
const std::string& projectName,
const std::string& groupName);
const std::string& projectName, const std::string& groupName);
enum cmCPackGenerator::CPackSetDestdirSupport SupportsSetDestdir() const;
virtual bool SupportsAbsoluteDestination() const;
@@ -118,11 +116,11 @@ protected:
std::string GetRootPackageName();
std::string GetGroupPackageName(cmCPackComponentGroup *group) const;
std::string GetComponentPackageName(cmCPackComponent *component) const;
std::string GetGroupPackageName(cmCPackComponentGroup* group) const;
std::string GetComponentPackageName(cmCPackComponent* component) const;
cmCPackIFWPackage* GetGroupPackage(cmCPackComponentGroup *group) const;
cmCPackIFWPackage* GetComponentPackage(cmCPackComponent *component) const;
cmCPackIFWPackage* GetGroupPackage(cmCPackComponentGroup* group) const;
cmCPackIFWPackage* GetComponentPackage(cmCPackComponent* component) const;
void WriteGeneratedByToStrim(cmXMLWriter& xout);
+181 -278
View File
@@ -20,310 +20,239 @@
#include <cmXMLWriter.h>
#ifdef cmCPackLogger
# undef cmCPackLogger
#undef cmCPackLogger
#endif
#define cmCPackLogger(logType, msg) \
do { \
std::ostringstream cmCPackLog_msg; \
cmCPackLog_msg << msg; \
if(Generator) { \
Generator->Logger->Log(logType, __FILE__, __LINE__, \
cmCPackLog_msg.str().c_str()); \
} \
} while ( 0 )
#define cmCPackLogger(logType, msg) \
do { \
std::ostringstream cmCPackLog_msg; \
cmCPackLog_msg << msg; \
if (Generator) { \
Generator->Logger->Log(logType, __FILE__, __LINE__, \
cmCPackLog_msg.str().c_str()); \
} \
} while (0)
cmCPackIFWInstaller::cmCPackIFWInstaller() :
Generator(0)
cmCPackIFWInstaller::cmCPackIFWInstaller()
: Generator(0)
{
}
const char *cmCPackIFWInstaller::GetOption(const std::string &op) const
const char* cmCPackIFWInstaller::GetOption(const std::string& op) const
{
return Generator ? Generator->GetOption(op) : 0;
}
bool cmCPackIFWInstaller::IsOn(const std::string &op) const
bool cmCPackIFWInstaller::IsOn(const std::string& op) const
{
return Generator ? Generator->IsOn(op) : false;
}
bool cmCPackIFWInstaller::IsVersionLess(const char *version)
bool cmCPackIFWInstaller::IsVersionLess(const char* version)
{
return Generator ? Generator->IsVersionLess(version) : false;
}
bool cmCPackIFWInstaller::IsVersionGreater(const char *version)
bool cmCPackIFWInstaller::IsVersionGreater(const char* version)
{
return Generator ? Generator->IsVersionGreater(version) : false;
}
bool cmCPackIFWInstaller::IsVersionEqual(const char *version)
bool cmCPackIFWInstaller::IsVersionEqual(const char* version)
{
return Generator ? Generator->IsVersionEqual(version) : false;
}
void cmCPackIFWInstaller::ConfigureFromOptions()
{
// Name;
if (const char* optIFW_PACKAGE_NAME =
this->GetOption("CPACK_IFW_PACKAGE_NAME"))
{
this->GetOption("CPACK_IFW_PACKAGE_NAME")) {
Name = optIFW_PACKAGE_NAME;
}
else if (const char* optPACKAGE_NAME =
this->GetOption("CPACK_PACKAGE_NAME"))
{
} else if (const char* optPACKAGE_NAME =
this->GetOption("CPACK_PACKAGE_NAME")) {
Name = optPACKAGE_NAME;
}
else
{
} else {
Name = "Your package";
}
}
// Title;
if (const char* optIFW_PACKAGE_TITLE =
GetOption("CPACK_IFW_PACKAGE_TITLE"))
{
GetOption("CPACK_IFW_PACKAGE_TITLE")) {
Title = optIFW_PACKAGE_TITLE;
}
else if (const char* optPACKAGE_DESCRIPTION_SUMMARY =
GetOption("CPACK_PACKAGE_DESCRIPTION_SUMMARY"))
{
} else if (const char* optPACKAGE_DESCRIPTION_SUMMARY =
GetOption("CPACK_PACKAGE_DESCRIPTION_SUMMARY")) {
Title = optPACKAGE_DESCRIPTION_SUMMARY;
}
else
{
} else {
Title = "Your package description";
}
}
// Version;
if (const char* option = GetOption("CPACK_PACKAGE_VERSION"))
{
if (const char* option = GetOption("CPACK_PACKAGE_VERSION")) {
Version = option;
}
else
{
} else {
Version = "1.0.0";
}
}
// Publisher
if(const char* optIFW_PACKAGE_PUBLISHER =
GetOption("CPACK_IFW_PACKAGE_PUBLISHER"))
{
if (const char* optIFW_PACKAGE_PUBLISHER =
GetOption("CPACK_IFW_PACKAGE_PUBLISHER")) {
Publisher = optIFW_PACKAGE_PUBLISHER;
}
else if(const char* optPACKAGE_VENDOR = GetOption("CPACK_PACKAGE_VENDOR"))
{
} else if (const char* optPACKAGE_VENDOR =
GetOption("CPACK_PACKAGE_VENDOR")) {
Publisher = optPACKAGE_VENDOR;
}
}
// ProductUrl
if(const char* option = GetOption("CPACK_IFW_PRODUCT_URL"))
{
if (const char* option = GetOption("CPACK_IFW_PRODUCT_URL")) {
ProductUrl = option;
}
}
// ApplicationIcon
if(const char* option = GetOption("CPACK_IFW_PACKAGE_ICON"))
{
if(cmSystemTools::FileExists(option))
{
if (const char* option = GetOption("CPACK_IFW_PACKAGE_ICON")) {
if (cmSystemTools::FileExists(option)) {
InstallerApplicationIcon = option;
}
else
{
} else {
// TODO: implement warning
}
}
}
// WindowIcon
if(const char* option = GetOption("CPACK_IFW_PACKAGE_WINDOW_ICON"))
{
if(cmSystemTools::FileExists(option))
{
if (const char* option = GetOption("CPACK_IFW_PACKAGE_WINDOW_ICON")) {
if (cmSystemTools::FileExists(option)) {
InstallerWindowIcon = option;
}
else
{
} else {
// TODO: implement warning
}
}
}
// Logo
if(const char* option = GetOption("CPACK_IFW_PACKAGE_LOGO"))
{
if(cmSystemTools::FileExists(option))
{
if (const char* option = GetOption("CPACK_IFW_PACKAGE_LOGO")) {
if (cmSystemTools::FileExists(option)) {
Logo = option;
}
else
{
} else {
// TODO: implement warning
}
}
}
// Start menu
if (const char* optIFW_START_MENU_DIR =
this->GetOption("CPACK_IFW_PACKAGE_START_MENU_DIRECTORY"))
{
this->GetOption("CPACK_IFW_PACKAGE_START_MENU_DIRECTORY")) {
StartMenuDir = optIFW_START_MENU_DIR;
}
else
{
} else {
StartMenuDir = Name;
}
}
// Default target directory for installation
if (const char* optIFW_TARGET_DIRECTORY =
GetOption("CPACK_IFW_TARGET_DIRECTORY"))
{
GetOption("CPACK_IFW_TARGET_DIRECTORY")) {
TargetDir = optIFW_TARGET_DIRECTORY;
}
else if (const char *optPACKAGE_INSTALL_DIRECTORY =
GetOption("CPACK_PACKAGE_INSTALL_DIRECTORY"))
{
} else if (const char* optPACKAGE_INSTALL_DIRECTORY =
GetOption("CPACK_PACKAGE_INSTALL_DIRECTORY")) {
TargetDir = "@ApplicationsDir@/";
TargetDir += optPACKAGE_INSTALL_DIRECTORY;
}
else
{
} else {
TargetDir = "@RootDir@/usr/local";
}
}
// Default target directory for installation with administrator rights
if (const char* option = GetOption("CPACK_IFW_ADMIN_TARGET_DIRECTORY"))
{
if (const char* option = GetOption("CPACK_IFW_ADMIN_TARGET_DIRECTORY")) {
AdminTargetDir = option;
}
}
// Repositories
Repositories.clear();
RepositoryStruct Repo;
if(const char *site = this->GetOption("CPACK_DOWNLOAD_SITE"))
{
if (const char* site = this->GetOption("CPACK_DOWNLOAD_SITE")) {
Repo.Url = site;
Repositories.push_back(Repo);
}
if(const char *RepoAllStr = this->GetOption("CPACK_IFW_REPOSITORIES_ALL"))
{
}
if (const char* RepoAllStr = this->GetOption("CPACK_IFW_REPOSITORIES_ALL")) {
std::vector<std::string> RepoAllVector;
cmSystemTools::ExpandListArgument(RepoAllStr,
RepoAllVector);
for(std::vector<std::string>::iterator
rit = RepoAllVector.begin(); rit != RepoAllVector.end(); ++rit)
{
std::string prefix = "CPACK_IFW_REPOSITORY_"
+ cmsys::SystemTools::UpperCase(*rit)
+ "_";
// Url
if (const char* url = GetOption(prefix + "URL"))
{
Repo.Url = url;
}
else
{
Repo.Url = "";
}
// Enabled
if (IsOn(prefix + "DISABLED"))
{
Repo.Enabled = "0";
}
else
{
Repo.Enabled = "";
}
// Username
if (const char* username = GetOption(prefix + "USERNAME"))
{
Repo.Username = username;
}
else
{
Repo.Username = "";
}
// Password
if (const char* password = GetOption(prefix + "PASSWORD"))
{
Repo.Password = password;
}
else
{
Repo.Password = "";
}
// DisplayName
if (const char* displayName = GetOption(prefix + "DISPLAY_NAME"))
{
Repo.DisplayName = displayName;
}
else
{
Repo.DisplayName = "";
}
cmSystemTools::ExpandListArgument(RepoAllStr, RepoAllVector);
for (std::vector<std::string>::iterator rit = RepoAllVector.begin();
rit != RepoAllVector.end(); ++rit) {
std::string prefix =
"CPACK_IFW_REPOSITORY_" + cmsys::SystemTools::UpperCase(*rit) + "_";
// Url
if (const char* url = GetOption(prefix + "URL")) {
Repo.Url = url;
} else {
Repo.Url = "";
}
// Enabled
if (IsOn(prefix + "DISABLED")) {
Repo.Enabled = "0";
} else {
Repo.Enabled = "";
}
// Username
if (const char* username = GetOption(prefix + "USERNAME")) {
Repo.Username = username;
} else {
Repo.Username = "";
}
// Password
if (const char* password = GetOption(prefix + "PASSWORD")) {
Repo.Password = password;
} else {
Repo.Password = "";
}
// DisplayName
if (const char* displayName = GetOption(prefix + "DISPLAY_NAME")) {
Repo.DisplayName = displayName;
} else {
Repo.DisplayName = "";
}
if(!Repo.Url.empty())
{
Repositories.push_back(Repo);
}
if (!Repo.Url.empty()) {
Repositories.push_back(Repo);
}
}
}
// Maintenance tool
if(const char* optIFW_MAINTENANCE_TOOL =
this->GetOption("CPACK_IFW_PACKAGE_MAINTENANCE_TOOL_NAME"))
{
if (const char* optIFW_MAINTENANCE_TOOL =
this->GetOption("CPACK_IFW_PACKAGE_MAINTENANCE_TOOL_NAME")) {
MaintenanceToolName = optIFW_MAINTENANCE_TOOL;
}
}
// Maintenance tool ini file
if(const char* optIFW_MAINTENANCE_TOOL_INI =
this->GetOption("CPACK_IFW_PACKAGE_MAINTENANCE_TOOL_INI_FILE"))
{
if (const char* optIFW_MAINTENANCE_TOOL_INI =
this->GetOption("CPACK_IFW_PACKAGE_MAINTENANCE_TOOL_INI_FILE")) {
MaintenanceToolIniFile = optIFW_MAINTENANCE_TOOL_INI;
}
}
// Allow non-ASCII characters
if(this->GetOption("CPACK_IFW_PACKAGE_ALLOW_NON_ASCII_CHARACTERS"))
{
if(IsOn("CPACK_IFW_PACKAGE_ALLOW_NON_ASCII_CHARACTERS"))
{
if (this->GetOption("CPACK_IFW_PACKAGE_ALLOW_NON_ASCII_CHARACTERS")) {
if (IsOn("CPACK_IFW_PACKAGE_ALLOW_NON_ASCII_CHARACTERS")) {
AllowNonAsciiCharacters = "true";
}
else
{
} else {
AllowNonAsciiCharacters = "false";
}
}
}
// Space in path
if(this->GetOption("CPACK_IFW_PACKAGE_ALLOW_SPACE_IN_PATH"))
{
if(IsOn("CPACK_IFW_PACKAGE_ALLOW_SPACE_IN_PATH"))
{
if (this->GetOption("CPACK_IFW_PACKAGE_ALLOW_SPACE_IN_PATH")) {
if (IsOn("CPACK_IFW_PACKAGE_ALLOW_SPACE_IN_PATH")) {
AllowSpaceInPath = "true";
}
else
{
} else {
AllowSpaceInPath = "false";
}
}
}
// Control script
if(const char* optIFW_CONTROL_SCRIPT =
this->GetOption("CPACK_IFW_PACKAGE_CONTROL_SCRIPT"))
{
if (const char* optIFW_CONTROL_SCRIPT =
this->GetOption("CPACK_IFW_PACKAGE_CONTROL_SCRIPT")) {
ControlScript = optIFW_CONTROL_SCRIPT;
}
}
}
void cmCPackIFWInstaller::GenerateInstallerFile()
{
// Lazy directory initialization
if(Directory.empty() && Generator)
{
if (Directory.empty() && Generator) {
Directory = Generator->toplevel;
}
}
// Output stream
cmGeneratedFileStream fout((Directory + "/config/config.xml").data());
@@ -339,140 +268,118 @@ void cmCPackIFWInstaller::GenerateInstallerFile()
xout.Element("Version", Version);
xout.Element("Title", Title);
if(!Publisher.empty())
{
if (!Publisher.empty()) {
xout.Element("Publisher", Publisher);
}
}
if(!ProductUrl.empty())
{
if (!ProductUrl.empty()) {
xout.Element("ProductUrl", ProductUrl);
}
}
// ApplicationIcon
if(!InstallerApplicationIcon.empty())
{
if (!InstallerApplicationIcon.empty()) {
std::string name =
cmSystemTools::GetFilenameName(InstallerApplicationIcon);
std::string path = Directory + "/config/" + name;
name = cmSystemTools::GetFilenameWithoutExtension(name);
cmsys::SystemTools::CopyFileIfDifferent(
InstallerApplicationIcon.data(), path.data());
cmsys::SystemTools::CopyFileIfDifferent(InstallerApplicationIcon.data(),
path.data());
xout.Element("InstallerApplicationIcon", name);
}
}
// WindowIcon
if(!InstallerWindowIcon.empty())
{
if (!InstallerWindowIcon.empty()) {
std::string name = cmSystemTools::GetFilenameName(InstallerWindowIcon);
std::string path = Directory + "/config/" + name;
cmsys::SystemTools::CopyFileIfDifferent(
InstallerWindowIcon.data(), path.data());
cmsys::SystemTools::CopyFileIfDifferent(InstallerWindowIcon.data(),
path.data());
xout.Element("InstallerWindowIcon", name);
}
}
// Logo
if(!Logo.empty())
{
if (!Logo.empty()) {
std::string name = cmSystemTools::GetFilenameName(Logo);
std::string path = Directory + "/config/" + name;
cmsys::SystemTools::CopyFileIfDifferent(Logo.data(), path.data());
xout.Element("Logo", name);
}
}
// Start menu
if(!IsVersionLess("2.0"))
{
if (!IsVersionLess("2.0")) {
xout.Element("StartMenuDir", StartMenuDir);
}
}
// Target dir
if(!TargetDir.empty())
{
if (!TargetDir.empty()) {
xout.Element("TargetDir", TargetDir);
}
}
// Admin target dir
if(!AdminTargetDir.empty())
{
if (!AdminTargetDir.empty()) {
xout.Element("AdminTargetDir", AdminTargetDir);
}
}
// Remote repositories
if (!Repositories.empty())
{
if (!Repositories.empty()) {
xout.StartElement("RemoteRepositories");
for(std::vector<RepositoryStruct>::iterator
rit = Repositories.begin(); rit != Repositories.end(); ++rit)
{
for (std::vector<RepositoryStruct>::iterator rit = Repositories.begin();
rit != Repositories.end(); ++rit) {
xout.StartElement("Repository");
// Url
xout.Element("Url", rit->Url);
// Enabled
if(!rit->Enabled.empty())
{
if (!rit->Enabled.empty()) {
xout.Element("Enabled", rit->Enabled);
}
// Username
if(!rit->Username.empty())
{
xout.Element("Username", rit->Username);
}
// Password
if(!rit->Password.empty())
{
xout.Element("Password", rit->Password);
}
// DisplayName
if(!rit->DisplayName.empty())
{
xout.Element("DisplayName", rit->DisplayName);
}
xout.EndElement();
}
xout.EndElement();
// Username
if (!rit->Username.empty()) {
xout.Element("Username", rit->Username);
}
// Password
if (!rit->Password.empty()) {
xout.Element("Password", rit->Password);
}
// DisplayName
if (!rit->DisplayName.empty()) {
xout.Element("DisplayName", rit->DisplayName);
}
xout.EndElement();
}
xout.EndElement();
}
// Maintenance tool
if(!IsVersionLess("2.0") && !MaintenanceToolName.empty())
{
if (!IsVersionLess("2.0") && !MaintenanceToolName.empty()) {
xout.Element("MaintenanceToolName", MaintenanceToolName);
}
}
// Maintenance tool ini file
if(!IsVersionLess("2.0") && !MaintenanceToolIniFile.empty())
{
if (!IsVersionLess("2.0") && !MaintenanceToolIniFile.empty()) {
xout.Element("MaintenanceToolIniFile", MaintenanceToolIniFile);
}
}
// Different allows
if(IsVersionLess("2.0"))
{
if (IsVersionLess("2.0")) {
// CPack IFW default policy
xout.Comment("CPack IFW default policy for QtIFW less 2.0");
xout.Element("AllowNonAsciiCharacters", "true");
xout.Element("AllowSpaceInPath", "true");
} else {
if (!AllowNonAsciiCharacters.empty()) {
xout.Element("AllowNonAsciiCharacters", AllowNonAsciiCharacters);
}
else
{
if(!AllowNonAsciiCharacters.empty())
{
xout.Element("AllowNonAsciiCharacters", AllowNonAsciiCharacters);
}
if(!AllowSpaceInPath.empty())
{
xout.Element("AllowSpaceInPath", AllowSpaceInPath);
}
if (!AllowSpaceInPath.empty()) {
xout.Element("AllowSpaceInPath", AllowSpaceInPath);
}
}
// Control script (copy to config dir)
if(!IsVersionLess("2.0") && !ControlScript.empty())
{
if (!IsVersionLess("2.0") && !ControlScript.empty()) {
std::string name = cmSystemTools::GetFilenameName(ControlScript);
std::string path = Directory + "/config/" + name;
cmsys::SystemTools::CopyFileIfDifferent(ControlScript.data(), path.data());
xout.Element("ControlScript", name);
}
}
xout.EndElement();
xout.EndDocument();
@@ -480,36 +387,32 @@ void cmCPackIFWInstaller::GenerateInstallerFile()
void cmCPackIFWInstaller::GeneratePackageFiles()
{
if (Packages.empty() || Generator->IsOnePackage())
{
if (Packages.empty() || Generator->IsOnePackage()) {
// Generate default package
cmCPackIFWPackage package;
package.Generator = Generator;
package.Installer = this;
// Check package group
if (const char* option = GetOption("CPACK_IFW_PACKAGE_GROUP"))
{
if (const char* option = GetOption("CPACK_IFW_PACKAGE_GROUP")) {
package.ConfigureFromGroup(option);
package.ForcedInstallation = "true";
}
else
{
} else {
package.ConfigureFromOptions();
}
}
package.GeneratePackageFile();
return;
}
}
// Generate packages meta information
for(PackagesMap::iterator pit = Packages.begin();
pit != Packages.end(); ++pit)
{
for (PackagesMap::iterator pit = Packages.begin(); pit != Packages.end();
++pit) {
cmCPackIFWPackage* package = pit->second;
package->GeneratePackageFile();
}
}
void cmCPackIFWInstaller::WriteGeneratedByToStrim(cmXMLWriter &xout)
void cmCPackIFWInstaller::WriteGeneratedByToStrim(cmXMLWriter& xout)
{
if(Generator) Generator->WriteGeneratedByToStrim(xout);
if (Generator)
Generator->WriteGeneratedByToStrim(xout);
}
+3 -3
View File
@@ -103,9 +103,9 @@ public:
const char* GetOption(const std::string& op) const;
bool IsOn(const std::string& op) const;
bool IsVersionLess(const char *version);
bool IsVersionGreater(const char *version);
bool IsVersionEqual(const char *version);
bool IsVersionLess(const char* version);
bool IsVersionGreater(const char* version);
bool IsVersionEqual(const char* version);
void ConfigureFromOptions();
+156 -233
View File
@@ -22,21 +22,21 @@
//----------------------------------------------------------------- Logger ---
#ifdef cmCPackLogger
# undef cmCPackLogger
#undef cmCPackLogger
#endif
#define cmCPackLogger(logType, msg) \
do { \
std::ostringstream cmCPackLog_msg; \
cmCPackLog_msg << msg; \
if(Generator) { \
Generator->Logger->Log(logType, __FILE__, __LINE__, \
cmCPackLog_msg.str().c_str()); \
} \
} while ( 0 )
#define cmCPackLogger(logType, msg) \
do { \
std::ostringstream cmCPackLog_msg; \
cmCPackLog_msg << msg; \
if (Generator) { \
Generator->Logger->Log(logType, __FILE__, __LINE__, \
cmCPackLog_msg.str().c_str()); \
} \
} while (0)
//---------------------------------------------------------- CompareStruct ---
cmCPackIFWPackage::CompareStruct::CompareStruct() :
Type(CompareNone)
cmCPackIFWPackage::CompareStruct::CompareStruct()
: Type(CompareNone)
{
}
@@ -46,64 +46,47 @@ cmCPackIFWPackage::DependenceStruct::DependenceStruct()
}
cmCPackIFWPackage::DependenceStruct::DependenceStruct(
const std::string &dependence)
const std::string& dependence)
{
// Search compare section
size_t pos = std::string::npos;
if((pos = dependence.find("<=")) != std::string::npos)
{
if ((pos = dependence.find("<=")) != std::string::npos) {
Compare.Type = CompareLessOrEqual;
Compare.Value = dependence.substr(pos + 2);
}
else if((pos = dependence.find(">=")) != std::string::npos)
{
} else if ((pos = dependence.find(">=")) != std::string::npos) {
Compare.Type = CompareGreaterOrEqual;
Compare.Value = dependence.substr(pos + 2);
}
else if((pos = dependence.find("<")) != std::string::npos)
{
} else if ((pos = dependence.find("<")) != std::string::npos) {
Compare.Type = CompareLess;
Compare.Value = dependence.substr(pos + 1);
}
else if((pos = dependence.find("=")) != std::string::npos)
{
} else if ((pos = dependence.find("=")) != std::string::npos) {
Compare.Type = CompareEqual;
Compare.Value = dependence.substr(pos + 1);
}
else if((pos = dependence.find(">")) != std::string::npos)
{
} else if ((pos = dependence.find(">")) != std::string::npos) {
Compare.Type = CompareGreater;
Compare.Value = dependence.substr(pos + 1);
}
}
Name = pos == std::string::npos ? dependence : dependence.substr(0, pos);
}
std::string cmCPackIFWPackage::DependenceStruct::NameWithCompare() const
{
if (Compare.Type == CompareNone) return Name;
if (Compare.Type == CompareNone)
return Name;
std::string result = Name;
if (Compare.Type == CompareLessOrEqual)
{
if (Compare.Type == CompareLessOrEqual) {
result += "<=";
}
else if (Compare.Type == CompareGreaterOrEqual)
{
} else if (Compare.Type == CompareGreaterOrEqual) {
result += ">=";
}
else if (Compare.Type == CompareLess)
{
} else if (Compare.Type == CompareLess) {
result += "<";
}
else if (Compare.Type == CompareEqual)
{
} else if (Compare.Type == CompareEqual) {
result += "=";
}
else if (Compare.Type == CompareGreater)
{
} else if (Compare.Type == CompareGreater) {
result += ">";
}
}
result += Compare.Value;
@@ -111,45 +94,45 @@ std::string cmCPackIFWPackage::DependenceStruct::NameWithCompare() const
}
//------------------------------------------------------ cmCPackIFWPackage ---
cmCPackIFWPackage::cmCPackIFWPackage() :
Generator(0),
Installer(0)
cmCPackIFWPackage::cmCPackIFWPackage()
: Generator(0)
, Installer(0)
{
}
const char *cmCPackIFWPackage::GetOption(const std::string &op) const
const char* cmCPackIFWPackage::GetOption(const std::string& op) const
{
const char *option = Generator ? Generator->GetOption(op) : 0;
const char* option = Generator ? Generator->GetOption(op) : 0;
return option && *option ? option : 0;
}
bool cmCPackIFWPackage::IsOn(const std::string &op) const
bool cmCPackIFWPackage::IsOn(const std::string& op) const
{
return Generator ? Generator->IsOn(op) : false;
}
bool cmCPackIFWPackage::IsVersionLess(const char *version)
bool cmCPackIFWPackage::IsVersionLess(const char* version)
{
return Generator ? Generator->IsVersionLess(version) : false;
}
bool cmCPackIFWPackage::IsVersionGreater(const char *version)
bool cmCPackIFWPackage::IsVersionGreater(const char* version)
{
return Generator ? Generator->IsVersionGreater(version) : false;
}
bool cmCPackIFWPackage::IsVersionEqual(const char *version)
bool cmCPackIFWPackage::IsVersionEqual(const char* version)
{
return Generator ? Generator->IsVersionEqual(version) : false;
}
std::string cmCPackIFWPackage::GetComponentName(cmCPackComponent *component)
std::string cmCPackIFWPackage::GetComponentName(cmCPackComponent* component)
{
if (!component) return "";
const char* option = GetOption(
"CPACK_IFW_COMPONENT_"
+ cmsys::SystemTools::UpperCase(component->Name)
+ "_NAME");
if (!component)
return "";
const char* option =
GetOption("CPACK_IFW_COMPONENT_" +
cmsys::SystemTools::UpperCase(component->Name) + "_NAME");
return option ? option : component->Name;
}
@@ -177,51 +160,42 @@ int cmCPackIFWPackage::ConfigureFromOptions()
Name = Generator->GetRootPackageName();
// Display name
if (const char *option = this->GetOption("CPACK_PACKAGE_NAME"))
{
if (const char* option = this->GetOption("CPACK_PACKAGE_NAME")) {
DisplayName = option;
}
else
{
} else {
DisplayName = "Your package";
}
}
// Description
if (const char* option =
this->GetOption("CPACK_PACKAGE_DESCRIPTION_SUMMARY"))
{
this->GetOption("CPACK_PACKAGE_DESCRIPTION_SUMMARY")) {
Description = option;
}
else
{
} else {
Description = "Your package description";
}
}
// Version
if(const char* option = GetOption("CPACK_PACKAGE_VERSION"))
{
if (const char* option = GetOption("CPACK_PACKAGE_VERSION")) {
Version = option;
}
else
{
} else {
Version = "1.0.0";
}
}
ForcedInstallation = "true";
return 1;
}
int cmCPackIFWPackage::ConfigureFromComponent(cmCPackComponent *component)
int cmCPackIFWPackage::ConfigureFromComponent(cmCPackComponent* component)
{
if(!component) return 0;
if (!component)
return 0;
// Restore defaul configuration
DefaultConfiguration();
std::string prefix = "CPACK_IFW_COMPONENT_"
+ cmsys::SystemTools::UpperCase(component->Name)
+ "_";
std::string prefix = "CPACK_IFW_COMPONENT_" +
cmsys::SystemTools::UpperCase(component->Name) + "_";
// Display name
DisplayName = component->DisplayName;
@@ -230,81 +204,65 @@ int cmCPackIFWPackage::ConfigureFromComponent(cmCPackComponent *component)
Description = component->Description;
// Version
if(const char* optVERSION = GetOption(prefix + "VERSION"))
{
if (const char* optVERSION = GetOption(prefix + "VERSION")) {
Version = optVERSION;
}
else if(const char* optPACKAGE_VERSION =
GetOption("CPACK_PACKAGE_VERSION"))
{
} else if (const char* optPACKAGE_VERSION =
GetOption("CPACK_PACKAGE_VERSION")) {
Version = optPACKAGE_VERSION;
}
else
{
} else {
Version = "1.0.0";
}
}
// Script
if (const char* option = GetOption(prefix + "SCRIPT"))
{
if (const char* option = GetOption(prefix + "SCRIPT")) {
Script = option;
}
}
// CMake dependencies
if (!component->Dependencies.empty())
{
if (!component->Dependencies.empty()) {
std::vector<cmCPackComponent*>::iterator dit;
for(dit = component->Dependencies.begin();
dit != component->Dependencies.end();
++dit)
{
for (dit = component->Dependencies.begin();
dit != component->Dependencies.end(); ++dit) {
Dependencies.insert(Generator->ComponentPackages[*dit]);
}
}
}
// QtIFW dependencies
if(const char* option = this->GetOption(prefix + "DEPENDS"))
{
if (const char* option = this->GetOption(prefix + "DEPENDS")) {
std::vector<std::string> deps;
cmSystemTools::ExpandListArgument(option,
deps);
for(std::vector<std::string>::iterator
dit = deps.begin(); dit != deps.end(); ++dit)
{
cmSystemTools::ExpandListArgument(option, deps);
for (std::vector<std::string>::iterator dit = deps.begin();
dit != deps.end(); ++dit) {
DependenceStruct dep(*dit);
if (!Generator->Packages.count(dep.Name))
{
if (!Generator->Packages.count(dep.Name)) {
bool hasDep = Generator->DependentPackages.count(dep.Name) > 0;
DependenceStruct &depRef =
Generator->DependentPackages[dep.Name];
if(!hasDep)
{
DependenceStruct& depRef = Generator->DependentPackages[dep.Name];
if (!hasDep) {
depRef = dep;
}
AlienDependencies.insert(&depRef);
}
AlienDependencies.insert(&depRef);
}
}
}
// Licenses
if (const char* option = this->GetOption(prefix + "LICENSES"))
{
if (const char* option = this->GetOption(prefix + "LICENSES")) {
Licenses.clear();
cmSystemTools::ExpandListArgument( option, Licenses );
if ( Licenses.size() % 2 != 0 )
{
cmCPackLogger(cmCPackLog::LOG_WARNING, prefix << "LICENSES"
<< " should contain pairs of <display_name> and <file_path>."
<< std::endl);
cmSystemTools::ExpandListArgument(option, Licenses);
if (Licenses.size() % 2 != 0) {
cmCPackLogger(
cmCPackLog::LOG_WARNING, prefix
<< "LICENSES"
<< " should contain pairs of <display_name> and <file_path>."
<< std::endl);
Licenses.clear();
}
}
}
// Priority
if(const char* option = this->GetOption(prefix + "PRIORITY"))
{
if (const char* option = this->GetOption(prefix + "PRIORITY")) {
SortingPriority = option;
}
}
// Default
Default = component->IsDisabledByDefault ? "false" : "true";
@@ -318,87 +276,74 @@ int cmCPackIFWPackage::ConfigureFromComponent(cmCPackComponent *component)
return 1;
}
int
cmCPackIFWPackage::ConfigureFromGroup(cmCPackComponentGroup *group)
int cmCPackIFWPackage::ConfigureFromGroup(cmCPackComponentGroup* group)
{
if(!group) return 0;
if (!group)
return 0;
// Restore defaul configuration
DefaultConfiguration();
std::string prefix = "CPACK_IFW_COMPONENT_GROUP_"
+ cmsys::SystemTools::UpperCase(group->Name)
+ "_";
std::string prefix = "CPACK_IFW_COMPONENT_GROUP_" +
cmsys::SystemTools::UpperCase(group->Name) + "_";
DisplayName = group->DisplayName;
Description = group->Description;
// Version
if(const char* optVERSION = GetOption(prefix + "VERSION"))
{
if (const char* optVERSION = GetOption(prefix + "VERSION")) {
Version = optVERSION;
}
else if(const char* optPACKAGE_VERSION =
GetOption("CPACK_PACKAGE_VERSION"))
{
} else if (const char* optPACKAGE_VERSION =
GetOption("CPACK_PACKAGE_VERSION")) {
Version = optPACKAGE_VERSION;
}
else
{
} else {
Version = "1.0.0";
}
}
// Script
if (const char* option = GetOption(prefix + "SCRIPT"))
{
if (const char* option = GetOption(prefix + "SCRIPT")) {
Script = option;
}
}
// Licenses
if (const char* option = this->GetOption(prefix + "LICENSES"))
{
if (const char* option = this->GetOption(prefix + "LICENSES")) {
Licenses.clear();
cmSystemTools::ExpandListArgument( option, Licenses );
if ( Licenses.size() % 2 != 0 )
{
cmCPackLogger(cmCPackLog::LOG_WARNING, prefix << "LICENSES"
<< " should contain pairs of <display_name> and <file_path>."
<< std::endl);
cmSystemTools::ExpandListArgument(option, Licenses);
if (Licenses.size() % 2 != 0) {
cmCPackLogger(
cmCPackLog::LOG_WARNING, prefix
<< "LICENSES"
<< " should contain pairs of <display_name> and <file_path>."
<< std::endl);
Licenses.clear();
}
}
}
// Priority
if(const char* option = this->GetOption(prefix + "PRIORITY"))
{
if (const char* option = this->GetOption(prefix + "PRIORITY")) {
SortingPriority = option;
}
}
return 1;
}
int cmCPackIFWPackage::ConfigureFromGroup(const std::string &groupName)
int cmCPackIFWPackage::ConfigureFromGroup(const std::string& groupName)
{
// Group configuration
cmCPackComponentGroup group;
std::string prefix = "CPACK_COMPONENT_GROUP_"
+ cmsys::SystemTools::UpperCase(groupName)
+ "_";
std::string prefix =
"CPACK_COMPONENT_GROUP_" + cmsys::SystemTools::UpperCase(groupName) + "_";
if (const char *option = GetOption(prefix + "DISPLAY_NAME"))
{
if (const char* option = GetOption(prefix + "DISPLAY_NAME")) {
group.DisplayName = option;
}
else
{
} else {
group.DisplayName = group.Name;
}
}
if (const char* option = GetOption(prefix + "DESCRIPTION"))
{
if (const char* option = GetOption(prefix + "DESCRIPTION")) {
group.Description = option;
}
}
group.IsBold = IsOn(prefix + "BOLD_TITLE");
group.IsExpandedByDefault = IsOn(prefix + "EXPANDED");
@@ -406,14 +351,11 @@ int cmCPackIFWPackage::ConfigureFromGroup(const std::string &groupName)
group.Name = groupName;
if(Generator)
{
if (Generator) {
Name = Generator->GetGroupPackageName(&group);
}
else
{
} else {
Name = group.Name;
}
}
return ConfigureFromGroup(&group);
}
@@ -421,17 +363,13 @@ int cmCPackIFWPackage::ConfigureFromGroup(const std::string &groupName)
void cmCPackIFWPackage::GeneratePackageFile()
{
// Lazy directory initialization
if (Directory.empty())
{
if(Installer)
{
if (Directory.empty()) {
if (Installer) {
Directory = Installer->Directory + "/packages/" + Name;
}
else if (Generator)
{
} else if (Generator) {
Directory = Generator->toplevel + "/packages/" + Name;
}
}
}
// Output stream
cmGeneratedFileStream fout((Directory + "/meta/package.xml").data());
@@ -448,98 +386,83 @@ void cmCPackIFWPackage::GeneratePackageFile()
xout.Element("Name", Name);
xout.Element("Version", Version);
if (!ReleaseDate.empty())
{
if (!ReleaseDate.empty()) {
xout.Element("ReleaseDate", ReleaseDate);
}
else
{
} else {
xout.Element("ReleaseDate", cmTimestamp().CurrentTime("%Y-%m-%d", true));
}
}
// Script (copy to meta dir)
if(!Script.empty())
{
if (!Script.empty()) {
std::string name = cmSystemTools::GetFilenameName(Script);
std::string path = Directory + "/meta/" + name;
cmsys::SystemTools::CopyFileIfDifferent(Script.data(), path.data());
xout.Element("Script", name);
}
}
// Dependencies
std::set<DependenceStruct> compDepSet;
for(std::set<DependenceStruct*>::iterator ait = AlienDependencies.begin();
ait != AlienDependencies.end(); ++ait)
{
for (std::set<DependenceStruct*>::iterator ait = AlienDependencies.begin();
ait != AlienDependencies.end(); ++ait) {
compDepSet.insert(*(*ait));
}
for(std::set<cmCPackIFWPackage*>::iterator it = Dependencies.begin();
it != Dependencies.end(); ++it)
{
}
for (std::set<cmCPackIFWPackage*>::iterator it = Dependencies.begin();
it != Dependencies.end(); ++it) {
compDepSet.insert(DependenceStruct((*it)->Name));
}
}
// Write dependencies
if (!compDepSet.empty())
{
if (!compDepSet.empty()) {
std::stringstream dependencies;
std::set<DependenceStruct>::iterator it = compDepSet.begin();
dependencies << it->NameWithCompare();
++it;
while(it != compDepSet.end())
{
while (it != compDepSet.end()) {
dependencies << "," << it->NameWithCompare();
++it;
}
xout.Element("Dependencies", dependencies.str());
}
xout.Element("Dependencies", dependencies.str());
}
// Licenses (copy to meta dir)
std::vector<std::string> licenses = Licenses;
for(size_t i = 1; i < licenses.size(); i += 2)
{
for (size_t i = 1; i < licenses.size(); i += 2) {
std::string name = cmSystemTools::GetFilenameName(licenses[i]);
std::string path = Directory + "/meta/" + name;
cmsys::SystemTools::CopyFileIfDifferent(licenses[i].data(), path.data());
licenses[i] = name;
}
if(!licenses.empty())
{
}
if (!licenses.empty()) {
xout.StartElement("Licenses");
for(size_t i = 0; i < licenses.size(); i += 2)
{
for (size_t i = 0; i < licenses.size(); i += 2) {
xout.StartElement("License");
xout.Attribute("name", licenses[i]);
xout.Attribute("file", licenses[i + 1]);
xout.EndElement();
}
}
xout.EndElement();
}
}
if (!ForcedInstallation.empty())
{
if (!ForcedInstallation.empty()) {
xout.Element("ForcedInstallation", ForcedInstallation);
}
}
if (!Virtual.empty())
{
if (!Virtual.empty()) {
xout.Element("Virtual", Virtual);
}
else if (!Default.empty())
{
} else if (!Default.empty()) {
xout.Element("Default", Default);
}
}
// Priority
if(!SortingPriority.empty())
{
if (!SortingPriority.empty()) {
xout.Element("SortingPriority", SortingPriority);
}
}
xout.EndElement();
xout.EndDocument();
}
void cmCPackIFWPackage::WriteGeneratedByToStrim(cmXMLWriter &xout)
void cmCPackIFWPackage::WriteGeneratedByToStrim(cmXMLWriter& xout)
{
if(Generator) Generator->WriteGeneratedByToStrim(xout);
if (Generator)
Generator->WriteGeneratedByToStrim(xout);
}
+16 -16
View File
@@ -31,11 +31,11 @@ public:
enum CompareTypes
{
CompareNone = 0x0,
CompareEqual = 0x1,
CompareLess = 0x2,
CompareLessOrEqual = 0x3,
CompareGreater = 0x4,
CompareNone = 0x0,
CompareEqual = 0x1,
CompareLess = 0x2,
CompareLessOrEqual = 0x3,
CompareGreater = 0x4,
CompareGreaterOrEqual = 0x5
};
@@ -50,17 +50,17 @@ public:
struct DependenceStruct
{
DependenceStruct();
DependenceStruct(const std::string &dependence);
DependenceStruct(const std::string& dependence);
std::string Name;
CompareStruct Compare;
std::string NameWithCompare() const;
bool operator < (const DependenceStruct &other) const
{
bool operator<(const DependenceStruct& other) const
{
return Name < other.Name;
}
}
};
public:
@@ -113,18 +113,18 @@ public:
const char* GetOption(const std::string& op) const;
bool IsOn(const std::string& op) const;
bool IsVersionLess(const char *version);
bool IsVersionGreater(const char *version);
bool IsVersionEqual(const char *version);
bool IsVersionLess(const char* version);
bool IsVersionGreater(const char* version);
bool IsVersionEqual(const char* version);
std::string GetComponentName(cmCPackComponent *component);
std::string GetComponentName(cmCPackComponent* component);
void DefaultConfiguration();
int ConfigureFromOptions();
int ConfigureFromComponent(cmCPackComponent *component);
int ConfigureFromGroup(cmCPackComponentGroup *group);
int ConfigureFromGroup(const std::string &groupName);
int ConfigureFromComponent(cmCPackComponent* component);
int ConfigureFromGroup(cmCPackComponentGroup* group);
int ConfigureFromGroup(const std::string& groupName);
void GeneratePackageFile();
+37 -55
View File
@@ -20,72 +20,65 @@
// For the PATH_MAX constant
#include <sys/syslimits.h>
#define DebugError(x) \
ofs << x << std::endl; \
#define DebugError(x) \
ofs << x << std::endl; \
std::cout << x << std::endl
int main(int argc, char* argv[])
{
//if ( cmsys::SystemTools::FileExists(
// if ( cmsys::SystemTools::FileExists(
std::string cwd = cmsys::SystemTools::GetCurrentWorkingDirectory();
cmsys::ofstream ofs("/tmp/output.txt");
CFStringRef fileName;
CFBundleRef appBundle;
CFURLRef scriptFileURL;
UInt8 *path;
UInt8* path;
//get CF URL for script
if (! (appBundle = CFBundleGetMainBundle()))
{
// get CF URL for script
if (!(appBundle = CFBundleGetMainBundle())) {
DebugError("Cannot get main bundle");
return 1;
}
}
fileName = CFSTR("RuntimeScript");
if (! (scriptFileURL = CFBundleCopyResourceURL(appBundle, fileName, NULL,
NULL)))
{
if (!(scriptFileURL =
CFBundleCopyResourceURL(appBundle, fileName, NULL, NULL))) {
DebugError("CFBundleCopyResourceURL failed");
return 1;
}
}
//create path string
if (! (path = new UInt8[PATH_MAX]))
{
// create path string
if (!(path = new UInt8[PATH_MAX])) {
return 1;
}
}
//get the file system path of the url as a cstring
//in an encoding suitable for posix apis
if ( CFURLGetFileSystemRepresentation(scriptFileURL, true, path,
PATH_MAX) == false)
{
// get the file system path of the url as a cstring
// in an encoding suitable for posix apis
if (CFURLGetFileSystemRepresentation(scriptFileURL, true, path, PATH_MAX) ==
false) {
DebugError("CFURLGetFileSystemRepresentation failed");
return 1;
}
}
//dispose of the CF variable
// dispose of the CF variable
CFRelease(scriptFileURL);
std::string fullScriptPath = reinterpret_cast<char*>(path);
delete [] path;
delete[] path;
if (! cmsys::SystemTools::FileExists(fullScriptPath.c_str()))
{
if (!cmsys::SystemTools::FileExists(fullScriptPath.c_str())) {
return 1;
}
}
std::string scriptDirectory = cmsys::SystemTools::GetFilenamePath(
fullScriptPath);
std::string scriptDirectory =
cmsys::SystemTools::GetFilenamePath(fullScriptPath);
ofs << fullScriptPath.c_str() << std::endl;
std::vector<const char*> args;
args.push_back(fullScriptPath.c_str());
int cc;
for ( cc = 1; cc < argc; ++ cc )
{
for (cc = 1; cc < argc; ++cc) {
args.push_back(argv[cc]);
}
}
args.push_back(0);
cmsysProcess* cp = cmsysProcess_New();
@@ -98,49 +91,38 @@ int main(int argc, char* argv[])
std::vector<char> tempOutput;
char* data;
int length;
while(cmsysProcess_WaitForData(cp, &data, &length, 0))
{
while (cmsysProcess_WaitForData(cp, &data, &length, 0)) {
// Translate NULL characters in the output into valid text.
// Visual Studio 7 puts these characters in the output of its
// build process.
for(int i=0; i < length; ++i)
{
if(data[i] == '\0')
{
for (int i = 0; i < length; ++i) {
if (data[i] == '\0') {
data[i] = ' ';
}
}
std::cout.write(data, length);
}
std::cout.write(data, length);
}
cmsysProcess_WaitForExit(cp, 0);
bool result = true;
if(cmsysProcess_GetState(cp) == cmsysProcess_State_Exited)
{
if ( cmsysProcess_GetExitValue(cp) != 0 )
{
if (cmsysProcess_GetState(cp) == cmsysProcess_State_Exited) {
if (cmsysProcess_GetExitValue(cp) != 0) {
result = false;
}
}
else if(cmsysProcess_GetState(cp) == cmsysProcess_State_Exception)
{
} else if (cmsysProcess_GetState(cp) == cmsysProcess_State_Exception) {
const char* exception_str = cmsysProcess_GetExceptionString(cp);
std::cerr << exception_str << std::endl;
result = false;
}
else if(cmsysProcess_GetState(cp) == cmsysProcess_State_Error)
{
} else if (cmsysProcess_GetState(cp) == cmsysProcess_State_Error) {
const char* error_str = cmsysProcess_GetErrorString(cp);
std::cerr << error_str << std::endl;
result = false;
}
else if(cmsysProcess_GetState(cp) == cmsysProcess_State_Expired)
{
} else if (cmsysProcess_GetState(cp) == cmsysProcess_State_Expired) {
const char* error_str = "Process terminated due to timeout\n";
std::cerr << error_str << std::endl;
result = false;
}
}
cmsysProcess_Delete(cp);
+350 -481
View File
@@ -32,18 +32,16 @@
#include <rpc.h> // for GUID generation
cmCPackWIXGenerator::cmCPackWIXGenerator():
Patch(0)
cmCPackWIXGenerator::cmCPackWIXGenerator()
: Patch(0)
{
}
cmCPackWIXGenerator::~cmCPackWIXGenerator()
{
if(this->Patch)
{
if (this->Patch) {
delete this->Patch;
}
}
}
int cmCPackWIXGenerator::InitializeInternal()
@@ -58,41 +56,39 @@ bool cmCPackWIXGenerator::RunWiXCommand(std::string const& command)
{
std::string logFileName = this->CPackTopLevel + "/wix.log";
cmCPackLogger(cmCPackLog::LOG_DEBUG,
"Running WiX command: " << command << std::endl);
cmCPackLogger(cmCPackLog::LOG_DEBUG, "Running WiX command: " << command
<< std::endl);
std::string output;
int returnValue = 0;
bool status = cmSystemTools::RunSingleCommand(
command.c_str(), &output, &output,
&returnValue, 0, cmSystemTools::OUTPUT_NONE);
bool status = cmSystemTools::RunSingleCommand(command.c_str(), &output,
&output, &returnValue, 0,
cmSystemTools::OUTPUT_NONE);
cmsys::ofstream logFile(logFileName.c_str(), std::ios::app);
logFile << command << std::endl;
logFile << output;
logFile.close();
if(!status || returnValue)
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Problem running WiX candle. "
"Please check '" << logFileName << "' for errors." << std::endl);
if (!status || returnValue) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem running WiX candle. "
"Please check '"
<< logFileName << "' for errors." << std::endl);
return false;
}
}
return true;
}
bool cmCPackWIXGenerator::RunCandleCommand(
std::string const& sourceFile, std::string const& objectFile)
bool cmCPackWIXGenerator::RunCandleCommand(std::string const& sourceFile,
std::string const& objectFile)
{
std::string executable;
if(!RequireOption("CPACK_WIX_CANDLE_EXECUTABLE", executable))
{
if (!RequireOption("CPACK_WIX_CANDLE_EXECUTABLE", executable)) {
return false;
}
}
std::stringstream command;
command << QuotePath(executable);
@@ -100,11 +96,10 @@ bool cmCPackWIXGenerator::RunCandleCommand(
command << " -arch " << GetArchitecture();
command << " -out " << QuotePath(objectFile);
for(extension_set_t::const_iterator i = CandleExtensions.begin();
i != CandleExtensions.end(); ++i)
{
for (extension_set_t::const_iterator i = CandleExtensions.begin();
i != CandleExtensions.end(); ++i) {
command << " -ext " << QuotePath(*i);
}
}
AddCustomFlags("CPACK_WIX_CANDLE_EXTRA_FLAGS", command);
@@ -116,27 +111,24 @@ bool cmCPackWIXGenerator::RunCandleCommand(
bool cmCPackWIXGenerator::RunLightCommand(std::string const& objectFiles)
{
std::string executable;
if(!RequireOption("CPACK_WIX_LIGHT_EXECUTABLE", executable))
{
if (!RequireOption("CPACK_WIX_LIGHT_EXECUTABLE", executable)) {
return false;
}
}
std::stringstream command;
command << QuotePath(executable);
command << " -nologo";
command << " -out " << QuotePath(packageFileNames.at(0));
for(extension_set_t::const_iterator i = this->LightExtensions.begin();
i != this->LightExtensions.end(); ++i)
{
for (extension_set_t::const_iterator i = this->LightExtensions.begin();
i != this->LightExtensions.end(); ++i) {
command << " -ext " << QuotePath(*i);
}
}
const char* const cultures = GetOption("CPACK_WIX_CULTURES");
if(cultures)
{
if (cultures) {
command << " -cultures:" << cultures;
}
}
AddCustomFlags("CPACK_WIX_LIGHT_EXTRA_FLAGS", command);
@@ -147,90 +139,80 @@ bool cmCPackWIXGenerator::RunLightCommand(std::string const& objectFiles)
int cmCPackWIXGenerator::PackageFiles()
{
if(!PackageFilesImpl() || cmSystemTools::GetErrorOccuredFlag())
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Fatal WiX Generator Error" << std::endl);
if (!PackageFilesImpl() || cmSystemTools::GetErrorOccuredFlag()) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Fatal WiX Generator Error"
<< std::endl);
return false;
}
}
return true;
}
bool cmCPackWIXGenerator::InitializeWiXConfiguration()
{
if(!ReadListFile("CPackWIX.cmake"))
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error while executing CPackWIX.cmake" << std::endl);
if (!ReadListFile("CPackWIX.cmake")) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Error while executing CPackWIX.cmake"
<< std::endl);
return false;
}
}
if(GetOption("CPACK_WIX_PRODUCT_GUID") == 0)
{
if (GetOption("CPACK_WIX_PRODUCT_GUID") == 0) {
std::string guid = GenerateGUID();
SetOption("CPACK_WIX_PRODUCT_GUID", guid.c_str());
cmCPackLogger(cmCPackLog::LOG_VERBOSE,
"CPACK_WIX_PRODUCT_GUID implicitly set to " << guid << " . "
<< std::endl);
}
"CPACK_WIX_PRODUCT_GUID implicitly set to " << guid << " . "
<< std::endl);
}
if(GetOption("CPACK_WIX_UPGRADE_GUID") == 0)
{
if (GetOption("CPACK_WIX_UPGRADE_GUID") == 0) {
std::string guid = GenerateGUID();
SetOption("CPACK_WIX_UPGRADE_GUID", guid.c_str());
cmCPackLogger(cmCPackLog::LOG_WARNING,
"CPACK_WIX_UPGRADE_GUID implicitly set to " << guid << " . "
"Please refer to the documentation on how and why "
"you might want to set this explicitly." << std::endl);
}
cmCPackLogger(
cmCPackLog::LOG_WARNING, "CPACK_WIX_UPGRADE_GUID implicitly set to "
<< guid << " . "
"Please refer to the documentation on how and why "
"you might want to set this explicitly."
<< std::endl);
}
if(!RequireOption("CPACK_TOPLEVEL_DIRECTORY", this->CPackTopLevel))
{
if (!RequireOption("CPACK_TOPLEVEL_DIRECTORY", this->CPackTopLevel)) {
return false;
}
}
if(GetOption("CPACK_WIX_LICENSE_RTF") == 0)
{
if (GetOption("CPACK_WIX_LICENSE_RTF") == 0) {
std::string licenseFilename = this->CPackTopLevel + "/License.rtf";
SetOption("CPACK_WIX_LICENSE_RTF", licenseFilename.c_str());
if(!CreateLicenseFile())
{
if (!CreateLicenseFile()) {
return false;
}
}
}
if(GetOption("CPACK_PACKAGE_VENDOR") == 0)
{
if (GetOption("CPACK_PACKAGE_VENDOR") == 0) {
std::string defaultVendor = "Humanity";
SetOption("CPACK_PACKAGE_VENDOR", defaultVendor.c_str());
cmCPackLogger(cmCPackLog::LOG_VERBOSE,
"CPACK_PACKAGE_VENDOR implicitly set to " << defaultVendor << " . "
<< std::endl);
}
"CPACK_PACKAGE_VENDOR implicitly set to "
<< defaultVendor << " . " << std::endl);
}
if(GetOption("CPACK_WIX_UI_REF") == 0)
{
if (GetOption("CPACK_WIX_UI_REF") == 0) {
std::string defaultRef = "WixUI_InstallDir";
if(!this->Components.empty())
{
if (!this->Components.empty()) {
defaultRef = "WixUI_FeatureTree";
}
}
SetOption("CPACK_WIX_UI_REF", defaultRef.c_str());
}
}
const char* packageContact = GetOption("CPACK_PACKAGE_CONTACT");
if(packageContact != 0 &&
GetOption("CPACK_WIX_PROPERTY_ARPCONTACT") == 0)
{
if (packageContact != 0 && GetOption("CPACK_WIX_PROPERTY_ARPCONTACT") == 0) {
SetOption("CPACK_WIX_PROPERTY_ARPCONTACT", packageContact);
}
}
CollectExtensions("CPACK_WIX_EXTENSIONS", this->CandleExtensions);
CollectExtensions("CPACK_WIX_CANDLE_EXTENSIONS", this->CandleExtensions);
@@ -240,46 +222,40 @@ bool cmCPackWIXGenerator::InitializeWiXConfiguration()
CollectExtensions("CPACK_WIX_LIGHT_EXTENSIONS", this->LightExtensions);
const char* patchFilePath = GetOption("CPACK_WIX_PATCH_FILE");
if(patchFilePath)
{
if (patchFilePath) {
std::vector<std::string> patchFilePaths;
cmSystemTools::ExpandListArgument(patchFilePath, patchFilePaths);
for(size_t i = 0; i < patchFilePaths.size(); ++i)
{
if(!this->Patch->LoadFragments(patchFilePaths[i]))
{
for (size_t i = 0; i < patchFilePaths.size(); ++i) {
if (!this->Patch->LoadFragments(patchFilePaths[i])) {
return false;
}
}
}
}
return true;
}
bool cmCPackWIXGenerator::PackageFilesImpl()
{
if(!InitializeWiXConfiguration())
{
if (!InitializeWiXConfiguration()) {
return false;
}
}
CreateWiXVariablesIncludeFile();
CreateWiXPropertiesIncludeFile();
CreateWiXProductFragmentIncludeFile();
if(!CreateWiXSourceFiles())
{
if (!CreateWiXSourceFiles()) {
return false;
}
}
AppendUserSuppliedExtraSources();
std::set<std::string> usedBaseNames;
std::stringstream objectFiles;
for(size_t i = 0; i < this->WixSources.size(); ++i)
{
for (size_t i = 0; i < this->WixSources.size(); ++i) {
std::string const& sourceFilename = this->WixSources[i];
std::string baseName =
@@ -288,25 +264,23 @@ bool cmCPackWIXGenerator::PackageFilesImpl()
unsigned int counter = 0;
std::string uniqueBaseName = baseName;
while(usedBaseNames.find(uniqueBaseName) != usedBaseNames.end())
{
while (usedBaseNames.find(uniqueBaseName) != usedBaseNames.end()) {
std::stringstream tmp;
tmp << baseName << ++counter;
uniqueBaseName = tmp.str();
}
}
usedBaseNames.insert(uniqueBaseName);
std::string objectFilename =
this->CPackTopLevel + "/" + uniqueBaseName + ".wixobj";
if(!RunCandleCommand(sourceFilename, objectFilename))
{
if (!RunCandleCommand(sourceFilename, objectFilename)) {
return false;
}
}
objectFiles << " " << QuotePath(objectFilename);
}
}
AppendUserSuppliedExtraObjects(objectFiles);
@@ -315,35 +289,34 @@ bool cmCPackWIXGenerator::PackageFilesImpl()
void cmCPackWIXGenerator::AppendUserSuppliedExtraSources()
{
const char *cpackWixExtraSources = GetOption("CPACK_WIX_EXTRA_SOURCES");
if(!cpackWixExtraSources) return;
const char* cpackWixExtraSources = GetOption("CPACK_WIX_EXTRA_SOURCES");
if (!cpackWixExtraSources)
return;
cmSystemTools::ExpandListArgument(cpackWixExtraSources, this->WixSources);
}
void cmCPackWIXGenerator::AppendUserSuppliedExtraObjects(std::ostream& stream)
{
const char *cpackWixExtraObjects = GetOption("CPACK_WIX_EXTRA_OBJECTS");
if(!cpackWixExtraObjects) return;
const char* cpackWixExtraObjects = GetOption("CPACK_WIX_EXTRA_OBJECTS");
if (!cpackWixExtraObjects)
return;
std::vector<std::string> expandedExtraObjects;
cmSystemTools::ExpandListArgument(
cpackWixExtraObjects, expandedExtraObjects);
cmSystemTools::ExpandListArgument(cpackWixExtraObjects,
expandedExtraObjects);
for(size_t i = 0; i < expandedExtraObjects.size(); ++i)
{
for (size_t i = 0; i < expandedExtraObjects.size(); ++i) {
stream << " " << QuotePath(expandedExtraObjects[i]);
}
}
}
void cmCPackWIXGenerator::CreateWiXVariablesIncludeFile()
{
std::string includeFilename =
this->CPackTopLevel + "/cpack_variables.wxi";
std::string includeFilename = this->CPackTopLevel + "/cpack_variables.wxi";
cmWIXSourceWriter includeFile(
this->Logger, includeFilename, true);
cmWIXSourceWriter includeFile(this->Logger, includeFilename, true);
CopyDefinition(includeFile, "CPACK_WIX_PRODUCT_GUID");
CopyDefinition(includeFile, "CPACK_WIX_UPGRADE_GUID");
@@ -355,29 +328,25 @@ void cmCPackWIXGenerator::CreateWiXVariablesIncludeFile()
CopyDefinition(includeFile, "CPACK_WIX_UI_BANNER");
CopyDefinition(includeFile, "CPACK_WIX_UI_DIALOG");
SetOptionIfNotSet("CPACK_WIX_PROGRAM_MENU_FOLDER",
GetOption("CPACK_PACKAGE_NAME"));
GetOption("CPACK_PACKAGE_NAME"));
CopyDefinition(includeFile, "CPACK_WIX_PROGRAM_MENU_FOLDER");
CopyDefinition(includeFile, "CPACK_WIX_UI_REF");
}
void cmCPackWIXGenerator::CreateWiXPropertiesIncludeFile()
{
std::string includeFilename =
this->CPackTopLevel + "/properties.wxi";
std::string includeFilename = this->CPackTopLevel + "/properties.wxi";
cmWIXSourceWriter includeFile(
this->Logger, includeFilename, true);
cmWIXSourceWriter includeFile(this->Logger, includeFilename, true);
std::string prefix = "CPACK_WIX_PROPERTY_";
std::vector<std::string> options = GetOptions();
for(size_t i = 0; i < options.size(); ++i)
{
for (size_t i = 0; i < options.size(); ++i) {
std::string const& name = options[i];
if(name.length() > prefix.length() &&
name.substr(0, prefix.length()) == prefix)
{
if (name.length() > prefix.length() &&
name.substr(0, prefix.length()) == prefix) {
std::string id = name.substr(prefix.length());
std::string value = GetOption(name.c_str());
@@ -385,11 +354,10 @@ void cmCPackWIXGenerator::CreateWiXPropertiesIncludeFile()
includeFile.AddAttribute("Id", id);
includeFile.AddAttribute("Value", value);
includeFile.EndElement("Property");
}
}
}
if(GetOption("CPACK_WIX_PROPERTY_ARPINSTALLLOCATION") == 0)
{
if (GetOption("CPACK_WIX_PROPERTY_ARPINSTALLLOCATION") == 0) {
includeFile.BeginElement("Property");
includeFile.AddAttribute("Id", "INSTALL_ROOT");
includeFile.AddAttribute("Secure", "yes");
@@ -397,8 +365,9 @@ void cmCPackWIXGenerator::CreateWiXPropertiesIncludeFile()
includeFile.BeginElement("RegistrySearch");
includeFile.AddAttribute("Id", "FindInstallLocation");
includeFile.AddAttribute("Root", "HKLM");
includeFile.AddAttribute("Key", "Software\\Microsoft\\Windows\\"
"CurrentVersion\\Uninstall\\[WIX_UPGRADE_DETECTED]");
includeFile.AddAttribute(
"Key", "Software\\Microsoft\\Windows\\"
"CurrentVersion\\Uninstall\\[WIX_UPGRADE_DETECTED]");
includeFile.AddAttribute("Name", "InstallLocation");
includeFile.AddAttribute("Type", "raw");
includeFile.EndElement("RegistrySearch");
@@ -409,38 +378,36 @@ void cmCPackWIXGenerator::CreateWiXPropertiesIncludeFile()
includeFile.AddAttribute("Value", "[INSTALL_ROOT]");
includeFile.AddAttribute("After", "CostFinalize");
includeFile.EndElement("SetProperty");
}
}
}
void cmCPackWIXGenerator::CreateWiXProductFragmentIncludeFile()
{
std::string includeFilename =
this->CPackTopLevel + "/product_fragment.wxi";
std::string includeFilename = this->CPackTopLevel + "/product_fragment.wxi";
cmWIXSourceWriter includeFile(
this->Logger, includeFilename, true);
cmWIXSourceWriter includeFile(this->Logger, includeFilename, true);
this->Patch->ApplyFragment("#PRODUCT", includeFile);
this->Patch->ApplyFragment("#PRODUCT", includeFile);
}
void cmCPackWIXGenerator::CopyDefinition(
cmWIXSourceWriter &source, std::string const& name)
void cmCPackWIXGenerator::CopyDefinition(cmWIXSourceWriter& source,
std::string const& name)
{
const char* value = GetOption(name.c_str());
if(value)
{
if (value) {
AddDefinition(source, name, value);
}
}
}
void cmCPackWIXGenerator::AddDefinition(cmWIXSourceWriter& source,
std::string const& name, std::string const& value)
std::string const& name,
std::string const& value)
{
std::stringstream tmp;
tmp << name << "=\"" << value << '"';
source.AddProcessingInstruction("define",
cmWIXSourceWriter::CMakeEncodingToUtf8(tmp.str()));
source.AddProcessingInstruction(
"define", cmWIXSourceWriter::CMakeEncodingToUtf8(tmp.str()));
}
bool cmCPackWIXGenerator::CreateWiXSourceFiles()
@@ -455,10 +422,9 @@ bool cmCPackWIXGenerator::CreateWiXSourceFiles()
directoryDefinitions.BeginElement("Fragment");
std::string installRoot;
if(!RequireOption("CPACK_PACKAGE_INSTALL_DIRECTORY", installRoot))
{
if (!RequireOption("CPACK_PACKAGE_INSTALL_DIRECTORY", installRoot)) {
return false;
}
}
directoryDefinitions.BeginElement("Directory");
directoryDefinitions.AddAttribute("Id", "TARGETDIR");
@@ -468,23 +434,22 @@ bool cmCPackWIXGenerator::CreateWiXSourceFiles()
directoryDefinitions.BeginInstallationPrefixDirectory(
GetProgramFilesFolderId(), installRoot);
std::string fileDefinitionsFilename =
this->CPackTopLevel + "/files.wxs";
std::string fileDefinitionsFilename = this->CPackTopLevel + "/files.wxs";
this->WixSources.push_back(fileDefinitionsFilename);
cmWIXFilesSourceWriter fileDefinitions(
this->Logger, fileDefinitionsFilename);
cmWIXFilesSourceWriter fileDefinitions(this->Logger,
fileDefinitionsFilename);
fileDefinitions.BeginElement("Fragment");
std::string featureDefinitionsFilename =
this->CPackTopLevel +"/features.wxs";
this->CPackTopLevel + "/features.wxs";
this->WixSources.push_back(featureDefinitionsFilename);
cmWIXFeaturesSourceWriter featureDefinitions(
this->Logger, featureDefinitionsFilename);
cmWIXFeaturesSourceWriter featureDefinitions(this->Logger,
featureDefinitionsFilename);
featureDefinitions.BeginElement("Fragment");
@@ -495,45 +460,39 @@ bool cmCPackWIXGenerator::CreateWiXSourceFiles()
featureDefinitions.AddAttribute("ConfigurableDirectory", "INSTALL_ROOT");
std::string cpackPackageName;
if(!RequireOption("CPACK_PACKAGE_NAME", cpackPackageName))
{
if (!RequireOption("CPACK_PACKAGE_NAME", cpackPackageName)) {
return false;
}
}
featureDefinitions.AddAttribute("Title", cpackPackageName);
featureDefinitions.AddAttribute("Level", "1");
this->Patch->ApplyFragment("#PRODUCTFEATURE", featureDefinitions);
const char* package = GetOption("CPACK_WIX_CMAKE_PACKAGE_REGISTRY");
if(package)
{
if (package) {
featureDefinitions.CreateCMakePackageRegistryEntry(
package, GetOption("CPACK_WIX_UPGRADE_GUID"));
}
package, GetOption("CPACK_WIX_UPGRADE_GUID"));
}
if(!CreateFeatureHierarchy(featureDefinitions))
{
if (!CreateFeatureHierarchy(featureDefinitions)) {
return false;
}
}
featureDefinitions.EndElement("Feature");
std::set<cmWIXShortcuts::Type> emittedShortcutTypes;
cmWIXShortcuts globalShortcuts;
if(Components.empty())
{
AddComponentsToFeature(toplevel, "ProductFeature",
directoryDefinitions, fileDefinitions, featureDefinitions,
globalShortcuts);
if (Components.empty()) {
AddComponentsToFeature(toplevel, "ProductFeature", directoryDefinitions,
fileDefinitions, featureDefinitions,
globalShortcuts);
globalShortcuts.AddShortcutTypes(emittedShortcutTypes);
}
else
{
for(std::map<std::string, cmCPackComponent>::const_iterator
i = this->Components.begin(); i != this->Components.end(); ++i)
{
} else {
for (std::map<std::string, cmCPackComponent>::const_iterator i =
this->Components.begin();
i != this->Components.end(); ++i) {
cmCPackComponent const& component = i->second;
std::string componentPath = toplevel;
@@ -544,102 +503,91 @@ bool cmCPackWIXGenerator::CreateWiXSourceFiles()
cmWIXShortcuts featureShortcuts;
AddComponentsToFeature(componentPath, componentFeatureId,
directoryDefinitions, fileDefinitions,
featureDefinitions, featureShortcuts);
directoryDefinitions, fileDefinitions,
featureDefinitions, featureShortcuts);
featureShortcuts.AddShortcutTypes(emittedShortcutTypes);
if(!CreateShortcuts(component.Name, componentFeatureId,
featureShortcuts, false, fileDefinitions, featureDefinitions))
{
if (!CreateShortcuts(component.Name, componentFeatureId,
featureShortcuts, false, fileDefinitions,
featureDefinitions)) {
return false;
}
}
}
}
bool emitUninstallShortcut = emittedShortcutTypes.find(
cmWIXShortcuts::START_MENU) != emittedShortcutTypes.end();
bool emitUninstallShortcut =
emittedShortcutTypes.find(cmWIXShortcuts::START_MENU) !=
emittedShortcutTypes.end();
if(!CreateShortcuts(std::string(), "ProductFeature",
globalShortcuts, emitUninstallShortcut,
fileDefinitions, featureDefinitions))
{
if (!CreateShortcuts(std::string(), "ProductFeature", globalShortcuts,
emitUninstallShortcut, fileDefinitions,
featureDefinitions)) {
return false;
}
}
featureDefinitions.EndElement("Fragment");
fileDefinitions.EndElement("Fragment");
directoryDefinitions.EndInstallationPrefixDirectory(
installRootSize);
directoryDefinitions.EndInstallationPrefixDirectory(installRootSize);
if(emittedShortcutTypes.find(cmWIXShortcuts::START_MENU) !=
emittedShortcutTypes.end())
{
if (emittedShortcutTypes.find(cmWIXShortcuts::START_MENU) !=
emittedShortcutTypes.end()) {
directoryDefinitions.EmitStartMenuFolder(
GetOption("CPACK_WIX_PROGRAM_MENU_FOLDER"));
}
}
if(emittedShortcutTypes.find(cmWIXShortcuts::DESKTOP) !=
emittedShortcutTypes.end())
{
if (emittedShortcutTypes.find(cmWIXShortcuts::DESKTOP) !=
emittedShortcutTypes.end()) {
directoryDefinitions.EmitDesktopFolder();
}
}
if(emittedShortcutTypes.find(cmWIXShortcuts::STARTUP) !=
emittedShortcutTypes.end())
{
if (emittedShortcutTypes.find(cmWIXShortcuts::STARTUP) !=
emittedShortcutTypes.end()) {
directoryDefinitions.EmitStartupFolder();
}
}
directoryDefinitions.EndElement("Directory");
directoryDefinitions.EndElement("Fragment");
if(!GenerateMainSourceFileFromTemplate())
{
if (!GenerateMainSourceFileFromTemplate()) {
return false;
}
}
return this->Patch->CheckForUnappliedFragments();
}
std::string cmCPackWIXGenerator::GetProgramFilesFolderId() const
{
if(GetArchitecture() == "x86")
{
if (GetArchitecture() == "x86") {
return "ProgramFilesFolder";
}
else
{
} else {
return "ProgramFiles64Folder";
}
}
}
bool cmCPackWIXGenerator::GenerateMainSourceFileFromTemplate()
{
std::string wixTemplate = FindTemplate("WIX.template.in");
if(GetOption("CPACK_WIX_TEMPLATE") != 0)
{
if (GetOption("CPACK_WIX_TEMPLATE") != 0) {
wixTemplate = GetOption("CPACK_WIX_TEMPLATE");
}
}
if(wixTemplate.empty())
{
if (wixTemplate.empty()) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Could not find CPack WiX template file WIX.template.in" << std::endl);
"Could not find CPack WiX template file WIX.template.in"
<< std::endl);
return false;
}
}
std::string mainSourceFilePath = this->CPackTopLevel + "/main.wxs";
if(!ConfigureFile(wixTemplate.c_str(), mainSourceFilePath .c_str()))
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Failed creating '" << mainSourceFilePath <<
"'' from template." << std::endl);
if (!ConfigureFile(wixTemplate.c_str(), mainSourceFilePath.c_str())) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Failed creating '"
<< mainSourceFilePath << "'' from template." << std::endl);
return false;
}
}
this->WixSources.push_back(mainSourceFilePath);
@@ -649,70 +597,64 @@ bool cmCPackWIXGenerator::GenerateMainSourceFileFromTemplate()
bool cmCPackWIXGenerator::CreateFeatureHierarchy(
cmWIXFeaturesSourceWriter& featureDefinitions)
{
for(std::map<std::string, cmCPackComponentGroup>::const_iterator
i = ComponentGroups.begin(); i != ComponentGroups.end(); ++i)
{
for (std::map<std::string, cmCPackComponentGroup>::const_iterator i =
ComponentGroups.begin();
i != ComponentGroups.end(); ++i) {
cmCPackComponentGroup const& group = i->second;
if(group.ParentGroup == 0)
{
if (group.ParentGroup == 0) {
featureDefinitions.EmitFeatureForComponentGroup(group);
}
}
}
for(std::map<std::string, cmCPackComponent>::const_iterator
i = this->Components.begin(); i != this->Components.end(); ++i)
{
for (std::map<std::string, cmCPackComponent>::const_iterator i =
this->Components.begin();
i != this->Components.end(); ++i) {
cmCPackComponent const& component = i->second;
if(!component.Group)
{
if (!component.Group) {
featureDefinitions.EmitFeatureForComponent(component);
}
}
}
return true;
}
bool cmCPackWIXGenerator::AddComponentsToFeature(
std::string const& rootPath,
std::string const& featureId,
std::string const& rootPath, std::string const& featureId,
cmWIXDirectoriesSourceWriter& directoryDefinitions,
cmWIXFilesSourceWriter& fileDefinitions,
cmWIXFeaturesSourceWriter& featureDefinitions,
cmWIXShortcuts& shortcuts)
cmWIXFeaturesSourceWriter& featureDefinitions, cmWIXShortcuts& shortcuts)
{
featureDefinitions.BeginElement("FeatureRef");
featureDefinitions.AddAttribute("Id", featureId);
std::vector<std::string> cpackPackageExecutablesList;
const char *cpackPackageExecutables = GetOption("CPACK_PACKAGE_EXECUTABLES");
if(cpackPackageExecutables)
{
cmSystemTools::ExpandListArgument(cpackPackageExecutables,
cpackPackageExecutablesList);
if(cpackPackageExecutablesList.size() % 2 != 0 )
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"CPACK_PACKAGE_EXECUTABLES should contain pairs of <executable> and "
"<text label>." << std::endl);
return false;
}
const char* cpackPackageExecutables = GetOption("CPACK_PACKAGE_EXECUTABLES");
if (cpackPackageExecutables) {
cmSystemTools::ExpandListArgument(cpackPackageExecutables,
cpackPackageExecutablesList);
if (cpackPackageExecutablesList.size() % 2 != 0) {
cmCPackLogger(
cmCPackLog::LOG_ERROR,
"CPACK_PACKAGE_EXECUTABLES should contain pairs of <executable> and "
"<text label>."
<< std::endl);
return false;
}
}
std::vector<std::string> cpackPackageDesktopLinksList;
const char *cpackPackageDesktopLinks =
const char* cpackPackageDesktopLinks =
GetOption("CPACK_CREATE_DESKTOP_LINKS");
if(cpackPackageDesktopLinks)
{
cmSystemTools::ExpandListArgument(cpackPackageDesktopLinks,
cpackPackageDesktopLinksList);
}
if (cpackPackageDesktopLinks) {
cmSystemTools::ExpandListArgument(cpackPackageDesktopLinks,
cpackPackageDesktopLinksList);
}
AddDirectoryAndFileDefinitons(
rootPath, "INSTALL_ROOT",
directoryDefinitions, fileDefinitions, featureDefinitions,
cpackPackageExecutablesList, cpackPackageDesktopLinksList,
shortcuts);
AddDirectoryAndFileDefinitons(rootPath, "INSTALL_ROOT", directoryDefinitions,
fileDefinitions, featureDefinitions,
cpackPackageExecutablesList,
cpackPackageDesktopLinksList, shortcuts);
featureDefinitions.EndElement("FeatureRef");
@@ -720,62 +662,48 @@ bool cmCPackWIXGenerator::AddComponentsToFeature(
}
bool cmCPackWIXGenerator::CreateShortcuts(
std::string const& cpackComponentName,
std::string const& featureId,
cmWIXShortcuts const& shortcuts,
bool emitUninstallShortcut,
std::string const& cpackComponentName, std::string const& featureId,
cmWIXShortcuts const& shortcuts, bool emitUninstallShortcut,
cmWIXFilesSourceWriter& fileDefinitions,
cmWIXFeaturesSourceWriter& featureDefinitions)
{
if(!shortcuts.empty(cmWIXShortcuts::START_MENU))
{
if(!this->CreateShortcutsOfSpecificType(cmWIXShortcuts::START_MENU,
cpackComponentName, featureId, "",
shortcuts, emitUninstallShortcut,
fileDefinitions, featureDefinitions))
{
if (!shortcuts.empty(cmWIXShortcuts::START_MENU)) {
if (!this->CreateShortcutsOfSpecificType(
cmWIXShortcuts::START_MENU, cpackComponentName, featureId, "",
shortcuts, emitUninstallShortcut, fileDefinitions,
featureDefinitions)) {
return false;
}
}
}
if(!shortcuts.empty(cmWIXShortcuts::DESKTOP))
{
if(!this->CreateShortcutsOfSpecificType(cmWIXShortcuts::DESKTOP,
cpackComponentName, featureId, "DESKTOP",
shortcuts, false,
fileDefinitions, featureDefinitions))
{
if (!shortcuts.empty(cmWIXShortcuts::DESKTOP)) {
if (!this->CreateShortcutsOfSpecificType(
cmWIXShortcuts::DESKTOP, cpackComponentName, featureId, "DESKTOP",
shortcuts, false, fileDefinitions, featureDefinitions)) {
return false;
}
}
}
if(!shortcuts.empty(cmWIXShortcuts::STARTUP))
{
if(!this->CreateShortcutsOfSpecificType(cmWIXShortcuts::STARTUP,
cpackComponentName, featureId, "STARTUP",
shortcuts, false,
fileDefinitions, featureDefinitions))
{
if (!shortcuts.empty(cmWIXShortcuts::STARTUP)) {
if (!this->CreateShortcutsOfSpecificType(
cmWIXShortcuts::STARTUP, cpackComponentName, featureId, "STARTUP",
shortcuts, false, fileDefinitions, featureDefinitions)) {
return false;
}
}
}
return true;
}
bool cmCPackWIXGenerator::CreateShortcutsOfSpecificType(
cmWIXShortcuts::Type type,
std::string const& cpackComponentName,
std::string const& featureId,
std::string const& idPrefix,
cmWIXShortcuts const& shortcuts,
bool emitUninstallShortcut,
cmWIXShortcuts::Type type, std::string const& cpackComponentName,
std::string const& featureId, std::string const& idPrefix,
cmWIXShortcuts const& shortcuts, bool emitUninstallShortcut,
cmWIXFilesSourceWriter& fileDefinitions,
cmWIXFeaturesSourceWriter& featureDefinitions)
{
std::string directoryId;
switch(type)
{
switch (type) {
case cmWIXShortcuts::START_MENU:
directoryId = "PROGRAM_MENU_FOLDER";
break;
@@ -787,35 +715,31 @@ bool cmCPackWIXGenerator::CreateShortcutsOfSpecificType(
break;
default:
return false;
}
}
featureDefinitions.BeginElement("FeatureRef");
featureDefinitions.AddAttribute("Id", featureId);
std::string cpackVendor;
if(!RequireOption("CPACK_PACKAGE_VENDOR", cpackVendor))
{
if (!RequireOption("CPACK_PACKAGE_VENDOR", cpackVendor)) {
return false;
}
}
std::string cpackPackageName;
if(!RequireOption("CPACK_PACKAGE_NAME", cpackPackageName))
{
if (!RequireOption("CPACK_PACKAGE_NAME", cpackPackageName)) {
return false;
}
}
std::string idSuffix;
if(!cpackComponentName.empty())
{
idSuffix += "_";
idSuffix += cpackComponentName;
}
if (!cpackComponentName.empty()) {
idSuffix += "_";
idSuffix += cpackComponentName;
}
std::string componentId = "CM_SHORTCUT";
if(idPrefix.size())
{
if (idPrefix.size()) {
componentId += "_" + idPrefix;
}
}
componentId += idSuffix;
@@ -828,22 +752,20 @@ bool cmCPackWIXGenerator::CreateShortcutsOfSpecificType(
this->Patch->ApplyFragment(componentId, fileDefinitions);
std::string registryKey = std::string("Software\\") +
cpackVendor + "\\" + cpackPackageName;
std::string registryKey =
std::string("Software\\") + cpackVendor + "\\" + cpackPackageName;
shortcuts.EmitShortcuts(type, registryKey,
cpackComponentName, fileDefinitions);
shortcuts.EmitShortcuts(type, registryKey, cpackComponentName,
fileDefinitions);
if(type == cmWIXShortcuts::START_MENU)
{
fileDefinitions.EmitRemoveFolder(
"CM_REMOVE_PROGRAM_MENU_FOLDER" + idSuffix);
}
if (type == cmWIXShortcuts::START_MENU) {
fileDefinitions.EmitRemoveFolder("CM_REMOVE_PROGRAM_MENU_FOLDER" +
idSuffix);
}
if(emitUninstallShortcut)
{
if (emitUninstallShortcut) {
fileDefinitions.EmitUninstallShortcut(cpackPackageName);
}
}
fileDefinitions.EndElement("Component");
fileDefinitions.EndElement("DirectoryRef");
@@ -857,53 +779,43 @@ bool cmCPackWIXGenerator::CreateShortcutsOfSpecificType(
bool cmCPackWIXGenerator::CreateLicenseFile()
{
std::string licenseSourceFilename;
if(!RequireOption("CPACK_RESOURCE_FILE_LICENSE", licenseSourceFilename))
{
if (!RequireOption("CPACK_RESOURCE_FILE_LICENSE", licenseSourceFilename)) {
return false;
}
}
std::string licenseDestinationFilename;
if(!RequireOption("CPACK_WIX_LICENSE_RTF", licenseDestinationFilename))
{
if (!RequireOption("CPACK_WIX_LICENSE_RTF", licenseDestinationFilename)) {
return false;
}
}
std::string extension = GetRightmostExtension(licenseSourceFilename);
if(extension == ".rtf")
{
cmSystemTools::CopyAFile(
licenseSourceFilename.c_str(),
licenseDestinationFilename.c_str());
}
else if(extension == ".txt")
{
if (extension == ".rtf") {
cmSystemTools::CopyAFile(licenseSourceFilename.c_str(),
licenseDestinationFilename.c_str());
} else if (extension == ".txt") {
cmWIXRichTextFormatWriter rtfWriter(licenseDestinationFilename);
cmsys::ifstream licenseSource(licenseSourceFilename.c_str());
std::string line;
while(std::getline(licenseSource, line))
{
while (std::getline(licenseSource, line)) {
rtfWriter.AddText(line);
rtfWriter.AddText("\n");
}
}
else
{
} else {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"unsupported WiX License file extension '" <<
extension << "'" << std::endl);
"unsupported WiX License file extension '"
<< extension << "'" << std::endl);
return false;
}
}
return true;
}
void cmCPackWIXGenerator::AddDirectoryAndFileDefinitons(
std::string const& topdir,
std::string const& directoryId,
std::string const& topdir, std::string const& directoryId,
cmWIXDirectoriesSourceWriter& directoryDefinitions,
cmWIXFilesSourceWriter& fileDefinitions,
cmWIXFeaturesSourceWriter& featureDefinitions,
@@ -917,61 +829,51 @@ void cmCPackWIXGenerator::AddDirectoryAndFileDefinitons(
std::string relativeDirectoryPath =
cmSystemTools::RelativePath(toplevel.c_str(), topdir.c_str());
if(relativeDirectoryPath.empty())
{
if (relativeDirectoryPath.empty()) {
relativeDirectoryPath = ".";
}
}
cmInstalledFile const* directoryInstalledFile = this->GetInstalledFile(
this->RelativePathWithoutComponentPrefix(relativeDirectoryPath)
);
this->RelativePathWithoutComponentPrefix(relativeDirectoryPath));
bool emptyDirectory = dir.GetNumberOfFiles() == 2;
bool createDirectory = false;
if(emptyDirectory)
{
if (emptyDirectory) {
createDirectory = true;
}
}
if(directoryInstalledFile)
{
if(directoryInstalledFile->HasProperty("CPACK_WIX_ACL"))
{
if (directoryInstalledFile) {
if (directoryInstalledFile->HasProperty("CPACK_WIX_ACL")) {
createDirectory = true;
}
}
}
if(createDirectory)
{
if (createDirectory) {
std::string componentId = fileDefinitions.EmitComponentCreateFolder(
directoryId, GenerateGUID(), directoryInstalledFile);
featureDefinitions.EmitComponentRef(componentId);
}
}
if(emptyDirectory)
{
if (emptyDirectory) {
return;
}
}
for(size_t i = 0; i < dir.GetNumberOfFiles(); ++i)
{
for (size_t i = 0; i < dir.GetNumberOfFiles(); ++i) {
std::string fileName = dir.GetFile(static_cast<unsigned long>(i));
if(fileName == "." || fileName == "..")
{
if (fileName == "." || fileName == "..") {
continue;
}
}
std::string fullPath = topdir + "/" + fileName;
std::string relativePath = cmSystemTools::RelativePath(
toplevel.c_str(), fullPath.c_str());
std::string relativePath =
cmSystemTools::RelativePath(toplevel.c_str(), fullPath.c_str());
std::string id = PathToId(relativePath);
if(cmSystemTools::FileIsDirectory(fullPath.c_str()))
{
if (cmSystemTools::FileIsDirectory(fullPath.c_str())) {
std::string subDirectoryId = std::string("CM_D") + id;
directoryDefinitions.BeginElement("Directory");
@@ -979,77 +881,60 @@ void cmCPackWIXGenerator::AddDirectoryAndFileDefinitons(
directoryDefinitions.AddAttribute("Name", fileName);
AddDirectoryAndFileDefinitons(
fullPath, subDirectoryId,
directoryDefinitions,
fileDefinitions,
featureDefinitions,
packageExecutables,
desktopExecutables,
shortcuts);
fullPath, subDirectoryId, directoryDefinitions, fileDefinitions,
featureDefinitions, packageExecutables, desktopExecutables, shortcuts);
this->Patch->ApplyFragment(subDirectoryId, directoryDefinitions);
directoryDefinitions.EndElement("Directory");
}
else
{
} else {
cmInstalledFile const* installedFile = this->GetInstalledFile(
this->RelativePathWithoutComponentPrefix(relativePath)
);
this->RelativePathWithoutComponentPrefix(relativePath));
if(installedFile)
{
if (installedFile) {
shortcuts.CreateFromProperties(id, directoryId, *installedFile);
}
}
std::string componentId = fileDefinitions.EmitComponentFile(
directoryId, id, fullPath, *(this->Patch), installedFile);
featureDefinitions.EmitComponentRef(componentId);
for(size_t j = 0; j < packageExecutables.size(); ++j)
{
for (size_t j = 0; j < packageExecutables.size(); ++j) {
std::string const& executableName = packageExecutables[j++];
std::string const& textLabel = packageExecutables[j];
if(cmSystemTools::LowerCase(fileName) ==
cmSystemTools::LowerCase(executableName) + ".exe")
{
if (cmSystemTools::LowerCase(fileName) ==
cmSystemTools::LowerCase(executableName) + ".exe") {
cmWIXShortcut shortcut;
shortcut.label= textLabel;
shortcut.label = textLabel;
shortcut.workingDirectoryId = directoryId;
shortcuts.insert(cmWIXShortcuts::START_MENU, id, shortcut);
if(!desktopExecutables.empty() &&
std::find(desktopExecutables.begin(),
desktopExecutables.end(),
executableName)
!= desktopExecutables.end())
{
shortcuts.insert(cmWIXShortcuts::DESKTOP, id, shortcut);
}
if (!desktopExecutables.empty() &&
std::find(desktopExecutables.begin(), desktopExecutables.end(),
executableName) != desktopExecutables.end()) {
shortcuts.insert(cmWIXShortcuts::DESKTOP, id, shortcut);
}
}
}
}
}
}
bool cmCPackWIXGenerator::RequireOption(
std::string const& name, std::string &value) const
bool cmCPackWIXGenerator::RequireOption(std::string const& name,
std::string& value) const
{
const char* tmp = GetOption(name.c_str());
if(tmp)
{
if (tmp) {
value = tmp;
return true;
}
else
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Required variable " << name << " not set" << std::endl);
} else {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Required variable "
<< name << " not set" << std::endl);
return false;
}
}
}
std::string cmCPackWIXGenerator::GetArchitecture() const
@@ -1057,14 +942,11 @@ std::string cmCPackWIXGenerator::GetArchitecture() const
std::string void_p_size;
RequireOption("CPACK_WIX_SIZEOF_VOID_P", void_p_size);
if(void_p_size == "8")
{
if (void_p_size == "8") {
return "x64";
}
else
{
} else {
return "x86";
}
}
}
std::string cmCPackWIXGenerator::GenerateGUID()
@@ -1072,7 +954,7 @@ std::string cmCPackWIXGenerator::GenerateGUID()
UUID guid;
UuidCreate(&guid);
unsigned short *tmp = 0;
unsigned short* tmp = 0;
UuidToStringW(&guid, &tmp);
std::string result =
@@ -1093,10 +975,9 @@ std::string cmCPackWIXGenerator::GetRightmostExtension(
std::string extension;
std::string::size_type i = filename.rfind(".");
if(i != std::string::npos)
{
if (i != std::string::npos) {
extension = filename.substr(i);
}
}
return cmSystemTools::LowerCase(extension);
}
@@ -1104,7 +985,8 @@ std::string cmCPackWIXGenerator::GetRightmostExtension(
std::string cmCPackWIXGenerator::PathToId(std::string const& path)
{
id_map_t::const_iterator i = PathToIdMap.find(path);
if(i != PathToIdMap.end()) return i->second;
if (i != PathToIdMap.end())
return i->second;
std::string id = CreateNewIdForPath(path);
return id;
@@ -1120,41 +1002,37 @@ std::string cmCPackWIXGenerator::CreateNewIdForPath(std::string const& path)
std::string identifier;
std::string currentComponent;
for(size_t i = 1; i < components.size(); ++i)
{
if(i != 1) identifier += '.';
for (size_t i = 1; i < components.size(); ++i) {
if (i != 1)
identifier += '.';
currentComponent = NormalizeComponentForId(
components[i], replacementCount);
currentComponent =
NormalizeComponentForId(components[i], replacementCount);
identifier += currentComponent;
}
}
std::string idPrefix = "P";
size_t replacementPercent = replacementCount * 100 / identifier.size();
if(replacementPercent > 33 || identifier.size() > 60)
{
if (replacementPercent > 33 || identifier.size() > 60) {
identifier = CreateHashedId(path, currentComponent);
idPrefix = "H";
}
}
std::stringstream result;
result << idPrefix << "_" << identifier;
size_t ambiguityCount = ++IdAmbiguityCounter[identifier];
if(ambiguityCount > 999)
{
if (ambiguityCount > 999) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error while trying to generate a unique Id for '" <<
path << "'" << std::endl);
"Error while trying to generate a unique Id for '"
<< path << "'" << std::endl);
return std::string();
}
else if(ambiguityCount > 1)
{
} else if (ambiguityCount > 1) {
result << "_" << ambiguityCount;
}
}
std::string resultString = result.str();
@@ -1173,15 +1051,12 @@ std::string cmCPackWIXGenerator::CreateHashedId(
identifier += hash.substr(0, 7) + "_";
const size_t maxFileNameLength = 52;
if(normalizedFilename.length() > maxFileNameLength)
{
if (normalizedFilename.length() > maxFileNameLength) {
identifier += normalizedFilename.substr(0, maxFileNameLength - 3);
identifier += "...";
}
else
{
} else {
identifier += normalizedFilename;
}
}
return identifier;
}
@@ -1192,65 +1067,59 @@ std::string cmCPackWIXGenerator::NormalizeComponentForId(
std::string result;
result.resize(component.size());
for(size_t i = 0; i < component.size(); ++i)
{
for (size_t i = 0; i < component.size(); ++i) {
char c = component[i];
if(IsLegalIdCharacter(c))
{
if (IsLegalIdCharacter(c)) {
result[i] = c;
}
else
{
} else {
result[i] = '_';
++ replacementCount;
}
++replacementCount;
}
}
return result;
}
bool cmCPackWIXGenerator::IsLegalIdCharacter(char c)
{
return (c >= '0' && c <= '9') ||
(c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
c == '_' || c == '.';
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') || c == '_' || c == '.';
}
void cmCPackWIXGenerator::CollectExtensions(
std::string const& variableName, extension_set_t& extensions)
void cmCPackWIXGenerator::CollectExtensions(std::string const& variableName,
extension_set_t& extensions)
{
const char *variableContent = GetOption(variableName.c_str());
if(!variableContent) return;
const char* variableContent = GetOption(variableName.c_str());
if (!variableContent)
return;
std::vector<std::string> list;
cmSystemTools::ExpandListArgument(variableContent, list);
extensions.insert(list.begin(), list.end());
}
void cmCPackWIXGenerator::AddCustomFlags(
std::string const& variableName, std::ostream& stream)
void cmCPackWIXGenerator::AddCustomFlags(std::string const& variableName,
std::ostream& stream)
{
const char *variableContent = GetOption(variableName.c_str());
if(!variableContent) return;
const char* variableContent = GetOption(variableName.c_str());
if (!variableContent)
return;
std::vector<std::string> list;
cmSystemTools::ExpandListArgument(variableContent, list);
for(std::vector<std::string>::const_iterator i = list.begin();
i != list.end(); ++i)
{
stream << " " << QuotePath(*i);
}
for (std::vector<std::string>::const_iterator i = list.begin();
i != list.end(); ++i) {
stream << " " << QuotePath(*i);
}
}
std::string cmCPackWIXGenerator::RelativePathWithoutComponentPrefix(
std::string const& path)
{
if(this->Components.empty())
{
if (this->Components.empty()) {
return path;
}
}
std::string::size_type pos = path.find('/');
+32 -51
View File
@@ -42,25 +42,16 @@ protected:
virtual int PackageFiles();
virtual const char* GetOutputExtension()
{
return ".msi";
}
virtual const char* GetOutputExtension() { return ".msi"; }
virtual enum CPackSetDestdirSupport SupportsSetDestdir() const
{
{
return SETDESTDIR_UNSUPPORTED;
}
}
virtual bool SupportsAbsoluteDestination() const
{
return false;
}
virtual bool SupportsAbsoluteDestination() const { return false; }
virtual bool SupportsComponentInstallation() const
{
return true;
}
virtual bool SupportsComponentInstallation() const { return true; }
private:
typedef std::map<std::string, std::string> id_map_t;
@@ -77,11 +68,10 @@ private:
void CreateWiXProductFragmentIncludeFile();
void CopyDefinition(
cmWIXSourceWriter &source, std::string const& name);
void CopyDefinition(cmWIXSourceWriter& source, std::string const& name);
void AddDefinition(cmWIXSourceWriter& source,
std::string const& name, std::string const& value);
void AddDefinition(cmWIXSourceWriter& source, std::string const& name,
std::string const& value);
bool CreateWiXSourceFiles();
@@ -89,32 +79,25 @@ private:
bool GenerateMainSourceFileFromTemplate();
bool CreateFeatureHierarchy(
cmWIXFeaturesSourceWriter& featureDefinitions);
bool CreateFeatureHierarchy(cmWIXFeaturesSourceWriter& featureDefinitions);
bool AddComponentsToFeature(
std::string const& rootPath,
std::string const& featureId,
std::string const& rootPath, std::string const& featureId,
cmWIXDirectoriesSourceWriter& directoryDefinitions,
cmWIXFilesSourceWriter& fileDefinitions,
cmWIXFeaturesSourceWriter& featureDefinitions,
cmWIXShortcuts& shortcuts);
cmWIXFeaturesSourceWriter& featureDefinitions, cmWIXShortcuts& shortcuts);
bool CreateShortcuts(
std::string const& cpackComponentName,
std::string const& featureId,
cmWIXShortcuts const& shortcuts,
bool emitUninstallShortcut,
cmWIXFilesSourceWriter& fileDefinitions,
cmWIXFeaturesSourceWriter& featureDefinitions);
bool CreateShortcuts(std::string const& cpackComponentName,
std::string const& featureId,
cmWIXShortcuts const& shortcuts,
bool emitUninstallShortcut,
cmWIXFilesSourceWriter& fileDefinitions,
cmWIXFeaturesSourceWriter& featureDefinitions);
bool CreateShortcutsOfSpecificType(
cmWIXShortcuts::Type type,
std::string const& cpackComponentName,
std::string const& featureId,
std::string const& idPrefix,
cmWIXShortcuts const& shortcuts,
bool emitUninstallShortcut,
cmWIXShortcuts::Type type, std::string const& cpackComponentName,
std::string const& featureId, std::string const& idPrefix,
cmWIXShortcuts const& shortcuts, bool emitUninstallShortcut,
cmWIXFilesSourceWriter& fileDefinitions,
cmWIXFeaturesSourceWriter& featureDefinitions);
@@ -126,13 +109,13 @@ private:
bool RunWiXCommand(std::string const& command);
bool RunCandleCommand(
std::string const& sourceFile, std::string const& objectFile);
bool RunCandleCommand(std::string const& sourceFile,
std::string const& objectFile);
bool RunLightCommand(std::string const& objectFiles);
void AddDirectoryAndFileDefinitons(std::string const& topdir,
std::string const& directoryId,
void AddDirectoryAndFileDefinitons(
std::string const& topdir, std::string const& directoryId,
cmWIXDirectoriesSourceWriter& directoryDefinitions,
cmWIXFilesSourceWriter& fileDefinitions,
cmWIXFeaturesSourceWriter& featureDefinitions,
@@ -154,22 +137,20 @@ private:
std::string CreateNewIdForPath(std::string const& path);
static std::string CreateHashedId(
std::string const& path, std::string const& normalizedFilename);
static std::string CreateHashedId(std::string const& path,
std::string const& normalizedFilename);
std::string NormalizeComponentForId(
std::string const& component, size_t& replacementCount);
std::string NormalizeComponentForId(std::string const& component,
size_t& replacementCount);
static bool IsLegalIdCharacter(char c);
void CollectExtensions(
std::string const& variableName, extension_set_t& extensions);
void CollectExtensions(std::string const& variableName,
extension_set_t& extensions);
void AddCustomFlags(
std::string const& variableName, std::ostream& stream);
void AddCustomFlags(std::string const& variableName, std::ostream& stream);
std::string RelativePathWithoutComponentPrefix(
std::string const& path);
std::string RelativePathWithoutComponentPrefix(std::string const& path);
std::vector<std::string> WixSources;
id_map_t PathToIdMap;
+31 -45
View File
@@ -17,14 +17,12 @@
#include <cmSystemTools.h>
cmWIXAccessControlList::cmWIXAccessControlList(
cmCPackLog *logger,
cmInstalledFile const& installedFile,
cmWIXSourceWriter &sourceWriter):
Logger(logger),
InstalledFile(installedFile),
SourceWriter(sourceWriter)
cmCPackLog* logger, cmInstalledFile const& installedFile,
cmWIXSourceWriter& sourceWriter)
: Logger(logger)
, InstalledFile(installedFile)
, SourceWriter(sourceWriter)
{
}
bool cmWIXAccessControlList::Apply()
@@ -32,23 +30,20 @@ bool cmWIXAccessControlList::Apply()
std::vector<std::string> entries;
this->InstalledFile.GetPropertyAsList("CPACK_WIX_ACL", entries);
for(size_t i = 0; i < entries.size(); ++i)
{
for (size_t i = 0; i < entries.size(); ++i) {
this->CreatePermissionElement(entries[i]);
}
}
return true;
}
void cmWIXAccessControlList::CreatePermissionElement(
std::string const& entry)
void cmWIXAccessControlList::CreatePermissionElement(std::string const& entry)
{
std::string::size_type pos = entry.find('=');
if(pos == std::string::npos)
{
if (pos == std::string::npos) {
this->ReportError(entry, "Did not find mandatory '='");
return;
}
}
std::string user_and_domain = entry.substr(0, pos);
std::string permission_string = entry.substr(pos + 1);
@@ -56,46 +51,38 @@ void cmWIXAccessControlList::CreatePermissionElement(
pos = user_and_domain.find('@');
std::string user;
std::string domain;
if(pos != std::string::npos)
{
if (pos != std::string::npos) {
user = user_and_domain.substr(0, pos);
domain = user_and_domain.substr(pos + 1);
}
else
{
} else {
user = user_and_domain;
}
}
std::vector<std::string> permissions =
cmSystemTools::tokenize(permission_string, ",");
this->SourceWriter.BeginElement("Permission");
this->SourceWriter.AddAttribute("User", user);
if(!domain.empty())
{
if (!domain.empty()) {
this->SourceWriter.AddAttribute("Domain", domain);
}
for(size_t i = 0; i < permissions.size(); ++i)
{
}
for (size_t i = 0; i < permissions.size(); ++i) {
this->EmitBooleanAttribute(entry,
cmSystemTools::TrimWhitespace(permissions[i]));
}
cmSystemTools::TrimWhitespace(permissions[i]));
}
this->SourceWriter.EndElement("Permission");
}
void cmWIXAccessControlList::ReportError(
std::string const& entry,
std::string const& message)
void cmWIXAccessControlList::ReportError(std::string const& entry,
std::string const& message)
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Failed processing ACL entry '" << entry <<
"': " << message << std::endl);
cmCPackLogger(cmCPackLog::LOG_ERROR, "Failed processing ACL entry '"
<< entry << "': " << message << std::endl);
}
bool cmWIXAccessControlList::IsBooleanAttribute(std::string const& name)
{
static const char* validAttributes[] =
{
static const char* validAttributes[] = {
/* clang-format needs this comment to break after the opening brace */
"Append",
"ChangePermission",
@@ -128,23 +115,22 @@ bool cmWIXAccessControlList::IsBooleanAttribute(std::string const& name)
};
size_t i = 0;
while(validAttributes[i])
{
if(name == validAttributes[i++]) return true;
}
while (validAttributes[i]) {
if (name == validAttributes[i++])
return true;
}
return false;
}
void cmWIXAccessControlList::EmitBooleanAttribute(
std::string const& entry, std::string const& name)
void cmWIXAccessControlList::EmitBooleanAttribute(std::string const& entry,
std::string const& name)
{
if(!this->IsBooleanAttribute(name))
{
if (!this->IsBooleanAttribute(name)) {
std::stringstream message;
message << "Unknown boolean attribute '" << name << "'";
this->ReportError(entry, message.str());
}
}
this->SourceWriter.AddAttribute(name, "yes");
}
+5 -7
View File
@@ -21,10 +21,9 @@
class cmWIXAccessControlList
{
public:
cmWIXAccessControlList(
cmCPackLog *logger,
cmInstalledFile const& installedFile,
cmWIXSourceWriter &sourceWriter);
cmWIXAccessControlList(cmCPackLog* logger,
cmInstalledFile const& installedFile,
cmWIXSourceWriter& sourceWriter);
bool Apply();
@@ -35,12 +34,11 @@ private:
bool IsBooleanAttribute(std::string const& name);
void EmitBooleanAttribute(
std::string const& entry, std::string const& name);
void EmitBooleanAttribute(std::string const& entry, std::string const& name);
cmCPackLog* Logger;
cmInstalledFile const& InstalledFile;
cmWIXSourceWriter &SourceWriter;
cmWIXSourceWriter& SourceWriter;
};
#endif
@@ -12,11 +12,10 @@
#include "cmWIXDirectoriesSourceWriter.h"
cmWIXDirectoriesSourceWriter::cmWIXDirectoriesSourceWriter(cmCPackLog* logger,
std::string const& filename):
cmWIXSourceWriter(logger, filename)
cmWIXDirectoriesSourceWriter::cmWIXDirectoriesSourceWriter(
cmCPackLog* logger, std::string const& filename)
: cmWIXSourceWriter(logger, filename)
{
}
void cmWIXDirectoriesSourceWriter::EmitStartMenuFolder(
@@ -60,25 +59,20 @@ size_t cmWIXDirectoriesSourceWriter::BeginInstallationPrefixDirectory(
cmSystemTools::SplitPath(installRootString.c_str(), installRoot);
if(!installRoot.empty() && installRoot.back().empty())
{
if (!installRoot.empty() && installRoot.back().empty()) {
installRoot.pop_back();
}
}
for(size_t i = 1; i < installRoot.size(); ++i)
{
for (size_t i = 1; i < installRoot.size(); ++i) {
BeginElement("Directory");
if(i == installRoot.size() - 1)
{
if (i == installRoot.size() - 1) {
AddAttribute("Id", "INSTALL_ROOT");
}
else
{
} else {
std::stringstream tmp;
tmp << "INSTALL_PREFIX_" << i;
AddAttribute("Id", tmp.str());
}
}
AddAttribute("Name", installRoot[i]);
}
@@ -88,8 +82,7 @@ size_t cmWIXDirectoriesSourceWriter::BeginInstallationPrefixDirectory(
void cmWIXDirectoriesSourceWriter::EndInstallationPrefixDirectory(size_t size)
{
for(size_t i = 0; i < size; ++i)
{
for (size_t i = 0; i < size; ++i) {
EndElement("Directory");
}
}
}
@@ -26,7 +26,7 @@ class cmWIXDirectoriesSourceWriter : public cmWIXSourceWriter
{
public:
cmWIXDirectoriesSourceWriter(cmCPackLog* logger,
std::string const& filename);
std::string const& filename);
void EmitStartMenuFolder(std::string const& startMenuFolder);
@@ -35,8 +35,8 @@ public:
void EmitStartupFolder();
size_t BeginInstallationPrefixDirectory(
std::string const& programFilesFolderId,
std::string const& installRootString);
std::string const& programFilesFolderId,
std::string const& installRootString);
void EndInstallationPrefixDirectory(size_t size);
};
+19 -24
View File
@@ -12,16 +12,14 @@
#include "cmWIXFeaturesSourceWriter.h"
cmWIXFeaturesSourceWriter::cmWIXFeaturesSourceWriter(cmCPackLog* logger,
std::string const& filename):
cmWIXSourceWriter(logger, filename)
cmWIXFeaturesSourceWriter::cmWIXFeaturesSourceWriter(
cmCPackLog* logger, std::string const& filename)
: cmWIXSourceWriter(logger, filename)
{
}
void cmWIXFeaturesSourceWriter::CreateCMakePackageRegistryEntry(
std::string const& package,
std::string const& upgradeGuid)
std::string const& package, std::string const& upgradeGuid)
{
BeginElement("Component");
AddAttribute("Id", "CM_PACKAGE_REGISTRY");
@@ -29,7 +27,7 @@ void cmWIXFeaturesSourceWriter::CreateCMakePackageRegistryEntry(
AddAttribute("Guid", "*");
std::string registryKey =
std::string("Software\\Kitware\\CMake\\Packages\\") + package;
std::string("Software\\Kitware\\CMake\\Packages\\") + package;
BeginElement("RegistryValue");
AddAttribute("Root", "HKLM");
@@ -49,25 +47,24 @@ void cmWIXFeaturesSourceWriter::EmitFeatureForComponentGroup(
BeginElement("Feature");
AddAttribute("Id", "CM_G_" + group.Name);
if(group.IsExpandedByDefault)
{
if (group.IsExpandedByDefault) {
AddAttribute("Display", "expand");
}
}
AddAttributeUnlessEmpty("Title", group.DisplayName);
AddAttributeUnlessEmpty("Description", group.Description);
for(std::vector<cmCPackComponentGroup*>::const_iterator
i = group.Subgroups.begin(); i != group.Subgroups.end(); ++i)
{
for (std::vector<cmCPackComponentGroup*>::const_iterator i =
group.Subgroups.begin();
i != group.Subgroups.end(); ++i) {
EmitFeatureForComponentGroup(**i);
}
}
for(std::vector<cmCPackComponent*>::const_iterator
i = group.Components.begin(); i != group.Components.end(); ++i)
{
for (std::vector<cmCPackComponent*>::const_iterator i =
group.Components.begin();
i != group.Components.end(); ++i) {
EmitFeatureForComponent(**i);
}
}
EndElement("Feature");
}
@@ -81,15 +78,13 @@ void cmWIXFeaturesSourceWriter::EmitFeatureForComponent(
AddAttributeUnlessEmpty("Title", component.DisplayName);
AddAttributeUnlessEmpty("Description", component.Description);
if(component.IsRequired)
{
if (component.IsRequired) {
AddAttribute("Absent", "disallow");
}
}
if(component.IsHidden)
{
if (component.IsHidden) {
AddAttribute("Display", "hidden");
}
}
EndElement("Feature");
}
+3 -5
View File
@@ -23,12 +23,10 @@
class cmWIXFeaturesSourceWriter : public cmWIXSourceWriter
{
public:
cmWIXFeaturesSourceWriter(cmCPackLog* logger,
std::string const& filename);
cmWIXFeaturesSourceWriter(cmCPackLog* logger, std::string const& filename);
void CreateCMakePackageRegistryEntry(
std::string const& package,
std::string const& upgradeGuid);
void CreateCMakePackageRegistryEntry(std::string const& package,
std::string const& upgradeGuid);
void EmitFeatureForComponentGroup(const cmCPackComponentGroup& group);
+29 -44
View File
@@ -21,25 +21,22 @@
#include <sys/stat.h>
cmWIXFilesSourceWriter::cmWIXFilesSourceWriter(cmCPackLog* logger,
std::string const& filename):
cmWIXSourceWriter(logger, filename)
std::string const& filename)
: cmWIXSourceWriter(logger, filename)
{
}
void cmWIXFilesSourceWriter::EmitShortcut(
std::string const& id,
cmWIXShortcut const& shortcut,
std::string const& shortcutPrefix,
size_t shortcutIndex)
void cmWIXFilesSourceWriter::EmitShortcut(std::string const& id,
cmWIXShortcut const& shortcut,
std::string const& shortcutPrefix,
size_t shortcutIndex)
{
std::stringstream shortcutId;
shortcutId << shortcutPrefix << id;
if(shortcutIndex > 0)
{
shortcutId << "_" << shortcutIndex;
}
if (shortcutIndex > 0) {
shortcutId << "_" << shortcutIndex;
}
std::string fileId = std::string("CM_F") + id;
@@ -61,15 +58,13 @@ void cmWIXFilesSourceWriter::EmitRemoveFolder(std::string const& id)
}
void cmWIXFilesSourceWriter::EmitInstallRegistryValue(
std::string const& registryKey,
std::string const& cpackComponentName,
std::string const& registryKey, std::string const& cpackComponentName,
std::string const& suffix)
{
std::string valueName;
if(!cpackComponentName.empty())
{
valueName = cpackComponentName + "_";
}
if (!cpackComponentName.empty()) {
valueName = cpackComponentName + "_";
}
valueName += "installed";
valueName += suffix;
@@ -97,12 +92,10 @@ void cmWIXFilesSourceWriter::EmitUninstallShortcut(
}
std::string cmWIXFilesSourceWriter::EmitComponentCreateFolder(
std::string const& directoryId,
std::string const& guid,
std::string const& directoryId, std::string const& guid,
cmInstalledFile const* installedFile)
{
std::string componentId =
std::string("CM_C_EMPTY_") + directoryId;
std::string componentId = std::string("CM_C_EMPTY_") + directoryId;
BeginElement("DirectoryRef");
AddAttribute("Id", directoryId);
@@ -113,11 +106,10 @@ std::string cmWIXFilesSourceWriter::EmitComponentCreateFolder(
BeginElement("CreateFolder");
if(installedFile)
{
if (installedFile) {
cmWIXAccessControlList acl(Logger, *installedFile, *this);
acl.Apply();
}
}
EndElement("CreateFolder");
EndElement("Component");
@@ -127,10 +119,8 @@ std::string cmWIXFilesSourceWriter::EmitComponentCreateFolder(
}
std::string cmWIXFilesSourceWriter::EmitComponentFile(
std::string const& directoryId,
std::string const& id,
std::string const& filePath,
cmWIXPatch &patch,
std::string const& directoryId, std::string const& id,
std::string const& filePath, cmWIXPatch& patch,
cmInstalledFile const* installedFile)
{
std::string componentId = std::string("CM_C") + id;
@@ -143,17 +133,14 @@ std::string cmWIXFilesSourceWriter::EmitComponentFile(
AddAttribute("Id", componentId);
AddAttribute("Guid", "*");
if(installedFile)
{
if(installedFile->GetPropertyAsBool("CPACK_NEVER_OVERWRITE"))
{
if (installedFile) {
if (installedFile->GetPropertyAsBool("CPACK_NEVER_OVERWRITE")) {
AddAttribute("NeverOverwrite", "yes");
}
if(installedFile->GetPropertyAsBool("CPACK_PERMANENT"))
{
AddAttribute("Permanent", "yes");
}
}
if (installedFile->GetPropertyAsBool("CPACK_PERMANENT")) {
AddAttribute("Permanent", "yes");
}
}
BeginElement("File");
AddAttribute("Id", fileId);
@@ -163,16 +150,14 @@ std::string cmWIXFilesSourceWriter::EmitComponentFile(
mode_t fileMode = 0;
cmSystemTools::GetPermissions(filePath.c_str(), fileMode);
if(!(fileMode & S_IWRITE))
{
if (!(fileMode & S_IWRITE)) {
AddAttribute("ReadOnly", "yes");
}
}
if(installedFile)
{
if (installedFile) {
cmWIXAccessControlList acl(Logger, *installedFile, *this);
acl.Apply();
}
}
patch.ApplyFragment(fileId, *this);
EndElement("File");
+13 -22
View File
@@ -26,36 +26,27 @@
class cmWIXFilesSourceWriter : public cmWIXSourceWriter
{
public:
cmWIXFilesSourceWriter(cmCPackLog* logger,
std::string const& filename);
cmWIXFilesSourceWriter(cmCPackLog* logger, std::string const& filename);
void EmitShortcut(
std::string const& id,
cmWIXShortcut const& shortcut,
std::string const& shortcutPrefix,
size_t shortcutIndex);
void EmitShortcut(std::string const& id, cmWIXShortcut const& shortcut,
std::string const& shortcutPrefix, size_t shortcutIndex);
void EmitRemoveFolder(std::string const& id);
void EmitInstallRegistryValue(
std::string const& registryKey,
std::string const& cpackComponentName,
std::string const& suffix);
void EmitInstallRegistryValue(std::string const& registryKey,
std::string const& cpackComponentName,
std::string const& suffix);
void EmitUninstallShortcut(std::string const& packageName);
std::string EmitComponentCreateFolder(
std::string const& directoryId,
std::string const& guid,
cmInstalledFile const* installedFile);
std::string EmitComponentCreateFolder(std::string const& directoryId,
std::string const& guid,
cmInstalledFile const* installedFile);
std::string EmitComponentFile(
std::string const& directoryId,
std::string const& id,
std::string const& filePath,
cmWIXPatch &patch,
cmInstalledFile const* installedFile);
std::string EmitComponentFile(std::string const& directoryId,
std::string const& id,
std::string const& filePath, cmWIXPatch& patch,
cmInstalledFile const* installedFile);
};
#endif
+40 -46
View File
@@ -14,31 +14,29 @@
#include <CPack/cmCPackGenerator.h>
cmWIXPatch::cmWIXPatch(cmCPackLog* logger):
Logger(logger)
cmWIXPatch::cmWIXPatch(cmCPackLog* logger)
: Logger(logger)
{
}
bool cmWIXPatch::LoadFragments(std::string const& patchFilePath)
{
cmWIXPatchParser parser(Fragments, Logger);
if(!parser.ParseFile(patchFilePath.c_str()))
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Failed parsing XML patch file: '" <<
patchFilePath << "'" << std::endl);
if (!parser.ParseFile(patchFilePath.c_str())) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Failed parsing XML patch file: '"
<< patchFilePath << "'" << std::endl);
return false;
}
}
return true;
}
void cmWIXPatch::ApplyFragment(
std::string const& id, cmWIXSourceWriter& writer)
void cmWIXPatch::ApplyFragment(std::string const& id,
cmWIXSourceWriter& writer)
{
cmWIXPatchParser::fragment_map_t::iterator i = Fragments.find(id);
if(i == Fragments.end()) return;
if (i == Fragments.end())
return;
const cmWIXPatchElement& fragment = i->second;
@@ -47,36 +45,35 @@ void cmWIXPatch::ApplyFragment(
Fragments.erase(i);
}
void cmWIXPatch::ApplyElementChildren(
const cmWIXPatchElement& element, cmWIXSourceWriter& writer)
void cmWIXPatch::ApplyElementChildren(const cmWIXPatchElement& element,
cmWIXSourceWriter& writer)
{
for(cmWIXPatchElement::child_list_t::const_iterator
j = element.children.begin(); j != element.children.end(); ++j)
{
cmWIXPatchNode *node = *j;
for (cmWIXPatchElement::child_list_t::const_iterator j =
element.children.begin();
j != element.children.end(); ++j) {
cmWIXPatchNode* node = *j;
switch(node->type())
{
case cmWIXPatchNode::ELEMENT:
ApplyElement(dynamic_cast<const cmWIXPatchElement&>(*node), writer);
break;
case cmWIXPatchNode::TEXT:
writer.AddTextNode(dynamic_cast<const cmWIXPatchText&>(*node).text);
break;
switch (node->type()) {
case cmWIXPatchNode::ELEMENT:
ApplyElement(dynamic_cast<const cmWIXPatchElement&>(*node), writer);
break;
case cmWIXPatchNode::TEXT:
writer.AddTextNode(dynamic_cast<const cmWIXPatchText&>(*node).text);
break;
}
}
}
void cmWIXPatch::ApplyElement(
const cmWIXPatchElement& element, cmWIXSourceWriter& writer)
void cmWIXPatch::ApplyElement(const cmWIXPatchElement& element,
cmWIXSourceWriter& writer)
{
writer.BeginElement(element.name);
for(cmWIXPatchElement::attributes_t::const_iterator
i = element.attributes.begin(); i != element.attributes.end(); ++i)
{
for (cmWIXPatchElement::attributes_t::const_iterator i =
element.attributes.begin();
i != element.attributes.end(); ++i) {
writer.AddAttribute(i->first, i->second);
}
}
this->ApplyElementChildren(element, writer);
@@ -86,26 +83,23 @@ void cmWIXPatch::ApplyElement(
bool cmWIXPatch::CheckForUnappliedFragments()
{
std::string fragmentList;
for(cmWIXPatchParser::fragment_map_t::const_iterator
i = Fragments.begin(); i != Fragments.end(); ++i)
{
if(!fragmentList.empty())
{
for (cmWIXPatchParser::fragment_map_t::const_iterator i = Fragments.begin();
i != Fragments.end(); ++i) {
if (!fragmentList.empty()) {
fragmentList += ", ";
}
}
fragmentList += "'";
fragmentList += i->first;
fragmentList += "'";
}
}
if(!fragmentList.empty())
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Some XML patch fragments did not have matching IDs: " <<
fragmentList << std::endl);
return false;
}
if (!fragmentList.empty()) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Some XML patch fragments did not have matching IDs: "
<< fragmentList << std::endl);
return false;
}
return true;
}
+2 -3
View File
@@ -34,15 +34,14 @@ public:
private:
void ApplyElementChildren(const cmWIXPatchElement& element,
cmWIXSourceWriter& writer);
cmWIXSourceWriter& writer);
void ApplyElement(const cmWIXPatchElement& element,
cmWIXSourceWriter& writer);
cmWIXSourceWriter& writer);
cmCPackLog* Logger;
cmWIXPatchParser::fragment_map_t Fragments;
};
#endif
+54 -79
View File
@@ -28,149 +28,124 @@ cmWIXPatchNode::Type cmWIXPatchElement::type()
cmWIXPatchNode::~cmWIXPatchNode()
{
}
cmWIXPatchElement::~cmWIXPatchElement()
{
for(child_list_t::iterator i = children.begin(); i != children.end(); ++i)
{
for (child_list_t::iterator i = children.begin(); i != children.end(); ++i) {
delete *i;
}
}
}
cmWIXPatchParser::cmWIXPatchParser(
fragment_map_t& fragments, cmCPackLog* logger):
Logger(logger),
State(BEGIN_DOCUMENT),
Valid(true),
Fragments(fragments)
cmWIXPatchParser::cmWIXPatchParser(fragment_map_t& fragments,
cmCPackLog* logger)
: Logger(logger)
, State(BEGIN_DOCUMENT)
, Valid(true)
, Fragments(fragments)
{
}
void cmWIXPatchParser::StartElement(const std::string& name, const char **atts)
void cmWIXPatchParser::StartElement(const std::string& name, const char** atts)
{
if(State == BEGIN_DOCUMENT)
{
if(name == "CPackWiXPatch")
{
if (State == BEGIN_DOCUMENT) {
if (name == "CPackWiXPatch") {
State = BEGIN_FRAGMENTS;
}
else
{
} else {
ReportValidationError("Expected root element 'CPackWiXPatch'");
}
}
else if(State == BEGIN_FRAGMENTS)
{
if(name == "CPackWiXFragment")
{
State = INSIDE_FRAGMENT;
StartFragment(atts);
}
else
{
ReportValidationError("Expected 'CPackWixFragment' element");
}
} else if (State == BEGIN_FRAGMENTS) {
if (name == "CPackWiXFragment") {
State = INSIDE_FRAGMENT;
StartFragment(atts);
} else {
ReportValidationError("Expected 'CPackWixFragment' element");
}
else if(State == INSIDE_FRAGMENT)
{
cmWIXPatchElement &parent = *ElementStack.back();
} else if (State == INSIDE_FRAGMENT) {
cmWIXPatchElement& parent = *ElementStack.back();
cmWIXPatchElement *element = new cmWIXPatchElement;
parent.children.push_back(element);
cmWIXPatchElement* element = new cmWIXPatchElement;
parent.children.push_back(element);
element->name = name;
element->name = name;
for(size_t i = 0; atts[i]; i += 2)
{
std::string key = atts[i];
std::string value = atts[i+1];
for (size_t i = 0; atts[i]; i += 2) {
std::string key = atts[i];
std::string value = atts[i + 1];
element->attributes[key] = value;
}
ElementStack.push_back(element);
element->attributes[key] = value;
}
ElementStack.push_back(element);
}
}
void cmWIXPatchParser::StartFragment(const char **attributes)
void cmWIXPatchParser::StartFragment(const char** attributes)
{
for(size_t i = 0; attributes[i]; i += 2)
{
for (size_t i = 0; attributes[i]; i += 2) {
std::string key = attributes[i];
std::string value = attributes[i+1];
std::string value = attributes[i + 1];
if(key == "Id")
{
if(Fragments.find(value) != Fragments.end())
{
if (key == "Id") {
if (Fragments.find(value) != Fragments.end()) {
std::stringstream tmp;
tmp << "Invalid reuse of 'CPackWixFragment' 'Id': " << value;
ReportValidationError(tmp.str());
}
}
ElementStack.push_back(&Fragments[value]);
}
else
{
} else {
ReportValidationError(
"The only allowed 'CPackWixFragment' attribute is 'Id'");
}
}
}
}
void cmWIXPatchParser::EndElement(const std::string& name)
{
if(State == INSIDE_FRAGMENT)
{
if(name == "CPackWiXFragment")
{
State = BEGIN_FRAGMENTS;
ElementStack.clear();
}
else
{
ElementStack.pop_back();
}
if (State == INSIDE_FRAGMENT) {
if (name == "CPackWiXFragment") {
State = BEGIN_FRAGMENTS;
ElementStack.clear();
} else {
ElementStack.pop_back();
}
}
}
void cmWIXPatchParser::CharacterDataHandler(const char* data, int length)
{
const char* whitespace = "\x20\x09\x0d\x0a";
if(State == INSIDE_FRAGMENT)
{
cmWIXPatchElement &parent = *ElementStack.back();
if (State == INSIDE_FRAGMENT) {
cmWIXPatchElement& parent = *ElementStack.back();
std::string text(data, length);
std::string::size_type first = text.find_first_not_of(whitespace);
std::string::size_type last = text.find_last_not_of(whitespace);
if(first != std::string::npos && last != std::string::npos)
{
cmWIXPatchText *text_node = new cmWIXPatchText;
if (first != std::string::npos && last != std::string::npos) {
cmWIXPatchText* text_node = new cmWIXPatchText;
text_node->text = text.substr(first, last - first + 1);
parent.children.push_back(text_node);
}
}
}
}
void cmWIXPatchParser::ReportError(int line, int column, const char* msg)
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error while processing XML patch file at " << line << ":" << column <<
": "<< msg << std::endl);
"Error while processing XML patch file at "
<< line << ":" << column << ": " << msg << std::endl);
Valid = false;
}
void cmWIXPatchParser::ReportValidationError(std::string const& message)
{
ReportError(XML_GetCurrentLineNumber(static_cast<XML_Parser>(this->Parser)),
ReportError(
XML_GetCurrentLineNumber(static_cast<XML_Parser>(this->Parser)),
XML_GetCurrentColumnNumber(static_cast<XML_Parser>(this->Parser)),
message.c_str());
}
+2 -2
View File
@@ -65,9 +65,9 @@ public:
cmWIXPatchParser(fragment_map_t& Fragments, cmCPackLog* logger);
private:
virtual void StartElement(const std::string& name, const char **atts);
virtual void StartElement(const std::string& name, const char** atts);
void StartFragment(const char **attributes);
void StartFragment(const char** attributes);
virtual void EndElement(const std::string& name);
+47 -79
View File
@@ -15,8 +15,8 @@
#include <cmVersion.h>
cmWIXRichTextFormatWriter::cmWIXRichTextFormatWriter(
std::string const& filename):
File(filename.c_str(), std::ios::binary)
std::string const& filename)
: File(filename.c_str(), std::ios::binary)
{
StartGroup();
WriteHeader();
@@ -37,74 +37,50 @@ void cmWIXRichTextFormatWriter::AddText(std::string const& text)
{
typedef unsigned char rtf_byte_t;
for(size_t i = 0; i < text.size(); ++i)
{
for (size_t i = 0; i < text.size(); ++i) {
rtf_byte_t c = rtf_byte_t(text[i]);
switch(c)
{
case '\\':
File << "\\\\";
break;
case '{':
File << "\\{";
break;
case '}':
File << "\\}";
break;
case '\n':
File << "\\par\r\n";
break;
case '\r':
continue;
default:
{
if(c <= 0x7F)
{
switch (c) {
case '\\':
File << "\\\\";
break;
case '{':
File << "\\{";
break;
case '}':
File << "\\}";
break;
case '\n':
File << "\\par\r\n";
break;
case '\r':
continue;
default: {
if (c <= 0x7F) {
File << c;
}
else
{
if(c <= 0xC0)
{
EmitInvalidCodepoint(c);
}
else if(c < 0xE0 && i+1 < text.size())
{
EmitUnicodeCodepoint(
(text[i+1] & 0x3F) |
((c & 0x1F) << 6)
);
i+= 1;
}
else if(c < 0xF0 && i+2 < text.size())
{
EmitUnicodeCodepoint(
(text[i+2] & 0x3F) |
((text[i+1] & 0x3F) << 6) |
((c & 0xF) << 12)
);
i += 2;
}
else if(c < 0xF8 && i+3 < text.size())
{
EmitUnicodeCodepoint(
(text[i+3] & 0x3F) |
((text[i+2] & 0x3F) << 6) |
((text[i+1] & 0x3F) << 12) |
((c & 0x7) << 18)
);
i += 3;
}
else
{
EmitInvalidCodepoint(c);
}
} else {
if (c <= 0xC0) {
EmitInvalidCodepoint(c);
} else if (c < 0xE0 && i + 1 < text.size()) {
EmitUnicodeCodepoint((text[i + 1] & 0x3F) | ((c & 0x1F) << 6));
i += 1;
} else if (c < 0xF0 && i + 2 < text.size()) {
EmitUnicodeCodepoint((text[i + 2] & 0x3F) |
((text[i + 1] & 0x3F) << 6) |
((c & 0xF) << 12));
i += 2;
} else if (c < 0xF8 && i + 3 < text.size()) {
EmitUnicodeCodepoint(
(text[i + 3] & 0x3F) | ((text[i + 2] & 0x3F) << 6) |
((text[i + 1] & 0x3F) << 12) | ((c & 0x7) << 18));
i += 3;
} else {
EmitInvalidCodepoint(c);
}
}
break;
}
} break;
}
}
}
void cmWIXRichTextFormatWriter::WriteHeader()
@@ -190,33 +166,25 @@ void cmWIXRichTextFormatWriter::EndGroup()
void cmWIXRichTextFormatWriter::EmitUnicodeCodepoint(int c)
{
// Do not emit byte order mark (BOM)
if(c == 0xFEFF)
{
if (c == 0xFEFF) {
return;
}
else if(c <= 0xFFFF)
{
} else if (c <= 0xFFFF) {
EmitUnicodeSurrogate(c);
}
else
{
} else {
c -= 0x10000;
EmitUnicodeSurrogate(((c >> 10) & 0x3FF) + 0xD800);
EmitUnicodeSurrogate((c & 0x3FF) + 0xDC00);
}
}
}
void cmWIXRichTextFormatWriter::EmitUnicodeSurrogate(int c)
{
ControlWord("u");
if(c <= 32767)
{
if (c <= 32767) {
File << c;
}
else
{
} else {
File << (c - 65536);
}
}
File << "?";
}
+34 -44
View File
@@ -14,8 +14,8 @@
#include "cmWIXFilesSourceWriter.h"
void cmWIXShortcuts::insert(
Type type, std::string const& id, cmWIXShortcut const& shortcut)
void cmWIXShortcuts::insert(Type type, std::string const& id,
cmWIXShortcut const& shortcut)
{
this->Shortcuts[type][id].push_back(shortcut);
}
@@ -26,25 +26,22 @@ bool cmWIXShortcuts::empty(Type type) const
}
bool cmWIXShortcuts::EmitShortcuts(
Type type,
std::string const& registryKey,
Type type, std::string const& registryKey,
std::string const& cpackComponentName,
cmWIXFilesSourceWriter& fileDefinitions) const
{
shortcut_type_map_t::const_iterator i = this->Shortcuts.find(type);
if(i == this->Shortcuts.end())
{
if (i == this->Shortcuts.end()) {
return false;
}
}
shortcut_id_map_t const& id_map = i->second;
std::string shortcutPrefix;
std::string registrySuffix;
switch(type)
{
switch (type) {
case START_MENU:
shortcutPrefix = "CM_S";
break;
@@ -58,68 +55,61 @@ bool cmWIXShortcuts::EmitShortcuts(
break;
default:
return false;
}
}
for(shortcut_id_map_t::const_iterator j = id_map.begin();
j != id_map.end(); ++j)
{
for (shortcut_id_map_t::const_iterator j = id_map.begin(); j != id_map.end();
++j) {
std::string const& id = j->first;
shortcut_list_t const& shortcutList = j->second;
for(size_t shortcutListIndex = 0;
shortcutListIndex < shortcutList.size(); ++shortcutListIndex)
{
for (size_t shortcutListIndex = 0; shortcutListIndex < shortcutList.size();
++shortcutListIndex) {
cmWIXShortcut const& shortcut = shortcutList[shortcutListIndex];
fileDefinitions.EmitShortcut(id, shortcut,
shortcutPrefix, shortcutListIndex);
}
fileDefinitions.EmitShortcut(id, shortcut, shortcutPrefix,
shortcutListIndex);
}
}
fileDefinitions.EmitInstallRegistryValue(
registryKey, cpackComponentName, registrySuffix);
fileDefinitions.EmitInstallRegistryValue(registryKey, cpackComponentName,
registrySuffix);
return true;
}
void cmWIXShortcuts::AddShortcutTypes(std::set<Type>& types)
{
for(shortcut_type_map_t::const_iterator i = this->Shortcuts.begin();
i != this->Shortcuts.end(); ++i)
{
for (shortcut_type_map_t::const_iterator i = this->Shortcuts.begin();
i != this->Shortcuts.end(); ++i) {
types.insert(i->first);
}
}
}
void cmWIXShortcuts::CreateFromProperties(
std::string const& id,
std::string const& directoryId,
cmInstalledFile const& installedFile)
void cmWIXShortcuts::CreateFromProperties(std::string const& id,
std::string const& directoryId,
cmInstalledFile const& installedFile)
{
CreateFromProperty("CPACK_START_MENU_SHORTCUTS",
START_MENU, id, directoryId, installedFile);
CreateFromProperty("CPACK_START_MENU_SHORTCUTS", START_MENU, id, directoryId,
installedFile);
CreateFromProperty("CPACK_DESKTOP_SHORTCUTS",
DESKTOP, id, directoryId, installedFile);
CreateFromProperty("CPACK_DESKTOP_SHORTCUTS", DESKTOP, id, directoryId,
installedFile);
CreateFromProperty("CPACK_STARTUP_SHORTCUTS",
STARTUP, id, directoryId, installedFile);
CreateFromProperty("CPACK_STARTUP_SHORTCUTS", STARTUP, id, directoryId,
installedFile);
}
void cmWIXShortcuts::CreateFromProperty(
std::string const& propertyName,
Type type,
std::string const& id,
std::string const& directoryId,
cmInstalledFile const& installedFile)
void cmWIXShortcuts::CreateFromProperty(std::string const& propertyName,
Type type, std::string const& id,
std::string const& directoryId,
cmInstalledFile const& installedFile)
{
std::vector<std::string> list;
installedFile.GetPropertyAsList(propertyName, list);
for(size_t i = 0; i < list.size(); ++i)
{
for (size_t i = 0; i < list.size(); ++i) {
cmWIXShortcut shortcut;
shortcut.label = list[i];
shortcut.workingDirectoryId = directoryId;
insert(type, id, shortcut);
}
}
}
+9 -12
View File
@@ -45,26 +45,23 @@ public:
bool empty(Type type) const;
bool EmitShortcuts(
Type type,
std::string const& registryKey,
std::string const& cpackComponentName,
cmWIXFilesSourceWriter& fileDefinitions) const;
bool EmitShortcuts(Type type, std::string const& registryKey,
std::string const& cpackComponentName,
cmWIXFilesSourceWriter& fileDefinitions) const;
void AddShortcutTypes(std::set<Type>& types);
void CreateFromProperties(std::string const& id,
std::string const& directoryId, cmInstalledFile const& installedFile);
std::string const& directoryId,
cmInstalledFile const& installedFile);
private:
typedef std::map<Type, shortcut_id_map_t> shortcut_type_map_t;
void CreateFromProperty(
std::string const& propertyName,
Type type,
std::string const& id,
std::string const& directoryId,
cmInstalledFile const& installedFile);
void CreateFromProperty(std::string const& propertyName, Type type,
std::string const& id,
std::string const& directoryId,
cmInstalledFile const& installedFile);
shortcut_type_map_t Shortcuts;
shortcut_id_map_t EmptyIdMap;
+75 -99
View File
@@ -17,46 +17,41 @@
#include <windows.h>
cmWIXSourceWriter::cmWIXSourceWriter(cmCPackLog* logger,
std::string const& filename,
bool isIncludeFile):
Logger(logger),
File(filename.c_str()),
State(DEFAULT),
SourceFilename(filename)
std::string const& filename,
bool isIncludeFile)
: Logger(logger)
, File(filename.c_str())
, State(DEFAULT)
, SourceFilename(filename)
{
WriteXMLDeclaration();
if(isIncludeFile)
{
if (isIncludeFile) {
BeginElement("Include");
}
else
{
} else {
BeginElement("Wix");
}
}
AddAttribute("xmlns", "http://schemas.microsoft.com/wix/2006/wi");
}
cmWIXSourceWriter::~cmWIXSourceWriter()
{
if(Elements.size() > 1)
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
Elements.size() - 1 << " WiX elements were still open when closing '" <<
SourceFilename << "'" << std::endl);
if (Elements.size() > 1) {
cmCPackLogger(cmCPackLog::LOG_ERROR, Elements.size() - 1
<< " WiX elements were still open when closing '"
<< SourceFilename << "'" << std::endl);
return;
}
}
EndElement(Elements.back());
}
void cmWIXSourceWriter::BeginElement(std::string const& name)
{
if(State == BEGIN)
{
if (State == BEGIN) {
File << ">";
}
}
File << "\n";
Indent(Elements.size());
@@ -68,33 +63,27 @@ void cmWIXSourceWriter::BeginElement(std::string const& name)
void cmWIXSourceWriter::EndElement(std::string const& name)
{
if(Elements.empty())
{
if (Elements.empty()) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"can not end WiX element with no open elements in '" <<
SourceFilename << "'" << std::endl);
"can not end WiX element with no open elements in '"
<< SourceFilename << "'" << std::endl);
return;
}
}
if(Elements.back() != name)
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"WiX element <" << Elements.back() <<
"> can not be closed by </" << name << "> in '" <<
SourceFilename << "'" << std::endl);
if (Elements.back() != name) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "WiX element <"
<< Elements.back() << "> can not be closed by </" << name
<< "> in '" << SourceFilename << "'" << std::endl);
return;
}
}
if(State == DEFAULT)
{
if (State == DEFAULT) {
File << "\n";
Indent(Elements.size()-1);
Indent(Elements.size() - 1);
File << "</" << Elements.back() << ">";
}
else
{
} else {
File << "/>";
}
}
Elements.pop_back();
State = DEFAULT;
@@ -102,30 +91,27 @@ void cmWIXSourceWriter::EndElement(std::string const& name)
void cmWIXSourceWriter::AddTextNode(std::string const& text)
{
if(State == BEGIN)
{
if (State == BEGIN) {
File << ">";
}
}
if(Elements.empty())
{
if (Elements.empty()) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"can not add text without open WiX element in '" <<
SourceFilename << "'" << std::endl);
"can not add text without open WiX element in '"
<< SourceFilename << "'" << std::endl);
return;
}
}
File << this->EscapeAttributeValue(text);
State = DEFAULT;
}
void cmWIXSourceWriter::AddProcessingInstruction(
std::string const& target, std::string const& content)
void cmWIXSourceWriter::AddProcessingInstruction(std::string const& target,
std::string const& content)
{
if(State == BEGIN)
{
if (State == BEGIN) {
File << ">";
}
}
File << "\n";
Indent(Elements.size());
@@ -134,21 +120,20 @@ void cmWIXSourceWriter::AddProcessingInstruction(
State = DEFAULT;
}
void cmWIXSourceWriter::AddAttribute(
std::string const& key, std::string const& value)
void cmWIXSourceWriter::AddAttribute(std::string const& key,
std::string const& value)
{
std::string utf8 = CMakeEncodingToUtf8(value);
File << " " << key << "=\"" << EscapeAttributeValue(utf8) << '"';
}
void cmWIXSourceWriter::AddAttributeUnlessEmpty(
std::string const& key, std::string const& value)
void cmWIXSourceWriter::AddAttributeUnlessEmpty(std::string const& key,
std::string const& value)
{
if(!value.empty())
{
if (!value.empty()) {
AddAttribute(key, value);
}
}
}
std::string cmWIXSourceWriter::CMakeEncodingToUtf8(std::string const& value)
@@ -156,43 +141,38 @@ std::string cmWIXSourceWriter::CMakeEncodingToUtf8(std::string const& value)
#ifdef CMAKE_ENCODING_UTF8
return value;
#else
if(value.empty())
{
if (value.empty()) {
return std::string();
}
}
int characterCount = MultiByteToWideChar(
CP_ACP, 0, value.c_str(), static_cast<int>(value.size()), 0, 0);
if(characterCount == 0)
{
if (characterCount == 0) {
return std::string();
}
}
std::vector<wchar_t> utf16(characterCount);
MultiByteToWideChar(
CP_ACP, 0, value.c_str(), static_cast<int>(value.size()),
&utf16[0], static_cast<int>(utf16.size()));
MultiByteToWideChar(CP_ACP, 0, value.c_str(), static_cast<int>(value.size()),
&utf16[0], static_cast<int>(utf16.size()));
int utf8ByteCount = WideCharToMultiByte(
CP_UTF8, 0, &utf16[0], static_cast<int>(utf16.size()), 0, 0, 0, 0);
if(utf8ByteCount == 0)
{
if (utf8ByteCount == 0) {
return std::string();
}
}
std::vector<char> utf8(utf8ByteCount);
WideCharToMultiByte(CP_UTF8, 0, &utf16[0], static_cast<int>(utf16.size()),
&utf8[0], static_cast<int>(utf8.size()), 0, 0);
&utf8[0], static_cast<int>(utf8.size()), 0, 0);
return std::string(&utf8[0], utf8.size());
#endif
}
void cmWIXSourceWriter::WriteXMLDeclaration()
{
File << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << std::endl;
@@ -200,41 +180,37 @@ void cmWIXSourceWriter::WriteXMLDeclaration()
void cmWIXSourceWriter::Indent(size_t count)
{
for(size_t i = 0; i < count; ++i)
{
for (size_t i = 0; i < count; ++i) {
File << " ";
}
}
}
std::string cmWIXSourceWriter::EscapeAttributeValue(
std::string const& value)
std::string cmWIXSourceWriter::EscapeAttributeValue(std::string const& value)
{
std::string result;
result.reserve(value.size());
char c = 0;
for(size_t i = 0 ; i < value.size(); ++i)
{
for (size_t i = 0; i < value.size(); ++i) {
c = value[i];
switch(c)
{
case '<':
result += "&lt;";
break;
case '>':
result += "&gt;";
break;
case '&':
result +="&amp;";
break;
case '"':
result += "&quot;";
break;
default:
result += c;
break;
}
switch (c) {
case '<':
result += "&lt;";
break;
case '>':
result += "&gt;";
break;
case '&':
result += "&amp;";
break;
case '"':
result += "&quot;";
break;
default:
result += c;
break;
}
}
return result;
}
+8 -9
View File
@@ -26,8 +26,8 @@
class cmWIXSourceWriter
{
public:
cmWIXSourceWriter(cmCPackLog* logger,
std::string const& filename, bool isIncludeFile = false);
cmWIXSourceWriter(cmCPackLog* logger, std::string const& filename,
bool isIncludeFile = false);
~cmWIXSourceWriter();
@@ -37,19 +37,18 @@ public:
void AddTextNode(std::string const& text);
void AddProcessingInstruction(
std::string const& target, std::string const& content);
void AddProcessingInstruction(std::string const& target,
std::string const& content);
void AddAttribute(
std::string const& key, std::string const& value);
void AddAttribute(std::string const& key, std::string const& value);
void AddAttributeUnlessEmpty(
std::string const& key, std::string const& value);
void AddAttributeUnlessEmpty(std::string const& key,
std::string const& value);
static std::string CMakeEncodingToUtf8(std::string const& value);
protected:
cmCPackLog* Logger;
cmCPackLog* Logger;
private:
enum State
+1 -2
View File
@@ -13,8 +13,7 @@
#include "cmCPack7zGenerator.h"
cmCPack7zGenerator::cmCPack7zGenerator()
:cmCPackArchiveGenerator(cmArchiveWrite::CompressNone,
"7zip")
: cmCPackArchiveGenerator(cmArchiveWrite::CompressNone, "7zip")
{
}
+101 -137
View File
@@ -25,7 +25,7 @@
#include <cmsys/SystemTools.hxx>
cmCPackArchiveGenerator::cmCPackArchiveGenerator(cmArchiveWrite::Compress t,
std::string const& format)
std::string const& format)
{
this->Compress = t;
this->ArchiveFormat = format;
@@ -40,48 +40,41 @@ int cmCPackArchiveGenerator::InitializeInternal()
this->SetOptionIfNotSet("CPACK_INCLUDE_TOPLEVEL_DIRECTORY", "1");
return this->Superclass::InitializeInternal();
}
int cmCPackArchiveGenerator::addOneComponentToArchive(cmArchiveWrite& archive,
cmCPackComponent* component)
int cmCPackArchiveGenerator::addOneComponentToArchive(
cmArchiveWrite& archive, cmCPackComponent* component)
{
cmCPackLogger(cmCPackLog::LOG_VERBOSE, " - packaging component: "
<< component->Name
<< std::endl);
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;
localToplevel += "/" + component->Name;
std::string dir = cmSystemTools::GetCurrentWorkingDirectory();
// Change to local toplevel
cmSystemTools::ChangeDirectory(localToplevel);
std::string filePrefix;
if (this->IsOn("CPACK_COMPONENT_INCLUDE_TOPLEVEL_DIRECTORY"))
{
if (this->IsOn("CPACK_COMPONENT_INCLUDE_TOPLEVEL_DIRECTORY")) {
filePrefix = this->GetOption("CPACK_PACKAGE_FILE_NAME");
filePrefix += "/";
}
}
const char* installPrefix =
this->GetOption("CPACK_PACKAGING_INSTALL_PREFIX");
if(installPrefix && installPrefix[0] == '/' && installPrefix[1] != 0)
{
if (installPrefix && installPrefix[0] == '/' && installPrefix[1] != 0) {
// add to file prefix and remove the leading '/'
filePrefix += installPrefix+1;
filePrefix += installPrefix + 1;
filePrefix += "/";
}
}
std::vector<std::string>::const_iterator fileIt;
for (fileIt = component->Files.begin(); fileIt != component->Files.end();
++fileIt )
{
++fileIt) {
std::string rp = filePrefix + *fileIt;
cmCPackLogger(cmCPackLog::LOG_DEBUG,"Adding file: "
<< rp << std::endl);
cmCPackLogger(cmCPackLog::LOG_DEBUG, "Adding file: " << rp << std::endl);
archive.Add(rp, 0, 0, false);
if (!archive)
{
if (!archive) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "ERROR while packaging files: "
<< archive.GetError()
<< std::endl);
<< archive.GetError() << std::endl);
return 0;
}
}
}
// Go back to previous dir
cmSystemTools::ChangeDirectory(dir);
return 1;
@@ -92,26 +85,21 @@ int cmCPackArchiveGenerator::addOneComponentToArchive(cmArchiveWrite& archive,
* 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->ArchiveFormat); \
if (!archive) \
{ \
cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem to create archive < " \
<< filename \
<< ">. ERROR =" \
<< archive.GetError() \
<< std::endl); \
return 0; \
#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->ArchiveFormat); \
if (!archive) { \
cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem to create archive < " \
<< filename << ">. ERROR =" << archive.GetError() \
<< std::endl); \
return 0; \
}
int cmCPackArchiveGenerator::PackageComponents(bool ignoreGroup)
@@ -119,99 +107,86 @@ int cmCPackArchiveGenerator::PackageComponents(bool ignoreGroup)
packageFileNames.clear();
// The default behavior is to have one package by component group
// unless CPACK_COMPONENTS_IGNORE_GROUP is specified.
if (!ignoreGroup)
{
if (!ignoreGroup) {
std::map<std::string, cmCPackComponentGroup>::iterator compGIt;
for (compGIt=this->ComponentGroups.begin();
compGIt!=this->ComponentGroups.end(); ++compGIt)
{
for (compGIt = this->ComponentGroups.begin();
compGIt != this->ComponentGroups.end(); ++compGIt) {
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Packaging component group: "
<< compGIt->first
<< std::endl);
<< compGIt->first << std::endl);
// Begin the archive for this group
std::string packageFileName= std::string(toplevel);
packageFileName += "/"+
GetComponentPackageFileName(this->GetOption("CPACK_PACKAGE_FILE_NAME"),
compGIt->first,
true)
+ this->GetOutputExtension();
std::string packageFileName = std::string(toplevel);
packageFileName += "/" +
GetComponentPackageFileName(this->GetOption("CPACK_PACKAGE_FILE_NAME"),
compGIt->first, true) +
this->GetOutputExtension();
// open a block in order to automatically close archive
// at the end of the block
{
DECLARE_AND_OPEN_ARCHIVE(packageFileName,archive);
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)
{
for (compIt = (compGIt->second).Components.begin();
compIt != (compGIt->second).Components.end(); ++compIt) {
// Add the files of this component to the archive
addOneComponentToArchive(archive,*compIt);
}
addOneComponentToArchive(archive, *compIt);
}
}
// add the generated package to package file names list
packageFileNames.push_back(packageFileName);
}
}
// Handle Orphan components (components not belonging to any groups)
std::map<std::string, cmCPackComponent>::iterator compIt;
for (compIt=this->Components.begin();
compIt!=this->Components.end(); ++compIt )
{
for (compIt = this->Components.begin(); compIt != this->Components.end();
++compIt) {
// Does the component belong to a group?
if (compIt->second.Group==NULL)
{
cmCPackLogger(cmCPackLog::LOG_VERBOSE,
"Component <"
<< compIt->second.Name
<< "> does not belong to any group, package it separately."
<< std::endl);
if (compIt->second.Group == NULL) {
cmCPackLogger(
cmCPackLog::LOG_VERBOSE, "Component <"
<< compIt->second.Name
<< "> does not belong to any group, package it separately."
<< std::endl);
std::string localToplevel(
this->GetOption("CPACK_TEMPORARY_DIRECTORY")
);
this->GetOption("CPACK_TEMPORARY_DIRECTORY"));
std::string packageFileName = std::string(toplevel);
localToplevel += "/"+ compIt->first;
packageFileName += "/"+
GetComponentPackageFileName(this->GetOption("CPACK_PACKAGE_FILE_NAME"),
compIt->first,
false)
+ this->GetOutputExtension();
localToplevel += "/" + compIt->first;
packageFileName += "/" + GetComponentPackageFileName(
this->GetOption("CPACK_PACKAGE_FILE_NAME"),
compIt->first, false) +
this->GetOutputExtension();
{
DECLARE_AND_OPEN_ARCHIVE(packageFileName,archive);
DECLARE_AND_OPEN_ARCHIVE(packageFileName, archive);
// Add the files of this component to the archive
addOneComponentToArchive(archive,&(compIt->second));
addOneComponentToArchive(archive, &(compIt->second));
}
// add the generated package to package file names list
packageFileNames.push_back(packageFileName);
}
}
}
}
// CPACK_COMPONENTS_IGNORE_GROUPS is set
// We build 1 package per component
else
{
else {
std::map<std::string, cmCPackComponent>::iterator compIt;
for (compIt=this->Components.begin();
compIt!=this->Components.end(); ++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 += "/"+
GetComponentPackageFileName(this->GetOption("CPACK_PACKAGE_FILE_NAME"),
compIt->first,
false)
+ this->GetOutputExtension();
localToplevel += "/" + compIt->first;
packageFileName += "/" +
GetComponentPackageFileName(this->GetOption("CPACK_PACKAGE_FILE_NAME"),
compIt->first, false) +
this->GetOutputExtension();
{
DECLARE_AND_OPEN_ARCHIVE(packageFileName,archive);
DECLARE_AND_OPEN_ARCHIVE(packageFileName, archive);
// Add the files of this component to the archive
addOneComponentToArchive(archive,&(compIt->second));
addOneComponentToArchive(archive, &(compIt->second));
}
// add the generated package to package file names list
packageFileNames.push_back(packageFileName);
}
}
}
return 1;
}
@@ -220,23 +195,22 @@ int cmCPackArchiveGenerator::PackageComponentsAllInOne()
// reset the package file names
packageFileNames.clear();
packageFileNames.push_back(std::string(toplevel));
packageFileNames[0] += "/"
+std::string(this->GetOption("CPACK_PACKAGE_FILE_NAME"))
+ this->GetOutputExtension();
packageFileNames[0] += "/" +
std::string(this->GetOption("CPACK_PACKAGE_FILE_NAME")) +
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);
<< std::endl);
DECLARE_AND_OPEN_ARCHIVE(packageFileNames[0], archive);
// The ALL COMPONENTS in ONE package case
std::map<std::string, cmCPackComponent>::iterator compIt;
for (compIt=this->Components.begin();compIt!=this->Components.end();
++compIt )
{
for (compIt = this->Components.begin(); compIt != this->Components.end();
++compIt) {
// Add the files of this component to the archive
addOneComponentToArchive(archive,&(compIt->second));
}
addOneComponentToArchive(archive, &(compIt->second));
}
// archive goes out of scope so it will finalized and closed.
return 1;
@@ -244,50 +218,42 @@ int cmCPackArchiveGenerator::PackageComponentsAllInOne()
int cmCPackArchiveGenerator::PackageFiles()
{
cmCPackLogger(cmCPackLog::LOG_DEBUG, "Toplevel: "
<< toplevel << std::endl);
cmCPackLogger(cmCPackLog::LOG_DEBUG, "Toplevel: " << toplevel << std::endl);
if (WantsComponentInstallation()) {
// CASE 1 : COMPONENT ALL-IN-ONE package
// If ALL COMPONENTS in ONE package has been requested
// then the package file is unique and should be open here.
if (componentPackageMethod == ONE_PACKAGE)
{
if (componentPackageMethod == ONE_PACKAGE) {
return PackageComponentsAllInOne();
}
}
// 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
{
else {
return PackageComponents(componentPackageMethod ==
ONE_PACKAGE_PER_COMPONENT);
}
}
}
// CASE 3 : NON COMPONENT package.
DECLARE_AND_OPEN_ARCHIVE(packageFileNames[0],archive);
DECLARE_AND_OPEN_ARCHIVE(packageFileNames[0], archive);
std::vector<std::string>::const_iterator fileIt;
std::string dir = cmSystemTools::GetCurrentWorkingDirectory();
cmSystemTools::ChangeDirectory(toplevel);
for ( fileIt = files.begin(); fileIt != files.end(); ++ fileIt )
{
for (fileIt = files.begin(); fileIt != files.end(); ++fileIt) {
// Get the relative path to the file
std::string rp = cmSystemTools::RelativePath(toplevel.c_str(),
fileIt->c_str());
std::string rp =
cmSystemTools::RelativePath(toplevel.c_str(), fileIt->c_str());
archive.Add(rp, 0, 0, false);
if(!archive)
{
if (!archive) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem while adding file< "
<< *fileIt
<< "> to archive <"
<< packageFileNames[0] << "> .ERROR ="
<< archive.GetError()
<< std::endl);
<< *fileIt << "> to archive <" << packageFileNames[0]
<< "> .ERROR =" << archive.GetError() << std::endl);
return 0;
}
}
}
cmSystemTools::ChangeDirectory(dir);
// The destructor of cmArchiveWrite will close and finish the write
return 1;
@@ -298,16 +264,14 @@ int cmCPackArchiveGenerator::GenerateHeader(std::ostream*)
return 1;
}
bool cmCPackArchiveGenerator::SupportsComponentInstallation() const {
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"))
{
if (IsOn("CPACK_ARCHIVE_COMPONENT_INSTALL")) {
return true;
}
else
{
} else {
return false;
}
}
}
+3 -3
View File
@@ -17,7 +17,6 @@
#include "cmArchiveWrite.h"
/** \class cmCPackArchiveGenerator
* \brief A generator base for libarchive generation.
* The generator itself uses the libarchive wrapper
@@ -25,7 +24,7 @@
*
*/
class cmCPackArchiveGenerator : public cmCPackGenerator
{
{
public:
cmTypeMacro(cmCPackArchiveGenerator, cmCPackGenerator);
@@ -38,6 +37,7 @@ public:
virtual int GenerateHeader(std::ostream* os);
// component support
virtual bool SupportsComponentInstallation() const;
protected:
virtual int InitializeInternal();
/**
@@ -70,6 +70,6 @@ protected:
virtual const char* GetOutputExtension() = 0;
cmArchiveWrite::Compress Compress;
std::string ArchiveFormat;
};
};
#endif
+89 -99
View File
@@ -28,29 +28,25 @@ cmCPackBundleGenerator::~cmCPackBundleGenerator()
int cmCPackBundleGenerator::InitializeInternal()
{
const char* name = this->GetOption("CPACK_BUNDLE_NAME");
if(0 == name)
{
if (0 == name) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"CPACK_BUNDLE_NAME must be set to use the Bundle generator."
<< std::endl);
"CPACK_BUNDLE_NAME must be set to use the Bundle generator."
<< std::endl);
return 0;
}
}
if(this->GetOption("CPACK_BUNDLE_APPLE_CERT_APP"))
{
const std::string codesign_path = cmSystemTools::FindProgram("codesign",
std::vector<std::string>(), false);
if (this->GetOption("CPACK_BUNDLE_APPLE_CERT_APP")) {
const std::string codesign_path = cmSystemTools::FindProgram(
"codesign", std::vector<std::string>(), false);
if(codesign_path.empty())
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Cannot locate codesign command"
<< std::endl);
if (codesign_path.empty()) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot locate codesign command"
<< std::endl);
return 0;
}
this->SetOptionIfNotSet("CPACK_COMMAND_CODESIGN", codesign_path.c_str());
}
this->SetOptionIfNotSet("CPACK_COMMAND_CODESIGN", codesign_path.c_str());
}
return this->Superclass::InitializeInternal();
}
@@ -69,42 +65,40 @@ int cmCPackBundleGenerator::ConstructBundle()
// Get required arguments ...
const std::string cpack_bundle_name = this->GetOption("CPACK_BUNDLE_NAME")
? this->GetOption("CPACK_BUNDLE_NAME") : "";
if(cpack_bundle_name.empty())
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"CPACK_BUNDLE_NAME must be set."
<< std::endl);
? this->GetOption("CPACK_BUNDLE_NAME")
: "";
if (cpack_bundle_name.empty()) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "CPACK_BUNDLE_NAME must be set."
<< std::endl);
return 0;
}
}
const std::string cpack_bundle_plist = this->GetOption("CPACK_BUNDLE_PLIST")
? this->GetOption("CPACK_BUNDLE_PLIST") : "";
if(cpack_bundle_plist.empty())
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"CPACK_BUNDLE_PLIST must be set."
<< std::endl);
? this->GetOption("CPACK_BUNDLE_PLIST")
: "";
if (cpack_bundle_plist.empty()) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "CPACK_BUNDLE_PLIST must be set."
<< std::endl);
return 0;
}
}
const std::string cpack_bundle_icon = this->GetOption("CPACK_BUNDLE_ICON")
? this->GetOption("CPACK_BUNDLE_ICON") : "";
if(cpack_bundle_icon.empty())
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"CPACK_BUNDLE_ICON must be set."
<< std::endl);
? this->GetOption("CPACK_BUNDLE_ICON")
: "";
if (cpack_bundle_icon.empty()) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "CPACK_BUNDLE_ICON must be set."
<< std::endl);
return 0;
}
}
// Get optional arguments ...
const std::string cpack_bundle_startup_command =
this->GetOption("CPACK_BUNDLE_STARTUP_COMMAND")
? this->GetOption("CPACK_BUNDLE_STARTUP_COMMAND") : "";
? this->GetOption("CPACK_BUNDLE_STARTUP_COMMAND")
: "";
// The staging directory contains everything that will end-up inside the
// final disk image ...
@@ -112,30 +106,33 @@ int cmCPackBundleGenerator::ConstructBundle()
staging << toplevel;
std::ostringstream contents;
contents << staging.str() << "/" << cpack_bundle_name
<< ".app/" << "Contents";
contents << staging.str() << "/" << cpack_bundle_name << ".app/"
<< "Contents";
std::ostringstream application;
application << contents.str() << "/" << "MacOS";
application << contents.str() << "/"
<< "MacOS";
std::ostringstream resources;
resources << contents.str() << "/" << "Resources";
resources << contents.str() << "/"
<< "Resources";
// Install a required, user-provided bundle metadata file ...
std::ostringstream plist_source;
plist_source << cpack_bundle_plist;
std::ostringstream plist_target;
plist_target << contents.str() << "/" << "Info.plist";
plist_target << contents.str() << "/"
<< "Info.plist";
if(!this->CopyFile(plist_source, plist_target))
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
if (!this->CopyFile(plist_source, plist_target)) {
cmCPackLogger(
cmCPackLog::LOG_ERROR,
"Error copying plist. Check the value of CPACK_BUNDLE_PLIST."
<< std::endl);
<< std::endl);
return 0;
}
}
// Install a user-provided bundle icon ...
std::ostringstream icon_source;
@@ -144,52 +141,48 @@ int cmCPackBundleGenerator::ConstructBundle()
std::ostringstream icon_target;
icon_target << resources.str() << "/" << cpack_bundle_name << ".icns";
if(!this->CopyFile(icon_source, icon_target))
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
if (!this->CopyFile(icon_source, icon_target)) {
cmCPackLogger(
cmCPackLog::LOG_ERROR,
"Error copying bundle icon. Check the value of CPACK_BUNDLE_ICON."
<< std::endl);
<< std::endl);
return 0;
}
}
// Optionally a user-provided startup command (could be an
// executable or a script) ...
if(!cpack_bundle_startup_command.empty())
{
if (!cpack_bundle_startup_command.empty()) {
std::ostringstream command_source;
command_source << cpack_bundle_startup_command;
std::ostringstream command_target;
command_target << application.str() << "/" << cpack_bundle_name;
if(!this->CopyFile(command_source, command_target))
{
if (!this->CopyFile(command_source, command_target)) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error copying startup command. "
" Check the value of CPACK_BUNDLE_STARTUP_COMMAND."
<< std::endl);
<< std::endl);
return 0;
}
}
cmSystemTools::SetPermissions(command_target.str().c_str(), 0777);
}
}
return 1;
}
int cmCPackBundleGenerator::PackageFiles()
{
if(!this->ConstructBundle())
{
if (!this->ConstructBundle()) {
return 0;
}
}
if(!this->SignBundle(toplevel))
{
if (!this->SignBundle(toplevel)) {
return 0;
}
}
return this->CreateDMG(toplevel, packageFileNames[0]);
}
@@ -199,16 +192,15 @@ bool cmCPackBundleGenerator::SupportsComponentInstallation() const
return false;
}
int cmCPackBundleGenerator::SignBundle(const std::string& src_dir)
{
const std::string cpack_apple_cert_app =
this->GetOption("CPACK_BUNDLE_APPLE_CERT_APP")
? this->GetOption("CPACK_BUNDLE_APPLE_CERT_APP") : "";
? this->GetOption("CPACK_BUNDLE_APPLE_CERT_APP")
: "";
// codesign the application.
if(!cpack_apple_cert_app.empty())
{
if (!cpack_apple_cert_app.empty()) {
std::string output;
std::string bundle_path;
bundle_path = src_dir + "/";
@@ -223,15 +215,15 @@ int cmCPackBundleGenerator::SignBundle(const std::string& src_dir)
const std::string sign_files =
this->GetOption("CPACK_BUNDLE_APPLE_CODESIGN_FILES")
? this->GetOption("CPACK_BUNDLE_APPLE_CODESIGN_FILES") : "";
? this->GetOption("CPACK_BUNDLE_APPLE_CODESIGN_FILES")
: "";
std::vector<std::string> relFiles;
cmSystemTools::ExpandListArgument(sign_files, relFiles);
// sign the files supplied by the user, ie. frameworks.
for(std::vector<std::string>::iterator it = relFiles.begin();
it != relFiles.end(); ++it)
{
for (std::vector<std::string>::iterator it = relFiles.begin();
it != relFiles.end(); ++it) {
std::ostringstream temp_sign_file_cmd;
temp_sign_file_cmd << this->GetOption("CPACK_COMMAND_CODESIGN");
temp_sign_file_cmd << " " << sign_parameter << " -s \""
@@ -242,15 +234,14 @@ int cmCPackBundleGenerator::SignBundle(const std::string& src_dir)
temp_sign_file_cmd << bundle_path;
temp_sign_file_cmd << it->c_str() << "\"";
if(!this->RunCommand(temp_sign_file_cmd, &output))
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error signing file:"
<< bundle_path << it->c_str() << std::endl << output << std::endl);
if (!this->RunCommand(temp_sign_file_cmd, &output)) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Error signing file:"
<< bundle_path << it->c_str() << std::endl
<< output << std::endl);
return 0;
}
}
}
// sign main binary
std::ostringstream temp_sign_binary_cmd;
@@ -259,43 +250,42 @@ int cmCPackBundleGenerator::SignBundle(const std::string& src_dir)
<< cpack_apple_cert_app;
temp_sign_binary_cmd << "\" \"" << bundle_path << "\"";
if(!this->RunCommand(temp_sign_binary_cmd, &output))
{
if (!this->RunCommand(temp_sign_binary_cmd, &output)) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error signing the application binary."
<< std::endl << output << std::endl);
"Error signing the application binary." << std::endl
<< output
<< std::endl);
return 0;
}
}
// sign app bundle
std::ostringstream temp_codesign_cmd;
temp_codesign_cmd << this->GetOption("CPACK_COMMAND_CODESIGN");
temp_codesign_cmd << " " << sign_parameter << " -s \""
<< cpack_apple_cert_app << "\"";
if(this->GetOption("CPACK_BUNDLE_APPLE_ENTITLEMENTS"))
{
if (this->GetOption("CPACK_BUNDLE_APPLE_ENTITLEMENTS")) {
temp_codesign_cmd << " --entitlements ";
temp_codesign_cmd << this->GetOption("CPACK_BUNDLE_APPLE_ENTITLEMENTS");
}
}
temp_codesign_cmd << " \"" << bundle_path << "\"";
if(!this->RunCommand(temp_codesign_cmd, &output))
{
if (!this->RunCommand(temp_codesign_cmd, &output)) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error signing the application package."
<< std::endl << output << std::endl);
"Error signing the application package." << std::endl
<< output
<< std::endl);
return 0;
}
}
cmCPackLogger(cmCPackLog::LOG_OUTPUT,
"- Application has been codesigned"
<< std::endl);
cmCPackLogger(cmCPackLog::LOG_OUTPUT, "- Application has been codesigned"
<< std::endl);
cmCPackLogger(cmCPackLog::LOG_VERBOSE,
(this->GetOption("CPACK_BUNDLE_APPLE_ENTITLEMENTS")
? "with entitlement sandboxing" : "without entitlement sandboxing")
<< std::endl);
(this->GetOption("CPACK_BUNDLE_APPLE_ENTITLEMENTS")
? "with entitlement sandboxing"
: "without entitlement sandboxing")
<< std::endl);
}
return 1;
+8 -10
View File
@@ -18,28 +18,26 @@
#include <vector>
unsigned long cmCPackComponent::GetInstalledSize(
const std::string& installDir) const
const std::string& installDir) const
{
if (this->TotalSize != 0)
{
if (this->TotalSize != 0) {
return this->TotalSize;
}
}
std::vector<std::string>::const_iterator fileIt;
for (fileIt = this->Files.begin(); fileIt != this->Files.end(); ++fileIt)
{
for (fileIt = this->Files.begin(); fileIt != this->Files.end(); ++fileIt) {
std::string path = installDir;
path += '/';
path += *fileIt;
this->TotalSize += cmSystemTools::FileLength(path);
}
}
return this->TotalSize;
}
unsigned long
cmCPackComponent::GetInstalledSizeInKbytes(const std::string& installDir) const
unsigned long cmCPackComponent::GetInstalledSizeInKbytes(
const std::string& installDir) const
{
unsigned long result = (GetInstalledSize(installDir) + 512) / 1024;
return result? result : 1;
return result ? result : 1;
}
+19 -10
View File
@@ -42,9 +42,15 @@ public:
class cmCPackComponent
{
public:
cmCPackComponent() : Group(0), IsRequired(true), IsHidden(false),
IsDisabledByDefault(false), IsDownloaded(false),
TotalSize(0) { }
cmCPackComponent()
: Group(0)
, IsRequired(true)
, IsHidden(false)
, IsDisabledByDefault(false)
, IsDownloaded(false)
, TotalSize(0)
{
}
/// The name of the component (used to reference the component).
std::string Name;
@@ -53,7 +59,7 @@ public:
std::string DisplayName;
/// The component group that contains this component (if any).
cmCPackComponentGroup *Group;
cmCPackComponentGroup* Group;
/// Whether this component group must always be installed.
bool IsRequired : 1;
@@ -73,17 +79,17 @@ public:
std::string Description;
/// The installation types that this component is a part of.
std::vector<cmCPackInstallationType *> InstallationTypes;
std::vector<cmCPackInstallationType*> InstallationTypes;
/// If IsDownloaded is true, the name of the archive file that
/// contains the files that are part of this component.
std::string ArchiveFile;
/// The components that this component depends on.
std::vector<cmCPackComponent *> Dependencies;
std::vector<cmCPackComponent*> Dependencies;
/// The components that depend on this component.
std::vector<cmCPackComponent *> ReverseDependencies;
std::vector<cmCPackComponent*> ReverseDependencies;
/// The list of installed files that are part of this component.
std::vector<std::string> Files;
@@ -100,7 +106,7 @@ public:
/// kilobytes.
unsigned long GetInstalledSizeInKbytes(const std::string& installDir) const;
private:
private:
mutable unsigned long TotalSize;
};
@@ -110,7 +116,10 @@ public:
class cmCPackComponentGroup
{
public:
cmCPackComponentGroup() : ParentGroup(0) { }
cmCPackComponentGroup()
: ParentGroup(0)
{
}
/// The name of the group (used to reference the group).
std::string Name;
@@ -131,7 +140,7 @@ public:
std::vector<cmCPackComponent*> Components;
/// The parent group of this component group (if any).
cmCPackComponentGroup *ParentGroup;
cmCPackComponentGroup* ParentGroup;
/// The subgroups of this group.
std::vector<cmCPackComponentGroup*> Subgroups;
+11 -14
View File
@@ -45,8 +45,7 @@ int cmCPackCygwinBinaryGenerator::PackageFiles()
std::string manifest = "/usr/share/doc/";
manifest += packageName;
manifest += "/MANIFEST";
std::string manifestFile
= this->GetOption("CPACK_TEMPORARY_DIRECTORY");
std::string manifestFile = this->GetOption("CPACK_TEMPORARY_DIRECTORY");
// Create a MANIFEST file that contains all of the files in
// the tar file
std::string tempdir = manifestFile;
@@ -54,14 +53,13 @@ int cmCPackCygwinBinaryGenerator::PackageFiles()
// create an extra scope to force the stream
// to create the file before the super class is called
{
cmGeneratedFileStream ofs(manifestFile.c_str());
for(std::vector<std::string>::const_iterator i = files.begin();
i != files.end(); ++i)
{
// remove the temp dir and replace with /usr
ofs << (*i).substr(tempdir.size()) << "\n";
cmGeneratedFileStream ofs(manifestFile.c_str());
for (std::vector<std::string>::const_iterator i = files.begin();
i != files.end(); ++i) {
// remove the temp dir and replace with /usr
ofs << (*i).substr(tempdir.size()) << "\n";
}
ofs << manifest << "\n";
ofs << manifest << "\n";
}
// add the manifest file to the list of all files
files.push_back(manifestFile);
@@ -73,14 +71,13 @@ int cmCPackCygwinBinaryGenerator::PackageFiles()
const char* cmCPackCygwinBinaryGenerator::GetOutputExtension()
{
this->OutputExtension = "-";
const char* patchNumber =this->GetOption("CPACK_CYGWIN_PATCH_NUMBER");
if(!patchNumber)
{
const char* patchNumber = this->GetOption("CPACK_CYGWIN_PATCH_NUMBER");
if (!patchNumber) {
patchNumber = "1";
cmCPackLogger(cmCPackLog::LOG_WARNING,
"CPACK_CYGWIN_PATCH_NUMBER not specified using 1"
<< std::endl);
}
<< std::endl);
}
this->OutputExtension += patchNumber;
this->OutputExtension += ".tar.bz2";
return this->OutputExtension.c_str();
@@ -28,6 +28,7 @@ public:
*/
cmCPackCygwinBinaryGenerator();
virtual ~cmCPackCygwinBinaryGenerator();
protected:
virtual int InitializeInternal();
int PackageFiles();
+33 -43
View File
@@ -25,8 +25,8 @@
// system tools because it is not implemented robustly enough to move
// files across directories.
#ifdef _WIN32
# include <sys/stat.h>
# include <windows.h>
#include <sys/stat.h>
#include <windows.h>
#endif
cmCPackCygwinSourceGenerator::cmCPackCygwinSourceGenerator()
@@ -46,8 +46,8 @@ int cmCPackCygwinSourceGenerator::InitializeInternal()
int cmCPackCygwinSourceGenerator::PackageFiles()
{
// Create a tar file of the sources
std::string packageDirFileName
= this->GetOption("CPACK_TEMPORARY_DIRECTORY");
std::string packageDirFileName =
this->GetOption("CPACK_TEMPORARY_DIRECTORY");
packageDirFileName += ".tar.bz2";
packageFileNames[0] = packageDirFileName;
std::string output;
@@ -55,10 +55,9 @@ int cmCPackCygwinSourceGenerator::PackageFiles()
// to create tar.bz2 file with the list of source
// files
this->Compress = cmArchiveWrite::CompressBZip2;
if ( !this->cmCPackTarBZip2Generator::PackageFiles() )
{
if (!this->cmCPackTarBZip2Generator::PackageFiles()) {
return 0;
}
}
// Now create a tar file that contains the above .tar.bz2 file
// and the CPACK_CYGWIN_PATCH_FILE and CPACK_TOPLEVEL_DIRECTORY
// files
@@ -76,47 +75,41 @@ int cmCPackCygwinSourceGenerator::PackageFiles()
// to the toplevel cpack temp dir
// copy the patch file into place
if(!this->GetOption("CPACK_CYGWIN_PATCH_FILE"))
{
if (!this->GetOption("CPACK_CYGWIN_PATCH_FILE")) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"No patch file specified for cygwin sources.");
return 0;
}
if(!cmSystemTools::CopyFileAlways(
this->GetOption("CPACK_CYGWIN_PATCH_FILE"),
this->GetOption("CPACK_TOPLEVEL_DIRECTORY")))
{
}
if (!cmSystemTools::CopyFileAlways(
this->GetOption("CPACK_CYGWIN_PATCH_FILE"),
this->GetOption("CPACK_TOPLEVEL_DIRECTORY"))) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "problem copying: ["
<< this->GetOption("CPACK_CYGWIN_PATCH_FILE") << "]\nto\n["
<< this->GetOption("CPACK_TOPLEVEL_DIRECTORY") << "]\n");
<< this->GetOption("CPACK_CYGWIN_PATCH_FILE") << "]\nto\n["
<< this->GetOption("CPACK_TOPLEVEL_DIRECTORY") << "]\n");
return 0;
}
if(!this->GetOption("CPACK_CYGWIN_BUILD_SCRIPT"))
{
}
if (!this->GetOption("CPACK_CYGWIN_BUILD_SCRIPT")) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"No build script specified for cygwin sources.");
return 0;
}
}
// copy the build script into place
if(!cmSystemTools::CopyFileAlways(
this->GetOption("CPACK_CYGWIN_BUILD_SCRIPT"),
this->GetOption("CPACK_TOPLEVEL_DIRECTORY")))
{
if (!cmSystemTools::CopyFileAlways(
this->GetOption("CPACK_CYGWIN_BUILD_SCRIPT"),
this->GetOption("CPACK_TOPLEVEL_DIRECTORY"))) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "problem copying: "
<< this->GetOption("CPACK_CYGWIN_BUILD_SCRIPT") << "\nto\n"
<< this->GetOption("CPACK_TOPLEVEL_DIRECTORY") << "]\n");
<< this->GetOption("CPACK_CYGWIN_BUILD_SCRIPT") << "\nto\n"
<< this->GetOption("CPACK_TOPLEVEL_DIRECTORY") << "]\n");
return 0;
}
std::string outerTarFile
= this->GetOption("CPACK_TEMPORARY_DIRECTORY");
}
std::string outerTarFile = this->GetOption("CPACK_TEMPORARY_DIRECTORY");
outerTarFile += "-";
const char* patch = this->GetOption("CPACK_CYGWIN_PATCH_NUMBER");
if(!patch)
{
if (!patch) {
cmCPackLogger(cmCPackLog::LOG_WARNING, "CPACK_CYGWIN_PATCH_NUMBER"
<< " not specified, defaulting to 1\n");
<< " not specified, defaulting to 1\n");
patch = "1";
}
}
outerTarFile += patch;
outerTarFile += "-src.tar.bz2";
std::string tmpDir = this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
@@ -126,8 +119,8 @@ int cmCPackCygwinSourceGenerator::PackageFiles()
this->GetOption("CPACK_CYGWIN_BUILD_SCRIPT"));
std::string patchFile = tmpDir;
patchFile += "/";
patchFile += cmSystemTools::GetFilenameName(
this->GetOption("CPACK_CYGWIN_PATCH_FILE"));
patchFile +=
cmSystemTools::GetFilenameName(this->GetOption("CPACK_CYGWIN_PATCH_FILE"));
std::string file = cmSystemTools::GetFilenameName(compressOutFile);
std::string sourceTar = cmSystemTools::GetFilenamePath(compressOutFile);
@@ -146,10 +139,9 @@ int cmCPackCygwinSourceGenerator::PackageFiles()
packageFileNames[0] = outerTarFile;
/* update the toplevel dir */
toplevel = tmpDir;
if ( !this->cmCPackTarBZip2Generator::PackageFiles() )
{
if (!this->cmCPackTarBZip2Generator::PackageFiles()) {
return 0;
}
}
return 1;
}
@@ -164,14 +156,12 @@ const char* cmCPackCygwinSourceGenerator::GetOutputExtension()
{
this->OutputExtension = "-";
const char* patch = this->GetOption("CPACK_CYGWIN_PATCH_NUMBER");
if(!patch)
{
if (!patch) {
cmCPackLogger(cmCPackLog::LOG_WARNING, "CPACK_CYGWIN_PATCH_NUMBER"
<< " not specified, defaulting to 1\n");
<< " not specified, defaulting to 1\n");
patch = "1";
}
}
this->OutputExtension += patch;
this->OutputExtension += "-src.tar.bz2";
return this->OutputExtension.c_str();
}
@@ -28,6 +28,7 @@ public:
*/
cmCPackCygwinSourceGenerator();
virtual ~cmCPackCygwinSourceGenerator();
protected:
const char* GetPackagingInstallPrefix();
virtual int InitializeInternal();
+350 -437
View File
@@ -30,7 +30,8 @@
// a GNU ar.
// See http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=161593 for more info
// Therefore we provide our own implementation of a BSD-ar:
static int ar_append(const char*archive,const std::vector<std::string>& files);
static int ar_append(const char* archive,
const std::vector<std::string>& files);
cmCPackDebGenerator::cmCPackDebGenerator()
{
@@ -43,70 +44,63 @@ cmCPackDebGenerator::~cmCPackDebGenerator()
int cmCPackDebGenerator::InitializeInternal()
{
this->SetOptionIfNotSet("CPACK_PACKAGING_INSTALL_PREFIX", "/usr");
if (cmSystemTools::IsOff(this->GetOption("CPACK_SET_DESTDIR")))
{
if (cmSystemTools::IsOff(this->GetOption("CPACK_SET_DESTDIR"))) {
this->SetOption("CPACK_SET_DESTDIR", "I_ON");
}
}
return this->Superclass::InitializeInternal();
}
int cmCPackDebGenerator::PackageOnePack(std::string initialTopLevel,
std::string packageName)
{
{
int retval = 1;
// Begin the archive for this pack
std::string localToplevel(initialTopLevel);
std::string packageFileName(
cmSystemTools::GetParentDirectory(toplevel)
);
std::string outputFileName(
cmsys::SystemTools::LowerCase(
std::string(this->GetOption("CPACK_PACKAGE_FILE_NAME")))
+"-"+packageName + this->GetOutputExtension()
);
std::string packageFileName(cmSystemTools::GetParentDirectory(toplevel));
std::string outputFileName(cmsys::SystemTools::LowerCase(std::string(
this->GetOption("CPACK_PACKAGE_FILE_NAME"))) +
"-" + packageName + this->GetOutputExtension());
localToplevel += "/"+ packageName;
localToplevel += "/" + packageName;
/* replace the TEMP DIRECTORY with the component one */
this->SetOption("CPACK_TEMPORARY_DIRECTORY",localToplevel.c_str());
packageFileName += "/"+ outputFileName;
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());
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());
packageFileName.c_str());
// Tell CPackDeb.cmake the name of the component GROUP.
this->SetOption("CPACK_DEB_PACKAGE_COMPONENT",packageName.c_str());
this->SetOption("CPACK_DEB_PACKAGE_COMPONENT", packageName.c_str());
// Tell CPackDeb.cmake the path where the component is.
std::string component_path = "/";
component_path += packageName;
this->SetOption("CPACK_DEB_PACKAGE_COMPONENT_PART_PATH",
component_path.c_str());
if (!this->ReadListFile("CPackDeb.cmake"))
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error while execution CPackDeb.cmake" << std::endl);
if (!this->ReadListFile("CPackDeb.cmake")) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Error while execution CPackDeb.cmake"
<< std::endl);
retval = 0;
return retval;
}
}
cmsys::Glob gl;
std::string findExpr(this->GetOption("GEN_WDIR"));
findExpr += "/*";
gl.RecurseOn();
gl.SetRecurseListDirs(true);
if ( !gl.FindFiles(findExpr) )
{
if (!gl.FindFiles(findExpr)) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Cannot find any files in the installed directory" << std::endl);
"Cannot find any files in the installed directory"
<< std::endl);
return 0;
}
}
packageFiles = gl.GetFiles();
int res = createDeb();
if (res != 1)
{
if (res != 1) {
retval = 0;
}
}
// add the generated package to package file names list
packageFileName = this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
packageFileName += "/";
@@ -125,53 +119,46 @@ int cmCPackDebGenerator::PackageComponents(bool ignoreGroup)
// The default behavior is to have one package by component group
// unless CPACK_COMPONENTS_IGNORE_GROUP is specified.
if (!ignoreGroup)
{
if (!ignoreGroup) {
std::map<std::string, cmCPackComponentGroup>::iterator compGIt;
for (compGIt=this->ComponentGroups.begin();
compGIt!=this->ComponentGroups.end(); ++compGIt)
{
for (compGIt = this->ComponentGroups.begin();
compGIt != this->ComponentGroups.end(); ++compGIt) {
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Packaging component group: "
<< compGIt->first
<< std::endl);
<< compGIt->first << std::endl);
// Begin the archive for this group
retval &= PackageOnePack(initialTopLevel,compGIt->first);
}
retval &= PackageOnePack(initialTopLevel, compGIt->first);
}
// Handle Orphan components (components not belonging to any groups)
std::map<std::string, cmCPackComponent>::iterator compIt;
for (compIt=this->Components.begin();
compIt!=this->Components.end(); ++compIt )
{
for (compIt = this->Components.begin(); compIt != this->Components.end();
++compIt) {
// Does the component belong to a group?
if (compIt->second.Group==NULL)
{
cmCPackLogger(cmCPackLog::LOG_VERBOSE,
"Component <"
if (compIt->second.Group == NULL) {
cmCPackLogger(
cmCPackLog::LOG_VERBOSE, "Component <"
<< compIt->second.Name
<< "> does not belong to any group, package it separately."
<< std::endl);
// Begin the archive for this orphan component
retval &= PackageOnePack(initialTopLevel,compIt->first);
}
retval &= PackageOnePack(initialTopLevel, compIt->first);
}
}
}
// CPACK_COMPONENTS_IGNORE_GROUPS is set
// We build 1 package per component
else
{
else {
std::map<std::string, cmCPackComponent>::iterator compIt;
for (compIt=this->Components.begin();
compIt!=this->Components.end(); ++compIt )
{
retval &= PackageOnePack(initialTopLevel,compIt->first);
}
for (compIt = this->Components.begin(); compIt != this->Components.end();
++compIt) {
retval &= PackageOnePack(initialTopLevel, compIt->first);
}
}
return retval;
}
//----------------------------------------------------------------------
int cmCPackDebGenerator::PackageComponentsAllInOne(
const std::string& compInstDirName)
const std::string& compInstDirName)
{
int retval = 1;
/* Reset package file name list it will be populated during the
@@ -182,65 +169,57 @@ int cmCPackDebGenerator::PackageComponentsAllInOne(
cmCPackLogger(cmCPackLog::LOG_VERBOSE,
"Packaging all groups in one package..."
"(CPACK_COMPONENTS_ALL_[GROUPS_]IN_ONE_PACKAGE is set)"
<< std::endl);
<< std::endl);
// The ALL GROUPS in ONE package case
std::string localToplevel(initialTopLevel);
std::string packageFileName(
cmSystemTools::GetParentDirectory(toplevel)
);
std::string outputFileName(
cmsys::SystemTools::LowerCase(
std::string(this->GetOption("CPACK_PACKAGE_FILE_NAME")))
+ this->GetOutputExtension()
);
std::string packageFileName(cmSystemTools::GetParentDirectory(toplevel));
std::string outputFileName(cmsys::SystemTools::LowerCase(std::string(
this->GetOption("CPACK_PACKAGE_FILE_NAME"))) +
this->GetOutputExtension());
// all GROUP in one vs all COMPONENT in one
localToplevel += "/"+compInstDirName;
localToplevel += "/" + compInstDirName;
/* replace the TEMP DIRECTORY with the component one */
this->SetOption("CPACK_TEMPORARY_DIRECTORY",localToplevel.c_str());
packageFileName += "/"+ outputFileName;
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());
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());
packageFileName.c_str());
if(!compInstDirName.empty())
{
if (!compInstDirName.empty()) {
// Tell CPackDeb.cmake the path where the component is.
std::string component_path = "/";
component_path += compInstDirName;
this->SetOption("CPACK_DEB_PACKAGE_COMPONENT_PART_PATH",
component_path.c_str());
}
if (!this->ReadListFile("CPackDeb.cmake"))
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error while execution CPackDeb.cmake" << std::endl);
}
if (!this->ReadListFile("CPackDeb.cmake")) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Error while execution CPackDeb.cmake"
<< std::endl);
retval = 0;
return retval;
}
}
cmsys::Glob gl;
std::string findExpr(this->GetOption("GEN_WDIR"));
findExpr += "/*";
gl.RecurseOn();
gl.SetRecurseListDirs(true);
if ( !gl.FindFiles(findExpr) )
{
if (!gl.FindFiles(findExpr)) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Cannot find any files in the installed directory" << std::endl);
"Cannot find any files in the installed directory"
<< std::endl);
return 0;
}
}
packageFiles = gl.GetFiles();
int res = createDeb();
if (res != 1)
{
if (res != 1) {
retval = 0;
}
}
// add the generated package to package file names list
packageFileName = this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
packageFileName += "/";
@@ -256,25 +235,22 @@ int cmCPackDebGenerator::PackageFiles()
// 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 (componentPackageMethod == ONE_PACKAGE)
{
if (componentPackageMethod == ONE_PACKAGE) {
return PackageComponentsAllInOne("ALL_COMPONENTS_IN_ONE");
}
}
// 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
{
else {
return PackageComponents(componentPackageMethod ==
ONE_PACKAGE_PER_COMPONENT);
}
}
}
// CASE 3 : NON COMPONENT package.
else
{
else {
return PackageComponentsAllInOne("");
}
}
}
int cmCPackDebGenerator::createDeb()
@@ -282,11 +258,11 @@ int cmCPackDebGenerator::createDeb()
// debian-binary file
const std::string strGenWDIR(this->GetOption("GEN_WDIR"));
const std::string dbfilename = strGenWDIR + "/debian-binary";
{ // the scope is needed for cmGeneratedFileStream
{ // the scope is needed for cmGeneratedFileStream
cmGeneratedFileStream out(dbfilename.c_str());
out << "2.0";
out << std::endl; // required for valid debian package
}
}
// control file
std::string ctlfilename = strGenWDIR + "/control";
@@ -294,194 +270,171 @@ int cmCPackDebGenerator::createDeb()
// debian policy enforce lower case for package name
// mandatory entries:
std::string debian_pkg_name = cmsys::SystemTools::LowerCase(
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_NAME") );
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_NAME"));
const char* debian_pkg_version =
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_VERSION");
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_VERSION");
const char* debian_pkg_section =
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_SECTION");
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_SECTION");
const char* debian_pkg_priority =
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_PRIORITY");
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_PRIORITY");
const char* debian_pkg_arch =
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_ARCHITECTURE");
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_ARCHITECTURE");
const char* maintainer =
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_MAINTAINER");
const char* desc =
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_DESCRIPTION");
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_MAINTAINER");
const char* desc = this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_DESCRIPTION");
// optional entries
const char* debian_pkg_dep =
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_DEPENDS");
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_DEPENDS");
const char* debian_pkg_rec =
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_RECOMMENDS");
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_RECOMMENDS");
const char* debian_pkg_sug =
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_SUGGESTS");
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_SUGGESTS");
const char* debian_pkg_url =
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_HOMEPAGE");
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_HOMEPAGE");
const char* debian_pkg_predep =
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_PREDEPENDS");
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_PREDEPENDS");
const char* debian_pkg_enhances =
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_ENHANCES");
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_ENHANCES");
const char* debian_pkg_breaks =
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_BREAKS");
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_BREAKS");
const char* debian_pkg_conflicts =
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_CONFLICTS");
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_CONFLICTS");
const char* debian_pkg_provides =
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_PROVIDES");
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_PROVIDES");
const char* debian_pkg_replaces =
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_REPLACES");
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_REPLACES");
const char* debian_pkg_source =
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_SOURCE");
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_SOURCE");
{ // the scope is needed for cmGeneratedFileStream
{ // the scope is needed for cmGeneratedFileStream
cmGeneratedFileStream out(ctlfilename.c_str());
out << "Package: " << debian_pkg_name << "\n";
out << "Version: " << debian_pkg_version << "\n";
out << "Section: " << debian_pkg_section << "\n";
out << "Priority: " << debian_pkg_priority << "\n";
out << "Architecture: " << debian_pkg_arch << "\n";
if(debian_pkg_source && *debian_pkg_source)
{
if (debian_pkg_source && *debian_pkg_source) {
out << "Source: " << debian_pkg_source << "\n";
}
if(debian_pkg_dep && *debian_pkg_dep)
{
}
if (debian_pkg_dep && *debian_pkg_dep) {
out << "Depends: " << debian_pkg_dep << "\n";
}
if(debian_pkg_rec && *debian_pkg_rec)
{
}
if (debian_pkg_rec && *debian_pkg_rec) {
out << "Recommends: " << debian_pkg_rec << "\n";
}
if(debian_pkg_sug && *debian_pkg_sug)
{
}
if (debian_pkg_sug && *debian_pkg_sug) {
out << "Suggests: " << debian_pkg_sug << "\n";
}
if(debian_pkg_url && *debian_pkg_url)
{
}
if (debian_pkg_url && *debian_pkg_url) {
out << "Homepage: " << debian_pkg_url << "\n";
}
if (debian_pkg_predep && *debian_pkg_predep)
{
}
if (debian_pkg_predep && *debian_pkg_predep) {
out << "Pre-Depends: " << debian_pkg_predep << "\n";
}
if (debian_pkg_enhances && *debian_pkg_enhances)
{
}
if (debian_pkg_enhances && *debian_pkg_enhances) {
out << "Enhances: " << debian_pkg_enhances << "\n";
}
if (debian_pkg_breaks && *debian_pkg_breaks)
{
}
if (debian_pkg_breaks && *debian_pkg_breaks) {
out << "Breaks: " << debian_pkg_breaks << "\n";
}
if (debian_pkg_conflicts && *debian_pkg_conflicts)
{
}
if (debian_pkg_conflicts && *debian_pkg_conflicts) {
out << "Conflicts: " << debian_pkg_conflicts << "\n";
}
if (debian_pkg_provides && *debian_pkg_provides)
{
}
if (debian_pkg_provides && *debian_pkg_provides) {
out << "Provides: " << debian_pkg_provides << "\n";
}
if (debian_pkg_replaces && *debian_pkg_replaces)
{
}
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");
dirName += '/';
for (std::vector<std::string>::const_iterator fileIt =
packageFiles.begin();
fileIt != packageFiles.end(); ++ fileIt )
{
packageFiles.begin();
fileIt != packageFiles.end(); ++fileIt) {
totalSize += cmSystemTools::FileLength(*fileIt);
}
}
}
out << "Installed-Size: " << (totalSize + 1023) / 1024 << "\n";
out << "Maintainer: " << maintainer << "\n";
out << "Description: " << desc << "\n";
out << std::endl;
}
}
const std::string shlibsfilename = strGenWDIR + "/shlibs";
const char* debian_pkg_shlibs = this->GetOption(
"GEN_CPACK_DEBIAN_PACKAGE_SHLIBS");
const bool gen_shibs = this->IsOn("CPACK_DEBIAN_PACKAGE_GENERATE_SHLIBS")
&& debian_pkg_shlibs && *debian_pkg_shlibs;
if( gen_shibs )
{
const char* debian_pkg_shlibs =
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_SHLIBS");
const bool gen_shibs = this->IsOn("CPACK_DEBIAN_PACKAGE_GENERATE_SHLIBS") &&
debian_pkg_shlibs && *debian_pkg_shlibs;
if (gen_shibs) {
cmGeneratedFileStream out(shlibsfilename.c_str());
out << debian_pkg_shlibs;
out << std::endl;
}
}
const std::string postinst = strGenWDIR + "/postinst";
const std::string postrm = strGenWDIR + "/postrm";
if(this->IsOn("GEN_CPACK_DEBIAN_GENERATE_POSTINST"))
{
if (this->IsOn("GEN_CPACK_DEBIAN_GENERATE_POSTINST")) {
cmGeneratedFileStream out(postinst.c_str());
out <<
"#!/bin/sh\n\n"
"set -e\n\n"
"if [ \"$1\" = \"configure\" ]; then\n"
"\tldconfig\n"
"fi\n";
}
if(this->IsOn("GEN_CPACK_DEBIAN_GENERATE_POSTRM"))
{
out << "#!/bin/sh\n\n"
"set -e\n\n"
"if [ \"$1\" = \"configure\" ]; then\n"
"\tldconfig\n"
"fi\n";
}
if (this->IsOn("GEN_CPACK_DEBIAN_GENERATE_POSTRM")) {
cmGeneratedFileStream out(postrm.c_str());
out <<
"#!/bin/sh\n\n"
"set -e\n\n"
"if [ \"$1\" = \"remove\" ]; then\n"
"\tldconfig\n"
"fi\n";
}
out << "#!/bin/sh\n\n"
"set -e\n\n"
"if [ \"$1\" = \"remove\" ]; then\n"
"\tldconfig\n"
"fi\n";
}
cmArchiveWrite::Compress tar_compression_type = cmArchiveWrite::CompressGZip;
const char* debian_compression_type =
this->GetOption("GEN_CPACK_DEBIAN_COMPRESSION_TYPE");
if(!debian_compression_type)
{
this->GetOption("GEN_CPACK_DEBIAN_COMPRESSION_TYPE");
if (!debian_compression_type) {
debian_compression_type = "gzip";
}
}
std::string compression_suffix;
if(!strcmp(debian_compression_type, "lzma")) {
compression_suffix = ".lzma";
tar_compression_type = cmArchiveWrite::CompressLZMA;
} else if(!strcmp(debian_compression_type, "xz")) {
compression_suffix = ".xz";
tar_compression_type = cmArchiveWrite::CompressXZ;
} else if(!strcmp(debian_compression_type, "bzip2")) {
compression_suffix = ".bz2";
tar_compression_type = cmArchiveWrite::CompressBZip2;
} else if(!strcmp(debian_compression_type, "gzip")) {
compression_suffix = ".gz";
tar_compression_type = cmArchiveWrite::CompressGZip;
} else if(!strcmp(debian_compression_type, "none")) {
compression_suffix = "";
tar_compression_type = cmArchiveWrite::CompressNone;
if (!strcmp(debian_compression_type, "lzma")) {
compression_suffix = ".lzma";
tar_compression_type = cmArchiveWrite::CompressLZMA;
} else if (!strcmp(debian_compression_type, "xz")) {
compression_suffix = ".xz";
tar_compression_type = cmArchiveWrite::CompressXZ;
} else if (!strcmp(debian_compression_type, "bzip2")) {
compression_suffix = ".bz2";
tar_compression_type = cmArchiveWrite::CompressBZip2;
} else if (!strcmp(debian_compression_type, "gzip")) {
compression_suffix = ".gz";
tar_compression_type = cmArchiveWrite::CompressGZip;
} else if (!strcmp(debian_compression_type, "none")) {
compression_suffix = "";
tar_compression_type = cmArchiveWrite::CompressNone;
} else {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error unrecognized compression type: "
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error unrecognized compression type: "
<< debian_compression_type << std::endl);
}
std::string filename_data_tar = strGenWDIR
+ "/data.tar" + compression_suffix;
std::string filename_data_tar =
strGenWDIR + "/data.tar" + compression_suffix;
// atomic file generation for data.tar
{
cmGeneratedFileStream fileStream_data_tar;
fileStream_data_tar.Open(filename_data_tar.c_str(), false, true);
if(!fileStream_data_tar)
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error opening the file \"" << filename_data_tar << "\" for writing"
<< std::endl);
if (!fileStream_data_tar) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Error opening the file \""
<< filename_data_tar << "\" for writing" << std::endl);
return 0;
}
}
cmArchiveWrite data_tar(fileStream_data_tar, tar_compression_type, "paxr");
// uid/gid should be the one of the root user, and this root user has
@@ -495,81 +448,69 @@ int cmCPackDebGenerator::createDeb()
// give /usr and /opt
size_t topLevelLength = strGenWDIR.length();
cmCPackLogger(cmCPackLog::LOG_DEBUG, "WDIR: \""
<< strGenWDIR
<< "\", length = " << topLevelLength
<< std::endl);
<< strGenWDIR << "\", length = " << topLevelLength
<< std::endl);
std::set<std::string> orderedFiles;
// we have to reconstruct the parent folders as well
for (std::vector<std::string>::const_iterator fileIt =
packageFiles.begin();
fileIt != packageFiles.end(); ++ fileIt )
{
packageFiles.begin();
fileIt != packageFiles.end(); ++fileIt) {
std::string currentPath = *fileIt;
while(currentPath != strGenWDIR)
{
while (currentPath != strGenWDIR) {
// the last one IS strGenWDIR, but we do not want this one:
// XXX/application/usr/bin/myprogram with GEN_WDIR=XXX/application
// should not add XXX/application
orderedFiles.insert(currentPath);
currentPath = cmSystemTools::CollapseCombinedPath(currentPath, "..");
}
}
}
for (std::set<std::string>::const_iterator fileIt =
orderedFiles.begin();
fileIt != orderedFiles.end(); ++ fileIt )
{
for (std::set<std::string>::const_iterator fileIt = orderedFiles.begin();
fileIt != orderedFiles.end(); ++fileIt) {
cmCPackLogger(cmCPackLog::LOG_DEBUG, "FILEIT: \"" << *fileIt << "\""
<< std::endl);
std::string::size_type slashPos = fileIt->find('/', topLevelLength+1);
std::string relativeDir = fileIt->substr(topLevelLength,
slashPos - topLevelLength);
cmCPackLogger(cmCPackLog::LOG_DEBUG, "RELATIVEDIR: \"" << relativeDir
<< "\"" << std::endl);
<< std::endl);
std::string::size_type slashPos = fileIt->find('/', topLevelLength + 1);
std::string relativeDir =
fileIt->substr(topLevelLength, slashPos - topLevelLength);
cmCPackLogger(cmCPackLog::LOG_DEBUG, "RELATIVEDIR: \""
<< relativeDir << "\"" << std::endl);
// do not recurse because the loop will do it
if(!data_tar.Add(*fileIt, topLevelLength, ".", false))
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Problem adding file to tar:" << std::endl
<< "#top level directory: "
<< strGenWDIR << std::endl
<< "#file: " << *fileIt << std::endl
<< "#error:" << data_tar.GetError() << std::endl);
if (!data_tar.Add(*fileIt, topLevelLength, ".", false)) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem adding file to tar:"
<< std::endl
<< "#top level directory: " << strGenWDIR << std::endl
<< "#file: " << *fileIt << std::endl
<< "#error:" << data_tar.GetError() << std::endl);
return 0;
}
}
}
} // scope for file generation
std::string md5filename = strGenWDIR + "/md5sums";
{
// the scope is needed for cmGeneratedFileStream
cmGeneratedFileStream out(md5filename.c_str());
std::string topLevelWithTrailingSlash =
this->GetOption("CPACK_TEMPORARY_DIRECTORY");
this->GetOption("CPACK_TEMPORARY_DIRECTORY");
topLevelWithTrailingSlash += '/';
for (std::vector<std::string>::const_iterator fileIt =
packageFiles.begin();
fileIt != packageFiles.end(); ++ fileIt )
{
fileIt != packageFiles.end(); ++fileIt) {
// hash only regular files
if( cmSystemTools::FileIsDirectory(*fileIt)
|| cmSystemTools::FileIsSymlink(*fileIt))
{
if (cmSystemTools::FileIsDirectory(*fileIt) ||
cmSystemTools::FileIsSymlink(*fileIt)) {
continue;
}
}
char md5sum[33];
if(!cmSystemTools::ComputeFileMD5(*fileIt, md5sum))
{
if (!cmSystemTools::ComputeFileMD5(*fileIt, md5sum)) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem computing the md5 of "
<< *fileIt << std::endl);
}
<< *fileIt << std::endl);
}
md5sum[32] = 0;
@@ -578,31 +519,27 @@ int cmCPackDebGenerator::createDeb()
// debian md5sums entries are like this:
// 014f3604694729f3bf19263bac599765 usr/bin/ccmake
// thus strip the full path (with the trailing slash)
cmSystemTools::ReplaceString(output,
topLevelWithTrailingSlash.c_str(), "");
cmSystemTools::ReplaceString(output, topLevelWithTrailingSlash.c_str(),
"");
out << output;
}
}
// each line contains a eol.
// Do not end the md5sum file with yet another (invalid)
}
std::string filename_control_tar = strGenWDIR + "/control.tar.gz";
// atomic file generation for control.tar
{
cmGeneratedFileStream fileStream_control_tar;
fileStream_control_tar.Open(filename_control_tar.c_str(), false, true);
if(!fileStream_control_tar)
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error opening the file \"" << filename_control_tar
<< "\" for writing" << std::endl);
if (!fileStream_control_tar) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Error opening the file \""
<< filename_control_tar << "\" for writing"
<< std::endl);
return 0;
}
}
cmArchiveWrite control_tar(fileStream_control_tar,
cmArchiveWrite::CompressGZip,
"paxr");
cmArchiveWrite::CompressGZip, "paxr");
// sets permissions and uid/gid for the files
control_tar.SetUIDAndGID(0u, 0u);
@@ -623,113 +560,96 @@ int cmCPackDebGenerator::createDeb()
control_tar.SetPermissions(permission644);
// adds control and md5sums
if( !control_tar.Add(md5filename, strGenWDIR.length(), ".")
|| !control_tar.Add(strGenWDIR + "/control", strGenWDIR.length(), "."))
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error adding file to tar:" << std::endl
<< "#top level directory: "
<< strGenWDIR << std::endl
<< "#file: \"control\" or \"md5sums\"" << std::endl
<< "#error:" << control_tar.GetError() << std::endl);
return 0;
}
if (!control_tar.Add(md5filename, strGenWDIR.length(), ".") ||
!control_tar.Add(strGenWDIR + "/control", strGenWDIR.length(), ".")) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Error adding file to tar:"
<< std::endl
<< "#top level directory: " << strGenWDIR << std::endl
<< "#file: \"control\" or \"md5sums\"" << std::endl
<< "#error:" << control_tar.GetError() << std::endl);
return 0;
}
// adds generated shlibs file
if( gen_shibs )
{
if( !control_tar.Add(shlibsfilename, strGenWDIR.length(), ".") )
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error adding file to tar:" << std::endl
<< "#top level directory: "
<< strGenWDIR << std::endl
<< "#file: \"shlibs\"" << std::endl
<< "#error:" << control_tar.GetError() << std::endl);
return 0;
}
if (gen_shibs) {
if (!control_tar.Add(shlibsfilename, strGenWDIR.length(), ".")) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Error adding file to tar:"
<< std::endl
<< "#top level directory: " << strGenWDIR << std::endl
<< "#file: \"shlibs\"" << std::endl
<< "#error:" << control_tar.GetError() << std::endl);
return 0;
}
}
// adds LDCONFIG related files
if(this->IsOn("GEN_CPACK_DEBIAN_GENERATE_POSTINST"))
{
if (this->IsOn("GEN_CPACK_DEBIAN_GENERATE_POSTINST")) {
control_tar.SetPermissions(permission755);
if(!control_tar.Add(postinst, strGenWDIR.length(), "."))
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error adding file to tar:" << std::endl
<< "#top level directory: "
<< strGenWDIR << std::endl
<< "#file: \"postinst\"" << std::endl
<< "#error:" << control_tar.GetError() << std::endl);
return 0;
}
control_tar.SetPermissions(permission644);
if (!control_tar.Add(postinst, strGenWDIR.length(), ".")) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Error adding file to tar:"
<< std::endl
<< "#top level directory: " << strGenWDIR << std::endl
<< "#file: \"postinst\"" << std::endl
<< "#error:" << control_tar.GetError() << std::endl);
return 0;
}
control_tar.SetPermissions(permission644);
}
if(this->IsOn("GEN_CPACK_DEBIAN_GENERATE_POSTRM"))
{
if (this->IsOn("GEN_CPACK_DEBIAN_GENERATE_POSTRM")) {
control_tar.SetPermissions(permission755);
if(!control_tar.Add(postrm, strGenWDIR.length(), "."))
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error adding file to tar:" << std::endl
<< "#top level directory: "
<< strGenWDIR << std::endl
<< "#file: \"postinst\"" << std::endl
<< "#error:" << control_tar.GetError() << std::endl);
return 0;
}
control_tar.SetPermissions(permission644);
if (!control_tar.Add(postrm, strGenWDIR.length(), ".")) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Error adding file to tar:"
<< std::endl
<< "#top level directory: " << strGenWDIR << std::endl
<< "#file: \"postinst\"" << std::endl
<< "#error:" << control_tar.GetError() << std::endl);
return 0;
}
control_tar.SetPermissions(permission644);
}
// for the other files, we use
// -either the original permission on the files
// -either a permission strictly defined by the Debian policies
const char* controlExtra =
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA");
if( controlExtra )
{
if (controlExtra) {
// permissions are now controlled by the original file permissions
const bool permissionStrictPolicy =
this->IsSet("GEN_CPACK_DEBIAN_PACKAGE_CONTROL_STRICT_PERMISSION");
static const char* strictFiles[] = {
"config", "postinst", "postrm", "preinst", "prerm"
};
static const char* strictFiles[] = { "config", "postinst", "postrm",
"preinst", "prerm" };
std::set<std::string> setStrictFiles(
strictFiles,
strictFiles + sizeof(strictFiles)/sizeof(strictFiles[0]));
strictFiles + sizeof(strictFiles) / sizeof(strictFiles[0]));
// default
control_tar.ClearPermissions();
std::vector<std::string> controlExtraList;
cmSystemTools::ExpandListArgument(controlExtra, controlExtraList);
for(std::vector<std::string>::iterator i = controlExtraList.begin();
i != controlExtraList.end(); ++i)
{
std::string filenamename =
cmsys::SystemTools::GetFilenameName(*i);
for (std::vector<std::string>::iterator i = controlExtraList.begin();
i != controlExtraList.end(); ++i) {
std::string filenamename = cmsys::SystemTools::GetFilenameName(*i);
std::string localcopy = strGenWDIR + "/" + filenamename;
if(permissionStrictPolicy)
{
control_tar.SetPermissions(setStrictFiles.count(filenamename) ?
permission755 : permission644);
}
if (permissionStrictPolicy) {
control_tar.SetPermissions(setStrictFiles.count(filenamename)
? permission755
: permission644);
}
// if we can copy the file, it means it does exist, let's add it:
if( cmsys::SystemTools::CopyFileIfDifferent(*i, localcopy) )
{
if (cmsys::SystemTools::CopyFileIfDifferent(*i, localcopy)) {
control_tar.Add(localcopy, strGenWDIR.length(), ".");
}
}
}
}
}
// ar -r your-package-name.deb debian-binary control.tar.* data.tar.*
// since debian packages require BSD ar (most Linux distros and even
// FreeBSD and NetBSD ship GNU ar) we use a copy of OpenBSD ar here.
@@ -742,33 +662,29 @@ int cmCPackDebGenerator::createDeb()
outputFileName += "/";
outputFileName += this->GetOption("GEN_CPACK_OUTPUT_FILE_NAME");
int res = ar_append(outputFileName.c_str(), arFiles);
if ( res!=0 )
{
std::string tmpFile = this->GetOption(
"GEN_CPACK_TEMPORARY_PACKAGE_FILE_NAME");
if (res != 0) {
std::string tmpFile =
this->GetOption("GEN_CPACK_TEMPORARY_PACKAGE_FILE_NAME");
tmpFile += "/Deb.log";
cmGeneratedFileStream ofs(tmpFile.c_str());
ofs << "# Problem creating archive using: " << res << std::endl;
return 0;
}
}
return 1;
}
bool cmCPackDebGenerator::SupportsComponentInstallation() const
{
if (IsOn("CPACK_DEB_COMPONENT_INSTALL"))
{
return true;
}
else
{
return false;
}
{
if (IsOn("CPACK_DEB_COMPONENT_INSTALL")) {
return true;
} else {
return false;
}
}
std::string cmCPackDebGenerator::GetComponentInstallDirNameSuffix(
const std::string& componentName)
{
const std::string& componentName)
{
if (componentPackageMethod == ONE_PACKAGE_PER_COMPONENT) {
return componentName;
}
@@ -778,18 +694,14 @@ std::string cmCPackDebGenerator::GetComponentInstallDirNameSuffix(
}
// We have to find the name of the COMPONENT GROUP
// the current COMPONENT belongs to.
std::string groupVar = "CPACK_COMPONENT_" +
cmSystemTools::UpperCase(componentName) + "_GROUP";
if (NULL != GetOption(groupVar))
{
return std::string(GetOption(groupVar));
}
else
{
return componentName;
}
std::string groupVar =
"CPACK_COMPONENT_" + cmSystemTools::UpperCase(componentName) + "_GROUP";
if (NULL != GetOption(groupVar)) {
return std::string(GetOption(groupVar));
} else {
return componentName;
}
}
// The following code is taken from OpenBSD ar:
// http://www.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ar/
@@ -840,58 +752,61 @@ std::string cmCPackDebGenerator::GetComponentInstallDirNameSuffix(
#include <stdlib.h>
#include <string.h>
#define ARMAG "!<arch>\n" /* ar "magic number" */
#define SARMAG 8 /* strlen(ARMAG); */
#define ARMAG "!<arch>\n" /* ar "magic number" */
#define SARMAG 8 /* strlen(ARMAG); */
#define AR_EFMT1 "#1/" /* extended format #1 */
#define ARFMAG "`\n"
#define AR_EFMT1 "#1/" /* extended format #1 */
#define ARFMAG "`\n"
/* Header format strings. */
#define HDR1 "%s%-13d%-12ld%-6u%-6u%-8o%-10lld%2s"
#define HDR2 "%-16.16s%-12ld%-6u%-6u%-8o%-10lld%2s"
#define HDR1 "%s%-13d%-12ld%-6u%-6u%-8o%-10lld%2s"
#define HDR2 "%-16.16s%-12ld%-6u%-6u%-8o%-10lld%2s"
struct ar_hdr {
char ar_name[16]; /* name */
char ar_date[12]; /* modification time */
char ar_uid[6]; /* user id */
char ar_gid[6]; /* group id */
char ar_mode[8]; /* octal file permissions */
char ar_size[10]; /* size in bytes */
char ar_fmag[2]; /* consistency check */
struct ar_hdr
{
char ar_name[16]; /* name */
char ar_date[12]; /* modification time */
char ar_uid[6]; /* user id */
char ar_gid[6]; /* group id */
char ar_mode[8]; /* octal file permissions */
char ar_size[10]; /* size in bytes */
char ar_fmag[2]; /* consistency check */
};
/* Set up file copy. */
#define SETCF(from, fromname, to, toname, pad) { \
cf.rFile = from; \
cf.rname = fromname; \
cf.wFile = to; \
cf.wname = toname; \
cf.flags = pad; \
}
#define SETCF(from, fromname, to, toname, pad) \
{ \
cf.rFile = from; \
cf.rname = fromname; \
cf.wFile = to; \
cf.wname = toname; \
cf.flags = pad; \
}
/* File copy structure. */
typedef struct {
FILE* rFile; /* read file descriptor */
const char *rname; /* read name */
FILE* wFile; /* write file descriptor */
const char *wname; /* write name */
#define NOPAD 0x00 /* don't pad */
#define WPAD 0x02 /* pad on writes */
unsigned int flags; /* pad flags */
typedef struct
{
FILE* rFile; /* read file descriptor */
const char* rname; /* read name */
FILE* wFile; /* write file descriptor */
const char* wname; /* write name */
#define NOPAD 0x00 /* don't pad */
#define WPAD 0x02 /* pad on writes */
unsigned int flags; /* pad flags */
} CF;
/* misc.c */
static const char * ar_rname(const char *path)
static const char* ar_rname(const char* path)
{
const char *ind = strrchr(path, '/');
return (ind ) ? ind + 1 : path;
const char* ind = strrchr(path, '/');
return (ind) ? ind + 1 : path;
}
/* archive.c */
typedef struct ar_hdr HDR;
static char ar_hb[sizeof(HDR) + 1]; /* real header */
static char ar_hb[sizeof(HDR) + 1]; /* real header */
static size_t ar_already_written;
@@ -908,12 +823,12 @@ static size_t ar_already_written;
* because 16-bit word addressed copies were faster?) Anyhow, it should
* have been ripped out long ago.
*/
static int copy_ar(CF *cfp, off_t size)
static int copy_ar(CF* cfp, off_t size)
{
static char pad = '\n';
off_t sz = size;
size_t nr, nw;
char buf[8*1024];
char buf[8 * 1024];
if (sz == 0)
return 0;
@@ -921,60 +836,59 @@ static int copy_ar(CF *cfp, off_t size)
FILE* from = cfp->rFile;
FILE* to = cfp->wFile;
while (sz &&
(nr = fread(buf, 1, sz < static_cast<off_t>(sizeof(buf))
? static_cast<size_t>(sz) : sizeof(buf), from ))
> 0) {
(nr = fread(buf, 1, sz < static_cast<off_t>(sizeof(buf))
? static_cast<size_t>(sz)
: sizeof(buf),
from)) > 0) {
sz -= nr;
for (size_t off = 0; off < nr; nr -= off, off += nw)
if ((nw = fwrite(buf + off, 1, nr, to)) < nr)
return -1;
}
}
if (sz)
return -2;
if (cfp->flags & WPAD && (size + ar_already_written) & 1
&& fwrite(&pad, 1, 1, to) != 1)
if (cfp->flags & WPAD && (size + ar_already_written) & 1 &&
fwrite(&pad, 1, 1, to) != 1)
return -4;
return 0;
}
/* put_arobj -- Write an archive member to a file. */
static int put_arobj(CF *cfp, struct stat *sb)
static int put_arobj(CF* cfp, struct stat* sb)
{
int result = 0;
struct ar_hdr *hdr;
struct ar_hdr* hdr;
/* If passed an sb structure, reading a file from disk. Get stat(2)
* information, build a name and construct a header. (Files are named
* by their last component in the archive.) */
/* If passed an sb structure, reading a file from disk. Get stat(2)
* information, build a name and construct a header. (Files are named
* by their last component in the archive.) */
const char* name = ar_rname(cfp->rname);
(void)stat(cfp->rname, sb);
/* If not truncating names and the name is too long or contains
* a space, use extended format 1. */
/* If not truncating names and the name is too long or contains
* a space, use extended format 1. */
size_t lname = strlen(name);
uid_t uid = sb->st_uid;
gid_t gid = sb->st_gid;
if (uid > USHRT_MAX) {
uid = USHRT_MAX;
}
}
if (gid > USHRT_MAX) {
gid = USHRT_MAX;
}
}
if (lname > sizeof(hdr->ar_name) || strchr(name, ' '))
(void)sprintf(ar_hb, HDR1, AR_EFMT1, (int)lname,
(long int)sb->st_mtime, (unsigned)uid, (unsigned)gid,
(unsigned)sb->st_mode, (long long)sb->st_size + lname,
(void)sprintf(ar_hb, HDR1, AR_EFMT1, (int)lname, (long int)sb->st_mtime,
(unsigned)uid, (unsigned)gid, (unsigned)sb->st_mode,
(long long)sb->st_size + lname, ARFMAG);
else {
lname = 0;
(void)sprintf(ar_hb, HDR2, name, (long int)sb->st_mtime, (unsigned)uid,
(unsigned)gid, (unsigned)sb->st_mode, (long long)sb->st_size,
ARFMAG);
else {
lname = 0;
(void)sprintf(ar_hb, HDR2, name,
(long int)sb->st_mtime, (unsigned)uid, (unsigned)gid,
(unsigned)sb->st_mode, (long long)sb->st_size,
ARFMAG);
}
off_t size = sb->st_size;
}
off_t size = sb->st_size;
if (fwrite(ar_hb, 1, sizeof(HDR), cfp->wFile) != sizeof(HDR))
return -1;
@@ -983,7 +897,7 @@ static int put_arobj(CF *cfp, struct stat *sb)
if (fwrite(name, 1, lname, cfp->wFile) != lname)
return -2;
ar_already_written = lname;
}
}
result = copy_ar(cfp, size);
ar_already_written = 0;
return result;
@@ -995,42 +909,41 @@ static int put_arobj(CF *cfp, struct stat *sb)
* Append files to the archive - modifies original archive or creates
* a new archive if named archive does not exist.
*/
static int ar_append(const char* archive,const std::vector<std::string>& files)
static int ar_append(const char* archive,
const std::vector<std::string>& files)
{
int eval = 0;
FILE* aFile = cmSystemTools::Fopen(archive, "wb+");
if (aFile!=NULL) {
if (aFile != NULL) {
fwrite(ARMAG, SARMAG, 1, aFile);
if (fseek(aFile, 0, SEEK_END) != -1) {
CF cf;
struct stat sb;
/* Read from disk, write to an archive; pad on write. */
SETCF(NULL, 0, aFile, archive, WPAD);
for(std::vector<std::string>::const_iterator fileIt = files.begin();
fileIt!=files.end(); ++fileIt) {
for (std::vector<std::string>::const_iterator fileIt = files.begin();
fileIt != files.end(); ++fileIt) {
const char* filename = fileIt->c_str();
FILE* file = cmSystemTools::Fopen(filename, "rb");
if (file == NULL) {
eval = -1;
continue;
}
}
cf.rFile = file;
cf.rname = filename;
int result = put_arobj(&cf, &sb);
(void)fclose(file);
if (result!=0) {
if (result != 0) {
eval = -2;
break;
}
}
}
else {
eval = -3;
}
} else {
eval = -3;
}
fclose(aFile);
}
else {
} else {
eval = -4;
}
}
return eval;
}
+4 -5
View File
@@ -31,18 +31,18 @@ public:
virtual ~cmCPackDebGenerator();
static bool CanGenerate()
{
{
#ifdef __APPLE__
// on MacOS enable CPackDeb iff dpkg is found
std::vector<std::string> locations;
locations.push_back("/sw/bin"); // Fink
locations.push_back("/opt/local/bin"); // MacPorts
return cmSystemTools::FindProgram("dpkg",locations) != "" ? true : false;
return cmSystemTools::FindProgram("dpkg", locations) != "" ? true : false;
#else
// legacy behavior on other systems
return true;
#endif
}
}
protected:
virtual int InitializeInternal();
@@ -65,12 +65,11 @@ protected:
virtual const char* GetOutputExtension() { return ".deb"; }
virtual bool SupportsComponentInstallation() const;
virtual std::string GetComponentInstallDirNameSuffix(
const std::string& componentName);
const std::string& componentName);
private:
int createDeb();
std::vector<std::string> packageFiles;
};
#endif
+319 -443
View File
@@ -31,35 +31,35 @@
#endif
static const char* SLAHeader =
"data 'LPic' (5000) {\n"
" $\"0002 0011 0003 0001 0000 0000 0002 0000\"\n"
" $\"0008 0003 0000 0001 0004 0000 0004 0005\"\n"
" $\"0000 000E 0006 0001 0005 0007 0000 0007\"\n"
" $\"0008 0000 0047 0009 0000 0034 000A 0001\"\n"
" $\"0035 000B 0001 0020 000C 0000 0011 000D\"\n"
" $\"0000 005B 0004 0000 0033 000F 0001 000C\"\n"
" $\"0010 0000 000B 000E 0000\"\n"
"};\n"
"\n";
"data 'LPic' (5000) {\n"
" $\"0002 0011 0003 0001 0000 0000 0002 0000\"\n"
" $\"0008 0003 0000 0001 0004 0000 0004 0005\"\n"
" $\"0000 000E 0006 0001 0005 0007 0000 0007\"\n"
" $\"0008 0000 0047 0009 0000 0034 000A 0001\"\n"
" $\"0035 000B 0001 0020 000C 0000 0011 000D\"\n"
" $\"0000 005B 0004 0000 0033 000F 0001 000C\"\n"
" $\"0010 0000 000B 000E 0000\"\n"
"};\n"
"\n";
static const char* SLASTREnglish =
"resource 'STR#' (5002, \"English\") {\n"
" {\n"
" \"English\",\n"
" \"Agree\",\n"
" \"Disagree\",\n"
" \"Print\",\n"
" \"Save...\",\n"
" \"You agree to the License Agreement terms when you click \"\n"
" \"the \\\"Agree\\\" button.\",\n"
" \"Software License Agreement\",\n"
" \"This text cannot be saved. This disk may be full or locked, "
"or the \"\n"
" \"file may be locked.\",\n"
" \"Unable to print. Make sure you have selected a printer.\"\n"
" }\n"
"};\n"
"\n";
"resource 'STR#' (5002, \"English\") {\n"
" {\n"
" \"English\",\n"
" \"Agree\",\n"
" \"Disagree\",\n"
" \"Print\",\n"
" \"Save...\",\n"
" \"You agree to the License Agreement terms when you click \"\n"
" \"the \\\"Agree\\\" button.\",\n"
" \"Software License Agreement\",\n"
" \"This text cannot be saved. This disk may be full or locked, "
"or the \"\n"
" \"file may be locked.\",\n"
" \"Unable to print. Make sure you have selected a printer.\"\n"
" }\n"
"};\n"
"\n";
cmCPackDragNDropGenerator::cmCPackDragNDropGenerator()
: singleLicense(false)
@@ -80,102 +80,84 @@ int cmCPackDragNDropGenerator::InitializeInternal()
paths.push_back("/Applications/Xcode.app/Contents/Developer/Tools");
paths.push_back("/Developer/Tools");
const std::string hdiutil_path = cmSystemTools::FindProgram("hdiutil",
std::vector<std::string>(), false);
if(hdiutil_path.empty())
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Cannot locate hdiutil command"
<< std::endl);
const std::string hdiutil_path =
cmSystemTools::FindProgram("hdiutil", std::vector<std::string>(), false);
if (hdiutil_path.empty()) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot locate hdiutil command"
<< std::endl);
return 0;
}
}
this->SetOptionIfNotSet("CPACK_COMMAND_HDIUTIL", hdiutil_path.c_str());
const std::string setfile_path = cmSystemTools::FindProgram("SetFile",
paths, false);
if(setfile_path.empty())
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Cannot locate SetFile command"
<< std::endl);
const std::string setfile_path =
cmSystemTools::FindProgram("SetFile", paths, false);
if (setfile_path.empty()) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot locate SetFile command"
<< std::endl);
return 0;
}
}
this->SetOptionIfNotSet("CPACK_COMMAND_SETFILE", setfile_path.c_str());
const std::string rez_path = cmSystemTools::FindProgram("Rez",
paths, false);
if(rez_path.empty())
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Cannot locate Rez command"
<< std::endl);
const std::string rez_path = cmSystemTools::FindProgram("Rez", paths, false);
if (rez_path.empty()) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot locate Rez command"
<< std::endl);
return 0;
}
}
this->SetOptionIfNotSet("CPACK_COMMAND_REZ", rez_path.c_str());
if(this->IsSet("CPACK_DMG_SLA_DIR"))
{
if (this->IsSet("CPACK_DMG_SLA_DIR")) {
slaDirectory = this->GetOption("CPACK_DMG_SLA_DIR");
if(!slaDirectory.empty() && this->IsSet("CPACK_RESOURCE_FILE_LICENSE"))
{
if (!slaDirectory.empty() && this->IsSet("CPACK_RESOURCE_FILE_LICENSE")) {
std::string license_file =
this->GetOption("CPACK_RESOURCE_FILE_LICENSE");
if(!license_file.empty() &&
(license_file.find("CPack.GenericLicense.txt") == std::string::npos))
{
cmCPackLogger(cmCPackLog::LOG_OUTPUT,
if (!license_file.empty() &&
(license_file.find("CPack.GenericLicense.txt") ==
std::string::npos)) {
cmCPackLogger(
cmCPackLog::LOG_OUTPUT,
"Both CPACK_DMG_SLA_DIR and CPACK_RESOURCE_FILE_LICENSE specified, "
"using CPACK_RESOURCE_FILE_LICENSE as a license for all languages."
<< std::endl);
<< std::endl);
singleLicense = true;
}
}
if(!this->IsSet("CPACK_DMG_SLA_LANGUAGES"))
{
}
if (!this->IsSet("CPACK_DMG_SLA_LANGUAGES")) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"CPACK_DMG_SLA_DIR set but no languages defined "
"(set CPACK_DMG_SLA_LANGUAGES)"
<< std::endl);
"CPACK_DMG_SLA_DIR set but no languages defined "
"(set CPACK_DMG_SLA_LANGUAGES)"
<< std::endl);
return 0;
}
if(!cmSystemTools::FileExists(slaDirectory, false))
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"CPACK_DMG_SLA_DIR does not exist"
<< std::endl);
}
if (!cmSystemTools::FileExists(slaDirectory, false)) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "CPACK_DMG_SLA_DIR does not exist"
<< std::endl);
return 0;
}
}
std::vector<std::string> languages;
cmSystemTools::ExpandListArgument(
this->GetOption("CPACK_DMG_SLA_LANGUAGES"), languages);
if(languages.empty())
{
if (languages.empty()) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"CPACK_DMG_SLA_LANGUAGES set but empty"
<< std::endl);
"CPACK_DMG_SLA_LANGUAGES set but empty" << std::endl);
return 0;
}
for(size_t i = 0; i < languages.size(); ++i)
{
}
for (size_t i = 0; i < languages.size(); ++i) {
std::string license = slaDirectory + "/" + languages[i] + ".license.txt";
if (!singleLicense && !cmSystemTools::FileExists(license))
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Missing license file " << languages[i] << ".license.txt"
<< std::endl);
if (!singleLicense && !cmSystemTools::FileExists(license)) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Missing license file "
<< languages[i] << ".license.txt" << std::endl);
return 0;
}
}
std::string menu = slaDirectory + "/" + languages[i] + ".menu.txt";
if (!cmSystemTools::FileExists(menu))
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Missing menu file " << languages[i] << ".menu.txt"
<< std::endl);
if (!cmSystemTools::FileExists(menu)) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Missing menu file "
<< languages[i] << ".menu.txt" << std::endl);
return 0;
}
}
}
}
return this->Superclass::InitializeInternal();
}
@@ -191,40 +173,32 @@ int cmCPackDragNDropGenerator::PackageFiles()
// multiple directories occur if packaging components or groups separately
// monolith
if(this->Components.empty())
{
if (this->Components.empty()) {
return this->CreateDMG(toplevel, packageFileNames[0]);
}
}
// component install
std::vector<std::string> package_files;
std::map<std::string, cmCPackComponent>::iterator compIt;
for (compIt=this->Components.begin();
compIt!=this->Components.end(); ++compIt )
{
for (compIt = this->Components.begin(); compIt != this->Components.end();
++compIt) {
std::string name = GetComponentInstallDirNameSuffix(compIt->first);
package_files.push_back(name);
}
}
std::sort(package_files.begin(), package_files.end());
package_files.erase(std::unique(package_files.begin(),
package_files.end()),
package_files.erase(std::unique(package_files.begin(), package_files.end()),
package_files.end());
// loop to create dmg files
packageFileNames.clear();
for(size_t i=0; i<package_files.size(); i++)
{
for (size_t i = 0; i < package_files.size(); i++) {
std::string full_package_name = std::string(toplevel) + std::string("/");
if(package_files[i] == "ALL_IN_ONE")
{
if (package_files[i] == "ALL_IN_ONE") {
full_package_name += this->GetOption("CPACK_PACKAGE_FILE_NAME");
}
else
{
} else {
full_package_name += package_files[i];
}
}
full_package_name += std::string(GetOutputExtension());
packageFileNames.push_back(full_package_name);
@@ -232,30 +206,23 @@ int cmCPackDragNDropGenerator::PackageFiles()
src_dir += "/";
src_dir += package_files[i];
if(0 == this->CreateDMG(src_dir, full_package_name))
{
if (0 == this->CreateDMG(src_dir, full_package_name)) {
return 0;
}
}
}
return 1;
}
bool cmCPackDragNDropGenerator::CopyFile(std::ostringstream& source,
std::ostringstream& target)
std::ostringstream& target)
{
if(!cmSystemTools::CopyFileIfDifferent(
source.str().c_str(),
target.str().c_str()))
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error copying "
<< source.str()
<< " to "
<< target.str()
<< std::endl);
if (!cmSystemTools::CopyFileIfDifferent(source.str().c_str(),
target.str().c_str())) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Error copying "
<< source.str() << " to " << target.str() << std::endl);
return false;
}
}
return true;
}
@@ -263,46 +230,35 @@ bool cmCPackDragNDropGenerator::CopyFile(std::ostringstream& source,
bool cmCPackDragNDropGenerator::CreateEmptyFile(std::ostringstream& target,
size_t size)
{
cmsys::ofstream fout(target.str().c_str(),
std::ios::out | std::ios::binary);
if(!fout)
{
cmsys::ofstream fout(target.str().c_str(), std::ios::out | std::ios::binary);
if (!fout) {
return false;
}
else
{
} else {
// Seek to desired size - 1 byte
fout.seekp(size - 1, std::ios_base::beg);
char byte = 0;
// Write one byte to ensure file grows
fout.write(&byte, 1);
}
}
return true;
}
bool cmCPackDragNDropGenerator::RunCommand(std::ostringstream& command,
std::string* output)
std::string* output)
{
int exit_code = 1;
bool result = cmSystemTools::RunSingleCommand(
command.str().c_str(),
output, output,
&exit_code,
0,
this->GeneratorVerbose,
0);
bool result =
cmSystemTools::RunSingleCommand(command.str().c_str(), output, output,
&exit_code, 0, this->GeneratorVerbose, 0);
if(!result || exit_code)
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error executing: "
<< command.str()
<< std::endl);
if (!result || exit_code) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Error executing: " << command.str()
<< std::endl);
return false;
}
}
return true;
}
@@ -312,51 +268,54 @@ int cmCPackDragNDropGenerator::CreateDMG(const std::string& src_dir,
{
// Get optional arguments ...
const std::string cpack_package_icon = this->GetOption("CPACK_PACKAGE_ICON")
? this->GetOption("CPACK_PACKAGE_ICON") : "";
? this->GetOption("CPACK_PACKAGE_ICON")
: "";
const std::string cpack_dmg_volume_name =
this->GetOption("CPACK_DMG_VOLUME_NAME")
? this->GetOption("CPACK_DMG_VOLUME_NAME")
: this->GetOption("CPACK_PACKAGE_FILE_NAME");
: this->GetOption("CPACK_PACKAGE_FILE_NAME");
const std::string cpack_dmg_format =
this->GetOption("CPACK_DMG_FORMAT")
? this->GetOption("CPACK_DMG_FORMAT") : "UDZO";
const std::string cpack_dmg_format = this->GetOption("CPACK_DMG_FORMAT")
? this->GetOption("CPACK_DMG_FORMAT")
: "UDZO";
// Get optional arguments ...
std::string cpack_license_file =
this->GetOption("CPACK_RESOURCE_FILE_LICENSE") ?
this->GetOption("CPACK_RESOURCE_FILE_LICENSE") : "";
this->GetOption("CPACK_RESOURCE_FILE_LICENSE")
? this->GetOption("CPACK_RESOURCE_FILE_LICENSE")
: "";
const std::string cpack_dmg_background_image =
this->GetOption("CPACK_DMG_BACKGROUND_IMAGE")
? this->GetOption("CPACK_DMG_BACKGROUND_IMAGE") : "";
? this->GetOption("CPACK_DMG_BACKGROUND_IMAGE")
: "";
const std::string cpack_dmg_ds_store =
this->GetOption("CPACK_DMG_DS_STORE")
? this->GetOption("CPACK_DMG_DS_STORE") : "";
const std::string cpack_dmg_ds_store = this->GetOption("CPACK_DMG_DS_STORE")
? this->GetOption("CPACK_DMG_DS_STORE")
: "";
const std::string cpack_dmg_languages =
this->GetOption("CPACK_DMG_SLA_LANGUAGES")
? this->GetOption("CPACK_DMG_SLA_LANGUAGES") : "";
? this->GetOption("CPACK_DMG_SLA_LANGUAGES")
: "";
const std::string cpack_dmg_ds_store_setup_script =
this->GetOption("CPACK_DMG_DS_STORE_SETUP_SCRIPT")
? this->GetOption("CPACK_DMG_DS_STORE_SETUP_SCRIPT") : "";
? this->GetOption("CPACK_DMG_DS_STORE_SETUP_SCRIPT")
: "";
// only put license on dmg if is user provided
if(!cpack_license_file.empty() &&
cpack_license_file.find("CPack.GenericLicense.txt") != std::string::npos)
{
if (!cpack_license_file.empty() &&
cpack_license_file.find("CPack.GenericLicense.txt") !=
std::string::npos) {
cpack_license_file = "";
}
}
// use sla_dir if both sla_dir and license_file are set
if(!cpack_license_file.empty() &&
!slaDirectory.empty() && !singleLicense)
{
if (!cpack_license_file.empty() && !slaDirectory.empty() && !singleLicense) {
cpack_license_file = "";
}
}
// The staging directory contains everything that will end-up inside the
// final disk image ...
@@ -368,56 +327,52 @@ int cmCPackDragNDropGenerator::CreateDMG(const std::string& src_dir,
std::ostringstream application_link;
application_link << staging.str() << "/Applications";
cmSystemTools::CreateSymlink("/Applications",
application_link.str().c_str());
application_link.str().c_str());
// Optionally add a custom volume icon ...
if(!cpack_package_icon.empty())
{
if (!cpack_package_icon.empty()) {
std::ostringstream package_icon_source;
package_icon_source << cpack_package_icon;
std::ostringstream package_icon_destination;
package_icon_destination << staging.str() << "/.VolumeIcon.icns";
if(!this->CopyFile(package_icon_source, package_icon_destination))
{
if (!this->CopyFile(package_icon_source, package_icon_destination)) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error copying disk volume icon. "
"Error copying disk volume icon. "
"Check the value of CPACK_PACKAGE_ICON."
<< std::endl);
<< std::endl);
return 0;
}
}
}
// Optionally add a custom .DS_Store file
// (e.g. for setting background/layout) ...
if(!cpack_dmg_ds_store.empty())
{
if (!cpack_dmg_ds_store.empty()) {
std::ostringstream package_settings_source;
package_settings_source << cpack_dmg_ds_store;
std::ostringstream package_settings_destination;
package_settings_destination << staging.str() << "/.DS_Store";
if(!this->CopyFile(package_settings_source, package_settings_destination))
{
if (!this->CopyFile(package_settings_source,
package_settings_destination)) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error copying disk volume settings file. "
"Error copying disk volume settings file. "
"Check the value of CPACK_DMG_DS_STORE."
<< std::endl);
<< std::endl);
return 0;
}
}
}
// Optionally add a custom background image ...
// Make sure the background file type is the same as the custom image
// and that the file is hidden so it doesn't show up.
if(!cpack_dmg_background_image.empty())
{
if (!cpack_dmg_background_image.empty()) {
const std::string extension =
cmSystemTools::GetFilenameLastExtension(cpack_dmg_background_image);
cmSystemTools::GetFilenameLastExtension(cpack_dmg_background_image);
std::ostringstream package_background_source;
package_background_source << cpack_dmg_background_image;
@@ -425,36 +380,32 @@ int cmCPackDragNDropGenerator::CreateDMG(const std::string& src_dir,
package_background_destination << staging.str()
<< "/.background/background" << extension;
if(!this->CopyFile(package_background_source,
package_background_destination))
{
if (!this->CopyFile(package_background_source,
package_background_destination)) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error copying disk volume background image. "
"Error copying disk volume background image. "
"Check the value of CPACK_DMG_BACKGROUND_IMAGE."
<< std::endl);
<< std::endl);
return 0;
}
}
}
bool remount_image = !cpack_package_icon.empty() ||
!cpack_dmg_ds_store_setup_script.empty();
bool remount_image =
!cpack_package_icon.empty() || !cpack_dmg_ds_store_setup_script.empty();
// Create 1 MB dummy padding file in staging area when we need to remount
// image, so we have enough space for storing changes ...
if(remount_image)
{
if (remount_image) {
std::ostringstream dummy_padding;
dummy_padding << staging.str() << "/.dummy-padding-file";
if(!this->CreateEmptyFile(dummy_padding, 1048576))
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error creating dummy padding file."
<< std::endl);
if (!this->CreateEmptyFile(dummy_padding, 1048576)) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Error creating dummy padding file."
<< std::endl);
return 0;
}
}
}
// Create a temporary read-write disk image ...
std::string temp_image = this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
@@ -465,22 +416,18 @@ int cmCPackDragNDropGenerator::CreateDMG(const std::string& src_dir,
temp_image_command << " create";
temp_image_command << " -ov";
temp_image_command << " -srcfolder \"" << staging.str() << "\"";
temp_image_command << " -volname \""
<< cpack_dmg_volume_name << "\"";
temp_image_command << " -volname \"" << cpack_dmg_volume_name << "\"";
temp_image_command << " -format UDRW";
temp_image_command << " \"" << temp_image << "\"";
if(!this->RunCommand(temp_image_command))
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error generating temporary disk image."
<< std::endl);
if (!this->RunCommand(temp_image_command)) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error generating temporary disk image." << std::endl);
return 0;
}
}
if(remount_image)
{
if (remount_image) {
// Store that we have a failure so that we always unmount the image
// before we exit.
bool had_error = false;
@@ -491,14 +438,12 @@ int cmCPackDragNDropGenerator::CreateDMG(const std::string& src_dir,
attach_command << " \"" << temp_image << "\"";
std::string attach_output;
if(!this->RunCommand(attach_command, &attach_output))
{
if (!this->RunCommand(attach_command, &attach_output)) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error attaching temporary disk image."
<< std::endl);
"Error attaching temporary disk image." << std::endl);
return 0;
}
}
cmsys::RegularExpression mountpoint_regex(".*(/Volumes/[^\n]+)\n.*");
mountpoint_regex.find(attach_output.c_str());
@@ -508,95 +453,81 @@ int cmCPackDragNDropGenerator::CreateDMG(const std::string& src_dir,
// Remove dummy padding file so we have enough space on RW image ...
std::ostringstream dummy_padding;
dummy_padding << temp_mount.str() << "/.dummy-padding-file";
if(!cmSystemTools::RemoveFile(dummy_padding.str()))
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error removing dummy padding file."
<< std::endl);
if (!cmSystemTools::RemoveFile(dummy_padding.str())) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Error removing dummy padding file."
<< std::endl);
had_error = true;
}
}
// Optionally set the custom icon flag for the image ...
if(!had_error && !cpack_package_icon.empty())
{
if (!had_error && !cpack_package_icon.empty()) {
std::ostringstream setfile_command;
setfile_command << this->GetOption("CPACK_COMMAND_SETFILE");
setfile_command << " -a C";
setfile_command << " \"" << temp_mount.str() << "\"";
if(!this->RunCommand(setfile_command))
{
if (!this->RunCommand(setfile_command)) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error assigning custom icon to temporary disk image."
<< std::endl);
"Error assigning custom icon to temporary disk image."
<< std::endl);
had_error = true;
}
}
}
// Optionally we can execute a custom apple script to generate
// the .DS_Store for the volume folder ...
if(!had_error && !cpack_dmg_ds_store_setup_script.empty())
{
if (!had_error && !cpack_dmg_ds_store_setup_script.empty()) {
std::ostringstream setup_script_command;
setup_script_command << "osascript"
<< " \"" << cpack_dmg_ds_store_setup_script << "\""
<< " \"" << cpack_dmg_volume_name << "\"";
std::string error;
if(!this->RunCommand(setup_script_command, &error))
{
if (!this->RunCommand(setup_script_command, &error)) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error executing custom script on disk image." << std::endl
<< error
<< std::endl);
"Error executing custom script on disk image."
<< std::endl
<< error << std::endl);
had_error = true;
}
}
}
std::ostringstream detach_command;
detach_command << this->GetOption("CPACK_COMMAND_HDIUTIL");
detach_command << " detach";
detach_command << " \"" << temp_mount.str() << "\"";
if(!this->RunCommand(detach_command))
{
if (!this->RunCommand(detach_command)) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error detaching temporary disk image."
<< std::endl);
"Error detaching temporary disk image." << std::endl);
return 0;
}
if(had_error)
{
return 0;
}
}
if(!cpack_license_file.empty() || !slaDirectory.empty())
{
if (had_error) {
return 0;
}
}
if (!cpack_license_file.empty() || !slaDirectory.empty()) {
// Use old hardcoded style if sla_dir is not set
bool oldStyle = slaDirectory.empty();
std::string sla_r = this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
sla_r += "/sla.r";
std::vector<std::string> languages;
if(!oldStyle)
{
if (!oldStyle) {
cmSystemTools::ExpandListArgument(cpack_dmg_languages, languages);
}
}
cmGeneratedFileStream ofs(sla_r.c_str());
ofs << "#include <CoreServices/CoreServices.r>\n\n";
if(oldStyle)
{
if (oldStyle) {
ofs << SLAHeader;
ofs << "\n";
}
else
{
} else {
/*
* LPic Layout
* (https://github.com/pypt/dmg-add-license/blob/master/main.c)
@@ -619,111 +550,92 @@ int cmCPackDragNDropGenerator::CreateDMG(const std::string& src_dir,
std::vector<uint16_t> header_data;
header_data.push_back(0);
header_data.push_back(languages.size());
for(size_t i = 0; i < languages.size(); ++i)
{
for (size_t i = 0; i < languages.size(); ++i) {
CFStringRef language_cfstring = CFStringCreateWithCString(
NULL, languages[i].c_str(), kCFStringEncodingUTF8);
CFStringRef iso_language =
CFLocaleCreateCanonicalLanguageIdentifierFromString(
NULL, language_cfstring);
if (!iso_language)
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
languages[i] << " is not a recognized language"
<< std::endl);
}
char *iso_language_cstr = (char *) malloc(65);
if (!iso_language) {
cmCPackLogger(cmCPackLog::LOG_ERROR, languages[i]
<< " is not a recognized language" << std::endl);
}
char* iso_language_cstr = (char*)malloc(65);
CFStringGetCString(iso_language, iso_language_cstr, 64,
kCFStringEncodingMacRoman);
LangCode lang = 0;
RegionCode region = 0;
#ifdef HAVE_CoreServices
OSStatus err = LocaleStringToLangAndRegionCodes(iso_language_cstr,
&lang, &region);
OSStatus err =
LocaleStringToLangAndRegionCodes(iso_language_cstr, &lang, &region);
if (err != noErr)
#endif
{
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"No language/region code available for " << iso_language_cstr
<< std::endl);
"No language/region code available for "
<< iso_language_cstr << std::endl);
free(iso_language_cstr);
return 0;
}
}
#ifdef HAVE_CoreServices
free(iso_language_cstr);
header_data.push_back(region);
header_data.push_back(i);
header_data.push_back(0);
#endif
}
}
ofs << "data 'LPic' (5000) {\n";
ofs << std::hex << std::uppercase << std::setfill('0');
for(size_t i = 0; i < header_data.size(); ++i)
{
if(i % 8 == 0)
{
for (size_t i = 0; i < header_data.size(); ++i) {
if (i % 8 == 0) {
ofs << " $\"";
}
}
ofs << std::setw(4) << header_data[i];
if(i % 8 == 7 || i == header_data.size() - 1)
{
if (i % 8 == 7 || i == header_data.size() - 1) {
ofs << "\"\n";
}
else
{
} else {
ofs << " ";
}
}
}
ofs << "};\n\n";
// Reset ofs options
ofs << std::dec << std::nouppercase << std::setfill(' ');
}
}
bool have_write_license_error = false;
std::string error;
if(oldStyle)
{
if(!this->WriteLicense(ofs, 0, "", cpack_license_file, &error))
{
if (oldStyle) {
if (!this->WriteLicense(ofs, 0, "", cpack_license_file, &error)) {
have_write_license_error = true;
}
}
else
{
for(size_t i = 0; i < languages.size() && !have_write_license_error; ++i)
{
if(singleLicense)
{
if(!this->WriteLicense(ofs, i + 5000, languages[i],
cpack_license_file, &error))
{
} else {
for (size_t i = 0; i < languages.size() && !have_write_license_error;
++i) {
if (singleLicense) {
if (!this->WriteLicense(ofs, i + 5000, languages[i],
cpack_license_file, &error)) {
have_write_license_error = true;
}
}
else
{
if(!this->WriteLicense(ofs, i + 5000, languages[i], "", &error))
{
} else {
if (!this->WriteLicense(ofs, i + 5000, languages[i], "", &error)) {
have_write_license_error = true;
}
}
}
}
}
ofs.Close();
if(have_write_license_error)
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error writing license file to SLA." << std::endl
<< error
<< std::endl);
if (have_write_license_error) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Error writing license file to SLA."
<< std::endl
<< error << std::endl);
return 0;
}
}
// convert to UDCO
std::string temp_udco = this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
@@ -735,14 +647,13 @@ int cmCPackDragNDropGenerator::CreateDMG(const std::string& src_dir,
udco_image_command << " -format UDCO";
udco_image_command << " -ov -o \"" << temp_udco << "\"";
if(!this->RunCommand(udco_image_command, &error))
{
if (!this->RunCommand(udco_image_command, &error)) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error converting to UDCO dmg for adding SLA." << std::endl
<< error
<< std::endl);
"Error converting to UDCO dmg for adding SLA."
<< std::endl
<< error << std::endl);
return 0;
}
}
// unflatten dmg
std::ostringstream unflatten_command;
@@ -750,35 +661,31 @@ int cmCPackDragNDropGenerator::CreateDMG(const std::string& src_dir,
unflatten_command << " unflatten ";
unflatten_command << "\"" << temp_udco << "\"";
if(!this->RunCommand(unflatten_command, &error))
{
if (!this->RunCommand(unflatten_command, &error)) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error unflattening dmg for adding SLA." << std::endl
<< error
<< std::endl);
"Error unflattening dmg for adding SLA." << std::endl
<< error
<< std::endl);
return 0;
}
}
// Rez the SLA
std::ostringstream embed_sla_command;
embed_sla_command << this->GetOption("CPACK_COMMAND_REZ");
const char* sysroot = this->GetOption("CPACK_OSX_SYSROOT");
if(sysroot && sysroot[0] != '\0')
{
if (sysroot && sysroot[0] != '\0') {
embed_sla_command << " -isysroot \"" << sysroot << "\"";
}
}
embed_sla_command << " \"" << sla_r << "\"";
embed_sla_command << " -a -o ";
embed_sla_command << "\"" << temp_udco << "\"";
if(!this->RunCommand(embed_sla_command, &error))
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error adding SLA." << std::endl
<< error
<< std::endl);
if (!this->RunCommand(embed_sla_command, &error)) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Error adding SLA." << std::endl
<< error
<< std::endl);
return 0;
}
}
// flatten dmg
std::ostringstream flatten_command;
@@ -786,18 +693,16 @@ int cmCPackDragNDropGenerator::CreateDMG(const std::string& src_dir,
flatten_command << " flatten ";
flatten_command << "\"" << temp_udco << "\"";
if(!this->RunCommand(flatten_command, &error))
{
if (!this->RunCommand(flatten_command, &error)) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error flattening dmg for adding SLA." << std::endl
<< error
<< std::endl);
"Error flattening dmg for adding SLA." << std::endl
<< error
<< std::endl);
return 0;
}
temp_image = temp_udco;
}
temp_image = temp_udco;
}
// Create the final compressed read-only disk image ...
std::ostringstream final_image_command;
@@ -809,14 +714,12 @@ int cmCPackDragNDropGenerator::CreateDMG(const std::string& src_dir,
final_image_command << " zlib-level=9";
final_image_command << " -o \"" << output_file << "\"";
if(!this->RunCommand(final_image_command))
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error compressing disk image."
<< std::endl);
if (!this->RunCommand(final_image_command)) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Error compressing disk image."
<< std::endl);
return 0;
}
}
return 1;
}
@@ -826,9 +729,8 @@ bool cmCPackDragNDropGenerator::SupportsComponentInstallation() const
return true;
}
std::string
cmCPackDragNDropGenerator::GetComponentInstallDirNameSuffix(
const std::string& componentName)
std::string cmCPackDragNDropGenerator::GetComponentInstallDirNameSuffix(
const std::string& componentName)
{
// we want to group components together that go in the same dmg package
std::string package_file_name = this->GetOption("CPACK_PACKAGE_FILE_NAME");
@@ -840,179 +742,153 @@ cmCPackDragNDropGenerator::GetComponentInstallDirNameSuffix(
// 3. ignore groups - if grouping is defined, it is ignored
// and each component goes in its own package
if(this->componentPackageMethod == ONE_PACKAGE)
{
if (this->componentPackageMethod == ONE_PACKAGE) {
return "ALL_IN_ONE";
}
}
if(this->componentPackageMethod == ONE_PACKAGE_PER_GROUP)
{
if (this->componentPackageMethod == ONE_PACKAGE_PER_GROUP) {
// We have to find the name of the COMPONENT GROUP
// the current COMPONENT belongs to.
std::string groupVar = "CPACK_COMPONENT_" +
cmSystemTools::UpperCase(componentName) + "_GROUP";
std::string groupVar =
"CPACK_COMPONENT_" + cmSystemTools::UpperCase(componentName) + "_GROUP";
const char* _groupName = GetOption(groupVar.c_str());
if (_groupName)
{
if (_groupName) {
std::string groupName = _groupName;
groupName = GetComponentPackageFileName(package_file_name,
groupName, true);
groupName =
GetComponentPackageFileName(package_file_name, groupName, true);
return groupName;
}
}
}
return GetComponentPackageFileName(package_file_name, componentName, false);
}
bool
cmCPackDragNDropGenerator::WriteLicense(cmGeneratedFileStream& outputStream,
int licenseNumber, std::string licenseLanguage, std::string licenseFile,
std::string *error)
bool cmCPackDragNDropGenerator::WriteLicense(
cmGeneratedFileStream& outputStream, int licenseNumber,
std::string licenseLanguage, std::string licenseFile, std::string* error)
{
if(!licenseFile.empty() && !singleLicense)
{
if (!licenseFile.empty() && !singleLicense) {
licenseNumber = 5002;
licenseLanguage = "English";
}
}
// License header
outputStream << "data 'TEXT' (" << licenseNumber << ", \""
<< licenseLanguage << "\") {\n";
outputStream << "data 'TEXT' (" << licenseNumber << ", \"" << licenseLanguage
<< "\") {\n";
// License body
std::string actual_license = !licenseFile.empty() ? licenseFile :
(slaDirectory + "/" + licenseLanguage + ".license.txt");
std::string actual_license = !licenseFile.empty()
? licenseFile
: (slaDirectory + "/" + licenseLanguage + ".license.txt");
cmsys::ifstream license_ifs;
license_ifs.open(actual_license.c_str());
if(license_ifs.is_open())
{
while(license_ifs.good())
{
if (license_ifs.is_open()) {
while (license_ifs.good()) {
std::string line;
std::getline(license_ifs, line);
if(!line.empty())
{
if (!line.empty()) {
EscapeQuotesAndBackslashes(line);
std::vector<std::string> lines;
if(!this->BreakLongLine(line, lines, error))
{
if (!this->BreakLongLine(line, lines, error)) {
return false;
}
for(size_t i = 0; i < lines.size(); ++i)
{
outputStream << " \"" << lines[i] << "\"\n";
}
}
outputStream << " \"\\n\"\n";
for (size_t i = 0; i < lines.size(); ++i) {
outputStream << " \"" << lines[i] << "\"\n";
}
}
license_ifs.close();
outputStream << " \"\\n\"\n";
}
license_ifs.close();
}
// End of License
outputStream << "};\n\n";
if(!licenseFile.empty() && !singleLicense)
{
if (!licenseFile.empty() && !singleLicense) {
outputStream << SLASTREnglish;
}
else
{
} else {
// Menu header
outputStream << "resource 'STR#' (" << licenseNumber << ", \""
<< licenseLanguage << "\") {\n";
<< licenseLanguage << "\") {\n";
outputStream << " {\n";
// Menu body
cmsys::ifstream menu_ifs;
menu_ifs.open((slaDirectory+"/"+licenseLanguage+".menu.txt").c_str());
if(menu_ifs.is_open())
{
menu_ifs.open(
(slaDirectory + "/" + licenseLanguage + ".menu.txt").c_str());
if (menu_ifs.is_open()) {
size_t lines_written = 0;
while(menu_ifs.good())
{
while (menu_ifs.good()) {
// Lines written from original file, not from broken up lines
std::string line;
std::getline(menu_ifs, line);
if(!line.empty())
{
if (!line.empty()) {
EscapeQuotesAndBackslashes(line);
std::vector<std::string> lines;
if(!this->BreakLongLine(line, lines, error))
{
if (!this->BreakLongLine(line, lines, error)) {
return false;
}
for(size_t i = 0; i < lines.size(); ++i)
{
}
for (size_t i = 0; i < lines.size(); ++i) {
std::string comma;
// We need a comma after every complete string,
// but not on the very last line
if(lines_written != 8 && i == lines.size() - 1)
{
if (lines_written != 8 && i == lines.size() - 1) {
comma = ",";
}
else
{
} else {
comma = "";
}
outputStream << " \"" << lines[i] << "\"" << comma << "\n";
}
++lines_written;
outputStream << " \"" << lines[i] << "\"" << comma << "\n";
}
++lines_written;
}
menu_ifs.close();
}
menu_ifs.close();
}
//End of menu
// End of menu
outputStream << " }\n";
outputStream << "};\n";
outputStream << "\n";
}
}
return true;
}
bool
cmCPackDragNDropGenerator::BreakLongLine(const std::string& line,
std::vector<std::string>& lines, std::string *error)
bool cmCPackDragNDropGenerator::BreakLongLine(const std::string& line,
std::vector<std::string>& lines,
std::string* error)
{
const size_t max_line_length = 512;
for(size_t i = 0; i < line.size(); i += max_line_length)
{
for (size_t i = 0; i < line.size(); i += max_line_length) {
size_t line_length = max_line_length;
if(i + line_length > line.size())
{
if (i + line_length > line.size()) {
line_length = line.size() - i;
}
else while(line_length > 0 && line[i + line_length - 1] != ' ')
{
line_length = line_length - 1;
} else
while (line_length > 0 && line[i + line_length - 1] != ' ') {
line_length = line_length - 1;
}
if(line_length == 0)
{
if (line_length == 0) {
*error = "Please make sure there are no words "
"(or character sequences not broken up by spaces or newlines) "
"in your license file which are more than 512 characters long.";
return false;
}
lines.push_back(line.substr(i, line_length));
}
lines.push_back(line.substr(i, line_length));
}
return true;
}
void
cmCPackDragNDropGenerator::EscapeQuotesAndBackslashes(std::string& line)
void cmCPackDragNDropGenerator::EscapeQuotesAndBackslashes(std::string& line)
{
std::string::size_type backslash_pos = line.find('\\');
while(backslash_pos != std::string::npos)
{
while (backslash_pos != std::string::npos) {
line.replace(backslash_pos, 1, "\\\\");
backslash_pos = line.find('\\', backslash_pos + 2);
}
}
std::string::size_type quote_pos = line.find('\"');
while(quote_pos != std::string::npos)
{
while (quote_pos != std::string::npos) {
line.replace(quote_pos, 1, "\\\"");
quote_pos = line.find('\"', quote_pos + 2);
}
}
}
+6 -8
View File
@@ -34,13 +34,12 @@ protected:
int PackageFiles();
bool SupportsComponentInstallation() const;
bool CopyFile(std::ostringstream& source, std::ostringstream& target);
bool CreateEmptyFile(std::ostringstream& target, size_t size);
bool RunCommand(std::ostringstream& command, std::string* output = 0);
std::string
GetComponentInstallDirNameSuffix(const std::string& componentName);
std::string GetComponentInstallDirNameSuffix(
const std::string& componentName);
int CreateDMG(const std::string& src_dir, const std::string& output_file);
@@ -51,11 +50,10 @@ private:
bool singleLicense;
bool WriteLicense(cmGeneratedFileStream& outputStream, int licenseNumber,
std::string licenseLanguage, std::string licenseFile,
std::string *error);
bool BreakLongLine(const std::string& line,
std::vector<std::string>& lines,
std::string *error);
std::string licenseLanguage, std::string licenseFile,
std::string* error);
bool BreakLongLine(const std::string& line, std::vector<std::string>& lines,
std::string* error);
void EscapeQuotesAndBackslashes(std::string& line);
};
+584 -809
View File
@@ -44,14 +44,13 @@ cmCPackGenerator::~cmCPackGenerator()
this->MakefileMap = 0;
}
void cmCPackGeneratorProgress(const char *msg, float prog, void* ptr)
void cmCPackGeneratorProgress(const char* msg, float prog, void* ptr)
{
cmCPackGenerator* self = static_cast<cmCPackGenerator*>(ptr);
self->DisplayVerboseOutput(msg, prog);
}
void cmCPackGenerator::DisplayVerboseOutput(const char* msg,
float progress)
void cmCPackGenerator::DisplayVerboseOutput(const char* msg, float progress)
{
(void)progress;
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "" << msg << std::endl);
@@ -59,63 +58,52 @@ void cmCPackGenerator::DisplayVerboseOutput(const char* msg,
int cmCPackGenerator::PrepareNames()
{
cmCPackLogger(cmCPackLog::LOG_DEBUG,
"Create temp directory." << std::endl);
cmCPackLogger(cmCPackLog::LOG_DEBUG, "Create temp directory." << std::endl);
// checks CPACK_SET_DESTDIR support
if (IsOn("CPACK_SET_DESTDIR"))
{
if (SETDESTDIR_UNSUPPORTED==SupportsSetDestdir())
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"CPACK_SET_DESTDIR is set to ON but the '"
<< Name << "' generator does NOT support it."
<< std::endl);
return 0;
}
else if (SETDESTDIR_SHOULD_NOT_BE_USED==SupportsSetDestdir())
{
cmCPackLogger(cmCPackLog::LOG_WARNING,
"CPACK_SET_DESTDIR is set to ON but it is "
<< "usually a bad idea to do that with '"
<< Name << "' generator. Use at your own risk."
<< std::endl);
}
if (IsOn("CPACK_SET_DESTDIR")) {
if (SETDESTDIR_UNSUPPORTED == SupportsSetDestdir()) {
cmCPackLogger(
cmCPackLog::LOG_ERROR, "CPACK_SET_DESTDIR is set to ON but the '"
<< Name << "' generator does NOT support it." << std::endl);
return 0;
} else if (SETDESTDIR_SHOULD_NOT_BE_USED == SupportsSetDestdir()) {
cmCPackLogger(cmCPackLog::LOG_WARNING,
"CPACK_SET_DESTDIR is set to ON but it is "
<< "usually a bad idea to do that with '" << Name
<< "' generator. Use at your own risk." << std::endl);
}
}
std::string tempDirectory = this->GetOption("CPACK_PACKAGE_DIRECTORY");
tempDirectory += "/_CPack_Packages/";
const char* toplevelTag = this->GetOption("CPACK_TOPLEVEL_TAG");
if ( toplevelTag )
{
if (toplevelTag) {
tempDirectory += toplevelTag;
tempDirectory += "/";
}
}
tempDirectory += this->GetOption("CPACK_GENERATOR");
std::string topDirectory = tempDirectory;
const char* pfname = this->GetOption("CPACK_PACKAGE_FILE_NAME");
if(!pfname)
{
if (!pfname) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"CPACK_PACKAGE_FILE_NAME not specified" << std::endl);
return 0;
}
}
std::string outName = pfname;
tempDirectory += "/" + outName;
if(!this->GetOutputExtension())
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"No output extension specified" << std::endl);
if (!this->GetOutputExtension()) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "No output extension specified"
<< std::endl);
return 0;
}
}
outName += this->GetOutputExtension();
const char* pdir = this->GetOption("CPACK_PACKAGE_DIRECTORY");
if(!pdir)
{
if (!pdir) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"CPACK_PACKAGE_DIRECTORY not specified" << std::endl);
return 0;
}
}
std::string destFile = pdir;
this->SetOptionIfNotSet("CPACK_OUTPUT_FILE_PREFIX", destFile.c_str());
@@ -128,52 +116,49 @@ int cmCPackGenerator::PrepareNames()
this->SetOptionIfNotSet("CPACK_TEMPORARY_PACKAGE_FILE_NAME",
outFile.c_str());
this->SetOptionIfNotSet("CPACK_INSTALL_DIRECTORY", this->GetInstallPath());
this->SetOptionIfNotSet("CPACK_NATIVE_INSTALL_DIRECTORY",
this->SetOptionIfNotSet(
"CPACK_NATIVE_INSTALL_DIRECTORY",
cmsys::SystemTools::ConvertToOutputPath(this->GetInstallPath()).c_str());
this->SetOptionIfNotSet("CPACK_TEMPORARY_INSTALL_DIRECTORY",
tempDirectory.c_str());
cmCPackLogger(cmCPackLog::LOG_DEBUG,
"Look for: CPACK_PACKAGE_DESCRIPTION_FILE" << std::endl);
const char* descFileName
= this->GetOption("CPACK_PACKAGE_DESCRIPTION_FILE");
if ( descFileName )
{
cmCPackLogger(cmCPackLog::LOG_DEBUG,
"Look for: " << descFileName << std::endl);
if ( !cmSystemTools::FileExists(descFileName) )
{
"Look for: CPACK_PACKAGE_DESCRIPTION_FILE" << std::endl);
const char* descFileName = this->GetOption("CPACK_PACKAGE_DESCRIPTION_FILE");
if (descFileName) {
cmCPackLogger(cmCPackLog::LOG_DEBUG, "Look for: " << descFileName
<< std::endl);
if (!cmSystemTools::FileExists(descFileName)) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Cannot find description file name: ["
<< descFileName << "]" << std::endl);
<< descFileName << "]" << std::endl);
return 0;
}
}
cmsys::ifstream ifs(descFileName);
if ( !ifs )
{
if (!ifs) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Cannot open description file name: " << descFileName << std::endl);
"Cannot open description file name: " << descFileName
<< std::endl);
return 0;
}
}
std::ostringstream ostr;
std::string line;
cmCPackLogger(cmCPackLog::LOG_VERBOSE,
"Read description file: " << descFileName << std::endl);
while ( ifs && cmSystemTools::GetLineFromStream(ifs, line) )
{
"Read description file: " << descFileName << std::endl);
while (ifs && cmSystemTools::GetLineFromStream(ifs, line)) {
ostr << cmXMLSafe(line) << std::endl;
}
this->SetOptionIfNotSet("CPACK_PACKAGE_DESCRIPTION", ostr.str().c_str());
}
if ( !this->GetOption("CPACK_PACKAGE_DESCRIPTION") )
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
this->SetOptionIfNotSet("CPACK_PACKAGE_DESCRIPTION", ostr.str().c_str());
}
if (!this->GetOption("CPACK_PACKAGE_DESCRIPTION")) {
cmCPackLogger(
cmCPackLog::LOG_ERROR,
"Project description not specified. Please specify "
"CPACK_PACKAGE_DESCRIPTION or CPACK_PACKAGE_DESCRIPTION_FILE."
<< std::endl);
<< std::endl);
return 0;
}
}
this->SetOptionIfNotSet("CPACK_REMOVE_TOPLEVEL_DIRECTORY", "1");
@@ -185,78 +170,66 @@ int cmCPackGenerator::InstallProject()
cmCPackLogger(cmCPackLog::LOG_OUTPUT, "Install projects" << std::endl);
this->CleanTemporaryDirectory();
std::string bareTempInstallDirectory
= this->GetOption("CPACK_TEMPORARY_INSTALL_DIRECTORY");
std::string bareTempInstallDirectory =
this->GetOption("CPACK_TEMPORARY_INSTALL_DIRECTORY");
std::string tempInstallDirectoryStr = bareTempInstallDirectory;
bool setDestDir = cmSystemTools::IsOn(this->GetOption("CPACK_SET_DESTDIR"))
| cmSystemTools::IsInternallyOn(
this->GetOption("CPACK_SET_DESTDIR"));
if (!setDestDir)
{
bool setDestDir = cmSystemTools::IsOn(this->GetOption("CPACK_SET_DESTDIR")) |
cmSystemTools::IsInternallyOn(this->GetOption("CPACK_SET_DESTDIR"));
if (!setDestDir) {
tempInstallDirectoryStr += this->GetPackagingInstallPrefix();
}
}
const char* tempInstallDirectory = tempInstallDirectoryStr.c_str();
int res = 1;
if ( !cmsys::SystemTools::MakeDirectory(bareTempInstallDirectory.c_str()))
{
if (!cmsys::SystemTools::MakeDirectory(bareTempInstallDirectory.c_str())) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Problem creating temporary directory: "
<< (tempInstallDirectory ? tempInstallDirectory : "(NULL)")
<< std::endl);
"Problem creating temporary directory: "
<< (tempInstallDirectory ? tempInstallDirectory : "(NULL)")
<< std::endl);
return 0;
}
}
if ( setDestDir )
{
if (setDestDir) {
std::string destDir = "DESTDIR=";
destDir += tempInstallDirectory;
cmSystemTools::PutEnv(destDir);
}
else
{
} else {
// Make sure there is no destdir
cmSystemTools::PutEnv("DESTDIR=");
}
}
// If the CPackConfig file sets CPACK_INSTALL_COMMANDS then run them
// as listed
if ( !this->InstallProjectViaInstallCommands(
setDestDir, tempInstallDirectory) )
{
if (!this->InstallProjectViaInstallCommands(setDestDir,
tempInstallDirectory)) {
return 0;
}
}
// If the CPackConfig file sets CPACK_INSTALL_SCRIPT then run them
// as listed
if ( !this->InstallProjectViaInstallScript(
setDestDir, tempInstallDirectory) )
{
if (!this->InstallProjectViaInstallScript(setDestDir,
tempInstallDirectory)) {
return 0;
}
}
// If the CPackConfig file sets CPACK_INSTALLED_DIRECTORIES
// then glob it and copy it to CPACK_TEMPORARY_DIRECTORY
// This is used in Source packaging
if ( !this->InstallProjectViaInstalledDirectories(
setDestDir, tempInstallDirectory) )
{
if (!this->InstallProjectViaInstalledDirectories(setDestDir,
tempInstallDirectory)) {
return 0;
}
}
// If the project is a CMAKE project then run pre-install
// and then read the cmake_install script to run it
if ( !this->InstallProjectViaInstallCMakeProjects(
setDestDir, bareTempInstallDirectory) )
{
if (!this->InstallProjectViaInstallCMakeProjects(setDestDir,
bareTempInstallDirectory)) {
return 0;
}
}
if ( setDestDir )
{
if (setDestDir) {
cmSystemTools::PutEnv("DESTDIR=");
}
}
return res;
}
@@ -264,43 +237,37 @@ int cmCPackGenerator::InstallProject()
int cmCPackGenerator::InstallProjectViaInstallCommands(
bool setDestDir, const std::string& tempInstallDirectory)
{
(void) setDestDir;
(void)setDestDir;
const char* installCommands = this->GetOption("CPACK_INSTALL_COMMANDS");
if ( installCommands && *installCommands )
{
if (installCommands && *installCommands) {
std::string tempInstallDirectoryEnv = "CMAKE_INSTALL_PREFIX=";
tempInstallDirectoryEnv += tempInstallDirectory;
cmSystemTools::PutEnv(tempInstallDirectoryEnv);
std::vector<std::string> installCommandsVector;
cmSystemTools::ExpandListArgument(installCommands,installCommandsVector);
cmSystemTools::ExpandListArgument(installCommands, installCommandsVector);
std::vector<std::string>::iterator it;
for ( it = installCommandsVector.begin();
it != installCommandsVector.end();
++it )
{
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Execute: " << *it
<< std::endl);
for (it = installCommandsVector.begin(); it != installCommandsVector.end();
++it) {
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Execute: " << *it << std::endl);
std::string output;
int retVal = 1;
bool resB = cmSystemTools::RunSingleCommand(
it->c_str(), &output, &output,
&retVal, 0, this->GeneratorVerbose, 0);
if ( !resB || retVal )
{
it->c_str(), &output, &output, &retVal, 0, this->GeneratorVerbose, 0);
if (!resB || retVal) {
std::string tmpFile = this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
tmpFile += "/InstallOutput.log";
cmGeneratedFileStream ofs(tmpFile.c_str());
ofs << "# Run command: " << *it << std::endl
<< "# Output:" << std::endl
<< output << std::endl;
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Problem running install command: " << *it << std::endl
<< "Please check " << tmpFile << " for errors"
<< std::endl);
<< "# Output:" << std::endl
<< output << std::endl;
cmCPackLogger(
cmCPackLog::LOG_ERROR, "Problem running install command: "
<< *it << std::endl
<< "Please check " << tmpFile << " for errors" << std::endl);
return 0;
}
}
}
}
return 1;
}
@@ -311,265 +278,230 @@ int cmCPackGenerator::InstallProjectViaInstalledDirectories(
(void)tempInstallDirectory;
std::vector<cmsys::RegularExpression> ignoreFilesRegex;
const char* cpackIgnoreFiles = this->GetOption("CPACK_IGNORE_FILES");
if ( cpackIgnoreFiles )
{
if (cpackIgnoreFiles) {
std::vector<std::string> ignoreFilesRegexString;
cmSystemTools::ExpandListArgument(cpackIgnoreFiles,
ignoreFilesRegexString);
std::vector<std::string>::iterator it;
for ( it = ignoreFilesRegexString.begin();
it != ignoreFilesRegexString.end();
++it )
{
for (it = ignoreFilesRegexString.begin();
it != ignoreFilesRegexString.end(); ++it) {
cmCPackLogger(cmCPackLog::LOG_VERBOSE,
"Create ignore files regex for: " << *it << std::endl);
"Create ignore files regex for: " << *it << std::endl);
ignoreFilesRegex.push_back(it->c_str());
}
}
const char* installDirectories
= this->GetOption("CPACK_INSTALLED_DIRECTORIES");
if ( installDirectories && *installDirectories )
{
}
const char* installDirectories =
this->GetOption("CPACK_INSTALLED_DIRECTORIES");
if (installDirectories && *installDirectories) {
std::vector<std::string> installDirectoriesVector;
cmSystemTools::ExpandListArgument(installDirectories,
installDirectoriesVector);
if ( installDirectoriesVector.size() % 2 != 0 )
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
installDirectoriesVector);
if (installDirectoriesVector.size() % 2 != 0) {
cmCPackLogger(
cmCPackLog::LOG_ERROR,
"CPACK_INSTALLED_DIRECTORIES should contain pairs of <directory> and "
"<subdirectory>. The <subdirectory> can be '.' to be installed in "
"the toplevel directory of installation." << std::endl);
"the toplevel directory of installation."
<< std::endl);
return 0;
}
}
std::vector<std::string>::iterator it;
const std::string& tempDir = tempInstallDirectory;
for ( it = installDirectoriesVector.begin();
it != installDirectoriesVector.end();
++it )
{
std::list<std::pair<std::string,std::string> > symlinkedFiles;
for (it = installDirectoriesVector.begin();
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 top = *it;
it ++;
it++;
std::string subdir = *it;
std::string findExpr = top;
findExpr += "/*";
cmCPackLogger(cmCPackLog::LOG_OUTPUT,
"- Install directory: " << top << std::endl);
"- Install directory: " << top << std::endl);
gl.RecurseOn();
gl.SetRecurseListDirs(true);
if ( !gl.FindFiles(findExpr) )
{
if (!gl.FindFiles(findExpr)) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Cannot find any files in the installed directory" << std::endl);
"Cannot find any files in the installed directory"
<< std::endl);
return 0;
}
}
files = gl.GetFiles();
std::vector<std::string>::iterator gfit;
std::vector<cmsys::RegularExpression>::iterator regIt;
for ( gfit = files.begin(); gfit != files.end(); ++ gfit )
{
for (gfit = files.begin(); gfit != files.end(); ++gfit) {
bool skip = false;
std::string inFile = *gfit;
if(cmSystemTools::FileIsDirectory(*gfit))
{
if (cmSystemTools::FileIsDirectory(*gfit)) {
inFile += '/';
}
for ( regIt= ignoreFilesRegex.begin();
regIt!= ignoreFilesRegex.end();
++ regIt)
{
if ( regIt->find(inFile.c_str()) )
{
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Ignore file: "
<< inFile << std::endl);
}
for (regIt = ignoreFilesRegex.begin(); regIt != ignoreFilesRegex.end();
++regIt) {
if (regIt->find(inFile.c_str())) {
cmCPackLogger(cmCPackLog::LOG_VERBOSE,
"Ignore file: " << inFile << std::endl);
skip = true;
}
}
if ( skip )
{
continue;
}
std::string filePath = tempDir;
filePath += "/" + subdir + "/"
+ cmSystemTools::RelativePath(top.c_str(), gfit->c_str());
cmCPackLogger(cmCPackLog::LOG_DEBUG, "Copy file: "
<< inFile << " -> " << filePath << std::endl);
/* If the file is a symlink we will have to re-create it */
if ( cmSystemTools::FileIsSymlink(inFile))
{
std::string targetFile;
std::string inFileRelative =
cmSystemTools::RelativePath(top.c_str(),inFile.c_str());
cmSystemTools::ReadSymlink(inFile,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())
&&
cmSystemTools::CopyFileTime(inFile.c_str(),filePath.c_str())
) )
{
cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem copying file: "
<< inFile << " -> " << filePath << std::endl);
return 0;
}
}
if (skip) {
continue;
}
std::string filePath = tempDir;
filePath += "/" + subdir + "/" +
cmSystemTools::RelativePath(top.c_str(), gfit->c_str());
cmCPackLogger(cmCPackLog::LOG_DEBUG, "Copy file: "
<< inFile << " -> " << filePath << std::endl);
/* If the file is a symlink we will have to re-create it */
if (cmSystemTools::FileIsSymlink(inFile)) {
std::string targetFile;
std::string inFileRelative =
cmSystemTools::RelativePath(top.c_str(), inFile.c_str());
cmSystemTools::ReadSymlink(inFile, 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()) &&
cmSystemTools::CopyFileTime(inFile.c_str(),
filePath.c_str()))) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem copying file: "
<< inFile << " -> " << filePath << std::endl);
return 0;
}
}
/* rebuild symlinks in the installed tree */
if (!symlinkedFiles.empty())
{
std::list< std::pair<std::string,std::string> >::iterator symlinkedIt;
if (!symlinkedFiles.empty()) {
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);
goToDir += "/" + subdir;
cmCPackLogger(cmCPackLog::LOG_DEBUG, "Change dir to: " << goToDir
<< std::endl);
cmSystemTools::ChangeDirectory(goToDir);
for (symlinkedIt=symlinkedFiles.begin();
symlinkedIt != symlinkedFiles.end();
++symlinkedIt)
{
for (symlinkedIt = symlinkedFiles.begin();
symlinkedIt != symlinkedFiles.end(); ++symlinkedIt) {
cmCPackLogger(cmCPackLog::LOG_DEBUG, "Will create a symlink: "
<< symlinkedIt->second << "--> "
<< symlinkedIt->first << std::endl);
<< symlinkedIt->second << "--> "
<< symlinkedIt->first << std::endl);
// make sure directory exists for symlink
std::string destDir =
cmSystemTools::GetFilenamePath(symlinkedIt->second);
if(!destDir.empty() && !cmSystemTools::MakeDirectory(destDir))
{
if (!destDir.empty() && !cmSystemTools::MakeDirectory(destDir)) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot create dir: "
<< destDir
<< "\nTrying to create symlink: "
<< symlinkedIt->second << "--> "
<< symlinkedIt->first
<< std::endl);
}
<< destDir << "\nTrying to create symlink: "
<< symlinkedIt->second << "--> "
<< symlinkedIt->first << std::endl);
}
if (!cmSystemTools::CreateSymlink(symlinkedIt->first,
symlinkedIt->second))
{
symlinkedIt->second)) {
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);
}
cmCPackLogger(cmCPackLog::LOG_DEBUG, "Going back to: " << curDir
<< std::endl);
cmSystemTools::ChangeDirectory(curDir);
}
}
}
return 1;
}
int cmCPackGenerator::InstallProjectViaInstallScript(
bool setDestDir, const std::string& tempInstallDirectory)
{
const char* cmakeScripts
= this->GetOption("CPACK_INSTALL_SCRIPT");
if ( cmakeScripts && *cmakeScripts )
{
cmCPackLogger(cmCPackLog::LOG_OUTPUT,
"- Install scripts: " << cmakeScripts << std::endl);
const char* cmakeScripts = this->GetOption("CPACK_INSTALL_SCRIPT");
if (cmakeScripts && *cmakeScripts) {
cmCPackLogger(cmCPackLog::LOG_OUTPUT, "- Install scripts: " << cmakeScripts
<< std::endl);
std::vector<std::string> cmakeScriptsVector;
cmSystemTools::ExpandListArgument(cmakeScripts,
cmakeScriptsVector);
cmSystemTools::ExpandListArgument(cmakeScripts, cmakeScriptsVector);
std::vector<std::string>::iterator it;
for ( it = cmakeScriptsVector.begin();
it != cmakeScriptsVector.end();
++it )
{
for (it = cmakeScriptsVector.begin(); it != cmakeScriptsVector.end();
++it) {
std::string installScript = *it;
cmCPackLogger(cmCPackLog::LOG_OUTPUT,
"- Install script: " << installScript << std::endl);
"- Install script: " << installScript << std::endl);
if ( setDestDir )
{
if (setDestDir) {
// For DESTDIR based packaging, use the *project* CMAKE_INSTALL_PREFIX
// 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;
if (this->GetOption("CPACK_INSTALL_PREFIX"))
{
if (this->GetOption("CPACK_INSTALL_PREFIX")) {
dir += this->GetOption("CPACK_INSTALL_PREFIX");
}
this->SetOption("CMAKE_INSTALL_PREFIX", dir.c_str());
cmCPackLogger(cmCPackLog::LOG_DEBUG,
"- Using DESTDIR + CPACK_INSTALL_PREFIX... (this->SetOption)"
<< std::endl);
cmCPackLogger(cmCPackLog::LOG_DEBUG,
"- Setting CMAKE_INSTALL_PREFIX to '" << dir << "'" << std::endl);
}
else
{
this->SetOption("CMAKE_INSTALL_PREFIX", dir.c_str());
cmCPackLogger(
cmCPackLog::LOG_DEBUG,
"- Using DESTDIR + CPACK_INSTALL_PREFIX... (this->SetOption)"
<< std::endl);
cmCPackLogger(cmCPackLog::LOG_DEBUG,
"- Setting CMAKE_INSTALL_PREFIX to '" << dir << "'"
<< std::endl);
} else {
this->SetOption("CMAKE_INSTALL_PREFIX", tempInstallDirectory.c_str());
cmCPackLogger(cmCPackLog::LOG_DEBUG,
"- Using non-DESTDIR install... (this->SetOption)" << std::endl);
"- Using non-DESTDIR install... (this->SetOption)"
<< std::endl);
cmCPackLogger(cmCPackLog::LOG_DEBUG,
"- Setting CMAKE_INSTALL_PREFIX to '" << tempInstallDirectory
<< "'" << std::endl);
}
"- Setting CMAKE_INSTALL_PREFIX to '"
<< tempInstallDirectory << "'" << std::endl);
}
this->SetOptionIfNotSet("CMAKE_CURRENT_BINARY_DIR",
tempInstallDirectory.c_str());
tempInstallDirectory.c_str());
this->SetOptionIfNotSet("CMAKE_CURRENT_SOURCE_DIR",
tempInstallDirectory.c_str());
tempInstallDirectory.c_str());
int res = this->MakefileMap->ReadListFile(installScript.c_str());
if ( cmSystemTools::GetErrorOccuredFlag() || !res )
{
if (cmSystemTools::GetErrorOccuredFlag() || !res) {
return 0;
}
}
}
}
return 1;
}
int cmCPackGenerator::InstallProjectViaInstallCMakeProjects(
bool setDestDir, const std::string& baseTempInstallDirectory)
{
const char* cmakeProjects
= this->GetOption("CPACK_INSTALL_CMAKE_PROJECTS");
const char* cmakeGenerator
= this->GetOption("CPACK_CMAKE_GENERATOR");
const char* cmakeProjects = this->GetOption("CPACK_INSTALL_CMAKE_PROJECTS");
const char* cmakeGenerator = this->GetOption("CPACK_CMAKE_GENERATOR");
std::string absoluteDestFiles;
if ( cmakeProjects && *cmakeProjects )
{
if ( !cmakeGenerator )
{
if (cmakeProjects && *cmakeProjects) {
if (!cmakeGenerator) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"CPACK_INSTALL_CMAKE_PROJECTS is specified, but "
"CPACK_CMAKE_GENERATOR is not. CPACK_CMAKE_GENERATOR "
"is required to install the project."
<< std::endl);
<< std::endl);
return 0;
}
}
std::vector<std::string> cmakeProjectsVector;
cmSystemTools::ExpandListArgument(cmakeProjects,
cmakeProjectsVector);
cmSystemTools::ExpandListArgument(cmakeProjects, cmakeProjectsVector);
std::vector<std::string>::iterator it;
for ( it = cmakeProjectsVector.begin();
it != cmakeProjectsVector.end();
++it )
{
if ( it+1 == cmakeProjectsVector.end() ||
it+2 == cmakeProjectsVector.end() ||
it+3 == cmakeProjectsVector.end() )
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
for (it = cmakeProjectsVector.begin(); it != cmakeProjectsVector.end();
++it) {
if (it + 1 == cmakeProjectsVector.end() ||
it + 2 == cmakeProjectsVector.end() ||
it + 3 == cmakeProjectsVector.end()) {
cmCPackLogger(
cmCPackLog::LOG_ERROR,
"Not enough items on list: CPACK_INSTALL_CMAKE_PROJECTS. "
"CPACK_INSTALL_CMAKE_PROJECTS should hold quadruplet of install "
"directory, install project name, install component, and install "
"subdirectory."
<< std::endl);
<< std::endl);
return 0;
}
}
std::string installDirectory = *it;
++it;
std::string installProjectName = *it;
@@ -589,60 +521,50 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects(
* (this works at CPack time too)
*/
if (this->SupportsComponentInstallation() &
!(this->IsOn("CPACK_MONOLITHIC_INSTALL")))
{
!(this->IsOn("CPACK_MONOLITHIC_INSTALL"))) {
// Determine the installation types for this project (if provided).
std::string installTypesVar = "CPACK_"
+ cmSystemTools::UpperCase(installComponent) + "_INSTALL_TYPES";
const char *installTypes = this->GetOption(installTypesVar);
if (installTypes && *installTypes)
{
std::string installTypesVar = "CPACK_" +
cmSystemTools::UpperCase(installComponent) + "_INSTALL_TYPES";
const char* installTypes = this->GetOption(installTypesVar);
if (installTypes && *installTypes) {
std::vector<std::string> installTypesVector;
cmSystemTools::ExpandListArgument(installTypes, installTypesVector);
std::vector<std::string>::iterator installTypeIt;
for (installTypeIt = installTypesVector.begin();
installTypeIt != installTypesVector.end();
++installTypeIt)
{
this->GetInstallationType(installProjectName,
*installTypeIt);
}
installTypeIt != installTypesVector.end(); ++installTypeIt) {
this->GetInstallationType(installProjectName, *installTypeIt);
}
}
// Determine the set of components that will be used in this project
std::string componentsVar
= "CPACK_COMPONENTS_" + cmSystemTools::UpperCase(installComponent);
const char *components = this->GetOption(componentsVar);
if (components && *components)
{
std::string componentsVar =
"CPACK_COMPONENTS_" + cmSystemTools::UpperCase(installComponent);
const char* components = this->GetOption(componentsVar);
if (components && *components) {
cmSystemTools::ExpandListArgument(components, componentsVector);
std::vector<std::string>::iterator compIt;
for (compIt = componentsVector.begin();
compIt != componentsVector.end();
++compIt)
{
compIt != componentsVector.end(); ++compIt) {
GetComponent(installProjectName, *compIt);
}
componentInstall = true;
}
componentInstall = true;
}
if (componentsVector.empty())
{
}
if (componentsVector.empty()) {
componentsVector.push_back(installComponent);
}
}
const char* buildConfigCstr = this->GetOption("CPACK_BUILD_CONFIG");
std::string buildConfig = buildConfigCstr ? buildConfigCstr : "";
cmGlobalGenerator* globalGenerator
= this->MakefileMap->GetCMakeInstance()->CreateGlobalGenerator(
cmGlobalGenerator* globalGenerator =
this->MakefileMap->GetCMakeInstance()->CreateGlobalGenerator(
cmakeGenerator);
if ( !globalGenerator )
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Specified package generator not found. "
"CPACK_CMAKE_GENERATOR value is invalid."
<< std::endl);
return 0;
if (!globalGenerator) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Specified package generator not found. "
"CPACK_CMAKE_GENERATOR value is invalid."
<< std::endl);
return 0;
}
// set the global flag for unix style paths on cmSystemTools as
// soon as the generator is set. This allows gmake to be used
@@ -650,59 +572,49 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects(
cmSystemTools::SetForceUnixPaths(globalGenerator->GetForceUnixPaths());
// Does this generator require pre-install?
if (const char* preinstall = globalGenerator->GetPreinstallTargetName())
{
std::string buildCommand =
globalGenerator->GenerateCMakeBuildCommand(
preinstall, buildConfig, "", false);
if (const char* preinstall =
globalGenerator->GetPreinstallTargetName()) {
std::string buildCommand = globalGenerator->GenerateCMakeBuildCommand(
preinstall, buildConfig, "", false);
cmCPackLogger(cmCPackLog::LOG_DEBUG,
"- Install command: " << buildCommand << std::endl);
cmCPackLogger(cmCPackLog::LOG_OUTPUT,
"- Run preinstall target for: " << installProjectName << std::endl);
"- Install command: " << buildCommand << std::endl);
cmCPackLogger(cmCPackLog::LOG_OUTPUT, "- Run preinstall target for: "
<< installProjectName << std::endl);
std::string output;
int retVal = 1;
bool resB =
cmSystemTools::RunSingleCommand(buildCommand.c_str(),
&output, &output,
&retVal,
installDirectory.c_str(),
this->GeneratorVerbose, 0);
if ( !resB || retVal )
{
bool resB = cmSystemTools::RunSingleCommand(
buildCommand.c_str(), &output, &output, &retVal,
installDirectory.c_str(), this->GeneratorVerbose, 0);
if (!resB || retVal) {
std::string tmpFile = this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
tmpFile += "/PreinstallOutput.log";
cmGeneratedFileStream ofs(tmpFile.c_str());
ofs << "# Run command: " << buildCommand << std::endl
<< "# Directory: " << installDirectory << std::endl
<< "# Output:" << std::endl
<< output << std::endl;
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Problem running install command: " << buildCommand
<< std::endl
<< "Please check " << tmpFile << " for errors"
<< std::endl);
<< "# Directory: " << installDirectory << std::endl
<< "# Output:" << std::endl
<< output << std::endl;
cmCPackLogger(
cmCPackLog::LOG_ERROR, "Problem running install command: "
<< buildCommand << std::endl
<< "Please check " << tmpFile << " for errors" << std::endl);
return 0;
}
}
}
delete globalGenerator;
cmCPackLogger(cmCPackLog::LOG_OUTPUT,
"- Install project: " << installProjectName << std::endl);
"- Install project: " << installProjectName << std::endl);
// Run the installation for each component
std::vector<std::string>::iterator componentIt;
for (componentIt = componentsVector.begin();
componentIt != componentsVector.end();
++componentIt)
{
componentIt != componentsVector.end(); ++componentIt) {
std::string tempInstallDirectory = baseTempInstallDirectory;
installComponent = *componentIt;
if (componentInstall)
{
cmCPackLogger(cmCPackLog::LOG_OUTPUT,
"- Install component: " << installComponent
<< std::endl);
}
if (componentInstall) {
cmCPackLogger(cmCPackLog::LOG_OUTPUT, "- Install component: "
<< installComponent << std::endl);
}
cmake cm;
cm.SetHomeDirectory("");
@@ -712,13 +624,11 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects(
cm.SetProgressCallback(cmCPackGeneratorProgress, this);
cmGlobalGenerator gg(&cm);
cmsys::auto_ptr<cmMakefile> mf(
new cmMakefile(&gg, cm.GetCurrentSnapshot()));
if ( !installSubDirectory.empty() && installSubDirectory != "/" )
{
new cmMakefile(&gg, cm.GetCurrentSnapshot()));
if (!installSubDirectory.empty() && installSubDirectory != "/") {
tempInstallDirectory += installSubDirectory;
}
if (componentInstall)
{
}
if (componentInstall) {
tempInstallDirectory += "/";
// Some CPack generators would rather chose
// the local installation directory suffix.
@@ -728,20 +638,17 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects(
// one install directory for each component.
tempInstallDirectory +=
GetComponentInstallDirNameSuffix(installComponent);
if (this->IsOn("CPACK_COMPONENT_INCLUDE_TOPLEVEL_DIRECTORY"))
{
if (this->IsOn("CPACK_COMPONENT_INCLUDE_TOPLEVEL_DIRECTORY")) {
tempInstallDirectory += "/";
tempInstallDirectory += this->GetOption("CPACK_PACKAGE_FILE_NAME");
}
}
}
if (!setDestDir)
{
if (!setDestDir) {
tempInstallDirectory += this->GetPackagingInstallPrefix();
}
}
if ( setDestDir )
{
if (setDestDir) {
// For DESTDIR based packaging, use the *project*
// CMAKE_INSTALL_PREFIX underneath the tempInstallDirectory. The
// value of the project's CMAKE_INSTALL_PREFIX is sent in here as
@@ -754,37 +661,32 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects(
// 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->GetOption("CPACK_SET_DESTDIR"))) {
this->SetOption("CPACK_INSTALL_PREFIX",
this->GetOption("CPACK_PACKAGING_INSTALL_PREFIX"));
}
}
std::string dir;
if (this->GetOption("CPACK_INSTALL_PREFIX"))
{
if (this->GetOption("CPACK_INSTALL_PREFIX")) {
dir += this->GetOption("CPACK_INSTALL_PREFIX");
}
}
mf->AddDefinition("CMAKE_INSTALL_PREFIX", dir.c_str());
cmCPackLogger(
cmCPackLog::LOG_DEBUG,
"- Using DESTDIR + CPACK_INSTALL_PREFIX... (mf->AddDefinition)"
<< std::endl);
<< std::endl);
cmCPackLogger(cmCPackLog::LOG_DEBUG,
"- Setting CMAKE_INSTALL_PREFIX to '" << dir << "'"
<< std::endl);
<< std::endl);
// Make sure that DESTDIR + CPACK_INSTALL_PREFIX directory
// exists:
//
if (cmSystemTools::StringStartsWith(dir.c_str(), "/"))
{
if (cmSystemTools::StringStartsWith(dir.c_str(), "/")) {
dir = tempInstallDirectory + dir;
}
else
{
} else {
dir = tempInstallDirectory + "/" + dir;
}
}
/*
* We must re-set DESTDIR for each component
* We must not add the CPACK_INSTALL_PREFIX part because
@@ -796,178 +698,157 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects(
* - Because it was already used for component install
* in order to put things in subdirs...
*/
cmSystemTools::PutEnv(
std::string("DESTDIR=")+tempInstallDirectory
);
cmCPackLogger(cmCPackLog::LOG_DEBUG,
"- Creating directory: '" << dir << "'" << std::endl);
cmSystemTools::PutEnv(std::string("DESTDIR=") +
tempInstallDirectory);
cmCPackLogger(cmCPackLog::LOG_DEBUG, "- Creating directory: '"
<< dir << "'" << std::endl);
if ( !cmsys::SystemTools::MakeDirectory(dir.c_str()))
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Problem creating temporary directory: "
<< dir << std::endl);
if (!cmsys::SystemTools::MakeDirectory(dir.c_str())) {
cmCPackLogger(
cmCPackLog::LOG_ERROR,
"Problem creating temporary directory: " << dir << std::endl);
return 0;
}
}
else
{
} else {
mf->AddDefinition("CMAKE_INSTALL_PREFIX",
tempInstallDirectory.c_str());
if ( !cmsys::SystemTools::MakeDirectory(
tempInstallDirectory.c_str()))
{
if (!cmsys::SystemTools::MakeDirectory(
tempInstallDirectory.c_str())) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Problem creating temporary directory: "
<< tempInstallDirectory << std::endl);
<< tempInstallDirectory << std::endl);
return 0;
}
}
cmCPackLogger(cmCPackLog::LOG_DEBUG,
"- Using non-DESTDIR install... (mf->AddDefinition)"
<< std::endl);
<< std::endl);
cmCPackLogger(cmCPackLog::LOG_DEBUG,
"- Setting CMAKE_INSTALL_PREFIX to '"
<< tempInstallDirectory
<< "'" << std::endl);
}
<< tempInstallDirectory << "'" << std::endl);
}
if (!buildConfig.empty())
{
if (!buildConfig.empty()) {
mf->AddDefinition("BUILD_TYPE", buildConfig.c_str());
}
std::string installComponentLowerCase
= cmSystemTools::LowerCase(installComponent);
if ( installComponentLowerCase != "all" )
{
}
std::string installComponentLowerCase =
cmSystemTools::LowerCase(installComponent);
if (installComponentLowerCase != "all") {
mf->AddDefinition("CMAKE_INSTALL_COMPONENT",
installComponent.c_str());
}
}
// strip on TRUE, ON, 1, one or several file names, but not on
// FALSE, OFF, 0 and an empty string
if (!cmSystemTools::IsOff(this->GetOption("CPACK_STRIP_FILES")))
{
if (!cmSystemTools::IsOff(this->GetOption("CPACK_STRIP_FILES"))) {
mf->AddDefinition("CMAKE_INSTALL_DO_STRIP", "1");
}
}
// Remember the list of files before installation
// of the current component (if we are in component install)
const char* InstallPrefix = tempInstallDirectory.c_str();
std::vector<std::string> filesBefore;
std::string findExpr(InstallPrefix);
if (componentInstall)
{
if (componentInstall) {
cmsys::Glob glB;
findExpr += "/*";
glB.RecurseOn();
glB.SetRecurseListDirs(true);
glB.FindFiles(findExpr);
filesBefore = glB.GetFiles();
std::sort(filesBefore.begin(),filesBefore.end());
}
std::sort(filesBefore.begin(), filesBefore.end());
}
// If CPack was asked to warn on ABSOLUTE INSTALL DESTINATION
// then forward request to cmake_install.cmake script
if (this->IsOn("CPACK_WARN_ON_ABSOLUTE_INSTALL_DESTINATION"))
{
mf->AddDefinition("CMAKE_WARN_ON_ABSOLUTE_INSTALL_DESTINATION",
"1");
}
if (this->IsOn("CPACK_WARN_ON_ABSOLUTE_INSTALL_DESTINATION")) {
mf->AddDefinition("CMAKE_WARN_ON_ABSOLUTE_INSTALL_DESTINATION", "1");
}
// If current CPack generator does support
// ABSOLUTE INSTALL DESTINATION or CPack has been asked for
// then ask cmake_install.cmake script to error out
// as soon as it occurs (before installing file)
if (!SupportsAbsoluteDestination() ||
this->IsOn("CPACK_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION"))
{
mf->AddDefinition("CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION",
"1");
}
this->IsOn("CPACK_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION")) {
mf->AddDefinition("CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION",
"1");
}
// do installation
int res = mf->ReadListFile(installFile.c_str());
// forward definition of CMAKE_ABSOLUTE_DESTINATION_FILES
// to CPack (may be used by generators like CPack RPM or DEB)
// in order to transparently handle ABSOLUTE PATH
if (mf->GetDefinition("CMAKE_ABSOLUTE_DESTINATION_FILES"))
{
mf->AddDefinition("CPACK_ABSOLUTE_DESTINATION_FILES",
mf->GetDefinition("CMAKE_ABSOLUTE_DESTINATION_FILES"));
}
if (mf->GetDefinition("CMAKE_ABSOLUTE_DESTINATION_FILES")) {
mf->AddDefinition(
"CPACK_ABSOLUTE_DESTINATION_FILES",
mf->GetDefinition("CMAKE_ABSOLUTE_DESTINATION_FILES"));
}
// Now rebuild the list of files after installation
// of the current component (if we are in component install)
if (componentInstall)
{
if (componentInstall) {
cmsys::Glob glA;
glA.RecurseOn();
glA.SetRecurseListDirs(true);
glA.FindFiles(findExpr);
std::vector<std::string> filesAfter = glA.GetFiles();
std::sort(filesAfter.begin(),filesAfter.end());
std::sort(filesAfter.begin(), filesAfter.end());
std::vector<std::string>::iterator diff;
std::vector<std::string> result(filesAfter.size());
diff = std::set_difference (
filesAfter.begin(),filesAfter.end(),
filesBefore.begin(),filesBefore.end(),
result.begin());
diff = std::set_difference(filesAfter.begin(), filesAfter.end(),
filesBefore.begin(), filesBefore.end(),
result.begin());
std::vector<std::string>::iterator fit;
std::string localFileName;
// Populate the File field of each component
for (fit=result.begin();fit!=diff;++fit)
{
for (fit = result.begin(); fit != diff; ++fit) {
localFileName =
cmSystemTools::RelativePath(InstallPrefix, fit->c_str());
localFileName =
localFileName.substr(localFileName.find_first_not_of('/'),
std::string::npos);
cmSystemTools::RelativePath(InstallPrefix, fit->c_str());
localFileName = localFileName.substr(
localFileName.find_first_not_of('/'), std::string::npos);
Components[installComponent].Files.push_back(localFileName);
cmCPackLogger(cmCPackLog::LOG_DEBUG, "Adding file <"
<<localFileName<<"> to component <"
<<installComponent<<">"<<std::endl);
}
<< localFileName << "> to component <"
<< installComponent << ">" << std::endl);
}
}
if (NULL !=mf->GetDefinition("CPACK_ABSOLUTE_DESTINATION_FILES")) {
if (NULL != mf->GetDefinition("CPACK_ABSOLUTE_DESTINATION_FILES")) {
if (!absoluteDestFiles.empty()) {
absoluteDestFiles +=";";
absoluteDestFiles += ";";
}
absoluteDestFiles +=
mf->GetDefinition("CPACK_ABSOLUTE_DESTINATION_FILES");
cmCPackLogger(cmCPackLog::LOG_DEBUG,
"Got some ABSOLUTE DESTINATION FILES: "
<< absoluteDestFiles << std::endl);
"Got some ABSOLUTE DESTINATION FILES: "
<< absoluteDestFiles << std::endl);
// define component specific var
if (componentInstall)
{
if (componentInstall) {
std::string absoluteDestFileComponent =
std::string("CPACK_ABSOLUTE_DESTINATION_FILES")
+ "_" + GetComponentInstallDirNameSuffix(installComponent);
if (NULL != this->GetOption(absoluteDestFileComponent))
{
std::string absoluteDestFilesListComponent =
this->GetOption(absoluteDestFileComponent);
absoluteDestFilesListComponent +=";";
absoluteDestFilesListComponent +=
mf->GetDefinition("CPACK_ABSOLUTE_DESTINATION_FILES");
this->SetOption(absoluteDestFileComponent,
absoluteDestFilesListComponent.c_str());
}
else
{
std::string("CPACK_ABSOLUTE_DESTINATION_FILES") + "_" +
GetComponentInstallDirNameSuffix(installComponent);
if (NULL != this->GetOption(absoluteDestFileComponent)) {
std::string absoluteDestFilesListComponent =
this->GetOption(absoluteDestFileComponent);
absoluteDestFilesListComponent += ";";
absoluteDestFilesListComponent +=
mf->GetDefinition("CPACK_ABSOLUTE_DESTINATION_FILES");
this->SetOption(absoluteDestFileComponent,
mf->GetDefinition("CPACK_ABSOLUTE_DESTINATION_FILES"));
}
absoluteDestFilesListComponent.c_str());
} else {
this->SetOption(
absoluteDestFileComponent,
mf->GetDefinition("CPACK_ABSOLUTE_DESTINATION_FILES"));
}
}
if ( cmSystemTools::GetErrorOccuredFlag() || !res )
{
return 0;
}
}
if (cmSystemTools::GetErrorOccuredFlag() || !res) {
return 0;
}
}
}
}
this->SetOption("CPACK_ABSOLUTE_DESTINATION_FILES",
absoluteDestFiles.c_str());
return 1;
@@ -979,84 +860,73 @@ bool cmCPackGenerator::ReadListFile(const char* moduleName)
std::string fullPath = this->MakefileMap->GetModulesFile(moduleName);
retval = this->MakefileMap->ReadListFile(fullPath.c_str());
// include FATAL_ERROR and ERROR in the return status
retval = retval && (! cmSystemTools::GetErrorOccuredFlag());
retval = retval && (!cmSystemTools::GetErrorOccuredFlag());
return retval;
}
void cmCPackGenerator::SetOptionIfNotSet(const std::string& op,
const char* value)
const char* value)
{
const char* def = this->MakefileMap->GetDefinition(op);
if ( def && *def )
{
if (def && *def) {
return;
}
}
this->SetOption(op, value);
}
void cmCPackGenerator::SetOption(const std::string& op, const char* value)
{
if ( !value )
{
if (!value) {
this->MakefileMap->RemoveDefinition(op);
return;
}
}
cmCPackLogger(cmCPackLog::LOG_DEBUG, this->GetNameOfClass()
<< "::SetOption(" << op << ", " << value << ")" << std::endl);
<< "::SetOption(" << op << ", " << value << ")"
<< std::endl);
this->MakefileMap->AddDefinition(op, value);
}
int cmCPackGenerator::DoPackage()
{
cmCPackLogger(cmCPackLog::LOG_OUTPUT,
"Create package using " << this->Name << std::endl);
cmCPackLogger(cmCPackLog::LOG_OUTPUT, "Create package using " << this->Name
<< std::endl);
// Prepare CPack internal name and check
// values for many CPACK_xxx vars
if ( !this->PrepareNames() )
{
if (!this->PrepareNames()) {
return 0;
}
}
// Digest Component grouping specification
if ( !this->PrepareGroupingKind() )
{
if (!this->PrepareGroupingKind()) {
return 0;
}
}
if ( cmSystemTools::IsOn(
this->GetOption("CPACK_REMOVE_TOPLEVEL_DIRECTORY")) )
{
const char* toplevelDirectory
= this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
if ( cmSystemTools::FileExists(toplevelDirectory) )
{
cmCPackLogger(cmCPackLog::LOG_VERBOSE,
"Remove toplevel directory: "
<< toplevelDirectory << std::endl);
if ( !cmSystemTools::RepeatedRemoveDirectory(toplevelDirectory) )
{
if (cmSystemTools::IsOn(
this->GetOption("CPACK_REMOVE_TOPLEVEL_DIRECTORY"))) {
const char* toplevelDirectory =
this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
if (cmSystemTools::FileExists(toplevelDirectory)) {
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Remove toplevel directory: "
<< toplevelDirectory << std::endl);
if (!cmSystemTools::RepeatedRemoveDirectory(toplevelDirectory)) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Problem removing toplevel directory: "
<< toplevelDirectory
<< std::endl);
"Problem removing toplevel directory: "
<< toplevelDirectory << std::endl);
return 0;
}
}
}
cmCPackLogger(cmCPackLog::LOG_DEBUG,
"About to install project " << std::endl);
}
cmCPackLogger(cmCPackLog::LOG_DEBUG, "About to install project "
<< std::endl);
if ( !this->InstallProject() )
{
if (!this->InstallProject()) {
return 0;
}
cmCPackLogger(cmCPackLog::LOG_DEBUG,
"Done install project " << std::endl);
}
cmCPackLogger(cmCPackLog::LOG_DEBUG, "Done install project " << std::endl);
const char* tempPackageFileName = this->GetOption(
"CPACK_TEMPORARY_PACKAGE_FILE_NAME");
const char* tempPackageFileName =
this->GetOption("CPACK_TEMPORARY_PACKAGE_FILE_NAME");
const char* tempDirectory = this->GetOption("CPACK_TEMPORARY_DIRECTORY");
cmCPackLogger(cmCPackLog::LOG_DEBUG, "Find files" << std::endl);
@@ -1066,27 +936,25 @@ int cmCPackGenerator::DoPackage()
gl.RecurseOn();
gl.SetRecurseListDirs(true);
gl.SetRecurseThroughSymlinks(false);
if ( !gl.FindFiles(findExpr) )
{
if (!gl.FindFiles(findExpr)) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Cannot find any files in the packaging tree" << std::endl);
"Cannot find any files in the packaging tree" << std::endl);
return 0;
}
}
cmCPackLogger(cmCPackLog::LOG_OUTPUT, "Create package" << std::endl);
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Package files to: "
<< (tempPackageFileName ? tempPackageFileName : "(NULL)") << std::endl);
if ( cmSystemTools::FileExists(tempPackageFileName) )
{
<< (tempPackageFileName ? tempPackageFileName : "(NULL)")
<< std::endl);
if (cmSystemTools::FileExists(tempPackageFileName)) {
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Remove old package file"
<< std::endl);
<< std::endl);
cmSystemTools::RemoveFile(tempPackageFileName);
}
if ( cmSystemTools::IsOn(this->GetOption(
"CPACK_INCLUDE_TOPLEVEL_DIRECTORY")) )
{
}
if (cmSystemTools::IsOn(
this->GetOption("CPACK_INCLUDE_TOPLEVEL_DIRECTORY"))) {
tempDirectory = this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
}
}
// The files to be installed
files = gl.GetFiles();
@@ -1099,12 +967,11 @@ int cmCPackGenerator::DoPackage()
*/
packageFileNames.push_back(tempPackageFileName ? tempPackageFileName : "");
toplevel = tempDirectory;
if ( !this->PackageFiles() || cmSystemTools::GetErrorOccuredFlag())
{
if (!this->PackageFiles() || cmSystemTools::GetErrorOccuredFlag()) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem compressing the directory"
<< std::endl);
<< std::endl);
return 0;
}
}
/*
* Copy the generated packages to final destination
@@ -1113,35 +980,29 @@ int cmCPackGenerator::DoPackage()
* (because the specific generator did 'normalize' it)
*/
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Copying final package(s) ["
<<packageFileNames.size()
<<"]:"<<std::endl);
<< packageFileNames.size() << "]:" << std::endl);
std::vector<std::string>::iterator it;
/* now copy package one by one */
for (it=packageFileNames.begin();it!=packageFileNames.end();++it)
{
for (it = packageFileNames.begin(); it != packageFileNames.end(); ++it) {
std::string tmpPF(this->GetOption("CPACK_OUTPUT_FILE_PREFIX"));
tempPackageFileName = it->c_str();
tmpPF += "/"+cmSystemTools::GetFilenameName(*it);
tmpPF += "/" + cmSystemTools::GetFilenameName(*it);
const char* 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);
<< (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 << " generated." << std::endl);
}
return 1;
}
@@ -1153,17 +1014,14 @@ int cmCPackGenerator::Initialize(const std::string& name, cmMakefile* mf)
// set the running generator name
this->SetOption("CPACK_GENERATOR", this->Name.c_str());
// Load the project specific config file
const char* config =
this->GetOption("CPACK_PROJECT_CONFIG_FILE");
if(config)
{
const char* config = this->GetOption("CPACK_PROJECT_CONFIG_FILE");
if (config) {
mf->ReadListFile(config);
}
}
int result = this->InitializeInternal();
if (cmSystemTools::GetErrorOccuredFlag())
{
if (cmSystemTools::GetErrorOccuredFlag()) {
return 0;
}
}
// If a generator subclass did not already set this option in its
// InitializeInternal implementation, and the project did not already set
@@ -1191,13 +1049,10 @@ bool cmCPackGenerator::IsOn(const std::string& name) const
const char* cmCPackGenerator::GetOption(const std::string& op) const
{
const char* ret = this->MakefileMap->GetDefinition(op);
if(!ret)
{
if (!ret) {
cmCPackLogger(cmCPackLog::LOG_DEBUG,
"Warning, GetOption return NULL for: "
<< op
<< std::endl);
}
"Warning, GetOption return NULL for: " << op << std::endl);
}
return ret;
}
@@ -1213,40 +1068,32 @@ int cmCPackGenerator::PackageFiles()
const char* cmCPackGenerator::GetInstallPath()
{
if ( !this->InstallPath.empty() )
{
if (!this->InstallPath.empty()) {
return this->InstallPath.c_str();
}
}
#if defined(_WIN32) && !defined(__CYGWIN__)
const char* prgfiles = cmsys::SystemTools::GetEnv("ProgramFiles");
const char* sysDrive = cmsys::SystemTools::GetEnv("SystemDrive");
if ( prgfiles )
{
if (prgfiles) {
this->InstallPath = prgfiles;
}
else if ( sysDrive )
{
} else if (sysDrive) {
this->InstallPath = sysDrive;
this->InstallPath += "/Program Files";
}
else
{
} else {
this->InstallPath = "c:/Program Files";
}
}
this->InstallPath += "/";
this->InstallPath += this->GetOption("CPACK_PACKAGE_NAME");
this->InstallPath += "-";
this->InstallPath += this->GetOption("CPACK_PACKAGE_VERSION");
#elif defined(__HAIKU__)
char dir[B_PATH_NAME_LENGTH];
if (find_directory(B_SYSTEM_DIRECTORY, -1, false, dir, sizeof(dir)) == B_OK)
{
if (find_directory(B_SYSTEM_DIRECTORY, -1, false, dir, sizeof(dir)) ==
B_OK) {
this->InstallPath = dir;
}
else
{
} else {
this->InstallPath = "/boot/system";
}
}
#else
this->InstallPath = "/usr/local/";
#endif
@@ -1256,7 +1103,8 @@ const char* cmCPackGenerator::GetInstallPath()
const char* cmCPackGenerator::GetPackagingInstallPrefix()
{
cmCPackLogger(cmCPackLog::LOG_DEBUG, "GetPackagingInstallPrefix: '"
<< this->GetOption("CPACK_PACKAGING_INSTALL_PREFIX") << "'" << std::endl);
<< this->GetOption("CPACK_PACKAGING_INSTALL_PREFIX") << "'"
<< std::endl);
return this->GetOption("CPACK_PACKAGING_INSTALL_PREFIX");
}
@@ -1264,47 +1112,42 @@ const char* cmCPackGenerator::GetPackagingInstallPrefix()
std::string cmCPackGenerator::FindTemplate(const char* name)
{
cmCPackLogger(cmCPackLog::LOG_DEBUG, "Look for template: "
<< (name ? name : "(NULL)") << std::endl);
<< (name ? name : "(NULL)") << std::endl);
std::string ffile = this->MakefileMap->GetModulesFile(name);
cmCPackLogger(cmCPackLog::LOG_DEBUG, "Found template: "
<< ffile << std::endl);
cmCPackLogger(cmCPackLog::LOG_DEBUG, "Found template: " << ffile
<< std::endl);
return ffile;
}
bool cmCPackGenerator::ConfigureString(const std::string& inString,
std::string& outString)
std::string& outString)
{
this->MakefileMap->ConfigureString(inString,
outString, true, false);
this->MakefileMap->ConfigureString(inString, outString, true, false);
return true;
}
bool cmCPackGenerator::ConfigureFile(const char* inName,
const char* outName, bool copyOnly /* = false */)
bool cmCPackGenerator::ConfigureFile(const char* inName, const char* outName,
bool copyOnly /* = false */)
{
return this->MakefileMap->ConfigureFile(inName, outName,
copyOnly, true, false) == 1;
return this->MakefileMap->ConfigureFile(inName, outName, copyOnly, true,
false) == 1;
}
int cmCPackGenerator::CleanTemporaryDirectory()
{
std::string tempInstallDirectoryWithPostfix
= this->GetOption("CPACK_TEMPORARY_INSTALL_DIRECTORY");
std::string tempInstallDirectoryWithPostfix =
this->GetOption("CPACK_TEMPORARY_INSTALL_DIRECTORY");
const char* tempInstallDirectory = tempInstallDirectoryWithPostfix.c_str();
if(cmsys::SystemTools::FileExists(tempInstallDirectory))
{
if (cmsys::SystemTools::FileExists(tempInstallDirectory)) {
cmCPackLogger(cmCPackLog::LOG_OUTPUT,
"- Clean temporary : "
<< tempInstallDirectory << std::endl);
if(!cmSystemTools::RepeatedRemoveDirectory(tempInstallDirectory))
{
"- Clean temporary : " << tempInstallDirectory << std::endl);
if (!cmSystemTools::RepeatedRemoveDirectory(tempInstallDirectory)) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Problem removing temporary directory: " <<
tempInstallDirectory
<< std::endl);
"Problem removing temporary directory: "
<< tempInstallDirectory << std::endl);
return 0;
}
}
}
return 1;
}
@@ -1320,138 +1163,116 @@ int cmCPackGenerator::PrepareGroupingKind()
// find a component package method specified by the user
ComponentPackageMethod method = UNKNOWN_COMPONENT_PACKAGE_METHOD;
if(this->GetOption("CPACK_COMPONENTS_ALL_IN_ONE_PACKAGE"))
{
if (this->GetOption("CPACK_COMPONENTS_ALL_IN_ONE_PACKAGE")) {
method = ONE_PACKAGE;
}
}
if(this->GetOption("CPACK_COMPONENTS_IGNORE_GROUPS"))
{
if (this->GetOption("CPACK_COMPONENTS_IGNORE_GROUPS")) {
method = ONE_PACKAGE_PER_COMPONENT;
}
}
if(this->GetOption("CPACK_COMPONENTS_ONE_PACKAGE_PER_GROUP"))
{
if (this->GetOption("CPACK_COMPONENTS_ONE_PACKAGE_PER_GROUP")) {
method = ONE_PACKAGE_PER_GROUP;
}
}
std::string groupingType;
// Second way to specify grouping
if (NULL != this->GetOption("CPACK_COMPONENTS_GROUPING")) {
groupingType = this->GetOption("CPACK_COMPONENTS_GROUPING");
groupingType = this->GetOption("CPACK_COMPONENTS_GROUPING");
}
if (!groupingType.empty())
{
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "["
<< this->Name << "]"
<< " requested component grouping = "<< groupingType <<std::endl);
if (groupingType == "ALL_COMPONENTS_IN_ONE")
{
if (!groupingType.empty()) {
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "["
<< this->Name << "]"
<< " requested component grouping = " << groupingType
<< std::endl);
if (groupingType == "ALL_COMPONENTS_IN_ONE") {
method = ONE_PACKAGE;
}
else if (groupingType == "IGNORE")
{
} else if (groupingType == "IGNORE") {
method = ONE_PACKAGE_PER_COMPONENT;
}
else if (groupingType == "ONE_PER_GROUP")
{
} else if (groupingType == "ONE_PER_GROUP") {
method = ONE_PACKAGE_PER_GROUP;
}
else
{
cmCPackLogger(cmCPackLog::LOG_WARNING, "["
} else {
cmCPackLogger(
cmCPackLog::LOG_WARNING, "["
<< this->Name << "]"
<< " requested component grouping type <"<< groupingType
<< " requested component grouping type <" << groupingType
<< "> UNKNOWN not in (ALL_COMPONENTS_IN_ONE,IGNORE,ONE_PER_GROUP)"
<< std::endl);
}
}
}
// Some components were defined but NO group
// fallback to default if not group based
if(method == ONE_PACKAGE_PER_GROUP &&
this->ComponentGroups.empty() && !this->Components.empty())
{
if(componentPackageMethod == ONE_PACKAGE)
{
if (method == ONE_PACKAGE_PER_GROUP && this->ComponentGroups.empty() &&
!this->Components.empty()) {
if (componentPackageMethod == ONE_PACKAGE) {
method = ONE_PACKAGE;
}
else
{
} else {
method = ONE_PACKAGE_PER_COMPONENT;
}
cmCPackLogger(cmCPackLog::LOG_WARNING, "["
<< this->Name << "]"
<< " One package per component group requested, "
<< "but NO component groups exist: Ignoring component group."
<< std::endl);
}
cmCPackLogger(
cmCPackLog::LOG_WARNING, "["
<< this->Name << "]"
<< " One package per component group requested, "
<< "but NO component groups exist: Ignoring component group."
<< std::endl);
}
// if user specified packaging method, override the default packaging method
if(method != UNKNOWN_COMPONENT_PACKAGE_METHOD)
{
if (method != UNKNOWN_COMPONENT_PACKAGE_METHOD) {
componentPackageMethod = method;
}
}
const char* method_names[] =
{
"ALL_COMPONENTS_IN_ONE",
"IGNORE_GROUPS",
"ONE_PER_GROUP"
};
const char* method_names[] = { "ALL_COMPONENTS_IN_ONE", "IGNORE_GROUPS",
"ONE_PER_GROUP" };
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "["
<< this->Name << "]"
<< " requested component grouping = "
<< method_names[componentPackageMethod]
<< std::endl);
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "["
<< this->Name << "]"
<< " requested component grouping = "
<< method_names[componentPackageMethod] << std::endl);
return 1;
}
std::string cmCPackGenerator::GetComponentInstallDirNameSuffix(
const std::string& componentName) {
const std::string& componentName)
{
return componentName;
}
std::string cmCPackGenerator::GetComponentPackageFileName(
const std::string& initialPackageFileName,
const std::string& groupOrComponentName,
bool isGroupName) {
const std::string& initialPackageFileName,
const std::string& groupOrComponentName, bool isGroupName)
{
/*
* the default behavior is to use the
* component [group] name as a suffix
*/
std::string suffix="-"+groupOrComponentName;
std::string suffix = "-" + groupOrComponentName;
/* check if we should use DISPLAY name */
std::string dispNameVar = "CPACK_"+Name+"_USE_DISPLAY_NAME_IN_FILENAME";
if (IsOn(dispNameVar))
{
std::string dispNameVar = "CPACK_" + Name + "_USE_DISPLAY_NAME_IN_FILENAME";
if (IsOn(dispNameVar)) {
/* the component Group case */
if (isGroupName)
{
std::string groupDispVar = "CPACK_COMPONENT_GROUP_"
+ cmSystemTools::UpperCase(groupOrComponentName) + "_DISPLAY_NAME";
if (isGroupName) {
std::string groupDispVar = "CPACK_COMPONENT_GROUP_" +
cmSystemTools::UpperCase(groupOrComponentName) + "_DISPLAY_NAME";
const char* groupDispName = GetOption(groupDispVar);
if (groupDispName)
{
suffix = "-"+std::string(groupDispName);
}
if (groupDispName) {
suffix = "-" + std::string(groupDispName);
}
}
/* the [single] component case */
else
{
std::string dispVar = "CPACK_COMPONENT_"
+ cmSystemTools::UpperCase(groupOrComponentName) + "_DISPLAY_NAME";
const char* dispName = GetOption(dispVar);
if(dispName)
{
suffix = "-"+std::string(dispName);
}
}
else {
std::string dispVar = "CPACK_COMPONENT_" +
cmSystemTools::UpperCase(groupOrComponentName) + "_DISPLAY_NAME";
const char* dispName = GetOption(dispVar);
if (dispName) {
suffix = "-" + std::string(dispName);
}
}
}
return initialPackageFileName + suffix;
}
@@ -1473,183 +1294,137 @@ bool cmCPackGenerator::SupportsComponentInstallation() const
bool cmCPackGenerator::WantsComponentInstallation() const
{
return (!IsOn("CPACK_MONOLITHIC_INSTALL")
&& SupportsComponentInstallation()
// check that we have at least one group or component
&& (!this->ComponentGroups.empty() || !this->Components.empty()));
return (!IsOn("CPACK_MONOLITHIC_INSTALL") && SupportsComponentInstallation()
// check that we have at least one group or component
&& (!this->ComponentGroups.empty() || !this->Components.empty()));
}
cmCPackInstallationType*
cmCPackGenerator::GetInstallationType(const std::string& projectName,
const std::string& name)
cmCPackInstallationType* cmCPackGenerator::GetInstallationType(
const std::string& projectName, const std::string& name)
{
(void) projectName;
(void)projectName;
bool hasInstallationType = this->InstallationTypes.count(name) != 0;
cmCPackInstallationType *installType = &this->InstallationTypes[name];
if (!hasInstallationType)
{
cmCPackInstallationType* installType = &this->InstallationTypes[name];
if (!hasInstallationType) {
// Define the installation type
std::string macroPrefix = "CPACK_INSTALL_TYPE_"
+ cmsys::SystemTools::UpperCase(name);
std::string macroPrefix =
"CPACK_INSTALL_TYPE_" + cmsys::SystemTools::UpperCase(name);
installType->Name = name;
const char* displayName
= this->GetOption(macroPrefix + "_DISPLAY_NAME");
if (displayName && *displayName)
{
const char* displayName = this->GetOption(macroPrefix + "_DISPLAY_NAME");
if (displayName && *displayName) {
installType->DisplayName = displayName;
}
else
{
} else {
installType->DisplayName = installType->Name;
}
installType->Index = static_cast<unsigned>(
this->InstallationTypes.size());
}
installType->Index = static_cast<unsigned>(this->InstallationTypes.size());
}
return installType;
}
cmCPackComponent*
cmCPackGenerator::GetComponent(const std::string& projectName,
const std::string& name)
cmCPackComponent* cmCPackGenerator::GetComponent(
const std::string& projectName, const std::string& name)
{
bool hasComponent = this->Components.count(name) != 0;
cmCPackComponent *component = &this->Components[name];
if (!hasComponent)
{
cmCPackComponent* component = &this->Components[name];
if (!hasComponent) {
// Define the component
std::string macroPrefix = "CPACK_COMPONENT_"
+ cmsys::SystemTools::UpperCase(name);
std::string macroPrefix =
"CPACK_COMPONENT_" + cmsys::SystemTools::UpperCase(name);
component->Name = name;
const char* displayName
= this->GetOption(macroPrefix + "_DISPLAY_NAME");
if (displayName && *displayName)
{
const char* displayName = this->GetOption(macroPrefix + "_DISPLAY_NAME");
if (displayName && *displayName) {
component->DisplayName = displayName;
}
else
{
} else {
component->DisplayName = component->Name;
}
component->IsHidden
= this->IsOn(macroPrefix + "_HIDDEN");
component->IsRequired
= this->IsOn(macroPrefix + "_REQUIRED");
component->IsDisabledByDefault
= this->IsOn(macroPrefix + "_DISABLED");
component->IsDownloaded
= this->IsOn(macroPrefix + "_DOWNLOADED")
|| cmSystemTools::IsOn(this->GetOption("CPACK_DOWNLOAD_ALL"));
}
component->IsHidden = this->IsOn(macroPrefix + "_HIDDEN");
component->IsRequired = this->IsOn(macroPrefix + "_REQUIRED");
component->IsDisabledByDefault = this->IsOn(macroPrefix + "_DISABLED");
component->IsDownloaded = this->IsOn(macroPrefix + "_DOWNLOADED") ||
cmSystemTools::IsOn(this->GetOption("CPACK_DOWNLOAD_ALL"));
const char* archiveFile = this->GetOption(macroPrefix +
"_ARCHIVE_FILE");
if (archiveFile && *archiveFile)
{
const char* archiveFile = this->GetOption(macroPrefix + "_ARCHIVE_FILE");
if (archiveFile && *archiveFile) {
component->ArchiveFile = archiveFile;
}
}
const char* groupName = this->GetOption(macroPrefix + "_GROUP");
if (groupName && *groupName)
{
if (groupName && *groupName) {
component->Group = GetComponentGroup(projectName, groupName);
component->Group->Components.push_back(component);
}
else
{
} else {
component->Group = 0;
}
}
const char* description
= this->GetOption(macroPrefix + "_DESCRIPTION");
if (description && *description)
{
const char* description = this->GetOption(macroPrefix + "_DESCRIPTION");
if (description && *description) {
component->Description = description;
}
}
// Determine the installation types.
const char *installTypes
= this->GetOption(macroPrefix + "_INSTALL_TYPES");
if (installTypes && *installTypes)
{
const char* installTypes = this->GetOption(macroPrefix + "_INSTALL_TYPES");
if (installTypes && *installTypes) {
std::vector<std::string> installTypesVector;
cmSystemTools::ExpandListArgument(installTypes, installTypesVector);
std::vector<std::string>::iterator installTypesIt;
for (installTypesIt = installTypesVector.begin();
installTypesIt != installTypesVector.end();
++installTypesIt)
{
installTypesIt != installTypesVector.end(); ++installTypesIt) {
component->InstallationTypes.push_back(
this->GetInstallationType(projectName, *installTypesIt));
}
}
}
// Determine the component dependencies.
const char *depends = this->GetOption(macroPrefix + "_DEPENDS");
if (depends && *depends)
{
const char* depends = this->GetOption(macroPrefix + "_DEPENDS");
if (depends && *depends) {
std::vector<std::string> dependsVector;
cmSystemTools::ExpandListArgument(depends, dependsVector);
std::vector<std::string>::iterator dependIt;
for (dependIt = dependsVector.begin();
dependIt != dependsVector.end();
++dependIt)
{
cmCPackComponent *child = GetComponent(projectName,
*dependIt);
for (dependIt = dependsVector.begin(); dependIt != dependsVector.end();
++dependIt) {
cmCPackComponent* child = GetComponent(projectName, *dependIt);
component->Dependencies.push_back(child);
child->ReverseDependencies.push_back(component);
}
}
}
}
return component;
}
cmCPackComponentGroup*
cmCPackGenerator::GetComponentGroup(const std::string& projectName,
const std::string& name)
cmCPackComponentGroup* cmCPackGenerator::GetComponentGroup(
const std::string& projectName, const std::string& name)
{
(void) projectName;
std::string macroPrefix = "CPACK_COMPONENT_GROUP_"
+ cmsys::SystemTools::UpperCase(name);
(void)projectName;
std::string macroPrefix =
"CPACK_COMPONENT_GROUP_" + cmsys::SystemTools::UpperCase(name);
bool hasGroup = this->ComponentGroups.count(name) != 0;
cmCPackComponentGroup *group = &this->ComponentGroups[name];
if (!hasGroup)
{
cmCPackComponentGroup* group = &this->ComponentGroups[name];
if (!hasGroup) {
// Define the group
group->Name = name;
const char* displayName
= this->GetOption(macroPrefix + "_DISPLAY_NAME");
if (displayName && *displayName)
{
const char* displayName = this->GetOption(macroPrefix + "_DISPLAY_NAME");
if (displayName && *displayName) {
group->DisplayName = displayName;
}
else
{
} else {
group->DisplayName = group->Name;
}
}
const char* description
= this->GetOption(macroPrefix + "_DESCRIPTION");
if (description && *description)
{
const char* description = this->GetOption(macroPrefix + "_DESCRIPTION");
if (description && *description) {
group->Description = description;
}
group->IsBold
= this->IsOn(macroPrefix + "_BOLD_TITLE");
group->IsExpandedByDefault
= this->IsOn(macroPrefix + "_EXPANDED");
const char* parentGroupName
= this->GetOption(macroPrefix + "_PARENT_GROUP");
if (parentGroupName && *parentGroupName)
{
}
group->IsBold = this->IsOn(macroPrefix + "_BOLD_TITLE");
group->IsExpandedByDefault = this->IsOn(macroPrefix + "_EXPANDED");
const char* parentGroupName =
this->GetOption(macroPrefix + "_PARENT_GROUP");
if (parentGroupName && *parentGroupName) {
group->ParentGroup = GetComponentGroup(projectName, parentGroupName);
group->ParentGroup->Subgroups.push_back(group);
}
else
{
} else {
group->ParentGroup = 0;
}
}
}
return group;
}
+27 -27
View File
@@ -20,29 +20,29 @@
#include <vector>
#include "cmCPackComponentGroup.h" // cmCPackComponent and friends
// Forward declarations are insufficient since we use them in
// std::map data members below...
// Forward declarations are insufficient since we use them in
// std::map data members below...
#define cmCPackTypeMacro(klass, superclass) \
cmTypeMacro(klass, superclass); \
static cmCPackGenerator* CreateGenerator() { return new klass; } \
#define cmCPackTypeMacro(klass, superclass) \
cmTypeMacro(klass, superclass); \
static cmCPackGenerator* CreateGenerator() { return new klass; } \
class cmCPackTypeMacro_UseTrailingSemicolon
#define cmCPackLogger(logType, msg) \
do { \
std::ostringstream cmCPackLog_msg; \
cmCPackLog_msg << msg; \
this->Logger->Log(logType, __FILE__, __LINE__,\
cmCPackLog_msg.str().c_str());\
} while ( 0 )
#define cmCPackLogger(logType, msg) \
do { \
std::ostringstream cmCPackLog_msg; \
cmCPackLog_msg << msg; \
this->Logger->Log(logType, __FILE__, __LINE__, \
cmCPackLog_msg.str().c_str()); \
} while (0)
#ifdef cerr
# undef cerr
#undef cerr
#endif
#define cerr no_cerr_use_cmCPack_Log
#ifdef cout
# undef cout
#undef cout
#endif
#define cout no_cout_use_cmCPack_Log
@@ -62,8 +62,10 @@ public:
* If verbose then more information is printed out
*/
void SetVerbose(bool val)
{ this->GeneratorVerbose = val ?
cmSystemTools::OUTPUT_MERGE : cmSystemTools::OUTPUT_NONE; }
{
this->GeneratorVerbose =
val ? cmSystemTools::OUTPUT_MERGE : cmSystemTools::OUTPUT_NONE;
}
/**
* Returns true if the generator may work on this system.
@@ -157,7 +159,7 @@ protected:
* default is "componentName"
*/
virtual std::string GetComponentInstallDirNameSuffix(
const std::string& componentName);
const std::string& componentName);
/**
* CPack specific generator may mangle CPACK_PACKAGE_FILE_NAME
@@ -169,9 +171,8 @@ protected:
* false otherwise
*/
virtual std::string GetComponentPackageFileName(
const std::string& initialPackageFileName,
const std::string& groupOrComponentName,
bool isGroupName);
const std::string& initialPackageFileName,
const std::string& groupOrComponentName, bool isGroupName);
/**
* Package the list of files and/or components which
@@ -188,11 +189,10 @@ protected:
virtual std::string FindTemplate(const char* name);
virtual bool ConfigureFile(const char* inName, const char* outName,
bool copyOnly = false);
bool copyOnly = false);
virtual bool ConfigureString(const std::string& input, std::string& output);
virtual int InitializeInternal();
//! Run install commands if specified
virtual int InstallProjectViaInstallCommands(
bool setDestDir, const std::string& tempInstallDirectory);
@@ -207,7 +207,8 @@ protected:
* The various level of support of
* CPACK_SET_DESTDIR used by the generator.
*/
enum CPackSetDestdirSupport {
enum CPackSetDestdirSupport
{
/* the generator works with or without it */
SETDESTDIR_SUPPORTED,
/* the generator works best if automatically handled */
@@ -251,13 +252,11 @@ protected:
*/
virtual bool WantsComponentInstallation() const;
virtual cmCPackInstallationType* GetInstallationType(
const std::string& projectName,
const std::string& name);
const std::string& projectName, const std::string& name);
virtual cmCPackComponent* GetComponent(const std::string& projectName,
const std::string& name);
virtual cmCPackComponentGroup* GetComponentGroup(
const std::string& projectName,
const std::string& name);
const std::string& projectName, const std::string& name);
cmSystemTools::OutputOption GeneratorVerbose;
std::string Name;
@@ -324,6 +323,7 @@ protected:
ComponentPackageMethod componentPackageMethod;
cmCPackLog* Logger;
private:
cmMakefile* MakefileMap;
};
+78 -100
View File
@@ -24,134 +24,115 @@
#include "cmCPackZIPGenerator.h"
#ifdef __APPLE__
# include "cmCPackBundleGenerator.h"
# include "cmCPackDragNDropGenerator.h"
# include "cmCPackOSXX11Generator.h"
# include "cmCPackPackageMakerGenerator.h"
#include "cmCPackBundleGenerator.h"
#include "cmCPackDragNDropGenerator.h"
#include "cmCPackOSXX11Generator.h"
#include "cmCPackPackageMakerGenerator.h"
#endif
#ifdef __CYGWIN__
# include "cmCPackCygwinBinaryGenerator.h"
# include "cmCPackCygwinSourceGenerator.h"
#include "cmCPackCygwinBinaryGenerator.h"
#include "cmCPackCygwinSourceGenerator.h"
#endif
#if !defined(_WIN32) \
&& !defined(__QNXNTO__) && !defined(__BEOS__) && !defined(__HAIKU__)
# include "cmCPackDebGenerator.h"
# include "cmCPackRPMGenerator.h"
#if !defined(_WIN32) && !defined(__QNXNTO__) && !defined(__BEOS__) && \
!defined(__HAIKU__)
#include "cmCPackDebGenerator.h"
#include "cmCPackRPMGenerator.h"
#endif
#ifdef _WIN32
# include "WiX/cmCPackWIXGenerator.h"
#include "WiX/cmCPackWIXGenerator.h"
#endif
#include "cmAlgorithms.h"
#include "cmCPackLog.h"
cmCPackGeneratorFactory::cmCPackGeneratorFactory()
{
if (cmCPackTGZGenerator::CanGenerate())
{
if (cmCPackTGZGenerator::CanGenerate()) {
this->RegisterGenerator("TGZ", "Tar GZip compression",
cmCPackTGZGenerator::CreateGenerator);
}
if (cmCPackTXZGenerator::CanGenerate())
{
cmCPackTGZGenerator::CreateGenerator);
}
if (cmCPackTXZGenerator::CanGenerate()) {
this->RegisterGenerator("TXZ", "Tar XZ compression",
cmCPackTXZGenerator::CreateGenerator);
}
if (cmCPackSTGZGenerator::CanGenerate())
{
cmCPackTXZGenerator::CreateGenerator);
}
if (cmCPackSTGZGenerator::CanGenerate()) {
this->RegisterGenerator("STGZ", "Self extracting Tar GZip compression",
cmCPackSTGZGenerator::CreateGenerator);
}
if (cmCPackNSISGenerator::CanGenerate())
{
cmCPackSTGZGenerator::CreateGenerator);
}
if (cmCPackNSISGenerator::CanGenerate()) {
this->RegisterGenerator("NSIS", "Null Soft Installer",
cmCPackNSISGenerator::CreateGenerator);
cmCPackNSISGenerator::CreateGenerator);
this->RegisterGenerator("NSIS64", "Null Soft Installer (64-bit)",
cmCPackNSISGenerator::CreateGenerator64);
}
if (cmCPackIFWGenerator::CanGenerate())
{
cmCPackNSISGenerator::CreateGenerator64);
}
if (cmCPackIFWGenerator::CanGenerate()) {
this->RegisterGenerator("IFW", "Qt Installer Framework",
cmCPackIFWGenerator::CreateGenerator);
}
cmCPackIFWGenerator::CreateGenerator);
}
#ifdef __CYGWIN__
if (cmCPackCygwinBinaryGenerator::CanGenerate())
{
if (cmCPackCygwinBinaryGenerator::CanGenerate()) {
this->RegisterGenerator("CygwinBinary", "Cygwin Binary Installer",
cmCPackCygwinBinaryGenerator::CreateGenerator);
}
if (cmCPackCygwinSourceGenerator::CanGenerate())
{
}
if (cmCPackCygwinSourceGenerator::CanGenerate()) {
this->RegisterGenerator("CygwinSource", "Cygwin Source Installer",
cmCPackCygwinSourceGenerator::CreateGenerator);
}
}
#endif
if (cmCPackZIPGenerator::CanGenerate())
{
if (cmCPackZIPGenerator::CanGenerate()) {
this->RegisterGenerator("ZIP", "ZIP file format",
cmCPackZIPGenerator::CreateGenerator);
}
if (cmCPack7zGenerator::CanGenerate())
{
cmCPackZIPGenerator::CreateGenerator);
}
if (cmCPack7zGenerator::CanGenerate()) {
this->RegisterGenerator("7Z", "7-Zip file format",
cmCPack7zGenerator::CreateGenerator);
}
cmCPack7zGenerator::CreateGenerator);
}
#ifdef _WIN32
if (cmCPackWIXGenerator::CanGenerate())
{
if (cmCPackWIXGenerator::CanGenerate()) {
this->RegisterGenerator("WIX", "MSI file format via WiX tools",
cmCPackWIXGenerator::CreateGenerator);
}
cmCPackWIXGenerator::CreateGenerator);
}
#endif
if (cmCPackTarBZip2Generator::CanGenerate())
{
if (cmCPackTarBZip2Generator::CanGenerate()) {
this->RegisterGenerator("TBZ2", "Tar BZip2 compression",
cmCPackTarBZip2Generator::CreateGenerator);
}
if (cmCPackTarCompressGenerator::CanGenerate())
{
cmCPackTarBZip2Generator::CreateGenerator);
}
if (cmCPackTarCompressGenerator::CanGenerate()) {
this->RegisterGenerator("TZ", "Tar Compress compression",
cmCPackTarCompressGenerator::CreateGenerator);
}
cmCPackTarCompressGenerator::CreateGenerator);
}
#ifdef __APPLE__
if (cmCPackDragNDropGenerator::CanGenerate())
{
if (cmCPackDragNDropGenerator::CanGenerate()) {
this->RegisterGenerator("DragNDrop", "Mac OSX Drag And Drop",
cmCPackDragNDropGenerator::CreateGenerator);
}
if (cmCPackBundleGenerator::CanGenerate())
{
cmCPackDragNDropGenerator::CreateGenerator);
}
if (cmCPackBundleGenerator::CanGenerate()) {
this->RegisterGenerator("Bundle", "Mac OSX bundle",
cmCPackBundleGenerator::CreateGenerator);
}
if (cmCPackPackageMakerGenerator::CanGenerate())
{
cmCPackBundleGenerator::CreateGenerator);
}
if (cmCPackPackageMakerGenerator::CanGenerate()) {
this->RegisterGenerator("PackageMaker", "Mac OSX Package Maker installer",
cmCPackPackageMakerGenerator::CreateGenerator);
}
if (cmCPackOSXX11Generator::CanGenerate())
{
cmCPackPackageMakerGenerator::CreateGenerator);
}
if (cmCPackOSXX11Generator::CanGenerate()) {
this->RegisterGenerator("OSXX11", "Mac OSX X11 bundle",
cmCPackOSXX11Generator::CreateGenerator);
}
cmCPackOSXX11Generator::CreateGenerator);
}
#endif
#if !defined(_WIN32) \
&& !defined(__QNXNTO__) && !defined(__BEOS__) && !defined(__HAIKU__)
if (cmCPackDebGenerator::CanGenerate())
{
#if !defined(_WIN32) && !defined(__QNXNTO__) && !defined(__BEOS__) && \
!defined(__HAIKU__)
if (cmCPackDebGenerator::CanGenerate()) {
this->RegisterGenerator("DEB", "Debian packages",
cmCPackDebGenerator::CreateGenerator);
}
if (cmCPackRPMGenerator::CanGenerate())
{
cmCPackDebGenerator::CreateGenerator);
}
if (cmCPackRPMGenerator::CanGenerate()) {
this->RegisterGenerator("RPM", "RPM packages",
cmCPackRPMGenerator::CreateGenerator);
}
cmCPackRPMGenerator::CreateGenerator);
}
#endif
}
@@ -161,13 +142,12 @@ cmCPackGeneratorFactory::~cmCPackGeneratorFactory()
}
cmCPackGenerator* cmCPackGeneratorFactory::NewGenerator(
const std::string& name)
const std::string& name)
{
cmCPackGenerator* gen = this->NewGeneratorInternal(name);
if ( !gen )
{
if (!gen) {
return 0;
}
}
this->Generators.push_back(gen);
gen->SetLogger(this->Logger);
return gen;
@@ -176,25 +156,23 @@ cmCPackGenerator* cmCPackGeneratorFactory::NewGenerator(
cmCPackGenerator* cmCPackGeneratorFactory::NewGeneratorInternal(
const std::string& name)
{
cmCPackGeneratorFactory::t_GeneratorCreatorsMap::iterator it
= this->GeneratorCreators.find(name);
if ( it == this->GeneratorCreators.end() )
{
cmCPackGeneratorFactory::t_GeneratorCreatorsMap::iterator it =
this->GeneratorCreators.find(name);
if (it == this->GeneratorCreators.end()) {
return 0;
}
}
return (it->second)();
}
void cmCPackGeneratorFactory::RegisterGenerator(const std::string& name,
const char* generatorDescription,
void cmCPackGeneratorFactory::RegisterGenerator(
const std::string& name, const char* generatorDescription,
CreateGeneratorCall* createGenerator)
{
if ( !createGenerator )
{
if (!createGenerator) {
cmCPack_Log(this->Logger, cmCPackLog::LOG_ERROR,
"Cannot register generator" << std::endl);
"Cannot register generator" << std::endl);
return;
}
}
this->GeneratorCreators[name] = createGenerator;
this->GeneratorDescriptions[name] = generatorDescription;
}
+5 -3
View File
@@ -37,14 +37,16 @@ public:
typedef cmCPackGenerator* CreateGeneratorCall();
void RegisterGenerator(const std::string& name,
const char* generatorDescription,
CreateGeneratorCall* createGenerator);
const char* generatorDescription,
CreateGeneratorCall* createGenerator);
void SetLogger(cmCPackLog* logger) { this->Logger = logger; }
typedef std::map<std::string, std::string> DescriptionsMap;
const DescriptionsMap& GetGeneratorsList() const
{ return this->GeneratorDescriptions; }
{
return this->GeneratorDescriptions;
}
private:
cmCPackGenerator* NewGeneratorInternal(const std::string& name);
+75 -105
View File
@@ -39,37 +39,33 @@ cmCPackLog::~cmCPackLog()
void cmCPackLog::SetLogOutputStream(std::ostream* os)
{
if ( this->LogOutputCleanup && this->LogOutput )
{
if (this->LogOutputCleanup && this->LogOutput) {
delete this->LogOutput;
}
}
this->LogOutputCleanup = false;
this->LogOutput = os;
}
bool cmCPackLog::SetLogOutputFile(const char* fname)
{
cmGeneratedFileStream *cg = 0;
if ( fname )
{
cmGeneratedFileStream* cg = 0;
if (fname) {
cg = new cmGeneratedFileStream(fname);
}
if ( cg && !*cg )
{
}
if (cg && !*cg) {
delete cg;
cg = 0;
}
}
this->SetLogOutputStream(cg);
if ( !cg )
{
if (!cg) {
return false;
}
}
this->LogOutputCleanup = true;
return true;
}
void cmCPackLog::Log(int tag, const char* file, int line,
const char* msg, size_t length)
void cmCPackLog::Log(int tag, const char* file, int line, const char* msg,
size_t length)
{
// By default no logging
bool display = false;
@@ -77,144 +73,118 @@ void cmCPackLog::Log(int tag, const char* file, int line,
// Display file and line number if debug
bool useFileAndLine = this->Debug;
bool output = false;
bool debug = false;
bool output = false;
bool debug = false;
bool warning = false;
bool error = false;
bool error = false;
bool verbose = false;
// When writing in file, add list of tags whenever tag changes.
std::string tagString;
bool needTagString = false;
if ( this->LogOutput && this->LastTag != tag )
{
if (this->LogOutput && this->LastTag != tag) {
needTagString = true;
}
}
if ( tag & LOG_OUTPUT )
{
if (tag & LOG_OUTPUT) {
output = true;
display = true;
if ( needTagString )
{
if (!tagString.empty()) { tagString += ","; }
tagString = "VERBOSE";
if (needTagString) {
if (!tagString.empty()) {
tagString += ",";
}
tagString = "VERBOSE";
}
if ( tag & LOG_WARNING )
{
}
if (tag & LOG_WARNING) {
warning = true;
display = true;
if ( needTagString )
{
if (!tagString.empty()) { tagString += ","; }
tagString = "WARNING";
if (needTagString) {
if (!tagString.empty()) {
tagString += ",";
}
tagString = "WARNING";
}
if ( tag & LOG_ERROR )
{
}
if (tag & LOG_ERROR) {
error = true;
display = true;
if ( needTagString )
{
if (!tagString.empty()) { tagString += ","; }
tagString = "ERROR";
if (needTagString) {
if (!tagString.empty()) {
tagString += ",";
}
tagString = "ERROR";
}
if ( tag & LOG_DEBUG && this->Debug )
{
}
if (tag & LOG_DEBUG && this->Debug) {
debug = true;
display = true;
if ( needTagString )
{
if (!tagString.empty()) { tagString += ","; }
tagString = "DEBUG";
if (needTagString) {
if (!tagString.empty()) {
tagString += ",";
}
useFileAndLine = true;
tagString = "DEBUG";
}
if ( tag & LOG_VERBOSE && this->Verbose )
{
useFileAndLine = true;
}
if (tag & LOG_VERBOSE && this->Verbose) {
verbose = true;
display = true;
if ( needTagString )
{
if (!tagString.empty()) { tagString += ","; }
if (needTagString) {
if (!tagString.empty()) {
tagString += ",";
}
tagString = "VERBOSE";
}
}
if ( this->Quiet )
{
}
if (this->Quiet) {
display = false;
}
if (this->LogOutput) {
if (needTagString) {
*this->LogOutput << "[" << file << ":" << line << " " << tagString
<< "] ";
}
if ( this->LogOutput )
{
if ( needTagString )
{
*this->LogOutput << "[" << file << ":" << line << " "
<< tagString << "] ";
}
this->LogOutput->write(msg, length);
}
}
this->LastTag = tag;
if ( !display )
{
if (!display) {
return;
}
if ( this->NewLine )
{
if ( error && !this->ErrorPrefix.empty() )
{
}
if (this->NewLine) {
if (error && !this->ErrorPrefix.empty()) {
*this->DefaultError << this->ErrorPrefix;
}
else if ( warning && !this->WarningPrefix.empty() )
{
} else if (warning && !this->WarningPrefix.empty()) {
*this->DefaultError << this->WarningPrefix;
}
else if ( output && !this->OutputPrefix.empty() )
{
} else if (output && !this->OutputPrefix.empty()) {
*this->DefaultOutput << this->OutputPrefix;
}
else if ( verbose && !this->VerbosePrefix.empty() )
{
} else if (verbose && !this->VerbosePrefix.empty()) {
*this->DefaultOutput << this->VerbosePrefix;
}
else if ( debug && !this->DebugPrefix.empty() )
{
} else if (debug && !this->DebugPrefix.empty()) {
*this->DefaultOutput << this->DebugPrefix;
}
else if ( !this->Prefix.empty() )
{
} else if (!this->Prefix.empty()) {
*this->DefaultOutput << this->Prefix;
}
if ( useFileAndLine )
{
if ( error || warning )
{
}
if (useFileAndLine) {
if (error || warning) {
*this->DefaultError << file << ":" << line << " ";
}
else
{
} else {
*this->DefaultOutput << file << ":" << line << " ";
}
}
}
if ( error || warning )
{
}
if (error || warning) {
this->DefaultError->write(msg, length);
this->DefaultError->flush();
}
else
{
} else {
this->DefaultOutput->write(msg, length);
this->DefaultOutput->flush();
}
if ( msg[length-1] == '\n' || length > 2 )
{
}
if (msg[length - 1] == '\n' || length > 2) {
this->NewLine = true;
}
}
if ( error )
{
if (error) {
cmSystemTools::SetErrorOccured();
}
}
}
+25 -22
View File
@@ -15,24 +15,23 @@
#include "cmObject.h"
#define cmCPack_Log(ctSelf, logType, msg) \
do { \
std::ostringstream cmCPackLog_msg; \
cmCPackLog_msg << msg; \
(ctSelf)->Log(logType, __FILE__, __LINE__, cmCPackLog_msg.str().c_str());\
} while ( 0 )
#define cmCPack_Log(ctSelf, logType, msg) \
do { \
std::ostringstream cmCPackLog_msg; \
cmCPackLog_msg << msg; \
(ctSelf)->Log(logType, __FILE__, __LINE__, cmCPackLog_msg.str().c_str()); \
} while (0)
#ifdef cerr
# undef cerr
#undef cerr
#endif
#define cerr no_cerr_use_cmCPack_Log
#ifdef cout
# undef cout
#undef cout
#endif
#define cout no_cout_use_cmCPack_Log
/** \class cmCPackLog
* \brief A container for CPack generators
*
@@ -45,7 +44,8 @@ public:
cmCPackLog();
~cmCPackLog();
enum __log_tags {
enum __log_tags
{
NOTAG = 0,
LOG_OUTPUT = 0x1,
LOG_VERBOSE = 0x2,
@@ -56,19 +56,19 @@ public:
//! Various signatures for logging.
void Log(const char* file, int line, const char* msg)
{
{
this->Log(LOG_OUTPUT, file, line, msg);
}
}
void Log(const char* file, int line, const char* msg, size_t length)
{
{
this->Log(LOG_OUTPUT, file, line, msg, length);
}
}
void Log(int tag, const char* file, int line, const char* msg)
{
{
this->Log(tag, file, line, msg, strlen(msg));
}
}
void Log(int tag, const char* file, int line, const char* msg,
size_t length);
size_t length);
//! Set Verbose
void VerboseOn() { this->SetVerbose(true); }
@@ -126,11 +126,11 @@ private:
std::string WarningPrefix;
std::string ErrorPrefix;
std::ostream *DefaultOutput;
std::ostream *DefaultError;
std::ostream* DefaultOutput;
std::ostream* DefaultError;
std::string LogOutputFileName;
std::ostream *LogOutput;
std::ostream* LogOutput;
// Do we need to cleanup log output stream
bool LogOutputCleanup;
};
@@ -139,13 +139,16 @@ class cmCPackLogWrite
{
public:
cmCPackLogWrite(const char* data, size_t length)
: Data(data), Length(length) {}
: Data(data)
, Length(length)
{
}
const char* Data;
size_t Length;
};
inline std::ostream& operator<< (std::ostream& os, const cmCPackLogWrite& c)
inline std::ostream& operator<<(std::ostream& os, const cmCPackLogWrite& c)
{
os.write(c.Data, c.Length);
os.flush();
+365 -503
View File
@@ -26,9 +26,9 @@
/* NSIS uses different command line syntax on Windows and others */
#ifdef _WIN32
# define NSIS_OPT "/"
#define NSIS_OPT "/"
#else
# define NSIS_OPT "-"
#define NSIS_OPT "-"
#endif
cmCPackNSISGenerator::cmCPackNSISGenerator(bool nsis64)
@@ -45,22 +45,20 @@ int cmCPackNSISGenerator::PackageFiles()
// TODO: Fix nsis to force out file name
std::string nsisInFileName = this->FindTemplate("NSIS.template.in");
if (nsisInFileName.empty())
{
if (nsisInFileName.empty()) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"CPack error: Could not find NSIS installer template file."
<< std::endl);
"CPack error: Could not find NSIS installer template file."
<< std::endl);
return false;
}
std::string nsisInInstallOptions
= this->FindTemplate("NSIS.InstallOptions.ini.in");
if (nsisInInstallOptions.empty())
{
}
std::string nsisInInstallOptions =
this->FindTemplate("NSIS.InstallOptions.ini.in");
if (nsisInInstallOptions.empty()) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"CPack error: Could not find NSIS installer options file."
<< std::endl);
"CPack error: Could not find NSIS installer options file."
<< std::endl);
return false;
}
}
std::string nsisFileName = this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
std::string tmpFile = nsisFileName;
@@ -69,93 +67,80 @@ int cmCPackNSISGenerator::PackageFiles()
nsisFileName += "/project.nsi";
std::ostringstream str;
std::vector<std::string>::const_iterator it;
for ( it = files.begin(); it != files.end(); ++ it )
{
std::string fileN = cmSystemTools::RelativePath(toplevel.c_str(),
it->c_str());
if (!this->Components.empty())
{
for (it = files.begin(); it != files.end(); ++it) {
std::string fileN =
cmSystemTools::RelativePath(toplevel.c_str(), it->c_str());
if (!this->Components.empty()) {
// Strip off the component part of the path.
fileN = fileN.substr(fileN.find('/')+1, std::string::npos);
}
fileN = fileN.substr(fileN.find('/') + 1, std::string::npos);
}
cmSystemTools::ReplaceString(fileN, "/", "\\");
str << " Delete \"$INSTDIR\\" << fileN << "\"" << std::endl;
}
cmCPackLogger(cmCPackLog::LOG_DEBUG, "Uninstall Files: "
<< str.str() << std::endl);
}
cmCPackLogger(cmCPackLog::LOG_DEBUG, "Uninstall Files: " << str.str()
<< std::endl);
this->SetOptionIfNotSet("CPACK_NSIS_DELETE_FILES", str.str().c_str());
std::vector<std::string> dirs;
this->GetListOfSubdirectories(toplevel.c_str(), dirs);
std::vector<std::string>::const_iterator sit;
std::ostringstream dstr;
for ( sit = dirs.begin(); sit != dirs.end(); ++ sit )
{
for (sit = dirs.begin(); sit != dirs.end(); ++sit) {
std::string componentName;
std::string fileN = cmSystemTools::RelativePath(toplevel.c_str(),
sit->c_str());
if ( fileN.empty() )
{
std::string fileN =
cmSystemTools::RelativePath(toplevel.c_str(), sit->c_str());
if (fileN.empty()) {
continue;
}
if (!Components.empty())
{
}
if (!Components.empty()) {
// If this is a component installation, strip off the component
// part of the path.
std::string::size_type slash = fileN.find('/');
if (slash != std::string::npos)
{
if (slash != std::string::npos) {
// If this is a component installation, determine which component it
// is.
componentName = fileN.substr(0, slash);
// Strip off the component part of the path.
fileN = fileN.substr(slash+1, std::string::npos);
}
}
cmSystemTools::ReplaceString(fileN, "/", "\\");
dstr << " RMDir \"$INSTDIR\\" << fileN << "\"" << std::endl;
if (!componentName.empty())
{
this->Components[componentName].Directories.push_back(fileN);
fileN = fileN.substr(slash + 1, std::string::npos);
}
}
cmCPackLogger(cmCPackLog::LOG_DEBUG, "Uninstall Dirs: "
<< dstr.str() << std::endl);
this->SetOptionIfNotSet("CPACK_NSIS_DELETE_DIRECTORIES",
dstr.str().c_str());
cmSystemTools::ReplaceString(fileN, "/", "\\");
dstr << " RMDir \"$INSTDIR\\" << fileN << "\"" << std::endl;
if (!componentName.empty()) {
this->Components[componentName].Directories.push_back(fileN);
}
}
cmCPackLogger(cmCPackLog::LOG_DEBUG, "Uninstall Dirs: " << dstr.str()
<< std::endl);
this->SetOptionIfNotSet("CPACK_NSIS_DELETE_DIRECTORIES", dstr.str().c_str());
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Configure file: " << nsisInFileName
<< " to " << nsisFileName << std::endl);
if(this->IsSet("CPACK_NSIS_MUI_ICON")
|| this->IsSet("CPACK_NSIS_MUI_UNIICON"))
{
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Configure file: "
<< nsisInFileName << " to " << nsisFileName << std::endl);
if (this->IsSet("CPACK_NSIS_MUI_ICON") ||
this->IsSet("CPACK_NSIS_MUI_UNIICON")) {
std::string installerIconCode;
if(this->IsSet("CPACK_NSIS_MUI_ICON"))
{
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"))
{
}
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());
}
if(this->IsSet("CPACK_PACKAGE_ICON"))
{
}
if (this->IsSet("CPACK_PACKAGE_ICON")) {
std::string installerIconCode = "!define MUI_HEADERIMAGE_BITMAP \"";
installerIconCode += this->GetOption("CPACK_PACKAGE_ICON");
installerIconCode += "\"\n";
this->SetOptionIfNotSet("CPACK_NSIS_INSTALLER_ICON_CODE",
installerIconCode.c_str());
}
}
if (this->IsSet("CPACK_NSIS_MUI_WELCOMEFINISHPAGE_BITMAP"))
{
if (this->IsSet("CPACK_NSIS_MUI_WELCOMEFINISHPAGE_BITMAP")) {
std::string installerBitmapCode =
"!define MUI_WELCOMEFINISHPAGE_BITMAP \"";
installerBitmapCode +=
@@ -163,10 +148,9 @@ int cmCPackNSISGenerator::PackageFiles()
installerBitmapCode += "\"\n";
this->SetOptionIfNotSet("CPACK_NSIS_INSTALLER_MUI_WELCOMEFINISH_CODE",
installerBitmapCode.c_str());
}
}
if (this->IsSet("CPACK_NSIS_MUI_UNWELCOMEFINISHPAGE_BITMAP"))
{
if (this->IsSet("CPACK_NSIS_MUI_UNWELCOMEFINISHPAGE_BITMAP")) {
std::string installerBitmapCode =
"!define MUI_UNWELCOMEFINISHPAGE_BITMAP \"";
installerBitmapCode +=
@@ -174,10 +158,9 @@ int cmCPackNSISGenerator::PackageFiles()
installerBitmapCode += "\"\n";
this->SetOptionIfNotSet("CPACK_NSIS_INSTALLER_MUI_UNWELCOMEFINISH_CODE",
installerBitmapCode.c_str());
}
}
if(this->IsSet("CPACK_NSIS_MUI_FINISHPAGE_RUN"))
{
if (this->IsSet("CPACK_NSIS_MUI_FINISHPAGE_RUN")) {
std::string installerRunCode = "!define MUI_FINISHPAGE_RUN \"$INSTDIR\\";
installerRunCode += this->GetOption("CPACK_NSIS_EXECUTABLES_DIRECTORY");
installerRunCode += "\\";
@@ -185,11 +168,10 @@ int cmCPackNSISGenerator::PackageFiles()
installerRunCode += "\"\n";
this->SetOptionIfNotSet("CPACK_NSIS_INSTALLER_MUI_FINISHPAGE_RUN_CODE",
installerRunCode.c_str());
}
}
// Setup all of the component sections
if (this->Components.empty())
{
if (this->Components.empty()) {
this->SetOptionIfNotSet("CPACK_NSIS_INSTALLATION_TYPES", "");
this->SetOptionIfNotSet("CPACK_NSIS_INSTALLER_MUI_COMPONENTS_DESC", "");
this->SetOptionIfNotSet("CPACK_NSIS_PAGE_COMPONENTS", "");
@@ -198,9 +180,7 @@ int cmCPackNSISGenerator::PackageFiles()
this->SetOptionIfNotSet("CPACK_NSIS_COMPONENT_SECTIONS", "");
this->SetOptionIfNotSet("CPACK_NSIS_COMPONENT_SECTION_LIST", "");
this->SetOptionIfNotSet("CPACK_NSIS_SECTION_SELECTED_VARS", "");
}
else
{
} else {
std::string componentCode;
std::string sectionList;
std::string selectedVarsList;
@@ -213,66 +193,54 @@ int cmCPackNSISGenerator::PackageFiles()
// Create installation types. The order is significant, so we first fill
// in a vector based on the indices, and print them in that order.
std::vector<cmCPackInstallationType *>
installTypes(this->InstallationTypes.size());
std::vector<cmCPackInstallationType*> installTypes(
this->InstallationTypes.size());
std::map<std::string, cmCPackInstallationType>::iterator installTypeIt;
for (installTypeIt = this->InstallationTypes.begin();
installTypeIt != this->InstallationTypes.end();
++installTypeIt)
{
installTypes[installTypeIt->second.Index-1] = &installTypeIt->second;
}
std::vector<cmCPackInstallationType *>::iterator installTypeIt2;
installTypeIt != this->InstallationTypes.end(); ++installTypeIt) {
installTypes[installTypeIt->second.Index - 1] = &installTypeIt->second;
}
std::vector<cmCPackInstallationType*>::iterator installTypeIt2;
for (installTypeIt2 = installTypes.begin();
installTypeIt2 != installTypes.end();
++installTypeIt2)
{
installTypeIt2 != installTypes.end(); ++installTypeIt2) {
installTypesCode += "InstType \"";
installTypesCode += (*installTypeIt2)->DisplayName;
installTypesCode += "\"\n";
}
}
// Create installation groups first
std::map<std::string, cmCPackComponentGroup>::iterator groupIt;
for (groupIt = this->ComponentGroups.begin();
groupIt != this->ComponentGroups.end();
++groupIt)
{
if (groupIt->second.ParentGroup == 0)
{
groupIt != this->ComponentGroups.end(); ++groupIt) {
if (groupIt->second.ParentGroup == 0) {
componentCode +=
this->CreateComponentGroupDescription(&groupIt->second, macrosOut);
}
}
// Add the group description, if any.
if (!groupIt->second.Description.empty())
{
groupDescriptions += " !insertmacro MUI_DESCRIPTION_TEXT ${"
+ groupIt->first + "} \""
+ this->TranslateNewlines(groupIt->second.Description) + "\"\n";
}
if (!groupIt->second.Description.empty()) {
groupDescriptions += " !insertmacro MUI_DESCRIPTION_TEXT ${" +
groupIt->first + "} \"" +
this->TranslateNewlines(groupIt->second.Description) + "\"\n";
}
}
// Create the remaining components, which aren't associated with groups.
std::map<std::string, cmCPackComponent>::iterator compIt;
for (compIt = this->Components.begin();
compIt != this->Components.end();
++compIt)
{
if (compIt->second.Files.empty())
{
for (compIt = this->Components.begin(); compIt != this->Components.end();
++compIt) {
if (compIt->second.Files.empty()) {
// NSIS cannot cope with components that have no files.
continue;
}
}
anyDownloadedComponents =
anyDownloadedComponents || compIt->second.IsDownloaded;
if (!compIt->second.Group)
{
componentCode
+= this->CreateComponentDescription(&compIt->second, macrosOut);
}
if (!compIt->second.Group) {
componentCode +=
this->CreateComponentDescription(&compIt->second, macrosOut);
}
// Add this component to the various section lists.
sectionList += " !insertmacro \"${MacroName}\" \"";
@@ -282,41 +250,33 @@ int cmCPackNSISGenerator::PackageFiles()
selectedVarsList += "Var " + compIt->first + "_was_installed\n";
// Add the component description, if any.
if (!compIt->second.Description.empty())
{
componentDescriptions += " !insertmacro MUI_DESCRIPTION_TEXT ${"
+ compIt->first + "} \""
+ this->TranslateNewlines(compIt->second.Description) + "\"\n";
}
if (!compIt->second.Description.empty()) {
componentDescriptions += " !insertmacro MUI_DESCRIPTION_TEXT ${" +
compIt->first + "} \"" +
this->TranslateNewlines(compIt->second.Description) + "\"\n";
}
}
componentCode += macrosOut.str();
if (componentDescriptions.empty() && groupDescriptions.empty())
{
if (componentDescriptions.empty() && groupDescriptions.empty()) {
// Turn off the "Description" box
this->SetOptionIfNotSet("CPACK_NSIS_INSTALLER_MUI_COMPONENTS_DESC",
"!define MUI_COMPONENTSPAGE_NODESC");
}
else
{
componentDescriptions =
"!insertmacro MUI_FUNCTION_DESCRIPTION_BEGIN\n"
+ componentDescriptions
+ groupDescriptions
+ "!insertmacro MUI_FUNCTION_DESCRIPTION_END\n";
} else {
componentDescriptions = "!insertmacro MUI_FUNCTION_DESCRIPTION_BEGIN\n" +
componentDescriptions + groupDescriptions +
"!insertmacro MUI_FUNCTION_DESCRIPTION_END\n";
this->SetOptionIfNotSet("CPACK_NSIS_INSTALLER_MUI_COMPONENTS_DESC",
componentDescriptions.c_str());
}
}
if (anyDownloadedComponents)
{
if (anyDownloadedComponents) {
defines += "!define CPACK_USES_DOWNLOAD\n";
if (cmSystemTools::IsOn(this->GetOption("CPACK_ADD_REMOVE")))
{
if (cmSystemTools::IsOn(this->GetOption("CPACK_ADD_REMOVE"))) {
defines += "!define CPACK_NSIS_ADD_REMOVE\n";
}
}
}
this->SetOptionIfNotSet("CPACK_NSIS_INSTALLATION_TYPES",
installTypesCode.c_str());
@@ -330,7 +290,7 @@ int cmCPackNSISGenerator::PackageFiles()
this->SetOptionIfNotSet("CPACK_NSIS_SECTION_SELECTED_VARS",
selectedVarsList.c_str());
this->SetOption("CPACK_NSIS_DEFINES", defines.c_str());
}
}
this->ConfigureFile(nsisInInstallOptions.c_str(),
nsisInstallOptions.c_str());
@@ -338,350 +298,308 @@ int cmCPackNSISGenerator::PackageFiles()
std::string nsisCmd = "\"";
nsisCmd += this->GetOption("CPACK_INSTALLER_PROGRAM");
nsisCmd += "\" \"" + nsisFileName + "\"";
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Execute: " << nsisCmd
<< std::endl);
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Execute: " << nsisCmd << std::endl);
std::string output;
int retVal = 1;
bool res = cmSystemTools::RunSingleCommand(nsisCmd.c_str(), &output, &output,
&retVal, 0, this->GeneratorVerbose, 0);
if ( !res || retVal )
{
bool res = cmSystemTools::RunSingleCommand(
nsisCmd.c_str(), &output, &output, &retVal, 0, this->GeneratorVerbose, 0);
if (!res || retVal) {
cmGeneratedFileStream ofs(tmpFile.c_str());
ofs << "# Run command: " << nsisCmd << std::endl
<< "# Output:" << std::endl
<< output << std::endl;
<< "# Output:" << std::endl
<< output << std::endl;
cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem running NSIS command: "
<< nsisCmd << std::endl
<< "Please check " << tmpFile << " for errors" << std::endl);
<< nsisCmd << std::endl
<< "Please check " << tmpFile << " for errors"
<< std::endl);
return 0;
}
}
return 1;
}
int cmCPackNSISGenerator::InitializeInternal()
{
if ( cmSystemTools::IsOn(this->GetOption(
"CPACK_INCLUDE_TOPLEVEL_DIRECTORY")) )
{
cmCPackLogger(cmCPackLog::LOG_WARNING,
if (cmSystemTools::IsOn(
this->GetOption("CPACK_INCLUDE_TOPLEVEL_DIRECTORY"))) {
cmCPackLogger(
cmCPackLog::LOG_WARNING,
"NSIS Generator cannot work with CPACK_INCLUDE_TOPLEVEL_DIRECTORY set. "
"This option will be reset to 0 (for this generator only)."
<< std::endl);
<< std::endl);
this->SetOption("CPACK_INCLUDE_TOPLEVEL_DIRECTORY", 0);
}
}
cmCPackLogger(cmCPackLog::LOG_DEBUG, "cmCPackNSISGenerator::Initialize()"
<< std::endl);
<< std::endl);
std::vector<std::string> path;
std::string nsisPath;
bool gotRegValue = false;
#ifdef _WIN32
if (Nsis64)
{
if ( !gotRegValue && cmsys::SystemTools::ReadRegistryValue(
"HKEY_LOCAL_MACHINE\\SOFTWARE\\NSIS\\Unicode", nsisPath,
cmsys::SystemTools::KeyWOW64_64) )
{
if (Nsis64) {
if (!gotRegValue && cmsys::SystemTools::ReadRegistryValue(
"HKEY_LOCAL_MACHINE\\SOFTWARE\\NSIS\\Unicode",
nsisPath, cmsys::SystemTools::KeyWOW64_64)) {
gotRegValue = true;
}
if ( !gotRegValue && cmsys::SystemTools::ReadRegistryValue(
"HKEY_LOCAL_MACHINE\\SOFTWARE\\NSIS", nsisPath,
cmsys::SystemTools::KeyWOW64_64) )
{
}
if (!gotRegValue && cmsys::SystemTools::ReadRegistryValue(
"HKEY_LOCAL_MACHINE\\SOFTWARE\\NSIS", nsisPath,
cmsys::SystemTools::KeyWOW64_64)) {
gotRegValue = true;
}
}
if ( !gotRegValue && cmsys::SystemTools::ReadRegistryValue(
"HKEY_LOCAL_MACHINE\\SOFTWARE\\NSIS\\Unicode", nsisPath,
cmsys::SystemTools::KeyWOW64_32) )
{
}
if (!gotRegValue && cmsys::SystemTools::ReadRegistryValue(
"HKEY_LOCAL_MACHINE\\SOFTWARE\\NSIS\\Unicode",
nsisPath, cmsys::SystemTools::KeyWOW64_32)) {
gotRegValue = true;
}
if ( !gotRegValue && cmsys::SystemTools::ReadRegistryValue(
"HKEY_LOCAL_MACHINE\\SOFTWARE\\NSIS\\Unicode", nsisPath) )
{
}
if (!gotRegValue &&
cmsys::SystemTools::ReadRegistryValue(
"HKEY_LOCAL_MACHINE\\SOFTWARE\\NSIS\\Unicode", nsisPath)) {
gotRegValue = true;
}
if ( !gotRegValue && cmsys::SystemTools::ReadRegistryValue(
"HKEY_LOCAL_MACHINE\\SOFTWARE\\NSIS", nsisPath,
cmsys::SystemTools::KeyWOW64_32) )
{
}
if (!gotRegValue && cmsys::SystemTools::ReadRegistryValue(
"HKEY_LOCAL_MACHINE\\SOFTWARE\\NSIS", nsisPath,
cmsys::SystemTools::KeyWOW64_32)) {
gotRegValue = true;
}
if ( !gotRegValue && cmsys::SystemTools::ReadRegistryValue(
"HKEY_LOCAL_MACHINE\\SOFTWARE\\NSIS", nsisPath) )
{
}
if (!gotRegValue && cmsys::SystemTools::ReadRegistryValue(
"HKEY_LOCAL_MACHINE\\SOFTWARE\\NSIS", nsisPath)) {
gotRegValue = true;
}
}
if (gotRegValue)
{
if (gotRegValue) {
path.push_back(nsisPath);
}
}
#endif
nsisPath = cmSystemTools::FindProgram("makensis", path, false);
if ( nsisPath.empty() )
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
if (nsisPath.empty()) {
cmCPackLogger(
cmCPackLog::LOG_ERROR,
"Cannot find NSIS compiler makensis: likely it is not installed, "
"or not in your PATH"
<< std::endl);
<< 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;
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 << std::endl);
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Test NSIS version: " << nsisCmd
<< std::endl);
std::string output;
int retVal = 1;
bool resS = cmSystemTools::RunSingleCommand(
nsisCmd.c_str(), &output, &output, &retVal, 0, this->GeneratorVerbose, 0);
cmsys::RegularExpression versionRex("v([0-9]+.[0-9]+)");
cmsys::RegularExpression versionRexCVS("v(.*)\\.cvs");
if ( !resS || retVal ||
(!versionRex.find(output) && !versionRexCVS.find(output))
)
{
if (!resS || retVal ||
(!versionRex.find(output) && !versionRexCVS.find(output))) {
const char* topDir = this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
std::string tmpFile = topDir ? topDir : ".";
tmpFile += "/NSISOutput.log";
cmGeneratedFileStream ofs(tmpFile.c_str());
ofs << "# Run command: " << nsisCmd << std::endl
<< "# Output:" << std::endl
<< output << std::endl;
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Problem checking NSIS version with command: "
<< nsisCmd << std::endl
<< "Please check " << tmpFile << " for errors" << std::endl);
<< "# Output:" << std::endl
<< output << std::endl;
cmCPackLogger(
cmCPackLog::LOG_ERROR, "Problem checking NSIS version with command: "
<< nsisCmd << std::endl
<< "Please check " << tmpFile << " for errors" << std::endl);
return 0;
}
if ( versionRex.find(output))
{
}
if (versionRex.find(output)) {
double nsisVersion = atof(versionRex.match(1).c_str());
double minNSISVersion = 2.09;
cmCPackLogger(cmCPackLog::LOG_DEBUG, "NSIS Version: "
<< nsisVersion << std::endl);
if ( nsisVersion < minNSISVersion )
{
cmCPackLogger(cmCPackLog::LOG_DEBUG, "NSIS Version: " << nsisVersion
<< std::endl);
if (nsisVersion < minNSISVersion) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"CPack requires NSIS Version 2.09 or greater. "
"NSIS found on the system was: "
<< nsisVersion << std::endl);
"CPack requires NSIS Version 2.09 or greater. "
"NSIS found on the system was: "
<< nsisVersion << std::endl);
return 0;
}
}
if ( versionRexCVS.find(output))
{
}
if (versionRexCVS.find(output)) {
// No version check for NSIS cvs build
cmCPackLogger(cmCPackLog::LOG_DEBUG, "NSIS Version: CVS "
<< versionRexCVS.match(1) << std::endl);
}
<< versionRexCVS.match(1) << std::endl);
}
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");
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)
{
if (cpackPackageDeskTopLinks) {
cmCPackLogger(cmCPackLog::LOG_DEBUG, "CPACK_CREATE_DESKTOP_LINKS: "
<< cpackPackageDeskTopLinks << std::endl);
<< cpackPackageDeskTopLinks << std::endl);
cmSystemTools::
ExpandListArgument(cpackPackageDeskTopLinks,
cpackPackageDesktopLinksVector);
for(std::vector<std::string>::iterator i =
cpackPackageDesktopLinksVector.begin(); i !=
cpackPackageDesktopLinksVector.end(); ++i)
{
cmCPackLogger(cmCPackLog::LOG_DEBUG, "CPACK_CREATE_DESKTOP_LINKS: "
<< *i << std::endl);
}
cmSystemTools::ExpandListArgument(cpackPackageDeskTopLinks,
cpackPackageDesktopLinksVector);
for (std::vector<std::string>::iterator i =
cpackPackageDesktopLinksVector.begin();
i != cpackPackageDesktopLinksVector.end(); ++i) {
cmCPackLogger(cmCPackLog::LOG_DEBUG,
"CPACK_CREATE_DESKTOP_LINKS: " << *i << std::endl);
}
else
{
} else {
cmCPackLogger(cmCPackLog::LOG_DEBUG, "CPACK_CREATE_DESKTOP_LINKS: "
<< "not set" << std::endl);
}
<< "not set" << std::endl);
}
std::ostringstream str;
std::ostringstream deleteStr;
if ( cpackPackageExecutables )
{
if (cpackPackageExecutables) {
cmCPackLogger(cmCPackLog::LOG_DEBUG, "The cpackPackageExecutables: "
<< cpackPackageExecutables << "." << std::endl);
<< cpackPackageExecutables << "." << std::endl);
std::vector<std::string> cpackPackageExecutablesVector;
cmSystemTools::ExpandListArgument(cpackPackageExecutables,
cpackPackageExecutablesVector);
if ( cpackPackageExecutablesVector.size() % 2 != 0 )
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
cpackPackageExecutablesVector);
if (cpackPackageExecutablesVector.size() % 2 != 0) {
cmCPackLogger(
cmCPackLog::LOG_ERROR,
"CPACK_PACKAGE_EXECUTABLES should contain pairs of <executable> and "
"<icon name>." << std::endl);
"<icon name>."
<< std::endl);
return 0;
}
}
std::vector<std::string>::iterator it;
for ( it = cpackPackageExecutablesVector.begin();
it != cpackPackageExecutablesVector.end();
++it )
{
for (it = cpackPackageExecutablesVector.begin();
it != cpackPackageExecutablesVector.end(); ++it) {
std::string execName = *it;
++ it;
++it;
std::string linkName = *it;
str << " CreateShortCut \"$SMPROGRAMS\\$STARTMENU_FOLDER\\"
<< linkName << ".lnk\" \"$INSTDIR\\"
<< cpackNsisExecutablesDirectory << "\\" << execName << ".exe\""
<< std::endl;
str << " CreateShortCut \"$SMPROGRAMS\\$STARTMENU_FOLDER\\" << linkName
<< ".lnk\" \"$INSTDIR\\" << cpackNsisExecutablesDirectory << "\\"
<< execName << ".exe\"" << std::endl;
deleteStr << " Delete \"$SMPROGRAMS\\$MUI_TEMP\\" << linkName
<< ".lnk\"" << std::endl;
<< ".lnk\"" << std::endl;
// see if CPACK_CREATE_DESKTOP_LINK_ExeName is on
// if so add a desktop link
if(!cpackPackageDesktopLinksVector.empty() &&
std::find(cpackPackageDesktopLinksVector.begin(),
cpackPackageDesktopLinksVector.end(),
execName)
!= cpackPackageDesktopLinksVector.end())
{
if (!cpackPackageDesktopLinksVector.empty() &&
std::find(cpackPackageDesktopLinksVector.begin(),
cpackPackageDesktopLinksVector.end(),
execName) != cpackPackageDesktopLinksVector.end()) {
str << " StrCmp \"$INSTALL_DESKTOP\" \"1\" 0 +2\n";
str << " CreateShortCut \"$DESKTOP\\"
<< linkName << ".lnk\" \"$INSTDIR\\"
<< cpackNsisExecutablesDirectory << "\\" << execName << ".exe\""
<< std::endl;
str << " CreateShortCut \"$DESKTOP\\" << linkName
<< ".lnk\" \"$INSTDIR\\" << cpackNsisExecutablesDirectory << "\\"
<< execName << ".exe\"" << std::endl;
deleteStr << " StrCmp \"$INSTALL_DESKTOP\" \"1\" 0 +2\n";
deleteStr << " Delete \"$DESKTOP\\" << linkName
<< ".lnk\"" << std::endl;
}
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->SetOptionIfNotSet("CPACK_NSIS_DELETE_ICONS", deleteStr.str().c_str());
this->SetOptionIfNotSet("CPACK_NSIS_COMPRESSOR", "lzma");
return this->Superclass::InitializeInternal();
}
void cmCPackNSISGenerator::CreateMenuLinks( std::ostringstream& str,
std::ostringstream& deleteStr)
void cmCPackNSISGenerator::CreateMenuLinks(std::ostringstream& str,
std::ostringstream& deleteStr)
{
const char* cpackMenuLinks
= this->GetOption("CPACK_NSIS_MENU_LINKS");
if(!cpackMenuLinks)
{
const char* cpackMenuLinks = this->GetOption("CPACK_NSIS_MENU_LINKS");
if (!cpackMenuLinks) {
return;
}
cmCPackLogger(cmCPackLog::LOG_DEBUG, "The cpackMenuLinks: "
<< cpackMenuLinks << "." << std::endl);
}
cmCPackLogger(cmCPackLog::LOG_DEBUG,
"The cpackMenuLinks: " << cpackMenuLinks << "." << std::endl);
std::vector<std::string> cpackMenuLinksVector;
cmSystemTools::ExpandListArgument(cpackMenuLinks,
cpackMenuLinksVector);
if ( cpackMenuLinksVector.size() % 2 != 0 )
{
cmSystemTools::ExpandListArgument(cpackMenuLinks, cpackMenuLinksVector);
if (cpackMenuLinksVector.size() % 2 != 0) {
cmCPackLogger(
cmCPackLog::LOG_ERROR,
"CPACK_NSIS_MENU_LINKS should contain pairs of <shortcut target> and "
"<shortcut label>." << std::endl);
"<shortcut label>."
<< std::endl);
return;
}
}
static cmsys::RegularExpression
urlRegex("^(mailto:|(ftps?|https?|news)://).*$");
static cmsys::RegularExpression urlRegex(
"^(mailto:|(ftps?|https?|news)://).*$");
std::vector<std::string>::iterator it;
for ( it = cpackMenuLinksVector.begin();
it != cpackMenuLinksVector.end();
++it )
{
for (it = cpackMenuLinksVector.begin(); it != cpackMenuLinksVector.end();
++it) {
std::string sourceName = *it;
const bool url = urlRegex.find(sourceName);
// Convert / to \ in filenames, but not in urls:
//
if(!url)
{
if (!url) {
cmSystemTools::ReplaceString(sourceName, "/", "\\");
}
}
++ it;
++it;
std::string linkName = *it;
if(!url)
{
str << " CreateShortCut \"$SMPROGRAMS\\$STARTMENU_FOLDER\\"
<< linkName << ".lnk\" \"$INSTDIR\\" << sourceName << "\""
<< std::endl;
if (!url) {
str << " CreateShortCut \"$SMPROGRAMS\\$STARTMENU_FOLDER\\" << linkName
<< ".lnk\" \"$INSTDIR\\" << sourceName << "\"" << std::endl;
deleteStr << " Delete \"$SMPROGRAMS\\$MUI_TEMP\\" << linkName
<< ".lnk\"" << std::endl;
}
else
{
str << " WriteINIStr \"$SMPROGRAMS\\$STARTMENU_FOLDER\\"
<< linkName << ".url\" \"InternetShortcut\" \"URL\" \""
<< sourceName << "\""
} else {
str << " WriteINIStr \"$SMPROGRAMS\\$STARTMENU_FOLDER\\" << linkName
<< ".url\" \"InternetShortcut\" \"URL\" \"" << sourceName << "\""
<< std::endl;
deleteStr << " Delete \"$SMPROGRAMS\\$MUI_TEMP\\" << linkName
<< ".url\"" << std::endl;
}
}
// see if CPACK_CREATE_DESKTOP_LINK_ExeName is on
// if so add a desktop link
std::string desktop = "CPACK_CREATE_DESKTOP_LINK_";
desktop += linkName;
if(this->IsSet(desktop))
{
if (this->IsSet(desktop)) {
str << " StrCmp \"$INSTALL_DESKTOP\" \"1\" 0 +2\n";
str << " CreateShortCut \"$DESKTOP\\"
<< linkName << ".lnk\" \"$INSTDIR\\" << sourceName << "\""
<< std::endl;
str << " CreateShortCut \"$DESKTOP\\" << linkName
<< ".lnk\" \"$INSTDIR\\" << sourceName << "\"" << std::endl;
deleteStr << " StrCmp \"$INSTALL_DESKTOP\" \"1\" 0 +2\n";
deleteStr << " Delete \"$DESKTOP\\" << linkName
<< ".lnk\"" << std::endl;
}
deleteStr << " Delete \"$DESKTOP\\" << linkName << ".lnk\""
<< std::endl;
}
}
}
bool cmCPackNSISGenerator::GetListOfSubdirectories(const char* topdir,
std::vector<std::string>& dirs)
bool cmCPackNSISGenerator::GetListOfSubdirectories(
const char* topdir, std::vector<std::string>& dirs)
{
cmsys::Directory dir;
dir.Load(topdir);
size_t fileNum;
for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum)
{
if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") &&
strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".."))
{
for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum) {
if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)), ".") &&
strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)), "..")) {
std::string fullPath = topdir;
fullPath += "/";
fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
if(cmsys::SystemTools::FileIsDirectory(fullPath) &&
!cmsys::SystemTools::FileIsSymlink(fullPath))
{
if (!this->GetListOfSubdirectories(fullPath.c_str(), dirs))
{
if (cmsys::SystemTools::FileIsDirectory(fullPath) &&
!cmsys::SystemTools::FileIsSymlink(fullPath)) {
if (!this->GetListOfSubdirectories(fullPath.c_str(), dirs)) {
return false;
}
}
}
}
}
dirs.push_back(topdir);
return true;
}
@@ -694,116 +612,95 @@ cmCPackNSISGenerator::SupportsSetDestdir() const
bool cmCPackNSISGenerator::SupportsAbsoluteDestination() const
{
return false;
return false;
}
bool cmCPackNSISGenerator::SupportsComponentInstallation() const
{
return true;
return true;
}
std::string
cmCPackNSISGenerator::
CreateComponentDescription(cmCPackComponent *component,
std::ostringstream& macrosOut)
std::string cmCPackNSISGenerator::CreateComponentDescription(
cmCPackComponent* component, std::ostringstream& macrosOut)
{
// Basic description of the component
std::string componentCode = "Section ";
if (component->IsDisabledByDefault)
{
if (component->IsDisabledByDefault) {
componentCode += "/o ";
}
}
componentCode += "\"";
if (component->IsHidden)
{
if (component->IsHidden) {
componentCode += "-";
}
}
componentCode += component->DisplayName + "\" " + component->Name + "\n";
if (component->IsRequired)
{
if (component->IsRequired) {
componentCode += " SectionIn RO\n";
}
else if (!component->InstallationTypes.empty())
{
} else if (!component->InstallationTypes.empty()) {
std::ostringstream out;
std::vector<cmCPackInstallationType *>::iterator installTypeIter;
std::vector<cmCPackInstallationType*>::iterator installTypeIter;
for (installTypeIter = component->InstallationTypes.begin();
installTypeIter != component->InstallationTypes.end();
++installTypeIter)
{
++installTypeIter) {
out << " " << (*installTypeIter)->Index;
}
componentCode += " SectionIn" + out.str() + "\n";
}
componentCode += " SectionIn" + out.str() + "\n";
}
componentCode += " SetOutPath \"$INSTDIR\"\n";
// Create the actual installation commands
if (component->IsDownloaded)
{
if (component->ArchiveFile.empty())
{
if (component->IsDownloaded) {
if (component->ArchiveFile.empty()) {
// Compute the name of the archive.
std::string packagesDir = this->GetOption("CPACK_TEMPORARY_DIRECTORY");
packagesDir += ".dummy";
std::ostringstream out;
out << cmSystemTools::GetFilenameWithoutLastExtension(packagesDir)
<< "-" << component->Name << ".zip";
out << cmSystemTools::GetFilenameWithoutLastExtension(packagesDir) << "-"
<< component->Name << ".zip";
component->ArchiveFile = out.str();
}
}
// Create the directory for the upload area
const char* userUploadDirectory =
this->GetOption("CPACK_UPLOAD_DIRECTORY");
std::string uploadDirectory;
if (userUploadDirectory && *userUploadDirectory)
{
if (userUploadDirectory && *userUploadDirectory) {
uploadDirectory = userUploadDirectory;
}
else
{
uploadDirectory= this->GetOption("CPACK_PACKAGE_DIRECTORY");
} else {
uploadDirectory = this->GetOption("CPACK_PACKAGE_DIRECTORY");
uploadDirectory += "/CPackUploads";
}
if(!cmSystemTools::FileExists(uploadDirectory.c_str()))
{
if (!cmSystemTools::MakeDirectory(uploadDirectory.c_str()))
{
}
if (!cmSystemTools::FileExists(uploadDirectory.c_str())) {
if (!cmSystemTools::MakeDirectory(uploadDirectory.c_str())) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Unable to create NSIS upload directory " << uploadDirectory
<< std::endl);
"Unable to create NSIS upload directory "
<< uploadDirectory << std::endl);
return "";
}
}
}
// Remove the old archive, if one exists
std::string archiveFile = uploadDirectory + '/' + component->ArchiveFile;
cmCPackLogger(cmCPackLog::LOG_OUTPUT,
"- Building downloaded component archive: "
<< archiveFile << std::endl);
if (cmSystemTools::FileExists(archiveFile.c_str(), true))
{
if (!cmSystemTools::RemoveFile(archiveFile))
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Unable to remove archive file " << archiveFile
<< std::endl);
"- Building downloaded component archive: " << archiveFile
<< std::endl);
if (cmSystemTools::FileExists(archiveFile.c_str(), true)) {
if (!cmSystemTools::RemoveFile(archiveFile)) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Unable to remove archive file "
<< archiveFile << std::endl);
return "";
}
}
}
// Find a ZIP program
if (!this->IsSet("ZIP_EXECUTABLE"))
{
if (!this->IsSet("ZIP_EXECUTABLE")) {
this->ReadListFile("CPackZIP.cmake");
if (!this->IsSet("ZIP_EXECUTABLE"))
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Unable to find ZIP program"
<< std::endl);
if (!this->IsSet("ZIP_EXECUTABLE")) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Unable to find ZIP program"
<< std::endl);
return "";
}
}
}
// The directory where this component's files reside
std::string dirName = this->GetOption("CPACK_TEMPORARY_DIRECTORY");
@@ -815,29 +712,25 @@ CreateComponentDescription(cmCPackComponent *component,
// size of the installed component.
std::string zipListFileName = this->GetOption("CPACK_TEMPORARY_DIRECTORY");
zipListFileName += "/winZip.filelist";
bool needQuotesInFile
= cmSystemTools::IsOn(this->GetOption("CPACK_ZIP_NEED_QUOTES"));
bool needQuotesInFile =
cmSystemTools::IsOn(this->GetOption("CPACK_ZIP_NEED_QUOTES"));
unsigned long totalSize = 0;
{ // the scope is needed for cmGeneratedFileStream
cmGeneratedFileStream out(zipListFileName.c_str());
std::vector<std::string>::iterator fileIt;
for (fileIt = component->Files.begin();
fileIt != component->Files.end();
++fileIt)
{
if ( needQuotesInFile )
{
for (fileIt = component->Files.begin(); fileIt != component->Files.end();
++fileIt) {
if (needQuotesInFile) {
out << "\"";
}
}
out << *fileIt;
if ( needQuotesInFile )
{
if (needQuotesInFile) {
out << "\"";
}
}
out << std::endl;
totalSize += cmSystemTools::FileLength(dirName + *fileIt);
}
}
}
// Build the archive in the upload area
@@ -847,29 +740,28 @@ CreateComponentDescription(cmCPackComponent *component,
zipListFileName.c_str());
std::string output;
int retVal = -1;
int res = cmSystemTools::RunSingleCommand(
cmd.c_str(), &output, &output,
&retVal, dirName.c_str(), cmSystemTools::OUTPUT_NONE, 0);
if ( !res || retVal )
{
int res = cmSystemTools::RunSingleCommand(cmd.c_str(), &output, &output,
&retVal, dirName.c_str(),
cmSystemTools::OUTPUT_NONE, 0);
if (!res || retVal) {
std::string tmpFile = this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
tmpFile += "/CompressZip.log";
cmGeneratedFileStream ofs(tmpFile.c_str());
ofs << "# Run command: " << cmd << std::endl
<< "# Output:" << std::endl
<< output << std::endl;
<< "# Output:" << std::endl
<< output << std::endl;
cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem running zip command: "
<< cmd << std::endl
<< "Please check " << tmpFile << " for errors" << std::endl);
<< cmd << std::endl
<< "Please check " << tmpFile << " for errors"
<< std::endl);
return "";
}
// Create the NSIS code to download this file on-the-fly.
unsigned long totalSizeInKbytes = (totalSize + 512) / 1024;
if (totalSizeInKbytes == 0)
{
if (totalSizeInKbytes == 0) {
totalSizeInKbytes = 1;
}
}
std::ostringstream out;
/* clang-format off */
out << " AddSize " << totalSizeInKbytes << "\n"
@@ -883,12 +775,10 @@ CreateComponentDescription(cmCPackComponent *component,
" Delete $INSTDIR\\$0\n";
/* clang-format on */
componentCode += out.str();
}
else
{
componentCode += " File /r \"${INST_DIR}\\" +
component->Name + "\\*.*\"\n";
}
} else {
componentCode +=
" File /r \"${INST_DIR}\\" + component->Name + "\\*.*\"\n";
}
componentCode += "SectionEnd\n";
// Macro used to remove the component
@@ -897,32 +787,24 @@ CreateComponentDescription(cmCPackComponent *component,
<< component->Name << "\n";
std::vector<std::string>::iterator pathIt;
std::string path;
for (pathIt = component->Files.begin();
pathIt != component->Files.end();
++pathIt)
{
for (pathIt = component->Files.begin(); pathIt != component->Files.end();
++pathIt) {
path = *pathIt;
cmSystemTools::ReplaceString(path, "/", "\\");
macrosOut << " Delete \"$INSTDIR\\"
<< path
<< "\"\n";
}
macrosOut << " Delete \"$INSTDIR\\" << path << "\"\n";
}
for (pathIt = component->Directories.begin();
pathIt != component->Directories.end();
++pathIt)
{
pathIt != component->Directories.end(); ++pathIt) {
path = *pathIt;
cmSystemTools::ReplaceString(path, "/", "\\");
macrosOut << " RMDir \"$INSTDIR\\"
<< path
<< "\"\n";
}
macrosOut << " RMDir \"$INSTDIR\\" << path << "\"\n";
}
macrosOut << " noremove_" << component->Name << ":\n";
macrosOut << "!macroend\n";
// Macro used to select each of the components that this component
// depends on.
std::set<cmCPackComponent *> visited;
std::set<cmCPackComponent*> visited;
macrosOut << "!macro Select_" << component->Name << "_depends\n";
macrosOut << CreateSelectionDependenciesDescription(component, visited);
macrosOut << "!macroend\n";
@@ -936,23 +818,19 @@ CreateComponentDescription(cmCPackComponent *component,
return componentCode;
}
std::string cmCPackNSISGenerator::CreateSelectionDependenciesDescription
(cmCPackComponent *component,
std::set<cmCPackComponent *>& visited)
std::string cmCPackNSISGenerator::CreateSelectionDependenciesDescription(
cmCPackComponent* component, std::set<cmCPackComponent*>& visited)
{
// Don't visit a component twice
if (visited.count(component))
{
if (visited.count(component)) {
return std::string();
}
}
visited.insert(component);
std::ostringstream out;
std::vector<cmCPackComponent *>::iterator dependIt;
std::vector<cmCPackComponent*>::iterator dependIt;
for (dependIt = component->Dependencies.begin();
dependIt != component->Dependencies.end();
++dependIt)
{
dependIt != component->Dependencies.end(); ++dependIt) {
// Write NSIS code to select this dependency
out << " SectionGetFlags ${" << (*dependIt)->Name << "} $0\n";
out << " IntOp $0 $0 | ${SF_SELECTED}\n";
@@ -961,29 +839,24 @@ std::string cmCPackNSISGenerator::CreateSelectionDependenciesDescription
<< "_selected 0 + ${SF_SELECTED}\n";
// Recurse
out << CreateSelectionDependenciesDescription(*dependIt, visited).c_str();
}
}
return out.str();
}
std::string cmCPackNSISGenerator::CreateDeselectionDependenciesDescription
(cmCPackComponent *component,
std::set<cmCPackComponent *>& visited)
std::string cmCPackNSISGenerator::CreateDeselectionDependenciesDescription(
cmCPackComponent* component, std::set<cmCPackComponent*>& visited)
{
// Don't visit a component twice
if (visited.count(component))
{
if (visited.count(component)) {
return std::string();
}
}
visited.insert(component);
std::ostringstream out;
std::vector<cmCPackComponent *>::iterator dependIt;
std::vector<cmCPackComponent*>::iterator dependIt;
for (dependIt = component->ReverseDependencies.begin();
dependIt != component->ReverseDependencies.end();
++dependIt)
{
dependIt != component->ReverseDependencies.end(); ++dependIt) {
// Write NSIS code to deselect this dependency
out << " SectionGetFlags ${" << (*dependIt)->Name << "} $0\n";
out << " IntOp $1 ${SF_SELECTED} ~\n";
@@ -992,57 +865,46 @@ std::string cmCPackNSISGenerator::CreateDeselectionDependenciesDescription
out << " IntOp $" << (*dependIt)->Name << "_selected 0 + 0\n";
// Recurse
out <<
CreateDeselectionDependenciesDescription(*dependIt, visited).c_str();
}
out
<< CreateDeselectionDependenciesDescription(*dependIt, visited).c_str();
}
return out.str();
}
std::string
cmCPackNSISGenerator::
CreateComponentGroupDescription(cmCPackComponentGroup *group,
std::ostringstream& macrosOut)
std::string cmCPackNSISGenerator::CreateComponentGroupDescription(
cmCPackComponentGroup* group, std::ostringstream& macrosOut)
{
if (group->Components.empty() && group->Subgroups.empty())
{
if (group->Components.empty() && group->Subgroups.empty()) {
// Silently skip empty groups. NSIS doesn't support them.
return std::string();
}
}
std::string code = "SectionGroup ";
if (group->IsExpandedByDefault)
{
if (group->IsExpandedByDefault) {
code += "/e ";
}
if (group->IsBold)
{
}
if (group->IsBold) {
code += "\"!" + group->DisplayName + "\" " + group->Name + "\n";
}
else
{
} else {
code += "\"" + group->DisplayName + "\" " + group->Name + "\n";
}
}
std::vector<cmCPackComponentGroup*>::iterator groupIt;
for (groupIt = group->Subgroups.begin(); groupIt != group->Subgroups.end();
++groupIt)
{
++groupIt) {
code += this->CreateComponentGroupDescription(*groupIt, macrosOut);
}
}
std::vector<cmCPackComponent*>::iterator comp;
for (comp = group->Components.begin();
comp != group->Components.end();
++comp)
{
if ((*comp)->Files.empty())
{
for (comp = group->Components.begin(); comp != group->Components.end();
++comp) {
if ((*comp)->Files.empty()) {
continue;
}
}
code += this->CreateComponentDescription(*comp, macrosOut);
}
}
code += "SectionGroupEnd\n";
return code;
}
+13 -16
View File
@@ -28,7 +28,9 @@ public:
cmCPackTypeMacro(cmCPackNSISGenerator, cmCPackGenerator);
static cmCPackGenerator* CreateGenerator64()
{ return new cmCPackNSISGenerator(true); }
{
return new cmCPackNSISGenerator(true);
}
/**
* Construct generator
@@ -38,14 +40,13 @@ public:
protected:
virtual int InitializeInternal();
void CreateMenuLinks( std::ostringstream& str,
std::ostringstream& deleteStr);
void CreateMenuLinks(std::ostringstream& str, std::ostringstream& deleteStr);
int PackageFiles();
virtual const char* GetOutputExtension() { return ".exe"; }
virtual const char* GetOutputPostfix() { return "win32"; }
bool GetListOfSubdirectories(const char* dir,
std::vector<std::string>& dirs);
std::vector<std::string>& dirs);
enum cmCPackGenerator::CPackSetDestdirSupport SupportsSetDestdir() const;
virtual bool SupportsAbsoluteDestination() const;
@@ -54,28 +55,24 @@ protected:
/// Produce a string that contains the NSIS code to describe a
/// particular component. Any added macros will be emitted via
/// macrosOut.
std::string
CreateComponentDescription(cmCPackComponent *component,
std::ostringstream& macrosOut);
std::string CreateComponentDescription(cmCPackComponent* component,
std::ostringstream& macrosOut);
/// Produce NSIS code that selects all of the components that this component
/// depends on, recursively.
std::string CreateSelectionDependenciesDescription
(cmCPackComponent *component,
std::set<cmCPackComponent *>& visited);
std::string CreateSelectionDependenciesDescription(
cmCPackComponent* component, std::set<cmCPackComponent*>& visited);
/// Produce NSIS code that de-selects all of the components that are
/// dependent on this component, recursively.
std::string CreateDeselectionDependenciesDescription
(cmCPackComponent *component,
std::set<cmCPackComponent *>& visited);
std::string CreateDeselectionDependenciesDescription(
cmCPackComponent* component, std::set<cmCPackComponent*>& visited);
/// Produce a string that contains the NSIS code to describe a
/// particular component group, including its components. Any
/// added macros will be emitted via macrosOut.
std::string
CreateComponentGroupDescription(cmCPackComponentGroup *group,
std::ostringstream& macrosOut);
std::string CreateComponentGroupDescription(cmCPackComponentGroup* group,
std::ostringstream& macrosOut);
/// Translations any newlines found in the string into \\r\\n, so that the
/// resulting string can be used within NSIS.
+94 -105
View File
@@ -36,41 +36,38 @@ int cmCPackOSXX11Generator::PackageFiles()
// TODO: Use toplevel ?
// It is used! Is this an obsolete comment?
const char* cpackPackageExecutables
= this->GetOption("CPACK_PACKAGE_EXECUTABLES");
if ( cpackPackageExecutables )
{
const char* cpackPackageExecutables =
this->GetOption("CPACK_PACKAGE_EXECUTABLES");
if (cpackPackageExecutables) {
cmCPackLogger(cmCPackLog::LOG_DEBUG, "The cpackPackageExecutables: "
<< cpackPackageExecutables << "." << std::endl);
<< cpackPackageExecutables << "." << std::endl);
std::ostringstream str;
std::ostringstream deleteStr;
std::vector<std::string> cpackPackageExecutablesVector;
cmSystemTools::ExpandListArgument(cpackPackageExecutables,
cpackPackageExecutablesVector);
if ( cpackPackageExecutablesVector.size() % 2 != 0 )
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
cpackPackageExecutablesVector);
if (cpackPackageExecutablesVector.size() % 2 != 0) {
cmCPackLogger(
cmCPackLog::LOG_ERROR,
"CPACK_PACKAGE_EXECUTABLES should contain pairs of <executable> and "
"<icon name>." << std::endl);
"<icon name>."
<< std::endl);
return 0;
}
std::vector<std::string>::iterator it;
for ( it = cpackPackageExecutablesVector.begin();
it != cpackPackageExecutablesVector.end();
++it )
{
std::string cpackExecutableName = *it;
++ it;
this->SetOptionIfNotSet("CPACK_EXECUTABLE_NAME",
cpackExecutableName.c_str());
}
}
std::vector<std::string>::iterator it;
for (it = cpackPackageExecutablesVector.begin();
it != cpackPackageExecutablesVector.end(); ++it) {
std::string cpackExecutableName = *it;
++it;
this->SetOptionIfNotSet("CPACK_EXECUTABLE_NAME",
cpackExecutableName.c_str());
}
}
// Disk image directories
std::string diskImageDirectory = toplevel;
std::string diskImageBackgroundImageDir
= diskImageDirectory + "/.background";
std::string diskImageBackgroundImageDir =
diskImageDirectory + "/.background";
// App bundle directories
std::string packageDirFileName = toplevel;
@@ -90,48 +87,45 @@ int cmCPackOSXX11Generator::PackageFiles()
const char* contDir = contentsDirectory.c_str();
const char* rsrcFile = resourceFileName.c_str();
const char* iconFile = this->GetOption("CPACK_PACKAGE_ICON");
if ( iconFile )
{
std::string iconFileName = cmsys::SystemTools::GetFilenameName(
iconFile);
if ( !cmSystemTools::FileExists(iconFile) )
{
if (iconFile) {
std::string iconFileName = cmsys::SystemTools::GetFilenameName(iconFile);
if (!cmSystemTools::FileExists(iconFile)) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot find icon file: "
<< iconFile << ". Please check CPACK_PACKAGE_ICON setting."
<< std::endl);
<< iconFile
<< ". Please check CPACK_PACKAGE_ICON setting."
<< std::endl);
return 0;
}
}
std::string destFileName = resourcesDirectory + "/" + iconFileName;
this->ConfigureFile(iconFile, destFileName.c_str(), true);
this->SetOptionIfNotSet("CPACK_APPLE_GUI_ICON", iconFileName.c_str());
}
}
std::string applicationsLinkName = diskImageDirectory + "/Applications";
cmSystemTools::CreateSymlink("/Applications", applicationsLinkName.c_str());
if (
!this->CopyResourcePlistFile("VolumeIcon.icns",
diskImageDirectory.c_str(),
".VolumeIcon.icns", true ) ||
!this->CopyResourcePlistFile("DS_Store", diskImageDirectory.c_str(),
".DS_Store", true ) ||
!this->CopyResourcePlistFile("background.png",
diskImageBackgroundImageDir.c_str(), "background.png", true ) ||
!this->CopyResourcePlistFile("RuntimeScript", dir) ||
!this->CopyResourcePlistFile("OSXX11.Info.plist", contDir,
"Info.plist" ) ||
!this->CopyResourcePlistFile("OSXX11.main.scpt", scrDir,
"main.scpt", true ) ||
!this->CopyResourcePlistFile("OSXScriptLauncher.rsrc", dir,
rsrcFile, true) ||
!this->CopyResourcePlistFile("OSXScriptLauncher", appdir,
this->GetOption("CPACK_PACKAGE_FILE_NAME"), true)
)
{
if (!this->CopyResourcePlistFile("VolumeIcon.icns",
diskImageDirectory.c_str(),
".VolumeIcon.icns", true) ||
!this->CopyResourcePlistFile("DS_Store", diskImageDirectory.c_str(),
".DS_Store", true) ||
!this->CopyResourcePlistFile("background.png",
diskImageBackgroundImageDir.c_str(),
"background.png", true) ||
!this->CopyResourcePlistFile("RuntimeScript", dir) ||
!this->CopyResourcePlistFile("OSXX11.Info.plist", contDir,
"Info.plist") ||
!this->CopyResourcePlistFile("OSXX11.main.scpt", scrDir, "main.scpt",
true) ||
!this->CopyResourcePlistFile("OSXScriptLauncher.rsrc", dir, rsrcFile,
true) ||
!this->CopyResourcePlistFile("OSXScriptLauncher", appdir,
this->GetOption("CPACK_PACKAGE_FILE_NAME"),
true)) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem copying the resource files"
<< std::endl);
<< std::endl);
return 0;
}
}
// Two of the files need to have execute permission, so ensure they do:
std::string runTimeScript = dir;
@@ -143,21 +137,21 @@ int cmCPackOSXX11Generator::PackageFiles()
appScriptName += this->GetOption("CPACK_PACKAGE_FILE_NAME");
mode_t mode;
if (cmsys::SystemTools::GetPermissions(runTimeScript.c_str(), mode))
{
if (cmsys::SystemTools::GetPermissions(runTimeScript.c_str(), mode)) {
mode |= (S_IXUSR | S_IXGRP | S_IXOTH);
cmsys::SystemTools::SetPermissions(runTimeScript.c_str(), mode);
cmCPackLogger(cmCPackLog::LOG_OUTPUT, "Setting: " << runTimeScript
<< " to permission: " << mode << std::endl);
}
cmCPackLogger(cmCPackLog::LOG_OUTPUT,
"Setting: " << runTimeScript << " to permission: " << mode
<< std::endl);
}
if (cmsys::SystemTools::GetPermissions(appScriptName.c_str(), mode))
{
if (cmsys::SystemTools::GetPermissions(appScriptName.c_str(), mode)) {
mode |= (S_IXUSR | S_IXGRP | S_IXOTH);
cmsys::SystemTools::SetPermissions(appScriptName.c_str(), mode);
cmCPackLogger(cmCPackLog::LOG_OUTPUT, "Setting: " << appScriptName
<< " to permission: " << mode << std::endl);
}
cmCPackLogger(cmCPackLog::LOG_OUTPUT,
"Setting: " << appScriptName << " to permission: " << mode
<< std::endl);
}
std::string output;
std::string tmpFile = this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
@@ -165,56 +159,52 @@ int cmCPackOSXX11Generator::PackageFiles()
std::ostringstream dmgCmd;
dmgCmd << "\"" << this->GetOption("CPACK_INSTALLER_PROGRAM_DISK_IMAGE")
<< "\" create -ov -format UDZO -srcfolder \""
<< diskImageDirectory.c_str()
<< "\" \"" << packageFileNames[0] << "\"";
cmCPackLogger(cmCPackLog::LOG_VERBOSE,
"Compress disk image using command: "
<< dmgCmd.str().c_str() << std::endl);
<< diskImageDirectory.c_str() << "\" \"" << packageFileNames[0]
<< "\"";
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Compress disk image using command: "
<< dmgCmd.str().c_str() << std::endl);
// since we get random dashboard failures with this one
// try running it more than once
int retVal = 1;
int numTries = 10;
bool res = false;
while(numTries > 0)
{
res = cmSystemTools::RunSingleCommand(
dmgCmd.str().c_str(), &output, &output,
&retVal, 0, this->GeneratorVerbose, 0);
if ( res && !retVal )
{
while (numTries > 0) {
res =
cmSystemTools::RunSingleCommand(dmgCmd.str().c_str(), &output, &output,
&retVal, 0, this->GeneratorVerbose, 0);
if (res && !retVal) {
numTries = -1;
break;
}
}
cmSystemTools::Delay(500);
numTries--;
}
if ( !res || retVal )
{
}
if (!res || retVal) {
cmGeneratedFileStream ofs(tmpFile.c_str());
ofs << "# Run command: " << dmgCmd.str().c_str() << std::endl
<< "# Output:" << std::endl
<< output.c_str() << std::endl;
<< "# Output:" << std::endl
<< output.c_str() << std::endl;
cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem running hdiutil command: "
<< dmgCmd.str().c_str() << std::endl
<< "Please check " << tmpFile.c_str() << " for errors" << std::endl);
<< dmgCmd.str().c_str() << std::endl
<< "Please check " << tmpFile.c_str() << " for errors"
<< std::endl);
return 0;
}
}
return 1;
}
int cmCPackOSXX11Generator::InitializeInternal()
{
cmCPackLogger(cmCPackLog::LOG_DEBUG,
"cmCPackOSXX11Generator::Initialize()" << std::endl);
cmCPackLogger(cmCPackLog::LOG_DEBUG, "cmCPackOSXX11Generator::Initialize()"
<< std::endl);
std::vector<std::string> path;
std::string pkgPath = cmSystemTools::FindProgram("hdiutil", path, false);
if ( pkgPath.empty() )
{
if (pkgPath.empty()) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot find hdiutil compiler"
<< std::endl);
<< std::endl);
return 0;
}
}
this->SetOptionIfNotSet("CPACK_INSTALLER_PROGRAM_DISK_IMAGE",
pkgPath.c_str());
@@ -265,32 +255,31 @@ bool cmCPackOSXX11Generator::CopyCreateResourceFile(const std::string& name)
}
*/
bool cmCPackOSXX11Generator::CopyResourcePlistFile(const std::string& name,
const std::string& dir, const char* outputFileName /* = 0 */,
bool copyOnly /* = false */)
bool cmCPackOSXX11Generator::CopyResourcePlistFile(
const std::string& name, const std::string& dir,
const char* outputFileName /* = 0 */, bool copyOnly /* = false */)
{
std::string inFName = "CPack.";
inFName += name;
inFName += ".in";
std::string inFileName = this->FindTemplate(inFName.c_str());
if ( inFileName.empty() )
{
cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot find input file: "
<< inFName << std::endl);
if (inFileName.empty()) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Cannot find input file: " << inFName << std::endl);
return false;
}
}
if ( !outputFileName )
{
if (!outputFileName) {
outputFileName = name.c_str();
}
}
std::string destFileName = dir;
destFileName += "/";
destFileName += outputFileName;
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Configure file: "
<< inFileName.c_str() << " to " << destFileName.c_str() << std::endl);
cmCPackLogger(cmCPackLog::LOG_VERBOSE,
"Configure file: " << inFileName.c_str() << " to "
<< destFileName.c_str() << std::endl);
this->ConfigureFile(inFileName.c_str(), destFileName.c_str(), copyOnly);
return true;
}
+3 -2
View File
@@ -37,10 +37,11 @@ protected:
virtual const char* GetPackagingInstallPrefix();
virtual const char* GetOutputExtension() { return ".dmg"; }
//bool CopyCreateResourceFile(const std::string& name,
// bool CopyCreateResourceFile(const std::string& name,
// const std::string& dir);
bool CopyResourcePlistFile(const std::string& name, const std::string& dir,
const char* outputFileName = 0, bool copyOnly = false);
const char* outputFileName = 0,
bool copyOnly = false);
std::string InstallPrefix;
};
+311 -449
View File
@@ -25,8 +25,7 @@
#include <assert.h>
static inline
unsigned int getVersion(unsigned int major, unsigned int minor)
static inline unsigned int getVersion(unsigned int major, unsigned int minor)
{
assert(major < 256 && minor < 256);
return ((major & 0xFF) << 16 | minor);
@@ -55,10 +54,9 @@ int cmCPackPackageMakerGenerator::CopyInstallScript(const std::string& resdir,
dst += "/";
dst += name;
cmSystemTools::CopyFileAlways(script.c_str(), dst.c_str());
cmSystemTools::SetPermissions(dst.c_str(),0777);
cmCPackLogger(cmCPackLog::LOG_VERBOSE,
"copy script : " << script << "\ninto " << dst.c_str() <<
std::endl);
cmSystemTools::SetPermissions(dst.c_str(), 0777);
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "copy script : "
<< script << "\ninto " << dst.c_str() << std::endl);
return 1;
}
@@ -69,102 +67,80 @@ int cmCPackPackageMakerGenerator::PackageFiles()
// It is used! Is this an obsolete comment?
std::string resDir; // Where this package's resources will go.
std::string packageDirFileName
= this->GetOption("CPACK_TEMPORARY_DIRECTORY");
if (this->Components.empty())
{
std::string packageDirFileName =
this->GetOption("CPACK_TEMPORARY_DIRECTORY");
if (this->Components.empty()) {
packageDirFileName += ".pkg";
resDir = this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
resDir += "/Resources";
}
else
{
} else {
packageDirFileName += ".mpkg";
if ( !cmsys::SystemTools::MakeDirectory(packageDirFileName.c_str()))
{
if (!cmsys::SystemTools::MakeDirectory(packageDirFileName.c_str())) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"unable to create package directory "
<< packageDirFileName << std::endl);
return 0;
}
"unable to create package directory " << packageDirFileName
<< std::endl);
return 0;
}
resDir = packageDirFileName;
resDir += "/Contents";
if ( !cmsys::SystemTools::MakeDirectory(resDir.c_str()))
{
if (!cmsys::SystemTools::MakeDirectory(resDir.c_str())) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"unable to create package subdirectory " << resDir
<< std::endl);
return 0;
}
<< std::endl);
return 0;
}
resDir += "/Resources";
if ( !cmsys::SystemTools::MakeDirectory(resDir.c_str()))
{
if (!cmsys::SystemTools::MakeDirectory(resDir.c_str())) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"unable to create package subdirectory " << resDir
<< std::endl);
return 0;
}
<< std::endl);
return 0;
}
resDir += "/en.lproj";
}
}
const char* preflight = this->GetOption("CPACK_PREFLIGHT_SCRIPT");
const char* postflight = this->GetOption("CPACK_POSTFLIGHT_SCRIPT");
const char* postupgrade = this->GetOption("CPACK_POSTUPGRADE_SCRIPT");
if(this->Components.empty())
{
if (this->Components.empty()) {
// Create directory structure
std::string preflightDirName = resDir + "/PreFlight";
std::string postflightDirName = resDir + "/PostFlight";
// if preflight or postflight scripts not there create directories
// of the same name, I think this makes it work
if(!preflight)
{
if ( !cmsys::SystemTools::MakeDirectory(preflightDirName.c_str()))
{
if (!preflight) {
if (!cmsys::SystemTools::MakeDirectory(preflightDirName.c_str())) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Problem creating installer directory: "
<< preflightDirName.c_str() << std::endl);
<< preflightDirName.c_str() << std::endl);
return 0;
}
}
if(!postflight)
{
if ( !cmsys::SystemTools::MakeDirectory(postflightDirName.c_str()))
{
}
if (!postflight) {
if (!cmsys::SystemTools::MakeDirectory(postflightDirName.c_str())) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Problem creating installer directory: "
<< postflightDirName.c_str() << std::endl);
<< postflightDirName.c_str() << std::endl);
return 0;
}
}
}
// if preflight, postflight, or postupgrade are set
// then copy them into the resource directory and make
// them executable
if(preflight)
{
this->CopyInstallScript(resDir.c_str(),
preflight,
"preflight");
}
if(postflight)
{
this->CopyInstallScript(resDir.c_str(),
postflight,
"postflight");
}
if(postupgrade)
{
this->CopyInstallScript(resDir.c_str(),
postupgrade,
"postupgrade");
}
if (preflight) {
this->CopyInstallScript(resDir.c_str(), preflight, "preflight");
}
else if(postflight)
{
if (postflight) {
this->CopyInstallScript(resDir.c_str(), postflight, "postflight");
}
if (postupgrade) {
this->CopyInstallScript(resDir.c_str(), postupgrade, "postupgrade");
}
} else if (postflight) {
// create a postflight component to house the script
this->PostFlightComponent.Name = "PostFlight";
this->PostFlightComponent.DisplayName = "PostFlight";
@@ -173,121 +149,101 @@ int cmCPackPackageMakerGenerator::PackageFiles()
// empty directory for pkg contents
std::string packageDir = toplevel + "/" + PostFlightComponent.Name;
if (!cmsys::SystemTools::MakeDirectory(packageDir.c_str()))
{
if (!cmsys::SystemTools::MakeDirectory(packageDir.c_str())) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Problem creating component packages directory: "
<< packageDir.c_str() << std::endl);
<< packageDir.c_str() << std::endl);
return 0;
}
}
// create package
std::string packageFileDir = packageDirFileName + "/Contents/Packages/";
if (!cmsys::SystemTools::MakeDirectory(packageFileDir.c_str()))
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Problem creating component PostFlight Packages directory: "
<< packageFileDir.c_str() << std::endl);
if (!cmsys::SystemTools::MakeDirectory(packageFileDir.c_str())) {
cmCPackLogger(
cmCPackLog::LOG_ERROR,
"Problem creating component PostFlight Packages directory: "
<< packageFileDir.c_str() << std::endl);
return 0;
}
std::string packageFile = packageFileDir +
this->GetPackageName(PostFlightComponent);
if (!this->GenerateComponentPackage(packageFile.c_str(),
packageDir.c_str(),
PostFlightComponent))
{
}
std::string packageFile =
packageFileDir + this->GetPackageName(PostFlightComponent);
if (!this->GenerateComponentPackage(
packageFile.c_str(), packageDir.c_str(), PostFlightComponent)) {
return 0;
}
}
// copy postflight script into resource directory of .pkg
std::string resourceDir = packageFile + "/Contents/Resources";
this->CopyInstallScript(resourceDir.c_str(),
postflight,
"postflight");
}
this->CopyInstallScript(resourceDir.c_str(), postflight, "postflight");
}
if (!this->Components.empty())
{
if (!this->Components.empty()) {
// Create the directory where component packages will be built.
std::string basePackageDir = packageDirFileName;
basePackageDir += "/Contents/Packages";
if (!cmsys::SystemTools::MakeDirectory(basePackageDir.c_str()))
{
if (!cmsys::SystemTools::MakeDirectory(basePackageDir.c_str())) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Problem creating component packages directory: "
<< basePackageDir.c_str() << std::endl);
<< basePackageDir.c_str() << std::endl);
return 0;
}
}
// Create the directory where downloaded component packages will
// be placed.
const char* userUploadDirectory =
this->GetOption("CPACK_UPLOAD_DIRECTORY");
std::string uploadDirectory;
if (userUploadDirectory && *userUploadDirectory)
{
if (userUploadDirectory && *userUploadDirectory) {
uploadDirectory = userUploadDirectory;
}
else
{
uploadDirectory= this->GetOption("CPACK_PACKAGE_DIRECTORY");
} else {
uploadDirectory = this->GetOption("CPACK_PACKAGE_DIRECTORY");
uploadDirectory += "/CPackUploads";
}
}
// Create packages for each component
bool warnedAboutDownloadCompatibility = false;
std::map<std::string, cmCPackComponent>::iterator compIt;
for (compIt = this->Components.begin(); compIt != this->Components.end();
++compIt)
{
++compIt) {
std::string packageFile;
if (compIt->second.IsDownloaded)
{
if (compIt->second.IsDownloaded) {
if (this->PackageCompatibilityVersion >= getVersion(10, 5) &&
this->PackageMakerVersion >= 3.0)
{
this->PackageMakerVersion >= 3.0) {
// Build this package within the upload directory.
packageFile = uploadDirectory;
if(!cmSystemTools::FileExists(uploadDirectory.c_str()))
{
if (!cmSystemTools::MakeDirectory(uploadDirectory.c_str()))
{
if (!cmSystemTools::FileExists(uploadDirectory.c_str())) {
if (!cmSystemTools::MakeDirectory(uploadDirectory.c_str())) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Unable to create package upload directory "
<< uploadDirectory << std::endl);
<< uploadDirectory << std::endl);
return 0;
}
}
}
else if (!warnedAboutDownloadCompatibility)
{
if (this->PackageCompatibilityVersion < getVersion(10, 5))
{
} else if (!warnedAboutDownloadCompatibility) {
if (this->PackageCompatibilityVersion < getVersion(10, 5)) {
cmCPackLogger(
cmCPackLog::LOG_WARNING,
"CPack warning: please set CPACK_OSX_PACKAGE_VERSION to 10.5 "
"or greater enable downloaded packages. CPack will build a "
"non-downloaded package."
<< std::endl);
}
<< std::endl);
}
if (this->PackageMakerVersion < 3)
{
if (this->PackageMakerVersion < 3) {
cmCPackLogger(cmCPackLog::LOG_WARNING,
"CPack warning: unable to build downloaded "
"CPack warning: unable to build downloaded "
"packages with PackageMaker versions prior "
"to 3.0. CPack will build a non-downloaded package."
<< std::endl);
}
<< std::endl);
}
warnedAboutDownloadCompatibility = true;
}
}
}
if (packageFile.empty())
{
if (packageFile.empty()) {
// Build this package within the overall distribution
// metapackage.
packageFile = basePackageDir;
@@ -295,7 +251,7 @@ int cmCPackPackageMakerGenerator::PackageFiles()
// We're not downloading this component, even if the user
// requested it.
compIt->second.IsDownloaded = false;
}
}
packageFile += '/';
packageFile += GetPackageName(compIt->second);
@@ -303,97 +259,85 @@ int cmCPackPackageMakerGenerator::PackageFiles()
std::string packageDir = toplevel;
packageDir += '/';
packageDir += compIt->first;
if (!this->GenerateComponentPackage(packageFile.c_str(),
packageDir.c_str(),
compIt->second))
{
if (!this->GenerateComponentPackage(
packageFile.c_str(), packageDir.c_str(), compIt->second)) {
return 0;
}
}
}
}
this->SetOption("CPACK_MODULE_VERSION_SUFFIX", "");
// Copy or create all of the resource files we need.
if ( !this->CopyCreateResourceFile("License", resDir.c_str())
|| !this->CopyCreateResourceFile("ReadMe", resDir.c_str())
|| !this->CopyCreateResourceFile("Welcome", resDir.c_str())
|| !this->CopyResourcePlistFile("Info.plist")
|| !this->CopyResourcePlistFile("Description.plist") )
{
if (!this->CopyCreateResourceFile("License", resDir.c_str()) ||
!this->CopyCreateResourceFile("ReadMe", resDir.c_str()) ||
!this->CopyCreateResourceFile("Welcome", resDir.c_str()) ||
!this->CopyResourcePlistFile("Info.plist") ||
!this->CopyResourcePlistFile("Description.plist")) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem copying the resource files"
<< std::endl);
<< std::endl);
return 0;
}
}
if (this->Components.empty())
{
if (this->Components.empty()) {
// Use PackageMaker to build the package.
std::ostringstream pkgCmd;
pkgCmd << "\"" << this->GetOption("CPACK_INSTALLER_PROGRAM")
<< "\" -build -p \"" << packageDirFileName << "\"";
if (this->Components.empty())
{
if (this->Components.empty()) {
pkgCmd << " -f \"" << this->GetOption("CPACK_TEMPORARY_DIRECTORY");
}
else
{
} else {
pkgCmd << " -mi \"" << this->GetOption("CPACK_TEMPORARY_DIRECTORY")
<< "/packages/";
}
}
pkgCmd << "\" -r \"" << this->GetOption("CPACK_TOPLEVEL_DIRECTORY")
<< "/Resources\" -i \""
<< this->GetOption("CPACK_TOPLEVEL_DIRECTORY")
<< "/Info.plist\" -d \""
<< this->GetOption("CPACK_TOPLEVEL_DIRECTORY")
<< "/Description.plist\"";
if ( this->PackageMakerVersion > 2.0 )
{
if (this->PackageMakerVersion > 2.0) {
pkgCmd << " -v";
}
}
if (!RunPackageMaker(pkgCmd.str().c_str(), packageDirFileName.c_str()))
return 0;
}
else
{
} else {
// We have built the package in place. Generate the
// distribution.dist file to describe it for the installer.
WriteDistributionFile(packageDirFileName.c_str());
}
}
std::string tmpFile = this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
tmpFile += "/hdiutilOutput.log";
std::ostringstream dmgCmd;
dmgCmd << "\"" << this->GetOption("CPACK_INSTALLER_PROGRAM_DISK_IMAGE")
<< "\" create -ov -format UDZO -srcfolder \"" << packageDirFileName
<< "\" \"" << packageFileNames[0] << "\"";
<< "\" create -ov -format UDZO -srcfolder \"" << packageDirFileName
<< "\" \"" << packageFileNames[0] << "\"";
std::string output;
int retVal = 1;
int numTries = 10;
bool res = false;
while(numTries > 0)
{
res = cmSystemTools::RunSingleCommand(
dmgCmd.str().c_str(), &output, &output,
&retVal, 0, this->GeneratorVerbose, 0);
if ( res && !retVal )
{
while (numTries > 0) {
res =
cmSystemTools::RunSingleCommand(dmgCmd.str().c_str(), &output, &output,
&retVal, 0, this->GeneratorVerbose, 0);
if (res && !retVal) {
numTries = -1;
break;
}
}
cmSystemTools::Delay(500);
numTries--;
}
if ( !res || retVal )
{
}
if (!res || retVal) {
cmGeneratedFileStream ofs(tmpFile.c_str());
ofs << "# Run command: " << dmgCmd.str().c_str() << std::endl
<< "# Output:" << std::endl
<< output.c_str() << std::endl;
<< "# Output:" << std::endl
<< output.c_str() << std::endl;
cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem running hdiutil command: "
<< dmgCmd.str().c_str() << std::endl
<< "Please check " << tmpFile.c_str() << " for errors" << std::endl);
<< dmgCmd.str().c_str() << std::endl
<< "Please check " << tmpFile.c_str() << " for errors"
<< std::endl);
return 0;
}
}
return 1;
}
@@ -401,7 +345,7 @@ int cmCPackPackageMakerGenerator::PackageFiles()
int cmCPackPackageMakerGenerator::InitializeInternal()
{
cmCPackLogger(cmCPackLog::LOG_DEBUG,
"cmCPackPackageMakerGenerator::Initialize()" << std::endl);
"cmCPackPackageMakerGenerator::Initialize()" << std::endl);
this->SetOptionIfNotSet("CPACK_PACKAGING_INSTALL_PREFIX", "/usr");
// Starting with Xcode 4.3, PackageMaker is a separate app, and you
@@ -418,39 +362,30 @@ int cmCPackPackageMakerGenerator::InitializeInternal()
// If found, save result in the CPACK_INSTALLER_PROGRAM variable.
std::vector<std::string> paths;
paths.push_back(
"/Applications/Xcode.app/Contents/Applications"
"/PackageMaker.app/Contents/MacOS");
paths.push_back(
"/Applications/Utilities"
"/PackageMaker.app/Contents/MacOS");
paths.push_back(
"/Applications"
"/PackageMaker.app/Contents/MacOS");
paths.push_back(
"/Developer/Applications/Utilities"
"/PackageMaker.app/Contents/MacOS");
paths.push_back(
"/Developer/Applications"
"/PackageMaker.app/Contents/MacOS");
paths.push_back("/Applications/Xcode.app/Contents/Applications"
"/PackageMaker.app/Contents/MacOS");
paths.push_back("/Applications/Utilities"
"/PackageMaker.app/Contents/MacOS");
paths.push_back("/Applications"
"/PackageMaker.app/Contents/MacOS");
paths.push_back("/Developer/Applications/Utilities"
"/PackageMaker.app/Contents/MacOS");
paths.push_back("/Developer/Applications"
"/PackageMaker.app/Contents/MacOS");
std::string pkgPath;
const char *inst_program = this->GetOption("CPACK_INSTALLER_PROGRAM");
if (inst_program && *inst_program)
{
const char* inst_program = this->GetOption("CPACK_INSTALLER_PROGRAM");
if (inst_program && *inst_program) {
pkgPath = inst_program;
}
else
{
} else {
pkgPath = cmSystemTools::FindProgram("PackageMaker", paths, false);
if ( pkgPath.empty() )
{
if (pkgPath.empty()) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot find PackageMaker compiler"
<< std::endl);
<< std::endl);
return 0;
}
this->SetOptionIfNotSet("CPACK_INSTALLER_PROGRAM", pkgPath.c_str());
}
this->SetOptionIfNotSet("CPACK_INSTALLER_PROGRAM", pkgPath.c_str());
}
// Get path to the real PackageMaker, not a symlink:
pkgPath = cmSystemTools::GetRealPath(pkgPath.c_str());
@@ -461,100 +396,85 @@ int cmCPackPackageMakerGenerator::InitializeInternal()
std::string versionFile = contents_dir + "/version.plist";
if ( !cmSystemTools::FileExists(versionFile.c_str()) )
{
if (!cmSystemTools::FileExists(versionFile.c_str())) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Cannot find PackageMaker compiler version file: "
<< versionFile.c_str()
<< std::endl);
"Cannot find PackageMaker compiler version file: "
<< versionFile.c_str() << std::endl);
return 0;
}
}
cmsys::ifstream ifs(versionFile.c_str());
if ( !ifs )
{
if (!ifs) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Cannot open PackageMaker compiler version file" << std::endl);
"Cannot open PackageMaker compiler version file"
<< std::endl);
return 0;
}
}
// Check the PackageMaker version
cmsys::RegularExpression rexKey("<key>CFBundleShortVersionString</key>");
cmsys::RegularExpression rexVersion("<string>([0-9]+.[0-9.]+)</string>");
std::string line;
bool foundKey = false;
while ( cmSystemTools::GetLineFromStream(ifs, line) )
{
if ( rexKey.find(line) )
{
while (cmSystemTools::GetLineFromStream(ifs, line)) {
if (rexKey.find(line)) {
foundKey = true;
break;
}
}
if ( !foundKey )
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
}
if (!foundKey) {
cmCPackLogger(
cmCPackLog::LOG_ERROR,
"Cannot find CFBundleShortVersionString in the PackageMaker compiler "
"version file" << std::endl);
"version file"
<< std::endl);
return 0;
}
if ( !cmSystemTools::GetLineFromStream(ifs, line) ||
!rexVersion.find(line) )
{
}
if (!cmSystemTools::GetLineFromStream(ifs, line) || !rexVersion.find(line)) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Problem reading the PackageMaker compiler version file: "
<< versionFile.c_str() << std::endl);
"Problem reading the PackageMaker compiler version file: "
<< versionFile.c_str() << std::endl);
return 0;
}
}
this->PackageMakerVersion = atof(rexVersion.match(1).c_str());
if ( this->PackageMakerVersion < 1.0 )
{
if (this->PackageMakerVersion < 1.0) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Require PackageMaker 1.0 or higher"
<< std::endl);
<< std::endl);
return 0;
}
}
cmCPackLogger(cmCPackLog::LOG_DEBUG, "PackageMaker version is: "
<< this->PackageMakerVersion << std::endl);
<< this->PackageMakerVersion << std::endl);
// Determine the package compatibility version. If it wasn't
// specified by the user, we define it based on which features the
// user requested.
const char *packageCompat = this->GetOption("CPACK_OSX_PACKAGE_VERSION");
if (packageCompat && *packageCompat)
{
const char* packageCompat = this->GetOption("CPACK_OSX_PACKAGE_VERSION");
if (packageCompat && *packageCompat) {
unsigned int majorVersion = 10;
unsigned int minorVersion = 5;
int res = sscanf(packageCompat, "%u.%u", &majorVersion, &minorVersion);
if (res == 2)
{
if (res == 2) {
this->PackageCompatibilityVersion =
getVersion(majorVersion, minorVersion);
}
}
else if (this->GetOption("CPACK_DOWNLOAD_SITE"))
{
} else if (this->GetOption("CPACK_DOWNLOAD_SITE")) {
this->SetOption("CPACK_OSX_PACKAGE_VERSION", "10.5");
this->PackageCompatibilityVersion = getVersion(10, 5);
}
else if (this->GetOption("CPACK_COMPONENTS_ALL"))
{
} else if (this->GetOption("CPACK_COMPONENTS_ALL")) {
this->SetOption("CPACK_OSX_PACKAGE_VERSION", "10.4");
this->PackageCompatibilityVersion = getVersion(10, 4);
}
else
{
} else {
this->SetOption("CPACK_OSX_PACKAGE_VERSION", "10.3");
this->PackageCompatibilityVersion = getVersion(10, 3);
}
}
std::vector<std::string> no_paths;
pkgPath = cmSystemTools::FindProgram("hdiutil", no_paths, false);
if ( pkgPath.empty() )
{
if (pkgPath.empty()) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot find hdiutil compiler"
<< std::endl);
<< std::endl);
return 0;
}
}
this->SetOptionIfNotSet("CPACK_INSTALLER_PROGRAM_DISK_IMAGE",
pkgPath.c_str());
@@ -562,36 +482,34 @@ int cmCPackPackageMakerGenerator::InitializeInternal()
}
bool cmCPackPackageMakerGenerator::CopyCreateResourceFile(
const std::string& name,
const std::string& dirName)
const std::string& name, const std::string& dirName)
{
std::string uname = cmSystemTools::UpperCase(name);
std::string cpackVar = "CPACK_RESOURCE_FILE_" + uname;
const char* inFileName = this->GetOption(cpackVar.c_str());
if ( !inFileName )
{
cmCPackLogger(cmCPackLog::LOG_ERROR, "CPack option: " << cpackVar.c_str()
<< " not specified. It should point to "
<< (!name.empty() ? name : "<empty>")
<< ".rtf, " << name
<< ".html, or " << name << ".txt file" << std::endl);
if (!inFileName) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "CPack option: "
<< cpackVar.c_str()
<< " not specified. It should point to "
<< (!name.empty() ? name : "<empty>") << ".rtf, " << name
<< ".html, or " << name << ".txt file" << std::endl);
return false;
}
if ( !cmSystemTools::FileExists(inFileName) )
{
}
if (!cmSystemTools::FileExists(inFileName)) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot find "
<< (!name.empty() ? name : "<empty>")
<< " resource file: " << inFileName << std::endl);
<< (!name.empty() ? name : "<empty>")
<< " resource file: " << inFileName << std::endl);
return false;
}
}
std::string ext = cmSystemTools::GetFilenameLastExtension(inFileName);
if ( ext != ".rtfd" && ext != ".rtf" && ext != ".html" && ext != ".txt" )
{
cmCPackLogger(cmCPackLog::LOG_ERROR, "Bad file extension specified: "
<< ext << ". Currently only .rtfd, .rtf, .html, and .txt files allowed."
<< std::endl);
if (ext != ".rtfd" && ext != ".rtf" && ext != ".html" && ext != ".txt") {
cmCPackLogger(
cmCPackLog::LOG_ERROR, "Bad file extension specified: "
<< ext
<< ". Currently only .rtfd, .rtf, .html, and .txt files allowed."
<< std::endl);
return false;
}
}
std::string destFileName = dirName;
destFileName += '/';
@@ -603,44 +521,42 @@ bool cmCPackPackageMakerGenerator::CopyCreateResourceFile(
(name + ext).c_str());
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Configure file: "
<< (inFileName ? inFileName : "(NULL)")
<< " to " << destFileName.c_str() << std::endl);
<< (inFileName ? inFileName : "(NULL)") << " to "
<< destFileName.c_str() << std::endl);
this->ConfigureFile(inFileName, destFileName.c_str());
return true;
}
bool cmCPackPackageMakerGenerator::CopyResourcePlistFile(
const std::string& name,
const char* outName)
const std::string& name, const char* outName)
{
if (!outName)
{
if (!outName) {
outName = name.c_str();
}
}
std::string inFName = "CPack.";
inFName += name;
inFName += ".in";
std::string inFileName = this->FindTemplate(inFName.c_str());
if ( inFileName.empty() )
{
cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot find input file: "
<< inFName << std::endl);
if (inFileName.empty()) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Cannot find input file: " << inFName << std::endl);
return false;
}
}
std::string destFileName = this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
destFileName += "/";
destFileName += outName;
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Configure file: "
<< inFileName.c_str() << " to " << destFileName.c_str() << std::endl);
cmCPackLogger(cmCPackLog::LOG_VERBOSE,
"Configure file: " << inFileName.c_str() << " to "
<< destFileName.c_str() << std::endl);
this->ConfigureFile(inFileName.c_str(), destFileName.c_str());
return true;
}
bool cmCPackPackageMakerGenerator::RunPackageMaker(const char *command,
const char *packageFile)
bool cmCPackPackageMakerGenerator::RunPackageMaker(const char* command,
const char* packageFile)
{
std::string tmpFile = this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
tmpFile += "/PackageMakerOutput.log";
@@ -649,78 +565,65 @@ bool cmCPackPackageMakerGenerator::RunPackageMaker(const char *command,
std::string output;
int retVal = 1;
bool res = cmSystemTools::RunSingleCommand(
command, &output, &output,
&retVal, 0, this->GeneratorVerbose, 0);
command, &output, &output, &retVal, 0, this->GeneratorVerbose, 0);
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Done running package maker"
<< std::endl);
if ( !res || retVal )
{
<< std::endl);
if (!res || retVal) {
cmGeneratedFileStream ofs(tmpFile.c_str());
ofs << "# Run command: " << command << std::endl
<< "# Output:" << std::endl
<< output.c_str() << std::endl;
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Problem running PackageMaker command: " << command
<< std::endl << "Please check " << tmpFile.c_str() << " for errors"
<< std::endl);
<< "# Output:" << std::endl
<< output.c_str() << std::endl;
cmCPackLogger(
cmCPackLog::LOG_ERROR, "Problem running PackageMaker command: "
<< command << std::endl
<< "Please check " << tmpFile.c_str() << " for errors" << std::endl);
return false;
}
}
// sometimes the command finishes but the directory is not yet
// created, so try 10 times to see if it shows up
int tries = 10;
while(tries > 0 &&
!cmSystemTools::FileExists(packageFile))
{
while (tries > 0 && !cmSystemTools::FileExists(packageFile)) {
cmSystemTools::Delay(500);
tries--;
}
if(!cmSystemTools::FileExists(packageFile))
{
cmCPackLogger(
cmCPackLog::LOG_ERROR,
"Problem running PackageMaker command: " << command
<< std::endl << "Package not created: " << packageFile
<< std::endl);
}
if (!cmSystemTools::FileExists(packageFile)) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Problem running PackageMaker command: "
<< command << std::endl
<< "Package not created: " << packageFile << std::endl);
return false;
}
}
return true;
}
std::string
cmCPackPackageMakerGenerator::GetPackageName(const cmCPackComponent& component)
std::string cmCPackPackageMakerGenerator::GetPackageName(
const cmCPackComponent& component)
{
if (component.ArchiveFile.empty())
{
if (component.ArchiveFile.empty()) {
std::string packagesDir = this->GetOption("CPACK_TEMPORARY_DIRECTORY");
packagesDir += ".dummy";
std::ostringstream out;
out << cmSystemTools::GetFilenameWithoutLastExtension(packagesDir)
<< "-" << component.Name << ".pkg";
out << cmSystemTools::GetFilenameWithoutLastExtension(packagesDir) << "-"
<< component.Name << ".pkg";
return out.str();
}
else
{
} else {
return component.ArchiveFile + ".pkg";
}
}
}
bool
cmCPackPackageMakerGenerator::
GenerateComponentPackage(const char *packageFile,
const char *packageDir,
const cmCPackComponent& component)
bool cmCPackPackageMakerGenerator::GenerateComponentPackage(
const char* packageFile, const char* packageDir,
const cmCPackComponent& component)
{
cmCPackLogger(cmCPackLog::LOG_OUTPUT,
"- Building component package: " <<
packageFile << std::endl);
cmCPackLogger(cmCPackLog::LOG_OUTPUT, "- Building component package: "
<< packageFile << std::endl);
// The command that will be used to run PackageMaker
std::ostringstream pkgCmd;
if (this->PackageCompatibilityVersion < getVersion(10, 5) ||
this->PackageMakerVersion < 3.0)
{
this->PackageMakerVersion < 3.0) {
// Create Description.plist and Info.plist files for normal Mac OS
// X packages, which work on Mac OS X 10.3 and newer.
std::string descriptionFile = this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
@@ -750,20 +653,17 @@ GenerateComponentPackage(const char *packageFile,
moduleVersionSuffix.c_str());
std::string infoFileName = component.Name;
infoFileName += "-Info.plist";
if (!this->CopyResourcePlistFile("Info.plist", infoFileName.c_str()))
{
if (!this->CopyResourcePlistFile("Info.plist", infoFileName.c_str())) {
return false;
}
}
pkgCmd << "\"" << this->GetOption("CPACK_INSTALLER_PROGRAM")
<< "\" -build -p \"" << packageFile << "\""
<< " -f \"" << packageDir << "\""
<< " -i \"" << this->GetOption("CPACK_TOPLEVEL_DIRECTORY")
<< "/" << infoFileName << "\""
<< " -i \"" << this->GetOption("CPACK_TOPLEVEL_DIRECTORY") << "/"
<< infoFileName << "\""
<< " -d \"" << descriptionFile << "\"";
}
else
{
} else {
// Create a "flat" package on Mac OS X 10.5 and newer. Flat
// packages are stored in a single file, rather than a directory
// like normal packages, and can be downloaded by the installer
@@ -778,27 +678,25 @@ GenerateComponentPackage(const char *packageFile,
pkgCmd << "\"" << this->GetOption("CPACK_INSTALLER_PROGRAM")
<< "\" --root \"" << packageDir << "\""
<< " --id " << pkgId
<< " --target " << this->GetOption("CPACK_OSX_PACKAGE_VERSION")
<< " --out \"" << packageFile << "\"";
}
<< " --id " << pkgId << " --target "
<< this->GetOption("CPACK_OSX_PACKAGE_VERSION") << " --out \""
<< packageFile << "\"";
}
// Run PackageMaker
return RunPackageMaker(pkgCmd.str().c_str(), packageFile);
}
void
cmCPackPackageMakerGenerator::
WriteDistributionFile(const char* metapackageFile)
void cmCPackPackageMakerGenerator::WriteDistributionFile(
const char* metapackageFile)
{
std::string distributionTemplate
= this->FindTemplate("CPack.distribution.dist.in");
if ( distributionTemplate.empty() )
{
std::string distributionTemplate =
this->FindTemplate("CPack.distribution.dist.in");
if (distributionTemplate.empty()) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot find input file: "
<< distributionTemplate << std::endl);
<< distributionTemplate << std::endl);
return;
}
}
std::string distributionFile = metapackageFile;
distributionFile += "/Contents/distribution.dist";
@@ -811,102 +709,83 @@ WriteDistributionFile(const char* metapackageFile)
// Emit the outline for the groups
std::map<std::string, cmCPackComponentGroup>::iterator groupIt;
for (groupIt = this->ComponentGroups.begin();
groupIt != this->ComponentGroups.end();
++groupIt)
{
if (groupIt->second.ParentGroup == 0)
{
groupIt != this->ComponentGroups.end(); ++groupIt) {
if (groupIt->second.ParentGroup == 0) {
CreateChoiceOutline(groupIt->second, choiceOut);
}
}
}
// Emit the outline for the non-grouped components
std::map<std::string, cmCPackComponent>::iterator compIt;
for (compIt = this->Components.begin(); compIt != this->Components.end();
++compIt)
{
if (!compIt->second.Group)
{
++compIt) {
if (!compIt->second.Group) {
choiceOut << "<line choice=\"" << compIt->first << "Choice\"></line>"
<< std::endl;
}
}
if(!this->PostFlightComponent.Name.empty())
{
choiceOut << "<line choice=\"" << PostFlightComponent.Name
<< "Choice\"></line>" << std::endl;
}
}
if (!this->PostFlightComponent.Name.empty()) {
choiceOut << "<line choice=\"" << PostFlightComponent.Name
<< "Choice\"></line>" << std::endl;
}
choiceOut << "</choices-outline>" << std::endl;
// Create the actual choices
for (groupIt = this->ComponentGroups.begin();
groupIt != this->ComponentGroups.end();
++groupIt)
{
groupIt != this->ComponentGroups.end(); ++groupIt) {
CreateChoice(groupIt->second, choiceOut);
}
}
for (compIt = this->Components.begin(); compIt != this->Components.end();
++compIt)
{
++compIt) {
CreateChoice(compIt->second, choiceOut);
}
}
if(!this->PostFlightComponent.Name.empty())
{
if (!this->PostFlightComponent.Name.empty()) {
CreateChoice(PostFlightComponent, choiceOut);
}
}
this->SetOption("CPACK_PACKAGEMAKER_CHOICES", choiceOut.str().c_str());
// Create the distribution.dist file in the metapackage to turn it
// into a distribution package.
this->ConfigureFile(distributionTemplate.c_str(),
distributionFile.c_str());
this->ConfigureFile(distributionTemplate.c_str(), distributionFile.c_str());
}
void
cmCPackPackageMakerGenerator::
CreateChoiceOutline(const cmCPackComponentGroup& group,
std::ostringstream& out)
void cmCPackPackageMakerGenerator::CreateChoiceOutline(
const cmCPackComponentGroup& group, std::ostringstream& out)
{
out << "<line choice=\"" << group.Name << "Choice\">" << std::endl;
std::vector<cmCPackComponentGroup*>::const_iterator groupIt;
for (groupIt = group.Subgroups.begin(); groupIt != group.Subgroups.end();
++groupIt)
{
++groupIt) {
CreateChoiceOutline(**groupIt, out);
}
}
std::vector<cmCPackComponent*>::const_iterator compIt;
for (compIt = group.Components.begin(); compIt != group.Components.end();
++compIt)
{
++compIt) {
out << " <line choice=\"" << (*compIt)->Name << "Choice\"></line>"
<< std::endl;
}
}
out << "</line>" << std::endl;
}
void
cmCPackPackageMakerGenerator::CreateChoice(const cmCPackComponentGroup& group,
std::ostringstream& out)
void cmCPackPackageMakerGenerator::CreateChoice(
const cmCPackComponentGroup& group, std::ostringstream& out)
{
out << "<choice id=\"" << group.Name << "Choice\" "
<< "title=\"" << group.DisplayName << "\" "
<< "start_selected=\"true\" "
<< "start_enabled=\"true\" "
<< "start_visible=\"true\" ";
if (!group.Description.empty())
{
out << "description=\"" << EscapeForXML(group.Description)
<< "\"";
}
if (!group.Description.empty()) {
out << "description=\"" << EscapeForXML(group.Description) << "\"";
}
out << "></choice>" << std::endl;
}
void
cmCPackPackageMakerGenerator::CreateChoice(const cmCPackComponent& component,
std::ostringstream& out)
void cmCPackPackageMakerGenerator::CreateChoice(
const cmCPackComponent& component, std::ostringstream& out)
{
std::string packageId = "com.";
packageId += this->GetOption("CPACK_PACKAGE_VENDOR");
@@ -918,21 +797,18 @@ cmCPackPackageMakerGenerator::CreateChoice(const cmCPackComponent& component,
out << "<choice id=\"" << component.Name << "Choice\" "
<< "title=\"" << component.DisplayName << "\" "
<< "start_selected=\""
<< (component.IsDisabledByDefault &&
!component.IsRequired? "false" : "true")
<< (component.IsDisabledByDefault && !component.IsRequired ? "false"
: "true")
<< "\" "
<< "start_enabled=\""
<< (component.IsRequired? "false" : "true")
<< "start_enabled=\"" << (component.IsRequired ? "false" : "true")
<< "\" "
<< "start_visible=\"" << (component.IsHidden? "false" : "true") << "\" ";
if (!component.Description.empty())
{
out << "description=\"" << EscapeForXML(component.Description)
<< "\" ";
}
<< "start_visible=\"" << (component.IsHidden ? "false" : "true")
<< "\" ";
if (!component.Description.empty()) {
out << "description=\"" << EscapeForXML(component.Description) << "\" ";
}
if (!component.Dependencies.empty() ||
!component.ReverseDependencies.empty())
{
!component.ReverseDependencies.empty()) {
// The "selected" expression is evaluated each time any choice is
// selected, for all choices *except* the one that the user
// selected. A component is marked selected if it has been
@@ -948,12 +824,12 @@ cmCPackPackageMakerGenerator::CreateChoice(const cmCPackComponent& component,
// on (B and A), while selecting something that depends on C--either D
// or E--will automatically cause C to get selected.
out << "selected=\"my.choice.selected";
std::set<const cmCPackComponent *> visited;
std::set<const cmCPackComponent*> visited;
AddDependencyAttributes(component, visited, out);
visited.clear();
AddReverseDependencyAttributes(component, visited, out);
out << "\"";
}
}
out << ">" << std::endl;
out << " <pkg-ref id=\"" << packageId << "\"></pkg-ref>" << std::endl;
out << "</choice>" << std::endl;
@@ -968,68 +844,54 @@ cmCPackPackageMakerGenerator::CreateChoice(const cmCPackComponent& component,
dirName += '/';
dirName += component.Name;
dirName += this->GetOption("CPACK_PACKAGING_INSTALL_PREFIX");
unsigned long installedSize
= component.GetInstalledSizeInKbytes(dirName.c_str());
unsigned long installedSize =
component.GetInstalledSizeInKbytes(dirName.c_str());
out << "<pkg-ref id=\"" << packageId << "\" "
<< "version=\"" << this->GetOption("CPACK_PACKAGE_VERSION") << "\" "
<< "installKBytes=\"" << installedSize << "\" "
<< "auth=\"Admin\" onConclusion=\"None\">";
if (component.IsDownloaded)
{
if (component.IsDownloaded) {
out << this->GetOption("CPACK_DOWNLOAD_SITE")
<< this->GetPackageName(component);
}
else
{
} else {
out << "file:./" << relativePackageLocation;
}
}
out << "</pkg-ref>" << std::endl;
}
void
cmCPackPackageMakerGenerator::
AddDependencyAttributes(const cmCPackComponent& component,
std::set<const cmCPackComponent *>& visited,
std::ostringstream& out)
void cmCPackPackageMakerGenerator::AddDependencyAttributes(
const cmCPackComponent& component,
std::set<const cmCPackComponent*>& visited, std::ostringstream& out)
{
if (visited.find(&component) != visited.end())
{
if (visited.find(&component) != visited.end()) {
return;
}
}
visited.insert(&component);
std::vector<cmCPackComponent *>::const_iterator dependIt;
std::vector<cmCPackComponent*>::const_iterator dependIt;
for (dependIt = component.Dependencies.begin();
dependIt != component.Dependencies.end();
++dependIt)
{
out << " &amp;&amp; choices['" <<
(*dependIt)->Name << "Choice'].selected";
dependIt != component.Dependencies.end(); ++dependIt) {
out << " &amp;&amp; choices['" << (*dependIt)->Name << "Choice'].selected";
AddDependencyAttributes(**dependIt, visited, out);
}
}
}
void
cmCPackPackageMakerGenerator::
AddReverseDependencyAttributes(const cmCPackComponent& component,
std::set<const cmCPackComponent *>& visited,
std::ostringstream& out)
void cmCPackPackageMakerGenerator::AddReverseDependencyAttributes(
const cmCPackComponent& component,
std::set<const cmCPackComponent*>& visited, std::ostringstream& out)
{
if (visited.find(&component) != visited.end())
{
if (visited.find(&component) != visited.end()) {
return;
}
}
visited.insert(&component);
std::vector<cmCPackComponent *>::const_iterator dependIt;
std::vector<cmCPackComponent*>::const_iterator dependIt;
for (dependIt = component.ReverseDependencies.begin();
dependIt != component.ReverseDependencies.end();
++dependIt)
{
dependIt != component.ReverseDependencies.end(); ++dependIt) {
out << " || choices['" << (*dependIt)->Name << "Choice'].selected";
AddReverseDependencyAttributes(**dependIt, visited, out);
}
}
}
std::string cmCPackPackageMakerGenerator::EscapeForXML(std::string str)
+8 -10
View File
@@ -37,8 +37,7 @@ public:
virtual bool SupportsComponentInstallation() const;
protected:
int CopyInstallScript(const std::string& resdir,
const std::string& script,
int CopyInstallScript(const std::string& resdir, const std::string& script,
const std::string& name);
virtual int InitializeInternal();
int PackageFiles();
@@ -57,7 +56,7 @@ protected:
// Run PackageMaker with the given command line, which will (if
// successful) produce the given package file. Returns true if
// PackageMaker succeeds, false otherwise.
bool RunPackageMaker(const char *command, const char *packageFile);
bool RunPackageMaker(const char* command, const char* packageFile);
// Retrieve the name of package file that will be generated for this
// component. The name is just the file name with extension, and
@@ -68,8 +67,8 @@ protected:
// component. All of the files within this component are stored in
// the directory packageDir. Returns true if successful, false
// otherwise.
bool GenerateComponentPackage(const char *packageFile,
const char *packageDir,
bool GenerateComponentPackage(const char* packageFile,
const char* packageDir,
const cmCPackComponent& component);
// Writes a distribution.dist file, which turns a metapackage into a
@@ -82,15 +81,14 @@ protected:
// Subroutine of WriteDistributionFile that writes out the
// dependency attributes for inter-component dependencies.
void AddDependencyAttributes(const cmCPackComponent& component,
std::set<const cmCPackComponent *>& visited,
std::set<const cmCPackComponent*>& visited,
std::ostringstream& out);
// Subroutine of WriteDistributionFile that writes out the
// reverse dependency attributes for inter-component dependencies.
void
AddReverseDependencyAttributes(const cmCPackComponent& component,
std::set<const cmCPackComponent *>& visited,
std::ostringstream& out);
void AddReverseDependencyAttributes(
const cmCPackComponent& component,
std::set<const cmCPackComponent*>& visited, std::ostringstream& out);
// Generates XML that encodes the hierarchy of component groups and
// their components in a form that can be used by distribution
+87 -119
View File
@@ -25,24 +25,23 @@ cmCPackRPMGenerator::~cmCPackRPMGenerator()
int cmCPackRPMGenerator::InitializeInternal()
{
this->SetOptionIfNotSet("CPACK_PACKAGING_INSTALL_PREFIX", "/usr");
if (cmSystemTools::IsOff(this->GetOption("CPACK_SET_DESTDIR")))
{
if (cmSystemTools::IsOff(this->GetOption("CPACK_SET_DESTDIR"))) {
this->SetOption("CPACK_SET_DESTDIR", "I_ON");
}
}
/* Replace space in CPACK_PACKAGE_NAME in order to avoid
* rpmbuild scream on unwanted space in filename issue
* Moreover RPM file do not usually embed space in filename
*/
if (this->GetOption("CPACK_PACKAGE_NAME")) {
std::string packageName=this->GetOption("CPACK_PACKAGE_NAME");
cmSystemTools::ReplaceString(packageName," ","-");
this->SetOption("CPACK_PACKAGE_NAME",packageName.c_str());
std::string packageName = this->GetOption("CPACK_PACKAGE_NAME");
cmSystemTools::ReplaceString(packageName, " ", "-");
this->SetOption("CPACK_PACKAGE_NAME", packageName.c_str());
}
/* same for CPACK_PACKAGE_FILE_NAME */
if (this->GetOption("CPACK_PACKAGE_FILE_NAME")) {
std::string packageName=this->GetOption("CPACK_PACKAGE_FILE_NAME");
cmSystemTools::ReplaceString(packageName," ","-");
this->SetOption("CPACK_PACKAGE_FILE_NAME",packageName.c_str());
std::string packageName = this->GetOption("CPACK_PACKAGE_FILE_NAME");
cmSystemTools::ReplaceString(packageName, " ", "-");
this->SetOption("CPACK_PACKAGE_FILE_NAME", packageName.c_str());
}
return this->Superclass::InitializeInternal();
}
@@ -53,14 +52,13 @@ void cmCPackRPMGenerator::AddGeneratedPackageNames()
std::string fileNames(this->GetOption("GEN_CPACK_OUTPUT_FILES"));
const char sep = ';';
std::string::size_type pos1 = 0;
std::string::size_type pos2 = fileNames.find(sep, pos1+1);
while(pos2 != std::string::npos)
{
packageFileNames.push_back(fileNames.substr(pos1, pos2-pos1));
pos1 = pos2+1;
pos2 = fileNames.find(sep, pos1+1);
}
packageFileNames.push_back(fileNames.substr(pos1, pos2-pos1));
std::string::size_type pos2 = fileNames.find(sep, pos1 + 1);
while (pos2 != std::string::npos) {
packageFileNames.push_back(fileNames.substr(pos1, pos2 - pos1));
pos1 = pos2 + 1;
pos2 = fileNames.find(sep, pos1 + 1);
}
packageFileNames.push_back(fileNames.substr(pos1, pos2 - pos1));
}
int cmCPackRPMGenerator::PackageOnePack(std::string initialToplevel,
@@ -69,38 +67,33 @@ int cmCPackRPMGenerator::PackageOnePack(std::string initialToplevel,
int retval = 1;
// Begin the archive for this pack
std::string localToplevel(initialToplevel);
std::string packageFileName(
cmSystemTools::GetParentDirectory(toplevel)
);
std::string packageFileName(cmSystemTools::GetParentDirectory(toplevel));
std::string outputFileName(
GetComponentPackageFileName(this->GetOption("CPACK_PACKAGE_FILE_NAME"),
packageName,
true)
+ this->GetOutputExtension()
);
GetComponentPackageFileName(this->GetOption("CPACK_PACKAGE_FILE_NAME"),
packageName, true) +
this->GetOutputExtension());
localToplevel += "/"+ packageName;
localToplevel += "/" + packageName;
/* replace the TEMP DIRECTORY with the component one */
this->SetOption("CPACK_TEMPORARY_DIRECTORY",localToplevel.c_str());
packageFileName += "/"+ outputFileName;
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());
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());
// Tell CPackRPM.cmake the name of the component NAME.
this->SetOption("CPACK_RPM_PACKAGE_COMPONENT",packageName.c_str());
this->SetOption("CPACK_RPM_PACKAGE_COMPONENT", packageName.c_str());
// Tell CPackRPM.cmake the path where the component is.
std::string component_path = "/";
component_path += packageName;
this->SetOption("CPACK_RPM_PACKAGE_COMPONENT_PART_PATH",
component_path.c_str());
if (!this->ReadListFile("CPackRPM.cmake"))
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error while execution CPackRPM.cmake" << std::endl);
if (!this->ReadListFile("CPackRPM.cmake")) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Error while execution CPackRPM.cmake"
<< std::endl);
retval = 0;
}
}
return retval;
}
@@ -115,56 +108,48 @@ int cmCPackRPMGenerator::PackageComponents(bool ignoreGroup)
// The default behavior is to have one package by component group
// unless CPACK_COMPONENTS_IGNORE_GROUP is specified.
if (!ignoreGroup)
{
if (!ignoreGroup) {
std::map<std::string, cmCPackComponentGroup>::iterator compGIt;
for (compGIt=this->ComponentGroups.begin();
compGIt!=this->ComponentGroups.end(); ++compGIt)
{
for (compGIt = this->ComponentGroups.begin();
compGIt != this->ComponentGroups.end(); ++compGIt) {
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Packaging component group: "
<< compGIt->first
<< std::endl);
retval &= PackageOnePack(initialTopLevel,compGIt->first);
}
<< compGIt->first << std::endl);
retval &= PackageOnePack(initialTopLevel, compGIt->first);
}
// Handle Orphan components (components not belonging to any groups)
std::map<std::string, cmCPackComponent>::iterator compIt;
for (compIt=this->Components.begin();
compIt!=this->Components.end(); ++compIt )
{
for (compIt = this->Components.begin(); compIt != this->Components.end();
++compIt) {
// Does the component belong to a group?
if (compIt->second.Group==NULL)
{
cmCPackLogger(cmCPackLog::LOG_VERBOSE,
"Component <"
if (compIt->second.Group == NULL) {
cmCPackLogger(
cmCPackLog::LOG_VERBOSE, "Component <"
<< compIt->second.Name
<< "> does not belong to any group, package it separately."
<< std::endl);
retval &= PackageOnePack(initialTopLevel,compIt->first);
}
retval &= PackageOnePack(initialTopLevel, compIt->first);
}
}
}
// CPACK_COMPONENTS_IGNORE_GROUPS is set
// We build 1 package per component
else
{
else {
std::map<std::string, cmCPackComponent>::iterator compIt;
for (compIt=this->Components.begin();
compIt!=this->Components.end(); ++compIt )
{
retval &= PackageOnePack(initialTopLevel,compIt->first);
}
for (compIt = this->Components.begin(); compIt != this->Components.end();
++compIt) {
retval &= PackageOnePack(initialTopLevel, compIt->first);
}
}
if(retval)
{
if (retval) {
AddGeneratedPackageNames();
}
}
return retval;
}
int cmCPackRPMGenerator::PackageComponentsAllInOne(
const std::string& compInstDirName)
const std::string& compInstDirName)
{
int retval = 1;
/* Reset package file name list it will be populated during the
@@ -175,98 +160,84 @@ int cmCPackRPMGenerator::PackageComponentsAllInOne(
cmCPackLogger(cmCPackLog::LOG_VERBOSE,
"Packaging all groups in one package..."
"(CPACK_COMPONENTS_ALL_[GROUPS_]IN_ONE_PACKAGE is set)"
<< std::endl);
<< std::endl);
// The ALL GROUPS in ONE package case
std::string localToplevel(initialTopLevel);
std::string packageFileName(
cmSystemTools::GetParentDirectory(toplevel)
);
std::string packageFileName(cmSystemTools::GetParentDirectory(toplevel));
std::string outputFileName(
std::string(this->GetOption("CPACK_PACKAGE_FILE_NAME"))
+ this->GetOutputExtension()
);
std::string(this->GetOption("CPACK_PACKAGE_FILE_NAME")) +
this->GetOutputExtension());
// all GROUP in one vs all COMPONENT in one
localToplevel += "/"+compInstDirName;
localToplevel += "/" + compInstDirName;
/* replace the TEMP DIRECTORY with the component one */
this->SetOption("CPACK_TEMPORARY_DIRECTORY",localToplevel.c_str());
packageFileName += "/"+ outputFileName;
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());
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());
packageFileName.c_str());
if(!compInstDirName.empty())
{
if (!compInstDirName.empty()) {
// Tell CPackRPM.cmake the path where the component is.
std::string component_path = "/";
component_path += compInstDirName;
this->SetOption("CPACK_RPM_PACKAGE_COMPONENT_PART_PATH",
component_path.c_str());
}
}
if (this->ReadListFile("CPackRPM.cmake"))
{
if (this->ReadListFile("CPackRPM.cmake")) {
AddGeneratedPackageNames();
}
else
{
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Error while execution CPackRPM.cmake" << std::endl);
} else {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Error while execution CPackRPM.cmake"
<< std::endl);
retval = 0;
}
}
return retval;
}
int cmCPackRPMGenerator::PackageFiles()
{
cmCPackLogger(cmCPackLog::LOG_DEBUG, "Toplevel: "
<< toplevel << std::endl);
cmCPackLogger(cmCPackLog::LOG_DEBUG, "Toplevel: " << toplevel << std::endl);
/* Are we in the component packaging case */
if (WantsComponentInstallation()) {
// CASE 1 : COMPONENT ALL-IN-ONE package
// If ALL COMPONENTS in ONE package has been requested
// then the package file is unique and should be open here.
if (componentPackageMethod == ONE_PACKAGE)
{
if (componentPackageMethod == ONE_PACKAGE) {
return PackageComponentsAllInOne("ALL_COMPONENTS_IN_ONE");
}
}
// 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
{
else {
return PackageComponents(componentPackageMethod ==
ONE_PACKAGE_PER_COMPONENT);
}
}
}
// CASE 3 : NON COMPONENT package.
else
{
else {
return PackageComponentsAllInOne("");
}
}
}
bool cmCPackRPMGenerator::SupportsComponentInstallation() const
{
if (IsOn("CPACK_RPM_COMPONENT_INSTALL"))
{
return true;
}
else
{
return false;
}
{
if (IsOn("CPACK_RPM_COMPONENT_INSTALL")) {
return true;
} else {
return false;
}
}
std::string cmCPackRPMGenerator::GetComponentInstallDirNameSuffix(
const std::string& componentName)
{
const std::string& componentName)
{
if (componentPackageMethod == ONE_PACKAGE_PER_COMPONENT) {
return componentName;
}
@@ -276,14 +247,11 @@ std::string cmCPackRPMGenerator::GetComponentInstallDirNameSuffix(
}
// We have to find the name of the COMPONENT GROUP
// the current COMPONENT belongs to.
std::string groupVar = "CPACK_COMPONENT_" +
cmSystemTools::UpperCase(componentName) + "_GROUP";
if (NULL != GetOption(groupVar))
{
return std::string(GetOption(groupVar));
}
else
{
return componentName;
}
std::string groupVar =
"CPACK_COMPONENT_" + cmSystemTools::UpperCase(componentName) + "_GROUP";
if (NULL != GetOption(groupVar)) {
return std::string(GetOption(groupVar));
} else {
return componentName;
}
}
+3 -3
View File
@@ -35,7 +35,7 @@ public:
virtual ~cmCPackRPMGenerator();
static bool CanGenerate()
{
{
#ifdef __APPLE__
// on MacOS enable CPackRPM iff rpmbuild is found
std::vector<std::string> locations;
@@ -46,7 +46,7 @@ public:
// legacy behavior on other systems
return true;
#endif
}
}
protected:
virtual int InitializeInternal();
@@ -69,7 +69,7 @@ protected:
virtual const char* GetOutputExtension() { return ".rpm"; }
virtual bool SupportsComponentInstallation() const;
virtual std::string GetComponentInstallDirNameSuffix(
const std::string& componentName);
const std::string& componentName);
void AddGeneratedPackageNames();
};
+27 -34
View File
@@ -37,12 +37,11 @@ int cmCPackSTGZGenerator::InitializeInternal()
this->SetOptionIfNotSet("CPACK_INCLUDE_TOPLEVEL_DIRECTORY", "0");
std::string inFile = this->FindTemplate("CPack.STGZ_Header.sh.in");
if ( inFile.empty() )
{
cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot find template file: "
<< inFile << std::endl);
if (inFile.empty()) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Cannot find template file: " << inFile << std::endl);
return 0;
}
}
this->SetOptionIfNotSet("CPACK_STGZ_HEADER_FILE", inFile.c_str());
this->SetOptionIfNotSet("CPACK_AT_SIGN", "@");
@@ -51,28 +50,26 @@ int cmCPackSTGZGenerator::InitializeInternal()
int cmCPackSTGZGenerator::PackageFiles()
{
bool retval = true;
if ( !this->Superclass::PackageFiles() )
{
bool retval = true;
if (!this->Superclass::PackageFiles()) {
return 0;
}
}
/* TGZ generator (our Superclass) may
* have generated several packages (component packaging)
* so we must iterate over generated packages.
*/
for (std::vector<std::string>::iterator it=packageFileNames.begin();
it != packageFileNames.end(); ++it)
{
for (std::vector<std::string>::iterator it = packageFileNames.begin();
it != packageFileNames.end(); ++it) {
retval &= cmSystemTools::SetPermissions((*it).c_str(),
#if defined( _MSC_VER ) || defined( __MINGW32__ )
S_IREAD | S_IWRITE | S_IEXEC
#if defined(_MSC_VER) || defined(__MINGW32__)
S_IREAD | S_IWRITE | S_IEXEC
#else
S_IRUSR | S_IWUSR | S_IXUSR |
S_IRGRP | S_IWGRP | S_IXGRP |
S_IROTH | S_IWOTH | S_IXOTH
S_IRUSR | S_IWUSR | S_IXUSR |
S_IRGRP | S_IWGRP | S_IXGRP |
S_IROTH | S_IWOTH | S_IXOTH
#endif
);
);
}
return retval;
}
@@ -87,10 +84,9 @@ int cmCPackSTGZGenerator::GenerateHeader(std::ostream* os)
std::string line;
cmsys::ifstream ilfs(inLicFile.c_str());
std::string licenseText;
while ( cmSystemTools::GetLineFromStream(ilfs, line) )
{
while (cmSystemTools::GetLineFromStream(ilfs, line)) {
licenseText += line + "\n";
}
}
this->SetOptionIfNotSet("CPACK_RESOURCE_FILE_LICENSE_CONTENT",
licenseText.c_str());
@@ -100,10 +96,9 @@ int cmCPackSTGZGenerator::GenerateHeader(std::ostream* os)
std::string inFile = this->GetOption("CPACK_STGZ_HEADER_FILE");
cmsys::ifstream ifs(inFile.c_str());
std::string packageHeaderText;
while ( cmSystemTools::GetLineFromStream(ifs, line) )
{
while (cmSystemTools::GetLineFromStream(ifs, line)) {
packageHeaderText += line + "\n";
}
}
// Configure in the values
std::string res;
@@ -111,17 +106,15 @@ int cmCPackSTGZGenerator::GenerateHeader(std::ostream* os)
// Count the lines
const char* ptr = res.c_str();
while ( *ptr )
{
if ( *ptr == '\n' )
{
counter ++;
}
++ptr;
while (*ptr) {
if (*ptr == '\n') {
counter++;
}
counter ++;
cmCPackLogger(cmCPackLog::LOG_DEBUG,
"Number of lines: " << counter << std::endl);
++ptr;
}
counter++;
cmCPackLogger(cmCPackLog::LOG_DEBUG, "Number of lines: " << counter
<< std::endl);
char buffer[1024];
sprintf(buffer, "%d", counter);
cmSystemTools::ReplaceString(res, headerLengthTag, buffer);
+1 -3
View File
@@ -13,12 +13,10 @@
#include "cmCPackTGZGenerator.h"
cmCPackTGZGenerator::cmCPackTGZGenerator()
:cmCPackArchiveGenerator(cmArchiveWrite::CompressGZip,
"paxr")
: cmCPackArchiveGenerator(cmArchiveWrite::CompressGZip, "paxr")
{
}
cmCPackTGZGenerator::~cmCPackTGZGenerator()
{
}
+1
View File
@@ -28,6 +28,7 @@ public:
*/
cmCPackTGZGenerator();
virtual ~cmCPackTGZGenerator();
protected:
virtual const char* GetOutputExtension() { return ".tar.gz"; }
};
+1 -2
View File
@@ -13,8 +13,7 @@
#include "cmCPackTXZGenerator.h"
cmCPackTXZGenerator::cmCPackTXZGenerator()
:cmCPackArchiveGenerator(cmArchiveWrite::CompressXZ,
"paxr")
: cmCPackArchiveGenerator(cmArchiveWrite::CompressXZ, "paxr")
{
}
+1
View File
@@ -28,6 +28,7 @@ public:
*/
cmCPackTXZGenerator();
virtual ~cmCPackTXZGenerator();
protected:
virtual const char* GetOutputExtension() { return ".tar.xz"; }
};
+1 -3
View File
@@ -13,12 +13,10 @@
#include "cmCPackTarBZip2Generator.h"
cmCPackTarBZip2Generator::cmCPackTarBZip2Generator()
:cmCPackArchiveGenerator(cmArchiveWrite::CompressBZip2,
"paxr")
: cmCPackArchiveGenerator(cmArchiveWrite::CompressBZip2, "paxr")
{
}
cmCPackTarBZip2Generator::~cmCPackTarBZip2Generator()
{
}
+1
View File
@@ -27,6 +27,7 @@ public:
*/
cmCPackTarBZip2Generator();
virtual ~cmCPackTarBZip2Generator();
protected:
virtual const char* GetOutputExtension() { return ".tar.bz2"; }
};
+1 -3
View File
@@ -13,12 +13,10 @@
#include "cmCPackTarCompressGenerator.h"
cmCPackTarCompressGenerator::cmCPackTarCompressGenerator()
:cmCPackArchiveGenerator(cmArchiveWrite::CompressCompress,
"paxr")
: cmCPackArchiveGenerator(cmArchiveWrite::CompressCompress, "paxr")
{
}
cmCPackTarCompressGenerator::~cmCPackTarCompressGenerator()
{
}
+1 -3
View File
@@ -13,12 +13,10 @@
#include "cmCPackZIPGenerator.h"
cmCPackZIPGenerator::cmCPackZIPGenerator()
:cmCPackArchiveGenerator(cmArchiveWrite::CompressNone,
"zip")
: cmCPackArchiveGenerator(cmArchiveWrite::CompressNone, "zip")
{
}
cmCPackZIPGenerator::~cmCPackZIPGenerator()
{
}
+165 -213
View File
@@ -26,33 +26,28 @@
#include <cmsys/Encoding.hxx>
#include <cmsys/SystemTools.hxx>
static const char * cmDocumentationName[][2] =
{
{0,
" cpack - Packaging driver provided by CMake."},
{0,0}
static const char* cmDocumentationName[][2] = {
{ 0, " cpack - Packaging driver provided by CMake." },
{ 0, 0 }
};
static const char * cmDocumentationUsage[][2] =
{
{0,
" cpack -G <generator> [options]"},
{0,0}
static const char* cmDocumentationUsage[][2] = {
{ 0, " cpack -G <generator> [options]" },
{ 0, 0 }
};
static const char * cmDocumentationOptions[][2] =
{
{"-G <generator>", "Use the specified generator to generate package."},
{"-C <Configuration>", "Specify the project configuration"},
{"-D <var>=<value>", "Set a CPack variable."},
{"--config <config file>", "Specify the config file."},
{"--verbose,-V","enable verbose output"},
{"--debug","enable debug output (for CPack developers)"},
{"-P <package name>","override/define CPACK_PACKAGE_NAME"},
{"-R <package version>","override/define CPACK_PACKAGE_VERSION"},
{"-B <package directory>","override/define CPACK_PACKAGE_DIRECTORY"},
{"--vendor <vendor name>","override/define CPACK_PACKAGE_VENDOR"},
{0,0}
static const char* cmDocumentationOptions[][2] = {
{ "-G <generator>", "Use the specified generator to generate package." },
{ "-C <Configuration>", "Specify the project configuration" },
{ "-D <var>=<value>", "Set a CPack variable." },
{ "--config <config file>", "Specify the config file." },
{ "--verbose,-V", "enable verbose output" },
{ "--debug", "enable debug output (for CPack developers)" },
{ "-P <package name>", "override/define CPACK_PACKAGE_NAME" },
{ "-R <package version>", "override/define CPACK_PACKAGE_VERSION" },
{ "-B <package directory>", "override/define CPACK_PACKAGE_DIRECTORY" },
{ "--vendor <vendor name>", "override/define CPACK_PACKAGE_VENDOR" },
{ 0, 0 }
};
int cpackUnknownArgument(const char*, void*)
@@ -64,33 +59,31 @@ struct cpackDefinitions
{
typedef std::map<std::string, std::string> MapType;
MapType Map;
cmCPackLog *Log;
cmCPackLog* Log;
};
int cpackDefinitionArgument(const char* argument, const char* cValue,
void* call_data)
void* call_data)
{
(void)argument;
cpackDefinitions* def = static_cast<cpackDefinitions*>(call_data);
std::string value = cValue;
size_t pos = value.find_first_of("=");
if ( pos == std::string::npos )
{
if (pos == std::string::npos) {
cmCPack_Log(def->Log, cmCPackLog::LOG_ERROR,
"Please specify CPack definitions as: KEY=VALUE" << std::endl);
"Please specify CPack definitions as: KEY=VALUE" << std::endl);
return 0;
}
}
std::string key = value.substr(0, pos);
value = value.c_str() + pos + 1;
def->Map[key] = value;
cmCPack_Log(def->Log, cmCPackLog::LOG_DEBUG, "Set CPack variable: "
<< key << " to \"" << value << "\"" << std::endl);
<< key << " to \"" << value << "\"" << std::endl);
return 1;
}
// this is CPack.
int main (int argc, char const* const* argv)
int main(int argc, char const* const* argv)
{
cmsys::Encoding::CommandLineArguments args =
cmsys::Encoding::CommandLineArguments::Main(argc, argv);
@@ -107,12 +100,12 @@ int main (int argc, char const* const* argv)
cmSystemTools::EnableMSVCDebugHook();
if (cmSystemTools::GetCurrentWorkingDirectory().empty())
{
if (cmSystemTools::GetCurrentWorkingDirectory().empty()) {
cmCPack_Log(&log, cmCPackLog::LOG_ERROR,
"Current working directory cannot be established." << std::endl);
"Current working directory cannot be established."
<< std::endl);
return 1;
}
}
std::string generator;
bool help = false;
@@ -142,9 +135,9 @@ int main (int argc, char const* const* argv)
// Help arguments
arg.AddArgument("--help", argT::NO_ARGUMENT, &help, "CPack help");
arg.AddArgument("--help-full", argT::SPACE_ARGUMENT, &helpFull,
"CPack help");
"CPack help");
arg.AddArgument("--help-html", argT::SPACE_ARGUMENT, &helpHTML,
"CPack help");
"CPack help");
arg.AddArgument("--help-man", argT::SPACE_ARGUMENT, &helpMAN, "CPack help");
arg.AddArgument("--version", argT::NO_ARGUMENT, &helpVersion, "CPack help");
@@ -152,42 +145,39 @@ int main (int argc, char const* const* argv)
arg.AddArgument("--verbose", argT::NO_ARGUMENT, &verbose, "-V");
arg.AddArgument("--debug", argT::NO_ARGUMENT, &debug, "-V");
arg.AddArgument("--config", argT::SPACE_ARGUMENT, &cpackConfigFile,
"CPack configuration file");
"CPack configuration file");
arg.AddArgument("-C", argT::SPACE_ARGUMENT, &cpackBuildConfig,
"CPack build configuration");
arg.AddArgument("-G", argT::SPACE_ARGUMENT,
&generator, "CPack generator");
arg.AddArgument("-P", argT::SPACE_ARGUMENT,
&cpackProjectName, "CPack project name");
arg.AddArgument("-R", argT::SPACE_ARGUMENT,
&cpackProjectVersion, "CPack project version");
arg.AddArgument("-B", argT::SPACE_ARGUMENT,
&cpackProjectDirectory, "CPack project directory");
arg.AddArgument("--patch", argT::SPACE_ARGUMENT,
&cpackProjectPatch, "CPack project patch");
arg.AddArgument("--vendor", argT::SPACE_ARGUMENT,
&cpackProjectVendor, "CPack project vendor");
arg.AddCallback("-D", argT::SPACE_ARGUMENT,
cpackDefinitionArgument, &definitions, "CPack Definitions");
"CPack build configuration");
arg.AddArgument("-G", argT::SPACE_ARGUMENT, &generator, "CPack generator");
arg.AddArgument("-P", argT::SPACE_ARGUMENT, &cpackProjectName,
"CPack project name");
arg.AddArgument("-R", argT::SPACE_ARGUMENT, &cpackProjectVersion,
"CPack project version");
arg.AddArgument("-B", argT::SPACE_ARGUMENT, &cpackProjectDirectory,
"CPack project directory");
arg.AddArgument("--patch", argT::SPACE_ARGUMENT, &cpackProjectPatch,
"CPack project patch");
arg.AddArgument("--vendor", argT::SPACE_ARGUMENT, &cpackProjectVendor,
"CPack project vendor");
arg.AddCallback("-D", argT::SPACE_ARGUMENT, cpackDefinitionArgument,
&definitions, "CPack Definitions");
arg.SetUnknownArgumentCallback(cpackUnknownArgument);
// Parse command line
int parsed = arg.Parse();
// Setup logging
if ( verbose )
{
if (verbose) {
log.SetVerbose(verbose);
cmCPack_Log(&log, cmCPackLog::LOG_OUTPUT, "Enable Verbose" << std::endl);
}
if ( debug )
{
}
if (debug) {
log.SetDebug(debug);
cmCPack_Log(&log, cmCPackLog::LOG_OUTPUT, "Enable Debug" << std::endl);
}
}
cmCPack_Log(&log, cmCPackLog::LOG_VERBOSE,
"Read CPack config file: " << cpackConfigFile << std::endl);
"Read CPack config file: " << cpackConfigFile << std::endl);
cmake cminst;
cminst.SetHomeDirectory("");
@@ -196,18 +186,17 @@ int main (int argc, char const* const* argv)
cminst.GetState()->RemoveUnscriptableCommands();
cmGlobalGenerator cmgg(&cminst);
cmsys::auto_ptr<cmMakefile> globalMF(
new cmMakefile(&cmgg, cminst.GetCurrentSnapshot()));
new cmMakefile(&cmgg, cminst.GetCurrentSnapshot()));
#if defined(__CYGWIN__)
globalMF->AddDefinition("CMAKE_LEGACY_CYGWIN_WIN32", "0");
#endif
bool cpackConfigFileSpecified = true;
if ( cpackConfigFile.empty() )
{
if (cpackConfigFile.empty()) {
cpackConfigFile = cmSystemTools::GetCurrentWorkingDirectory();
cpackConfigFile += "/CPackConfig.cmake";
cpackConfigFileSpecified = false;
}
}
cmCPackGeneratorFactory generators;
generators.SetLogger(&log);
@@ -220,262 +209,225 @@ int main (int argc, char const* const* argv)
* should launch cpack using "cpackConfigFile" if it exists
* in the current directory.
*/
if((doc.CheckOptions(argc, argv,"-G")) && !(argc==1))
{
help = true;
}
else
{
help = false;
}
if ((doc.CheckOptions(argc, argv, "-G")) && !(argc == 1)) {
help = true;
} else {
help = false;
}
// This part is used for cpack documentation lookup as well.
cminst.AddCMakePaths();
if ( parsed && !help )
{
if (parsed && !help) {
// find out which system cpack is running on, so it can setup the search
// paths, so FIND_XXX() commands can be used in scripts
std::string systemFile =
globalMF->GetModulesFile("CMakeDetermineSystem.cmake");
if (!globalMF->ReadListFile(systemFile.c_str()))
{
if (!globalMF->ReadListFile(systemFile.c_str())) {
cmCPack_Log(&log, cmCPackLog::LOG_ERROR,
"Error reading CMakeDetermineSystem.cmake" << std::endl);
"Error reading CMakeDetermineSystem.cmake" << std::endl);
return 1;
}
}
systemFile =
globalMF->GetModulesFile("CMakeSystemSpecificInformation.cmake");
if (!globalMF->ReadListFile(systemFile.c_str()))
{
if (!globalMF->ReadListFile(systemFile.c_str())) {
cmCPack_Log(&log, cmCPackLog::LOG_ERROR,
"Error reading CMakeSystemSpecificInformation.cmake" << std::endl);
"Error reading CMakeSystemSpecificInformation.cmake"
<< std::endl);
return 1;
}
}
if ( !cpackBuildConfig.empty() )
{
if (!cpackBuildConfig.empty()) {
globalMF->AddDefinition("CPACK_BUILD_CONFIG", cpackBuildConfig.c_str());
}
}
if ( cmSystemTools::FileExists(cpackConfigFile.c_str()) )
{
cpackConfigFile =
cmSystemTools::CollapseFullPath(cpackConfigFile);
if (cmSystemTools::FileExists(cpackConfigFile.c_str())) {
cpackConfigFile = cmSystemTools::CollapseFullPath(cpackConfigFile);
cmCPack_Log(&log, cmCPackLog::LOG_VERBOSE,
"Read CPack configuration file: " << cpackConfigFile
<< std::endl);
if ( !globalMF->ReadListFile(cpackConfigFile.c_str()) )
{
"Read CPack configuration file: " << cpackConfigFile
<< std::endl);
if (!globalMF->ReadListFile(cpackConfigFile.c_str())) {
cmCPack_Log(&log, cmCPackLog::LOG_ERROR,
"Problem reading CPack config file: \""
<< cpackConfigFile << "\"" << std::endl);
"Problem reading CPack config file: \""
<< cpackConfigFile << "\"" << std::endl);
return 1;
}
}
else if ( cpackConfigFileSpecified )
{
} else if (cpackConfigFileSpecified) {
cmCPack_Log(&log, cmCPackLog::LOG_ERROR,
"Cannot find CPack config file: \"" <<
cpackConfigFile << "\"" << std::endl);
"Cannot find CPack config file: \"" << cpackConfigFile
<< "\"" << std::endl);
return 1;
}
}
if ( !generator.empty() )
{
if (!generator.empty()) {
globalMF->AddDefinition("CPACK_GENERATOR", generator.c_str());
}
if ( !cpackProjectName.empty() )
{
}
if (!cpackProjectName.empty()) {
globalMF->AddDefinition("CPACK_PACKAGE_NAME", cpackProjectName.c_str());
}
if ( !cpackProjectVersion.empty() )
{
}
if (!cpackProjectVersion.empty()) {
globalMF->AddDefinition("CPACK_PACKAGE_VERSION",
cpackProjectVersion.c_str());
}
if ( !cpackProjectVendor.empty() )
{
cpackProjectVersion.c_str());
}
if (!cpackProjectVendor.empty()) {
globalMF->AddDefinition("CPACK_PACKAGE_VENDOR",
cpackProjectVendor.c_str());
}
cpackProjectVendor.c_str());
}
// if this is not empty it has been set on the command line
// go for it. Command line override values set in config file.
if ( !cpackProjectDirectory.empty() )
{
if (!cpackProjectDirectory.empty()) {
globalMF->AddDefinition("CPACK_PACKAGE_DIRECTORY",
cpackProjectDirectory.c_str());
}
}
// The value has not been set on the command line
else
{
else {
// get a default value (current working directory)
cpackProjectDirectory = cmsys::SystemTools::GetCurrentWorkingDirectory();
// use default value iff no value has been provided by the config file
if (!globalMF->IsSet("CPACK_PACKAGE_DIRECTORY"))
{
if (!globalMF->IsSet("CPACK_PACKAGE_DIRECTORY")) {
globalMF->AddDefinition("CPACK_PACKAGE_DIRECTORY",
cpackProjectDirectory.c_str());
}
}
}
cpackDefinitions::MapType::iterator cdit;
for ( cdit = definitions.Map.begin();
cdit != definitions.Map.end();
++cdit )
{
for (cdit = definitions.Map.begin(); cdit != definitions.Map.end();
++cdit) {
globalMF->AddDefinition(cdit->first, cdit->second.c_str());
}
}
const char* cpackModulesPath =
globalMF->GetDefinition("CPACK_MODULE_PATH");
if ( cpackModulesPath )
{
if (cpackModulesPath) {
globalMF->AddDefinition("CMAKE_MODULE_PATH", cpackModulesPath);
}
}
const char* genList = globalMF->GetDefinition("CPACK_GENERATOR");
if ( !genList )
{
cmCPack_Log(&log, cmCPackLog::LOG_ERROR,
"CPack generator not specified" << std::endl);
}
else
{
if (!genList) {
cmCPack_Log(&log, cmCPackLog::LOG_ERROR, "CPack generator not specified"
<< std::endl);
} else {
std::vector<std::string> generatorsVector;
cmSystemTools::ExpandListArgument(genList,
generatorsVector);
cmSystemTools::ExpandListArgument(genList, generatorsVector);
std::vector<std::string>::iterator it;
for ( it = generatorsVector.begin();
it != generatorsVector.end();
++it )
{
for (it = generatorsVector.begin(); it != generatorsVector.end(); ++it) {
const char* gen = it->c_str();
cmMakefile::ScopePushPop raii(globalMF.get());
cmMakefile* mf = globalMF.get();
cmCPack_Log(&log, cmCPackLog::LOG_VERBOSE,
"Specified generator: " << gen << std::endl);
if ( parsed && !mf->GetDefinition("CPACK_PACKAGE_NAME") )
{
"Specified generator: " << gen << std::endl);
if (parsed && !mf->GetDefinition("CPACK_PACKAGE_NAME")) {
cmCPack_Log(&log, cmCPackLog::LOG_ERROR,
"CPack project name not specified" << std::endl);
"CPack project name not specified" << std::endl);
parsed = 0;
}
}
if (parsed &&
!(mf->GetDefinition("CPACK_PACKAGE_VERSION") ||
(mf->GetDefinition("CPACK_PACKAGE_VERSION_MAJOR") &&
mf->GetDefinition("CPACK_PACKAGE_VERSION_MINOR") &&
mf->GetDefinition("CPACK_PACKAGE_VERSION_PATCH"))))
{
mf->GetDefinition("CPACK_PACKAGE_VERSION_PATCH")))) {
cmCPack_Log(&log, cmCPackLog::LOG_ERROR,
"CPack project version not specified" << std::endl
<< "Specify CPACK_PACKAGE_VERSION, or "
"CPACK_PACKAGE_VERSION_MAJOR, "
"CPACK_PACKAGE_VERSION_MINOR, and CPACK_PACKAGE_VERSION_PATCH."
<< std::endl);
"CPack project version not specified"
<< std::endl
<< "Specify CPACK_PACKAGE_VERSION, or "
"CPACK_PACKAGE_VERSION_MAJOR, "
"CPACK_PACKAGE_VERSION_MINOR, and "
"CPACK_PACKAGE_VERSION_PATCH."
<< std::endl);
parsed = 0;
}
if ( parsed )
{
}
if (parsed) {
cpackGenerator = generators.NewGenerator(gen);
if ( !cpackGenerator )
{
if (!cpackGenerator) {
cmCPack_Log(&log, cmCPackLog::LOG_ERROR,
"Cannot initialize CPack generator: "
<< gen << std::endl);
"Cannot initialize CPack generator: " << gen
<< std::endl);
parsed = 0;
}
if ( parsed && !cpackGenerator->Initialize(gen, mf) )
{
}
if (parsed && !cpackGenerator->Initialize(gen, mf)) {
cmCPack_Log(&log, cmCPackLog::LOG_ERROR,
"Cannot initialize the generator " << gen << std::endl);
"Cannot initialize the generator " << gen
<< std::endl);
parsed = 0;
}
}
if ( !mf->GetDefinition("CPACK_INSTALL_COMMANDS") &&
!mf->GetDefinition("CPACK_INSTALLED_DIRECTORIES") &&
!mf->GetDefinition("CPACK_INSTALL_CMAKE_PROJECTS") )
{
cmCPack_Log(&log, cmCPackLog::LOG_ERROR,
if (!mf->GetDefinition("CPACK_INSTALL_COMMANDS") &&
!mf->GetDefinition("CPACK_INSTALLED_DIRECTORIES") &&
!mf->GetDefinition("CPACK_INSTALL_CMAKE_PROJECTS")) {
cmCPack_Log(
&log, cmCPackLog::LOG_ERROR,
"Please specify build tree of the project that uses CMake "
"using CPACK_INSTALL_CMAKE_PROJECTS, specify "
"CPACK_INSTALL_COMMANDS, or specify "
"CPACK_INSTALLED_DIRECTORIES."
<< std::endl);
<< std::endl);
parsed = 0;
}
if ( parsed )
{
}
if (parsed) {
const char* projName = mf->GetDefinition("CPACK_PACKAGE_NAME");
cmCPack_Log(&log, cmCPackLog::LOG_VERBOSE, "Use generator: "
<< cpackGenerator->GetNameOfClass() << std::endl);
cmCPack_Log(&log, cmCPackLog::LOG_VERBOSE, "For project: "
<< projName << std::endl);
<< cpackGenerator->GetNameOfClass() << std::endl);
cmCPack_Log(&log, cmCPackLog::LOG_VERBOSE,
"For project: " << projName << std::endl);
const char* projVersion =
mf->GetDefinition("CPACK_PACKAGE_VERSION");
if ( !projVersion )
{
const char* projVersionMajor
= mf->GetDefinition("CPACK_PACKAGE_VERSION_MAJOR");
const char* projVersionMinor
= mf->GetDefinition("CPACK_PACKAGE_VERSION_MINOR");
const char* projVersionPatch
= mf->GetDefinition("CPACK_PACKAGE_VERSION_PATCH");
if (!projVersion) {
const char* projVersionMajor =
mf->GetDefinition("CPACK_PACKAGE_VERSION_MAJOR");
const char* projVersionMinor =
mf->GetDefinition("CPACK_PACKAGE_VERSION_MINOR");
const char* projVersionPatch =
mf->GetDefinition("CPACK_PACKAGE_VERSION_PATCH");
std::ostringstream ostr;
ostr << projVersionMajor << "." << projVersionMinor << "."
<< projVersionPatch;
mf->AddDefinition("CPACK_PACKAGE_VERSION",
ostr.str().c_str());
}
<< projVersionPatch;
mf->AddDefinition("CPACK_PACKAGE_VERSION", ostr.str().c_str());
}
int res = cpackGenerator->DoPackage();
if ( !res )
{
if (!res) {
cmCPack_Log(&log, cmCPackLog::LOG_ERROR,
"Error when generating package: " << projName << std::endl);
"Error when generating package: " << projName
<< std::endl);
return 1;
}
}
}
}
}
}
}
/* In this case we are building the documentation object
* instance in order to create appropriate structure
* in order to satisfy the appropriate --help-xxx request
*/
if ( help )
{
if (help) {
// Construct and print requested documentation.
doc.SetName("cpack");
doc.SetSection("Name",cmDocumentationName);
doc.SetSection("Usage",cmDocumentationUsage);
doc.PrependSection("Options",cmDocumentationOptions);
doc.SetSection("Name", cmDocumentationName);
doc.SetSection("Usage", cmDocumentationUsage);
doc.PrependSection("Options", cmDocumentationOptions);
std::vector<cmDocumentationEntry> v;
cmCPackGeneratorFactory::DescriptionsMap::const_iterator generatorIt;
for( generatorIt = generators.GetGeneratorsList().begin();
generatorIt != generators.GetGeneratorsList().end();
++ generatorIt )
{
for (generatorIt = generators.GetGeneratorsList().begin();
generatorIt != generators.GetGeneratorsList().end(); ++generatorIt) {
cmDocumentationEntry e;
e.Name = generatorIt->first.c_str();
e.Brief = generatorIt->second.c_str();
v.push_back(e);
}
doc.SetSection("Generators",v);
}
doc.SetSection("Generators", v);
#undef cout
return doc.PrintRequestedDocumentation(std::cout)? 0:1;
return doc.PrintRequestedDocumentation(std::cout) ? 0 : 1;
#define cout no_cout_use_cmCPack_Log
}
}
if (cmSystemTools::GetErrorOccuredFlag())
{
if (cmSystemTools::GetErrorOccuredFlag()) {
return 1;
}
}
return 0;
}
+180 -220
View File
@@ -19,63 +19,58 @@
#include <cm_expat.h>
extern "C"
int cmBZRXMLParserUnknownEncodingHandler(void*,
const XML_Char *name,
XML_Encoding *info)
extern "C" int cmBZRXMLParserUnknownEncodingHandler(void*,
const XML_Char* name,
XML_Encoding* info)
{
static const int latin1[]=
{
0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007,
0x0008, 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x000E, 0x000F,
0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017,
0x0018, 0x0019, 0x001A, 0x001B, 0x001C, 0x001D, 0x001E, 0x001F,
0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027,
0x0028, 0x0029, 0x002A, 0x002B, 0x002C, 0x002D, 0x002E, 0x002F,
0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037,
0x0038, 0x0039, 0x003A, 0x003B, 0x003C, 0x003D, 0x003E, 0x003F,
0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047,
0x0048, 0x0049, 0x004A, 0x004B, 0x004C, 0x004D, 0x004E, 0x004F,
0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057,
0x0058, 0x0059, 0x005A, 0x005B, 0x005C, 0x005D, 0x005E, 0x005F,
0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067,
0x0068, 0x0069, 0x006A, 0x006B, 0x006C, 0x006D, 0x006E, 0x006F,
0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077,
0x0078, 0x0079, 0x007A, 0x007B, 0x007C, 0x007D, 0x007E, 0x007F,
0x20AC, 0x0081, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021,
0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0x008D, 0x017D, 0x008F,
0x0090, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014,
0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0x009D, 0x017E, 0x0178,
0x00A0, 0x00A1, 0x00A2, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7,
0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF,
0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, 0x00B6, 0x00B7,
0x00B8, 0x00B9, 0x00BA, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF,
0x00C0, 0x00C1, 0x00C2, 0x00C3, 0x00C4, 0x00C5, 0x00C6, 0x00C7,
0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x00CC, 0x00CD, 0x00CE, 0x00CF,
0x00D0, 0x00D1, 0x00D2, 0x00D3, 0x00D4, 0x00D5, 0x00D6, 0x00D7,
0x00D8, 0x00D9, 0x00DA, 0x00DB, 0x00DC, 0x00DD, 0x00DE, 0x00DF,
0x00E0, 0x00E1, 0x00E2, 0x00E3, 0x00E4, 0x00E5, 0x00E6, 0x00E7,
0x00E8, 0x00E9, 0x00EA, 0x00EB, 0x00EC, 0x00ED, 0x00EE, 0x00EF,
0x00F0, 0x00F1, 0x00F2, 0x00F3, 0x00F4, 0x00F5, 0x00F6, 0x00F7,
0x00F8, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x00FD, 0x00FE, 0x00FF
};
static const int latin1[] = {
0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, 0x0008,
0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x000E, 0x000F, 0x0010, 0x0011,
0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, 0x0018, 0x0019, 0x001A,
0x001B, 0x001C, 0x001D, 0x001E, 0x001F, 0x0020, 0x0021, 0x0022, 0x0023,
0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002A, 0x002B, 0x002C,
0x002D, 0x002E, 0x002F, 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035,
0x0036, 0x0037, 0x0038, 0x0039, 0x003A, 0x003B, 0x003C, 0x003D, 0x003E,
0x003F, 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047,
0x0048, 0x0049, 0x004A, 0x004B, 0x004C, 0x004D, 0x004E, 0x004F, 0x0050,
0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059,
0x005A, 0x005B, 0x005C, 0x005D, 0x005E, 0x005F, 0x0060, 0x0061, 0x0062,
0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006A, 0x006B,
0x006C, 0x006D, 0x006E, 0x006F, 0x0070, 0x0071, 0x0072, 0x0073, 0x0074,
0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007A, 0x007B, 0x007C, 0x007D,
0x007E, 0x007F, 0x20AC, 0x0081, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020,
0x2021, 0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0x008D, 0x017D, 0x008F,
0x0090, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC,
0x2122, 0x0161, 0x203A, 0x0153, 0x009D, 0x017E, 0x0178, 0x00A0, 0x00A1,
0x00A2, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x00AA,
0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, 0x00B0, 0x00B1, 0x00B2, 0x00B3,
0x00B4, 0x00B5, 0x00B6, 0x00B7, 0x00B8, 0x00B9, 0x00BA, 0x00BB, 0x00BC,
0x00BD, 0x00BE, 0x00BF, 0x00C0, 0x00C1, 0x00C2, 0x00C3, 0x00C4, 0x00C5,
0x00C6, 0x00C7, 0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x00CC, 0x00CD, 0x00CE,
0x00CF, 0x00D0, 0x00D1, 0x00D2, 0x00D3, 0x00D4, 0x00D5, 0x00D6, 0x00D7,
0x00D8, 0x00D9, 0x00DA, 0x00DB, 0x00DC, 0x00DD, 0x00DE, 0x00DF, 0x00E0,
0x00E1, 0x00E2, 0x00E3, 0x00E4, 0x00E5, 0x00E6, 0x00E7, 0x00E8, 0x00E9,
0x00EA, 0x00EB, 0x00EC, 0x00ED, 0x00EE, 0x00EF, 0x00F0, 0x00F1, 0x00F2,
0x00F3, 0x00F4, 0x00F5, 0x00F6, 0x00F7, 0x00F8, 0x00F9, 0x00FA, 0x00FB,
0x00FC, 0x00FD, 0x00FE, 0x00FF
};
// The BZR xml output plugin can use some encodings that are not
// recognized by expat. This will lead to an error, e.g. "Error
// parsing bzr log xml: unknown encoding", the following is a
// workaround for these unknown encodings.
if(name == std::string("ascii") || name == std::string("cp1252") ||
name == std::string("ANSI_X3.4-1968"))
{
for(unsigned int i=0;i<256;++i) info->map[i] = latin1[i];
if (name == std::string("ascii") || name == std::string("cp1252") ||
name == std::string("ANSI_X3.4-1968")) {
for (unsigned int i = 0; i < 256; ++i)
info->map[i] = latin1[i];
return 1;
}
}
return 0;
}
cmCTestBZR::cmCTestBZR(cmCTest* ct, std::ostream& log):
cmCTestGlobalVC(ct, log)
cmCTestBZR::cmCTestBZR(cmCTest* ct, std::ostream& log)
: cmCTestGlobalVC(ct, log)
{
this->PriorRev = this->Unknown;
// Even though it is specified in the documentation, with bzr 1.13
@@ -88,69 +83,68 @@ cmCTestBZR::~cmCTestBZR()
{
}
class cmCTestBZR::InfoParser: public cmCTestVC::LineParser
class cmCTestBZR::InfoParser : public cmCTestVC::LineParser
{
public:
InfoParser(cmCTestBZR* bzr, const char* prefix):
BZR(bzr), CheckOutFound(false)
{
InfoParser(cmCTestBZR* bzr, const char* prefix)
: BZR(bzr)
, CheckOutFound(false)
{
this->SetLog(&bzr->Log, prefix);
this->RegexCheckOut.compile("checkout of branch: *([^\t\r\n]+)$");
this->RegexParent.compile("parent branch: *([^\t\r\n]+)$");
}
}
private:
cmCTestBZR* BZR;
bool CheckOutFound;
cmsys::RegularExpression RegexCheckOut;
cmsys::RegularExpression RegexParent;
virtual bool ProcessLine()
{
if(this->RegexCheckOut.find(this->Line))
{
{
if (this->RegexCheckOut.find(this->Line)) {
this->BZR->URL = this->RegexCheckOut.match(1);
CheckOutFound = true;
}
else if(!CheckOutFound && this->RegexParent.find(this->Line))
{
} else if (!CheckOutFound && this->RegexParent.find(this->Line)) {
this->BZR->URL = this->RegexParent.match(1);
}
return true;
}
return true;
}
};
class cmCTestBZR::RevnoParser: public cmCTestVC::LineParser
class cmCTestBZR::RevnoParser : public cmCTestVC::LineParser
{
public:
RevnoParser(cmCTestBZR* bzr, const char* prefix, std::string& rev):
Rev(rev)
{
RevnoParser(cmCTestBZR* bzr, const char* prefix, std::string& rev)
: Rev(rev)
{
this->SetLog(&bzr->Log, prefix);
this->RegexRevno.compile("^([0-9]+)$");
}
}
private:
std::string& Rev;
cmsys::RegularExpression RegexRevno;
virtual bool ProcessLine()
{
if(this->RegexRevno.find(this->Line))
{
{
if (this->RegexRevno.find(this->Line)) {
this->Rev = this->RegexRevno.match(1);
}
return true;
}
return true;
}
};
std::string cmCTestBZR::LoadInfo()
{
// Run "bzr info" to get the repository info from the work tree.
const char* bzr = this->CommandLineTool.c_str();
const char* bzr_info[] = {bzr, "info", 0};
const char* bzr_info[] = { bzr, "info", 0 };
InfoParser iout(this, "info-out> ");
OutputLogger ierr(this->Log, "info-err> ");
this->RunChild(bzr_info, &iout, &ierr);
// Run "bzr revno" to get the repository revision number from the work tree.
const char* bzr_revno[] = {bzr, "revno", 0};
const char* bzr_revno[] = { bzr, "revno", 0 };
std::string rev;
RevnoParser rout(this, "revno-out> ", rev);
OutputLogger rerr(this->Log, "revno-err> ");
@@ -164,7 +158,7 @@ void cmCTestBZR::NoteOldRevision()
this->OldRevision = this->LoadInfo();
this->Log << "Revision before update: " << this->OldRevision << "\n";
cmCTestLog(this->CTest, HANDLER_OUTPUT, " Old revision of repository is: "
<< this->OldRevision << "\n");
<< this->OldRevision << "\n");
this->PriorRev.Rev = this->OldRevision;
}
@@ -173,35 +167,38 @@ void cmCTestBZR::NoteNewRevision()
this->NewRevision = this->LoadInfo();
this->Log << "Revision after update: " << this->NewRevision << "\n";
cmCTestLog(this->CTest, HANDLER_OUTPUT, " New revision of repository is: "
<< this->NewRevision << "\n");
<< this->NewRevision << "\n");
this->Log << "URL = " << this->URL << "\n";
}
class cmCTestBZR::LogParser: public cmCTestVC::OutputLogger,
private cmXMLParser
class cmCTestBZR::LogParser : public cmCTestVC::OutputLogger,
private cmXMLParser
{
public:
LogParser(cmCTestBZR* bzr, const char* prefix):
OutputLogger(bzr->Log, prefix), BZR(bzr),
EmailRegex("(.*) <([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+)>")
{ this->InitializeParser(); }
LogParser(cmCTestBZR* bzr, const char* prefix)
: OutputLogger(bzr->Log, prefix)
, BZR(bzr)
, EmailRegex("(.*) <([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+)>")
{
this->InitializeParser();
}
~LogParser() { this->CleanupParser(); }
virtual int InitializeParser()
{
int res = cmXMLParser::InitializeParser();
if (res)
{
XML_SetUnknownEncodingHandler(static_cast<XML_Parser>(this->Parser),
cmBZRXMLParserUnknownEncodingHandler, 0);
}
return res;
}
{
int res = cmXMLParser::InitializeParser();
if (res) {
XML_SetUnknownEncodingHandler(static_cast<XML_Parser>(this->Parser),
cmBZRXMLParserUnknownEncodingHandler, 0);
}
return res;
}
private:
cmCTestBZR* BZR;
typedef cmCTestBZR::Revision Revision;
typedef cmCTestBZR::Change Change;
typedef cmCTestBZR::Change Change;
Revision Rev;
std::vector<Change> Changes;
Change CurChange;
@@ -210,194 +207,161 @@ private:
cmsys::RegularExpression EmailRegex;
virtual bool ProcessChunk(const char* data, int length)
{
{
this->OutputLogger::ProcessChunk(data, length);
this->ParseChunk(data, length);
return true;
}
}
virtual void StartElement(const std::string& name, const char**)
{
{
this->CData.clear();
if(name == "log")
{
if (name == "log") {
this->Rev = Revision();
this->Changes.clear();
}
}
// affected-files can contain blocks of
// modified, unknown, renamed, kind-changed, removed, conflicts, added
else if(name == "modified"
|| name == "renamed"
|| name == "kind-changed")
{
else if (name == "modified" || name == "renamed" ||
name == "kind-changed") {
this->CurChange = Change();
this->CurChange.Action = 'M';
}
else if(name == "added")
{
} else if (name == "added") {
this->CurChange = Change();
this->CurChange = 'A';
}
else if(name == "removed")
{
} else if (name == "removed") {
this->CurChange = Change();
this->CurChange = 'D';
}
else if(name == "unknown"
|| name == "conflicts")
{
} else if (name == "unknown" || name == "conflicts") {
// Should not happen here
this->CurChange = Change();
}
}
}
virtual void CharacterDataHandler(const char* data, int length)
{
this->CData.insert(this->CData.end(), data, data+length);
}
{
this->CData.insert(this->CData.end(), data, data + length);
}
virtual void EndElement(const std::string& name)
{
if(name == "log")
{
{
if (name == "log") {
this->BZR->DoRevision(this->Rev, this->Changes);
}
else if(!this->CData.empty() &&
(name == "file" || name == "directory"))
{
} else if (!this->CData.empty() &&
(name == "file" || name == "directory")) {
this->CurChange.Path.assign(&this->CData[0], this->CData.size());
cmSystemTools::ConvertToUnixSlashes(this->CurChange.Path);
this->Changes.push_back(this->CurChange);
}
else if(!this->CData.empty() && name == "symlink")
{
} else if (!this->CData.empty() && name == "symlink") {
// symlinks have an arobase at the end in the log
this->CurChange.Path.assign(&this->CData[0], this->CData.size()-1);
this->CurChange.Path.assign(&this->CData[0], this->CData.size() - 1);
cmSystemTools::ConvertToUnixSlashes(this->CurChange.Path);
this->Changes.push_back(this->CurChange);
}
else if(!this->CData.empty() && name == "committer")
{
} else if (!this->CData.empty() && name == "committer") {
this->Rev.Author.assign(&this->CData[0], this->CData.size());
if(this->EmailRegex.find(this->Rev.Author))
{
if (this->EmailRegex.find(this->Rev.Author)) {
this->Rev.Author = this->EmailRegex.match(1);
this->Rev.EMail = this->EmailRegex.match(2);
}
}
else if(!this->CData.empty() && name == "timestamp")
{
} else if (!this->CData.empty() && name == "timestamp") {
this->Rev.Date.assign(&this->CData[0], this->CData.size());
}
else if(!this->CData.empty() && name == "message")
{
} else if (!this->CData.empty() && name == "message") {
this->Rev.Log.assign(&this->CData[0], this->CData.size());
}
else if(!this->CData.empty() && name == "revno")
{
} else if (!this->CData.empty() && name == "revno") {
this->Rev.Rev.assign(&this->CData[0], this->CData.size());
}
this->CData.clear();
}
this->CData.clear();
}
virtual void ReportError(int, int, const char* msg)
{
{
this->BZR->Log << "Error parsing bzr log xml: " << msg << "\n";
}
}
};
class cmCTestBZR::UpdateParser: public cmCTestVC::LineParser
class cmCTestBZR::UpdateParser : public cmCTestVC::LineParser
{
public:
UpdateParser(cmCTestBZR* bzr, const char* prefix): BZR(bzr)
{
UpdateParser(cmCTestBZR* bzr, const char* prefix)
: BZR(bzr)
{
this->SetLog(&bzr->Log, prefix);
this->RegexUpdate.compile("^([-+R?XCP ])([NDKM ])([* ]) +(.+)$");
}
}
private:
cmCTestBZR* BZR;
cmsys::RegularExpression RegexUpdate;
virtual bool ProcessChunk(const char* first, int length)
{
{
bool last_is_new_line = (*first == '\r' || *first == '\n');
const char* const last = first + length;
for(const char* c = first; c != last; ++c)
{
if(*c == '\r' || *c == '\n')
{
if(!last_is_new_line)
{
for (const char* c = first; c != last; ++c) {
if (*c == '\r' || *c == '\n') {
if (!last_is_new_line) {
// Log this line.
if(this->Log && this->Prefix)
{
if (this->Log && this->Prefix) {
*this->Log << this->Prefix << this->Line << "\n";
}
}
// Hand this line to the subclass implementation.
if(!this->ProcessLine())
{
if (!this->ProcessLine()) {
this->Line = "";
return false;
}
}
this->Line = "";
last_is_new_line = true;
}
}
else
{
} else {
// Append this character to the line under construction.
this->Line.append(1, *c);
last_is_new_line = false;
}
}
return true;
}
return true;
}
bool ProcessLine()
{
if(this->RegexUpdate.find(this->Line))
{
{
if (this->RegexUpdate.find(this->Line)) {
this->DoPath(this->RegexUpdate.match(1)[0],
this->RegexUpdate.match(2)[0],
this->RegexUpdate.match(3)[0],
this->RegexUpdate.match(4));
}
return true;
this->RegexUpdate.match(3)[0], this->RegexUpdate.match(4));
}
return true;
}
void DoPath(char c0, char c1, char c2, std::string path)
{
if(path.empty()) return;
{
if (path.empty())
return;
cmSystemTools::ConvertToUnixSlashes(path);
const std::string dir = cmSystemTools::GetFilenamePath(path);
const std::string name = cmSystemTools::GetFilenameName(path);
if ( c0=='C' )
{
if (c0 == 'C') {
this->BZR->Dirs[dir][name].Status = PathConflicting;
return;
}
}
if ( c1=='M' || c1=='K' || c1=='N' || c1=='D' || c2 =='*' )
{
if (c1 == 'M' || c1 == 'K' || c1 == 'N' || c1 == 'D' || c2 == '*') {
this->BZR->Dirs[dir][name].Status = PathUpdated;
return;
}
}
}
};
bool cmCTestBZR::UpdateImpl()
{
// Get user-specified update options.
std::string opts = this->CTest->GetCTestConfiguration("UpdateOptions");
if(opts.empty())
{
if (opts.empty()) {
opts = this->CTest->GetCTestConfiguration("BZRUpdateOptions");
}
}
std::vector<std::string> args = cmSystemTools::ParseArguments(opts.c_str());
// TODO: if(this->CTest->GetTestModel() == cmCTest::NIGHTLY)
@@ -407,11 +371,10 @@ bool cmCTestBZR::UpdateImpl()
bzr_update.push_back(this->CommandLineTool.c_str());
bzr_update.push_back("pull");
for(std::vector<std::string>::const_iterator ai = args.begin();
ai != args.end(); ++ai)
{
for (std::vector<std::string>::const_iterator ai = args.begin();
ai != args.end(); ++ai) {
bzr_update.push_back(ai->c_str());
}
}
bzr_update.push_back(this->URL.c_str());
@@ -427,82 +390,79 @@ void cmCTestBZR::LoadRevisions()
{
cmCTestLog(this->CTest, HANDLER_OUTPUT,
" Gathering version information (one . per revision):\n"
" " << std::flush);
" "
<< std::flush);
// We are interested in every revision included in the update.
this->Revisions.clear();
std::string revs;
if(atoi(this->OldRevision.c_str()) <= atoi(this->NewRevision.c_str()))
{
if (atoi(this->OldRevision.c_str()) <= atoi(this->NewRevision.c_str())) {
// DoRevision takes care of discarding the information about OldRevision
revs = this->OldRevision + ".." + this->NewRevision;
}
else
{
} else {
return;
}
}
// Run "bzr log" to get all global revisions of interest.
const char* bzr = this->CommandLineTool.c_str();
const char* bzr_log[] = {bzr, "log", "-v", "-r", revs.c_str(), "--xml",
this->URL.c_str(), 0};
const char* bzr_log[] = {
bzr, "log", "-v", "-r", revs.c_str(), "--xml", this->URL.c_str(), 0
};
{
LogParser out(this, "log-out> ");
OutputLogger err(this->Log, "log-err> ");
this->RunChild(bzr_log, &out, &err);
LogParser out(this, "log-out> ");
OutputLogger err(this->Log, "log-err> ");
this->RunChild(bzr_log, &out, &err);
}
cmCTestLog(this->CTest, HANDLER_OUTPUT, std::endl);
}
class cmCTestBZR::StatusParser: public cmCTestVC::LineParser
class cmCTestBZR::StatusParser : public cmCTestVC::LineParser
{
public:
StatusParser(cmCTestBZR* bzr, const char* prefix): BZR(bzr)
{
StatusParser(cmCTestBZR* bzr, const char* prefix)
: BZR(bzr)
{
this->SetLog(&bzr->Log, prefix);
this->RegexStatus.compile("^([-+R?XCP ])([NDKM ])([* ]) +(.+)$");
}
}
private:
cmCTestBZR* BZR;
cmsys::RegularExpression RegexStatus;
bool ProcessLine()
{
if(this->RegexStatus.find(this->Line))
{
{
if (this->RegexStatus.find(this->Line)) {
this->DoPath(this->RegexStatus.match(1)[0],
this->RegexStatus.match(2)[0],
this->RegexStatus.match(3)[0],
this->RegexStatus.match(4));
}
return true;
this->RegexStatus.match(3)[0], this->RegexStatus.match(4));
}
return true;
}
void DoPath(char c0, char c1, char c2, std::string path)
{
if(path.empty()) return;
{
if (path.empty())
return;
cmSystemTools::ConvertToUnixSlashes(path);
if ( c0=='C' )
{
if (c0 == 'C') {
this->BZR->DoModification(PathConflicting, path);
return;
}
}
if ( c0 == '+' || c0 == 'R' || c0 == 'P'
|| c1=='M' || c1=='K' || c1=='N' || c1=='D'
|| c2 =='*' )
{
if (c0 == '+' || c0 == 'R' || c0 == 'P' || c1 == 'M' || c1 == 'K' ||
c1 == 'N' || c1 == 'D' || c2 == '*') {
this->BZR->DoModification(PathModified, path);
return;
}
}
}
};
void cmCTestBZR::LoadModifications()
{
// Run "bzr status" which reports local modifications.
const char* bzr = this->CommandLineTool.c_str();
const char* bzr_status[] = {bzr, "status", "-SV", 0};
const char* bzr_status[] = { bzr, "status", "-SV", 0 };
StatusParser out(this, "status-out> ");
OutputLogger err(this->Log, "status-err> ");
this->RunChild(bzr_status, &out, &err);
+1 -1
View File
@@ -18,7 +18,7 @@
* \brief Interaction with bzr command-line tool
*
*/
class cmCTestBZR: public cmCTestGlobalVC
class cmCTestBZR : public cmCTestGlobalVC
{
public:
/** Construct with a CTest instance and update log stream. */
+27 -35
View File
@@ -30,18 +30,17 @@ void cmCTestBatchTestHandler::RunTests()
void cmCTestBatchTestHandler::WriteBatchScript()
{
this->Script = this->CTest->GetBinaryDir()
+ "/Testing/CTestBatch.txt";
this->Script = this->CTest->GetBinaryDir() + "/Testing/CTestBatch.txt";
cmsys::ofstream fout;
fout.open(this->Script.c_str());
fout << "#!/bin/sh\n";
for(TestMap::iterator i = this->Tests.begin(); i != this->Tests.end(); ++i)
{
for (TestMap::iterator i = this->Tests.begin(); i != this->Tests.end();
++i) {
this->WriteSrunArgs(i->first, fout);
this->WriteTestCommand(i->first, fout);
fout << "\n";
}
}
fout.flush();
fout.close();
}
@@ -49,13 +48,13 @@ void cmCTestBatchTestHandler::WriteBatchScript()
void cmCTestBatchTestHandler::WriteSrunArgs(int test, cmsys::ofstream& fout)
{
cmCTestTestHandler::cmCTestTestProperties* properties =
this->Properties[test];
this->Properties[test];
fout << "srun ";
//fout << "--jobid=" << test << " ";
// fout << "--jobid=" << test << " ";
fout << "-J=" << properties->Name << " ";
//Write dependency information
// Write dependency information
/*if(!this->Tests[test].empty())
{
fout << "-P=afterany";
@@ -66,14 +65,12 @@ void cmCTestBatchTestHandler::WriteSrunArgs(int test, cmsys::ofstream& fout)
}
fout << " ";
}*/
if(properties->RunSerial)
{
if (properties->RunSerial) {
fout << "--exclusive ";
}
if(properties->Processors > 1)
{
}
if (properties->Processors > 1) {
fout << "-n" << properties->Processors << " ";
}
}
}
void cmCTestBatchTestHandler::WriteTestCommand(int test, cmsys::ofstream& fout)
@@ -85,36 +82,32 @@ void cmCTestBatchTestHandler::WriteTestCommand(int test, cmsys::ofstream& fout)
command = this->TestHandler->FindTheExecutable(args[1].c_str());
command = cmSystemTools::ConvertToOutputPath(command.c_str());
//Prepends memcheck args to our command string if this is a memcheck
// Prepends memcheck args to our command string if this is a memcheck
this->TestHandler->GenerateTestCommand(processArgs, test);
processArgs.push_back(command);
for(std::vector<std::string>::iterator arg = processArgs.begin();
arg != processArgs.end(); ++arg)
{
for (std::vector<std::string>::iterator arg = processArgs.begin();
arg != processArgs.end(); ++arg) {
fout << *arg << " ";
}
}
std::vector<std::string>::iterator i = args.begin();
++i; //the test name
++i; //the executable (command)
if(args.size() > 2)
{
++i; // the test name
++i; // the executable (command)
if (args.size() > 2) {
fout << "'";
}
while(i != args.end())
{
fout << "\"" << *i << "\""; //args to the test executable
}
while (i != args.end()) {
fout << "\"" << *i << "\""; // args to the test executable
++i;
if(i == args.end() && args.size() > 2)
{
if (i == args.end() && args.size() > 2) {
fout << "'";
}
fout << " ";
}
//TODO ZACH build TestResult.FullCommandLine
//this->TestResult.FullCommandLine = this->TestCommand;
fout << " ";
}
// TODO ZACH build TestResult.FullCommandLine
// this->TestResult.FullCommandLine = this->TestCommand;
}
void cmCTestBatchTestHandler::SubmitBatchScript()
@@ -123,8 +116,7 @@ void cmCTestBatchTestHandler::SubmitBatchScript()
std::vector<std::string> args;
args.push_back(this->Script);
args.push_back("-o");
args.push_back(this->CTest->GetBinaryDir()
+ "/Testing/CTestBatch.txt");
args.push_back(this->CTest->GetBinaryDir() + "/Testing/CTestBatch.txt");
sbatch.SetCommand("sbatch");
sbatch.SetCommandArguments(args);
+1
View File
@@ -30,6 +30,7 @@ class cmCTestBatchTestHandler : public cmCTestMultiProcessHandler
public:
~cmCTestBatchTestHandler();
virtual void RunTests();
protected:
void WriteBatchScript();
void WriteSrunArgs(int test, cmsys::ofstream& fout);
+167 -255
View File
@@ -21,9 +21,9 @@
cmCTestBuildAndTestHandler::cmCTestBuildAndTestHandler()
{
this->BuildTwoConfig = false;
this->BuildNoClean = false;
this->BuildNoCMake = false;
this->BuildTwoConfig = false;
this->BuildNoClean = false;
this->BuildNoCMake = false;
this->Timeout = 0;
}
@@ -48,91 +48,75 @@ int cmCTestBuildAndTestHandler::ProcessHandler()
}
int cmCTestBuildAndTestHandler::RunCMake(std::string* outstring,
std::ostringstream &out, std::string &cmakeOutString, std::string &cwd,
cmake *cm)
std::ostringstream& out,
std::string& cmakeOutString,
std::string& cwd, cmake* cm)
{
unsigned int k;
std::vector<std::string> args;
args.push_back(cmSystemTools::GetCMakeCommand());
args.push_back(this->SourceDir);
if(!this->BuildGenerator.empty())
{
if (!this->BuildGenerator.empty()) {
std::string generator = "-G";
generator += this->BuildGenerator;
args.push_back(generator);
}
if(!this->BuildGeneratorPlatform.empty())
{
}
if (!this->BuildGeneratorPlatform.empty()) {
std::string platform = "-A";
platform += this->BuildGeneratorPlatform;
args.push_back(platform);
}
if(!this->BuildGeneratorToolset.empty())
{
}
if (!this->BuildGeneratorToolset.empty()) {
std::string toolset = "-T";
toolset += this->BuildGeneratorToolset;
args.push_back(toolset);
}
}
const char* config = 0;
if (!this->CTest->GetConfigType().empty())
{
if (!this->CTest->GetConfigType().empty()) {
config = this->CTest->GetConfigType().c_str();
}
}
#ifdef CMAKE_INTDIR
if(!config)
{
if (!config) {
config = CMAKE_INTDIR;
}
}
#endif
if ( config )
{
std::string btype
= "-DCMAKE_BUILD_TYPE:STRING=" + std::string(config);
if (config) {
std::string btype = "-DCMAKE_BUILD_TYPE:STRING=" + std::string(config);
args.push_back(btype);
}
}
for(k=0; k < this->BuildOptions.size(); ++k)
{
for (k = 0; k < this->BuildOptions.size(); ++k) {
args.push_back(this->BuildOptions[k]);
}
if (cm->Run(args) != 0)
{
}
if (cm->Run(args) != 0) {
out << "Error: cmake execution failed\n";
out << cmakeOutString << "\n";
// return to the original directory
cmSystemTools::ChangeDirectory(cwd);
if(outstring)
{
if (outstring) {
*outstring = out.str();
}
else
{
} else {
cmCTestLog(this->CTest, ERROR_MESSAGE, out.str() << std::endl);
}
return 1;
}
return 1;
}
// do another config?
if(this->BuildTwoConfig)
{
if (cm->Run(args) != 0)
{
if (this->BuildTwoConfig) {
if (cm->Run(args) != 0) {
out << "Error: cmake execution failed\n";
out << cmakeOutString << "\n";
// return to the original directory
cmSystemTools::ChangeDirectory(cwd);
if(outstring)
{
if (outstring) {
*outstring = out.str();
}
else
{
} else {
cmCTestLog(this->CTest, ERROR_MESSAGE, out.str() << std::endl);
}
return 1;
}
return 1;
}
}
out << "======== CMake output ======\n";
out << cmakeOutString;
out << "======== End CMake output ======\n";
@@ -146,7 +130,7 @@ void CMakeMessageCallback(const char* m, const char*, bool&, void* s)
*out += "\n";
}
void CMakeProgressCallback(const char*msg, float , void * s)
void CMakeProgressCallback(const char* msg, float, void* s)
{
std::string* out = (std::string*)s;
*out += msg;
@@ -162,37 +146,36 @@ void CMakeOutputCallback(const char* m, size_t len, void* s)
class cmCTestBuildAndTestCaptureRAII
{
cmake& CM;
public:
cmCTestBuildAndTestCaptureRAII(cmake& cm, std::string& s): CM(cm)
{
cmCTestBuildAndTestCaptureRAII(cmake& cm, std::string& s)
: CM(cm)
{
cmSystemTools::SetMessageCallback(CMakeMessageCallback, &s);
cmSystemTools::SetStdoutCallback(CMakeOutputCallback, &s);
cmSystemTools::SetStderrCallback(CMakeOutputCallback, &s);
this->CM.SetProgressCallback(CMakeProgressCallback, &s);
}
}
~cmCTestBuildAndTestCaptureRAII()
{
{
this->CM.SetProgressCallback(0, 0);
cmSystemTools::SetStderrCallback(0, 0);
cmSystemTools::SetStdoutCallback(0, 0);
cmSystemTools::SetMessageCallback(0, 0);
}
}
};
int cmCTestBuildAndTestHandler::RunCMakeAndTest(std::string* outstring)
{
// if the generator and make program are not specified then it is an error
if (this->BuildGenerator.empty())
{
if(outstring)
{
*outstring =
"--build-and-test requires that the generator "
"be provided using the --build-generator "
"command line option. ";
}
return 1;
if (this->BuildGenerator.empty()) {
if (outstring) {
*outstring = "--build-and-test requires that the generator "
"be provided using the --build-generator "
"command line option. ";
}
return 1;
}
cmake cm;
cm.SetHomeDirectory("");
@@ -202,27 +185,21 @@ int cmCTestBuildAndTestHandler::RunCMakeAndTest(std::string* outstring)
static_cast<void>(captureRAII);
std::ostringstream out;
if ( this->CTest->GetConfigType().empty() &&
!this->ConfigSample.empty())
{
if (this->CTest->GetConfigType().empty() && !this->ConfigSample.empty()) {
// use the config sample to set the ConfigType
std::string fullPath;
std::string resultingConfig;
std::vector<std::string> extraPaths;
std::vector<std::string> failed;
fullPath =
cmCTestTestHandler::FindExecutable(this->CTest,
this->ConfigSample.c_str(),
resultingConfig,
extraPaths,
failed);
if (!fullPath.empty() && !resultingConfig.empty())
{
fullPath = cmCTestTestHandler::FindExecutable(
this->CTest, this->ConfigSample.c_str(), resultingConfig, extraPaths,
failed);
if (!fullPath.empty() && !resultingConfig.empty()) {
this->CTest->SetConfigType(resultingConfig.c_str());
}
out << "Using config sample with results: "
<< fullPath << " and " << resultingConfig << std::endl;
}
out << "Using config sample with results: " << fullPath << " and "
<< resultingConfig << std::endl;
}
// we need to honor the timeout specified, the timeout include cmake, build
// and test time
@@ -230,100 +207,79 @@ int cmCTestBuildAndTestHandler::RunCMakeAndTest(std::string* outstring)
// make sure the binary dir is there
std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
out << "Internal cmake changing into directory: "
<< this->BinaryDir << std::endl;
if (!cmSystemTools::FileIsDirectory(this->BinaryDir))
{
out << "Internal cmake changing into directory: " << this->BinaryDir
<< std::endl;
if (!cmSystemTools::FileIsDirectory(this->BinaryDir)) {
cmSystemTools::MakeDirectory(this->BinaryDir.c_str());
}
}
cmSystemTools::ChangeDirectory(this->BinaryDir);
if(this->BuildNoCMake)
{
if (this->BuildNoCMake) {
// Make the generator available for the Build call below.
cm.SetGlobalGenerator(cm.CreateGlobalGenerator(
this->BuildGenerator));
cm.SetGlobalGenerator(cm.CreateGlobalGenerator(this->BuildGenerator));
cm.SetGeneratorPlatform(this->BuildGeneratorPlatform);
cm.SetGeneratorToolset(this->BuildGeneratorToolset);
// Load the cache to make CMAKE_MAKE_PROGRAM available.
cm.LoadCache(this->BinaryDir);
}
else
{
} else {
// do the cmake step, no timeout here since it is not a sub process
if (this->RunCMake(outstring,out,cmakeOutString,cwd,&cm))
{
if (this->RunCMake(outstring, out, cmakeOutString, cwd, &cm)) {
return 1;
}
}
}
// do the build
std::vector<std::string>::iterator tarIt;
if (this->BuildTargets.empty())
{
if (this->BuildTargets.empty()) {
this->BuildTargets.push_back("");
}
for ( tarIt = this->BuildTargets.begin();
tarIt != this->BuildTargets.end(); ++ tarIt )
{
}
for (tarIt = this->BuildTargets.begin(); tarIt != this->BuildTargets.end();
++tarIt) {
double remainingTime = 0;
if (this->Timeout > 0)
{
if (this->Timeout > 0) {
remainingTime = this->Timeout - cmSystemTools::GetTime() + clock_start;
if (remainingTime <= 0)
{
if(outstring)
{
if (remainingTime <= 0) {
if (outstring) {
*outstring = "--build-and-test timeout exceeded. ";
}
return 1;
}
return 1;
}
}
std::string output;
const char* config = 0;
if (!this->CTest->GetConfigType().empty())
{
if (!this->CTest->GetConfigType().empty()) {
config = this->CTest->GetConfigType().c_str();
}
}
#ifdef CMAKE_INTDIR
if(!config)
{
if (!config) {
config = CMAKE_INTDIR;
}
}
#endif
if(!config)
{
if (!config) {
config = "Debug";
}
}
int retVal = cm.GetGlobalGenerator()->Build(
this->SourceDir, this->BinaryDir,
this->BuildProject, *tarIt,
output, this->BuildMakeProgram,
config,
!this->BuildNoClean,
false, false, remainingTime);
this->SourceDir, this->BinaryDir, this->BuildProject, *tarIt, output,
this->BuildMakeProgram, config, !this->BuildNoClean, false, false,
remainingTime);
out << output;
// if the build failed then return
if (retVal)
{
if(outstring)
{
*outstring = out.str();
}
return 1;
if (retVal) {
if (outstring) {
*outstring = out.str();
}
return 1;
}
if(outstring)
{
*outstring = out.str();
}
}
if (outstring) {
*outstring = out.str();
}
// if no test was specified then we are done
if (this->TestCommand.empty())
{
if (this->TestCommand.empty()) {
return 0;
}
}
// now run the compiled test if we can find it
// store the final location in fullPath
@@ -331,99 +287,80 @@ int cmCTestBuildAndTestHandler::RunCMakeAndTest(std::string* outstring)
std::string resultingConfig;
std::vector<std::string> extraPaths;
// if this->ExecutableDirectory is set try that as well
if (!this->ExecutableDirectory.empty())
{
if (!this->ExecutableDirectory.empty()) {
std::string tempPath = this->ExecutableDirectory;
tempPath += "/";
tempPath += this->TestCommand;
extraPaths.push_back(tempPath);
}
}
std::vector<std::string> failed;
fullPath =
cmCTestTestHandler::FindExecutable(this->CTest,
this->TestCommand.c_str(),
resultingConfig,
extraPaths,
failed);
cmCTestTestHandler::FindExecutable(this->CTest, this->TestCommand.c_str(),
resultingConfig, extraPaths, failed);
if(!cmSystemTools::FileExists(fullPath.c_str()))
{
if (!cmSystemTools::FileExists(fullPath.c_str())) {
out << "Could not find path to executable, perhaps it was not built: "
<< this->TestCommand << "\n";
<< this->TestCommand << "\n";
out << "tried to find it in these places:\n";
out << fullPath.c_str() << "\n";
for(unsigned int i=0; i < failed.size(); ++i)
{
for (unsigned int i = 0; i < failed.size(); ++i) {
out << failed[i] << "\n";
}
if(outstring)
{
*outstring = out.str();
}
else
{
}
if (outstring) {
*outstring = out.str();
} else {
cmCTestLog(this->CTest, ERROR_MESSAGE, out.str());
}
}
// return to the original directory
cmSystemTools::ChangeDirectory(cwd);
return 1;
}
}
std::vector<const char*> testCommand;
testCommand.push_back(fullPath.c_str());
for(size_t k=0; k < this->TestCommandArgs.size(); ++k)
{
for (size_t k = 0; k < this->TestCommandArgs.size(); ++k) {
testCommand.push_back(this->TestCommandArgs[k].c_str());
}
}
testCommand.push_back(0);
std::string outs;
int retval = 0;
// run the test from the this->BuildRunDir if set
if(!this->BuildRunDir.empty())
{
if (!this->BuildRunDir.empty()) {
out << "Run test in directory: " << this->BuildRunDir << "\n";
cmSystemTools::ChangeDirectory(this->BuildRunDir);
}
}
out << "Running test command: \"" << fullPath << "\"";
for(size_t k=0; k < this->TestCommandArgs.size(); ++k)
{
for (size_t k = 0; k < this->TestCommandArgs.size(); ++k) {
out << " \"" << this->TestCommandArgs[k] << "\"";
}
}
out << "\n";
// how much time is remaining
double remainingTime = 0;
if (this->Timeout > 0)
{
if (this->Timeout > 0) {
remainingTime = this->Timeout - cmSystemTools::GetTime() + clock_start;
if (remainingTime <= 0)
{
if(outstring)
{
if (remainingTime <= 0) {
if (outstring) {
*outstring = "--build-and-test timeout exceeded. ";
}
return 1;
}
return 1;
}
}
int runTestRes = this->CTest->RunTest(testCommand, &outs, &retval, 0,
remainingTime, 0);
int runTestRes =
this->CTest->RunTest(testCommand, &outs, &retval, 0, remainingTime, 0);
if(runTestRes != cmsysProcess_State_Exited || retval != 0)
{
if (runTestRes != cmsysProcess_State_Exited || retval != 0) {
out << "Test command failed: " << testCommand[0] << "\n";
retval = 1;
}
}
out << outs << "\n";
if(outstring)
{
if (outstring) {
*outstring = out.str();
}
else
{
} else {
cmCTestLog(this->CTest, OUTPUT, out.str() << std::endl);
}
}
return retval;
}
@@ -432,114 +369,89 @@ int cmCTestBuildAndTestHandler::ProcessCommandLineArguments(
const std::vector<std::string>& allArgs)
{
// --build-and-test options
if(currentArg.find("--build-and-test",0) == 0 && idx < allArgs.size() - 1)
{
if(idx+2 < allArgs.size())
{
if (currentArg.find("--build-and-test", 0) == 0 &&
idx < allArgs.size() - 1) {
if (idx + 2 < allArgs.size()) {
idx++;
this->SourceDir = allArgs[idx];
idx++;
this->BinaryDir = allArgs[idx];
// dir must exist before CollapseFullPath is called
cmSystemTools::MakeDirectory(this->BinaryDir.c_str());
this->BinaryDir
= cmSystemTools::CollapseFullPath(this->BinaryDir);
this->SourceDir
= cmSystemTools::CollapseFullPath(this->SourceDir);
}
else
{
this->BinaryDir = cmSystemTools::CollapseFullPath(this->BinaryDir);
this->SourceDir = cmSystemTools::CollapseFullPath(this->SourceDir);
} else {
cmCTestLog(this->CTest, ERROR_MESSAGE,
"--build-and-test must have source and binary dir" << std::endl);
"--build-and-test must have source and binary dir"
<< std::endl);
return 0;
}
}
if(currentArg.find("--build-target",0) == 0 && idx < allArgs.size() - 1)
{
}
if (currentArg.find("--build-target", 0) == 0 && idx < allArgs.size() - 1) {
idx++;
this->BuildTargets.push_back(allArgs[idx]);
}
if(currentArg.find("--build-nocmake",0) == 0)
{
}
if (currentArg.find("--build-nocmake", 0) == 0) {
this->BuildNoCMake = true;
}
if(currentArg.find("--build-run-dir",0) == 0 && idx < allArgs.size() - 1)
{
}
if (currentArg.find("--build-run-dir", 0) == 0 && idx < allArgs.size() - 1) {
idx++;
this->BuildRunDir = allArgs[idx];
}
if(currentArg.find("--build-two-config",0) == 0)
{
}
if (currentArg.find("--build-two-config", 0) == 0) {
this->BuildTwoConfig = true;
}
if(currentArg.find("--build-exe-dir",0) == 0 && idx < allArgs.size() - 1)
{
}
if (currentArg.find("--build-exe-dir", 0) == 0 && idx < allArgs.size() - 1) {
idx++;
this->ExecutableDirectory = allArgs[idx];
}
if(currentArg.find("--test-timeout",0) == 0 && idx < allArgs.size() - 1)
{
}
if (currentArg.find("--test-timeout", 0) == 0 && idx < allArgs.size() - 1) {
idx++;
this->Timeout = atof(allArgs[idx].c_str());
}
if(currentArg == "--build-generator" && idx < allArgs.size() - 1)
{
}
if (currentArg == "--build-generator" && idx < allArgs.size() - 1) {
idx++;
this->BuildGenerator = allArgs[idx];
}
if(currentArg == "--build-generator-platform" &&
idx < allArgs.size() - 1)
{
}
if (currentArg == "--build-generator-platform" && idx < allArgs.size() - 1) {
idx++;
this->BuildGeneratorPlatform = allArgs[idx];
}
if(currentArg == "--build-generator-toolset" &&
idx < allArgs.size() - 1)
{
}
if (currentArg == "--build-generator-toolset" && idx < allArgs.size() - 1) {
idx++;
this->BuildGeneratorToolset = allArgs[idx];
}
if(currentArg.find("--build-project",0) == 0 && idx < allArgs.size() - 1)
{
}
if (currentArg.find("--build-project", 0) == 0 && idx < allArgs.size() - 1) {
idx++;
this->BuildProject = allArgs[idx];
}
if(currentArg.find("--build-makeprogram",0) == 0 &&
idx < allArgs.size() - 1)
{
}
if (currentArg.find("--build-makeprogram", 0) == 0 &&
idx < allArgs.size() - 1) {
idx++;
this->BuildMakeProgram = allArgs[idx];
}
if(currentArg.find("--build-config-sample",0) == 0 &&
idx < allArgs.size() - 1)
{
}
if (currentArg.find("--build-config-sample", 0) == 0 &&
idx < allArgs.size() - 1) {
idx++;
this->ConfigSample = allArgs[idx];
}
if(currentArg.find("--build-noclean",0) == 0)
{
}
if (currentArg.find("--build-noclean", 0) == 0) {
this->BuildNoClean = true;
}
if(currentArg.find("--build-options",0) == 0)
{
while(idx+1 < allArgs.size() &&
allArgs[idx+1] != "--build-target" &&
allArgs[idx+1] != "--test-command")
{
}
if (currentArg.find("--build-options", 0) == 0) {
while (idx + 1 < allArgs.size() && allArgs[idx + 1] != "--build-target" &&
allArgs[idx + 1] != "--test-command") {
++idx;
this->BuildOptions.push_back(allArgs[idx]);
}
}
if(currentArg.find("--test-command",0) == 0 && idx < allArgs.size() - 1)
{
}
if (currentArg.find("--test-command", 0) == 0 && idx < allArgs.size() - 1) {
++idx;
this->TestCommand = allArgs[idx];
while(idx+1 < allArgs.size())
{
while (idx + 1 < allArgs.size()) {
++idx;
this->TestCommandArgs.push_back(allArgs[idx]);
}
}
}
return 1;
}
+18 -21
View File
@@ -13,7 +13,6 @@
#ifndef cmCTestBuildAndTestHandler_h
#define cmCTestBuildAndTestHandler_h
#include "cmCTestGenericHandler.h"
#include "cmListFileCache.h"
@@ -50,31 +49,29 @@ public:
protected:
///! Run CMake and build a test and then run it as a single test.
int RunCMakeAndTest(std::string* output);
int RunCMake(std::string* outstring, std::ostringstream &out,
std::string &cmakeOutString,
std::string &cwd, cmake *cm);
int RunCMake(std::string* outstring, std::ostringstream& out,
std::string& cmakeOutString, std::string& cwd, cmake* cm);
std::string Output;
std::string Output;
std::string BuildGenerator;
std::string BuildGeneratorPlatform;
std::string BuildGeneratorToolset;
std::string BuildGenerator;
std::string BuildGeneratorPlatform;
std::string BuildGeneratorToolset;
std::vector<std::string> BuildOptions;
bool BuildTwoConfig;
std::string BuildMakeProgram;
std::string ConfigSample;
std::string SourceDir;
std::string BinaryDir;
std::string BuildProject;
std::string TestCommand;
bool BuildNoClean;
std::string BuildRunDir;
std::string ExecutableDirectory;
bool BuildTwoConfig;
std::string BuildMakeProgram;
std::string ConfigSample;
std::string SourceDir;
std::string BinaryDir;
std::string BuildProject;
std::string TestCommand;
bool BuildNoClean;
std::string BuildRunDir;
std::string ExecutableDirectory;
std::vector<std::string> TestCommandArgs;
std::vector<std::string> BuildTargets;
bool BuildNoCMake;
double Timeout;
bool BuildNoCMake;
double Timeout;
};
#endif
+62 -83
View File
@@ -17,7 +17,6 @@
#include "cmGlobalGenerator.h"
#include "cmake.h"
cmCTestBuildCommand::cmCTestBuildCommand()
{
this->GlobalGenerator = 0;
@@ -33,37 +32,31 @@ cmCTestBuildCommand::cmCTestBuildCommand()
cmCTestBuildCommand::~cmCTestBuildCommand()
{
if ( this->GlobalGenerator )
{
if (this->GlobalGenerator) {
delete this->GlobalGenerator;
this->GlobalGenerator = 0;
}
}
}
cmCTestGenericHandler* cmCTestBuildCommand::InitializeHandler()
{
cmCTestGenericHandler* handler
= this->CTest->GetInitializedHandler("build");
if ( !handler )
{
cmCTestGenericHandler* handler = this->CTest->GetInitializedHandler("build");
if (!handler) {
this->SetError("internal CTest error. Cannot instantiate build handler");
return 0;
}
this->Handler = (cmCTestBuildHandler*)handler;
}
this->Handler = (cmCTestBuildHandler*)handler;
const char* ctestBuildCommand
= this->Makefile->GetDefinition("CTEST_BUILD_COMMAND");
if ( ctestBuildCommand && *ctestBuildCommand )
{
const char* ctestBuildCommand =
this->Makefile->GetDefinition("CTEST_BUILD_COMMAND");
if (ctestBuildCommand && *ctestBuildCommand) {
this->CTest->SetCTestConfiguration("MakeCommand", ctestBuildCommand,
this->Quiet);
}
else
{
const char* cmakeGeneratorName
= this->Makefile->GetDefinition("CTEST_CMAKE_GENERATOR");
const char* cmakeProjectName
= (this->Values[ctb_PROJECT_NAME] && *this->Values[ctb_PROJECT_NAME])
this->Quiet);
} else {
const char* cmakeGeneratorName =
this->Makefile->GetDefinition("CTEST_CMAKE_GENERATOR");
const char* cmakeProjectName =
(this->Values[ctb_PROJECT_NAME] && *this->Values[ctb_PROJECT_NAME])
? this->Values[ctb_PROJECT_NAME]
: this->Makefile->GetDefinition("CTEST_PROJECT_NAME");
@@ -72,81 +65,71 @@ cmCTestGenericHandler* cmCTestBuildCommand::InitializeHandler()
// CTEST_CONFIGURATION_TYPE script variable, or ctest -C command
// line argument... in that order.
//
const char* ctestBuildConfiguration
= this->Makefile->GetDefinition("CTEST_BUILD_CONFIGURATION");
const char* cmakeBuildConfiguration
= (this->Values[ctb_CONFIGURATION] && *this->Values[ctb_CONFIGURATION])
const char* ctestBuildConfiguration =
this->Makefile->GetDefinition("CTEST_BUILD_CONFIGURATION");
const char* cmakeBuildConfiguration =
(this->Values[ctb_CONFIGURATION] && *this->Values[ctb_CONFIGURATION])
? this->Values[ctb_CONFIGURATION]
: ((ctestBuildConfiguration && *ctestBuildConfiguration)
? ctestBuildConfiguration
: this->CTest->GetConfigType().c_str());
? ctestBuildConfiguration
: this->CTest->GetConfigType().c_str());
const char* cmakeBuildAdditionalFlags
= (this->Values[ctb_FLAGS] && *this->Values[ctb_FLAGS])
const char* cmakeBuildAdditionalFlags =
(this->Values[ctb_FLAGS] && *this->Values[ctb_FLAGS])
? this->Values[ctb_FLAGS]
: this->Makefile->GetDefinition("CTEST_BUILD_FLAGS");
const char* cmakeBuildTarget
= (this->Values[ctb_TARGET] && *this->Values[ctb_TARGET])
const char* cmakeBuildTarget =
(this->Values[ctb_TARGET] && *this->Values[ctb_TARGET])
? this->Values[ctb_TARGET]
: this->Makefile->GetDefinition("CTEST_BUILD_TARGET");
if ( cmakeGeneratorName && *cmakeGeneratorName &&
cmakeProjectName && *cmakeProjectName )
{
if ( !cmakeBuildConfiguration )
{
if (cmakeGeneratorName && *cmakeGeneratorName && cmakeProjectName &&
*cmakeProjectName) {
if (!cmakeBuildConfiguration) {
cmakeBuildConfiguration = "Release";
}
if ( this->GlobalGenerator )
{
if ( this->GlobalGenerator->GetName() != cmakeGeneratorName )
{
}
if (this->GlobalGenerator) {
if (this->GlobalGenerator->GetName() != cmakeGeneratorName) {
delete this->GlobalGenerator;
this->GlobalGenerator = 0;
}
}
if ( !this->GlobalGenerator )
{
}
if (!this->GlobalGenerator) {
this->GlobalGenerator =
this->Makefile->GetCMakeInstance()->CreateGlobalGenerator(
cmakeGeneratorName);
if(!this->GlobalGenerator)
{
if (!this->GlobalGenerator) {
std::string e = "could not create generator named \"";
e += cmakeGeneratorName;
e += "\"";
this->Makefile->IssueMessage(cmake::FATAL_ERROR, e);
cmSystemTools::SetFatalErrorOccured();
return 0;
}
}
if(strlen(cmakeBuildConfiguration) == 0)
{
}
if (strlen(cmakeBuildConfiguration) == 0) {
const char* config = 0;
#ifdef CMAKE_INTDIR
config = CMAKE_INTDIR;
#endif
if(!config)
{
if (!config) {
config = "Debug";
}
cmakeBuildConfiguration = config;
}
cmakeBuildConfiguration = config;
}
std::string dir = this->CTest->GetCTestConfiguration("BuildDirectory");
std::string buildCommand
= this->GlobalGenerator->
GenerateCMakeBuildCommand(cmakeBuildTarget ? cmakeBuildTarget : "",
cmakeBuildConfiguration,
std::string buildCommand =
this->GlobalGenerator->GenerateCMakeBuildCommand(
cmakeBuildTarget ? cmakeBuildTarget : "", cmakeBuildConfiguration,
cmakeBuildAdditionalFlags ? cmakeBuildAdditionalFlags : "",
this->Makefile->IgnoreErrorsCMP0061());
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"SetMakeCommand:" << buildCommand << "\n", this->Quiet);
"SetMakeCommand:" << buildCommand << "\n",
this->Quiet);
this->CTest->SetCTestConfiguration("MakeCommand", buildCommand.c_str(),
this->Quiet);
}
else
{
this->Quiet);
} else {
std::ostringstream ostr;
/* clang-format off */
ostr << "has no project to build. If this is a "
@@ -163,39 +146,35 @@ cmCTestGenericHandler* cmCTestBuildCommand::InitializeHandler()
/* clang-format on */
this->SetError(ostr.str());
return 0;
}
}
}
if(const char* useLaunchers =
this->Makefile->GetDefinition("CTEST_USE_LAUNCHERS"))
{
if (const char* useLaunchers =
this->Makefile->GetDefinition("CTEST_USE_LAUNCHERS")) {
this->CTest->SetCTestConfiguration("UseLaunchers", useLaunchers,
this->Quiet);
}
this->Quiet);
}
handler->SetQuiet(this->Quiet);
return handler;
}
bool cmCTestBuildCommand::InitialPass(std::vector<std::string> const& args,
cmExecutionStatus &status)
cmExecutionStatus& status)
{
bool ret = cmCTestHandlerCommand::InitialPass(args, status);
if ( this->Values[ctb_NUMBER_ERRORS] && *this->Values[ctb_NUMBER_ERRORS])
{
bool ret = cmCTestHandlerCommand::InitialPass(args, status);
if (this->Values[ctb_NUMBER_ERRORS] && *this->Values[ctb_NUMBER_ERRORS]) {
std::ostringstream str;
str << this->Handler->GetTotalErrors();
this->Makefile->AddDefinition(
this->Values[ctb_NUMBER_ERRORS], str.str().c_str());
}
if ( this->Values[ctb_NUMBER_WARNINGS]
&& *this->Values[ctb_NUMBER_WARNINGS])
{
this->Makefile->AddDefinition(this->Values[ctb_NUMBER_ERRORS],
str.str().c_str());
}
if (this->Values[ctb_NUMBER_WARNINGS] &&
*this->Values[ctb_NUMBER_WARNINGS]) {
std::ostringstream str;
str << this->Handler->GetTotalWarnings();
this->Makefile->AddDefinition(
this->Values[ctb_NUMBER_WARNINGS], str.str().c_str());
}
this->Makefile->AddDefinition(this->Values[ctb_NUMBER_WARNINGS],
str.str().c_str());
}
return ret;
}
+6 -7
View File
@@ -25,7 +25,6 @@ class cmCTestBuildHandler;
class cmCTestBuildCommand : public cmCTestHandlerCommand
{
public:
cmCTestBuildCommand();
~cmCTestBuildCommand();
@@ -33,20 +32,20 @@ public:
* This is a virtual constructor for the command.
*/
virtual cmCommand* Clone()
{
{
cmCTestBuildCommand* ni = new cmCTestBuildCommand;
ni->CTest = this->CTest;
ni->CTestScriptHandler = this->CTestScriptHandler;
return ni;
}
}
/**
* The name of the command as specified in CMakeList.txt.
*/
virtual std::string GetName() const { return "ctest_build";}
virtual std::string GetName() const { return "ctest_build"; }
virtual bool InitialPass(std::vector<std::string> const& args,
cmExecutionStatus &status);
cmExecutionStatus& status);
cmTypeMacro(cmCTestBuildCommand, cmCTestHandlerCommand);
@@ -54,7 +53,8 @@ public:
protected:
cmCTestBuildHandler* Handler;
enum {
enum
{
ctb_BUILD = ct_LAST,
ctb_NUMBER_ERRORS,
ctb_NUMBER_WARNINGS,
@@ -68,5 +68,4 @@ protected:
cmCTestGenericHandler* InitializeHandler();
};
#endif
+413 -528
View File
@@ -36,7 +36,6 @@
#include <stdlib.h>
#include <time.h>
static const char* cmCTestErrorMatches[] = {
"^[Bb]us [Ee]rror",
"^[Ss]egmentation [Vv]iolation",
@@ -163,16 +162,15 @@ struct cmCTestBuildCompileErrorWarningRex
int LineIndex;
};
static cmCTestBuildCompileErrorWarningRex
cmCTestWarningErrorFileLine[] = {
{ "^Warning W[0-9]+ ([a-zA-Z.\\:/0-9_+ ~-]+) ([0-9]+):", 1, 2 },
{ "^([a-zA-Z./0-9_+ ~-]+):([0-9]+):", 1, 2 },
{ "^([a-zA-Z.\\:/0-9_+ ~-]+)\\(([0-9]+)\\)", 1, 2 },
{ "^[0-9]+>([a-zA-Z.\\:/0-9_+ ~-]+)\\(([0-9]+)\\)", 1, 2 },
{ "^([a-zA-Z./0-9_+ ~-]+)\\(([0-9]+)\\)", 1, 2 },
{ "\"([a-zA-Z./0-9_+ ~-]+)\", line ([0-9]+)", 1, 2 },
{ "File = ([a-zA-Z./0-9_+ ~-]+), Line = ([0-9]+)", 1, 2 },
{ 0, 0, 0 }
static cmCTestBuildCompileErrorWarningRex cmCTestWarningErrorFileLine[] = {
{ "^Warning W[0-9]+ ([a-zA-Z.\\:/0-9_+ ~-]+) ([0-9]+):", 1, 2 },
{ "^([a-zA-Z./0-9_+ ~-]+):([0-9]+):", 1, 2 },
{ "^([a-zA-Z.\\:/0-9_+ ~-]+)\\(([0-9]+)\\)", 1, 2 },
{ "^[0-9]+>([a-zA-Z.\\:/0-9_+ ~-]+)\\(([0-9]+)\\)", 1, 2 },
{ "^([a-zA-Z./0-9_+ ~-]+)\\(([0-9]+)\\)", 1, 2 },
{ "\"([a-zA-Z./0-9_+ ~-]+)\", line ([0-9]+)", 1, 2 },
{ "File = ([a-zA-Z./0-9_+ ~-]+), Line = ([0-9]+)", 1, 2 },
{ 0, 0, 0 }
};
cmCTestBuildHandler::cmCTestBuildHandler()
@@ -233,131 +231,113 @@ void cmCTestBuildHandler::Initialize()
this->UseCTestLaunch = false;
}
void cmCTestBuildHandler::PopulateCustomVectors(cmMakefile *mf)
void cmCTestBuildHandler::PopulateCustomVectors(cmMakefile* mf)
{
this->CTest->PopulateCustomVector(mf, "CTEST_CUSTOM_ERROR_MATCH",
this->CustomErrorMatches);
this->CustomErrorMatches);
this->CTest->PopulateCustomVector(mf, "CTEST_CUSTOM_ERROR_EXCEPTION",
this->CustomErrorExceptions);
this->CustomErrorExceptions);
this->CTest->PopulateCustomVector(mf, "CTEST_CUSTOM_WARNING_MATCH",
this->CustomWarningMatches);
this->CustomWarningMatches);
this->CTest->PopulateCustomVector(mf, "CTEST_CUSTOM_WARNING_EXCEPTION",
this->CustomWarningExceptions);
this->CTest->PopulateCustomInteger(mf,
"CTEST_CUSTOM_MAXIMUM_NUMBER_OF_ERRORS",
this->MaxErrors);
this->CTest->PopulateCustomInteger(mf,
"CTEST_CUSTOM_MAXIMUM_NUMBER_OF_WARNINGS",
this->MaxWarnings);
this->CustomWarningExceptions);
this->CTest->PopulateCustomInteger(
mf, "CTEST_CUSTOM_MAXIMUM_NUMBER_OF_ERRORS", this->MaxErrors);
this->CTest->PopulateCustomInteger(
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)
{
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)
{
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"))
{
if (const char* customWarningMatchers =
mf->GetDefinition("CTEST_CUSTOM_WARNING_MATCH")) {
cmSystemTools::ExpandListArgument(customWarningMatchers,
this->ReallyCustomWarningMatches);
}
if(const char* customWarningExceptions =
mf->GetDefinition("CTEST_CUSTOM_WARNING_EXCEPTION"))
{
}
if (const char* customWarningExceptions =
mf->GetDefinition("CTEST_CUSTOM_WARNING_EXCEPTION")) {
cmSystemTools::ExpandListArgument(customWarningExceptions,
this->ReallyCustomWarningExceptions);
}
}
}
std::string cmCTestBuildHandler::GetMakeCommand()
{
std::string makeCommand
= this->CTest->GetCTestConfiguration("MakeCommand");
cmCTestOptionalLog(this->CTest,
HANDLER_VERBOSE_OUTPUT, "MakeCommand:" << makeCommand << "\n",
this->Quiet);
std::string makeCommand = this->CTest->GetCTestConfiguration("MakeCommand");
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"MakeCommand:" << makeCommand << "\n", this->Quiet);
std::string configType = this->CTest->GetConfigType();
if (configType == "")
{
configType
= this->CTest->GetCTestConfiguration("DefaultCTestConfigurationType");
}
if (configType == "")
{
if (configType == "") {
configType =
this->CTest->GetCTestConfiguration("DefaultCTestConfigurationType");
}
if (configType == "") {
configType = "Release";
}
}
cmSystemTools::ReplaceString(makeCommand,
"${CTEST_CONFIGURATION_TYPE}", configType.c_str());
cmSystemTools::ReplaceString(makeCommand, "${CTEST_CONFIGURATION_TYPE}",
configType.c_str());
return makeCommand;
}
//clearly it would be nice if this were broken up into a few smaller
//functions and commented...
// clearly it would be nice if this were broken up into a few smaller
// functions and commented...
int cmCTestBuildHandler::ProcessHandler()
{
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "Build project" << std::endl,
this->Quiet);
this->Quiet);
// do we have time for this
if (this->CTest->GetRemainingTimeAllowed() < 120)
{
if (this->CTest->GetRemainingTimeAllowed() < 120) {
return 0;
}
}
int entry;
for ( entry = 0;
cmCTestWarningErrorFileLine[entry].RegularExpressionString;
++ entry )
{
for (entry = 0; cmCTestWarningErrorFileLine[entry].RegularExpressionString;
++entry) {
cmCTestBuildHandler::cmCTestCompileErrorWarningRex r;
if ( r.RegularExpression.compile(
cmCTestWarningErrorFileLine[entry].RegularExpressionString) )
{
if (r.RegularExpression.compile(
cmCTestWarningErrorFileLine[entry].RegularExpressionString)) {
r.FileIndex = cmCTestWarningErrorFileLine[entry].FileIndex;
r.LineIndex = cmCTestWarningErrorFileLine[entry].LineIndex;
this->ErrorWarningFileLineRegex.push_back(r);
}
else
{
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Problem Compiling regular expression: "
<< cmCTestWarningErrorFileLine[entry].RegularExpressionString
<< std::endl);
}
} else {
cmCTestLog(
this->CTest, ERROR_MESSAGE, "Problem Compiling regular expression: "
<< cmCTestWarningErrorFileLine[entry].RegularExpressionString
<< std::endl);
}
}
// Determine build command and build directory
std::string makeCommand = this->GetMakeCommand();
if (makeCommand.empty())
{
if (makeCommand.empty()) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Cannot find MakeCommand key in the DartConfiguration.tcl"
<< std::endl);
"Cannot find MakeCommand key in the DartConfiguration.tcl"
<< std::endl);
return -1;
}
}
const std::string &buildDirectory
= this->CTest->GetCTestConfiguration("BuildDirectory");
if (buildDirectory.empty())
{
const std::string& buildDirectory =
this->CTest->GetCTestConfiguration("BuildDirectory");
if (buildDirectory.empty()) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Cannot find BuildDirectory key in the DartConfiguration.tcl"
<< std::endl);
"Cannot find BuildDirectory key in the DartConfiguration.tcl"
<< std::endl);
return -1;
}
}
std::string const& useLaunchers =
this->CTest->GetCTestConfiguration("UseLaunchers");
@@ -366,94 +346,81 @@ int cmCTestBuildHandler::ProcessHandler()
// Create a last build log
cmGeneratedFileStream ofs;
double elapsed_time_start = cmSystemTools::GetTime();
if ( !this->StartLogFile("Build", ofs) )
{
if (!this->StartLogFile("Build", ofs)) {
cmCTestLog(this->CTest, ERROR_MESSAGE, "Cannot create build log file"
<< std::endl);
}
<< std::endl);
}
// Create lists of regular expression strings for errors, error exceptions,
// warnings and warning exceptions.
std::vector<std::string>::size_type cc;
for ( cc = 0; cmCTestErrorMatches[cc]; cc ++ )
{
for (cc = 0; cmCTestErrorMatches[cc]; cc++) {
this->CustomErrorMatches.push_back(cmCTestErrorMatches[cc]);
}
for ( cc = 0; cmCTestErrorExceptions[cc]; cc ++ )
{
}
for (cc = 0; cmCTestErrorExceptions[cc]; cc++) {
this->CustomErrorExceptions.push_back(cmCTestErrorExceptions[cc]);
}
for ( cc = 0; cmCTestWarningMatches[cc]; cc ++ )
{
}
for (cc = 0; cmCTestWarningMatches[cc]; cc++) {
this->CustomWarningMatches.push_back(cmCTestWarningMatches[cc]);
}
}
for ( cc = 0; cmCTestWarningExceptions[cc]; cc ++ )
{
for (cc = 0; cmCTestWarningExceptions[cc]; cc++) {
this->CustomWarningExceptions.push_back(cmCTestWarningExceptions[cc]);
}
}
// Pre-compile regular expressions objects for all regular expressions
std::vector<std::string>::iterator it;
#define cmCTestBuildHandlerPopulateRegexVector(strings, regexes) \
regexes.clear(); \
cmCTestOptionalLog(this->CTest, DEBUG, this << "Add " #regexes \
<< std::endl, this->Quiet); \
for ( it = strings.begin(); it != strings.end(); ++it ) \
{ \
cmCTestOptionalLog(this->CTest, DEBUG, "Add " #strings ": " \
<< *it << std::endl, this->Quiet); \
regexes.push_back(it->c_str()); \
}
cmCTestBuildHandlerPopulateRegexVector(
this->CustomErrorMatches, this->ErrorMatchRegex);
cmCTestBuildHandlerPopulateRegexVector(
this->CustomErrorExceptions, this->ErrorExceptionRegex);
cmCTestBuildHandlerPopulateRegexVector(
this->CustomWarningMatches, this->WarningMatchRegex);
cmCTestBuildHandlerPopulateRegexVector(
this->CustomWarningExceptions, this->WarningExceptionRegex);
#define cmCTestBuildHandlerPopulateRegexVector(strings, regexes) \
regexes.clear(); \
cmCTestOptionalLog(this->CTest, DEBUG, \
this << "Add " #regexes << std::endl, this->Quiet); \
for (it = strings.begin(); it != strings.end(); ++it) { \
cmCTestOptionalLog(this->CTest, DEBUG, \
"Add " #strings ": " << *it << std::endl, \
this->Quiet); \
regexes.push_back(it->c_str()); \
}
cmCTestBuildHandlerPopulateRegexVector(this->CustomErrorMatches,
this->ErrorMatchRegex);
cmCTestBuildHandlerPopulateRegexVector(this->CustomErrorExceptions,
this->ErrorExceptionRegex);
cmCTestBuildHandlerPopulateRegexVector(this->CustomWarningMatches,
this->WarningMatchRegex);
cmCTestBuildHandlerPopulateRegexVector(this->CustomWarningExceptions,
this->WarningExceptionRegex);
// Determine source and binary tree substitutions to simplify the output.
this->SimplifySourceDir = "";
this->SimplifyBuildDir = "";
if ( this->CTest->GetCTestConfiguration("SourceDirectory").size() > 20 )
{
std::string srcdir
= this->CTest->GetCTestConfiguration("SourceDirectory") + "/";
if (this->CTest->GetCTestConfiguration("SourceDirectory").size() > 20) {
std::string srcdir =
this->CTest->GetCTestConfiguration("SourceDirectory") + "/";
std::string srcdirrep;
for ( cc = srcdir.size()-2; cc > 0; cc -- )
{
if ( srcdir[cc] == '/' )
{
for (cc = srcdir.size() - 2; cc > 0; cc--) {
if (srcdir[cc] == '/') {
srcdirrep = srcdir.c_str() + cc;
srcdirrep = "/..." + srcdirrep;
srcdir = srcdir.substr(0, cc+1);
srcdir = srcdir.substr(0, cc + 1);
break;
}
}
this->SimplifySourceDir = srcdir;
}
if ( this->CTest->GetCTestConfiguration("BuildDirectory").size() > 20 )
{
std::string bindir
= this->CTest->GetCTestConfiguration("BuildDirectory") + "/";
this->SimplifySourceDir = srcdir;
}
if (this->CTest->GetCTestConfiguration("BuildDirectory").size() > 20) {
std::string bindir =
this->CTest->GetCTestConfiguration("BuildDirectory") + "/";
std::string bindirrep;
for ( cc = bindir.size()-2; cc > 0; cc -- )
{
if ( bindir[cc] == '/' )
{
for (cc = bindir.size() - 2; cc > 0; cc--) {
if (bindir[cc] == '/') {
bindirrep = bindir.c_str() + cc;
bindirrep = "/..." + bindirrep;
bindir = bindir.substr(0, cc+1);
bindir = bindir.substr(0, cc + 1);
break;
}
}
this->SimplifyBuildDir = bindir;
}
this->SimplifyBuildDir = bindir;
}
// Ok, let's do the build
@@ -462,16 +429,14 @@ int cmCTestBuildHandler::ProcessHandler()
this->StartBuildTime = cmSystemTools::GetTime();
int retVal = 0;
int res = cmsysProcess_State_Exited;
if ( !this->CTest->GetShowOnly() )
{
if (!this->CTest->GetShowOnly()) {
res = this->RunMakeCommand(makeCommand.c_str(), &retVal,
buildDirectory.c_str(), 0, ofs);
}
else
{
cmCTestOptionalLog(this->CTest, DEBUG, "Build with command: " <<
makeCommand << std::endl, this->Quiet);
}
buildDirectory.c_str(), 0, ofs);
} else {
cmCTestOptionalLog(this->CTest, DEBUG,
"Build with command: " << makeCommand << std::endl,
this->Quiet);
}
// Remember end build time and calculate elapsed time
this->EndBuild = this->CTest->CurrentTime();
@@ -480,69 +445,60 @@ int cmCTestBuildHandler::ProcessHandler()
// Cleanups strings in the errors and warnings list.
t_ErrorsAndWarningsVector::iterator evit;
if ( !this->SimplifySourceDir.empty() )
{
for ( evit = this->ErrorsAndWarnings.begin();
evit != this->ErrorsAndWarnings.end();
++ evit )
{
cmSystemTools::ReplaceString(
evit->Text, this->SimplifySourceDir.c_str(), "/.../");
cmSystemTools::ReplaceString(
evit->PreContext, this->SimplifySourceDir.c_str(), "/.../");
cmSystemTools::ReplaceString(
evit->PostContext, this->SimplifySourceDir.c_str(), "/.../");
}
if (!this->SimplifySourceDir.empty()) {
for (evit = this->ErrorsAndWarnings.begin();
evit != this->ErrorsAndWarnings.end(); ++evit) {
cmSystemTools::ReplaceString(evit->Text, this->SimplifySourceDir.c_str(),
"/.../");
cmSystemTools::ReplaceString(evit->PreContext,
this->SimplifySourceDir.c_str(), "/.../");
cmSystemTools::ReplaceString(evit->PostContext,
this->SimplifySourceDir.c_str(), "/.../");
}
}
if ( !this->SimplifyBuildDir.empty() )
{
for ( evit = this->ErrorsAndWarnings.begin();
evit != this->ErrorsAndWarnings.end();
++ evit )
{
cmSystemTools::ReplaceString(
evit->Text, this->SimplifyBuildDir.c_str(), "/.../");
cmSystemTools::ReplaceString(
evit->PreContext, this->SimplifyBuildDir.c_str(), "/.../");
cmSystemTools::ReplaceString(
evit->PostContext, this->SimplifyBuildDir.c_str(), "/.../");
}
if (!this->SimplifyBuildDir.empty()) {
for (evit = this->ErrorsAndWarnings.begin();
evit != this->ErrorsAndWarnings.end(); ++evit) {
cmSystemTools::ReplaceString(evit->Text, this->SimplifyBuildDir.c_str(),
"/.../");
cmSystemTools::ReplaceString(evit->PreContext,
this->SimplifyBuildDir.c_str(), "/.../");
cmSystemTools::ReplaceString(evit->PostContext,
this->SimplifyBuildDir.c_str(), "/.../");
}
}
// Generate XML output
cmGeneratedFileStream xofs;
if(!this->StartResultingXML(cmCTest::PartBuild, "Build", xofs))
{
if (!this->StartResultingXML(cmCTest::PartBuild, "Build", xofs)) {
cmCTestLog(this->CTest, ERROR_MESSAGE, "Cannot create build XML file"
<< std::endl);
<< std::endl);
return -1;
}
}
cmXMLWriter xml(xofs);
this->GenerateXMLHeader(xml);
if(this->UseCTestLaunch)
{
if (this->UseCTestLaunch) {
this->GenerateXMLLaunched(xml);
}
else
{
} else {
this->GenerateXMLLogScraped(xml);
}
}
this->GenerateXMLFooter(xml, elapsed_build_time);
if (res != cmsysProcess_State_Exited || retVal || this->TotalErrors > 0)
{
if (res != cmsysProcess_State_Exited || retVal || this->TotalErrors > 0) {
cmCTestLog(this->CTest, ERROR_MESSAGE, "Error(s) when building project"
<< std::endl);
}
<< std::endl);
}
// Display message about number of errors and warnings
cmCTestLog(this->CTest, HANDLER_OUTPUT, " " << this->TotalErrors
<< (this->TotalErrors >= this->MaxErrors ? " or more" : "")
<< " Compiler errors" << std::endl);
cmCTestLog(this->CTest, HANDLER_OUTPUT, " " << this->TotalWarnings
<< (this->TotalWarnings >= this->MaxWarnings ? " or more" : "")
<< " Compiler warnings" << std::endl);
cmCTestLog(this->CTest, HANDLER_OUTPUT, " "
<< this->TotalErrors
<< (this->TotalErrors >= this->MaxErrors ? " or more" : "")
<< " Compiler errors" << std::endl);
cmCTestLog(this->CTest, HANDLER_OUTPUT, " "
<< this->TotalWarnings
<< (this->TotalWarnings >= this->MaxWarnings ? " or more" : "")
<< " Compiler warnings" << std::endl);
return retVal;
}
@@ -553,40 +509,43 @@ void cmCTestBuildHandler::GenerateXMLHeader(cmXMLWriter& xml)
xml.StartElement("Build");
xml.Element("StartDateTime", this->StartBuild);
xml.Element("StartBuildTime",
static_cast<unsigned int>(this->StartBuildTime));
static_cast<unsigned int>(this->StartBuildTime));
xml.Element("BuildCommand", this->GetMakeCommand());
}
class cmCTestBuildHandler::FragmentCompare
{
public:
FragmentCompare(cmFileTimeComparison* ftc): FTC(ftc) {}
FragmentCompare(): FTC(0) {}
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
// among files with the same time.
int result;
if(this->FTC->FileTimeCompare(l.c_str(), r.c_str(), &result) &&
result != 0)
{
if (this->FTC->FileTimeCompare(l.c_str(), r.c_str(), &result) &&
result != 0) {
return result < 0;
}
else
{
} else {
return l < r;
}
}
}
private:
cmFileTimeComparison* FTC;
};
void cmCTestBuildHandler::GenerateXMLLaunched(cmXMLWriter& xml)
{
if(this->CTestLaunchDir.empty())
{
if (this->CTestLaunchDir.empty()) {
return;
}
}
// Sort XML fragments in chronological order.
cmFileTimeComparison ftc;
@@ -601,29 +560,24 @@ void cmCTestBuildHandler::GenerateXMLLaunched(cmXMLWriter& xml)
cmsys::Directory launchDir;
launchDir.Load(this->CTestLaunchDir);
unsigned long n = launchDir.GetNumberOfFiles();
for(unsigned long i=0; i < n; ++i)
{
for (unsigned long i = 0; i < n; ++i) {
const char* fname = launchDir.GetFile(i);
if(this->IsLaunchedErrorFile(fname) && numErrorsAllowed)
{
if (this->IsLaunchedErrorFile(fname) && numErrorsAllowed) {
numErrorsAllowed--;
fragments.insert(this->CTestLaunchDir + "/" + fname);
++this->TotalErrors;
}
else if(this->IsLaunchedWarningFile(fname) && numWarningsAllowed)
{
} else if (this->IsLaunchedWarningFile(fname) && numWarningsAllowed) {
numWarningsAllowed--;
fragments.insert(this->CTestLaunchDir + "/" + fname);
++this->TotalWarnings;
}
}
}
// Copy the fragments into the final XML file.
for(Fragments::const_iterator fi = fragments.begin();
fi != fragments.end(); ++fi)
{
for (Fragments::const_iterator fi = fragments.begin(); fi != fragments.end();
++fi) {
xml.FragmentFile(fi->c_str());
}
}
}
void cmCTestBuildHandler::GenerateXMLLogScraped(cmXMLWriter& xml)
@@ -639,87 +593,69 @@ void cmCTestBuildHandler::GenerateXMLLogScraped(cmXMLWriter& xml)
// via a call to collapse full path.
srcdir = cmSystemTools::CollapseFullPath(srcdir);
srcdir += "/";
for ( it = ew.begin();
it != ew.end() && (numErrorsAllowed || numWarningsAllowed); it++ )
{
cmCTestBuildErrorWarning *cm = &(*it);
for (it = ew.begin();
it != ew.end() && (numErrorsAllowed || numWarningsAllowed); it++) {
cmCTestBuildErrorWarning* cm = &(*it);
if ((cm->Error && numErrorsAllowed) ||
(!cm->Error && numWarningsAllowed))
{
if (cm->Error)
{
(!cm->Error && numWarningsAllowed)) {
if (cm->Error) {
numErrorsAllowed--;
}
else
{
} else {
numWarningsAllowed--;
}
}
xml.StartElement(cm->Error ? "Error" : "Warning");
xml.Element("BuildLogLine", cm->LogLine);
xml.Element("Text", cm->Text);
std::vector<cmCTestCompileErrorWarningRex>::iterator rit;
for ( rit = this->ErrorWarningFileLineRegex.begin();
rit != this->ErrorWarningFileLineRegex.end(); ++ rit )
{
for (rit = this->ErrorWarningFileLineRegex.begin();
rit != this->ErrorWarningFileLineRegex.end(); ++rit) {
cmsys::RegularExpression* re = &rit->RegularExpression;
if ( re->find(cm->Text.c_str() ) )
{
if (re->find(cm->Text.c_str())) {
cm->SourceFile = re->match(rit->FileIndex);
// At this point we need to make this->SourceFile relative to
// the source root of the project, so cvs links will work
cmSystemTools::ConvertToUnixSlashes(cm->SourceFile);
if(cm->SourceFile.find("/.../") != cm->SourceFile.npos)
{
if (cm->SourceFile.find("/.../") != cm->SourceFile.npos) {
cmSystemTools::ReplaceString(cm->SourceFile, "/.../", "");
std::string::size_type p = cm->SourceFile.find("/");
if(p != cm->SourceFile.npos)
{
cm->SourceFile = cm->SourceFile.substr(
p+1, cm->SourceFile.size()-p);
}
if (p != cm->SourceFile.npos) {
cm->SourceFile =
cm->SourceFile.substr(p + 1, cm->SourceFile.size() - p);
}
else
{
} else {
// make sure it is a full path with the correct case
cm->SourceFile = cmSystemTools::CollapseFullPath(
cm->SourceFile);
cmSystemTools::ReplaceString(
cm->SourceFile, srcdir.c_str(), "");
}
cm->SourceFile = cmSystemTools::CollapseFullPath(cm->SourceFile);
cmSystemTools::ReplaceString(cm->SourceFile, srcdir.c_str(), "");
}
cm->LineNumber = atoi(re->match(rit->LineIndex).c_str());
break;
}
}
if ( !cm->SourceFile.empty() && cm->LineNumber >= 0 )
{
if (!cm->SourceFile.empty())
{
}
if (!cm->SourceFile.empty() && cm->LineNumber >= 0) {
if (!cm->SourceFile.empty()) {
xml.Element("SourceFile", cm->SourceFile);
}
if (!cm->SourceFileTail.empty())
{
xml.Element("SourceFileTail", cm->SourceFileTail);
}
if ( cm->LineNumber >= 0 )
{
xml.Element("SourceLineNumber", cm->LineNumber);
}
}
if (!cm->SourceFileTail.empty()) {
xml.Element("SourceFileTail", cm->SourceFileTail);
}
if (cm->LineNumber >= 0) {
xml.Element("SourceLineNumber", cm->LineNumber);
}
}
xml.Element("PreContext", cm->PreContext);
xml.StartElement("PostContext");
xml.Content(cm->PostContext);
// is this the last warning or error, if so notify
if ((cm->Error && !numErrorsAllowed) ||
(!cm->Error && !numWarningsAllowed))
{
(!cm->Error && !numWarningsAllowed)) {
xml.Content("\nThe maximum number of reported warnings or errors "
"has been reached!!!\n");
}
"has been reached!!!\n");
}
xml.EndElement(); // PostContext
xml.Element("RepeatCount", "0");
xml.EndElement(); // "Error" / "Warning"
}
}
}
}
void cmCTestBuildHandler::GenerateXMLFooter(cmXMLWriter& xml,
@@ -732,7 +668,8 @@ void cmCTestBuildHandler::GenerateXMLFooter(cmXMLWriter& xml,
xml.Element("EndDateTime", this->EndBuild);
xml.Element("EndBuildTime", static_cast<unsigned int>(this->EndBuildTime));
xml.Element("ElapsedMinutes", static_cast<int>(elapsed_build_time/6)/10.0);
xml.Element("ElapsedMinutes",
static_cast<int>(elapsed_build_time / 6) / 10.0);
xml.EndElement(); // Build
this->CTest->EndXML(xml);
}
@@ -741,14 +678,14 @@ bool cmCTestBuildHandler::IsLaunchedErrorFile(const char* fname)
{
// error-{hash}.xml
return (cmHasLiteralPrefix(fname, "error-") &&
strcmp(fname+strlen(fname)-4, ".xml") == 0);
strcmp(fname + strlen(fname) - 4, ".xml") == 0);
}
bool cmCTestBuildHandler::IsLaunchedWarningFile(const char* fname)
{
// warning-{hash}.xml
return (cmHasLiteralPrefix(fname, "warning-") &&
strcmp(fname+strlen(fname)-4, ".xml") == 0);
strcmp(fname + strlen(fname) - 4, ".xml") == 0);
}
//######################################################################
@@ -761,6 +698,7 @@ class cmCTestBuildHandler::LaunchHelper
public:
LaunchHelper(cmCTestBuildHandler* handler);
~LaunchHelper();
private:
cmCTestBuildHandler* Handler;
cmCTest* CTest;
@@ -770,18 +708,16 @@ private:
std::vector<std::string> const& matchers);
};
cmCTestBuildHandler::LaunchHelper::LaunchHelper(cmCTestBuildHandler* handler):
Handler(handler), CTest(handler->CTest)
cmCTestBuildHandler::LaunchHelper::LaunchHelper(cmCTestBuildHandler* handler)
: Handler(handler)
, CTest(handler->CTest)
{
std::string tag = this->CTest->GetCurrentTag();
if(tag.empty())
{
if (tag.empty()) {
// This is not for a dashboard submission, so there is no XML.
// Skip enabling the launchers.
this->Handler->UseCTestLaunch = false;
}
else
{
} else {
// Compute a directory in which to store launcher fragments.
std::string& launchDir = this->Handler->CTestLaunchDir;
launchDir = this->CTest->GetBinaryDir();
@@ -792,30 +728,27 @@ cmCTestBuildHandler::LaunchHelper::LaunchHelper(cmCTestBuildHandler* handler):
// Clean out any existing launcher fragments.
cmSystemTools::RemoveADirectory(launchDir);
if(this->Handler->UseCTestLaunch)
{
if (this->Handler->UseCTestLaunch) {
// Enable launcher fragments.
cmSystemTools::MakeDirectory(launchDir.c_str());
this->WriteLauncherConfig();
std::string launchEnv = "CTEST_LAUNCH_LOGS=";
launchEnv += launchDir;
cmSystemTools::PutEnv(launchEnv);
}
}
}
// If not using launchers, make sure they passthru.
if(!this->Handler->UseCTestLaunch)
{
if (!this->Handler->UseCTestLaunch) {
cmSystemTools::UnsetEnv("CTEST_LAUNCH_LOGS");
}
}
}
cmCTestBuildHandler::LaunchHelper::~LaunchHelper()
{
if(this->Handler->UseCTestLaunch)
{
if (this->Handler->UseCTestLaunch) {
cmSystemTools::UnsetEnv("CTEST_LAUNCH_LOGS");
}
}
}
void cmCTestBuildHandler::LaunchHelper::WriteLauncherConfig()
@@ -833,56 +766,50 @@ void cmCTestBuildHandler::LaunchHelper::WriteLauncherConfig()
fout << "set(CTEST_SOURCE_DIRECTORY \"" << srcdir << "\")\n";
}
void
cmCTestBuildHandler::LaunchHelper
::WriteScrapeMatchers(const char* purpose,
std::vector<std::string> const& matchers)
void cmCTestBuildHandler::LaunchHelper::WriteScrapeMatchers(
const char* purpose, std::vector<std::string> const& matchers)
{
if(matchers.empty())
{
if (matchers.empty()) {
return;
}
}
std::string fname = this->Handler->CTestLaunchDir;
fname += "/Custom";
fname += purpose;
fname += ".txt";
cmGeneratedFileStream fout(fname.c_str());
for(std::vector<std::string>::const_iterator mi = matchers.begin();
mi != matchers.end(); ++mi)
{
for (std::vector<std::string>::const_iterator mi = matchers.begin();
mi != matchers.end(); ++mi) {
fout << *mi << "\n";
}
}
}
int cmCTestBuildHandler::RunMakeCommand(const char* command,
int* retVal, const char* dir, int timeout, std::ostream& ofs)
int cmCTestBuildHandler::RunMakeCommand(const char* command, int* retVal,
const char* dir, int timeout,
std::ostream& ofs)
{
// First generate the command and arguments
std::vector<std::string> args = cmSystemTools::ParseArguments(command);
if(args.size() < 1)
{
if (args.size() < 1) {
return false;
}
}
std::vector<const char*> argv;
for(std::vector<std::string>::const_iterator a = args.begin();
a != args.end(); ++a)
{
for (std::vector<std::string>::const_iterator a = args.begin();
a != args.end(); ++a) {
argv.push_back(a->c_str());
}
}
argv.push_back(0);
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Run command:",
this->Quiet);
this->Quiet);
std::vector<const char*>::iterator ait;
for ( ait = argv.begin(); ait != argv.end() && *ait; ++ ait )
{
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, " \"" << *ait <<
"\"", this->Quiet);
}
for (ait = argv.begin(); ait != argv.end() && *ait; ++ait) {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
" \"" << *ait << "\"", this->Quiet);
}
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, std::endl,
this->Quiet);
this->Quiet);
// Optionally use make rule launchers to record errors and warnings.
LaunchHelper launchHelper(this);
@@ -902,12 +829,14 @@ int cmCTestBuildHandler::RunMakeCommand(const char* command,
char* data;
int length;
cmCTestOptionalLog(this->CTest, HANDLER_PROGRESS_OUTPUT,
" Each symbol represents " << tick_len << " bytes of output."
<< std::endl
<< (this->UseCTestLaunch? "" :
" '!' represents an error and '*' a warning.\n")
<< " " << std::flush, this->Quiet);
cmCTestOptionalLog(
this->CTest, HANDLER_PROGRESS_OUTPUT, " Each symbol represents "
<< tick_len << " bytes of output." << std::endl
<< (this->UseCTestLaunch
? ""
: " '!' represents an error and '*' a warning.\n")
<< " " << std::flush,
this->Quiet);
// Initialize building structures
this->BuildProcessingQueue.clear();
@@ -922,96 +851,84 @@ int cmCTestBuildHandler::RunMakeCommand(const char* command,
// For every chunk of data
int res;
while((res = cmsysProcess_WaitForData(cp, &data, &length, 0)))
{
while ((res = cmsysProcess_WaitForData(cp, &data, &length, 0))) {
// Replace '\0' with '\n', since '\0' does not really make sense. This is
// for Visual Studio output
for(int cc =0; cc < length; ++cc)
{
if(data[cc] == 0)
{
for (int cc = 0; cc < length; ++cc) {
if (data[cc] == 0) {
data[cc] = '\n';
}
}
// Process the chunk of data
if ( res == cmsysProcess_Pipe_STDERR )
{
this->ProcessBuffer(data, length, tick, tick_len, ofs,
&this->BuildProcessingErrorQueue);
}
else
{
this->ProcessBuffer(data, length, tick, tick_len, ofs,
&this->BuildProcessingQueue);
}
}
// Process the chunk of data
if (res == cmsysProcess_Pipe_STDERR) {
this->ProcessBuffer(data, length, tick, tick_len, ofs,
&this->BuildProcessingErrorQueue);
} else {
this->ProcessBuffer(data, length, tick, tick_len, ofs,
&this->BuildProcessingQueue);
}
}
this->ProcessBuffer(0, 0, tick, tick_len, ofs, &this->BuildProcessingQueue);
this->ProcessBuffer(0, 0, tick, tick_len, ofs,
&this->BuildProcessingErrorQueue);
&this->BuildProcessingErrorQueue);
cmCTestOptionalLog(this->CTest, HANDLER_PROGRESS_OUTPUT, " Size of output: "
<< ((this->BuildOutputLogSize + 512) / 1024) << "K" << std::endl,
this->Quiet);
<< ((this->BuildOutputLogSize + 512) / 1024) << "K"
<< std::endl,
this->Quiet);
// Properly handle output of the build command
cmsysProcess_WaitForExit(cp, 0);
int result = cmsysProcess_GetState(cp);
if(result == cmsysProcess_State_Exited)
{
if (retVal)
{
if (result == cmsysProcess_State_Exited) {
if (retVal) {
*retVal = cmsysProcess_GetExitValue(cp);
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Command exited with the value: " << *retVal << std::endl, this->Quiet);
"Command exited with the value: " << *retVal
<< std::endl,
this->Quiet);
// if a non zero return value
if (*retVal)
{
if (*retVal) {
// If there was an error running command, report that on the
// dashboard.
cmCTestBuildErrorWarning errorwarning;
errorwarning.LogLine = 1;
errorwarning.Text
= "*** WARNING non-zero return value in ctest from: ";
errorwarning.Text += argv[0];
errorwarning.PreContext = "";
errorwarning.LogLine = 1;
errorwarning.Text =
"*** WARNING non-zero return value in ctest from: ";
errorwarning.Text += argv[0];
errorwarning.PreContext = "";
errorwarning.PostContext = "";
errorwarning.Error = false;
errorwarning.Error = false;
this->ErrorsAndWarnings.push_back(errorwarning);
this->TotalWarnings ++;
}
this->TotalWarnings++;
}
}
else if(result == cmsysProcess_State_Exception)
{
if (retVal)
{
} else if (result == cmsysProcess_State_Exception) {
if (retVal) {
*retVal = cmsysProcess_GetExitException(cp);
cmCTestOptionalLog(this->CTest, WARNING, "There was an exception: " <<
*retVal << std::endl, this->Quiet);
}
cmCTestOptionalLog(this->CTest, WARNING,
"There was an exception: " << *retVal << std::endl,
this->Quiet);
}
else if(result == cmsysProcess_State_Expired)
{
cmCTestOptionalLog(this->CTest, WARNING, "There was a timeout" <<
std::endl, this->Quiet);
}
else if(result == cmsysProcess_State_Error)
{
} else if (result == cmsysProcess_State_Expired) {
cmCTestOptionalLog(this->CTest, WARNING,
"There was a timeout" << std::endl, this->Quiet);
} else if (result == cmsysProcess_State_Error) {
// If there was an error running command, report that on the dashboard.
cmCTestBuildErrorWarning errorwarning;
errorwarning.LogLine = 1;
errorwarning.Text = "*** ERROR executing: ";
errorwarning.Text += cmsysProcess_GetErrorString(cp);
errorwarning.PreContext = "";
errorwarning.LogLine = 1;
errorwarning.Text = "*** ERROR executing: ";
errorwarning.Text += cmsysProcess_GetErrorString(cp);
errorwarning.PreContext = "";
errorwarning.PostContext = "";
errorwarning.Error = true;
errorwarning.Error = true;
this->ErrorsAndWarnings.push_back(errorwarning);
this->TotalErrors ++;
this->TotalErrors++;
cmCTestLog(this->CTest, ERROR_MESSAGE, "There was an error: "
<< cmsysProcess_GetErrorString(cp) << std::endl);
}
<< cmsysProcess_GetErrorString(cp) << std::endl);
}
cmsysProcess_Delete(cp);
return result;
@@ -1023,46 +940,38 @@ int cmCTestBuildHandler::RunMakeCommand(const char* command,
//######################################################################
void cmCTestBuildHandler::ProcessBuffer(const char* data, int length,
size_t& tick, size_t tick_len, std::ostream& ofs,
t_BuildProcessingQueueType* queue)
size_t& tick, size_t tick_len,
std::ostream& ofs,
t_BuildProcessingQueueType* queue)
{
const std::string::size_type tick_line_len = 50;
const char* ptr;
for ( ptr = data; ptr < data+length; ptr ++ )
{
for (ptr = data; ptr < data + length; ptr++) {
queue->push_back(*ptr);
}
}
this->BuildOutputLogSize += length;
// until there are any lines left in the buffer
while ( 1 )
{
while (1) {
// Find the end of line
t_BuildProcessingQueueType::iterator it;
for ( it = queue->begin();
it != queue->end();
++ it )
{
if ( *it == '\n' )
{
for (it = queue->begin(); it != queue->end(); ++it) {
if (*it == '\n') {
break;
}
}
}
// Once certain number of errors or warnings reached, ignore future errors
// or warnings.
if ( this->TotalWarnings >= this->MaxWarnings )
{
if (this->TotalWarnings >= this->MaxWarnings) {
this->WarningQuotaReached = true;
}
if ( this->TotalErrors >= this->MaxErrors )
{
}
if (this->TotalErrors >= this->MaxErrors) {
this->ErrorQuotaReached = true;
}
}
// If the end of line was found
if ( it != queue->end() )
{
if (it != queue->end()) {
// Create a contiguous array for the line
this->CurrentProcessingLine.clear();
this->CurrentProcessingLine.insert(this->CurrentProcessingLine.end(),
@@ -1074,106 +983,93 @@ void cmCTestBuildHandler::ProcessBuffer(const char* data, int length,
int lineType = this->ProcessSingleLine(line);
// Erase the line from the queue
queue->erase(queue->begin(), it+1);
queue->erase(queue->begin(), it + 1);
// Depending on the line type, produce error or warning, or nothing
cmCTestBuildErrorWarning errorwarning;
bool found = false;
switch ( lineType )
{
case b_WARNING_LINE:
this->LastTickChar = '*';
errorwarning.Error = false;
found = true;
this->TotalWarnings ++;
break;
case b_ERROR_LINE:
this->LastTickChar = '!';
errorwarning.Error = true;
found = true;
this->TotalErrors ++;
break;
}
if ( found )
{
switch (lineType) {
case b_WARNING_LINE:
this->LastTickChar = '*';
errorwarning.Error = false;
found = true;
this->TotalWarnings++;
break;
case b_ERROR_LINE:
this->LastTickChar = '!';
errorwarning.Error = true;
found = true;
this->TotalErrors++;
break;
}
if (found) {
// This is an error or warning, so generate report
errorwarning.LogLine = static_cast<int>(this->OutputLineCounter+1);
errorwarning.Text = line;
errorwarning.PreContext = "";
errorwarning.LogLine = static_cast<int>(this->OutputLineCounter + 1);
errorwarning.Text = line;
errorwarning.PreContext = "";
errorwarning.PostContext = "";
// Copy pre-context to report
std::deque<std::string>::iterator pcit;
for ( pcit = this->PreContext.begin();
pcit != this->PreContext.end();
++pcit )
{
for (pcit = this->PreContext.begin(); pcit != this->PreContext.end();
++pcit) {
errorwarning.PreContext += *pcit + "\n";
}
}
this->PreContext.clear();
// Store report
this->ErrorsAndWarnings.push_back(errorwarning);
this->LastErrorOrWarning = this->ErrorsAndWarnings.end()-1;
this->LastErrorOrWarning = this->ErrorsAndWarnings.end() - 1;
this->PostContextCount = 0;
}
else
{
} else {
// This is not an error or warning.
// So, figure out if this is a post-context line
if ( !this->ErrorsAndWarnings.empty() &&
this->LastErrorOrWarning != this->ErrorsAndWarnings.end() &&
this->PostContextCount < this->MaxPostContext )
{
this->PostContextCount ++;
if (!this->ErrorsAndWarnings.empty() &&
this->LastErrorOrWarning != this->ErrorsAndWarnings.end() &&
this->PostContextCount < this->MaxPostContext) {
this->PostContextCount++;
this->LastErrorOrWarning->PostContext += line;
if ( this->PostContextCount < this->MaxPostContext )
{
if (this->PostContextCount < this->MaxPostContext) {
this->LastErrorOrWarning->PostContext += "\n";
}
}
else
{
} else {
// Otherwise store pre-context for the next error
this->PreContext.push_back(line);
if ( this->PreContext.size() > this->MaxPreContext )
{
if (this->PreContext.size() > this->MaxPreContext) {
this->PreContext.erase(this->PreContext.begin(),
this->PreContext.end()-this->MaxPreContext);
}
this->PreContext.end() -
this->MaxPreContext);
}
}
this->OutputLineCounter ++;
}
else
{
this->OutputLineCounter++;
} else {
break;
}
}
}
// Now that the buffer is processed, display missing ticks
int tickDisplayed = false;
while ( this->BuildOutputLogSize > (tick * tick_len) )
{
tick ++;
while (this->BuildOutputLogSize > (tick * tick_len)) {
tick++;
cmCTestOptionalLog(this->CTest, HANDLER_PROGRESS_OUTPUT,
this->LastTickChar, this->Quiet);
this->LastTickChar, this->Quiet);
tickDisplayed = true;
if ( tick % tick_line_len == 0 && tick > 0 )
{
if (tick % tick_line_len == 0 && tick > 0) {
cmCTestOptionalLog(this->CTest, HANDLER_PROGRESS_OUTPUT, " Size: "
<< ((this->BuildOutputLogSize + 512) / 1024) << "K" << std::endl
<< " ", this->Quiet);
}
<< ((this->BuildOutputLogSize + 512) / 1024) << "K"
<< std::endl
<< " ",
this->Quiet);
}
if ( tickDisplayed )
{
}
if (tickDisplayed) {
this->LastTickChar = '.';
}
}
// And if this is verbose output, display the content of the chunk
cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
cmCTestLogWrite(data, length));
cmCTestLogWrite(data, length));
// Always store the chunk to the file
ofs << cmCTestLogWrite(data, length);
@@ -1181,14 +1077,13 @@ void cmCTestBuildHandler::ProcessBuffer(const char* data, int length,
int cmCTestBuildHandler::ProcessSingleLine(const char* data)
{
if(this->UseCTestLaunch)
{
if (this->UseCTestLaunch) {
// No log scraping when using launchers.
return b_REGULAR_LINE;
}
}
cmCTestOptionalLog(this->CTest, DEBUG, "Line: [" << data << "]" <<
std::endl, this->Quiet);
cmCTestOptionalLog(this->CTest, DEBUG, "Line: [" << data << "]" << std::endl,
this->Quiet);
std::vector<cmsys::RegularExpression>::iterator it;
@@ -1197,86 +1092,76 @@ int cmCTestBuildHandler::ProcessSingleLine(const char* data)
// Check for regular expressions
if ( !this->ErrorQuotaReached )
{
if (!this->ErrorQuotaReached) {
// Errors
int wrxCnt = 0;
for ( it = this->ErrorMatchRegex.begin();
it != this->ErrorMatchRegex.end();
++ it )
{
if ( it->find(data) )
{
for (it = this->ErrorMatchRegex.begin(); it != this->ErrorMatchRegex.end();
++it) {
if (it->find(data)) {
errorLine = 1;
cmCTestOptionalLog(this->CTest, DEBUG, " Error Line: " << data
<< " (matches: " << this->CustomErrorMatches[wrxCnt] << ")"
<< std::endl, this->Quiet);
cmCTestOptionalLog(this->CTest, DEBUG,
" Error Line: " << data << " (matches: "
<< this->CustomErrorMatches[wrxCnt]
<< ")" << std::endl,
this->Quiet);
break;
}
wrxCnt ++;
}
wrxCnt++;
}
// Error exceptions
wrxCnt = 0;
for ( it = this->ErrorExceptionRegex.begin();
it != this->ErrorExceptionRegex.end();
++ it )
{
if ( it->find(data) )
{
for (it = this->ErrorExceptionRegex.begin();
it != this->ErrorExceptionRegex.end(); ++it) {
if (it->find(data)) {
errorLine = 0;
cmCTestOptionalLog(this->CTest, DEBUG, " Not an error Line: " << data
<< " (matches: " << this->CustomErrorExceptions[wrxCnt] << ")"
<< std::endl, this->Quiet);
cmCTestOptionalLog(this->CTest, DEBUG, " Not an error Line: "
<< data << " (matches: "
<< this->CustomErrorExceptions[wrxCnt] << ")"
<< std::endl,
this->Quiet);
break;
}
wrxCnt ++;
}
wrxCnt++;
}
if ( !this->WarningQuotaReached )
{
}
if (!this->WarningQuotaReached) {
// Warnings
int wrxCnt = 0;
for ( it = this->WarningMatchRegex.begin();
it != this->WarningMatchRegex.end();
++ it )
{
if ( it->find(data) )
{
for (it = this->WarningMatchRegex.begin();
it != this->WarningMatchRegex.end(); ++it) {
if (it->find(data)) {
warningLine = 1;
cmCTestOptionalLog(this->CTest, DEBUG,
" Warning Line: " << data
<< " (matches: " << this->CustomWarningMatches[wrxCnt] << ")"
<< std::endl, this->Quiet);
cmCTestOptionalLog(this->CTest, DEBUG, " Warning Line: "
<< data << " (matches: "
<< this->CustomWarningMatches[wrxCnt] << ")"
<< std::endl,
this->Quiet);
break;
}
wrxCnt ++;
}
wrxCnt++;
}
wrxCnt = 0;
// Warning exceptions
for ( it = this->WarningExceptionRegex.begin();
it != this->WarningExceptionRegex.end();
++ it )
{
if ( it->find(data) )
{
for (it = this->WarningExceptionRegex.begin();
it != this->WarningExceptionRegex.end(); ++it) {
if (it->find(data)) {
warningLine = 0;
cmCTestOptionalLog(this->CTest, DEBUG, " Not a warning Line: " << data
<< " (matches: " << this->CustomWarningExceptions[wrxCnt] << ")"
<< std::endl, this->Quiet);
cmCTestOptionalLog(this->CTest, DEBUG, " Not a warning Line: "
<< data << " (matches: "
<< this->CustomWarningExceptions[wrxCnt] << ")"
<< std::endl,
this->Quiet);
break;
}
wrxCnt ++;
}
wrxCnt++;
}
if ( errorLine )
{
}
if (errorLine) {
return b_ERROR_LINE;
}
if ( warningLine )
{
}
if (warningLine) {
return b_WARNING_LINE;
}
}
return b_REGULAR_LINE;
}
+38 -37
View File
@@ -40,48 +40,48 @@ public:
cmCTestBuildHandler();
void PopulateCustomVectors(cmMakefile *mf);
void PopulateCustomVectors(cmMakefile* mf);
/**
* Initialize handler
*/
virtual void Initialize();
int GetTotalErrors() { return this->TotalErrors;}
int GetTotalWarnings() { return this->TotalWarnings;}
int GetTotalErrors() { return this->TotalErrors; }
int GetTotalWarnings() { return this->TotalWarnings; }
private:
std::string GetMakeCommand();
//! Run command specialized for make and configure. Returns process status
// and retVal is return value or exception.
int RunMakeCommand(const char* command,
int* retVal, const char* dir, int timeout,
std::ostream& ofs);
int RunMakeCommand(const char* command, int* retVal, const char* dir,
int timeout, std::ostream& ofs);
enum {
enum
{
b_REGULAR_LINE,
b_WARNING_LINE,
b_ERROR_LINE
};
class cmCTestCompileErrorWarningRex
{
{
public:
cmCTestCompileErrorWarningRex() {}
int FileIndex;
int LineIndex;
cmsys::RegularExpression RegularExpression;
};
};
struct cmCTestBuildErrorWarning
{
bool Error;
int LogLine;
bool Error;
int LogLine;
std::string Text;
std::string SourceFile;
std::string SourceFileTail;
int LineNumber;
int LineNumber;
std::string PreContext;
std::string PostContext;
};
@@ -94,10 +94,10 @@ private:
bool IsLaunchedErrorFile(const char* fname);
bool IsLaunchedWarningFile(const char* fname);
std::string StartBuild;
std::string EndBuild;
double StartBuildTime;
double EndBuildTime;
std::string StartBuild;
std::string EndBuild;
double StartBuildTime;
double EndBuildTime;
std::vector<std::string> CustomErrorMatches;
std::vector<std::string> CustomErrorExceptions;
@@ -115,34 +115,35 @@ private:
typedef std::deque<char> t_BuildProcessingQueueType;
void ProcessBuffer(const char* data, int length, size_t& tick,
size_t tick_len, std::ostream& ofs, t_BuildProcessingQueueType* queue);
size_t tick_len, std::ostream& ofs,
t_BuildProcessingQueueType* queue);
int ProcessSingleLine(const char* data);
t_BuildProcessingQueueType BuildProcessingQueue;
t_BuildProcessingQueueType BuildProcessingErrorQueue;
size_t BuildOutputLogSize;
std::vector<char> CurrentProcessingLine;
t_BuildProcessingQueueType BuildProcessingQueue;
t_BuildProcessingQueueType BuildProcessingErrorQueue;
size_t BuildOutputLogSize;
std::vector<char> CurrentProcessingLine;
std::string SimplifySourceDir;
std::string SimplifyBuildDir;
size_t OutputLineCounter;
std::string SimplifySourceDir;
std::string SimplifyBuildDir;
size_t OutputLineCounter;
typedef std::vector<cmCTestBuildErrorWarning> t_ErrorsAndWarningsVector;
t_ErrorsAndWarningsVector ErrorsAndWarnings;
t_ErrorsAndWarningsVector::iterator LastErrorOrWarning;
size_t PostContextCount;
size_t MaxPreContext;
size_t MaxPostContext;
std::deque<std::string> PreContext;
t_ErrorsAndWarningsVector ErrorsAndWarnings;
t_ErrorsAndWarningsVector::iterator LastErrorOrWarning;
size_t PostContextCount;
size_t MaxPreContext;
size_t MaxPostContext;
std::deque<std::string> PreContext;
int TotalErrors;
int TotalWarnings;
char LastTickChar;
int TotalErrors;
int TotalWarnings;
char LastTickChar;
bool ErrorQuotaReached;
bool WarningQuotaReached;
bool ErrorQuotaReached;
bool WarningQuotaReached;
int MaxErrors;
int MaxWarnings;
int MaxErrors;
int MaxWarnings;
bool UseCTestLaunch;
std::string CTestLaunchDir;
+83 -109
View File
@@ -18,7 +18,8 @@
#include <cmsys/FStream.hxx>
#include <cmsys/RegularExpression.hxx>
cmCTestCVS::cmCTestCVS(cmCTest* ct, std::ostream& log): cmCTestVC(ct, log)
cmCTestCVS::cmCTestCVS(cmCTest* ct, std::ostream& log)
: cmCTestVC(ct, log)
{
}
@@ -26,11 +27,12 @@ cmCTestCVS::~cmCTestCVS()
{
}
class cmCTestCVS::UpdateParser: public cmCTestVC::LineParser
class cmCTestCVS::UpdateParser : public cmCTestVC::LineParser
{
public:
UpdateParser(cmCTestCVS* cvs, const char* prefix): CVS(cvs)
{
UpdateParser(cmCTestCVS* cvs, const char* prefix)
: CVS(cvs)
{
this->SetLog(&cvs->Log, prefix);
// See "man cvs", section "update output".
this->RegexFileUpdated.compile("^([UP]) *(.*)");
@@ -41,7 +43,8 @@ public:
this->RegexFileRemoved2.compile(
"cvs[^ ]* update: "
"warning: `?([^']*)'? is not \\(any longer\\) pertinent");
}
}
private:
cmCTestCVS* CVS;
cmsys::RegularExpression RegexFileUpdated;
@@ -51,68 +54,55 @@ private:
cmsys::RegularExpression RegexFileRemoved2;
virtual bool ProcessLine()
{
if(this->RegexFileUpdated.find(this->Line))
{
{
if (this->RegexFileUpdated.find(this->Line)) {
this->DoFile(PathUpdated, this->RegexFileUpdated.match(2));
}
else if(this->RegexFileModified.find(this->Line))
{
} else if (this->RegexFileModified.find(this->Line)) {
this->DoFile(PathModified, this->RegexFileModified.match(2));
}
else if(this->RegexFileConflicting.find(this->Line))
{
} else if (this->RegexFileConflicting.find(this->Line)) {
this->DoFile(PathConflicting, this->RegexFileConflicting.match(2));
}
else if(this->RegexFileRemoved1.find(this->Line))
{
} else if (this->RegexFileRemoved1.find(this->Line)) {
this->DoFile(PathUpdated, this->RegexFileRemoved1.match(1));
}
else if(this->RegexFileRemoved2.find(this->Line))
{
} else if (this->RegexFileRemoved2.find(this->Line)) {
this->DoFile(PathUpdated, this->RegexFileRemoved2.match(1));
}
return true;
}
return true;
}
void DoFile(PathStatus status, std::string const& file)
{
{
std::string dir = cmSystemTools::GetFilenamePath(file);
std::string name = cmSystemTools::GetFilenameName(file);
this->CVS->Dirs[dir][name] = status;
}
}
};
bool cmCTestCVS::UpdateImpl()
{
// Get user-specified update options.
std::string opts = this->CTest->GetCTestConfiguration("UpdateOptions");
if(opts.empty())
{
if (opts.empty()) {
opts = this->CTest->GetCTestConfiguration("CVSUpdateOptions");
if(opts.empty())
{
if (opts.empty()) {
opts = "-dP";
}
}
}
std::vector<std::string> args = cmSystemTools::ParseArguments(opts.c_str());
// Specify the start time for nightly testing.
if(this->CTest->GetTestModel() == cmCTest::NIGHTLY)
{
if (this->CTest->GetTestModel() == cmCTest::NIGHTLY) {
args.push_back("-D" + this->GetNightlyTime() + " UTC");
}
}
// Run "cvs update" to update the work tree.
std::vector<char const*> cvs_update;
cvs_update.push_back(this->CommandLineTool.c_str());
cvs_update.push_back("-z3");
cvs_update.push_back("update");
for(std::vector<std::string>::const_iterator ai = args.begin();
ai != args.end(); ++ai)
{
for (std::vector<std::string>::const_iterator ai = args.begin();
ai != args.end(); ++ai) {
cvs_update.push_back(ai->c_str());
}
}
cvs_update.push_back(0);
UpdateParser out(this, "up-out> ");
@@ -120,83 +110,76 @@ bool cmCTestCVS::UpdateImpl()
return this->RunUpdateCommand(&cvs_update[0], &out, &err);
}
class cmCTestCVS::LogParser: public cmCTestVC::LineParser
class cmCTestCVS::LogParser : public cmCTestVC::LineParser
{
public:
typedef cmCTestCVS::Revision Revision;
LogParser(cmCTestCVS* cvs, const char* prefix, std::vector<Revision>& revs):
CVS(cvs), Revisions(revs), Section(SectionHeader)
{
LogParser(cmCTestCVS* cvs, const char* prefix, std::vector<Revision>& revs)
: CVS(cvs)
, Revisions(revs)
, Section(SectionHeader)
{
this->SetLog(&cvs->Log, prefix),
this->RegexRevision.compile("^revision +([^ ]*) *$");
this->RegexRevision.compile("^revision +([^ ]*) *$");
this->RegexBranches.compile("^branches: .*$");
this->RegexPerson.compile("^date: +([^;]+); +author: +([^;]+);");
}
}
private:
cmCTestCVS* CVS;
std::vector<Revision>& Revisions;
cmsys::RegularExpression RegexRevision;
cmsys::RegularExpression RegexBranches;
cmsys::RegularExpression RegexPerson;
enum SectionType { SectionHeader, SectionRevisions, SectionEnd };
enum SectionType
{
SectionHeader,
SectionRevisions,
SectionEnd
};
SectionType Section;
Revision Rev;
virtual bool ProcessLine()
{
if(this->Line == ("======================================="
"======================================"))
{
{
if (this->Line == ("======================================="
"======================================")) {
// This line ends the revision list.
if(this->Section == SectionRevisions)
{
if (this->Section == SectionRevisions) {
this->FinishRevision();
}
}
this->Section = SectionEnd;
}
else if(this->Line == "----------------------------")
{
} else if (this->Line == "----------------------------") {
// This line divides revisions from the header and each other.
if(this->Section == SectionHeader)
{
if (this->Section == SectionHeader) {
this->Section = SectionRevisions;
}
else if(this->Section == SectionRevisions)
{
} else if (this->Section == SectionRevisions) {
this->FinishRevision();
}
}
else if(this->Section == SectionRevisions)
{
if(!this->Rev.Log.empty())
{
} else if (this->Section == SectionRevisions) {
if (!this->Rev.Log.empty()) {
// Continue the existing log.
this->Rev.Log += this->Line;
this->Rev.Log += "\n";
}
else if(this->Rev.Rev.empty() && this->RegexRevision.find(this->Line))
{
} else if (this->Rev.Rev.empty() &&
this->RegexRevision.find(this->Line)) {
this->Rev.Rev = this->RegexRevision.match(1);
}
else if(this->Rev.Date.empty() && this->RegexPerson.find(this->Line))
{
} else if (this->Rev.Date.empty() &&
this->RegexPerson.find(this->Line)) {
this->Rev.Date = this->RegexPerson.match(1);
this->Rev.Author = this->RegexPerson.match(2);
}
else if(!this->RegexBranches.find(this->Line))
{
} else if (!this->RegexBranches.find(this->Line)) {
// Start the log.
this->Rev.Log += this->Line;
this->Rev.Log += "\n";
}
}
return this->Section != SectionEnd;
}
return this->Section != SectionEnd;
}
void FinishRevision()
{
if(!this->Rev.Rev.empty())
{
{
if (!this->Rev.Rev.empty()) {
// Record this revision.
/* clang-format off */
this->CVS->Log << "Found revision " << this->Rev.Rev << "\n"
@@ -206,65 +189,57 @@ private:
this->Revisions.push_back(this->Rev);
// We only need two revisions.
if(this->Revisions.size() >= 2)
{
if (this->Revisions.size() >= 2) {
this->Section = SectionEnd;
}
}
this->Rev = Revision();
}
this->Rev = Revision();
}
};
std::string cmCTestCVS::ComputeBranchFlag(std::string const& dir)
{
// Compute the tag file location for this directory.
std::string tagFile = this->SourceDirectory;
if(!dir.empty())
{
if (!dir.empty()) {
tagFile += "/";
tagFile += dir;
}
}
tagFile += "/CVS/Tag";
// Lookup the branch in the tag file, if any.
std::string tagLine;
cmsys::ifstream tagStream(tagFile.c_str());
if(tagStream && cmSystemTools::GetLineFromStream(tagStream, tagLine) &&
tagLine.size() > 1 && tagLine[0] == 'T')
{
if (tagStream && cmSystemTools::GetLineFromStream(tagStream, tagLine) &&
tagLine.size() > 1 && tagLine[0] == 'T') {
// Use the branch specified in the tag file.
std::string flag = "-r";
flag += tagLine.substr(1);
return flag;
}
else
{
} else {
// Use the default branch.
return "-b";
}
}
}
void cmCTestCVS::LoadRevisions(std::string const& file,
const char* branchFlag,
void cmCTestCVS::LoadRevisions(std::string const& file, const char* branchFlag,
std::vector<Revision>& revisions)
{
cmCTestLog(this->CTest, HANDLER_OUTPUT, "." << std::flush);
// Run "cvs log" to get revisions of this file on this branch.
const char* cvs = this->CommandLineTool.c_str();
const char* cvs_log[] =
{cvs, "log", "-N", branchFlag, file.c_str(), 0};
const char* cvs_log[] = { cvs, "log", "-N", branchFlag, file.c_str(), 0 };
LogParser out(this, "log-out> ", revisions);
OutputLogger err(this->Log, "log-err> ");
this->RunChild(cvs_log, &out, &err);
}
void cmCTestCVS::WriteXMLDirectory(cmXMLWriter& xml,
std::string const& path,
void cmCTestCVS::WriteXMLDirectory(cmXMLWriter& xml, std::string const& path,
Directory const& dir)
{
const char* slash = path.empty()? "":"/";
const char* slash = path.empty() ? "" : "/";
xml.StartElement("Directory");
xml.Element("Name", path);
@@ -273,25 +248,23 @@ void cmCTestCVS::WriteXMLDirectory(cmXMLWriter& xml,
// Load revisions and write an entry for each file in this directory.
std::vector<Revision> revisions;
for(Directory::const_iterator fi = dir.begin(); fi != dir.end(); ++fi)
{
for (Directory::const_iterator fi = dir.begin(); fi != dir.end(); ++fi) {
std::string full = path + slash + fi->first;
// Load two real or unknown revisions.
revisions.clear();
if(fi->second != PathUpdated)
{
if (fi->second != PathUpdated) {
// For local modifications the current rev is unknown and the
// prior rev is the latest from cvs.
revisions.push_back(this->Unknown);
}
}
this->LoadRevisions(full, branchFlag.c_str(), revisions);
revisions.resize(2, this->Unknown);
// Write the entry for this file with these revisions.
File f(fi->second, &revisions[0], &revisions[1]);
this->WriteXMLEntry(xml, path, fi->first, full, f);
}
}
xml.EndElement(); // Directory
}
@@ -299,13 +272,14 @@ bool cmCTestCVS::WriteXMLUpdates(cmXMLWriter& xml)
{
cmCTestLog(this->CTest, HANDLER_OUTPUT,
" Gathering version information (one . per updated file):\n"
" " << std::flush);
" "
<< std::flush);
for(std::map<std::string, Directory>::const_iterator
di = this->Dirs.begin(); di != this->Dirs.end(); ++di)
{
for (std::map<std::string, Directory>::const_iterator di =
this->Dirs.begin();
di != this->Dirs.end(); ++di) {
this->WriteXMLDirectory(xml, di->first, di->second);
}
}
cmCTestLog(this->CTest, HANDLER_OUTPUT, std::endl);
+4 -2
View File
@@ -18,7 +18,7 @@
* \brief Interaction with cvs command-line tool
*
*/
class cmCTestCVS: public cmCTestVC
class cmCTestCVS : public cmCTestVC
{
public:
/** Construct with a CTest instance and update log stream. */
@@ -32,7 +32,9 @@ private:
virtual bool WriteXMLUpdates(cmXMLWriter& xml);
// Update status for files in each directory.
class Directory: public std::map<std::string, PathStatus> {};
class Directory : public std::map<std::string, PathStatus>
{
};
std::map<std::string, Directory> Dirs;
std::string ComputeBranchFlag(std::string const& dir);
+7 -5
View File
@@ -27,14 +27,16 @@ class cmCTestScriptHandler;
class cmCTestCommand : public cmCommand
{
public:
cmCTestCommand()
{
this->CTest = 0;
this->CTestScriptHandler = 0;
}
cmCTestCommand() {this->CTest = 0; this->CTestScriptHandler = 0;}
cmCTest *CTest;
cmCTestScriptHandler *CTestScriptHandler;
cmCTest* CTest;
cmCTestScriptHandler* CTestScriptHandler;
cmTypeMacro(cmCTestCommand, cmCommand);
};
#endif
+45 -60
View File
@@ -26,64 +26,56 @@ cmCTestGenericHandler* cmCTestConfigureCommand::InitializeHandler()
{
std::vector<std::string> options;
if (this->Values[ctc_OPTIONS])
{
if (this->Values[ctc_OPTIONS]) {
cmSystemTools::ExpandListArgument(this->Values[ctc_OPTIONS], options);
}
}
if ( this->CTest->GetCTestConfiguration("BuildDirectory").empty() )
{
this->SetError("Build directory not specified. Either use BUILD "
if (this->CTest->GetCTestConfiguration("BuildDirectory").empty()) {
this->SetError(
"Build directory not specified. Either use BUILD "
"argument to CTEST_CONFIGURE command or set CTEST_BINARY_DIRECTORY "
"variable");
return 0;
}
}
const char* ctestConfigureCommand
= this->Makefile->GetDefinition("CTEST_CONFIGURE_COMMAND");
const char* ctestConfigureCommand =
this->Makefile->GetDefinition("CTEST_CONFIGURE_COMMAND");
if ( ctestConfigureCommand && *ctestConfigureCommand )
{
if (ctestConfigureCommand && *ctestConfigureCommand) {
this->CTest->SetCTestConfiguration("ConfigureCommand",
ctestConfigureCommand, this->Quiet);
}
else
{
const char* cmakeGeneratorName
= this->Makefile->GetDefinition("CTEST_CMAKE_GENERATOR");
if ( cmakeGeneratorName && *cmakeGeneratorName )
{
const std::string& source_dir
= this->CTest->GetCTestConfiguration("SourceDirectory");
if ( source_dir.empty() )
{
this->SetError("Source directory not specified. Either use SOURCE "
ctestConfigureCommand, this->Quiet);
} else {
const char* cmakeGeneratorName =
this->Makefile->GetDefinition("CTEST_CMAKE_GENERATOR");
if (cmakeGeneratorName && *cmakeGeneratorName) {
const std::string& source_dir =
this->CTest->GetCTestConfiguration("SourceDirectory");
if (source_dir.empty()) {
this->SetError(
"Source directory not specified. Either use SOURCE "
"argument to CTEST_CONFIGURE command or set CTEST_SOURCE_DIRECTORY "
"variable");
return 0;
}
}
const std::string cmakelists_file = source_dir + "/CMakeLists.txt";
if ( !cmSystemTools::FileExists(cmakelists_file.c_str()) )
{
if (!cmSystemTools::FileExists(cmakelists_file.c_str())) {
std::ostringstream e;
e << "CMakeLists.txt file does not exist ["
<< cmakelists_file << "]";
e << "CMakeLists.txt file does not exist [" << cmakelists_file << "]";
this->SetError(e.str());
return 0;
}
}
bool multiConfig = false;
bool cmakeBuildTypeInOptions = false;
cmGlobalGenerator *gg =
cmGlobalGenerator* gg =
this->Makefile->GetCMakeInstance()->CreateGlobalGenerator(
cmakeGeneratorName);
if(gg)
{
if (gg) {
multiConfig = gg->IsMultiConfig();
delete gg;
}
}
std::string cmakeConfigureCommand = "\"";
cmakeConfigureCommand += cmSystemTools::GetCMakeCommand();
@@ -91,8 +83,7 @@ cmCTestGenericHandler* cmCTestConfigureCommand::InitializeHandler()
std::vector<std::string>::const_iterator it;
std::string option;
for (it= options.begin(); it!=options.end(); ++it)
{
for (it = options.begin(); it != options.end(); ++it) {
option = *it;
cmakeConfigureCommand += " \"";
@@ -100,19 +91,17 @@ cmCTestGenericHandler* cmCTestConfigureCommand::InitializeHandler()
cmakeConfigureCommand += "\"";
if ((0 != strstr(option.c_str(), "CMAKE_BUILD_TYPE=")) ||
(0 != strstr(option.c_str(), "CMAKE_BUILD_TYPE:STRING=")))
{
(0 != strstr(option.c_str(), "CMAKE_BUILD_TYPE:STRING="))) {
cmakeBuildTypeInOptions = true;
}
}
}
if (!multiConfig && !cmakeBuildTypeInOptions &&
!this->CTest->GetConfigType().empty())
{
!this->CTest->GetConfigType().empty()) {
cmakeConfigureCommand += " \"-DCMAKE_BUILD_TYPE:STRING=";
cmakeConfigureCommand += this->CTest->GetConfigType();
cmakeConfigureCommand += "\"";
}
}
cmakeConfigureCommand += " \"-G";
cmakeConfigureCommand += cmakeGeneratorName;
@@ -120,46 +109,42 @@ cmCTestGenericHandler* cmCTestConfigureCommand::InitializeHandler()
const char* cmakeGeneratorPlatform =
this->Makefile->GetDefinition("CTEST_CMAKE_GENERATOR_PLATFORM");
if(cmakeGeneratorPlatform && *cmakeGeneratorPlatform)
{
if (cmakeGeneratorPlatform && *cmakeGeneratorPlatform) {
cmakeConfigureCommand += " \"-A";
cmakeConfigureCommand += cmakeGeneratorPlatform;
cmakeConfigureCommand += "\"";
}
}
const char* cmakeGeneratorToolset =
this->Makefile->GetDefinition("CTEST_CMAKE_GENERATOR_TOOLSET");
if(cmakeGeneratorToolset && *cmakeGeneratorToolset)
{
if (cmakeGeneratorToolset && *cmakeGeneratorToolset) {
cmakeConfigureCommand += " \"-T";
cmakeConfigureCommand += cmakeGeneratorToolset;
cmakeConfigureCommand += "\"";
}
}
cmakeConfigureCommand += " \"";
cmakeConfigureCommand += source_dir;
cmakeConfigureCommand += "\"";
this->CTest->SetCTestConfiguration("ConfigureCommand",
cmakeConfigureCommand.c_str(), this->Quiet);
}
else
{
this->SetError("Configure command is not specified. If this is a "
this->CTest->SetCTestConfiguration(
"ConfigureCommand", cmakeConfigureCommand.c_str(), this->Quiet);
} else {
this->SetError(
"Configure command is not specified. If this is a "
"\"built with CMake\" project, set CTEST_CMAKE_GENERATOR. If not, "
"set CTEST_CONFIGURE_COMMAND.");
return 0;
}
}
}
cmCTestGenericHandler* handler
= this->CTest->GetInitializedHandler("configure");
if ( !handler )
{
cmCTestGenericHandler* handler =
this->CTest->GetInitializedHandler("configure");
if (!handler) {
this->SetError(
"internal CTest error. Cannot instantiate configure handler");
return 0;
}
}
handler->SetQuiet(this->Quiet);
return handler;
}
+5 -5
View File
@@ -28,29 +28,29 @@ public:
* This is a virtual constructor for the command.
*/
virtual cmCommand* Clone()
{
{
cmCTestConfigureCommand* ni = new cmCTestConfigureCommand;
ni->CTest = this->CTest;
ni->CTestScriptHandler = this->CTestScriptHandler;
return ni;
}
}
/**
* The name of the command as specified in CMakeList.txt.
*/
virtual std::string GetName() const { return "ctest_configure";}
virtual std::string GetName() const { return "ctest_configure"; }
cmTypeMacro(cmCTestConfigureCommand, cmCTestHandlerCommand);
protected:
cmCTestGenericHandler* InitializeHandler();
enum {
enum
{
ctc_FIRST = ct_LAST,
ctc_OPTIONS,
ctc_LAST
};
};
#endif
+40 -47
View File
@@ -18,7 +18,6 @@
#include "cmake.h"
#include <cmsys/Process.h>
cmCTestConfigureHandler::cmCTestConfigureHandler()
{
}
@@ -28,64 +27,58 @@ void cmCTestConfigureHandler::Initialize()
this->Superclass::Initialize();
}
//clearly it would be nice if this were broken up into a few smaller
//functions and commented...
// clearly it would be nice if this were broken up into a few smaller
// functions and commented...
int cmCTestConfigureHandler::ProcessHandler()
{
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
"Configure project" << std::endl, this->Quiet);
std::string cCommand
= this->CTest->GetCTestConfiguration("ConfigureCommand");
if (cCommand.empty())
{
"Configure project" << std::endl, this->Quiet);
std::string cCommand =
this->CTest->GetCTestConfiguration("ConfigureCommand");
if (cCommand.empty()) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Cannot find ConfigureCommand key in the DartConfiguration.tcl"
<< std::endl);
"Cannot find ConfigureCommand key in the DartConfiguration.tcl"
<< std::endl);
return -1;
}
}
std::string buildDirectory
= this->CTest->GetCTestConfiguration("BuildDirectory");
if (buildDirectory.empty())
{
std::string buildDirectory =
this->CTest->GetCTestConfiguration("BuildDirectory");
if (buildDirectory.empty()) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Cannot find BuildDirectory key in the DartConfiguration.tcl"
<< std::endl);
"Cannot find BuildDirectory key in the DartConfiguration.tcl"
<< std::endl);
return -1;
}
}
double elapsed_time_start = cmSystemTools::GetTime();
std::string output;
int retVal = 0;
int res = 0;
if ( !this->CTest->GetShowOnly() )
{
if (!this->CTest->GetShowOnly()) {
cmGeneratedFileStream os;
if(!this->StartResultingXML(cmCTest::PartConfigure, "Configure", os))
{
if (!this->StartResultingXML(cmCTest::PartConfigure, "Configure", os)) {
cmCTestLog(this->CTest, ERROR_MESSAGE, "Cannot open configure file"
<< std::endl);
<< std::endl);
return 1;
}
}
std::string start_time = this->CTest->CurrentTime();
unsigned int start_time_time = static_cast<unsigned int>(
cmSystemTools::GetTime());
unsigned int start_time_time =
static_cast<unsigned int>(cmSystemTools::GetTime());
cmGeneratedFileStream ofs;
this->StartLogFile("Configure", ofs);
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Configure with command: " << cCommand << std::endl, this->Quiet);
res = this->CTest->RunMakeCommand(cCommand.c_str(), output,
&retVal, buildDirectory.c_str(),
0, ofs);
"Configure with command: " << cCommand << std::endl,
this->Quiet);
res = this->CTest->RunMakeCommand(cCommand.c_str(), output, &retVal,
buildDirectory.c_str(), 0, ofs);
if ( ofs )
{
if (ofs) {
ofs.close();
}
}
if ( os )
{
if (os) {
cmXMLWriter xml(os);
this->CTest->StartXML(xml, this->AppendXML);
xml.StartElement("Configure");
@@ -97,23 +90,23 @@ int cmCTestConfigureHandler::ProcessHandler()
xml.Element("ConfigureStatus", retVal);
xml.Element("EndDateTime", this->CTest->CurrentTime());
xml.Element("EndConfigureTime",
static_cast<unsigned int>(cmSystemTools::GetTime()));
xml.Element("ElapsedMinutes", static_cast<int>(
(cmSystemTools::GetTime() - elapsed_time_start)/6)/10.0);
static_cast<unsigned int>(cmSystemTools::GetTime()));
xml.Element(
"ElapsedMinutes",
static_cast<int>((cmSystemTools::GetTime() - elapsed_time_start) / 6) /
10.0);
xml.EndElement(); // Configure
this->CTest->EndXML(xml);
}
}
else
{
} else {
cmCTestOptionalLog(this->CTest, DEBUG,
"Configure with command: " << cCommand << std::endl, this->Quiet);
}
if (! res || retVal )
{
"Configure with command: " << cCommand << std::endl,
this->Quiet);
}
if (!res || retVal) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Error(s) when configuring the project" << std::endl);
"Error(s) when configuring the project" << std::endl);
return -1;
}
}
return 0;
}
+13 -16
View File
@@ -21,23 +21,22 @@ cmCTestCoverageCommand::cmCTestCoverageCommand()
cmCTestGenericHandler* cmCTestCoverageCommand::InitializeHandler()
{
this->CTest->SetCTestConfigurationFromCMakeVariable(this->Makefile,
"CoverageCommand", "CTEST_COVERAGE_COMMAND", this->Quiet);
this->CTest->SetCTestConfigurationFromCMakeVariable(this->Makefile,
"CoverageExtraFlags", "CTEST_COVERAGE_EXTRA_FLAGS", this->Quiet);
this->CTest->SetCTestConfigurationFromCMakeVariable(
this->Makefile, "CoverageCommand", "CTEST_COVERAGE_COMMAND", this->Quiet);
this->CTest->SetCTestConfigurationFromCMakeVariable(
this->Makefile, "CoverageExtraFlags", "CTEST_COVERAGE_EXTRA_FLAGS",
this->Quiet);
cmCTestCoverageHandler* handler = static_cast<cmCTestCoverageHandler*>(
this->CTest->GetInitializedHandler("coverage"));
if ( !handler )
{
if (!handler) {
this->SetError("internal CTest error. Cannot instantiate test handler");
return 0;
}
}
// If a LABELS option was given, select only files with the labels.
if(this->LabelsMentioned)
{
if (this->LabelsMentioned) {
handler->SetLabelFilter(this->Labels);
}
}
handler->SetQuiet(this->Quiet);
return handler;
@@ -46,12 +45,11 @@ cmCTestGenericHandler* cmCTestCoverageCommand::InitializeHandler()
bool cmCTestCoverageCommand::CheckArgumentKeyword(std::string const& arg)
{
// Look for arguments specific to this command.
if(arg == "LABELS")
{
if (arg == "LABELS") {
this->ArgumentDoing = ArgumentDoingLabels;
this->LabelsMentioned = true;
return true;
}
}
// Look for other arguments.
return this->Superclass::CheckArgumentKeyword(arg);
@@ -60,11 +58,10 @@ bool cmCTestCoverageCommand::CheckArgumentKeyword(std::string const& arg)
bool cmCTestCoverageCommand::CheckArgumentValue(std::string const& arg)
{
// Handle states specific to this command.
if(this->ArgumentDoing == ArgumentDoingLabels)
{
if (this->ArgumentDoing == ArgumentDoingLabels) {
this->Labels.insert(arg);
return true;
}
}
// Look for other arguments.
return this->Superclass::CheckArgumentValue(arg);
+3 -6
View File
@@ -22,24 +22,23 @@
class cmCTestCoverageCommand : public cmCTestHandlerCommand
{
public:
cmCTestCoverageCommand();
/**
* This is a virtual constructor for the command.
*/
virtual cmCommand* Clone()
{
{
cmCTestCoverageCommand* ni = new cmCTestCoverageCommand;
ni->CTest = this->CTest;
ni->CTestScriptHandler = this->CTestScriptHandler;
return ni;
}
}
/**
* The name of the command as specified in CMakeList.txt.
*/
virtual std::string GetName() const { return "ctest_coverage";}
virtual std::string GetName() const { return "ctest_coverage"; }
cmTypeMacro(cmCTestCoverageCommand, cmCTestHandlerCommand);
@@ -59,6 +58,4 @@ protected:
std::set<std::string> Labels;
};
#endif
+964 -1238
View File
@@ -34,95 +34,82 @@
#include <math.h>
#include <stdlib.h>
#define SAFEDIV(x,y) (((y)!=0)?((x)/(y)):(0))
#define SAFEDIV(x, y) (((y) != 0) ? ((x) / (y)) : (0))
class cmCTestRunProcess
{
public:
cmCTestRunProcess()
{
this->Process = cmsysProcess_New();
this->PipeState = -1;
this->TimeOut = -1;
}
{
this->Process = cmsysProcess_New();
this->PipeState = -1;
this->TimeOut = -1;
}
~cmCTestRunProcess()
{
if(!(this->PipeState == -1)
&& !(this->PipeState == cmsysProcess_Pipe_None )
&& !(this->PipeState == cmsysProcess_Pipe_Timeout))
{
this->WaitForExit();
}
cmsysProcess_Delete(this->Process);
{
if (!(this->PipeState == -1) &&
!(this->PipeState == cmsysProcess_Pipe_None) &&
!(this->PipeState == cmsysProcess_Pipe_Timeout)) {
this->WaitForExit();
}
cmsysProcess_Delete(this->Process);
}
void SetCommand(const char* command)
{
this->CommandLineStrings.clear();
this->CommandLineStrings.push_back(command);;
}
{
this->CommandLineStrings.clear();
this->CommandLineStrings.push_back(command);
;
}
void AddArgument(const char* arg)
{
if(arg)
{
this->CommandLineStrings.push_back(arg);
}
}
void SetWorkingDirectory(const char* dir)
{
this->WorkingDirectory = dir;
}
void SetTimeout(double t)
{
this->TimeOut = t;
{
if (arg) {
this->CommandLineStrings.push_back(arg);
}
}
void SetWorkingDirectory(const char* dir) { this->WorkingDirectory = dir; }
void SetTimeout(double t) { this->TimeOut = t; }
bool StartProcess()
{
std::vector<const char*> args;
for(std::vector<std::string>::iterator i =
this->CommandLineStrings.begin();
i != this->CommandLineStrings.end(); ++i)
{
args.push_back(i->c_str());
}
args.push_back(0); // null terminate
cmsysProcess_SetCommand(this->Process, &*args.begin());
if(!this->WorkingDirectory.empty())
{
cmsysProcess_SetWorkingDirectory(this->Process,
this->WorkingDirectory.c_str());
}
{
std::vector<const char*> args;
for (std::vector<std::string>::iterator i =
this->CommandLineStrings.begin();
i != this->CommandLineStrings.end(); ++i) {
args.push_back(i->c_str());
}
args.push_back(0); // null terminate
cmsysProcess_SetCommand(this->Process, &*args.begin());
if (!this->WorkingDirectory.empty()) {
cmsysProcess_SetWorkingDirectory(this->Process,
this->WorkingDirectory.c_str());
}
cmsysProcess_SetOption(this->Process,
cmsysProcess_Option_HideWindow, 1);
if(this->TimeOut != -1)
{
cmsysProcess_SetTimeout(this->Process, this->TimeOut);
}
cmsysProcess_Execute(this->Process);
this->PipeState = cmsysProcess_GetState(this->Process);
// if the process is running or exited return true
if(this->PipeState == cmsysProcess_State_Executing
|| this->PipeState == cmsysProcess_State_Exited)
{
return true;
}
return false;
cmsysProcess_SetOption(this->Process, cmsysProcess_Option_HideWindow, 1);
if (this->TimeOut != -1) {
cmsysProcess_SetTimeout(this->Process, this->TimeOut);
}
cmsysProcess_Execute(this->Process);
this->PipeState = cmsysProcess_GetState(this->Process);
// if the process is running or exited return true
if (this->PipeState == cmsysProcess_State_Executing ||
this->PipeState == cmsysProcess_State_Exited) {
return true;
}
return false;
}
void SetStdoutFile(const char* fname)
{
{
cmsysProcess_SetPipeFile(this->Process, cmsysProcess_Pipe_STDOUT, fname);
}
}
void SetStderrFile(const char* fname)
{
{
cmsysProcess_SetPipeFile(this->Process, cmsysProcess_Pipe_STDERR, fname);
}
int WaitForExit(double* timeout =0)
{
this->PipeState = cmsysProcess_WaitForExit(this->Process,
timeout);
return this->PipeState;
}
int GetProcessState() { return this->PipeState;}
}
int WaitForExit(double* timeout = 0)
{
this->PipeState = cmsysProcess_WaitForExit(this->Process, timeout);
return this->PipeState;
}
int GetProcessState() { return this->PipeState; }
private:
int PipeState;
cmsysProcess* Process;
@@ -131,8 +118,6 @@ private:
double TimeOut;
};
cmCTestCoverageHandler::cmCTestCoverageHandler()
{
}
@@ -157,12 +142,11 @@ void cmCTestCoverageHandler::CleanCoverageLogFiles(std::ostream& log)
cmsys::Glob gl;
gl.FindFiles(logGlob);
std::vector<std::string> const& files = gl.GetFiles();
for(std::vector<std::string>::const_iterator fi = files.begin();
fi != files.end(); ++fi)
{
for (std::vector<std::string>::const_iterator fi = files.begin();
fi != files.end(); ++fi) {
log << "Removing old coverage log: " << *fi << "\n";
cmSystemTools::RemoveFile(*fi);
}
}
}
bool cmCTestCoverageHandler::StartCoverageLogFile(
@@ -170,25 +154,26 @@ bool cmCTestCoverageHandler::StartCoverageLogFile(
{
char covLogFilename[1024];
sprintf(covLogFilename, "CoverageLog-%d", logFileCount);
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Open file: "
<< covLogFilename << std::endl, this->Quiet);
if(!this->StartResultingXML(cmCTest::PartCoverage,
covLogFilename, covLogFile))
{
cmCTestLog(this->CTest, ERROR_MESSAGE, "Cannot open log file: "
<< covLogFilename << std::endl);
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Open file: " << covLogFilename << std::endl,
this->Quiet);
if (!this->StartResultingXML(cmCTest::PartCoverage, covLogFilename,
covLogFile)) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Cannot open log file: " << covLogFilename << std::endl);
return false;
}
}
return true;
}
void cmCTestCoverageHandler::EndCoverageLogFile(cmGeneratedFileStream& ostr,
int logFileCount)
int logFileCount)
{
char covLogFilename[1024];
sprintf(covLogFilename, "CoverageLog-%d.xml", logFileCount);
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Close file: "
<< covLogFilename << std::endl, this->Quiet);
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Close file: " << covLogFilename << std::endl,
this->Quiet);
ostr.Close();
}
@@ -198,7 +183,7 @@ void cmCTestCoverageHandler::StartCoverageLogXML(cmXMLWriter& xml)
xml.StartElement("CoverageLog");
xml.Element("StartDateTime", this->CTest->CurrentTime());
xml.Element("StartTime",
static_cast<unsigned int>(cmSystemTools::GetTime()));
static_cast<unsigned int>(cmSystemTools::GetTime()));
}
void cmCTestCoverageHandler::EndCoverageLogXML(cmXMLWriter& xml)
@@ -210,138 +195,117 @@ void cmCTestCoverageHandler::EndCoverageLogXML(cmXMLWriter& xml)
}
bool cmCTestCoverageHandler::ShouldIDoCoverage(const char* file,
const char* srcDir,
const char* binDir)
const char* srcDir,
const char* binDir)
{
if(this->IsFilteredOut(file))
{
if (this->IsFilteredOut(file)) {
return false;
}
}
std::vector<cmsys::RegularExpression>::iterator sit;
for ( sit = this->CustomCoverageExcludeRegex.begin();
sit != this->CustomCoverageExcludeRegex.end(); ++ sit )
{
if ( sit->find(file) )
{
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, " File " << file
<< " is excluded in CTestCustom.ctest" << std::endl;, this->Quiet);
for (sit = this->CustomCoverageExcludeRegex.begin();
sit != this->CustomCoverageExcludeRegex.end(); ++sit) {
if (sit->find(file)) {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, " File "
<< file << " is excluded in CTestCustom.ctest"
<< std::endl;
, this->Quiet);
return false;
}
}
}
std::string fSrcDir = cmSystemTools::CollapseFullPath(srcDir);
std::string fBinDir = cmSystemTools::CollapseFullPath(binDir);
std::string fFile = cmSystemTools::CollapseFullPath(file);
bool sourceSubDir = cmSystemTools::IsSubDirectory(fFile,
fSrcDir);
bool buildSubDir = cmSystemTools::IsSubDirectory(fFile,
fBinDir);
bool sourceSubDir = cmSystemTools::IsSubDirectory(fFile, fSrcDir);
bool buildSubDir = cmSystemTools::IsSubDirectory(fFile, fBinDir);
// Always check parent directory of the file.
std::string fileDir = cmSystemTools::GetFilenamePath(fFile);
std::string checkDir;
// We also need to check the binary/source directory pair.
if ( sourceSubDir && buildSubDir )
{
if ( fSrcDir.size() > fBinDir.size() )
{
if (sourceSubDir && buildSubDir) {
if (fSrcDir.size() > fBinDir.size()) {
checkDir = fSrcDir;
}
else
{
} else {
checkDir = fBinDir;
}
}
else if ( sourceSubDir )
{
} else if (sourceSubDir) {
checkDir = fSrcDir;
}
else if ( buildSubDir )
{
} else if (buildSubDir) {
checkDir = fBinDir;
}
std::string ndc
= cmSystemTools::FileExistsInParentDirectories(".NoDartCoverage",
fFile.c_str(), checkDir.c_str());
if (!ndc.empty())
{
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Found: " << ndc
<< " so skip coverage of " << file << std::endl, this->Quiet);
}
std::string ndc = cmSystemTools::FileExistsInParentDirectories(
".NoDartCoverage", fFile.c_str(), checkDir.c_str());
if (!ndc.empty()) {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Found: " << ndc << " so skip coverage of " << file
<< std::endl,
this->Quiet);
return false;
}
}
// By now checkDir should be set to parent directory of the file.
// Get the relative path to the file an apply it to the opposite directory.
// If it is the same as fileDir, then ignore, otherwise check.
std::string relPath;
if(!checkDir.empty())
{
relPath = cmSystemTools::RelativePath(checkDir.c_str(),
fFile.c_str());
}
else
{
if (!checkDir.empty()) {
relPath = cmSystemTools::RelativePath(checkDir.c_str(), fFile.c_str());
} else {
relPath = fFile;
}
if ( checkDir == fSrcDir )
{
}
if (checkDir == fSrcDir) {
checkDir = fBinDir;
}
else
{
} else {
checkDir = fSrcDir;
}
}
fFile = checkDir + "/" + relPath;
fFile = cmSystemTools::GetFilenamePath(fFile);
if ( fileDir == fFile )
{
if (fileDir == fFile) {
// This is in-source build, so we trust the previous check.
return true;
}
}
ndc = cmSystemTools::FileExistsInParentDirectories(".NoDartCoverage",
fFile.c_str(), checkDir.c_str());
if (!ndc.empty())
{
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Found: " << ndc
<< " so skip coverage of: " << file << std::endl, this->Quiet);
ndc = cmSystemTools::FileExistsInParentDirectories(
".NoDartCoverage", fFile.c_str(), checkDir.c_str());
if (!ndc.empty()) {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Found: " << ndc << " so skip coverage of: " << file
<< std::endl,
this->Quiet);
return false;
}
}
// Ok, nothing in source tree, nothing in binary tree
return true;
}
//clearly it would be nice if this were broken up into a few smaller
//functions and commented...
// clearly it would be nice if this were broken up into a few smaller
// functions and commented...
int cmCTestCoverageHandler::ProcessHandler()
{
this->CTest->ClearSubmitFiles(cmCTest::PartCoverage);
int error = 0;
// do we have time for this
if (this->CTest->GetRemainingTimeAllowed() < 120)
{
if (this->CTest->GetRemainingTimeAllowed() < 120) {
return error;
}
}
std::string coverage_start_time = this->CTest->CurrentTime();
unsigned int coverage_start_time_time = static_cast<unsigned int>(
cmSystemTools::GetTime());
std::string sourceDir
= this->CTest->GetCTestConfiguration("SourceDirectory");
std::string binaryDir
= this->CTest->GetCTestConfiguration("BuildDirectory");
unsigned int coverage_start_time_time =
static_cast<unsigned int>(cmSystemTools::GetTime());
std::string sourceDir =
this->CTest->GetCTestConfiguration("SourceDirectory");
std::string binaryDir = this->CTest->GetCTestConfiguration("BuildDirectory");
this->LoadLabels();
cmGeneratedFileStream ofs;
double elapsed_time_start = cmSystemTools::GetTime();
if ( !this->StartLogFile("Coverage", ofs) )
{
if (!this->StartLogFile("Coverage", ofs)) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Cannot create LastCoverage.log file" << std::endl);
}
"Cannot create LastCoverage.log file" << std::endl);
}
ofs << "Performing coverage: " << elapsed_time_start << std::endl;
this->CleanCoverageLogFiles(ofs);
@@ -350,7 +314,7 @@ int cmCTestCoverageHandler::ProcessHandler()
cmSystemTools::ConvertToUnixSlashes(binaryDir);
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
"Performing coverage" << std::endl, this->Quiet);
"Performing coverage" << std::endl, this->Quiet);
cmCTestCoverageHandlerContainer cont;
cont.Error = error;
@@ -362,97 +326,86 @@ int cmCTestCoverageHandler::ProcessHandler()
// setup the regex exclude stuff
this->CustomCoverageExcludeRegex.clear();
std::vector<std::string>::iterator rexIt;
for ( rexIt = this->CustomCoverageExclude.begin();
rexIt != this->CustomCoverageExclude.end();
++ rexIt )
{
for (rexIt = this->CustomCoverageExclude.begin();
rexIt != this->CustomCoverageExclude.end(); ++rexIt) {
this->CustomCoverageExcludeRegex.push_back(
cmsys::RegularExpression(rexIt->c_str()));
}
}
if(this->HandleBullseyeCoverage(&cont))
{
if (this->HandleBullseyeCoverage(&cont)) {
return cont.Error;
}
}
int file_count = 0;
file_count += this->HandleGCovCoverage(&cont);
error = cont.Error;
if ( file_count < 0 )
{
if (file_count < 0) {
return error;
}
}
file_count += this->HandleLCovCoverage(&cont);
error = cont.Error;
if ( file_count < 0 )
{
if (file_count < 0) {
return error;
}
}
file_count += this->HandleTracePyCoverage(&cont);
error = cont.Error;
if ( file_count < 0 )
{
if (file_count < 0) {
return error;
}
}
file_count += this->HandlePHPCoverage(&cont);
error = cont.Error;
if ( file_count < 0 )
{
if (file_count < 0) {
return error;
}
}
file_count += this->HandleCoberturaCoverage(&cont);
error = cont.Error;
if ( file_count < 0 )
{
if (file_count < 0) {
return error;
}
}
file_count += this->HandleMumpsCoverage(&cont);
error = cont.Error;
if ( file_count < 0 )
{
if (file_count < 0) {
return error;
}
}
file_count += this->HandleJacocoCoverage(&cont);
error = cont.Error;
if ( file_count < 0 )
{
if (file_count < 0) {
return error;
}
}
file_count += this->HandleBlanketJSCoverage(&cont);
error = cont.Error;
if ( file_count < 0 )
{
if (file_count < 0) {
return error;
}
}
file_count += this->HandleDelphiCoverage(&cont);
file_count += this->HandleDelphiCoverage(&cont);
error = cont.Error;
if ( file_count < 0 )
{
if (file_count < 0) {
return error;
}
}
std::set<std::string> uncovered = this->FindUncoveredFiles(&cont);
if (file_count == 0 && this->ExtraCoverageGlobs.empty())
{
cmCTestOptionalLog(this->CTest, WARNING,
if (file_count == 0 && this->ExtraCoverageGlobs.empty()) {
cmCTestOptionalLog(
this->CTest, WARNING,
" Cannot find any coverage files. Ignoring Coverage request."
<< std::endl, this->Quiet);
<< std::endl,
this->Quiet);
return error;
}
}
cmGeneratedFileStream covSumFile;
cmGeneratedFileStream covLogFile;
cmXMLWriter covSumXML(covSumFile);
cmXMLWriter covLogXML(covLogFile);
if(!this->StartResultingXML(cmCTest::PartCoverage, "Coverage", covSumFile))
{
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Cannot open coverage summary file." << std::endl);
if (!this->StartResultingXML(cmCTest::PartCoverage, "Coverage",
covSumFile)) {
cmCTestLog(this->CTest, ERROR_MESSAGE, "Cannot open coverage summary file."
<< std::endl);
return -1;
}
}
covSumFile.setf(std::ios::fixed, std::ios::floatfield);
covSumFile.precision(2);
@@ -463,19 +416,19 @@ int cmCTestCoverageHandler::ProcessHandler()
covSumXML.Element("StartDateTime", coverage_start_time);
covSumXML.Element("StartTime", coverage_start_time_time);
int logFileCount = 0;
if ( !this->StartCoverageLogFile(covLogFile, logFileCount) )
{
if (!this->StartCoverageLogFile(covLogFile, logFileCount)) {
return -1;
}
}
this->StartCoverageLogXML(covLogXML);
cmCTestCoverageHandlerContainer::TotalCoverageMap::iterator fileIterator;
int cnt = 0;
long total_tested = 0;
long total_untested = 0;
//std::string fullSourceDir = sourceDir + "/";
//std::string fullBinaryDir = binaryDir + "/";
// std::string fullSourceDir = sourceDir + "/";
// std::string fullBinaryDir = binaryDir + "/";
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, std::endl, this->Quiet);
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
cmCTestOptionalLog(
this->CTest, HANDLER_OUTPUT,
" Accumulating results (each . represents one file):" << std::endl,
this->Quiet);
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " ", this->Quiet);
@@ -483,77 +436,68 @@ int cmCTestCoverageHandler::ProcessHandler()
std::vector<std::string> errorsWhileAccumulating;
file_count = 0;
for ( fileIterator = cont.TotalCoverage.begin();
fileIterator != cont.TotalCoverage.end();
++fileIterator )
{
for (fileIterator = cont.TotalCoverage.begin();
fileIterator != cont.TotalCoverage.end(); ++fileIterator) {
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "." << std::flush,
this->Quiet);
file_count ++;
if ( file_count % 50 == 0 )
{
this->Quiet);
file_count++;
if (file_count % 50 == 0) {
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " processed: "
<< file_count
<< " out of "
<< cont.TotalCoverage.size() << std::endl, this->Quiet);
<< file_count << " out of "
<< cont.TotalCoverage.size() << std::endl,
this->Quiet);
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " ", this->Quiet);
}
}
const std::string fullFileName = fileIterator->first;
bool shouldIDoCoverage
= this->ShouldIDoCoverage(fullFileName.c_str(),
sourceDir.c_str(), binaryDir.c_str());
if ( !shouldIDoCoverage )
{
bool shouldIDoCoverage = this->ShouldIDoCoverage(
fullFileName.c_str(), sourceDir.c_str(), binaryDir.c_str());
if (!shouldIDoCoverage) {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
".NoDartCoverage found, so skip coverage check for: "
<< fullFileName
<< std::endl, this->Quiet);
".NoDartCoverage found, so skip coverage check for: "
<< fullFileName << std::endl,
this->Quiet);
continue;
}
}
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Process file: " << fullFileName << std::endl, this->Quiet);
"Process file: " << fullFileName << std::endl,
this->Quiet);
if ( !cmSystemTools::FileExists(fullFileName.c_str()) )
{
cmCTestLog(this->CTest, ERROR_MESSAGE, "Cannot find file: "
<< fullFileName << std::endl);
if (!cmSystemTools::FileExists(fullFileName.c_str())) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Cannot find file: " << fullFileName << std::endl);
continue;
}
}
if ( ++cnt % 100 == 0 )
{
if (++cnt % 100 == 0) {
this->EndCoverageLogXML(covLogXML);
this->EndCoverageLogFile(covLogFile, logFileCount);
logFileCount ++;
if ( !this->StartCoverageLogFile(covLogFile, logFileCount) )
{
logFileCount++;
if (!this->StartCoverageLogFile(covLogFile, logFileCount)) {
return -1;
}
this->StartCoverageLogXML(covLogXML);
}
this->StartCoverageLogXML(covLogXML);
}
const std::string fileName
= cmSystemTools::GetFilenameName(fullFileName);
const std::string fileName = cmSystemTools::GetFilenameName(fullFileName);
std::string shortFileName =
this->CTest->GetShortPathToFile(fullFileName.c_str());
const cmCTestCoverageHandlerContainer::SingleFileCoverageVector& fcov
= fileIterator->second;
const cmCTestCoverageHandlerContainer::SingleFileCoverageVector& fcov =
fileIterator->second;
covLogXML.StartElement("File");
covLogXML.Attribute("Name", fileName);
covLogXML.Attribute("FullPath", shortFileName);
covLogXML.StartElement("Report");
cmsys::ifstream ifs(fullFileName.c_str());
if ( !ifs)
{
if (!ifs) {
std::ostringstream ostr;
ostr << "Cannot open source file: " << fullFileName;
ostr << "Cannot open source file: " << fullFileName;
errorsWhileAccumulating.push_back(ostr.str());
error ++;
error++;
continue;
}
}
int tested = 0;
int untested = 0;
@@ -561,49 +505,43 @@ int cmCTestCoverageHandler::ProcessHandler()
cmCTestCoverageHandlerContainer::SingleFileCoverageVector::size_type cc;
std::string line;
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Actually performing coverage for: " << fullFileName << std::endl,
this->Quiet);
for ( cc= 0; cc < fcov.size(); cc ++ )
{
if ( !cmSystemTools::GetLineFromStream(ifs, line) &&
cc != fcov.size() -1 )
{
"Actually performing coverage for: " << fullFileName
<< std::endl,
this->Quiet);
for (cc = 0; cc < fcov.size(); cc++) {
if (!cmSystemTools::GetLineFromStream(ifs, line) &&
cc != fcov.size() - 1) {
std::ostringstream ostr;
ostr << "Problem reading source file: " << fullFileName
<< " line:" << cc << " out total: " << fcov.size()-1;
<< " line:" << cc << " out total: " << fcov.size() - 1;
errorsWhileAccumulating.push_back(ostr.str());
error ++;
error++;
break;
}
}
covLogXML.StartElement("Line");
covLogXML.Attribute("Number", cc);
covLogXML.Attribute("Count", fcov[cc]);
covLogXML.Content(line);
covLogXML.EndElement(); // Line
if ( fcov[cc] == 0 )
{
untested ++;
}
else if ( fcov[cc] > 0 )
{
tested ++;
}
if (fcov[cc] == 0) {
untested++;
} else if (fcov[cc] > 0) {
tested++;
}
if ( cmSystemTools::GetLineFromStream(ifs, line) )
{
}
if (cmSystemTools::GetLineFromStream(ifs, line)) {
std::ostringstream ostr;
ostr << "Looks like there are more lines in the file: " << fullFileName;
ostr << "Looks like there are more lines in the file: " << fullFileName;
errorsWhileAccumulating.push_back(ostr.str());
}
}
float cper = 0;
float cmet = 0;
if ( tested + untested > 0 )
{
if (tested + untested > 0) {
cper = (100 * SAFEDIV(static_cast<float>(tested),
static_cast<float>(tested + untested)));
cmet = ( SAFEDIV(static_cast<float>(tested + 10),
static_cast<float>(tested + untested + 10)));
}
static_cast<float>(tested + untested)));
cmet = (SAFEDIV(static_cast<float>(tested + 10),
static_cast<float>(tested + untested + 10)));
}
total_tested += tested;
total_untested += untested;
covLogXML.EndElement(); // Report
@@ -611,7 +549,7 @@ int cmCTestCoverageHandler::ProcessHandler()
covSumXML.StartElement("File");
covSumXML.Attribute("Name", fileName);
covSumXML.Attribute("FullPath",
this->CTest->GetShortPathToFile(fullFileName.c_str()));
this->CTest->GetShortPathToFile(fullFileName.c_str()));
covSumXML.Attribute("Covered", tested + untested > 0 ? "true" : "false");
covSumXML.Element("LOCTested", tested);
covSumXML.Element("LOCUnTested", untested);
@@ -619,12 +557,11 @@ int cmCTestCoverageHandler::ProcessHandler()
covSumXML.Element("CoverageMetric", cmet);
this->WriteXMLLabels(covSumXML, shortFileName);
covSumXML.EndElement(); // File
}
}
//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)
{
// 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;
@@ -634,27 +571,26 @@ int cmCTestCoverageHandler::ProcessHandler()
covLogXML.StartElement("Report");
cmsys::ifstream ifs(fullPath.c_str());
if (!ifs)
{
if (!ifs) {
std::ostringstream ostr;
ostr << "Cannot open source file: " << fullPath;
ostr << "Cannot open source file: " << fullPath;
errorsWhileAccumulating.push_back(ostr.str());
error ++;
error++;
continue;
}
}
int untested = 0;
std::string line;
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Actually performing coverage for: " << *i << std::endl, this->Quiet);
while (cmSystemTools::GetLineFromStream(ifs, line))
{
"Actually performing coverage for: " << *i << std::endl,
this->Quiet);
while (cmSystemTools::GetLineFromStream(ifs, line)) {
covLogXML.StartElement("Line");
covLogXML.Attribute("Number", untested);
covLogXML.Attribute("Count", 0);
covLogXML.Content(line);
covLogXML.EndElement(); // Line
untested ++;
}
untested++;
}
covLogXML.EndElement(); // Report
covLogXML.EndElement(); // File
@@ -669,33 +605,28 @@ int cmCTestCoverageHandler::ProcessHandler()
covSumXML.Element("CoverageMetric", 0);
this->WriteXMLLabels(covSumXML, *i);
covSumXML.EndElement(); // File
}
}
this->EndCoverageLogXML(covLogXML);
this->EndCoverageLogFile(covLogFile, logFileCount);
if (!errorsWhileAccumulating.empty())
{
if (!errorsWhileAccumulating.empty()) {
cmCTestLog(this->CTest, ERROR_MESSAGE, std::endl);
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Error(s) while accumulating results:" << std::endl);
"Error(s) while accumulating results:" << std::endl);
std::vector<std::string>::iterator erIt;
for ( erIt = errorsWhileAccumulating.begin();
erIt != errorsWhileAccumulating.end();
++ erIt )
{
cmCTestLog(this->CTest, ERROR_MESSAGE,
" " << *erIt << std::endl);
}
for (erIt = errorsWhileAccumulating.begin();
erIt != errorsWhileAccumulating.end(); ++erIt) {
cmCTestLog(this->CTest, ERROR_MESSAGE, " " << *erIt << std::endl);
}
}
long total_lines = total_tested + total_untested;
float percent_coverage = 100 * SAFEDIV(static_cast<float>(total_tested),
static_cast<float>(total_lines));
if ( total_lines == 0 )
{
float percent_coverage = 100 *
SAFEDIV(static_cast<float>(total_tested), static_cast<float>(total_lines));
if (total_lines == 0) {
percent_coverage = 0;
}
}
std::string end_time = this->CTest->CurrentTime();
@@ -705,60 +636,57 @@ int cmCTestCoverageHandler::ProcessHandler()
covSumXML.Element("PercentCoverage", percent_coverage);
covSumXML.Element("EndDateTime", end_time);
covSumXML.Element("EndTime",
static_cast<unsigned int>(cmSystemTools::GetTime()));
covSumXML.Element("ElapsedMinutes",
static_cast<int>((cmSystemTools::GetTime() - elapsed_time_start)/6)/10.0);
static_cast<unsigned int>(cmSystemTools::GetTime()));
covSumXML.Element(
"ElapsedMinutes",
static_cast<int>((cmSystemTools::GetTime() - elapsed_time_start) / 6) /
10.0);
covSumXML.EndElement(); // Coverage
this->CTest->EndXML(covSumXML);
cmCTestLog(this->CTest, HANDLER_OUTPUT, "" << std::endl
<< "\tCovered LOC: "
<< total_tested << std::endl
<< "\tNot covered LOC: " << total_untested << std::endl
<< "\tTotal LOC: " << total_lines << std::endl
<< "\tPercentage Coverage: "
<< std::setiosflags(std::ios::fixed)
<< std::setprecision(2)
<< (percent_coverage) << "%" << std::endl);
cmCTestLog(this->CTest, HANDLER_OUTPUT, ""
<< std::endl
<< "\tCovered LOC: " << total_tested << std::endl
<< "\tNot covered LOC: " << total_untested << std::endl
<< "\tTotal LOC: " << total_lines << std::endl
<< "\tPercentage Coverage: "
<< std::setiosflags(std::ios::fixed) << std::setprecision(2)
<< (percent_coverage) << "%" << std::endl);
ofs << "\tCovered LOC: " << total_tested << std::endl
<< "\tNot covered LOC: " << total_untested << std::endl
<< "\tTotal LOC: " << total_lines << std::endl
<< "\tPercentage Coverage: "
<< std::setiosflags(std::ios::fixed)
<< std::setprecision(2)
<< (percent_coverage) << "%" << std::endl;
<< "\tNot covered LOC: " << total_untested << std::endl
<< "\tTotal LOC: " << total_lines << std::endl
<< "\tPercentage Coverage: " << std::setiosflags(std::ios::fixed)
<< std::setprecision(2) << (percent_coverage) << "%" << std::endl;
if ( error )
{
if (error) {
return -1;
}
}
return 0;
}
void cmCTestCoverageHandler::PopulateCustomVectors(cmMakefile *mf)
void cmCTestCoverageHandler::PopulateCustomVectors(cmMakefile* mf)
{
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
" Add coverage exclude regular expressions." << std::endl, this->Quiet);
" Add coverage exclude regular expressions." << std::endl,
this->Quiet);
this->CTest->PopulateCustomVector(mf, "CTEST_CUSTOM_COVERAGE_EXCLUDE",
this->CustomCoverageExclude);
this->CustomCoverageExclude);
this->CTest->PopulateCustomVector(mf, "CTEST_EXTRA_COVERAGE_GLOB",
this->ExtraCoverageGlobs);
this->ExtraCoverageGlobs);
std::vector<std::string>::iterator it;
for ( it = this->CustomCoverageExclude.begin();
it != this->CustomCoverageExclude.end();
++ it )
{
for (it = this->CustomCoverageExclude.begin();
it != this->CustomCoverageExclude.end(); ++it) {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
" Add coverage exclude: " << *it << std::endl, this->Quiet);
}
for ( it = this->ExtraCoverageGlobs.begin();
it != this->ExtraCoverageGlobs.end(); ++it)
{
" Add coverage exclude: " << *it << std::endl,
this->Quiet);
}
for (it = this->ExtraCoverageGlobs.begin();
it != this->ExtraCoverageGlobs.end(); ++it) {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
" Add coverage glob: " << *it << std::endl, this->Quiet);
}
" Add coverage glob: " << *it << std::endl,
this->Quiet);
}
}
// Fix for issue #4971 where the case of the drive letter component of
@@ -772,19 +700,16 @@ void cmCTestCoverageHandler::PopulateCustomVectors(cmMakefile *mf)
#define fnc(s) s
#endif
bool IsFileInDir(const std::string &infile, const std::string &indir)
bool IsFileInDir(const std::string& infile, const std::string& indir)
{
std::string file = cmSystemTools::CollapseFullPath(infile);
std::string dir = cmSystemTools::CollapseFullPath(indir);
if (
file.size() > dir.size() &&
(fnc(file.substr(0, dir.size())) == fnc(dir)) &&
file[dir.size()] == '/'
)
{
if (file.size() > dir.size() &&
(fnc(file.substr(0, dir.size())) == fnc(dir)) &&
file[dir.size()] == '/') {
return true;
}
}
return false;
}
@@ -794,10 +719,9 @@ int cmCTestCoverageHandler::HandlePHPCoverage(
{
cmParsePHPCoverage cov(*cont, this->CTest);
std::string coverageDir = this->CTest->GetBinaryDir() + "/xdebugCoverage";
if(cmSystemTools::FileIsDirectory(coverageDir))
{
if (cmSystemTools::FileIsDirectory(coverageDir)) {
cov.ReadPHPCoverageDirectory(coverageDir.c_str());
}
}
return static_cast<int>(cont->TotalCoverage.size());
}
@@ -812,31 +736,27 @@ int cmCTestCoverageHandler::HandleCoberturaCoverage(
// binary directory is used.
std::string coverageXMLFile;
const char* covDir = cmSystemTools::GetEnv("COBERTURADIR");
if(covDir && strlen(covDir) != 0)
{
coverageXMLFile = std::string(covDir);
}
else
{
coverageXMLFile = this->CTest->GetBinaryDir();
}
if (covDir && strlen(covDir) != 0) {
coverageXMLFile = std::string(covDir);
} else {
coverageXMLFile = this->CTest->GetBinaryDir();
}
// build the find file string with the directory from above
coverageXMLFile += "/coverage.xml";
if(cmSystemTools::FileExists(coverageXMLFile.c_str()))
{
if (cmSystemTools::FileExists(coverageXMLFile.c_str())) {
// If file exists, parse it
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Parsing Cobertura XML file: " << coverageXMLFile
<< std::endl, this->Quiet);
"Parsing Cobertura XML file: " << coverageXMLFile
<< std::endl,
this->Quiet);
cov.ReadCoverageXML(coverageXMLFile.c_str());
}
else
{
} else {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
" Cannot find Cobertura XML file: " << coverageXMLFile
<< std::endl, this->Quiet);
}
" Cannot find Cobertura XML file: " << coverageXMLFile
<< std::endl,
this->Quiet);
}
return static_cast<int>(cont->TotalCoverage.size());
}
@@ -845,82 +765,71 @@ int cmCTestCoverageHandler::HandleMumpsCoverage(
{
// try gtm coverage
cmParseGTMCoverage cov(*cont, this->CTest);
std::string coverageFile = this->CTest->GetBinaryDir() +
"/gtm_coverage.mcov";
if(cmSystemTools::FileExists(coverageFile.c_str()))
{
std::string coverageFile =
this->CTest->GetBinaryDir() + "/gtm_coverage.mcov";
if (cmSystemTools::FileExists(coverageFile.c_str())) {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Parsing Cache Coverage: " << coverageFile
<< std::endl, this->Quiet);
"Parsing Cache Coverage: " << coverageFile << std::endl,
this->Quiet);
cov.ReadCoverageFile(coverageFile.c_str());
return static_cast<int>(cont->TotalCoverage.size());
}
else
{
} else {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
" Cannot find GTM coverage file: " << coverageFile
<< std::endl, this->Quiet);
}
" Cannot find GTM coverage file: " << coverageFile
<< std::endl,
this->Quiet);
}
cmParseCacheCoverage ccov(*cont, this->CTest);
coverageFile = this->CTest->GetBinaryDir() +
"/cache_coverage.cmcov";
if(cmSystemTools::FileExists(coverageFile.c_str()))
{
coverageFile = this->CTest->GetBinaryDir() + "/cache_coverage.cmcov";
if (cmSystemTools::FileExists(coverageFile.c_str())) {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Parsing Cache Coverage: " << coverageFile
<< std::endl, this->Quiet);
"Parsing Cache Coverage: " << coverageFile << std::endl,
this->Quiet);
ccov.ReadCoverageFile(coverageFile.c_str());
}
else
{
} else {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
" Cannot find Cache coverage file: " << coverageFile
<< std::endl, this->Quiet);
}
" Cannot find Cache coverage file: " << coverageFile
<< std::endl,
this->Quiet);
}
return static_cast<int>(cont->TotalCoverage.size());
}
struct cmCTestCoverageHandlerLocale
{
cmCTestCoverageHandlerLocale()
{
if(const char* l = cmSystemTools::GetEnv("LC_ALL"))
{
{
if (const char* l = cmSystemTools::GetEnv("LC_ALL")) {
lc_all = l;
}
if(lc_all != "C")
{
}
if (lc_all != "C") {
cmSystemTools::PutEnv("LC_ALL=C");
}
}
}
~cmCTestCoverageHandlerLocale()
{
if(!lc_all.empty())
{
{
if (!lc_all.empty()) {
cmSystemTools::PutEnv("LC_ALL=" + lc_all);
}
else
{
} else {
cmSystemTools::UnsetEnv("LC_ALL");
}
}
}
std::string lc_all;
};
int cmCTestCoverageHandler::HandleJacocoCoverage(
cmCTestCoverageHandlerContainer* cont)
{
cmParseJacocoCoverage cov =
cmParseJacocoCoverage(*cont, this->CTest);
cmParseJacocoCoverage cov = cmParseJacocoCoverage(*cont, this->CTest);
// Search in the source directory.
cmsys::Glob g1;
std::vector<std::string> files;
g1.SetRecurse(true);
std::string SourceDir
= this->CTest->GetCTestConfiguration("SourceDirectory");
std::string coverageFile = SourceDir+ "/*jacoco.xml";
std::string SourceDir =
this->CTest->GetCTestConfiguration("SourceDirectory");
std::string coverageFile = SourceDir + "/*jacoco.xml";
g1.FindFiles(coverageFile);
files = g1.GetFiles();
@@ -929,147 +838,132 @@ int cmCTestCoverageHandler::HandleJacocoCoverage(
cmsys::Glob g2;
std::vector<std::string> binFiles;
g2.SetRecurse(true);
std::string binaryDir
= this->CTest->GetCTestConfiguration("BuildDirectory");
std::string binCoverageFile = binaryDir+ "/*jacoco.xml";
std::string binaryDir = this->CTest->GetCTestConfiguration("BuildDirectory");
std::string binCoverageFile = binaryDir + "/*jacoco.xml";
g2.FindFiles(binCoverageFile);
binFiles = g2.GetFiles();
if (!binFiles.empty())
{
if (!binFiles.empty()) {
files.insert(files.end(), binFiles.begin(), binFiles.end());
}
}
if (!files.empty())
{
if (!files.empty()) {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Found Jacoco Files, Performing Coverage" << std::endl, this->Quiet);
"Found Jacoco Files, Performing Coverage" << std::endl,
this->Quiet);
cov.LoadCoverageData(files);
}
else
{
} else {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
" Cannot find Jacoco coverage files: " << coverageFile
<< std::endl, this->Quiet);
}
" Cannot find Jacoco coverage files: " << coverageFile
<< std::endl,
this->Quiet);
}
return static_cast<int>(cont->TotalCoverage.size());
}
int cmCTestCoverageHandler::HandleDelphiCoverage(
cmCTestCoverageHandlerContainer* cont)
{
cmParseDelphiCoverage cov =
cmParseDelphiCoverage(*cont, this->CTest);
cmParseDelphiCoverage cov = cmParseDelphiCoverage(*cont, this->CTest);
cmsys::Glob g;
std::vector<std::string> files;
g.SetRecurse(true);
std::string BinDir
= this->CTest->GetBinaryDir();
std::string coverageFile = BinDir+ "/*(*.pas).html";
std::string BinDir = this->CTest->GetBinaryDir();
std::string coverageFile = BinDir + "/*(*.pas).html";
g.FindFiles(coverageFile);
files=g.GetFiles();
if (!files.empty())
{
files = g.GetFiles();
if (!files.empty()) {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Found Delphi HTML Files, Performing Coverage" << std::endl,
this->Quiet);
"Found Delphi HTML Files, Performing Coverage"
<< std::endl,
this->Quiet);
cov.LoadCoverageData(files);
}
else
{
} else {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
" Cannot find Delphi coverage files: " << coverageFile
<< std::endl, this->Quiet);
}
" Cannot find Delphi coverage files: " << coverageFile
<< std::endl,
this->Quiet);
}
return static_cast<int>(cont->TotalCoverage.size());
}
int cmCTestCoverageHandler::HandleBlanketJSCoverage(
cmCTestCoverageHandlerContainer* cont)
{
cmParseBlanketJSCoverage cov =
cmParseBlanketJSCoverage(*cont, this->CTest);
std::string SourceDir
= this->CTest->GetCTestConfiguration("SourceDirectory");
{
cmParseBlanketJSCoverage cov = cmParseBlanketJSCoverage(*cont, this->CTest);
std::string SourceDir =
this->CTest->GetCTestConfiguration("SourceDirectory");
//Look for something other than output.json, still JSON extension.
std::string coverageFile = SourceDir+ "/*.json";
// Look for something other than output.json, still JSON extension.
std::string coverageFile = SourceDir + "/*.json";
cmsys::Glob g;
std::vector<std::string> files;
std::vector<std::string> blanketFiles;
g.FindFiles(coverageFile);
files=g.GetFiles();
files = g.GetFiles();
// Ensure that the JSON files found are the result of the
// Blanket.js output. Check for the "node-jscoverage"
// string on the second line
std::string line;
for(unsigned int fileEntry=0;fileEntry<files.size();fileEntry++)
{
for (unsigned int fileEntry = 0; fileEntry < files.size(); fileEntry++) {
cmsys::ifstream in(files[fileEntry].c_str());
cmSystemTools::GetLineFromStream(in, line);
cmSystemTools::GetLineFromStream(in, line);
if (line.find("node-jscoverage") != line.npos)
{
if (line.find("node-jscoverage") != line.npos) {
blanketFiles.push_back(files[fileEntry]);
}
}
// Take all files with the node-jscoverage string and parse those
if (!blanketFiles.empty())
{
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Found BlanketJS output JSON, Performing Coverage" << std::endl,
this->Quiet);
cov.LoadCoverageData(files);
}
else
{
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
" Cannot find BlanketJS coverage files: " << coverageFile
<< std::endl, this->Quiet);
}
return static_cast<int>(cont->TotalCoverage.size());
}
// Take all files with the node-jscoverage string and parse those
if (!blanketFiles.empty()) {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Found BlanketJS output JSON, Performing Coverage"
<< std::endl,
this->Quiet);
cov.LoadCoverageData(files);
} else {
cmCTestOptionalLog(
this->CTest, HANDLER_VERBOSE_OUTPUT,
" Cannot find BlanketJS coverage files: " << coverageFile << std::endl,
this->Quiet);
}
return static_cast<int>(cont->TotalCoverage.size());
}
int cmCTestCoverageHandler::HandleGCovCoverage(
cmCTestCoverageHandlerContainer* cont)
{
std::string gcovCommand
= this->CTest->GetCTestConfiguration("CoverageCommand");
if (gcovCommand.empty())
{
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Could not find gcov." << std::endl);
std::string gcovCommand =
this->CTest->GetCTestConfiguration("CoverageCommand");
if (gcovCommand.empty()) {
cmCTestLog(this->CTest, ERROR_MESSAGE, "Could not find gcov."
<< std::endl);
return 0;
}
std::string gcovExtraFlags
= this->CTest->GetCTestConfiguration("CoverageExtraFlags");
}
std::string gcovExtraFlags =
this->CTest->GetCTestConfiguration("CoverageExtraFlags");
// Immediately skip to next coverage option since codecov is only for Intel
// compiler
if ( gcovCommand == "codecov" )
{
if (gcovCommand == "codecov") {
return 0;
}
}
// Style 1
std::string st1gcovOutputRex1
= "[0-9]+\\.[0-9]+% of [0-9]+ (source |)lines executed in file (.*)$";
std::string st1gcovOutputRex1 =
"[0-9]+\\.[0-9]+% of [0-9]+ (source |)lines executed in file (.*)$";
std::string st1gcovOutputRex2 = "^Creating (.*\\.gcov)\\.";
cmsys::RegularExpression st1re1(st1gcovOutputRex1.c_str());
cmsys::RegularExpression st1re2(st1gcovOutputRex2.c_str());
// Style 2
std::string st2gcovOutputRex1 = "^File *[`'](.*)'$";
std::string st2gcovOutputRex2
= "Lines executed: *[0-9]+\\.[0-9]+% of [0-9]+$";
std::string st2gcovOutputRex2 =
"Lines executed: *[0-9]+\\.[0-9]+% of [0-9]+$";
std::string st2gcovOutputRex3 = "^(.*)reating [`'](.*\\.gcov)'";
std::string st2gcovOutputRex4 = "^(.*):unexpected EOF *$";
std::string st2gcovOutputRex5 = "^(.*):cannot open source file*$";
std::string st2gcovOutputRex6
= "^(.*):source file is newer than graph file `(.*)'$";
std::string st2gcovOutputRex6 =
"^(.*):source file is newer than graph file `(.*)'$";
cmsys::RegularExpression st2re1(st2gcovOutputRex1.c_str());
cmsys::RegularExpression st2re2(st2gcovOutputRex2.c_str());
cmsys::RegularExpression st2re3(st2gcovOutputRex3.c_str());
@@ -1081,14 +975,13 @@ int cmCTestCoverageHandler::HandleGCovCoverage(
this->FindGCovFiles(files);
std::vector<std::string>::iterator it;
if (files.empty())
{
if (files.empty()) {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
" Cannot find any GCov coverage files."
<< std::endl, this->Quiet);
" Cannot find any GCov coverage files." << std::endl,
this->Quiet);
// No coverage files is a valid thing, so the exit code is 0
return 0;
}
}
std::string testingDir = this->CTest->GetBinaryDir() + "/Testing";
std::string tempDir = testingDir + "/CoverageInfo";
@@ -1101,7 +994,8 @@ int cmCTestCoverageHandler::HandleGCovCoverage(
std::set<std::string> missingFiles;
std::string actualSourceFile = "";
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
cmCTestOptionalLog(
this->CTest, HANDLER_OUTPUT,
" Processing coverage (each . represents one file):" << std::endl,
this->Quiet);
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " ", this->Quiet);
@@ -1115,259 +1009,216 @@ int cmCTestCoverageHandler::HandleGCovCoverage(
// These are binary files that you give as input to gcov so that it will
// give us text output we can analyze to summarize coverage.
//
for ( it = files.begin(); it != files.end(); ++ it )
{
for (it = files.begin(); it != files.end(); ++it) {
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "." << std::flush,
this->Quiet);
this->Quiet);
// Call gcov to get coverage data for this *.gcda file:
//
std::string fileDir = cmSystemTools::GetFilenamePath(*it);
std::string command = "\"" + gcovCommand + "\" " +
gcovExtraFlags + " " +
"-o \"" + fileDir + "\" " +
"\"" + *it + "\"";
std::string command = "\"" + gcovCommand + "\" " + gcovExtraFlags + " " +
"-o \"" + fileDir + "\" " + "\"" + *it + "\"";
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, command.c_str()
<< std::endl, this->Quiet);
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
command.c_str() << std::endl, this->Quiet);
std::string output = "";
std::string errors = "";
int retVal = 0;
*cont->OFS << "* Run coverage for: " << fileDir << std::endl;
*cont->OFS << " Command: " << command << std::endl;
int res = this->CTest->RunCommand(command.c_str(), &output, &errors,
&retVal, tempDir.c_str(), 0 /*this->TimeOut*/);
int res =
this->CTest->RunCommand(command.c_str(), &output, &errors, &retVal,
tempDir.c_str(), 0 /*this->TimeOut*/);
*cont->OFS << " Output: " << output << std::endl;
*cont->OFS << " Errors: " << errors << std::endl;
if ( ! res )
{
if (!res) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Problem running coverage on file: " << *it << std::endl);
"Problem running coverage on file: " << *it << std::endl);
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Command produced error: " << errors << std::endl);
cont->Error ++;
"Command produced error: " << errors << std::endl);
cont->Error++;
continue;
}
if ( retVal != 0 )
{
}
if (retVal != 0) {
cmCTestLog(this->CTest, ERROR_MESSAGE, "Coverage command returned: "
<< retVal << " while processing: " << *it << std::endl);
<< retVal << " while processing: " << *it << std::endl);
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Command produced error: " << cont->Error << std::endl);
}
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Command produced error: " << cont->Error << std::endl);
}
cmCTestOptionalLog(
this->CTest, HANDLER_VERBOSE_OUTPUT,
"--------------------------------------------------------------"
<< std::endl
<< output << std::endl
<< "--------------------------------------------------------------"
<< std::endl, this->Quiet);
<< std::endl
<< output << std::endl
<< "--------------------------------------------------------------"
<< std::endl,
this->Quiet);
std::vector<std::string> lines;
std::vector<std::string>::iterator line;
cmSystemTools::Split(output.c_str(), lines);
for ( line = lines.begin(); line != lines.end(); ++line)
{
for (line = lines.begin(); line != lines.end(); ++line) {
std::string sourceFile;
std::string gcovFile;
cmCTestOptionalLog(this->CTest, DEBUG, "Line: [" << *line << "]"
<< std::endl, this->Quiet);
cmCTestOptionalLog(this->CTest, DEBUG,
"Line: [" << *line << "]" << std::endl, this->Quiet);
if (line->empty())
{
if (line->empty()) {
// Ignore empty line; probably style 2
}
else if ( st1re1.find(line->c_str()) )
{
if ( gcovStyle == 0 )
{
} else if (st1re1.find(line->c_str())) {
if (gcovStyle == 0) {
gcovStyle = 1;
}
if ( gcovStyle != 1 )
{
}
if (gcovStyle != 1) {
cmCTestLog(this->CTest, ERROR_MESSAGE, "Unknown gcov output style e1"
<< std::endl);
cont->Error ++;
<< std::endl);
cont->Error++;
break;
}
}
actualSourceFile = "";
sourceFile = st1re1.match(2);
}
else if ( st1re2.find(line->c_str() ) )
{
if ( gcovStyle == 0 )
{
} else if (st1re2.find(line->c_str())) {
if (gcovStyle == 0) {
gcovStyle = 1;
}
if ( gcovStyle != 1 )
{
}
if (gcovStyle != 1) {
cmCTestLog(this->CTest, ERROR_MESSAGE, "Unknown gcov output style e2"
<< std::endl);
cont->Error ++;
<< std::endl);
cont->Error++;
break;
}
}
gcovFile = st1re2.match(1);
}
else if ( st2re1.find(line->c_str() ) )
{
if ( gcovStyle == 0 )
{
} else if (st2re1.find(line->c_str())) {
if (gcovStyle == 0) {
gcovStyle = 2;
}
if ( gcovStyle != 2 )
{
}
if (gcovStyle != 2) {
cmCTestLog(this->CTest, ERROR_MESSAGE, "Unknown gcov output style e3"
<< std::endl);
cont->Error ++;
<< std::endl);
cont->Error++;
break;
}
}
actualSourceFile = "";
sourceFile = st2re1.match(1);
}
else if ( st2re2.find(line->c_str() ) )
{
if ( gcovStyle == 0 )
{
} else if (st2re2.find(line->c_str())) {
if (gcovStyle == 0) {
gcovStyle = 2;
}
if ( gcovStyle != 2 )
{
}
if (gcovStyle != 2) {
cmCTestLog(this->CTest, ERROR_MESSAGE, "Unknown gcov output style e4"
<< std::endl);
cont->Error ++;
<< std::endl);
cont->Error++;
break;
}
}
else if ( st2re3.find(line->c_str() ) )
{
if ( gcovStyle == 0 )
{
} else if (st2re3.find(line->c_str())) {
if (gcovStyle == 0) {
gcovStyle = 2;
}
if ( gcovStyle != 2 )
{
}
if (gcovStyle != 2) {
cmCTestLog(this->CTest, ERROR_MESSAGE, "Unknown gcov output style e5"
<< std::endl);
cont->Error ++;
<< std::endl);
cont->Error++;
break;
}
}
gcovFile = st2re3.match(2);
}
else if ( st2re4.find(line->c_str() ) )
{
if ( gcovStyle == 0 )
{
} else if (st2re4.find(line->c_str())) {
if (gcovStyle == 0) {
gcovStyle = 2;
}
if ( gcovStyle != 2 )
{
}
if (gcovStyle != 2) {
cmCTestLog(this->CTest, ERROR_MESSAGE, "Unknown gcov output style e6"
<< std::endl);
cont->Error ++;
<< std::endl);
cont->Error++;
break;
}
cmCTestOptionalLog(this->CTest, WARNING, "Warning: " << st2re4.match(1)
<< " had unexpected EOF" << std::endl, this->Quiet);
}
else if ( st2re5.find(line->c_str() ) )
{
if ( gcovStyle == 0 )
{
cmCTestOptionalLog(this->CTest, WARNING,
"Warning: " << st2re4.match(1)
<< " had unexpected EOF" << std::endl,
this->Quiet);
} else if (st2re5.find(line->c_str())) {
if (gcovStyle == 0) {
gcovStyle = 2;
}
if ( gcovStyle != 2 )
{
}
if (gcovStyle != 2) {
cmCTestLog(this->CTest, ERROR_MESSAGE, "Unknown gcov output style e7"
<< std::endl);
cont->Error ++;
<< std::endl);
cont->Error++;
break;
}
}
cmCTestOptionalLog(this->CTest, WARNING, "Warning: Cannot open file: "
<< st2re5.match(1) << std::endl, this->Quiet);
}
else if ( st2re6.find(line->c_str() ) )
{
if ( gcovStyle == 0 )
{
<< st2re5.match(1) << std::endl,
this->Quiet);
} else if (st2re6.find(line->c_str())) {
if (gcovStyle == 0) {
gcovStyle = 2;
}
if ( gcovStyle != 2 )
{
}
if (gcovStyle != 2) {
cmCTestLog(this->CTest, ERROR_MESSAGE, "Unknown gcov output style e8"
<< std::endl);
cont->Error ++;
<< std::endl);
cont->Error++;
break;
}
}
cmCTestOptionalLog(this->CTest, WARNING, "Warning: File: "
<< st2re6.match(1)
<< " is newer than " << st2re6.match(2) << std::endl, this->Quiet);
}
else
{
<< st2re6.match(1) << " is newer than "
<< st2re6.match(2) << std::endl,
this->Quiet);
} else {
// gcov 4.7 can have output lines saying "No executable lines" and
// "Removing 'filename.gcov'"... Don't log those as "errors."
if(*line != "No executable lines" &&
!cmSystemTools::StringStartsWith(line->c_str(), "Removing "))
{
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Unknown gcov output line: [" << *line << "]"
<< std::endl);
cont->Error ++;
//abort();
}
if (*line != "No executable lines" &&
!cmSystemTools::StringStartsWith(line->c_str(), "Removing ")) {
cmCTestLog(this->CTest, ERROR_MESSAGE, "Unknown gcov output line: ["
<< *line << "]" << std::endl);
cont->Error++;
// abort();
}
}
// If the last line of gcov output gave us a valid value for gcovFile,
// and we have an actualSourceFile, then insert a (or add to existing)
// SingleFileCoverageVector for actualSourceFile:
//
if ( !gcovFile.empty() && !actualSourceFile.empty() )
{
cmCTestCoverageHandlerContainer::SingleFileCoverageVector& vec
= cont->TotalCoverage[actualSourceFile];
if (!gcovFile.empty() && !actualSourceFile.empty()) {
cmCTestCoverageHandlerContainer::SingleFileCoverageVector& vec =
cont->TotalCoverage[actualSourceFile];
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
" in gcovFile: " << gcovFile << std::endl, this->Quiet);
" in gcovFile: " << gcovFile << std::endl,
this->Quiet);
cmsys::ifstream ifile(gcovFile.c_str());
if ( ! ifile )
{
cmCTestLog(this->CTest, ERROR_MESSAGE, "Cannot open file: "
<< gcovFile << std::endl);
}
else
{
if (!ifile) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Cannot open file: " << gcovFile << std::endl);
} else {
long cnt = -1;
std::string nl;
while ( cmSystemTools::GetLineFromStream(ifile, nl) )
{
cnt ++;
while (cmSystemTools::GetLineFromStream(ifile, nl)) {
cnt++;
//TODO: Handle gcov 3.0 non-coverage lines
// TODO: Handle gcov 3.0 non-coverage lines
// Skip empty lines
if (nl.empty())
{
if (nl.empty()) {
continue;
}
}
// Skip unused lines
if ( nl.size() < 12 )
{
if (nl.size() < 12) {
continue;
}
}
// Read the coverage count from the beginning of the gcov output
// line
@@ -1378,96 +1229,86 @@ int cmCTestCoverageHandler::HandleGCovCoverage(
// output line
std::string lineNumber = nl.substr(10, 5);
int lineIdx = atoi(lineNumber.c_str())-1;
if ( lineIdx >= 0 )
{
while ( vec.size() <= static_cast<size_t>(lineIdx) )
{
int lineIdx = atoi(lineNumber.c_str()) - 1;
if (lineIdx >= 0) {
while (vec.size() <= static_cast<size_t>(lineIdx)) {
vec.push_back(-1);
}
}
// Initially all entries are -1 (not used). If we get coverage
// information, increment it to 0 first.
if ( vec[lineIdx] < 0 )
{
if ( cov > 0 || prefix.find("#") != prefix.npos )
{
if (vec[lineIdx] < 0) {
if (cov > 0 || prefix.find("#") != prefix.npos) {
vec[lineIdx] = 0;
}
}
}
vec[lineIdx] += cov;
}
}
}
actualSourceFile = "";
}
actualSourceFile = "";
}
if ( !sourceFile.empty() && actualSourceFile.empty() )
{
if (!sourceFile.empty() && actualSourceFile.empty()) {
gcovFile = "";
// Is it in the source dir or the binary dir?
//
if ( IsFileInDir(sourceFile, cont->SourceDir) )
{
if (IsFileInDir(sourceFile, cont->SourceDir)) {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
" produced s: " << sourceFile << std::endl, this->Quiet);
" produced s: " << sourceFile << std::endl,
this->Quiet);
*cont->OFS << " produced in source dir: " << sourceFile
<< std::endl;
actualSourceFile
= cmSystemTools::CollapseFullPath(sourceFile);
}
else if ( IsFileInDir(sourceFile, cont->BinaryDir) )
{
<< std::endl;
actualSourceFile = cmSystemTools::CollapseFullPath(sourceFile);
} else if (IsFileInDir(sourceFile, cont->BinaryDir)) {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
" produced b: " << sourceFile << std::endl, this->Quiet);
" produced b: " << sourceFile << std::endl,
this->Quiet);
*cont->OFS << " produced in binary dir: " << sourceFile
<< std::endl;
actualSourceFile
= cmSystemTools::CollapseFullPath(sourceFile);
}
<< std::endl;
actualSourceFile = cmSystemTools::CollapseFullPath(sourceFile);
}
if ( actualSourceFile.empty() )
{
if ( missingFiles.find(sourceFile) == missingFiles.end() )
{
if (actualSourceFile.empty()) {
if (missingFiles.find(sourceFile) == missingFiles.end()) {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Something went wrong" << std::endl, this->Quiet);
"Something went wrong" << std::endl,
this->Quiet);
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Cannot find file: ["
<< sourceFile << "]" << std::endl, this->Quiet);
"Cannot find file: [" << sourceFile << "]"
<< std::endl,
this->Quiet);
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
" in source dir: ["
<< cont->SourceDir << "]"
<< std::endl, this->Quiet);
" in source dir: [" << cont->SourceDir << "]"
<< std::endl,
this->Quiet);
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
" or binary dir: ["
<< cont->BinaryDir.size() << "]"
<< std::endl, this->Quiet);
" or binary dir: [" << cont->BinaryDir.size()
<< "]" << std::endl,
this->Quiet);
*cont->OFS << " Something went wrong. Cannot find file: "
<< sourceFile
<< " in source dir: " << cont->SourceDir
<< " or binary dir: " << cont->BinaryDir << std::endl;
<< sourceFile << " in source dir: " << cont->SourceDir
<< " or binary dir: " << cont->BinaryDir << std::endl;
missingFiles.insert(sourceFile);
}
}
}
}
}
file_count++;
if ( file_count % 50 == 0 )
{
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " processed: "
<< file_count
<< " out of " << files.size() << std::endl, this->Quiet);
if (file_count % 50 == 0) {
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
" processed: " << file_count << " out of "
<< files.size() << std::endl,
this->Quiet);
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " ", this->Quiet);
}
}
}
cmSystemTools::ChangeDirectory(currentDirectory);
return file_count;
@@ -1476,46 +1317,44 @@ int cmCTestCoverageHandler::HandleGCovCoverage(
int cmCTestCoverageHandler::HandleLCovCoverage(
cmCTestCoverageHandlerContainer* cont)
{
std::string lcovCommand
= this->CTest->GetCTestConfiguration("CoverageCommand");
std::string lcovExtraFlags
= this->CTest->GetCTestConfiguration("CoverageExtraFlags");
if ( lcovCommand != "codecov" )
{
std::string lcovCommand =
this->CTest->GetCTestConfiguration("CoverageCommand");
std::string lcovExtraFlags =
this->CTest->GetCTestConfiguration("CoverageExtraFlags");
if (lcovCommand != "codecov") {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
" Not a valid Intel Coverage command."
<< std::endl, this->Quiet);
" Not a valid Intel Coverage command." << std::endl,
this->Quiet);
return 0;
}
}
// There is only percentage completed output from LCOV
std::string st2lcovOutputRex3 = "[0-9]+%";
cmsys::RegularExpression st2re3(st2lcovOutputRex3.c_str());
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
" This is coverage command: " << lcovCommand
<< std::endl, this->Quiet);
" This is coverage command: " << lcovCommand << std::endl,
this->Quiet);
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
" These are coverage command flags: " << lcovExtraFlags
<< std::endl, this->Quiet);
" These are coverage command flags: " << lcovExtraFlags
<< std::endl,
this->Quiet);
std::vector<std::string> files;
if (!this->FindLCovFiles(files))
{
if (!this->FindLCovFiles(files)) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Error while finding LCov files.\n");
return 0;
}
}
std::vector<std::string>::iterator it;
if (files.empty())
{
if (files.empty()) {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
" Cannot find any LCov coverage files."
<< std::endl, this->Quiet);
" Cannot find any LCov coverage files." << std::endl,
this->Quiet);
// No coverage files is a valid thing, so the exit code is 0
return 0;
}
}
std::string testingDir = this->CTest->GetBinaryDir();
std::string tempDir = testingDir;
std::string currentDirectory = cmSystemTools::GetCurrentWorkingDirectory();
@@ -1523,7 +1362,8 @@ int cmCTestCoverageHandler::HandleLCovCoverage(
std::set<std::string> missingFiles;
std::string actualSourceFile = "";
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
cmCTestOptionalLog(
this->CTest, HANDLER_OUTPUT,
" Processing coverage (each . represents one file):" << std::endl,
this->Quiet);
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " ", this->Quiet);
@@ -1535,67 +1375,65 @@ int cmCTestCoverageHandler::HandleLCovCoverage(
// In intel compiler we have to call codecov only once in each executable
// directory. It collects all *.dyn files to generate .dpi file.
for ( it = files.begin(); it != files.end(); ++ it )
{
for (it = files.begin(); it != files.end(); ++it) {
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "." << std::flush,
this->Quiet);
this->Quiet);
std::string fileDir = cmSystemTools::GetFilenamePath(*it);
cmSystemTools::ChangeDirectory(fileDir);
std::string command = "\"" + lcovCommand + "\" " +
lcovExtraFlags + " ";
std::string command = "\"" + lcovCommand + "\" " + lcovExtraFlags + " ";
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Current coverage dir: " << fileDir << std::endl, this->Quiet);
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, command.c_str()
<< std::endl, this->Quiet);
"Current coverage dir: " << fileDir << std::endl,
this->Quiet);
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
command.c_str() << std::endl, this->Quiet);
std::string output = "";
std::string errors = "";
int retVal = 0;
*cont->OFS << "* Run coverage for: " << fileDir << std::endl;
*cont->OFS << " Command: " << command << std::endl;
int res = this->CTest->RunCommand(command.c_str(), &output, &errors,
&retVal, fileDir.c_str(), 0 /*this->TimeOut*/);
int res =
this->CTest->RunCommand(command.c_str(), &output, &errors, &retVal,
fileDir.c_str(), 0 /*this->TimeOut*/);
*cont->OFS << " Output: " << output << std::endl;
*cont->OFS << " Errors: " << errors << std::endl;
if ( ! res )
{
if (!res) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Problem running coverage on file: " << *it << std::endl);
"Problem running coverage on file: " << *it << std::endl);
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Command produced error: " << errors << std::endl);
cont->Error ++;
"Command produced error: " << errors << std::endl);
cont->Error++;
continue;
}
if ( retVal != 0 )
{
}
if (retVal != 0) {
cmCTestLog(this->CTest, ERROR_MESSAGE, "Coverage command returned: "
<< retVal << " while processing: " << *it << std::endl);
<< retVal << " while processing: " << *it << std::endl);
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Command produced error: " << cont->Error << std::endl);
}
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Command produced error: " << cont->Error << std::endl);
}
cmCTestOptionalLog(
this->CTest, HANDLER_VERBOSE_OUTPUT,
"--------------------------------------------------------------"
<< std::endl
<< output << std::endl
<< "--------------------------------------------------------------"
<< std::endl, this->Quiet);
<< std::endl
<< output << std::endl
<< "--------------------------------------------------------------"
<< std::endl,
this->Quiet);
std::vector<std::string> lines;
std::vector<std::string>::iterator line;
cmSystemTools::Split(output.c_str(), lines);
for ( line = lines.begin(); line != lines.end(); ++line)
{
for (line = lines.begin(); line != lines.end(); ++line) {
std::string sourceFile;
std::string lcovFile;
if (line->empty())
{
if (line->empty()) {
// Ignore empty line
}
}
// Look for LCOV files in binary directory
// Intel Compiler creates a CodeCoverage dir for each subfolder and
// each subfolder has LCOV files
@@ -1608,89 +1446,84 @@ int cmCTestCoverageHandler::HandleLCovCoverage(
std::string daGlob;
daGlob = dir;
daGlob += "/*.LCOV";
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
cmCTestOptionalLog(
this->CTest, HANDLER_VERBOSE_OUTPUT,
" looking for LCOV files in: " << daGlob << std::endl, this->Quiet);
gl.FindFiles(daGlob);
// Keep a list of all LCOV files
lcovFiles.insert(lcovFiles.end(), gl.GetFiles().begin(),
gl.GetFiles().end());
for(std::vector<std::string>::iterator a = lcovFiles.begin();
a != lcovFiles.end(); ++a)
{
for (std::vector<std::string>::iterator a = lcovFiles.begin();
a != lcovFiles.end(); ++a) {
lcovFile = *a;
cmsys::ifstream srcead(lcovFile.c_str());
if ( ! srcead )
{
cmCTestLog(this->CTest, ERROR_MESSAGE, "Cannot open file: "
<< lcovFile << std::endl);
}
if (!srcead) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Cannot open file: " << lcovFile << std::endl);
}
std::string srcname;
int success = cmSystemTools::GetLineFromStream(srcead, srcname);
if ( !success )
{
if (!success) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Error while parsing lcov file '" << lcovFile << "':"
<< " No source file name found!" << std::endl);
"Error while parsing lcov file '"
<< lcovFile << "':"
<< " No source file name found!" << std::endl);
return 0;
}
}
srcname = srcname.substr(18);
// We can directly read found LCOV files to determine the source
// files
sourceFile = srcname;
actualSourceFile = srcname;
for(std::vector<std::string>::iterator t = lcovFiles.begin();
t != lcovFiles.end(); ++t)
{
for (std::vector<std::string>::iterator t = lcovFiles.begin();
t != lcovFiles.end(); ++t) {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Found LCOV File: " << *t << std::endl, this->Quiet);
}
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "SourceFile: "
<< sourceFile << std::endl, this->Quiet);
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "lCovFile: "
<< lcovFile << std::endl, this->Quiet);
"Found LCOV File: " << *t << std::endl,
this->Quiet);
}
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"SourceFile: " << sourceFile << std::endl,
this->Quiet);
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"lCovFile: " << lcovFile << std::endl, this->Quiet);
// If we have some LCOV files to process
if ( !lcovFile.empty() && !actualSourceFile.empty() )
{
cmCTestCoverageHandlerContainer::SingleFileCoverageVector& vec
= cont->TotalCoverage[actualSourceFile];
if (!lcovFile.empty() && !actualSourceFile.empty()) {
cmCTestCoverageHandlerContainer::SingleFileCoverageVector& vec =
cont->TotalCoverage[actualSourceFile];
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
" in lcovFile: " << lcovFile << std::endl, this->Quiet);
" in lcovFile: " << lcovFile << std::endl,
this->Quiet);
cmsys::ifstream ifile(lcovFile.c_str());
if ( ! ifile )
{
cmCTestLog(this->CTest, ERROR_MESSAGE, "Cannot open file: "
<< lcovFile << std::endl);
}
else
{
if (!ifile) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Cannot open file: " << lcovFile << std::endl);
} else {
long cnt = -1;
std::string nl;
// Skip the first line
cmSystemTools::GetLineFromStream(ifile, nl);
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"File is ready, start reading." << std::endl, this->Quiet);
while ( cmSystemTools::GetLineFromStream(ifile, nl) )
{
cnt ++;
"File is ready, start reading." << std::endl,
this->Quiet);
while (cmSystemTools::GetLineFromStream(ifile, nl)) {
cnt++;
// Skip empty lines
if (nl.empty())
{
if (nl.empty()) {
continue;
}
}
// Skip unused lines
if ( nl.size() < 12 )
{
if (nl.size() < 12) {
continue;
}
}
// Read the coverage count from the beginning of the lcov
// output line
@@ -1701,44 +1534,40 @@ int cmCTestCoverageHandler::HandleLCovCoverage(
// lcov output line
std::string lineNumber = nl.substr(17, 7);
int lineIdx = atoi(lineNumber.c_str())-1;
if ( lineIdx >= 0 )
{
while ( vec.size() <= static_cast<size_t>(lineIdx) )
{
int lineIdx = atoi(lineNumber.c_str()) - 1;
if (lineIdx >= 0) {
while (vec.size() <= static_cast<size_t>(lineIdx)) {
vec.push_back(-1);
}
}
// Initially all entries are -1 (not used). If we get coverage
// information, increment it to 0 first.
if ( vec[lineIdx] < 0 )
{
if ( cov > 0 || prefix.find("#") != prefix.npos )
{
if (vec[lineIdx] < 0) {
if (cov > 0 || prefix.find("#") != prefix.npos) {
vec[lineIdx] = 0;
}
}
}
vec[lineIdx] += cov;
}
}
}
}
actualSourceFile = "";
}
}
}
}
file_count++;
if ( file_count % 50 == 0 )
{
if (file_count % 50 == 0) {
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
" processed: " << file_count << " out of " << files.size()
<< std::endl, this->Quiet);
" processed: " << file_count << " out of "
<< files.size() << std::endl,
this->Quiet);
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " ", this->Quiet);
}
}
}
cmSystemTools::ChangeDirectory(currentDirectory);
return file_count;
@@ -1750,18 +1579,17 @@ void cmCTestCoverageHandler::FindGCovFiles(std::vector<std::string>& files)
gl.RecurseOn();
gl.RecurseThroughSymlinksOff();
for(LabelMapType::const_iterator lmi = this->TargetDirs.begin();
lmi != this->TargetDirs.end(); ++lmi)
{
for (LabelMapType::const_iterator lmi = this->TargetDirs.begin();
lmi != this->TargetDirs.end(); ++lmi) {
// Skip targets containing no interesting labels.
if(!this->IntersectsFilter(lmi->second))
{
if (!this->IntersectsFilter(lmi->second)) {
continue;
}
}
// Coverage files appear next to their object files in the target
// support directory.
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
cmCTestOptionalLog(
this->CTest, HANDLER_VERBOSE_OUTPUT,
" globbing for coverage in: " << lmi->first << std::endl, this->Quiet);
std::string daGlob = lmi->first;
daGlob += "/*.da";
@@ -1771,7 +1599,7 @@ void cmCTestCoverageHandler::FindGCovFiles(std::vector<std::string>& files)
daGlob += "/*.gcda";
gl.FindFiles(daGlob);
files.insert(files.end(), gl.GetFiles().begin(), gl.GetFiles().end());
}
}
}
bool cmCTestCoverageHandler::FindLCovFiles(std::vector<std::string>& files)
@@ -1782,20 +1610,17 @@ bool cmCTestCoverageHandler::FindLCovFiles(std::vector<std::string>& files)
gl.RecurseThroughSymlinksOff();
std::string prevBinaryDir;
std::string buildDir = this->CTest->GetCTestConfiguration("BuildDirectory");
if (cmSystemTools::ChangeDirectory(buildDir))
{
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Error changing directory to " << buildDir << std::endl);
if (cmSystemTools::ChangeDirectory(buildDir)) {
cmCTestLog(this->CTest, ERROR_MESSAGE, "Error changing directory to "
<< buildDir << std::endl);
return false;
}
}
// Run profmerge to merge all *.dyn files into dpi files
if (!cmSystemTools::RunSingleCommand("profmerge"))
{
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Error while running profmerge.\n");
if (!cmSystemTools::RunSingleCommand("profmerge")) {
cmCTestLog(this->CTest, ERROR_MESSAGE, "Error while running profmerge.\n");
return false;
}
}
prevBinaryDir = cmSystemTools::GetCurrentWorkingDirectory().c_str();
@@ -1804,16 +1629,16 @@ bool cmCTestCoverageHandler::FindLCovFiles(std::vector<std::string>& files)
daGlob = prevBinaryDir;
daGlob += "/*.dpi";
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
" looking for dpi files in: " << daGlob << std::endl, this->Quiet);
if (!gl.FindFiles(daGlob))
{
" looking for dpi files in: " << daGlob << std::endl,
this->Quiet);
if (!gl.FindFiles(daGlob)) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Error while finding files matching " << daGlob << std::endl);
return false;
}
}
files.insert(files.end(), gl.GetFiles().begin(), gl.GetFiles().end());
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Now searching in: " << daGlob << std::endl, this->Quiet);
"Now searching in: " << daGlob << std::endl, this->Quiet);
return true;
}
@@ -1827,14 +1652,14 @@ int cmCTestCoverageHandler::HandleTracePyCoverage(
gl.FindFiles(daGlob);
std::vector<std::string> files = gl.GetFiles();
if (files.empty())
{
if (files.empty()) {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
" Cannot find any Python Trace.py coverage files."
<< std::endl, this->Quiet);
" Cannot find any Python Trace.py coverage files."
<< std::endl,
this->Quiet);
// No coverage files is a valid thing, so the exit code is 0
return 0;
}
}
std::string testingDir = this->CTest->GetBinaryDir() + "/Testing";
std::string tempDir = testingDir + "/CoverageInfo";
@@ -1846,319 +1671,276 @@ int cmCTestCoverageHandler::HandleTracePyCoverage(
std::vector<std::string>::iterator fileIt;
int file_count = 0;
for ( fileIt = files.begin(); fileIt != files.end(); ++ fileIt )
{
for (fileIt = files.begin(); fileIt != files.end(); ++fileIt) {
std::string fileName = this->FindFile(cont, *fileIt);
if ( fileName.empty() )
{
if (fileName.empty()) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Cannot find source Python file corresponding to: "
<< *fileIt << std::endl);
"Cannot find source Python file corresponding to: "
<< *fileIt << std::endl);
continue;
}
}
std::string actualSourceFile
= cmSystemTools::CollapseFullPath(fileName);
std::string actualSourceFile = cmSystemTools::CollapseFullPath(fileName);
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
" Check coverage for file: " << actualSourceFile
<< std::endl, this->Quiet);
cmCTestCoverageHandlerContainer::SingleFileCoverageVector* vec
= &cont->TotalCoverage[actualSourceFile];
" Check coverage for file: " << actualSourceFile
<< std::endl,
this->Quiet);
cmCTestCoverageHandlerContainer::SingleFileCoverageVector* vec =
&cont->TotalCoverage[actualSourceFile];
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
" in file: " << *fileIt << std::endl, this->Quiet);
" in file: " << *fileIt << std::endl, this->Quiet);
cmsys::ifstream ifile(fileIt->c_str());
if ( ! ifile )
{
cmCTestLog(this->CTest, ERROR_MESSAGE, "Cannot open file: "
<< *fileIt << std::endl);
}
else
{
if (!ifile) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Cannot open file: " << *fileIt << std::endl);
} else {
long cnt = -1;
std::string nl;
while ( cmSystemTools::GetLineFromStream(ifile, nl) )
{
cnt ++;
while (cmSystemTools::GetLineFromStream(ifile, nl)) {
cnt++;
// Skip empty lines
if (nl.empty())
{
if (nl.empty()) {
continue;
}
}
// Skip unused lines
if ( nl.size() < 12 )
{
if (nl.size() < 12) {
continue;
}
}
// Read the coverage count from the beginning of the Trace.py output
// line
std::string prefix = nl.substr(0, 6);
if ( prefix[5] != ' ' && prefix[5] != ':' )
{
if (prefix[5] != ' ' && prefix[5] != ':') {
// This is a hack. We should really do something more elaborate
prefix = nl.substr(0, 7);
if ( prefix[6] != ' ' && prefix[6] != ':' )
{
if (prefix[6] != ' ' && prefix[6] != ':') {
prefix = nl.substr(0, 8);
if ( prefix[7] != ' ' && prefix[7] != ':' )
{
if (prefix[7] != ' ' && prefix[7] != ':') {
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Currently the limit is maximum coverage of 999999"
<< std::endl);
}
"Currently the limit is maximum coverage of 999999"
<< std::endl);
}
}
}
int cov = atoi(prefix.c_str());
if ( prefix[prefix.size()-1] != ':' )
{
if (prefix[prefix.size() - 1] != ':') {
// This line does not have ':' so no coverage here. That said,
// Trace.py does not handle not covered lines versus comments etc.
// So, this will be set to 0.
cov = 0;
}
cmCTestOptionalLog(this->CTest, DEBUG, "Prefix: " << prefix
<< " cov: " << cov
<< std::endl, this->Quiet);
}
cmCTestOptionalLog(
this->CTest, DEBUG,
"Prefix: " << prefix << " cov: " << cov << std::endl, this->Quiet);
// Read the line number starting at the 10th character of the gcov
// output line
long lineIdx = cnt;
if ( lineIdx >= 0 )
{
while ( vec->size() <=
static_cast<size_t>(lineIdx) )
{
if (lineIdx >= 0) {
while (vec->size() <= static_cast<size_t>(lineIdx)) {
vec->push_back(-1);
}
}
// Initially all entries are -1 (not used). If we get coverage
// information, increment it to 0 first.
if ( (*vec)[lineIdx] < 0 )
{
if ( cov >= 0 )
{
if ((*vec)[lineIdx] < 0) {
if (cov >= 0) {
(*vec)[lineIdx] = 0;
}
}
(*vec)[lineIdx] += cov;
}
(*vec)[lineIdx] += cov;
}
}
++ file_count;
}
++file_count;
}
cmSystemTools::ChangeDirectory(currentDirectory);
return file_count;
}
std::string cmCTestCoverageHandler::FindFile(
cmCTestCoverageHandlerContainer* cont,
std::string fileName)
cmCTestCoverageHandlerContainer* cont, std::string fileName)
{
std::string fileNameNoE
= cmSystemTools::GetFilenameWithoutLastExtension(fileName);
std::string fileNameNoE =
cmSystemTools::GetFilenameWithoutLastExtension(fileName);
// First check in source and binary directory
std::string fullName = cont->SourceDir + "/" + fileNameNoE + ".py";
if ( cmSystemTools::FileExists(fullName.c_str()) )
{
if (cmSystemTools::FileExists(fullName.c_str())) {
return fullName;
}
}
fullName = cont->BinaryDir + "/" + fileNameNoE + ".py";
if ( cmSystemTools::FileExists(fullName.c_str()) )
{
if (cmSystemTools::FileExists(fullName.c_str())) {
return fullName;
}
}
return "";
}
// This is a header put on each marked up source file
namespace
{
const char* bullseyeHelp[] =
{" Coverage produced by bullseye covbr tool: ",
" www.bullseye.com/help/ref_covbr.html",
" * An arrow --> indicates incomplete coverage.",
" * An X indicates a function that was invoked, a switch label that ",
" was exercised, a try-block that finished, or an exception handler ",
" that was invoked.",
" * A T or F indicates a boolean decision that evaluated true or false,",
" respectively.",
" * A t or f indicates a boolean condition within a decision if the ",
" condition evaluated true or false, respectively.",
" * A k indicates a constant decision or condition.",
" * The slash / means this probe is excluded from summary results. ",
0};
namespace {
const char* bullseyeHelp[] = {
" Coverage produced by bullseye covbr tool: ",
" www.bullseye.com/help/ref_covbr.html",
" * An arrow --> indicates incomplete coverage.",
" * An X indicates a function that was invoked, a switch label that ",
" was exercised, a try-block that finished, or an exception handler ",
" that was invoked.",
" * A T or F indicates a boolean decision that evaluated true or false,",
" respectively.",
" * A t or f indicates a boolean condition within a decision if the ",
" condition evaluated true or false, respectively.",
" * A k indicates a constant decision or condition.",
" * The slash / means this probe is excluded from summary results. ",
0
};
}
int cmCTestCoverageHandler::RunBullseyeCoverageBranch(
cmCTestCoverageHandlerContainer* cont,
std::set<std::string>& coveredFileNames,
std::vector<std::string>& files,
std::set<std::string>& coveredFileNames, std::vector<std::string>& files,
std::vector<std::string>& filesFullPath)
{
if(files.size() != filesFullPath.size())
{
if (files.size() != filesFullPath.size()) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Files and full path files not the same size?:\n");
return 0;
}
}
// create the output stream for the CoverageLog-N.xml file
cmGeneratedFileStream covLogFile;
cmXMLWriter covLogXML(covLogFile);
int logFileCount = 0;
if ( !this->StartCoverageLogFile(covLogFile, logFileCount) )
{
if (!this->StartCoverageLogFile(covLogFile, logFileCount)) {
return -1;
}
}
this->StartCoverageLogXML(covLogXML);
// for each file run covbr on that file to get the coverage
// information for that file
std::string outputFile;
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"run covbr: " << std::endl, this->Quiet);
"run covbr: " << std::endl, this->Quiet);
if(!this->RunBullseyeCommand(cont, "covbr", 0, outputFile))
{
cmCTestLog(this->CTest, ERROR_MESSAGE, "error running covbr for." << "\n");
if (!this->RunBullseyeCommand(cont, "covbr", 0, outputFile)) {
cmCTestLog(this->CTest, ERROR_MESSAGE, "error running covbr for."
<< "\n");
return -1;
}
}
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"covbr output in " << outputFile << std::endl, this->Quiet);
"covbr output in " << outputFile << std::endl,
this->Quiet);
// open the output file
cmsys::ifstream fin(outputFile.c_str());
if(!fin)
{
if (!fin) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Cannot open coverage file: " <<
outputFile << std::endl);
"Cannot open coverage file: " << outputFile << std::endl);
return 0;
}
}
std::map<std::string, std::string> fileMap;
std::vector<std::string>::iterator fp = filesFullPath.begin();
for(std::vector<std::string>::iterator f = files.begin();
f != files.end(); ++f, ++fp)
{
for (std::vector<std::string>::iterator f = files.begin(); f != files.end();
++f, ++fp) {
fileMap[*f] = *fp;
}
}
int count =0; // keep count of the number of files
int count = 0; // keep count of the number of files
// Now parse each line from the bullseye cov log file
std::string lineIn;
bool valid = false; // are we in a valid output file
int line = 0; // line of the current file
int line = 0; // line of the current file
std::string file;
while(cmSystemTools::GetLineFromStream(fin, lineIn))
{
while (cmSystemTools::GetLineFromStream(fin, lineIn)) {
bool startFile = false;
if(lineIn.size() > 1 && lineIn[lineIn.size()-1] == ':')
{
file = lineIn.substr(0, lineIn.size()-1);
if(coveredFileNames.find(file) != coveredFileNames.end())
{
if (lineIn.size() > 1 && lineIn[lineIn.size() - 1] == ':') {
file = lineIn.substr(0, lineIn.size() - 1);
if (coveredFileNames.find(file) != coveredFileNames.end()) {
startFile = true;
}
}
if(startFile)
{
}
if (startFile) {
// if we are in a valid file close it because a new one started
if(valid)
{
if (valid) {
covLogXML.EndElement(); // Report
covLogXML.EndElement(); // File
}
}
// only allow 100 files in each log file
if ( count != 0 && count % 100 == 0 )
{
if (count != 0 && count % 100 == 0) {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"start a new log file: " << count << std::endl, this->Quiet);
"start a new log file: " << count << std::endl,
this->Quiet);
this->EndCoverageLogXML(covLogXML);
this->EndCoverageLogFile(covLogFile, logFileCount);
logFileCount ++;
if ( !this->StartCoverageLogFile(covLogFile, logFileCount) )
{
logFileCount++;
if (!this->StartCoverageLogFile(covLogFile, logFileCount)) {
return -1;
}
}
this->StartCoverageLogXML(covLogXML);
count++; // move on one
}
std::map<std::string, std::string>::iterator
i = fileMap.find(file);
}
std::map<std::string, std::string>::iterator i = fileMap.find(file);
// if the file should be covered write out the header for that file
if(i != fileMap.end())
{
if (i != fileMap.end()) {
// we have a new file so count it in the output
count++;
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Produce coverage for file: " << file << " " << count
<< std::endl, this->Quiet);
"Produce coverage for file: " << file << " "
<< count << std::endl,
this->Quiet);
// start the file output
covLogXML.StartElement("File");
covLogXML.Attribute("Name", i->first);
covLogXML.Attribute("FullPath",
this->CTest->GetShortPathToFile(i->second.c_str()));
covLogXML.Attribute(
"FullPath", this->CTest->GetShortPathToFile(i->second.c_str()));
covLogXML.StartElement("Report");
// write the bullseye header
line =0;
for(int k =0; bullseyeHelp[k] != 0; ++k)
{
line = 0;
for (int k = 0; bullseyeHelp[k] != 0; ++k) {
covLogXML.StartElement("Line");
covLogXML.Attribute("Number", line);
covLogXML.Attribute("Count", -1);
covLogXML.Content(bullseyeHelp[k]);
covLogXML.EndElement(); // Line
line++;
}
valid = true; // we are in a valid file section
}
else
{
valid = true; // we are in a valid file section
} else {
// this is not a file that we want coverage for
valid = false;
}
}
}
// we are not at a start file, and we are in a valid file output the line
else if(valid)
{
else if (valid) {
covLogXML.StartElement("Line");
covLogXML.Attribute("Number", line);
covLogXML.Attribute("Count", -1);
covLogXML.Content(lineIn);
covLogXML.EndElement(); // Line
line++;
}
}
}
// if we ran out of lines a valid file then close that file
if(valid)
{
if (valid) {
covLogXML.EndElement(); // Report
covLogXML.EndElement(); // File
}
}
this->EndCoverageLogXML(covLogXML);
this->EndCoverageLogFile(covLogFile, logFileCount);
return 1;
}
int cmCTestCoverageHandler::RunBullseyeCommand(
cmCTestCoverageHandlerContainer* cont,
const char* cmd,
const char* arg,
cmCTestCoverageHandlerContainer* cont, const char* cmd, const char* arg,
std::string& outputFile)
{
std::string program = cmSystemTools::FindProgram(cmd);
if(program.empty())
{
if (program.empty()) {
cmCTestLog(this->CTest, ERROR_MESSAGE, "Cannot find :" << cmd << "\n");
return 0;
}
if(arg)
{
}
if (arg) {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Run : " << program << " " << arg << "\n", this->Quiet);
}
else
{
"Run : " << program << " " << arg << "\n", this->Quiet);
} else {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Run : " << program << "\n", this->Quiet);
}
"Run : " << program << "\n", this->Quiet);
}
// create a process object and start it
cmCTestRunProcess runCoverageSrc;
runCoverageSrc.SetCommand(program.c_str());
@@ -2172,14 +1954,13 @@ int cmCTestCoverageHandler::RunBullseyeCommand(
stderrFile += ".stderr";
runCoverageSrc.SetStdoutFile(stdoutFile.c_str());
runCoverageSrc.SetStderrFile(stderrFile.c_str());
if(!runCoverageSrc.StartProcess())
{
cmCTestLog(this->CTest, ERROR_MESSAGE, "Could not run : "
<< program << " " << arg << "\n"
<< "kwsys process state : "
<< runCoverageSrc.GetProcessState());
if (!runCoverageSrc.StartProcess()) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Could not run : " << program << " " << arg << "\n"
<< "kwsys process state : "
<< runCoverageSrc.GetProcessState());
return 0;
}
}
// since we set the output file names wait for it to end
runCoverageSrc.WaitForExit();
outputFile = stdoutFile;
@@ -2191,29 +1972,28 @@ int cmCTestCoverageHandler::RunBullseyeSourceSummary(
{
// Run the covsrc command and create a temp outputfile
std::string outputFile;
if(!this->RunBullseyeCommand(cont, "covsrc", "-c", outputFile))
{
if (!this->RunBullseyeCommand(cont, "covsrc", "-c", outputFile)) {
cmCTestLog(this->CTest, ERROR_MESSAGE, "error running covsrc:\n");
return 0;
}
}
std::ostream& tmpLog = *cont->OFS;
// copen the Coverage.xml file in the Testing directory
cmGeneratedFileStream covSumFile;
cmXMLWriter xml(covSumFile);
if(!this->StartResultingXML(cmCTest::PartCoverage, "Coverage", covSumFile))
{
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Cannot open coverage summary file." << std::endl);
if (!this->StartResultingXML(cmCTest::PartCoverage, "Coverage",
covSumFile)) {
cmCTestLog(this->CTest, ERROR_MESSAGE, "Cannot open coverage summary file."
<< std::endl);
return 0;
}
}
this->CTest->StartXML(xml, this->AppendXML);
double elapsed_time_start = cmSystemTools::GetTime();
std::string coverage_start_time = this->CTest->CurrentTime();
xml.StartElement("Coverage");
xml.Element("StartDateTime", coverage_start_time);
xml.Element("StartTime",
static_cast<unsigned int>(cmSystemTools::GetTime()));
static_cast<unsigned int>(cmSystemTools::GetTime()));
std::string stdline;
std::string errline;
// expected output:
@@ -2230,66 +2010,53 @@ int cmCTestCoverageHandler::RunBullseyeSourceSummary(
double total_tested = 0;
double total_untested = 0;
double total_functions = 0;
double percent_coverage =0;
double number_files = 0;
double percent_coverage = 0;
double number_files = 0;
std::vector<std::string> coveredFiles;
std::vector<std::string> coveredFilesFullPath;
// Read and parse the summary output file
cmsys::ifstream fin(outputFile.c_str());
if(!fin)
{
if (!fin) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Cannot open coverage summary file: " <<
outputFile << std::endl);
"Cannot open coverage summary file: " << outputFile
<< std::endl);
return 0;
}
}
std::set<std::string> coveredFileNames;
while(cmSystemTools::GetLineFromStream(fin, stdline))
{
while (cmSystemTools::GetLineFromStream(fin, stdline)) {
// if we have a line of output from stdout
if(!stdline.empty())
{
if (!stdline.empty()) {
// parse the comma separated output
this->ParseBullsEyeCovsrcLine(stdline,
sourceFile,
functionsCalled,
totalFunctions,
percentFunction,
branchCovered,
totalBranches,
percentBranch);
this->ParseBullsEyeCovsrcLine(
stdline, sourceFile, functionsCalled, totalFunctions, percentFunction,
branchCovered, totalBranches, percentBranch);
// The first line is the header
if(sourceFile == "Source" || sourceFile == "Total")
{
if (sourceFile == "Source" || sourceFile == "Total") {
continue;
}
}
std::string file = sourceFile;
coveredFileNames.insert(file);
if(!cmSystemTools::FileIsFullPath(sourceFile.c_str()))
{
if (!cmSystemTools::FileIsFullPath(sourceFile.c_str())) {
// file will be relative to the binary dir
file = cont->BinaryDir;
file += "/";
file += sourceFile;
}
}
file = cmSystemTools::CollapseFullPath(file);
bool shouldIDoCoverage
= this->ShouldIDoCoverage(file.c_str(),
cont->SourceDir.c_str(),
cont->BinaryDir.c_str());
if ( !shouldIDoCoverage )
{
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
".NoDartCoverage found, so skip coverage check for: "
<< file
<< std::endl, this->Quiet);
bool shouldIDoCoverage = this->ShouldIDoCoverage(
file.c_str(), cont->SourceDir.c_str(), cont->BinaryDir.c_str());
if (!shouldIDoCoverage) {
cmCTestOptionalLog(
this->CTest, HANDLER_VERBOSE_OUTPUT,
".NoDartCoverage found, so skip coverage check for: " << file
<< std::endl,
this->Quiet);
continue;
}
}
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Doing coverage for: "
<< file
<< std::endl, this->Quiet);
"Doing coverage for: " << file << std::endl,
this->Quiet);
coveredFiles.push_back(sourceFile);
coveredFilesFullPath.push_back(file);
@@ -2304,21 +2071,19 @@ int cmCTestCoverageHandler::RunBullseyeSourceSummary(
this->CTest->GetShortPathToFile(file.c_str());
float cper = static_cast<float>(percentBranch + percentFunction);
if(totalBranches > 0)
{
if (totalBranches > 0) {
cper /= 2.0f;
}
}
percent_coverage += static_cast<double>(cper);
float cmet = static_cast<float>(percentFunction + percentBranch);
if(totalBranches > 0)
{
if (totalBranches > 0) {
cmet /= 2.0f;
}
}
cmet /= 100.0f;
tmpLog << stdline << "\n";
tmpLog << fileName << "\n";
tmpLog << "functionsCalled: " << functionsCalled/100 << "\n";
tmpLog << "totalFunctions: " << totalFunctions/100 << "\n";
tmpLog << "functionsCalled: " << functionsCalled / 100 << "\n";
tmpLog << "totalFunctions: " << totalFunctions / 100 << "\n";
tmpLog << "percentFunction: " << percentFunction << "\n";
tmpLog << "branchCovered: " << branchCovered << "\n";
tmpLog << "totalBranches: " << totalBranches << "\n";
@@ -2341,8 +2106,8 @@ int cmCTestCoverageHandler::RunBullseyeSourceSummary(
xml.Element("CoverageMetric", cmet);
this->WriteXMLLabels(xml, shortFileName);
xml.EndElement(); // File
}
}
}
std::string end_time = this->CTest->CurrentTime();
xml.Element("LOCTested", total_tested);
xml.Element("LOCUntested", total_untested);
@@ -2350,15 +2115,15 @@ int cmCTestCoverageHandler::RunBullseyeSourceSummary(
xml.Element("PercentCoverage", SAFEDIV(percent_coverage, number_files));
xml.Element("EndDateTime", end_time);
xml.Element("EndTime", static_cast<unsigned int>(cmSystemTools::GetTime()));
xml.Element("ElapsedMinutes",
static_cast<int>((cmSystemTools::GetTime() - elapsed_time_start)/6)/10.0);
xml.Element(
"ElapsedMinutes",
static_cast<int>((cmSystemTools::GetTime() - elapsed_time_start) / 6) /
10.0);
xml.EndElement(); // Coverage
this->CTest->EndXML(xml);
// Now create the coverage information for each file
return this->RunBullseyeCoverageBranch(cont,
coveredFileNames,
coveredFiles,
return this->RunBullseyeCoverageBranch(cont, coveredFileNames, coveredFiles,
coveredFilesFullPath);
}
@@ -2366,25 +2131,24 @@ int cmCTestCoverageHandler::HandleBullseyeCoverage(
cmCTestCoverageHandlerContainer* cont)
{
const char* covfile = cmSystemTools::GetEnv("COVFILE");
if(!covfile || strlen(covfile) == 0)
{
if (!covfile || strlen(covfile) == 0) {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
" COVFILE environment variable not found, not running "
" bullseye\n", this->Quiet);
" COVFILE environment variable not found, not running "
" bullseye\n",
this->Quiet);
return 0;
}
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
" run covsrc with COVFILE=["
<< covfile
<< "]" << std::endl, this->Quiet);
if(!this->RunBullseyeSourceSummary(cont))
{
}
cmCTestOptionalLog(
this->CTest, HANDLER_VERBOSE_OUTPUT,
" run covsrc with COVFILE=[" << covfile << "]" << std::endl, this->Quiet);
if (!this->RunBullseyeSourceSummary(cont)) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Error running bullseye summary.\n");
return 0;
}
cmCTestOptionalLog(this->CTest, DEBUG, "HandleBullseyeCoverage return 1 "
<< std::endl, this->Quiet);
}
cmCTestOptionalLog(this->CTest, DEBUG,
"HandleBullseyeCoverage return 1 " << std::endl,
this->Quiet);
return 1;
}
@@ -2395,79 +2159,63 @@ bool cmCTestCoverageHandler::GetNextInt(std::string const& inputLine,
std::string::size_type start = pos;
pos = inputLine.find(',', start);
value = atoi(inputLine.substr(start, pos).c_str());
if(pos == inputLine.npos)
{
if (pos == inputLine.npos) {
return true;
}
}
pos++;
return true;
}
bool cmCTestCoverageHandler::ParseBullsEyeCovsrcLine(
std::string const& inputLine,
std::string& sourceFile,
int& functionsCalled,
int& totalFunctions,
int& percentFunction,
int& branchCovered,
int& totalBranches,
int& percentBranch)
std::string const& inputLine, std::string& sourceFile, int& functionsCalled,
int& totalFunctions, int& percentFunction, int& branchCovered,
int& totalBranches, int& percentBranch)
{
// find the first comma
std::string::size_type pos = inputLine.find(',');
if(pos == inputLine.npos)
{
cmCTestLog(this->CTest, ERROR_MESSAGE, "Error parsing string : "
<< inputLine << "\n");
if (pos == inputLine.npos) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Error parsing string : " << inputLine << "\n");
return false;
}
}
// the source file has "" around it so extract out the file name
sourceFile = inputLine.substr(1,pos-2);
sourceFile = inputLine.substr(1, pos - 2);
pos++;
if(!this->GetNextInt(inputLine, pos, functionsCalled))
{
if (!this->GetNextInt(inputLine, pos, functionsCalled)) {
return false;
}
if(!this->GetNextInt(inputLine, pos, totalFunctions))
{
}
if (!this->GetNextInt(inputLine, pos, totalFunctions)) {
return false;
}
if(!this->GetNextInt(inputLine, pos, percentFunction))
{
}
if (!this->GetNextInt(inputLine, pos, percentFunction)) {
return false;
}
if(!this->GetNextInt(inputLine, pos, branchCovered))
{
}
if (!this->GetNextInt(inputLine, pos, branchCovered)) {
return false;
}
if(!this->GetNextInt(inputLine, pos, totalBranches))
{
}
if (!this->GetNextInt(inputLine, pos, totalBranches)) {
return false;
}
if(!this->GetNextInt(inputLine, pos, percentBranch))
{
}
if (!this->GetNextInt(inputLine, pos, percentBranch)) {
return false;
}
}
// should be at the end now
if(pos != inputLine.npos)
{
if (pos != inputLine.npos) {
cmCTestLog(this->CTest, ERROR_MESSAGE, "Error parsing input : "
<< inputLine << " last pos not npos = " << pos <<
"\n");
}
<< inputLine << " last pos not npos = " << pos << "\n");
}
return true;
}
int cmCTestCoverageHandler::GetLabelId(std::string const& label)
{
LabelIdMapType::iterator i = this->LabelIdMap.find(label);
if(i == this->LabelIdMap.end())
{
if (i == this->LabelIdMap.end()) {
int n = int(this->Labels.size());
this->Labels.push_back(label);
LabelIdMapType::value_type entry(label, n);
i = this->LabelIdMap.insert(entry).first;
}
}
return i->second;
}
@@ -2477,13 +2225,13 @@ void cmCTestCoverageHandler::LoadLabels()
fileList += cmake::GetCMakeFilesDirectory();
fileList += "/TargetDirectories.txt";
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
" target directory list [" << fileList << "]\n", this->Quiet);
" target directory list [" << fileList << "]\n",
this->Quiet);
cmsys::ifstream finList(fileList.c_str());
std::string line;
while(cmSystemTools::GetLineFromStream(finList, line))
{
while (cmSystemTools::GetLineFromStream(finList, line)) {
this->LoadLabels(line.c_str());
}
}
}
void cmCTestCoverageHandler::LoadLabels(const char* dir)
@@ -2492,41 +2240,31 @@ void cmCTestCoverageHandler::LoadLabels(const char* dir)
std::string fname = dir;
fname += "/Labels.txt";
cmsys::ifstream fin(fname.c_str());
if(!fin)
{
if (!fin) {
return;
}
}
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
" loading labels from [" << fname << "]\n", this->Quiet);
" loading labels from [" << fname << "]\n", this->Quiet);
bool inTarget = true;
std::string source;
std::string line;
std::vector<int> targetLabels;
while(cmSystemTools::GetLineFromStream(fin, line))
{
if(line.empty() || line[0] == '#')
{
while (cmSystemTools::GetLineFromStream(fin, line)) {
if (line.empty() || line[0] == '#') {
// Ignore blank and comment lines.
continue;
}
else if(line[0] == ' ')
{
} else if (line[0] == ' ') {
// Label lines appear indented by one space.
std::string label = line.substr(1);
int id = this->GetLabelId(label);
dirLabels.insert(id);
if(inTarget)
{
if (inTarget) {
targetLabels.push_back(id);
}
else
{
} else {
this->SourceLabels[source].insert(id);
}
}
else
{
} else {
// Non-indented lines specify a source file name. The first one
// is the end of the target-wide labels.
inTarget = false;
@@ -2536,69 +2274,62 @@ void cmCTestCoverageHandler::LoadLabels(const char* dir)
// Label the source with the target labels.
LabelSet& labelSet = this->SourceLabels[source];
labelSet.insert(targetLabels.begin(), targetLabels.end());
}
}
}
}
void cmCTestCoverageHandler::WriteXMLLabels(cmXMLWriter& xml,
std::string const& source)
{
LabelMapType::const_iterator li = this->SourceLabels.find(source);
if(li != this->SourceLabels.end() && !li->second.empty())
{
if (li != this->SourceLabels.end() && !li->second.empty()) {
xml.StartElement("Labels");
for(LabelSet::const_iterator lsi = li->second.begin();
lsi != li->second.end(); ++lsi)
{
for (LabelSet::const_iterator lsi = li->second.begin();
lsi != li->second.end(); ++lsi) {
xml.Element("Label", this->Labels[*lsi]);
}
xml.EndElement(); // Labels
}
xml.EndElement(); // Labels
}
}
void
cmCTestCoverageHandler::SetLabelFilter(std::set<std::string> const& labels)
void cmCTestCoverageHandler::SetLabelFilter(
std::set<std::string> const& labels)
{
this->LabelFilter.clear();
for(std::set<std::string>::const_iterator li = labels.begin();
li != labels.end(); ++li)
{
for (std::set<std::string>::const_iterator li = labels.begin();
li != labels.end(); ++li) {
this->LabelFilter.insert(this->GetLabelId(*li));
}
}
}
bool cmCTestCoverageHandler::IntersectsFilter(LabelSet const& labels)
{
// If there is no label filter then nothing is filtered out.
if(this->LabelFilter.empty())
{
if (this->LabelFilter.empty()) {
return true;
}
}
std::vector<int> ids;
std::set_intersection
(labels.begin(), labels.end(),
this->LabelFilter.begin(), this->LabelFilter.end(),
std::back_inserter(ids));
std::set_intersection(labels.begin(), labels.end(),
this->LabelFilter.begin(), this->LabelFilter.end(),
std::back_inserter(ids));
return !ids.empty();
}
bool cmCTestCoverageHandler::IsFilteredOut(std::string const& source)
{
// If there is no label filter then nothing is filtered out.
if(this->LabelFilter.empty())
{
if (this->LabelFilter.empty()) {
return false;
}
}
// The source is filtered out if it does not have any labels in
// common with the filter set.
std::string shortSrc = this->CTest->GetShortPathToFile(source.c_str());
LabelMapType::const_iterator li = this->SourceLabels.find(shortSrc);
if(li != this->SourceLabels.end())
{
if (li != this->SourceLabels.end()) {
return !this->IntersectsFilter(li->second);
}
}
return true;
}
@@ -2607,36 +2338,31 @@ std::set<std::string> cmCTestCoverageHandler::FindUncoveredFiles(
{
std::set<std::string> extraMatches;
for(std::vector<std::string>::iterator i = this->ExtraCoverageGlobs.begin();
i != this->ExtraCoverageGlobs.end(); ++i)
{
for (std::vector<std::string>::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()));
}
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.empty())
{
for(cmCTestCoverageHandlerContainer::TotalCoverageMap::iterator i =
cont->TotalCoverage.begin(); i != cont->TotalCoverage.end(); ++i)
{
std::string shortPath = this->CTest->GetShortPathToFile(
i->first.c_str());
if (!extraMatches.empty()) {
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;
}
+16 -22
View File
@@ -54,14 +54,14 @@ public:
/**
* This method is called when reading CTest custom file
*/
void PopulateCustomVectors(cmMakefile *mf);
void PopulateCustomVectors(cmMakefile* mf);
/** Report coverage only for sources with these labels. */
void SetLabelFilter(std::set<std::string> const& labels);
private:
bool ShouldIDoCoverage(const char* file, const char* srcDir,
const char* binDir);
const char* binDir);
void CleanCoverageLogFiles(std::ostream& log);
bool StartCoverageLogFile(cmGeneratedFileStream& ostr, int logFileCount);
void EndCoverageLogFile(cmGeneratedFileStream& ostr, int logFileCount);
@@ -95,7 +95,7 @@ private:
//! Handle coverage for Jacoco
int HandleBlanketJSCoverage(cmCTestCoverageHandlerContainer* cont);
//! Handle coverage using Bullseye
//! Handle coverage using Bullseye
int HandleBullseyeCoverage(cmCTestCoverageHandlerContainer* cont);
int RunBullseyeSourceSummary(cmCTestCoverageHandlerContainer* cont);
int RunBullseyeCoverageBranch(cmCTestCoverageHandlerContainer* cont,
@@ -103,22 +103,15 @@ private:
std::vector<std::string>& files,
std::vector<std::string>& filesFullPath);
int RunBullseyeCommand(
cmCTestCoverageHandlerContainer* cont,
const char* cmd,
const char* arg,
std::string& outputFile);
bool ParseBullsEyeCovsrcLine(
std::string const& inputLine,
std::string& sourceFile,
int& functionsCalled,
int& totalFunctions,
int& percentFunction,
int& branchCovered,
int& totalBranches,
int& percentBranch);
bool GetNextInt(std::string const& inputLine,
std::string::size_type& pos,
int RunBullseyeCommand(cmCTestCoverageHandlerContainer* cont,
const char* cmd, const char* arg,
std::string& outputFile);
bool ParseBullsEyeCovsrcLine(std::string const& inputLine,
std::string& sourceFile, int& functionsCalled,
int& totalFunctions, int& percentFunction,
int& branchCovered, int& totalBranches,
int& percentBranch);
bool GetNextInt(std::string const& inputLine, std::string::size_type& pos,
int& value);
//! Handle Python coverage using Python's Trace.py
int HandleTracePyCoverage(cmCTestCoverageHandlerContainer* cont);
@@ -126,7 +119,7 @@ private:
// Find the source file based on the source and build tree. This is used for
// Trace.py mode, since that one does not tell us where the source file is.
std::string FindFile(cmCTestCoverageHandlerContainer* cont,
std::string fileName);
std::string fileName);
std::set<std::string> FindUncoveredFiles(
cmCTestCoverageHandlerContainer* cont);
@@ -134,9 +127,10 @@ private:
std::vector<cmsys::RegularExpression> CustomCoverageExcludeRegex;
std::vector<std::string> ExtraCoverageGlobs;
// Map from source file to label ids.
class LabelSet: public std::set<int> {};
class LabelSet : public std::set<int>
{
};
typedef std::map<std::string, LabelSet> LabelMapType;
LabelMapType SourceLabels;
LabelMapType TargetDirs;
+75 -114
View File
@@ -42,115 +42,95 @@ std::string cmCTestCurl::Escape(std::string const& source)
return ret;
}
namespace
{
static size_t
curlWriteMemoryCallback(void *ptr, size_t size, size_t nmemb,
void *data)
namespace {
static size_t curlWriteMemoryCallback(void* ptr, size_t size, size_t nmemb,
void* data)
{
int realsize = (int)(size * nmemb);
std::vector<char> *vec
= static_cast<std::vector<char>* >(data);
std::vector<char>* vec = static_cast<std::vector<char>*>(data);
const char* chPtr = static_cast<char*>(ptr);
vec->insert(vec->end(), chPtr, chPtr + realsize);
return realsize;
}
static size_t
curlDebugCallback(CURL *, curl_infotype, char *chPtr,
size_t size, void *data)
static size_t curlDebugCallback(CURL*, curl_infotype, char* chPtr, size_t size,
void* data)
{
std::vector<char> *vec
= static_cast<std::vector<char>* >(data);
std::vector<char>* vec = static_cast<std::vector<char>*>(data);
vec->insert(vec->end(), chPtr, chPtr + size);
return size;
}
}
void cmCTestCurl::SetCurlOptions(std::vector<std::string> const& args)
{
for( std::vector<std::string>::const_iterator i = args.begin();
i != args.end(); ++i)
{
if(*i == "CURLOPT_SSL_VERIFYPEER_OFF")
{
for (std::vector<std::string>::const_iterator i = args.begin();
i != args.end(); ++i) {
if (*i == "CURLOPT_SSL_VERIFYPEER_OFF") {
this->VerifyPeerOff = true;
}
if(*i == "CURLOPT_SSL_VERIFYHOST_OFF")
{
this->VerifyHostOff = true;
}
}
if (*i == "CURLOPT_SSL_VERIFYHOST_OFF") {
this->VerifyHostOff = true;
}
}
}
bool cmCTestCurl::InitCurl()
{
if(!this->Curl)
{
if (!this->Curl) {
return false;
}
if(this->VerifyPeerOff)
{
}
if (this->VerifyPeerOff) {
curl_easy_setopt(this->Curl, CURLOPT_SSL_VERIFYPEER, 0);
}
if(this->VerifyHostOff)
{
}
if (this->VerifyHostOff) {
curl_easy_setopt(this->Curl, CURLOPT_SSL_VERIFYHOST, 0);
}
if(this->HTTPProxy.size())
{
}
if (this->HTTPProxy.size()) {
curl_easy_setopt(this->Curl, CURLOPT_PROXY, this->HTTPProxy.c_str());
curl_easy_setopt(this->Curl, CURLOPT_PROXYTYPE, this->HTTPProxyType);
if (this->HTTPProxyAuth.size() > 0)
{
if (this->HTTPProxyAuth.size() > 0) {
curl_easy_setopt(this->Curl, CURLOPT_PROXYUSERPWD,
this->HTTPProxyAuth.c_str());
}
}
if(this->UseHttp10)
{
}
if (this->UseHttp10) {
curl_easy_setopt(this->Curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
}
}
// enable HTTP ERROR parsing
curl_easy_setopt(this->Curl, CURLOPT_FAILONERROR, 1);
return true;
}
bool cmCTestCurl::UploadFile(std::string const& local_file,
std::string const& url,
std::string const& fields,
std::string const& url, std::string const& fields,
std::string& response)
{
response = "";
if(!this->InitCurl())
{
if (!this->InitCurl()) {
cmCTestLog(this->CTest, ERROR_MESSAGE, "Initialization of curl failed");
return false;
}
}
/* enable uploading */
curl_easy_setopt(this->Curl, CURLOPT_UPLOAD, 1);
// if there is little to no activity for too long stop submitting
if(this->TimeOutSeconds)
{
if (this->TimeOutSeconds) {
::curl_easy_setopt(this->Curl, CURLOPT_LOW_SPEED_LIMIT, 1);
::curl_easy_setopt(this->Curl, CURLOPT_LOW_SPEED_TIME,
this->TimeOutSeconds);
}
}
/* HTTP PUT please */
::curl_easy_setopt(this->Curl, CURLOPT_PUT, 1);
::curl_easy_setopt(this->Curl, CURLOPT_VERBOSE, 1);
FILE* ftpfile = cmsys::SystemTools::Fopen(local_file, "rb");
if(!ftpfile)
{
if (!ftpfile) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Could not open file for upload: " << local_file << "\n");
return false;
}
}
// set the url
std::string upload_url = url;
upload_url += "?";
@@ -164,16 +144,15 @@ bool cmCTestCurl::UploadFile(std::string const& local_file,
static_cast<long>(filelen));
::curl_easy_setopt(this->Curl, CURLOPT_WRITEFUNCTION,
curlWriteMemoryCallback);
::curl_easy_setopt(this->Curl, CURLOPT_DEBUGFUNCTION,
curlDebugCallback);
::curl_easy_setopt(this->Curl, CURLOPT_DEBUGFUNCTION, curlDebugCallback);
// Be sure to set Content-Type to satisfy fussy modsecurity rules
struct curl_slist *headers = ::curl_slist_append(NULL,
"Content-Type: text/xml");
struct curl_slist* headers =
::curl_slist_append(NULL, "Content-Type: text/xml");
::curl_easy_setopt(this->Curl, CURLOPT_HTTPHEADER, headers);
std::vector<char> responseData;
std::vector<char> debugData;
::curl_easy_setopt(this->Curl, CURLOPT_FILE, (void *)&responseData);
::curl_easy_setopt(this->Curl, CURLOPT_DEBUGDATA, (void *)&debugData);
::curl_easy_setopt(this->Curl, CURLOPT_FILE, (void*)&responseData);
::curl_easy_setopt(this->Curl, CURLOPT_DEBUGDATA, (void*)&debugData);
::curl_easy_setopt(this->Curl, CURLOPT_FAILONERROR, 1);
// Now run off and do what you've been told!
::curl_easy_perform(this->Curl);
@@ -181,108 +160,90 @@ bool cmCTestCurl::UploadFile(std::string const& local_file,
::curl_easy_setopt(this->Curl, CURLOPT_HTTPHEADER, NULL);
::curl_slist_free_all(headers);
if ( responseData.size() > 0 )
{
if (responseData.size() > 0) {
response = std::string(responseData.begin(), responseData.end());
cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Curl response: [" << response << "]\n");
}
cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Curl response: ["
<< response << "]\n");
}
std::string curlDebug;
if ( debugData.size() > 0 )
{
if (debugData.size() > 0) {
curlDebug = std::string(debugData.begin(), debugData.end());
cmCTestLog(this->CTest, DEBUG, "Curl debug: [" << curlDebug << "]\n");
}
if(response.size() == 0)
{
cmCTestLog(this->CTest, ERROR_MESSAGE, "No response from server.\n" <<
curlDebug);
}
if (response.size() == 0) {
cmCTestLog(this->CTest, ERROR_MESSAGE, "No response from server.\n"
<< curlDebug);
return false;
}
}
return true;
}
bool cmCTestCurl::HttpRequest(std::string const& url,
std::string const& fields,
std::string& response)
std::string const& fields, std::string& response)
{
response = "";
cmCTestLog(this->CTest, DEBUG, "HttpRequest\n"
<< "url: " << url << "\n"
<< "fields " << fields << "\n");
if(!this->InitCurl())
{
<< "url: " << url << "\n"
<< "fields " << fields << "\n");
if (!this->InitCurl()) {
cmCTestLog(this->CTest, ERROR_MESSAGE, "Initialization of curl failed");
return false;
}
}
curl_easy_setopt(this->Curl, CURLOPT_POST, 1);
curl_easy_setopt(this->Curl, CURLOPT_POSTFIELDS, fields.c_str());
::curl_easy_setopt(this->Curl, CURLOPT_URL, url.c_str());
::curl_easy_setopt(this->Curl, CURLOPT_FOLLOWLOCATION, 1);
//set response options
// set response options
::curl_easy_setopt(this->Curl, CURLOPT_WRITEFUNCTION,
curlWriteMemoryCallback);
::curl_easy_setopt(this->Curl, CURLOPT_DEBUGFUNCTION,
curlDebugCallback);
::curl_easy_setopt(this->Curl, CURLOPT_DEBUGFUNCTION, curlDebugCallback);
std::vector<char> responseData;
std::vector<char> debugData;
::curl_easy_setopt(this->Curl, CURLOPT_FILE, (void *)&responseData);
::curl_easy_setopt(this->Curl, CURLOPT_DEBUGDATA, (void *)&debugData);
::curl_easy_setopt(this->Curl, CURLOPT_FILE, (void*)&responseData);
::curl_easy_setopt(this->Curl, CURLOPT_DEBUGDATA, (void*)&debugData);
::curl_easy_setopt(this->Curl, CURLOPT_FAILONERROR, 1);
CURLcode res = ::curl_easy_perform(this->Curl);
if ( responseData.size() > 0 )
{
if (responseData.size() > 0) {
response = std::string(responseData.begin(), responseData.end());
cmCTestLog(this->CTest, DEBUG, "Curl response: [" << response << "]\n");
}
if ( debugData.size() > 0 )
{
}
if (debugData.size() > 0) {
std::string curlDebug = std::string(debugData.begin(), debugData.end());
cmCTestLog(this->CTest, DEBUG, "Curl debug: [" << curlDebug << "]\n");
}
}
cmCTestLog(this->CTest, DEBUG, "Curl res: " << res << "\n");
return (res == 0);
}
void cmCTestCurl::SetProxyType()
{
if ( cmSystemTools::GetEnv("HTTP_PROXY") )
{
if (cmSystemTools::GetEnv("HTTP_PROXY")) {
this->HTTPProxy = cmSystemTools::GetEnv("HTTP_PROXY");
if ( cmSystemTools::GetEnv("HTTP_PROXY_PORT") )
{
if (cmSystemTools::GetEnv("HTTP_PROXY_PORT")) {
this->HTTPProxy += ":";
this->HTTPProxy += cmSystemTools::GetEnv("HTTP_PROXY_PORT");
}
if ( cmSystemTools::GetEnv("HTTP_PROXY_TYPE") )
{
}
if (cmSystemTools::GetEnv("HTTP_PROXY_TYPE")) {
// this is the default
this->HTTPProxyType = CURLPROXY_HTTP;
std::string type = cmSystemTools::GetEnv("HTTP_PROXY_TYPE");
// HTTP/SOCKS4/SOCKS5
if ( type == "HTTP" )
{
if (type == "HTTP") {
this->HTTPProxyType = CURLPROXY_HTTP;
}
else if ( type == "SOCKS4" )
{
} else if (type == "SOCKS4") {
this->HTTPProxyType = CURLPROXY_SOCKS4;
}
else if ( type == "SOCKS5" )
{
} else if (type == "SOCKS5") {
this->HTTPProxyType = CURLPROXY_SOCKS5;
}
}
if ( cmSystemTools::GetEnv("HTTP_PROXY_USER") )
{
this->HTTPProxyAuth = cmSystemTools::GetEnv("HTTP_PROXY_USER");
}
if ( cmSystemTools::GetEnv("HTTP_PROXY_PASSWD") )
{
this->HTTPProxyAuth += ":";
this->HTTPProxyAuth += cmSystemTools::GetEnv("HTTP_PROXY_PASSWD");
}
}
if (cmSystemTools::GetEnv("HTTP_PROXY_USER")) {
this->HTTPProxyAuth = cmSystemTools::GetEnv("HTTP_PROXY_USER");
}
if (cmSystemTools::GetEnv("HTTP_PROXY_PASSWD")) {
this->HTTPProxyAuth += ":";
this->HTTPProxyAuth += cmSystemTools::GetEnv("HTTP_PROXY_PASSWD");
}
}
}
+7 -8
View File
@@ -23,22 +23,21 @@ class cmCTestCurl
public:
cmCTestCurl(cmCTest*);
~cmCTestCurl();
bool UploadFile(std::string const& url,
std::string const& file,
std::string const& fields,
std::string& response);
bool HttpRequest(std::string const& url,
std::string const& fields,
bool UploadFile(std::string const& url, std::string const& file,
std::string const& fields, std::string& response);
bool HttpRequest(std::string const& url, std::string const& fields,
std::string& response);
// currently only supports CURLOPT_SSL_VERIFYPEER_OFF
// and CURLOPT_SSL_VERIFYHOST_OFF
void SetCurlOptions(std::vector<std::string> const& args);
void SetUseHttp10On() { this->UseHttp10 = true;}
void SetTimeOutSeconds(int s) { this->TimeOutSeconds = s;}
void SetUseHttp10On() { this->UseHttp10 = true; }
void SetTimeOutSeconds(int s) { this->TimeOutSeconds = s; }
std::string Escape(std::string const& source);
protected:
void SetProxyType();
bool InitCurl();
private:
cmCTest* CTest;
CURL* Curl;
@@ -13,24 +13,20 @@
#include "cmCTestScriptHandler.h"
bool cmCTestEmptyBinaryDirectoryCommand
::InitialPass(std::vector<std::string> const& args, cmExecutionStatus &)
bool cmCTestEmptyBinaryDirectoryCommand::InitialPass(
std::vector<std::string> const& args, cmExecutionStatus&)
{
if(args.size() != 1 )
{
if (args.size() != 1) {
this->SetError("called with incorrect number of arguments");
return false;
}
}
if ( !cmCTestScriptHandler::EmptyBinaryDirectory(args[0].c_str()) )
{
if (!cmCTestScriptHandler::EmptyBinaryDirectory(args[0].c_str())) {
std::ostringstream ostr;
ostr << "problem removing the binary directory: " << args[0];
this->SetError(ostr.str());
return false;
}
}
return true;
}
@@ -23,36 +23,36 @@
class cmCTestEmptyBinaryDirectoryCommand : public cmCTestCommand
{
public:
cmCTestEmptyBinaryDirectoryCommand() {}
/**
* This is a virtual constructor for the command.
*/
virtual cmCommand* Clone()
{
cmCTestEmptyBinaryDirectoryCommand* ni
= new cmCTestEmptyBinaryDirectoryCommand;
{
cmCTestEmptyBinaryDirectoryCommand* ni =
new cmCTestEmptyBinaryDirectoryCommand;
ni->CTest = this->CTest;
ni->CTestScriptHandler = this->CTestScriptHandler;
return ni;
}
}
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
virtual bool InitialPass(std::vector<std::string> const& args,
cmExecutionStatus &status);
cmExecutionStatus& status);
/**
* The name of the command as specified in CMakeList.txt.
*/
virtual std::string GetName() const { return "ctest_empty_binary_directory";}
virtual std::string GetName() const
{
return "ctest_empty_binary_directory";
}
cmTypeMacro(cmCTestEmptyBinaryDirectoryCommand, cmCTestCommand);
};
#endif
Loaded 100 of 1450 files, more files were not shown because too many files have changed in this diff. Show more