This commit is contained in:
thosakwe 2016-12-21 12:34:15 -05:00
parent d40a20e52c
commit 08e12d9f4a
4 changed files with 110 additions and 51 deletions

View file

@ -1,41 +1,41 @@
import "dart:io"; import 'dart:io';
import "package:args/command_runner.dart"; import 'package:args/command_runner.dart';
import "package:console/console.dart"; import 'package:console/console.dart';
class ServiceCommand extends Command { class ServiceCommand extends Command {
final String CUSTOM = "Custom"; final String CUSTOM = 'Custom';
final String MEMORY = "In-Memory"; final String MEMORY = 'In-Memory';
final String MONGO = "MongoDB"; final String MONGO = 'MongoDB';
final String MONGO_TYPED = "MongoDB (typed)"; final String MONGO_TYPED = 'MongoDB (typed)';
final String TRESTLE = "Trestle"; final String TRESTLE = 'Trestle';
final TextPen _pen = new TextPen(); final TextPen _pen = new TextPen();
@override @override
String get name => "service"; String get name => 'service';
@override @override
String get description => "Creates a new service within the given project."; String get description => 'Creates a new service within the given project.';
@override @override
run() async { run() async {
var name = await readInput("Name of Service (not plural): "); var name = await readInput('Name of Service (not plural): ');
var chooser = new Chooser([TRESTLE, MONGO, MONGO_TYPED, MEMORY, CUSTOM], var chooser = new Chooser([TRESTLE, MONGO, MONGO_TYPED, MEMORY, CUSTOM],
message: "What type of service would you like to create? "); message: 'What type of service would you like to create? ');
var type = await chooser.choose(); var type = await chooser.choose();
fail() { fail() {
_pen.red(); _pen.red();
_pen("Could not successfully create service $name."); _pen('Could not successfully create service $name.');
_pen(); _pen();
} }
String serviceSource = ""; String serviceSource = '';
if (type == MONGO) { if (type == MONGO) {
serviceSource = _generateMongoService(name); serviceSource = _generateMongoService(name);
await _generateMemoryModel(name);
} else if (type == MONGO_TYPED) { } else if (type == MONGO_TYPED) {
serviceSource = _generateMongoTypedService(name); serviceSource = _generateMongoTypedService(name);
await _generateMongoModel(name); await _generateMongoModel(name);
} else if (type == MEMORY) { } else if (type == MEMORY) {
serviceSource = _generateMemoryService(name); serviceSource = _generateMemoryService(name);
@ -43,23 +43,23 @@ class ServiceCommand extends Command {
serviceSource = _generateCustomService(name); serviceSource = _generateCustomService(name);
} else if (type == TRESTLE) { } else if (type == TRESTLE) {
_pen.blue(); _pen.blue();
_pen("${Icon.STAR} Trestle services are not yet implemented. :("); _pen('${Icon.STAR} Trestle services are not yet implemented. :(');
_pen(); _pen();
} else { } else {
print("Code to generate a $type service is not yet written."); print('Code to generate a $type service is not yet written.');
} }
if (serviceSource.isEmpty) { if (serviceSource.isEmpty) {
fail(); fail();
throw new Exception("Empty generated service code."); throw new Exception('Empty generated service code.');
} }
var servicesDir = new Directory("lib/src/services"); var servicesDir = new Directory('lib/src/services');
var serviceFile = var serviceFile =
new File.fromUri(servicesDir.uri.resolve("${name.toLowerCase()}.dart")); new File.fromUri(servicesDir.uri.resolve('${name.toLowerCase()}.dart'));
var testDir = new Directory("test/services"); var testDir = new Directory('test/services');
var testFile = new File.fromUri( var testFile = new File.fromUri(
testDir.uri.resolve("${name.toLowerCase()}_test.dart")); testDir.uri.resolve('${name.toLowerCase()}_test.dart'));
if (!await servicesDir.exists()) await servicesDir.create(recursive: true); if (!await servicesDir.exists()) await servicesDir.create(recursive: true);
@ -67,10 +67,10 @@ class ServiceCommand extends Command {
await serviceFile.writeAsString(serviceSource); await serviceFile.writeAsString(serviceSource);
if (type == MONGO_TYPED) { if (type == MONGO_TYPED || type == MEMORY) {
var serviceLibrary = new File("lib/src/models/models.dart"); var serviceLibrary = new File('lib/src/models/models.dart');
await serviceLibrary.writeAsString( await serviceLibrary.writeAsString(
"\nexport '${name.toLowerCase()}.dart';", '\nexport "${name.toLowerCase()}.dart";',
mode: FileMode.APPEND); mode: FileMode.APPEND);
} }
@ -84,7 +84,7 @@ class ServiceCommand extends Command {
} }
_pen.green(); _pen.green();
_pen("${Icon.CHECKMARK} Successfully generated service $name."); _pen('${Icon.CHECKMARK} Successfully generated service $name.');
_pen(); _pen();
} }
@ -101,6 +101,44 @@ class ${name}Service extends Service {
.trim(); .trim();
} }
_generateMemoryModel(String name) async {
final lower = name.toLowerCase();
final file = new File('lib/src/models/$lower.dart');
if (!await file.exists()) await file.createSync(recursive: true);
await file.writeAsString('''
library angel.models.$lower;
import 'dart:convert';
import 'package:angel_framework/angel_framework.dart';
class $name extends MemoryModel {
String name, desc;
$name({String id, this.name, this.desc}) {
this.id = id;
}
factory $name.fromJson(String json) => new $name.fromMap(JSON.decode(json));
factory $name.fromMap(Map data) => new $name(
id: data['id']
name: data['name'],
desc: data['desc']);
Map toJson() {
return {
'id': id,
'name': name,
'desc': desc
};
}
}
'''
.trim());
}
_generateMemoryService(String name) { _generateMemoryService(String name) {
return ''' return '''
import 'package:angel_framework/defs.dart'; import 'package:angel_framework/defs.dart';
@ -108,6 +146,26 @@ import 'package:angel_framework/angel_framework.dart';
/// Store in-memory instances of this class. /// Store in-memory instances of this class.
class $name extends MemoryModel { class $name extends MemoryModel {
String name, desc;
$name({String id, this.name, this.desc}) {
this.id = id;
}
factory $name.fromJson(String json) => new $name.fromMap(JSON.decode(json));
factory $name.fromMap(Map data) => new $name(
id: data['id']
name: data['name'],
desc: data['desc']);
Map toJson() {
return {
'id': id,
'name': name,
'desc': desc
};
}
} }
/// Manages [$name] in-memory. /// Manages [$name] in-memory.
@ -135,18 +193,22 @@ import 'package:angel_mongo/model.dart';
class $name extends Model { class $name extends Model {
String name, desc; String name, desc;
$name({this.name, this.desc}); $name({String id, this.name, this.desc}) {
this.id = id;
}
factory $name.fromJson(String json) => new $name.fromMap(JSON.decode(json)); factory $name.fromJson(String json) => new $name.fromMap(JSON.decode(json));
factory $name.fromMap(Map data) => new $name( factory $name.fromMap(Map data) => new $name(
name: data["name"], id: data['id']
desc: data["desc"]); name: data['name'],
desc: data['desc']);
Map toJson() { Map toJson() {
return { return {
"name": name, 'id': id,
"desc": desc 'name': name,
'desc': desc
}; };
} }
} }
@ -164,9 +226,9 @@ import 'package:mongo_dart/mongo_dart.dart';
configureServer(Db db) { configureServer(Db db) {
return (Angel app) async { return (Angel app) async {
app.use("/api/${lower}s", new ${name}Service(db.collection("${lower}s"))); app.use('/api/${lower}s', new ${name}Service(db.collection('${lower}s')));
HookedService service = app.service("api/${lower}s"); HookedService service = app.service('api/${lower}s');
app.container.singleton(service.inner); app.container.singleton(service.inner);
}; };
} }
@ -193,9 +255,9 @@ export '../models/$lower.dart';
configureServer(Db db) { configureServer(Db db) {
return (Angel app) async { return (Angel app) async {
app.use("/api/${lower}s", new ${name}Service(db.collection("${lower}s"))); app.use('/api/${lower}s', new ${name}Service(db.collection('${lower}s')));
HookedService service = app.service("api/${lower}s"); HookedService service = app.service('api/${lower}s');
app.container.singleton(service.inner); app.container.singleton(service.inner);
}; };
} }
@ -257,6 +319,7 @@ main() async {
}); });
} }
'''.trim(); '''
.trim();
} }
} }

