1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
|
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmFileAPI.h"
#include "cmAlgorithms.h"
#include "cmCryptoHash.h"
#include "cmFileAPICodemodel.h"
#include "cmGlobalGenerator.h"
#include "cmSystemTools.h"
#include "cmTimestamp.h"
#include "cmake.h"
#include "cmsys/Directory.hxx"
#include "cmsys/FStream.hxx"
#include <algorithm>
#include <cassert>
#include <chrono>
#include <ctime>
#include <iomanip>
#include <sstream>
#include <utility>
cmFileAPI::cmFileAPI(cmake* cm)
: CMakeInstance(cm)
{
this->APIv1 =
this->CMakeInstance->GetHomeOutputDirectory() + "/.cmake/api/v1";
Json::CharReaderBuilder rbuilder;
rbuilder["collectComments"] = false;
rbuilder["failIfExtra"] = true;
rbuilder["rejectDupKeys"] = false;
rbuilder["strictRoot"] = true;
this->JsonReader =
std::unique_ptr<Json::CharReader>(rbuilder.newCharReader());
Json::StreamWriterBuilder wbuilder;
wbuilder["indentation"] = "\t";
this->JsonWriter =
std::unique_ptr<Json::StreamWriter>(wbuilder.newStreamWriter());
}
void cmFileAPI::ReadQueries()
{
std::string const query_dir = this->APIv1 + "/query";
this->QueryExists = cmSystemTools::FileIsDirectory(query_dir);
if (!this->QueryExists) {
return;
}
// Load queries at the top level.
std::vector<std::string> queries = cmFileAPI::LoadDir(query_dir);
// Read the queries and save for later.
for (std::string& query : queries) {
if (cmHasLiteralPrefix(query, "client-")) {
this->ReadClient(query);
} else if (!cmFileAPI::ReadQuery(query, this->TopQuery.Known)) {
this->TopQuery.Unknown.push_back(std::move(query));
}
}
}
void cmFileAPI::WriteReplies()
{
if (this->QueryExists) {
cmSystemTools::MakeDirectory(this->APIv1 + "/reply");
this->WriteJsonFile(this->BuildReplyIndex(), "index", ComputeSuffixTime);
}
this->RemoveOldReplyFiles();
}
std::vector<std::string> cmFileAPI::LoadDir(std::string const& dir)
{
std::vector<std::string> files;
cmsys::Directory d;
d.Load(dir);
for (unsigned long i = 0; i < d.GetNumberOfFiles(); ++i) {
std::string f = d.GetFile(i);
if (f != "." && f != "..") {
files.push_back(std::move(f));
}
}
std::sort(files.begin(), files.end());
return files;
}
void cmFileAPI::RemoveOldReplyFiles()
{
std::string const reply_dir = this->APIv1 + "/reply";
std::vector<std::string> files = this->LoadDir(reply_dir);
for (std::string const& f : files) {
if (this->ReplyFiles.find(f) == this->ReplyFiles.end()) {
std::string file = reply_dir + "/" + f;
cmSystemTools::RemoveFile(file);
}
}
}
bool cmFileAPI::ReadJsonFile(std::string const& file, Json::Value& value,
std::string& error)
{
std::vector<char> content;
cmsys::ifstream fin;
if (!cmSystemTools::FileIsDirectory(file)) {
fin.open(file.c_str(), std::ios::binary);
}
auto finEnd = fin.rdbuf()->pubseekoff(0, std::ios::end);
if (finEnd > 0) {
size_t finSize = finEnd;
try {
// Allocate a buffer to read the whole file.
content.resize(finSize);
// Now read the file from the beginning.
fin.seekg(0, std::ios::beg);
fin.read(content.data(), finSize);
} catch (...) {
fin.setstate(std::ios::failbit);
}
}
fin.close();
if (!fin) {
value = Json::Value();
error = "failed to read from file";
return false;
}
// Parse our buffer as json.
if (!this->JsonReader->parse(content.data(), content.data() + content.size(),
&value, &error)) {
value = Json::Value();
return false;
}
return true;
}
std::string cmFileAPI::WriteJsonFile(
Json::Value const& value, std::string const& prefix,
std::string (*computeSuffix)(std::string const&))
{
std::string fileName;
// Write the json file with a temporary name.
std::string const& tmpFile = this->APIv1 + "/tmp.json";
cmsys::ofstream ftmp(tmpFile.c_str());
this->JsonWriter->write(value, &ftmp);
ftmp << "\n";
ftmp.close();
if (!ftmp) {
cmSystemTools::RemoveFile(tmpFile);
return fileName;
}
// Compute the final name for the file.
fileName = prefix + "-" + computeSuffix(tmpFile) + ".json";
// Create the destination.
std::string file = this->APIv1 + "/reply";
cmSystemTools::MakeDirectory(file);
file += "/";
file += fileName;
// If the final name already exists then assume it has proper content.
// Otherwise, atomically place the reply file at its final name
if (cmSystemTools::FileExists(file, true) ||
!cmSystemTools::RenameFile(tmpFile.c_str(), file.c_str())) {
cmSystemTools::RemoveFile(tmpFile);
}
// Record this among files we have just written.
this->ReplyFiles.insert(fileName);
return fileName;
}
Json::Value cmFileAPI::MaybeJsonFile(Json::Value in, std::string const& prefix)
{
Json::Value out;
if (in.isObject() || in.isArray()) {
out = Json::objectValue;
out["jsonFile"] = this->WriteJsonFile(in, prefix);
} else {
out = std::move(in);
}
return out;
}
std::string cmFileAPI::ComputeSuffixHash(std::string const& file)
{
cmCryptoHash hasher(cmCryptoHash::AlgoSHA3_256);
std::string hash = hasher.HashFile(file);
hash.resize(20, '0');
return hash;
}
std::string cmFileAPI::ComputeSuffixTime(std::string const&)
{
std::chrono::milliseconds ms =
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch());
std::chrono::seconds s =
std::chrono::duration_cast<std::chrono::seconds>(ms);
std::time_t ts = s.count();
std::size_t tms = ms.count() % 1000;
cmTimestamp cmts;
std::ostringstream ss;
ss << cmts.CreateTimestampFromTimeT(ts, "%Y-%m-%dT%H-%M-%S", true) << '-'
<< std::setfill('0') << std::setw(4) << tms;
return ss.str();
}
bool cmFileAPI::ReadQuery(std::string const& query,
std::vector<Object>& objects)
{
// Parse the "<kind>-" syntax.
std::string::size_type sep_pos = query.find('-');
if (sep_pos == std::string::npos) {
return false;
}
std::string kindName = query.substr(0, sep_pos);
std::string verStr = query.substr(sep_pos + 1);
if (kindName == ObjectKindName(ObjectKind::CodeModel)) {
Object o;
o.Kind = ObjectKind::CodeModel;
if (verStr == "v2") {
o.Version = 2;
} else {
return false;
}
objects.push_back(o);
return true;
}
if (kindName == ObjectKindName(ObjectKind::InternalTest)) {
Object o;
o.Kind = ObjectKind::InternalTest;
if (verStr == "v1") {
o.Version = 1;
} else if (verStr == "v2") {
o.Version = 2;
} else {
return false;
}
objects.push_back(o);
return true;
}
return false;
}
void cmFileAPI::ReadClient(std::string const& client)
{
// Load queries for the client.
std::string clientDir = this->APIv1 + "/query/" + client;
std::vector<std::string> queries = this->LoadDir(clientDir);
// Read the queries and save for later.
ClientQuery& clientQuery = this->ClientQueries[client];
for (std::string& query : queries) {
if (query == "query.json") {
clientQuery.HaveQueryJson = true;
this->ReadClientQuery(client, clientQuery.QueryJson);
} else if (!this->ReadQuery(query, clientQuery.DirQuery.Known)) {
clientQuery.DirQuery.Unknown.push_back(std::move(query));
}
}
}
void cmFileAPI::ReadClientQuery(std::string const& client, ClientQueryJson& q)
{
// Read the query.json file.
std::string queryFile = this->APIv1 + "/query/" + client + "/query.json";
Json::Value query;
if (!this->ReadJsonFile(queryFile, query, q.Error)) {
return;
}
if (!query.isObject()) {
q.Error = "query root is not an object";
return;
}
Json::Value const& clientValue = query["client"];
if (!clientValue.isNull()) {
q.ClientValue = clientValue;
}
q.RequestsValue = std::move(query["requests"]);
q.Requests = this->BuildClientRequests(q.RequestsValue);
}
Json::Value cmFileAPI::BuildReplyIndex()
{
Json::Value index(Json::objectValue);
// Report information about this version of CMake.
index["cmake"] = this->BuildCMake();
// Reply to all queries that we loaded.
Json::Value& reply = index["reply"] = this->BuildReply(this->TopQuery);
for (auto const& client : this->ClientQueries) {
std::string const& clientName = client.first;
ClientQuery const& clientQuery = client.second;
reply[clientName] = this->BuildClientReply(clientQuery);
}
// Move our index of generated objects into its field.
Json::Value& objects = index["objects"] = Json::arrayValue;
for (auto& entry : this->ReplyIndexObjects) {
objects.append(std::move(entry.second)); // NOLINT(*)
}
return index;
}
Json::Value cmFileAPI::BuildCMake()
{
Json::Value cmake = Json::objectValue;
cmake["version"] = this->CMakeInstance->ReportVersionJson();
Json::Value& cmake_paths = cmake["paths"] = Json::objectValue;
cmake_paths["cmake"] = cmSystemTools::GetCMakeCommand();
cmake_paths["ctest"] = cmSystemTools::GetCTestCommand();
cmake_paths["cpack"] = cmSystemTools::GetCPackCommand();
cmake_paths["root"] = cmSystemTools::GetCMakeRoot();
cmake["generator"] = this->CMakeInstance->GetGlobalGenerator()->GetJson();
return cmake;
}
Json::Value cmFileAPI::BuildReply(Query const& q)
{
Json::Value reply = Json::objectValue;
for (Object const& o : q.Known) {
std::string const& name = ObjectName(o);
reply[name] = this->AddReplyIndexObject(o);
}
for (std::string const& name : q.Unknown) {
reply[name] = cmFileAPI::BuildReplyError("unknown query file");
}
return reply;
}
Json::Value cmFileAPI::BuildReplyError(std::string const& error)
{
Json::Value e = Json::objectValue;
e["error"] = error;
return e;
}
Json::Value const& cmFileAPI::AddReplyIndexObject(Object const& o)
{
Json::Value& indexEntry = this->ReplyIndexObjects[o];
if (!indexEntry.isNull()) {
// The reply object has already been generated.
return indexEntry;
}
// Generate this reply object.
Json::Value const& object = this->BuildObject(o);
assert(object.isObject());
// Populate this index entry.
indexEntry = Json::objectValue;
indexEntry["kind"] = object["kind"];
indexEntry["version"] = object["version"];
indexEntry["jsonFile"] = this->WriteJsonFile(object, ObjectName(o));
return indexEntry;
}
const char* cmFileAPI::ObjectKindName(ObjectKind kind)
{
// Keep in sync with ObjectKind enum.
static const char* objectKindNames[] = {
"codemodel", //
"__test" //
};
return objectKindNames[size_t(kind)];
}
std::string cmFileAPI::ObjectName(Object const& o)
{
std::string name = ObjectKindName(o.Kind);
name += "-v";
name += std::to_string(o.Version);
return name;
}
Json::Value cmFileAPI::BuildObject(Object const& object)
{
Json::Value value;
switch (object.Kind) {
case ObjectKind::CodeModel:
value = this->BuildCodeModel(object);
break;
case ObjectKind::InternalTest:
value = this->BuildInternalTest(object);
break;
}
return value;
}
cmFileAPI::ClientRequests cmFileAPI::BuildClientRequests(
Json::Value const& requests)
{
ClientRequests result;
if (requests.isNull()) {
result.Error = "'requests' member missing";
return result;
}
if (!requests.isArray()) {
result.Error = "'requests' member is not an array";
return result;
}
result.reserve(requests.size());
for (Json::Value const& request : requests) {
result.emplace_back(this->BuildClientRequest(request));
}
return result;
}
cmFileAPI::ClientRequest cmFileAPI::BuildClientRequest(
Json::Value const& request)
{
ClientRequest r;
if (!request.isObject()) {
r.Error = "request is not an object";
return r;
}
Json::Value const& kind = request["kind"];
if (kind.isNull()) {
r.Error = "'kind' member missing";
return r;
}
if (!kind.isString()) {
r.Error = "'kind' member is not a string";
return r;
}
std::string const& kindName = kind.asString();
if (kindName == this->ObjectKindName(ObjectKind::CodeModel)) {
r.Kind = ObjectKind::CodeModel;
} else if (kindName == this->ObjectKindName(ObjectKind::InternalTest)) {
r.Kind = ObjectKind::InternalTest;
} else {
r.Error = "unknown request kind '" + kindName + "'";
return r;
}
Json::Value const& version = request["version"];
if (version.isNull()) {
r.Error = "'version' member missing";
return r;
}
std::vector<RequestVersion> versions;
if (!cmFileAPI::ReadRequestVersions(version, versions, r.Error)) {
return r;
}
switch (r.Kind) {
case ObjectKind::CodeModel:
this->BuildClientRequestCodeModel(r, versions);
break;
case ObjectKind::InternalTest:
this->BuildClientRequestInternalTest(r, versions);
break;
}
return r;
}
Json::Value cmFileAPI::BuildClientReply(ClientQuery const& q)
{
Json::Value reply = this->BuildReply(q.DirQuery);
if (!q.HaveQueryJson) {
return reply;
}
Json::Value& reply_query_json = reply["query.json"];
ClientQueryJson const& qj = q.QueryJson;
if (!qj.Error.empty()) {
reply_query_json = this->BuildReplyError(qj.Error);
return reply;
}
if (!qj.ClientValue.isNull()) {
reply_query_json["client"] = qj.ClientValue;
}
if (!qj.RequestsValue.isNull()) {
reply_query_json["requests"] = qj.RequestsValue;
}
reply_query_json["responses"] = this->BuildClientReplyResponses(qj.Requests);
return reply;
}
Json::Value cmFileAPI::BuildClientReplyResponses(
ClientRequests const& requests)
{
Json::Value responses;
if (!requests.Error.empty()) {
responses = this->BuildReplyError(requests.Error);
return responses;
}
responses = Json::arrayValue;
for (ClientRequest const& request : requests) {
responses.append(this->BuildClientReplyResponse(request));
}
return responses;
}
Json::Value cmFileAPI::BuildClientReplyResponse(ClientRequest const& request)
{
Json::Value response;
if (!request.Error.empty()) {
response = this->BuildReplyError(request.Error);
return response;
}
response = this->AddReplyIndexObject(request);
return response;
}
bool cmFileAPI::ReadRequestVersions(Json::Value const& version,
std::vector<RequestVersion>& versions,
std::string& error)
{
if (version.isArray()) {
for (Json::Value const& v : version) {
if (!ReadRequestVersion(v, /*inArray=*/true, versions, error)) {
return false;
}
}
} else {
if (!ReadRequestVersion(version, /*inArray=*/false, versions, error)) {
return false;
}
}
return true;
}
bool cmFileAPI::ReadRequestVersion(Json::Value const& version, bool inArray,
std::vector<RequestVersion>& result,
std::string& error)
{
if (version.isUInt()) {
RequestVersion v;
v.Major = version.asUInt();
result.push_back(v);
return true;
}
if (!version.isObject()) {
if (inArray) {
error = "'version' array entry is not a non-negative integer or object";
} else {
error =
"'version' member is not a non-negative integer, object, or array";
}
return false;
}
Json::Value const& major = version["major"];
if (major.isNull()) {
error = "'version' object 'major' member missing";
return false;
}
if (!major.isUInt()) {
error = "'version' object 'major' member is not a non-negative integer";
return false;
}
RequestVersion v;
v.Major = major.asUInt();
Json::Value const& minor = version["minor"];
if (minor.isUInt()) {
v.Minor = minor.asUInt();
} else if (!minor.isNull()) {
error = "'version' object 'minor' member is not a non-negative integer";
return false;
}
result.push_back(v);
return true;
}
std::string cmFileAPI::NoSupportedVersion(
std::vector<RequestVersion> const& versions)
{
std::ostringstream msg;
msg << "no supported version specified";
if (!versions.empty()) {
msg << " among:";
for (RequestVersion const& v : versions) {
msg << " " << v.Major << "." << v.Minor;
}
}
return msg.str();
}
// The "codemodel" object kind.
static unsigned int const CodeModelV2Minor = 0;
void cmFileAPI::BuildClientRequestCodeModel(
ClientRequest& r, std::vector<RequestVersion> const& versions)
{
// Select a known version from those requested.
for (RequestVersion const& v : versions) {
if ((v.Major == 2 && v.Minor <= CodeModelV2Minor)) {
r.Version = v.Major;
break;
}
}
if (!r.Version) {
r.Error = NoSupportedVersion(versions);
}
}
Json::Value cmFileAPI::BuildCodeModel(Object const& object)
{
using namespace std::placeholders;
Json::Value codemodel = cmFileAPICodemodelDump(*this, object.Version);
codemodel["kind"] = this->ObjectKindName(object.Kind);
Json::Value& version = codemodel["version"] = Json::objectValue;
if (object.Version == 2) {
version["major"] = 2;
version["minor"] = CodeModelV2Minor;
} else {
return codemodel; // should be unreachable
}
return codemodel;
}
// The "__test" object kind is for internal testing of CMake.
static unsigned int const InternalTestV1Minor = 3;
static unsigned int const InternalTestV2Minor = 0;
void cmFileAPI::BuildClientRequestInternalTest(
ClientRequest& r, std::vector<RequestVersion> const& versions)
{
// Select a known version from those requested.
for (RequestVersion const& v : versions) {
if ((v.Major == 1 && v.Minor <= InternalTestV1Minor) || //
(v.Major == 2 && v.Minor <= InternalTestV2Minor)) {
r.Version = v.Major;
break;
}
}
if (!r.Version) {
r.Error = NoSupportedVersion(versions);
}
}
Json::Value cmFileAPI::BuildInternalTest(Object const& object)
{
Json::Value test = Json::objectValue;
test["kind"] = this->ObjectKindName(object.Kind);
Json::Value& version = test["version"] = Json::objectValue;
if (object.Version == 2) {
version["major"] = 2;
version["minor"] = InternalTestV2Minor;
} else {
version["major"] = 1;
version["minor"] = InternalTestV1Minor;
}
return test;
}
|