Skip to content

Commit 708a886

Browse files
authored
[material_ui] gen_defaults should follow new versioning strategy (#12627)
Work towards flutter/flutter#191088 **Ports over #11918 which landed on the `m3e_migration` feature branch.** ### Original PR description Work towards flutter/flutter#186906 Work towards flutter/flutter#187899 Previously, the `gen_defaults` script generated the files in different directories based on whether or not the template was an M3 or M3E template. Since we are planning on using an variant enum instead of different libraries to separate M3 and M3E implementations, the `gen_defaults` script needs to be accordingly updated. ## Pre-Review Checklist **Note**: The Flutter team is currently trialing the use of [Gemini Code Assist for GitHub](https://developers.google.com/gemini-code-assist/docs/review-github-code). Comments from the `gemini-code-assist` bot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed. [^1]: Regular contributors who have demonstrated familiarity with the repository guidelines only need to comment if the PR is not auto-exempted by repo tooling.
1 parent 2c65fb5 commit 708a886

4 files changed

Lines changed: 225 additions & 101 deletions

File tree

‎packages/material_ui/tool/gen_defaults/templates/template.dart‎

Lines changed: 72 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -8,65 +8,107 @@ import 'package:meta/meta.dart';
88

99
enum _MaterialVersion { material3, material3Expressive }
1010

11-
abstract class M3TokenTemplate extends _TokenTemplate {
11+
/// A template for generating Material 3 component defaults.
12+
abstract class M3TokenTemplate extends TokenTemplate {
1213
const M3TokenTemplate();
1314

1415
@override
1516
_MaterialVersion get _version => _MaterialVersion.material3;
1617
}
1718

18-
abstract class M3ETokenTemplate extends _TokenTemplate {
19+
/// A template for generating Material 3 Expressive component defaults.
20+
abstract class M3ETokenTemplate extends TokenTemplate {
1921
const M3ETokenTemplate();
2022

2123
@override
2224
_MaterialVersion get _version => _MaterialVersion.material3Expressive;
2325
}
2426

25-
abstract class _TokenTemplate {
26-
const _TokenTemplate();
27+
@visibleForTesting
28+
abstract class TokenTemplate {
29+
const TokenTemplate();
2730

28-
static const String copyrightHeader = '''
31+
/// The copyright header prepended to all generated defaults files.
32+
static const String _copyrightHeader = '''
2933
// Copyright 2013 The Flutter Authors
3034
// Use of this source code is governed by a BSD-style license that can be
3135
// found in the LICENSE file.
3236
''';
3337

34-
static const String headerComment = '''
38+
/// The warning comment prepended to all generated defaults files informing
39+
/// readers not to edit them by hand.
40+
static const String _headerComment = '''
3541
3642
// Do not edit by hand. The code is generated from data in the Material
3743
// Design token database by the script:
3844
// packages/material_ui/tool/gen_defaults/bin/gen_defaults.dart.
3945
''';
4046

41-
/// The Material version this template is for.
42-
_MaterialVersion get _version;
47+
/// The regular expression used to verify that a template name is written with
48+
/// spaces and capitalized words (e.g., "Icon Button").
49+
static final RegExp _nameRegExp = RegExp(r'^[A-Z][a-zA-Z0-9]*( [A-Z][a-zA-Z0-9]*)*$');
4350

4451
/// The name of the template, which corresponds to the target file name.
45-
/// E.g., 'typography' for generating 'typography_defaults.g.dart'.
52+
/// E.g., 'Icon Button' for generating 'icon_button_m3_defaults.g.dart'.
4653
String get name;
4754

55+
/// The path of the parent file relative to `lib/src`.
56+
/// E.g., 'icon_button.dart' or 'buttons/icon_button.dart'.
57+
String get parentFilePath;
58+
59+
/// The path to the library's directory where generated files are placed.
4860
@visibleForTesting
4961
String get materialLib {
5062
const packagePath = 'packages/material_ui';
5163
const generatedDirectory = 'lib/src/generated';
52-
final String relativeOutputPath = switch (_version) {
53-
_MaterialVersion.material3 => generatedDirectory,
54-
_MaterialVersion.material3Expressive => '$generatedDirectory/material_3_expressive',
55-
};
5664
if (Directory(packagePath).existsSync()) {
57-
return '$packagePath/$relativeOutputPath';
65+
return '$packagePath/$generatedDirectory';
5866
}
59-
return relativeOutputPath;
67+
return generatedDirectory;
6068
}
6169

62-
String generateContents();
70+
/// The Material version this template is for.
71+
_MaterialVersion get _version;
6372

73+
/// The name of the class that will be generated (e.g. `_M3IconButtonDefaults`
74+
/// or `_M3EIconButtonDefaults`).
75+
String get _className {
76+
assert(
77+
_nameRegExp.hasMatch(name),
78+
'The template name "$name" must use spaces and capitalized words (e.g., "Typography" or "Icon Button").',
79+
);
80+
final String camelName = name.replaceAll(' ', '');
81+
return switch (_version) {
82+
_MaterialVersion.material3 => '_M3${camelName}Defaults',
83+
_MaterialVersion.material3Expressive => '_M3E${camelName}Defaults',
84+
};
85+
}
86+
87+
/// The regular expression used to verify that the generated contents declare
88+
/// the class.
89+
RegExp get _classRegExp => RegExp('class\\s+$_className\\b');
90+
91+
/// Returns the body of the generated file as a string.
92+
///
93+
/// The [className] parameter must be used to declare the class.
94+
String generateContents(String className);
95+
96+
/// Generates the file under the target path [materialLib] and formats it.
6497
void generateFile({bool verbose = false}) {
65-
final fileName = '$materialLib/${name}_defaults.g.dart';
98+
final String snakeName = name.toLowerCase().replaceAll(' ', '_');
99+
final String outputFileName = switch (_version) {
100+
_MaterialVersion.material3 => '${snakeName}_m3_defaults.g.dart',
101+
_MaterialVersion.material3Expressive => '${snakeName}_m3e_defaults.g.dart',
102+
};
103+
final fileName = '$materialLib/$outputFileName';
66104
if (verbose) {
67105
stdout.writeln('Generating file: $fileName');
68-
stdout.writeln('Target parent file name: $name.dart');
106+
stdout.writeln('Target parent file path: lib/src/$parentFilePath');
69107
}
108+
assert(
109+
!parentFilePath.startsWith('/') && !parentFilePath.startsWith('lib/'),
110+
'parentFilePath must be relative to lib/src/ (e.g. "icon_button.dart").',
111+
);
70112
final file = File(fileName);
71113
if (!file.existsSync()) {
72114
if (verbose) {
@@ -75,20 +117,21 @@ abstract class _TokenTemplate {
75117
file.createSync(recursive: true);
76118
}
77119

78-
final parentName = '$name.dart';
79-
80120
if (verbose) {
81121
stdout.writeln('Generating contents...');
82122
}
123+
final String contents = generateContents(_className);
124+
assert(
125+
contents.contains(_classRegExp),
126+
'The generated contents for "$name" must define the class "$_className". '
127+
'Make sure you are utilizing the passed `className` parameter.',
128+
);
129+
83130
final buffer = StringBuffer();
84-
buffer.write(copyrightHeader);
85-
buffer.write(headerComment);
86-
final String partOfPath = switch (_version) {
87-
_MaterialVersion.material3 => '../$parentName',
88-
_MaterialVersion.material3Expressive => '../../material_3_expressive/$parentName',
89-
};
90-
buffer.write("part of '$partOfPath';\n\n");
91-
buffer.write(generateContents());
131+
buffer.write(_copyrightHeader);
132+
buffer.write(_headerComment);
133+
buffer.write("part of '../$parentFilePath';\n\n");
134+
buffer.write(contents);
92135

93136
if (verbose) {
94137
stdout.writeln('Writing generated contents to $fileName...');
@@ -97,7 +140,7 @@ abstract class _TokenTemplate {
97140
if (verbose) {
98141
stdout.writeln('Formatting $fileName...');
99142
}
100-
final ProcessResult result = Process.runSync(Platform.resolvedExecutable, <String>[
143+
final ProcessResult result = Process.runSync(Platform.isWindows ? 'dart.bat' : 'dart', <String>[
101144
'format',
102145
fileName,
103146
]);

‎packages/material_ui/tool/gen_defaults/test/gen_defaults_test.dart‎

Lines changed: 78 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import 'dart:io';
66

77
import 'package:test/test.dart';
8+
import '../templates/template.dart';
89
import 'test_fixtures/test_templates.dart';
910

1011
void main() {
@@ -20,69 +21,85 @@ void main() {
2021
tempDir!.deleteSync(recursive: true);
2122
});
2223

23-
test('will generate a part file ending in _defaults.g.dart', () {
24-
final template = ButtonTemplate(testPath());
25-
template.generateFile(verbose: true);
24+
for (final isM3E in <bool>[true, false]) {
25+
TokenTemplate buttonTemplate() =>
26+
isM3E ? M3EIconButtonTemplate(testPath()) : M3IconButtonTemplate(testPath());
2627

27-
final file = File('${testPath()}/button_defaults.g.dart');
28-
expect(file.existsSync(), isTrue);
29-
});
30-
31-
test('will generate a file with the correct header text', () {
32-
final template = ButtonTemplate(testPath());
33-
template.generateFile();
34-
35-
final file = File('${testPath()}/button_defaults.g.dart');
36-
final String fileContents = file.readAsStringSync();
37-
expect(fileContents, contains(_fileHeader));
38-
});
39-
40-
test('will generate a file with the expected contents', () {
41-
final template = ButtonTemplate(testPath());
42-
template.generateFile();
43-
44-
final file = File('${testPath()}/button_defaults.g.dart');
45-
final String fileContents = file.readAsStringSync();
46-
expect(fileContents, contains(_buttonDefaultsClass));
47-
});
28+
String filePath() {
29+
final fileName = 'icon_button_m3${isM3E ? 'e' : ''}_defaults.g.dart';
30+
return '${testPath()}/$fileName';
31+
}
4832

49-
test('will completely overwrite any previous code', () {
50-
final file = File('${testPath()}/button_defaults.g.dart');
51-
const randomText = 'Pre-existing random text.';
52-
file.writeAsStringSync(randomText);
33+
group(isM3E ? 'M3E Template' : 'M3 Template', () {
34+
test(
35+
'will generate a part file ending in icon_button_m3${isM3E ? 'e' : ''}_defaults.g.dart',
36+
() {
37+
buttonTemplate().generateFile(verbose: true);
38+
expect(File(filePath()).existsSync(), isTrue);
39+
},
40+
);
5341

54-
final template = ButtonTemplate(testPath());
55-
template.generateFile();
56-
final String fileContents = file.readAsStringSync();
57-
expect(fileContents, isNot(contains(randomText)));
58-
expect(fileContents, contains(_buttonDefaultsClass));
59-
});
42+
test('will generate a file with the correct header text', () {
43+
buttonTemplate().generateFile(verbose: true);
44+
final String fileContents = File(filePath()).readAsStringSync();
45+
expect(fileContents, contains(_fileHeader));
46+
});
47+
48+
test('will generate a file with the expected contents', () {
49+
buttonTemplate().generateFile(verbose: true);
50+
final String fileContents = File(filePath()).readAsStringSync();
51+
expect(
52+
fileContents,
53+
contains(isM3E ? _buttonExpressiveDefaultsClass : _buttonDefaultsClass),
54+
);
55+
});
56+
57+
test('will completely overwrite any previous code', () {
58+
final file = File(filePath());
59+
const randomText = 'Pre-existing random text.';
60+
file.writeAsStringSync(randomText);
61+
62+
buttonTemplate().generateFile(verbose: true);
63+
final String fileContents = file.readAsStringSync();
64+
expect(fileContents, isNot(contains(randomText)));
65+
});
66+
});
67+
}
6068

6169
test('will run dart format over the generated file', () {
6270
final template = UnformattedTemplate(testPath());
6371
template.generateFile();
6472

65-
final file = File('${testPath()}/unformatted_defaults.g.dart');
73+
final file = File('${testPath()}/unformatted_m3_defaults.g.dart');
6674
expect(file.readAsStringSync(), contains(formattedClass));
6775
});
6876

69-
test('materialLib path resolves correctly based on MaterialVersion', () {
70-
final m3Template = TestM3Template();
71-
final m3ExpressiveTemplate = TestM3ExpressiveTemplate();
72-
const materialUiDir = 'packages/material_ui';
73-
const generatedDir = 'lib/src/generated';
74-
75-
final bool hasPackageDir = Directory(materialUiDir).existsSync();
76-
if (hasPackageDir) {
77-
expect(m3Template.materialLib, '$materialUiDir/$generatedDir');
78-
expect(
79-
m3ExpressiveTemplate.materialLib,
80-
'$materialUiDir/$generatedDir/material_3_expressive',
81-
);
82-
} else {
83-
expect(m3Template.materialLib, generatedDir);
84-
expect(m3ExpressiveTemplate.materialLib, '$generatedDir/material_3_expressive');
85-
}
77+
test('throws AssertionError if class name is not defined in generateContents', () {
78+
final template = InvalidTemplate(testPath());
79+
expect(
80+
() => template.generateFile(),
81+
throwsA(
82+
isA<AssertionError>().having(
83+
(AssertionError e) => e.message,
84+
'message',
85+
contains('Make sure you are utilizing the passed `className` parameter.'),
86+
),
87+
),
88+
);
89+
});
90+
91+
test('throws AssertionError if name is not in Spaced / TitleCase', () {
92+
final template = SnakeCaseNameTemplate(testPath());
93+
expect(
94+
() => template.generateFile(),
95+
throwsA(
96+
isA<AssertionError>().having(
97+
(AssertionError e) => e.message,
98+
'message',
99+
contains('must use spaces and capitalized words'),
100+
),
101+
),
102+
);
86103
});
87104
});
88105
}
@@ -97,15 +114,22 @@ const _fileHeader = '''
97114
// packages/material_ui/tool/gen_defaults/bin/gen_defaults.dart.
98115
''';
99116

117+
const _buttonExpressiveDefaultsClass = '''
118+
class _M3EIconButtonDefaults {
119+
static const double height = 40.0;
120+
static const double borderRadius = 8.0;
121+
}
122+
''';
123+
100124
const _buttonDefaultsClass = '''
101-
class _ButtonDefaults {
125+
class _M3IconButtonDefaults {
102126
static const double height = 40.0;
103127
static const double borderRadius = 8.0;
104128
}
105129
''';
106130

107131
const formattedClass = '''
108-
class UnformattedClass {
132+
class _M3UnformattedDefaults {
109133
final int x = 1;
110134
final String y = 'hello';
111135
}

packages/material_ui/tool/gen_defaults/test/test_fixtures/button_token_data.dart renamed to packages/material_ui/tool/gen_defaults/test/test_fixtures/icon_button_token_data.dart

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
// Use of this source code is governed by a BSD-style license that can be
33
// found in the LICENSE file.
44

5-
class TokenButton {
5+
class TokenIconButton {
66
static const double height = 40.0;
77
static const double borderRadius = 8.0;
88
}

0 commit comments

Comments
 (0)