/
builder.dart
54 lines (41 loc) · 1.54 KB
/
builder.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
/// Configuration for using `package:build`-compatible build systems.
///
/// This library is **not** intended to be imported by typical end-users unless
/// you are creating a custom compilation pipeline.
///
/// See [package:build_runner](https://pub.dev/packages/build_runner)
/// for more information.
library builder;
import 'dart:async';
import 'package:build/build.dart';
import 'package:pubspec_parse/pubspec_parse.dart';
const _defaultOutput = 'lib/src/version.dart';
Builder buildVersion([BuilderOptions? options]) =>
_VersionBuilder((options?.config['output'] as String?) ?? _defaultOutput);
class _VersionBuilder implements Builder {
final String output;
_VersionBuilder(this.output);
@override
Future<void> build(BuildStep buildStep) async {
final assetId = AssetId(buildStep.inputId.package, 'pubspec.yaml');
if (assetId != buildStep.inputId) {
// Skip nested packages!
// Should be able to use `^pubspec.yaml` – but it no work
// See https://github.com/dart-lang/build/issues/3286
return;
}
final content = await buildStep.readAsString(assetId);
final pubspec = Pubspec.parse(content, sourceUrl: assetId.uri);
if (pubspec.version == null) {
throw StateError('pubspec.yaml does not have a version defined.');
}
await buildStep.writeAsString(buildStep.allowedOutputs.single, '''
// Generated code. Do not modify.
const packageVersion = '${pubspec.version}';
''');
}
@override
Map<String, List<String>> get buildExtensions => {
'pubspec.yaml': [output],
};
}