file_store.dart 7.58 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
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

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

import 'package:crypto/crypto.dart';
9
import 'package:meta/meta.dart';
10 11

import '../base/file_system.dart';
12
import '../base/logger.dart';
13
import '../base/utils.dart';
14
import '../convert.dart';
15
import 'hash.dart';
16

17 18 19 20 21
/// An encoded representation of all file hashes.
class FileStorage {
  FileStorage(this.version, this.files);

  factory FileStorage.fromBuffer(Uint8List buffer) {
22 23 24
    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>>();
25
    final List<FileHash> cachedFiles = <FileHash>[
26
      for (final Map<String, Object> rawFile in rawCachedFiles) FileHash.fromJson(rawFile),
27 28 29 30 31 32 33 34 35 36 37
    ];
    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>[
38
        for (final FileHash file in files) file.toJson(),
39 40 41 42 43 44 45 46 47 48 49
      ],
    };
    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) {
50
    return FileHash(json['path'] as String, json['hash'] as String);
51 52 53 54 55 56 57 58 59 60 61 62
  }

  final String path;
  final String hash;

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

64 65 66 67 68 69 70 71 72 73 74 75
/// 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.
76 77 78
///
/// In cases where multiple targets read the same source files as inputs, we
/// avoid recomputing or storing multiple copies of hashes by delegating
79 80 81 82 83 84
/// 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.
85 86
///
/// The format of the file store is subject to change and not part of its API.
87 88 89
class FileStore {
  FileStore({
    @required File cacheFile,
90
    @required Logger logger,
91 92 93
    FileStoreStrategy strategy = FileStoreStrategy.hash,
  }) : _logger = logger,
       _strategy = strategy,
94
       _cacheFile = cacheFile;
95

96
  final File _cacheFile;
97
  final Logger _logger;
98
  final FileStoreStrategy _strategy;
99

100 101
  final HashMap<String, String> previousAssetKeys = HashMap<String, String>();
  final HashMap<String, String> currentAssetKeys = HashMap<String, String>();
102 103

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

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

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

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

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

173 174 175 176 177 178 179 180
  /// 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
181
  /// that were dirty.
182
  List<File> diffFileList(List<File> files) {
183
    final List<File> dirty = <File>[];
184 185
    switch (_strategy) {
      case FileStoreStrategy.hash:
186 187 188
        for (final File file in files) {
          _hashFile(file, dirty);
        }
189 190 191 192 193 194 195
        break;
      case FileStoreStrategy.timestamp:
        for (final File file in files) {
          _checkModification(file, dirty);
        }
        break;
    }
196 197
    return dirty;
  }
198

199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
  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;
  }

217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
  // 64k is the same sized buffer used by dart:io for `File.openRead`.
  static final Uint8List _readBuffer = Uint8List(64 * 1024);

  void _hashFile(File file, List<File> dirty) {
    final String absolutePath = file.path;
    final String previousHash = 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 int fileBytes = file.lengthSync();
    final Md5Hash hash = Md5Hash();
    RandomAccessFile openFile;
233
    try {
234 235 236 237 238 239
      openFile = file.openSync(mode: FileMode.read);
      int bytes = 0;
      while (bytes < fileBytes) {
        final int bytesRead = openFile.readIntoSync(_readBuffer);
        hash.addChunk(_readBuffer, bytesRead);
        bytes += bytesRead;
240
      }
241
    } finally {
242 243 244 245 246 247
      openFile?.closeSync();
    }
    final Digest digest = Digest(hash.finalize().buffer.asUint8List());
    final String currentHash = digest.toString();
    if (currentHash != previousHash) {
      dirty.add(file);
248
    }
249
    currentAssetKeys[absolutePath] = currentHash;
250 251
  }
}