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 "cmStringCommand.h"
13 #include "cmCryptoHash.h"
15 #include <cmsys/RegularExpression.hxx>
16 #include <cmsys/SystemTools.hxx>
18 #include <stdlib.h> // required for atoi
22 #include <cmTimestamp.h>
24 //----------------------------------------------------------------------------
26 ::InitialPass(std::vector<std::string> const& args, cmExecutionStatus &)
30 this->SetError("must be called with at least one argument.");
34 const std::string &subCommand = args[0];
35 if(subCommand == "REGEX")
37 return this->HandleRegexCommand(args);
39 else if(subCommand == "REPLACE")
41 return this->HandleReplaceCommand(args);
43 else if ( subCommand == "MD5" ||
44 subCommand == "SHA1" ||
45 subCommand == "SHA224" ||
46 subCommand == "SHA256" ||
47 subCommand == "SHA384" ||
48 subCommand == "SHA512" )
50 return this->HandleHashCommand(args);
52 else if(subCommand == "TOLOWER")
54 return this->HandleToUpperLowerCommand(args, false);
56 else if(subCommand == "TOUPPER")
58 return this->HandleToUpperLowerCommand(args, true);
60 else if(subCommand == "COMPARE")
62 return this->HandleCompareCommand(args);
64 else if(subCommand == "ASCII")
66 return this->HandleAsciiCommand(args);
68 else if(subCommand == "CONFIGURE")
70 return this->HandleConfigureCommand(args);
72 else if(subCommand == "LENGTH")
74 return this->HandleLengthCommand(args);
76 else if(subCommand == "SUBSTRING")
78 return this->HandleSubstringCommand(args);
80 else if(subCommand == "STRIP")
82 return this->HandleStripCommand(args);
84 else if(subCommand == "RANDOM")
86 return this->HandleRandomCommand(args);
88 else if(subCommand == "FIND")
90 return this->HandleFindCommand(args);
92 else if(subCommand == "TIMESTAMP")
94 return this->HandleTimestampCommand(args);
97 std::string e = "does not recognize sub-command "+subCommand;
98 this->SetError(e.c_str());
102 //----------------------------------------------------------------------------
103 bool cmStringCommand::HandleHashCommand(std::vector<std::string> const& args)
105 #if defined(CMAKE_BUILD_WITH_CMAKE)
109 e << args[0] << " requires an output variable and an input string";
110 this->SetError(e.str().c_str());
114 cmsys::auto_ptr<cmCryptoHash> hash(cmCryptoHash::New(args[0].c_str()));
117 std::string out = hash->HashString(args[2].c_str());
118 this->Makefile->AddDefinition(args[1].c_str(), out.c_str());
124 e << args[0] << " not available during bootstrap";
125 this->SetError(e.str().c_str());
130 //----------------------------------------------------------------------------
131 bool cmStringCommand::HandleToUpperLowerCommand(
132 std::vector<std::string> const& args, bool toUpper)
134 if ( args.size() < 3 )
136 this->SetError("no output variable specified");
140 std::string outvar = args[2];
145 output = cmSystemTools::UpperCase(args[1]);
149 output = cmSystemTools::LowerCase(args[1]);
152 // Store the output in the provided variable.
153 this->Makefile->AddDefinition(outvar.c_str(), output.c_str());
157 //----------------------------------------------------------------------------
158 bool cmStringCommand::HandleAsciiCommand(std::vector<std::string> const& args)
160 if ( args.size() < 3 )
162 this->SetError("No output variable specified");
165 std::string::size_type cc;
166 std::string outvar = args[args.size()-1];
167 std::string output = "";
168 for ( cc = 1; cc < args.size()-1; cc ++ )
170 int ch = atoi(args[cc].c_str());
171 if ( ch > 0 && ch < 256 )
173 output += static_cast<char>(ch);
177 std::string error = "Character with code ";
179 error += " does not exist.";
180 this->SetError(error.c_str());
184 // Store the output in the provided variable.
185 this->Makefile->AddDefinition(outvar.c_str(), output.c_str());
189 //----------------------------------------------------------------------------
190 bool cmStringCommand::HandleConfigureCommand(
191 std::vector<std::string> const& args)
193 if ( args.size() < 2 )
195 this->SetError("No input string specified.");
198 else if ( args.size() < 3 )
200 this->SetError("No output variable specified.");
205 bool escapeQuotes = false;
207 for(unsigned int i = 3; i < args.size(); ++i)
209 if(args[i] == "@ONLY")
213 else if(args[i] == "ESCAPE_QUOTES")
220 err << "Unrecognized argument \"" << args[i] << "\"";
221 this->SetError(err.str().c_str());
226 // Configure the string.
228 this->Makefile->ConfigureString(args[1], output, atOnly, escapeQuotes);
230 // Store the output in the provided variable.
231 this->Makefile->AddDefinition(args[2].c_str(), output.c_str());
236 //----------------------------------------------------------------------------
237 bool cmStringCommand::HandleRegexCommand(std::vector<std::string> const& args)
241 this->SetError("sub-command REGEX requires a mode to be specified.");
244 std::string mode = args[1];
249 this->SetError("sub-command REGEX, mode MATCH needs "
250 "at least 5 arguments total to command.");
253 return this->RegexMatch(args);
255 else if(mode == "MATCHALL")
259 this->SetError("sub-command REGEX, mode MATCHALL needs "
260 "at least 5 arguments total to command.");
263 return this->RegexMatchAll(args);
265 else if(mode == "REPLACE")
269 this->SetError("sub-command REGEX, mode REPLACE needs "
270 "at least 6 arguments total to command.");
273 return this->RegexReplace(args);
276 std::string e = "sub-command REGEX does not recognize mode "+mode;
277 this->SetError(e.c_str());
281 //----------------------------------------------------------------------------
282 bool cmStringCommand::RegexMatch(std::vector<std::string> const& args)
284 //"STRING(REGEX MATCH <regular_expression> <output variable>
285 // <input> [<input>...])\n";
286 std::string regex = args[2];
287 std::string outvar = args[3];
289 // Concatenate all the last arguments together.
290 std::string input = args[4];
291 for(unsigned int i=5; i < args.size(); ++i)
296 this->ClearMatches(this->Makefile);
297 // Compile the regular expression.
298 cmsys::RegularExpression re;
299 if(!re.compile(regex.c_str()))
302 "sub-command REGEX, mode MATCH failed to compile regex \""+regex+"\".";
303 this->SetError(e.c_str());
307 // Scan through the input for all matches.
309 if(re.find(input.c_str()))
311 this->StoreMatches(this->Makefile, re);
312 std::string::size_type l = re.start();
313 std::string::size_type r = re.end();
317 "sub-command REGEX, mode MATCH regex \""+regex+
318 "\" matched an empty string.";
319 this->SetError(e.c_str());
322 output = input.substr(l, r-l);
325 // Store the output in the provided variable.
326 this->Makefile->AddDefinition(outvar.c_str(), output.c_str());
330 //----------------------------------------------------------------------------
331 bool cmStringCommand::RegexMatchAll(std::vector<std::string> const& args)
333 //"STRING(REGEX MATCHALL <regular_expression> <output variable> <input>
335 std::string regex = args[2];
336 std::string outvar = args[3];
338 // Concatenate all the last arguments together.
339 std::string input = args[4];
340 for(unsigned int i=5; i < args.size(); ++i)
345 this->ClearMatches(this->Makefile);
346 // Compile the regular expression.
347 cmsys::RegularExpression re;
348 if(!re.compile(regex.c_str()))
351 "sub-command REGEX, mode MATCHALL failed to compile regex \""+
353 this->SetError(e.c_str());
357 // Scan through the input for all matches.
359 const char* p = input.c_str();
362 this->StoreMatches(this->Makefile, re);
363 std::string::size_type l = re.start();
364 std::string::size_type r = re.end();
367 std::string e = "sub-command REGEX, mode MATCHALL regex \""+
368 regex+"\" matched an empty string.";
369 this->SetError(e.c_str());
372 if(output.length() > 0)
376 output += std::string(p+l, r-l);
380 // Store the output in the provided variable.
381 this->Makefile->AddDefinition(outvar.c_str(), output.c_str());
385 //----------------------------------------------------------------------------
386 bool cmStringCommand::RegexReplace(std::vector<std::string> const& args)
388 //"STRING(REGEX REPLACE <regular_expression> <replace_expression>
389 // <output variable> <input> [<input>...])\n"
390 std::string regex = args[2];
391 std::string replace = args[3];
392 std::string outvar = args[4];
394 // Pull apart the replace expression to find the escaped [0-9] values.
395 std::vector<RegexReplacement> replacement;
396 std::string::size_type l = 0;
397 while(l < replace.length())
399 std::string::size_type r = replace.find("\\", l);
400 if(r == std::string::npos)
402 r = replace.length();
403 replacement.push_back(replace.substr(l, r-l));
409 replacement.push_back(replace.substr(l, r-l));
411 if(r == (replace.length()-1))
413 this->SetError("sub-command REGEX, mode REPLACE: "
414 "replace-expression ends in a backslash.");
417 if((replace[r+1] >= '0') && (replace[r+1] <= '9'))
419 replacement.push_back(replace[r+1]-'0');
421 else if(replace[r+1] == 'n')
423 replacement.push_back("\n");
425 else if(replace[r+1] == '\\')
427 replacement.push_back("\\");
431 std::string e = "sub-command REGEX, mode REPLACE: Unknown escape \"";
432 e += replace.substr(r, 2);
433 e += "\" in replace-expression.";
434 this->SetError(e.c_str());
442 // Concatenate all the last arguments together.
443 std::string input = args[5];
444 for(unsigned int i=6; i < args.size(); ++i)
449 this->ClearMatches(this->Makefile);
450 // Compile the regular expression.
451 cmsys::RegularExpression re;
452 if(!re.compile(regex.c_str()))
455 "sub-command REGEX, mode REPLACE failed to compile regex \""+
457 this->SetError(e.c_str());
461 // Scan through the input for all matches.
463 std::string::size_type base = 0;
464 while(re.find(input.c_str()+base))
466 this->StoreMatches(this->Makefile, re);
467 std::string::size_type l2 = re.start();
468 std::string::size_type r = re.end();
470 // Concatenate the part of the input that was not matched.
471 output += input.substr(base, l2);
473 // Make sure the match had some text.
476 std::string e = "sub-command REGEX, mode REPLACE regex \""+
477 regex+"\" matched an empty string.";
478 this->SetError(e.c_str());
482 // Concatenate the replacement for the match.
483 for(unsigned int i=0; i < replacement.size(); ++i)
485 if(replacement[i].number < 0)
487 // This is just a plain-text part of the replacement.
488 output += replacement[i].value;
492 // Replace with part of the match.
493 int n = replacement[i].number;
494 std::string::size_type start = re.start(n);
495 std::string::size_type end = re.end(n);
496 std::string::size_type len = input.length()-base;
497 if((start != std::string::npos) && (end != std::string::npos) &&
498 (start <= len) && (end <= len))
500 output += input.substr(base+start, end-start);
505 "sub-command REGEX, mode REPLACE: replace expression \""+
506 replace+"\" contains an out-of-range escape for regex \""+
508 this->SetError(e.c_str());
514 // Move past the match.
518 // Concatenate the text after the last match.
519 output += input.substr(base, input.length()-base);
521 // Store the output in the provided variable.
522 this->Makefile->AddDefinition(outvar.c_str(), output.c_str());
526 //----------------------------------------------------------------------------
527 void cmStringCommand::ClearMatches(cmMakefile* mf)
529 for (unsigned int i=0; i<10; i++)
532 sprintf(name, "CMAKE_MATCH_%d", i);
533 mf->AddDefinition(name, "");
534 mf->MarkVariableAsUsed(name);
538 //----------------------------------------------------------------------------
539 void cmStringCommand::StoreMatches(cmMakefile* mf,cmsys::RegularExpression& re)
541 for (unsigned int i=0; i<10; i++)
544 sprintf(name, "CMAKE_MATCH_%d", i);
545 mf->AddDefinition(name, re.match(i).c_str());
546 mf->MarkVariableAsUsed(name);
550 //----------------------------------------------------------------------------
551 bool cmStringCommand::HandleFindCommand(std::vector<std::string> const&
554 // check if all required parameters were passed
555 if(args.size() < 4 || args.size() > 5)
557 this->SetError("sub-command FIND requires 3 or 4 parameters.");
561 // check if the reverse flag was set or not
562 bool reverseMode = false;
563 if(args.size() == 5 && args[4] == "REVERSE")
568 // if we have 5 arguments the last one must be REVERSE
569 if(args.size() == 5 && args[4] != "REVERSE")
571 this->SetError("sub-command FIND: unknown last parameter");
575 // local parameter names.
576 const std::string& sstring = args[1];
577 const std::string& schar = args[2];
578 const std::string& outvar = args[3];
580 // ensure that the user cannot accidentally specify REVERSE as a variable
581 if(outvar == "REVERSE")
583 this->SetError("sub-command FIND does not allow to select REVERSE as "
584 "the output variable. "
585 "Maybe you missed the actual output variable?");
589 // try to find the character and return its position
593 pos = sstring.find(schar);
597 pos = sstring.rfind(schar);
599 if(std::string::npos != pos)
603 this->Makefile->AddDefinition(outvar.c_str(), s.str().c_str());
607 // the character was not found, but this is not really an error
608 this->Makefile->AddDefinition(outvar.c_str(), "-1");
612 //----------------------------------------------------------------------------
613 bool cmStringCommand::HandleCompareCommand(std::vector<std::string> const&
618 this->SetError("sub-command COMPARE requires a mode to be specified.");
621 std::string mode = args[1];
622 if((mode == "EQUAL") || (mode == "NOTEQUAL") ||
623 (mode == "LESS") || (mode == "GREATER"))
627 std::string e = "sub-command COMPARE, mode ";
629 e += " needs at least 5 arguments total to command.";
630 this->SetError(e.c_str());
634 const std::string& left = args[2];
635 const std::string& right = args[3];
636 const std::string& outvar = args[4];
640 result = (left < right);
642 else if(mode == "GREATER")
644 result = (left > right);
646 else if(mode == "EQUAL")
648 result = (left == right);
650 else // if(mode == "NOTEQUAL")
652 result = !(left == right);
656 this->Makefile->AddDefinition(outvar.c_str(), "1");
660 this->Makefile->AddDefinition(outvar.c_str(), "0");
664 std::string e = "sub-command COMPARE does not recognize mode "+mode;
665 this->SetError(e.c_str());
669 //----------------------------------------------------------------------------
670 bool cmStringCommand::HandleReplaceCommand(std::vector<std::string> const&
675 this->SetError("sub-command REPLACE requires at least four arguments.");
679 const std::string& matchExpression = args[1];
680 const std::string& replaceExpression = args[2];
681 const std::string& variableName = args[3];
683 std::string input = args[4];
684 for(unsigned int i=5; i < args.size(); ++i)
689 cmsys::SystemTools::ReplaceString(input, matchExpression.c_str(),
690 replaceExpression.c_str());
692 this->Makefile->AddDefinition(variableName.c_str(), input.c_str());
696 //----------------------------------------------------------------------------
697 bool cmStringCommand::HandleSubstringCommand(std::vector<std::string> const&
702 this->SetError("sub-command SUBSTRING requires four arguments.");
706 const std::string& stringValue = args[1];
707 int begin = atoi(args[2].c_str());
708 int end = atoi(args[3].c_str());
709 const std::string& variableName = args[4];
711 size_t stringLength = stringValue.size();
712 int intStringLength = static_cast<int>(stringLength);
713 if ( begin < 0 || begin > intStringLength )
715 cmOStringStream ostr;
716 ostr << "begin index: " << begin << " is out of range 0 - "
718 this->SetError(ostr.str().c_str());
721 int leftOverLength = intStringLength - begin;
722 if ( end < -1 || end > leftOverLength )
724 cmOStringStream ostr;
725 ostr << "end index: " << end << " is out of range -1 - "
727 this->SetError(ostr.str().c_str());
731 this->Makefile->AddDefinition(variableName.c_str(),
732 stringValue.substr(begin, end).c_str());
736 //----------------------------------------------------------------------------
738 ::HandleLengthCommand(std::vector<std::string> const& args)
742 this->SetError("sub-command LENGTH requires two arguments.");
746 const std::string& stringValue = args[1];
747 const std::string& variableName = args[2];
749 size_t length = stringValue.size();
751 sprintf(buffer, "%d", static_cast<int>(length));
753 this->Makefile->AddDefinition(variableName.c_str(), buffer);
757 //----------------------------------------------------------------------------
758 bool cmStringCommand::HandleStripCommand(
759 std::vector<std::string> const& args)
763 this->SetError("sub-command STRIP requires two arguments.");
767 const std::string& stringValue = args[1];
768 const std::string& variableName = args[2];
769 size_t inStringLength = stringValue.size();
770 size_t startPos = inStringLength + 1;
772 const char* ptr = stringValue.c_str();
774 for ( cc = 0; cc < inStringLength; ++ cc )
776 if ( !isspace(*ptr) )
778 if ( startPos > inStringLength )
787 size_t outLength = 0;
789 // if the input string didn't contain any non-space characters, return
791 if (startPos > inStringLength)
798 outLength=endPos - startPos + 1;
801 this->Makefile->AddDefinition(variableName.c_str(),
802 stringValue.substr(startPos, outLength).c_str());
806 //----------------------------------------------------------------------------
808 ::HandleRandomCommand(std::vector<std::string> const& args)
810 if(args.size() < 2 || args.size() == 3 || args.size() == 5)
812 this->SetError("sub-command RANDOM requires at least one argument.");
816 static bool seeded = false;
817 bool force_seed = false;
818 unsigned int seed = 0;
820 const char cmStringCommandDefaultAlphabet[] = "qwertyuiopasdfghjklzxcvbnm"
821 "QWERTYUIOPASDFGHJKLZXCVBNM"
823 std::string alphabet;
825 if ( args.size() > 3 )
828 size_t stopAt = args.size() - 2;
830 for ( ; i < stopAt; ++i )
832 if ( args[i] == "LENGTH" )
835 length = atoi(args[i].c_str());
837 else if ( args[i] == "ALPHABET" )
842 else if ( args[i] == "RANDOM_SEED" )
845 seed = static_cast<unsigned int>(atoi(args[i].c_str()));
850 if ( !alphabet.size() )
852 alphabet = cmStringCommandDefaultAlphabet;
855 double sizeofAlphabet = static_cast<double>(alphabet.size());
856 if ( sizeofAlphabet < 1 )
858 this->SetError("sub-command RANDOM invoked with bad alphabet.");
863 this->SetError("sub-command RANDOM invoked with bad length.");
866 const std::string& variableName = args[args.size()-1];
868 std::vector<char> result;
870 if (!seeded || force_seed)
873 srand(force_seed? seed : cmSystemTools::RandomSeed());
876 const char* alphaPtr = alphabet.c_str();
878 for ( cc = 0; cc < length; cc ++ )
880 int idx=(int) (sizeofAlphabet* rand()/(RAND_MAX+1.0));
881 result.push_back(*(alphaPtr + idx));
885 this->Makefile->AddDefinition(variableName.c_str(), &*result.begin());
889 //----------------------------------------------------------------------------
891 ::HandleTimestampCommand(std::vector<std::string> const& args)
895 this->SetError("sub-command TIMESTAMP requires at least one argument.");
898 else if(args.size() > 4)
900 this->SetError("sub-command TIMESTAMP takes at most three arguments.");
904 unsigned int argsIndex = 1;
906 const std::string &outputVariable = args[argsIndex++];
908 std::string formatString;
909 if(args.size() > argsIndex && args[argsIndex] != "UTC")
911 formatString = args[argsIndex++];
914 bool utcFlag = false;
915 if(args.size() > argsIndex)
917 if(args[argsIndex] == "UTC")
923 std::string e = " TIMESTAMP sub-command does not recognize option " +
924 args[argsIndex] + ".";
925 this->SetError(e.c_str());
930 cmTimestamp timestamp;
931 std::string result = timestamp.CurrentTime(formatString, utcFlag);
932 this->Makefile->AddDefinition(outputVariable.c_str(), result.c_str());