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"
7 #include <memory> // IWYU pragma: keep
12 #include "cmAlgorithms.h"
13 #include "cmCryptoHash.h"
14 #include "cmGeneratorExpression.h"
15 #include "cmMakefile.h"
16 #include "cmStringReplaceHelper.h"
17 #include "cmSystemTools.h"
18 #include "cmTimestamp.h"
21 class cmExecutionStatus;
23 bool cmStringCommand::InitialPass(std::vector<std::string> const& args,
27 this->SetError("must be called with at least one argument.");
31 const std::string& subCommand = args[0];
32 if (subCommand == "REGEX") {
33 return this->HandleRegexCommand(args);
35 if (subCommand == "REPLACE") {
36 return this->HandleReplaceCommand(args);
38 if (subCommand == "MD5" || subCommand == "SHA1" || subCommand == "SHA224" ||
39 subCommand == "SHA256" || subCommand == "SHA384" ||
40 subCommand == "SHA512" || subCommand == "SHA3_224" ||
41 subCommand == "SHA3_256" || subCommand == "SHA3_384" ||
42 subCommand == "SHA3_512") {
43 return this->HandleHashCommand(args);
45 if (subCommand == "TOLOWER") {
46 return this->HandleToUpperLowerCommand(args, false);
48 if (subCommand == "TOUPPER") {
49 return this->HandleToUpperLowerCommand(args, true);
51 if (subCommand == "COMPARE") {
52 return this->HandleCompareCommand(args);
54 if (subCommand == "ASCII") {
55 return this->HandleAsciiCommand(args);
57 if (subCommand == "CONFIGURE") {
58 return this->HandleConfigureCommand(args);
60 if (subCommand == "LENGTH") {
61 return this->HandleLengthCommand(args);
63 if (subCommand == "APPEND") {
64 return this->HandleAppendCommand(args);
66 if (subCommand == "PREPEND") {
67 return this->HandlePrependCommand(args);
69 if (subCommand == "CONCAT") {
70 return this->HandleConcatCommand(args);
72 if (subCommand == "JOIN") {
73 return this->HandleJoinCommand(args);
75 if (subCommand == "SUBSTRING") {
76 return this->HandleSubstringCommand(args);
78 if (subCommand == "STRIP") {
79 return this->HandleStripCommand(args);
81 if (subCommand == "RANDOM") {
82 return this->HandleRandomCommand(args);
84 if (subCommand == "FIND") {
85 return this->HandleFindCommand(args);
87 if (subCommand == "TIMESTAMP") {
88 return this->HandleTimestampCommand(args);
90 if (subCommand == "MAKE_C_IDENTIFIER") {
91 return this->HandleMakeCIdentifierCommand(args);
93 if (subCommand == "GENEX_STRIP") {
94 return this->HandleGenexStripCommand(args);
96 if (subCommand == "UUID") {
97 return this->HandleUuidCommand(args);
100 std::string e = "does not recognize sub-command " + subCommand;
105 bool cmStringCommand::HandleHashCommand(std::vector<std::string> const& args)
107 #if defined(CMAKE_BUILD_WITH_CMAKE)
108 if (args.size() != 3) {
109 std::ostringstream e;
110 e << args[0] << " requires an output variable and an input string";
111 this->SetError(e.str());
115 std::unique_ptr<cmCryptoHash> hash(cmCryptoHash::New(args[0].c_str()));
117 std::string out = hash->HashString(args[2]);
118 this->Makefile->AddDefinition(args[1], out.c_str());
123 std::ostringstream e;
124 e << args[0] << " not available during bootstrap";
125 this->SetError(e.str().c_str());
130 bool cmStringCommand::HandleToUpperLowerCommand(
131 std::vector<std::string> const& args, bool toUpper)
133 if (args.size() < 3) {
134 this->SetError("no output variable specified");
138 std::string const& outvar = args[2];
142 output = cmSystemTools::UpperCase(args[1]);
144 output = cmSystemTools::LowerCase(args[1]);
147 // Store the output in the provided variable.
148 this->Makefile->AddDefinition(outvar, output.c_str());
152 bool cmStringCommand::HandleAsciiCommand(std::vector<std::string> const& args)
154 if (args.size() < 3) {
155 this->SetError("No output variable specified");
158 std::string::size_type cc;
159 std::string const& outvar = args[args.size() - 1];
161 for (cc = 1; cc < args.size() - 1; cc++) {
162 int ch = atoi(args[cc].c_str());
163 if (ch > 0 && ch < 256) {
164 output += static_cast<char>(ch);
166 std::string error = "Character with code ";
168 error += " does not exist.";
169 this->SetError(error);
173 // Store the output in the provided variable.
174 this->Makefile->AddDefinition(outvar, output.c_str());
178 bool cmStringCommand::HandleConfigureCommand(
179 std::vector<std::string> const& args)
181 if (args.size() < 2) {
182 this->SetError("No input string specified.");
185 if (args.size() < 3) {
186 this->SetError("No output variable specified.");
191 bool escapeQuotes = false;
193 for (unsigned int i = 3; i < args.size(); ++i) {
194 if (args[i] == "@ONLY") {
196 } else if (args[i] == "ESCAPE_QUOTES") {
199 std::ostringstream err;
200 err << "Unrecognized argument \"" << args[i] << "\"";
201 this->SetError(err.str());
206 // Configure the string.
208 this->Makefile->ConfigureString(args[1], output, atOnly, escapeQuotes);
210 // Store the output in the provided variable.
211 this->Makefile->AddDefinition(args[2], output.c_str());
216 bool cmStringCommand::HandleRegexCommand(std::vector<std::string> const& args)
218 if (args.size() < 2) {
219 this->SetError("sub-command REGEX requires a mode to be specified.");
222 std::string const& mode = args[1];
223 if (mode == "MATCH") {
224 if (args.size() < 5) {
225 this->SetError("sub-command REGEX, mode MATCH needs "
226 "at least 5 arguments total to command.");
229 return this->RegexMatch(args);
231 if (mode == "MATCHALL") {
232 if (args.size() < 5) {
233 this->SetError("sub-command REGEX, mode MATCHALL needs "
234 "at least 5 arguments total to command.");
237 return this->RegexMatchAll(args);
239 if (mode == "REPLACE") {
240 if (args.size() < 6) {
241 this->SetError("sub-command REGEX, mode REPLACE needs "
242 "at least 6 arguments total to command.");
245 return this->RegexReplace(args);
248 std::string e = "sub-command REGEX does not recognize mode " + mode;
253 bool cmStringCommand::RegexMatch(std::vector<std::string> const& args)
255 //"STRING(REGEX MATCH <regular_expression> <output variable>
256 // <input> [<input>...])\n";
257 std::string const& regex = args[2];
258 std::string const& outvar = args[3];
260 this->Makefile->ClearMatches();
261 // Compile the regular expression.
262 cmsys::RegularExpression re;
263 if (!re.compile(regex.c_str())) {
265 "sub-command REGEX, mode MATCH failed to compile regex \"" + regex +
271 // Concatenate all the last arguments together.
272 std::string input = cmJoin(cmMakeRange(args).advance(4), std::string());
274 // Scan through the input for all matches.
276 if (re.find(input)) {
277 this->Makefile->StoreMatches(re);
278 std::string::size_type l = re.start();
279 std::string::size_type r = re.end();
281 std::string e = "sub-command REGEX, mode MATCH regex \"" + regex +
282 "\" matched an empty string.";
286 output = input.substr(l, r - l);
289 // Store the output in the provided variable.
290 this->Makefile->AddDefinition(outvar, output.c_str());
294 bool cmStringCommand::RegexMatchAll(std::vector<std::string> const& args)
296 //"STRING(REGEX MATCHALL <regular_expression> <output variable> <input>
298 std::string const& regex = args[2];
299 std::string const& outvar = args[3];
301 this->Makefile->ClearMatches();
302 // Compile the regular expression.
303 cmsys::RegularExpression re;
304 if (!re.compile(regex.c_str())) {
306 "sub-command REGEX, mode MATCHALL failed to compile regex \"" + regex +
312 // Concatenate all the last arguments together.
313 std::string input = cmJoin(cmMakeRange(args).advance(4), std::string());
315 // Scan through the input for all matches.
317 const char* p = input.c_str();
319 this->Makefile->ClearMatches();
320 this->Makefile->StoreMatches(re);
321 std::string::size_type l = re.start();
322 std::string::size_type r = re.end();
324 std::string e = "sub-command REGEX, mode MATCHALL regex \"" + regex +
325 "\" matched an empty string.";
329 if (!output.empty()) {
332 output += std::string(p + l, r - l);
336 // Store the output in the provided variable.
337 this->Makefile->AddDefinition(outvar, output.c_str());
341 bool cmStringCommand::RegexReplace(std::vector<std::string> const& args)
343 //"STRING(REGEX REPLACE <regular_expression> <replace_expression>
344 // <output variable> <input> [<input>...])\n"
345 std::string const& regex = args[2];
346 std::string const& replace = args[3];
347 std::string const& outvar = args[4];
348 cmStringReplaceHelper replaceHelper(regex, replace, this->Makefile);
350 if (!replaceHelper.IsReplaceExpressionValid()) {
352 "sub-command REGEX, mode REPLACE: " + replaceHelper.GetError() + ".");
356 this->Makefile->ClearMatches();
358 if (!replaceHelper.IsRegularExpressionValid()) {
360 "sub-command REGEX, mode REPLACE failed to compile regex \"" + regex +
366 // Concatenate all the last arguments together.
367 const std::string input =
368 cmJoin(cmMakeRange(args).advance(5), std::string());
371 if (!replaceHelper.Replace(input, output)) {
373 "sub-command REGEX, mode REPLACE: " + replaceHelper.GetError() + ".");
377 // Store the output in the provided variable.
378 this->Makefile->AddDefinition(outvar, output.c_str());
382 bool cmStringCommand::HandleFindCommand(std::vector<std::string> const& args)
384 // check if all required parameters were passed
385 if (args.size() < 4 || args.size() > 5) {
386 this->SetError("sub-command FIND requires 3 or 4 parameters.");
390 // check if the reverse flag was set or not
391 bool reverseMode = false;
392 if (args.size() == 5 && args[4] == "REVERSE") {
396 // if we have 5 arguments the last one must be REVERSE
397 if (args.size() == 5 && args[4] != "REVERSE") {
398 this->SetError("sub-command FIND: unknown last parameter");
402 // local parameter names.
403 const std::string& sstring = args[1];
404 const std::string& schar = args[2];
405 const std::string& outvar = args[3];
407 // ensure that the user cannot accidentally specify REVERSE as a variable
408 if (outvar == "REVERSE") {
409 this->SetError("sub-command FIND does not allow one to select REVERSE as "
410 "the output variable. "
411 "Maybe you missed the actual output variable?");
415 // try to find the character and return its position
418 pos = sstring.find(schar);
420 pos = sstring.rfind(schar);
422 if (std::string::npos != pos) {
423 std::ostringstream s;
425 this->Makefile->AddDefinition(outvar, s.str().c_str());
429 // the character was not found, but this is not really an error
430 this->Makefile->AddDefinition(outvar, "-1");
434 bool cmStringCommand::HandleCompareCommand(
435 std::vector<std::string> const& args)
437 if (args.size() < 2) {
438 this->SetError("sub-command COMPARE requires a mode to be specified.");
441 std::string const& mode = args[1];
442 if ((mode == "EQUAL") || (mode == "NOTEQUAL") || (mode == "LESS") ||
443 (mode == "LESS_EQUAL") || (mode == "GREATER") ||
444 (mode == "GREATER_EQUAL")) {
445 if (args.size() < 5) {
446 std::string e = "sub-command COMPARE, mode ";
448 e += " needs at least 5 arguments total to command.";
453 const std::string& left = args[2];
454 const std::string& right = args[3];
455 const std::string& outvar = args[4];
457 if (mode == "LESS") {
458 result = (left < right);
459 } else if (mode == "LESS_EQUAL") {
460 result = (left <= right);
461 } else if (mode == "GREATER") {
462 result = (left > right);
463 } else if (mode == "GREATER_EQUAL") {
464 result = (left >= right);
465 } else if (mode == "EQUAL") {
466 result = (left == right);
467 } else // if(mode == "NOTEQUAL")
469 result = !(left == right);
472 this->Makefile->AddDefinition(outvar, "1");
474 this->Makefile->AddDefinition(outvar, "0");
478 std::string e = "sub-command COMPARE does not recognize mode " + mode;
483 bool cmStringCommand::HandleReplaceCommand(
484 std::vector<std::string> const& args)
486 if (args.size() < 5) {
487 this->SetError("sub-command REPLACE requires at least four arguments.");
491 const std::string& matchExpression = args[1];
492 const std::string& replaceExpression = args[2];
493 const std::string& variableName = args[3];
495 std::string input = cmJoin(cmMakeRange(args).advance(4), std::string());
497 cmsys::SystemTools::ReplaceString(input, matchExpression.c_str(),
498 replaceExpression.c_str());
500 this->Makefile->AddDefinition(variableName, input.c_str());
504 bool cmStringCommand::HandleSubstringCommand(
505 std::vector<std::string> const& args)
507 if (args.size() != 5) {
508 this->SetError("sub-command SUBSTRING requires four arguments.");
512 const std::string& stringValue = args[1];
513 int begin = atoi(args[2].c_str());
514 int end = atoi(args[3].c_str());
515 const std::string& variableName = args[4];
517 size_t stringLength = stringValue.size();
518 int intStringLength = static_cast<int>(stringLength);
519 if (begin < 0 || begin > intStringLength) {
520 std::ostringstream ostr;
521 ostr << "begin index: " << begin << " is out of range 0 - "
523 this->SetError(ostr.str());
527 std::ostringstream ostr;
528 ostr << "end index: " << end << " should be -1 or greater";
529 this->SetError(ostr.str());
533 this->Makefile->AddDefinition(variableName,
534 stringValue.substr(begin, end).c_str());
538 bool cmStringCommand::HandleLengthCommand(std::vector<std::string> const& args)
540 if (args.size() != 3) {
541 this->SetError("sub-command LENGTH requires two arguments.");
545 const std::string& stringValue = args[1];
546 const std::string& variableName = args[2];
548 size_t length = stringValue.size();
550 sprintf(buffer, "%d", static_cast<int>(length));
552 this->Makefile->AddDefinition(variableName, buffer);
556 bool cmStringCommand::HandleAppendCommand(std::vector<std::string> const& args)
558 if (args.size() < 2) {
559 this->SetError("sub-command APPEND requires at least one argument.");
563 // Skip if nothing to append.
564 if (args.size() < 3) {
568 const std::string& variable = args[1];
571 const char* oldValue = this->Makefile->GetDefinition(variable);
575 value += cmJoin(cmMakeRange(args).advance(2), std::string());
576 this->Makefile->AddDefinition(variable, value.c_str());
580 bool cmStringCommand::HandlePrependCommand(
581 std::vector<std::string> const& args)
583 if (args.size() < 2) {
584 this->SetError("sub-command PREPEND requires at least one argument.");
588 // Skip if nothing to prepend.
589 if (args.size() < 3) {
593 const std::string& variable = args[1];
595 std::string value = cmJoin(cmMakeRange(args).advance(2), std::string());
596 const char* oldValue = this->Makefile->GetDefinition(variable);
600 this->Makefile->AddDefinition(variable, value.c_str());
604 bool cmStringCommand::HandleConcatCommand(std::vector<std::string> const& args)
606 if (args.size() < 2) {
607 this->SetError("sub-command CONCAT requires at least one argument.");
611 return this->joinImpl(args, std::string(), 1);
614 bool cmStringCommand::HandleJoinCommand(std::vector<std::string> const& args)
616 if (args.size() < 3) {
617 this->SetError("sub-command JOIN requires at least two arguments.");
621 return this->joinImpl(args, args[1], 2);
624 bool cmStringCommand::joinImpl(std::vector<std::string> const& args,
625 std::string const& glue, const size_t varIdx)
627 std::string const& variableName = args[varIdx];
628 // NOTE Items to concat/join placed right after the variable for
629 // both `CONCAT` and `JOIN` sub-commands.
630 std::string value = cmJoin(cmMakeRange(args).advance(varIdx + 1), glue);
632 this->Makefile->AddDefinition(variableName, value.c_str());
636 bool cmStringCommand::HandleMakeCIdentifierCommand(
637 std::vector<std::string> const& args)
639 if (args.size() != 3) {
640 this->SetError("sub-command MAKE_C_IDENTIFIER requires two arguments.");
644 const std::string& input = args[1];
645 const std::string& variableName = args[2];
647 this->Makefile->AddDefinition(variableName,
648 cmSystemTools::MakeCidentifier(input).c_str());
652 bool cmStringCommand::HandleGenexStripCommand(
653 std::vector<std::string> const& args)
655 if (args.size() != 3) {
656 this->SetError("sub-command GENEX_STRIP requires two arguments.");
660 const std::string& input = args[1];
662 std::string result = cmGeneratorExpression::Preprocess(
663 input, cmGeneratorExpression::StripAllGeneratorExpressions);
665 const std::string& variableName = args[2];
667 this->Makefile->AddDefinition(variableName, result.c_str());
671 bool cmStringCommand::HandleStripCommand(std::vector<std::string> const& args)
673 if (args.size() != 3) {
674 this->SetError("sub-command STRIP requires two arguments.");
678 const std::string& stringValue = args[1];
679 const std::string& variableName = args[2];
680 size_t inStringLength = stringValue.size();
681 size_t startPos = inStringLength + 1;
683 const char* ptr = stringValue.c_str();
685 for (cc = 0; cc < inStringLength; ++cc) {
686 if (!isspace(*ptr)) {
687 if (startPos > inStringLength) {
695 size_t outLength = 0;
697 // if the input string didn't contain any non-space characters, return
699 if (startPos > inStringLength) {
703 outLength = endPos - startPos + 1;
706 this->Makefile->AddDefinition(
707 variableName, stringValue.substr(startPos, outLength).c_str());
711 bool cmStringCommand::HandleRandomCommand(std::vector<std::string> const& args)
713 if (args.size() < 2 || args.size() == 3 || args.size() == 5) {
714 this->SetError("sub-command RANDOM requires at least one argument.");
718 static bool seeded = false;
719 bool force_seed = false;
720 unsigned int seed = 0;
722 const char cmStringCommandDefaultAlphabet[] = "qwertyuiopasdfghjklzxcvbnm"
723 "QWERTYUIOPASDFGHJKLZXCVBNM"
725 std::string alphabet;
727 if (args.size() > 3) {
729 size_t stopAt = args.size() - 2;
731 for (; i < stopAt; ++i) {
732 if (args[i] == "LENGTH") {
734 length = atoi(args[i].c_str());
735 } else if (args[i] == "ALPHABET") {
738 } else if (args[i] == "RANDOM_SEED") {
740 seed = static_cast<unsigned int>(atoi(args[i].c_str()));
745 if (alphabet.empty()) {
746 alphabet = cmStringCommandDefaultAlphabet;
749 double sizeofAlphabet = static_cast<double>(alphabet.size());
750 if (sizeofAlphabet < 1) {
751 this->SetError("sub-command RANDOM invoked with bad alphabet.");
755 this->SetError("sub-command RANDOM invoked with bad length.");
758 const std::string& variableName = args[args.size() - 1];
760 std::vector<char> result;
762 if (!seeded || force_seed) {
764 srand(force_seed ? seed : cmSystemTools::RandomSeed());
767 const char* alphaPtr = alphabet.c_str();
769 for (cc = 0; cc < length; cc++) {
770 int idx = static_cast<int>(sizeofAlphabet * rand() / (RAND_MAX + 1.0));
771 result.push_back(*(alphaPtr + idx));
775 this->Makefile->AddDefinition(variableName, &*result.begin());
779 bool cmStringCommand::HandleTimestampCommand(
780 std::vector<std::string> const& args)
782 if (args.size() < 2) {
783 this->SetError("sub-command TIMESTAMP requires at least one argument.");
786 if (args.size() > 4) {
787 this->SetError("sub-command TIMESTAMP takes at most three arguments.");
791 unsigned int argsIndex = 1;
793 const std::string& outputVariable = args[argsIndex++];
795 std::string formatString;
796 if (args.size() > argsIndex && args[argsIndex] != "UTC") {
797 formatString = args[argsIndex++];
800 bool utcFlag = false;
801 if (args.size() > argsIndex) {
802 if (args[argsIndex] == "UTC") {
805 std::string e = " TIMESTAMP sub-command does not recognize option " +
806 args[argsIndex] + ".";
812 cmTimestamp timestamp;
813 std::string result = timestamp.CurrentTime(formatString, utcFlag);
814 this->Makefile->AddDefinition(outputVariable, result.c_str());
819 bool cmStringCommand::HandleUuidCommand(std::vector<std::string> const& args)
821 #if defined(CMAKE_BUILD_WITH_CMAKE)
822 unsigned int argsIndex = 1;
824 if (args.size() < 2) {
825 this->SetError("UUID sub-command requires an output variable.");
829 const std::string& outputVariable = args[argsIndex++];
831 std::string uuidNamespaceString;
832 std::string uuidName;
833 std::string uuidType;
834 bool uuidUpperCase = false;
836 while (args.size() > argsIndex) {
837 if (args[argsIndex] == "NAMESPACE") {
839 if (argsIndex >= args.size()) {
840 this->SetError("UUID sub-command, NAMESPACE requires a value.");
843 uuidNamespaceString = args[argsIndex++];
844 } else if (args[argsIndex] == "NAME") {
846 if (argsIndex >= args.size()) {
847 this->SetError("UUID sub-command, NAME requires a value.");
850 uuidName = args[argsIndex++];
851 } else if (args[argsIndex] == "TYPE") {
853 if (argsIndex >= args.size()) {
854 this->SetError("UUID sub-command, TYPE requires a value.");
857 uuidType = args[argsIndex++];
858 } else if (args[argsIndex] == "UPPER") {
860 uuidUpperCase = true;
863 "UUID sub-command does not recognize option " + args[argsIndex] + ".";
870 cmUuid uuidGenerator;
872 std::vector<unsigned char> uuidNamespace;
873 if (!uuidGenerator.StringToBinary(uuidNamespaceString, uuidNamespace)) {
874 this->SetError("UUID sub-command, malformed NAMESPACE UUID.");
878 if (uuidType == "MD5") {
879 uuid = uuidGenerator.FromMd5(uuidNamespace, uuidName);
880 } else if (uuidType == "SHA1") {
881 uuid = uuidGenerator.FromSha1(uuidNamespace, uuidName);
883 std::string e = "UUID sub-command, unknown TYPE '" + uuidType + "'.";
889 this->SetError("UUID sub-command, generation failed.");
894 uuid = cmSystemTools::UpperCase(uuid);
897 this->Makefile->AddDefinition(outputVariable, uuid.c_str());
900 std::ostringstream e;
901 e << args[0] << " not available during bootstrap";
902 this->SetError(e.str().c_str());