Coverage Report

Created: 2026-07-30 06:52

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