project.dart 2.48 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 'package:file/file.dart';
6
import 'package:flutter_tools/src/web/file_generators/flutter_js.dart';
7 8

import '../test_utils.dart';
9
import 'deferred_components_config.dart';
10

11 12 13 14 15 16 17 18 19 20 21
const String _kDefaultHtml  = '''
<html>
    <head>
        <title>Hello, World</title>
    </head>
    <body>
        <script src="main.dart.js"></script>
    </body>
</html>
''';

22
abstract class Project {
23 24 25 26 27
  /// Creates a flutter Project for testing.
  ///
  /// If passed, `indexHtml` is used as the contents of the web/index.html file.
  Project({this.indexHtml = _kDefaultHtml});

28
  late Directory dir;
29 30

  String get pubspec;
31 32 33 34
  String? get main => null;
  String? get test => null;
  String? get generatedFile => null;
  DeferredComponentsConfig? get deferredComponents => null;
35

36
  Uri get mainDart => Uri.parse('package:test/main.dart');
37

38 39 40 41 42 43 44
  /// The contents for the index.html file of this `Project`.
  ///
  /// Defaults to [_kDefaultHtml] via the Project constructor.
  ///
  /// (Used by [HotReloadProject].)
  final String indexHtml;

45 46
  Future<void> setUpIn(Directory dir) async {
    this.dir = dir;
47
    writeFile(fileSystem.path.join(dir.path, 'pubspec.yaml'), pubspec);
48
    final String? main = this.main;
49
    if (main != null) {
50
      writeFile(fileSystem.path.join(dir.path, 'lib', 'main.dart'), main);
51
    }
52
    final String? test = this.test;
53
    if (test != null) {
54
      writeFile(fileSystem.path.join(dir.path, 'test', 'test.dart'), test);
55
    }
56
    final String? generatedFile = this.generatedFile;
57
    if (generatedFile != null) {
58
      writeFile(fileSystem.path.join(dir.path, '.dart_tool', 'flutter_gen', 'flutter_gen.dart'), generatedFile);
59
    }
60
    deferredComponents?.setUpIn(dir);
61 62 63 64 65

    // Setup for different flutter web initializations
    writeFile(fileSystem.path.join(dir.path, 'web', 'index.html'), indexHtml);
    writeFile(fileSystem.path.join(dir.path, 'web', 'flutter.js'), generateFlutterJsFile());
    writeFile(fileSystem.path.join(dir.path, 'web', 'flutter_service_worker.js'), '');
66
    writePackages(dir.path);
67 68 69
    await getPackages(dir.path);
  }

70 71
  int lineContaining(String contents, String search) {
    final int index = contents.split('\n').indexWhere((String l) => l.contains(search));
72
    if (index == -1) {
73
      throw Exception("Did not find '$search' inside the file");
74
    }
75
    return index + 1; // first line is line 1, not line 0
76
  }
77
}