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

import 'dart:async';
import 'dart:collection';
import 'dart:typed_data';

import 'package:crypto/crypto.dart';
10
import 'package:meta/meta.dart';
11
import 'package:pool/pool.dart';
12 13

import '../base/file_system.dart';
14
import '../base/logger.dart';
15
import '../base/utils.dart';
16
import '../convert.dart';
17
import 'build_system.dart';
18 19 20 21 22 23

/// An encoded representation of all file hashes.
class FileStorage {
  FileStorage(this.version, this.files);

  factory FileStorage.fromBuffer(Uint8List buffer) {
24 25 26
    final Map<String, dynamic> json = castStringKeyedMap(jsonDecode(utf8.decode(buffer)));
    final int version = json['version'] as int;
    final List<Map<String, Object>> rawCachedFiles = (json['files'] as List<dynamic>).cast<Map<String, Object>>();
27
    final List<FileHash> cachedFiles = <FileHash>[
28
      for (final Map<String, Object> rawFile in rawCachedFiles) FileHash.fromJson(rawFile),
29 30 31 32 33 34 35 36 37 38 39
    ];
    return FileStorage(version, cachedFiles);
  }

  final int version;
  final List<FileHash> files;

  List<int> toBuffer() {
    final Map<String, Object> json = <String, Object>{
      'version': version,
      'files': <Object>[
40
        for (final FileHash file in files) file.toJson(),
41 42 43 44 45 46 47 48 49 50 51
      ],
    };
    return utf8.encode(jsonEncode(json));
  }
}

/// A stored file hash and path.
class FileHash {
  FileHash(this.path, this.hash);

  factory FileHash.fromJson(Map<String, Object> json) {
52
    return FileHash(json['path'] as String, json['hash'] as String);
53 54 55 56 57 58 59 60 61 62 63 64
  }

  final String path;
  final String hash;

  Object toJson() {
    return <String, Object>{
      'path': path,
      'hash': hash,
    };
  }
}
65

66 67 68 69 70 71 72 73 74 75 76 77
/// The strategy used by [FileStore] to determine if a file has been
/// invalidated.
enum FileStoreStrategy {
  /// The [FileStore] will compute an md5 hash of the file contents.
  hash,

  /// The [FileStore] will check for differences in the file's last modified
  /// timestamp.
  timestamp,
}

/// A globally accessible cache of files.
78 79 80
///
/// In cases where multiple targets read the same source files as inputs, we
/// avoid recomputing or storing multiple copies of hashes by delegating
81 82 83 84 85 86
/// through this class.
///
/// This class uses either timestamps or file hashes depending on the
/// provided [FileStoreStrategy]. All information  is held in memory during
/// a build operation, and may be persisted to cache in the root build
/// directory.
87 88
///
/// The format of the file store is subject to change and not part of its API.
89 90 91
class FileStore {
  FileStore({
    @required File cacheFile,
92
    @required Logger logger,
93 94 95 96
    FileStoreStrategy strategy = FileStoreStrategy.hash,
  }) : _logger = logger,
       _strategy = strategy,
       _cacheFile = cacheFile;
97

98
  final File _cacheFile;
99
  final Logger _logger;
100
  final FileStoreStrategy _strategy;
101

102 103
  final HashMap<String, String> previousAssetKeys = HashMap<String, String>();
  final HashMap<String, String> currentAssetKeys = HashMap<String, String>();
104 105

  // The name of the file which stores the file hashes.
106
  static const String kFileCache = '.filecache';
107 108

  // The current version of the file cache storage format.
109
  static const int _kVersion = 2;
110 111 112

