cmStringCommand.cxx 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file LICENSE.rst or https://cmake.org/licensing for details. */
  3. // NOLINTNEXTLINE(bugprone-reserved-identifier)
  4. #define _SCL_SECURE_NO_WARNINGS
  5. #include "cmStringCommand.h"
  6. #include <cstdio>
  7. #include <cstdlib>
  8. #include <exception>
  9. #include <limits>
  10. #include <memory>
  11. #include <stdexcept>
  12. #include <utility>
  13. #include <cm/iterator>
  14. #include <cm/optional>
  15. #include <cm/string_view>
  16. #include <cmext/string_view>
  17. #include <cm3p/json/reader.h>
  18. #include <cm3p/json/value.h>
  19. #include <cm3p/json/writer.h>
  20. #include "cmCMakeString.hxx"
  21. #include "cmExecutionStatus.h"
  22. #include "cmList.h"
  23. #include "cmMakefile.h"
  24. #include "cmMessageType.h"
  25. #include "cmRange.h"
  26. #include "cmStringAlgorithms.h"
  27. #include "cmSubcommandTable.h"
  28. namespace {
  29. bool RegexMatch(std::vector<std::string> const& args,
  30. cmExecutionStatus& status);
  31. bool RegexMatchAll(std::vector<std::string> const& args,
  32. cmExecutionStatus& status);
  33. bool RegexReplace(std::vector<std::string> const& args,
  34. cmExecutionStatus& status);
  35. bool RegexQuote(std::vector<std::string> const& args,
  36. cmExecutionStatus& status);
  37. bool joinImpl(std::vector<std::string> const& args, std::string const& glue,
  38. size_t varIdx, cmMakefile& makefile);
  39. bool HandleHashCommand(std::vector<std::string> const& args,
  40. cmExecutionStatus& status)
  41. {
  42. if (args.size() != 3) {
  43. status.SetError(
  44. cmStrCat(args[0], " requires an output variable and an input string"));
  45. return false;
  46. }
  47. cm::CMakeString data{ args[2] };
  48. try {
  49. data.Hash(args[0]);
  50. status.GetMakefile().AddDefinition(args[1], data);
  51. return true;
  52. } catch (std::exception const& e) {
  53. status.SetError(e.what());
  54. return false;
  55. }
  56. }
  57. bool HandleToUpperLowerCommand(std::vector<std::string> const& args,
  58. bool toUpper, cmExecutionStatus& status)
  59. {
  60. if (args.size() < 3) {
  61. status.SetError("no output variable specified");
  62. return false;
  63. }
  64. std::string const& outvar = args[2];
  65. cm::CMakeString data{ args[1] };
  66. if (toUpper) {
  67. data.ToUpper();
  68. } else {
  69. data.ToLower();
  70. }
  71. // Store the output in the provided variable.
  72. status.GetMakefile().AddDefinition(outvar, data);
  73. return true;
  74. }
  75. bool HandleToUpperCommand(std::vector<std::string> const& args,
  76. cmExecutionStatus& status)
  77. {
  78. return HandleToUpperLowerCommand(args, true, status);
  79. }
  80. bool HandleToLowerCommand(std::vector<std::string> const& args,
  81. cmExecutionStatus& status)
  82. {
  83. return HandleToUpperLowerCommand(args, false, status);
  84. }
  85. bool HandleAsciiCommand(std::vector<std::string> const& args,
  86. cmExecutionStatus& status)
  87. {
  88. if (args.size() < 3) {
  89. status.SetError("No output variable specified");
  90. return false;
  91. }
  92. try {
  93. std::string const& outvar = args.back();
  94. cm::CMakeString data;
  95. data.FromASCII(cmMakeRange(args).advance(1).retreat(1));
  96. status.GetMakefile().AddDefinition(outvar, data);
  97. return true;
  98. } catch (std::exception const& e) {
  99. status.SetError(e.what());
  100. return false;
  101. }
  102. }
  103. bool HandleHexCommand(std::vector<std::string> const& args,
  104. cmExecutionStatus& status)
  105. {
  106. if (args.size() != 3) {
  107. status.SetError("Incorrect number of arguments");
  108. return false;
  109. }
  110. auto const& outvar = args[2];
  111. cm::CMakeString data{ args[1] };
  112. data.ToHexadecimal();
  113. status.GetMakefile().AddDefinition(outvar, data);
  114. return true;
  115. }
  116. bool HandleConfigureCommand(std::vector<std::string> const& args,
  117. cmExecutionStatus& status)
  118. {
  119. if (args.size() < 2) {
  120. status.SetError("No input string specified.");
  121. return false;
  122. }
  123. if (args.size() < 3) {
  124. status.SetError("No output variable specified.");
  125. return false;
  126. }
  127. // Parse options.
  128. bool escapeQuotes = false;
  129. bool atOnly = false;
  130. for (unsigned int i = 3; i < args.size(); ++i) {
  131. if (args[i] == "@ONLY") {
  132. atOnly = true;
  133. } else if (args[i] == "ESCAPE_QUOTES") {
  134. escapeQuotes = true;
  135. } else {
  136. status.SetError(cmStrCat("Unrecognized argument \"", args[i], '"'));
  137. return false;
  138. }
  139. }
  140. // Configure the string.
  141. std::string output;
  142. status.GetMakefile().ConfigureString(args[1], output, atOnly, escapeQuotes);
  143. // Store the output in the provided variable.
  144. status.GetMakefile().AddDefinition(args[2], output);
  145. return true;
  146. }
  147. bool HandleRegexCommand(std::vector<std::string> const& args,
  148. cmExecutionStatus& status)
  149. {
  150. if (args.size() < 2) {
  151. status.SetError("sub-command REGEX requires a mode to be specified.");
  152. return false;
  153. }
  154. std::string const& mode = args[1];
  155. if (mode == "MATCH") {
  156. if (args.size() < 5) {
  157. status.SetError("sub-command REGEX, mode MATCH needs "
  158. "at least 5 arguments total to command.");
  159. return false;
  160. }
  161. return RegexMatch(args, status);
  162. }
  163. if (mode == "MATCHALL") {
  164. if (args.size() < 5) {
  165. status.SetError("sub-command REGEX, mode MATCHALL needs "
  166. "at least 5 arguments total to command.");
  167. return false;
  168. }
  169. return RegexMatchAll(args, status);
  170. }
  171. if (mode == "REPLACE") {
  172. if (args.size() < 6) {
  173. status.SetError("sub-command REGEX, mode REPLACE needs "
  174. "at least 6 arguments total to command.");
  175. return false;
  176. }
  177. return RegexReplace(args, status);
  178. }
  179. if (mode == "QUOTE") {
  180. if (args.size() < 4) {
  181. status.SetError("sub-command REGEX, mode QUOTE needs "
  182. "at least 4 arguments total to command.");
  183. return false;
  184. }
  185. return RegexQuote(args, status);
  186. }
  187. std::string e = "sub-command REGEX does not recognize mode " + mode;
  188. status.SetError(e);
  189. return false;
  190. }
  191. bool RegexMatch(std::vector<std::string> const& args,
  192. cmExecutionStatus& status)
  193. {
  194. //"STRING(REGEX MATCH <regular_expression> <output variable>
  195. // <input> [<input>...])\n";
  196. try {
  197. std::string const& regex = args[2];
  198. std::string const& outvar = args[3];
  199. cm::CMakeString data{ cmMakeRange(args).advance(4) };
  200. auto result = data.Match(regex, cm::CMakeString::MatchItems::Once,
  201. &status.GetMakefile());
  202. // Store the result in the provided variable.
  203. status.GetMakefile().AddDefinition(outvar, result.to_string());
  204. return true;
  205. } catch (std::exception const& e) {
  206. status.SetError(
  207. cmStrCat("sub-command REGEX, mode MATCH: ", e.what(), '.'));
  208. return false;
  209. }
  210. }
  211. bool RegexMatchAll(std::vector<std::string> const& args,
  212. cmExecutionStatus& status)
  213. {
  214. //"STRING(REGEX MATCHALL <regular_expression> <output variable> <input>
  215. // [<input>...])\n";
  216. try {
  217. std::string const& regex = args[2];
  218. std::string const& outvar = args[3];
  219. cm::CMakeString data{ cmMakeRange(args).advance(4) };
  220. auto result = data.Match(regex, cm::CMakeString::MatchItems::All,
  221. &status.GetMakefile());
  222. // Store the result in the provided variable.
  223. status.GetMakefile().AddDefinition(outvar, result.to_string());
  224. return true;
  225. } catch (std::exception const& e) {
  226. status.SetError(
  227. cmStrCat("sub-command REGEX, mode MATCHALL: ", e.what(), '.'));
  228. return false;
  229. }
  230. }
  231. bool RegexReplace(std::vector<std::string> const& args,
  232. cmExecutionStatus& status)
  233. {
  234. //"STRING(REGEX REPLACE <regular_expression> <replace_expression>
  235. // <output variable> <input> [<input>...])\n"
  236. std::string const& regex = args[2];
  237. std::string const& replace = args[3];
  238. std::string const& outvar = args[4];
  239. try {
  240. cm::CMakeString data{ cmMakeRange(args).advance(5) };
  241. data.Replace(regex, replace, cm::CMakeString::Regex::Yes,
  242. &status.GetMakefile());
  243. // Store the result in the provided variable.
  244. status.GetMakefile().AddDefinition(outvar, data);
  245. return true;
  246. } catch (std::exception const& e) {
  247. status.SetError(
  248. cmStrCat("sub-command REGEX, mode REPLACE: ", e.what(), '.'));
  249. return false;
  250. }
  251. }
  252. bool RegexQuote(std::vector<std::string> const& args,
  253. cmExecutionStatus& status)
  254. {
  255. //"STRING(REGEX QUOTE <output variable> <input> [<input>...]\n"
  256. std::string const& outvar = args[2];
  257. cm::CMakeString data{ cmMakeRange(args).advance(3) };
  258. try {
  259. // Escape all regex special characters
  260. data.Quote();
  261. // Store the output in the provided variable.
  262. status.GetMakefile().AddDefinition(outvar, data);
  263. return true;
  264. } catch (std::exception const& e) {
  265. status.SetError(
  266. cmStrCat("sub-command REGEX, mode QUOTE: ", e.what(), '.'));
  267. return false;
  268. }
  269. }
  270. bool HandleFindCommand(std::vector<std::string> const& args,
  271. cmExecutionStatus& status)
  272. {
  273. // check if all required parameters were passed
  274. if (args.size() < 4 || args.size() > 5) {
  275. status.SetError("sub-command FIND requires 3 or 4 parameters.");
  276. return false;
  277. }
  278. // check if the reverse flag was set or not
  279. bool reverseMode = false;
  280. if (args.size() == 5 && args[4] == "REVERSE") {
  281. reverseMode = true;
  282. }
  283. // if we have 5 arguments the last one must be REVERSE
  284. if (args.size() == 5 && args[4] != "REVERSE") {
  285. status.SetError("sub-command FIND: unknown last parameter");
  286. return false;
  287. }
  288. // local parameter names.
  289. std::string const& sstring = args[1];
  290. std::string const& schar = args[2];
  291. std::string const& outvar = args[3];
  292. // ensure that the user cannot accidentally specify REVERSE as a variable
  293. if (outvar == "REVERSE") {
  294. status.SetError("sub-command FIND does not allow one to select REVERSE as "
  295. "the output variable. "
  296. "Maybe you missed the actual output variable?");
  297. return false;
  298. }
  299. // try to find the character and return its position
  300. auto pos = cm::CMakeString{ sstring }.Find(
  301. schar,
  302. reverseMode ? cm::CMakeString::FindFrom::End
  303. : cm::CMakeString::FindFrom::Begin);
  304. status.GetMakefile().AddDefinition(
  305. outvar, pos != cm::CMakeString::npos ? std::to_string(pos) : "-1");
  306. return true;
  307. }
  308. bool HandleCompareCommand(std::vector<std::string> const& args,
  309. cmExecutionStatus& status)
  310. {
  311. if (args.size() < 2) {
  312. status.SetError("sub-command COMPARE requires a mode to be specified.");
  313. return false;
  314. }
  315. std::string const& mode = args[1];
  316. if ((mode == "EQUAL") || (mode == "NOTEQUAL") || (mode == "LESS") ||
  317. (mode == "LESS_EQUAL") || (mode == "GREATER") ||
  318. (mode == "GREATER_EQUAL")) {
  319. if (args.size() < 5) {
  320. std::string e =
  321. cmStrCat("sub-command COMPARE, mode ", mode,
  322. " needs at least 5 arguments total to command.");
  323. status.SetError(e);
  324. return false;
  325. }
  326. std::string const& left = args[2];
  327. std::string const& right = args[3];
  328. std::string const& outvar = args[4];
  329. bool result;
  330. cm::CMakeString::CompOperator op = cm::CMakeString::CompOperator::EQUAL;
  331. if (mode == "LESS") {
  332. op = cm::CMakeString::CompOperator::LESS;
  333. } else if (mode == "LESS_EQUAL") {
  334. op = cm::CMakeString::CompOperator::LESS_EQUAL;
  335. } else if (mode == "GREATER") {
  336. op = cm::CMakeString::CompOperator::GREATER;
  337. } else if (mode == "GREATER_EQUAL") {
  338. op = cm::CMakeString::CompOperator::GREATER_EQUAL;
  339. }
  340. result = cm::CMakeString{ left }.Compare(op, right);
  341. if (mode == "NOTEQUAL") {
  342. result = !result;
  343. }
  344. status.GetMakefile().AddDefinition(outvar, result ? "1" : "0");
  345. return true;
  346. }
  347. std::string e = "sub-command COMPARE does not recognize mode " + mode;
  348. status.SetError(e);
  349. return false;
  350. }
  351. bool HandleReplaceCommand(std::vector<std::string> const& args,
  352. cmExecutionStatus& status)
  353. {
  354. if (args.size() < 5) {
  355. status.SetError("sub-command REPLACE requires at least four arguments.");
  356. return false;
  357. }
  358. try {
  359. std::string const& matchExpression = args[1];
  360. std::string const& replaceExpression = args[2];
  361. std::string const& variableName = args[3];
  362. cm::CMakeString data{ cmMakeRange(args).advance(4) };
  363. data.Replace(matchExpression, replaceExpression);
  364. status.GetMakefile().AddDefinition(variableName, data);
  365. return true;
  366. } catch (std::exception const& e) {
  367. status.SetError(cmStrCat("sub-command REPLACE: ", e.what(), '.'));
  368. return false;
  369. }
  370. }
  371. bool HandleSubstringCommand(std::vector<std::string> const& args,
  372. cmExecutionStatus& status)
  373. {
  374. if (args.size() != 5) {
  375. status.SetError("sub-command SUBSTRING requires four arguments.");
  376. return false;
  377. }
  378. try {
  379. std::string const& stringValue = args[1];
  380. int begin = atoi(args[2].c_str());
  381. int end = atoi(args[3].c_str());
  382. std::string const& variableName = args[4];
  383. cm::CMakeString data{ stringValue };
  384. status.GetMakefile().AddDefinition(variableName,
  385. data.Substring(begin, end));
  386. } catch (std::exception const& e) {
  387. status.SetError(e.what());
  388. return false;
  389. }
  390. return true;
  391. }
  392. bool HandleLengthCommand(std::vector<std::string> const& args,
  393. cmExecutionStatus& status)
  394. {
  395. if (args.size() != 3) {
  396. status.SetError("sub-command LENGTH requires two arguments.");
  397. return false;
  398. }
  399. std::string const& stringValue = args[1];
  400. std::string const& variableName = args[2];
  401. status.GetMakefile().AddDefinition(
  402. variableName, std::to_string(cm::CMakeString{ stringValue }.Length()));
  403. return true;
  404. }
  405. bool HandleAppendCommand(std::vector<std::string> const& args,
  406. cmExecutionStatus& status)
  407. {
  408. if (args.size() < 2) {
  409. status.SetError("sub-command APPEND requires at least one argument.");
  410. return false;
  411. }
  412. // Skip if nothing to append.
  413. if (args.size() < 3) {
  414. return true;
  415. }
  416. auto const& variableName = args[1];
  417. cm::CMakeString data{ status.GetMakefile().GetDefinition(variableName) };
  418. data.Append(cmMakeRange(args).advance(2));
  419. status.GetMakefile().AddDefinition(variableName, data);
  420. return true;
  421. }
  422. bool HandlePrependCommand(std::vector<std::string> const& args,
  423. cmExecutionStatus& status)
  424. {
  425. if (args.size() < 2) {
  426. status.SetError("sub-command PREPEND requires at least one argument.");
  427. return false;
  428. }
  429. // Skip if nothing to prepend.
  430. if (args.size() < 3) {
  431. return true;
  432. }
  433. std::string const& variable = args[1];
  434. cm::CMakeString data{ status.GetMakefile().GetDefinition(variable) };
  435. data.Prepend(cmMakeRange(args).advance(2));
  436. status.GetMakefile().AddDefinition(variable, data);
  437. return true;
  438. }
  439. bool HandleConcatCommand(std::vector<std::string> const& args,
  440. cmExecutionStatus& status)
  441. {
  442. if (args.size() < 2) {
  443. status.SetError("sub-command CONCAT requires at least one argument.");
  444. return false;
  445. }
  446. return joinImpl(args, std::string(), 1, status.GetMakefile());
  447. }
  448. bool HandleJoinCommand(std::vector<std::string> const& args,
  449. cmExecutionStatus& status)
  450. {
  451. if (args.size() < 3) {
  452. status.SetError("sub-command JOIN requires at least two arguments.");
  453. return false;
  454. }
  455. return joinImpl(args, args[1], 2, status.GetMakefile());
  456. }
  457. bool joinImpl(std::vector<std::string> const& args, std::string const& glue,
  458. size_t const varIdx, cmMakefile& makefile)
  459. {
  460. std::string const& variableName = args[varIdx];
  461. // NOTE Items to concat/join placed right after the variable for
  462. // both `CONCAT` and `JOIN` sub-commands.
  463. cm::CMakeString data{ cmMakeRange(args).advance(varIdx + 1), glue };
  464. makefile.AddDefinition(variableName, data);
  465. return true;
  466. }
  467. bool HandleMakeCIdentifierCommand(std::vector<std::string> const& args,
  468. cmExecutionStatus& status)
  469. {
  470. if (args.size() != 3) {
  471. status.SetError("sub-command MAKE_C_IDENTIFIER requires two arguments.");
  472. return false;
  473. }
  474. std::string const& input = args[1];
  475. std::string const& variableName = args[2];
  476. status.GetMakefile().AddDefinition(variableName,
  477. cm::CMakeString{}.MakeCIdentifier(input));
  478. return true;
  479. }
  480. bool HandleGenexStripCommand(std::vector<std::string> const& args,
  481. cmExecutionStatus& status)
  482. {
  483. if (args.size() != 3) {
  484. status.SetError("sub-command GENEX_STRIP requires two arguments.");
  485. return false;
  486. }
  487. cm::CMakeString data{ args[1] };
  488. std::string const& variableName = args[2];
  489. status.GetMakefile().AddDefinition(
  490. variableName, data.Strip(cm::CMakeString::StripItems::Genex));
  491. return true;
  492. }
  493. bool HandleStripCommand(std::vector<std::string> const& args,
  494. cmExecutionStatus& status)
  495. {
  496. if (args.size() != 3) {
  497. status.SetError("sub-command STRIP requires two arguments.");
  498. return false;
  499. }
  500. cm::CMakeString data{ args[1] };
  501. std::string const& variableName = args[2];
  502. status.GetMakefile().AddDefinition(variableName, data.Strip());
  503. return true;
  504. }
  505. bool HandleRepeatCommand(std::vector<std::string> const& args,
  506. cmExecutionStatus& status)
  507. {
  508. cmMakefile& makefile = status.GetMakefile();
  509. // `string(REPEAT "<str>" <times> OUTPUT_VARIABLE)`
  510. enum ArgPos : std::size_t
  511. {
  512. SUB_COMMAND,
  513. VALUE,
  514. TIMES,
  515. OUTPUT_VARIABLE,
  516. TOTAL_ARGS
  517. };
  518. if (args.size() != ArgPos::TOTAL_ARGS) {
  519. makefile.IssueMessage(MessageType::FATAL_ERROR,
  520. "sub-command REPEAT requires three arguments.");
  521. return true;
  522. }
  523. unsigned long times;
  524. if (!cmStrToULong(args[ArgPos::TIMES], &times)) {
  525. makefile.IssueMessage(MessageType::FATAL_ERROR,
  526. "repeat count is not a positive number.");
  527. return true;
  528. }
  529. cm::CMakeString data{ args[ArgPos::VALUE] };
  530. data.Repeat(times);
  531. auto const& variableName = args[ArgPos::OUTPUT_VARIABLE];
  532. makefile.AddDefinition(variableName, data);
  533. return true;
  534. }
  535. bool HandleRandomCommand(std::vector<std::string> const& args,
  536. cmExecutionStatus& status)
  537. {
  538. if (args.size() < 2 || args.size() == 3 || args.size() == 5) {
  539. status.SetError("sub-command RANDOM requires at least one argument.");
  540. return false;
  541. }
  542. int length = 5;
  543. cm::string_view alphabet;
  544. bool force_seed = false;
  545. unsigned int seed = 0;
  546. if (args.size() > 3) {
  547. size_t i = 1;
  548. size_t stopAt = args.size() - 2;
  549. for (; i < stopAt; ++i) {
  550. if (args[i] == "LENGTH") {
  551. ++i;
  552. length = atoi(args[i].c_str());
  553. } else if (args[i] == "ALPHABET") {
  554. ++i;
  555. alphabet = args[i];
  556. } else if (args[i] == "RANDOM_SEED") {
  557. ++i;
  558. seed = static_cast<unsigned int>(atoi(args[i].c_str()));
  559. force_seed = true;
  560. }
  561. }
  562. }
  563. try {
  564. cm::CMakeString data;
  565. std::string const& variableName = args.back();
  566. if (force_seed) {
  567. data.Random(seed, length, alphabet);
  568. } else {
  569. data.Random(length, alphabet);
  570. }
  571. status.GetMakefile().AddDefinition(variableName, data);
  572. return true;
  573. } catch (std::exception const& e) {
  574. status.SetError(cmStrCat("sub-command RANDOM: ", e.what(), '.'));
  575. return false;
  576. }
  577. }
  578. bool HandleTimestampCommand(std::vector<std::string> const& args,
  579. cmExecutionStatus& status)
  580. {
  581. if (args.size() < 2) {
  582. status.SetError("sub-command TIMESTAMP requires at least one argument.");
  583. return false;
  584. }
  585. if (args.size() > 4) {
  586. status.SetError("sub-command TIMESTAMP takes at most three arguments.");
  587. return false;
  588. }
  589. unsigned int argsIndex = 1;
  590. std::string const& outputVariable = args[argsIndex++];
  591. cm::string_view formatString;
  592. if (args.size() > argsIndex && args[argsIndex] != "UTC") {
  593. formatString = args[argsIndex++];
  594. }
  595. cm::CMakeString::UTC utcFlag = cm::CMakeString::UTC::No;
  596. if (args.size() > argsIndex) {
  597. if (args[argsIndex] == "UTC") {
  598. utcFlag = cm::CMakeString::UTC::Yes;
  599. } else {
  600. std::string e =
  601. cmStrCat(" TIMESTAMP sub-command does not recognize option ",
  602. args[argsIndex], '.');
  603. status.SetError(e);
  604. return false;
  605. }
  606. }
  607. cm::CMakeString data;
  608. status.GetMakefile().AddDefinition(outputVariable,
  609. data.Timestamp(formatString, utcFlag));
  610. return true;
  611. }
  612. bool HandleUuidCommand(std::vector<std::string> const& args,
  613. cmExecutionStatus& status)
  614. {
  615. #if !defined(CMAKE_BOOTSTRAP)
  616. unsigned int argsIndex = 1;
  617. if (args.size() < 2) {
  618. status.SetError("UUID sub-command requires an output variable.");
  619. return false;
  620. }
  621. std::string const& outputVariable = args[argsIndex++];
  622. cm::string_view uuidNamespaceString;
  623. cm::string_view uuidName;
  624. cm::CMakeString::UUIDType uuidType = cm::CMakeString::UUIDType::MD5;
  625. cm::CMakeString::Case uuidCase = cm::CMakeString::Case::Lower;
  626. while (args.size() > argsIndex) {
  627. if (args[argsIndex] == "NAMESPACE") {
  628. ++argsIndex;
  629. if (argsIndex >= args.size()) {
  630. status.SetError("UUID sub-command, NAMESPACE requires a value.");
  631. return false;
  632. }
  633. uuidNamespaceString = args[argsIndex++];
  634. } else if (args[argsIndex] == "NAME") {
  635. ++argsIndex;
  636. if (argsIndex >= args.size()) {
  637. status.SetError("UUID sub-command, NAME requires a value.");
  638. return false;
  639. }
  640. uuidName = args[argsIndex++];
  641. } else if (args[argsIndex] == "TYPE") {
  642. ++argsIndex;
  643. if (argsIndex >= args.size()) {
  644. status.SetError("UUID sub-command, TYPE requires a value.");
  645. return false;
  646. }
  647. if (args[argsIndex] == "MD5") {
  648. uuidType = cm::CMakeString::UUIDType::MD5;
  649. } else if (args[argsIndex] == "SHA1") {
  650. uuidType = cm::CMakeString::UUIDType::SHA1;
  651. } else {
  652. status.SetError(
  653. cmStrCat("UUID sub-command, unknown TYPE '", args[argsIndex], "'."));
  654. return false;
  655. }
  656. argsIndex++;
  657. } else if (args[argsIndex] == "UPPER") {
  658. ++argsIndex;
  659. uuidCase = cm::CMakeString::Case::Upper;
  660. } else {
  661. std::string e = cmStrCat("UUID sub-command does not recognize option ",
  662. args[argsIndex], '.');
  663. status.SetError(e);
  664. return false;
  665. }
  666. }
  667. try {
  668. cm::CMakeString data;
  669. data.UUID(uuidNamespaceString, uuidName, uuidType, uuidCase);
  670. status.GetMakefile().AddDefinition(outputVariable, data);
  671. return true;
  672. } catch (std::exception const& e) {
  673. status.SetError(cmStrCat("UUID sub-command, ", e.what(), '.'));
  674. return false;
  675. }
  676. #else
  677. status.SetError("UUID sub-command not available during bootstrap.");
  678. return false;
  679. #endif
  680. }
  681. #if !defined(CMAKE_BOOTSTRAP)
  682. // Helpers for string(JSON ...)
  683. struct Args : cmRange<typename std::vector<std::string>::const_iterator>
  684. {
  685. using cmRange<typename std::vector<std::string>::const_iterator>::cmRange;
  686. auto PopFront(cm::string_view error) -> std::string const&;
  687. auto PopBack(cm::string_view error) -> std::string const&;
  688. };
  689. class json_error : public std::runtime_error
  690. {
  691. public:
  692. json_error(std::string const& message,
  693. cm::optional<Args> errorPath = cm::nullopt)
  694. : std::runtime_error(message)
  695. , ErrorPath{
  696. std::move(errorPath) // NOLINT(performance-move-const-arg)
  697. }
  698. {
  699. }
  700. cm::optional<Args> ErrorPath;
  701. };
  702. std::string const& Args::PopFront(cm::string_view error)
  703. {
  704. if (this->empty()) {
  705. throw json_error(std::string(error));
  706. }
  707. std::string const& res = *this->begin();
  708. this->advance(1);
  709. return res;
  710. }
  711. std::string const& Args::PopBack(cm::string_view error)
  712. {
  713. if (this->empty()) {
  714. throw json_error(std::string(error));
  715. }
  716. std::string const& res = *(this->end() - 1);
  717. this->retreat(1);
  718. return res;
  719. }
  720. cm::string_view JsonTypeToString(Json::ValueType type)
  721. {
  722. switch (type) {
  723. case Json::ValueType::nullValue:
  724. return "NULL"_s;
  725. case Json::ValueType::intValue:
  726. case Json::ValueType::uintValue:
  727. case Json::ValueType::realValue:
  728. return "NUMBER"_s;
  729. case Json::ValueType::stringValue:
  730. return "STRING"_s;
  731. case Json::ValueType::booleanValue:
  732. return "BOOLEAN"_s;
  733. case Json::ValueType::arrayValue:
  734. return "ARRAY"_s;
  735. case Json::ValueType::objectValue:
  736. return "OBJECT"_s;
  737. }
  738. throw json_error("invalid JSON type found");
  739. }
  740. int ParseIndex(
  741. std::string const& str, cm::optional<Args> const& progress = cm::nullopt,
  742. Json::ArrayIndex max = std::numeric_limits<Json::ArrayIndex>::max())
  743. {
  744. unsigned long lindex;
  745. if (!cmStrToULong(str, &lindex)) {
  746. throw json_error(cmStrCat("expected an array index, got: '"_s, str, "'"_s),
  747. progress);
  748. }
  749. Json::ArrayIndex index = static_cast<Json::ArrayIndex>(lindex);
  750. if (index >= max) {
  751. cmAlphaNum sizeStr{ max };
  752. throw json_error(cmStrCat("expected an index less than "_s, sizeStr.View(),
  753. " got '"_s, str, "'"_s),
  754. progress);
  755. }
  756. return index;
  757. }
  758. Json::Value& ResolvePath(Json::Value& json, Args path)
  759. {
  760. Json::Value* search = &json;
  761. for (auto curr = path.begin(); curr != path.end(); ++curr) {
  762. std::string const& field = *curr;
  763. Args progress{ path.begin(), curr + 1 };
  764. if (search->isArray()) {
  765. auto index = ParseIndex(field, progress, search->size());
  766. search = &(*search)[index];
  767. } else if (search->isObject()) {
  768. if (!search->isMember(field)) {
  769. auto const progressStr = cmJoin(progress, " "_s);
  770. throw json_error(cmStrCat("member '"_s, progressStr, "' not found"_s),
  771. progress);
  772. }
  773. search = &(*search)[field];
  774. } else {
  775. auto const progressStr = cmJoin(progress, " "_s);
  776. throw json_error(
  777. cmStrCat("invalid path '"_s, progressStr,
  778. "', need element of OBJECT or ARRAY type to lookup '"_s,
  779. field, "' got "_s, JsonTypeToString(search->type())),
  780. progress);
  781. }
  782. }
  783. return *search;
  784. }
  785. Json::Value ReadJson(std::string const& jsonstr)
  786. {
  787. Json::CharReaderBuilder builder;
  788. builder["collectComments"] = false;
  789. auto jsonReader = std::unique_ptr<Json::CharReader>(builder.newCharReader());
  790. Json::Value json;
  791. std::string error;
  792. if (!jsonReader->parse(jsonstr.data(), jsonstr.data() + jsonstr.size(),
  793. &json, &error)) {
  794. throw json_error(
  795. cmStrCat("failed parsing json string:\n"_s, jsonstr, '\n', error));
  796. }
  797. return json;
  798. }
  799. std::string WriteJson(Json::Value const& value)
  800. {
  801. Json::StreamWriterBuilder writer;
  802. writer["indentation"] = " ";
  803. writer["commentStyle"] = "None";
  804. return Json::writeString(writer, value);
  805. }
  806. #endif
  807. bool HandleJSONCommand(std::vector<std::string> const& arguments,
  808. cmExecutionStatus& status)
  809. {
  810. #if !defined(CMAKE_BOOTSTRAP)
  811. auto& makefile = status.GetMakefile();
  812. Args args{ arguments.begin() + 1, arguments.end() };
  813. std::string const* errorVariable = nullptr;
  814. std::string const* outputVariable = nullptr;
  815. bool success = true;
  816. try {
  817. outputVariable = &args.PopFront("missing out-var argument"_s);
  818. if (!args.empty() && *args.begin() == "ERROR_VARIABLE"_s) {
  819. args.PopFront("");
  820. errorVariable = &args.PopFront("missing error-var argument"_s);
  821. makefile.AddDefinition(*errorVariable, "NOTFOUND"_s);
  822. }
  823. auto const& mode = args.PopFront("missing mode argument"_s);
  824. if (mode != "GET"_s && mode != "TYPE"_s && mode != "MEMBER"_s &&
  825. mode != "LENGTH"_s && mode != "REMOVE"_s && mode != "SET"_s &&
  826. mode != "EQUAL"_s) {
  827. throw json_error(
  828. cmStrCat("got an invalid mode '"_s, mode,
  829. "', expected one of GET, TYPE, MEMBER, LENGTH, REMOVE, SET, "
  830. " EQUAL"_s));
  831. }
  832. auto const& jsonstr = args.PopFront("missing json string argument"_s);
  833. Json::Value json = ReadJson(jsonstr);
  834. if (mode == "GET"_s) {
  835. auto const& value = ResolvePath(json, args);
  836. if (value.isObject() || value.isArray()) {
  837. makefile.AddDefinition(*outputVariable, WriteJson(value));
  838. } else if (value.isBool()) {
  839. makefile.AddDefinitionBool(*outputVariable, value.asBool());
  840. } else {
  841. makefile.AddDefinition(*outputVariable, value.asString());
  842. }
  843. } else if (mode == "TYPE"_s) {
  844. auto const& value = ResolvePath(json, args);
  845. makefile.AddDefinition(*outputVariable, JsonTypeToString(value.type()));
  846. } else if (mode == "MEMBER"_s) {
  847. auto const& indexStr = args.PopBack("missing member index"_s);
  848. auto const& value = ResolvePath(json, args);
  849. if (!value.isObject()) {
  850. throw json_error(
  851. cmStrCat("MEMBER needs to be called with an element of "
  852. "type OBJECT, got "_s,
  853. JsonTypeToString(value.type())),
  854. args);
  855. }
  856. auto const index = ParseIndex(
  857. indexStr, Args{ args.begin(), args.end() + 1 }, value.size());
  858. auto const memIt = std::next(value.begin(), index);
  859. makefile.AddDefinition(*outputVariable, memIt.name());
  860. } else if (mode == "LENGTH"_s) {
  861. auto const& value = ResolvePath(json, args);
  862. if (!value.isArray() && !value.isObject()) {
  863. throw json_error(cmStrCat("LENGTH needs to be called with an "
  864. "element of type ARRAY or OBJECT, got "_s,
  865. JsonTypeToString(value.type())),
  866. args);
  867. }
  868. cmAlphaNum sizeStr{ value.size() };
  869. makefile.AddDefinition(*outputVariable, sizeStr.View());
  870. } else if (mode == "REMOVE"_s) {
  871. auto const& toRemove =
  872. args.PopBack("missing member or index to remove"_s);
  873. auto& value = ResolvePath(json, args);
  874. if (value.isArray()) {
  875. auto const index = ParseIndex(
  876. toRemove, Args{ args.begin(), args.end() + 1 }, value.size());
  877. Json::Value removed;
  878. value.removeIndex(index, &removed);
  879. } else if (value.isObject()) {
  880. Json::Value removed;
  881. value.removeMember(toRemove, &removed);
  882. } else {
  883. throw json_error(cmStrCat("REMOVE needs to be called with an "
  884. "element of type ARRAY or OBJECT, got "_s,
  885. JsonTypeToString(value.type())),
  886. args);
  887. }
  888. makefile.AddDefinition(*outputVariable, WriteJson(json));
  889. } else if (mode == "SET"_s) {
  890. auto const& newValueStr = args.PopBack("missing new value remove"_s);
  891. auto const& toAdd = args.PopBack("missing member name to add"_s);
  892. auto& value = ResolvePath(json, args);
  893. Json::Value newValue = ReadJson(newValueStr);
  894. if (value.isObject()) {
  895. value[toAdd] = newValue;
  896. } else if (value.isArray()) {
  897. auto const index =
  898. ParseIndex(toAdd, Args{ args.begin(), args.end() + 1 });
  899. if (value.isValidIndex(index)) {
  900. value[static_cast<int>(index)] = newValue;
  901. } else {
  902. value.append(newValue);
  903. }
  904. } else {
  905. throw json_error(cmStrCat("SET needs to be called with an "
  906. "element of type OBJECT or ARRAY, got "_s,
  907. JsonTypeToString(value.type())));
  908. }
  909. makefile.AddDefinition(*outputVariable, WriteJson(json));
  910. } else if (mode == "EQUAL"_s) {
  911. auto const& jsonstr2 =
  912. args.PopFront("missing second json string argument"_s);
  913. Json::Value json2 = ReadJson(jsonstr2);
  914. makefile.AddDefinitionBool(*outputVariable, json == json2);
  915. }
  916. } catch (json_error const& e) {
  917. if (outputVariable && e.ErrorPath) {
  918. auto const errorPath = cmJoin(*e.ErrorPath, "-");
  919. makefile.AddDefinition(*outputVariable,
  920. cmStrCat(errorPath, "-NOTFOUND"_s));
  921. } else if (outputVariable) {
  922. makefile.AddDefinition(*outputVariable, "NOTFOUND"_s);
  923. }
  924. if (errorVariable) {
  925. makefile.AddDefinition(*errorVariable, e.what());
  926. } else {
  927. status.SetError(cmStrCat("sub-command JSON "_s, e.what(), "."_s));
  928. success = false;
  929. }
  930. }
  931. return success;
  932. #else
  933. status.SetError(cmStrCat(arguments[0], " not available during bootstrap"_s));
  934. return false;
  935. #endif
  936. }
  937. } // namespace
  938. bool cmStringCommand(std::vector<std::string> const& args,
  939. cmExecutionStatus& status)
  940. {
  941. if (args.empty()) {
  942. status.SetError("must be called with at least one argument.");
  943. return false;
  944. }
  945. static cmSubcommandTable const subcommand{
  946. { "REGEX"_s, HandleRegexCommand },
  947. { "REPLACE"_s, HandleReplaceCommand },
  948. { "MD5"_s, HandleHashCommand },
  949. { "SHA1"_s, HandleHashCommand },
  950. { "SHA224"_s, HandleHashCommand },
  951. { "SHA256"_s, HandleHashCommand },
  952. { "SHA384"_s, HandleHashCommand },
  953. { "SHA512"_s, HandleHashCommand },
  954. { "SHA3_224"_s, HandleHashCommand },
  955. { "SHA3_256"_s, HandleHashCommand },
  956. { "SHA3_384"_s, HandleHashCommand },
  957. { "SHA3_512"_s, HandleHashCommand },
  958. { "TOLOWER"_s, HandleToLowerCommand },
  959. { "TOUPPER"_s, HandleToUpperCommand },
  960. { "COMPARE"_s, HandleCompareCommand },
  961. { "ASCII"_s, HandleAsciiCommand },
  962. { "HEX"_s, HandleHexCommand },
  963. { "CONFIGURE"_s, HandleConfigureCommand },
  964. { "LENGTH"_s, HandleLengthCommand },
  965. { "APPEND"_s, HandleAppendCommand },
  966. { "PREPEND"_s, HandlePrependCommand },
  967. { "CONCAT"_s, HandleConcatCommand },
  968. { "JOIN"_s, HandleJoinCommand },
  969. { "SUBSTRING"_s, HandleSubstringCommand },
  970. { "STRIP"_s, HandleStripCommand },
  971. { "REPEAT"_s, HandleRepeatCommand },
  972. { "RANDOM"_s, HandleRandomCommand },
  973. { "FIND"_s, HandleFindCommand },
  974. { "TIMESTAMP"_s, HandleTimestampCommand },
  975. { "MAKE_C_IDENTIFIER"_s, HandleMakeCIdentifierCommand },
  976. { "GENEX_STRIP"_s, HandleGenexStripCommand },
  977. { "UUID"_s, HandleUuidCommand },
  978. { "JSON"_s, HandleJSONCommand },
  979. };
  980. return subcommand(args[0], args, status);
  981. }