devfs.dart 23.8 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
// @dart = 2.8

7
import 'dart:async';
8

9
import 'package:meta/meta.dart';
10
import 'package:package_config/package_config.dart';
11
import 'package:vm_service/vm_service.dart' as vm_service;
12

13
import 'asset.dart';
14
import 'base/context.dart';
15
import 'base/file_system.dart';
16
import 'base/io.dart';
17
import 'base/logger.dart';
18
import 'base/net.dart';
19
import 'base/os.dart';
20
import 'build_info.dart';
21
import 'compile.dart';
22
import 'convert.dart' show base64, utf8;
23
import 'vmservice.dart';
24

25 26 27
class DevFSConfig {
  /// Should DevFS assume that symlink targets are stable?
  bool cacheSymlinks = false;
28 29
  /// Should DevFS assume that there are no symlinks to directories?
  bool noDirectorySymlinks = false;
30 31
}

32
DevFSConfig get devFSConfig => context.get<DevFSConfig>();
33

34 35
/// Common superclass for content copied to the device.
abstract class DevFSContent {
36
  /// Return true if this is the first time this method is called
37 38
  /// or if the entry has been modified since this method was last called.
  bool get isModified;
39

40 41 42 43 44
  /// Return true if this is the first time this method is called
  /// or if the entry has been modified after the given time
  /// or if the given time is null.
  bool isModifiedAfter(DateTime time);

45 46
  int get size;

47
  Future<List<int>> contentsAsBytes();
48

49 50
  Stream<List<int>> contentsAsStream();

51 52 53 54
  Stream<List<int>> contentsAsCompressedStream(
    OperatingSystemUtils osUtils,
  ) {
    return osUtils.gzipLevel1Stream(contentsAsStream());
55 56 57
  }
}

58
// File content to be copied to the device.
59 60
class DevFSFileContent extends DevFSContent {
  DevFSFileContent(this.file);
61

62
  final FileSystemEntity file;
63
  File _linkTarget;
64
  FileStat _fileStat;
65

66 67 68
  File _getFile() {
    if (_linkTarget != null) {
      return _linkTarget;
69
    }
70 71
    if (file is Link) {
      // The link target.
72
      return file.fileSystem.file(file.resolveSymbolicLinksSync());
73
    }
74
    return file as File;
75 76
  }

77
  void _stat() {
78 79
    if (_linkTarget != null) {
      // Stat the cached symlink target.
80 81 82 83 84 85 86
      final FileStat fileStat = _linkTarget.statSync();
      if (fileStat.type == FileSystemEntityType.notFound) {
        _linkTarget = null;
      } else {
        _fileStat = fileStat;
        return;
      }
87
    }
88 89 90
    final FileStat fileStat = file.statSync();
    _fileStat = fileStat.type == FileSystemEntityType.notFound ? null : fileStat;
    if (_fileStat != null && _fileStat.type == FileSystemEntityType.link) {
91
      // Resolve, stat, and maybe cache the symlink target.
92
      final String resolved = file.resolveSymbolicLinksSync();
93
      final File linkTarget = file.fileSystem.file(resolved);
94
      // Stat the link target.
95 96 97 98 99
      final FileStat fileStat = linkTarget.statSync();
      if (fileStat.type == FileSystemEntityType.notFound) {
        _fileStat = null;
        _linkTarget = null;
      } else if (devFSConfig.cacheSymlinks) {
100 101
        _linkTarget = linkTarget;
      }
102
    }
103
  }
104

105 106
  @override
  bool get isModified {
107
    final FileStat _oldFileStat = _fileStat;
108
    _stat();
109
    if (_oldFileStat == null && _fileStat == null) {
110
      return false;
111
    }
112
    return _oldFileStat == null || _fileStat == null || _fileStat.modified.isAfter(_oldFileStat.modified);
113 114
  }

115 116 117 118
  @override
  bool isModifiedAfter(DateTime time) {
    final FileStat _oldFileStat = _fileStat;
    _stat();
119
    if (_oldFileStat == null && _fileStat == null) {
120
      return false;
121
    }
122 123 124 125
    return time == null
        || _oldFileStat == null
        || _fileStat == null
        || _fileStat.modified.isAfter(time);
126 127
  }

128 129
  @override
  int get size {
130
    if (_fileStat == null) {
131
      _stat();
132
    }
133 134
    // Can still be null if the file wasn't found.
    return _fileStat?.size ?? 0;
135
  }
136

137
  @override
138
  Future<List<int>> contentsAsBytes() => _getFile().readAsBytes();
139 140

