1 /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
2 file Copyright.txt or https://cmake.org/licensing for details. */
3 // NOLINTNEXTLINE(bugprone-reserved-identifier)
4 #define _SCL_SECURE_NO_WARNINGS
6 #include "cmStringCommand.h"
12 #include <initializer_list>
18 #include <cm/iterator>
19 #include <cm/optional>
20 #include <cm/string_view>
21 #include <cmext/string_view>
23 #include <cm3p/json/reader.h>
24 #include <cm3p/json/value.h>
25 #include <cm3p/json/writer.h>
27 #include "cmsys/RegularExpression.hxx"
29 #include "cmCryptoHash.h"
30 #include "cmExecutionStatus.h"
31 #include "cmGeneratorExpression.h"
32 #include "cmMakefile.h"
33 #include "cmMessageType.h"
35 #include "cmStringAlgorithms.h"
36 #include "cmStringReplaceHelper.h"
37 #include "cmSubcommandTable.h"
38 #include "cmSystemTools.h"
39 #include "cmTimestamp.h"
45 bool RegexMatch(std::vector<std::string> const& args,
46 cmExecutionStatus& status);
47 bool RegexMatchAll(std::vector<std::string> const& args,
48 cmExecutionStatus& status);
49 bool RegexReplace(std::vector<std::string> const& args,
50 cmExecutionStatus& status);
52 bool joinImpl(std::vector<std::string> const& args, std::string const& glue,
53 size_t varIdx, cmMakefile& makefile);
55 bool HandleHashCommand(std::vector<std::string> const& args,
56 cmExecutionStatus& status)
58 #if !defined(CMAKE_BOOTSTRAP)
59 if (args.size() != 3) {
61 cmStrCat(args[0], " requires an output variable and an input string"));
65 std::unique_ptr<cmCryptoHash> hash(cmCryptoHash::New(args[0]));
67 std::string out = hash->HashString(args[2]);
68 status.GetMakefile().AddDefinition(args[1], out);
73 status.SetError(cmStrCat(args[0], " not available during bootstrap"));
78 bool HandleToUpperLowerCommand(std::vector<std::string> const& args,
79 bool toUpper, cmExecutionStatus& status)
81 if (args.size() < 3) {
82 status.SetError("no output variable specified");
86 std::string const& outvar = args[2];
90 output = cmSystemTools::UpperCase(args[1]);
92 output = cmSystemTools::LowerCase(args[1]);
95 // Store the output in the provided variable.
96 status.GetMakefile().AddDefinition(outvar, output);
100 bool HandleToUpperCommand(std::vector<std::string> const& args,
101 cmExecutionStatus& status)
103 return HandleToUpperLowerCommand(args, true, status);
106 bool HandleToLowerCommand(std::vector<std::string> const& args,
107 cmExecutionStatus& status)
109 return HandleToUpperLowerCommand(args, false, status);
112 bool HandleAsciiCommand(std::vector<std::string> const& args,
113 cmExecutionStatus& status)
115 if (args.size() < 3) {
116 status.SetError("No output variable specified");
119 std::string::size_type cc;
120 std::string const& outvar = args.back();
122 for (cc = 1; cc < args.size() - 1; cc++) {
123 int ch = atoi(args[cc].c_str());
124 if (ch > 0 && ch < 256) {
125 output += static_cast<char>(ch);
128 cmStrCat("Character with code ", args[cc], " does not exist.");
129 status.SetError(error);
133 // Store the output in the provided variable.
134 status.GetMakefile().AddDefinition(outvar, output);
138 bool HandleHexCommand(std::vector<std::string> const& args,
139 cmExecutionStatus& status)
141 if (args.size() != 3) {
142 status.SetError("Incorrect number of arguments");
145 auto const& instr = args[1];
146 auto const& outvar = args[2];
147 std::string output(instr.size() * 2, ' ');
149 std::string::size_type hexIndex = 0;
150 for (auto const& c : instr) {
151 sprintf(&output[hexIndex], "%.2x", static_cast<unsigned char>(c) & 0xFF);
155 status.GetMakefile().AddDefinition(outvar, output);
159 bool HandleConfigureCommand(std::vector<std::string> const& args,
160 cmExecutionStatus& status)
162 if (args.size() < 2) {
163 status.SetError("No input string specified.");
166 if (args.size() < 3) {
167 status.SetError("No output variable specified.");
172 bool escapeQuotes = false;
174 for (unsigned int i = 3; i < args.size(); ++i) {
175 if (args[i] == "@ONLY") {
177 } else if (args[i] == "ESCAPE_QUOTES") {
180 status.SetError(cmStrCat("Unrecognized argument \"", args[i], "\""));
185 // Configure the string.
187 status.GetMakefile().ConfigureString(args[1], output, atOnly, escapeQuotes);
189 // Store the output in the provided variable.
190 status.GetMakefile().AddDefinition(args[2], output);
195 bool HandleRegexCommand(std::vector<std::string> const& args,
196 cmExecutionStatus& status)
198 if (args.size() < 2) {
199 status.SetError("sub-command REGEX requires a mode to be specified.");
202 std::string const& mode = args[1];
203 if (mode == "MATCH") {
204 if (args.size() < 5) {
205 status.SetError("sub-command REGEX, mode MATCH needs "
206 "at least 5 arguments total to command.");
209 return RegexMatch(args, status);
211 if (mode == "MATCHALL") {
212 if (args.size() < 5) {
213 status.SetError("sub-command REGEX, mode MATCHALL needs "
214 "at least 5 arguments total to command.");
217 return RegexMatchAll(args, status);
219 if (mode == "REPLACE") {
220 if (args.size() < 6) {
221 status.SetError("sub-command REGEX, mode REPLACE needs "
222 "at least 6 arguments total to command.");
225 return RegexReplace(args, status);
228 std::string e = "sub-command REGEX does not recognize mode " + mode;
233 bool RegexMatch(std::vector<std::string> const& args,
234 cmExecutionStatus& status)
236 //"STRING(REGEX MATCH <regular_expression> <output variable>
237 // <input> [<input>...])\n";
238 std::string const& regex = args[2];
239 std::string const& outvar = args[3];
241 status.GetMakefile().ClearMatches();
242 // Compile the regular expression.
243 cmsys::RegularExpression re;
244 if (!re.compile(regex)) {
246 "sub-command REGEX, mode MATCH failed to compile regex \"" + regex +
252 // Concatenate all the last arguments together.
253 std::string input = cmJoin(cmMakeRange(args).advance(4), std::string());
255 // Scan through the input for all matches.
257 if (re.find(input)) {
258 status.GetMakefile().StoreMatches(re);
259 std::string::size_type l = re.start();
260 std::string::size_type r = re.end();
262 std::string e = "sub-command REGEX, mode MATCH regex \"" + regex +
263 "\" matched an empty string.";
267 output = input.substr(l, r - l);
270 // Store the output in the provided variable.
271 status.GetMakefile().AddDefinition(outvar, output);
275 bool RegexMatchAll(std::vector<std::string> const& args,
276 cmExecutionStatus& status)
278 //"STRING(REGEX MATCHALL <regular_expression> <output variable> <input>
280 std::string const& regex = args[2];
281 std::string const& outvar = args[3];
283 status.GetMakefile().ClearMatches();
284 // Compile the regular expression.
285 cmsys::RegularExpression re;
286 if (!re.compile(regex)) {
288 "sub-command REGEX, mode MATCHALL failed to compile regex \"" + regex +
294 // Concatenate all the last arguments together.
295 std::string input = cmJoin(cmMakeRange(args).advance(4), std::string());
297 // Scan through the input for all matches.
299 const char* p = input.c_str();
301 status.GetMakefile().ClearMatches();
302 status.GetMakefile().StoreMatches(re);
303 std::string::size_type l = re.start();
304 std::string::size_type r = re.end();
306 std::string e = "sub-command REGEX, mode MATCHALL regex \"" + regex +
307 "\" matched an empty string.";
311 if (!output.empty()) {
314 output += std::string(p + l, r - l);
318 // Store the output in the provided variable.
319 status.GetMakefile().AddDefinition(outvar, output);
323 bool RegexReplace(std::vector<std::string> const& args,
324 cmExecutionStatus& status)
326 //"STRING(REGEX REPLACE <regular_expression> <replace_expression>
327 // <output variable> <input> [<input>...])\n"
328 std::string const& regex = args[2];
329 std::string const& replace = args[3];
330 std::string const& outvar = args[4];
331 cmStringReplaceHelper replaceHelper(regex, replace, &status.GetMakefile());
333 if (!replaceHelper.IsReplaceExpressionValid()) {
335 "sub-command REGEX, mode REPLACE: " + replaceHelper.GetError() + ".");
339 status.GetMakefile().ClearMatches();
341 if (!replaceHelper.IsRegularExpressionValid()) {
343 "sub-command REGEX, mode REPLACE failed to compile regex \"" + regex +
349 // Concatenate all the last arguments together.
350 const std::string input =
351 cmJoin(cmMakeRange(args).advance(5), std::string());
354 if (!replaceHelper.Replace(input, output)) {
356 "sub-command REGEX, mode REPLACE: " + replaceHelper.GetError() + ".");
360 // Store the output in the provided variable.
361 status.GetMakefile().AddDefinition(outvar, output);
365 bool HandleFindCommand(std::vector<std::string> const& args,
366 cmExecutionStatus& status)
368 // check if all required parameters were passed
369 if (args.size() < 4 || args.size() > 5) {
370 status.SetError("sub-command FIND requires 3 or 4 parameters.");
374 // check if the reverse flag was set or not
375 bool reverseMode = false;
376 if (args.size() == 5 && args[4] == "REVERSE") {
380 // if we have 5 arguments the last one must be REVERSE
381 if (args.size() == 5 && args[4] != "REVERSE") {
382 status.SetError("sub-command FIND: unknown last parameter");
386 // local parameter names.
387 const std::string& sstring = args[1];
388 const std::string& schar = args[2];
389 const std::string& outvar = args[3];
391 // ensure that the user cannot accidentally specify REVERSE as a variable
392 if (outvar == "REVERSE") {
393 status.SetError("sub-command FIND does not allow one to select REVERSE as "
394 "the output variable. "
395 "Maybe you missed the actual output variable?");
399 // try to find the character and return its position
402 pos = sstring.find(schar);
404 pos = sstring.rfind(schar);
406 if (std::string::npos != pos) {
407 status.GetMakefile().AddDefinition(outvar, std::to_string(pos));
411 // the character was not found, but this is not really an error
412 status.GetMakefile().AddDefinition(outvar, "-1");
416 bool HandleCompareCommand(std::vector<std::string> const& args,
417 cmExecutionStatus& status)
419 if (args.size() < 2) {
420 status.SetError("sub-command COMPARE requires a mode to be specified.");
423 std::string const& mode = args[1];
424 if ((mode == "EQUAL") || (mode == "NOTEQUAL") || (mode == "LESS") ||
425 (mode == "LESS_EQUAL") || (mode == "GREATER") ||
426 (mode == "GREATER_EQUAL")) {
427 if (args.size() < 5) {
429 cmStrCat("sub-command COMPARE, mode ", mode,
430 " needs at least 5 arguments total to command.");
435 const std::string& left = args[2];
436 const std::string& right = args[3];
437 const std::string& outvar = args[4];
439 if (mode == "LESS") {
440 result = (left < right);
441 } else if (mode == "LESS_EQUAL") {
442 result = (left <= right);
443 } else if (mode == "GREATER") {
444 result = (left > right);
445 } else if (mode == "GREATER_EQUAL") {
446 result = (left >= right);
447 } else if (mode == "EQUAL") {
448 result = (left == right);
449 } else // if(mode == "NOTEQUAL")
451 result = !(left == right);
454 status.GetMakefile().AddDefinition(outvar, "1");
456 status.GetMakefile().AddDefinition(outvar, "0");
460 std::string e = "sub-command COMPARE does not recognize mode " + mode;
465 bool HandleReplaceCommand(std::vector<std::string> const& args,
466 cmExecutionStatus& status)
468 if (args.size() < 5) {
469 status.SetError("sub-command REPLACE requires at least four arguments.");
473 const std::string& matchExpression = args[1];
474 const std::string& replaceExpression = args[2];
475 const std::string& variableName = args[3];
477 std::string input = cmJoin(cmMakeRange(args).advance(4), std::string());
479 cmsys::SystemTools::ReplaceString(input, matchExpression.c_str(),
480 replaceExpression.c_str());
482 status.GetMakefile().AddDefinition(variableName, input);
486 bool HandleSubstringCommand(std::vector<std::string> const& args,
487 cmExecutionStatus& status)
489 if (args.size() != 5) {
490 status.SetError("sub-command SUBSTRING requires four arguments.");
494 const std::string& stringValue = args[1];
495 int begin = atoi(args[2].c_str());
496 int end = atoi(args[3].c_str());
497 const std::string& variableName = args[4];
499 size_t stringLength = stringValue.size();
500 int intStringLength = static_cast<int>(stringLength);
501 if (begin < 0 || begin > intStringLength) {
503 cmStrCat("begin index: ", begin, " is out of range 0 - ", stringLength));
507 status.SetError(cmStrCat("end index: ", end, " should be -1 or greater"));
511 status.GetMakefile().AddDefinition(variableName,
512 stringValue.substr(begin, end));
516 bool HandleLengthCommand(std::vector<std::string> const& args,
517 cmExecutionStatus& status)
519 if (args.size() != 3) {
520 status.SetError("sub-command LENGTH requires two arguments.");
524 const std::string& stringValue = args[1];
525 const std::string& variableName = args[2];
527 size_t length = stringValue.size();
529 sprintf(buffer, "%d", static_cast<int>(length));
531 status.GetMakefile().AddDefinition(variableName, buffer);
535 bool HandleAppendCommand(std::vector<std::string> const& args,
536 cmExecutionStatus& status)
538 if (args.size() < 2) {
539 status.SetError("sub-command APPEND requires at least one argument.");
543 // Skip if nothing to append.
544 if (args.size() < 3) {
548 auto const& variableName = args[1];
550 cm::string_view oldView{ status.GetMakefile().GetSafeDefinition(
553 auto const newValue = cmJoin(cmMakeRange(args).advance(2), {}, oldView);
554 status.GetMakefile().AddDefinition(variableName, newValue);
559 bool HandlePrependCommand(std::vector<std::string> const& args,
560 cmExecutionStatus& status)
562 if (args.size() < 2) {
563 status.SetError("sub-command PREPEND requires at least one argument.");
567 // Skip if nothing to prepend.
568 if (args.size() < 3) {
572 const std::string& variable = args[1];
574 std::string value = cmJoin(cmMakeRange(args).advance(2), std::string());
575 cmValue oldValue = status.GetMakefile().GetDefinition(variable);
579 status.GetMakefile().AddDefinition(variable, value);
583 bool HandleConcatCommand(std::vector<std::string> const& args,
584 cmExecutionStatus& status)
586 if (args.size() < 2) {
587 status.SetError("sub-command CONCAT requires at least one argument.");
591 return joinImpl(args, std::string(), 1, status.GetMakefile());
594 bool HandleJoinCommand(std::vector<std::string> const& args,
595 cmExecutionStatus& status)
597 if (args.size() < 3) {
598 status.SetError("sub-command JOIN requires at least two arguments.");
602 return joinImpl(args, args[1], 2, status.GetMakefile());
605 bool joinImpl(std::vector<std::string> const& args, std::string const& glue,
606 const size_t varIdx, cmMakefile& makefile)
608 std::string const& variableName = args[varIdx];
609 // NOTE Items to concat/join placed right after the variable for
610 // both `CONCAT` and `JOIN` sub-commands.
611 std::string value = cmJoin(cmMakeRange(args).advance(varIdx + 1), glue);
613 makefile.AddDefinition(variableName, value);
617 bool HandleMakeCIdentifierCommand(std::vector<std::string> const& args,
618 cmExecutionStatus& status)
620 if (args.size() != 3) {
621 status.SetError("sub-command MAKE_C_IDENTIFIER requires two arguments.");
625 const std::string& input = args[1];
626 const std::string& variableName = args[2];
628 status.GetMakefile().AddDefinition(variableName,
629 cmSystemTools::MakeCidentifier(input));
633 bool HandleGenexStripCommand(std::vector<std::string> const& args,
634 cmExecutionStatus& status)
636 if (args.size() != 3) {
637 status.SetError("sub-command GENEX_STRIP requires two arguments.");
641 const std::string& input = args[1];
643 std::string result = cmGeneratorExpression::Preprocess(
644 input, cmGeneratorExpression::StripAllGeneratorExpressions);
646 const std::string& variableName = args[2];
648 status.GetMakefile().AddDefinition(variableName, result);
652 bool HandleStripCommand(std::vector<std::string> const& args,
653 cmExecutionStatus& status)
655 if (args.size() != 3) {
656 status.SetError("sub-command STRIP requires two arguments.");
660 const std::string& stringValue = args[1];
661 const std::string& variableName = args[2];
662 size_t inStringLength = stringValue.size();
663 size_t startPos = inStringLength + 1;
665 const char* ptr = stringValue.c_str();
667 for (cc = 0; cc < inStringLength; ++cc) {
668 if (!isspace(*ptr)) {
669 if (startPos > inStringLength) {
677 size_t outLength = 0;
679 // if the input string didn't contain any non-space characters, return
681 if (startPos > inStringLength) {
685 outLength = endPos - startPos + 1;
688 status.GetMakefile().AddDefinition(variableName,
689 stringValue.substr(startPos, outLength));
693 bool HandleRepeatCommand(std::vector<std::string> const& args,
694 cmExecutionStatus& status)
696 cmMakefile& makefile = status.GetMakefile();
698 // `string(REPEAT "<str>" <times> OUTPUT_VARIABLE)`
699 enum ArgPos : std::size_t
708 if (args.size() != ArgPos::TOTAL_ARGS) {
709 makefile.IssueMessage(MessageType::FATAL_ERROR,
710 "sub-command REPEAT requires three arguments.");
715 if (!cmStrToULong(args[ArgPos::TIMES], ×)) {
716 makefile.IssueMessage(MessageType::FATAL_ERROR,
717 "repeat count is not a positive number.");
721 const auto& stringValue = args[ArgPos::VALUE];
722 const auto& variableName = args[ArgPos::OUTPUT_VARIABLE];
723 const auto inStringLength = stringValue.size();
726 switch (inStringLength) {
728 // Nothing to do for zero length input strings
731 // NOTE If the string to repeat consists of the only character,
732 // use the appropriate constructor.
733 result = std::string(times, stringValue[0]);
736 result = std::string(inStringLength * times, char{});
737 for (auto i = 0u; i < times; ++i) {
738 std::copy(cm::cbegin(stringValue), cm::cend(stringValue),
739 &result[i * inStringLength]);
744 makefile.AddDefinition(variableName, result);
748 bool HandleRandomCommand(std::vector<std::string> const& args,
749 cmExecutionStatus& status)
751 if (args.size() < 2 || args.size() == 3 || args.size() == 5) {
752 status.SetError("sub-command RANDOM requires at least one argument.");
756 static bool seeded = false;
757 bool force_seed = false;
758 unsigned int seed = 0;
760 const char cmStringCommandDefaultAlphabet[] = "qwertyuiopasdfghjklzxcvbnm"
761 "QWERTYUIOPASDFGHJKLZXCVBNM"
763 std::string alphabet;
765 if (args.size() > 3) {
767 size_t stopAt = args.size() - 2;
769 for (; i < stopAt; ++i) {
770 if (args[i] == "LENGTH") {
772 length = atoi(args[i].c_str());
773 } else if (args[i] == "ALPHABET") {
776 } else if (args[i] == "RANDOM_SEED") {
778 seed = static_cast<unsigned int>(atoi(args[i].c_str()));
783 if (alphabet.empty()) {
784 alphabet = cmStringCommandDefaultAlphabet;
787 double sizeofAlphabet = static_cast<double>(alphabet.size());
788 if (sizeofAlphabet < 1) {
789 status.SetError("sub-command RANDOM invoked with bad alphabet.");
793 status.SetError("sub-command RANDOM invoked with bad length.");
796 const std::string& variableName = args.back();
798 std::vector<char> result;
800 if (!seeded || force_seed) {
802 srand(force_seed ? seed : cmSystemTools::RandomSeed());
805 const char* alphaPtr = alphabet.c_str();
806 for (int cc = 0; cc < length; cc++) {
807 int idx = static_cast<int>(sizeofAlphabet * rand() / (RAND_MAX + 1.0));
808 result.push_back(*(alphaPtr + idx));
812 status.GetMakefile().AddDefinition(variableName, result.data());
816 bool HandleTimestampCommand(std::vector<std::string> const& args,
817 cmExecutionStatus& status)
819 if (args.size() < 2) {
820 status.SetError("sub-command TIMESTAMP requires at least one argument.");
823 if (args.size() > 4) {
824 status.SetError("sub-command TIMESTAMP takes at most three arguments.");
828 unsigned int argsIndex = 1;
830 const std::string& outputVariable = args[argsIndex++];
832 std::string formatString;
833 if (args.size() > argsIndex && args[argsIndex] != "UTC") {
834 formatString = args[argsIndex++];
837 bool utcFlag = false;
838 if (args.size() > argsIndex) {
839 if (args[argsIndex] == "UTC") {
842 std::string e = " TIMESTAMP sub-command does not recognize option " +
843 args[argsIndex] + ".";
849 cmTimestamp timestamp;
850 std::string result = timestamp.CurrentTime(formatString, utcFlag);
851 status.GetMakefile().AddDefinition(outputVariable, result);
856 bool HandleUuidCommand(std::vector<std::string> const& args,
857 cmExecutionStatus& status)
859 #if !defined(CMAKE_BOOTSTRAP)
860 unsigned int argsIndex = 1;
862 if (args.size() < 2) {
863 status.SetError("UUID sub-command requires an output variable.");
867 const std::string& outputVariable = args[argsIndex++];
869 std::string uuidNamespaceString;
870 std::string uuidName;
871 std::string uuidType;
872 bool uuidUpperCase = false;
874 while (args.size() > argsIndex) {
875 if (args[argsIndex] == "NAMESPACE") {
877 if (argsIndex >= args.size()) {
878 status.SetError("UUID sub-command, NAMESPACE requires a value.");
881 uuidNamespaceString = args[argsIndex++];
882 } else if (args[argsIndex] == "NAME") {
884 if (argsIndex >= args.size()) {
885 status.SetError("UUID sub-command, NAME requires a value.");
888 uuidName = args[argsIndex++];
889 } else if (args[argsIndex] == "TYPE") {
891 if (argsIndex >= args.size()) {
892 status.SetError("UUID sub-command, TYPE requires a value.");
895 uuidType = args[argsIndex++];
896 } else if (args[argsIndex] == "UPPER") {
898 uuidUpperCase = true;
901 "UUID sub-command does not recognize option " + args[argsIndex] + ".";
908 cmUuid uuidGenerator;
910 std::vector<unsigned char> uuidNamespace;
911 if (!uuidGenerator.StringToBinary(uuidNamespaceString, uuidNamespace)) {
912 status.SetError("UUID sub-command, malformed NAMESPACE UUID.");
916 if (uuidType == "MD5") {
917 uuid = uuidGenerator.FromMd5(uuidNamespace, uuidName);
918 } else if (uuidType == "SHA1") {
919 uuid = uuidGenerator.FromSha1(uuidNamespace, uuidName);
921 std::string e = "UUID sub-command, unknown TYPE '" + uuidType + "'.";
927 status.SetError("UUID sub-command, generation failed.");
932 uuid = cmSystemTools::UpperCase(uuid);
935 status.GetMakefile().AddDefinition(outputVariable, uuid);
938 status.SetError(cmStrCat(args[0], " not available during bootstrap"));
943 #if !defined(CMAKE_BOOTSTRAP)
945 // Helpers for string(JSON ...)
946 struct Args : cmRange<typename std::vector<std::string>::const_iterator>
948 using cmRange<typename std::vector<std::string>::const_iterator>::cmRange;
950 auto PopFront(cm::string_view error) -> const std::string&;
951 auto PopBack(cm::string_view error) -> const std::string&;
954 class json_error : public std::runtime_error
957 json_error(std::initializer_list<cm::string_view> message,
958 cm::optional<Args> errorPath = cm::nullopt)
959 : std::runtime_error(cmCatViews(message))
961 std::move(errorPath) // NOLINT(performance-move-const-arg)
965 cm::optional<Args> ErrorPath;
968 const std::string& Args::PopFront(cm::string_view error)
971 throw json_error({ error });
973 const std::string& res = *this->begin();
978 const std::string& Args::PopBack(cm::string_view error)
981 throw json_error({ error });
983 const std::string& res = *(this->end() - 1);
988 cm::string_view JsonTypeToString(Json::ValueType type)
991 case Json::ValueType::nullValue:
993 case Json::ValueType::intValue:
994 case Json::ValueType::uintValue:
995 case Json::ValueType::realValue:
997 case Json::ValueType::stringValue:
999 case Json::ValueType::booleanValue:
1001 case Json::ValueType::arrayValue:
1003 case Json::ValueType::objectValue:
1006 throw json_error({ "invalid JSON type found"_s });
1010 const std::string& str, cm::optional<Args> const& progress = cm::nullopt,
1011 Json::ArrayIndex max = std::numeric_limits<Json::ArrayIndex>::max())
1013 unsigned long lindex;
1014 if (!cmStrToULong(str, &lindex)) {
1015 throw json_error({ "expected an array index, got: '"_s, str, "'"_s },
1018 Json::ArrayIndex index = static_cast<Json::ArrayIndex>(lindex);
1020 cmAlphaNum sizeStr{ max };
1021 throw json_error({ "expected an index less then "_s, sizeStr.View(),
1022 " got '"_s, str, "'"_s },
1028 Json::Value& ResolvePath(Json::Value& json, Args path)
1030 Json::Value* search = &json;
1032 for (auto curr = path.begin(); curr != path.end(); ++curr) {
1033 const std::string& field = *curr;
1034 Args progress{ path.begin(), curr + 1 };
1036 if (search->isArray()) {
1037 auto index = ParseIndex(field, progress, search->size());
1038 search = &(*search)[index];
1040 } else if (search->isObject()) {
1041 if (!search->isMember(field)) {
1042 const auto progressStr = cmJoin(progress, " "_s);
1043 throw json_error({ "member '"_s, progressStr, "' not found"_s },
1046 search = &(*search)[field];
1048 const auto progressStr = cmJoin(progress, " "_s);
1050 { "invalid path '"_s, progressStr,
1051 "', need element of OBJECT or ARRAY type to lookup '"_s, field,
1052 "' got "_s, JsonTypeToString(search->type()) },
1059 Json::Value ReadJson(const std::string& jsonstr)
1061 Json::CharReaderBuilder builder;
1062 builder["collectComments"] = false;
1063 auto jsonReader = std::unique_ptr<Json::CharReader>(builder.newCharReader());
1066 if (!jsonReader->parse(jsonstr.data(), jsonstr.data() + jsonstr.size(),
1068 throw json_error({ "failed parsing json string: "_s, error });
1072 std::string WriteJson(const Json::Value& value)
1074 Json::StreamWriterBuilder writer;
1075 writer["indentation"] = " ";
1076 writer["commentStyle"] = "None";
1077 return Json::writeString(writer, value);
1082 bool HandleJSONCommand(std::vector<std::string> const& arguments,
1083 cmExecutionStatus& status)
1085 #if !defined(CMAKE_BOOTSTRAP)
1087 auto& makefile = status.GetMakefile();
1088 Args args{ arguments.begin() + 1, arguments.end() };
1090 const std::string* errorVariable = nullptr;
1091 const std::string* outputVariable = nullptr;
1092 bool success = true;
1095 outputVariable = &args.PopFront("missing out-var argument"_s);
1097 if (!args.empty() && *args.begin() == "ERROR_VARIABLE"_s) {
1099 errorVariable = &args.PopFront("missing error-var argument"_s);
1100 makefile.AddDefinition(*errorVariable, "NOTFOUND"_s);
1103 const auto& mode = args.PopFront("missing mode argument"_s);
1104 if (mode != "GET"_s && mode != "TYPE"_s && mode != "MEMBER"_s &&
1105 mode != "LENGTH"_s && mode != "REMOVE"_s && mode != "SET"_s &&
1106 mode != "EQUAL"_s) {
1108 { "got an invalid mode '"_s, mode,
1109 "', expected one of GET, GET_ARRAY, TYPE, MEMBER, MEMBERS,"
1110 " LENGTH, REMOVE, SET, EQUAL"_s });
1113 const auto& jsonstr = args.PopFront("missing json string argument"_s);
1114 Json::Value json = ReadJson(jsonstr);
1116 if (mode == "GET"_s) {
1117 const auto& value = ResolvePath(json, args);
1118 if (value.isObject() || value.isArray()) {
1119 makefile.AddDefinition(*outputVariable, WriteJson(value));
1120 } else if (value.isBool()) {
1121 makefile.AddDefinitionBool(*outputVariable, value.asBool());
1123 makefile.AddDefinition(*outputVariable, value.asString());
1126 } else if (mode == "TYPE"_s) {
1127 const auto& value = ResolvePath(json, args);
1128 makefile.AddDefinition(*outputVariable, JsonTypeToString(value.type()));
1130 } else if (mode == "MEMBER"_s) {
1131 const auto& indexStr = args.PopBack("missing member index"_s);
1132 const auto& value = ResolvePath(json, args);
1133 if (!value.isObject()) {
1134 throw json_error({ "MEMBER needs to be called with an element of "
1135 "type OBJECT, got "_s,
1136 JsonTypeToString(value.type()) },
1139 const auto index = ParseIndex(
1140 indexStr, Args{ args.begin(), args.end() + 1 }, value.size());
1141 const auto memIt = std::next(value.begin(), index);
1142 makefile.AddDefinition(*outputVariable, memIt.name());
1144 } else if (mode == "LENGTH"_s) {
1145 const auto& value = ResolvePath(json, args);
1146 if (!value.isArray() && !value.isObject()) {
1147 throw json_error({ "LENGTH needs to be called with an "
1148 "element of type ARRAY or OBJECT, got "_s,
1149 JsonTypeToString(value.type()) },
1153 cmAlphaNum sizeStr{ value.size() };
1154 makefile.AddDefinition(*outputVariable, sizeStr.View());
1156 } else if (mode == "REMOVE"_s) {
1157 const auto& toRemove =
1158 args.PopBack("missing member or index to remove"_s);
1159 auto& value = ResolvePath(json, args);
1161 if (value.isArray()) {
1162 const auto index = ParseIndex(
1163 toRemove, Args{ args.begin(), args.end() + 1 }, value.size());
1164 Json::Value removed;
1165 value.removeIndex(index, &removed);
1167 } else if (value.isObject()) {
1168 Json::Value removed;
1169 value.removeMember(toRemove, &removed);
1172 throw json_error({ "REMOVE needs to be called with an "
1173 "element of type ARRAY or OBJECT, got "_s,
1174 JsonTypeToString(value.type()) },
1177 makefile.AddDefinition(*outputVariable, WriteJson(json));
1179 } else if (mode == "SET"_s) {
1180 const auto& newValueStr = args.PopBack("missing new value remove"_s);
1181 const auto& toAdd = args.PopBack("missing member name to add"_s);
1182 auto& value = ResolvePath(json, args);
1184 Json::Value newValue = ReadJson(newValueStr);
1185 if (value.isObject()) {
1186 value[toAdd] = newValue;
1187 } else if (value.isArray()) {
1189 ParseIndex(toAdd, Args{ args.begin(), args.end() + 1 });
1190 if (value.isValidIndex(index)) {
1191 value[static_cast<int>(index)] = newValue;
1193 value.append(newValue);
1196 throw json_error({ "SET needs to be called with an "
1197 "element of type OBJECT or ARRAY, got "_s,
1198 JsonTypeToString(value.type()) });
1201 makefile.AddDefinition(*outputVariable, WriteJson(json));
1203 } else if (mode == "EQUAL"_s) {
1204 const auto& jsonstr2 =
1205 args.PopFront("missing second json string argument"_s);
1206 Json::Value json2 = ReadJson(jsonstr2);
1207 makefile.AddDefinitionBool(*outputVariable, json == json2);
1210 } catch (const json_error& e) {
1211 if (outputVariable && e.ErrorPath) {
1212 const auto errorPath = cmJoin(*e.ErrorPath, "-");
1213 makefile.AddDefinition(*outputVariable,
1214 cmCatViews({ errorPath, "-NOTFOUND"_s }));
1215 } else if (outputVariable) {
1216 makefile.AddDefinition(*outputVariable, "NOTFOUND"_s);
1219 if (errorVariable) {
1220 makefile.AddDefinition(*errorVariable, e.what());
1222 status.SetError(cmCatViews({ "sub-command JSON "_s, e.what(), "."_s }));
1228 status.SetError(cmStrCat(arguments[0], " not available during bootstrap"_s));
1235 bool cmStringCommand(std::vector<std::string> const& args,
1236 cmExecutionStatus& status)
1239 status.SetError("must be called with at least one argument.");
1243 static cmSubcommandTable const subcommand{
1244 { "REGEX"_s, HandleRegexCommand },
1245 { "REPLACE"_s, HandleReplaceCommand },
1246 { "MD5"_s, HandleHashCommand },
1247 { "SHA1"_s, HandleHashCommand },
1248 { "SHA224"_s, HandleHashCommand },
1249 { "SHA256"_s, HandleHashCommand },
1250 { "SHA384"_s, HandleHashCommand },
1251 { "SHA512"_s, HandleHashCommand },
1252 { "SHA3_224"_s, HandleHashCommand },
1253 { "SHA3_256"_s, HandleHashCommand },
1254 { "SHA3_384"_s, HandleHashCommand },
1255 { "SHA3_512"_s, HandleHashCommand },
1256 { "TOLOWER"_s, HandleToLowerCommand },
1257 { "TOUPPER"_s, HandleToUpperCommand },
1258 { "COMPARE"_s, HandleCompareCommand },
1259 { "ASCII"_s, HandleAsciiCommand },
1260 { "HEX"_s, HandleHexCommand },
1261 { "CONFIGURE"_s, HandleConfigureCommand },
1262 { "LENGTH"_s, HandleLengthCommand },
1263 { "APPEND"_s, HandleAppendCommand },
1264 { "PREPEND"_s, HandlePrependCommand },
1265 { "CONCAT"_s, HandleConcatCommand },
1266 { "JOIN"_s, HandleJoinCommand },
1267 { "SUBSTRING"_s, HandleSubstringCommand },
1268 { "STRIP"_s, HandleStripCommand },
1269 { "REPEAT"_s, HandleRepeatCommand },
1270 { "RANDOM"_s, HandleRandomCommand },
1271 { "FIND"_s, HandleFindCommand },
1272 { "TIMESTAMP"_s, HandleTimestampCommand },
1273 { "MAKE_C_IDENTIFIER"_s, HandleMakeCIdentifierCommand },
1274 { "GENEX_STRIP"_s, HandleGenexStripCommand },
1275 { "UUID"_s, HandleUuidCommand },
1276 { "JSON"_s, HandleJSONCommand },
1279 return subcommand(args[0], args, status);