forked from Andersbakken/rtags
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Project.cpp
2683 lines (2453 loc) · 87.5 KB
/
Project.cpp
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
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* This file is part of RTags (http://rtags.net).
RTags is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
RTags is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with RTags. If not, see <http://www.gnu.org/licenses/>. */
#include "Project.h"
#include <fnmatch.h>
#include <memory>
#include <regex>
#include "Diagnostic.h"
#include "FileManager.h"
#include "CompilerManager.h"
#include "IndexDataMessage.h"
#include "JobScheduler.h"
#include "LogOutputMessage.h"
#include "rct/DataFile.h"
#include "rct/Log.h"
#include "rct/MemoryMonitor.h"
#include "rct/Path.h"
#include "rct/Rct.h"
#include "rct/ReadLocker.h"
#include "rct/Thread.h"
#include "rct/Value.h"
#include "RTags.h"
#include "RTagsLogOutput.h"
#include "Server.h"
#include "RTagsVersion.h"
enum { DirtyTimeout = 100 };
class Dirty
{
public:
virtual ~Dirty() {}
virtual Set<uint32_t> dirtied() const = 0;
virtual bool isDirty(const SourceList &) = 0;
};
class SimpleDirty : public Dirty
{
public:
void init(const Set<uint32_t> &dirty, const std::shared_ptr<Project> &project)
{
for (auto fileId : dirty) {
mDirty.insert(fileId);
mDirty += project->dependencies(fileId, Project::DependsOnArg);
}
}
virtual Set<uint32_t> dirtied() const override
{
return mDirty;
}
virtual bool isDirty(const SourceList &sourceList) override
{
return mDirty.contains(sourceList.fileId());
}
Set<uint32_t> mDirty;
};
class ComplexDirty : public Dirty
{
public:
virtual Set<uint32_t> dirtied() const override
{
return mDirty;
}
void insertDirtyFile(uint32_t fileId)
{
mDirty.insert(fileId);
}
inline uint64_t lastModified(uint32_t fileId)
{
uint64_t &time = mLastModified[fileId];
if (!time) {
time = Location::path(fileId).lastModifiedMs();
}
return time;
}
Hash<uint32_t, uint64_t> mLastModified;
Set<uint32_t> mDirty;
};
class SuspendedDirty : public ComplexDirty
{
public:
bool isDirty(const SourceList &) override
{
return false;
}
};
class IfModifiedDirty : public ComplexDirty
{
public:
IfModifiedDirty(const std::shared_ptr<Project> &project, const Match &match = Match())
: mProject(project), mMatch(match)
{
}
virtual bool isDirty(const SourceList &sourceList) override
{
bool ret = false;
const uint32_t fileId = sourceList.fileId();
if (mMatch.isEmpty() || mMatch.match(Location::path(fileId))) {
for (auto it : mProject->dependencies(fileId, Project::ArgDependsOn)) {
uint64_t depLastModified = lastModified(it);
if (!depLastModified || depLastModified > sourceList.parsed) {
ret = true;
insertDirtyFile(it);
}
}
if (ret)
mDirty.insert(fileId);
assert(!ret || mDirty.contains(fileId));
}
return ret;
}
std::shared_ptr<Project> mProject;
Match mMatch;
};
class WatcherDirty : public ComplexDirty
{
public:
WatcherDirty(const std::shared_ptr<Project> &project, const Set<uint32_t> &modified)
{
for (auto it : modified) {
mModified[it] = project->dependencies(it, Project::DependsOnArg);
}
}
virtual bool isDirty(const SourceList &sourceList) override
{
bool ret = false;
for (auto it : mModified) {
const auto &deps = it.second;
if (deps.contains(sourceList.fileId())) {
const uint64_t depLastModified = lastModified(it.first);
if (!depLastModified || depLastModified > sourceList.parsed) {
// dependency is gone
ret = true;
insertDirtyFile(it.first);
}
}
}
if (ret)
insertDirtyFile(sourceList.fileId());
return ret;
}
Hash<uint32_t, Set<uint32_t> > mModified;
};
static bool loadDependencies(DataFile &file, Dependencies &dependencies)
{
int size;
file >> size;
for (int i=0; i<size; ++i) {
uint32_t fileId;
file >> fileId;
if (!fileId)
return false;
dependencies[fileId] = new DependencyNode(fileId);
}
for (int i=0; i<size; ++i) {
int links;
file >> links;
if (links) {
uint32_t dependee;
file >> dependee;
DependencyNode *ee = dependencies[dependee];
if (!ee) {
return false;
}
while (links--) {
uint32_t dependent;
file >> dependent;
DependencyNode *ent = dependencies[dependent];
if (!ent) {
return false;
}
ent->include(ee);
}
}
}
return true;
}
static void saveDependencies(DataFile &file, const Dependencies &dependencies)
{
file << static_cast<int>(dependencies.size());
for (const auto &it : dependencies) {
file << it.first;
}
for (const auto &it : dependencies) {
file << static_cast<int>(it.second->dependents.size());
if (!it.second->dependents.isEmpty()) {
file << it.first;
for (const auto &dep : it.second->dependents) {
file << dep.first;
}
}
}
}
Project::Project(const Path &path)
: mPath(path), mSourceFilePathBase(RTags::encodeSourceFilePath(Server::instance()->options().dataDir, path)),
mJobCounter(0), mJobsStarted(0), mBytesWritten(0), mSaveDirty(false)
{
Path srcPath = mPath;
RTags::encodePath(srcPath);
const Server::Options &options = Server::instance()->options();
const Path tmp = options.dataDir + srcPath;
mProjectFilePath = tmp + "/project";
mSourcesFilePath = tmp + "/sources";
}
Project::~Project()
{
if (mSaveDirty)
save();
for (const auto &job : mActiveJobs) {
assert(job.second);
Server::instance()->jobScheduler()->abort(job.second);
}
mDependencies.deleteAll();
assert(EventLoop::isMainThread());
mDirtyTimer.stop();
}
static bool hasSourceDependency(const DependencyNode *node, const std::shared_ptr<Project> &project, Set<uint32_t> &seen)
{
const Path path = Location::path(node->fileId);
// error("%s %d %d", path.constData(), path.isFile(), path.isSource());
if (path.isFile() && path.isSource() && project->hasSource(node->fileId)) {
return true;
}
for (auto it : node->dependents) {
if (seen.insert(it.first) && hasSourceDependency(it.second, project, seen))
return true;
}
return false;
}
static inline bool hasSourceDependency(const DependencyNode *node, const std::shared_ptr<Project> &project)
{
Set<uint32_t> seen;
return hasSourceDependency(node, project, seen);
}
bool Project::readSources(const Path &path, IndexParseData &data, String *err)
{
DataFile file(path, RTags::SourcesFileVersion);
if (!file.open(DataFile::Read)) {
Path::rm(path);
if (err && !file.error().isEmpty())
*err = file.error();
return false;
}
file >> data;
if (Sandbox::hasRoot()) {
forEachSource(data, [](Source &source) {
for (String &arg : source.arguments) {
arg = Sandbox::decoded(arg);
}
return Continue;
});
}
return true;
}
bool Project::init()
{
const JobScheduler::JobScope scope(Server::instance()->jobScheduler());
const Server::Options &options = Server::instance()->options();
if (!(options.options & Server::NoFileSystemWatch)) {
mWatcher.modified().connect(std::bind(&Project::onFileModified, this, std::placeholders::_1));
mWatcher.added().connect(std::bind(&Project::onFileAdded, this, std::placeholders::_1));
mWatcher.removed().connect(std::bind(&Project::onFileRemoved, this, std::placeholders::_1));
}
if (!(options.options & Server::NoFileManager)) {
mFileManager.reset(new FileManager(shared_from_this()));
mWatcher.removed().connect([this](const Path &path) { if (mWatchedPaths.value(path.parentDir()) & Watch_FileManager) mFileManager->onFileRemoved(path); });
mWatcher.added().connect([this](const Path &path) { if (mWatchedPaths.value(path.parentDir()) & Watch_FileManager) mFileManager->onFileAdded(path); });
}
mDirtyTimer.timeout().connect(std::bind(&Project::onDirtyTimeout, this, std::placeholders::_1));
String err;
if (!Project::readSources(mSourcesFilePath, mIndexParseData, &err)) {
if (!err.isEmpty())
error("Sources restore error %s: %s", mPath.constData(), err.constData());
return false;
}
auto reindexAll = [this]() {
mProjectFilePath.visit([](const Path &path) {
if (strcmp(path.fileName(), "sources")) {
if (path.isDir()) {
Path::rmdir(path);
} else {
path.rm();
}
}
return Path::Continue;
});
auto parseData = std::move(mIndexParseData);
processParseData(std::move(parseData));
};
DataFile file(mProjectFilePath, RTags::DatabaseVersion);
if (!file.open(DataFile::Read)) {
if (!file.error().isEmpty())
error("Restore error %s: %s", mPath.constData(), file.error().constData());
reindexAll();
return true;
}
{
std::lock_guard<std::mutex> lock(mMutex);
file >> mVisitedFiles;
Sandbox::decode(mVisitedFiles);
}
file >> mDiagnostics;
for (const auto &info : mIndexParseData.compileCommands)
watch(Location::path(info.first), Watch_CompileCommands);
if (!loadDependencies(file, mDependencies)) {
mDependencies.deleteAll();
mVisitedFiles.clear();
mDiagnostics.clear();
error("Restore error %s: Failed to load dependencies.", mPath.constData());
reindexAll();
return true;
}
for (const auto &dep : mDependencies) {
watchFile(dep.first);
}
bool needsSave = false;
std::unique_ptr<ComplexDirty> dirty;
if (Server::instance()->suspended()) {
dirty.reset(new SuspendedDirty);
} else {
dirty.reset(new IfModifiedDirty(shared_from_this()));
}
Set<uint32_t> missingFileMaps;
{
List<uint32_t> removed;
int idx = 0;
bool outputDirty = false;
if (mDependencies.size() >= 100) {
logDirect(LogLevel::Error, String::format<128>("Restoring %s ", mPath.constData()), LogOutput::StdOut);
outputDirty = true;
}
const std::shared_ptr<Project> project = shared_from_this();
for (auto it : mDependencies) {
const Path path = Location::path(it.first);
if (!path.isFile()) {
warning() << path << "seems to have disappeared";
dirty.get()->insertDirtyFile(it.first);
const Set<uint32_t> dependents = dependencies(it.first, DependsOnArg);
for (auto dependent : dependents) {
dirty.get()->insertDirtyFile(dependent);
}
removed << it.first;
needsSave = true;
} else {
String errorString;
if (!validate(it.first, options.options & Server::ValidateFileMaps ? Validate : StatOnly, &errorString)) {
if (!errorString.isEmpty()) {
if (outputDirty) {
outputDirty = false;
logDirect(LogLevel::Error, String("\n"), LogOutput::StdOut);
}
error() << errorString;
}
if (hasSource(it.first) || hasSourceDependency(it.second, project)) {
missingFileMaps.insert(it.first);
} else {
removed << it.first;
needsSave = true;
}
}
}
if (++idx % 100 == 0) {
outputDirty = true;
logDirect(LogLevel::Error, ".", 1, LogOutput::StdOut);
// error("%d/%d (%.2f%%)", idx, count, (idx / static_cast<double>(count)) * 100.0);
}
}
if (outputDirty)
logDirect(LogLevel::Error, "\n", 1, LogOutput::StdOut);
for (uint32_t r : removed) {
removeDependencies(r);
}
}
forEachSourceList([&dirty, this, &needsSave](SourceList &src) -> VisitResult {
uint32_t fileId = src.fileId();
const Path sourceFile = Location::path(fileId);
if (!sourceFile.isFile()) {
warning() << sourceFile << "seems to have disappeared";
removeDependencies(fileId);
dirty.get()->insertDirtyFile(fileId);
needsSave = true;
return Remove;
}
watchFile(fileId);
return Continue;
});
reloadCompileCommands();
if (needsSave)
save();
startDirtyJobs(dirty.get(), IndexerJob::Dirty|IndexerJob::NoAbort);
// don't want to abort the jobs we just started from reloadCompileCommands
if (!missingFileMaps.isEmpty()) {
SimpleDirty simple;
simple.init(missingFileMaps, shared_from_this());
startDirtyJobs(&simple, IndexerJob::Dirty);
}
return true;
}
bool Project::match(const Match &p, bool *indexed) const
{
Path paths[] = { p.pattern(), p.pattern() };
paths[1].resolve();
const int count = paths[1].compare(paths[0]) ? 2 : 1;
bool ret = false;
const Path resolvedPath = mPath.resolved();
for (int i=0; i<count; ++i) {
const Path &path = paths[i];
const uint32_t id = Location::fileId(path);
if (id && isIndexed(id)) {
if (indexed)
*indexed = true;
return true;
} else if (mFiles.contains(path) || p.match(mPath) || p.match(resolvedPath)) {
if (!indexed)
return true;
ret = true;
}
}
if (indexed)
*indexed = false;
return ret;
}
static const char *severities[] = { "none", "warning", "error", "fixit", "note", "skipped" };
static String formatDiagnostics(const Diagnostics &diagnostics, Flags<QueryMessage::Flag> flags, uint32_t fileId = 0)
{
if (flags & QueryMessage::JSON) {
std::function<Value(uint32_t, Location, const Diagnostic &)> toValue = [&toValue, flags](uint32_t file, Location loc, const Diagnostic &diagnostic) {
Value value;
if (loc.fileId() != file)
value["file"] = loc.path();
value["line"] = loc.line();
value["column"] = loc.column();
if (diagnostic.length > 0)
value["length"] = diagnostic.length;
value["type"] = severities[diagnostic.type];
if (!diagnostic.message.isEmpty())
value["message"] = diagnostic.message;
if (!diagnostic.children.isEmpty()) {
Value &children = value["children"];
for (const auto &c : diagnostic.children) {
children.push_back(toValue(file, c.first, c.second));
}
}
return value;
};
Diagnostics::const_iterator it;
Diagnostics::const_iterator end;
if (fileId) {
it = diagnostics.lower_bound(Location(fileId, 0, 0));
end = diagnostics.lower_bound(Location(fileId + 1, 0, 0));
} else {
it = diagnostics.begin();
end = diagnostics.end();
}
Value val;
Value &checkStyle = val["checkStyle"];
Value *currentFile = 0;
uint32_t lastFileId = 0;
while (it != diagnostics.end()) {
if (it->first.fileId() != lastFileId) {
lastFileId = it->first.fileId();
if (fileId && lastFileId != fileId)
break;
currentFile = &checkStyle[it->first.path()];
}
currentFile->push_back(toValue(lastFileId, it->first, it->second));
++it;
}
return val.toJSON();
}
static const char *header[] = {
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n <checkstyle>",
"(list 'checkstyle "
};
static const char *fileEmpty[] = {
"\n <file name=\"%s\">\n </file>",
"(cons \"%s\" nil)"
};
static const char *startFile[] = {
"\n <file name=\"%s\">",
"(cons \"%s\" (list"
};
static const char *endFile[] = {
"\n </file>",
"))"
};
static const char *trailer[] = {
"\n </checkstyle>",
")"
};
std::function<String(Location , const Diagnostic &, uint32_t)> formatDiagnostic;
enum DiagnosticsFormat {
Diagnostics_XML,
Diagnostics_Elisp
} const format = flags & QueryMessage::Elisp ? Diagnostics_Elisp : Diagnostics_XML;
if (format == Diagnostics_XML) {
formatDiagnostic = [&formatDiagnostic](Location loc, const Diagnostic &diagnostic, uint32_t) {
return String::format<256>("\n <error line=\"%d\" column=\"%d\" %sseverity=\"%s\" message=\"%s\"/>",
loc.line(), loc.column(),
(diagnostic.length <= 0 ? ""
: String::format<32>("length=\"%d\" ", diagnostic.length).constData()),
severities[diagnostic.type], RTags::xmlEscape(diagnostic.message).constData());
};
} else {
formatDiagnostic = [&formatDiagnostic](Location loc, const Diagnostic &diagnostic, uint32_t file) {
String children;
if (!diagnostic.children.isEmpty()) {
children = "(list";
for (const auto &c : diagnostic.children) {
children << ' ' << formatDiagnostic(c.first, c.second, file);
}
children << ")";
} else {
children = "nil";
}
const bool fn = (loc.fileId() != file);
return String::format<256>(" (list %s%s%s %d %d %s '%s \"%s\" %s)",
fn ? "\"" : "",
fn ? loc.path().constData() : "nil",
fn ? "\"" : "",
loc.line(),
loc.column(),
diagnostic.length > 0 ? String::number(diagnostic.length).constData() : "nil",
severities[diagnostic.type],
RTags::elispEscape(diagnostic.message).constData(),
children.constData());
};
}
String ret;
if (fileId) {
const Path path = Location::path(fileId);
ret << header[format];
Diagnostics::const_iterator it = diagnostics.lower_bound(Location(fileId, 0, 0));
bool found = false;
while (it != diagnostics.end() && it->first.fileId() == fileId) {
if (!found) {
found = true;
ret << String::format<256>(startFile[format], path.constData());
}
ret << formatDiagnostic(it->first, it->second, fileId);
++it;
}
if (!found) {
ret << String::format<256>(fileEmpty[format], path.constData());
}
ret << endFile[format] << trailer[format];
} else {
uint32_t lastFileId = 0;
bool first = true;
const Set<uint32_t> active = Server::instance()->activeBuffers();
for (const auto &entry : diagnostics) {
Location loc = entry.first;
if (!active.isEmpty() && !active.contains(loc.fileId()))
continue;
const Diagnostic &diagnostic = entry.second;
if (loc.fileId() != lastFileId) {
if (first) {
ret = header[format];
first = false;
}
if (lastFileId)
ret << endFile[format];
lastFileId = loc.fileId();
ret << String::format<256>(startFile[format], loc.path().constData());
}
ret << formatDiagnostic(loc, diagnostic, lastFileId);
}
if (lastFileId)
ret << endFile[format];
if (!first)
ret << trailer[format];
}
return ret;
}
void Project::onJobFinished(const std::shared_ptr<IndexerJob> &job, const std::shared_ptr<IndexDataMessage> &msg)
{
mBytesWritten += msg->bytesWritten();
std::shared_ptr<IndexerJob> restart;
const uint32_t fileId = msg->fileId();
auto j = mActiveJobs.take(fileId);
if (!j) {
error() << "Couldn't find JobData for" << Location::path(fileId) << msg->id() << job->id << job.get();
return;
} else if (j != job) {
error() << "Wrong IndexerJob for" << Location::path(fileId) << msg->id() << job->id << job.get();
return;
}
const bool success = job->flags & IndexerJob::Complete;
assert(!(job->flags & IndexerJob::Aborted));
assert(((job->flags & (IndexerJob::Complete|IndexerJob::Crashed)) == IndexerJob::Complete)
|| ((job->flags & (IndexerJob::Complete|IndexerJob::Crashed)) == IndexerJob::Crashed));
const auto &options = Server::instance()->options();
if (!success) {
releaseFileIds(job->visited);
}
if (!hasSource(msg->fileId())) {
releaseFileIds(job->visited);
error() << "Can't find source for" << Location::path(fileId);
return;
}
if (!(msg->flags() & IndexDataMessage::ParseFailure)) {
for (uint32_t file : job->visited) {
if (!validate(file, Validate)) {
releaseFileIds(job->visited);
dirty(job->fileId());
return;
}
}
}
const int idx = mJobCounter - mActiveJobs.size();
const Diagnostics changed = updateDiagnostics(msg->diagnostics());
if (!changed.isEmpty() || options.options & Server::Progress) {
log([&](const std::shared_ptr<LogOutput> &output) {
if (output->testLog(RTags::DiagnosticsLevel)) {
QueryMessage::Flag format = QueryMessage::XML;
if (output->flags() & RTagsLogOutput::Elisp) {
// I know this is RTagsLogOutput because it returned
// true for testLog(RTags::DiagnosticsLevel)
format = QueryMessage::Elisp;
}
if (!msg->diagnostics().isEmpty()) {
const String log = formatDiagnostics(changed, format, false);
if (!log.isEmpty()) {
output->log(log);
}
}
if (options.options & Server::Progress) {
if (format == QueryMessage::XML) {
output->vlog("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<progress index=\"%d\" total=\"%d\"></progress>",
idx, mJobCounter);
} else {
output->vlog("(list 'progress %d %d)", idx, mJobCounter);
}
}
}
});
}
Set<uint32_t> visited = msg->visitedFiles();
updateFixIts(visited, msg->fixIts());
updateDependencies(msg);
if (success) {
forEachSources([&msg](Sources &sources) -> VisitResult {
// error() << "finished with" << Location::path(msg->fileId()) << sources.contains(msg->fileId()) << msg->parseTime();
if (sources.contains(msg->fileId())) {
sources[msg->fileId()].parsed = msg->parseTime();
}
return Continue;
});
logDirect(LogLevel::Error, String::format("[%3d%%] %d/%d %s %s. (%s)",
static_cast<int>(round((double(idx) / double(mJobCounter)) * 100.0)), idx, mJobCounter,
String::formatTime(time(0), String::Time).constData(),
msg->message().constData(),
(job->priority == IndexerJob::HeaderError
? "header-error"
: String::format<16>("priority %d", job->priority).constData())),
LogOutput::StdOut|LogOutput::TrailingNewLine);
} else {
assert(msg->indexerJobFlags() & IndexerJob::Crashed);
logDirect(LogLevel::Error, String::format("[%3d%%] %d/%d %s %s indexing crashed.",
static_cast<int>(round((double(idx) / double(mJobCounter)) * 100.0)), idx, mJobCounter,
String::formatTime(time(0), String::Time).constData(),
Location::path(fileId).toTilde().constData()),
LogOutput::StdOut|LogOutput::TrailingNewLine);
}
if (mActiveJobs.isEmpty()) {
save();
double timerElapsed = (mTimer.elapsed() / 1000.0);
const double averageJobTime = timerElapsed / mJobsStarted;
const String m = String::format<1024>("Jobs took %.2fs%s. We're using %lldmb of memory. ",
timerElapsed, mJobsStarted > 1 ? String::format(", (avg %.2fs)", averageJobTime).constData() : "",
static_cast<unsigned long long>(MemoryMonitor::usage() / (1024 * 1024)));
Log(LogLevel::Error, LogOutput::StdOut|LogOutput::TrailingNewLine) << m;
mJobsStarted = mJobCounter = 0;
// error() << "Finished this
} else {
mSaveDirty = true;
}
}
void Project::diagnose(uint32_t fileId)
{
log([&](const std::shared_ptr<LogOutput> &output) {
if (output->testLog(RTags::DiagnosticsLevel)) {
QueryMessage::Flag format = QueryMessage::XML;
if (output->flags() & RTagsLogOutput::Elisp) {
// I know this is RTagsLogOutput because it returned
// true for testLog(RTags::DiagnosticsLevel)
format = QueryMessage::Elisp;
}
const String log = formatDiagnostics(mDiagnostics, format, fileId);
if (!log.isEmpty())
output->log(log);
}
});
}
void Project::diagnoseAll()
{
log([&](const std::shared_ptr<LogOutput> &output) {
if (output->testLog(RTags::DiagnosticsLevel)) {
QueryMessage::Flag format = QueryMessage::XML;
if (output->flags() & RTagsLogOutput::Elisp) {
// I know this is RTagsLogOutput because it returned
// true for testLog(RTags::DiagnosticsLevel)
format = QueryMessage::Elisp;
}
const String log = formatDiagnostics(mDiagnostics, format);
if (!log.isEmpty())
output->log(log);
}
});
}
String Project::diagnosticsToString(Flags<QueryMessage::Flag> flags, uint32_t fileId)
{
return formatDiagnostics(mDiagnostics, flags, fileId);
}
bool Project::save()
{
Path::mkdir(mSourcesFilePath.parentDir(), Path::Recursive);
{
DataFile file(mSourcesFilePath, RTags::SourcesFileVersion);
if (!file.open(DataFile::Write)) {
error("Save error %s: %s", mProjectFilePath.constData(), file.error().constData());
return false;
}
file << mIndexParseData;
}
{
DataFile file(mProjectFilePath, RTags::DatabaseVersion);
if (!file.open(DataFile::Write)) {
error("Save error %s: %s", mProjectFilePath.constData(), file.error().constData());
return false;
}
{
std::lock_guard<std::mutex> lock(mMutex);
if (Sandbox::hasRoot()) {
file << Sandbox::encoded(mVisitedFiles);
} else {
file << mVisitedFiles;
}
}
file << mDiagnostics;
saveDependencies(file, mDependencies);
if (!file.flush()) {
error("Save error %s: %s", mProjectFilePath.constData(), file.error().constData());
return false;
}
}
mSaveDirty = false;
return true;
}
void Project::index(const std::shared_ptr<IndexerJob> &job)
{
const Path sourceFile = job->sourceFile;
static const char *fileFilter = getenv("RTAGS_FILE_FILTER");
if (fileFilter && !strstr(job->sourceFile.constData(), fileFilter)) {
error() << "Not indexing" << job->sourceFile.constData() << "because of file filter"
<< fileFilter;
return;
}
if (Server::instance()->suspended() && hasSource(job->fileId()) && (job->flags & IndexerJob::Compile)) {
return;
}
if (job->flags & IndexerJob::Compile && Server::instance()->options().options & Server::NoFileSystemWatch && hasSource(job->fileId())) {
// When we're not watching the file system, we ignore
// updating compiles. This means that you always have to
// do check-reindex to build existing files!
return;
}
std::shared_ptr<IndexerJob> &ref = mActiveJobs[job->fileId()];
if (ref) {
// warning() << "Aborting a job" << ref.get() << Location::path(job->fileId());
releaseFileIds(ref->visited);
Server::instance()->jobScheduler()->abort(ref);
--mJobCounter;
}
ref = job;
++mJobsStarted;
if (!mJobCounter++) {
mTimer.start();
}
Server::instance()->jobScheduler()->add(job);
}
void Project::onFileModified(const Path &path)
{
debug() << path << "was modified";
onFileAddedOrModified(path);
}
void Project::onFileAdded(const Path &path)
{
debug() << path << "was added";
onFileAddedOrModified(path);
}
void Project::onFileAddedOrModified(const Path &file)
{
const uint32_t fileId = Location::fileId(file);
debug() << file << "was modified" << fileId;
if (!fileId)
return;
// error() << file.fileName() << mCompileCommandsInfos.dir << file;
if (mIndexParseData.compileCommands.contains(fileId)) {
reloadCompileCommands();
return;
}
if (Server::instance()->suspended() || mSuspendedFiles.contains(fileId)) {
warning() << file << "is suspended. Ignoring modification";
return;
}
Server::instance()->jobScheduler()->clearHeaderError(fileId);
if (mPendingDirtyFiles.insert(fileId)) {
mDirtyTimer.restart(DirtyTimeout, Timer::SingleShot);
}
}
void Project::onFileRemoved(const Path &file)
{
const uint32_t fileId = Location::fileId(file);
debug() << file << "was removed" << fileId;
if (!fileId)
return;
if (mIndexParseData.compileCommands.contains(fileId)) {
reloadCompileCommands();
return;
}
removeSource(fileId);
Server::instance()->jobScheduler()->clearHeaderError(fileId);
if (Server::instance()->suspended() || mSuspendedFiles.contains(fileId)) {
warning() << file << "is suspended. Ignoring modification";
return;
}
if (mPendingDirtyFiles.insert(fileId)) {
mDirtyTimer.restart(DirtyTimeout, Timer::SingleShot);
}
}
void Project::onDirtyTimeout(Timer *)
{
Set<uint32_t> dirtyFiles = std::move(mPendingDirtyFiles);
WatcherDirty dirty(shared_from_this(), dirtyFiles);
const int dirtied = startDirtyJobs(&dirty, IndexerJob::Dirty);
debug() << "onDirtyTimeout" << dirtyFiles << dirtied;
}
SourceList Project::sources(uint32_t fileId) const
{
SourceList ret;
forEachSources([&ret, fileId](const Sources &srcs) {
const auto it = srcs.find(fileId);
if (it != srcs.end())
ret += it->second;
return Continue;
});
return ret;
}
bool Project::hasSource(uint32_t fileId) const
{
bool ret = false;
forEachSources([&ret, fileId](const Sources &srcs) {
if (srcs.contains(fileId)) {
ret = true;
return Stop;
}
return Continue;
});
return ret;
}
Set<uint32_t> Project::dependencies(uint32_t fileId, DependencyMode mode) const
{
Set<uint32_t> ret;
ret.insert(fileId);
std::function<void(uint32_t)> fill = [&](uint32_t file) {
if (DependencyNode *node = mDependencies.value(file)) {
const auto &nodes = (mode == ArgDependsOn ? node->includes : node->dependents);
for (const auto &it : nodes) {
if (ret.insert(it.first))
fill(it.first);
}
}
};
fill(fileId);
return ret;
}
bool Project::dependsOn(uint32_t source, uint32_t header) const
{
Set<uint32_t> seen;
std::function<bool(DependencyNode *node)> dep = [&](DependencyNode *node) {
assert(node);
if (!seen.insert(node->fileId))
return false;
if (node->dependents.contains(source))
return true;
for (const std::pair<uint32_t, DependencyNode*> &n : node->dependents) {
if (dep(n.second))
return true;
}
return false;
};
DependencyNode *node = mDependencies.value(header);
return node && dep(node);
}
void Project::removeDependencies(uint32_t fileId)
{
if (DependencyNode *node = mDependencies.take(fileId)) {
for (auto it : node->includes)
it.second->dependents.remove(fileId);