cmFileAPI.cxx 29 KB

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