platform/lib/src/commands/start.dart

102 lines
2.5 KiB
Dart
Raw Normal View History

2016-12-13 17:50:53 +00:00
import 'dart:io';
import 'package:args/command_runner.dart';
2016-12-24 04:42:55 +00:00
import 'package:watcher/watcher.dart';
2016-12-13 17:50:53 +00:00
import 'package:yaml/yaml.dart';
2016-12-24 04:42:55 +00:00
Process server;
bool watching = false;
2016-12-13 17:50:53 +00:00
class StartCommand extends Command {
@override
String get name => 'start';
@override
String get description =>
'Runs any `start` scripts, and then runs the server.';
StartCommand() : super() {
2016-12-24 04:42:55 +00:00
argParser
..addFlag('production',
help: 'Starts the server in production mode.',
negatable: false,
defaultsTo: false)
..addFlag('watch',
abbr: 'w',
help: 'Restart the server on file changes.',
defaultsTo: true);
2016-12-13 17:50:53 +00:00
}
@override
run() async {
2016-12-24 04:42:55 +00:00
if (argResults['watch']) {
new DirectoryWatcher('bin').events.listen((_) async => start());
new DirectoryWatcher('config').events.listen((_) async => start());
new DirectoryWatcher('lib').events.listen((_) async => start());
}
return await start();
}
start() async {
bool isNew = true;
if (server != null) {
isNew = false;
if (!server.kill()) {
throw new Exception('Could not kill existing server process.');
}
}
2016-12-13 17:50:53 +00:00
final pubspec = new File('pubspec.yaml');
if (await pubspec.exists()) {
// Run start scripts
final doc = loadYamlDocument(await pubspec.readAsString());
final scriptsNode = doc.contents['scripts'];
if (scriptsNode != null && scriptsNode.containsKey('start')) {
2016-12-21 17:34:15 +00:00
try {
var scripts =
await Process.start('pub', ['global', 'run', 'scripts', 'start']);
scripts.stdout.pipe(stdout);
scripts.stderr.pipe(stderr);
int code = await scripts.exitCode;
2016-12-13 17:50:53 +00:00
if (code != 0) {
2016-12-21 17:34:15 +00:00
throw new Exception('`scripts start` failed with exit code $code.');
2016-12-13 17:50:53 +00:00
}
2016-12-21 17:34:15 +00:00
} catch (e) {
// No scripts? No problem...
2016-12-13 17:50:53 +00:00
}
}
}
2016-12-24 04:42:55 +00:00
if (isNew)
print('Starting server...');
else
print('Changes detected - restarting server...');
2016-12-13 17:50:53 +00:00
final env = {};
if (argResults['production']) env['ANGEL_ENV'] = 'production';
2016-12-24 04:42:55 +00:00
server = await Process.start(Platform.executable, ['bin/server.dart'],
2016-12-13 17:50:53 +00:00
environment: env);
2016-12-24 04:42:55 +00:00
try {
if (isNew) {
server.stdout.pipe(stdout);
server.stderr.pipe(stderr);
}
} catch (e) {
print(e);
}
if (!isNew) {
print('Successfully restarted server.');
}
2016-12-13 17:50:53 +00:00
exitCode = await server.exitCode;
}
}