/
build_script_generate.dart
385 lines (349 loc) · 14.3 KB
/
build_script_generate.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
// Copyright (c) 2017, 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 'package:analyzer/dart/analysis/features.dart';
import 'package:analyzer/dart/analysis/utilities.dart';
import 'package:build/build.dart'
show AssetId, AssetNotFoundException, AssetReader, BuilderOptions;
import 'package:build_config/build_config.dart';
import 'package:build_runner_core/build_runner_core.dart';
import 'package:code_builder/code_builder.dart';
import 'package:dart_style/dart_style.dart';
import 'package:graphs/graphs.dart';
import 'package:logging/logging.dart';
import 'package:package_config/package_config.dart' show LanguageVersion;
import 'package:path/path.dart' as p;
import 'package:pub_semver/pub_semver.dart';
import '../package_graph/build_config_overrides.dart';
import 'builder_ordering.dart';
const scriptLocation = '$entryPointDir/build.dart';
const scriptKernelLocation = '$scriptLocation$scriptKernelSuffix';
const scriptKernelSuffix = '.dill';
const scriptKernelCachedLocation =
'$scriptKernelLocation$scriptKernelCachedSuffix';
const scriptKernelCachedSuffix = '.cached';
final _log = Logger('Entrypoint');
Future<String> generateBuildScript() =>
logTimedAsync(_log, 'Generating build script', _generateBuildScript);
Future<String> _generateBuildScript() async {
final info = await findBuildScriptOptions();
final builders = info.builderApplications;
final library = Library((b) => b.body.addAll([
literalList(
builders,
refer('BuilderApplication',
'package:build_runner_core/build_runner_core.dart'))
.assignFinal('_builders')
.statement,
_main()
]));
final emitter = DartEmitter(
allocator: Allocator.simplePrefixing(),
useNullSafetySyntax: info.canRunWithSoundNullSafety);
try {
final content = StringBuffer();
if (!info.canRunWithSoundNullSafety) {
content.writeln('''
// Ensure that the build script itself is not opted in to null safety,
// instead of taking the language version from the current package.
//
// @dart=2.9
//''');
}
content
..writeln('// ignore_for_file: directives_ordering')
..writeln(
'// ignore_for_file: no_leading_underscores_for_library_prefixes')
..writeln(library.accept(emitter));
return DartFormatter().format(content.toString());
} on FormatterException {
_log.severe('Generated build script could not be parsed.\n'
'This is likely caused by a misconfigured builder definition.');
throw CannotBuildException();
}
}
/// Finds expressions to create all the `BuilderApplication` instances that
/// should be applied packages in the build.
///
/// Adds `apply` expressions based on the BuildefDefinitions from any package
/// which has a `build.yaml`.
///
/// Optionally, a custom [packageGraph] and [buildConfigOverrides] can be used
/// to change which packages and build configurations are considered.
/// By default, the [PackageGraph.forThisPackage] will be used and configuration
/// overrides will be loaded from the root package.
Future<Iterable<Expression>> findBuilderApplications({
PackageGraph? packageGraph,
Map<String, BuildConfig>? buildConfigOverrides,
}) async {
final info = await findBuildScriptOptions(
packageGraph: packageGraph, buildConfigOverrides: buildConfigOverrides);
return info.builderApplications;
}
Future<BuildScriptInfo> findBuildScriptOptions({
PackageGraph? packageGraph,
Map<String, BuildConfig>? buildConfigOverrides,
}) async {
packageGraph ??= await PackageGraph.forThisPackage();
final orderedPackages = stronglyConnectedComponents<PackageNode>(
[packageGraph.root],
(node) => node.dependencies,
equals: (a, b) => a.name == b.name,
hashCode: (n) => n.name.hashCode,
).expand((c) => c);
var reader = FileBasedAssetReader(packageGraph);
var overrides = buildConfigOverrides ??=
await findBuildConfigOverrides(packageGraph, reader);
Future<BuildConfig> _packageBuildConfig(PackageNode package) async {
if (overrides.containsKey(package.name)) {
return overrides[package.name]!;
}
try {
return await BuildConfig.fromBuildConfigDir(
package.name, package.dependencies.map((n) => n.name), package.path);
} on ArgumentError catch (_) {
// During the build an error will be logged.
return BuildConfig.useDefault(
package.name, package.dependencies.map((n) => n.name));
}
}
bool _isValidDefinition(dynamic definition) {
// Filter out builderDefinitions with relative imports that aren't
// from the root package, because they will never work.
if (definition.import.startsWith('package:') as bool) return true;
return definition.package == packageGraph!.root.name;
}
final orderedConfigs =
await Future.wait(orderedPackages.map(_packageBuildConfig));
final builderDefinitions = orderedConfigs
.expand((c) => c.builderDefinitions.values)
.where(_isValidDefinition);
final orderedBuilders = findBuilderOrder(builderDefinitions).toList();
final postProcessBuilderDefinitions = orderedConfigs
.expand((c) => c.postProcessBuilderDefinitions.values)
.where(_isValidDefinition);
final applications = [
for (var builder in orderedBuilders) _applyBuilder(builder),
for (var builder in postProcessBuilderDefinitions)
_applyPostProcessBuilder(builder)
];
final canRunWithSoundNullSafety = await _allMigratedToNullSafety(
packageGraph,
reader,
orderedBuilders
.map((e) => e.import)
.followedBy(postProcessBuilderDefinitions.map((e) => e.import)));
return BuildScriptInfo(applications, canRunWithSoundNullSafety);
}
Future<bool> _allMigratedToNullSafety(PackageGraph packageGraph,
AssetReader reader, Iterable<String> imports) async {
final baseForRelative = AssetId(packageGraph.root.name, scriptLocation);
// Regardless of imports, the root package must have support for null safety
// since the build script will run in its context.
final rootPackageVersion = packageGraph.root.languageVersion;
if (rootPackageVersion == null) return false;
final rootPackageFeatures = FeatureSet.fromEnableFlags2(
sdkLanguageVersion: rootPackageVersion.asVersion, flags: const []);
if (!rootPackageFeatures.isEnabled(Feature.non_nullable)) {
return false;
}
for (final import in imports.toSet()) {
final id = AssetId.resolve(Uri.parse(_buildScriptImport(import)),
from: baseForRelative);
String content;
try {
content = await reader.readAsString(id);
} on AssetNotFoundException {
// Build is likely to be invalid, so the language version shouldn't
// matter. Still, don't assume null safety.
return false;
}
final version =
packageGraph.allPackages[id.package]?.languageVersion?.asVersion;
if (version == null) {
// Can't determine language version of import, bail out
return false;
}
final parsedFile = parseString(
content: content,
featureSet: FeatureSet.fromEnableFlags2(
sdkLanguageVersion: version, flags: const []),
throwIfDiagnostics: false,
);
if (parsedFile.errors.isNotEmpty) {
// Don't try to assume a language version if the imported file is invalid
return false;
}
if (!parsedFile.unit.featureSet.isEnabled(Feature.non_nullable)) {
// An import does not support null-safety, so the build script can't opt
// in either.
return false;
}
}
return true;
}
class BuildScriptInfo {
final Iterable<Expression> builderApplications;
final bool canRunWithSoundNullSafety;
BuildScriptInfo(this.builderApplications, this.canRunWithSoundNullSafety);
}
/// A method forwarding to `run`.
Method _main() => Method((b) => b
..name = 'main'
..returns = refer('void')
..modifier = MethodModifier.async
..requiredParameters.add(Parameter((b) => b
..name = 'args'
..type = TypeReference((b) => b
..symbol = 'List'
..types.add(refer('String')))))
..optionalParameters.add(Parameter((b) => b
..name = 'sendPort'
..type = TypeReference((b) => b
..symbol = 'SendPort'
..url = 'dart:isolate'
..isNullable = true)))
..body = Block.of([
refer('run', 'package:build_runner/build_runner.dart')
.call([refer('args'), refer('_builders')])
.awaited
.assignVar('result')
.statement,
refer('sendPort')
.nullSafeProperty('send')
.call([refer('result')]).statement,
refer('exitCode', 'dart:io').assign(refer('result')).statement,
]));
/// An expression calling `apply` with appropriate setup for a Builder.
Expression _applyBuilder(BuilderDefinition definition) {
final namedArgs = {
if (definition.isOptional) 'isOptional': literalTrue,
if (definition.buildTo == BuildTo.cache)
'hideOutput': literalTrue
else
'hideOutput': literalFalse,
if (!identical(definition.defaults.generateFor, InputSet.anything))
'defaultGenerateFor':
refer('InputSet', 'package:build_config/build_config.dart')
.constInstance([], {
if (definition.defaults.generateFor.include != null)
'include': _rawStringList(definition.defaults.generateFor.include!),
if (definition.defaults.generateFor.exclude != null)
'exclude': _rawStringList(definition.defaults.generateFor.exclude!),
}),
if (definition.defaults.options.isNotEmpty)
'defaultOptions': _constructBuilderOptions(definition.defaults.options),
if (definition.defaults.devOptions.isNotEmpty)
'defaultDevOptions':
_constructBuilderOptions(definition.defaults.devOptions),
if (definition.defaults.releaseOptions.isNotEmpty)
'defaultReleaseOptions':
_constructBuilderOptions(definition.defaults.releaseOptions),
if (definition.appliesBuilders.isNotEmpty)
'appliesBuilders': _rawStringList(definition.appliesBuilders),
};
var import = _buildScriptImport(definition.import);
return refer('apply', 'package:build_runner_core/build_runner_core.dart')
.call([
literalString(definition.key, raw: true),
literalList([for (var f in definition.builderFactories) refer(f, import)]),
_findToExpression(definition),
], namedArgs);
}
/// An expression calling `applyPostProcess` with appropriate setup for a
/// PostProcessBuilder.
Expression _applyPostProcessBuilder(PostProcessBuilderDefinition definition) {
final namedArgs = {
if (!identical(definition.defaults.generateFor, InputSet.anything))
'defaultGenerateFor':
refer('InputSet', 'package:build_config/build_config.dart')
.constInstance([], {
if (definition.defaults.generateFor.include != null)
'include': _rawStringList(definition.defaults.generateFor.include!),
if (definition.defaults.generateFor.exclude != null)
'exclude': _rawStringList(definition.defaults.generateFor.exclude!),
}),
if (definition.defaults.options.isNotEmpty)
'defaultOptions': _constructBuilderOptions(definition.defaults.options),
if (definition.defaults.devOptions.isNotEmpty)
'defaultDevOptions':
_constructBuilderOptions(definition.defaults.devOptions),
if (definition.defaults.releaseOptions.isNotEmpty)
'defaultReleaseOptions':
_constructBuilderOptions(definition.defaults.releaseOptions),
};
var import = _buildScriptImport(definition.import);
return refer('applyPostProcess',
'package:build_runner_core/build_runner_core.dart')
.call([
literalString(definition.key, raw: true),
refer(definition.builderFactory, import),
], namedArgs);
}
Expression _rawStringList(List<String> strings) =>
strings.toExpression(constant: true);
/// Returns the actual import to put in the generated script based on an import
/// found in the build.yaml.
String _buildScriptImport(String import) {
if (import.startsWith('package:')) {
return import;
} else if (import.startsWith('../') || import.startsWith('/')) {
_log.warning('The `../` import syntax in build.yaml is now deprecated, '
'instead do a normal relative import as if it was from the root of '
'the package. Found `$import` in your `build.yaml` file.');
return import;
} else {
return p.url.relative(import, from: p.url.dirname(scriptLocation));
}
}
Expression _findToExpression(BuilderDefinition definition) {
switch (definition.autoApply) {
case AutoApply.none:
return refer('toNoneByDefault',
'package:build_runner_core/build_runner_core.dart')
.call([]);
case AutoApply.dependents:
return refer('toDependentsOf',
'package:build_runner_core/build_runner_core.dart')
.call([literalString(definition.package, raw: true)]);
case AutoApply.allPackages:
return refer('toAllPackages',
'package:build_runner_core/build_runner_core.dart')
.call([]);
case AutoApply.rootPackage:
return refer('toRoot', 'package:build_runner_core/build_runner_core.dart')
.call([]);
}
}
/// An expression creating a [BuilderOptions] from a json string.
Expression _constructBuilderOptions(Map<String, dynamic> options) =>
refer('BuilderOptions', 'package:build/build.dart')
.constInstance([options.toExpression()]);
extension on LanguageVersion {
Version get asVersion => Version(major, minor, 0);
}
/// Converts a Dart object to a source code representation.
///
/// This is similar to [literal] from `package:code_builder`, except that it
/// always writes raw string literals.
extension ConvertToExpression on Object? {
Expression toExpression({bool constant = false}) {
final $this = this;
if ($this is Map) {
final create = constant ? literalConstMap : literalMap;
return create({
for (final entry in $this.cast<Object?, Object?>().entries)
entry.key.toExpression(): entry.value.toExpression()
});
} else if ($this is List) {
final create = constant ? literalConstList : literalList;
return create(
[for (final entry in $this.cast<Object?>()) entry.toExpression()]);
} else if ($this is String) {
return literalString($this, raw: true);
} else {
return literal(this);
}
}
}