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