cmFileAPI.cxx 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmFileAPI.h"
  4. #include "cmCryptoHash.h"
  5. #include "cmSystemTools.h"
  6. #include "cmTimestamp.h"
  7. #include "cmake.h"
  8. #include "cmsys/Directory.hxx"
  9. #include "cmsys/FStream.hxx"
  10. #include <algorithm>
  11. #include <cassert>
  12. #include <chrono>
  13. #include <ctime>
  14. #include <iomanip>
  15. #include <sstream>
  16. #include <utility>
  17. cmFileAPI::cmFileAPI(cmake* cm)
  18. : CMakeInstance(cm)
  19. {
  20. this->APIv1 =
  21. this->CMakeInstance->GetHomeOutputDirectory() + "/.cmake/api/v1";
  22. Json::StreamWriterBuilder wbuilder;
  23. wbuilder["indentation"] = "\t";
  24. this->JsonWriter =
  25. std::unique_ptr<Json::StreamWriter>(wbuilder.newStreamWriter());
  26. }
  27. void cmFileAPI::ReadQueries()
  28. {
  29. std::string const query_dir = this->APIv1 + "/query";
  30. this->QueryExists = cmSystemTools::FileIsDirectory(query_dir);
  31. if (!this->QueryExists) {
  32. return;
  33. }
  34. // Load queries at the top level.
  35. std::vector<std::string> queries = cmFileAPI::LoadDir(query_dir);
  36. // Read the queries and save for later.
  37. for (std::string& query : queries) {
  38. if (!cmFileAPI::ReadQuery(query, this->TopQuery.Known)) {
  39. this->TopQuery.Unknown.push_back(std::move(query));
  40. }
  41. }
  42. }
  43. void cmFileAPI::WriteReplies()
  44. {
  45. if (this->QueryExists) {
  46. cmSystemTools::MakeDirectory(this->APIv1 + "/reply");
  47. this->WriteJsonFile(this->BuildReplyIndex(), "index", ComputeSuffixTime);
  48. }
  49. this->RemoveOldReplyFiles();
  50. }
  51. std::vector<std::string> cmFileAPI::LoadDir(std::string const& dir)
  52. {
  53. std::vector<std::string> files;
  54. cmsys::Directory d;
  55. d.Load(dir);
  56. for (unsigned long i = 0; i < d.GetNumberOfFiles(); ++i) {
  57. std::string f = d.GetFile(i);
  58. if (f != "." && f != "..") {
  59. files.push_back(std::move(f));
  60. }
  61. }
  62. std::sort(files.begin(), files.end());
  63. return files;
  64. }
  65. void cmFileAPI::RemoveOldReplyFiles()
  66. {
  67. std::string const reply_dir = this->APIv1 + "/reply";
  68. std::vector<std::string> files = this->LoadDir(reply_dir);
  69. for (std::string const& f : files) {
  70. if (this->ReplyFiles.find(f) == this->ReplyFiles.end()) {
  71. std::string file = reply_dir + "/" + f;
  72. cmSystemTools::RemoveFile(file);
  73. }
  74. }
  75. }
  76. std::string cmFileAPI::WriteJsonFile(
  77. Json::Value const& value, std::string const& prefix,
  78. std::string (*computeSuffix)(std::string const&))
  79. {
  80. std::string fileName;
  81. // Write the json file with a temporary name.
  82. std::string const& tmpFile = this->APIv1 + "/tmp.json";
  83. cmsys::ofstream ftmp(tmpFile.c_str());
  84. this->JsonWriter->write(value, &ftmp);
  85. ftmp << "\n";
  86. ftmp.close();
  87. if (!ftmp) {
  88. cmSystemTools::RemoveFile(tmpFile);
  89. return fileName;
  90. }
  91. // Compute the final name for the file.
  92. fileName = prefix + "-" + computeSuffix(tmpFile) + ".json";
  93. // Create the destination.
  94. std::string file = this->APIv1 + "/reply";
  95. cmSystemTools::MakeDirectory(file);
  96. file += "/";
  97. file += fileName;
  98. // If the final name already exists then assume it has proper content.
  99. // Otherwise, atomically place the reply file at its final name
  100. if (cmSystemTools::FileExists(file, true) ||
  101. !cmSystemTools::RenameFile(tmpFile.c_str(), file.c_str())) {
  102. cmSystemTools::RemoveFile(tmpFile);
  103. }
  104. // Record this among files we have just written.
  105. this->ReplyFiles.insert(fileName);
  106. return fileName;
  107. }
  108. std::string cmFileAPI::ComputeSuffixHash(std::string const& file)
  109. {
  110. cmCryptoHash hasher(cmCryptoHash::AlgoSHA3_256);
  111. std::string hash = hasher.HashFile(file);
  112. hash.resize(20, '0');
  113. return hash;
  114. }
  115. std::string cmFileAPI::ComputeSuffixTime(std::string const&)
  116. {
  117. std::chrono::milliseconds ms =
  118. std::chrono::duration_cast<std::chrono::milliseconds>(
  119. std::chrono::system_clock::now().time_since_epoch());
  120. std::chrono::seconds s =
  121. std::chrono::duration_cast<std::chrono::seconds>(ms);
  122. std::time_t ts = s.count();
  123. std::size_t tms = ms.count() % 1000;
  124. cmTimestamp cmts;
  125. std::ostringstream ss;
  126. ss << cmts.CreateTimestampFromTimeT(ts, "%Y-%m-%dT%H-%M-%S", true) << '-'
  127. << std::setfill('0') << std::setw(4) << tms;
  128. return ss.str();
  129. }
  130. bool cmFileAPI::ReadQuery(std::string const& query,
  131. std::vector<Object>& objects)
  132. {
  133. // Parse the "<kind>-" syntax.
  134. std::string::size_type sep_pos = query.find('-');
  135. if (sep_pos == std::string::npos) {
  136. return false;
  137. }
  138. std::string kindName = query.substr(0, sep_pos);
  139. std::string verStr = query.substr(sep_pos + 1);
  140. if (kindName == ObjectKindName(ObjectKind::InternalTest)) {
  141. Object o;
  142. o.Kind = ObjectKind::InternalTest;
  143. if (verStr == "v1") {
  144. o.Version = 1;
  145. } else if (verStr == "v2") {
  146. o.Version = 2;
  147. } else {
  148. return false;
  149. }
  150. objects.push_back(o);
  151. return true;
  152. }
  153. return false;
  154. }
  155. Json::Value cmFileAPI::BuildReplyIndex()
  156. {
  157. Json::Value index(Json::objectValue);
  158. // Report information about this version of CMake.
  159. index["cmake"] = this->BuildCMake();
  160. // Reply to all queries that we loaded.
  161. index["reply"] = this->BuildReply(this->TopQuery);
  162. // Move our index of generated objects into its field.
  163. Json::Value& objects = index["objects"] = Json::arrayValue;
  164. for (auto& entry : this->ReplyIndexObjects) {
  165. objects.append(std::move(entry.second)); // NOLINT(*)
  166. }
  167. return index;
  168. }
  169. Json::Value cmFileAPI::BuildCMake()
  170. {
  171. Json::Value cmake = Json::objectValue;
  172. cmake["version"] = this->CMakeInstance->ReportVersionJson();
  173. Json::Value& cmake_paths = cmake["paths"] = Json::objectValue;
  174. cmake_paths["cmake"] = cmSystemTools::GetCMakeCommand();
  175. cmake_paths["ctest"] = cmSystemTools::GetCTestCommand();
  176. cmake_paths["cpack"] = cmSystemTools::GetCPackCommand();
  177. cmake_paths["root"] = cmSystemTools::GetCMakeRoot();
  178. return cmake;
  179. }
  180. Json::Value cmFileAPI::BuildReply(Query const& q)
  181. {
  182. Json::Value reply = Json::objectValue;
  183. for (Object const& o : q.Known) {
  184. std::string const& name = ObjectName(o);
  185. reply[name] = this->AddReplyIndexObject(o);
  186. }
  187. for (std::string const& name : q.Unknown) {
  188. reply[name] = cmFileAPI::BuildReplyError("unknown query file");
  189. }
  190. return reply;
  191. }
  192. Json::Value cmFileAPI::BuildReplyError(std::string const& error)
  193. {
  194. Json::Value e = Json::objectValue;
  195. e["error"] = error;
  196. return e;
  197. }
  198. Json::Value const& cmFileAPI::AddReplyIndexObject(Object const& o)
  199. {
  200. Json::Value& indexEntry = this->ReplyIndexObjects[o];
  201. if (!indexEntry.isNull()) {
  202. // The reply object has already been generated.
  203. return indexEntry;
  204. }
  205. // Generate this reply object.
  206. Json::Value const& object = this->BuildObject(o);
  207. assert(object.isObject());
  208. // Populate this index entry.
  209. indexEntry = Json::objectValue;
  210. indexEntry["kind"] = object["kind"];
  211. indexEntry["version"] = object["version"];
  212. indexEntry["jsonFile"] = this->WriteJsonFile(object, ObjectName(o));
  213. return indexEntry;
  214. }
  215. const char* cmFileAPI::ObjectKindName(ObjectKind kind)
  216. {
  217. // Keep in sync with ObjectKind enum.
  218. static const char* objectKindNames[] = {
  219. "__test" //
  220. };
  221. return objectKindNames[size_t(kind)];
  222. }
  223. std::string cmFileAPI::ObjectName(Object const& o)
  224. {
  225. std::string name = ObjectKindName(o.Kind);
  226. name += "-v";
  227. name += std::to_string(o.Version);
  228. return name;
  229. }
  230. Json::Value cmFileAPI::BuildObject(Object const& object)
  231. {
  232. Json::Value value;
  233. switch (object.Kind) {
  234. case ObjectKind::InternalTest:
  235. value = this->BuildInternalTest(object);
  236. break;
  237. }
  238. return value;
  239. }
  240. // The "__test" object kind is for internal testing of CMake.
  241. static unsigned int const InternalTestV1Minor = 3;
  242. static unsigned int const InternalTestV2Minor = 0;
  243. Json::Value cmFileAPI::BuildInternalTest(Object const& object)
  244. {
  245. Json::Value test = Json::objectValue;
  246. test["kind"] = this->ObjectKindName(object.Kind);
  247. Json::Value& version = test["version"] = Json::objectValue;
  248. if (object.Version == 2) {
  249. version["major"] = 2;
  250. version["minor"] = InternalTestV2Minor;
  251. } else {
  252. version["major"] = 1;
  253. version["minor"] = InternalTestV1Minor;
  254. }
  255. return test;
  256. }