forked from FlutterGen/flutter_gen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
assets_generator.dart
607 lines (551 loc) · 23.2 KB
/
assets_generator.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
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
import 'dart:collection';
import 'dart:io';
import 'package:collection/collection.dart';
import 'package:dart_style/dart_style.dart';
import 'package:dartx/dartx.dart';
import 'package:glob/glob.dart';
import 'package:path/path.dart';
import '../settings/asset_type.dart';
import '../settings/config.dart';
import '../settings/pubspec.dart';
import '../utils/error.dart';
import '../utils/string.dart';
import 'generator_helper.dart';
import 'integrations/flare_integration.dart';
import 'integrations/integration.dart';
import 'integrations/rive_integration.dart';
import 'integrations/svg_integration.dart';
import 'integrations/lottie_integration.dart';
class AssetsGenConfig {
AssetsGenConfig._(
this.rootPath,
this._packageName,
this.flutterGen,
this.assets,
this.exclude,
);
factory AssetsGenConfig.fromConfig(File pubspecFile, Config config) {
return AssetsGenConfig._(
pubspecFile.parent.absolute.path,
config.pubspec.packageName,
config.pubspec.flutterGen,
config.pubspec.flutter.assets,
config.pubspec.flutterGen.assets.exclude
.map((pattern) => Glob(pattern))
.toList(),
);
}
final String rootPath;
final String _packageName;
final FlutterGen flutterGen;
final List<String> assets;
final List<Glob> exclude;
String get packageParameterLiteral =>
flutterGen.assets.outputs.packageParameterEnabled ? _packageName : '';
}
String generateAssets(
AssetsGenConfig config,
DartFormatter formatter,
) {
if (config.assets.isEmpty) {
throw const InvalidSettingsException(
'The value of "flutter/assets:" is incorrect.');
}
final importsBuffer = StringBuffer();
final classesBuffer = StringBuffer();
final integrations = <Integration>[
if (config.flutterGen.integrations.flutterSvg)
SvgIntegration(config.packageParameterLiteral),
if (config.flutterGen.integrations.flareFlutter)
FlareIntegration(config.packageParameterLiteral),
if (config.flutterGen.integrations.rive)
RiveIntegration(config.packageParameterLiteral),
if (config.flutterGen.integrations.lottie)
LottieIntegration(config.packageParameterLiteral),
];
// TODO: This code will be removed.
// ignore: deprecated_member_use_from_same_package
final deprecatedStyle = config.flutterGen.assets.style != null;
final deprecatedPackageParam =
// ignore: deprecated_member_use_from_same_package
config.flutterGen.assets.packageParameterEnabled != null;
if (deprecatedStyle || deprecatedPackageParam) {
stderr.writeln('''
░░░░
██
██░░██
░░ ░░ ██░░░░░░██ ░░░░
██░░░░░░░░░░██
██░░░░░░░░░░██
██░░░░░░░░░░░░░░██
██░░░░░░██████░░░░░░██
██░░░░░░██████░░░░░░██
██░░░░░░░░██████░░░░░░░░██
██░░░░░░░░██████░░░░░░░░██
██░░░░░░░░░░██████░░░░░░░░░░██
██░░░░░░░░░░░░██████░░░░░░░░░░░░██
██░░░░░░░░░░░░██████░░░░░░░░░░░░██
██░░░░░░░░░░░░░░██████░░░░░░░░░░░░░░██
██░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░██
██░░░░░░░░░░░░░░░░██████░░░░░░░░░░░░░░░░██
██░░░░░░░░░░░░░░░░██████░░░░░░░░░░░░░░░░██
██░░░░░░░░░░░░░░░░░░██████░░░░░░░░░░░░░░░░░░██
░░ ██░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░██
██████████████████████████████████████████
░░''');
}
if (deprecatedStyle && deprecatedPackageParam) {
stderr.writeln('''
┌────────────────────────────────────────────────────────────────────────────────────────────────┐
│ ⚠️ Warning │
│ The `style` and `package_parameter_enabled` property moved from asset to under asset.output. │
│ It should be changed in the following pubspec.yaml. │
│ https://github.com/FlutterGen/flutter_gen/pull/294 │
│ │
│ [pubspec.yaml] │
│ │
│ fluttergen: │
│ assets: │
│ outputs: │
│ style: snake-case │
│ package_parameter_enabled: true │
└────────────────────────────────────────────────────────────────────────────────────────────────┘''');
} else if (deprecatedStyle) {
stderr.writeln('''
┌───────────────────────────────────────────────────────────────────────┐
│ ⚠️ Warning │
│ The `style` property moved from asset to under asset.output. │
│ It should be changed in the following ways │
│ https://github.com/FlutterGen/flutter_gen/pull/294 │
│ │
│ [pubspec.yaml] │
│ │
│ fluttergen: │
│ assets: │
│ outputs: │
│ style: snake-case │
└───────────────────────────────────────────────────────────────────────┘''');
} else if (deprecatedPackageParam) {
stderr.writeln('''
┌────────────────────────────────────────────────────────────────────────────────────────┐
│ ⚠️ Warning │
│ The `package_parameter_enabled` property moved from asset to under asset.output. │
│ It should be changed in the following pubspec.yaml. │
│ https://github.com/FlutterGen/flutter_gen/pull/294 │
│ │
│ [pubspec.yaml] │
│ │
│ fluttergen: │
│ assets: │
│ outputs: │
│ package_parameter_enabled: true │
└────────────────────────────────────────────────────────────────────────────────────────┘''');
}
if (config.flutterGen.assets.outputs.isDotDelimiterStyle) {
classesBuffer.writeln(_dotDelimiterStyleDefinition(config, integrations));
} else if (config.flutterGen.assets.outputs.isSnakeCaseStyle) {
classesBuffer.writeln(_snakeCaseStyleDefinition(config, integrations));
} else if (config.flutterGen.assets.outputs.isCamelCaseStyle) {
classesBuffer.writeln(_camelCaseStyleDefinition(config, integrations));
} else {
throw 'The value of "flutter_gen/assets/style." is incorrect.';
}
classesBuffer.writeln(_assetGenImageClassDefinition(
config.packageParameterLiteral,
));
final imports = <String>{'package:flutter/widgets.dart'};
integrations
.where((integration) => integration.isEnabled)
.forEach((integration) {
imports.addAll(integration.requiredImports);
classesBuffer.writeln(integration.classOutput);
});
for (final package in imports) {
importsBuffer.writeln(import(package));
}
final buffer = StringBuffer();
buffer.writeln(header);
buffer.writeln(ignore);
buffer.writeln(importsBuffer.toString());
buffer.writeln(classesBuffer.toString());
return formatter.format(buffer.toString());
}
List<String> _getAssetRelativePathList(
String rootPath,
List<String> assets,
List<Glob> excludes,
) {
final assetRelativePathList = <String>[];
for (final assetName in assets) {
final assetAbsolutePath = join(rootPath, assetName);
if (FileSystemEntity.isDirectorySync(assetAbsolutePath)) {
assetRelativePathList.addAll(Directory(assetAbsolutePath)
.listSync()
.whereType<File>()
.map((e) => relative(e.path, from: rootPath))
.toList());
} else if (FileSystemEntity.isFileSync(assetAbsolutePath)) {
assetRelativePathList.add(relative(assetAbsolutePath, from: rootPath));
}
}
if (excludes.isEmpty) {
return assetRelativePathList;
}
return assetRelativePathList
.where((file) => !excludes.any((exclude) => exclude.matches(file)))
.toList();
}
AssetType _constructAssetTree(
List<String> assetRelativePathList, String rootPath) {
// Relative path is the key
final assetTypeMap = <String, AssetType>{
'.': AssetType(rootPath: rootPath, path: '.'),
};
for (final assetPath in assetRelativePathList) {
var path = assetPath;
while (path != '.') {
assetTypeMap.putIfAbsent(
path, () => AssetType(rootPath: rootPath, path: path));
path = dirname(path);
}
}
// Construct the AssetType tree
for (final assetType in assetTypeMap.values) {
if (assetType.path == '.') {
continue;
}
final parentPath = dirname(assetType.path);
assetTypeMap[parentPath]?.addChild(assetType);
}
return assetTypeMap['.']!;
}
_Statement? _createAssetTypeStatement(
String rootPath,
AssetType assetType,
List<Integration> integrations,
String name,
) {
final childAssetAbsolutePath = join(rootPath, assetType.path);
if (assetType.isSupportedImage) {
return _Statement(
type: 'AssetGenImage',
filePath: assetType.path,
name: name,
value: 'AssetGenImage(\'${posixStyle(assetType.path)}\')',
isConstConstructor: true,
isDirectory: false,
needDartDoc: true,
);
} else if (FileSystemEntity.isDirectorySync(childAssetAbsolutePath)) {
final childClassName = '\$${assetType.path.camelCase().capitalize()}Gen';
return _Statement(
type: childClassName,
filePath: assetType.path,
name: name,
value: '$childClassName()',
isConstConstructor: true,
isDirectory: true,
needDartDoc: false,
);
} else if (!assetType.isIgnoreFile) {
final integration = integrations.firstWhereOrNull(
(element) => element.isSupport(assetType),
);
if (integration == null) {
return _Statement(
type: 'String',
filePath: assetType.path,
name: name,
value: '\'${posixStyle(assetType.path)}\'',
isConstConstructor: false,
isDirectory: false,
needDartDoc: true,
);
} else {
integration.isEnabled = true;
return _Statement(
type: integration.className,
filePath: assetType.path,
name: name,
value: integration.classInstantiate(posixStyle(assetType.path)),
isConstConstructor: integration.isConstConstructor,
isDirectory: false,
needDartDoc: true,
);
}
}
return null;
}
/// Generate style like Assets.foo.bar
String _dotDelimiterStyleDefinition(
AssetsGenConfig config,
List<Integration> integrations,
) {
final buffer = StringBuffer();
final className = config.flutterGen.assets.outputs.className;
final assetRelativePathList = _getAssetRelativePathList(
config.rootPath,
config.assets,
config.exclude,
);
final assetsStaticStatements = <_Statement>[];
final assetTypeQueue = ListQueue<AssetType>.from(
_constructAssetTree(assetRelativePathList, config.rootPath).children);
while (assetTypeQueue.isNotEmpty) {
final assetType = assetTypeQueue.removeFirst();
final assetAbsolutePath = join(config.rootPath, assetType.path);
if (FileSystemEntity.isDirectorySync(assetAbsolutePath)) {
final statements = assetType.children
.mapToIsUniqueWithoutExtension()
.map(
(e) => _createAssetTypeStatement(
config.rootPath,
e.assetType,
integrations,
(e.isUniqueWithoutExtension
? basenameWithoutExtension(e.assetType.path)
: basename(e.assetType.path))
.camelCase(),
),
)
.whereType<_Statement>()
.toList();
if (assetType.isDefaultAssetsDirectory) {
assetsStaticStatements.addAll(statements);
} else {
final className = '\$${assetType.path.camelCase().capitalize()}Gen';
buffer.writeln(_directoryClassGenDefinition(className, statements));
// Add this directory reference to Assets class
// if we are not under the default asset folder
if (dirname(assetType.path) == '.') {
assetsStaticStatements.add(_Statement(
type: className,
filePath: assetType.path,
name: assetType.baseName.camelCase(),
value: '$className()',
isConstConstructor: true,
isDirectory: true,
needDartDoc: true,
));
}
}
assetTypeQueue.addAll(assetType.children);
}
}
buffer.writeln(_dotDelimiterStyleAssetsClassDefinition(
className, assetsStaticStatements));
return buffer.toString();
}
/// Generate style like Assets.fooBar
String _camelCaseStyleDefinition(
AssetsGenConfig config,
List<Integration> integrations,
) {
return _flatStyleDefinition(
config,
integrations,
(e) => (e.isUniqueWithoutExtension
? withoutExtension(e.assetType.path)
: e.assetType.path)
.replaceFirst(RegExp(r'asset(s)?'), '')
.camelCase(),
);
}
/// Generate style like Assets.foo_bar
String _snakeCaseStyleDefinition(
AssetsGenConfig config,
List<Integration> integrations,
) {
return _flatStyleDefinition(
config,
integrations,
(e) => (e.isUniqueWithoutExtension
? withoutExtension(e.assetType.path)
: e.assetType.path)
.replaceFirst(RegExp(r'asset(s)?'), '')
.snakeCase(),
);
}
String _flatStyleDefinition(
AssetsGenConfig config,
List<Integration> integrations,
String Function(AssetTypeIsUniqueWithoutExtension) createName,
) {
final statements = _getAssetRelativePathList(
config.rootPath,
config.assets,
config.exclude,
)
.distinct()
.sorted()
.map((assetPath) => AssetType(rootPath: config.rootPath, path: assetPath))
.mapToIsUniqueWithoutExtension()
.map(
(e) => _createAssetTypeStatement(
config.rootPath,
e.assetType,
integrations,
createName(e),
),
)
.whereType<_Statement>()
.toList();
final className = config.flutterGen.assets.outputs.className;
return _flatStyleAssetsClassDefinition(className, statements);
}
String _flatStyleAssetsClassDefinition(
String className,
List<_Statement> statements,
) {
final statementsBlock =
statements.map((statement) => '''${statement.toDartDocString()}
${statement.toStaticFieldString()}
''').join('\n');
return _assetsClassDefinition(className, statements, statementsBlock);
}
String _dotDelimiterStyleAssetsClassDefinition(
String className,
List<_Statement> statements,
) {
final statementsBlock =
statements.map((statement) => statement.toStaticFieldString()).join('\n');
return _assetsClassDefinition(className, statements, statementsBlock);
}
String _assetValuesDefinition(List<_Statement> statements) {
final values = statements.where((element) => !element.isDirectory);
if (values.isEmpty) return '';
final names = values.map((value) => value.name).join(', ');
var type = values.first.type;
for (var value in values) {
if (type != value.type) {
type = 'dynamic';
break;
}
}
return '''
/// List of all assets
List<$type> get values => [$names];''';
}
String _assetsClassDefinition(
String className,
List<_Statement> statements,
String statementsBlock,
) {
final valuesBlock = _assetValuesDefinition(statements);
return '''
class $className {
$className._();
$statementsBlock
$valuesBlock
}
''';
}
String _directoryClassGenDefinition(
String className,
List<_Statement> statements,
) {
final statementsBlock = statements
.map((statement) => statement.needDartDoc
? '''${statement.toDartDocString()}
${statement.toGetterString()}
'''
: statement.toGetterString())
.join('\n');
final valuesBlock = _assetValuesDefinition(statements);
return '''
class $className {
const $className();
$statementsBlock
$valuesBlock
}
''';
}
String _assetGenImageClassDefinition(String packageName) {
final packageParameter = packageName.isNotEmpty ? " = '$packageName'" : '';
final keyName = packageName.isEmpty
? '_assetName'
: "'packages/$packageName/\$_assetName'";
return '''
class AssetGenImage {
const AssetGenImage(this._assetName);
final String _assetName;
Image image({
Key? key,
AssetBundle? bundle,
ImageFrameBuilder? frameBuilder,
ImageErrorWidgetBuilder? errorBuilder,
String? semanticLabel,
bool excludeFromSemantics = false,
double? scale,
double? width,
double? height,
Color? color,
Animation<double>? opacity,
BlendMode? colorBlendMode,
BoxFit? fit,
AlignmentGeometry alignment = Alignment.center,
ImageRepeat repeat = ImageRepeat.noRepeat,
Rect? centerSlice,
bool matchTextDirection = false,
bool gaplessPlayback = false,
bool isAntiAlias = false,
String? package$packageParameter,
FilterQuality filterQuality = FilterQuality.low,
int? cacheWidth,
int? cacheHeight,
}) {
return Image.asset(
_assetName,
key: key,
bundle: bundle,
frameBuilder: frameBuilder,
errorBuilder: errorBuilder,
semanticLabel: semanticLabel,
excludeFromSemantics: excludeFromSemantics,
scale: scale,
width: width,
height: height,
color: color,
opacity: opacity,
colorBlendMode: colorBlendMode,
fit: fit,
alignment: alignment,
repeat: repeat,
centerSlice: centerSlice,
matchTextDirection: matchTextDirection,
gaplessPlayback: gaplessPlayback,
isAntiAlias: isAntiAlias,
package: package,
filterQuality: filterQuality,
cacheWidth: cacheWidth,
cacheHeight: cacheHeight,
);
}
ImageProvider provider() => AssetImage(_assetName);
String get path => _assetName;
String get keyName => $keyName;
}
''';
}
class _Statement {
const _Statement({
required this.type,
required this.filePath,
required this.name,
required this.value,
required this.isConstConstructor,
required this.isDirectory,
required this.needDartDoc,
});
final String type;
final String filePath;
final String name;
final String value;
final bool isConstConstructor;
final bool isDirectory;
final bool needDartDoc;
String toDartDocString() => '/// File path: ${posixStyle(filePath)}';
String toGetterString() =>
'$type get $name => ${isConstConstructor ? 'const' : ''} $value;';
String toStaticFieldString() => 'static const $type $name = $value;';
}