Skip to content

Commit 129b42b

Browse files
authored
[material_ui] Set up gen_defaults sub-directory (#11762)
Work towards flutter/flutter#186906 Adds the initial `gen_defaults` sub-directory with the initial `TokenTemplate` and generator. This is simply the initial scaffold, we will need to add additional helper functions as necessary as we begin adding the actual templates. ## Pre-Review Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [AI contribution guidelines] and understand my responsibilities, or I am not using AI tools. - [x] I read the [Tree Hygiene] page, which explains my responsibilities. - [x] I read and followed the [relevant style guides] and ran [the auto-formatter]. - [x] I signed the [CLA]. - [x] The title of the PR starts with the name of the package surrounded by square brackets, e.g. `[shared_preferences]` - [x] I [linked to at least one issue that this PR fixes] in the description above. - [x] I followed [the version and CHANGELOG instructions], using [semantic versioning] and the [repository CHANGELOG style], or I have commented below to indicate which documented exception this PR falls under[^1]. - [x] I updated/added any relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or I have commented below to indicate which [test exemption] this PR falls under[^1]. - [ ] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. **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. <!-- Links --> [Contributor Guide]: https://github.com/flutter/packages/blob/main/CONTRIBUTING.md [AI contribution guidelines]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#ai-contribution-guidelines [Tree Hygiene]: https://github.com/flutter/flutter/blob/master/docs/contributing/Tree-hygiene.md [relevant style guides]: https://github.com/flutter/packages/blob/main/CONTRIBUTING.md#style [the auto-formatter]: https://github.com/flutter/packages/blob/main/script/tool/README.md#format-code [CLA]: https://cla.developers.google.com/ [Discord]: https://github.com/flutter/flutter/blob/master/docs/contributing/Chat.md [linked to at least one issue that this PR fixes]: https://github.com/flutter/flutter/blob/master/docs/contributing/Tree-hygiene.md#overview [the version and CHANGELOG instructions]: https://github.com/flutter/flutter/blob/master/docs/ecosystem/contributing/README.md#version-and-changelog-updates [semantic versioning]: https://dart.dev/tools/pub/versioning#semantic-versions [repository CHANGELOG style]: https://github.com/flutter/flutter/blob/master/docs/ecosystem/contributing/README.md#changelog-style [test exemption]: https://github.com/flutter/flutter/blob/master/docs/contributing/Tree-hygiene.md#tests
1 parent 819f04e commit 129b42b

9 files changed

Lines changed: 371 additions & 0 deletions

File tree

‎packages/material_ui/pubspec.yaml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ environment:
1111

1212
workspace:
1313
- example
14+
- tool/gen_defaults
1415

1516
dependencies:
1617
cupertino_ui:
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
## Token Defaults Generator
2+
3+
Script that generates component theme data defaults based on token data.
4+
5+
## Usage
6+
Run this program from the root of the git repository:
7+
```sh
8+
dart packages/material_ui/tool/gen_defaults/bin/gen_defaults.dart [-v]
9+
```
10+
11+
This updates generated component theming files under
12+
`packages/material_ui/lib/src/generated`.
13+
14+
## Templates
15+
16+
There is a template file for every component that needs defaults from the token
17+
database. These templates are implemented as subclasses of either `M3TokenTemplate` or `M3ETokenTemplate`.
18+
19+
Templates need to override the `generateContents` method to provide the
20+
generated code block as a string.
21+
22+
## Tokens
23+
24+
Tokens are stored in `data/`, and are sourced from an internal Google database.
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
include: ../../../../analysis_options.yaml
2+
3+
formatter:
4+
page_width: 100
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Copyright 2013 The Flutter Authors
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
//
5+
// ## Usage
6+
//
7+
// Run from the root of flutter/packages:
8+
//
9+
// ```
10+
// dart packages/material_ui/tool/gen_defaults/bin/gen_defaults.dart [-v]
11+
// ```
12+
13+
import 'package:args/args.dart';
14+
15+
// TODO(elliette): Import template files.
16+
// import '../templates/x_template.dart';
17+
18+
Future<void> main(List<String> args) async {
19+
// Parse arguments
20+
final parser = ArgParser();
21+
parser.addFlag('verbose', abbr: 'v', help: 'Enable verbose output', negatable: false);
22+
final ArgResults argResults = parser.parse(args);
23+
// TODO(elliette): Add token logger when verbose flag is used.
24+
// ignore: unused_local_variable
25+
final verbose = argResults['verbose'] as bool;
26+
// TODO(elliette): Invoke template generators.
27+
// const XTemplate().generateFile(verbose: verbose);
28+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
name: gen_defaults
2+
description: A command line script to generate Material component defaults from the token database.
3+
publish_to: none
4+
version: 1.0.0
5+
6+
environment:
7+
sdk: ^3.10.0-0
8+
9+
resolution: workspace
10+
11+
dependencies:
12+
args: any
13+
meta: any
14+
15+
dev_dependencies:
16+
path: any
17+
test: any
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
// Copyright 2013 The Flutter Authors
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
import 'dart:io';
6+
7+
import 'package:meta/meta.dart';
8+
9+
enum _MaterialVersion { material3, material3Expressive }
10+
11+
abstract class M3TokenTemplate extends _TokenTemplate {
12+
const M3TokenTemplate();
13+
14+
@override
15+
_MaterialVersion get _version => _MaterialVersion.material3;
16+
}
17+
18+
abstract class M3ETokenTemplate extends _TokenTemplate {
19+
const M3ETokenTemplate();
20+
21+
@override
22+
_MaterialVersion get _version => _MaterialVersion.material3Expressive;
23+
}
24+
25+
abstract class _TokenTemplate {
26+
const _TokenTemplate();
27+
28+
static const String copyrightHeader = '''
29+
// Copyright 2013 The Flutter Authors
30+
// Use of this source code is governed by a BSD-style license that can be
31+
// found in the LICENSE file.
32+
''';
33+
34+
static const String headerComment = '''
35+
36+
// Do not edit by hand. The code is generated from data in the Material
37+
// Design token database by the script:
38+
// packages/material_ui/tool/gen_defaults/bin/gen_defaults.dart.
39+
''';
40+
41+
/// The Material version this template is for.
42+
_MaterialVersion get _version;
43+
44+
/// The name of the template, which corresponds to the target file name.
45+
/// E.g., 'typography' for generating 'typography_defaults.g.dart'.
46+
String get name;
47+
48+
@visibleForTesting
49+
String get materialLib {
50+
const packagePath = 'packages/material_ui';
51+
const generatedDirectory = 'lib/src/generated';
52+
final String relativeOutputPath = switch (_version) {
53+
_MaterialVersion.material3 => generatedDirectory,
54+
_MaterialVersion.material3Expressive => '$generatedDirectory/material_3_expressive',
55+
};
56+
if (Directory(packagePath).existsSync()) {
57+
return '$packagePath/$relativeOutputPath';
58+
}
59+
return relativeOutputPath;
60+
}
61+
62+
String generateContents();
63+
64+
void generateFile({bool verbose = false}) {
65+
final fileName = '$materialLib/${name}_defaults.g.dart';
66+
if (verbose) {
67+
stdout.writeln('Generating file: $fileName');
68+
stdout.writeln('Target parent file name: $name.dart');
69+
}
70+
final file = File(fileName);
71+
if (!file.existsSync()) {
72+
if (verbose) {
73+
stdout.writeln('File does not exist, creating it.');
74+
}
75+
file.createSync(recursive: true);
76+
}
77+
78+
final parentName = '$name.dart';
79+
80+
if (verbose) {
81+
stdout.writeln('Generating contents...');
82+
}
83+
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());
92+
93+
if (verbose) {
94+
stdout.writeln('Writing generated contents to $fileName...');
95+
}
96+
file.writeAsStringSync(buffer.toString());
97+
if (verbose) {
98+
stdout.writeln('Formatting $fileName...');
99+
}
100+
final ProcessResult result = Process.runSync(Platform.resolvedExecutable, <String>[
101+
'format',
102+
fileName,
103+
]);
104+
if (result.exitCode != 0) {
105+
stderr.writeln('Failed to format $fileName: ${result.stderr}');
106+
}
107+
if (verbose) {
108+
stdout.writeln('Done generating $fileName.');
109+
}
110+
}
111+
}
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
// Copyright 2013 The Flutter Authors
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
import 'dart:io';
6+
7+
import 'package:test/test.dart';
8+
import 'test_fixtures/test_templates.dart';
9+
10+
void main() {
11+
Directory? tempDir;
12+
String testPath() => tempDir!.path;
13+
14+
group('gen_defaults templates', () {
15+
setUp(() {
16+
tempDir = Directory.systemTemp.createTempSync('gen_defaults');
17+
});
18+
19+
tearDown(() {
20+
tempDir!.deleteSync(recursive: true);
21+
});
22+
23+
test('will generate a part file ending in _defaults.g.dart', () {
24+
final template = ButtonTemplate(testPath());
25+
template.generateFile(verbose: true);
26+
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+
});
48+
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);
53+
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+
});
60+
61+
test('will run dart format over the generated file', () {
62+
final template = UnformattedTemplate(testPath());
63+
template.generateFile();
64+
65+
final file = File('${testPath()}/unformatted_defaults.g.dart');
66+
expect(file.readAsStringSync(), contains(formattedClass));
67+
});
68+
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+
}
86+
});
87+
});
88+
}
89+
90+
const _fileHeader = '''
91+
// Copyright 2013 The Flutter Authors
92+
// Use of this source code is governed by a BSD-style license that can be
93+
// found in the LICENSE file.
94+
95+
// Do not edit by hand. The code is generated from data in the Material
96+
// Design token database by the script:
97+
// packages/material_ui/tool/gen_defaults/bin/gen_defaults.dart.
98+
''';
99+
100+
const _buttonDefaultsClass = '''
101+
class _ButtonDefaults {
102+
static const double height = 40.0;
103+
static const double borderRadius = 8.0;
104+
}
105+
''';
106+
107+
const formattedClass = '''
108+
class UnformattedClass {
109+
final int x = 1;
110+
final String y = 'hello';
111+
}
112+
''';
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
// Copyright 2013 The Flutter Authors
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
class TokenButton {
6+
static const double height = 40.0;
7+
static const double borderRadius = 8.0;
8+
}
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
// Copyright 2013 The Flutter Authors
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
import '../../templates/template.dart';
6+
import 'button_token_data.dart';
7+
8+
class ButtonTemplate extends M3ETokenTemplate {
9+
ButtonTemplate(this.customMaterialLib);
10+
11+
final String customMaterialLib;
12+
13+
@override
14+
String get name => 'button';
15+
16+
@override
17+
String get materialLib => customMaterialLib;
18+
19+
@override
20+
String generateContents() {
21+
return '''
22+
class _ButtonDefaults {
23+
static const double height = ${TokenButton.height};
24+
static const double borderRadius = ${TokenButton.borderRadius};
25+
}
26+
''';
27+
}
28+
}
29+
30+
class UnformattedTemplate extends M3TokenTemplate {
31+
UnformattedTemplate(this.customMaterialLib);
32+
33+
final String customMaterialLib;
34+
35+
@override
36+
String get name => 'unformatted';
37+
38+
@override
39+
String get materialLib => customMaterialLib;
40+
41+
@override
42+
String generateContents() {
43+
return '''
44+
class UnformattedClass {
45+
final int x = 1 ;
46+
final String y = 'hello' ;
47+
}
48+
''';
49+
}
50+
}
51+
52+
class TestM3Template extends M3TokenTemplate {
53+
@override
54+
String get name => 'm3';
55+
56+
@override
57+
String generateContents() => '';
58+
}
59+
60+
class TestM3ExpressiveTemplate extends M3ETokenTemplate {
61+
@override
62+
String get name => 'm3e';
63+
64+
@override
65+
String generateContents() => '';
66+
}

0 commit comments

Comments
 (0)