-
Notifications
You must be signed in to change notification settings - Fork 281
Expand file tree
/
Copy pathgenerate_workflows_command.dart
More file actions
727 lines (670 loc) · 21 KB
/
generate_workflows_command.dart
File metadata and controls
727 lines (670 loc) · 21 KB
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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import 'dart:io';
import 'package:aft/aft.dart';
import 'package:path/path.dart' as p;
import 'package:yaml/yaml.dart';
/// Command for generating GitHub Actions workflows for all packages in the
/// repo.
class GenerateWorkflowsCommand extends AmplifyCommand {
GenerateWorkflowsCommand() {
argParser.addFlag(
'set-exit-if-changed',
defaultsTo: false,
help: 'Return exit code 1 if there are any workflow changes.',
);
}
@override
String get name => 'workflows';
@override
String get description =>
'Generate GitHub Actions workflows for repo packages';
late final bool setExitIfChanged = argResults!['set-exit-if-changed'] as bool;
late final StringBuffer _dependabotConfig = () {
final groupPubPackages = repo.aftConfig.dependencies.keys
.map(_dependabotGroup)
.join('\n');
return StringBuffer('''
# Generated with aft. To update, run: `aft generate workflows`
version: 2
enable-beta-ecosystems: true
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
# The `github-actions` ecosystem only searches
# `.github/workflows` by default.
- package-ecosystem: "github-actions"
directory: ".github/composite_actions"
schedule:
interval: "weekly"
- package-ecosystem: "npm"
directory: "infra"
schedule:
interval: "weekly"
groups:
cdk:
patterns:
- "aws-cdk"
- "aws-cdk-lib"
- "@aws-cdk/*"
- "constructs"
aws-sdk-js:
patterns:
- "@aws-sdk/*"
- "@aws-crypto/*"
ignore:
# Ignore patch version bumps
- dependency-name: "*"
update-types:
- "version-update:semver-patch"
- package-ecosystem: "npm"
directory: "infra-gen2"
schedule:
interval: "weekly"
groups:
cdk:
patterns:
- "aws-amplify"
- "@aws-amplify/*"
- "aws-cdk"
- "aws-cdk-lib"
- "constructs"
aws-sdk-js:
patterns:
- "@aws-sdk/*"
- "@aws-crypto/*"
ignore:
# Ignore patch version bumps
- dependency-name: "*"
update-types:
- "version-update:semver-patch"
- package-ecosystem: "pub"
directory: "/"
schedule:
interval: "daily"
# Group dependencies which have a constraint set in the global "pubspec.yaml"
groups:
$groupPubPackages
''');
}();
String _dependabotGroup(String pkg) {
return '''
$pkg:
patterns:
- "$pkg"''';
}
/// Collects all dependencies (direct + transitive) for [package].
List<PackageInfo> _collectDependencies(
PackageInfo package, {
required String repoRelativePath,
}) {
final dependentPackages = <PackageInfo>[];
dfs(repo.getPackageGraph(includeDevDependencies: true), root: package, (
dependent,
) {
if (dependent == package || !dependent.isDevelopmentPackage) {
return;
}
dependentPackages.add(dependent);
});
// skip aft tests which include a snapshot of the mono repo
if (repoRelativePath.contains('snapshot')) {
return [];
}
_dependabotConfig.write('''
- package-ecosystem: "pub"
directory: "$repoRelativePath"
schedule:
interval: "daily"
ignore:
# Ignore patch version bumps
- dependency-name: "*"
update-types:
- "version-update:semver-patch"
''');
if (dependentPackages.isNotEmpty) {
_dependabotConfig.write('''
# Ignore all repo packages
${dependentPackages.map((dep) => ' - dependency-name: "${dep.name}"').join('\n')}
''');
}
final dependabotGroups =
{
...package.pubspecInfo.pubspec.dependencies.keys,
...package.pubspecInfo.pubspec.devDependencies.keys,
}
.where(repo.aftConfig.dependencies.keys.contains)
.map(_dependabotGroup)
.toList();
if (dependabotGroups.isNotEmpty) {
_dependabotConfig.write('''
# Group dependencies which have a constraint set in the global "pubspec.yaml"
groups:
${dependabotGroups.join('\n')}
''');
}
return dependentPackages;
}
@override
Future<void> run() async {
await super.run();
for (final package in commandPackages.values) {
final repoRelativePath = p.relative(package.path, from: rootDir.path);
final dependentPackages = _collectDependencies(
package,
repoRelativePath: repoRelativePath,
);
if (package.pubspecInfo.pubspec.publishTo == 'none' &&
!falsePositiveExamples.contains(package.name)) {
continue;
}
await generateForPackage(
package,
repoRelativePath: repoRelativePath,
dependentPackages: dependentPackages,
);
}
final dependabotFile = File(
p.join(rootDir.path, '.github', 'dependabot.yaml'),
);
writeWorkflowFile(dependabotFile, _dependabotConfig.toString());
// Check if workflow generation caused `git diff` to change.
if (setExitIfChanged) {
final gitDiff = await Process.start('git', [
'diff',
'--relative',
'--',
'.github/workflows',
], workingDirectory: rootDir.path);
final gitDiffOutput = StringBuffer();
gitDiff
..captureStdout()
..captureStdout(sink: gitDiffOutput.write)
..captureStderr()
..captureStderr(sink: gitDiffOutput.write);
if (await gitDiff.exitCode != 0 || gitDiffOutput.isNotEmpty) {
logger
..error('Workflows are not up to date.')
..error('Run `aft generate workflows` to regenerate them.');
exit(1);
}
}
}
Future<void> generateForPackage(
PackageInfo package, {
required String repoRelativePath,
required List<PackageInfo> dependentPackages,
}) async {
// Packages without a `lib/` folder generally contain only native code.
// These packages are tested via their parent package and do not require
// a workflow of their own.
final libDir = Directory(p.join(package.path, 'lib'));
if (!libDir.existsSync()) {
return;
}
final workflowFilepath = p.join(
rootDir.path,
'.github',
'workflows',
'${package.name}.yaml',
);
final workflowFile = File(workflowFilepath);
if (package.pubspecInfo.config.aft?.github?.custom ?? false) {
if (!workflowFile.existsSync()) {
throw Exception(
'Package "${package.name}" sets `custom: true` but no workflow '
'file was found at: $workflowFilepath',
);
}
return;
}
final isDartPackage = package.flavor == PackageFlavor.dart;
const ddcWorkflow = 'dart_ddc.yaml';
const dart2JsWorkflow = 'dart_dart2js.yaml';
const nativeWorkflow = 'dart_native.yaml';
final e2eWorkflows = {
'android': 'e2e_android.yaml',
'ios': 'e2e_ios.yaml',
if (!package.name.contains('datastore')) ...{
'web': 'e2e_web.yaml',
'linux': 'e2e_linux.yaml',
'windows': 'e2e_windows.yaml',
},
};
// Determine workflows used
final analyzeAndTestWorkflow = isDartPackage
? 'dart_vm.yaml'
: 'flutter_vm.yaml';
final needsNativeTest = isDartPackage && package.unitTestDirectory != null;
final needsWebTest = package.pubspecInfo.pubspec.devDependencies
.containsKey('build_test');
// TODO(dnys1): Enable E2E runs for Dart packages
final needsE2ETest =
package.flavor == PackageFlavor.flutter &&
package.integrationTestDirectory != null;
final hasGoldens =
package.flavor == PackageFlavor.flutter &&
package.goldensTestDirectory != null;
// Detect ffigen configurations
const ffigenWorkflow = 'ffigen_validate.yaml';
final ffigenConfigs = _detectFfigenConfigs(package);
final hasFfigen = ffigenConfigs.isNotEmpty;
final workflows = <String>[
analyzeAndTestWorkflow,
if (needsNativeTest) nativeWorkflow,
if (needsWebTest) ...[ddcWorkflow, dart2JsWorkflow],
if (needsE2ETest) ...e2eWorkflows.values,
if (hasFfigen) ffigenWorkflow,
];
// Collect all the paths for which this workflow will run. This includes
// paths in the package itself plus any modifications in transitive
// dependencies which could impact this.
final workflowPaths = [
if (needsWebTest) '.github/composite_actions/setup_firefox/action.yaml',
...workflows.map((workflow) => '.github/workflows/$workflow'),
p.relative(workflowFilepath, from: rootDir.path),
'$repoRelativePath/**/*.dart',
'$repoRelativePath/**/*.yaml',
'$repoRelativePath/lib/**/*',
'$repoRelativePath/test/**/*',
];
for (final dependent in dependentPackages) {
final repoRelativePath = p.relative(dependent.path, from: rootDir.path);
if (dependent.isLintsPackage) {
workflowPaths.addAll([
'$repoRelativePath/pubspec.yaml',
'$repoRelativePath/lib/**/*.yaml',
]);
continue;
}
workflowPaths.addAll([
'$repoRelativePath/pubspec.yaml',
'$repoRelativePath/lib/**/*.dart',
]);
// run e2e tests (if present) when native resources change in a dependency
if (needsE2ETest) {
const nativeDirectories = [
'android',
'ios',
'macos',
'darwin',
'windows',
'linux',
'web',
];
workflowPaths.addAll([
for (final dir in nativeDirectories)
if (dependent.hasDirectory(dir)) '$repoRelativePath/$dir/**/*',
]);
}
}
workflowPaths.sort();
final workflowContents = StringBuffer('''
# Generated with aft. To update, run: `aft generate workflows`
name: ${package.name}
on:
push:
branches:
- main
- stable
paths:
${workflowPaths.map((path) => " - '$path'").join('\n')}
pull_request:
paths:
${workflowPaths.map((path) => " - '$path'").join('\n')}
schedule:
- cron: "0 13 * * 1" # Every Monday at 06:00 PST
workflow_dispatch:
defaults:
run:
shell: bash
$permissionsBlock
# Cancels in-progress job when there is another push to same ref.
# https://docs.github.com/en/actions/using-jobs/using-concurrency#example-only-cancel-in-progress-jobs-or-runs-for-the-current-workflow
concurrency:
group: \${{ github.workflow }}-\${{ github.ref }}
cancel-in-progress: true
jobs:
test:
uses: ./.github/workflows/$analyzeAndTestWorkflow
secrets: inherit
with:
package-name: ${package.name}
working-directory: $repoRelativePath
''');
if (!isDartPackage) {
workflowContents.write('''
has-goldens: $hasGoldens
''');
}
if (needsNativeTest) {
workflowContents.write('''
native_test:
needs: test
uses: ./.github/workflows/$nativeWorkflow
secrets: inherit
with:
package-name: ${package.name}
working-directory: $repoRelativePath
''');
if (needsWebTest) {
workflowContents.write('''
ddc_test:
needs: test
uses: ./.github/workflows/$ddcWorkflow
secrets: inherit
with:
package-name: ${package.name}
working-directory: $repoRelativePath
dart2js_test:
needs: test
uses: ./.github/workflows/$dart2JsWorkflow
secrets: inherit
with:
package-name: ${package.name}
working-directory: $repoRelativePath
''');
}
}
if (needsE2ETest) {
final dependsOn = [
'test',
if (needsNativeTest) 'native_test',
if (needsWebTest) ...['ddc_test', 'dart2js_test'],
];
final needsAwsConfig = File(
p.join(package.path, 'tool', 'pull_test_backend.sh'),
).existsSync();
for (final MapEntry(key: platform, value: e2eWorkflow)
in e2eWorkflows.entries) {
workflowContents.write('''
e2e_${platform}_test:
needs: [${dependsOn.join(', ')}]
uses: ./.github/workflows/$e2eWorkflow
secrets: inherit
with:
package-name: ${package.name}
working-directory: $repoRelativePath
needs-aws-config: $needsAwsConfig
''');
}
}
// Add ffigen validation jobs
if (hasFfigen) {
for (final MapEntry(key: os, value: configs) in ffigenConfigs.entries) {
final osLabel = os.startsWith('macos') ? 'macos' : 'linux';
final configFiles = configs.join(' ');
workflowContents.write('''
ffigen_${osLabel}_test:
needs: test
uses: ./.github/workflows/$ffigenWorkflow
secrets: inherit
with:
package-name: ${package.name}
working-directory: $repoRelativePath
ffigen-configs: '$configFiles'
os: $os
''');
}
}
writeWorkflowFile(workflowFile, workflowContents.toString());
await generateAndroidUnitTestWorkflow(
package: package,
repoRelativePath: repoRelativePath,
);
await generateIosUnitTestWorkflow(
package: package,
repoRelativePath: repoRelativePath,
);
if (package.example case final examplePackage?) {
final repoRelativePath = p.relative(
examplePackage.path,
from: rootDir.path,
);
await generateForPackage(
examplePackage,
repoRelativePath: repoRelativePath,
dependentPackages: _collectDependencies(
examplePackage,
repoRelativePath: repoRelativePath,
),
);
}
}
/// If a package has Android unit tests, generate a separate workflow for them.
///
// Tests are run from example/android since Android packages
// are tested through their example apps.
//
// Builds are run from example for the same reason.
Future<void> generateAndroidUnitTestWorkflow({
required PackageInfo package,
required String repoRelativePath,
}) async {
final androidPath = p.join(package.path, 'android');
final androidDir = Directory(androidPath);
final hasAndroidCode = androidDir.existsSync();
if (package.flavor != PackageFlavor.flutter ||
!hasAndroidCode ||
package.example == null) {
return;
}
_dependabotConfig.write('''
- package-ecosystem: "gradle"
directory: "${p.relative(androidPath, from: rootDir.path)}"
schedule:
interval: "weekly"
ignore:
# Ignore Kotlin updates since we should always match Flutter stable
# to ensure users can have Kt versions >= Flutter stable.
- dependency-name: "kotlin_version"
- dependency-name: "org.jetbrains.kotlin:kotlin-gradle-plugin"
# Ignore patch version bumps
- dependency-name: "*"
update-types:
- "version-update:semver-patch"
groups:
amplify-android:
patterns:
- "com.amplifyframework:*"
- "com.amazonaws:*"
mockito:
patterns:
- "org.mockito:*"
''');
final androidTestDir = Directory(p.join(androidDir.path, 'src', 'test'));
final exampleAndroidDir = Directory(
p.join(package.path, 'example', 'android'),
);
final hasAndroidTests =
androidTestDir.existsSync() && exampleAndroidDir.existsSync();
final androidWorkflowFilepath = p.join(
rootDir.path,
'.github',
'workflows',
'${package.name}_android.yaml',
);
const androidWorkflow = 'flutter_android.yaml';
final androidWorkflowPaths = [
'.github/workflows/$androidWorkflow',
p.relative(androidWorkflowFilepath, from: rootDir.path),
];
final androidWorkflowFile = File(androidWorkflowFilepath);
final androidWorkflowContents =
'''
# Generated with aft. To update, run: `aft generate workflows`
name: ${package.name} Android
on:
push:
branches:
- main
- stable
pull_request:
paths:
- '$repoRelativePath/**/*.yaml'
- '$repoRelativePath/android/**/*'
- '$repoRelativePath/example/android/**/*'
${androidWorkflowPaths.map((path) => " - '$path'").join('\n')}
schedule:
- cron: "0 0 * * 0" # Every Sunday at 00:00
workflow_dispatch:
defaults:
run:
shell: bash
$permissionsBlock
# Cancels in-progress job when there is another push to same ref.
# https://docs.github.com/en/actions/using-jobs/using-concurrency#example-only-cancel-in-progress-jobs-or-runs-for-the-current-workflow
concurrency:
group: \${{ github.workflow }}-\${{ github.ref }}
cancel-in-progress: true
jobs:
android:
uses: ./.github/workflows/$androidWorkflow
secrets: inherit
with:
example-directory: $repoRelativePath/example
package-name: ${package.name}
has-native-tests: $hasAndroidTests
''';
writeWorkflowFile(androidWorkflowFile, androidWorkflowContents);
}
/// If a package has iOS unit tests, generate a separate workflow for them.
Future<void> generateIosUnitTestWorkflow({
required PackageInfo package,
required String repoRelativePath,
}) async {
final iosDir = Directory(p.join(package.path, 'ios'));
final hasIosCode = iosDir.existsSync();
if (package.flavor != PackageFlavor.flutter ||
!hasIosCode ||
package.example == null) {
return;
}
final iosTestDir = Directory(
p.join(package.path, 'example', 'ios', 'unit_tests'),
);
final hasIosTests = iosTestDir.existsSync();
final workflowFilepath = p.join(
rootDir.path,
'.github',
'workflows',
'${package.name}_ios.yaml',
);
const iosWorkflow = 'flutter_ios.yaml';
final iosWorkflowPaths = [
'.github/workflows/$iosWorkflow',
p.relative(workflowFilepath, from: rootDir.path),
];
final iosWorkflowFile = File(workflowFilepath);
final iosWorkflowContents =
'''
# Generated with aft. To update, run: `aft generate workflows`
name: ${package.name} iOS
on:
push:
branches:
- main
- stable
pull_request:
paths:
- '$repoRelativePath/**/*.yaml'
- '$repoRelativePath/ios/**/*'
- '$repoRelativePath/example/ios/**/*'
${iosWorkflowPaths.map((path) => " - '$path'").join('\n')}
schedule:
- cron: "0 0 * * 0" # Every Sunday at 00:00
workflow_dispatch:
defaults:
run:
shell: bash
$permissionsBlock
# Cancels in-progress job when there is another push to same ref.
# https://docs.github.com/en/actions/using-jobs/using-concurrency#example-only-cancel-in-progress-jobs-or-runs-for-the-current-workflow
concurrency:
group: \${{ github.workflow }}-\${{ github.ref }}
cancel-in-progress: true
jobs:
ios:
uses: ./.github/workflows/$iosWorkflow
secrets: inherit
with:
example-directory: $repoRelativePath/example
package-name: ${package.name}
has-native-tests: $hasIosTests
''';
writeWorkflowFile(iosWorkflowFile, iosWorkflowContents);
}
/// Detects ffigen configuration files in the package directory and groups
/// them by the OS runner needed.
///
/// Returns a map of runner OS -> list of config file names.
Map<String, List<String>> _detectFfigenConfigs(PackageInfo package) {
final packageDir = Directory(package.path);
final ffigenConfigFiles = packageDir
.listSync()
.whereType<File>()
.where(
(f) =>
p.basename(f.path).startsWith('ffigen') &&
p.basename(f.path).endsWith('.yaml'),
)
.toList();
if (ffigenConfigFiles.isEmpty) {
return {};
}
// Group configs by OS runner
final configsByOs = <String, List<String>>{};
for (final configFile in ffigenConfigFiles) {
final configName = p.basename(configFile.path);
final os = _ffigenConfigOs(configFile);
configsByOs.putIfAbsent(os, () => []).add(configName);
}
// Sort config names within each OS group for deterministic output
for (final configs in configsByOs.values) {
configs.sort();
}
// Return with sorted keys for deterministic job ordering
return Map.fromEntries(
configsByOs.entries.toList()..sort((a, b) => a.key.compareTo(b.key)),
);
}
/// Determines the OS runner needed for a given ffigen config file.
///
/// Checks for macOS indicators (Xcode paths, ObjC language) in the config.
/// Defaults to `ubuntu-latest` for Linux-based configs.
String _ffigenConfigOs(File configFile) {
try {
final content = configFile.readAsStringSync();
final yaml = loadYaml(content);
if (yaml is YamlMap) {
// Check for ObjC language (requires macOS)
final language = yaml['language'];
if (language is String && language == 'objc') {
return 'macos-26';
}
// Check for macOS SDK paths in headers or compiler-opts
if (content.contains('MacOSX.platform') ||
content.contains('MacOSX.sdk') ||
content.contains('Xcode.app')) {
return 'macos-26';
}
}
} on Object {
// If we can't parse the config, default to Linux
}
return 'ubuntu-latest';
}
void writeWorkflowFile(File workflowFile, String content) {
if (!workflowFile.existsSync()) {
workflowFile.createSync();
}
workflowFile.writeAsStringSync(content);
}
}
const permissionsBlock = '''
# These permissions are needed to interact with GitHub's OIDC Token endpoint.
permissions:
id-token: write
contents: read''';