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

import 'dart:async';
6

7
import 'package:package_config/package_config.dart';
8
import 'package:vm_service/vm_service.dart' as vm_service;
9

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

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

29
DevFSConfig? get devFSConfig => context.get<DevFSConfig>();
30

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

37 38 39 40 41
  /// 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);

42 43
  int get size;

44
  Future<List<int>> contentsAsBytes();
45

46 47
  Stream<List<int>> contentsAsStream();

48 49 50 51
  Stream<List<int>> contentsAsCompressedStream(
    OperatingSystemUtils osUtils,
  ) {
    return osUtils.gzipLevel1Stream(contentsAsStream());
52 53 54
  }
}

55
// File content to be copied to the device.
56 57
class DevFSFileContent extends DevFSContent {
  DevFSFileContent(this.file);
58

59
  final FileSystemEntity file;
60 61
  File? _linkTarget;
  FileStat? _fileStat;
62

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

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

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

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

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

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

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

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

  List<int> _bytes;

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

  List<int> get bytes => _bytes;

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

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

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

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

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

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

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

  String _string;

  String get string => _string;

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

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

207 208 209 210 211 212 213 214 215 216 217
/// 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 {
218
  DevFSStringCompressingBytesContent(this._string, { String? hintString })
219 220 221 222 223 224 225 226 227 228 229 230 231 232
    : _compressor = ZLibEncoder(
      dictionary: hintString == null
          ? null
          : utf8.encode(hintString),
      gzip: true,
      level: 9,
    );

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

  bool _isModified = true;

233
  late final List<int> bytes = _compressor.convert(utf8.encode(_string));
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

  /// 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
class DevFSException implements Exception {
  DevFSException(this.message, [this.error, this.stackTrace]);
  final String message;
  final dynamic error;
265
  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 286 287 288
    required OperatingSystemUtils osUtils,
    required HttpClient httpClient,
    required Logger logger,
    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

  final String fsName;
302
  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

  int _inFlight = 0;
311 312
  late Map<Uri, DevFSContent> _outstanding;
  late Completer<void> _completer;
313

314
  @override
315
  Future<void> write(Map<Uri, DevFSContent> entries, Uri devFSBase, [DevFSWriter? parent]) async {
316 317 318 319 320 321 322 323 324 325 326 327 328
    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
      final Uri deviceUri = _outstanding.keys.first;
334
      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
  }) async {
    while(true) {
      try {
350
        final HttpClientRequest request = await _client.putUrl(httpAddress!);
351 352 353
        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 454 455 456 457
    required OperatingSystemUtils osUtils,
    required Logger logger,
    required FileSystem fileSystem,
    HttpClient? httpClient,
    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
          : context.get<HttpClientFactory>()!())),
471
       _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
  List<Uri> sources = <Uri>[];
487 488 489 490
  DateTime? lastCompiled;
  DateTime? _previousCompiled;
  PackageConfig? lastPackageConfig;
  File? _widgetCacheOutputFile;
491

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

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
      final vm_service.Response response = await _vmService.createDevFS(fsName);
509
      _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
      final vm_service.Response response = await _vmService.createDevFS(fsName);
525
      _baseUri = Uri.parse(response.json!['uri'] as String);
526
    }
527
    _logger.printTrace('DevFS: Created new filesystem on the device ($_baseUri)');
528
    return _baseUri!;
529 530
  }

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
  /// 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`.
555 556
  String? _checkIfSingleWidgetReloadApplied() {
    final File? widgetCacheOutputFile = _widgetCacheOutputFile;
557 558
    if (widgetCacheOutputFile != null && widgetCacheOutputFile.existsSync()) {
      final String widget = widgetCacheOutputFile.readAsStringSync().trim();
559 560 561 562 563 564 565
      if (widget.isNotEmpty) {
        return widget;
      }
    }
    return null;
  }

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

591 592 593
    // Update modified files
    final Map<Uri, DevFSContent> dirtyEntries = <Uri, DevFSContent>{};
    int syncedBytes = 0;
594 595 596 597 598 599 600 601 602 603
    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.
604
    final Stopwatch compileTimer = _stopwatchFactory.createStopwatch('compile')..start();
