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

5
import '../convert.dart';
6
import '../globals.dart' as globals;
7
import 'file_system.dart';
8
import 'logger.dart';
9
import 'utils.dart';
10 11

class Config {
12
  Config([File configFile, Logger localLogger]) {
13
    final Logger loggerInstance = localLogger ?? globals.logger;
14 15 16 17
    _configFile = configFile ?? globals.fs.file(globals.fs.path.join(
      fsUtils.userHomePath,
      '.flutter_settings',
    ));
18
    if (_configFile.existsSync()) {
19 20 21 22 23 24 25 26 27 28 29
      try {
        _values = castStringKeyedMap(json.decode(_configFile.readAsStringSync()));
      } on FormatException {
        loggerInstance
          ..printError('Failed to decode preferences in ${_configFile.path}.')
          ..printError(
              'You may need to reapply any previously saved configuration '
              'with the "flutter config" command.',
          );
        _configFile.deleteSync();
      }
30
    }
31 32 33
  }

  File _configFile;
34 35
  String get configPath => _configFile.path;

36 37 38 39
  Map<String, dynamic> _values = <String, dynamic>{};

  Iterable<String> get keys => _values.keys;

40 41
  bool containsKey(String key) => _values.containsKey(key);

42 43
  dynamic getValue(String key) => _values[key];

44
  void setValue(String key, Object value) {
45 46 47 48 49 50 51 52 53 54
    _values[key] = value;
    _flushValues();
  }

  void removeValue(String key) {
    _values.remove(key);
    _flushValues();
  }

  void _flushValues() {
55
    String json = const JsonEncoder.withIndent('  ').convert(_values);
56 57 58 59
    json = '$json\n';
    _configFile.writeAsStringSync(json);
  }
}