cmFileAPI.cxx 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file LICENSE.rst or https://cmake.org/licensing for details. */
  3. #include "cmFileAPI.h"
  4. #include <algorithm>
  5. #include <cassert>
  6. #include <chrono>
  7. #include <ctime>
  8. #include <iomanip>
  9. #include <iterator>
  10. #include <sstream>
  11. #include <utility>
  12. #include <cm/optional>
  13. #include <cmext/string_view>
  14. #include "cmsys/Directory.hxx"
  15. #include "cmsys/FStream.hxx"
  16. #include "cmCryptoHash.h"
  17. #include "cmFileAPICMakeFiles.h"
  18. #include "cmFileAPICache.h"
  19. #include "cmFileAPICodemodel.h"
  20. #include "cmFileAPIConfigureLog.h"
  21. #include "cmFileAPIToolchains.h"
  22. #include "cmGlobalGenerator.h"
  23. #include "cmStringAlgorithms.h"
  24. #include "cmSystemTools.h"
  25. #include "cmTimestamp.h"
  26. #include "cmake.h"
  27. #if defined(__clang__) && defined(__has_warning)
  28. # if __has_warning("-Wrange-loop-analysis")
  29. # if defined(__apple_build_version__)
  30. # if __apple_build_version__ < 13000000
  31. # define CM_CLANG_SUPPRESS_WARN_RANGE_LOOP_ANALYSIS
  32. # endif
  33. # else
  34. # if __clang_major__ < 11
  35. # define CM_CLANG_SUPPRESS_WARN_RANGE_LOOP_ANALYSIS
  36. # endif
  37. # endif
  38. # endif
  39. #endif
  40. cmFileAPI::cmFileAPI(cmake* cm)
  41. : CMakeInstance(cm)
  42. {
  43. this->APIv1 =
  44. cmStrCat(this->CMakeInstance->GetHomeOutputDirectory(), "/.cmake/api/v1");
  45. if (cm::optional<std::string> cmakeConfigDir =
  46. cmSystemTools::GetCMakeConfigDirectory()) {
  47. this->UserAPIv1 = cmStrCat(std::move(*cmakeConfigDir), "/api/v1"_s);
  48. }
  49. Json::CharReaderBuilder rbuilder;
  50. rbuilder["collectComments"] = false;
  51. rbuilder["failIfExtra"] = true;
  52. rbuilder["rejectDupKeys"] = false;
  53. rbuilder["strictRoot"] = true;
  54. this->JsonReader =
  55. std::unique_ptr<Json::CharReader>(rbuilder.newCharReader());
  56. Json::StreamWriterBuilder wbuilder;
  57. wbuilder["indentation"] = "\t";
  58. this->JsonWriter =
  59. std::unique_ptr<Json::StreamWriter>(wbuilder.newStreamWriter());
  60. }
  61. void cmFileAPI::ReadQueries()
  62. {
  63. std::string const query_dir = cmStrCat(this->APIv1, "/query");
  64. std::string const user_query_dir = cmStrCat(this->UserAPIv1, "/query");
  65. this->QueryExists =
  66. this->QueryExists || cmSystemTools::FileIsDirectory(query_dir);
  67. if (!this->UserAPIv1.empty()) {
  68. this->QueryExists =
  69. this->QueryExists || cmSystemTools::FileIsDirectory(user_query_dir);
  70. }
  71. if (!this->QueryExists) {
  72. return;
  73. }
  74. // Load queries at the top level.
  75. std::vector<std::string> queries = cmFileAPI::LoadDir(query_dir);
  76. if (!this->UserAPIv1.empty()) {
  77. std::vector<std::string> user_queries = cmFileAPI::LoadDir(user_query_dir);
  78. std::move(user_queries.begin(), user_queries.end(),
  79. std::back_inserter(queries));
  80. }
  81. // Read the queries and save for later.
  82. for (std::string& query : queries) {
  83. if (cmHasLiteralPrefix(query, "client-")) {
  84. this->ReadClient(query);
  85. } else if (!cmFileAPI::ReadQuery(query, this->TopQuery.Known)) {
  86. this->TopQuery.Unknown.push_back(std::move(query));
  87. }
  88. }
  89. }
  90. std::vector<unsigned int> cmFileAPI::GetConfigureLogVersions()
  91. {
  92. std::vector<unsigned int> versions;
  93. auto getConfigureLogVersions = [&versions](Query const& q) {
  94. #ifdef CM_CLANG_SUPPRESS_WARN_RANGE_LOOP_ANALYSIS
  95. # pragma clang diagnostic push
  96. # pragma clang diagnostic ignored "-Wrange-loop-analysis"
  97. #endif
  98. for (Object const o : q.Known) {
  99. #ifdef CM_CLANG_SUPPRESS_WARN_RANGE_LOOP_ANALYSIS
  100. # pragma clang diagnostic pop
  101. #endif
  102. if (o.Kind == ObjectKind::ConfigureLog) {
  103. versions.emplace_back(o.Version);
  104. }
  105. }
  106. };
  107. getConfigureLogVersions(this->TopQuery);
  108. for (auto const& client : this->ClientQueries) {
  109. getConfigureLogVersions(client.second.DirQuery);
  110. }
  111. std::sort(versions.begin(), versions.end());
  112. versions.erase(std::unique(versions.begin(), versions.end()),
  113. versions.end());
  114. return versions;
  115. }
  116. void cmFileAPI::WriteReplies(IndexFor indexFor)
  117. {
  118. bool const success = indexFor == IndexFor::Success;
  119. this->ReplyIndexFor = indexFor;
  120. if (this->QueryExists) {
  121. cmSystemTools::MakeDirectory(this->APIv1 + "/reply");
  122. this->WriteJsonFile(this->BuildReplyIndex(), success ? "index" : "error",
  123. ComputeSuffixTime);
  124. }
  125. if (success) {
  126. this->RemoveOldReplyFiles();
  127. }
  128. }
  129. std::vector<std::string> cmFileAPI::LoadDir(std::string const& dir)
  130. {
  131. std::vector<std::string> files;
  132. cmsys::Directory d;
  133. d.Load(dir);
  134. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i) {
  135. std::string f = d.GetFile(i);
  136. if (f != "." && f != "..") {
  137. files.push_back(std::move(f));
  138. }
  139. }
  140. std::sort(files.begin(), files.end());
  141. return files;
  142. }
  143. void cmFileAPI::RemoveOldReplyFiles()
  144. {
  145. std::string const reply_dir = this->APIv1 + "/reply";
  146. std::vector<std::string> files = this->LoadDir(reply_dir);
  147. for (std::string const& f : files) {
  148. if (this->ReplyFiles.find(f) == this->ReplyFiles.end()) {
  149. std::string file = cmStrCat(reply_dir, '/', f);
  150. cmSystemTools::RemoveFile(file);
  151. }
  152. }
  153. }
  154. bool cmFileAPI::ReadJsonFile(std::string const& file, Json::Value& value,
  155. std::string& error)
  156. {
  157. std::vector<char> content;
  158. cmsys::ifstream fin;
  159. if (!cmSystemTools::FileIsDirectory(file)) {
  160. fin.open(file.c_str(), std::ios::binary);
  161. }
  162. auto finEnd = fin.rdbuf()->pubseekoff(0, std::ios::end);
  163. if (finEnd > 0) {
  164. size_t finSize = finEnd;
  165. try {
  166. // Allocate a buffer to read the whole file.
  167. content.resize(finSize);
  168. // Now read the file from the beginning.
  169. fin.seekg(0, std::ios::beg);
  170. fin.read(content.data(), finSize);
  171. } catch (...) {
  172. fin.setstate(std::ios::failbit);
  173. }
  174. }
  175. fin.close();
  176. if (!fin) {
  177. value = Json::Value();
  178. error = "failed to read from file";
  179. return false;
  180. }
  181. // Parse our buffer as json.
  182. if (!this->JsonReader->parse(content.data(), content.data() + content.size(),
  183. &value, &error)) {
  184. value = Json::Value();
  185. return false;
  186. }
  187. return true;
  188. }
  189. std::string cmFileAPI::WriteJsonFile(
  190. Json::Value const& value, std::string const& prefix,
  191. std::string (*computeSuffix)(std::string const&))
  192. {
  193. std::string fileName;
  194. // Write the json file with a temporary name.
  195. std::string const& tmpFile = this->APIv1 + "/tmp.json";
  196. cmsys::ofstream ftmp(tmpFile.c_str());
  197. this->JsonWriter->write(value, &ftmp);
  198. ftmp << "\n";
  199. ftmp.close();
  200. if (!ftmp) {
  201. cmSystemTools::RemoveFile(tmpFile);
  202. return fileName;
  203. }
  204. // Compute the final name for the file.
  205. std::string suffix = computeSuffix(tmpFile);
  206. std::string suffixWithExtension = cmStrCat('-', suffix, ".json");
  207. fileName = cmStrCat(prefix, suffixWithExtension);
  208. // Truncate the file name length
  209. // eCryptFS has a maximal file name length recommendation of 140
  210. size_t const maxFileNameLength = 140;
  211. size_t const fileNameLength = fileName.size();
  212. if (fileNameLength > maxFileNameLength) {
  213. size_t const newHashLength = 20;
  214. size_t const newSuffixLength =
  215. suffixWithExtension.size() - suffix.size() + newHashLength;
  216. size_t const overLength =
  217. fileNameLength - maxFileNameLength + newSuffixLength;
  218. size_t const startPos = fileNameLength - overLength;
  219. std::string const toBeRemoved = fileName.substr(startPos, overLength);
  220. suffix = cmCryptoHash(cmCryptoHash::AlgoSHA256)
  221. .HashString(toBeRemoved)
  222. .substr(0, newHashLength);
  223. suffixWithExtension = cmStrCat('-', suffix, ".json");
  224. fileName.replace(startPos, overLength, suffixWithExtension);
  225. }
  226. // Create the destination.
  227. std::string file = this->APIv1 + "/reply";
  228. cmSystemTools::MakeDirectory(file);
  229. file += "/";
  230. file += fileName;
  231. // If the final name already exists then assume it has proper content.
  232. // Otherwise, atomically place the reply file at its final name
  233. if (cmSystemTools::FileExists(file, true) ||
  234. !cmSystemTools::RenameFile(tmpFile, file)) {
  235. cmSystemTools::RemoveFile(tmpFile);
  236. }
  237. // Record this among files we have just written.
  238. this->ReplyFiles.insert(fileName);
  239. return fileName;
  240. }
  241. Json::Value cmFileAPI::MaybeJsonFile(Json::Value in, std::string const& prefix)
  242. {
  243. Json::Value out;
  244. if (in.isObject() || in.isArray()) {
  245. out = Json::objectValue;
  246. out["jsonFile"] = this->WriteJsonFile(in, prefix);
  247. } else {
  248. out = std::move(in);
  249. }
  250. return out;
  251. }
  252. std::string cmFileAPI::ComputeSuffixHash(std::string const& file)
  253. {
  254. cmCryptoHash hasher(cmCryptoHash::AlgoSHA3_256);
  255. std::string hash = hasher.HashFile(file);
  256. hash.resize(20, '0');
  257. return hash;
  258. }
  259. std::string cmFileAPI::ComputeSuffixTime(std::string const&)
  260. {
  261. std::chrono::milliseconds ms =
  262. std::chrono::duration_cast<std::chrono::milliseconds>(
  263. std::chrono::system_clock::now().time_since_epoch());
  264. std::chrono::seconds s =
  265. std::chrono::duration_cast<std::chrono::seconds>(ms);
  266. std::time_t ts = s.count();
  267. std::size_t tms = ms.count() % 1000;
  268. cmTimestamp cmts;
  269. std::ostringstream ss;
  270. ss << cmts.CreateTimestampFromTimeT(ts, "%Y-%m-%dT%H-%M-%S", true) << '-'
  271. << std::setfill('0') << std::setw(4) << tms;
  272. return ss.str();
  273. }
  274. bool cmFileAPI::ReadQuery(std::string const& query,
  275. std::vector<Object>& objects)
  276. {
  277. // Parse the "<kind>-" syntax.
  278. std::string::size_type sep_pos = query.find('-');
  279. if (sep_pos == std::string::npos) {
  280. return false;
  281. }
  282. std::string kindName = query.substr(0, sep_pos);
  283. std::string verStr = query.substr(sep_pos + 1);
  284. if (kindName == ObjectKindName(ObjectKind::CodeModel)) {
  285. Object o;
  286. o.Kind = ObjectKind::CodeModel;
  287. if (verStr == "v2") {
  288. o.Version = 2;
  289. } else {
  290. return false;
  291. }
  292. objects.push_back(o);
  293. return true;
  294. }
  295. if (kindName == ObjectKindName(ObjectKind::ConfigureLog)) {
  296. Object o;
  297. o.Kind = ObjectKind::ConfigureLog;
  298. if (verStr == "v1") {
  299. o.Version = 1;
  300. } else {
  301. return false;
  302. }
  303. objects.push_back(o);
  304. return true;
  305. }
  306. if (kindName == ObjectKindName(ObjectKind::Cache)) {
  307. Object o;
  308. o.Kind = ObjectKind::Cache;
  309. if (verStr == "v2") {
  310. o.Version = 2;
  311. } else {
  312. return false;
  313. }
  314. objects.push_back(o);
  315. return true;
  316. }
  317. if (kindName == ObjectKindName(ObjectKind::CMakeFiles)) {
  318. Object o;
  319. o.Kind = ObjectKind::CMakeFiles;
  320. if (verStr == "v1") {
  321. o.Version = 1;
  322. } else {
  323. return false;
  324. }
  325. objects.push_back(o);
  326. return true;
  327. }
  328. if (kindName == ObjectKindName(ObjectKind::Toolchains)) {
  329. Object o;
  330. o.Kind = ObjectKind::Toolchains;
  331. if (verStr == "v1") {
  332. o.Version = 1;
  333. } else {
  334. return false;
  335. }
  336. objects.push_back(o);
  337. return true;
  338. }
  339. if (kindName == ObjectKindName(ObjectKind::InternalTest)) {
  340. Object o;
  341. o.Kind = ObjectKind::InternalTest;
  342. if (verStr == "v1") {
  343. o.Version = 1;
  344. } else if (verStr == "v2") {
  345. o.Version = 2;
  346. } else {
  347. return false;
  348. }
  349. objects.push_back(o);
  350. return true;
  351. }
  352. return false;
  353. }
  354. void cmFileAPI::ReadClient(std::string const& client)
  355. {
  356. // Load queries for the client.
  357. std::string clientDir = this->APIv1 + "/query/" + client;
  358. std::vector<std::string> queries = this->LoadDir(clientDir);
  359. // Read the queries and save for later.
  360. ClientQuery& clientQuery = this->ClientQueries[client];
  361. for (std::string& query : queries) {
  362. if (query == "query.json") {
  363. clientQuery.HaveQueryJson = true;
  364. this->ReadClientQuery(client, clientQuery.QueryJson);
  365. } else if (!this->ReadQuery(query, clientQuery.DirQuery.Known)) {
  366. clientQuery.DirQuery.Unknown.push_back(std::move(query));
  367. }
  368. }
  369. }
  370. void cmFileAPI::ReadClientQuery(std::string const& client, ClientQueryJson& q)
  371. {
  372. // Read the query.json file.
  373. std::string queryFile = this->APIv1 + "/query/" + client + "/query.json";
  374. Json::Value query;
  375. if (!this->ReadJsonFile(queryFile, query, q.Error)) {
  376. return;
  377. }
  378. if (!query.isObject()) {
  379. q.Error = "query root is not an object";
  380. return;
  381. }
  382. Json::Value const& clientValue = query["client"];
  383. if (!clientValue.isNull()) {
  384. q.ClientValue = clientValue;
  385. }
  386. q.RequestsValue = std::move(query["requests"]);
  387. q.Requests = this->BuildClientRequests(q.RequestsValue);
  388. }
  389. Json::Value cmFileAPI::BuildReplyIndex()
  390. {
  391. Json::Value index(Json::objectValue);
  392. // Report information about this version of CMake.
  393. index["cmake"] = this->BuildCMake();
  394. // Reply to all queries that we loaded.
  395. Json::Value& reply = index["reply"] = this->BuildReply(this->TopQuery);
  396. for (auto const& client : this->ClientQueries) {
  397. std::string const& clientName = client.first;
  398. ClientQuery const& clientQuery = client.second;
  399. reply[clientName] = this->BuildClientReply(clientQuery);
  400. }
  401. // Move our index of generated objects into its field.
  402. Json::Value& objects = index["objects"] = Json::arrayValue;
  403. for (auto& entry : this->ReplyIndexObjects) {
  404. objects.append(std::move(entry.second)); // NOLINT(*)
  405. }
  406. return index;
  407. }
  408. Json::Value cmFileAPI::BuildCMake()
  409. {
  410. Json::Value cmake = Json::objectValue;
  411. cmake["version"] = this->CMakeInstance->ReportVersionJson();
  412. Json::Value& cmake_paths = cmake["paths"] = Json::objectValue;
  413. cmake_paths["cmake"] = cmSystemTools::GetCMakeCommand();
  414. cmake_paths["ctest"] = cmSystemTools::GetCTestCommand();
  415. cmake_paths["cpack"] = cmSystemTools::GetCPackCommand();
  416. cmake_paths["root"] = cmSystemTools::GetCMakeRoot();
  417. cmake["generator"] = this->CMakeInstance->GetGlobalGenerator()->GetJson();
  418. return cmake;
  419. }
  420. Json::Value cmFileAPI::BuildReply(Query const& q)
  421. {
  422. Json::Value reply = Json::objectValue;
  423. #ifdef CM_CLANG_SUPPRESS_WARN_RANGE_LOOP_ANALYSIS
  424. # pragma clang diagnostic push
  425. # pragma clang diagnostic ignored "-Wrange-loop-analysis"
  426. #endif
  427. for (Object const o : q.Known) {
  428. #ifdef CM_CLANG_SUPPRESS_WARN_RANGE_LOOP_ANALYSIS
  429. # pragma clang diagnostic pop
  430. #endif
  431. std::string const& name = ObjectName(o);
  432. reply[name] = this->BuildReplyEntry(o);
  433. }
  434. for (std::string const& name : q.Unknown) {
  435. reply[name] = cmFileAPI::BuildReplyError("unknown query file");
  436. }
  437. return reply;
  438. }
  439. Json::Value cmFileAPI::BuildReplyEntry(Object object)
  440. {
  441. if (this->ReplyIndexFor != IndexFor::Success) {
  442. switch (object.Kind) {
  443. case ObjectKind::ConfigureLog:
  444. break;
  445. case ObjectKind::CodeModel:
  446. case ObjectKind::Cache:
  447. case ObjectKind::CMakeFiles:
  448. case ObjectKind::Toolchains:
  449. case ObjectKind::InternalTest:
  450. return this->BuildReplyError("no buildsystem generated");
  451. }
  452. }
  453. return this->AddReplyIndexObject(object);
  454. }
  455. Json::Value cmFileAPI::BuildReplyError(std::string const& error)
  456. {
  457. Json::Value e = Json::objectValue;
  458. e["error"] = error;
  459. return e;
  460. }
  461. Json::Value const& cmFileAPI::AddReplyIndexObject(Object o)
  462. {
  463. Json::Value& indexEntry = this->ReplyIndexObjects[o];
  464. if (!indexEntry.isNull()) {
  465. // The reply object has already been generated.
  466. return indexEntry;
  467. }
  468. // Generate this reply object.
  469. Json::Value const& object = this->BuildObject(o);
  470. assert(object.isObject());
  471. // Populate this index entry.
  472. indexEntry = Json::objectValue;
  473. indexEntry["kind"] = object["kind"];
  474. indexEntry["version"] = object["version"];
  475. indexEntry["jsonFile"] = this->WriteJsonFile(object, ObjectName(o));
  476. return indexEntry;
  477. }
  478. char const* cmFileAPI::ObjectKindName(ObjectKind kind)
  479. {
  480. // Keep in sync with ObjectKind enum.
  481. static char const* objectKindNames[] = {
  482. "codemodel", //
  483. "configureLog", //
  484. "cache", //
  485. "cmakeFiles", //
  486. "toolchains", //
  487. "__test" //
  488. };
  489. return objectKindNames[static_cast<size_t>(kind)];
  490. }
  491. std::string cmFileAPI::ObjectName(Object o)
  492. {
  493. std::string name = cmStrCat(ObjectKindName(o.Kind), "-v", o.Version);
  494. return name;
  495. }
  496. Json::Value cmFileAPI::BuildVersion(unsigned int major, unsigned int minor)
  497. {
  498. Json::Value version;
  499. version["major"] = major;
  500. version["minor"] = minor;
  501. return version;
  502. }
  503. Json::Value cmFileAPI::BuildObject(Object object)
  504. {
  505. Json::Value value;
  506. switch (object.Kind) {
  507. case ObjectKind::CodeModel:
  508. value = this->BuildCodeModel(object);
  509. break;
  510. case ObjectKind::ConfigureLog:
  511. value = this->BuildConfigureLog(object);
  512. break;
  513. case ObjectKind::Cache:
  514. value = this->BuildCache(object);
  515. break;
  516. case ObjectKind::CMakeFiles:
  517. value = this->BuildCMakeFiles(object);
  518. break;
  519. case ObjectKind::Toolchains:
  520. value = this->BuildToolchains(object);
  521. break;
  522. case ObjectKind::InternalTest:
  523. value = this->BuildInternalTest(object);
  524. break;
  525. }
  526. return value;
  527. }
  528. cmFileAPI::ClientRequests cmFileAPI::BuildClientRequests(
  529. Json::Value const& requests)
  530. {
  531. ClientRequests result;
  532. if (requests.isNull()) {
  533. result.Error = "'requests' member missing";
  534. return result;
  535. }
  536. if (!requests.isArray()) {
  537. result.Error = "'requests' member is not an array";
  538. return result;
  539. }
  540. result.reserve(requests.size());
  541. for (Json::Value const& request : requests) {
  542. result.emplace_back(this->BuildClientRequest(request));
  543. }
  544. return result;
  545. }
  546. cmFileAPI::ClientRequest cmFileAPI::BuildClientRequest(
  547. Json::Value const& request)
  548. {
  549. ClientRequest r;
  550. if (!request.isObject()) {
  551. r.Error = "request is not an object";
  552. return r;
  553. }
  554. Json::Value const& kind = request["kind"];
  555. if (kind.isNull()) {
  556. r.Error = "'kind' member missing";
  557. return r;
  558. }
  559. if (!kind.isString()) {
  560. r.Error = "'kind' member is not a string";
  561. return r;
  562. }
  563. std::string const& kindName = kind.asString();
  564. if (kindName == this->ObjectKindName(ObjectKind::CodeModel)) {
  565. r.Kind = ObjectKind::CodeModel;
  566. } else if (kindName == this->ObjectKindName(ObjectKind::ConfigureLog)) {
  567. r.Kind = ObjectKind::ConfigureLog;
  568. } else if (kindName == this->ObjectKindName(ObjectKind::Cache)) {
  569. r.Kind = ObjectKind::Cache;
  570. } else if (kindName == this->ObjectKindName(ObjectKind::CMakeFiles)) {
  571. r.Kind = ObjectKind::CMakeFiles;
  572. } else if (kindName == this->ObjectKindName(ObjectKind::Toolchains)) {
  573. r.Kind = ObjectKind::Toolchains;
  574. } else if (kindName == this->ObjectKindName(ObjectKind::InternalTest)) {
  575. r.Kind = ObjectKind::InternalTest;
  576. } else {
  577. r.Error = "unknown request kind '" + kindName + "'";
  578. return r;
  579. }
  580. Json::Value const& version = request["version"];
  581. if (version.isNull()) {
  582. r.Error = "'version' member missing";
  583. return r;
  584. }
  585. std::vector<RequestVersion> versions;
  586. if (!cmFileAPI::ReadRequestVersions(version, versions, r.Error)) {
  587. return r;
  588. }
  589. switch (r.Kind) {
  590. case ObjectKind::CodeModel:
  591. this->BuildClientRequestCodeModel(r, versions);
  592. break;
  593. case ObjectKind::ConfigureLog:
  594. this->BuildClientRequestConfigureLog(r, versions);
  595. break;
  596. case ObjectKind::Cache:
  597. this->BuildClientRequestCache(r, versions);
  598. break;
  599. case ObjectKind::CMakeFiles:
  600. this->BuildClientRequestCMakeFiles(r, versions);
  601. break;
  602. case ObjectKind::Toolchains:
  603. this->BuildClientRequestToolchains(r, versions);
  604. break;
  605. case ObjectKind::InternalTest:
  606. this->BuildClientRequestInternalTest(r, versions);
  607. break;
  608. }
  609. return r;
  610. }
  611. Json::Value cmFileAPI::BuildClientReply(ClientQuery const& q)
  612. {
  613. Json::Value reply = this->BuildReply(q.DirQuery);
  614. if (!q.HaveQueryJson) {
  615. return reply;
  616. }
  617. Json::Value& reply_query_json = reply["query.json"];
  618. ClientQueryJson const& qj = q.QueryJson;
  619. if (!qj.Error.empty()) {
  620. reply_query_json = this->BuildReplyError(qj.Error);
  621. return reply;
  622. }
  623. if (!qj.ClientValue.isNull()) {
  624. reply_query_json["client"] = qj.ClientValue;
  625. }
  626. if (!qj.RequestsValue.isNull()) {
  627. reply_query_json["requests"] = qj.RequestsValue;
  628. }
  629. reply_query_json["responses"] = this->BuildClientReplyResponses(qj.Requests);
  630. return reply;
  631. }
  632. Json::Value cmFileAPI::BuildClientReplyResponses(
  633. ClientRequests const& requests)
  634. {
  635. Json::Value responses;
  636. if (!requests.Error.empty()) {
  637. responses = this->BuildReplyError(requests.Error);
  638. return responses;
  639. }
  640. responses = Json::arrayValue;
  641. for (ClientRequest const& request : requests) {
  642. responses.append(this->BuildClientReplyResponse(request));
  643. }
  644. return responses;
  645. }
  646. Json::Value cmFileAPI::BuildClientReplyResponse(ClientRequest const& request)
  647. {
  648. Json::Value response;
  649. if (!request.Error.empty()) {
  650. response = this->BuildReplyError(request.Error);
  651. return response;
  652. }
  653. response = this->BuildReplyEntry(request);
  654. return response;
  655. }
  656. bool cmFileAPI::ReadRequestVersions(Json::Value const& version,
  657. std::vector<RequestVersion>& versions,
  658. std::string& error)
  659. {
  660. if (version.isArray()) {
  661. for (Json::Value const& v : version) {
  662. if (!ReadRequestVersion(v, /*inArray=*/true, versions, error)) {
  663. return false;
  664. }
  665. }
  666. } else {
  667. if (!ReadRequestVersion(version, /*inArray=*/false, versions, error)) {
  668. return false;
  669. }
  670. }
  671. return true;
  672. }
  673. bool cmFileAPI::ReadRequestVersion(Json::Value const& version, bool inArray,
  674. std::vector<RequestVersion>& result,
  675. std::string& error)
  676. {
  677. if (version.isUInt()) {
  678. RequestVersion v;
  679. v.Major = version.asUInt();
  680. result.push_back(v);
  681. return true;
  682. }
  683. if (!version.isObject()) {
  684. if (inArray) {
  685. error = "'version' array entry is not a non-negative integer or object";
  686. } else {
  687. error =
  688. "'version' member is not a non-negative integer, object, or array";
  689. }
  690. return false;
  691. }
  692. Json::Value const& major = version["major"];
  693. if (major.isNull()) {
  694. error = "'version' object 'major' member missing";
  695. return false;
  696. }
  697. if (!major.isUInt()) {
  698. error = "'version' object 'major' member is not a non-negative integer";
  699. return false;
  700. }
  701. RequestVersion v;
  702. v.Major = major.asUInt();
  703. Json::Value const& minor = version["minor"];
  704. if (minor.isUInt()) {
  705. v.Minor = minor.asUInt();
  706. } else if (!minor.isNull()) {
  707. error = "'version' object 'minor' member is not a non-negative integer";
  708. return false;
  709. }
  710. result.push_back(v);
  711. return true;
  712. }
  713. std::string cmFileAPI::NoSupportedVersion(
  714. std::vector<RequestVersion> const& versions)
  715. {
  716. std::ostringstream msg;
  717. msg << "no supported version specified";
  718. if (!versions.empty()) {
  719. msg << " among:";
  720. for (RequestVersion const& v : versions) {
  721. msg << " " << v.Major << "." << v.Minor;
  722. }
  723. }
  724. return msg.str();
  725. }
  726. // The "codemodel" object kind.
  727. // Update the following files as well when updating this constant:
  728. // Help/manual/cmake-file-api.7.rst
  729. // Tests/RunCMake/FileAPI/codemodel-v2-check.py (check_objects())
  730. static unsigned int const CodeModelV2Minor = 9;
  731. void cmFileAPI::BuildClientRequestCodeModel(
  732. ClientRequest& r, std::vector<RequestVersion> const& versions)
  733. {
  734. // Select a known version from those requested.
  735. for (RequestVersion const& v : versions) {
  736. if ((v.Major == 2 && v.Minor <= CodeModelV2Minor)) {
  737. r.Version = v.Major;
  738. break;
  739. }
  740. }
  741. if (!r.Version) {
  742. r.Error = NoSupportedVersion(versions);
  743. }
  744. }
  745. Json::Value cmFileAPI::BuildCodeModel(Object object)
  746. {
  747. assert(object.Version == 2);
  748. Json::Value codemodel =
  749. cmFileAPICodemodelDump(*this, object.Version, CodeModelV2Minor);
  750. codemodel["kind"] = this->ObjectKindName(object.Kind);
  751. Json::Value& version = codemodel["version"];
  752. if (object.Version == 2) {
  753. version = BuildVersion(2, CodeModelV2Minor);
  754. } else {
  755. return codemodel; // should be unreachable
  756. }
  757. return codemodel;
  758. }
  759. // The "configureLog" object kind.
  760. // Update Help/manual/cmake-file-api.7.rst when updating this constant.
  761. static unsigned int const ConfigureLogV1Minor = 0;
  762. void cmFileAPI::BuildClientRequestConfigureLog(
  763. ClientRequest& r, std::vector<RequestVersion> const& versions)
  764. {
  765. // Select a known version from those requested.
  766. for (RequestVersion const& v : versions) {
  767. if ((v.Major == 1 && v.Minor <= ConfigureLogV1Minor)) {
  768. r.Version = v.Major;
  769. break;
  770. }
  771. }
  772. if (!r.Version) {
  773. r.Error = NoSupportedVersion(versions);
  774. }
  775. }
  776. Json::Value cmFileAPI::BuildConfigureLog(Object object)
  777. {
  778. Json::Value configureLog = cmFileAPIConfigureLogDump(*this, object.Version);
  779. configureLog["kind"] = this->ObjectKindName(object.Kind);
  780. Json::Value& version = configureLog["version"];
  781. if (object.Version == 1) {
  782. version = BuildVersion(1, ConfigureLogV1Minor);
  783. } else {
  784. return configureLog; // should be unreachable
  785. }
  786. return configureLog;
  787. }
  788. // The "cache" object kind.
  789. static unsigned int const CacheV2Minor = 0;
  790. void cmFileAPI::BuildClientRequestCache(
  791. ClientRequest& r, std::vector<RequestVersion> const& versions)
  792. {
  793. // Select a known version from those requested.
  794. for (RequestVersion const& v : versions) {
  795. if ((v.Major == 2 && v.Minor <= CacheV2Minor)) {
  796. r.Version = v.Major;
  797. break;
  798. }
  799. }
  800. if (!r.Version) {
  801. r.Error = NoSupportedVersion(versions);
  802. }
  803. }
  804. Json::Value cmFileAPI::BuildCache(Object object)
  805. {
  806. Json::Value cache = cmFileAPICacheDump(*this, object.Version);
  807. cache["kind"] = this->ObjectKindName(object.Kind);
  808. Json::Value& version = cache["version"];
  809. if (object.Version == 2) {
  810. version = BuildVersion(2, CacheV2Minor);
  811. } else {
  812. return cache; // should be unreachable
  813. }
  814. return cache;
  815. }
  816. // The "cmakeFiles" object kind.
  817. static unsigned int const CMakeFilesV1Minor = 1;
  818. void cmFileAPI::BuildClientRequestCMakeFiles(
  819. ClientRequest& r, std::vector<RequestVersion> const& versions)
  820. {
  821. // Select a known version from those requested.
  822. for (RequestVersion const& v : versions) {
  823. if ((v.Major == 1 && v.Minor <= CMakeFilesV1Minor)) {
  824. r.Version = v.Major;
  825. break;
  826. }
  827. }
  828. if (!r.Version) {
  829. r.Error = NoSupportedVersion(versions);
  830. }
  831. }
  832. Json::Value cmFileAPI::BuildCMakeFiles(Object object)
  833. {
  834. Json::Value cmakeFiles = cmFileAPICMakeFilesDump(*this, object.Version);
  835. cmakeFiles["kind"] = this->ObjectKindName(object.Kind);
  836. Json::Value& version = cmakeFiles["version"];
  837. if (object.Version == 1) {
  838. version = BuildVersion(1, CMakeFilesV1Minor);
  839. } else {
  840. return cmakeFiles; // should be unreachable
  841. }
  842. return cmakeFiles;
  843. }
  844. // The "toolchains" object kind.
  845. static unsigned int const ToolchainsV1Minor = 0;
  846. void cmFileAPI::BuildClientRequestToolchains(
  847. ClientRequest& r, std::vector<RequestVersion> const& versions)
  848. {
  849. // Select a known version from those requested.
  850. for (RequestVersion const& v : versions) {
  851. if ((v.Major == 1 && v.Minor <= ToolchainsV1Minor)) {
  852. r.Version = v.Major;
  853. break;
  854. }
  855. }
  856. if (!r.Version) {
  857. r.Error = NoSupportedVersion(versions);
  858. }
  859. }
  860. Json::Value cmFileAPI::BuildToolchains(Object object)
  861. {
  862. Json::Value toolchains = cmFileAPIToolchainsDump(*this, object.Version);
  863. toolchains["kind"] = this->ObjectKindName(object.Kind);
  864. Json::Value& version = toolchains["version"];
  865. if (object.Version == 1) {
  866. version = BuildVersion(1, ToolchainsV1Minor);
  867. } else {
  868. return toolchains; // should be unreachable
  869. }
  870. return toolchains;
  871. }
  872. // The "__test" object kind is for internal testing of CMake.
  873. static unsigned int const InternalTestV1Minor = 3;
  874. static unsigned int const InternalTestV2Minor = 0;
  875. void cmFileAPI::BuildClientRequestInternalTest(
  876. ClientRequest& r, std::vector<RequestVersion> const& versions)
  877. {
  878. // Select a known version from those requested.
  879. for (RequestVersion const& v : versions) {
  880. if ((v.Major == 1 && v.Minor <= InternalTestV1Minor) || //
  881. (v.Major == 2 && v.Minor <= InternalTestV2Minor)) {
  882. r.Version = v.Major;
  883. break;
  884. }
  885. }
  886. if (!r.Version) {
  887. r.Error = NoSupportedVersion(versions);
  888. }
  889. }
  890. Json::Value cmFileAPI::BuildInternalTest(Object object)
  891. {
  892. Json::Value test = Json::objectValue;
  893. test["kind"] = this->ObjectKindName(object.Kind);
  894. Json::Value& version = test["version"];
  895. if (object.Version == 2) {
  896. version = BuildVersion(2, InternalTestV2Minor);
  897. } else {
  898. version = BuildVersion(1, InternalTestV1Minor);
  899. }
  900. return test;
  901. }
  902. Json::Value cmFileAPI::ReportCapabilities()
  903. {
  904. Json::Value capabilities = Json::objectValue;
  905. Json::Value& requests = capabilities["requests"] = Json::arrayValue;
  906. {
  907. Json::Value request = Json::objectValue;
  908. request["kind"] = ObjectKindName(ObjectKind::CodeModel);
  909. Json::Value& versions = request["version"] = Json::arrayValue;
  910. versions.append(BuildVersion(2, CodeModelV2Minor));
  911. requests.append(std::move(request)); // NOLINT(*)
  912. }
  913. {
  914. Json::Value request = Json::objectValue;
  915. request["kind"] = ObjectKindName(ObjectKind::ConfigureLog);
  916. Json::Value& versions = request["version"] = Json::arrayValue;
  917. versions.append(BuildVersion(1, ConfigureLogV1Minor));
  918. requests.append(std::move(request)); // NOLINT(*)
  919. }
  920. {
  921. Json::Value request = Json::objectValue;
  922. request["kind"] = ObjectKindName(ObjectKind::Cache);
  923. Json::Value& versions = request["version"] = Json::arrayValue;
  924. versions.append(BuildVersion(2, CacheV2Minor));
  925. requests.append(std::move(request)); // NOLINT(*)
  926. }
  927. {
  928. Json::Value request = Json::objectValue;
  929. request["kind"] = ObjectKindName(ObjectKind::CMakeFiles);
  930. Json::Value& versions = request["version"] = Json::arrayValue;
  931. versions.append(BuildVersion(1, CMakeFilesV1Minor));
  932. requests.append(std::move(request)); // NOLINT(*)
  933. }
  934. {
  935. Json::Value request = Json::objectValue;
  936. request["kind"] = ObjectKindName(ObjectKind::Toolchains);
  937. Json::Value& versions = request["version"] = Json::arrayValue;
  938. versions.append(BuildVersion(1, ToolchainsV1Minor));
  939. requests.append(std::move(request)); // NOLINT(*)
  940. }
  941. return capabilities;
  942. }
  943. bool cmFileAPI::AddProjectQuery(cmFileAPI::ObjectKind kind,
  944. unsigned majorVersion, unsigned minorVersion)
  945. {
  946. switch (kind) {
  947. case ObjectKind::CodeModel:
  948. if (majorVersion != 2 || minorVersion > CodeModelV2Minor) {
  949. return false;
  950. }
  951. break;
  952. case ObjectKind::Cache:
  953. if (majorVersion != 2 || minorVersion > CacheV2Minor) {
  954. return false;
  955. }
  956. break;
  957. case ObjectKind::CMakeFiles:
  958. if (majorVersion != 1 || minorVersion > CMakeFilesV1Minor) {
  959. return false;
  960. }
  961. break;
  962. case ObjectKind::Toolchains:
  963. if (majorVersion != 1 || minorVersion > ToolchainsV1Minor) {
  964. return false;
  965. }
  966. break;
  967. // These cannot be requested by the project
  968. case ObjectKind::ConfigureLog:
  969. case ObjectKind::InternalTest:
  970. return false;
  971. }
  972. Object query;
  973. query.Kind = kind;
  974. query.Version = majorVersion;
  975. if (std::find(this->TopQuery.Known.begin(), this->TopQuery.Known.end(),
  976. query) == this->TopQuery.Known.end()) {
  977. this->TopQuery.Known.emplace_back(query);
  978. this->QueryExists = true;
  979. }
  980. return true;
  981. }