Repository navigation
Expand file tree
/
Copy pathplugins.dart
More file actions
533 lines (485 loc) · 18.6 KB
/
Copy pathplugins.dart
File metadata and controls
533 lines (485 loc) · 18.6 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
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:pub_semver/pub_semver.dart';
import 'package:yaml/yaml.dart';
import 'base/common.dart';
import 'base/file_system.dart';
import 'platform_plugins.dart';
import 'plugin_yaml_parser.dart';
class Plugin {
Plugin({
required this.name,
required this.path,
required this.platforms,
required this.defaultPackagePlatforms,
required this.pluginDartClassPlatforms,
this.flutterConstraint,
required this.dependencies,
required this.isDirectDependency,
required this.isDevDependency,
this.implementsPackage,
});
/// Parses [Plugin] specification from the provided pluginYaml.
///
/// This currently supports two formats. Legacy and Multi-platform.
///
/// Example of the deprecated Legacy format.
///
/// flutter:
/// plugin:
/// androidPackage: io.flutter.plugins.sample
/// iosPrefix: FLT
/// pluginClass: SamplePlugin
///
/// Example Multi-platform format.
///
/// flutter:
/// plugin:
/// platforms:
/// android:
/// package: io.flutter.plugins.sample
/// pluginClass: SamplePlugin
/// ios:
/// # A plugin implemented through method channels.
/// pluginClass: SamplePlugin
/// linux:
/// # A plugin implemented purely in Dart code.
/// dartPluginClass: SamplePlugin
/// # Optional field to determine file containing dartPluginClass.
/// # This file will be used in imports in generated files, e.g.:
/// # import 'package:{{pluginName}}/{{dartFileName}}'
/// # instead of default:
/// # import 'package:{{pluginName}}/{{pluginName}}.dart'
/// dartFileName: src/sample_plugin.dart
/// macos:
/// # A plugin implemented with `dart:ffi`.
/// ffiPlugin: true
/// windows:
/// # A plugin using platform-specific Dart and method channels.
/// dartPluginClass: SamplePlugin
/// pluginClass: SamplePlugin
factory Plugin.fromYaml(
String name,
String path,
YamlMap? pluginYaml,
VersionConstraint? flutterConstraint,
List<String> dependencies, {
required bool isDevDependency,
Set<String>? appDependencies,
}) {
final ParseResult<Plugin> result = _parseFromYaml(
name,
path,
pluginYaml,
flutterConstraint,
dependencies,
isDevDependency: isDevDependency,
appDependencies: appDependencies,
);
switch (result) {
case ParseResultPass(value: final Plugin plugin):
return plugin;
case ParseResultFail(errors: final List<String> errors):
throwToolExit('Invalid plugin specification $name.\n${errors.join('\n')}');
}
}
static ParseResult<Plugin> _parseFromYaml(
String name,
String path,
YamlMap? pluginYaml,
VersionConstraint? flutterConstraint,
List<String> dependencies, {
required bool isDevDependency,
Set<String>? appDependencies,
}) {
if (pluginYaml == null) {
return .fail(<String>['Invalid "plugin" specification.']);
}
final bool usesOldPluginFormat = const <String>{
'androidPackage',
'iosPrefix',
'pluginClass',
}.any(pluginYaml.containsKey);
final bool usesNewPluginFormat = pluginYaml.containsKey('platforms');
if (usesOldPluginFormat && usesNewPluginFormat) {
const errorMessage =
'The flutter.plugin.platforms key cannot be used in combination with the old '
'flutter.plugin.{androidPackage,iosPrefix,pluginClass} keys. '
'See: https://flutter.dev/to/pubspec-plugin-platforms';
return .fail(<String>[errorMessage]);
}
if (!usesOldPluginFormat && !usesNewPluginFormat) {
const errorMessage =
'Cannot find the `flutter.plugin.platforms` key in the `pubspec.yaml` file. '
'An instruction to format the `pubspec.yaml` can be found here: '
'https://flutter.dev/to/pubspec-plugin-platforms';
return .fail(<String>[errorMessage]);
}
final bool isDirectDependency = appDependencies != null && appDependencies.contains(name);
if (usesNewPluginFormat) {
return _parseMultiPlatformYaml(
name,
path,
pluginYaml,
flutterConstraint,
dependencies,
isDirectDependency,
isDevDependency: isDevDependency,
);
}
return _parseLegacyYaml(
name,
path,
pluginYaml,
flutterConstraint,
dependencies,
isDirectDependency,
isDevDependency: isDevDependency,
);
}
static ParseResult<Plugin> _parseMultiPlatformYaml(
String name,
String path,
YamlMap pluginYaml,
VersionConstraint? flutterConstraint,
List<String> dependencies,
bool isDirectDependency, {
required bool isDevDependency,
}) {
final Object? platformsValue = pluginYaml['platforms'];
if (platformsValue is! YamlMap?) {
const errorMessage =
'flutter.plugin.platforms should be a map with the platform name as the key';
return .fail(<String>[errorMessage]);
}
if (platformsValue == null) {
return .fail(<String>['Invalid "platforms" specification.']);
}
final YamlMap platformsYaml = platformsValue;
final errors = <String>[];
final platforms = <String, PluginPlatform>{};
// TODO(stuartmorgan): Consider merging web into this common handling; the
// fact that its implementation of Dart-only plugins and default packages
// are separate is legacy.
final defaultPackages = <String, String>{};
final dartPluginClasses = <String, DartPluginClassAndFilePair>{};
void parsePlatform<T extends PluginPlatform>(
String platformKey,
ParseResult<T?> Function(YamlMap) parse, {
bool isWebPlugin = false,
}) {
if (!platformsYaml.containsKey(platformKey)) {
return;
}
final Object? yamlValue = platformsYaml[platformKey];
if (yamlValue is! YamlMap) {
if (!isWebPlugin) {
// Unlike native/Dart platforms, an empty `web:` entry (where the value is
// null rather than a YamlMap) is ignored rather than rejected, as existing
// published packages use an empty `web:` key to declare web support without
// a WebPlugin registrant class.
errors.add('Invalid "$platformKey" plugin specification.');
}
return;
}
if (isWebPlugin && yamlValue.containsKey(kDefaultPackage)) {
// Unlike native/Dart platforms, a `web:` entry with `default_package` is
// ignored.
return;
}
final parser = PluginYamlParser(yamlValue, pluginName: name, configKey: platformKey);
final ParseResult<void> result =
(parser.string(kDefaultPackage, allowNull: false), parse(yamlValue)).flatMap((
String? defaultPackage,
T? parsed,
) {
if (defaultPackage != null) {
defaultPackages[platformKey] = defaultPackage;
} else if (parsed != null) {
platforms[platformKey] = parsed;
} else {
return .fail(<String>['Invalid "$platformKey" plugin specification.']);
}
if (parsed case DartPlugin(:final String dartPluginClass, :final String dartFileName)) {
dartPluginClasses[platformKey] = (
dartClass: dartPluginClass,
dartFileName: dartFileName,
);
}
return .pass(null);
});
if (result case ParseResultFail(errors: final List<String> platformErrors)) {
errors.addAll(platformErrors);
}
}
parsePlatform(
AndroidPlugin.kConfigKey,
(YamlMap yaml) => AndroidPlugin.parseFromYaml(name, yaml, pluginPath: path),
);
parsePlatform(IOSPlugin.kConfigKey, (YamlMap yaml) => IOSPlugin.parseFromYaml(name, yaml));
parsePlatform(LinuxPlugin.kConfigKey, (YamlMap yaml) => LinuxPlugin.parseFromYaml(name, yaml));
parsePlatform(MacOSPlugin.kConfigKey, (YamlMap yaml) => MacOSPlugin.parseFromYaml(name, yaml));
parsePlatform(
WebPlugin.kConfigKey,
(YamlMap yaml) => WebPlugin.parseFromYaml(name, yaml),
isWebPlugin: true,
);
parsePlatform(
WindowsPlugin.kConfigKey,
(YamlMap yaml) => WindowsPlugin.parseFromYaml(name, yaml),
);
final Object? implementsValue = pluginYaml['implements'];
var implementsPackage = '';
if (implementsValue != null) {
if (implementsValue is String) {
implementsPackage = implementsValue;
} else {
errors.add('Invalid "implements" specification.');
}
}
if (errors.isNotEmpty) {
return .fail(errors);
}
return .pass(
Plugin(
name: name,
path: path,
platforms: platforms,
defaultPackagePlatforms: defaultPackages,
pluginDartClassPlatforms: dartPluginClasses,
flutterConstraint: flutterConstraint,
dependencies: dependencies,
isDirectDependency: isDirectDependency,
implementsPackage: implementsPackage,
isDevDependency: isDevDependency,
),
);
}
static ParseResult<Plugin> _parseLegacyYaml(
String name,
String path,
YamlMap pluginYaml,
VersionConstraint? flutterConstraint,
List<String> dependencies,
bool isDirectDependency, {
required bool isDevDependency,
}) {
final Object? androidPackage = pluginYaml['androidPackage'];
final Object? iosPrefix = pluginYaml['iosPrefix'];
final Object? pluginClass = pluginYaml['pluginClass'];
// As in the `platforms:` format, every identifier is checked here: they are
// interpolated verbatim into the generated GeneratedPluginRegistrant source
// files, so anything that is not a plain identifier would let a (possibly
// transitive) dependency inject native code into the consuming app's build.
const identifierRequirement =
'must be a valid identifier, optionally with dot-separated segments';
final errors = <String>[
if (androidPackage is! String?)
'The "androidPackage" must either be null or a string.'
else if (androidPackage != null && !isValidPluginIdentifier(androidPackage))
'The "androidPackage" $identifierRequirement.',
if (iosPrefix is! String?)
'The "iosPrefix" must either be null or a string.'
// An empty prefix is the default for a legacy plugin that does not set one.
else if (iosPrefix != null && iosPrefix.isNotEmpty && !isValidPluginIdentifier(iosPrefix))
'The "iosPrefix" $identifierRequirement.',
if (pluginClass is! String?)
'The "pluginClass" must either be null or a string.'
else if (pluginClass != null && !isValidPluginIdentifier(pluginClass))
'The "pluginClass" $identifierRequirement.',
];
if (errors.isNotEmpty) {
return .fail(errors);
}
final platforms = <String, PluginPlatform>{};
if (pluginClass is String) {
if (androidPackage is String) {
platforms[AndroidPlugin.kConfigKey] = AndroidPlugin(
name: name,
package: androidPackage,
pluginClass: pluginClass,
pluginPath: path,
);
}
platforms[IOSPlugin.kConfigKey] = IOSPlugin(
name: name,
classPrefix: iosPrefix as String? ?? '',
pluginClass: pluginClass,
);
}
return .pass(
Plugin(
name: name,
path: path,
platforms: platforms,
defaultPackagePlatforms: <String, String>{},
pluginDartClassPlatforms: <String, DartPluginClassAndFilePair>{},
flutterConstraint: flutterConstraint,
dependencies: dependencies,
isDirectDependency: isDirectDependency,
isDevDependency: isDevDependency,
),
);
}
/// Create a YamlMap that represents the supported platforms.
///
/// For example, if the `platforms` contains 'ios' and 'android', the return map looks like:
///
/// android:
/// package: io.flutter.plugins.sample
/// pluginClass: SamplePlugin
/// ios:
/// pluginClass: SamplePlugin
static YamlMap createPlatformsYamlMap(
List<String> platforms,
String pluginClass,
String androidPackage,
) {
final map = <String, dynamic>{};
for (final platform in platforms) {
map[platform] = <String, String>{
'pluginClass': pluginClass,
...platform == 'android' ? <String, String>{'package': androidPackage} : <String, String>{},
};
}
return YamlMap.wrap(map);
}
static List<String> validatePluginYaml(YamlMap? yaml, {required String packageName}) {
final ParseResult<Plugin> result = _parseFromYaml(
packageName,
'',
yaml,
null,
const <String>[],
isDevDependency: false,
);
return switch (result) {
ParseResultFail(:final List<String> errors) => errors,
ParseResultPass() => const <String>[],
};
}
final String name;
final String path;
/// The name of the interface package that this plugin implements.
/// If `null`, this plugin doesn't implement an interface.
final String? implementsPackage;
/// The required version of Flutter, if specified.
final VersionConstraint? flutterConstraint;
/// The name of the packages this plugin depends on.
final List<String> dependencies;
/// This is a mapping from platform config key to the plugin platform spec.
final Map<String, PluginPlatform> platforms;
/// This is a mapping from platform config key to the default package implementation.
final Map<String, String> defaultPackagePlatforms;
/// This is a mapping from platform config key to the Dart plugin class for the given platform.
final Map<String, DartPluginClassAndFilePair> pluginDartClassPlatforms;
/// Whether this plugin is a direct dependency of the app.
/// If `false`, the plugin is a dependency of another plugin.
final bool isDirectDependency;
/// Whether this plugin is exclusively used as a dev dependency of the app.
///
/// If `false`, the plugin is either:
/// - _Not_ a dev dependency
/// - _Not_ a dev dependency of some dependency that itself is not a dev
/// dependency
///
/// Dev dependencies are intended to be stripped out in release builds.
final bool isDevDependency;
/// Expected path to the plugin's swift package, which contains the Package.swift.
///
/// This path should be `/path/to/[package_name]/[platform]/[package_name]`
/// (e.g. `/path/to/my_plugin/ios/my_plugin`).
///
/// Returns null if the plugin does not support the [platform] or the
/// [platform] is not iOS or macOS.
///
/// If [overridePath] is provided, returns `[overridePath]/[platform]/[package_name]`.
String? pluginSwiftPackagePath(FileSystem fileSystem, String platform, {String? overridePath}) {
final String? platformDirectoryName = _darwinPluginDirectoryName(platform);
if (platformDirectoryName == null) {
return null;
}
if (overridePath != null) {
return fileSystem.path.join(overridePath, platformDirectoryName, name);
}
return fileSystem.path.join(path, platformDirectoryName, name);
}
/// Expected path to the plugin's Package.swift. Returns null if the plugin
/// does not support the [platform] or the [platform] is not iOS or macOS.
String? pluginSwiftPackageManifestPath(FileSystem fileSystem, String platform) {
final String? packagePath = pluginSwiftPackagePath(fileSystem, platform);
if (packagePath == null) {
return null;
}
return fileSystem.path.join(packagePath, 'Package.swift');
}
/// Returns true if the plugin supports the [platform] and a Package.swift exists.
bool supportSwiftPackageManagerForPlatform(FileSystem fileSystem, String platform) {
final String? manifestPath = pluginSwiftPackageManifestPath(fileSystem, platform);
return platforms[platform] != null &&
manifestPath != null &&
fileSystem.file(manifestPath).existsSync();
}
/// Returns true if the plugin supports the [platform] and a podspec exists.
bool supportCocoapodsForPlatform(FileSystem fileSystem, String platform) {
final String? podspecPath = pluginPodspecPath(fileSystem, platform);
return platforms[platform] != null &&
podspecPath != null &&
fileSystem.file(podspecPath).existsSync();
}
/// Expected path to the plugin's podspec. Returns null if the plugin does
/// not support the [platform] or the [platform] is not iOS or macOS.
String? pluginPodspecPath(FileSystem fileSystem, String platform) {
final String? platformDirectoryName = _darwinPluginDirectoryName(platform);
if (platformDirectoryName == null) {
return null;
}
return fileSystem.path.join(path, platformDirectoryName, '$name.podspec');
}
String? _darwinPluginDirectoryName(String platform) {
final PluginPlatform? platformPlugin = platforms[platform];
if (platformPlugin == null ||
(platform != IOSPlugin.kConfigKey && platform != MacOSPlugin.kConfigKey)) {
return null;
}
// iOS and macOS code can be shared in "darwin" directory, otherwise
// respectively in "ios" or "macos" directories.
if (platformPlugin is DarwinPlugin && (platformPlugin as DarwinPlugin).sharedDarwinSource) {
return 'darwin';
}
return platform;
}
}
/// Metadata associated with the resolution of a platform interface of a plugin.
class PluginInterfaceResolution {
PluginInterfaceResolution({required this.plugin, required this.platform});
/// The plugin.
final Plugin plugin;
/// The name of the platform that this plugin implements.
final String platform;
Map<String, String> toMap() {
return <String, String>{
'pluginName': plugin.name,
'platform': platform,
'dartClass': plugin.pluginDartClassPlatforms[platform]?.dartClass ?? '',
'dartFileName': plugin.pluginDartClassPlatforms[platform]?.dartFileName ?? '',
};
}
@override
String toString() {
return '<PluginInterfaceResolution ${plugin.name} for $platform>';
}
}
/// A record representing pair of dartPluginClass and dartFileName used as metadata
/// in [PluginInterfaceResolution].
///
/// The `dartClass` and `dartFileName` fields are guaranteed to be non-null:
///
/// - record should be created only if dartClassName exists in plugin configuration.
/// - dartFileName either taken from configuration, or, if absent, should be
/// constructed from plugin name.
///
/// See also:
/// - [PluginInterfaceResolution], which uses this record to create Map with metadata.
typedef DartPluginClassAndFilePair = ({String dartClass, String dartFileName});