plist_parser.dart 2.41 KB
Newer Older
1 2 3 4 5 6
// Copyright 2016 The Chromium 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 '../base/context.dart';
import '../base/file_system.dart';
7
import '../base/io.dart';
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
import '../base/process.dart';
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';
31
    if (!fs.isFileSync(executable)) {
32
      throw const FileNotFoundException(executable);
33 34
    }
    if (!fs.isFileSync(plistFilePath)) {
35
      return const <String, dynamic>{};
36
    }
37 38 39 40 41 42 43

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

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