  @override
141
  Stream<List<int>> contentsAsStream() => _getFile().openRead();
142 143 144 145 146 147 148 149 150
}

/// Byte content to be copied to the device.
class DevFSByteContent extends DevFSContent {
  DevFSByteContent(this._bytes);

  List<int> _bytes;

  bool _isModified = true;
151
  DateTime _modificationTime = DateTime.now();
152 153 154

  List<int> get bytes => _bytes;

155 156
  set bytes(List<int> value) {
    _bytes = value;
157
    _isModified = true;
158
    _modificationTime = DateTime.now();
159 160
  }

161
  /// Return true only once so that the content is written to the device only once.
162 163
  @override
  bool get isModified {
164
    final bool modified = _isModified;
165 166
    _isModified = false;
    return modified;
167
  }
168

169 170 171 172 173
  @override
  bool isModifiedAfter(DateTime time) {
    return time == null || _modificationTime.isAfter(time);
  }

174 175 176 177
  @override
  int get size => _bytes.length;

  @override
178
  Future<List<int>> contentsAsBytes() async => _bytes;
179 180

  @override
181 182
  Stream<List<int>> contentsAsStream() =>
      Stream<List<int>>.fromIterable(<List<int>>[_bytes]);
183 184
}

185
/// String content to be copied to the device.
186
class DevFSStringContent extends DevFSByteContent {
187 188 189
  DevFSStringContent(String string)
    : _string = string,
      super(utf8.encode(string));
190 191 192 193 194

  String _string;

  String get string => _string;

195 196
  set string(String value) {
    _string = value;
197
    super.bytes = utf8.encode(_string);
198 199 200
  }

  @override
201
  set bytes(List<int> value) {
202
    string = utf8.decode(value);
203 204
  }
}
205

206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
/// A string compressing DevFSContent.
///
/// A specialized DevFSContent similar to DevFSByteContent where the contents
/// are the compressed bytes of a string. Its difference is that the original
/// uncompressed string can be compared with directly without the indirection
/// of a compute-expensive uncompress/decode and compress/encode to compare
/// the strings.
///
/// The `hintString` parameter is a zlib dictionary hinting mechanism to suggest
/// the most common string occurrences to potentially assist with compression.
class DevFSStringCompressingBytesContent extends DevFSContent {
  DevFSStringCompressingBytesContent(this._string, { String hintString })
    : _compressor = ZLibEncoder(
      dictionary: hintString == null
          ? null
          : utf8.encode(hintString),
      gzip: true,
      level: 9,
    );

  final String _string;
  final ZLibEncoder _compressor;
  final DateTime _modificationTime = DateTime.now();

  List<int> _bytes;
  bool _isModified = true;

  List<int> get bytes => _bytes ??= _compressor.convert(utf8.encode(_string));

  /// Return true only once so that the content is written to the device only once.
  @override
  bool get isModified {
    final bool modified = _isModified;
    _isModified = false;
    return modified;
  }

  @override
  bool isModifiedAfter(DateTime time) {
    return time == null || _modificationTime.isAfter(time);
  }

  @override
  int get size => bytes.length;

  @override
  Future<List<int>> contentsAsBytes() async => bytes;

  @override
  Stream<List<int>> contentsAsStream() => Stream<List<int>>.value(bytes);

