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 //----------------------------------------------------------------------------
24 ::InitialPass(std::vector<std::string> const& args, cmExecutionStatus &)
28 this->SetError("must be called with at least one argument.");
32 const std::string &subCommand = args[0];
33 if(subCommand == "REGEX")
35 return this->HandleRegexCommand(args);
37 else if(subCommand == "REPLACE")
39 return this->HandleReplaceCommand(args);
41 else if ( subCommand == "MD5" ||
42 subCommand == "SHA1" ||
43 subCommand == "SHA224" ||
44 subCommand == "SHA256" ||
45 subCommand == "SHA384" ||
46 subCommand == "SHA512" )
48 return this->HandleHashCommand(args);
50 else if(subCommand == "TOLOWER")
52 return this->HandleToUpperLowerCommand(args, false);
54 else if(subCommand == "TOUPPER")
56 return this->HandleToUpperLowerCommand(args, true);
58 else if(subCommand == "COMPARE")
60 return this->HandleCompareCommand(args);
62 else if(subCommand == "ASCII")
64 return this->HandleAsciiCommand(args);
66 else if(subCommand == "CONFIGURE")
68 return this->HandleConfigureCommand(args);
70 else if(subCommand == "LENGTH")
72 return this->HandleLengthCommand(args);
74 else if(subCommand == "SUBSTRING")
76 return this->HandleSubstringCommand(args);
78 else if(subCommand == "STRIP")
80 return this->HandleStripCommand(args);
82 else if(subCommand == "RANDOM")
84 return this->HandleRandomCommand(args);
86 else if(subCommand == "FIND")
88 return this->HandleFindCommand(args);
91 std::string e = "does not recognize sub-command "+subCommand;
92 this->SetError(e.c_str());
96 //----------------------------------------------------------------------------
97 bool cmStringCommand::HandleHashCommand(std::vector<std::string> const& args)
99 #if defined(CMAKE_BUILD_WITH_CMAKE)
103 e << args[0] << " requires an output variable and an input string";
104 this->SetError(e.str().c_str());
108 cmsys::auto_ptr<cmCryptoHash> hash(cmCryptoHash::New(args[0].c_str()));
111 std::string out = hash->HashString(args[2].c_str());
112 this->Makefile->AddDefinition(args[1].c_str(), out.c_str());
118 e << args[0] << " not available during bootstrap";
119 this->SetError(e.str().c_str());
124 //----------------------------------------------------------------------------
125 bool cmStringCommand::HandleToUpperLowerCommand(
126 std::vector<std::string> const& args, bool toUpper)
128 if ( args.size() < 3 )
130 this->SetError("no output variable specified");
134 std::string outvar = args[2];
139 output = cmSystemTools::UpperCase(args[1]);
143 output = cmSystemTools::LowerCase(args[1]);
146 // Store the output in the provided variable.
147 this->Makefile->AddDefinition(outvar.c_str(), output.c_str());
151 //----------------------------------------------------------------------------
152 bool cmStringCommand::HandleAsciiCommand(std::vector<std::string> const& args)
154 if ( args.size() < 3 )
156 this->SetError("No output variable specified");
159 std::string::size_type cc;
160 std::string outvar = args[args.size()-1];
161 std::string output = "";
162 for ( cc = 1; cc < args.size()-1; cc ++ )
164 int ch = atoi(args[cc].c_str());
165 if ( ch > 0 && ch < 256 )
167 output += static_cast<char>(ch);
171 std::string error = "Character with code ";
173 error += " does not exist.";
174 this->SetError(error.c_str());
178 // Store the output in the provided variable.
179 this->Makefile->AddDefinition(outvar.c_str(), output.c_str());
183 //----------------------------------------------------------------------------
184 bool cmStringCommand::HandleConfigureCommand(
185 std::vector<std::string> const& args)
187 if ( args.size() < 2 )
189 this->SetError("No input string specified.");
192 else if ( args.size() < 3 )
194 this->SetError("No output variable specified.");
199 bool escapeQuotes = false;
201 for(unsigned int i = 3; i < args.size(); ++i)
203 if(args[i] == "@ONLY")
207 else if(args[i] == "ESCAPE_QUOTES")
214 err << "Unrecognized argument \"" << args[i] << "\"";
215 this->SetError(err.str().c_str());
220 // Configure the string.
222 this->Makefile->ConfigureString(args[1], output, atOnly, escapeQuotes);
224 // Store the output in the provided variable.
225 this->Makefile->AddDefinition(args[2].c_str(), output.c_str());
230 //----------------------------------------------------------------------------
231 bool cmStringCommand::HandleRegexCommand(std::vector<std::string> const& args)
235 this->SetError("sub-command REGEX requires a mode to be specified.");
238 std::string mode = args[1];
243 this->SetError("sub-command REGEX, mode MATCH needs "
244 "at least 5 arguments total to command.");
247 return this->RegexMatch(args);
249 else if(mode == "MATCHALL")
253 this->SetError("sub-command REGEX, mode MATCHALL needs "
254 "at least 5 arguments total to command.");
257 return this->RegexMatchAll(args);
259 else if(mode == "REPLACE")
263 this->SetError("sub-command REGEX, mode REPLACE needs "
264 "at least 6 arguments total to command.");
267 return this->RegexReplace(args);
270 std::string e = "sub-command REGEX does not recognize mode "+mode;
271 this->SetError(e.c_str());
275 //----------------------------------------------------------------------------
276 bool cmStringCommand::RegexMatch(std::vector<std::string> const& args)
278 //"STRING(REGEX MATCH <regular_expression> <output variable>
279 // <input> [<input>...])\n";
280 std::string regex = args[2];
281 std::string outvar = args[3];
283 // Concatenate all the last arguments together.
284 std::string input = args[4];
285 for(unsigned int i=5; i < args.size(); ++i)
290 this->ClearMatches(this->Makefile);
291 // Compile the regular expression.
292 cmsys::RegularExpression re;
293 if(!re.compile(regex.c_str()))
296 "sub-command REGEX, mode MATCH failed to compile regex \""+regex+"\".";
297 this->SetError(e.c_str());
301 // Scan through the input for all matches.
303 if(re.find(input.c_str()))
305 this->StoreMatches(this->Makefile, re);
306 std::string::size_type l = re.start();
307 std::string::size_type r = re.end();
311 "sub-command REGEX, mode MATCH regex \""+regex+
312 "\" matched an empty string.";
313 this->SetError(e.c_str());
316 output = input.substr(l, r-l);
319 // Store the output in the provided variable.
320 this->Makefile->AddDefinition(outvar.c_str(), output.c_str());
324 //----------------------------------------------------------------------------
325 bool cmStringCommand::RegexMatchAll(std::vector<std::string> const& args)
327 //"STRING(REGEX MATCHALL <regular_expression> <output variable> <input>
329 std::string regex = args[2];
330 std::string outvar = args[3];
332 // Concatenate all the last arguments together.
333 std::string input = args[4];
334 for(unsigned int i=5; i < args.size(); ++i)
339 this->ClearMatches(this->Makefile);
340 // Compile the regular expression.
341 cmsys::RegularExpression re;
342 if(!re.compile(regex.c_str()))
345 "sub-command REGEX, mode MATCHALL failed to compile regex \""+
347 this->SetError(e.c_str());
351 // Scan through the input for all matches.
353 const char* p = input.c_str();
356 this->StoreMatches(this->Makefile, re);
357 std::string::size_type l = re.start();
358 std::string::size_type r = re.end();
361 std::string e = "sub-command REGEX, mode MATCHALL regex \""+
362 regex+"\" matched an empty string.";
363 this->SetError(e.c_str());
366 if(output.length() > 0)
370 output += std::string(p+l, r-l);
374 // Store the output in the provided variable.
375 this->Makefile->AddDefinition(outvar.c_str(), output.c_str());
379 //----------------------------------------------------------------------------
380 bool cmStringCommand::RegexReplace(std::vector<std::string> const& args)
382 //"STRING(REGEX REPLACE <regular_expression> <replace_expression>
383 // <output variable> <input> [<input>...])\n"
384 std::string regex = args[2];
385 std::string replace = args[3];
386 std::string outvar = args[4];
388 // Pull apart the replace expression to find the escaped [0-9] values.
389 std::vector<RegexReplacement> replacement;
390 std::string::size_type l = 0;
391 while(l < replace.length())
393 std::string::size_type r = replace.find("\\", l);
394 if(r == std::string::npos)
396 r = replace.length();
397 replacement.push_back(replace.substr(l, r-l));
403 replacement.push_back(replace.substr(l, r-l));
405 if(r == (replace.length()-1))
407 this->SetError("sub-command REGEX, mode REPLACE: "
408 "replace-expression ends in a backslash.");
411 if((replace[r+1] >= '0') && (replace[r+1] <= '9'))
413 replacement.push_back(replace[r+1]-'0');
415 else if(replace[r+1] == 'n')
417 replacement.push_back("\n");
419 else if(replace[r+1] == '\\')
421 replacement.push_back("\\");
425 std::string e = "sub-command REGEX, mode REPLACE: Unknown escape \"";
426 e += replace.substr(r, 2);
427 e += "\" in replace-expression.";
428 this->SetError(e.c_str());
436 // Concatenate all the last arguments together.
437 std::string input = args[5];
438 for(unsigned int i=6; i < args.size(); ++i)
443 this->ClearMatches(this->Makefile);
444 // Compile the regular expression.
445 cmsys::RegularExpression re;
446 if(!re.compile(regex.c_str()))
449 "sub-command REGEX, mode REPLACE failed to compile regex \""+
451 this->SetError(e.c_str());
455 // Scan through the input for all matches.
457 std::string::size_type base = 0;
458 while(re.find(input.c_str()+base))
460 this->StoreMatches(this->Makefile, re);
461 std::string::size_type l2 = re.start();
462 std::string::size_type r = re.end();
464 // Concatenate the part of the input that was not matched.
465 output += input.substr(base, l2);
467 // Make sure the match had some text.
470 std::string e = "sub-command REGEX, mode REPLACE regex \""+
471 regex+"\" matched an empty string.";
472 this->SetError(e.c_str());
476 // Concatenate the replacement for the match.
477 for(unsigned int i=0; i < replacement.size(); ++i)
479 if(replacement[i].number < 0)
481 // This is just a plain-text part of the replacement.
482 output += replacement[i].value;
486 // Replace with part of the match.
487 int n = replacement[i].number;
488 std::string::size_type start = re.start(n);
489 std::string::size_type end = re.end(n);
490 std::string::size_type len = input.length()-base;
491 if((start != std::string::npos) && (end != std::string::npos) &&
492 (start <= len) && (end <= len))
494 output += input.substr(base+start, end-start);
499 "sub-command REGEX, mode REPLACE: replace expression \""+
500 replace+"\" contains an out-of-range escape for regex \""+
502 this->SetError(e.c_str());
508 // Move past the match.
512 // Concatenate the text after the last match.
513 output += input.substr(base, input.length()-base);
515 // Store the output in the provided variable.
516 this->Makefile->AddDefinition(outvar.c_str(), output.c_str());
520 //----------------------------------------------------------------------------
521 void cmStringCommand::ClearMatches(cmMakefile* mf)
523 for (unsigned int i=0; i<10; i++)
526 sprintf(name, "CMAKE_MATCH_%d", i);
527 mf->AddDefinition(name, "");
528 mf->MarkVariableAsUsed(name);
532 //----------------------------------------------------------------------------
533 void cmStringCommand::StoreMatches(cmMakefile* mf,cmsys::RegularExpression& re)
535 for (unsigned int i=0; i<10; i++)
538 sprintf(name, "CMAKE_MATCH_%d", i);
539 mf->AddDefinition(name, re.match(i).c_str());
540 mf->MarkVariableAsUsed(name);
544 //----------------------------------------------------------------------------
545 bool cmStringCommand::HandleFindCommand(std::vector<std::string> const&
548 // check if all required parameters were passed
549 if(args.size() < 4 || args.size() > 5)
551 this->SetError("sub-command FIND requires 3 or 4 parameters.");
555 // check if the reverse flag was set or not
556 bool reverseMode = false;
557 if(args.size() == 5 && args[4] == "REVERSE")
562 // if we have 5 arguments the last one must be REVERSE
563 if(args.size() == 5 && args[4] != "REVERSE")
565 this->SetError("sub-command FIND: unknown last parameter");
569 // local parameter names.
570 const std::string& sstring = args[1];
571 const std::string& schar = args[2];
572 const std::string& outvar = args[3];
574 // ensure that the user cannot accidentally specify REVERSE as a variable
575 if(outvar == "REVERSE")
577 this->SetError("sub-command FIND does not allow to select REVERSE as "
578 "the output variable. "
579 "Maybe you missed the actual output variable?");
583 // try to find the character and return its position
587 pos = sstring.find(schar);
591 pos = sstring.rfind(schar);
593 if(std::string::npos != pos)
597 this->Makefile->AddDefinition(outvar.c_str(), s.str().c_str());
601 // the character was not found, but this is not really an error
602 this->Makefile->AddDefinition(outvar.c_str(), "-1");
606 //----------------------------------------------------------------------------
607 bool cmStringCommand::HandleCompareCommand(std::vector<std::string> const&
612 this->SetError("sub-command COMPARE requires a mode to be specified.");
615 std::string mode = args[1];
616 if((mode == "EQUAL") || (mode == "NOTEQUAL") ||
617 (mode == "LESS") || (mode == "GREATER"))
621 std::string e = "sub-command COMPARE, mode ";
623 e += " needs at least 5 arguments total to command.";
624 this->SetError(e.c_str());
628 const std::string& left = args[2];
629 const std::string& right = args[3];
630 const std::string& outvar = args[4];
634 result = (left < right);
636 else if(mode == "GREATER")
638 result = (left > right);
640 else if(mode == "EQUAL")
642 result = (left == right);
644 else // if(mode == "NOTEQUAL")
646 result = !(left == right);
650 this->Makefile->AddDefinition(outvar.c_str(), "1");
654 this->Makefile->AddDefinition(outvar.c_str(), "0");
658 std::string e = "sub-command COMPARE does not recognize mode "+mode;
659 this->SetError(e.c_str());
663 //----------------------------------------------------------------------------
664 bool cmStringCommand::HandleReplaceCommand(std::vector<std::string> const&
669 this->SetError("sub-command REPLACE requires at least four arguments.");
673 const std::string& matchExpression = args[1];
674 const std::string& replaceExpression = args[2];
675 const std::string& variableName = args[3];
677 std::string input = args[4];
678 for(unsigned int i=5; i < args.size(); ++i)
683 cmsys::SystemTools::ReplaceString(input, matchExpression.c_str(),
684 replaceExpression.c_str());
686 this->Makefile->AddDefinition(variableName.c_str(), input.c_str());
690 //----------------------------------------------------------------------------
691 bool cmStringCommand::HandleSubstringCommand(std::vector<std::string> const&
696 this->SetError("sub-command SUBSTRING requires four arguments.");
700 const std::string& stringValue = args[1];
701 int begin = atoi(args[2].c_str());
702 int end = atoi(args[3].c_str());
703 const std::string& variableName = args[4];
705 size_t stringLength = stringValue.size();
706 int intStringLength = static_cast<int>(stringLength);
707 if ( begin < 0 || begin > intStringLength )
709 cmOStringStream ostr;
710 ostr << "begin index: " << begin << " is out of range 0 - "
712 this->SetError(ostr.str().c_str());
715 int leftOverLength = intStringLength - begin;
716 if ( end < -1 || end > leftOverLength )
718 cmOStringStream ostr;
719 ostr << "end index: " << end << " is out of range -1 - "
721 this->SetError(ostr.str().c_str());
725 this->Makefile->AddDefinition(variableName.c_str(),
726 stringValue.substr(begin, end).c_str());
730 //----------------------------------------------------------------------------
732 ::HandleLengthCommand(std::vector<std::string> const& args)
736 this->SetError("sub-command LENGTH requires two arguments.");
740 const std::string& stringValue = args[1];
741 const std::string& variableName = args[2];
743 size_t length = stringValue.size();
745 sprintf(buffer, "%d", static_cast<int>(length));
747 this->Makefile->AddDefinition(variableName.c_str(), buffer);
751 //----------------------------------------------------------------------------
752 bool cmStringCommand::HandleStripCommand(
753 std::vector<std::string> const& args)
757 this->SetError("sub-command STRIP requires two arguments.");
761 const std::string& stringValue = args[1];
762 const std::string& variableName = args[2];
763 size_t inStringLength = stringValue.size();
764 size_t startPos = inStringLength + 1;
766 const char* ptr = stringValue.c_str();
768 for ( cc = 0; cc < inStringLength; ++ cc )
770 if ( !isspace(*ptr) )
772 if ( startPos > inStringLength )
781 size_t outLength = 0;
783 // if the input string didn't contain any non-space characters, return
785 if (startPos > inStringLength)
792 outLength=endPos - startPos + 1;
795 this->Makefile->AddDefinition(variableName.c_str(),
796 stringValue.substr(startPos, outLength).c_str());
800 //----------------------------------------------------------------------------
802 ::HandleRandomCommand(std::vector<std::string> const& args)
804 if(args.size() < 2 || args.size() == 3 || args.size() == 5)
806 this->SetError("sub-command RANDOM requires at least one argument.");
810 static bool seeded = false;
811 bool force_seed = false;
812 unsigned int seed = 0;
814 const char cmStringCommandDefaultAlphabet[] = "qwertyuiopasdfghjklzxcvbnm"
815 "QWERTYUIOPASDFGHJKLZXCVBNM"
817 std::string alphabet;
819 if ( args.size() > 3 )
822 size_t stopAt = args.size() - 2;
824 for ( ; i < stopAt; ++i )
826 if ( args[i] == "LENGTH" )
829 length = atoi(args[i].c_str());
831 else if ( args[i] == "ALPHABET" )
836 else if ( args[i] == "RANDOM_SEED" )
839 seed = static_cast<unsigned int>(atoi(args[i].c_str()));
844 if ( !alphabet.size() )
846 alphabet = cmStringCommandDefaultAlphabet;
849 double sizeofAlphabet = static_cast<double>(alphabet.size());
850 if ( sizeofAlphabet < 1 )
852 this->SetError("sub-command RANDOM invoked with bad alphabet.");
857 this->SetError("sub-command RANDOM invoked with bad length.");
860 const std::string& variableName = args[args.size()-1];
862 std::vector<char> result;
864 if (!seeded || force_seed)
867 srand(force_seed? seed : cmSystemTools::RandomSeed());
870 const char* alphaPtr = alphabet.c_str();
872 for ( cc = 0; cc < length; cc ++ )
874 int idx=(int) (sizeofAlphabet* rand()/(RAND_MAX+1.0));
875 result.push_back(*(alphaPtr + idx));
879 this->Makefile->AddDefinition(variableName.c_str(), &*result.begin());