config.dart 4.84 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 6
import 'package:meta/meta.dart';

7
import '../convert.dart';
8
import 'error_handling_io.dart';
9
import 'file_system.dart';
10
import 'logger.dart';
11
import 'platform.dart';
12
import 'utils.dart';
13

14
/// A class to abstract configuration files.
15
class Config {
16
  /// Constructs a new [Config] object from a file called [name] in the
17 18 19 20 21 22 23 24
  /// current user's configuration directory as determined by the [Platform]
  /// and [FileSystem].
  ///
  /// The configuration directory defaults to $XDG_CONFIG_HOME on Linux and
  /// macOS, but falls back to the home directory if a file named
  /// `.flutter_$name` already exists there. On other platforms the
  /// configuration file will always be a file named `.flutter_$name` in the
  /// home directory.
25 26 27
  factory Config(
    String name, {
    @required FileSystem fileSystem,
28
    @required Logger logger,
29 30
    @required Platform platform,
  }) {
31 32 33
    final String filePath = _configPath(platform, fileSystem, name);
    final File file = fileSystem.file(filePath);
    file.parent.createSync(recursive: true);
34
    return Config.createForTesting(file, logger);
35 36 37 38 39 40 41 42
  }

  /// Constructs a new [Config] object from a file called [name] in
  /// the given [Directory].
  factory Config.test(
    String name, {
    @required Directory directory,
    @required Logger logger,
43
  }) => Config.createForTesting(directory.childFile('.${kConfigDir}_$name'), logger);
44

45 46 47
  /// Test only access to the Config constructor.
  @visibleForTesting
  Config.createForTesting(File file, Logger logger) : _file = file, _logger = logger {
48 49 50 51
    if (!_file.existsSync()) {
      return;
    }
    try {
52 53 54
      ErrorHandlingFileSystem.noExitOnFailure(() {
        _values = castStringKeyedMap(json.decode(_file.readAsStringSync()));
      });
55 56 57 58 59 60 61 62
    } on FormatException {
      _logger
        ..printError('Failed to decode preferences in ${_file.path}.')
        ..printError(
            'You may need to reapply any previously saved configuration '
            'with the "flutter config" command.',
        );
      _file.deleteSync();
63 64 65 66 67 68 69
    } on Exception catch (err) {
      _logger
        ..printError('Could not read preferences in ${file.path}.\n$err')
        ..printError(
            'You may need to resolve the error above and reapply any previously '
            'saved configuration with the "flutter config" command.',
        );
70
    }
71 72
  }

73 74 75 76 77 78 79 80 81 82 83 84 85 86
  /// The default directory name for Flutter's configs.

  /// Configs will be written to the user's config path. If there is already a
  /// file with the name `.${kConfigDir}_$name` in the user's home path, that
  /// file will be used instead.
  static const String kConfigDir = 'flutter';

  /// Environment variable specified in the XDG Base Directory
  /// [specification](https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html)
  /// to specify the user's configuration directory.
  static const String kXdgConfigHome = 'XDG_CONFIG_HOME';

  /// Fallback directory in the user's home directory if `XDG_CONFIG_HOME` is
  /// not defined.
87
  static const String kXdgConfigFallback = '.config';
88

89
  /// The default name for the Flutter config file.
90
  static const String kFlutterSettings = 'settings';
91 92 93

  final Logger _logger;

94 95
  File _file;

96
  String get configPath => _file.path;
97

98 99 100 101
  Map<String, dynamic> _values = <String, dynamic>{};

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

102 103
  bool containsKey(String key) => _values.containsKey(key);

104 105
  dynamic getValue(String key) => _values[key];

106
  void setValue(String key, Object value) {
107 108 109 110 111 112 113 114 115 116
    _values[key] = value;
    _flushValues();
  }

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

  void _flushValues() {
117
    String json = const JsonEncoder.withIndent('  ').convert(_values);
118
    json = '$json\n';
119
    _file.writeAsStringSync(json);
120
  }
121 122 123 124 125 126 127

  // Reads the process environment to find the current user's home directory.
  //
  // If the searched environment variables are not set, '.' is returned instead.
  //
  // Note that this is different from FileSystemUtils.homeDirPath.
  static String _userHomePath(Platform platform) {
128
    final String envKey = platform.isWindows ? 'APPDATA' : 'HOME';
129 130
    return platform.environment[envKey] ?? '.';
  }
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145

  static String _configPath(
      Platform platform, FileSystem fileSystem, String name) {
    final String homeDirFile =
        fileSystem.path.join(_userHomePath(platform), '.${kConfigDir}_$name');
    if (platform.isLinux || platform.isMacOS) {
      if (fileSystem.isFileSync(homeDirFile)) {
        return homeDirFile;
      }
      final String configDir = platform.environment[kXdgConfigHome] ??
          fileSystem.path.join(_userHomePath(platform), '.config', kConfigDir);
      return fileSystem.path.join(configDir, name);
    }
    return homeDirFile;
  }
146
}