View file

@ -27,22 +27,18 @@ class StartCommand extends Command {
final scriptsNode = doc.contents['scripts']; final scriptsNode = doc.contents['scripts'];
if (scriptsNode != null && scriptsNode.containsKey('start')) { if (scriptsNode != null && scriptsNode.containsKey('start')) {
final scripts = scriptsNode['start'] is List try {
? scriptsNode['start'] var scripts =
: [scriptsNode['start']]; await Process.start('pub', ['global', 'run', 'scripts', 'start']);
scripts.stdout.pipe(stdout);
for (String script in scripts) { scripts.stderr.pipe(stderr);
final split = script.split(' '); int code = await scripts.exitCode;
final result = await Process.run(split.first, split.skip(1).toList(),
stdoutEncoding: null, stderrEncoding: null);
final code = result.exitCode;
stdout.add(result.stdout);
stderr.add(result.stderr);
if (code != 0) { if (code != 0) {
throw new Exception("Command '$script' exited with code $code."); throw new Exception('`scripts start` failed with exit code $code.');
} }
} catch (e) {
// No scripts? No problem...
} }
} }
} }

View file

@ -63,7 +63,7 @@ main() async {
setUp(() async { setUp(() async {
app = await createServer(); app = await createServer();
client = await connectTo(app, saveSession: false); client = await connectTo(app);
}); });
tearDown(() async { tearDown(() async {

View file

@ -1,5 +1,5 @@
name: angel_cli name: angel_cli
version: 1.0.0-dev+6 version: 1.0.0-dev+7
description: Command-line tools for the Angel framework. description: Command-line tools for the Angel framework.
author: Tobe O <thosakwe@gmail.com> author: Tobe O <thosakwe@gmail.com>
homepage: https://github.com/angel-dart/angel_cli homepage: https://github.com/angel-dart/angel_cli