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);
171 std::string e = "does not recognize sub-command "+subCommand;
172 this->SetError(e.c_str());
176 //----------------------------------------------------------------------------
177 bool cmFileCommand::HandleWriteCommand(std::vector<std::string> const& args,
181 std::vector<std::string>::const_iterator i = args.begin();
183 i++; // Get rid of subcommand
185 std::string fileName = *i;
186 if ( !cmsys::SystemTools::FileIsFullPath(i->c_str()) )
188 fileName = this->Makefile->GetCurrentDirectory();
189 fileName += "/" + *i;
194 for(;i != args.end(); ++i)
198 if ( !this->Makefile->CanIWriteThisFile(fileName.c_str()) )
201 = "attempted to write a file: " + fileName +
202 " into a source directory.";
203 this->SetError(e.c_str());
204 cmSystemTools::SetFatalErrorOccured();
207 std::string dir = cmSystemTools::GetFilenamePath(fileName);
208 cmSystemTools::MakeDirectory(dir.c_str());
212 // Set permissions to writable
213 if ( cmSystemTools::GetPermissions(fileName.c_str(), mode) )
215 cmSystemTools::SetPermissions(fileName.c_str(),
216 #if defined( _MSC_VER ) || defined( __MINGW32__ )
218 #elif defined( __BORLANDC__ )
221 mode | S_IWUSR | S_IWGRP
225 // If GetPermissions fails, pretend like it is ok. File open will fail if
226 // the file is not writable
227 std::ofstream file(fileName.c_str(), append?std::ios::app: std::ios::out);
230 std::string error = "Internal CMake error when trying to open file: ";
231 error += fileName.c_str();
232 error += " for writing.";
233 this->SetError(error.c_str());
240 cmSystemTools::SetPermissions(fileName.c_str(), mode);
245 //----------------------------------------------------------------------------
246 bool cmFileCommand::HandleReadCommand(std::vector<std::string> const& args)
248 if ( args.size() < 3 )
250 this->SetError("READ must be called with at least two additional "
255 cmCommandArgumentsHelper argHelper;
256 cmCommandArgumentGroup group;
258 cmCAString readArg (&argHelper, "READ");
259 cmCAString fileNameArg (&argHelper, 0);
260 cmCAString resultArg (&argHelper, 0);
262 cmCAString offsetArg (&argHelper, "OFFSET", &group);
263 cmCAString limitArg (&argHelper, "LIMIT", &group);
264 cmCAEnabler hexOutputArg (&argHelper, "HEX", &group);
266 fileNameArg.Follows(&readArg);
267 resultArg.Follows(&fileNameArg);
268 group.Follows(&resultArg);
269 argHelper.Parse(&args, 0);
271 std::string fileName = fileNameArg.GetString();
272 if ( !cmsys::SystemTools::FileIsFullPath(fileName.c_str()) )
274 fileName = this->Makefile->GetCurrentDirectory();
275 fileName += "/" + fileNameArg.GetString();
278 std::string variable = resultArg.GetString();
280 // Open the specified file.
281 #if defined(_WIN32) || defined(__CYGWIN__)
282 std::ifstream file(fileName.c_str(), std::ios::in |
283 (hexOutputArg.IsEnabled() ? std::ios::binary : std::ios::in));
285 std::ifstream file(fileName.c_str(), std::ios::in);
290 std::string error = "Internal CMake error when trying to open file: ";
291 error += fileName.c_str();
292 error += " for reading.";
293 this->SetError(error.c_str());
299 if (limitArg.GetString().size() > 0)
301 sizeLimit = atoi(limitArg.GetCString());
304 // is there an offset?
306 if (offsetArg.GetString().size() > 0)
308 offset = atoi(offsetArg.GetCString());
311 file.seekg(offset, std::ios::beg); // explicit ios::beg for IBM VisualAge 6
315 if (hexOutputArg.IsEnabled())
317 // Convert part of the file into hex code
319 while((sizeLimit != 0) && (file.get(c)))
322 sprintf(hex, "%.2x", c&0xff);
333 bool has_newline = false;
334 while (sizeLimit != 0 &&
335 cmSystemTools::GetLineFromStream(file, line, &has_newline,
340 sizeLimit = sizeLimit - static_cast<long>(line.size());
357 this->Makefile->AddDefinition(variable.c_str(), output.c_str());
361 //----------------------------------------------------------------------------
362 bool cmFileCommand::HandleHashCommand(std::vector<std::string> const& args)
364 #if defined(CMAKE_BUILD_WITH_CMAKE)
368 e << args[0] << " requires a file name and output variable";
369 this->SetError(e.str().c_str());
373 cmsys::auto_ptr<cmCryptoHash> hash(cmCryptoHash::New(args[0].c_str()));
376 std::string out = hash->HashFile(args[1].c_str());
379 this->Makefile->AddDefinition(args[2].c_str(), out.c_str());
383 e << args[0] << " failed to read file \"" << args[1] << "\": "
384 << cmSystemTools::GetLastSystemError();
385 this->SetError(e.str().c_str());
390 e << args[0] << " not available during bootstrap";
391 this->SetError(e.str().c_str());
396 //----------------------------------------------------------------------------
397 bool cmFileCommand::HandleStringsCommand(std::vector<std::string> const& args)
401 this->SetError("STRINGS requires a file name and output variable");
405 // Get the file to read.
406 std::string fileName = args[1];
407 if(!cmsys::SystemTools::FileIsFullPath(fileName.c_str()))
409 fileName = this->Makefile->GetCurrentDirectory();
410 fileName += "/" + args[1];
413 // Get the variable in which to store the results.
414 std::string outVar = args[2];
416 // Parse the options.
425 unsigned int minlen = 0;
426 unsigned int maxlen = 0;
427 int limit_input = -1;
428 int limit_output = -1;
429 unsigned int limit_count = 0;
430 cmsys::RegularExpression regex;
431 bool have_regex = false;
432 bool newline_consume = false;
433 bool hex_conversion_enabled = true;
434 int arg_mode = arg_none;
435 for(unsigned int i=3; i < args.size(); ++i)
437 if(args[i] == "LIMIT_INPUT")
439 arg_mode = arg_limit_input;
441 else if(args[i] == "LIMIT_OUTPUT")
443 arg_mode = arg_limit_output;
445 else if(args[i] == "LIMIT_COUNT")
447 arg_mode = arg_limit_count;
449 else if(args[i] == "LENGTH_MINIMUM")
451 arg_mode = arg_length_minimum;
453 else if(args[i] == "LENGTH_MAXIMUM")
455 arg_mode = arg_length_maximum;
457 else if(args[i] == "REGEX")
459 arg_mode = arg_regex;
461 else if(args[i] == "NEWLINE_CONSUME")
463 newline_consume = true;
466 else if(args[i] == "NO_HEX_CONVERSION")
468 hex_conversion_enabled = false;
471 else if(arg_mode == arg_limit_input)
473 if(sscanf(args[i].c_str(), "%d", &limit_input) != 1 ||
477 e << "STRINGS option LIMIT_INPUT value \""
478 << args[i] << "\" is not an unsigned integer.";
479 this->SetError(e.str().c_str());
484 else if(arg_mode == arg_limit_output)
486 if(sscanf(args[i].c_str(), "%d", &limit_output) != 1 ||
490 e << "STRINGS option LIMIT_OUTPUT value \""
491 << args[i] << "\" is not an unsigned integer.";
492 this->SetError(e.str().c_str());
497 else if(arg_mode == arg_limit_count)
500 if(sscanf(args[i].c_str(), "%d", &count) != 1 || count < 0)
503 e << "STRINGS option LIMIT_COUNT value \""
504 << args[i] << "\" is not an unsigned integer.";
505 this->SetError(e.str().c_str());
511 else if(arg_mode == arg_length_minimum)
514 if(sscanf(args[i].c_str(), "%d", &len) != 1 || len < 0)
517 e << "STRINGS option LENGTH_MINIMUM value \""
518 << args[i] << "\" is not an unsigned integer.";
519 this->SetError(e.str().c_str());
525 else if(arg_mode == arg_length_maximum)
528 if(sscanf(args[i].c_str(), "%d", &len) != 1 || len < 0)
531 e << "STRINGS option LENGTH_MAXIMUM value \""
532 << args[i] << "\" is not an unsigned integer.";
533 this->SetError(e.str().c_str());
539 else if(arg_mode == arg_regex)
541 if(!regex.compile(args[i].c_str()))
544 e << "STRINGS option REGEX value \""
545 << args[i] << "\" could not be compiled.";
546 this->SetError(e.str().c_str());
555 e << "STRINGS given unknown argument \""
557 this->SetError(e.str().c_str());
562 if (hex_conversion_enabled)
564 // TODO: should work without temp file, but just on a memory buffer
565 std::string binaryFileName = this->Makefile->GetCurrentOutputDirectory();
566 binaryFileName += cmake::GetCMakeFilesDirectory();
567 binaryFileName += "/FileCommandStringsBinaryFile";
568 if(cmHexFileConverter::TryConvert(fileName.c_str(),binaryFileName.c_str()))
570 fileName = binaryFileName;
574 // Open the specified file.
575 #if defined(_WIN32) || defined(__CYGWIN__)
576 std::ifstream fin(fileName.c_str(), std::ios::in | std::ios::binary);
578 std::ifstream fin(fileName.c_str(), std::ios::in);
583 e << "STRINGS file \"" << fileName << "\" cannot be read.";
584 this->SetError(e.str().c_str());
588 // Parse strings out of the file.
590 std::vector<std::string> strings;
593 while((!limit_count || strings.size() < limit_count) &&
594 (limit_input < 0 || static_cast<int>(fin.tellg()) < limit_input) &&
595 (c = fin.get(), fin))
597 if(c == '\n' && !newline_consume)
599 // The current line has been terminated. Check if the current
600 // string matches the requirements. The length may now be as
601 // low as zero since blank lines are allowed.
602 if(s.length() >= minlen &&
603 (!have_regex || regex.find(s.c_str())))
605 output_size += static_cast<int>(s.size()) + 1;
606 if(limit_output >= 0 && output_size >= limit_output)
611 strings.push_back(s);
614 // Reset the string to empty.
619 // Ignore CR character to make output always have UNIX newlines.
621 else if((c >= 0x20 && c < 0x7F) || c == '\t' ||
622 (c == '\n' && newline_consume))
624 // This is an ASCII character that may be part of a string.
625 // Cast added to avoid compiler warning. Cast is ok because
626 // c is guaranteed to fit in char by the above if...
627 s += static_cast<char>(c);
631 // TODO: Support ENCODING option. See issue #10519.
632 // A non-string character has been found. Check if the current
633 // string matches the requirements. We require that the length
634 // be at least one no matter what the user specified.
635 if(s.length() >= minlen && s.length() >= 1 &&
636 (!have_regex || regex.find(s.c_str())))
638 output_size += static_cast<int>(s.size()) + 1;
639 if(limit_output >= 0 && output_size >= limit_output)
644 strings.push_back(s);
647 // Reset the string to empty.
651 // Terminate a string if the maximum length is reached.
652 if(maxlen > 0 && s.size() == maxlen)
654 if(s.length() >= minlen &&
655 (!have_regex || regex.find(s.c_str())))
657 output_size += static_cast<int>(s.size()) + 1;
658 if(limit_output >= 0 && output_size >= limit_output)
663 strings.push_back(s);
669 // If there is a non-empty current string we have hit the end of the
670 // input file or the input size limit. Check if the current string
671 // matches the requirements.
672 if((!limit_count || strings.size() < limit_count) &&
673 !s.empty() && s.length() >= minlen &&
674 (!have_regex || regex.find(s.c_str())))
676 output_size += static_cast<int>(s.size()) + 1;
677 if(limit_output < 0 || output_size < limit_output)
679 strings.push_back(s);
683 // Encode the result in a CMake list.
684 const char* sep = "";
686 for(std::vector<std::string>::const_iterator si = strings.begin();
687 si != strings.end(); ++si)
689 // Separate the strings in the output to make it a list.
693 // Store the string in the output, but escape semicolons to
694 // make sure it is a list.
695 std::string const& sr = *si;
696 for(unsigned int i=0; i < sr.size(); ++i)
706 // Save the output in a makefile variable.
707 this->Makefile->AddDefinition(outVar.c_str(), output.c_str());
711 //----------------------------------------------------------------------------
712 bool cmFileCommand::HandleGlobCommand(std::vector<std::string> const& args,
715 // File commands has at least one argument
716 assert(args.size() > 1);
718 std::vector<std::string>::const_iterator i = args.begin();
720 i++; // Get rid of subcommand
722 std::string variable = *i;
725 g.SetRecurse(recurse);
727 bool explicitFollowSymlinks = false;
728 cmPolicies::PolicyStatus status =
729 this->Makefile->GetPolicyStatus(cmPolicies::CMP0009);
734 case cmPolicies::NEW:
735 g.RecurseThroughSymlinksOff();
737 case cmPolicies::OLD:
738 case cmPolicies::WARN:
739 case cmPolicies::REQUIRED_IF_USED:
740 case cmPolicies::REQUIRED_ALWAYS:
741 g.RecurseThroughSymlinksOn();
746 std::string output = "";
748 for ( ; i != args.end(); ++i )
750 if ( recurse && (*i == "FOLLOW_SYMLINKS") )
752 explicitFollowSymlinks = true;
753 g.RecurseThroughSymlinksOn();
755 if ( i == args.end() )
758 "GLOB_RECURSE requires a glob expression after FOLLOW_SYMLINKS");
763 if ( *i == "RELATIVE" )
765 ++i; // skip RELATIVE
766 if ( i == args.end() )
768 this->SetError("GLOB requires a directory after the RELATIVE tag");
771 g.SetRelative(i->c_str());
775 this->SetError("GLOB requires a glob expression after the directory");
780 if ( !cmsys::SystemTools::FileIsFullPath(i->c_str()) )
782 std::string expr = this->Makefile->GetCurrentDirectory();
783 // Handle script mode
784 if ( expr.size() > 0 )
799 std::vector<std::string>::size_type cc;
800 std::vector<std::string>& files = g.GetFiles();
801 for ( cc = 0; cc < files.size(); cc ++ )
812 if(recurse && !explicitFollowSymlinks)
816 case cmPolicies::NEW:
817 // Correct behavior, yay!
819 case cmPolicies::OLD:
820 // Probably not really the expected behavior, but the author explicitly
821 // asked for the old behavior... no warning.
822 case cmPolicies::WARN:
823 // Possibly unexpected old behavior *and* we actually traversed
824 // symlinks without being explicitly asked to: warn the author.
825 if(g.GetFollowedSymlinkCount() != 0)
827 this->Makefile->IssueMessage(cmake::AUTHOR_WARNING,
828 this->Makefile->GetPolicies()->
829 GetPolicyWarning(cmPolicies::CMP0009));
832 case cmPolicies::REQUIRED_IF_USED:
833 case cmPolicies::REQUIRED_ALWAYS:
834 this->SetError("policy CMP0009 error");
835 this->Makefile->IssueMessage(cmake::FATAL_ERROR,
836 this->Makefile->GetPolicies()->
837 GetRequiredPolicyError(cmPolicies::CMP0009));
842 this->Makefile->AddDefinition(variable.c_str(), output.c_str());
846 //----------------------------------------------------------------------------
847 bool cmFileCommand::HandleMakeDirectoryCommand(
848 std::vector<std::string> const& args)
850 // File command has at least one argument
851 assert(args.size() > 1);
853 std::vector<std::string>::const_iterator i = args.begin();
855 i++; // Get rid of subcommand
858 for ( ; i != args.end(); ++i )
860 const std::string* cdir = &(*i);
861 if ( !cmsys::SystemTools::FileIsFullPath(i->c_str()) )
863 expr = this->Makefile->GetCurrentDirectory();
867 if ( !this->Makefile->CanIWriteThisFile(cdir->c_str()) )
869 std::string e = "attempted to create a directory: " + *cdir
870 + " into a source directory.";
871 this->SetError(e.c_str());
872 cmSystemTools::SetFatalErrorOccured();
875 if ( !cmSystemTools::MakeDirectory(cdir->c_str()) )
877 std::string error = "problem creating directory: " + *cdir;
878 this->SetError(error.c_str());
885 //----------------------------------------------------------------------------
887 cmFileCommand::HandleDifferentCommand(std::vector<std::string> const& args)
890 FILE(DIFFERENT <variable> FILES <lhs> <rhs>)
893 // Evaluate arguments.
894 const char* file_lhs = 0;
895 const char* file_rhs = 0;
897 enum Doing { DoingNone, DoingVar, DoingFileLHS, DoingFileRHS };
898 Doing doing = DoingVar;
899 for(unsigned int i=1; i < args.size(); ++i)
901 if(args[i] == "FILES")
903 doing = DoingFileLHS;
905 else if(doing == DoingVar)
907 var = args[i].c_str();
910 else if(doing == DoingFileLHS)
912 file_lhs = args[i].c_str();
913 doing = DoingFileRHS;
915 else if(doing == DoingFileRHS)
917 file_rhs = args[i].c_str();
923 e << "DIFFERENT given unknown argument " << args[i];
924 this->SetError(e.str().c_str());
930 this->SetError("DIFFERENT not given result variable name.");
933 if(!file_lhs || !file_rhs)
935 this->SetError("DIFFERENT not given FILES option with two file names.");
939 // Compare the files.
941 cmSystemTools::FilesDiffer(file_lhs, file_rhs)? "1" : "0";
942 this->Makefile->AddDefinition(var, result);
946 //----------------------------------------------------------------------------
947 // File installation helper class.
950 cmFileCopier(cmFileCommand* command, const char* name = "COPY"):
951 FileCommand(command),
952 Makefile(command->GetMakefile()),
955 MatchlessFiles(true),
959 UseGivenPermissionsFile(false),
960 UseGivenPermissionsDir(false),
961 UseSourcePermissions(true),
965 virtual ~cmFileCopier() {}
967 bool Run(std::vector<std::string> const& args);
970 cmFileCommand* FileCommand;
971 cmMakefile* Makefile;
974 cmFileTimeComparison FileTimes;
976 // Whether to install a file not matching any expression.
979 // Permissions for files and directories installed by this object.
980 mode_t FilePermissions;
981 mode_t DirPermissions;
983 // Properties set by pattern and regex match rules.
984 struct MatchProperties
988 MatchProperties(): Exclude(false), Permissions(0) {}
991 friend struct MatchRule;
994 cmsys::RegularExpression Regex;
995 MatchProperties Properties;
996 std::string RegexString;
997 MatchRule(std::string const& regex):
998 Regex(regex.c_str()), RegexString(regex) {}
1000 std::vector<MatchRule> MatchRules;
1002 // Get the properties from rules matching this input file.
1003 MatchProperties CollectMatchProperties(const char* file)
1005 // Match rules are case-insensitive on some platforms.
1006 #if defined(_WIN32) || defined(__APPLE__) || defined(__CYGWIN__)
1007 std::string lower = cmSystemTools::LowerCase(file);
1008 const char* file_to_match = lower.c_str();
1010 const char* file_to_match = file;
1013 // Collect properties from all matching rules.
1014 bool matched = false;
1015 MatchProperties result;
1016 for(std::vector<MatchRule>::iterator mr = this->MatchRules.begin();
1017 mr != this->MatchRules.end(); ++mr)
1019 if(mr->Regex.find(file_to_match))
1022 result.Exclude |= mr->Properties.Exclude;
1023 result.Permissions |= mr->Properties.Permissions;
1026 if(!matched && !this->MatchlessFiles)
1028 result.Exclude = !cmSystemTools::FileIsDirectory(file);
1033 bool SetPermissions(const char* toFile, mode_t permissions)
1035 if(permissions && !cmSystemTools::SetPermissions(toFile, permissions))
1038 e << this->Name << " cannot set permissions on \"" << toFile << "\"";
1039 this->FileCommand->SetError(e.str().c_str());
1045 // Translate an argument to a permissions bit.
1046 bool CheckPermissions(std::string const& arg, mode_t& permissions)
1048 if(arg == "OWNER_READ") { permissions |= mode_owner_read; }
1049 else if(arg == "OWNER_WRITE") { permissions |= mode_owner_write; }
1050 else if(arg == "OWNER_EXECUTE") { permissions |= mode_owner_execute; }
1051 else if(arg == "GROUP_READ") { permissions |= mode_group_read; }
1052 else if(arg == "GROUP_WRITE") { permissions |= mode_group_write; }
1053 else if(arg == "GROUP_EXECUTE") { permissions |= mode_group_execute; }
1054 else if(arg == "WORLD_READ") { permissions |= mode_world_read; }
1055 else if(arg == "WORLD_WRITE") { permissions |= mode_world_write; }
1056 else if(arg == "WORLD_EXECUTE") { permissions |= mode_world_execute; }
1057 else if(arg == "SETUID") { permissions |= mode_setuid; }
1058 else if(arg == "SETGID") { permissions |= mode_setgid; }
1062 e << this->Name << " given invalid permission \"" << arg << "\".";
1063 this->FileCommand->SetError(e.str().c_str());
1069 bool InstallSymlink(const char* fromFile, const char* toFile);
1070 bool InstallFile(const char* fromFile, const char* toFile,
1071 MatchProperties const& match_properties);
1072 bool InstallDirectory(const char* source, const char* destination,
1073 MatchProperties const& match_properties);
1074 virtual bool Install(const char* fromFile, const char* toFile);
1075 virtual std::string const& ToName(std::string const& fromName)
1076 { return fromName; }
1084 virtual void ReportCopy(const char*, Type, bool) {}
1085 virtual bool ReportMissing(const char* fromFile)
1087 // The input file does not exist and installation is not optional.
1089 e << this->Name << " cannot find \"" << fromFile << "\".";
1090 this->FileCommand->SetError(e.str().c_str());
1094 MatchRule* CurrentMatchRule;
1095 bool UseGivenPermissionsFile;
1096 bool UseGivenPermissionsDir;
1097 bool UseSourcePermissions;
1098 std::string Destination;
1099 std::vector<std::string> Files;
1102 virtual bool Parse(std::vector<std::string> const& args);
1111 DoingPermissionsFile,
1112 DoingPermissionsDir,
1113 DoingPermissionsMatch,
1116 virtual bool CheckKeyword(std::string const& arg);
1117 virtual bool CheckValue(std::string const& arg);
1119 void NotBeforeMatch(std::string const& arg)
1122 e << "option " << arg << " may not appear before PATTERN or REGEX.";
1123 this->FileCommand->SetError(e.str().c_str());
1124 this->Doing = DoingError;
1126 void NotAfterMatch(std::string const& arg)
1129 e << "option " << arg << " may not appear after PATTERN or REGEX.";
1130 this->FileCommand->SetError(e.str().c_str());
1131 this->Doing = DoingError;
1133 virtual void DefaultFilePermissions()
1135 // Use read/write permissions.
1136 this->FilePermissions = 0;
1137 this->FilePermissions |= mode_owner_read;
1138 this->FilePermissions |= mode_owner_write;
1139 this->FilePermissions |= mode_group_read;
1140 this->FilePermissions |= mode_world_read;
1142 virtual void DefaultDirectoryPermissions()
1144 // Use read/write/executable permissions.
1145 this->DirPermissions = 0;
1146 this->DirPermissions |= mode_owner_read;
1147 this->DirPermissions |= mode_owner_write;
1148 this->DirPermissions |= mode_owner_execute;
1149 this->DirPermissions |= mode_group_read;
1150 this->DirPermissions |= mode_group_execute;
1151 this->DirPermissions |= mode_world_read;
1152 this->DirPermissions |= mode_world_execute;
1156 //----------------------------------------------------------------------------
1157 bool cmFileCopier::Parse(std::vector<std::string> const& args)
1159 this->Doing = DoingFiles;
1160 for(unsigned int i=1; i < args.size(); ++i)
1162 // Check this argument.
1163 if(!this->CheckKeyword(args[i]) &&
1164 !this->CheckValue(args[i]))
1167 e << "called with unknown argument \"" << args[i] << "\".";
1168 this->FileCommand->SetError(e.str().c_str());
1172 // Quit if an argument is invalid.
1173 if(this->Doing == DoingError)
1179 // Require a destination.
1180 if(this->Destination.empty())
1183 e << this->Name << " given no DESTINATION";
1184 this->FileCommand->SetError(e.str().c_str());
1188 // If file permissions were not specified set default permissions.
1189 if(!this->UseGivenPermissionsFile && !this->UseSourcePermissions)
1191 this->DefaultFilePermissions();
1194 // If directory permissions were not specified set default permissions.
1195 if(!this->UseGivenPermissionsDir && !this->UseSourcePermissions)
1197 this->DefaultDirectoryPermissions();
1203 //----------------------------------------------------------------------------
1204 bool cmFileCopier::CheckKeyword(std::string const& arg)
1206 if(arg == "DESTINATION")
1208 if(this->CurrentMatchRule)
1210 this->NotAfterMatch(arg);
1214 this->Doing = DoingDestination;
1217 else if(arg == "PATTERN")
1219 this->Doing = DoingPattern;
1221 else if(arg == "REGEX")
1223 this->Doing = DoingRegex;
1225 else if(arg == "EXCLUDE")
1227 // Add this property to the current match rule.
1228 if(this->CurrentMatchRule)
1230 this->CurrentMatchRule->Properties.Exclude = true;
1231 this->Doing = DoingNone;
1235 this->NotBeforeMatch(arg);
1238 else if(arg == "PERMISSIONS")
1240 if(this->CurrentMatchRule)
1242 this->Doing = DoingPermissionsMatch;
1246 this->NotBeforeMatch(arg);
1249 else if(arg == "FILE_PERMISSIONS")
1251 if(this->CurrentMatchRule)
1253 this->NotAfterMatch(arg);
1257 this->Doing = DoingPermissionsFile;
1258 this->UseGivenPermissionsFile = true;
1261 else if(arg == "DIRECTORY_PERMISSIONS")
1263 if(this->CurrentMatchRule)
1265 this->NotAfterMatch(arg);
1269 this->Doing = DoingPermissionsDir;
1270 this->UseGivenPermissionsDir = true;
1273 else if(arg == "USE_SOURCE_PERMISSIONS")
1275 if(this->CurrentMatchRule)
1277 this->NotAfterMatch(arg);
1281 this->Doing = DoingNone;
1282 this->UseSourcePermissions = true;
1285 else if(arg == "NO_SOURCE_PERMISSIONS")
1287 if(this->CurrentMatchRule)
1289 this->NotAfterMatch(arg);
1293 this->Doing = DoingNone;
1294 this->UseSourcePermissions = false;
1297 else if(arg == "FILES_MATCHING")
1299 if(this->CurrentMatchRule)
1301 this->NotAfterMatch(arg);
1305 this->Doing = DoingNone;
1306 this->MatchlessFiles = false;
1316 //----------------------------------------------------------------------------
1317 bool cmFileCopier::CheckValue(std::string const& arg)
1322 if(arg.empty() || cmSystemTools::FileIsFullPath(arg.c_str()))
1324 this->Files.push_back(arg);
1328 std::string file = this->Makefile->GetCurrentDirectory();
1330 this->Files.push_back(file);
1333 case DoingDestination:
1334 if(arg.empty() || cmSystemTools::FileIsFullPath(arg.c_str()))
1336 this->Destination = arg;
1340 this->Destination = this->Makefile->GetCurrentOutputDirectory();
1341 this->Destination += "/" + arg;
1343 this->Doing = DoingNone;
1347 // Convert the pattern to a regular expression. Require a
1348 // leading slash and trailing end-of-string in the matched
1349 // string to make sure the pattern matches only whole file
1351 std::string regex = "/";
1352 regex += cmsys::Glob::PatternToRegex(arg, false);
1354 this->MatchRules.push_back(MatchRule(regex));
1355 this->CurrentMatchRule = &*(this->MatchRules.end()-1);
1356 if(this->CurrentMatchRule->Regex.is_valid())
1358 this->Doing = DoingNone;
1363 e << "could not compile PATTERN \"" << arg << "\".";
1364 this->FileCommand->SetError(e.str().c_str());
1365 this->Doing = DoingError;
1370 this->MatchRules.push_back(MatchRule(arg));
1371 this->CurrentMatchRule = &*(this->MatchRules.end()-1);
1372 if(this->CurrentMatchRule->Regex.is_valid())
1374 this->Doing = DoingNone;
1379 e << "could not compile REGEX \"" << arg << "\".";
1380 this->FileCommand->SetError(e.str().c_str());
1381 this->Doing = DoingError;
1384 case DoingPermissionsFile:
1385 if(!this->CheckPermissions(arg, this->FilePermissions))
1387 this->Doing = DoingError;
1390 case DoingPermissionsDir:
1391 if(!this->CheckPermissions(arg, this->DirPermissions))
1393 this->Doing = DoingError;
1396 case DoingPermissionsMatch:
1397 if(!this->CheckPermissions(
1398 arg, this->CurrentMatchRule->Properties.Permissions))
1400 this->Doing = DoingError;
1409 //----------------------------------------------------------------------------
1410 bool cmFileCopier::Run(std::vector<std::string> const& args)
1412 if(!this->Parse(args))
1417 std::vector<std::string> const& files = this->Files;
1418 for(std::vector<std::string>::size_type i = 0; i < files.size(); ++i)
1420 // Split the input file into its directory and name components.
1421 std::vector<std::string> fromPathComponents;
1422 cmSystemTools::SplitPath(files[i].c_str(), fromPathComponents);
1423 std::string fromName = *(fromPathComponents.end()-1);
1424 std::string fromDir = cmSystemTools::JoinPath(fromPathComponents.begin(),
1425 fromPathComponents.end()-1);
1427 // Compute the full path to the destination file.
1428 std::string toFile = this->Destination;
1429 std::string const& toName = this->ToName(fromName);
1436 // Construct the full path to the source file. The file name may
1437 // have been changed above.
1438 std::string fromFile = fromDir;
1439 if(!fromName.empty())
1442 fromFile += fromName;
1445 if(!this->Install(fromFile.c_str(), toFile.c_str()))
1453 //----------------------------------------------------------------------------
1454 bool cmFileCopier::Install(const char* fromFile, const char* toFile)
1459 e << "INSTALL encountered an empty string input file name.";
1460 this->FileCommand->SetError(e.str().c_str());
1464 // Collect any properties matching this file name.
1465 MatchProperties match_properties = this->CollectMatchProperties(fromFile);
1467 // Skip the file if it is excluded.
1468 if(match_properties.Exclude)
1473 if(cmSystemTools::SameFile(fromFile, toFile))
1477 else if(cmSystemTools::FileIsSymlink(fromFile))
1479 return this->InstallSymlink(fromFile, toFile);
1481 else if(cmSystemTools::FileIsDirectory(fromFile))
1483 return this->InstallDirectory(fromFile, toFile, match_properties);
1485 else if(cmSystemTools::FileExists(fromFile))
1487 return this->InstallFile(fromFile, toFile, match_properties);
1489 return this->ReportMissing(fromFile);
1492 //----------------------------------------------------------------------------
1493 bool cmFileCopier::InstallSymlink(const char* fromFile, const char* toFile)
1495 // Read the original symlink.
1496 std::string symlinkTarget;
1497 if(!cmSystemTools::ReadSymlink(fromFile, symlinkTarget))
1500 e << this->Name << " cannot read symlink \"" << fromFile
1501 << "\" to duplicate at \"" << toFile << "\".";
1502 this->FileCommand->SetError(e.str().c_str());
1506 // Compare the symlink value to that at the destination if not
1507 // always installing.
1511 std::string oldSymlinkTarget;
1512 if(cmSystemTools::ReadSymlink(toFile, oldSymlinkTarget))
1514 if(symlinkTarget == oldSymlinkTarget)
1521 // Inform the user about this file installation.
1522 this->ReportCopy(toFile, TypeLink, copy);
1526 // Remove the destination file so we can always create the symlink.
1527 cmSystemTools::RemoveFile(toFile);
1529 // Create the symlink.
1530 if(!cmSystemTools::CreateSymlink(symlinkTarget.c_str(), toFile))
1533 e << this->Name << " cannot duplicate symlink \"" << fromFile
1534 << "\" at \"" << toFile << "\".";
1535 this->FileCommand->SetError(e.str().c_str());
1543 //----------------------------------------------------------------------------
1544 bool cmFileCopier::InstallFile(const char* fromFile, const char* toFile,
1545 MatchProperties const& match_properties)
1547 // Determine whether we will copy the file.
1551 // If both files exist with the same time do not copy.
1552 if(!this->FileTimes.FileTimesDiffer(fromFile, toFile))
1558 // Inform the user about this file installation.
1559 this->ReportCopy(toFile, TypeFile, copy);
1562 if(copy && !cmSystemTools::CopyAFile(fromFile, toFile, true))
1565 e << this->Name << " cannot copy file \"" << fromFile
1566 << "\" to \"" << toFile << "\".";
1567 this->FileCommand->SetError(e.str().c_str());
1571 // Set the file modification time of the destination file.
1572 if(copy && !this->Always)
1574 // Add write permission so we can set the file time.
1575 // Permissions are set unconditionally below anyway.
1577 if(cmSystemTools::GetPermissions(toFile, perm))
1579 cmSystemTools::SetPermissions(toFile, perm | mode_owner_write);
1581 if (!cmSystemTools::CopyFileTime(fromFile, toFile))
1584 e << this->Name << " cannot set modification time on \""
1586 this->FileCommand->SetError(e.str().c_str());
1591 // Set permissions of the destination file.
1592 mode_t permissions = (match_properties.Permissions?
1593 match_properties.Permissions : this->FilePermissions);
1596 // No permissions were explicitly provided but the user requested
1597 // that the source file permissions be used.
1598 cmSystemTools::GetPermissions(fromFile, permissions);
1600 return this->SetPermissions(toFile, permissions);
1603 //----------------------------------------------------------------------------
1604 bool cmFileCopier::InstallDirectory(const char* source,
1605 const char* destination,
1606 MatchProperties const& match_properties)
1608 // Inform the user about this directory installation.
1609 this->ReportCopy(destination, TypeDir, true);
1611 // Make sure the destination directory exists.
1612 if(!cmSystemTools::MakeDirectory(destination))
1615 e << this->Name << " cannot make directory \"" << destination << "\": "
1616 << cmSystemTools::GetLastSystemError();
1617 this->FileCommand->SetError(e.str().c_str());
1621 // Compute the requested permissions for the destination directory.
1622 mode_t permissions = (match_properties.Permissions?
1623 match_properties.Permissions : this->DirPermissions);
1626 // No permissions were explicitly provided but the user requested
1627 // that the source directory permissions be used.
1628 cmSystemTools::GetPermissions(source, permissions);
1631 // Compute the set of permissions required on this directory to
1632 // recursively install files and subdirectories safely.
1633 mode_t required_permissions =
1634 mode_owner_read | mode_owner_write | mode_owner_execute;
1636 // If the required permissions are specified it is safe to set the
1637 // final permissions now. Otherwise we must add the required
1638 // permissions temporarily during file installation.
1639 mode_t permissions_before = 0;
1640 mode_t permissions_after = 0;
1641 if((permissions & required_permissions) == required_permissions)
1643 permissions_before = permissions;
1647 permissions_before = permissions | required_permissions;
1648 permissions_after = permissions;
1651 // Set the required permissions of the destination directory.
1652 if(!this->SetPermissions(destination, permissions_before))
1657 // Load the directory contents to traverse it recursively.
1658 cmsys::Directory dir;
1659 if(source && *source)
1663 unsigned long numFiles = static_cast<unsigned long>(dir.GetNumberOfFiles());
1664 for(unsigned long fileNum = 0; fileNum < numFiles; ++fileNum)
1666 if(!(strcmp(dir.GetFile(fileNum), ".") == 0 ||
1667 strcmp(dir.GetFile(fileNum), "..") == 0))
1669 cmsys_stl::string fromPath = source;
1671 fromPath += dir.GetFile(fileNum);
1672 std::string toPath = destination;
1674 toPath += dir.GetFile(fileNum);
1675 if(!this->Install(fromPath.c_str(), toPath.c_str()))
1682 // Set the requested permissions of the destination directory.
1683 return this->SetPermissions(destination, permissions_after);
1686 //----------------------------------------------------------------------------
1687 bool cmFileCommand::HandleCopyCommand(std::vector<std::string> const& args)
1689 cmFileCopier copier(this);
1690 return copier.Run(args);
1693 //----------------------------------------------------------------------------
1694 struct cmFileInstaller: public cmFileCopier
1696 cmFileInstaller(cmFileCommand* command):
1697 cmFileCopier(command, "INSTALL"),
1698 InstallType(cmInstallType_FILES),
1702 // Installation does not use source permissions by default.
1703 this->UseSourcePermissions = false;
1704 // Check whether to copy files always or only if they have changed.
1706 cmSystemTools::IsOn(cmSystemTools::GetEnv("CMAKE_INSTALL_ALWAYS"));
1707 // Get the current manifest.
1709 this->Makefile->GetSafeDefinition("CMAKE_INSTALL_MANIFEST_FILES");
1713 // Save the updated install manifest.
1714 this->Makefile->AddDefinition("CMAKE_INSTALL_MANIFEST_FILES",
1715 this->Manifest.c_str());
1719 cmInstallType InstallType;
1724 std::string Manifest;
1725 void ManifestAppend(std::string const& file)
1727 this->Manifest += ";";
1728 this->Manifest += file.substr(this->DestDirLength);
1731 virtual std::string const& ToName(std::string const& fromName)
1732 { return this->Rename.empty()? fromName : this->Rename; }
1734 virtual void ReportCopy(const char* toFile, Type type, bool copy)
1736 std::string message = (copy? "Installing: " : "Up-to-date: ");
1738 this->Makefile->DisplayStatus(message.c_str(), -1);
1741 // Add the file to the manifest.
1742 this->ManifestAppend(toFile);
1745 virtual bool ReportMissing(const char* fromFile)
1747 return (this->Optional ||
1748 this->cmFileCopier::ReportMissing(fromFile));
1750 virtual bool Install(const char* fromFile, const char* toFile)
1752 // Support installing from empty source to make a directory.
1753 if(this->InstallType == cmInstallType_DIRECTORY && !*fromFile)
1755 return this->InstallDirectory(fromFile, toFile, MatchProperties());
1757 return this->cmFileCopier::Install(fromFile, toFile);
1760 virtual bool Parse(std::vector<std::string> const& args);
1763 DoingType = DoingLast1,
1767 virtual bool CheckKeyword(std::string const& arg);
1768 virtual bool CheckValue(std::string const& arg);
1769 virtual void DefaultFilePermissions()
1771 this->cmFileCopier::DefaultFilePermissions();
1772 // Add execute permissions based on the target type.
1773 switch(this->InstallType)
1775 case cmInstallType_SHARED_LIBRARY:
1776 case cmInstallType_MODULE_LIBRARY:
1777 if(this->Makefile->IsOn("CMAKE_INSTALL_SO_NO_EXE"))
1781 case cmInstallType_EXECUTABLE:
1782 case cmInstallType_PROGRAMS:
1783 this->FilePermissions |= mode_owner_execute;
1784 this->FilePermissions |= mode_group_execute;
1785 this->FilePermissions |= mode_world_execute;
1790 bool GetTargetTypeFromString(const std::string& stype);
1791 bool HandleInstallDestination();
1794 //----------------------------------------------------------------------------
1795 bool cmFileInstaller::Parse(std::vector<std::string> const& args)
1797 if(!this->cmFileCopier::Parse(args))
1802 if(!this->Rename.empty())
1804 if(this->InstallType != cmInstallType_FILES &&
1805 this->InstallType != cmInstallType_PROGRAMS)
1807 this->FileCommand->SetError("INSTALL option RENAME may be used "
1808 "only with FILES or PROGRAMS.");
1811 if(this->Files.size() > 1)
1813 this->FileCommand->SetError("INSTALL option RENAME may be used "
1814 "only with one file.");
1819 if(!this->HandleInstallDestination())
1827 //----------------------------------------------------------------------------
1828 bool cmFileInstaller::CheckKeyword(std::string const& arg)
1832 if(this->CurrentMatchRule)
1834 this->NotAfterMatch(arg);
1838 this->Doing = DoingType;
1841 else if(arg == "FILES")
1843 if(this->CurrentMatchRule)
1845 this->NotAfterMatch(arg);
1849 this->Doing = DoingFiles;
1852 else if(arg == "RENAME")
1854 if(this->CurrentMatchRule)
1856 this->NotAfterMatch(arg);
1860 this->Doing = DoingRename;
1863 else if(arg == "OPTIONAL")
1865 if(this->CurrentMatchRule)
1867 this->NotAfterMatch(arg);
1871 this->Doing = DoingNone;
1872 this->Optional = true;
1875 else if(arg == "PERMISSIONS")
1877 if(this->CurrentMatchRule)
1879 this->Doing = DoingPermissionsMatch;
1883 // file(INSTALL) aliases PERMISSIONS to FILE_PERMISSIONS
1884 this->Doing = DoingPermissionsFile;
1885 this->UseGivenPermissionsFile = true;
1888 else if(arg == "DIR_PERMISSIONS")
1890 if(this->CurrentMatchRule)
1892 this->NotAfterMatch(arg);
1896 // file(INSTALL) aliases DIR_PERMISSIONS to DIRECTORY_PERMISSIONS
1897 this->Doing = DoingPermissionsDir;
1898 this->UseGivenPermissionsDir = true;
1901 else if(arg == "COMPONENTS" || arg == "CONFIGURATIONS" ||
1902 arg == "PROPERTIES")
1905 e << "INSTALL called with old-style " << arg << " argument. "
1906 << "This script was generated with an older version of CMake. "
1907 << "Re-run this cmake version on your build tree.";
1908 this->FileCommand->SetError(e.str().c_str());
1909 this->Doing = DoingError;
1913 return this->cmFileCopier::CheckKeyword(arg);
1918 //----------------------------------------------------------------------------
1919 bool cmFileInstaller::CheckValue(std::string const& arg)
1924 if(!this->GetTargetTypeFromString(arg))
1926 this->Doing = DoingError;
1933 return this->cmFileCopier::CheckValue(arg);
1938 //----------------------------------------------------------------------------
1939 bool cmFileInstaller
1940 ::GetTargetTypeFromString(const std::string& stype)
1942 if ( stype == "EXECUTABLE" )
1944 this->InstallType = cmInstallType_EXECUTABLE;
1946 else if ( stype == "FILE" )
1948 this->InstallType = cmInstallType_FILES;
1950 else if ( stype == "PROGRAM" )
1952 this->InstallType = cmInstallType_PROGRAMS;
1954 else if ( stype == "STATIC_LIBRARY" )
1956 this->InstallType = cmInstallType_STATIC_LIBRARY;
1958 else if ( stype == "SHARED_LIBRARY" )
1960 this->InstallType = cmInstallType_SHARED_LIBRARY;
1962 else if ( stype == "MODULE" )
1964 this->InstallType = cmInstallType_MODULE_LIBRARY;
1966 else if ( stype == "DIRECTORY" )
1968 this->InstallType = cmInstallType_DIRECTORY;
1973 e << "Option TYPE given uknown value \"" << stype << "\".";
1974 this->FileCommand->SetError(e.str().c_str());
1980 //----------------------------------------------------------------------------
1981 bool cmFileInstaller::HandleInstallDestination()
1983 std::string& destination = this->Destination;
1985 // allow for / to be a valid destination
1986 if ( destination.size() < 2 && destination != "/" )
1988 this->FileCommand->SetError("called with inapropriate arguments. "
1989 "No DESTINATION provided or .");
1993 const char* destdir = cmSystemTools::GetEnv("DESTDIR");
1994 if ( destdir && *destdir )
1996 std::string sdestdir = destdir;
1997 cmSystemTools::ConvertToUnixSlashes(sdestdir);
1998 char ch1 = destination[0];
1999 char ch2 = destination[1];
2001 if ( destination.size() > 2 )
2003 ch3 = destination[2];
2009 if (((ch1 >= 'a' && ch1 <= 'z') || (ch1 >= 'A' && ch1 <= 'Z')) &&
2013 // let's do some destdir magic:
2026 // This is relative path on unix or windows. Since we are doing
2027 // destdir, this case does not make sense.
2028 this->FileCommand->SetError(
2029 "called with relative DESTINATION. This "
2030 "does not make sense when using DESTDIR. Specify "
2031 "absolute path or remove DESTDIR environment variable.");
2039 // looks like a network path.
2040 std::string message = "called with network path DESTINATION. This "
2041 "does not make sense when using DESTDIR. Specify local "
2042 "absolute path or remove DESTDIR environment variable."
2044 message += destination;
2045 this->FileCommand->SetError(message.c_str());
2049 destination = sdestdir + (destination.c_str() + skip);
2050 this->DestDirLength = int(sdestdir.size());
2053 if ( !cmSystemTools::FileExists(destination.c_str()) )
2055 if ( !cmSystemTools::MakeDirectory(destination.c_str()) )
2057 std::string errstring = "cannot create directory: " + destination +
2058 ". Maybe need administrative privileges.";
2059 this->FileCommand->SetError(errstring.c_str());
2063 if ( !cmSystemTools::FileIsDirectory(destination.c_str()) )
2065 std::string errstring = "INSTALL destination: " + destination +
2066 " is not a directory.";
2067 this->FileCommand->SetError(errstring.c_str());
2073 //----------------------------------------------------------------------------
2075 cmFileCommand::HandleRPathChangeCommand(std::vector<std::string> const& args)
2077 // Evaluate arguments.
2078 const char* file = 0;
2079 const char* oldRPath = 0;
2080 const char* newRPath = 0;
2081 enum Doing { DoingNone, DoingFile, DoingOld, DoingNew };
2082 Doing doing = DoingNone;
2083 for(unsigned int i=1; i < args.size(); ++i)
2085 if(args[i] == "OLD_RPATH")
2089 else if(args[i] == "NEW_RPATH")
2093 else if(args[i] == "FILE")
2097 else if(doing == DoingFile)
2099 file = args[i].c_str();
2102 else if(doing == DoingOld)
2104 oldRPath = args[i].c_str();
2107 else if(doing == DoingNew)
2109 newRPath = args[i].c_str();
2115 e << "RPATH_CHANGE given unknown argument " << args[i];
2116 this->SetError(e.str().c_str());
2122 this->SetError("RPATH_CHANGE not given FILE option.");
2127 this->SetError("RPATH_CHANGE not given OLD_RPATH option.");
2132 this->SetError("RPATH_CHANGE not given NEW_RPATH option.");
2135 if(!cmSystemTools::FileExists(file, true))
2138 e << "RPATH_CHANGE given FILE \"" << file << "\" that does not exist.";
2139 this->SetError(e.str().c_str());
2142 bool success = true;
2143 cmSystemToolsFileTime* ft = cmSystemTools::FileTimeNew();
2144 bool have_ft = cmSystemTools::FileTimeGet(file, ft);
2147 if(!cmSystemTools::ChangeRPath(file, oldRPath, newRPath, &emsg, &changed))
2150 e << "RPATH_CHANGE could not write new RPATH:\n"
2151 << " " << newRPath << "\n"
2153 << " " << file << "\n"
2155 this->SetError(e.str().c_str());
2162 std::string message = "Set runtime path of \"";
2164 message += "\" to \"";
2165 message += newRPath;
2167 this->Makefile->DisplayStatus(message.c_str(), -1);
2171 cmSystemTools::FileTimeSet(file, ft);
2174 cmSystemTools::FileTimeDelete(ft);
2178 //----------------------------------------------------------------------------
2180 cmFileCommand::HandleRPathRemoveCommand(std::vector<std::string> const& args)
2182 // Evaluate arguments.
2183 const char* file = 0;
2184 enum Doing { DoingNone, DoingFile };
2185 Doing doing = DoingNone;
2186 for(unsigned int i=1; i < args.size(); ++i)
2188 if(args[i] == "FILE")
2192 else if(doing == DoingFile)
2194 file = args[i].c_str();
2200 e << "RPATH_REMOVE given unknown argument " << args[i];
2201 this->SetError(e.str().c_str());
2207 this->SetError("RPATH_REMOVE not given FILE option.");
2210 if(!cmSystemTools::FileExists(file, true))
2213 e << "RPATH_REMOVE given FILE \"" << file << "\" that does not exist.";
2214 this->SetError(e.str().c_str());
2217 bool success = true;
2218 cmSystemToolsFileTime* ft = cmSystemTools::FileTimeNew();
2219 bool have_ft = cmSystemTools::FileTimeGet(file, ft);
2222 if(!cmSystemTools::RemoveRPath(file, &emsg, &removed))
2225 e << "RPATH_REMOVE could not remove RPATH from file:\n"
2226 << " " << file << "\n"
2228 this->SetError(e.str().c_str());
2235 std::string message = "Removed runtime path from \"";
2238 this->Makefile->DisplayStatus(message.c_str(), -1);
2242 cmSystemTools::FileTimeSet(file, ft);
2245 cmSystemTools::FileTimeDelete(ft);
2249 //----------------------------------------------------------------------------
2251 cmFileCommand::HandleRPathCheckCommand(std::vector<std::string> const& args)
2253 // Evaluate arguments.
2254 const char* file = 0;
2255 const char* rpath = 0;
2256 enum Doing { DoingNone, DoingFile, DoingRPath };
2257 Doing doing = DoingNone;
2258 for(unsigned int i=1; i < args.size(); ++i)
2260 if(args[i] == "RPATH")
2264 else if(args[i] == "FILE")
2268 else if(doing == DoingFile)
2270 file = args[i].c_str();
2273 else if(doing == DoingRPath)
2275 rpath = args[i].c_str();
2281 e << "RPATH_CHECK given unknown argument " << args[i];
2282 this->SetError(e.str().c_str());
2288 this->SetError("RPATH_CHECK not given FILE option.");
2293 this->SetError("RPATH_CHECK not given RPATH option.");
2297 // If the file exists but does not have the desired RPath then
2298 // delete it. This is used during installation to re-install a file
2299 // if its RPath will change.
2300 if(cmSystemTools::FileExists(file, true) &&
2301 !cmSystemTools::CheckRPath(file, rpath))
2303 cmSystemTools::RemoveFile(file);
2309 //----------------------------------------------------------------------------
2310 bool cmFileCommand::HandleInstallCommand(std::vector<std::string> const& args)
2312 cmFileInstaller installer(this);
2313 return installer.Run(args);
2316 //----------------------------------------------------------------------------
2317 bool cmFileCommand::HandleRelativePathCommand(
2318 std::vector<std::string> const& args)
2320 if(args.size() != 4 )
2322 this->SetError("RELATIVE_PATH called with incorrect number of arguments");
2326 const std::string& outVar = args[1];
2327 const std::string& directoryName = args[2];
2328 const std::string& fileName = args[3];
2330 if(!cmSystemTools::FileIsFullPath(directoryName.c_str()))
2332 std::string errstring =
2333 "RELATIVE_PATH must be passed a full path to the directory: "
2335 this->SetError(errstring.c_str());
2338 if(!cmSystemTools::FileIsFullPath(fileName.c_str()))
2340 std::string errstring =
2341 "RELATIVE_PATH must be passed a full path to the file: "
2343 this->SetError(errstring.c_str());
2347 std::string res = cmSystemTools::RelativePath(directoryName.c_str(),
2349 this->Makefile->AddDefinition(outVar.c_str(),
2355 //----------------------------------------------------------------------------
2356 bool cmFileCommand::HandleRename(std::vector<std::string> const& args)
2358 if(args.size() != 3)
2360 this->SetError("RENAME given incorrect number of arguments.");
2364 // Compute full path for old and new names.
2365 std::string oldname = args[1];
2366 if(!cmsys::SystemTools::FileIsFullPath(oldname.c_str()))
2368 oldname = this->Makefile->GetCurrentDirectory();
2369 oldname += "/" + args[1];
2371 std::string newname = args[2];
2372 if(!cmsys::SystemTools::FileIsFullPath(newname.c_str()))
2374 newname = this->Makefile->GetCurrentDirectory();
2375 newname += "/" + args[2];
2378 if(!cmSystemTools::RenameFile(oldname.c_str(), newname.c_str()))
2380 std::string err = cmSystemTools::GetLastSystemError();
2382 e << "RENAME failed to rename\n"
2383 << " " << oldname << "\n"
2385 << " " << newname << "\n"
2386 << "because: " << err << "\n";
2387 this->SetError(e.str().c_str());
2394 //----------------------------------------------------------------------------
2395 bool cmFileCommand::HandleRemove(std::vector<std::string> const& args,
2399 std::string message;
2400 std::vector<std::string>::const_iterator i = args.begin();
2402 i++; // Get rid of subcommand
2403 for(;i != args.end(); ++i)
2405 std::string fileName = *i;
2406 if(!cmsys::SystemTools::FileIsFullPath(fileName.c_str()))
2408 fileName = this->Makefile->GetCurrentDirectory();
2409 fileName += "/" + *i;
2412 if(cmSystemTools::FileIsDirectory(fileName.c_str()) &&
2413 !cmSystemTools::FileIsSymlink(fileName.c_str()) && recurse)
2415 cmSystemTools::RemoveADirectory(fileName.c_str());
2419 cmSystemTools::RemoveFile(fileName.c_str());
2425 //----------------------------------------------------------------------------
2426 bool cmFileCommand::HandleCMakePathCommand(std::vector<std::string>
2430 std::vector<std::string>::const_iterator i = args.begin();
2431 if(args.size() != 3)
2433 this->SetError("FILE([TO_CMAKE_PATH|TO_NATIVE_PATH] path result) must be "
2434 "called with exactly three arguments.");
2437 i++; // Get rid of subcommand
2438 #if defined(_WIN32) && !defined(__CYGWIN__)
2443 std::vector<cmsys::String> path = cmSystemTools::SplitString(i->c_str(),
2446 const char* var = i->c_str();
2448 for(std::vector<cmsys::String>::iterator j = path.begin();
2449 j != path.end(); ++j)
2451 if(j != path.begin())
2457 cmSystemTools::ConvertToUnixSlashes(*j);
2461 *j = cmSystemTools::ConvertToOutputPath(j->c_str());
2462 // remove double quotes in the path
2463 cmsys::String& s = *j;
2465 if(s.size() > 1 && s[0] == '\"' && s[s.size()-1] == '\"')
2467 s = s.substr(1,s.size()-2);
2472 this->Makefile->AddDefinition(var, value.c_str());
2477 #if defined(CMAKE_BUILD_WITH_CMAKE)
2479 // Stuff for curl download/upload
2480 typedef std::vector<char> cmFileCommandVectorOfChar;
2485 cmWriteToFileCallback(void *ptr, size_t size, size_t nmemb,
2488 register int realsize = (int)(size * nmemb);
2489 std::ofstream* fout = static_cast<std::ofstream*>(data);
2490 const char* chPtr = static_cast<char*>(ptr);
2491 fout->write(chPtr, realsize);
2497 cmWriteToMemoryCallback(void *ptr, size_t size, size_t nmemb,
2500 register int realsize = (int)(size * nmemb);
2501 cmFileCommandVectorOfChar *vec
2502 = static_cast<cmFileCommandVectorOfChar*>(data);
2503 const char* chPtr = static_cast<char*>(ptr);
2504 vec->insert(vec->end(), chPtr, chPtr + realsize);
2510 cmFileCommandCurlDebugCallback(CURL *, curl_infotype, char *chPtr,
2511 size_t size, void *data)
2513 cmFileCommandVectorOfChar *vec
2514 = static_cast<cmFileCommandVectorOfChar*>(data);
2515 vec->insert(vec->end(), chPtr, chPtr + size);
2520 class cURLProgressHelper
2523 cURLProgressHelper(cmFileCommand *fc, const char *text)
2525 this->CurrentPercentage = -1;
2526 this->FileCommand = fc;
2530 bool UpdatePercentage(double value, double total, std::string &status)
2532 int OldPercentage = this->CurrentPercentage;
2536 this->CurrentPercentage = static_cast<int>(value/total*100.0 + 0.5);
2539 bool updated = (OldPercentage != this->CurrentPercentage);
2543 cmOStringStream oss;
2544 oss << "[" << this->Text << " " << this->CurrentPercentage
2552 cmFileCommand *GetFileCommand()
2554 return this->FileCommand;
2558 int CurrentPercentage;
2559 cmFileCommand *FileCommand;
2565 cmFileDownloadProgressCallback(void *clientp,
2566 double dltotal, double dlnow,
2567 double ultotal, double ulnow)
2569 cURLProgressHelper *helper =
2570 reinterpret_cast<cURLProgressHelper *>(clientp);
2572 static_cast<void>(ultotal);
2573 static_cast<void>(ulnow);
2576 if (helper->UpdatePercentage(dlnow, dltotal, status))
2578 cmFileCommand *fc = helper->GetFileCommand();
2579 cmMakefile *mf = fc->GetMakefile();
2580 mf->DisplayStatus(status.c_str(), -1);
2588 cmFileUploadProgressCallback(void *clientp,
2589 double dltotal, double dlnow,
2590 double ultotal, double ulnow)
2592 cURLProgressHelper *helper =
2593 reinterpret_cast<cURLProgressHelper *>(clientp);
2595 static_cast<void>(dltotal);
2596 static_cast<void>(dlnow);
2599 if (helper->UpdatePercentage(ulnow, ultotal, status))
2601 cmFileCommand *fc = helper->GetFileCommand();
2602 cmMakefile *mf = fc->GetMakefile();
2603 mf->DisplayStatus(status.c_str(), -1);
2616 cURLEasyGuard(CURL * easy)
2620 ~cURLEasyGuard(void)
2624 ::curl_easy_cleanup(this->Easy);
2628 inline void release(void)
2642 #define check_curl_result(result, errstr) \
2643 if (result != CURLE_OK) \
2645 std::string e(errstr); \
2646 e += ::curl_easy_strerror(result); \
2647 this->SetError(e.c_str()); \
2653 cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args)
2655 #if defined(CMAKE_BUILD_WITH_CMAKE)
2656 std::vector<std::string>::const_iterator i = args.begin();
2659 this->SetError("DOWNLOAD must be called with at least three arguments.");
2662 ++i; // Get rid of subcommand
2663 std::string url = *i;
2665 std::string file = *i;
2669 long inactivity_timeout = 0;
2670 std::string verboseLog;
2671 std::string statusVar;
2672 bool tls_verify = this->Makefile->IsOn("CMAKE_TLS_VERIFY");
2673 const char* cainfo = this->Makefile->GetDefinition("CMAKE_TLS_CAINFO");
2674 std::string expectedHash;
2675 std::string hashMatchMSG;
2676 cmsys::auto_ptr<cmCryptoHash> hash;
2677 bool showProgress = false;
2679 while(i != args.end())
2686 timeout = atol(i->c_str());
2690 this->SetError("DOWNLOAD missing time for TIMEOUT.");
2694 else if(*i == "INACTIVITY_TIMEOUT")
2699 inactivity_timeout = atol(i->c_str());
2703 this->SetError("DOWNLOAD missing time for INACTIVITY_TIMEOUT.");
2707 else if(*i == "LOG")
2710 if( i == args.end())
2712 this->SetError("DOWNLOAD missing VAR for LOG.");
2717 else if(*i == "STATUS")
2720 if( i == args.end())
2722 this->SetError("DOWNLOAD missing VAR for STATUS.");
2727 else if(*i == "TLS_VERIFY")
2732 tls_verify = cmSystemTools::IsOn(i->c_str());
2736 this->SetError("TLS_VERIFY missing bool value.");
2740 else if(*i == "TLS_CAINFO")
2745 cainfo = i->c_str();
2749 this->SetError("TLS_CAFILE missing file value.");
2753 else if(*i == "EXPECTED_MD5")
2756 if( i == args.end())
2758 this->SetError("DOWNLOAD missing sum value for EXPECTED_MD5.");
2761 hash = cmsys::auto_ptr<cmCryptoHash>(cmCryptoHash::New("MD5"));
2762 hashMatchMSG = "MD5 sum";
2763 expectedHash = cmSystemTools::LowerCase(*i);
2765 else if(*i == "SHOW_PROGRESS")
2767 showProgress = true;
2769 else if(*i == "EXPECTED_HASH")
2774 this->SetError("DOWNLOAD missing ALGO=value for EXPECTED_HASH.");
2777 std::string::size_type pos = i->find("=");
2778 if(pos == std::string::npos)
2781 "DOWNLOAD EXPECTED_HASH expects ALGO=value but got: ";
2783 this->SetError(err.c_str());
2786 std::string algo = i->substr(0, pos);
2787 expectedHash = cmSystemTools::LowerCase(i->substr(pos+1));
2788 hash = cmsys::auto_ptr<cmCryptoHash>(cmCryptoHash::New(algo.c_str()));
2791 std::string err = "DOWNLOAD EXPECTED_HASH given unknown ALGO: ";
2793 this->SetError(err.c_str());
2796 hashMatchMSG = algo + " hash";
2800 // If file exists already, and caller specified an expected md5 or sha,
2801 // and the existing file already has the expected hash, then simply
2804 if(cmSystemTools::FileExists(file.c_str()) && hash.get())
2807 std::string actualHash = hash->HashFile(file.c_str());
2808 if(actualHash == expectedHash)
2810 msg = "returning early; file already exists with expected ";
2811 msg += hashMatchMSG;
2813 if(statusVar.size())
2815 cmOStringStream result;
2816 result << (int)0 << ";\"" << msg;
2817 this->Makefile->AddDefinition(statusVar.c_str(),
2818 result.str().c_str());
2823 // Make sure parent directory exists so we can write to the file
2824 // as we receive downloaded bits from curl...
2826 std::string dir = cmSystemTools::GetFilenamePath(file.c_str());
2827 if(!cmSystemTools::FileExists(dir.c_str()) &&
2828 !cmSystemTools::MakeDirectory(dir.c_str()))
2830 std::string errstring = "DOWNLOAD error: cannot create directory '"
2831 + dir + "' - Specify file by full path name and verify that you "
2832 "have directory creation and file write privileges.";
2833 this->SetError(errstring.c_str());
2837 std::ofstream fout(file.c_str(), std::ios::binary);
2840 this->SetError("DOWNLOAD cannot open file for write.");
2845 ::curl_global_init(CURL_GLOBAL_DEFAULT);
2846 curl = ::curl_easy_init();
2849 this->SetError("DOWNLOAD error initializing curl.");
2853 cURLEasyGuard g_curl(curl);
2854 ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
2855 check_curl_result(res, "DOWNLOAD cannot set url: ");
2857 // enable HTTP ERROR parsing
2858 res = ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
2859 check_curl_result(res, "DOWNLOAD cannot set http failure option: ");
2861 res = ::curl_easy_setopt(curl, CURLOPT_USERAGENT, "curl/" LIBCURL_VERSION);
2862 check_curl_result(res, "DOWNLOAD cannot set user agent option: ");
2864 res = ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
2865 cmWriteToFileCallback);
2866 check_curl_result(res, "DOWNLOAD cannot set write function: ");
2868 res = ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
2869 cmFileCommandCurlDebugCallback);
2870 check_curl_result(res, "DOWNLOAD cannot set debug function: ");
2872 // check to see if TLS verification is requested
2875 res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1);
2876 check_curl_result(res, "Unable to set TLS/SSL Verify on: ");
2880 res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
2881 check_curl_result(res, "Unable to set TLS/SSL Verify off: ");
2883 // check to see if a CAINFO file has been specified
2884 // command arg comes first
2885 if(cainfo && *cainfo)
2887 res = ::curl_easy_setopt(curl, CURLOPT_CAINFO, cainfo);
2888 check_curl_result(res, "Unable to set TLS/SSL Verify CAINFO: ");
2891 cmFileCommandVectorOfChar chunkDebug;
2893 res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&fout);
2894 check_curl_result(res, "DOWNLOAD cannot set write data: ");
2896 res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)&chunkDebug);
2897 check_curl_result(res, "DOWNLOAD cannot set debug data: ");
2899 res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
2900 check_curl_result(res, "DOWNLOAD cannot set follow-redirect option: ");
2902 if(verboseLog.size())
2904 res = ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
2905 check_curl_result(res, "DOWNLOAD cannot set verbose: ");
2910 res = ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout );
2911 check_curl_result(res, "DOWNLOAD cannot set timeout: ");
2914 if(inactivity_timeout > 0)
2916 // Give up if there is no progress for a long time.
2917 ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
2918 ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, inactivity_timeout);
2921 // Need the progress helper's scope to last through the duration of
2922 // the curl_easy_perform call... so this object is declared at function
2923 // scope intentionally, rather than inside the "if(showProgress)"
2926 cURLProgressHelper helper(this, "download");
2930 res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
2931 check_curl_result(res, "DOWNLOAD cannot set noprogress value: ");
2933 res = ::curl_easy_setopt(curl,
2934 CURLOPT_PROGRESSFUNCTION, cmFileDownloadProgressCallback);
2935 check_curl_result(res, "DOWNLOAD cannot set progress function: ");
2937 res = ::curl_easy_setopt(curl,
2938 CURLOPT_PROGRESSDATA, reinterpret_cast<void*>(&helper));
2939 check_curl_result(res, "DOWNLOAD cannot set progress data: ");
2942 res = ::curl_easy_perform(curl);
2944 /* always cleanup */
2946 ::curl_easy_cleanup(curl);
2948 if(statusVar.size())
2950 cmOStringStream result;
2951 result << (int)res << ";\"" << ::curl_easy_strerror(res) << "\"";
2952 this->Makefile->AddDefinition(statusVar.c_str(),
2953 result.str().c_str());
2956 ::curl_global_cleanup();
2958 // Explicitly flush/close so we can measure the md5 accurately.
2963 // Verify MD5 sum if requested:
2967 std::string actualHash = hash->HashFile(file.c_str());
2968 if (actualHash.size() == 0)
2970 this->SetError("DOWNLOAD cannot compute hash on downloaded file");
2974 if (expectedHash != actualHash)
2976 cmOStringStream oss;
2977 oss << "DOWNLOAD HASH mismatch" << std::endl
2978 << " for file: [" << file << "]" << std::endl
2979 << " expected hash: [" << expectedHash << "]" << std::endl
2980 << " actual hash: [" << actualHash << "]" << std::endl
2982 this->SetError(oss.str().c_str());
2987 if(chunkDebug.size())
2989 chunkDebug.push_back(0);
2990 if(CURLE_OPERATION_TIMEOUTED == res)
2992 std::string output = &*chunkDebug.begin();
2994 if(verboseLog.size())
2996 this->Makefile->AddDefinition(verboseLog.c_str(),
2997 &*chunkDebug.begin());
3001 this->Makefile->AddDefinition(verboseLog.c_str(),
3002 &*chunkDebug.begin());
3007 this->SetError("DOWNLOAD not supported by bootstrap cmake.");
3014 cmFileCommand::HandleUploadCommand(std::vector<std::string> const& args)
3016 #if defined(CMAKE_BUILD_WITH_CMAKE)
3019 this->SetError("UPLOAD must be called with at least three arguments.");
3022 std::vector<std::string>::const_iterator i = args.begin();
3024 std::string filename = *i;
3026 std::string url = *i;
3030 long inactivity_timeout = 0;
3032 std::string statusVar;
3033 bool showProgress = false;
3035 while(i != args.end())
3042 timeout = atol(i->c_str());
3046 this->SetError("UPLOAD missing time for TIMEOUT.");
3050 else if(*i == "INACTIVITY_TIMEOUT")
3055 inactivity_timeout = atol(i->c_str());
3059 this->SetError("UPLOAD missing time for INACTIVITY_TIMEOUT.");
3063 else if(*i == "LOG")
3066 if( i == args.end())
3068 this->SetError("UPLOAD missing VAR for LOG.");
3073 else if(*i == "STATUS")
3076 if( i == args.end())
3078 this->SetError("UPLOAD missing VAR for STATUS.");
3083 else if(*i == "SHOW_PROGRESS")
3085 showProgress = true;
3091 // Open file for reading:
3093 FILE *fin = fopen(filename.c_str(), "rb");
3096 std::string errStr = "UPLOAD cannot open file '";
3097 errStr += filename + "' for reading.";
3098 this->SetError(errStr.c_str());
3103 if(::stat(filename.c_str(), &st))
3105 std::string errStr = "UPLOAD cannot stat file '";
3106 errStr += filename + "'.";
3107 this->SetError(errStr.c_str());
3113 ::curl_global_init(CURL_GLOBAL_DEFAULT);
3114 curl = ::curl_easy_init();
3117 this->SetError("UPLOAD error initializing curl.");
3122 cURLEasyGuard g_curl(curl);
3124 // enable HTTP ERROR parsing
3125 ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
3128 res = ::curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
3129 check_curl_result(res, "UPLOAD cannot set upload flag: ");
3131 res = ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
3132 check_curl_result(res, "UPLOAD cannot set url: ");
3134 res = ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
3135 cmWriteToMemoryCallback);
3136 check_curl_result(res, "UPLOAD cannot set write function: ");
3138 res = ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
3139 cmFileCommandCurlDebugCallback);
3140 check_curl_result(res, "UPLOAD cannot set debug function: ");
3142 cmFileCommandVectorOfChar chunkResponse;
3143 cmFileCommandVectorOfChar chunkDebug;
3145 res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunkResponse);
3146 check_curl_result(res, "UPLOAD cannot set write data: ");
3148 res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)&chunkDebug);
3149 check_curl_result(res, "UPLOAD cannot set debug data: ");
3151 res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
3152 check_curl_result(res, "UPLOAD cannot set follow-redirect option: ");
3156 res = ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
3157 check_curl_result(res, "UPLOAD cannot set verbose: ");
3162 res = ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout );
3163 check_curl_result(res, "UPLOAD cannot set timeout: ");
3166 if(inactivity_timeout > 0)
3168 // Give up if there is no progress for a long time.
3169 ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
3170 ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, inactivity_timeout);
3173 // Need the progress helper's scope to last through the duration of
3174 // the curl_easy_perform call... so this object is declared at function
3175 // scope intentionally, rather than inside the "if(showProgress)"
3178 cURLProgressHelper helper(this, "upload");
3182 res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
3183 check_curl_result(res, "UPLOAD cannot set noprogress value: ");
3185 res = ::curl_easy_setopt(curl,
3186 CURLOPT_PROGRESSFUNCTION, cmFileUploadProgressCallback);
3187 check_curl_result(res, "UPLOAD cannot set progress function: ");
3189 res = ::curl_easy_setopt(curl,
3190 CURLOPT_PROGRESSDATA, reinterpret_cast<void*>(&helper));
3191 check_curl_result(res, "UPLOAD cannot set progress data: ");
3194 // now specify which file to upload
3195 res = ::curl_easy_setopt(curl, CURLOPT_INFILE, fin);
3196 check_curl_result(res, "UPLOAD cannot set input file: ");
3198 // and give the size of the upload (optional)
3199 res = ::curl_easy_setopt(curl,
3200 CURLOPT_INFILESIZE, static_cast<long>(st.st_size));
3201 check_curl_result(res, "UPLOAD cannot set input file size: ");
3203 res = ::curl_easy_perform(curl);
3205 /* always cleanup */
3207 ::curl_easy_cleanup(curl);
3209 if(statusVar.size())
3211 cmOStringStream result;
3212 result << (int)res << ";\"" << ::curl_easy_strerror(res) << "\"";
3213 this->Makefile->AddDefinition(statusVar.c_str(),
3214 result.str().c_str());
3217 ::curl_global_cleanup();
3226 if(chunkResponse.size())
3228 chunkResponse.push_back(0);
3229 log += "Response:\n";
3230 log += &*chunkResponse.begin();
3234 if(chunkDebug.size())
3236 chunkDebug.push_back(0);
3238 log += &*chunkDebug.begin();
3242 this->Makefile->AddDefinition(logVar.c_str(), log.c_str());
3247 this->SetError("UPLOAD not supported by bootstrap cmake.");
3252 //----------------------------------------------------------------------------
3253 bool cmFileCommand::HandleTimestampCommand(
3254 std::vector<std::string> const& args)
3258 this->SetError("sub-command TIMESTAMP requires at least two arguments.");
3261 else if(args.size() > 5)
3263 this->SetError("sub-command TIMESTAMP takes at most four arguments.");
3267 unsigned int argsIndex = 1;
3269 const std::string& filename = args[argsIndex++];
3271 const std::string& outputVariable = args[argsIndex++];
3273 std::string formatString;
3274 if(args.size() > argsIndex && args[argsIndex] != "UTC")
3276 formatString = args[argsIndex++];
3279 bool utcFlag = false;
3280 if(args.size() > argsIndex)
3282 if(args[argsIndex] == "UTC")
3288 std::string e = " TIMESTAMP sub-command does not recognize option " +
3289 args[argsIndex] + ".";
3290 this->SetError(e.c_str());
3295 cmTimestamp timestamp;
3296 std::string result = timestamp.FileModificationTime(
3297 filename.c_str(), formatString, utcFlag);
3298 this->Makefile->AddDefinition(outputVariable.c_str(), result.c_str());