-
Notifications
You must be signed in to change notification settings - Fork 226
/
Copy pathentrypoint.dart
1581 lines (1459 loc) · 55.2 KB
/
entrypoint.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) 2012, 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.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'package:collection/collection.dart';
import 'package:path/path.dart' as p;
import 'package:pool/pool.dart';
import 'package:pub_semver/pub_semver.dart';
import 'package:source_span/source_span.dart';
import 'package:yaml/yaml.dart';
import 'package:yaml_edit/yaml_edit.dart';
import 'command_runner.dart';
import 'dart.dart' as dart;
import 'exceptions.dart';
import 'executable.dart';
import 'io.dart';
import 'language_version.dart';
import 'lock_file.dart';
import 'log.dart' as log;
import 'package.dart';
import 'package_config.dart';
import 'package_graph.dart';
import 'package_name.dart';
import 'pubspec.dart';
import 'pubspec_utils.dart';
import 'sdk.dart';
import 'sdk/flutter.dart';
import 'solver.dart';
import 'solver/report.dart';
import 'solver/solve_suggestions.dart';
import 'source/cached.dart';
import 'source/hosted.dart';
import 'source/root.dart';
import 'source/unknown.dart';
import 'system_cache.dart';
import 'utils.dart';
/// The context surrounding the workspace pub is operating on.
///
/// Pub operates over a directed graph of dependencies that starts at a root
/// "entrypoint" package. This is typically the package where the current
/// working directory is located.
///
/// An entrypoint knows the [workspaceRoot] package it is associated with and is
/// responsible for managing the package config (.dart_tool/package_config.json)
/// and lock file (pubspec.lock) for it.
///
/// While entrypoints are typically applications, a pure library package may end
/// up being used as an entrypoint while under development. Also, a single
/// package may be used as an entrypoint in one context but not in another. For
/// example, a package that contains a reusable library may not be the
/// entrypoint when used by an app, but may be the entrypoint when you're
/// running its tests.
class Entrypoint {
/// The directory where this entrypoint is created.
///
/// [workspaceRoot] will be the package in the nearest parent directory that
/// has `resolution: null`
final String workingDir;
/// Finds the [workspaceRoot] and [workPackage] based on [workingDir].
///
/// Works by iterating through the parent directories from [workingDir].
///
/// [workPackage] is the package of first dir we find with a `pubspec.yaml`
/// file.
///
/// [workspaceRoot] is the package of the first dir we find with a
/// `pubspec.yaml` that does not have `resolution: workspace`.
///
/// [workPackage] and [workspaceRoot] can be the same. And will always be the
/// same when no `workspace` is involved.
/// =
/// If [workingDir] doesn't exist, [fail].
///
/// If no `pubspec.yaml` is found without `resolution: workspace` we [fail].
static ({Package root, Package work}) _loadWorkspace(
String workingDir,
SystemCache cache,
) {
if (!dirExists(workingDir)) {
fail('The directory `$workingDir` does not exist.');
}
// Keep track of all the pubspecs met when walking up the file system.
// The first of these is the workingPackage.
final pubspecsMet = <String, Pubspec>{};
for (final dir in parentDirs(workingDir)) {
final Pubspec pubspec;
try {
pubspec = Pubspec.load(
dir,
cache.sources,
containingDescription: RootDescription(dir),
allowOverridesFile: true,
);
} on FileException {
continue;
}
pubspecsMet[p.canonicalize(dir)] = pubspec;
final Package root;
if (pubspec.resolution == Resolution.none) {
root = Package.load(
dir,
loadPubspec:
(path, {expectedName, required withPubspecOverrides}) =>
pubspecsMet[p.canonicalize(path)] ??
Pubspec.load(
path,
cache.sources,
expectedName: expectedName,
allowOverridesFile: withPubspecOverrides,
containingDescription: RootDescription(path),
),
withPubspecOverrides: true,
);
for (final package in root.transitiveWorkspace) {
if (identical(pubspecsMet.entries.first.value, package.pubspec)) {
validateWorkspace(root);
return (root: root, work: package);
}
}
assert(false);
}
}
if (pubspecsMet.isEmpty) {
final dir = p.normalize(p.absolute(workingDir));
throw FileException(
'Found no `pubspec.yaml` file in `$dir` or parent directories',
p.join(workingDir, 'pubspec.yaml'),
);
} else {
final firstEntry = pubspecsMet.entries.first;
throw FileException(
'''
Found a pubspec.yaml at ${firstEntry.key}. But it has resolution `${firstEntry.value.resolution.name}`.
But found no workspace root including it in parent directories.
See $workspacesDocUrl for more information.''',
p.join(workingDir, 'pubspec.yaml'),
);
}
}
/// Stores the result of [_loadWorkspace].
/// Only access via [workspaceRoot], [workPackage] and [canFindWorkspaceRoot].
({Package root, Package work})? _packages;
/// Only access via [workspaceRoot], [workPackage] and [canFindWorkspaceRoot].
({Package root, Package work}) get _getPackages =>
_packages ??= _loadWorkspace(workingDir, cache);
/// The root package this entrypoint is associated with.
///
/// For a global package, this is the activated package.
Package get workspaceRoot => _getPackages.root;
/// True if we can find a `pubspec.yaml` to resolve in [workingDir] or any
/// parent directory.
bool get canFindWorkspaceRoot {
try {
_getPackages;
return true;
} on FileException {
return false;
}
}
/// The "focus" package that the current command should act upon.
///
/// It will be the package in the nearest parent directory to `workingDir`.
/// Example: if a workspace looks like this:
///
/// foo/ pubspec.yaml # contains `workspace: [- 'bar'] bar/ pubspec.yaml #
/// contains `resolution: workspace`.
///
/// Running `pub add` in `foo/bar` will have bar as workPackage, and add
/// dependencies to `foo/bar/pubspec.yaml`.
///
/// Running `pub add` in `foo` will have foo as workPackage, and add
/// dependencies to `foo/pubspec.yaml`.
Package get workPackage => _getPackages.work;
/// The system-wide cache which caches packages that need to be fetched over
/// the network.
final SystemCache cache;
/// Whether this entrypoint exists within the package cache.
bool get isCached => p.isWithin(cache.rootDir, workingDir);
/// Whether this is an entrypoint for a globally-activated package.
///
/// False for path-activated global packages.
final bool isCachedGlobal;
/// The lockfile for the entrypoint.
///
/// If not provided to the entrypoint, it will be loaded lazily from disk.
LockFile get lockFile => _lockFile ??= _loadLockFile(lockFilePath, cache);
static LockFile _loadLockFile(String lockFilePath, SystemCache cache) {
if (!fileExists(lockFilePath)) {
return LockFile.empty();
} else {
try {
return LockFile.load(lockFilePath, cache.sources);
} on SourceSpanException catch (e) {
throw SourceSpanApplicationException(
e.message,
e.span,
explanation: 'Failed parsing lock file:',
hint:
'Consider deleting the file and running '
'`$topLevelProgram pub get` to recreate it.',
);
}
}
}
LockFile? _lockFile;
/// The `.dart_tool/package_config.json` package-config of this entrypoint.
///
/// Lazily initialized. Will throw [DataException] when initializing if the
/// `.dart_tool/packageConfig.json` file doesn't exist or has a bad format .
PackageConfig get packageConfig =>
_packageConfig ??= _loadPackageConfig(packageConfigPath);
PackageConfig? _packageConfig;
static PackageConfig _loadPackageConfig(String packageConfigPath) {
Never badPackageConfig() {
dataError(
'The "$packageConfigPath" file is not recognized by '
'"pub" version, please run "$topLevelProgram pub get".',
);
}
final String packageConfigRaw;
try {
packageConfigRaw = readTextFile(packageConfigPath);
} on FileException {
dataError(
'The "$packageConfigPath" file does not exist, '
'please run "$topLevelProgram pub get".',
);
}
final PackageConfig result;
try {
result = PackageConfig.fromJson(json.decode(packageConfigRaw) as Object?);
} on FormatException {
badPackageConfig();
}
// Version 2 is the initial version number for `package_config.json`,
// because `.packages` was version 1 (even if it was a different file).
// If the version is different from 2, then it must be a newer incompatible
// version, hence, the user should run `pub get` with the downgraded SDK.
if (result.configVersion != 2) {
badPackageConfig();
}
return result;
}
/// The package graph for the application and all of its transitive
/// dependencies.
///
/// Throws a [DataException] if the `.dart_tool/package_config.json` file
/// isn't up-to-date relative to the pubspec and the lockfile.
Future<PackageGraph> get packageGraph =>
_packageGraph ??= _createPackageGraph();
Future<PackageGraph> _createPackageGraph() async {
// TODO(sigurdm): consider having [ensureUptoDate] and [acquireDependencies]
// return the package-graph, such it by construction will always made from
// an up-to-date package-config.
await ensureUpToDate(workspaceRoot.dir, cache: cache);
final packages = {
for (var packageEntry in packageConfig.nonInjectedPackages)
packageEntry.name: Package.load(
packageEntry.resolvedRootDir(packageConfigPath),
expectedName: packageEntry.name,
loadPubspec: Pubspec.loadRootWithSources(cache.sources),
),
};
packages[workspaceRoot.name] = workspaceRoot;
return PackageGraph(this, packages);
}
Future<PackageGraph>? _packageGraph;
/// The path to the entrypoint's ".dart_tool/package_config.json" file
/// relative to the current working directory .
late final String packageConfigPath = p.relative(
p.normalize(p.join(workspaceRoot.dir, '.dart_tool', 'package_config.json')),
);
late final String packageGraphPath = p.relative(
p.normalize(p.join(workspaceRoot.dir, '.dart_tool', 'package_graph.json')),
);
/// The path to the entrypoint workspace's lockfile.
String get lockFilePath =>
p.normalize(p.join(workspaceRoot.dir, 'pubspec.lock'));
/// The path to the directory containing dependency executable snapshots.
String get _snapshotPath => p.join(
isCachedGlobal
? workspaceRoot.dir
: p.join(workspaceRoot.dir, '.dart_tool/pub'),
'bin',
);
Entrypoint._(
this.workingDir,
this._lockFile,
this._example,
this._packageGraph,
this.cache,
this._packages,
this.isCachedGlobal,
);
/// An entrypoint for the workspace containing [workingDir]/
///
/// If [checkInCache] is `true` (the default) an error will be thrown if
/// [workingDir] is located inside [cache]`.rootDir`.
Entrypoint(this.workingDir, this.cache, {bool checkInCache = true})
: isCachedGlobal = false {
if (checkInCache && p.isWithin(cache.rootDir, workingDir)) {
fail('Cannot operate on packages inside the cache.');
}
}
/// Creates an entrypoint at the same location, but with each pubspec in
/// [updatedPubspecs] replacing the with one for the corresponding package.
Entrypoint withUpdatedRootPubspecs(Map<Package, Pubspec> updatedPubspecs) {
final newWorkspaceRoot = workspaceRoot.transformWorkspace(
(package) => updatedPubspecs[package] ?? package.pubspec,
);
final newWorkPackage = newWorkspaceRoot.transitiveWorkspace.firstWhere(
(package) => package.dir == workPackage.dir,
);
return Entrypoint._(workingDir, _lockFile, _example, _packageGraph, cache, (
root: newWorkspaceRoot,
work: newWorkPackage,
), isCachedGlobal);
}
/// Creates an entrypoint at the same location, that will use [pubspec] for
/// resolution of the [workPackage].
Entrypoint withWorkPubspec(Pubspec pubspec) {
return withUpdatedRootPubspecs({workPackage: pubspec});
}
/// Creates an entrypoint given package and lockfile objects.
/// If a SolveResult is already created it can be passed as an optimization.
Entrypoint.global(
Package package,
this._lockFile,
this.cache, {
SolveResult? solveResult,
}) : _packages = (root: package, work: package),
workingDir = package.dir,
isCachedGlobal = true {
if (solveResult != null) {
_packageGraph = Future.value(
PackageGraph.fromSolveResult(this, solveResult),
);
}
}
/// Gets the [Entrypoint] package for the current working directory.
///
/// This will be null if the example folder doesn't have a `pubspec.yaml`.
Entrypoint? get example {
if (_example != null) return _example;
if (!fileExists(workspaceRoot.path('example', 'pubspec.yaml'))) {
return null;
}
return _example = Entrypoint(workspaceRoot.path('example'), cache);
}
Entrypoint? _example;
/// Writes the .dart_tool/package_config.json file and workspace references to
/// it.
///
/// Also writes the .dart_tool.package_graph.json file.
///
/// If the workspace is non-trivial: For each package in the workspace write:
/// `.dart_tool/pub/workspace_ref.json` with a pointer to the workspace root
/// package dir.
Future<void> writePackageConfigFiles() async {
ensureDir(p.dirname(packageConfigPath));
writeTextFile(
packageConfigPath,
await _packageConfigFile(
cache,
entrypointSdkConstraint:
workspaceRoot
.pubspec
.sdkConstraints[sdk.identifier]
?.effectiveConstraint,
),
);
writeTextFile(packageGraphPath, await _packageGraphFile(cache));
if (workspaceRoot.workspaceChildren.isNotEmpty) {
for (final package in workspaceRoot.transitiveWorkspace) {
final workspaceRefDir = p.join(package.dir, '.dart_tool', 'pub');
final workspaceRefPath = p.join(workspaceRefDir, 'workspace_ref.json');
ensureDir(workspaceRefDir);
final relativeRootPath = p.relative(
workspaceRoot.dir,
from: workspaceRefDir,
);
final workspaceRef = const JsonEncoder.withIndent(
' ',
).convert({'workspaceRoot': relativeRootPath});
writeTextFile(workspaceRefPath, '$workspaceRef\n');
}
}
}
Future<String> _packageGraphFile(SystemCache cache) async {
return const JsonEncoder.withIndent(' ').convert({
'roots':
workspaceRoot.transitiveWorkspace.map((p) => p.name).toList()..sort(),
'packages': [
for (final p in workspaceRoot.transitiveWorkspace)
{
'name': p.name,
'version': p.version.toString(),
'dependencies': p.dependencies.keys.toList()..sort(),
'devDependencies': p.devDependencies.keys.toList()..sort(),
},
for (final p in lockFile.packages.values)
{
'name': p.name,
'version': p.version.toString(),
'dependencies':
(await cache.describe(p)).dependencies.keys.toList()..sort(),
},
],
'configVersion': 1,
});
}
/// Returns the contents of the `.dart_tool/package_config` file generated
/// from this entrypoint based on [lockFile].
///
/// If [isCachedGlobal] no entry will be created for [workspaceRoot].
Future<String> _packageConfigFile(
SystemCache cache, {
VersionConstraint? entrypointSdkConstraint,
}) async {
final entries = <PackageConfigEntry>[];
if (lockFile.packages.isNotEmpty) {
final relativeFromPath = p.join(workspaceRoot.dir, '.dart_tool');
for (final name in lockFile.packages.keys.sorted()) {
final id = lockFile.packages[name]!;
final rootPath = cache.getDirectory(id, relativeFrom: relativeFromPath);
final pubspec = await cache.describe(id);
entries.add(
PackageConfigEntry(
name: name,
rootUri: p.toUri(rootPath),
packageUri: p.toUri('lib/'),
languageVersion: pubspec.languageVersion,
),
);
}
}
if (!isCachedGlobal) {
/// Run through the entire workspace transitive closure and add an entry
/// for each package.
for (final package in workspaceRoot.transitiveWorkspace) {
entries.add(
PackageConfigEntry(
name: package.name,
rootUri: p.toUri(
p.relative(
package.dir,
from: p.join(workspaceRoot.dir, '.dart_tool'),
),
),
packageUri: p.toUri('lib/'),
languageVersion: package.pubspec.languageVersion,
),
);
}
}
final packageConfig = PackageConfig(
configVersion: 2,
packages: entries,
generated: DateTime.now(),
generator: 'pub',
generatorVersion: sdk.version,
additionalProperties: {
if (FlutterSdk().isAvailable) ...{
'flutterRoot':
p.toUri(p.absolute(FlutterSdk().rootDirectory!)).toString(),
'flutterVersion': FlutterSdk().version.toString(),
},
'pubCache': p.toUri(p.absolute(cache.rootDir)).toString(),
},
);
final jsonText = const JsonEncoder.withIndent(
' ',
).convert(packageConfig.toJson());
return '$jsonText\n';
}
/// Gets all dependencies of the [workspaceRoot] package.
///
/// Performs version resolution according to [SolveType].
///
/// The iterable [unlock] specifies the list of packages whose versions can be
/// changed even if they are locked in the pubspec.lock file.
///
/// Shows a report of the changes made relative to the previous lockfile. If
/// this is an upgrade or downgrade, all transitive dependencies are shown in
/// the report. Otherwise, only dependencies that were changed are shown. If
/// [dryRun] is `true`, no physical changes are made.
///
/// If [precompile] is `true` (the default), this snapshots dependencies'
/// executables.
///
/// if [summaryOnly] is `true` only success or failure will be
/// shown --- in case of failure, a reproduction command is shown.
///
/// Updates [lockFile] and [packageGraph] accordingly.
///
/// If [enforceLockfile] is true no changes to the current lockfile are
/// allowed. Instead the existing lockfile is loaded, verified against
/// pubspec.yaml and all dependencies downloaded.
Future<void> acquireDependencies(
SolveType type, {
Iterable<String> unlock = const [],
bool dryRun = false,
bool precompile = false,
bool summaryOnly = false,
bool enforceLockfile = false,
}) async {
workspaceRoot; // This will throw early if pubspec.yaml could not be found.
summaryOnly = summaryOnly || _summaryOnlyEnvironment;
final suffix =
workspaceRoot.dir == '.'
? ''
: ' in `${workspaceRoot.presentationDir}`';
if (enforceLockfile && !fileExists(lockFilePath)) {
throw ApplicationException('''
Retrieving dependencies failed$suffix.
Cannot do `--enforce-lockfile` without an existing `pubspec.lock`.
Try running `$topLevelProgram pub get` to create `$lockFilePath`.''');
}
SolveResult result;
try {
result = await log.progress('Resolving dependencies$suffix', () async {
// TODO(https://github.com/dart-lang/pub/issues/4127): Check this for
// all workspace pubspecs.
_checkSdkConstraint(workspaceRoot.pubspecPath, workspaceRoot.pubspec);
return resolveVersions(
type,
cache,
workspaceRoot,
lockFile: lockFile,
unlock: unlock,
);
});
} on SolveFailure catch (e) {
throw SolveFailure(
e.incompatibility,
suggestions: await suggestResolutionAlternatives(
this,
type,
e.incompatibility,
unlock,
cache,
),
);
}
// We have to download files also with --dry-run to ensure we know the
// archive hashes for downloaded files.
final newLockFile = await result.downloadCachedPackages(cache);
final report = SolveReport(
type,
workspaceRoot.presentationDir,
workspaceRoot.pubspec,
workspaceRoot.allOverridesInWorkspace,
lockFile,
newLockFile,
result.availableVersions,
cache,
dryRun: dryRun,
enforceLockfile: enforceLockfile,
quiet: summaryOnly,
);
await report.show(summary: true);
if (enforceLockfile && !lockFile.samePackageIds(newLockFile)) {
dataError('''
Unable to satisfy `${workspaceRoot.pubspecPath}` using `$lockFilePath`$suffix.
To update `$lockFilePath` run `$topLevelProgram pub get`$suffix without
`--enforce-lockfile`.''');
}
if (!(dryRun || enforceLockfile)) {
newLockFile.writeToFile(lockFilePath, cache);
}
_lockFile = newLockFile;
if (!dryRun) {
_removeStrayLockAndConfigFiles();
/// Build a package graph from the version solver results so we don't
/// have to reload and reparse all the pubspecs.
_packageGraph = Future.value(PackageGraph.fromSolveResult(this, result));
await writePackageConfigFiles();
try {
if (precompile) {
await precompileExecutables();
} else {
await _deleteExecutableSnapshots();
}
} catch (error, stackTrace) {
// Just log exceptions here. Since the method is just about acquiring
// dependencies, it shouldn't fail unless that fails.
log.exception(error, stackTrace);
}
}
}
/// All executables that should be snapshotted from this entrypoint.
///
/// This is all executables in direct dependencies.
/// that don't transitively depend on `this` or on a mutable dependency.
///
/// Except globally activated packages they should precompile executables from
/// the package itself if they are immutable.
Future<List<Executable>> get _builtExecutables async {
final graph = await packageGraph;
final r =
workspaceRoot.immediateDependencies.keys.expand((packageName) {
final package = graph.packages[packageName]!;
return package.executablePaths.map(
(path) => Executable(packageName, path),
);
}).toList();
return r;
}
/// Precompiles all [_builtExecutables].
Future<void> precompileExecutables() async {
final executables = await _builtExecutables;
if (executables.isEmpty) return;
await log.progress('Building package executables', () async {
if (isCachedGlobal) {
/// Global snapshots might linger in the cache if we don't remove old
/// snapshots when it is re-activated.
cleanDir(_snapshotPath);
} else {
ensureDir(_snapshotPath);
}
// Don't do more than `Platform.numberOfProcessors - 1` compilations
// concurrently. Though at least one.
final pool = Pool(max(Platform.numberOfProcessors - 1, 1));
return waitAndPrintErrors(
executables.map((executable) async {
await pool.withResource(() async {
return _precompileExecutable(executable);
});
}),
);
});
}
/// Precompiles [executable] to a snapshot.
///
/// The [additionalSources], if provided, instruct the compiler to include
/// additional source files into compilation even if they are not referenced
/// from the main library.
///
/// The [nativeAssets], if provided, instruct the compiler include a native
/// assets map.
Future<void> precompileExecutable(
Executable executable, {
List<String> additionalSources = const [],
String? nativeAssets,
}) async {
await log.progress('Building package executable', () async {
ensureDir(p.dirname(pathOfSnapshot(executable)));
return await _precompileExecutable(
executable,
additionalSources: additionalSources,
nativeAssets: nativeAssets,
);
});
}
Future<void> _precompileExecutable(
Executable executable, {
List<String> additionalSources = const [],
String? nativeAssets,
}) async {
final package = executable.package;
await dart.precompile(
executablePath: executable.resolve(packageConfig, packageConfigPath),
outputPath: pathOfSnapshot(executable),
packageConfigPath: packageConfigPath,
name: '$package:${p.basenameWithoutExtension(executable.relativePath)}',
additionalSources: additionalSources,
nativeAssets: nativeAssets,
);
cache.maintainCache();
}
/// The location of the snapshot of the dart program at [executable]
/// will be stored here.
///
/// We use the sdk version to make sure we don't run snapshots from a
/// different sdk.
String pathOfSnapshot(Executable executable) {
return isCachedGlobal
? executable.pathOfGlobalSnapshot(workspaceRoot.dir)
: executable.pathOfSnapshot(workspaceRoot.dir);
}
/// Deletes cached snapshots that are from a different sdk.
Future<void> _deleteExecutableSnapshots() async {
if (!dirExists(_snapshotPath)) return;
// Clean out any outdated snapshots.
for (var entry in listDir(_snapshotPath)) {
if (!fileExists(entry)) {
// Not a file
continue;
}
if (!entry.endsWith('${sdk.version}.snapshot')) {
// Made with a different sdk version. Clean it up.
deleteEntry(entry);
}
}
}
/// Does a fast-pass check to see if the resolution is up-to-date. If not, run
/// a resolution with `pub get` semantics.
///
/// If [summaryOnly] is `true` (the default) only a short summary is shown of
/// the solve.
///
/// If [onlyOutputWhenTerminal] is `true` (the default) there will be no
/// output if no terminal is attached.
///
/// When succesfull returns the found/created `PackageConfig` and the
/// directory containing it.
static Future<({PackageConfig packageConfig, String rootDir})> ensureUpToDate(
String dir, {
required SystemCache cache,
bool summaryOnly = true,
bool onlyOutputWhenTerminal = true,
}) async {
late final wasRelative = p.isRelative(dir);
String relativeIfNeeded(String path) =>
wasRelative ? p.relative(path) : path;
/// Whether the lockfile is out of date with respect to the dependencies'
/// pubspecs.
///
/// If any mutable pubspec contains dependencies that are not in the
/// lockfile or that don't match what's in there, this will return `false`.
bool isLockFileUpToDate(
LockFile lockFile,
Package root, {
required String lockFilePath,
}) {
/// Returns whether the locked version of [dep] matches the dependency.
bool isDependencyUpToDate(PackageRange dep) {
if (dep.name == root.name) return true;
final locked = lockFile.packages[dep.name];
return locked != null && dep.allows(locked);
}
for (final MapEntry(key: sdkName, value: constraint)
in lockFile.sdkConstraints.entries) {
final sdk = sdks[sdkName];
if (sdk == null) {
log.fine('Unknown sdk $sdkName in `$lockFilePath`');
return false;
}
if (!sdk.isAvailable) {
log.fine('sdk: ${sdk.name} not available');
return false;
}
final sdkVersion = sdk.version;
if (sdkVersion != null) {
if (!constraint.effectiveConstraint.allows(sdkVersion)) {
log.fine(
'`$lockFilePath` requires $sdkName $constraint. '
'Current version is $sdkVersion',
);
return false;
}
}
}
if (!root.immediateDependencies.values.every(isDependencyUpToDate)) {
final pubspecPath = p.normalize(p.join(dir, 'pubspec.yaml'));
log.fine(
'The $pubspecPath file has changed since the $lockFilePath file '
'was generated.',
);
return false;
}
// Check that uncached dependencies' pubspecs are also still satisfied,
// since they're mutable and may have changed since the last get.
for (var id in lockFile.packages.values) {
final source = id.source;
if (source is CachedSource) continue;
try {
if (cache
.load(id)
.dependencies
.values
.every(
(dep) =>
root.allOverridesInWorkspace.containsKey(dep.name) ||
isDependencyUpToDate(dep),
)) {
continue;
}
} on FileException {
// If we can't load the pubspec, the user needs to re-run "pub get".
}
final relativePubspecPath = p.join(
cache.getDirectory(id, relativeFrom: '.'),
'pubspec.yaml',
);
log.fine(
'$relativePubspecPath has '
'changed since the $lockFilePath file was generated.',
);
return false;
}
return true;
}
/// Whether or not the `.dart_tool/package_config.json` file is
/// out of date with respect to the lockfile.
bool isPackageConfigUpToDate(
PackageConfig packageConfig,
LockFile lockFile,
Package root, {
required String packageConfigPath,
required String lockFilePath,
}) {
/// Determines if [lockFile] agrees with the given [packagePathsMapping].
///
/// The [packagePathsMapping] is a mapping from package names to paths
/// where the packages are located. (The library is located under `lib/`
/// relative to the path given).
bool isPackagePathsMappingUpToDateWithLockfile(
Map<String, String> packagePathsMapping, {
required String lockFilePath,
required String packageConfigPath,
}) {
// Check that [packagePathsMapping] does not contain more packages than
// what is required. This could lead to import statements working, when
// they are not supposed to work.
final hasExtraMappings =
!packagePathsMapping.keys.every((packageName) {
return packageName == root.name ||
lockFile.packages.containsKey(packageName);
});
if (hasExtraMappings) {
return false;
}
// Check that all packages in the [lockFile] are reflected in the
// [packagePathsMapping].
return lockFile.packages.values.every((lockFileId) {
// It's very unlikely that the lockfile is invalid here, but it's not
// impossible—for example, the user may have a very old application
// package with a checked-in lockfile that's newer than the pubspec,
// but that contains SDK dependencies.
if (lockFileId.source is UnknownSource) return false;
final packagePath = packagePathsMapping[lockFileId.name];
if (packagePath == null) {
return false;
}
final source = lockFileId.source;
final lockFilePackagePath = root.path(
cache.getDirectory(lockFileId, relativeFrom: root.dir),
);
// Make sure that the packagePath agrees with the lock file about the
// path to the package.
if (p.normalize(packagePath) != p.normalize(lockFilePackagePath)) {
return false;
}
// For cached sources, make sure the directory exists and looks like a
// package. This is also done by [_arePackagesAvailable] but that may
// not be run if the lockfile is newer than the pubspec.
if (source is CachedSource && !dirExists(lockFilePackagePath) ||
!fileExists(p.join(lockFilePackagePath, 'pubspec.yaml'))) {
return false;
}
return true;
});
}
final packagePathsMapping = <String, String>{};
final packagesToCheck = packageConfig.nonInjectedPackages;
for (final pkg in packagesToCheck) {
// Pub always makes a packageUri of lib/
if (pkg.packageUri == null || pkg.packageUri.toString() != 'lib/') {
log.fine(
'The "$packageConfigPath" file '
'is not recognized by this pub version.',
);
return false;
}
packagePathsMapping[pkg.name] = root.path(
'.dart_tool',
p.fromUri(pkg.rootUri),
);
}
if (!isPackagePathsMappingUpToDateWithLockfile(
packagePathsMapping,
packageConfigPath: packageConfigPath,
lockFilePath: lockFilePath,
)) {
log.fine(
'The $lockFilePath file has changed since the '
'$packageConfigPath file '
'was generated, please run "$topLevelProgram pub get" again.',
);
return false;
}
// Check if language version specified in the `package_config.json` is
// correct. This is important for path dependencies as these can mutate.
for (final pkg in packageConfig.nonInjectedPackages) {
if (pkg.name == root.name) continue;
final id = lockFile.packages[pkg.name];
if (id == null) {
assert(
false,
'unnecessary package_config.json entries should be forbidden by '
'_isPackagePathsMappingUpToDateWithLockfile',
);
continue;
}
// If a package is cached, then it's universally immutable and we need
// not check if the language version is correct.
final source = id.source;
if (source is CachedSource) {
continue;
}
try {
// Load `pubspec.yaml` and extract language version to compare with
// the language version from `package_config.json`.
final languageVersion = cache.load(id).pubspec.languageVersion;
if (pkg.languageVersion != languageVersion) {
final relativePubspecPath = p.join(
cache.getDirectory(id, relativeFrom: '.'),
'pubspec.yaml',