  /// This checks the source string with another string.
  bool equals(String string) => _string == string;
}

261 262 263 264 265
class DevFSException implements Exception {
  DevFSException(this.message, [this.error, this.stackTrace]);
  final String message;
  final dynamic error;
  final StackTrace stackTrace;
266 267 268

  @override
  String toString() => 'DevFSException($message, $error, $stackTrace)';
269 270
}

271 272 273 274 275 276 277 278 279 280 281
/// Interface responsible for syncing asset files to a development device.
abstract class DevFSWriter {
  /// Write the assets in [entries] to the target device.
  ///
  /// The keys of the map are relative from the [baseUri].
  ///
  /// Throws a [DevFSException] if the process fails to complete.
  Future<void> write(Map<Uri, DevFSContent> entries, Uri baseUri, DevFSWriter parent);
}

class _DevFSHttpWriter implements DevFSWriter {
282 283
  _DevFSHttpWriter(
    this.fsName,
284
    FlutterVmService serviceProtocol, {
285
    @required OperatingSystemUtils osUtils,
286 287
    @required HttpClient httpClient,
    @required Logger logger,
288
    Duration uploadRetryThrottle,
289
  })
290
    : httpAddress = serviceProtocol.httpAddress,
291 292
      _client = httpClient,
      _osUtils = osUtils,
293
      _uploadRetryThrottle = uploadRetryThrottle,
294
      _logger = logger;
295

296
  final HttpClient _client;
297
  final OperatingSystemUtils _osUtils;
298
  final Logger _logger;
299
  final Duration _uploadRetryThrottle;
300 301 302

  final String fsName;
  final Uri httpAddress;
303

304
  // 3 was chosen to try to limit the variance in the time it takes to execute
305 306 307 308
  // `await request.close()` since there is a known bug in Dart where it doesn't
  // always return a status code in response to a PUT request:
  // https://github.com/dart-lang/sdk/issues/43525.
  static const int kMaxInFlight = 3;
309 310 311 312 313

  int _inFlight = 0;
  Map<Uri, DevFSContent> _outstanding;
  Completer<void> _completer;

314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
  @override
  Future<void> write(Map<Uri, DevFSContent> entries, Uri devFSBase, [DevFSWriter parent]) async {
    try {
      _client.maxConnectionsPerHost = kMaxInFlight;
      _completer = Completer<void>();
      _outstanding = Map<Uri, DevFSContent>.of(entries);
      _scheduleWrites();
      await _completer.future;
    } on SocketException catch (socketException, stackTrace) {
      _logger.printTrace('DevFS sync failed. Lost connection to device: $socketException');
      throw DevFSException('Lost connection to device.', socketException, stackTrace);
    } on Exception catch (exception, stackTrace) {
      _logger.printError('Could not update files on device: $exception');
      throw DevFSException('Sync failed', exception, stackTrace);
    }
329 330
  }

331
  void _scheduleWrites() {
332
    while ((_inFlight < kMaxInFlight) && (!_completer.isCompleted) && _outstanding.isNotEmpty) {
333 334
      final Uri deviceUri = _outstanding.keys.first;
      final DevFSContent content = _outstanding.remove(deviceUri);
335
      _startWrite(deviceUri, content, retry: 10);
336
      _inFlight += 1;
337
    }
338
    if ((_inFlight == 0) && (!_completer.isCompleted) && _outstanding.isEmpty) {
339
      _completer.complete();
340
    }
341 342
  }

343
  Future<void> _startWrite(
344
    Uri deviceUri,
345
    DevFSContent content, {
346
    int retry = 0,
347 348 349 350 351 352 353
  }) async {
    while(true) {
      try {
        final HttpClientRequest request = await _client.putUrl(httpAddress);
        request.headers.removeAll(HttpHeaders.acceptEncodingHeader);
        request.headers.add('dev_fs_name', fsName);
        request.headers.add('dev_fs_uri_b64', base64.encode(utf8.encode('$deviceUri')));
354 355 356
        final Stream<List<int>> contents = content.contentsAsCompressedStream(
          _osUtils,
        );
357
        await request.addStream(contents);
358
        // Once the bug in Dart is solved we can remove the timeout
359
        // (https://github.com/dart-lang/sdk/issues/43525).
360 361
        try {
          final HttpClientResponse response = await request.close().timeout(
362
            const Duration(seconds: 60));
363 364 365 366 367 368 369 370 371 372 373 374 375
          response.listen((_) {},
            onError: (dynamic error) {
              _logger.printTrace('error: $error');
            },
            cancelOnError: true,
          );
        } on TimeoutException {
          request.abort();
          // This should throw "HttpException: Request has been aborted".
          await request.done;
          // Just to be safe we rethrow the TimeoutException.
          rethrow;
        }
376
        break;
377
      } on Exception catch (error, trace) {
378
        if (!_completer.isCompleted) {
379
          _logger.printTrace('Error writing "$deviceUri" to DevFS: $error');
380 381
          if (retry > 0) {
            retry--;
382
            _logger.printTrace('trying again in a few - $retry more attempts left');
383
            await Future<void>.delayed(_uploadRetryThrottle ?? const Duration(milliseconds: 500));
384 385 386 387
            continue;
          }
          _completer.completeError(error, trace);
        }
388
      }
Ryan Macnak's avatar
Ryan Macnak committed
389
    }
390 391
    _inFlight -= 1;
    _scheduleWrites();
392 393 394
  }
}

