1 /*============================================================================
2 CMake - Cross Platform Makefile Generator
3 Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
5 Distributed under the OSI-approved BSD License (the "License");
6 see accompanying file Copyright.txt for details.
8 This software is distributed WITHOUT ANY WARRANTY; without even the
9 implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10 See the License for more information.
11 ============================================================================*/
12 #include "cmFileCommand.h"
13 #include "cmCryptoHash.h"
15 #include "cmHexFileConverter.h"
16 #include "cmInstallType.h"
17 #include "cmFileTimeComparison.h"
18 #include "cmCryptoHash.h"
20 #include "cmTimestamp.h"
22 #if defined(CMAKE_BUILD_WITH_CMAKE)
26 #undef GetCurrentDirectory
28 #include <sys/types.h>
31 #include <cmsys/auto_ptr.hxx>
32 #include <cmsys/Directory.hxx>
33 #include <cmsys/Glob.hxx>
34 #include <cmsys/RegularExpression.hxx>
36 // Table of permissions flags.
37 #if defined(_WIN32) && !defined(__CYGWIN__)
38 static mode_t mode_owner_read = S_IREAD;
39 static mode_t mode_owner_write = S_IWRITE;
40 static mode_t mode_owner_execute = S_IEXEC;
41 static mode_t mode_group_read = 0;
42 static mode_t mode_group_write = 0;
43 static mode_t mode_group_execute = 0;
44 static mode_t mode_world_read = 0;
45 static mode_t mode_world_write = 0;
46 static mode_t mode_world_execute = 0;
47 static mode_t mode_setuid = 0;
48 static mode_t mode_setgid = 0;
50 static mode_t mode_owner_read = S_IRUSR;
51 static mode_t mode_owner_write = S_IWUSR;
52 static mode_t mode_owner_execute = S_IXUSR;
53 static mode_t mode_group_read = S_IRGRP;
54 static mode_t mode_group_write = S_IWGRP;
55 static mode_t mode_group_execute = S_IXGRP;
56 static mode_t mode_world_read = S_IROTH;
57 static mode_t mode_world_write = S_IWOTH;
58 static mode_t mode_world_execute = S_IXOTH;
59 static mode_t mode_setuid = S_ISUID;
60 static mode_t mode_setgid = S_ISGID;
65 ::InitialPass(std::vector<std::string> const& args, cmExecutionStatus &)
69 this->SetError("must be called with at least two arguments.");
72 std::string subCommand = args[0];
73 if ( subCommand == "WRITE" )
75 return this->HandleWriteCommand(args, false);
77 else if ( subCommand == "APPEND" )
79 return this->HandleWriteCommand(args, true);
81 else if ( subCommand == "DOWNLOAD" )
83 return this->HandleDownloadCommand(args);
85 else if ( subCommand == "UPLOAD" )
87 return this->HandleUploadCommand(args);
89 else if ( subCommand == "READ" )
91 return this->HandleReadCommand(args);
93 else if ( subCommand == "MD5" ||
94 subCommand == "SHA1" ||
95 subCommand == "SHA224" ||
96 subCommand == "SHA256" ||
97 subCommand == "SHA384" ||
98 subCommand == "SHA512" )
100 return this->HandleHashCommand(args);
102 else if ( subCommand == "STRINGS" )
104 return this->HandleStringsCommand(args);
106 else if ( subCommand == "GLOB" )
108 return this->HandleGlobCommand(args, false);
110 else if ( subCommand == "GLOB_RECURSE" )
112 return this->HandleGlobCommand(args, true);
114 else if ( subCommand == "MAKE_DIRECTORY" )
116 return this->HandleMakeDirectoryCommand(args);
118 else if ( subCommand == "RENAME" )
120 return this->HandleRename(args);
122 else if ( subCommand == "REMOVE" )
124 return this->HandleRemove(args, false);
126 else if ( subCommand == "REMOVE_RECURSE" )
128 return this->HandleRemove(args, true);
130 else if ( subCommand == "COPY" )
132 return this->HandleCopyCommand(args);
134 else if ( subCommand == "INSTALL" )
136 return this->HandleInstallCommand(args);
138 else if ( subCommand == "DIFFERENT" )
140 return this->HandleDifferentCommand(args);
142 else if ( subCommand == "RPATH_CHANGE" || subCommand == "CHRPATH" )
144 return this->HandleRPathChangeCommand(args);
146 else if ( subCommand == "RPATH_CHECK" )
148 return this->HandleRPathCheckCommand(args);
150 else if ( subCommand == "RPATH_REMOVE" )
152 return this->HandleRPathRemoveCommand(args);
154 else if ( subCommand == "RELATIVE_PATH" )
156 return this->HandleRelativePathCommand(args);
158 else if ( subCommand == "TO_CMAKE_PATH" )
160 return this->HandleCMakePathCommand(args, false);
162 else if ( subCommand == "TO_NATIVE_PATH" )
164 return this->HandleCMakePathCommand(args, true);
166 else if ( subCommand == "TIMESTAMP" )
168 return this->HandleTimestampCommand(args);
170 else if ( subCommand == "GENERATE" )
172 return this->HandleGenerateCommand(args);
175 std::string e = "does not recognize sub-command "+subCommand;
176 this->SetError(e.c_str());
180 //----------------------------------------------------------------------------
181 bool cmFileCommand::HandleWriteCommand(std::vector<std::string> const& args,
185 std::vector<std::string>::const_iterator i = args.begin();
187 i++; // Get rid of subcommand
189 std::string fileName = *i;
190 if ( !cmsys::SystemTools::FileIsFullPath(i->c_str()) )
192 fileName = this->Makefile->GetCurrentDirectory();
193 fileName += "/" + *i;
198 for(;i != args.end(); ++i)
202 if ( !this->Makefile->CanIWriteThisFile(fileName.c_str()) )
205 = "attempted to write a file: " + fileName +
206 " into a source directory.";
207 this->SetError(e.c_str());
208 cmSystemTools::SetFatalErrorOccured();
211 std::string dir = cmSystemTools::GetFilenamePath(fileName);
212 cmSystemTools::MakeDirectory(dir.c_str());
216 // Set permissions to writable
217 if ( cmSystemTools::GetPermissions(fileName.c_str(), mode) )
219 cmSystemTools::SetPermissions(fileName.c_str(),
220 #if defined( _MSC_VER ) || defined( __MINGW32__ )
222 #elif defined( __BORLANDC__ )
225 mode | S_IWUSR | S_IWGRP
229 // If GetPermissions fails, pretend like it is ok. File open will fail if
230 // the file is not writable
231 std::ofstream file(fileName.c_str(), append?std::ios::app: std::ios::out);
234 std::string error = "Internal CMake error when trying to open file: ";
235 error += fileName.c_str();
236 error += " for writing.";
237 this->SetError(error.c_str());
244 cmSystemTools::SetPermissions(fileName.c_str(), mode);
249 //----------------------------------------------------------------------------
250 bool cmFileCommand::HandleReadCommand(std::vector<std::string> const& args)
252 if ( args.size() < 3 )
254 this->SetError("READ must be called with at least two additional "
259 cmCommandArgumentsHelper argHelper;
260 cmCommandArgumentGroup group;
262 cmCAString readArg (&argHelper, "READ");
263 cmCAString fileNameArg (&argHelper, 0);
264 cmCAString resultArg (&argHelper, 0);
266 cmCAString offsetArg (&argHelper, "OFFSET", &group);
267 cmCAString limitArg (&argHelper, "LIMIT", &group);
268 cmCAEnabler hexOutputArg (&argHelper, "HEX", &group);
270 fileNameArg.Follows(&readArg);
271 resultArg.Follows(&fileNameArg);
272 group.Follows(&resultArg);
273 argHelper.Parse(&args, 0);
275 std::string fileName = fileNameArg.GetString();
276 if ( !cmsys::SystemTools::FileIsFullPath(fileName.c_str()) )
278 fileName = this->Makefile->GetCurrentDirectory();
279 fileName += "/" + fileNameArg.GetString();
282 std::string variable = resultArg.GetString();
284 // Open the specified file.
285 #if defined(_WIN32) || defined(__CYGWIN__)
286 std::ifstream file(fileName.c_str(), std::ios::in |
287 (hexOutputArg.IsEnabled() ? std::ios::binary : std::ios::in));
289 std::ifstream file(fileName.c_str(), std::ios::in);
294 std::string error = "Internal CMake error when trying to open file: ";
295 error += fileName.c_str();
296 error += " for reading.";
297 this->SetError(error.c_str());
303 if (limitArg.GetString().size() > 0)
305 sizeLimit = atoi(limitArg.GetCString());
308 // is there an offset?
310 if (offsetArg.GetString().size() > 0)
312 offset = atoi(offsetArg.GetCString());
315 file.seekg(offset, std::ios::beg); // explicit ios::beg for IBM VisualAge 6
319 if (hexOutputArg.IsEnabled())
321 // Convert part of the file into hex code
323 while((sizeLimit != 0) && (file.get(c)))
326 sprintf(hex, "%.2x", c&0xff);
337 bool has_newline = false;
338 while (sizeLimit != 0 &&
339 cmSystemTools::GetLineFromStream(file, line, &has_newline,
344 sizeLimit = sizeLimit - static_cast<long>(line.size());
361 this->Makefile->AddDefinition(variable.c_str(), output.c_str());
365 //----------------------------------------------------------------------------
366 bool cmFileCommand::HandleHashCommand(std::vector<std::string> const& args)
368 #if defined(CMAKE_BUILD_WITH_CMAKE)
372 e << args[0] << " requires a file name and output variable";
373 this->SetError(e.str().c_str());
377 cmsys::auto_ptr<cmCryptoHash> hash(cmCryptoHash::New(args[0].c_str()));
380 std::string out = hash->HashFile(args[1].c_str());
383 this->Makefile->AddDefinition(args[2].c_str(), out.c_str());
387 e << args[0] << " failed to read file \"" << args[1] << "\": "
388 << cmSystemTools::GetLastSystemError();
389 this->SetError(e.str().c_str());
394 e << args[0] << " not available during bootstrap";
395 this->SetError(e.str().c_str());
400 //----------------------------------------------------------------------------
401 bool cmFileCommand::HandleStringsCommand(std::vector<std::string> const& args)
405 this->SetError("STRINGS requires a file name and output variable");
409 // Get the file to read.
410 std::string fileName = args[1];
411 if(!cmsys::SystemTools::FileIsFullPath(fileName.c_str()))
413 fileName = this->Makefile->GetCurrentDirectory();
414 fileName += "/" + args[1];
417 // Get the variable in which to store the results.
418 std::string outVar = args[2];
420 // Parse the options.
429 unsigned int minlen = 0;
430 unsigned int maxlen = 0;
431 int limit_input = -1;
432 int limit_output = -1;
433 unsigned int limit_count = 0;
434 cmsys::RegularExpression regex;
435 bool have_regex = false;
436 bool newline_consume = false;
437 bool hex_conversion_enabled = true;
438 int arg_mode = arg_none;
439 for(unsigned int i=3; i < args.size(); ++i)
441 if(args[i] == "LIMIT_INPUT")
443 arg_mode = arg_limit_input;
445 else if(args[i] == "LIMIT_OUTPUT")
447 arg_mode = arg_limit_output;
449 else if(args[i] == "LIMIT_COUNT")
451 arg_mode = arg_limit_count;
453 else if(args[i] == "LENGTH_MINIMUM")
455 arg_mode = arg_length_minimum;
457 else if(args[i] == "LENGTH_MAXIMUM")
459 arg_mode = arg_length_maximum;
461 else if(args[i] == "REGEX")
463 arg_mode = arg_regex;
465 else if(args[i] == "NEWLINE_CONSUME")
467 newline_consume = true;
470 else if(args[i] == "NO_HEX_CONVERSION")
472 hex_conversion_enabled = false;
475 else if(arg_mode == arg_limit_input)
477 if(sscanf(args[i].c_str(), "%d", &limit_input) != 1 ||
481 e << "STRINGS option LIMIT_INPUT value \""
482 << args[i] << "\" is not an unsigned integer.";
483 this->SetError(e.str().c_str());
488 else if(arg_mode == arg_limit_output)
490 if(sscanf(args[i].c_str(), "%d", &limit_output) != 1 ||
494 e << "STRINGS option LIMIT_OUTPUT value \""
495 << args[i] << "\" is not an unsigned integer.";
496 this->SetError(e.str().c_str());
501 else if(arg_mode == arg_limit_count)
504 if(sscanf(args[i].c_str(), "%d", &count) != 1 || count < 0)
507 e << "STRINGS option LIMIT_COUNT value \""
508 << args[i] << "\" is not an unsigned integer.";
509 this->SetError(e.str().c_str());
515 else if(arg_mode == arg_length_minimum)
518 if(sscanf(args[i].c_str(), "%d", &len) != 1 || len < 0)
521 e << "STRINGS option LENGTH_MINIMUM value \""
522 << args[i] << "\" is not an unsigned integer.";
523 this->SetError(e.str().c_str());
529 else if(arg_mode == arg_length_maximum)
532 if(sscanf(args[i].c_str(), "%d", &len) != 1 || len < 0)
535 e << "STRINGS option LENGTH_MAXIMUM value \""
536 << args[i] << "\" is not an unsigned integer.";
537 this->SetError(e.str().c_str());
543 else if(arg_mode == arg_regex)
545 if(!regex.compile(args[i].c_str()))
548 e << "STRINGS option REGEX value \""
549 << args[i] << "\" could not be compiled.";
550 this->SetError(e.str().c_str());
559 e << "STRINGS given unknown argument \""
561 this->SetError(e.str().c_str());
566 if (hex_conversion_enabled)
568 // TODO: should work without temp file, but just on a memory buffer
569 std::string binaryFileName = this->Makefile->GetCurrentOutputDirectory();
570 binaryFileName += cmake::GetCMakeFilesDirectory();
571 binaryFileName += "/FileCommandStringsBinaryFile";
572 if(cmHexFileConverter::TryConvert(fileName.c_str(),binaryFileName.c_str()))
574 fileName = binaryFileName;
578 // Open the specified file.
579 #if defined(_WIN32) || defined(__CYGWIN__)
580 std::ifstream fin(fileName.c_str(), std::ios::in | std::ios::binary);
582 std::ifstream fin(fileName.c_str(), std::ios::in);
587 e << "STRINGS file \"" << fileName << "\" cannot be read.";
588 this->SetError(e.str().c_str());
592 // Parse strings out of the file.
594 std::vector<std::string> strings;
597 while((!limit_count || strings.size() < limit_count) &&
598 (limit_input < 0 || static_cast<int>(fin.tellg()) < limit_input) &&
599 (c = fin.get(), fin))
601 if(c == '\n' && !newline_consume)
603 // The current line has been terminated. Check if the current
604 // string matches the requirements. The length may now be as
605 // low as zero since blank lines are allowed.
606 if(s.length() >= minlen &&
607 (!have_regex || regex.find(s.c_str())))
609 output_size += static_cast<int>(s.size()) + 1;
610 if(limit_output >= 0 && output_size >= limit_output)
615 strings.push_back(s);
618 // Reset the string to empty.
623 // Ignore CR character to make output always have UNIX newlines.
625 else if((c >= 0x20 && c < 0x7F) || c == '\t' ||
626 (c == '\n' && newline_consume))
628 // This is an ASCII character that may be part of a string.
629 // Cast added to avoid compiler warning. Cast is ok because
630 // c is guaranteed to fit in char by the above if...
631 s += static_cast<char>(c);
635 // TODO: Support ENCODING option. See issue #10519.
636 // A non-string character has been found. Check if the current
637 // string matches the requirements. We require that the length
638 // be at least one no matter what the user specified.
639 if(s.length() >= minlen && s.length() >= 1 &&
640 (!have_regex || regex.find(s.c_str())))
642 output_size += static_cast<int>(s.size()) + 1;
643 if(limit_output >= 0 && output_size >= limit_output)
648 strings.push_back(s);
651 // Reset the string to empty.
655 // Terminate a string if the maximum length is reached.
656 if(maxlen > 0 && s.size() == maxlen)
658 if(s.length() >= minlen &&
659 (!have_regex || regex.find(s.c_str())))
661 output_size += static_cast<int>(s.size()) + 1;
662 if(limit_output >= 0 && output_size >= limit_output)
667 strings.push_back(s);
673 // If there is a non-empty current string we have hit the end of the
674 // input file or the input size limit. Check if the current string
675 // matches the requirements.
676 if((!limit_count || strings.size() < limit_count) &&
677 !s.empty() && s.length() >= minlen &&
678 (!have_regex || regex.find(s.c_str())))
680 output_size += static_cast<int>(s.size()) + 1;
681 if(limit_output < 0 || output_size < limit_output)
683 strings.push_back(s);
687 // Encode the result in a CMake list.
688 const char* sep = "";
690 for(std::vector<std::string>::const_iterator si = strings.begin();
691 si != strings.end(); ++si)
693 // Separate the strings in the output to make it a list.
697 // Store the string in the output, but escape semicolons to
698 // make sure it is a list.
699 std::string const& sr = *si;
700 for(unsigned int i=0; i < sr.size(); ++i)
710 // Save the output in a makefile variable.
711 this->Makefile->AddDefinition(outVar.c_str(), output.c_str());
715 //----------------------------------------------------------------------------
716 bool cmFileCommand::HandleGlobCommand(std::vector<std::string> const& args,
719 // File commands has at least one argument
720 assert(args.size() > 1);
722 std::vector<std::string>::const_iterator i = args.begin();
724 i++; // Get rid of subcommand
726 std::string variable = *i;
729 g.SetRecurse(recurse);
731 bool explicitFollowSymlinks = false;
732 cmPolicies::PolicyStatus status =
733 this->Makefile->GetPolicyStatus(cmPolicies::CMP0009);
738 case cmPolicies::NEW:
739 g.RecurseThroughSymlinksOff();
741 case cmPolicies::OLD:
742 case cmPolicies::WARN:
743 case cmPolicies::REQUIRED_IF_USED:
744 case cmPolicies::REQUIRED_ALWAYS:
745 g.RecurseThroughSymlinksOn();
750 std::string output = "";
752 for ( ; i != args.end(); ++i )
754 if ( recurse && (*i == "FOLLOW_SYMLINKS") )
756 explicitFollowSymlinks = true;
757 g.RecurseThroughSymlinksOn();
759 if ( i == args.end() )
762 "GLOB_RECURSE requires a glob expression after FOLLOW_SYMLINKS");
767 if ( *i == "RELATIVE" )
769 ++i; // skip RELATIVE
770 if ( i == args.end() )
772 this->SetError("GLOB requires a directory after the RELATIVE tag");
775 g.SetRelative(i->c_str());
779 this->SetError("GLOB requires a glob expression after the directory");
784 if ( !cmsys::SystemTools::FileIsFullPath(i->c_str()) )
786 std::string expr = this->Makefile->GetCurrentDirectory();
787 // Handle script mode
788 if ( expr.size() > 0 )
803 std::vector<std::string>::size_type cc;
804 std::vector<std::string>& files = g.GetFiles();
805 for ( cc = 0; cc < files.size(); cc ++ )
816 if(recurse && !explicitFollowSymlinks)
820 case cmPolicies::NEW:
821 // Correct behavior, yay!
823 case cmPolicies::OLD:
824 // Probably not really the expected behavior, but the author explicitly
825 // asked for the old behavior... no warning.
826 case cmPolicies::WARN:
827 // Possibly unexpected old behavior *and* we actually traversed
828 // symlinks without being explicitly asked to: warn the author.
829 if(g.GetFollowedSymlinkCount() != 0)
831 this->Makefile->IssueMessage(cmake::AUTHOR_WARNING,
832 this->Makefile->GetPolicies()->
833 GetPolicyWarning(cmPolicies::CMP0009));
836 case cmPolicies::REQUIRED_IF_USED:
837 case cmPolicies::REQUIRED_ALWAYS:
838 this->SetError("policy CMP0009 error");
839 this->Makefile->IssueMessage(cmake::FATAL_ERROR,
840 this->Makefile->GetPolicies()->
841 GetRequiredPolicyError(cmPolicies::CMP0009));
846 this->Makefile->AddDefinition(variable.c_str(), output.c_str());
850 //----------------------------------------------------------------------------
851 bool cmFileCommand::HandleMakeDirectoryCommand(
852 std::vector<std::string> const& args)
854 // File command has at least one argument
855 assert(args.size() > 1);
857 std::vector<std::string>::const_iterator i = args.begin();
859 i++; // Get rid of subcommand
862 for ( ; i != args.end(); ++i )
864 const std::string* cdir = &(*i);
865 if ( !cmsys::SystemTools::FileIsFullPath(i->c_str()) )
867 expr = this->Makefile->GetCurrentDirectory();
871 if ( !this->Makefile->CanIWriteThisFile(cdir->c_str()) )
873 std::string e = "attempted to create a directory: " + *cdir
874 + " into a source directory.";
875 this->SetError(e.c_str());
876 cmSystemTools::SetFatalErrorOccured();
879 if ( !cmSystemTools::MakeDirectory(cdir->c_str()) )
881 std::string error = "problem creating directory: " + *cdir;
882 this->SetError(error.c_str());
889 //----------------------------------------------------------------------------
891 cmFileCommand::HandleDifferentCommand(std::vector<std::string> const& args)
894 FILE(DIFFERENT <variable> FILES <lhs> <rhs>)
897 // Evaluate arguments.
898 const char* file_lhs = 0;
899 const char* file_rhs = 0;
901 enum Doing { DoingNone, DoingVar, DoingFileLHS, DoingFileRHS };
902 Doing doing = DoingVar;
903 for(unsigned int i=1; i < args.size(); ++i)
905 if(args[i] == "FILES")
907 doing = DoingFileLHS;
909 else if(doing == DoingVar)
911 var = args[i].c_str();
914 else if(doing == DoingFileLHS)
916 file_lhs = args[i].c_str();
917 doing = DoingFileRHS;
919 else if(doing == DoingFileRHS)
921 file_rhs = args[i].c_str();
927 e << "DIFFERENT given unknown argument " << args[i];
928 this->SetError(e.str().c_str());
934 this->SetError("DIFFERENT not given result variable name.");
937 if(!file_lhs || !file_rhs)
939 this->SetError("DIFFERENT not given FILES option with two file names.");
943 // Compare the files.
945 cmSystemTools::FilesDiffer(file_lhs, file_rhs)? "1" : "0";
946 this->Makefile->AddDefinition(var, result);
950 //----------------------------------------------------------------------------
951 // File installation helper class.
954 cmFileCopier(cmFileCommand* command, const char* name = "COPY"):
955 FileCommand(command),
956 Makefile(command->GetMakefile()),
959 MatchlessFiles(true),
963 UseGivenPermissionsFile(false),
964 UseGivenPermissionsDir(false),
965 UseSourcePermissions(true),
969 virtual ~cmFileCopier() {}
971 bool Run(std::vector<std::string> const& args);
974 cmFileCommand* FileCommand;
975 cmMakefile* Makefile;
978 cmFileTimeComparison FileTimes;
980 // Whether to install a file not matching any expression.
983 // Permissions for files and directories installed by this object.
984 mode_t FilePermissions;
985 mode_t DirPermissions;
987 // Properties set by pattern and regex match rules.
988 struct MatchProperties
992 MatchProperties(): Exclude(false), Permissions(0) {}
995 friend struct MatchRule;
998 cmsys::RegularExpression Regex;
999 MatchProperties Properties;
1000 std::string RegexString;
1001 MatchRule(std::string const& regex):
1002 Regex(regex.c_str()), RegexString(regex) {}
1004 std::vector<MatchRule> MatchRules;
1006 // Get the properties from rules matching this input file.
1007 MatchProperties CollectMatchProperties(const char* file)
1009 // Match rules are case-insensitive on some platforms.
1010 #if defined(_WIN32) || defined(__APPLE__) || defined(__CYGWIN__)
1011 std::string lower = cmSystemTools::LowerCase(file);
1012 const char* file_to_match = lower.c_str();
1014 const char* file_to_match = file;
1017 // Collect properties from all matching rules.
1018 bool matched = false;
1019 MatchProperties result;
1020 for(std::vector<MatchRule>::iterator mr = this->MatchRules.begin();
1021 mr != this->MatchRules.end(); ++mr)
1023 if(mr->Regex.find(file_to_match))
1026 result.Exclude |= mr->Properties.Exclude;
1027 result.Permissions |= mr->Properties.Permissions;
1030 if(!matched && !this->MatchlessFiles)
1032 result.Exclude = !cmSystemTools::FileIsDirectory(file);
1037 bool SetPermissions(const char* toFile, mode_t permissions)
1039 if(permissions && !cmSystemTools::SetPermissions(toFile, permissions))
1042 e << this->Name << " cannot set permissions on \"" << toFile << "\"";
1043 this->FileCommand->SetError(e.str().c_str());
1049 // Translate an argument to a permissions bit.
1050 bool CheckPermissions(std::string const& arg, mode_t& permissions)
1052 if(arg == "OWNER_READ") { permissions |= mode_owner_read; }
1053 else if(arg == "OWNER_WRITE") { permissions |= mode_owner_write; }
1054 else if(arg == "OWNER_EXECUTE") { permissions |= mode_owner_execute; }
1055 else if(arg == "GROUP_READ") { permissions |= mode_group_read; }
1056 else if(arg == "GROUP_WRITE") { permissions |= mode_group_write; }
1057 else if(arg == "GROUP_EXECUTE") { permissions |= mode_group_execute; }
1058 else if(arg == "WORLD_READ") { permissions |= mode_world_read; }
1059 else if(arg == "WORLD_WRITE") { permissions |= mode_world_write; }
1060 else if(arg == "WORLD_EXECUTE") { permissions |= mode_world_execute; }
1061 else if(arg == "SETUID") { permissions |= mode_setuid; }
1062 else if(arg == "SETGID") { permissions |= mode_setgid; }
1066 e << this->Name << " given invalid permission \"" << arg << "\".";
1067 this->FileCommand->SetError(e.str().c_str());
1073 bool InstallSymlink(const char* fromFile, const char* toFile);
1074 bool InstallFile(const char* fromFile, const char* toFile,
1075 MatchProperties const& match_properties);
1076 bool InstallDirectory(const char* source, const char* destination,
1077 MatchProperties const& match_properties);
1078 virtual bool Install(const char* fromFile, const char* toFile);
1079 virtual std::string const& ToName(std::string const& fromName)
1080 { return fromName; }
1088 virtual void ReportCopy(const char*, Type, bool) {}
1089 virtual bool ReportMissing(const char* fromFile)
1091 // The input file does not exist and installation is not optional.
1093 e << this->Name << " cannot find \"" << fromFile << "\".";
1094 this->FileCommand->SetError(e.str().c_str());
1098 MatchRule* CurrentMatchRule;
1099 bool UseGivenPermissionsFile;
1100 bool UseGivenPermissionsDir;
1101 bool UseSourcePermissions;
1102 std::string Destination;
1103 std::vector<std::string> Files;
1106 virtual bool Parse(std::vector<std::string> const& args);
1115 DoingPermissionsFile,
1116 DoingPermissionsDir,
1117 DoingPermissionsMatch,
1120 virtual bool CheckKeyword(std::string const& arg);
1121 virtual bool CheckValue(std::string const& arg);
1123 void NotBeforeMatch(std::string const& arg)
1126 e << "option " << arg << " may not appear before PATTERN or REGEX.";
1127 this->FileCommand->SetError(e.str().c_str());
1128 this->Doing = DoingError;
1130 void NotAfterMatch(std::string const& arg)
1133 e << "option " << arg << " may not appear after PATTERN or REGEX.";
1134 this->FileCommand->SetError(e.str().c_str());
1135 this->Doing = DoingError;
1137 virtual void DefaultFilePermissions()
1139 // Use read/write permissions.
1140 this->FilePermissions = 0;
1141 this->FilePermissions |= mode_owner_read;
1142 this->FilePermissions |= mode_owner_write;
1143 this->FilePermissions |= mode_group_read;
1144 this->FilePermissions |= mode_world_read;
1146 virtual void DefaultDirectoryPermissions()
1148 // Use read/write/executable permissions.
1149 this->DirPermissions = 0;
1150 this->DirPermissions |= mode_owner_read;
1151 this->DirPermissions |= mode_owner_write;
1152 this->DirPermissions |= mode_owner_execute;
1153 this->DirPermissions |= mode_group_read;
1154 this->DirPermissions |= mode_group_execute;
1155 this->DirPermissions |= mode_world_read;
1156 this->DirPermissions |= mode_world_execute;
1160 //----------------------------------------------------------------------------
1161 bool cmFileCopier::Parse(std::vector<std::string> const& args)
1163 this->Doing = DoingFiles;
1164 for(unsigned int i=1; i < args.size(); ++i)
1166 // Check this argument.
1167 if(!this->CheckKeyword(args[i]) &&
1168 !this->CheckValue(args[i]))
1171 e << "called with unknown argument \"" << args[i] << "\".";
1172 this->FileCommand->SetError(e.str().c_str());
1176 // Quit if an argument is invalid.
1177 if(this->Doing == DoingError)
1183 // Require a destination.
1184 if(this->Destination.empty())
1187 e << this->Name << " given no DESTINATION";
1188 this->FileCommand->SetError(e.str().c_str());
1192 // If file permissions were not specified set default permissions.
1193 if(!this->UseGivenPermissionsFile && !this->UseSourcePermissions)
1195 this->DefaultFilePermissions();
1198 // If directory permissions were not specified set default permissions.
1199 if(!this->UseGivenPermissionsDir && !this->UseSourcePermissions)
1201 this->DefaultDirectoryPermissions();
1207 //----------------------------------------------------------------------------
1208 bool cmFileCopier::CheckKeyword(std::string const& arg)
1210 if(arg == "DESTINATION")
1212 if(this->CurrentMatchRule)
1214 this->NotAfterMatch(arg);
1218 this->Doing = DoingDestination;
1221 else if(arg == "PATTERN")
1223 this->Doing = DoingPattern;
1225 else if(arg == "REGEX")
1227 this->Doing = DoingRegex;
1229 else if(arg == "EXCLUDE")
1231 // Add this property to the current match rule.
1232 if(this->CurrentMatchRule)
1234 this->CurrentMatchRule->Properties.Exclude = true;
1235 this->Doing = DoingNone;
1239 this->NotBeforeMatch(arg);
1242 else if(arg == "PERMISSIONS")
1244 if(this->CurrentMatchRule)
1246 this->Doing = DoingPermissionsMatch;
1250 this->NotBeforeMatch(arg);
1253 else if(arg == "FILE_PERMISSIONS")
1255 if(this->CurrentMatchRule)
1257 this->NotAfterMatch(arg);
1261 this->Doing = DoingPermissionsFile;
1262 this->UseGivenPermissionsFile = true;
1265 else if(arg == "DIRECTORY_PERMISSIONS")
1267 if(this->CurrentMatchRule)
1269 this->NotAfterMatch(arg);
1273 this->Doing = DoingPermissionsDir;
1274 this->UseGivenPermissionsDir = true;
1277 else if(arg == "USE_SOURCE_PERMISSIONS")
1279 if(this->CurrentMatchRule)
1281 this->NotAfterMatch(arg);
1285 this->Doing = DoingNone;
1286 this->UseSourcePermissions = true;
1289 else if(arg == "NO_SOURCE_PERMISSIONS")
1291 if(this->CurrentMatchRule)
1293 this->NotAfterMatch(arg);
1297 this->Doing = DoingNone;
1298 this->UseSourcePermissions = false;
1301 else if(arg == "FILES_MATCHING")
1303 if(this->CurrentMatchRule)
1305 this->NotAfterMatch(arg);
1309 this->Doing = DoingNone;
1310 this->MatchlessFiles = false;
1320 //----------------------------------------------------------------------------
1321 bool cmFileCopier::CheckValue(std::string const& arg)
1326 if(arg.empty() || cmSystemTools::FileIsFullPath(arg.c_str()))
1328 this->Files.push_back(arg);
1332 std::string file = this->Makefile->GetCurrentDirectory();
1334 this->Files.push_back(file);
1337 case DoingDestination:
1338 if(arg.empty() || cmSystemTools::FileIsFullPath(arg.c_str()))
1340 this->Destination = arg;
1344 this->Destination = this->Makefile->GetCurrentOutputDirectory();
1345 this->Destination += "/" + arg;
1347 this->Doing = DoingNone;
1351 // Convert the pattern to a regular expression. Require a
1352 // leading slash and trailing end-of-string in the matched
1353 // string to make sure the pattern matches only whole file
1355 std::string regex = "/";
1356 regex += cmsys::Glob::PatternToRegex(arg, false);
1358 this->MatchRules.push_back(MatchRule(regex));
1359 this->CurrentMatchRule = &*(this->MatchRules.end()-1);
1360 if(this->CurrentMatchRule->Regex.is_valid())
1362 this->Doing = DoingNone;
1367 e << "could not compile PATTERN \"" << arg << "\".";
1368 this->FileCommand->SetError(e.str().c_str());
1369 this->Doing = DoingError;
1374 this->MatchRules.push_back(MatchRule(arg));
1375 this->CurrentMatchRule = &*(this->MatchRules.end()-1);
1376 if(this->CurrentMatchRule->Regex.is_valid())
1378 this->Doing = DoingNone;
1383 e << "could not compile REGEX \"" << arg << "\".";
1384 this->FileCommand->SetError(e.str().c_str());
1385 this->Doing = DoingError;
1388 case DoingPermissionsFile:
1389 if(!this->CheckPermissions(arg, this->FilePermissions))
1391 this->Doing = DoingError;
1394 case DoingPermissionsDir:
1395 if(!this->CheckPermissions(arg, this->DirPermissions))
1397 this->Doing = DoingError;
1400 case DoingPermissionsMatch:
1401 if(!this->CheckPermissions(
1402 arg, this->CurrentMatchRule->Properties.Permissions))
1404 this->Doing = DoingError;
1413 //----------------------------------------------------------------------------
1414 bool cmFileCopier::Run(std::vector<std::string> const& args)
1416 if(!this->Parse(args))
1421 std::vector<std::string> const& files = this->Files;
1422 for(std::vector<std::string>::size_type i = 0; i < files.size(); ++i)
1424 // Split the input file into its directory and name components.
1425 std::vector<std::string> fromPathComponents;
1426 cmSystemTools::SplitPath(files[i].c_str(), fromPathComponents);
1427 std::string fromName = *(fromPathComponents.end()-1);
1428 std::string fromDir = cmSystemTools::JoinPath(fromPathComponents.begin(),
1429 fromPathComponents.end()-1);
1431 // Compute the full path to the destination file.
1432 std::string toFile = this->Destination;
1433 std::string const& toName = this->ToName(fromName);
1440 // Construct the full path to the source file. The file name may
1441 // have been changed above.
1442 std::string fromFile = fromDir;
1443 if(!fromName.empty())
1446 fromFile += fromName;
1449 if(!this->Install(fromFile.c_str(), toFile.c_str()))
1457 //----------------------------------------------------------------------------
1458 bool cmFileCopier::Install(const char* fromFile, const char* toFile)
1463 e << "INSTALL encountered an empty string input file name.";
1464 this->FileCommand->SetError(e.str().c_str());
1468 // Collect any properties matching this file name.
1469 MatchProperties match_properties = this->CollectMatchProperties(fromFile);
1471 // Skip the file if it is excluded.
1472 if(match_properties.Exclude)
1477 if(cmSystemTools::SameFile(fromFile, toFile))
1481 else if(cmSystemTools::FileIsSymlink(fromFile))
1483 return this->InstallSymlink(fromFile, toFile);
1485 else if(cmSystemTools::FileIsDirectory(fromFile))
1487 return this->InstallDirectory(fromFile, toFile, match_properties);
1489 else if(cmSystemTools::FileExists(fromFile))
1491 return this->InstallFile(fromFile, toFile, match_properties);
1493 return this->ReportMissing(fromFile);
1496 //----------------------------------------------------------------------------
1497 bool cmFileCopier::InstallSymlink(const char* fromFile, const char* toFile)
1499 // Read the original symlink.
1500 std::string symlinkTarget;
1501 if(!cmSystemTools::ReadSymlink(fromFile, symlinkTarget))
1504 e << this->Name << " cannot read symlink \"" << fromFile
1505 << "\" to duplicate at \"" << toFile << "\".";
1506 this->FileCommand->SetError(e.str().c_str());
1510 // Compare the symlink value to that at the destination if not
1511 // always installing.
1515 std::string oldSymlinkTarget;
1516 if(cmSystemTools::ReadSymlink(toFile, oldSymlinkTarget))
1518 if(symlinkTarget == oldSymlinkTarget)
1525 // Inform the user about this file installation.
1526 this->ReportCopy(toFile, TypeLink, copy);
1530 // Remove the destination file so we can always create the symlink.
1531 cmSystemTools::RemoveFile(toFile);
1533 // Create the symlink.
1534 if(!cmSystemTools::CreateSymlink(symlinkTarget.c_str(), toFile))
1537 e << this->Name << " cannot duplicate symlink \"" << fromFile
1538 << "\" at \"" << toFile << "\".";
1539 this->FileCommand->SetError(e.str().c_str());
1547 //----------------------------------------------------------------------------
1548 bool cmFileCopier::InstallFile(const char* fromFile, const char* toFile,
1549 MatchProperties const& match_properties)
1551 // Determine whether we will copy the file.
1555 // If both files exist with the same time do not copy.
1556 if(!this->FileTimes.FileTimesDiffer(fromFile, toFile))
1562 // Inform the user about this file installation.
1563 this->ReportCopy(toFile, TypeFile, copy);
1566 if(copy && !cmSystemTools::CopyAFile(fromFile, toFile, true))
1569 e << this->Name << " cannot copy file \"" << fromFile
1570 << "\" to \"" << toFile << "\".";
1571 this->FileCommand->SetError(e.str().c_str());
1575 // Set the file modification time of the destination file.
1576 if(copy && !this->Always)
1578 // Add write permission so we can set the file time.
1579 // Permissions are set unconditionally below anyway.
1581 if(cmSystemTools::GetPermissions(toFile, perm))
1583 cmSystemTools::SetPermissions(toFile, perm | mode_owner_write);
1585 if (!cmSystemTools::CopyFileTime(fromFile, toFile))
1588 e << this->Name << " cannot set modification time on \""
1590 this->FileCommand->SetError(e.str().c_str());
1595 // Set permissions of the destination file.
1596 mode_t permissions = (match_properties.Permissions?
1597 match_properties.Permissions : this->FilePermissions);
1600 // No permissions were explicitly provided but the user requested
1601 // that the source file permissions be used.
1602 cmSystemTools::GetPermissions(fromFile, permissions);
1604 return this->SetPermissions(toFile, permissions);
1607 //----------------------------------------------------------------------------
1608 bool cmFileCopier::InstallDirectory(const char* source,
1609 const char* destination,
1610 MatchProperties const& match_properties)
1612 // Inform the user about this directory installation.
1613 this->ReportCopy(destination, TypeDir, true);
1615 // Make sure the destination directory exists.
1616 if(!cmSystemTools::MakeDirectory(destination))
1619 e << this->Name << " cannot make directory \"" << destination << "\": "
1620 << cmSystemTools::GetLastSystemError();
1621 this->FileCommand->SetError(e.str().c_str());
1625 // Compute the requested permissions for the destination directory.
1626 mode_t permissions = (match_properties.Permissions?
1627 match_properties.Permissions : this->DirPermissions);
1630 // No permissions were explicitly provided but the user requested
1631 // that the source directory permissions be used.
1632 cmSystemTools::GetPermissions(source, permissions);
1635 // Compute the set of permissions required on this directory to
1636 // recursively install files and subdirectories safely.
1637 mode_t required_permissions =
1638 mode_owner_read | mode_owner_write | mode_owner_execute;
1640 // If the required permissions are specified it is safe to set the
1641 // final permissions now. Otherwise we must add the required
1642 // permissions temporarily during file installation.
1643 mode_t permissions_before = 0;
1644 mode_t permissions_after = 0;
1645 if((permissions & required_permissions) == required_permissions)
1647 permissions_before = permissions;
1651 permissions_before = permissions | required_permissions;
1652 permissions_after = permissions;
1655 // Set the required permissions of the destination directory.
1656 if(!this->SetPermissions(destination, permissions_before))
1661 // Load the directory contents to traverse it recursively.
1662 cmsys::Directory dir;
1663 if(source && *source)
1667 unsigned long numFiles = static_cast<unsigned long>(dir.GetNumberOfFiles());
1668 for(unsigned long fileNum = 0; fileNum < numFiles; ++fileNum)
1670 if(!(strcmp(dir.GetFile(fileNum), ".") == 0 ||
1671 strcmp(dir.GetFile(fileNum), "..") == 0))
1673 cmsys_stl::string fromPath = source;
1675 fromPath += dir.GetFile(fileNum);
1676 std::string toPath = destination;
1678 toPath += dir.GetFile(fileNum);
1679 if(!this->Install(fromPath.c_str(), toPath.c_str()))
1686 // Set the requested permissions of the destination directory.
1687 return this->SetPermissions(destination, permissions_after);
1690 //----------------------------------------------------------------------------
1691 bool cmFileCommand::HandleCopyCommand(std::vector<std::string> const& args)
1693 cmFileCopier copier(this);
1694 return copier.Run(args);
1697 //----------------------------------------------------------------------------
1698 struct cmFileInstaller: public cmFileCopier
1700 cmFileInstaller(cmFileCommand* command):
1701 cmFileCopier(command, "INSTALL"),
1702 InstallType(cmInstallType_FILES),
1706 // Installation does not use source permissions by default.
1707 this->UseSourcePermissions = false;
1708 // Check whether to copy files always or only if they have changed.
1710 cmSystemTools::IsOn(cmSystemTools::GetEnv("CMAKE_INSTALL_ALWAYS"));
1711 // Get the current manifest.
1713 this->Makefile->GetSafeDefinition("CMAKE_INSTALL_MANIFEST_FILES");
1717 // Save the updated install manifest.
1718 this->Makefile->AddDefinition("CMAKE_INSTALL_MANIFEST_FILES",
1719 this->Manifest.c_str());
1723 cmInstallType InstallType;
1728 std::string Manifest;
1729 void ManifestAppend(std::string const& file)
1731 this->Manifest += ";";
1732 this->Manifest += file.substr(this->DestDirLength);
1735 virtual std::string const& ToName(std::string const& fromName)
1736 { return this->Rename.empty()? fromName : this->Rename; }
1738 virtual void ReportCopy(const char* toFile, Type type, bool copy)
1740 std::string message = (copy? "Installing: " : "Up-to-date: ");
1742 this->Makefile->DisplayStatus(message.c_str(), -1);
1745 // Add the file to the manifest.
1746 this->ManifestAppend(toFile);
1749 virtual bool ReportMissing(const char* fromFile)
1751 return (this->Optional ||
1752 this->cmFileCopier::ReportMissing(fromFile));
1754 virtual bool Install(const char* fromFile, const char* toFile)
1756 // Support installing from empty source to make a directory.
1757 if(this->InstallType == cmInstallType_DIRECTORY && !*fromFile)
1759 return this->InstallDirectory(fromFile, toFile, MatchProperties());
1761 return this->cmFileCopier::Install(fromFile, toFile);
1764 virtual bool Parse(std::vector<std::string> const& args);
1767 DoingType = DoingLast1,
1771 virtual bool CheckKeyword(std::string const& arg);
1772 virtual bool CheckValue(std::string const& arg);
1773 virtual void DefaultFilePermissions()
1775 this->cmFileCopier::DefaultFilePermissions();
1776 // Add execute permissions based on the target type.
1777 switch(this->InstallType)
1779 case cmInstallType_SHARED_LIBRARY:
1780 case cmInstallType_MODULE_LIBRARY:
1781 if(this->Makefile->IsOn("CMAKE_INSTALL_SO_NO_EXE"))
1785 case cmInstallType_EXECUTABLE:
1786 case cmInstallType_PROGRAMS:
1787 this->FilePermissions |= mode_owner_execute;
1788 this->FilePermissions |= mode_group_execute;
1789 this->FilePermissions |= mode_world_execute;
1794 bool GetTargetTypeFromString(const std::string& stype);
1795 bool HandleInstallDestination();
1798 //----------------------------------------------------------------------------
1799 bool cmFileInstaller::Parse(std::vector<std::string> const& args)
1801 if(!this->cmFileCopier::Parse(args))
1806 if(!this->Rename.empty())
1808 if(this->InstallType != cmInstallType_FILES &&
1809 this->InstallType != cmInstallType_PROGRAMS)
1811 this->FileCommand->SetError("INSTALL option RENAME may be used "
1812 "only with FILES or PROGRAMS.");
1815 if(this->Files.size() > 1)
1817 this->FileCommand->SetError("INSTALL option RENAME may be used "
1818 "only with one file.");
1823 if(!this->HandleInstallDestination())
1831 //----------------------------------------------------------------------------
1832 bool cmFileInstaller::CheckKeyword(std::string const& arg)
1836 if(this->CurrentMatchRule)
1838 this->NotAfterMatch(arg);
1842 this->Doing = DoingType;
1845 else if(arg == "FILES")
1847 if(this->CurrentMatchRule)
1849 this->NotAfterMatch(arg);
1853 this->Doing = DoingFiles;
1856 else if(arg == "RENAME")
1858 if(this->CurrentMatchRule)
1860 this->NotAfterMatch(arg);
1864 this->Doing = DoingRename;
1867 else if(arg == "OPTIONAL")
1869 if(this->CurrentMatchRule)
1871 this->NotAfterMatch(arg);
1875 this->Doing = DoingNone;
1876 this->Optional = true;
1879 else if(arg == "PERMISSIONS")
1881 if(this->CurrentMatchRule)
1883 this->Doing = DoingPermissionsMatch;
1887 // file(INSTALL) aliases PERMISSIONS to FILE_PERMISSIONS
1888 this->Doing = DoingPermissionsFile;
1889 this->UseGivenPermissionsFile = true;
1892 else if(arg == "DIR_PERMISSIONS")
1894 if(this->CurrentMatchRule)
1896 this->NotAfterMatch(arg);
1900 // file(INSTALL) aliases DIR_PERMISSIONS to DIRECTORY_PERMISSIONS
1901 this->Doing = DoingPermissionsDir;
1902 this->UseGivenPermissionsDir = true;
1905 else if(arg == "COMPONENTS" || arg == "CONFIGURATIONS" ||
1906 arg == "PROPERTIES")
1909 e << "INSTALL called with old-style " << arg << " argument. "
1910 << "This script was generated with an older version of CMake. "
1911 << "Re-run this cmake version on your build tree.";
1912 this->FileCommand->SetError(e.str().c_str());
1913 this->Doing = DoingError;
1917 return this->cmFileCopier::CheckKeyword(arg);
1922 //----------------------------------------------------------------------------
1923 bool cmFileInstaller::CheckValue(std::string const& arg)
1928 if(!this->GetTargetTypeFromString(arg))
1930 this->Doing = DoingError;
1937 return this->cmFileCopier::CheckValue(arg);
1942 //----------------------------------------------------------------------------
1943 bool cmFileInstaller
1944 ::GetTargetTypeFromString(const std::string& stype)
1946 if ( stype == "EXECUTABLE" )
1948 this->InstallType = cmInstallType_EXECUTABLE;
1950 else if ( stype == "FILE" )
1952 this->InstallType = cmInstallType_FILES;
1954 else if ( stype == "PROGRAM" )
1956 this->InstallType = cmInstallType_PROGRAMS;
1958 else if ( stype == "STATIC_LIBRARY" )
1960 this->InstallType = cmInstallType_STATIC_LIBRARY;
1962 else if ( stype == "SHARED_LIBRARY" )
1964 this->InstallType = cmInstallType_SHARED_LIBRARY;
1966 else if ( stype == "MODULE" )
1968 this->InstallType = cmInstallType_MODULE_LIBRARY;
1970 else if ( stype == "DIRECTORY" )
1972 this->InstallType = cmInstallType_DIRECTORY;
1977 e << "Option TYPE given unknown value \"" << stype << "\".";
1978 this->FileCommand->SetError(e.str().c_str());
1984 //----------------------------------------------------------------------------
1985 bool cmFileInstaller::HandleInstallDestination()
1987 std::string& destination = this->Destination;
1989 // allow for / to be a valid destination
1990 if ( destination.size() < 2 && destination != "/" )
1992 this->FileCommand->SetError("called with inappropriate arguments. "
1993 "No DESTINATION provided or .");
1997 const char* destdir = cmSystemTools::GetEnv("DESTDIR");
1998 if ( destdir && *destdir )
2000 std::string sdestdir = destdir;
2001 cmSystemTools::ConvertToUnixSlashes(sdestdir);
2002 char ch1 = destination[0];
2003 char ch2 = destination[1];
2005 if ( destination.size() > 2 )
2007 ch3 = destination[2];
2013 if (((ch1 >= 'a' && ch1 <= 'z') || (ch1 >= 'A' && ch1 <= 'Z')) &&
2017 // let's do some destdir magic:
2030 // This is relative path on unix or windows. Since we are doing
2031 // destdir, this case does not make sense.
2032 this->FileCommand->SetError(
2033 "called with relative DESTINATION. This "
2034 "does not make sense when using DESTDIR. Specify "
2035 "absolute path or remove DESTDIR environment variable.");
2043 // looks like a network path.
2044 std::string message = "called with network path DESTINATION. This "
2045 "does not make sense when using DESTDIR. Specify local "
2046 "absolute path or remove DESTDIR environment variable."
2048 message += destination;
2049 this->FileCommand->SetError(message.c_str());
2053 destination = sdestdir + (destination.c_str() + skip);
2054 this->DestDirLength = int(sdestdir.size());
2057 if ( !cmSystemTools::FileExists(destination.c_str()) )
2059 if ( !cmSystemTools::MakeDirectory(destination.c_str()) )
2061 std::string errstring = "cannot create directory: " + destination +
2062 ". Maybe need administrative privileges.";
2063 this->FileCommand->SetError(errstring.c_str());
2067 if ( !cmSystemTools::FileIsDirectory(destination.c_str()) )
2069 std::string errstring = "INSTALL destination: " + destination +
2070 " is not a directory.";
2071 this->FileCommand->SetError(errstring.c_str());
2077 //----------------------------------------------------------------------------
2079 cmFileCommand::HandleRPathChangeCommand(std::vector<std::string> const& args)
2081 // Evaluate arguments.
2082 const char* file = 0;
2083 const char* oldRPath = 0;
2084 const char* newRPath = 0;
2085 enum Doing { DoingNone, DoingFile, DoingOld, DoingNew };
2086 Doing doing = DoingNone;
2087 for(unsigned int i=1; i < args.size(); ++i)
2089 if(args[i] == "OLD_RPATH")
2093 else if(args[i] == "NEW_RPATH")
2097 else if(args[i] == "FILE")
2101 else if(doing == DoingFile)
2103 file = args[i].c_str();
2106 else if(doing == DoingOld)
2108 oldRPath = args[i].c_str();
2111 else if(doing == DoingNew)
2113 newRPath = args[i].c_str();
2119 e << "RPATH_CHANGE given unknown argument " << args[i];
2120 this->SetError(e.str().c_str());
2126 this->SetError("RPATH_CHANGE not given FILE option.");
2131 this->SetError("RPATH_CHANGE not given OLD_RPATH option.");
2136 this->SetError("RPATH_CHANGE not given NEW_RPATH option.");
2139 if(!cmSystemTools::FileExists(file, true))
2142 e << "RPATH_CHANGE given FILE \"" << file << "\" that does not exist.";
2143 this->SetError(e.str().c_str());
2146 bool success = true;
2147 cmSystemToolsFileTime* ft = cmSystemTools::FileTimeNew();
2148 bool have_ft = cmSystemTools::FileTimeGet(file, ft);
2151 if(!cmSystemTools::ChangeRPath(file, oldRPath, newRPath, &emsg, &changed))
2154 e << "RPATH_CHANGE could not write new RPATH:\n"
2155 << " " << newRPath << "\n"
2157 << " " << file << "\n"
2159 this->SetError(e.str().c_str());
2166 std::string message = "Set runtime path of \"";
2168 message += "\" to \"";
2169 message += newRPath;
2171 this->Makefile->DisplayStatus(message.c_str(), -1);
2175 cmSystemTools::FileTimeSet(file, ft);
2178 cmSystemTools::FileTimeDelete(ft);
2182 //----------------------------------------------------------------------------
2184 cmFileCommand::HandleRPathRemoveCommand(std::vector<std::string> const& args)
2186 // Evaluate arguments.
2187 const char* file = 0;
2188 enum Doing { DoingNone, DoingFile };
2189 Doing doing = DoingNone;
2190 for(unsigned int i=1; i < args.size(); ++i)
2192 if(args[i] == "FILE")
2196 else if(doing == DoingFile)
2198 file = args[i].c_str();
2204 e << "RPATH_REMOVE given unknown argument " << args[i];
2205 this->SetError(e.str().c_str());
2211 this->SetError("RPATH_REMOVE not given FILE option.");
2214 if(!cmSystemTools::FileExists(file, true))
2217 e << "RPATH_REMOVE given FILE \"" << file << "\" that does not exist.";
2218 this->SetError(e.str().c_str());
2221 bool success = true;
2222 cmSystemToolsFileTime* ft = cmSystemTools::FileTimeNew();
2223 bool have_ft = cmSystemTools::FileTimeGet(file, ft);
2226 if(!cmSystemTools::RemoveRPath(file, &emsg, &removed))
2229 e << "RPATH_REMOVE could not remove RPATH from file:\n"
2230 << " " << file << "\n"
2232 this->SetError(e.str().c_str());
2239 std::string message = "Removed runtime path from \"";
2242 this->Makefile->DisplayStatus(message.c_str(), -1);
2246 cmSystemTools::FileTimeSet(file, ft);
2249 cmSystemTools::FileTimeDelete(ft);
2253 //----------------------------------------------------------------------------
2255 cmFileCommand::HandleRPathCheckCommand(std::vector<std::string> const& args)
2257 // Evaluate arguments.
2258 const char* file = 0;
2259 const char* rpath = 0;
2260 enum Doing { DoingNone, DoingFile, DoingRPath };
2261 Doing doing = DoingNone;
2262 for(unsigned int i=1; i < args.size(); ++i)
2264 if(args[i] == "RPATH")
2268 else if(args[i] == "FILE")
2272 else if(doing == DoingFile)
2274 file = args[i].c_str();
2277 else if(doing == DoingRPath)
2279 rpath = args[i].c_str();
2285 e << "RPATH_CHECK given unknown argument " << args[i];
2286 this->SetError(e.str().c_str());
2292 this->SetError("RPATH_CHECK not given FILE option.");
2297 this->SetError("RPATH_CHECK not given RPATH option.");
2301 // If the file exists but does not have the desired RPath then
2302 // delete it. This is used during installation to re-install a file
2303 // if its RPath will change.
2304 if(cmSystemTools::FileExists(file, true) &&
2305 !cmSystemTools::CheckRPath(file, rpath))
2307 cmSystemTools::RemoveFile(file);
2313 //----------------------------------------------------------------------------
2314 bool cmFileCommand::HandleInstallCommand(std::vector<std::string> const& args)
2316 cmFileInstaller installer(this);
2317 return installer.Run(args);
2320 //----------------------------------------------------------------------------
2321 bool cmFileCommand::HandleRelativePathCommand(
2322 std::vector<std::string> const& args)
2324 if(args.size() != 4 )
2326 this->SetError("RELATIVE_PATH called with incorrect number of arguments");
2330 const std::string& outVar = args[1];
2331 const std::string& directoryName = args[2];
2332 const std::string& fileName = args[3];
2334 if(!cmSystemTools::FileIsFullPath(directoryName.c_str()))
2336 std::string errstring =
2337 "RELATIVE_PATH must be passed a full path to the directory: "
2339 this->SetError(errstring.c_str());
2342 if(!cmSystemTools::FileIsFullPath(fileName.c_str()))
2344 std::string errstring =
2345 "RELATIVE_PATH must be passed a full path to the file: "
2347 this->SetError(errstring.c_str());
2351 std::string res = cmSystemTools::RelativePath(directoryName.c_str(),
2353 this->Makefile->AddDefinition(outVar.c_str(),
2359 //----------------------------------------------------------------------------
2360 bool cmFileCommand::HandleRename(std::vector<std::string> const& args)
2362 if(args.size() != 3)
2364 this->SetError("RENAME given incorrect number of arguments.");
2368 // Compute full path for old and new names.
2369 std::string oldname = args[1];
2370 if(!cmsys::SystemTools::FileIsFullPath(oldname.c_str()))
2372 oldname = this->Makefile->GetCurrentDirectory();
2373 oldname += "/" + args[1];
2375 std::string newname = args[2];
2376 if(!cmsys::SystemTools::FileIsFullPath(newname.c_str()))
2378 newname = this->Makefile->GetCurrentDirectory();
2379 newname += "/" + args[2];
2382 if(!cmSystemTools::RenameFile(oldname.c_str(), newname.c_str()))
2384 std::string err = cmSystemTools::GetLastSystemError();
2386 e << "RENAME failed to rename\n"
2387 << " " << oldname << "\n"
2389 << " " << newname << "\n"
2390 << "because: " << err << "\n";
2391 this->SetError(e.str().c_str());
2398 //----------------------------------------------------------------------------
2399 bool cmFileCommand::HandleRemove(std::vector<std::string> const& args,
2403 std::string message;
2404 std::vector<std::string>::const_iterator i = args.begin();
2406 i++; // Get rid of subcommand
2407 for(;i != args.end(); ++i)
2409 std::string fileName = *i;
2410 if(!cmsys::SystemTools::FileIsFullPath(fileName.c_str()))
2412 fileName = this->Makefile->GetCurrentDirectory();
2413 fileName += "/" + *i;
2416 if(cmSystemTools::FileIsDirectory(fileName.c_str()) &&
2417 !cmSystemTools::FileIsSymlink(fileName.c_str()) && recurse)
2419 cmSystemTools::RemoveADirectory(fileName.c_str());
2423 cmSystemTools::RemoveFile(fileName.c_str());
2429 //----------------------------------------------------------------------------
2430 bool cmFileCommand::HandleCMakePathCommand(std::vector<std::string>
2434 std::vector<std::string>::const_iterator i = args.begin();
2435 if(args.size() != 3)
2437 this->SetError("FILE([TO_CMAKE_PATH|TO_NATIVE_PATH] path result) must be "
2438 "called with exactly three arguments.");
2441 i++; // Get rid of subcommand
2442 #if defined(_WIN32) && !defined(__CYGWIN__)
2447 std::vector<cmsys::String> path = cmSystemTools::SplitString(i->c_str(),
2450 const char* var = i->c_str();
2452 for(std::vector<cmsys::String>::iterator j = path.begin();
2453 j != path.end(); ++j)
2455 if(j != path.begin())
2461 cmSystemTools::ConvertToUnixSlashes(*j);
2465 *j = cmSystemTools::ConvertToOutputPath(j->c_str());
2466 // remove double quotes in the path
2467 cmsys::String& s = *j;
2469 if(s.size() > 1 && s[0] == '\"' && s[s.size()-1] == '\"')
2471 s = s.substr(1,s.size()-2);
2476 this->Makefile->AddDefinition(var, value.c_str());
2481 #if defined(CMAKE_BUILD_WITH_CMAKE)
2483 // Stuff for curl download/upload
2484 typedef std::vector<char> cmFileCommandVectorOfChar;
2489 cmWriteToFileCallback(void *ptr, size_t size, size_t nmemb,
2492 int realsize = (int)(size * nmemb);
2493 std::ofstream* fout = static_cast<std::ofstream*>(data);
2494 const char* chPtr = static_cast<char*>(ptr);
2495 fout->write(chPtr, realsize);
2501 cmWriteToMemoryCallback(void *ptr, size_t size, size_t nmemb,
2504 int realsize = (int)(size * nmemb);
2505 cmFileCommandVectorOfChar *vec
2506 = static_cast<cmFileCommandVectorOfChar*>(data);
2507 const char* chPtr = static_cast<char*>(ptr);
2508 vec->insert(vec->end(), chPtr, chPtr + realsize);
2514 cmFileCommandCurlDebugCallback(CURL *, curl_infotype, char *chPtr,
2515 size_t size, void *data)
2517 cmFileCommandVectorOfChar *vec
2518 = static_cast<cmFileCommandVectorOfChar*>(data);
2519 vec->insert(vec->end(), chPtr, chPtr + size);
2524 class cURLProgressHelper
2527 cURLProgressHelper(cmFileCommand *fc, const char *text)
2529 this->CurrentPercentage = -1;
2530 this->FileCommand = fc;
2534 bool UpdatePercentage(double value, double total, std::string &status)
2536 int OldPercentage = this->CurrentPercentage;
2540 this->CurrentPercentage = static_cast<int>(value/total*100.0 + 0.5);
2543 bool updated = (OldPercentage != this->CurrentPercentage);
2547 cmOStringStream oss;
2548 oss << "[" << this->Text << " " << this->CurrentPercentage
2556 cmFileCommand *GetFileCommand()
2558 return this->FileCommand;
2562 int CurrentPercentage;
2563 cmFileCommand *FileCommand;
2569 cmFileDownloadProgressCallback(void *clientp,
2570 double dltotal, double dlnow,
2571 double ultotal, double ulnow)
2573 cURLProgressHelper *helper =
2574 reinterpret_cast<cURLProgressHelper *>(clientp);
2576 static_cast<void>(ultotal);
2577 static_cast<void>(ulnow);
2580 if (helper->UpdatePercentage(dlnow, dltotal, status))
2582 cmFileCommand *fc = helper->GetFileCommand();
2583 cmMakefile *mf = fc->GetMakefile();
2584 mf->DisplayStatus(status.c_str(), -1);
2592 cmFileUploadProgressCallback(void *clientp,
2593 double dltotal, double dlnow,
2594 double ultotal, double ulnow)
2596 cURLProgressHelper *helper =
2597 reinterpret_cast<cURLProgressHelper *>(clientp);
2599 static_cast<void>(dltotal);
2600 static_cast<void>(dlnow);
2603 if (helper->UpdatePercentage(ulnow, ultotal, status))
2605 cmFileCommand *fc = helper->GetFileCommand();
2606 cmMakefile *mf = fc->GetMakefile();
2607 mf->DisplayStatus(status.c_str(), -1);
2620 cURLEasyGuard(CURL * easy)
2624 ~cURLEasyGuard(void)
2628 ::curl_easy_cleanup(this->Easy);
2632 inline void release(void)
2646 #define check_curl_result(result, errstr) \
2647 if (result != CURLE_OK) \
2649 std::string e(errstr); \
2650 e += ::curl_easy_strerror(result); \
2651 this->SetError(e.c_str()); \
2657 cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args)
2659 #if defined(CMAKE_BUILD_WITH_CMAKE)
2660 std::vector<std::string>::const_iterator i = args.begin();
2663 this->SetError("DOWNLOAD must be called with at least three arguments.");
2666 ++i; // Get rid of subcommand
2667 std::string url = *i;
2669 std::string file = *i;
2673 long inactivity_timeout = 0;
2674 std::string verboseLog;
2675 std::string statusVar;
2676 bool tls_verify = this->Makefile->IsOn("CMAKE_TLS_VERIFY");
2677 const char* cainfo = this->Makefile->GetDefinition("CMAKE_TLS_CAINFO");
2678 std::string expectedHash;
2679 std::string hashMatchMSG;
2680 cmsys::auto_ptr<cmCryptoHash> hash;
2681 bool showProgress = false;
2683 while(i != args.end())
2690 timeout = atol(i->c_str());
2694 this->SetError("DOWNLOAD missing time for TIMEOUT.");
2698 else if(*i == "INACTIVITY_TIMEOUT")
2703 inactivity_timeout = atol(i->c_str());
2707 this->SetError("DOWNLOAD missing time for INACTIVITY_TIMEOUT.");
2711 else if(*i == "LOG")
2714 if( i == args.end())
2716 this->SetError("DOWNLOAD missing VAR for LOG.");
2721 else if(*i == "STATUS")
2724 if( i == args.end())
2726 this->SetError("DOWNLOAD missing VAR for STATUS.");
2731 else if(*i == "TLS_VERIFY")
2736 tls_verify = cmSystemTools::IsOn(i->c_str());
2740 this->SetError("TLS_VERIFY missing bool value.");
2744 else if(*i == "TLS_CAINFO")
2749 cainfo = i->c_str();
2753 this->SetError("TLS_CAFILE missing file value.");
2757 else if(*i == "EXPECTED_MD5")
2760 if( i == args.end())
2762 this->SetError("DOWNLOAD missing sum value for EXPECTED_MD5.");
2765 hash = cmsys::auto_ptr<cmCryptoHash>(cmCryptoHash::New("MD5"));
2766 hashMatchMSG = "MD5 sum";
2767 expectedHash = cmSystemTools::LowerCase(*i);
2769 else if(*i == "SHOW_PROGRESS")
2771 showProgress = true;
2773 else if(*i == "EXPECTED_HASH")
2778 this->SetError("DOWNLOAD missing ALGO=value for EXPECTED_HASH.");
2781 std::string::size_type pos = i->find("=");
2782 if(pos == std::string::npos)
2785 "DOWNLOAD EXPECTED_HASH expects ALGO=value but got: ";
2787 this->SetError(err.c_str());
2790 std::string algo = i->substr(0, pos);
2791 expectedHash = cmSystemTools::LowerCase(i->substr(pos+1));
2792 hash = cmsys::auto_ptr<cmCryptoHash>(cmCryptoHash::New(algo.c_str()));
2795 std::string err = "DOWNLOAD EXPECTED_HASH given unknown ALGO: ";
2797 this->SetError(err.c_str());
2800 hashMatchMSG = algo + " hash";
2804 // If file exists already, and caller specified an expected md5 or sha,
2805 // and the existing file already has the expected hash, then simply
2808 if(cmSystemTools::FileExists(file.c_str()) && hash.get())
2811 std::string actualHash = hash->HashFile(file.c_str());
2812 if(actualHash == expectedHash)
2814 msg = "returning early; file already exists with expected ";
2815 msg += hashMatchMSG;
2817 if(statusVar.size())
2819 cmOStringStream result;
2820 result << (int)0 << ";\"" << msg;
2821 this->Makefile->AddDefinition(statusVar.c_str(),
2822 result.str().c_str());
2827 // Make sure parent directory exists so we can write to the file
2828 // as we receive downloaded bits from curl...
2830 std::string dir = cmSystemTools::GetFilenamePath(file.c_str());
2831 if(!cmSystemTools::FileExists(dir.c_str()) &&
2832 !cmSystemTools::MakeDirectory(dir.c_str()))
2834 std::string errstring = "DOWNLOAD error: cannot create directory '"
2835 + dir + "' - Specify file by full path name and verify that you "
2836 "have directory creation and file write privileges.";
2837 this->SetError(errstring.c_str());
2841 std::ofstream fout(file.c_str(), std::ios::binary);
2844 this->SetError("DOWNLOAD cannot open file for write.");
2849 ::curl_global_init(CURL_GLOBAL_DEFAULT);
2850 curl = ::curl_easy_init();
2853 this->SetError("DOWNLOAD error initializing curl.");
2857 cURLEasyGuard g_curl(curl);
2858 ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
2859 check_curl_result(res, "DOWNLOAD cannot set url: ");
2861 // enable HTTP ERROR parsing
2862 res = ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
2863 check_curl_result(res, "DOWNLOAD cannot set http failure option: ");
2865 res = ::curl_easy_setopt(curl, CURLOPT_USERAGENT, "curl/" LIBCURL_VERSION);
2866 check_curl_result(res, "DOWNLOAD cannot set user agent option: ");
2868 res = ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
2869 cmWriteToFileCallback);
2870 check_curl_result(res, "DOWNLOAD cannot set write function: ");
2872 res = ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
2873 cmFileCommandCurlDebugCallback);
2874 check_curl_result(res, "DOWNLOAD cannot set debug function: ");
2876 // check to see if TLS verification is requested
2879 res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1);
2880 check_curl_result(res, "Unable to set TLS/SSL Verify on: ");
2884 res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
2885 check_curl_result(res, "Unable to set TLS/SSL Verify off: ");
2887 // check to see if a CAINFO file has been specified
2888 // command arg comes first
2889 if(cainfo && *cainfo)
2891 res = ::curl_easy_setopt(curl, CURLOPT_CAINFO, cainfo);
2892 check_curl_result(res, "Unable to set TLS/SSL Verify CAINFO: ");
2895 cmFileCommandVectorOfChar chunkDebug;
2897 res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&fout);
2898 check_curl_result(res, "DOWNLOAD cannot set write data: ");
2900 res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)&chunkDebug);
2901 check_curl_result(res, "DOWNLOAD cannot set debug data: ");
2903 res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
2904 check_curl_result(res, "DOWNLOAD cannot set follow-redirect option: ");
2906 if(verboseLog.size())
2908 res = ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
2909 check_curl_result(res, "DOWNLOAD cannot set verbose: ");
2914 res = ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout );
2915 check_curl_result(res, "DOWNLOAD cannot set timeout: ");
2918 if(inactivity_timeout > 0)
2920 // Give up if there is no progress for a long time.
2921 ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
2922 ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, inactivity_timeout);
2925 // Need the progress helper's scope to last through the duration of
2926 // the curl_easy_perform call... so this object is declared at function
2927 // scope intentionally, rather than inside the "if(showProgress)"
2930 cURLProgressHelper helper(this, "download");
2934 res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
2935 check_curl_result(res, "DOWNLOAD cannot set noprogress value: ");
2937 res = ::curl_easy_setopt(curl,
2938 CURLOPT_PROGRESSFUNCTION, cmFileDownloadProgressCallback);
2939 check_curl_result(res, "DOWNLOAD cannot set progress function: ");
2941 res = ::curl_easy_setopt(curl,
2942 CURLOPT_PROGRESSDATA, reinterpret_cast<void*>(&helper));
2943 check_curl_result(res, "DOWNLOAD cannot set progress data: ");
2946 res = ::curl_easy_perform(curl);
2948 /* always cleanup */
2950 ::curl_easy_cleanup(curl);
2952 if(statusVar.size())
2954 cmOStringStream result;
2955 result << (int)res << ";\"" << ::curl_easy_strerror(res) << "\"";
2956 this->Makefile->AddDefinition(statusVar.c_str(),
2957 result.str().c_str());
2960 ::curl_global_cleanup();
2962 // Explicitly flush/close so we can measure the md5 accurately.
2967 // Verify MD5 sum if requested:
2971 std::string actualHash = hash->HashFile(file.c_str());
2972 if (actualHash.size() == 0)
2974 this->SetError("DOWNLOAD cannot compute hash on downloaded file");
2978 if (expectedHash != actualHash)
2980 cmOStringStream oss;
2981 oss << "DOWNLOAD HASH mismatch" << std::endl
2982 << " for file: [" << file << "]" << std::endl
2983 << " expected hash: [" << expectedHash << "]" << std::endl
2984 << " actual hash: [" << actualHash << "]" << std::endl
2986 this->SetError(oss.str().c_str());
2991 if(chunkDebug.size())
2993 chunkDebug.push_back(0);
2994 if(CURLE_OPERATION_TIMEOUTED == res)
2996 std::string output = &*chunkDebug.begin();
2998 if(verboseLog.size())
3000 this->Makefile->AddDefinition(verboseLog.c_str(),
3001 &*chunkDebug.begin());
3005 this->Makefile->AddDefinition(verboseLog.c_str(),
3006 &*chunkDebug.begin());
3011 this->SetError("DOWNLOAD not supported by bootstrap cmake.");
3018 cmFileCommand::HandleUploadCommand(std::vector<std::string> const& args)
3020 #if defined(CMAKE_BUILD_WITH_CMAKE)
3023 this->SetError("UPLOAD must be called with at least three arguments.");
3026 std::vector<std::string>::const_iterator i = args.begin();
3028 std::string filename = *i;
3030 std::string url = *i;
3034 long inactivity_timeout = 0;
3036 std::string statusVar;
3037 bool showProgress = false;
3039 while(i != args.end())
3046 timeout = atol(i->c_str());
3050 this->SetError("UPLOAD missing time for TIMEOUT.");
3054 else if(*i == "INACTIVITY_TIMEOUT")
3059 inactivity_timeout = atol(i->c_str());
3063 this->SetError("UPLOAD missing time for INACTIVITY_TIMEOUT.");
3067 else if(*i == "LOG")
3070 if( i == args.end())
3072 this->SetError("UPLOAD missing VAR for LOG.");
3077 else if(*i == "STATUS")
3080 if( i == args.end())
3082 this->SetError("UPLOAD missing VAR for STATUS.");
3087 else if(*i == "SHOW_PROGRESS")
3089 showProgress = true;
3095 // Open file for reading:
3097 FILE *fin = fopen(filename.c_str(), "rb");
3100 std::string errStr = "UPLOAD cannot open file '";
3101 errStr += filename + "' for reading.";
3102 this->SetError(errStr.c_str());
3107 if(::stat(filename.c_str(), &st))
3109 std::string errStr = "UPLOAD cannot stat file '";
3110 errStr += filename + "'.";
3111 this->SetError(errStr.c_str());
3117 ::curl_global_init(CURL_GLOBAL_DEFAULT);
3118 curl = ::curl_easy_init();
3121 this->SetError("UPLOAD error initializing curl.");
3126 cURLEasyGuard g_curl(curl);
3128 // enable HTTP ERROR parsing
3129 ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
3132 res = ::curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
3133 check_curl_result(res, "UPLOAD cannot set upload flag: ");
3135 res = ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
3136 check_curl_result(res, "UPLOAD cannot set url: ");
3138 res = ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
3139 cmWriteToMemoryCallback);
3140 check_curl_result(res, "UPLOAD cannot set write function: ");
3142 res = ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
3143 cmFileCommandCurlDebugCallback);
3144 check_curl_result(res, "UPLOAD cannot set debug function: ");
3146 cmFileCommandVectorOfChar chunkResponse;
3147 cmFileCommandVectorOfChar chunkDebug;
3149 res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunkResponse);
3150 check_curl_result(res, "UPLOAD cannot set write data: ");
3152 res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)&chunkDebug);
3153 check_curl_result(res, "UPLOAD cannot set debug data: ");
3155 res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
3156 check_curl_result(res, "UPLOAD cannot set follow-redirect option: ");
3160 res = ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
3161 check_curl_result(res, "UPLOAD cannot set verbose: ");
3166 res = ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout );
3167 check_curl_result(res, "UPLOAD cannot set timeout: ");
3170 if(inactivity_timeout > 0)
3172 // Give up if there is no progress for a long time.
3173 ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
3174 ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, inactivity_timeout);
3177 // Need the progress helper's scope to last through the duration of
3178 // the curl_easy_perform call... so this object is declared at function
3179 // scope intentionally, rather than inside the "if(showProgress)"
3182 cURLProgressHelper helper(this, "upload");
3186 res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
3187 check_curl_result(res, "UPLOAD cannot set noprogress value: ");
3189 res = ::curl_easy_setopt(curl,
3190 CURLOPT_PROGRESSFUNCTION, cmFileUploadProgressCallback);
3191 check_curl_result(res, "UPLOAD cannot set progress function: ");
3193 res = ::curl_easy_setopt(curl,
3194 CURLOPT_PROGRESSDATA, reinterpret_cast<void*>(&helper));
3195 check_curl_result(res, "UPLOAD cannot set progress data: ");
3198 // now specify which file to upload
3199 res = ::curl_easy_setopt(curl, CURLOPT_INFILE, fin);
3200 check_curl_result(res, "UPLOAD cannot set input file: ");
3202 // and give the size of the upload (optional)
3203 res = ::curl_easy_setopt(curl,
3204 CURLOPT_INFILESIZE, static_cast<long>(st.st_size));
3205 check_curl_result(res, "UPLOAD cannot set input file size: ");
3207 res = ::curl_easy_perform(curl);
3209 /* always cleanup */
3211 ::curl_easy_cleanup(curl);
3213 if(statusVar.size())
3215 cmOStringStream result;
3216 result << (int)res << ";\"" << ::curl_easy_strerror(res) << "\"";
3217 this->Makefile->AddDefinition(statusVar.c_str(),
3218 result.str().c_str());
3221 ::curl_global_cleanup();
3230 if(chunkResponse.size())
3232 chunkResponse.push_back(0);
3233 log += "Response:\n";
3234 log += &*chunkResponse.begin();
3238 if(chunkDebug.size())
3240 chunkDebug.push_back(0);
3242 log += &*chunkDebug.begin();
3246 this->Makefile->AddDefinition(logVar.c_str(), log.c_str());
3251 this->SetError("UPLOAD not supported by bootstrap cmake.");
3256 //----------------------------------------------------------------------------
3257 void cmFileCommand::AddEvaluationFile(const std::string &inputName,
3258 const std::string &outputExpr,
3259 const std::string &condition,
3263 cmListFileBacktrace lfbt;
3264 this->Makefile->GetBacktrace(lfbt);
3266 cmGeneratorExpression outputGe(lfbt);
3267 cmsys::auto_ptr<cmCompiledGeneratorExpression> outputCge
3268 = outputGe.Parse(outputExpr);
3270 cmGeneratorExpression conditionGe(lfbt);
3271 cmsys::auto_ptr<cmCompiledGeneratorExpression> conditionCge
3272 = conditionGe.Parse(condition);
3274 this->Makefile->GetLocalGenerator()
3275 ->GetGlobalGenerator()->AddEvaluationFile(inputName,
3282 //----------------------------------------------------------------------------
3283 bool cmFileCommand::HandleGenerateCommand(
3284 std::vector<std::string> const& args)
3286 if (args.size() < 5)
3288 this->SetError("Incorrect arguments to GENERATE subcommand.");
3291 if (args[1] != "OUTPUT")
3293 this->SetError("Incorrect arguments to GENERATE subcommand.");
3296 std::string condition;
3297 if (args.size() > 5)
3299 if (args[5] != "CONDITION")
3301 this->SetError("Incorrect arguments to GENERATE subcommand.");
3304 if (args.size() != 7)
3306 this->SetError("Incorrect arguments to GENERATE subcommand.");
3309 condition = args[6];
3310 if (condition.empty())
3312 this->SetError("CONDITION of sub-command GENERATE must not be empty if "
3317 std::string output = args[2];
3318 const bool inputIsContent = args[3] != "INPUT";
3319 if (inputIsContent && args[3] != "CONTENT")
3321 this->SetError("Incorrect arguments to GENERATE subcommand.");
3324 std::string input = args[4];
3326 this->AddEvaluationFile(input, output, condition, inputIsContent);
3330 //----------------------------------------------------------------------------
3331 bool cmFileCommand::HandleTimestampCommand(
3332 std::vector<std::string> const& args)
3336 this->SetError("sub-command TIMESTAMP requires at least two arguments.");
3339 else if(args.size() > 5)
3341 this->SetError("sub-command TIMESTAMP takes at most four arguments.");
3345 unsigned int argsIndex = 1;
3347 const std::string& filename = args[argsIndex++];
3349 const std::string& outputVariable = args[argsIndex++];
3351 std::string formatString;
3352 if(args.size() > argsIndex && args[argsIndex] != "UTC")
3354 formatString = args[argsIndex++];
3357 bool utcFlag = false;
3358 if(args.size() > argsIndex)
3360 if(args[argsIndex] == "UTC")
3366 std::string e = " TIMESTAMP sub-command does not recognize option " +
3367 args[argsIndex] + ".";
3368 this->SetError(e.c_str());
3373 cmTimestamp timestamp;
3374 std::string result = timestamp.FileModificationTime(
3375 filename.c_str(), formatString, utcFlag);
3376 this->Makefile->AddDefinition(outputVariable.c_str(), result.c_str());