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"
14 #include "cmHexFileConverter.h"
15 #include "cmInstallType.h"
16 #include "cmFileTimeComparison.h"
17 #include "cmCryptoHash.h"
19 #if defined(CMAKE_BUILD_WITH_CMAKE)
23 #undef GetCurrentDirectory
24 #include <sys/types.h>
27 #include <cmsys/auto_ptr.hxx>
28 #include <cmsys/Directory.hxx>
29 #include <cmsys/Glob.hxx>
30 #include <cmsys/RegularExpression.hxx>
32 // Table of permissions flags.
33 #if defined(_WIN32) && !defined(__CYGWIN__)
34 static mode_t mode_owner_read = S_IREAD;
35 static mode_t mode_owner_write = S_IWRITE;
36 static mode_t mode_owner_execute = S_IEXEC;
37 static mode_t mode_group_read = 0;
38 static mode_t mode_group_write = 0;
39 static mode_t mode_group_execute = 0;
40 static mode_t mode_world_read = 0;
41 static mode_t mode_world_write = 0;
42 static mode_t mode_world_execute = 0;
43 static mode_t mode_setuid = 0;
44 static mode_t mode_setgid = 0;
46 static mode_t mode_owner_read = S_IRUSR;
47 static mode_t mode_owner_write = S_IWUSR;
48 static mode_t mode_owner_execute = S_IXUSR;
49 static mode_t mode_group_read = S_IRGRP;
50 static mode_t mode_group_write = S_IWGRP;
51 static mode_t mode_group_execute = S_IXGRP;
52 static mode_t mode_world_read = S_IROTH;
53 static mode_t mode_world_write = S_IWOTH;
54 static mode_t mode_world_execute = S_IXOTH;
55 static mode_t mode_setuid = S_ISUID;
56 static mode_t mode_setgid = S_ISGID;
61 ::InitialPass(std::vector<std::string> const& args, cmExecutionStatus &)
65 this->SetError("must be called with at least two arguments.");
68 std::string subCommand = args[0];
69 if ( subCommand == "WRITE" )
71 return this->HandleWriteCommand(args, false);
73 else if ( subCommand == "APPEND" )
75 return this->HandleWriteCommand(args, true);
77 else if ( subCommand == "DOWNLOAD" )
79 return this->HandleDownloadCommand(args);
81 else if ( subCommand == "UPLOAD" )
83 return this->HandleUploadCommand(args);
85 else if ( subCommand == "READ" )
87 return this->HandleReadCommand(args);
89 else if ( subCommand == "MD5" ||
90 subCommand == "SHA1" ||
91 subCommand == "SHA224" ||
92 subCommand == "SHA256" ||
93 subCommand == "SHA384" ||
94 subCommand == "SHA512" )
96 return this->HandleHashCommand(args);
98 else if ( subCommand == "STRINGS" )
100 return this->HandleStringsCommand(args);
102 else if ( subCommand == "GLOB" )
104 return this->HandleGlobCommand(args, false);
106 else if ( subCommand == "GLOB_RECURSE" )
108 return this->HandleGlobCommand(args, true);
110 else if ( subCommand == "MAKE_DIRECTORY" )
112 return this->HandleMakeDirectoryCommand(args);
114 else if ( subCommand == "RENAME" )
116 return this->HandleRename(args);
118 else if ( subCommand == "REMOVE" )
120 return this->HandleRemove(args, false);
122 else if ( subCommand == "REMOVE_RECURSE" )
124 return this->HandleRemove(args, true);
126 else if ( subCommand == "COPY" )
128 return this->HandleCopyCommand(args);
130 else if ( subCommand == "INSTALL" )
132 return this->HandleInstallCommand(args);
134 else if ( subCommand == "DIFFERENT" )
136 return this->HandleDifferentCommand(args);
138 else if ( subCommand == "RPATH_CHANGE" || subCommand == "CHRPATH" )
140 return this->HandleRPathChangeCommand(args);
142 else if ( subCommand == "RPATH_CHECK" )
144 return this->HandleRPathCheckCommand(args);
146 else if ( subCommand == "RPATH_REMOVE" )
148 return this->HandleRPathRemoveCommand(args);
150 else if ( subCommand == "RELATIVE_PATH" )
152 return this->HandleRelativePathCommand(args);
154 else if ( subCommand == "TO_CMAKE_PATH" )
156 return this->HandleCMakePathCommand(args, false);
158 else if ( subCommand == "TO_NATIVE_PATH" )
160 return this->HandleCMakePathCommand(args, true);
163 std::string e = "does not recognize sub-command "+subCommand;
164 this->SetError(e.c_str());
168 //----------------------------------------------------------------------------
169 bool cmFileCommand::HandleWriteCommand(std::vector<std::string> const& args,
173 std::vector<std::string>::const_iterator i = args.begin();
175 i++; // Get rid of subcommand
177 std::string fileName = *i;
178 if ( !cmsys::SystemTools::FileIsFullPath(i->c_str()) )
180 fileName = this->Makefile->GetCurrentDirectory();
181 fileName += "/" + *i;
186 for(;i != args.end(); ++i)
190 if ( !this->Makefile->CanIWriteThisFile(fileName.c_str()) )
193 = "attempted to write a file: " + fileName +
194 " into a source directory.";
195 this->SetError(e.c_str());
196 cmSystemTools::SetFatalErrorOccured();
199 std::string dir = cmSystemTools::GetFilenamePath(fileName);
200 cmSystemTools::MakeDirectory(dir.c_str());
204 // Set permissions to writable
205 if ( cmSystemTools::GetPermissions(fileName.c_str(), mode) )
207 cmSystemTools::SetPermissions(fileName.c_str(),
208 #if defined( _MSC_VER ) || defined( __MINGW32__ )
210 #elif defined( __BORLANDC__ )
213 mode | S_IWUSR | S_IWGRP
217 // If GetPermissions fails, pretend like it is ok. File open will fail if
218 // the file is not writable
219 std::ofstream file(fileName.c_str(), append?std::ios::app: std::ios::out);
222 std::string error = "Internal CMake error when trying to open file: ";
223 error += fileName.c_str();
224 error += " for writing.";
225 this->SetError(error.c_str());
232 cmSystemTools::SetPermissions(fileName.c_str(), mode);
237 //----------------------------------------------------------------------------
238 bool cmFileCommand::HandleReadCommand(std::vector<std::string> const& args)
240 if ( args.size() < 3 )
242 this->SetError("READ must be called with at least two additional "
247 cmCommandArgumentsHelper argHelper;
248 cmCommandArgumentGroup group;
250 cmCAString readArg (&argHelper, "READ");
251 cmCAString fileNameArg (&argHelper, 0);
252 cmCAString resultArg (&argHelper, 0);
254 cmCAString offsetArg (&argHelper, "OFFSET", &group);
255 cmCAString limitArg (&argHelper, "LIMIT", &group);
256 cmCAEnabler hexOutputArg (&argHelper, "HEX", &group);
258 fileNameArg.Follows(&readArg);
259 resultArg.Follows(&fileNameArg);
260 group.Follows(&resultArg);
261 argHelper.Parse(&args, 0);
263 std::string fileName = fileNameArg.GetString();
264 if ( !cmsys::SystemTools::FileIsFullPath(fileName.c_str()) )
266 fileName = this->Makefile->GetCurrentDirectory();
267 fileName += "/" + fileNameArg.GetString();
270 std::string variable = resultArg.GetString();
272 // Open the specified file.
273 #if defined(_WIN32) || defined(__CYGWIN__)
274 std::ifstream file(fileName.c_str(), std::ios::in |
275 (hexOutputArg.IsEnabled() ? std::ios::binary : std::ios::in));
277 std::ifstream file(fileName.c_str(), std::ios::in);
282 std::string error = "Internal CMake error when trying to open file: ";
283 error += fileName.c_str();
284 error += " for reading.";
285 this->SetError(error.c_str());
291 if (limitArg.GetString().size() > 0)
293 sizeLimit = atoi(limitArg.GetCString());
296 // is there an offset?
298 if (offsetArg.GetString().size() > 0)
300 offset = atoi(offsetArg.GetCString());
303 file.seekg(offset, std::ios::beg); // explicit ios::beg for IBM VisualAge 6
307 if (hexOutputArg.IsEnabled())
309 // Convert part of the file into hex code
311 while((sizeLimit != 0) && (file.get(c)))
314 sprintf(hex, "%.2x", c&0xff);
325 bool has_newline = false;
326 while (sizeLimit != 0 &&
327 cmSystemTools::GetLineFromStream(file, line, &has_newline,
332 sizeLimit = sizeLimit - static_cast<long>(line.size());
349 this->Makefile->AddDefinition(variable.c_str(), output.c_str());
353 //----------------------------------------------------------------------------
354 bool cmFileCommand::HandleHashCommand(std::vector<std::string> const& args)
356 #if defined(CMAKE_BUILD_WITH_CMAKE)
360 e << args[0] << " requires a file name and output variable";
361 this->SetError(e.str().c_str());
365 cmsys::auto_ptr<cmCryptoHash> hash(cmCryptoHash::New(args[0].c_str()));
368 std::string out = hash->HashFile(args[1].c_str());
371 this->Makefile->AddDefinition(args[2].c_str(), out.c_str());
375 e << args[0] << " failed to read file \"" << args[1] << "\": "
376 << cmSystemTools::GetLastSystemError();
377 this->SetError(e.str().c_str());
382 e << args[0] << " not available during bootstrap";
383 this->SetError(e.str().c_str());
388 //----------------------------------------------------------------------------
389 bool cmFileCommand::HandleStringsCommand(std::vector<std::string> const& args)
393 this->SetError("STRINGS requires a file name and output variable");
397 // Get the file to read.
398 std::string fileName = args[1];
399 if(!cmsys::SystemTools::FileIsFullPath(fileName.c_str()))
401 fileName = this->Makefile->GetCurrentDirectory();
402 fileName += "/" + args[1];
405 // Get the variable in which to store the results.
406 std::string outVar = args[2];
408 // Parse the options.
417 unsigned int minlen = 0;
418 unsigned int maxlen = 0;
419 int limit_input = -1;
420 int limit_output = -1;
421 unsigned int limit_count = 0;
422 cmsys::RegularExpression regex;
423 bool have_regex = false;
424 bool newline_consume = false;
425 bool hex_conversion_enabled = true;
426 int arg_mode = arg_none;
427 for(unsigned int i=3; i < args.size(); ++i)
429 if(args[i] == "LIMIT_INPUT")
431 arg_mode = arg_limit_input;
433 else if(args[i] == "LIMIT_OUTPUT")
435 arg_mode = arg_limit_output;
437 else if(args[i] == "LIMIT_COUNT")
439 arg_mode = arg_limit_count;
441 else if(args[i] == "LENGTH_MINIMUM")
443 arg_mode = arg_length_minimum;
445 else if(args[i] == "LENGTH_MAXIMUM")
447 arg_mode = arg_length_maximum;
449 else if(args[i] == "REGEX")
451 arg_mode = arg_regex;
453 else if(args[i] == "NEWLINE_CONSUME")
455 newline_consume = true;
458 else if(args[i] == "NO_HEX_CONVERSION")
460 hex_conversion_enabled = false;
463 else if(arg_mode == arg_limit_input)
465 if(sscanf(args[i].c_str(), "%d", &limit_input) != 1 ||
469 e << "STRINGS option LIMIT_INPUT value \""
470 << args[i] << "\" is not an unsigned integer.";
471 this->SetError(e.str().c_str());
476 else if(arg_mode == arg_limit_output)
478 if(sscanf(args[i].c_str(), "%d", &limit_output) != 1 ||
482 e << "STRINGS option LIMIT_OUTPUT value \""
483 << args[i] << "\" is not an unsigned integer.";
484 this->SetError(e.str().c_str());
489 else if(arg_mode == arg_limit_count)
492 if(sscanf(args[i].c_str(), "%d", &count) != 1 || count < 0)
495 e << "STRINGS option LIMIT_COUNT value \""
496 << args[i] << "\" is not an unsigned integer.";
497 this->SetError(e.str().c_str());
503 else if(arg_mode == arg_length_minimum)
506 if(sscanf(args[i].c_str(), "%d", &len) != 1 || len < 0)
509 e << "STRINGS option LENGTH_MINIMUM value \""
510 << args[i] << "\" is not an unsigned integer.";
511 this->SetError(e.str().c_str());
517 else if(arg_mode == arg_length_maximum)
520 if(sscanf(args[i].c_str(), "%d", &len) != 1 || len < 0)
523 e << "STRINGS option LENGTH_MAXIMUM value \""
524 << args[i] << "\" is not an unsigned integer.";
525 this->SetError(e.str().c_str());
531 else if(arg_mode == arg_regex)
533 if(!regex.compile(args[i].c_str()))
536 e << "STRINGS option REGEX value \""
537 << args[i] << "\" could not be compiled.";
538 this->SetError(e.str().c_str());
547 e << "STRINGS given unknown argument \""
549 this->SetError(e.str().c_str());
554 if (hex_conversion_enabled)
556 // TODO: should work without temp file, but just on a memory buffer
557 std::string binaryFileName = this->Makefile->GetCurrentOutputDirectory();
558 binaryFileName += cmake::GetCMakeFilesDirectory();
559 binaryFileName += "/FileCommandStringsBinaryFile";
560 if(cmHexFileConverter::TryConvert(fileName.c_str(),binaryFileName.c_str()))
562 fileName = binaryFileName;
566 // Open the specified file.
567 #if defined(_WIN32) || defined(__CYGWIN__)
568 std::ifstream fin(fileName.c_str(), std::ios::in | std::ios::binary);
570 std::ifstream fin(fileName.c_str(), std::ios::in);
575 e << "STRINGS file \"" << fileName << "\" cannot be read.";
576 this->SetError(e.str().c_str());
580 // Parse strings out of the file.
582 std::vector<std::string> strings;
585 while((!limit_count || strings.size() < limit_count) &&
586 (limit_input < 0 || static_cast<int>(fin.tellg()) < limit_input) &&
587 (c = fin.get(), fin))
589 if(c == '\n' && !newline_consume)
591 // The current line has been terminated. Check if the current
592 // string matches the requirements. The length may now be as
593 // low as zero since blank lines are allowed.
594 if(s.length() >= minlen &&
595 (!have_regex || regex.find(s.c_str())))
597 output_size += static_cast<int>(s.size()) + 1;
598 if(limit_output >= 0 && output_size >= limit_output)
603 strings.push_back(s);
606 // Reset the string to empty.
611 // Ignore CR character to make output always have UNIX newlines.
613 else if((c >= 0x20 && c < 0x7F) || c == '\t' ||
614 (c == '\n' && newline_consume))
616 // This is an ASCII character that may be part of a string.
617 // Cast added to avoid compiler warning. Cast is ok because
618 // c is guaranteed to fit in char by the above if...
619 s += static_cast<char>(c);
623 // TODO: Support ENCODING option. See issue #10519.
624 // A non-string character has been found. Check if the current
625 // string matches the requirements. We require that the length
626 // be at least one no matter what the user specified.
627 if(s.length() >= minlen && s.length() >= 1 &&
628 (!have_regex || regex.find(s.c_str())))
630 output_size += static_cast<int>(s.size()) + 1;
631 if(limit_output >= 0 && output_size >= limit_output)
636 strings.push_back(s);
639 // Reset the string to empty.
643 // Terminate a string if the maximum length is reached.
644 if(maxlen > 0 && s.size() == maxlen)
646 if(s.length() >= minlen &&
647 (!have_regex || regex.find(s.c_str())))
649 output_size += static_cast<int>(s.size()) + 1;
650 if(limit_output >= 0 && output_size >= limit_output)
655 strings.push_back(s);
661 // If there is a non-empty current string we have hit the end of the
662 // input file or the input size limit. Check if the current string
663 // matches the requirements.
664 if((!limit_count || strings.size() < limit_count) &&
665 !s.empty() && s.length() >= minlen &&
666 (!have_regex || regex.find(s.c_str())))
668 output_size += static_cast<int>(s.size()) + 1;
669 if(limit_output < 0 || output_size < limit_output)
671 strings.push_back(s);
675 // Encode the result in a CMake list.
676 const char* sep = "";
678 for(std::vector<std::string>::const_iterator si = strings.begin();
679 si != strings.end(); ++si)
681 // Separate the strings in the output to make it a list.
685 // Store the string in the output, but escape semicolons to
686 // make sure it is a list.
687 std::string const& sr = *si;
688 for(unsigned int i=0; i < sr.size(); ++i)
698 // Save the output in a makefile variable.
699 this->Makefile->AddDefinition(outVar.c_str(), output.c_str());
703 //----------------------------------------------------------------------------
704 bool cmFileCommand::HandleGlobCommand(std::vector<std::string> const& args,
707 if ( args.size() < 2 )
709 this->SetError("GLOB requires at least a variable name");
713 std::vector<std::string>::const_iterator i = args.begin();
715 i++; // Get rid of subcommand
717 std::string variable = *i;
720 g.SetRecurse(recurse);
722 bool explicitFollowSymlinks = false;
723 cmPolicies::PolicyStatus status =
724 this->Makefile->GetPolicyStatus(cmPolicies::CMP0009);
729 case cmPolicies::NEW:
730 g.RecurseThroughSymlinksOff();
732 case cmPolicies::OLD:
733 case cmPolicies::WARN:
734 case cmPolicies::REQUIRED_IF_USED:
735 case cmPolicies::REQUIRED_ALWAYS:
736 g.RecurseThroughSymlinksOn();
741 std::string output = "";
743 for ( ; i != args.end(); ++i )
745 if ( recurse && (*i == "FOLLOW_SYMLINKS") )
747 explicitFollowSymlinks = true;
748 g.RecurseThroughSymlinksOn();
750 if ( i == args.end() )
753 "GLOB_RECURSE requires a glob expression after FOLLOW_SYMLINKS");
758 if ( *i == "RELATIVE" )
760 ++i; // skip RELATIVE
761 if ( i == args.end() )
763 this->SetError("GLOB requires a directory after the RELATIVE tag");
766 g.SetRelative(i->c_str());
770 this->SetError("GLOB requires a glob expression after the directory");
775 if ( !cmsys::SystemTools::FileIsFullPath(i->c_str()) )
777 std::string expr = this->Makefile->GetCurrentDirectory();
778 // Handle script mode
779 if ( expr.size() > 0 )
794 std::vector<std::string>::size_type cc;
795 std::vector<std::string>& files = g.GetFiles();
796 for ( cc = 0; cc < files.size(); cc ++ )
807 if(recurse && !explicitFollowSymlinks)
811 case cmPolicies::NEW:
812 // Correct behavior, yay!
814 case cmPolicies::OLD:
815 // Probably not really the expected behavior, but the author explicitly
816 // asked for the old behavior... no warning.
817 case cmPolicies::WARN:
818 // Possibly unexpected old behavior *and* we actually traversed
819 // symlinks without being explicitly asked to: warn the author.
820 if(g.GetFollowedSymlinkCount() != 0)
822 this->Makefile->IssueMessage(cmake::AUTHOR_WARNING,
823 this->Makefile->GetPolicies()->
824 GetPolicyWarning(cmPolicies::CMP0009));
827 case cmPolicies::REQUIRED_IF_USED:
828 case cmPolicies::REQUIRED_ALWAYS:
829 this->SetError("policy CMP0009 error");
830 this->Makefile->IssueMessage(cmake::FATAL_ERROR,
831 this->Makefile->GetPolicies()->
832 GetRequiredPolicyError(cmPolicies::CMP0009));
837 this->Makefile->AddDefinition(variable.c_str(), output.c_str());
841 //----------------------------------------------------------------------------
842 bool cmFileCommand::HandleMakeDirectoryCommand(
843 std::vector<std::string> const& args)
847 this->SetError("called with incorrect number of arguments");
851 std::vector<std::string>::const_iterator i = args.begin();
853 i++; // Get rid of subcommand
856 for ( ; i != args.end(); ++i )
858 const std::string* cdir = &(*i);
859 if ( !cmsys::SystemTools::FileIsFullPath(i->c_str()) )
861 expr = this->Makefile->GetCurrentDirectory();
865 if ( !this->Makefile->CanIWriteThisFile(cdir->c_str()) )
867 std::string e = "attempted to create a directory: " + *cdir
868 + " into a source directory.";
869 this->SetError(e.c_str());
870 cmSystemTools::SetFatalErrorOccured();
873 if ( !cmSystemTools::MakeDirectory(cdir->c_str()) )
875 std::string error = "problem creating directory: " + *cdir;
876 this->SetError(error.c_str());
883 //----------------------------------------------------------------------------
885 cmFileCommand::HandleDifferentCommand(std::vector<std::string> const& args)
888 FILE(DIFFERENT <variable> FILES <lhs> <rhs>)
891 // Evaluate arguments.
892 const char* file_lhs = 0;
893 const char* file_rhs = 0;
895 enum Doing { DoingNone, DoingVar, DoingFileLHS, DoingFileRHS };
896 Doing doing = DoingVar;
897 for(unsigned int i=1; i < args.size(); ++i)
899 if(args[i] == "FILES")
901 doing = DoingFileLHS;
903 else if(doing == DoingVar)
905 var = args[i].c_str();
908 else if(doing == DoingFileLHS)
910 file_lhs = args[i].c_str();
911 doing = DoingFileRHS;
913 else if(doing == DoingFileRHS)
915 file_rhs = args[i].c_str();
921 e << "DIFFERENT given unknown argument " << args[i];
922 this->SetError(e.str().c_str());
928 this->SetError("DIFFERENT not given result variable name.");
931 if(!file_lhs || !file_rhs)
933 this->SetError("DIFFERENT not given FILES option with two file names.");
937 // Compare the files.
939 cmSystemTools::FilesDiffer(file_lhs, file_rhs)? "1" : "0";
940 this->Makefile->AddDefinition(var, result);
944 //----------------------------------------------------------------------------
945 // File installation helper class.
948 cmFileCopier(cmFileCommand* command, const char* name = "COPY"):
949 FileCommand(command),
950 Makefile(command->GetMakefile()),
953 MatchlessFiles(true),
957 UseGivenPermissionsFile(false),
958 UseGivenPermissionsDir(false),
959 UseSourcePermissions(true),
963 virtual ~cmFileCopier() {}
965 bool Run(std::vector<std::string> const& args);
968 cmFileCommand* FileCommand;
969 cmMakefile* Makefile;
972 cmFileTimeComparison FileTimes;
974 // Whether to install a file not matching any expression.
977 // Permissions for files and directories installed by this object.
978 mode_t FilePermissions;
979 mode_t DirPermissions;
981 // Properties set by pattern and regex match rules.
982 struct MatchProperties
986 MatchProperties(): Exclude(false), Permissions(0) {}
989 friend struct MatchRule;
992 cmsys::RegularExpression Regex;
993 MatchProperties Properties;
994 std::string RegexString;
995 MatchRule(std::string const& regex):
996 Regex(regex.c_str()), RegexString(regex) {}
998 std::vector<MatchRule> MatchRules;
1000 // Get the properties from rules matching this input file.
1001 MatchProperties CollectMatchProperties(const char* file)
1003 // Match rules are case-insensitive on some platforms.
1004 #if defined(_WIN32) || defined(__APPLE__) || defined(__CYGWIN__)
1005 std::string lower = cmSystemTools::LowerCase(file);
1006 const char* file_to_match = lower.c_str();
1008 const char* file_to_match = file;
1011 // Collect properties from all matching rules.
1012 bool matched = false;
1013 MatchProperties result;
1014 for(std::vector<MatchRule>::iterator mr = this->MatchRules.begin();
1015 mr != this->MatchRules.end(); ++mr)
1017 if(mr->Regex.find(file_to_match))
1020 result.Exclude |= mr->Properties.Exclude;
1021 result.Permissions |= mr->Properties.Permissions;
1024 if(!matched && !this->MatchlessFiles)
1026 result.Exclude = !cmSystemTools::FileIsDirectory(file);
1031 bool SetPermissions(const char* toFile, mode_t permissions)
1033 if(permissions && !cmSystemTools::SetPermissions(toFile, permissions))
1036 e << this->Name << " cannot set permissions on \"" << toFile << "\"";
1037 this->FileCommand->SetError(e.str().c_str());
1043 // Translate an argument to a permissions bit.
1044 bool CheckPermissions(std::string const& arg, mode_t& permissions)
1046 if(arg == "OWNER_READ") { permissions |= mode_owner_read; }
1047 else if(arg == "OWNER_WRITE") { permissions |= mode_owner_write; }
1048 else if(arg == "OWNER_EXECUTE") { permissions |= mode_owner_execute; }
1049 else if(arg == "GROUP_READ") { permissions |= mode_group_read; }
1050 else if(arg == "GROUP_WRITE") { permissions |= mode_group_write; }
1051 else if(arg == "GROUP_EXECUTE") { permissions |= mode_group_execute; }
1052 else if(arg == "WORLD_READ") { permissions |= mode_world_read; }
1053 else if(arg == "WORLD_WRITE") { permissions |= mode_world_write; }
1054 else if(arg == "WORLD_EXECUTE") { permissions |= mode_world_execute; }
1055 else if(arg == "SETUID") { permissions |= mode_setuid; }
1056 else if(arg == "SETGID") { permissions |= mode_setgid; }
1060 e << this->Name << " given invalid permission \"" << arg << "\".";
1061 this->FileCommand->SetError(e.str().c_str());
1067 bool InstallSymlink(const char* fromFile, const char* toFile);
1068 bool InstallFile(const char* fromFile, const char* toFile,
1069 MatchProperties const& match_properties);
1070 bool InstallDirectory(const char* source, const char* destination,
1071 MatchProperties const& match_properties);
1072 virtual bool Install(const char* fromFile, const char* toFile);
1073 virtual std::string const& ToName(std::string const& fromName)
1074 { return fromName; }
1082 virtual void ReportCopy(const char*, Type, bool) {}
1083 virtual bool ReportMissing(const char* fromFile)
1085 // The input file does not exist and installation is not optional.
1087 e << this->Name << " cannot find \"" << fromFile << "\".";
1088 this->FileCommand->SetError(e.str().c_str());
1092 MatchRule* CurrentMatchRule;
1093 bool UseGivenPermissionsFile;
1094 bool UseGivenPermissionsDir;
1095 bool UseSourcePermissions;
1096 std::string Destination;
1097 std::vector<std::string> Files;
1100 virtual bool Parse(std::vector<std::string> const& args);
1109 DoingPermissionsFile,
1110 DoingPermissionsDir,
1111 DoingPermissionsMatch,
1114 virtual bool CheckKeyword(std::string const& arg);
1115 virtual bool CheckValue(std::string const& arg);
1117 void NotBeforeMatch(std::string const& arg)
1120 e << "option " << arg << " may not appear before PATTERN or REGEX.";
1121 this->FileCommand->SetError(e.str().c_str());
1122 this->Doing = DoingError;
1124 void NotAfterMatch(std::string const& arg)
1127 e << "option " << arg << " may not appear after PATTERN or REGEX.";
1128 this->FileCommand->SetError(e.str().c_str());
1129 this->Doing = DoingError;
1131 virtual void DefaultFilePermissions()
1133 // Use read/write permissions.
1134 this->FilePermissions = 0;
1135 this->FilePermissions |= mode_owner_read;
1136 this->FilePermissions |= mode_owner_write;
1137 this->FilePermissions |= mode_group_read;
1138 this->FilePermissions |= mode_world_read;
1140 virtual void DefaultDirectoryPermissions()
1142 // Use read/write/executable permissions.
1143 this->DirPermissions = 0;
1144 this->DirPermissions |= mode_owner_read;
1145 this->DirPermissions |= mode_owner_write;
1146 this->DirPermissions |= mode_owner_execute;
1147 this->DirPermissions |= mode_group_read;
1148 this->DirPermissions |= mode_group_execute;
1149 this->DirPermissions |= mode_world_read;
1150 this->DirPermissions |= mode_world_execute;
1154 //----------------------------------------------------------------------------
1155 bool cmFileCopier::Parse(std::vector<std::string> const& args)
1157 this->Doing = DoingFiles;
1158 for(unsigned int i=1; i < args.size(); ++i)
1160 // Check this argument.
1161 if(!this->CheckKeyword(args[i]) &&
1162 !this->CheckValue(args[i]))
1165 e << "called with unknown argument \"" << args[i] << "\".";
1166 this->FileCommand->SetError(e.str().c_str());
1170 // Quit if an argument is invalid.
1171 if(this->Doing == DoingError)
1177 // Require a destination.
1178 if(this->Destination.empty())
1181 e << this->Name << " given no DESTINATION";
1182 this->FileCommand->SetError(e.str().c_str());
1186 // If file permissions were not specified set default permissions.
1187 if(!this->UseGivenPermissionsFile && !this->UseSourcePermissions)
1189 this->DefaultFilePermissions();
1192 // If directory permissions were not specified set default permissions.
1193 if(!this->UseGivenPermissionsDir && !this->UseSourcePermissions)
1195 this->DefaultDirectoryPermissions();
1201 //----------------------------------------------------------------------------
1202 bool cmFileCopier::CheckKeyword(std::string const& arg)
1204 if(arg == "DESTINATION")
1206 if(this->CurrentMatchRule)
1208 this->NotAfterMatch(arg);
1212 this->Doing = DoingDestination;
1215 else if(arg == "PATTERN")
1217 this->Doing = DoingPattern;
1219 else if(arg == "REGEX")
1221 this->Doing = DoingRegex;
1223 else if(arg == "EXCLUDE")
1225 // Add this property to the current match rule.
1226 if(this->CurrentMatchRule)
1228 this->CurrentMatchRule->Properties.Exclude = true;
1229 this->Doing = DoingNone;
1233 this->NotBeforeMatch(arg);
1236 else if(arg == "PERMISSIONS")
1238 if(this->CurrentMatchRule)
1240 this->Doing = DoingPermissionsMatch;
1244 this->NotBeforeMatch(arg);
1247 else if(arg == "FILE_PERMISSIONS")
1249 if(this->CurrentMatchRule)
1251 this->NotAfterMatch(arg);
1255 this->Doing = DoingPermissionsFile;
1256 this->UseGivenPermissionsFile = true;
1259 else if(arg == "DIRECTORY_PERMISSIONS")
1261 if(this->CurrentMatchRule)
1263 this->NotAfterMatch(arg);
1267 this->Doing = DoingPermissionsDir;
1268 this->UseGivenPermissionsDir = true;
1271 else if(arg == "USE_SOURCE_PERMISSIONS")
1273 if(this->CurrentMatchRule)
1275 this->NotAfterMatch(arg);
1279 this->Doing = DoingNone;
1280 this->UseSourcePermissions = true;
1283 else if(arg == "NO_SOURCE_PERMISSIONS")
1285 if(this->CurrentMatchRule)
1287 this->NotAfterMatch(arg);
1291 this->Doing = DoingNone;
1292 this->UseSourcePermissions = false;
1295 else if(arg == "FILES_MATCHING")
1297 if(this->CurrentMatchRule)
1299 this->NotAfterMatch(arg);
1303 this->Doing = DoingNone;
1304 this->MatchlessFiles = false;
1314 //----------------------------------------------------------------------------
1315 bool cmFileCopier::CheckValue(std::string const& arg)
1320 if(arg.empty() || cmSystemTools::FileIsFullPath(arg.c_str()))
1322 this->Files.push_back(arg);
1326 std::string file = this->Makefile->GetCurrentDirectory();
1328 this->Files.push_back(file);
1331 case DoingDestination:
1332 if(arg.empty() || cmSystemTools::FileIsFullPath(arg.c_str()))
1334 this->Destination = arg;
1338 this->Destination = this->Makefile->GetCurrentOutputDirectory();
1339 this->Destination += "/" + arg;
1341 this->Doing = DoingNone;
1345 // Convert the pattern to a regular expression. Require a
1346 // leading slash and trailing end-of-string in the matched
1347 // string to make sure the pattern matches only whole file
1349 std::string regex = "/";
1350 regex += cmsys::Glob::PatternToRegex(arg, false);
1352 this->MatchRules.push_back(MatchRule(regex));
1353 this->CurrentMatchRule = &*(this->MatchRules.end()-1);
1354 if(this->CurrentMatchRule->Regex.is_valid())
1356 this->Doing = DoingNone;
1361 e << "could not compile PATTERN \"" << arg << "\".";
1362 this->FileCommand->SetError(e.str().c_str());
1363 this->Doing = DoingError;
1368 this->MatchRules.push_back(MatchRule(arg));
1369 this->CurrentMatchRule = &*(this->MatchRules.end()-1);
1370 if(this->CurrentMatchRule->Regex.is_valid())
1372 this->Doing = DoingNone;
1377 e << "could not compile REGEX \"" << arg << "\".";
1378 this->FileCommand->SetError(e.str().c_str());
1379 this->Doing = DoingError;
1382 case DoingPermissionsFile:
1383 if(!this->CheckPermissions(arg, this->FilePermissions))
1385 this->Doing = DoingError;
1388 case DoingPermissionsDir:
1389 if(!this->CheckPermissions(arg, this->DirPermissions))
1391 this->Doing = DoingError;
1394 case DoingPermissionsMatch:
1395 if(!this->CheckPermissions(
1396 arg, this->CurrentMatchRule->Properties.Permissions))
1398 this->Doing = DoingError;
1407 //----------------------------------------------------------------------------
1408 bool cmFileCopier::Run(std::vector<std::string> const& args)
1410 if(!this->Parse(args))
1415 std::vector<std::string> const& files = this->Files;
1416 for(std::vector<std::string>::size_type i = 0; i < files.size(); ++i)
1418 // Split the input file into its directory and name components.
1419 std::vector<std::string> fromPathComponents;
1420 cmSystemTools::SplitPath(files[i].c_str(), fromPathComponents);
1421 std::string fromName = *(fromPathComponents.end()-1);
1422 std::string fromDir = cmSystemTools::JoinPath(fromPathComponents.begin(),
1423 fromPathComponents.end()-1);
1425 // Compute the full path to the destination file.
1426 std::string toFile = this->Destination;
1427 std::string const& toName = this->ToName(fromName);
1434 // Construct the full path to the source file. The file name may
1435 // have been changed above.
1436 std::string fromFile = fromDir;
1437 if(!fromName.empty())
1440 fromFile += fromName;
1443 if(!this->Install(fromFile.c_str(), toFile.c_str()))
1451 //----------------------------------------------------------------------------
1452 bool cmFileCopier::Install(const char* fromFile, const char* toFile)
1457 e << "INSTALL encountered an empty string input file name.";
1458 this->FileCommand->SetError(e.str().c_str());
1462 // Collect any properties matching this file name.
1463 MatchProperties match_properties = this->CollectMatchProperties(fromFile);
1465 // Skip the file if it is excluded.
1466 if(match_properties.Exclude)
1471 if(cmSystemTools::SameFile(fromFile, toFile))
1475 else if(cmSystemTools::FileIsSymlink(fromFile))
1477 return this->InstallSymlink(fromFile, toFile);
1479 else if(cmSystemTools::FileIsDirectory(fromFile))
1481 return this->InstallDirectory(fromFile, toFile, match_properties);
1483 else if(cmSystemTools::FileExists(fromFile))
1485 return this->InstallFile(fromFile, toFile, match_properties);
1487 return this->ReportMissing(fromFile);
1490 //----------------------------------------------------------------------------
1491 bool cmFileCopier::InstallSymlink(const char* fromFile, const char* toFile)
1493 // Read the original symlink.
1494 std::string symlinkTarget;
1495 if(!cmSystemTools::ReadSymlink(fromFile, symlinkTarget))
1498 e << this->Name << " cannot read symlink \"" << fromFile
1499 << "\" to duplicate at \"" << toFile << "\".";
1500 this->FileCommand->SetError(e.str().c_str());
1504 // Compare the symlink value to that at the destination if not
1505 // always installing.
1509 std::string oldSymlinkTarget;
1510 if(cmSystemTools::ReadSymlink(toFile, oldSymlinkTarget))
1512 if(symlinkTarget == oldSymlinkTarget)
1519 // Inform the user about this file installation.
1520 this->ReportCopy(toFile, TypeLink, copy);
1524 // Remove the destination file so we can always create the symlink.
1525 cmSystemTools::RemoveFile(toFile);
1527 // Create the symlink.
1528 if(!cmSystemTools::CreateSymlink(symlinkTarget.c_str(), toFile))
1531 e << this->Name << " cannot duplicate symlink \"" << fromFile
1532 << "\" at \"" << toFile << "\".";
1533 this->FileCommand->SetError(e.str().c_str());
1541 //----------------------------------------------------------------------------
1542 bool cmFileCopier::InstallFile(const char* fromFile, const char* toFile,
1543 MatchProperties const& match_properties)
1545 // Determine whether we will copy the file.
1549 // If both files exist with the same time do not copy.
1550 if(!this->FileTimes.FileTimesDiffer(fromFile, toFile))
1556 // Inform the user about this file installation.
1557 this->ReportCopy(toFile, TypeFile, copy);
1560 if(copy && !cmSystemTools::CopyAFile(fromFile, toFile, true))
1563 e << this->Name << " cannot copy file \"" << fromFile
1564 << "\" to \"" << toFile << "\".";
1565 this->FileCommand->SetError(e.str().c_str());
1569 // Set the file modification time of the destination file.
1570 if(copy && !this->Always)
1572 // Add write permission so we can set the file time.
1573 // Permissions are set unconditionally below anyway.
1575 if(cmSystemTools::GetPermissions(toFile, perm))
1577 cmSystemTools::SetPermissions(toFile, perm | mode_owner_write);
1579 if (!cmSystemTools::CopyFileTime(fromFile, toFile))
1582 e << this->Name << " cannot set modification time on \""
1584 this->FileCommand->SetError(e.str().c_str());
1589 // Set permissions of the destination file.
1590 mode_t permissions = (match_properties.Permissions?
1591 match_properties.Permissions : this->FilePermissions);
1594 // No permissions were explicitly provided but the user requested
1595 // that the source file permissions be used.
1596 cmSystemTools::GetPermissions(fromFile, permissions);
1598 return this->SetPermissions(toFile, permissions);
1601 //----------------------------------------------------------------------------
1602 bool cmFileCopier::InstallDirectory(const char* source,
1603 const char* destination,
1604 MatchProperties const& match_properties)
1606 // Inform the user about this directory installation.
1607 this->ReportCopy(destination, TypeDir, true);
1609 // Make sure the destination directory exists.
1610 if(!cmSystemTools::MakeDirectory(destination))
1613 e << this->Name << " cannot make directory \"" << destination << "\": "
1614 << cmSystemTools::GetLastSystemError();
1615 this->FileCommand->SetError(e.str().c_str());
1619 // Compute the requested permissions for the destination directory.
1620 mode_t permissions = (match_properties.Permissions?
1621 match_properties.Permissions : this->DirPermissions);
1624 // No permissions were explicitly provided but the user requested
1625 // that the source directory permissions be used.
1626 cmSystemTools::GetPermissions(source, permissions);
1629 // Compute the set of permissions required on this directory to
1630 // recursively install files and subdirectories safely.
1631 mode_t required_permissions =
1632 mode_owner_read | mode_owner_write | mode_owner_execute;
1634 // If the required permissions are specified it is safe to set the
1635 // final permissions now. Otherwise we must add the required
1636 // permissions temporarily during file installation.
1637 mode_t permissions_before = 0;
1638 mode_t permissions_after = 0;
1639 if((permissions & required_permissions) == required_permissions)
1641 permissions_before = permissions;
1645 permissions_before = permissions | required_permissions;
1646 permissions_after = permissions;
1649 // Set the required permissions of the destination directory.
1650 if(!this->SetPermissions(destination, permissions_before))
1655 // Load the directory contents to traverse it recursively.
1656 cmsys::Directory dir;
1657 if(source && *source)
1661 unsigned long numFiles = static_cast<unsigned long>(dir.GetNumberOfFiles());
1662 for(unsigned long fileNum = 0; fileNum < numFiles; ++fileNum)
1664 if(!(strcmp(dir.GetFile(fileNum), ".") == 0 ||
1665 strcmp(dir.GetFile(fileNum), "..") == 0))
1667 cmsys_stl::string fromPath = source;
1669 fromPath += dir.GetFile(fileNum);
1670 std::string toPath = destination;
1672 toPath += dir.GetFile(fileNum);
1673 if(!this->Install(fromPath.c_str(), toPath.c_str()))
1680 // Set the requested permissions of the destination directory.
1681 return this->SetPermissions(destination, permissions_after);
1684 //----------------------------------------------------------------------------
1685 bool cmFileCommand::HandleCopyCommand(std::vector<std::string> const& args)
1687 cmFileCopier copier(this);
1688 return copier.Run(args);
1691 //----------------------------------------------------------------------------
1692 struct cmFileInstaller: public cmFileCopier
1694 cmFileInstaller(cmFileCommand* command):
1695 cmFileCopier(command, "INSTALL"),
1696 InstallType(cmInstallType_FILES),
1700 // Installation does not use source permissions by default.
1701 this->UseSourcePermissions = false;
1702 // Check whether to copy files always or only if they have changed.
1704 cmSystemTools::IsOn(cmSystemTools::GetEnv("CMAKE_INSTALL_ALWAYS"));
1705 // Get the current manifest.
1707 this->Makefile->GetSafeDefinition("CMAKE_INSTALL_MANIFEST_FILES");
1711 // Save the updated install manifest.
1712 this->Makefile->AddDefinition("CMAKE_INSTALL_MANIFEST_FILES",
1713 this->Manifest.c_str());
1717 cmInstallType InstallType;
1722 std::string Manifest;
1723 void ManifestAppend(std::string const& file)
1725 this->Manifest += ";";
1726 this->Manifest += file.substr(this->DestDirLength);
1729 virtual std::string const& ToName(std::string const& fromName)
1730 { return this->Rename.empty()? fromName : this->Rename; }
1732 virtual void ReportCopy(const char* toFile, Type type, bool copy)
1734 std::string message = (copy? "Installing: " : "Up-to-date: ");
1736 this->Makefile->DisplayStatus(message.c_str(), -1);
1739 // Add the file to the manifest.
1740 this->ManifestAppend(toFile);
1743 virtual bool ReportMissing(const char* fromFile)
1745 return (this->Optional ||
1746 this->cmFileCopier::ReportMissing(fromFile));
1748 virtual bool Install(const char* fromFile, const char* toFile)
1750 // Support installing from empty source to make a directory.
1751 if(this->InstallType == cmInstallType_DIRECTORY && !*fromFile)
1753 return this->InstallDirectory(fromFile, toFile, MatchProperties());
1755 return this->cmFileCopier::Install(fromFile, toFile);
1758 virtual bool Parse(std::vector<std::string> const& args);
1761 DoingType = DoingLast1,
1765 virtual bool CheckKeyword(std::string const& arg);
1766 virtual bool CheckValue(std::string const& arg);
1767 virtual void DefaultFilePermissions()
1769 this->cmFileCopier::DefaultFilePermissions();
1770 // Add execute permissions based on the target type.
1771 switch(this->InstallType)
1773 case cmInstallType_SHARED_LIBRARY:
1774 case cmInstallType_MODULE_LIBRARY:
1775 if(this->Makefile->IsOn("CMAKE_INSTALL_SO_NO_EXE"))
1779 case cmInstallType_EXECUTABLE:
1780 case cmInstallType_PROGRAMS:
1781 this->FilePermissions |= mode_owner_execute;
1782 this->FilePermissions |= mode_group_execute;
1783 this->FilePermissions |= mode_world_execute;
1788 bool GetTargetTypeFromString(const std::string& stype);
1789 bool HandleInstallDestination();
1792 //----------------------------------------------------------------------------
1793 bool cmFileInstaller::Parse(std::vector<std::string> const& args)
1795 if(!this->cmFileCopier::Parse(args))
1800 if(!this->Rename.empty())
1802 if(this->InstallType != cmInstallType_FILES &&
1803 this->InstallType != cmInstallType_PROGRAMS)
1805 this->FileCommand->SetError("INSTALL option RENAME may be used "
1806 "only with FILES or PROGRAMS.");
1809 if(this->Files.size() > 1)
1811 this->FileCommand->SetError("INSTALL option RENAME may be used "
1812 "only with one file.");
1817 if(!this->HandleInstallDestination())
1825 //----------------------------------------------------------------------------
1826 bool cmFileInstaller::CheckKeyword(std::string const& arg)
1830 if(this->CurrentMatchRule)
1832 this->NotAfterMatch(arg);
1836 this->Doing = DoingType;
1839 else if(arg == "FILES")
1841 if(this->CurrentMatchRule)
1843 this->NotAfterMatch(arg);
1847 this->Doing = DoingFiles;
1850 else if(arg == "RENAME")
1852 if(this->CurrentMatchRule)
1854 this->NotAfterMatch(arg);
1858 this->Doing = DoingRename;
1861 else if(arg == "OPTIONAL")
1863 if(this->CurrentMatchRule)
1865 this->NotAfterMatch(arg);
1869 this->Doing = DoingNone;
1870 this->Optional = true;
1873 else if(arg == "PERMISSIONS")
1875 if(this->CurrentMatchRule)
1877 this->Doing = DoingPermissionsMatch;
1881 // file(INSTALL) aliases PERMISSIONS to FILE_PERMISSIONS
1882 this->Doing = DoingPermissionsFile;
1883 this->UseGivenPermissionsFile = true;
1886 else if(arg == "DIR_PERMISSIONS")
1888 if(this->CurrentMatchRule)
1890 this->NotAfterMatch(arg);
1894 // file(INSTALL) aliases DIR_PERMISSIONS to DIRECTORY_PERMISSIONS
1895 this->Doing = DoingPermissionsDir;
1896 this->UseGivenPermissionsDir = true;
1899 else if(arg == "COMPONENTS" || arg == "CONFIGURATIONS" ||
1900 arg == "PROPERTIES")
1903 e << "INSTALL called with old-style " << arg << " argument. "
1904 << "This script was generated with an older version of CMake. "
1905 << "Re-run this cmake version on your build tree.";
1906 this->FileCommand->SetError(e.str().c_str());
1907 this->Doing = DoingError;
1911 return this->cmFileCopier::CheckKeyword(arg);
1916 //----------------------------------------------------------------------------
1917 bool cmFileInstaller::CheckValue(std::string const& arg)
1922 if(!this->GetTargetTypeFromString(arg))
1924 this->Doing = DoingError;
1931 return this->cmFileCopier::CheckValue(arg);
1936 //----------------------------------------------------------------------------
1937 bool cmFileInstaller
1938 ::GetTargetTypeFromString(const std::string& stype)
1940 if ( stype == "EXECUTABLE" )
1942 this->InstallType = cmInstallType_EXECUTABLE;
1944 else if ( stype == "FILE" )
1946 this->InstallType = cmInstallType_FILES;
1948 else if ( stype == "PROGRAM" )
1950 this->InstallType = cmInstallType_PROGRAMS;
1952 else if ( stype == "STATIC_LIBRARY" )
1954 this->InstallType = cmInstallType_STATIC_LIBRARY;
1956 else if ( stype == "SHARED_LIBRARY" )
1958 this->InstallType = cmInstallType_SHARED_LIBRARY;
1960 else if ( stype == "MODULE" )
1962 this->InstallType = cmInstallType_MODULE_LIBRARY;
1964 else if ( stype == "DIRECTORY" )
1966 this->InstallType = cmInstallType_DIRECTORY;
1971 e << "Option TYPE given uknown value \"" << stype << "\".";
1972 this->FileCommand->SetError(e.str().c_str());
1978 //----------------------------------------------------------------------------
1979 bool cmFileInstaller::HandleInstallDestination()
1981 std::string& destination = this->Destination;
1983 // allow for / to be a valid destination
1984 if ( destination.size() < 2 && destination != "/" )
1986 this->FileCommand->SetError("called with inapropriate arguments. "
1987 "No DESTINATION provided or .");
1991 const char* destdir = cmSystemTools::GetEnv("DESTDIR");
1992 if ( destdir && *destdir )
1994 std::string sdestdir = destdir;
1995 cmSystemTools::ConvertToUnixSlashes(sdestdir);
1996 char ch1 = destination[0];
1997 char ch2 = destination[1];
1999 if ( destination.size() > 2 )
2001 ch3 = destination[2];
2007 if (((ch1 >= 'a' && ch1 <= 'z') || (ch1 >= 'A' && ch1 <= 'Z')) &&
2011 // let's do some destdir magic:
2024 // This is relative path on unix or windows. Since we are doing
2025 // destdir, this case does not make sense.
2026 this->FileCommand->SetError(
2027 "called with relative DESTINATION. This "
2028 "does not make sense when using DESTDIR. Specify "
2029 "absolute path or remove DESTDIR environment variable.");
2037 // looks like a network path.
2038 std::string message = "called with network path DESTINATION. This "
2039 "does not make sense when using DESTDIR. Specify local "
2040 "absolute path or remove DESTDIR environment variable."
2042 message += destination;
2043 this->FileCommand->SetError(message.c_str());
2047 destination = sdestdir + (destination.c_str() + skip);
2048 this->DestDirLength = int(sdestdir.size());
2051 if ( !cmSystemTools::FileExists(destination.c_str()) )
2053 if ( !cmSystemTools::MakeDirectory(destination.c_str()) )
2055 std::string errstring = "cannot create directory: " + destination +
2056 ". Maybe need administrative privileges.";
2057 this->FileCommand->SetError(errstring.c_str());
2061 if ( !cmSystemTools::FileIsDirectory(destination.c_str()) )
2063 std::string errstring = "INSTALL destination: " + destination +
2064 " is not a directory.";
2065 this->FileCommand->SetError(errstring.c_str());
2071 //----------------------------------------------------------------------------
2073 cmFileCommand::HandleRPathChangeCommand(std::vector<std::string> const& args)
2075 // Evaluate arguments.
2076 const char* file = 0;
2077 const char* oldRPath = 0;
2078 const char* newRPath = 0;
2079 enum Doing { DoingNone, DoingFile, DoingOld, DoingNew };
2080 Doing doing = DoingNone;
2081 for(unsigned int i=1; i < args.size(); ++i)
2083 if(args[i] == "OLD_RPATH")
2087 else if(args[i] == "NEW_RPATH")
2091 else if(args[i] == "FILE")
2095 else if(doing == DoingFile)
2097 file = args[i].c_str();
2100 else if(doing == DoingOld)
2102 oldRPath = args[i].c_str();
2105 else if(doing == DoingNew)
2107 newRPath = args[i].c_str();
2113 e << "RPATH_CHANGE given unknown argument " << args[i];
2114 this->SetError(e.str().c_str());
2120 this->SetError("RPATH_CHANGE not given FILE option.");
2125 this->SetError("RPATH_CHANGE not given OLD_RPATH option.");
2130 this->SetError("RPATH_CHANGE not given NEW_RPATH option.");
2133 if(!cmSystemTools::FileExists(file, true))
2136 e << "RPATH_CHANGE given FILE \"" << file << "\" that does not exist.";
2137 this->SetError(e.str().c_str());
2140 bool success = true;
2141 cmSystemToolsFileTime* ft = cmSystemTools::FileTimeNew();
2142 bool have_ft = cmSystemTools::FileTimeGet(file, ft);
2145 if(!cmSystemTools::ChangeRPath(file, oldRPath, newRPath, &emsg, &changed))
2148 e << "RPATH_CHANGE could not write new RPATH:\n"
2149 << " " << newRPath << "\n"
2151 << " " << file << "\n"
2153 this->SetError(e.str().c_str());
2160 std::string message = "Set runtime path of \"";
2162 message += "\" to \"";
2163 message += newRPath;
2165 this->Makefile->DisplayStatus(message.c_str(), -1);
2169 cmSystemTools::FileTimeSet(file, ft);
2172 cmSystemTools::FileTimeDelete(ft);
2176 //----------------------------------------------------------------------------
2178 cmFileCommand::HandleRPathRemoveCommand(std::vector<std::string> const& args)
2180 // Evaluate arguments.
2181 const char* file = 0;
2182 enum Doing { DoingNone, DoingFile };
2183 Doing doing = DoingNone;
2184 for(unsigned int i=1; i < args.size(); ++i)
2186 if(args[i] == "FILE")
2190 else if(doing == DoingFile)
2192 file = args[i].c_str();
2198 e << "RPATH_REMOVE given unknown argument " << args[i];
2199 this->SetError(e.str().c_str());
2205 this->SetError("RPATH_REMOVE not given FILE option.");
2208 if(!cmSystemTools::FileExists(file, true))
2211 e << "RPATH_REMOVE given FILE \"" << file << "\" that does not exist.";
2212 this->SetError(e.str().c_str());
2215 bool success = true;
2216 cmSystemToolsFileTime* ft = cmSystemTools::FileTimeNew();
2217 bool have_ft = cmSystemTools::FileTimeGet(file, ft);
2220 if(!cmSystemTools::RemoveRPath(file, &emsg, &removed))
2223 e << "RPATH_REMOVE could not remove RPATH from file:\n"
2224 << " " << file << "\n"
2226 this->SetError(e.str().c_str());
2233 std::string message = "Removed runtime path from \"";
2236 this->Makefile->DisplayStatus(message.c_str(), -1);
2240 cmSystemTools::FileTimeSet(file, ft);
2243 cmSystemTools::FileTimeDelete(ft);
2247 //----------------------------------------------------------------------------
2249 cmFileCommand::HandleRPathCheckCommand(std::vector<std::string> const& args)
2251 // Evaluate arguments.
2252 const char* file = 0;
2253 const char* rpath = 0;
2254 enum Doing { DoingNone, DoingFile, DoingRPath };
2255 Doing doing = DoingNone;
2256 for(unsigned int i=1; i < args.size(); ++i)
2258 if(args[i] == "RPATH")
2262 else if(args[i] == "FILE")
2266 else if(doing == DoingFile)
2268 file = args[i].c_str();
2271 else if(doing == DoingRPath)
2273 rpath = args[i].c_str();
2279 e << "RPATH_CHECK given unknown argument " << args[i];
2280 this->SetError(e.str().c_str());
2286 this->SetError("RPATH_CHECK not given FILE option.");
2291 this->SetError("RPATH_CHECK not given RPATH option.");
2295 // If the file exists but does not have the desired RPath then
2296 // delete it. This is used during installation to re-install a file
2297 // if its RPath will change.
2298 if(cmSystemTools::FileExists(file, true) &&
2299 !cmSystemTools::CheckRPath(file, rpath))
2301 cmSystemTools::RemoveFile(file);
2307 //----------------------------------------------------------------------------
2308 bool cmFileCommand::HandleInstallCommand(std::vector<std::string> const& args)
2310 cmFileInstaller installer(this);
2311 return installer.Run(args);
2314 //----------------------------------------------------------------------------
2315 bool cmFileCommand::HandleRelativePathCommand(
2316 std::vector<std::string> const& args)
2318 if(args.size() != 4 )
2320 this->SetError("RELATIVE_PATH called with incorrect number of arguments");
2324 const std::string& outVar = args[1];
2325 const std::string& directoryName = args[2];
2326 const std::string& fileName = args[3];
2328 if(!cmSystemTools::FileIsFullPath(directoryName.c_str()))
2330 std::string errstring =
2331 "RELATIVE_PATH must be passed a full path to the directory: "
2333 this->SetError(errstring.c_str());
2336 if(!cmSystemTools::FileIsFullPath(fileName.c_str()))
2338 std::string errstring =
2339 "RELATIVE_PATH must be passed a full path to the file: "
2341 this->SetError(errstring.c_str());
2345 std::string res = cmSystemTools::RelativePath(directoryName.c_str(),
2347 this->Makefile->AddDefinition(outVar.c_str(),
2353 //----------------------------------------------------------------------------
2354 bool cmFileCommand::HandleRename(std::vector<std::string> const& args)
2356 if(args.size() != 3)
2358 this->SetError("RENAME given incorrect number of arguments.");
2362 // Compute full path for old and new names.
2363 std::string oldname = args[1];
2364 if(!cmsys::SystemTools::FileIsFullPath(oldname.c_str()))
2366 oldname = this->Makefile->GetCurrentDirectory();
2367 oldname += "/" + args[1];
2369 std::string newname = args[2];
2370 if(!cmsys::SystemTools::FileIsFullPath(newname.c_str()))
2372 newname = this->Makefile->GetCurrentDirectory();
2373 newname += "/" + args[2];
2376 if(!cmSystemTools::RenameFile(oldname.c_str(), newname.c_str()))
2378 std::string err = cmSystemTools::GetLastSystemError();
2380 e << "RENAME failed to rename\n"
2381 << " " << oldname << "\n"
2383 << " " << newname << "\n"
2384 << "because: " << err << "\n";
2385 this->SetError(e.str().c_str());
2392 //----------------------------------------------------------------------------
2393 bool cmFileCommand::HandleRemove(std::vector<std::string> const& args,
2397 std::string message;
2398 std::vector<std::string>::const_iterator i = args.begin();
2400 i++; // Get rid of subcommand
2401 for(;i != args.end(); ++i)
2403 std::string fileName = *i;
2404 if(!cmsys::SystemTools::FileIsFullPath(fileName.c_str()))
2406 fileName = this->Makefile->GetCurrentDirectory();
2407 fileName += "/" + *i;
2410 if(cmSystemTools::FileIsDirectory(fileName.c_str()) && recurse)
2412 cmSystemTools::RemoveADirectory(fileName.c_str());
2416 cmSystemTools::RemoveFile(fileName.c_str());
2422 //----------------------------------------------------------------------------
2423 bool cmFileCommand::HandleCMakePathCommand(std::vector<std::string>
2427 std::vector<std::string>::const_iterator i = args.begin();
2428 if(args.size() != 3)
2430 this->SetError("FILE([TO_CMAKE_PATH|TO_NATIVE_PATH] path result) must be "
2431 "called with exactly three arguments.");
2434 i++; // Get rid of subcommand
2435 #if defined(_WIN32) && !defined(__CYGWIN__)
2440 std::vector<cmsys::String> path = cmSystemTools::SplitString(i->c_str(),
2443 const char* var = i->c_str();
2445 for(std::vector<cmsys::String>::iterator j = path.begin();
2446 j != path.end(); ++j)
2448 if(j != path.begin())
2454 cmSystemTools::ConvertToUnixSlashes(*j);
2458 *j = cmSystemTools::ConvertToOutputPath(j->c_str());
2459 // remove double quotes in the path
2460 cmsys::String& s = *j;
2462 if(s.size() > 1 && s[0] == '\"' && s[s.size()-1] == '\"')
2464 s = s.substr(1,s.size()-2);
2469 this->Makefile->AddDefinition(var, value.c_str());
2474 #if defined(CMAKE_BUILD_WITH_CMAKE)
2476 // Stuff for curl download/upload
2477 typedef std::vector<char> cmFileCommandVectorOfChar;
2482 cmWriteToFileCallback(void *ptr, size_t size, size_t nmemb,
2485 register int realsize = (int)(size * nmemb);
2486 std::ofstream* fout = static_cast<std::ofstream*>(data);
2487 const char* chPtr = static_cast<char*>(ptr);
2488 fout->write(chPtr, realsize);
2494 cmWriteToMemoryCallback(void *ptr, size_t size, size_t nmemb,
2497 register int realsize = (int)(size * nmemb);
2498 cmFileCommandVectorOfChar *vec
2499 = static_cast<cmFileCommandVectorOfChar*>(data);
2500 const char* chPtr = static_cast<char*>(ptr);
2501 vec->insert(vec->end(), chPtr, chPtr + realsize);
2507 cmFileCommandCurlDebugCallback(CURL *, curl_infotype, char *chPtr,
2508 size_t size, void *data)
2510 cmFileCommandVectorOfChar *vec
2511 = static_cast<cmFileCommandVectorOfChar*>(data);
2512 vec->insert(vec->end(), chPtr, chPtr + size);
2517 class cURLProgressHelper
2520 cURLProgressHelper(cmFileCommand *fc, const char *text)
2522 this->CurrentPercentage = -1;
2523 this->FileCommand = fc;
2527 bool UpdatePercentage(double value, double total, std::string &status)
2529 int OldPercentage = this->CurrentPercentage;
2533 this->CurrentPercentage = static_cast<int>(value/total*100.0 + 0.5);
2536 bool updated = (OldPercentage != this->CurrentPercentage);
2540 cmOStringStream oss;
2541 oss << "[" << this->Text << " " << this->CurrentPercentage
2549 cmFileCommand *GetFileCommand()
2551 return this->FileCommand;
2555 int CurrentPercentage;
2556 cmFileCommand *FileCommand;
2562 cmFileDownloadProgressCallback(void *clientp,
2563 double dltotal, double dlnow,
2564 double ultotal, double ulnow)
2566 cURLProgressHelper *helper =
2567 reinterpret_cast<cURLProgressHelper *>(clientp);
2569 static_cast<void>(ultotal);
2570 static_cast<void>(ulnow);
2573 if (helper->UpdatePercentage(dlnow, dltotal, status))
2575 cmFileCommand *fc = helper->GetFileCommand();
2576 cmMakefile *mf = fc->GetMakefile();
2577 mf->DisplayStatus(status.c_str(), -1);
2585 cmFileUploadProgressCallback(void *clientp,
2586 double dltotal, double dlnow,
2587 double ultotal, double ulnow)
2589 cURLProgressHelper *helper =
2590 reinterpret_cast<cURLProgressHelper *>(clientp);
2592 static_cast<void>(dltotal);
2593 static_cast<void>(dlnow);
2596 if (helper->UpdatePercentage(ulnow, ultotal, status))
2598 cmFileCommand *fc = helper->GetFileCommand();
2599 cmMakefile *mf = fc->GetMakefile();
2600 mf->DisplayStatus(status.c_str(), -1);
2613 cURLEasyGuard(CURL * easy)
2617 ~cURLEasyGuard(void)
2621 ::curl_easy_cleanup(this->Easy);
2625 inline void release(void)
2639 #define check_curl_result(result, errstr) \
2640 if (result != CURLE_OK) \
2642 std::string e(errstr); \
2643 e += ::curl_easy_strerror(result); \
2644 this->SetError(e.c_str()); \
2650 cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args)
2652 #if defined(CMAKE_BUILD_WITH_CMAKE)
2653 std::vector<std::string>::const_iterator i = args.begin();
2656 this->SetError("DOWNLOAD must be called with at least three arguments.");
2659 ++i; // Get rid of subcommand
2660 std::string url = *i;
2662 std::string file = *i;
2666 long inactivity_timeout = 0;
2667 std::string verboseLog;
2668 std::string statusVar;
2669 std::string expectedMD5sum;
2670 bool showProgress = false;
2672 while(i != args.end())
2679 timeout = atol(i->c_str());
2683 this->SetError("DOWNLOAD missing time for TIMEOUT.");
2687 else if(*i == "INACTIVITY_TIMEOUT")
2692 inactivity_timeout = atol(i->c_str());
2696 this->SetError("DOWNLOAD missing time for INACTIVITY_TIMEOUT.");
2700 else if(*i == "LOG")
2703 if( i == args.end())
2705 this->SetError("DOWNLOAD missing VAR for LOG.");
2710 else if(*i == "STATUS")
2713 if( i == args.end())
2715 this->SetError("DOWNLOAD missing VAR for STATUS.");
2720 else if(*i == "EXPECTED_MD5")
2723 if( i == args.end())
2725 this->SetError("DOWNLOAD missing sum value for EXPECTED_MD5.");
2728 expectedMD5sum = cmSystemTools::LowerCase(*i);
2730 else if(*i == "SHOW_PROGRESS")
2732 showProgress = true;
2737 // If file exists already, and caller specified an expected md5 sum,
2738 // and the existing file already has the expected md5 sum, then simply
2741 if(cmSystemTools::FileExists(file.c_str()) &&
2742 !expectedMD5sum.empty())
2744 char computedMD5[32];
2746 if (!cmSystemTools::ComputeFileMD5(file.c_str(), computedMD5))
2748 this->SetError("DOWNLOAD cannot compute MD5 sum on pre-existing file");
2752 std::string actualMD5sum = cmSystemTools::LowerCase(
2753 std::string(computedMD5, 32));
2755 if (expectedMD5sum == actualMD5sum)
2757 if(statusVar.size())
2759 cmOStringStream result;
2760 result << (int)0 << ";\""
2761 "returning early: file already exists with expected MD5 sum\"";
2762 this->Makefile->AddDefinition(statusVar.c_str(),
2763 result.str().c_str());
2770 // Make sure parent directory exists so we can write to the file
2771 // as we receive downloaded bits from curl...
2773 std::string dir = cmSystemTools::GetFilenamePath(file.c_str());
2774 if(!cmSystemTools::FileExists(dir.c_str()) &&
2775 !cmSystemTools::MakeDirectory(dir.c_str()))
2777 std::string errstring = "DOWNLOAD error: cannot create directory '"
2778 + dir + "' - Specify file by full path name and verify that you "
2779 "have directory creation and file write privileges.";
2780 this->SetError(errstring.c_str());
2784 std::ofstream fout(file.c_str(), std::ios::binary);
2787 this->SetError("DOWNLOAD cannot open file for write.");
2792 ::curl_global_init(CURL_GLOBAL_DEFAULT);
2793 curl = ::curl_easy_init();
2796 this->SetError("DOWNLOAD error initializing curl.");
2800 cURLEasyGuard g_curl(curl);
2802 ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
2803 check_curl_result(res, "DOWNLOAD cannot set url: ");
2805 // enable HTTP ERROR parsing
2806 res = ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
2807 check_curl_result(res, "DOWNLOAD cannot set http failure option: ");
2809 res = ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
2810 cmWriteToFileCallback);
2811 check_curl_result(res, "DOWNLOAD cannot set write function: ");
2813 res = ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
2814 cmFileCommandCurlDebugCallback);
2815 check_curl_result(res, "DOWNLOAD cannot set debug function: ");
2817 cmFileCommandVectorOfChar chunkDebug;
2819 res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&fout);
2820 check_curl_result(res, "DOWNLOAD cannot set write data: ");
2822 res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)&chunkDebug);
2823 check_curl_result(res, "DOWNLOAD cannot set debug data: ");
2825 res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
2826 check_curl_result(res, "DOWNLOAD cannot set follow-redirect option: ");
2828 if(verboseLog.size())
2830 res = ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
2831 check_curl_result(res, "DOWNLOAD cannot set verbose: ");
2836 res = ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout );
2837 check_curl_result(res, "DOWNLOAD cannot set timeout: ");
2840 if(inactivity_timeout > 0)
2842 // Give up if there is no progress for a long time.
2843 ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
2844 ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, inactivity_timeout);
2847 // Need the progress helper's scope to last through the duration of
2848 // the curl_easy_perform call... so this object is declared at function
2849 // scope intentionally, rather than inside the "if(showProgress)"
2852 cURLProgressHelper helper(this, "download");
2856 res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
2857 check_curl_result(res, "DOWNLOAD cannot set noprogress value: ");
2859 res = ::curl_easy_setopt(curl,
2860 CURLOPT_PROGRESSFUNCTION, cmFileDownloadProgressCallback);
2861 check_curl_result(res, "DOWNLOAD cannot set progress function: ");
2863 res = ::curl_easy_setopt(curl,
2864 CURLOPT_PROGRESSDATA, reinterpret_cast<void*>(&helper));
2865 check_curl_result(res, "DOWNLOAD cannot set progress data: ");
2868 res = ::curl_easy_perform(curl);
2870 /* always cleanup */
2872 ::curl_easy_cleanup(curl);
2874 if(statusVar.size())
2876 cmOStringStream result;
2877 result << (int)res << ";\"" << ::curl_easy_strerror(res) << "\"";
2878 this->Makefile->AddDefinition(statusVar.c_str(),
2879 result.str().c_str());
2882 ::curl_global_cleanup();
2884 // Explicitly flush/close so we can measure the md5 accurately.
2889 // Verify MD5 sum if requested:
2891 if (!expectedMD5sum.empty())
2893 char computedMD5[32];
2895 if (!cmSystemTools::ComputeFileMD5(file.c_str(), computedMD5))
2897 this->SetError("DOWNLOAD cannot compute MD5 sum on downloaded file");
2901 std::string actualMD5sum = cmSystemTools::LowerCase(
2902 std::string(computedMD5, 32));
2904 if (expectedMD5sum != actualMD5sum)
2906 cmOStringStream oss;
2907 oss << "DOWNLOAD MD5 mismatch" << std::endl
2908 << " for file: [" << file << "]" << std::endl
2909 << " expected MD5 sum: [" << expectedMD5sum << "]" << std::endl
2910 << " actual MD5 sum: [" << actualMD5sum << "]" << std::endl
2912 this->SetError(oss.str().c_str());
2917 if(chunkDebug.size())
2919 chunkDebug.push_back(0);
2920 if(CURLE_OPERATION_TIMEOUTED == res)
2922 std::string output = &*chunkDebug.begin();
2924 if(verboseLog.size())
2926 this->Makefile->AddDefinition(verboseLog.c_str(),
2927 &*chunkDebug.begin());
2931 this->Makefile->AddDefinition(verboseLog.c_str(),
2932 &*chunkDebug.begin());
2937 this->SetError("DOWNLOAD not supported by bootstrap cmake.");
2944 cmFileCommand::HandleUploadCommand(std::vector<std::string> const& args)
2946 #if defined(CMAKE_BUILD_WITH_CMAKE)
2949 this->SetError("UPLOAD must be called with at least three arguments.");
2952 std::vector<std::string>::const_iterator i = args.begin();
2954 std::string filename = *i;
2956 std::string url = *i;
2960 long inactivity_timeout = 0;
2962 std::string statusVar;
2963 bool showProgress = false;
2965 while(i != args.end())
2972 timeout = atol(i->c_str());
2976 this->SetError("UPLOAD missing time for TIMEOUT.");
2980 else if(*i == "INACTIVITY_TIMEOUT")
2985 inactivity_timeout = atol(i->c_str());
2989 this->SetError("UPLOAD missing time for INACTIVITY_TIMEOUT.");
2993 else if(*i == "LOG")
2996 if( i == args.end())
2998 this->SetError("UPLOAD missing VAR for LOG.");
3003 else if(*i == "STATUS")
3006 if( i == args.end())
3008 this->SetError("UPLOAD missing VAR for STATUS.");
3013 else if(*i == "SHOW_PROGRESS")
3015 showProgress = true;
3021 // Open file for reading:
3023 FILE *fin = fopen(filename.c_str(), "rb");
3026 std::string errStr = "UPLOAD cannot open file '";
3027 errStr += filename + "' for reading.";
3028 this->SetError(errStr.c_str());
3033 if(::stat(filename.c_str(), &st))
3035 std::string errStr = "UPLOAD cannot stat file '";
3036 errStr += filename + "'.";
3037 this->SetError(errStr.c_str());
3043 ::curl_global_init(CURL_GLOBAL_DEFAULT);
3044 curl = ::curl_easy_init();
3047 this->SetError("UPLOAD error initializing curl.");
3052 cURLEasyGuard g_curl(curl);
3054 // enable HTTP ERROR parsing
3055 ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
3058 res = ::curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
3059 check_curl_result(res, "UPLOAD cannot set upload flag: ");
3061 res = ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
3062 check_curl_result(res, "UPLOAD cannot set url: ");
3064 res = ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
3065 cmWriteToMemoryCallback);
3066 check_curl_result(res, "UPLOAD cannot set write function: ");
3068 res = ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
3069 cmFileCommandCurlDebugCallback);
3070 check_curl_result(res, "UPLOAD cannot set debug function: ");
3072 cmFileCommandVectorOfChar chunkResponse;
3073 cmFileCommandVectorOfChar chunkDebug;
3075 res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunkResponse);
3076 check_curl_result(res, "UPLOAD cannot set write data: ");
3078 res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)&chunkDebug);
3079 check_curl_result(res, "UPLOAD cannot set debug data: ");
3081 res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
3082 check_curl_result(res, "UPLOAD cannot set follow-redirect option: ");
3086 res = ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
3087 check_curl_result(res, "UPLOAD cannot set verbose: ");
3092 res = ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout );
3093 check_curl_result(res, "UPLOAD cannot set timeout: ");
3096 if(inactivity_timeout > 0)
3098 // Give up if there is no progress for a long time.
3099 ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
3100 ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, inactivity_timeout);
3103 // Need the progress helper's scope to last through the duration of
3104 // the curl_easy_perform call... so this object is declared at function
3105 // scope intentionally, rather than inside the "if(showProgress)"
3108 cURLProgressHelper helper(this, "upload");
3112 res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
3113 check_curl_result(res, "UPLOAD cannot set noprogress value: ");
3115 res = ::curl_easy_setopt(curl,
3116 CURLOPT_PROGRESSFUNCTION, cmFileUploadProgressCallback);
3117 check_curl_result(res, "UPLOAD cannot set progress function: ");
3119 res = ::curl_easy_setopt(curl,
3120 CURLOPT_PROGRESSDATA, reinterpret_cast<void*>(&helper));
3121 check_curl_result(res, "UPLOAD cannot set progress data: ");
3124 // now specify which file to upload
3125 res = ::curl_easy_setopt(curl, CURLOPT_INFILE, fin);
3126 check_curl_result(res, "UPLOAD cannot set input file: ");
3128 // and give the size of the upload (optional)
3129 res = ::curl_easy_setopt(curl,
3130 CURLOPT_INFILESIZE, static_cast<long>(st.st_size));
3131 check_curl_result(res, "UPLOAD cannot set input file size: ");
3133 res = ::curl_easy_perform(curl);
3135 /* always cleanup */
3137 ::curl_easy_cleanup(curl);
3139 if(statusVar.size())
3141 cmOStringStream result;
3142 result << (int)res << ";\"" << ::curl_easy_strerror(res) << "\"";
3143 this->Makefile->AddDefinition(statusVar.c_str(),
3144 result.str().c_str());
3147 ::curl_global_cleanup();
3156 if(chunkResponse.size())
3158 chunkResponse.push_back(0);
3159 log += "Response:\n";
3160 log += &*chunkResponse.begin();
3164 if(chunkDebug.size())
3166 chunkDebug.push_back(0);
3168 log += &*chunkDebug.begin();
3172 this->Makefile->AddDefinition(logVar.c_str(), log.c_str());
3177 this->SetError("UPLOAD not supported by bootstrap cmake.");