395 396
// Basic statistics for DevFS update operation.
class UpdateFSReport {
397 398 399 400
  UpdateFSReport({
    bool success = false,
    int invalidatedSourcesCount = 0,
    int syncedBytes = 0,
401
    this.fastReassembleClassName,
402 403 404 405
    int scannedSourcesCount = 0,
    Duration compileDuration = Duration.zero,
    Duration transferDuration = Duration.zero,
    Duration findInvalidatedDuration = Duration.zero,
406 407
  }) : _success = success,
       _invalidatedSourcesCount = invalidatedSourcesCount,
408 409 410 411 412
       _syncedBytes = syncedBytes,
       _scannedSourcesCount = scannedSourcesCount,
       _compileDuration = compileDuration,
       _transferDuration = transferDuration,
       _findInvalidatedDuration = findInvalidatedDuration;
413 414 415 416

  bool get success => _success;
  int get invalidatedSourcesCount => _invalidatedSourcesCount;
  int get syncedBytes => _syncedBytes;
417 418 419 420
  int get scannedSourcesCount => _scannedSourcesCount;
  Duration get compileDuration => _compileDuration;
  Duration get transferDuration => _transferDuration;
  Duration get findInvalidatedDuration => _findInvalidatedDuration;
421

422
  bool _success;
423
  String fastReassembleClassName;
424 425
  int _invalidatedSourcesCount;
  int _syncedBytes;
426 427 428 429
  int _scannedSourcesCount;
  Duration _compileDuration;
  Duration _transferDuration;
  Duration _findInvalidatedDuration;
430

431 432 433 434
  void incorporateResults(UpdateFSReport report) {
    if (!report._success) {
      _success = false;
    }
435
    fastReassembleClassName ??= report.fastReassembleClassName;
436 437
    _invalidatedSourcesCount += report._invalidatedSourcesCount;
    _syncedBytes += report._syncedBytes;
438 439 440 441
    _scannedSourcesCount += report._scannedSourcesCount;
    _compileDuration += report._compileDuration;
    _transferDuration += report._transferDuration;
    _findInvalidatedDuration += report._findInvalidatedDuration;
442 443 444
  }
}