605
    final Future<CompilerOutput?> pendingCompilerOutput = generator.recompile(
606 607
      mainUri,
      invalidatedFiles,
608
      outputPath: dillOutputPath,
609 610
      fs: _fileSystem,
      projectRootPath: projectRootPath,
611
      packageConfig: packageConfig,
612
      checkDartPluginRegistry: true, // The entry point is assumed not to have changed.
613
    ).then((CompilerOutput? result) {
614 615 616 617
      compileTimer.stop();
      return result;
    });

618
    if (bundle != null) {
619 620 621 622 623 624
      // Mark processing of bundle started for testability of starting the compile
      // before processing bundle.
      _logger.printTrace('Processing bundle.');
      // await null to give time for telling the compiler to compile.
      await null;

625
      // The tool writes the assets into the AssetBundle working dir so that they
626
      // are in the same location in DevFS and the iOS simulator.
627
      final String assetBuildDirPrefix = _asUriPath(getAssetBuildDirectory());
628
      final String assetDirectory = getAssetBuildDirectory();
629
      bundle.entries.forEach((String archivePath, DevFSContent content) {
630 631
        // 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.
632 633 634
        if (!content.isModified || bundleFirstUpload) {
          return;
        }
635
        final Uri deviceUri = _fileSystem.path.toUri(_fileSystem.path.join(assetDirectory, archivePath));
636 637 638
        if (deviceUri.path.startsWith(assetBuildDirPrefix)) {
          archivePath = deviceUri.path.substring(assetBuildDirPrefix.length);
        }
639 640 641 642
        dirtyEntries[deviceUri] = content;
        syncedBytes += content.size;
        if (archivePath != null && !bundleFirstUpload) {
          assetPathsToEvict.add(archivePath);
643
        }
644
      });
645 646 647 648

      // Mark processing of bundle done for testability of starting the compile
      // before processing bundle.
      _logger.printTrace('Bundle processing done.');
649
    }
650
    final CompilerOutput? compilerOutput = await pendingCompilerOutput;
651
    if (compilerOutput == null || compilerOutput.errorCount > 0) {
652
      return UpdateFSReport();
653
    }
654
    // Only update the last compiled time if we successfully compiled.
655
    _previousCompiled = lastCompiled;
656
    lastCompiled = candidateCompileTime;
657
    // list of sources that needs to be monitored are in [compilerOutput.sources]
658
    sources = compilerOutput.sources;
659
    //
660 661 662
    // Don't send full kernel file that would overwrite what VM already
    // started loading from.
    if (!bundleFirstUpload) {
663 664
      final String compiledBinary = compilerOutput.outputFilename;
      if (compiledBinary.isNotEmpty) {
665
        final Uri entryUri = _fileSystem.path.toUri(pathToReload);
666
        final DevFSFileContent content = DevFSFileContent(_fileSystem.file(compiledBinary));
667 668
        syncedBytes += content.size;
        dirtyEntries[entryUri] = content;
669
      }
670
    }
671
    _logger.printTrace('Updating files.');
672
    final Stopwatch transferTimer = _stopwatchFactory.createStopwatch('transfer')..start();
673
    if (dirtyEntries.isNotEmpty) {
674
      await (devFSWriter ?? _httpWriter).write(dirtyEntries, _baseUri!, _httpWriter);
675
    }
676
    transferTimer.stop();
677
    _logger.printTrace('DevFS: Sync finished');
678 679 680 681 682
    return UpdateFSReport(
      success: true,
      syncedBytes: syncedBytes,
      invalidatedSourcesCount: invalidatedFiles.length,
      fastReassembleClassName: _checkIfSingleWidgetReloadApplied(),
683 684
      compileDuration: compileTimer.elapsed,
      transferDuration: transferTimer.elapsed,
685
    );
686
  }
687

688
  /// Converts a platform-specific file path to a platform-independent URL path.
689
  String _asUriPath(String filePath) => '${_fileSystem.path.toUri(filePath).path}/';
690
}
691 692 693 694 695 696 697 698 699 700 701

/// 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({
702
    required FileSystem fileSystem,
703 704 705 706 707
  }) : _fileSystem = fileSystem;

  final FileSystem _fileSystem;

  @override
708
  Future<void> write(Map<Uri, DevFSContent> entries, Uri baseUri, [DevFSWriter? parent]) async {
709
    try {
710 711 712
      for (final MapEntry<Uri, DevFSContent> entry in entries.entries) {
        final Uri uri = entry.key;
        final DevFSContent devFSContent = entry.value;
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
        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());
    }
  }
}