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);
96 else if(subCommand == "MAKE_C_IDENTIFIER")
98 return this->HandleMakeCIdentifierCommand(args);
101 std::string e = "does not recognize sub-command "+subCommand;
102 this->SetError(e.c_str());
106 //----------------------------------------------------------------------------
107 bool cmStringCommand::HandleHashCommand(std::vector<std::string> const& args)
109 #if defined(CMAKE_BUILD_WITH_CMAKE)
113 e << args[0] << " requires an output variable and an input string";
114 this->SetError(e.str().c_str());
118 cmsys::auto_ptr<cmCryptoHash> hash(cmCryptoHash::New(args[0].c_str()));
121 std::string out = hash->HashString(args[2].c_str());
122 this->Makefile->AddDefinition(args[1].c_str(), out.c_str());
128 e << args[0] << " not available during bootstrap";
129 this->SetError(e.str().c_str());
134 //----------------------------------------------------------------------------
135 bool cmStringCommand::HandleToUpperLowerCommand(
136 std::vector<std::string> const& args, bool toUpper)
138 if ( args.size() < 3 )
140 this->SetError("no output variable specified");
144 std::string outvar = args[2];
149 output = cmSystemTools::UpperCase(args[1]);
153 output = cmSystemTools::LowerCase(args[1]);
156 // Store the output in the provided variable.
157 this->Makefile->AddDefinition(outvar.c_str(), output.c_str());
161 //----------------------------------------------------------------------------
162 bool cmStringCommand::HandleAsciiCommand(std::vector<std::string> const& args)
164 if ( args.size() < 3 )
166 this->SetError("No output variable specified");
169 std::string::size_type cc;
170 std::string outvar = args[args.size()-1];
171 std::string output = "";
172 for ( cc = 1; cc < args.size()-1; cc ++ )
174 int ch = atoi(args[cc].c_str());
175 if ( ch > 0 && ch < 256 )
177 output += static_cast<char>(ch);
181 std::string error = "Character with code ";
183 error += " does not exist.";
184 this->SetError(error.c_str());
188 // Store the output in the provided variable.
189 this->Makefile->AddDefinition(outvar.c_str(), output.c_str());
193 //----------------------------------------------------------------------------
194 bool cmStringCommand::HandleConfigureCommand(
195 std::vector<std::string> const& args)
197 if ( args.size() < 2 )
199 this->SetError("No input string specified.");
202 else if ( args.size() < 3 )
204 this->SetError("No output variable specified.");
209 bool escapeQuotes = false;
211 for(unsigned int i = 3; i < args.size(); ++i)
213 if(args[i] == "@ONLY")
217 else if(args[i] == "ESCAPE_QUOTES")
224 err << "Unrecognized argument \"" << args[i] << "\"";
225 this->SetError(err.str().c_str());
230 // Configure the string.
232 this->Makefile->ConfigureString(args[1], output, atOnly, escapeQuotes);
234 // Store the output in the provided variable.
235 this->Makefile->AddDefinition(args[2].c_str(), output.c_str());
240 //----------------------------------------------------------------------------
241 bool cmStringCommand::HandleRegexCommand(std::vector<std::string> const& args)
245 this->SetError("sub-command REGEX requires a mode to be specified.");
248 std::string mode = args[1];
253 this->SetError("sub-command REGEX, mode MATCH needs "
254 "at least 5 arguments total to command.");
257 return this->RegexMatch(args);
259 else if(mode == "MATCHALL")
263 this->SetError("sub-command REGEX, mode MATCHALL needs "
264 "at least 5 arguments total to command.");
267 return this->RegexMatchAll(args);
269 else if(mode == "REPLACE")
273 this->SetError("sub-command REGEX, mode REPLACE needs "
274 "at least 6 arguments total to command.");
277 return this->RegexReplace(args);
280 std::string e = "sub-command REGEX does not recognize mode "+mode;
281 this->SetError(e.c_str());
285 //----------------------------------------------------------------------------
286 bool cmStringCommand::RegexMatch(std::vector<std::string> const& args)
288 //"STRING(REGEX MATCH <regular_expression> <output variable>
289 // <input> [<input>...])\n";
290 std::string regex = args[2];
291 std::string outvar = args[3];
293 // Concatenate all the last arguments together.
294 std::string input = args[4];
295 for(unsigned int i=5; i < args.size(); ++i)
300 this->ClearMatches(this->Makefile);
301 // Compile the regular expression.
302 cmsys::RegularExpression re;
303 if(!re.compile(regex.c_str()))
306 "sub-command REGEX, mode MATCH failed to compile regex \""+regex+"\".";
307 this->SetError(e.c_str());
311 // Scan through the input for all matches.
313 if(re.find(input.c_str()))
315 this->StoreMatches(this->Makefile, re);
316 std::string::size_type l = re.start();
317 std::string::size_type r = re.end();
321 "sub-command REGEX, mode MATCH regex \""+regex+
322 "\" matched an empty string.";
323 this->SetError(e.c_str());
326 output = input.substr(l, r-l);
329 // Store the output in the provided variable.
330 this->Makefile->AddDefinition(outvar.c_str(), output.c_str());
334 //----------------------------------------------------------------------------
335 bool cmStringCommand::RegexMatchAll(std::vector<std::string> const& args)
337 //"STRING(REGEX MATCHALL <regular_expression> <output variable> <input>
339 std::string regex = args[2];
340 std::string outvar = args[3];
342 // Concatenate all the last arguments together.
343 std::string input = args[4];
344 for(unsigned int i=5; i < args.size(); ++i)
349 this->ClearMatches(this->Makefile);
350 // Compile the regular expression.
351 cmsys::RegularExpression re;
352 if(!re.compile(regex.c_str()))
355 "sub-command REGEX, mode MATCHALL failed to compile regex \""+
357 this->SetError(e.c_str());
361 // Scan through the input for all matches.
363 const char* p = input.c_str();
366 this->StoreMatches(this->Makefile, re);
367 std::string::size_type l = re.start();
368 std::string::size_type r = re.end();
371 std::string e = "sub-command REGEX, mode MATCHALL regex \""+
372 regex+"\" matched an empty string.";
373 this->SetError(e.c_str());
376 if(output.length() > 0)
380 output += std::string(p+l, r-l);
384 // Store the output in the provided variable.
385 this->Makefile->AddDefinition(outvar.c_str(), output.c_str());
389 //----------------------------------------------------------------------------
390 bool cmStringCommand::RegexReplace(std::vector<std::string> const& args)
392 //"STRING(REGEX REPLACE <regular_expression> <replace_expression>
393 // <output variable> <input> [<input>...])\n"
394 std::string regex = args[2];
395 std::string replace = args[3];
396 std::string outvar = args[4];
398 // Pull apart the replace expression to find the escaped [0-9] values.
399 std::vector<RegexReplacement> replacement;
400 std::string::size_type l = 0;
401 while(l < replace.length())
403 std::string::size_type r = replace.find("\\", l);
404 if(r == std::string::npos)
406 r = replace.length();
407 replacement.push_back(replace.substr(l, r-l));
413 replacement.push_back(replace.substr(l, r-l));
415 if(r == (replace.length()-1))
417 this->SetError("sub-command REGEX, mode REPLACE: "
418 "replace-expression ends in a backslash.");
421 if((replace[r+1] >= '0') && (replace[r+1] <= '9'))
423 replacement.push_back(replace[r+1]-'0');
425 else if(replace[r+1] == 'n')
427 replacement.push_back("\n");
429 else if(replace[r+1] == '\\')
431 replacement.push_back("\\");
435 std::string e = "sub-command REGEX, mode REPLACE: Unknown escape \"";
436 e += replace.substr(r, 2);
437 e += "\" in replace-expression.";
438 this->SetError(e.c_str());
446 // Concatenate all the last arguments together.
447 std::string input = args[5];
448 for(unsigned int i=6; i < args.size(); ++i)
453 this->ClearMatches(this->Makefile);
454 // Compile the regular expression.
455 cmsys::RegularExpression re;
456 if(!re.compile(regex.c_str()))
459 "sub-command REGEX, mode REPLACE failed to compile regex \""+
461 this->SetError(e.c_str());
465 // Scan through the input for all matches.
467 std::string::size_type base = 0;
468 while(re.find(input.c_str()+base))
470 this->StoreMatches(this->Makefile, re);
471 std::string::size_type l2 = re.start();
472 std::string::size_type r = re.end();
474 // Concatenate the part of the input that was not matched.
475 output += input.substr(base, l2);
477 // Make sure the match had some text.
480 std::string e = "sub-command REGEX, mode REPLACE regex \""+
481 regex+"\" matched an empty string.";
482 this->SetError(e.c_str());
486 // Concatenate the replacement for the match.
487 for(unsigned int i=0; i < replacement.size(); ++i)
489 if(replacement[i].number < 0)
491 // This is just a plain-text part of the replacement.
492 output += replacement[i].value;
496 // Replace with part of the match.
497 int n = replacement[i].number;
498 std::string::size_type start = re.start(n);
499 std::string::size_type end = re.end(n);
500 std::string::size_type len = input.length()-base;
501 if((start != std::string::npos) && (end != std::string::npos) &&
502 (start <= len) && (end <= len))
504 output += input.substr(base+start, end-start);
509 "sub-command REGEX, mode REPLACE: replace expression \""+
510 replace+"\" contains an out-of-range escape for regex \""+
512 this->SetError(e.c_str());
518 // Move past the match.
522 // Concatenate the text after the last match.
523 output += input.substr(base, input.length()-base);
525 // Store the output in the provided variable.
526 this->Makefile->AddDefinition(outvar.c_str(), output.c_str());
530 //----------------------------------------------------------------------------
531 void cmStringCommand::ClearMatches(cmMakefile* mf)
533 for (unsigned int i=0; i<10; i++)
536 sprintf(name, "CMAKE_MATCH_%d", i);
537 const char* s = mf->GetDefinition(name);
540 mf->AddDefinition(name, "");
541 mf->MarkVariableAsUsed(name);
546 //----------------------------------------------------------------------------
547 void cmStringCommand::StoreMatches(cmMakefile* mf,cmsys::RegularExpression& re)
549 for (unsigned int i=0; i<10; i++)
551 std::string m = re.match(i);
555 sprintf(name, "CMAKE_MATCH_%d", i);
556 mf->AddDefinition(name, re.match(i).c_str());
557 mf->MarkVariableAsUsed(name);
562 //----------------------------------------------------------------------------
563 bool cmStringCommand::HandleFindCommand(std::vector<std::string> const&
566 // check if all required parameters were passed
567 if(args.size() < 4 || args.size() > 5)
569 this->SetError("sub-command FIND requires 3 or 4 parameters.");
573 // check if the reverse flag was set or not
574 bool reverseMode = false;
575 if(args.size() == 5 && args[4] == "REVERSE")
580 // if we have 5 arguments the last one must be REVERSE
581 if(args.size() == 5 && args[4] != "REVERSE")
583 this->SetError("sub-command FIND: unknown last parameter");
587 // local parameter names.
588 const std::string& sstring = args[1];
589 const std::string& schar = args[2];
590 const std::string& outvar = args[3];
592 // ensure that the user cannot accidentally specify REVERSE as a variable
593 if(outvar == "REVERSE")
595 this->SetError("sub-command FIND does not allow to select REVERSE as "
596 "the output variable. "
597 "Maybe you missed the actual output variable?");
601 // try to find the character and return its position
605 pos = sstring.find(schar);
609 pos = sstring.rfind(schar);
611 if(std::string::npos != pos)
615 this->Makefile->AddDefinition(outvar.c_str(), s.str().c_str());
619 // the character was not found, but this is not really an error
620 this->Makefile->AddDefinition(outvar.c_str(), "-1");
624 //----------------------------------------------------------------------------
625 bool cmStringCommand::HandleCompareCommand(std::vector<std::string> const&
630 this->SetError("sub-command COMPARE requires a mode to be specified.");
633 std::string mode = args[1];
634 if((mode == "EQUAL") || (mode == "NOTEQUAL") ||
635 (mode == "LESS") || (mode == "GREATER"))
639 std::string e = "sub-command COMPARE, mode ";
641 e += " needs at least 5 arguments total to command.";
642 this->SetError(e.c_str());
646 const std::string& left = args[2];
647 const std::string& right = args[3];
648 const std::string& outvar = args[4];
652 result = (left < right);
654 else if(mode == "GREATER")
656 result = (left > right);
658 else if(mode == "EQUAL")
660 result = (left == right);
662 else // if(mode == "NOTEQUAL")
664 result = !(left == right);
668 this->Makefile->AddDefinition(outvar.c_str(), "1");
672 this->Makefile->AddDefinition(outvar.c_str(), "0");
676 std::string e = "sub-command COMPARE does not recognize mode "+mode;
677 this->SetError(e.c_str());
681 //----------------------------------------------------------------------------
682 bool cmStringCommand::HandleReplaceCommand(std::vector<std::string> const&
687 this->SetError("sub-command REPLACE requires at least four arguments.");
691 const std::string& matchExpression = args[1];
692 const std::string& replaceExpression = args[2];
693 const std::string& variableName = args[3];
695 std::string input = args[4];
696 for(unsigned int i=5; i < args.size(); ++i)
701 cmsys::SystemTools::ReplaceString(input, matchExpression.c_str(),
702 replaceExpression.c_str());
704 this->Makefile->AddDefinition(variableName.c_str(), input.c_str());
708 //----------------------------------------------------------------------------
709 bool cmStringCommand::HandleSubstringCommand(std::vector<std::string> const&
714 this->SetError("sub-command SUBSTRING requires four arguments.");
718 const std::string& stringValue = args[1];
719 int begin = atoi(args[2].c_str());
720 int end = atoi(args[3].c_str());
721 const std::string& variableName = args[4];
723 size_t stringLength = stringValue.size();
724 int intStringLength = static_cast<int>(stringLength);
725 if ( begin < 0 || begin > intStringLength )
727 cmOStringStream ostr;
728 ostr << "begin index: " << begin << " is out of range 0 - "
730 this->SetError(ostr.str().c_str());
733 int leftOverLength = intStringLength - begin;
734 if ( end < -1 || end > leftOverLength )
736 cmOStringStream ostr;
737 ostr << "end index: " << end << " is out of range -1 - "
739 this->SetError(ostr.str().c_str());
743 this->Makefile->AddDefinition(variableName.c_str(),
744 stringValue.substr(begin, end).c_str());
748 //----------------------------------------------------------------------------
750 ::HandleLengthCommand(std::vector<std::string> const& args)
754 this->SetError("sub-command LENGTH requires two arguments.");
758 const std::string& stringValue = args[1];
759 const std::string& variableName = args[2];
761 size_t length = stringValue.size();
763 sprintf(buffer, "%d", static_cast<int>(length));
765 this->Makefile->AddDefinition(variableName.c_str(), buffer);
769 //----------------------------------------------------------------------------
771 ::HandleMakeCIdentifierCommand(std::vector<std::string> const& args)
775 this->SetError("sub-command MAKE_C_IDENTIFIER requires two arguments.");
779 const std::string& input = args[1];
780 const std::string& variableName = args[2];
782 this->Makefile->AddDefinition(variableName.c_str(),
783 cmSystemTools::MakeCidentifier(input.c_str()).c_str());
787 //----------------------------------------------------------------------------
788 bool cmStringCommand::HandleStripCommand(
789 std::vector<std::string> const& args)
793 this->SetError("sub-command STRIP requires two arguments.");
797 const std::string& stringValue = args[1];
798 const std::string& variableName = args[2];
799 size_t inStringLength = stringValue.size();
800 size_t startPos = inStringLength + 1;
802 const char* ptr = stringValue.c_str();
804 for ( cc = 0; cc < inStringLength; ++ cc )
806 if ( !isspace(*ptr) )
808 if ( startPos > inStringLength )
817 size_t outLength = 0;
819 // if the input string didn't contain any non-space characters, return
821 if (startPos > inStringLength)
828 outLength=endPos - startPos + 1;
831 this->Makefile->AddDefinition(variableName.c_str(),
832 stringValue.substr(startPos, outLength).c_str());
836 //----------------------------------------------------------------------------
838 ::HandleRandomCommand(std::vector<std::string> const& args)
840 if(args.size() < 2 || args.size() == 3 || args.size() == 5)
842 this->SetError("sub-command RANDOM requires at least one argument.");
846 static bool seeded = false;
847 bool force_seed = false;
848 unsigned int seed = 0;
850 const char cmStringCommandDefaultAlphabet[] = "qwertyuiopasdfghjklzxcvbnm"
851 "QWERTYUIOPASDFGHJKLZXCVBNM"
853 std::string alphabet;
855 if ( args.size() > 3 )
858 size_t stopAt = args.size() - 2;
860 for ( ; i < stopAt; ++i )
862 if ( args[i] == "LENGTH" )
865 length = atoi(args[i].c_str());
867 else if ( args[i] == "ALPHABET" )
872 else if ( args[i] == "RANDOM_SEED" )
875 seed = static_cast<unsigned int>(atoi(args[i].c_str()));
880 if ( !alphabet.size() )
882 alphabet = cmStringCommandDefaultAlphabet;
885 double sizeofAlphabet = static_cast<double>(alphabet.size());
886 if ( sizeofAlphabet < 1 )
888 this->SetError("sub-command RANDOM invoked with bad alphabet.");
893 this->SetError("sub-command RANDOM invoked with bad length.");
896 const std::string& variableName = args[args.size()-1];
898 std::vector<char> result;
900 if (!seeded || force_seed)
903 srand(force_seed? seed : cmSystemTools::RandomSeed());
906 const char* alphaPtr = alphabet.c_str();
908 for ( cc = 0; cc < length; cc ++ )
910 int idx=(int) (sizeofAlphabet* rand()/(RAND_MAX+1.0));
911 result.push_back(*(alphaPtr + idx));
915 this->Makefile->AddDefinition(variableName.c_str(), &*result.begin());
919 //----------------------------------------------------------------------------
921 ::HandleTimestampCommand(std::vector<std::string> const& args)
925 this->SetError("sub-command TIMESTAMP requires at least one argument.");
928 else if(args.size() > 4)
930 this->SetError("sub-command TIMESTAMP takes at most three arguments.");
934 unsigned int argsIndex = 1;
936 const std::string &outputVariable = args[argsIndex++];
938 std::string formatString;
939 if(args.size() > argsIndex && args[argsIndex] != "UTC")
941 formatString = args[argsIndex++];
944 bool utcFlag = false;
945 if(args.size() > argsIndex)
947 if(args[argsIndex] == "UTC")
953 std::string e = " TIMESTAMP sub-command does not recognize option " +
954 args[argsIndex] + ".";
955 this->SetError(e.c_str());
960 cmTimestamp timestamp;
961 std::string result = timestamp.CurrentTime(formatString, utcFlag);
962 this->Makefile->AddDefinition(outputVariable.c_str(), result.c_str());