plist_parser.dart 2.46 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import '../base/context.dart';
import '../base/file_system.dart';
7
import '../base/io.dart';
8
import '../base/process.dart';
9
import '../base/utils.dart';
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
import '../convert.dart';
import '../globals.dart';

class PlistParser {
  const PlistParser();

  static const String kCFBundleIdentifierKey = 'CFBundleIdentifier';
  static const String kCFBundleShortVersionStringKey = 'CFBundleShortVersionString';
  static const String kCFBundleExecutable = 'CFBundleExecutable';

  static PlistParser get instance => context.get<PlistParser>() ?? const PlistParser();

  /// Parses the plist file located at [plistFilePath] and returns the
  /// associated map of key/value property list pairs.
  ///
  /// If [plistFilePath] points to a non-existent file or a file that's not a
  /// valid property list file, this will return an empty map.
  ///
  /// The [plistFilePath] argument must not be null.
  Map<String, dynamic> parseFile(String plistFilePath) {
    assert(plistFilePath != null);
    const String executable = '/usr/bin/plutil';
32
    if (!fs.isFileSync(executable)) {
33
      throw const FileNotFoundException(executable);
34 35
    }
    if (!fs.isFileSync(plistFilePath)) {
36
      return const <String, dynamic>{};
37
    }
38 39 40 41 42 43 44

    final String normalizedPlistPath = fs.path.absolute(plistFilePath);

    try {
      final List<String> args = <String>[
        executable, '-convert', 'json', '-o', '-', normalizedPlistPath,
      ];
45 46 47 48
      final String jsonContent = processUtils.runSync(
        args,
        throwOnError: true,
      ).stdout.trim();
49
      return castStringKeyedMap(json.decode(jsonContent));
50
    } on ProcessException catch (error) {
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
      printTrace('$error');
      return const <String, dynamic>{};
    }
  }

  /// Parses the Plist file located at [plistFilePath] and returns the 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.
  ///
  /// 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);
    final Map<String, dynamic> parsed = parseFile(plistFilePath);
68
    return parsed[key] as String;
69 70
  }
}