Use XML format in PlistParser (#94863)

* Switch to use xml in PlistParser

* Review feedbacks: Change dynamic to Object, remove getValueFromFile
This commit is contained in:
Lau Ching Jun
2021-12-13 18:22:29 -08:00
committed by GitHub
parent 5691671194
commit 8186fb7435
9 changed files with 158 additions and 66 deletions

View File

@@ -500,7 +500,7 @@ class IntelliJValidatorOnMac extends IntelliJValidator {
@override
String get version {
return _version ??= _plistParser.getValueFromFile(
return _version ??= _plistParser.getStringValueFromFile(
plistFile,
PlistParser.kCFBundleShortVersionStringKey,
) ?? 'unknown';
@@ -514,7 +514,7 @@ class IntelliJValidatorOnMac extends IntelliJValidator {
}
final String? altLocation = _plistParser
.getValueFromFile(plistFile, 'JetBrainsToolboxApp');
.getStringValueFromFile(plistFile, 'JetBrainsToolboxApp');
if (altLocation != null) {
_pluginsPath = '$altLocation.plugins';

View File

@@ -56,7 +56,7 @@ abstract class IOSApp extends ApplicationPackage {
globals.printError('Invalid prebuilt iOS app. Does not contain Info.plist.');
return null;
}
final String? id = globals.plistParser.getValueFromFile(
final String? id = globals.plistParser.getStringValueFromFile(
plistPath,
PlistParser.kCFBundleIdentifierKey,
);

View File

@@ -27,7 +27,7 @@ Future<void> validateBitcode(BuildMode buildMode, TargetPlatform targetPlatform,
final String? clangVersion = clangResult?.stdout.split('\n').first;
final String? engineClangVersion = flutterFrameworkPath == null
? null
: globals.plistParser.getValueFromFile(
: globals.plistParser.getStringValueFromFile(
globals.fs.path.join(flutterFrameworkPath, 'Info.plist'),
'ClangVersion',
);

View File

@@ -3,12 +3,12 @@
// found in the LICENSE file.
import 'package:process/process.dart';
import 'package:xml/xml.dart';
import '../base/file_system.dart';
import '../base/io.dart';
import '../base/logger.dart';
import '../base/process.dart';
import '../base/utils.dart';
import '../convert.dart';
class PlistParser {
@@ -28,6 +28,33 @@ class PlistParser {
static const String kCFBundleShortVersionStringKey = 'CFBundleShortVersionString';
static const String kCFBundleExecutable = 'CFBundleExecutable';
/// Returns the content, converted to XML, of the plist file located at
/// [plistFilePath].
///
/// If [plistFilePath] points to a non-existent file or a file that's not a
/// valid property list file, this will return null.
///
/// The [plistFilePath] argument must not be null.
String? plistXmlContent(String plistFilePath) {
const String executable = '/usr/bin/plutil';
if (!_fileSystem.isFileSync(executable)) {
throw const FileNotFoundException(executable);
}
final List<String> args = <String>[
executable, '-convert', 'xml1', '-o', '-', plistFilePath,
];
try {
final String xmlContent = _processUtils.runSync(
args,
throwOnError: true,
).stdout.trim();
return xmlContent;
} on ProcessException catch (error) {
_logger.printTrace('$error');
return null;
}
}
/// Parses the plist file located at [plistFilePath] and returns the
/// associated map of key/value property list pairs.
///
@@ -35,35 +62,75 @@ class PlistParser {
/// valid property list file, this will return an empty map.
///
/// The [plistFilePath] argument must not be null.
Map<String, dynamic> parseFile(String plistFilePath) {
Map<String, Object> parseFile(String plistFilePath) {
assert(plistFilePath != null);
const String executable = '/usr/bin/plutil';
if (!_fileSystem.isFileSync(executable)) {
throw const FileNotFoundException(executable);
}
if (!_fileSystem.isFileSync(plistFilePath)) {
return const <String, dynamic>{};
return const <String, Object>{};
}
final String normalizedPlistPath = _fileSystem.path.absolute(plistFilePath);
try {
final List<String> args = <String>[
executable, '-convert', 'json', '-o', '-', normalizedPlistPath,
];
final String jsonContent = _processUtils.runSync(
args,
throwOnError: true,
).stdout.trim();
return castStringKeyedMap(json.decode(jsonContent)) ?? const <String, dynamic>{};
} on ProcessException catch (error) {
_logger.printTrace('$error');
return const <String, dynamic>{};
final String? xmlContent = plistXmlContent(normalizedPlistPath);
if (xmlContent == null) {
return const <String, Object>{};
}
return _parseXml(xmlContent);
}
/// Parses the Plist file located at [plistFilePath] and returns the value
/// that's associated with the specified [key] within the property list.
Map<String, Object> _parseXml(String xmlContent) {
final XmlDocument document = XmlDocument.parse(xmlContent);
// First element child is <plist>. The first element child of plist is <dict>.
final XmlElement dictObject = document.firstElementChild!.firstElementChild!;
return _parseXmlDict(dictObject);
}
Map<String, Object> _parseXmlDict(XmlElement node) {
String? lastKey;
final Map<String, Object> result = <String, Object>{};
for (final XmlNode child in node.children) {
if (child is XmlElement) {
if (child.name.local == 'key') {
lastKey = child.text;
} else {
assert(lastKey != null);
result[lastKey!] = _parseXmlNode(child)!;
lastKey = null;
}
}
}
return result;
}
static final RegExp _nonBase64Pattern = RegExp('[^a-zA-Z0-9+/=]+');
Object? _parseXmlNode(XmlElement node) {
switch (node.name.local){
case 'string':
return node.text;
case 'real':
return double.parse(node.text);
case 'integer':
return int.parse(node.text);
case 'true':
return true;
case 'false':
return false;
case 'date':
return DateTime.parse(node.text);
case 'data':
return base64.decode(node.text.replaceAll(_nonBase64Pattern, ''));
case 'array':
return node.children.whereType<XmlElement>().map<Object?>(_parseXmlNode).whereType<Object>().toList();
case 'dict':
return _parseXmlDict(node);
}
return null;
}
/// Parses the Plist file located at [plistFilePath] and returns the string
/// value that's associated with the specified [key] within the property list.
///
/// If [plistFilePath] points to a non-existent file or a file that's not a
/// valid property list file, this will return null.
@@ -71,9 +138,8 @@ class PlistParser {
/// If [key] is not found in the property list, this will return null.
///
/// The [plistFilePath] and [key] arguments must not be null.
String? getValueFromFile(String plistFilePath, String key) {
assert(key != null);
String? getStringValueFromFile(String plistFilePath, String key) {
final Map<String, dynamic> parsed = parseFile(plistFilePath);
return parsed[key] as String;
return parsed[key] as String?;
}
}

View File

@@ -495,7 +495,7 @@ class IOSSimulator extends Device {
// parsing the xcodeproj or configuration files.
// See https://github.com/flutter/flutter/issues/31037 for more information.
final String plistPath = globals.fs.path.join(package.simulatorBundlePath, 'Info.plist');
final String? bundleIdentifier = globals.plistParser.getValueFromFile(plistPath, PlistParser.kCFBundleIdentifierKey);
final String? bundleIdentifier = globals.plistParser.getStringValueFromFile(plistPath, PlistParser.kCFBundleIdentifierKey);
if (bundleIdentifier == null) {
globals.printError('Invalid prebuilt iOS app. Info.plist does not contain bundle identifier');
return LaunchResult.failed();

View File

@@ -180,7 +180,7 @@ class IosProject extends XcodeBasedProject {
// Try parsing the default, first.
if (defaultInfoPlist.existsSync()) {
try {
fromPlist = globals.plistParser.getValueFromFile(
fromPlist = globals.plistParser.getStringValueFromFile(
defaultHostInfoPlist.path,
PlistParser.kCFBundleIdentifierKey,
);
@@ -332,7 +332,7 @@ class IosProject extends XcodeBasedProject {
// The Info.plist file of a target contains the key WKCompanionAppBundleIdentifier,
// if it is a watchOS companion app.
if (infoFile.existsSync()) {
final String? fromPlist = globals.plistParser.getValueFromFile(infoFile.path, 'WKCompanionAppBundleIdentifier');
final String? fromPlist = globals.plistParser.getStringValueFromFile(infoFile.path, 'WKCompanionAppBundleIdentifier');
if (bundleIdentifier == fromPlist) {
return true;
}