-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
context_manager.dart
1464 lines (1324 loc) · 47.9 KB
/
context_manager.dart
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
// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
library context.directory.manager;
import 'dart:async';
import 'dart:collection';
import 'dart:convert';
import 'dart:core' hide Resource;
import 'package:analysis_server/plugin/analysis/resolver_provider.dart';
import 'package:analysis_server/src/analysis_server.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/instrumentation/instrumentation.dart';
import 'package:analyzer/plugin/options.dart';
import 'package:analyzer/source/analysis_options_provider.dart';
import 'package:analyzer/source/package_map_provider.dart';
import 'package:analyzer/source/package_map_resolver.dart';
import 'package:analyzer/source/path_filter.dart';
import 'package:analyzer/source/pub_package_map_provider.dart';
import 'package:analyzer/source/sdk_ext.dart';
import 'package:analyzer/src/context/context.dart' as context;
import 'package:analyzer/src/generated/engine.dart';
import 'package:analyzer/src/generated/java_engine.dart';
import 'package:analyzer/src/generated/java_io.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/generated/source_io.dart';
import 'package:analyzer/src/task/options.dart';
import 'package:package_config/packages.dart';
import 'package:package_config/packages_file.dart' as pkgfile show parse;
import 'package:package_config/src/packages_impl.dart' show MapPackages;
import 'package:path/path.dart' as pathos;
import 'package:watcher/watcher.dart';
import 'package:yaml/yaml.dart';
/**
* Information tracked by the [ContextManager] for each context.
*/
class ContextInfo {
/**
* The [ContextManager] which is tracking this information.
*/
final ContextManagerImpl contextManager;
/**
* The [Folder] for which this information object is created.
*/
final Folder folder;
/// The [PathFilter] used to filter sources from being analyzed.
final PathFilter pathFilter;
/**
* The enclosed pubspec-based contexts.
*/
final List<ContextInfo> children = <ContextInfo>[];
/**
* The package root for this context, or null if there is no package root.
*/
String packageRoot;
/**
* The [ContextInfo] that encloses this one, or `null` if this is the virtual
* [ContextInfo] object that acts as the ancestor of all other [ContextInfo]
* objects.
*/
ContextInfo parent;
/**
* The package description file path for this context.
*/
String packageDescriptionPath;
/**
* Paths to files which determine the folder disposition and package map.
*
* TODO(paulberry): if any of these files are outside of [folder], they won't
* be watched for changes. I believe the use case for watching these files
* is no longer relevant.
*/
Set<String> _dependencies = new Set<String>();
/**
* The analysis context that was created for the [folder].
*/
AnalysisContext context;
/**
* Map from full path to the [Source] object, for each source that has been
* added to the context.
*/
Map<String, Source> sources = new HashMap<String, Source>();
ContextInfo(ContextManagerImpl contextManager, this.parent, Folder folder,
File packagespecFile, this.packageRoot)
: contextManager = contextManager,
folder = folder,
pathFilter = new PathFilter(
folder.path, null, contextManager.resourceProvider.pathContext) {
packageDescriptionPath = packagespecFile.path;
parent.children.add(this);
}
/**
* Create the virtual [ContextInfo] which acts as an ancestor to all other
* [ContextInfo]s.
*/
ContextInfo._root()
: contextManager = null,
folder = null,
pathFilter = null;
/**
* Iterate through all [children] and their children, recursively.
*/
Iterable<ContextInfo> get descendants sync* {
for (ContextInfo child in children) {
yield child;
yield* child.descendants;
}
}
/**
* Returns `true` if this is a "top level" context, meaning that the folder
* associated with it is not contained within any other folders that have an
* associated context.
*/
bool get isTopLevel => parent.parent == null;
/**
* Returns `true` if [path] is excluded, as it is in one of the children.
*/
bool excludes(String path) {
return children.any((child) {
return child.folder.contains(path);
});
}
/**
* Returns `true` if [resource] is excluded, as it is in one of the children.
*/
bool excludesResource(Resource resource) => excludes(resource.path);
/**
* Return the first [ContextInfo] in [children] whose associated folder is or
* contains [path]. If there is no such [ContextInfo], return `null`.
*/
ContextInfo findChildInfoFor(String path) {
for (ContextInfo info in children) {
if (info.folder.isOrContains(path)) {
return info;
}
}
return null;
}
/**
* Determine if the given [path] is one of the dependencies most recently
* passed to [setDependencies].
*/
bool hasDependency(String path) => _dependencies.contains(path);
/// Returns `true` if [path] should be ignored.
bool ignored(String path) => pathFilter.ignored(path);
/**
* Returns `true` if [path] is the package description file for this context
* (pubspec.yaml or .packages).
*/
bool isPathToPackageDescription(String path) =>
path == packageDescriptionPath;
/**
* Update the set of dependencies for this context.
*/
void setDependencies(Iterable<String> newDependencies) {
_dependencies = newDependencies.toSet();
}
}
/**
* Class that maintains a mapping from included/excluded paths to a set of
* folders that should correspond to analysis contexts.
*/
abstract class ContextManager {
// TODO(brianwilkerson) Support:
// setting the default analysis options
// setting the default content cache
// setting the default SDK
// maintaining AnalysisContext.folderMap (or remove it)
// telling server when a context has been added or removed (see onContextsChanged)
// telling server when a context needs to be re-analyzed
// notifying the client when results should be flushed
// using analyzeFileFunctions to determine which files to analyze
//
// TODO(brianwilkerson) Move this class to a public library.
/**
* Get the callback interface used to create, destroy, and update contexts.
*/
ContextManagerCallbacks get callbacks;
/**
* Set the callback interface used to create, destroy, and update contexts.
*/
void set callbacks(ContextManagerCallbacks value);
/**
* Return the list of excluded paths (folders and files) most recently passed
* to [setRoots].
*/
List<String> get excludedPaths;
/**
* Return the list of included paths (folders and files) most recently passed
* to [setRoots].
*/
List<String> get includedPaths;
/**
* Return a list of all of the contexts reachable from the given
* [analysisRoot] (the context associated with [analysisRoot] and all of its
* descendants).
*/
List<AnalysisContext> contextsInAnalysisRoot(Folder analysisRoot);
/**
* Return `true` if the given absolute [path] is in one of the current
* root folders and is not excluded.
*/
bool isInAnalysisRoot(String path);
/**
* Rebuild the set of contexts from scratch based on the data last sent to
* [setRoots]. Only contexts contained in the given list of analysis [roots]
* will be rebuilt, unless the list is `null`, in which case every context
* will be rebuilt.
*/
void refresh(List<Resource> roots);
/**
* Change the set of paths which should be used as starting points to
* determine the context directories.
*/
void setRoots(List<String> includedPaths, List<String> excludedPaths,
Map<String, String> packageRoots);
}
/**
* Callback interface used by [ContextManager] to (a) request that contexts be
* created, destroyed or updated, (b) inform the client when "pub list"
* operations are in progress, and (c) determine which files should be
* analyzed.
*
* TODO(paulberry): eliminate this interface, and instead have [ContextManager]
* operations return data structures describing how context state should be
* modified.
*/
abstract class ContextManagerCallbacks {
/**
* Create and return a new analysis context, allowing [disposition] to govern
* details of how the context is to be created.
*/
AnalysisContext addContext(Folder folder, FolderDisposition disposition);
/**
* Called when the set of files associated with a context have changed (or
* some of those files have been modified). [changeSet] is the set of
* changes that need to be applied to the context.
*/
void applyChangesToContext(Folder contextFolder, ChangeSet changeSet);
/**
* Called when the ContextManager is about to start computing the package
* map.
*/
void beginComputePackageMap() {
// By default, do nothing.
}
/**
* Called when the ContextManager has finished computing the package map.
*/
void endComputePackageMap() {
// By default, do nothing.
}
/**
* Remove the context associated with the given [folder]. [flushedFiles] is
* a list of the files which will be "orphaned" by removing this context
* (they will no longer be analyzed by any context).
*/
void removeContext(Folder folder, List<String> flushedFiles);
/**
* Return `true` if the given [file] should be analyzed.
*/
bool shouldFileBeAnalyzed(File file);
/**
* Called when the disposition for a context has changed.
*/
void updateContextPackageUriResolver(
Folder contextFolder, FolderDisposition disposition);
}
/**
* Class that maintains a mapping from included/excluded paths to a set of
* folders that should correspond to analysis contexts.
*/
class ContextManagerImpl implements ContextManager {
/**
* The name of the `doc` directory.
*/
static const String DOC_DIR_NAME = 'doc';
/**
* The name of the `lib` directory.
*/
static const String LIB_DIR_NAME = 'lib';
/**
* The name of `packages` folders.
*/
static const String PACKAGES_NAME = 'packages';
/**
* File name of pubspec files.
*/
static const String PUBSPEC_NAME = 'pubspec.yaml';
/**
* File name of package spec files.
*/
static const String PACKAGE_SPEC_NAME = '.packages';
/**
* The [ResourceProvider] using which paths are converted into [Resource]s.
*/
final ResourceProvider resourceProvider;
/**
* The context used to work with file system paths.
*/
pathos.Context pathContext;
/**
* The list of excluded paths (folders and files) most recently passed to
* [setRoots].
*/
List<String> excludedPaths = <String>[];
/**
* The list of included paths (folders and files) most recently passed to
* [setRoots].
*/
List<String> includedPaths = <String>[];
/**
* The map of package roots most recently passed to [setRoots].
*/
Map<String, String> packageRoots = <String, String>{};
/**
* Same as [packageRoots], except that source folders have been normalized
* and non-folders have been removed.
*/
Map<String, String> normalizedPackageRoots = <String, String>{};
/**
* A function that will return a [UriResolver] that can be used to resolve
* `package:` URI's within a given folder, or `null` if we should fall back
* to the standard URI resolver.
*/
final ResolverProvider packageResolverProvider;
/**
* Provider which is used to determine the mapping from package name to
* package folder.
*/
final PubPackageMapProvider _packageMapProvider;
/// Provider of analysis options.
AnalysisOptionsProvider analysisOptionsProvider =
new AnalysisOptionsProvider();
/**
* The instrumentation service used to report instrumentation data.
*/
final InstrumentationService _instrumentationService;
@override
ContextManagerCallbacks callbacks;
/**
* Virtual [ContextInfo] which acts as the ancestor of all other
* [ContextInfo]s.
*/
final ContextInfo _rootInfo = new ContextInfo._root();
/**
* Stream subscription we are using to watch each analysis root directory for
* changes.
*/
final Map<Folder, StreamSubscription<WatchEvent>> _changeSubscriptions =
<Folder, StreamSubscription<WatchEvent>>{};
ContextManagerImpl(this.resourceProvider, this.packageResolverProvider,
this._packageMapProvider, this._instrumentationService) {
pathContext = resourceProvider.pathContext;
}
@override
List<AnalysisContext> contextsInAnalysisRoot(Folder analysisRoot) {
List<AnalysisContext> contexts = <AnalysisContext>[];
ContextInfo innermostContainingInfo =
_getInnermostContextInfoFor(analysisRoot.path);
void addContextAndDescendants(ContextInfo info) {
contexts.add(info.context);
info.children.forEach(addContextAndDescendants);
}
if (innermostContainingInfo != null) {
if (analysisRoot == innermostContainingInfo.folder) {
addContextAndDescendants(innermostContainingInfo);
} else {
for (ContextInfo info in innermostContainingInfo.children) {
if (analysisRoot.isOrContains(info.folder.path)) {
addContextAndDescendants(info);
}
}
}
}
return contexts;
}
/**
* For testing: get the [ContextInfo] object for the given [folder], if any.
*/
ContextInfo getContextInfoFor(Folder folder) {
ContextInfo info = _getInnermostContextInfoFor(folder.path);
if (info != null && folder == info.folder) {
return info;
}
return null;
}
@override
bool isInAnalysisRoot(String path) {
// check if excluded
if (_isExcluded(path)) {
return false;
}
// check if in one of the roots
for (ContextInfo info in _rootInfo.children) {
if (info.folder.contains(path)) {
return true;
}
}
// no
return false;
}
/**
* Process [options] for the given context [info].
*/
void processOptionsForContext(ContextInfo info, Folder folder,
{bool optionsRemoved: false}) {
Map<String, YamlNode> options;
try {
options = analysisOptionsProvider.getOptions(folder);
} catch (e, stacktrace) {
AnalysisEngine.instance.logger.logError(
'Error processing .analysis_options',
new CaughtException(e, stacktrace));
// TODO(pquitslund): contribute plugin that sends error notification on
// options file.
// Related test:
// context_manager_test.test_analysis_options_parse_failure()
// AnalysisEngine.instance.optionsPlugin.optionsProcessors
// .forEach((OptionsProcessor p) => p.onError(e));
}
if (options == null && !optionsRemoved) {
return;
}
// Notify options processors.
AnalysisEngine.instance.optionsPlugin.optionsProcessors
.forEach((OptionsProcessor p) {
try {
p.optionsProcessed(info.context, options);
} catch (e, stacktrace) {
AnalysisEngine.instance.logger.logError(
'Error processing .analysis_options',
new CaughtException(e, stacktrace));
}
});
// In case options files are removed, revert to default options.
if (optionsRemoved) {
info.context.analysisOptions = new AnalysisOptionsImpl();
return;
}
// Analysis options are processed 'in-line'.
var analyzer = options[AnalyzerOptions.analyzer];
if (analyzer is! YamlMap) {
// No options for analyzer.
return;
}
configureContextOptions(info.context, options);
// Set ignore patterns.
YamlList exclude = analyzer[AnalyzerOptions.exclude];
if (exclude != null) {
setIgnorePatternsForContext(info, exclude);
}
}
@override
void refresh(List<Resource> roots) {
// Destroy old contexts
List<ContextInfo> contextInfos = _rootInfo.descendants.toList();
if (roots == null) {
contextInfos.forEach(_destroyContext);
} else {
roots.forEach((Resource resource) {
contextInfos.forEach((ContextInfo contextInfo) {
if (resource is Folder &&
resource.isOrContains(contextInfo.folder.path)) {
_destroyContext(contextInfo);
}
});
});
}
// Rebuild contexts based on the data last sent to setRoots().
setRoots(includedPaths, excludedPaths, packageRoots);
}
/**
* Sets the [ignorePatterns] for the context having info [info].
*/
void setIgnorePatternsForContext(
ContextInfo info, List<String> ignorePatterns) {
info.pathFilter.setIgnorePatterns(ignorePatterns);
}
@override
void setRoots(List<String> includedPaths, List<String> excludedPaths,
Map<String, String> packageRoots) {
this.packageRoots = packageRoots;
// Normalize all package root sources by mapping them to folders on the
// filesystem. Ignore any package root sources that aren't folders.
normalizedPackageRoots = <String, String>{};
packageRoots.forEach((String sourcePath, String targetPath) {
Resource resource = resourceProvider.getResource(sourcePath);
if (resource is Folder) {
normalizedPackageRoots[resource.path] = targetPath;
}
});
List<ContextInfo> contextInfos = _rootInfo.descendants.toList();
// included
Set<Folder> includedFolders = new HashSet<Folder>();
for (int i = 0; i < includedPaths.length; i++) {
String path = includedPaths[i];
Resource resource = resourceProvider.getResource(path);
if (resource is Folder) {
includedFolders.add(resource);
} else if (!resource.exists) {
// Non-existent resources are ignored. TODO(paulberry): we should set
// up a watcher to ensure that if the resource appears later, we will
// begin analyzing it.
} else {
// TODO(scheglov) implemented separate files analysis
throw new UnimplementedError('$path is not a folder. '
'Only support for folder analysis is implemented currently.');
}
}
this.includedPaths = includedPaths;
// excluded
List<String> oldExcludedPaths = this.excludedPaths;
this.excludedPaths = excludedPaths;
// destroy old contexts
for (ContextInfo contextInfo in contextInfos) {
bool isIncluded = includedFolders.any((folder) {
return folder.isOrContains(contextInfo.folder.path);
});
if (!isIncluded) {
_destroyContext(contextInfo);
}
}
// Update package roots for existing contexts
for (ContextInfo info in _rootInfo.descendants) {
String newPackageRoot = normalizedPackageRoots[info.folder.path];
if (info.packageRoot != newPackageRoot) {
info.packageRoot = newPackageRoot;
_recomputeFolderDisposition(info);
}
}
// create new contexts
for (Folder includedFolder in includedFolders) {
bool wasIncluded = contextInfos.any((info) {
return info.folder.isOrContains(includedFolder.path);
});
if (!wasIncluded) {
_changeSubscriptions[includedFolder] =
includedFolder.changes.listen(_handleWatchEvent);
_createContexts(_rootInfo, includedFolder, false);
}
}
// remove newly excluded sources
for (ContextInfo info in _rootInfo.descendants) {
// prepare excluded sources
Map<String, Source> excludedSources = new HashMap<String, Source>();
info.sources.forEach((String path, Source source) {
if (_isExcludedBy(excludedPaths, path) &&
!_isExcludedBy(oldExcludedPaths, path)) {
excludedSources[path] = source;
}
});
// apply exclusion
ChangeSet changeSet = new ChangeSet();
excludedSources.forEach((String path, Source source) {
info.sources.remove(path);
changeSet.removedSource(source);
});
callbacks.applyChangesToContext(info.folder, changeSet);
}
// add previously excluded sources
for (ContextInfo info in _rootInfo.descendants) {
ChangeSet changeSet = new ChangeSet();
_addPreviouslyExcludedSources(
info, changeSet, info.folder, oldExcludedPaths);
callbacks.applyChangesToContext(info.folder, changeSet);
}
}
/**
* Recursively adds all Dart and HTML files to the [changeSet].
*/
void _addPreviouslyExcludedSources(ContextInfo info, ChangeSet changeSet,
Folder folder, List<String> oldExcludedPaths) {
if (info.excludesResource(folder)) {
return;
}
List<Resource> children;
try {
children = folder.getChildren();
} on FileSystemException {
// The folder no longer exists, or cannot be read, to there's nothing to
// do.
return;
}
for (Resource child in children) {
String path = child.path;
// Path is being ignored.
if (info.ignored(path)) {
continue;
}
// add files, recurse into folders
if (child is File) {
// ignore if should not be analyzed at all
if (!callbacks.shouldFileBeAnalyzed(child)) {
continue;
}
// ignore if was not excluded
bool wasExcluded = _isExcludedBy(oldExcludedPaths, path) &&
!_isExcludedBy(excludedPaths, path);
if (!wasExcluded) {
continue;
}
// do add the file
Source source = createSourceInContext(info.context, child);
changeSet.addedSource(source);
info.sources[path] = source;
} else if (child is Folder) {
if (child.shortName == PACKAGES_NAME) {
continue;
}
_addPreviouslyExcludedSources(info, changeSet, child, oldExcludedPaths);
}
}
}
/**
* Recursively adds all Dart and HTML files to the [changeSet].
*/
void _addSourceFiles(ChangeSet changeSet, Folder folder, ContextInfo info) {
if (info.excludesResource(folder) ||
folder.shortName.startsWith('.') ||
_isInTopLevelDocDir(info.folder.path, folder.path)) {
return;
}
List<Resource> children = null;
try {
children = folder.getChildren();
} on FileSystemException {
// The directory either doesn't exist or cannot be read. Either way, there
// are no children that need to be added.
return;
}
for (Resource child in children) {
String path = child.path;
// ignore excluded files or folders
if (_isExcluded(path) || info.excludes(path) || info.ignored(path)) {
continue;
}
// add files, recurse into folders
if (child is File) {
if (callbacks.shouldFileBeAnalyzed(child)) {
Source source = createSourceInContext(info.context, child);
changeSet.addedSource(source);
info.sources[path] = source;
}
} else if (child is Folder) {
String shortName = child.shortName;
if (shortName == PACKAGES_NAME) {
continue;
}
_addSourceFiles(changeSet, child, info);
}
}
}
void _checkForAnalysisOptionsUpdate(
String path, ContextInfo info, ChangeType changeType) {
if (AnalysisEngine.isAnalysisOptionsFileName(path, pathContext)) {
var analysisContext = info.context;
if (analysisContext is context.AnalysisContextImpl) {
processOptionsForContext(info, info.folder,
optionsRemoved: changeType == ChangeType.REMOVE);
analysisContext.invalidateCachedResults();
callbacks.applyChangesToContext(info.folder, new ChangeSet());
}
}
}
void _checkForPackagespecUpdate(
String path, ContextInfo info, Folder folder) {
// Check to see if this is the .packages file for this context and if so,
// update the context's source factory.
if (pathContext.basename(path) == PACKAGE_SPEC_NAME &&
info.isPathToPackageDescription(path)) {
File packagespec = resourceProvider.getFile(path);
if (packagespec.exists) {
Packages packages = _readPackagespec(packagespec);
if (packages != null) {
callbacks.updateContextPackageUriResolver(
folder, new PackagesFileDisposition(packages));
}
}
}
}
/**
* Compute the set of files that are being flushed, this is defined as
* the set of sources in the removed context (context.sources), that are
* orphaned by this context being removed (no other context includes this
* file.)
*/
List<String> _computeFlushedFiles(ContextInfo info) {
AnalysisContext context = info.context;
HashSet<String> flushedFiles = new HashSet<String>();
for (Source source in context.sources) {
flushedFiles.add(source.fullName);
}
for (ContextInfo contextInfo in _rootInfo.descendants) {
AnalysisContext contextN = contextInfo.context;
if (context != contextN) {
for (Source source in contextN.sources) {
flushedFiles.remove(source.fullName);
}
}
}
return flushedFiles.toList(growable: false);
}
/**
* Compute the appropriate [FolderDisposition] for [folder]. Use
* [addDependency] to indicate which files needed to be consulted in order to
* figure out the [FolderDisposition]; these dependencies will be watched in
* order to determine when it is necessary to call this function again.
*
* TODO(paulberry): use [addDependency] for tracking all folder disposition
* dependencies (currently we only use it to track "pub list" dependencies).
*/
FolderDisposition _computeFolderDisposition(
Folder folder, void addDependency(String path), File packagespecFile) {
String packageRoot = normalizedPackageRoots[folder.path];
if (packageRoot != null) {
// TODO(paulberry): We shouldn't be using JavaFile here because it
// makes the code untestable (see dartbug.com/23909).
JavaFile packagesDir = new JavaFile(packageRoot);
Map<String, List<Folder>> packageMap = new Map<String, List<Folder>>();
if (packagesDir.isDirectory()) {
for (JavaFile file in packagesDir.listFiles()) {
// Ensure symlinks in packages directory are canonicalized
// to prevent 'type X cannot be assigned to type X' warnings
String path;
try {
path = file.getCanonicalPath();
} catch (e, s) {
// Ignore packages that do not exist
_instrumentationService.logException(e, s);
continue;
}
Resource res = resourceProvider.getResource(path);
if (res is Folder) {
packageMap[file.getName()] = <Folder>[res];
}
}
return new PackageMapDisposition(packageMap, packageRoot: packageRoot);
}
// The package root does not exist (or is not a folder). Since
// [setRoots] ignores any package roots that don't exist (or aren't
// folders), the only way we should be able to get here is due to a race
// condition. In any case, the package root folder is gone, so we can't
// resolve packages.
return new NoPackageFolderDisposition(packageRoot: packageRoot);
} else {
PackageMapInfo packageMapInfo;
callbacks.beginComputePackageMap();
try {
// Try .packages first.
if (pathContext.basename(packagespecFile.path) == PACKAGE_SPEC_NAME) {
Packages packages = _readPackagespec(packagespecFile);
return new PackagesFileDisposition(packages);
}
if (packageResolverProvider != null) {
UriResolver resolver = packageResolverProvider(folder);
if (resolver != null) {
return new CustomPackageResolverDisposition(resolver);
}
}
ServerPerformanceStatistics.pub.makeCurrentWhile(() {
packageMapInfo = _packageMapProvider.computePackageMap(folder);
});
} finally {
callbacks.endComputePackageMap();
}
for (String dependencyPath in packageMapInfo.dependencies) {
addDependency(dependencyPath);
}
if (packageMapInfo.packageMap == null) {
return new NoPackageFolderDisposition();
}
return new PackageMapDisposition(packageMapInfo.packageMap);
}
}
/**
* Create a new empty context associated with [folder], having parent
* [parent] and using [packagespecFile] to resolve package URI's.
*/
ContextInfo _createContext(
ContextInfo parent, Folder folder, File packagespecFile) {
ContextInfo info = new ContextInfo(this, parent, folder, packagespecFile,
normalizedPackageRoots[folder.path]);
FolderDisposition disposition;
List<String> dependencies = <String>[];
// Next resort to a package uri resolver.
if (disposition == null) {
disposition =
_computeFolderDisposition(folder, dependencies.add, packagespecFile);
}
info.setDependencies(dependencies);
info.context = callbacks.addContext(folder, disposition);
info.context.name = folder.path;
processOptionsForContext(info, folder);
return info;
}
/**
* Potentially create a new context associated with the given [folder].
*
* If there are subfolders with 'pubspec.yaml' files, separate contexts are
* created for them and excluded from the context associated with the
* [folder].
*
* If [withPackageSpecOnly] is `true`, a context will be created only if there
* is a 'pubspec.yaml' or '.packages' file in the [folder].
*
* [parent] should be the parent of any contexts that are created.
*/
void _createContexts(
ContextInfo parent, Folder folder, bool withPackageSpecOnly) {
if (_isExcluded(folder.path) ||
folder.shortName.startsWith('.') ||
folder.shortName == 'packages') {
return;
}
// Decide whether a context needs to be created for [folder] here, and if
// so, create it.
File packageSpec = _findPackageSpecFile(folder);
bool createContext = packageSpec.exists || !withPackageSpecOnly;
if (withPackageSpecOnly &&
packageSpec.exists &&
parent != null &&
parent.ignored(packageSpec.path)) {
// Don't create a context if the package spec is required and ignored.
createContext = false;
}
if (createContext) {
parent = _createContext(parent, folder, packageSpec);
}
// Try to find subfolders with pubspecs or .packages files.
try {
for (Resource child in folder.getChildren()) {
if (child is Folder) {
if (!parent.ignored(child.path)) {
_createContexts(parent, child, true);
}
}
}
} on FileSystemException {
// The directory either doesn't exist or cannot be read. Either way, there
// are no subfolders that need to be added.
}
if (createContext) {
// Now that the child contexts have been created, add the sources that
// don't belong to the children.
ChangeSet changeSet = new ChangeSet();
_addSourceFiles(changeSet, folder, parent);
callbacks.applyChangesToContext(folder, changeSet);
}
}
/**
* Clean up and destroy the context associated with the given folder.
*/
void _destroyContext(ContextInfo info) {
if (_changeSubscriptions.containsKey(info.folder)) {
_changeSubscriptions[info.folder].cancel();
}
callbacks.removeContext(info.folder, _computeFlushedFiles(info));
bool wasRemoved = info.parent.children.remove(info);
assert(wasRemoved);
}
/**
* Extract a new [packagespecFile]-based context from [oldInfo].
*/
void _extractContext(ContextInfo oldInfo, File packagespecFile) {
Folder newFolder = packagespecFile.parent;
ContextInfo newInfo = _createContext(oldInfo, newFolder, packagespecFile);
// prepare sources to extract
Map<String, Source> extractedSources = new HashMap<String, Source>();
oldInfo.sources.forEach((path, source) {
if (newFolder.contains(path)) {
extractedSources[path] = source;
}
});
// update new context
{
ChangeSet changeSet = new ChangeSet();
extractedSources.forEach((path, source) {
newInfo.sources[path] = source;
changeSet.addedSource(source);
});
callbacks.applyChangesToContext(newFolder, changeSet);
}
// update old context
{
ChangeSet changeSet = new ChangeSet();
extractedSources.forEach((path, source) {
oldInfo.sources.remove(path);
changeSet.removedSource(source);
});
callbacks.applyChangesToContext(oldInfo.folder, changeSet);
}
// TODO(paulberry): every context that was previously a child of oldInfo is
// is still a child of oldInfo. This is wrong--some of them ought to be
// adopted by newInfo now.
}
/**
* Find the file that should be used to determine whether a context needs to
* be created here--this is either the ".packages" file or the "pubspec.yaml"
* file.
*/
File _findPackageSpecFile(Folder folder) {
// Decide whether a context needs to be created for [folder] here, and if
// so, create it.
File packageSpec;
// Start by looking for .packages.