cmFileAPI.cxx 29 KB

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