1 /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
2 file Copyright.txt or https://cmake.org/licensing for details. */
3 #include "cmStringCommand.h"
5 #include "cmsys/RegularExpression.hxx"
11 #include "cmAlgorithms.h"
12 #include "cmCryptoHash.h"
13 #include "cmGeneratorExpression.h"
14 #include "cmMakefile.h"
15 #include "cmSystemTools.h"
16 #include "cmTimestamp.h"
18 #include "cm_auto_ptr.hxx"
20 class cmExecutionStatus;
22 bool cmStringCommand::InitialPass(std::vector<std::string> const& args,
26 this->SetError("must be called with at least one argument.");
30 const std::string& subCommand = args[0];
31 if (subCommand == "REGEX") {
32 return this->HandleRegexCommand(args);
34 if (subCommand == "REPLACE") {
35 return this->HandleReplaceCommand(args);
37 if (subCommand == "MD5" || subCommand == "SHA1" || subCommand == "SHA224" ||
38 subCommand == "SHA256" || subCommand == "SHA384" ||
39 subCommand == "SHA512" || subCommand == "SHA3_224" ||
40 subCommand == "SHA3_256" || subCommand == "SHA3_384" ||
41 subCommand == "SHA3_512") {
42 return this->HandleHashCommand(args);
44 if (subCommand == "TOLOWER") {
45 return this->HandleToUpperLowerCommand(args, false);
47 if (subCommand == "TOUPPER") {
48 return this->HandleToUpperLowerCommand(args, true);
50 if (subCommand == "COMPARE") {
51 return this->HandleCompareCommand(args);
53 if (subCommand == "ASCII") {
54 return this->HandleAsciiCommand(args);
56 if (subCommand == "CONFIGURE") {
57 return this->HandleConfigureCommand(args);
59 if (subCommand == "LENGTH") {
60 return this->HandleLengthCommand(args);
62 if (subCommand == "APPEND") {
63 return this->HandleAppendCommand(args);
65 if (subCommand == "CONCAT") {
66 return this->HandleConcatCommand(args);
68 if (subCommand == "SUBSTRING") {
69 return this->HandleSubstringCommand(args);
71 if (subCommand == "STRIP") {
72 return this->HandleStripCommand(args);
74 if (subCommand == "RANDOM") {
75 return this->HandleRandomCommand(args);
77 if (subCommand == "FIND") {
78 return this->HandleFindCommand(args);
80 if (subCommand == "TIMESTAMP") {
81 return this->HandleTimestampCommand(args);
83 if (subCommand == "MAKE_C_IDENTIFIER") {
84 return this->HandleMakeCIdentifierCommand(args);
86 if (subCommand == "GENEX_STRIP") {
87 return this->HandleGenexStripCommand(args);
89 if (subCommand == "UUID") {
90 return this->HandleUuidCommand(args);
93 std::string e = "does not recognize sub-command " + subCommand;
98 bool cmStringCommand::HandleHashCommand(std::vector<std::string> const& args)
100 #if defined(CMAKE_BUILD_WITH_CMAKE)
101 if (args.size() != 3) {
102 std::ostringstream e;
103 e << args[0] << " requires an output variable and an input string";
104 this->SetError(e.str());
108 CM_AUTO_PTR<cmCryptoHash> hash(cmCryptoHash::New(args[0].c_str()));
110 std::string out = hash->HashString(args[2]);
111 this->Makefile->AddDefinition(args[1], out.c_str());
116 std::ostringstream e;
117 e << args[0] << " not available during bootstrap";
118 this->SetError(e.str().c_str());
123 bool cmStringCommand::HandleToUpperLowerCommand(
124 std::vector<std::string> const& args, bool toUpper)
126 if (args.size() < 3) {
127 this->SetError("no output variable specified");
131 std::string const& outvar = args[2];
135 output = cmSystemTools::UpperCase(args[1]);
137 output = cmSystemTools::LowerCase(args[1]);
140 // Store the output in the provided variable.
141 this->Makefile->AddDefinition(outvar, output.c_str());
145 bool cmStringCommand::HandleAsciiCommand(std::vector<std::string> const& args)
147 if (args.size() < 3) {
148 this->SetError("No output variable specified");
151 std::string::size_type cc;
152 std::string const& outvar = args[args.size() - 1];
154 for (cc = 1; cc < args.size() - 1; cc++) {
155 int ch = atoi(args[cc].c_str());
156 if (ch > 0 && ch < 256) {
157 output += static_cast<char>(ch);
159 std::string error = "Character with code ";
161 error += " does not exist.";
162 this->SetError(error);
166 // Store the output in the provided variable.
167 this->Makefile->AddDefinition(outvar, output.c_str());
171 bool cmStringCommand::HandleConfigureCommand(
172 std::vector<std::string> const& args)
174 if (args.size() < 2) {
175 this->SetError("No input string specified.");
178 if (args.size() < 3) {
179 this->SetError("No output variable specified.");
184 bool escapeQuotes = false;
186 for (unsigned int i = 3; i < args.size(); ++i) {
187 if (args[i] == "@ONLY") {
189 } else if (args[i] == "ESCAPE_QUOTES") {
192 std::ostringstream err;
193 err << "Unrecognized argument \"" << args[i] << "\"";
194 this->SetError(err.str());
199 // Configure the string.
201 this->Makefile->ConfigureString(args[1], output, atOnly, escapeQuotes);
203 // Store the output in the provided variable.
204 this->Makefile->AddDefinition(args[2], output.c_str());
209 bool cmStringCommand::HandleRegexCommand(std::vector<std::string> const& args)
211 if (args.size() < 2) {
212 this->SetError("sub-command REGEX requires a mode to be specified.");
215 std::string const& mode = args[1];
216 if (mode == "MATCH") {
217 if (args.size() < 5) {
218 this->SetError("sub-command REGEX, mode MATCH needs "
219 "at least 5 arguments total to command.");
222 return this->RegexMatch(args);
224 if (mode == "MATCHALL") {
225 if (args.size() < 5) {
226 this->SetError("sub-command REGEX, mode MATCHALL needs "
227 "at least 5 arguments total to command.");
230 return this->RegexMatchAll(args);
232 if (mode == "REPLACE") {
233 if (args.size() < 6) {
234 this->SetError("sub-command REGEX, mode REPLACE needs "
235 "at least 6 arguments total to command.");
238 return this->RegexReplace(args);
241 std::string e = "sub-command REGEX does not recognize mode " + mode;
246 bool cmStringCommand::RegexMatch(std::vector<std::string> const& args)
248 //"STRING(REGEX MATCH <regular_expression> <output variable>
249 // <input> [<input>...])\n";
250 std::string const& regex = args[2];
251 std::string const& outvar = args[3];
253 this->Makefile->ClearMatches();
254 // Compile the regular expression.
255 cmsys::RegularExpression re;
256 if (!re.compile(regex.c_str())) {
258 "sub-command REGEX, mode MATCH failed to compile regex \"" + regex +
264 // Concatenate all the last arguments together.
265 std::string input = cmJoin(cmMakeRange(args).advance(4), std::string());
267 // Scan through the input for all matches.
269 if (re.find(input.c_str())) {
270 this->Makefile->StoreMatches(re);
271 std::string::size_type l = re.start();
272 std::string::size_type r = re.end();
274 std::string e = "sub-command REGEX, mode MATCH regex \"" + regex +
275 "\" matched an empty string.";
279 output = input.substr(l, r - l);
282 // Store the output in the provided variable.
283 this->Makefile->AddDefinition(outvar, output.c_str());
287 bool cmStringCommand::RegexMatchAll(std::vector<std::string> const& args)
289 //"STRING(REGEX MATCHALL <regular_expression> <output variable> <input>
291 std::string const& regex = args[2];
292 std::string const& outvar = args[3];
294 this->Makefile->ClearMatches();
295 // Compile the regular expression.
296 cmsys::RegularExpression re;
297 if (!re.compile(regex.c_str())) {
299 "sub-command REGEX, mode MATCHALL failed to compile regex \"" + regex +
305 // Concatenate all the last arguments together.
306 std::string input = cmJoin(cmMakeRange(args).advance(4), std::string());
308 // Scan through the input for all matches.
310 const char* p = input.c_str();
312 this->Makefile->StoreMatches(re);
313 std::string::size_type l = re.start();
314 std::string::size_type r = re.end();
316 std::string e = "sub-command REGEX, mode MATCHALL regex \"" + regex +
317 "\" matched an empty string.";
321 if (!output.empty()) {
324 output += std::string(p + l, r - l);
328 // Store the output in the provided variable.
329 this->Makefile->AddDefinition(outvar, output.c_str());
333 bool cmStringCommand::RegexReplace(std::vector<std::string> const& args)
335 //"STRING(REGEX REPLACE <regular_expression> <replace_expression>
336 // <output variable> <input> [<input>...])\n"
337 std::string const& regex = args[2];
338 std::string const& replace = args[3];
339 std::string const& outvar = args[4];
341 // Pull apart the replace expression to find the escaped [0-9] values.
342 std::vector<RegexReplacement> replacement;
343 std::string::size_type l = 0;
344 while (l < replace.length()) {
345 std::string::size_type r = replace.find('\\', l);
346 if (r == std::string::npos) {
347 r = replace.length();
348 replacement.push_back(replace.substr(l, r - l));
351 replacement.push_back(replace.substr(l, r - l));
353 if (r == (replace.length() - 1)) {
354 this->SetError("sub-command REGEX, mode REPLACE: "
355 "replace-expression ends in a backslash.");
358 if ((replace[r + 1] >= '0') && (replace[r + 1] <= '9')) {
359 replacement.push_back(replace[r + 1] - '0');
360 } else if (replace[r + 1] == 'n') {
361 replacement.push_back("\n");
362 } else if (replace[r + 1] == '\\') {
363 replacement.push_back("\\");
365 std::string e = "sub-command REGEX, mode REPLACE: Unknown escape \"";
366 e += replace.substr(r, 2);
367 e += "\" in replace-expression.";
376 this->Makefile->ClearMatches();
377 // Compile the regular expression.
378 cmsys::RegularExpression re;
379 if (!re.compile(regex.c_str())) {
381 "sub-command REGEX, mode REPLACE failed to compile regex \"" + regex +
387 // Concatenate all the last arguments together.
388 std::string input = cmJoin(cmMakeRange(args).advance(5), std::string());
390 // Scan through the input for all matches.
392 std::string::size_type base = 0;
393 while (re.find(input.c_str() + base)) {
394 this->Makefile->StoreMatches(re);
395 std::string::size_type l2 = re.start();
396 std::string::size_type r = re.end();
398 // Concatenate the part of the input that was not matched.
399 output += input.substr(base, l2);
401 // Make sure the match had some text.
403 std::string e = "sub-command REGEX, mode REPLACE regex \"" + regex +
404 "\" matched an empty string.";
409 // Concatenate the replacement for the match.
410 for (unsigned int i = 0; i < replacement.size(); ++i) {
411 if (replacement[i].number < 0) {
412 // This is just a plain-text part of the replacement.
413 output += replacement[i].value;
415 // Replace with part of the match.
416 int n = replacement[i].number;
417 std::string::size_type start = re.start(n);
418 std::string::size_type end = re.end(n);
419 std::string::size_type len = input.length() - base;
420 if ((start != std::string::npos) && (end != std::string::npos) &&
421 (start <= len) && (end <= len)) {
422 output += input.substr(base + start, end - start);
425 "sub-command REGEX, mode REPLACE: replace expression \"" +
426 replace + "\" contains an out-of-range escape for regex \"" +
434 // Move past the match.
438 // Concatenate the text after the last match.
439 output += input.substr(base, input.length() - base);
441 // Store the output in the provided variable.
442 this->Makefile->AddDefinition(outvar, output.c_str());
446 bool cmStringCommand::HandleFindCommand(std::vector<std::string> const& args)
448 // check if all required parameters were passed
449 if (args.size() < 4 || args.size() > 5) {
450 this->SetError("sub-command FIND requires 3 or 4 parameters.");
454 // check if the reverse flag was set or not
455 bool reverseMode = false;
456 if (args.size() == 5 && args[4] == "REVERSE") {
460 // if we have 5 arguments the last one must be REVERSE
461 if (args.size() == 5 && args[4] != "REVERSE") {
462 this->SetError("sub-command FIND: unknown last parameter");
466 // local parameter names.
467 const std::string& sstring = args[1];
468 const std::string& schar = args[2];
469 const std::string& outvar = args[3];
471 // ensure that the user cannot accidentally specify REVERSE as a variable
472 if (outvar == "REVERSE") {
473 this->SetError("sub-command FIND does not allow one to select REVERSE as "
474 "the output variable. "
475 "Maybe you missed the actual output variable?");
479 // try to find the character and return its position
482 pos = sstring.find(schar);
484 pos = sstring.rfind(schar);
486 if (std::string::npos != pos) {
487 std::ostringstream s;
489 this->Makefile->AddDefinition(outvar, s.str().c_str());
493 // the character was not found, but this is not really an error
494 this->Makefile->AddDefinition(outvar, "-1");
498 bool cmStringCommand::HandleCompareCommand(
499 std::vector<std::string> const& args)
501 if (args.size() < 2) {
502 this->SetError("sub-command COMPARE requires a mode to be specified.");
505 std::string const& mode = args[1];
506 if ((mode == "EQUAL") || (mode == "NOTEQUAL") || (mode == "LESS") ||
507 (mode == "LESS_EQUAL") || (mode == "GREATER") ||
508 (mode == "GREATER_EQUAL")) {
509 if (args.size() < 5) {
510 std::string e = "sub-command COMPARE, mode ";
512 e += " needs at least 5 arguments total to command.";
517 const std::string& left = args[2];
518 const std::string& right = args[3];
519 const std::string& outvar = args[4];
521 if (mode == "LESS") {
522 result = (left < right);
523 } else if (mode == "LESS_EQUAL") {
524 result = (left <= right);
525 } else if (mode == "GREATER") {
526 result = (left > right);
527 } else if (mode == "GREATER_EQUAL") {
528 result = (left >= right);
529 } else if (mode == "EQUAL") {
530 result = (left == right);
531 } else // if(mode == "NOTEQUAL")
533 result = !(left == right);
536 this->Makefile->AddDefinition(outvar, "1");
538 this->Makefile->AddDefinition(outvar, "0");
542 std::string e = "sub-command COMPARE does not recognize mode " + mode;
547 bool cmStringCommand::HandleReplaceCommand(
548 std::vector<std::string> const& args)
550 if (args.size() < 5) {
551 this->SetError("sub-command REPLACE requires at least four arguments.");
555 const std::string& matchExpression = args[1];
556 const std::string& replaceExpression = args[2];
557 const std::string& variableName = args[3];
559 std::string input = cmJoin(cmMakeRange(args).advance(4), std::string());
561 cmsys::SystemTools::ReplaceString(input, matchExpression.c_str(),
562 replaceExpression.c_str());
564 this->Makefile->AddDefinition(variableName, input.c_str());
568 bool cmStringCommand::HandleSubstringCommand(
569 std::vector<std::string> const& args)
571 if (args.size() != 5) {
572 this->SetError("sub-command SUBSTRING requires four arguments.");
576 const std::string& stringValue = args[1];
577 int begin = atoi(args[2].c_str());
578 int end = atoi(args[3].c_str());
579 const std::string& variableName = args[4];
581 size_t stringLength = stringValue.size();
582 int intStringLength = static_cast<int>(stringLength);
583 if (begin < 0 || begin > intStringLength) {
584 std::ostringstream ostr;
585 ostr << "begin index: " << begin << " is out of range 0 - "
587 this->SetError(ostr.str());
591 std::ostringstream ostr;
592 ostr << "end index: " << end << " should be -1 or greater";
593 this->SetError(ostr.str());
597 this->Makefile->AddDefinition(variableName,
598 stringValue.substr(begin, end).c_str());
602 bool cmStringCommand::HandleLengthCommand(std::vector<std::string> const& args)
604 if (args.size() != 3) {
605 this->SetError("sub-command LENGTH requires two arguments.");
609 const std::string& stringValue = args[1];
610 const std::string& variableName = args[2];
612 size_t length = stringValue.size();
614 sprintf(buffer, "%d", static_cast<int>(length));
616 this->Makefile->AddDefinition(variableName, buffer);
620 bool cmStringCommand::HandleAppendCommand(std::vector<std::string> const& args)
622 if (args.size() < 2) {
623 this->SetError("sub-command APPEND requires at least one argument.");
627 // Skip if nothing to append.
628 if (args.size() < 3) {
632 const std::string& variable = args[1];
635 const char* oldValue = this->Makefile->GetDefinition(variable);
639 value += cmJoin(cmMakeRange(args).advance(2), std::string());
640 this->Makefile->AddDefinition(variable, value.c_str());
644 bool cmStringCommand::HandleConcatCommand(std::vector<std::string> const& args)
646 if (args.size() < 2) {
647 this->SetError("sub-command CONCAT requires at least one argument.");
651 std::string const& variableName = args[1];
652 std::string value = cmJoin(cmMakeRange(args).advance(2), std::string());
654 this->Makefile->AddDefinition(variableName, value.c_str());
658 bool cmStringCommand::HandleMakeCIdentifierCommand(
659 std::vector<std::string> const& args)
661 if (args.size() != 3) {
662 this->SetError("sub-command MAKE_C_IDENTIFIER requires two arguments.");
666 const std::string& input = args[1];
667 const std::string& variableName = args[2];
669 this->Makefile->AddDefinition(variableName,
670 cmSystemTools::MakeCidentifier(input).c_str());
674 bool cmStringCommand::HandleGenexStripCommand(
675 std::vector<std::string> const& args)
677 if (args.size() != 3) {
678 this->SetError("sub-command GENEX_STRIP requires two arguments.");
682 const std::string& input = args[1];
684 std::string result = cmGeneratorExpression::Preprocess(
685 input, cmGeneratorExpression::StripAllGeneratorExpressions);
687 const std::string& variableName = args[2];
689 this->Makefile->AddDefinition(variableName, result.c_str());
693 bool cmStringCommand::HandleStripCommand(std::vector<std::string> const& args)
695 if (args.size() != 3) {
696 this->SetError("sub-command STRIP requires two arguments.");
700 const std::string& stringValue = args[1];
701 const std::string& variableName = args[2];
702 size_t inStringLength = stringValue.size();
703 size_t startPos = inStringLength + 1;
705 const char* ptr = stringValue.c_str();
707 for (cc = 0; cc < inStringLength; ++cc) {
708 if (!isspace(*ptr)) {
709 if (startPos > inStringLength) {
717 size_t outLength = 0;
719 // if the input string didn't contain any non-space characters, return
721 if (startPos > inStringLength) {
725 outLength = endPos - startPos + 1;
728 this->Makefile->AddDefinition(
729 variableName, stringValue.substr(startPos, outLength).c_str());
733 bool cmStringCommand::HandleRandomCommand(std::vector<std::string> const& args)
735 if (args.size() < 2 || args.size() == 3 || args.size() == 5) {
736 this->SetError("sub-command RANDOM requires at least one argument.");
740 static bool seeded = false;
741 bool force_seed = false;
742 unsigned int seed = 0;
744 const char cmStringCommandDefaultAlphabet[] = "qwertyuiopasdfghjklzxcvbnm"
745 "QWERTYUIOPASDFGHJKLZXCVBNM"
747 std::string alphabet;
749 if (args.size() > 3) {
751 size_t stopAt = args.size() - 2;
753 for (; i < stopAt; ++i) {
754 if (args[i] == "LENGTH") {
756 length = atoi(args[i].c_str());
757 } else if (args[i] == "ALPHABET") {
760 } else if (args[i] == "RANDOM_SEED") {
762 seed = static_cast<unsigned int>(atoi(args[i].c_str()));
767 if (alphabet.empty()) {
768 alphabet = cmStringCommandDefaultAlphabet;
771 double sizeofAlphabet = static_cast<double>(alphabet.size());
772 if (sizeofAlphabet < 1) {
773 this->SetError("sub-command RANDOM invoked with bad alphabet.");
777 this->SetError("sub-command RANDOM invoked with bad length.");
780 const std::string& variableName = args[args.size() - 1];
782 std::vector<char> result;
784 if (!seeded || force_seed) {
786 srand(force_seed ? seed : cmSystemTools::RandomSeed());
789 const char* alphaPtr = alphabet.c_str();
791 for (cc = 0; cc < length; cc++) {
792 int idx = (int)(sizeofAlphabet * rand() / (RAND_MAX + 1.0));
793 result.push_back(*(alphaPtr + idx));
797 this->Makefile->AddDefinition(variableName, &*result.begin());
801 bool cmStringCommand::HandleTimestampCommand(
802 std::vector<std::string> const& args)
804 if (args.size() < 2) {
805 this->SetError("sub-command TIMESTAMP requires at least one argument.");
808 if (args.size() > 4) {
809 this->SetError("sub-command TIMESTAMP takes at most three arguments.");
813 unsigned int argsIndex = 1;
815 const std::string& outputVariable = args[argsIndex++];
817 std::string formatString;
818 if (args.size() > argsIndex && args[argsIndex] != "UTC") {
819 formatString = args[argsIndex++];
822 bool utcFlag = false;
823 if (args.size() > argsIndex) {
824 if (args[argsIndex] == "UTC") {
827 std::string e = " TIMESTAMP sub-command does not recognize option " +
828 args[argsIndex] + ".";
834 cmTimestamp timestamp;
835 std::string result = timestamp.CurrentTime(formatString, utcFlag);
836 this->Makefile->AddDefinition(outputVariable, result.c_str());
841 bool cmStringCommand::HandleUuidCommand(std::vector<std::string> const& args)
843 #if defined(CMAKE_BUILD_WITH_CMAKE)
844 unsigned int argsIndex = 1;
846 if (args.size() < 2) {
847 this->SetError("UUID sub-command requires an output variable.");
851 const std::string& outputVariable = args[argsIndex++];
853 std::string uuidNamespaceString;
854 std::string uuidName;
855 std::string uuidType;
856 bool uuidUpperCase = false;
858 while (args.size() > argsIndex) {
859 if (args[argsIndex] == "NAMESPACE") {
861 if (argsIndex >= args.size()) {
862 this->SetError("UUID sub-command, NAMESPACE requires a value.");
865 uuidNamespaceString = args[argsIndex++];
866 } else if (args[argsIndex] == "NAME") {
868 if (argsIndex >= args.size()) {
869 this->SetError("UUID sub-command, NAME requires a value.");
872 uuidName = args[argsIndex++];
873 } else if (args[argsIndex] == "TYPE") {
875 if (argsIndex >= args.size()) {
876 this->SetError("UUID sub-command, TYPE requires a value.");
879 uuidType = args[argsIndex++];
880 } else if (args[argsIndex] == "UPPER") {
882 uuidUpperCase = true;
885 "UUID sub-command does not recognize option " + args[argsIndex] + ".";
892 cmUuid uuidGenerator;
894 std::vector<unsigned char> uuidNamespace;
895 if (!uuidGenerator.StringToBinary(uuidNamespaceString, uuidNamespace)) {
896 this->SetError("UUID sub-command, malformed NAMESPACE UUID.");
900 if (uuidType == "MD5") {
901 uuid = uuidGenerator.FromMd5(uuidNamespace, uuidName);
902 } else if (uuidType == "SHA1") {
903 uuid = uuidGenerator.FromSha1(uuidNamespace, uuidName);
905 std::string e = "UUID sub-command, unknown TYPE '" + uuidType + "'.";
911 this->SetError("UUID sub-command, generation failed.");
916 uuid = cmSystemTools::UpperCase(uuid);
919 this->Makefile->AddDefinition(outputVariable, uuid.c_str());
922 std::ostringstream e;
923 e << args[0] << " not available during bootstrap";
924 this->SetError(e.str().c_str());