forked from felangel/mason
/
dev.dart
321 lines (278 loc) · 9.93 KB
/
dev.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
import 'dart:collection';
import 'dart:convert';
import 'dart:io' as io;
import 'package:dart_frog_cli/src/command.dart';
import 'package:dart_frog_cli/src/commands/commands.dart';
import 'package:dart_frog_cli/src/commands/dev/templates/dart_frog_dev_server_bundle.dart';
import 'package:dart_frog_cli/src/runtime_compatibility.dart'
as runtime_compatibility;
import 'package:mason/mason.dart';
import 'package:path/path.dart' as path;
import 'package:stream_transform/stream_transform.dart';
import 'package:watcher/watcher.dart';
/// Typedef for [io.Process.start].
typedef ProcessStart = Future<io.Process> Function(
String executable,
List<String> arguments, {
bool runInShell,
});
/// Typedef for [io.Process.run].
typedef ProcessRun = Future<io.ProcessResult> Function(
String executable,
List<String> arguments,
);
/// Typedef for [DirectoryWatcher.new].
typedef DirectoryWatcherBuilder = DirectoryWatcher Function(
String directory,
);
/// Typedef for [RestorableDirectoryGeneratorTarget.new]
typedef RestorableDirectoryGeneratorTargetBuilder
= RestorableDirectoryGeneratorTarget Function(Logger? logger);
/// Typedef for [io.exit].
typedef Exit = dynamic Function(int exitCode);
RestorableDirectoryGeneratorTarget _defaultGeneratorTarget(Logger? logger) {
return RestorableDirectoryGeneratorTarget(
io.Directory(
path.join(io.Directory.current.path, '.dart_frog'),
),
logger: logger,
);
}
/// {@template dev_command}
/// `dart_frog dev` command which starts the dev server`.
/// {@endtemplate}
class DevCommand extends DartFrogCommand {
/// {@macro dev_command}
DevCommand({
super.logger,
void Function(io.Directory)? ensureRuntimeCompatibility,
DirectoryWatcherBuilder? directoryWatcher,
GeneratorBuilder? generator,
RestorableDirectoryGeneratorTargetBuilder? generatorTarget,
Exit? exit,
bool? isWindows,
ProcessRun? runProcess,
io.ProcessSignal? sigint,
ProcessStart? startProcess,
}) : _ensureRuntimeCompatibility = ensureRuntimeCompatibility ??
runtime_compatibility.ensureRuntimeCompatibility,
_directoryWatcher = directoryWatcher ?? DirectoryWatcher.new,
_generator = generator ?? MasonGenerator.fromBundle,
_exit = exit ?? io.exit,
_isWindows = isWindows ?? io.Platform.isWindows,
_runProcess = runProcess ?? io.Process.run,
_sigint = sigint ?? io.ProcessSignal.sigint,
_startProcess = startProcess ?? io.Process.start,
_generatorTarget = generatorTarget ?? _defaultGeneratorTarget {
argParser.addOption(
'port',
abbr: 'p',
defaultsTo: '8080',
help: 'Which port number the server should start on.',
);
}
final void Function(io.Directory) _ensureRuntimeCompatibility;
final DirectoryWatcherBuilder _directoryWatcher;
final GeneratorBuilder _generator;
final Exit _exit;
final bool _isWindows;
final ProcessRun _runProcess;
final io.ProcessSignal _sigint;
final ProcessStart _startProcess;
final RestorableDirectoryGeneratorTargetBuilder _generatorTarget;
@override
final String description = 'Run a local development server.';
@override
final String name = 'dev';
@override
Future<int> run() async {
_ensureRuntimeCompatibility(cwd);
var reloading = false;
var hotReloadEnabled = false;
final port = io.Platform.environment['PORT'] ?? results['port'] as String;
final target = _generatorTarget(logger);
final generator = await _generator(dartFrogDevServerBundle);
Future<void> codegen() async {
logger.detail('[codegen] running pre-gen...');
var vars = <String, dynamic>{'port': port};
await generator.hooks.preGen(
vars: vars,
workingDirectory: cwd.path,
onVarsChanged: (v) => vars = v,
);
logger.detail('[codegen] running generate...');
final _ = await generator.generate(
target,
vars: vars,
fileConflictResolution: FileConflictResolution.overwrite,
);
logger.detail('[codegen] complete.');
}
Future<void> reload() async {
logger.detail('[codegen] reloading...');
reloading = true;
await codegen();
reloading = false;
logger.detail('[codegen] reload complete.');
}
Future<void> serve() async {
logger.detail(
'''[process] dart --enable-vm-service ${path.join('.dart_frog', 'server.dart')}''',
);
final process = await _startProcess(
'dart',
['--enable-vm-service', path.join('.dart_frog', 'server.dart')],
runInShell: true,
);
// On Windows listen for CTRL-C and use taskkill to kill
// the spawned process along with any child processes.
// https://github.com/dart-lang/sdk/issues/22470
if (_isWindows) _sigint.watch().listen((_) => _killProcess(process));
var hasError = false;
process.stderr.listen((_) async {
hasError = true;
if (reloading) return;
final message = utf8.decode(_).trim();
if (message.isEmpty) return;
logger.err(message);
if (!hotReloadEnabled) {
await _killProcess(process);
logger.detail('[process] exit(1)');
_exit(1);
}
await target.rollback();
});
process.stdout.listen((_) {
final message = utf8.decode(_).trim();
final containsHotReload = message.contains('[hotreload]');
if (containsHotReload) hotReloadEnabled = true;
if (message.isNotEmpty) logger.info(message);
final shouldCacheSnapshot = containsHotReload && !hasError;
if (shouldCacheSnapshot) target.cacheLatestSnapshot();
hasError = false;
});
}
final progress = logger.progress('Serving');
await codegen();
await serve();
final localhost = link(uri: Uri.parse('http://localhost:$port'));
progress.complete('Running on $localhost');
final entrypoint = path.join(cwd.path, 'main.dart');
final pubspec = path.join(cwd.path, 'pubspec.yaml');
final public = path.join(cwd.path, 'public');
final routes = path.join(cwd.path, 'routes');
bool shouldReload(WatchEvent event) {
logger.detail('[watcher] $event');
return path.equals(entrypoint, event.path) ||
path.equals(pubspec, event.path) ||
path.isWithin(routes, event.path) ||
path.isWithin(public, event.path);
}
final watcher = _directoryWatcher(path.join(cwd.path));
final subscription = watcher.events
.where(shouldReload)
.debounce(Duration.zero)
.listen((_) => reload());
await subscription.asFuture<void>();
await subscription.cancel();
return ExitCode.success.code;
}
Future<void> _killProcess(io.Process process) async {
logger.detail('[process] killing process...');
if (_isWindows) {
logger.detail('[process] taskkill /F /T /PID ${process.pid}');
await _runProcess('taskkill', ['/F', '/T', '/PID', '${process.pid}']);
} else {
logger.detail('[process] process.kill()...');
process.kill();
}
logger.detail('[process] killing process complete.');
}
}
/// {@template cached_file}
/// A cached file which consists of the file path and contents.
/// {@endtemplate}
class CachedFile {
/// {@macro cached_file}
const CachedFile({required this.path, required this.contents});
/// The generated file path.
final String path;
/// The contents of the generated file.s
final List<int> contents;
}
/// Signature for the `createFile` method on [DirectoryGeneratorTarget].
typedef CreateFile = Future<GeneratedFile> Function(
String path,
List<int> contents, {
Logger? logger,
OverwriteRule? overwriteRule,
});
/// {@template restorable_directory_generator_target}
/// A [DirectoryGeneratorTarget] that is capable of
/// caching and restoring file snapshots.
/// {@endtemplate}
class RestorableDirectoryGeneratorTarget extends DirectoryGeneratorTarget {
/// {@macro restorable_directory_generator_target}
RestorableDirectoryGeneratorTarget(
super.dir, {
CreateFile? createFile,
Logger? logger,
}) : _cachedSnapshots = Queue<CachedFile>(),
_createFile = createFile,
_logger = logger;
final CreateFile? _createFile;
final Logger? _logger;
final Queue<CachedFile> _cachedSnapshots;
CachedFile? get _cachedSnapshot {
return _cachedSnapshots.isNotEmpty ? _cachedSnapshots.last : null;
}
CachedFile? _latestSnapshot;
/// Removes the latest cached snapshot.
void _removeLatestSnapshot() {
_logger?.detail('[codegen] attempting to remove latest snapshot.');
if (_cachedSnapshots.length > 1) {
_cachedSnapshots.removeLast();
_logger?.detail('[codegen] removed latest snapshot.');
}
}
/// Remove the latest snapshot and restore the previously
/// cached snapshot.
Future<void> rollback() async {
_logger?.detail('[codegen] rolling back...');
_removeLatestSnapshot();
await _restoreLatestSnapshot();
_logger?.detail('[codegen] rollback complete.');
}
/// Restore the latest cached snapshot.
Future<void> _restoreLatestSnapshot() async {
final snapshot = _cachedSnapshot;
if (snapshot == null) return;
_logger?.detail('[codegen] restoring previous snapshot...');
await createFile(snapshot.path, snapshot.contents);
_logger?.detail('[codegen] restored previous snapshot.');
}
/// Cache the latest recorded snapshot.
void cacheLatestSnapshot() {
final snapshot = _latestSnapshot;
if (snapshot == null) return;
_cachedSnapshots.add(snapshot);
_logger?.detail('[codegen] cached latest snapshot.');
// Keep only the 2 most recent snapshots.
if (_cachedSnapshots.length > 2) _cachedSnapshots.removeFirst();
}
@override
Future<GeneratedFile> createFile(
String path,
List<int> contents, {
Logger? logger,
OverwriteRule? overwriteRule,
}) {
_latestSnapshot = CachedFile(path: path, contents: contents);
return (_createFile ?? super.createFile)(
path,
contents,
logger: logger,
overwriteRule: overwriteRule,
);
}
}