  /// Read file hashes from disk.
  void initialize() {
113
    _logger.printTrace('Initializing file store');
114
    if (!_cacheFile.existsSync()) {
115 116
      return;
    }
117
    Uint8List data;
118
    try {
119
      data = _cacheFile.readAsBytesSync();
120
    } on FileSystemException catch (err) {
121
      _logger.printError(
122
        'Failed to read file store at ${_cacheFile.path} due to $err.\n'
123 124 125 126 127 128
        'Build artifacts will not be cached. Try clearing the cache directories '
        'with "flutter clean"',
      );
      return;
    }

129 130 131
    FileStorage fileStorage;
    try {
      fileStorage = FileStorage.fromBuffer(data);
132 133
    } on Exception catch (err) {
      _logger.printTrace('Filestorage format changed: $err');
134
      _cacheFile.deleteSync();
135 136
      return;
    }
137
    if (fileStorage.version != _kVersion) {
138
      _logger.printTrace('file cache format updating, clearing old hashes.');
139
      _cacheFile.deleteSync();
140 141
      return;
    }
142
    for (final FileHash fileHash in fileStorage.files) {
143
      previousAssetKeys[fileHash.path] = fileHash.hash;
144
    }
145
    _logger.printTrace('Done initializing file store');
146 147
  }

148
  /// Persist file marks to disk for a non-incremental build.
149
  void persist() {
150
    _logger.printTrace('Persisting file store');
151 152
    if (!_cacheFile.existsSync()) {
      _cacheFile.createSync(recursive: true);
153
    }
154
    final List<FileHash> fileHashes = <FileHash>[];
155
    for (final MapEntry<String, String> entry in currentAssetKeys.entries) {
156
      fileHashes.add(FileHash(entry.key, entry.value));
157
    }
158 159 160 161
    final FileStorage fileStorage = FileStorage(
      _kVersion,
      fileHashes,
    );
162
    final List<int> buffer = fileStorage.toBuffer();
163
    try {
164
      _cacheFile.writeAsBytesSync(buffer);
165
    } on FileSystemException catch (err) {
166
      _logger.printError(
167
        'Failed to persist file store at ${_cacheFile.path} due to $err.\n'
168 169 170 171
        'Build artifacts will not be cached. Try clearing the cache directories '
        'with "flutter clean"',
      );
    }
172
    _logger.printTrace('Done persisting file store');
173 174
  }

175 176 177 178 179 180 181 182
  /// Reset `previousMarks` for an incremental build.
  void persistIncremental() {
    previousAssetKeys.clear();
    previousAssetKeys.addAll(currentAssetKeys);
    currentAssetKeys.clear();
  }

  /// Computes a diff of the provided files and returns a list of files
183
  /// that were dirty.
184
  Future<List<File>> diffFileList(List<File> files) async {
185
    final List<File> dirty = <File>[];
186 187 188 189 190 191 192 193 194 195 196 197 198
    switch (_strategy) {
      case FileStoreStrategy.hash:
        final Pool openFiles = Pool(kMaxOpenFiles);
        await Future.wait(<Future<void>>[
          for (final File file in files) _hashFile(file, dirty, openFiles)
        ]);
        break;
      case FileStoreStrategy.timestamp:
        for (final File file in files) {
          _checkModification(file, dirty);
        }
        break;
    }
199 200
    return dirty;
  }
201

202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
  void _checkModification(File file, List<File> dirty) {
    final String absolutePath = file.path;
    final String previousTime = previousAssetKeys[absolutePath];

    // If the file is missing it is assumed to be dirty.
    if (!file.existsSync()) {
      currentAssetKeys.remove(absolutePath);
      previousAssetKeys.remove(absolutePath);
      dirty.add(file);
      return;
    }
    final String modifiedTime = file.lastModifiedSync().toString();
    if (modifiedTime != previousTime) {
      dirty.add(file);
    }
    currentAssetKeys[absolutePath] = modifiedTime;
  }

220 221 222 223
  Future<void> _hashFile(File file, List<File> dirty, Pool pool) async {
    final PoolResource resource = await pool.request();
    try {
      final String absolutePath = file.path;
224
      final String previousHash = previousAssetKeys[absolutePath];
225 226
      // If the file is missing it is assumed to be dirty.
      if (!file.existsSync()) {
227 228
        currentAssetKeys.remove(absolutePath);
        previousAssetKeys.remove(absolutePath);
229 230 231
        dirty.add(file);
        return;
      }
232 233
      final Digest digest = md5.convert(await file.readAsBytes());
      final String currentHash = digest.toString();
234 235 236
      if (currentHash != previousHash) {
        dirty.add(file);
      }
237
      currentAssetKeys[absolutePath] = currentHash;
238 239
    } finally {
      resource.release();
240 241 242
    }
  }
}