445
class DevFS {
446
  /// Create a [DevFS] named [fsName] for the local files in [rootDirectory].
447 448
  ///
  /// Failed uploads are retried after [uploadRetryThrottle] duration, defaults to 500ms.
449
  DevFS(
450
    FlutterVmService serviceProtocol,
451 452
    this.fsName,
    this.rootDirectory, {
453
    @required OperatingSystemUtils osUtils,
454 455 456
    @required Logger logger,
    @required FileSystem fileSystem,
    HttpClient httpClient,
457
    Duration uploadRetryThrottle,
458
    StopwatchFactory stopwatchFactory = const StopwatchFactory(),
459 460 461
  }) : _vmService = serviceProtocol,
       _logger = logger,
       _fileSystem = fileSystem,
462 463 464 465
       _httpWriter = _DevFSHttpWriter(
        fsName,
        serviceProtocol,
        osUtils: osUtils,
466
        logger: logger,
467
        uploadRetryThrottle: uploadRetryThrottle,
468 469
        httpClient: httpClient ?? ((context.get<HttpClientFactory>() == null)
          ? HttpClient()
470 471
          : context.get<HttpClientFactory>()())),
       _stopwatchFactory = stopwatchFactory;
472

473
  final FlutterVmService _vmService;
474
  final _DevFSHttpWriter _httpWriter;
475 476
  final Logger _logger;
  final FileSystem _fileSystem;
477
  final StopwatchFactory _stopwatchFactory;
478

479 480
  final String fsName;
  final Directory rootDirectory;
481
  final Set<String> assetPathsToEvict = <String>{};
482

483 484 485
  // A flag to indicate whether we have called `setAssetDirectory` on the target device.
  bool hasSetAssetDirectory = false;

486 487
  List<Uri> sources = <Uri>[];
  DateTime lastCompiled;
488
  DateTime _previousCompiled;
489
  PackageConfig lastPackageConfig;
490
  File _widgetCacheOutputFile;
491

492 493 494
  Uri _baseUri;
  Uri get baseUri => _baseUri;

495 496 497 498 499 500 501 502 503 504
  Uri deviceUriToHostUri(Uri deviceUri) {
    final String deviceUriString = deviceUri.toString();
    final String baseUriString = baseUri.toString();
    if (deviceUriString.startsWith(baseUriString)) {
      final String deviceUriSuffix = deviceUriString.substring(baseUriString.length);
      return rootDirectory.uri.resolve(deviceUriSuffix);
    }
    return deviceUri;
  }

505
  Future<Uri> create() async {
506
    _logger.printTrace('DevFS: Creating new filesystem on the device ($_baseUri)');
507
    try {
508 509
      final vm_service.Response response = await _vmService.createDevFS(fsName);
      _baseUri = Uri.parse(response.json['uri'] as String);
510
    } on vm_service.RPCError catch (rpcException) {
511 512 513 514 515
      if (rpcException.code == RPCErrorCodes.kServiceDisappeared) {
        // This can happen if the device has been disconnected, so translate to
        // a DevFSException, which the caller will handle.
        throw DevFSException('Service disconnected', rpcException);
      }
516
      // 1001 is kFileSystemAlreadyExists in //dart/runtime/vm/json_stream.h
517
      if (rpcException.code != 1001) {
518 519
        // Other RPCErrors are unexpected. Rethrow so it will hit crash
        // logging.
520
        rethrow;
521
      }
522
      _logger.printTrace('DevFS: Creating failed. Destroying and trying again');
523
      await destroy();
524 525
      final vm_service.Response response = await _vmService.createDevFS(fsName);
      _baseUri = Uri.parse(response.json['uri'] as String);
526
    }
527
    _logger.printTrace('DevFS: Created new filesystem on the device ($_baseUri)');
528 529 530
    return _baseUri;
  }

531
  Future<void> destroy() async {
532 533 534
    _logger.printTrace('DevFS: Deleting filesystem on the device ($_baseUri)');
    await _vmService.deleteDevFS(fsName);
    _logger.printTrace('DevFS: Deleted filesystem on the device ($_baseUri)');
535 536
  }

537 538 539 540 541 542 543 544 545 546 547 548 549 550
  /// Mark the [lastCompiled] time to the previous successful compile.
  ///
  /// Sometimes a hot reload will be rejected by the VM due to a change in the
  /// structure of the code not supporting the hot reload. In these cases,
  /// the best resolution is a hot restart. However, the resident runner
  /// will not recognize this file as having been changed since the delta
  /// will already have been accepted. Instead, reset the compile time so
  /// that the last updated files are included in subsequent compilations until
  /// a reload is accepted.
  void resetLastCompiled() {
    lastCompiled = _previousCompiled;
  }


551 552 553 554 555 556 557 558 559 560 561 562 563 564
  /// If the build method of a single widget was modified, return the widget name.
  ///
  /// If any other changes were made, or there is an error scanning the file,
  /// return `null`.
  String _checkIfSingleWidgetReloadApplied() {
    if (_widgetCacheOutputFile != null && _widgetCacheOutputFile.existsSync()) {
      final String widget = _widgetCacheOutputFile.readAsStringSync().trim();
      if (widget.isNotEmpty) {
        return widget;
      }
    }
    return null;
  }

565 566 567
  /// Updates files on the device.
  ///
  /// Returns the number of bytes synced.
568
  Future<UpdateFSReport> update({
569 570 571 572 573 574
    @required Uri mainUri,
    @required ResidentCompiler generator,
    @required bool trackWidgetCreation,
    @required String pathToReload,
    @required List<Uri> invalidatedFiles,
    @required PackageConfig packageConfig,
575
    @required String dillOutputPath,
576
    DevFSWriter devFSWriter,
577
    String target,
578
    AssetBundle bundle,
579
    DateTime firstBuildTime,
580 581
    bool bundleFirstUpload = false,
    bool fullRestart = false,
582
    String projectRootPath,
583
  }) async {
584 585
    assert(trackWidgetCreation != null);
    assert(generator != null);
586
    final DateTime candidateCompileTime = DateTime.now();
587
    lastPackageConfig = packageConfig;
588
    _widgetCacheOutputFile = _fileSystem.file('$dillOutputPath.incremental.dill.widget_cache');
589

590 591 592
    // Update modified files
    final Map<Uri, DevFSContent> dirtyEntries = <Uri, DevFSContent>{};
    int syncedBytes = 0;
593 594 595 596 597 598 599 600 601 602
    if (fullRestart) {
      generator.reset();
    }
    // On a full restart, or on an initial compile for the attach based workflow,
    // this will produce a full dill. Subsequent invocations will produce incremental
    // dill files that depend on the invalidated files.
    _logger.printTrace('Compiling dart to kernel with ${invalidatedFiles.length} updated files');

    // Await the compiler response after checking if the bundle is updated. This allows the file
    // stating to be done while waiting for the frontend_server response.
603
    final Stopwatch compileTimer = _stopwatchFactory.createStopwatch('compile')..start();
604 605 606
    final Future<CompilerOutput> pendingCompilerOutput = generator.recompile(
      mainUri,
      invalidatedFiles,
607
      outputPath: dillOutputPath,
608 609
      fs: _fileSystem,
      projectRootPath: projectRootPath,
610
      packageConfig: packageConfig,
611 612 613 614 615
    ).then((CompilerOutput result) {
      compileTimer.stop();
      return result;
    });

616 617
    if (bundle != null) {
      // The tool writes the assets into the AssetBundle working dir so that they
618
      // are in the same location in DevFS and the iOS simulator.
619
      final String assetBuildDirPrefix = _asUriPath(getAssetBuildDirectory());
620
      final String assetDirectory = getAssetBuildDirectory();
621
      bundle.entries.forEach((String archivePath, DevFSContent content) {
622 623
        // If the content is backed by a real file, isModified will file stat and return true if
        // it was modified since the last time this was called.
624 625 626
        if (!content.isModified || bundleFirstUpload) {
          return;
        }
627
        final Uri deviceUri = _fileSystem.path.toUri(_fileSystem.path.join(assetDirectory, archivePath));
628 629 630
        if (deviceUri.path.startsWith(assetBuildDirPrefix)) {
          archivePath = deviceUri.path.substring(assetBuildDirPrefix.length);
        }
631 632 633 634
        dirtyEntries[deviceUri] = content;
        syncedBytes += content.size;
        if (archivePath != null && !bundleFirstUpload) {
          assetPathsToEvict.add(archivePath);
635
        }
636
      });
637
    }
638
    final CompilerOutput compilerOutput = await pendingCompilerOutput;
639
    if (compilerOutput == null || compilerOutput.errorCount > 0) {
640 641
      return UpdateFSReport(success: false);
    }
642
    // Only update the last compiled time if we successfully compiled.
643
    _previousCompiled = lastCompiled;
644
    lastCompiled = candidateCompileTime;
645
    // list of sources that needs to be monitored are in [compilerOutput.sources]
646
    sources = compilerOutput.sources;
647
    //
648 649 650 651 652
    // Don't send full kernel file that would overwrite what VM already
    // started loading from.
    if (!bundleFirstUpload) {
      final String compiledBinary = compilerOutput?.outputFilename;
      if (compiledBinary != null && compiledBinary.isNotEmpty) {
653
        final Uri entryUri = _fileSystem.path.toUri(pathToReload);
654
        final DevFSFileContent content = DevFSFileContent(_fileSystem.file(compiledBinary));
655 656
        syncedBytes += content.size;
        dirtyEntries[entryUri] = content;
657
      }
658
    }
659
    _logger.printTrace('Updating files.');
660
    final Stopwatch transferTimer = _stopwatchFactory.createStopwatch('transfer')..start();
661
    if (dirtyEntries.isNotEmpty) {
662
      await (devFSWriter ?? _httpWriter).write(dirtyEntries, _baseUri, _httpWriter);
663
    }
664
    transferTimer.stop();
665
    _logger.printTrace('DevFS: Sync finished');
666 667 668 669 670
    return UpdateFSReport(
      success: true,
      syncedBytes: syncedBytes,
      invalidatedSourcesCount: invalidatedFiles.length,
      fastReassembleClassName: _checkIfSingleWidgetReloadApplied(),
671 672
      compileDuration: compileTimer.elapsed,
      transferDuration: transferTimer.elapsed,
673
    );
674
  }
675

676
  /// Converts a platform-specific file path to a platform-independent URL path.
677
  String _asUriPath(String filePath) => '${_fileSystem.path.toUri(filePath).path}/';
678
}
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715

/// An implementation of a devFS writer which copies physical files for devices
/// running on the same host.
///
/// DevFS entries which correspond to physical files are copied using [File.copySync],
/// while entries that correspond to arbitrary string/byte values are written from
/// memory.
///
/// Requires that the file system is the same for both the tool and application.
class LocalDevFSWriter implements DevFSWriter {
  LocalDevFSWriter({
    @required FileSystem fileSystem,
  }) : _fileSystem = fileSystem;

  final FileSystem _fileSystem;

  @override
  Future<void> write(Map<Uri, DevFSContent> entries, Uri baseUri, [DevFSWriter parent]) async {
    try {
      for (final Uri uri in entries.keys) {
        final DevFSContent devFSContent = entries[uri];
        final File destination = _fileSystem.file(baseUri.resolveUri(uri));
        if (!destination.parent.existsSync()) {
          destination.parent.createSync(recursive: true);
        }
        if (devFSContent is DevFSFileContent) {
          final File content = devFSContent.file as File;
          content.copySync(destination.path);
          continue;
        }
        destination.writeAsBytesSync(await devFSContent.contentsAsBytes());
      }
    } on FileSystemException catch (err) {
      throw DevFSException(err.toString());
    }
  }
}