Cleared static analytics errors

This commit is contained in:
thomashii 2021-02-16 10:10:09 +08:00
parent 896d1a76fe
commit daec5e35ca
32 changed files with 196 additions and 136 deletions

View file

@ -46,6 +46,12 @@ dart --observe bin/dev.dart
Next, check out the [detailed documentation](https://docs.angel-dart.dev/v/2.x) to learn to flesh out your project. Next, check out the [detailed documentation](https://docs.angel-dart.dev/v/2.x) to learn to flesh out your project.
## Development
* Install development version of Angel CLI
`dart pub global activate --source path ./packages/cli`
`dart pub global activate --source git https://github.com/dukefirehawk/angel/packages/cli`
## Examples and Documentation ## Examples and Documentation
Visit the [documentation](https://docs.angel-dart.dev/v/2.x) Visit the [documentation](https://docs.angel-dart.dev/v/2.x)
for dozens of guides and resources, including video tutorials, for dozens of guides and resources, including video tutorials,

View file

@ -9,12 +9,16 @@ Includes functionality such as:
* Renaming projects * Renaming projects
* Much more... * Much more...
To install: * To install:
```bash ```bash
$ pub global activate angel_cli $ pub global activate angel_cli
``` ```
* Install development version
`dart pub global activate --source path ./packages/cli`
`dart pub global activate --source git https://github.com/dukefirehawk/angel/packages/cli`
And then, for information on each command: And then, for information on each command:
```bash ```bash

View file

@ -11,7 +11,7 @@ class DeployCommand extends Command {
'Generates scaffolding + helper functionality for deploying servers. Run this in your project root.'; 'Generates scaffolding + helper functionality for deploying servers. Run this in your project root.';
DeployCommand() { DeployCommand() {
addSubcommand(new NginxCommand()); addSubcommand(NginxCommand());
addSubcommand(new SystemdCommand()); addSubcommand(SystemdCommand());
} }
} }

View file

@ -26,7 +26,7 @@ class DoctorCommand extends Command {
print(green.wrap( print(green.wrap(
"$checkmark Git executable found: v${version.replaceAll('git version', '').trim()}")); "$checkmark Git executable found: v${version.replaceAll('git version', '').trim()}"));
} else } else
throw new Exception("Git executable exit code not 0"); throw Exception("Git executable exit code not 0");
} catch (exc) { } catch (exc) {
print(red.wrap("$ballot Git executable not found")); print(red.wrap("$ballot Git executable not found"));
} }

View file

@ -263,41 +263,44 @@ Future preBuild(Directory projectDir) async {
if (buildCode != 0) throw new Exception('Failed to pre-build resources.'); if (buildCode != 0) throw new Exception('Failed to pre-build resources.');
} }
const RepoArchiveLocation = "https://github.com/angel-dart";
const RepoLocation = "https://github.com/dukefirehawk";
const BoilerplateInfo graphQLBoilerplate = const BoilerplateInfo( const BoilerplateInfo graphQLBoilerplate = const BoilerplateInfo(
'GraphQL', 'GraphQL',
"A starting point for GraphQL API servers.", "A starting point for GraphQL API servers.",
'https://github.com/angel-dart/angel.git', '${RepoLocation}/boilerplates.git',
ref: 'graphql', ref: 'graphql',
); );
const BoilerplateInfo ormBoilerplate = const BoilerplateInfo( const BoilerplateInfo ormBoilerplate = const BoilerplateInfo(
'ORM', 'ORM',
"A starting point for applications that use Angel's ORM.", "A starting point for applications that use Angel's ORM.",
'https://github.com/angel-dart/angel.git', '${RepoLocation}/boilerplates.git',
ref: 'orm', ref: 'orm',
); );
const BoilerplateInfo basicBoilerplate = const BoilerplateInfo( const BoilerplateInfo basicBoilerplate = const BoilerplateInfo(
'Basic', 'Basic',
'Minimal starting point for Angel 2.x - A simple server with only a few additional packages.', 'Minimal starting point for Angel 2.x - A simple server with only a few additional packages.',
'https://github.com/angel-dart/angel.git'); '${RepoLocation}/boilerplates.git');
const BoilerplateInfo legacyBoilerplate = const BoilerplateInfo( const BoilerplateInfo legacyBoilerplate = const BoilerplateInfo(
'Legacy', 'Legacy',
'Minimal starting point for applications running Angel 1.1.x.', 'Minimal starting point for applications running Angel 1.1.x.',
'https://github.com/angel-dart/angel.git', '${RepoArchiveLocation}/angel.git',
ref: '1.1.x', ref: '1.1.x',
); );
const BoilerplateInfo sharedBoilerplate = const BoilerplateInfo( const BoilerplateInfo sharedBoilerplate = const BoilerplateInfo(
'Shared', 'Shared',
'Holds common models and files shared across multiple Dart projects.', 'Holds common models and files shared across multiple Dart projects.',
'https://github.com/angel-dart/boilerplate_shared.git'); '${RepoLocation}/boilerplate_shared.git');
const BoilerplateInfo sharedOrmBoilerplate = const BoilerplateInfo( const BoilerplateInfo sharedOrmBoilerplate = const BoilerplateInfo(
'Shared (ORM)', 'Shared (ORM)',
'Holds common models and files shared across multiple Dart projects.', 'Holds common models and files shared across multiple Dart projects.',
'https://github.com/angel-dart/boilerplate_shared.git', '${RepoLocation}/boilerplate_shared.git',
ref: 'orm', ref: 'orm',
); );
@ -306,8 +309,8 @@ const List<BoilerplateInfo> boilerplates = const [
//legacyBoilerplate, //legacyBoilerplate,
ormBoilerplate, ormBoilerplate,
graphQLBoilerplate, graphQLBoilerplate,
sharedBoilerplate, //sharedBoilerplate,
sharedOrmBoilerplate, //sharedOrmBoilerplate,
]; ];
class BoilerplateInfo { class BoilerplateInfo {

View file

@ -14,7 +14,7 @@ import 'make/maker.dart';
class InstallCommand extends Command { class InstallCommand extends Command {
static const String repo = 'https://github.com/angel-dart/install.git'; static const String repo = 'https://github.com/angel-dart/install.git';
static final Directory installRepo = static final Directory installRepo =
new Directory.fromUri(homeDir.uri.resolve('./.angel/addons')); Directory.fromUri(homeDir.uri.resolve('./.angel/addons'));
@override @override
String get name => 'install'; String get name => 'install';
@ -72,7 +72,7 @@ class InstallCommand extends Command {
for (var packageName in argResults.rest) { for (var packageName in argResults.rest) {
var packageDir = var packageDir =
new Directory.fromUri(installRepo.uri.resolve(packageName)); Directory.fromUri(installRepo.uri.resolve(packageName));
if (!await packageDir.exists()) if (!await packageDir.exists())
throw 'No add-on named "$packageName" is installed. You might need to run `angel install --update`.'; throw 'No add-on named "$packageName" is installed. You might need to run `angel install --update`.';
@ -90,7 +90,7 @@ class InstallCommand extends Command {
.map((k) { .map((k) {
var dep = projectPubspec.dependencies[k]; var dep = projectPubspec.dependencies[k];
if (dep is HostedDependency) if (dep is HostedDependency)
return new MakerDependency(k, dep.version.toString()); return MakerDependency(k, dep.version.toString());
return null; return null;
}) })
.where((d) => d != null) .where((d) => d != null)
@ -99,14 +99,13 @@ class InstallCommand extends Command {
deps.addAll(projectPubspec.devDependencies.keys.map((k) { deps.addAll(projectPubspec.devDependencies.keys.map((k) {
var dep = projectPubspec.devDependencies[k]; var dep = projectPubspec.devDependencies[k];
if (dep is HostedDependency) if (dep is HostedDependency)
return new MakerDependency(k, dep.version.toString(), dev: true); return MakerDependency(k, dep.version.toString(), dev: true);
return null; return null;
}).where((d) => d != null)); }).where((d) => d != null));
await depend(deps); await depend(deps);
var promptFile = var promptFile = File.fromUri(packageDir.uri.resolve('angel_cli.yaml'));
new File.fromUri(packageDir.uri.resolve('angel_cli.yaml'));
if (await promptFile.exists()) { if (await promptFile.exists()) {
var contents = await promptFile.readAsString(); var contents = await promptFile.readAsString();
@ -116,7 +115,7 @@ class InstallCommand extends Command {
// Loads globs // Loads globs
if (cfg['templates'] is List) { if (cfg['templates'] is List) {
globs.addAll( globs.addAll(
(cfg['templates'] as List).map((p) => new Glob(p.toString()))); (cfg['templates'] as List).map((p) => Glob(p.toString())));
} }
if (cfg['values'] is Map) { if (cfg['values'] is Map) {
@ -144,14 +143,14 @@ class InstallCommand extends Command {
await for (var entity in src.list()) { await for (var entity in src.list()) {
if (entity is Directory) { if (entity is Directory) {
var name = p.basename(entity.path); var name = p.basename(entity.path);
var newDir = new Directory.fromUri(dst.uri.resolve(name)); var newDir = Directory.fromUri(dst.uri.resolve(name));
await merge( await merge(
entity, newDir, prefix.isEmpty ? name : '$prefix/$name'); entity, newDir, prefix.isEmpty ? name : '$prefix/$name');
} else if (entity is File && } else if (entity is File &&
!entity.path.endsWith('angel_cli.yaml')) { !entity.path.endsWith('angel_cli.yaml')) {
var name = p.basename(entity.path); var name = p.basename(entity.path);
var target = dst.uri.resolve(name); var target = dst.uri.resolve(name);
var targetFile = new File.fromUri(target); var targetFile = File.fromUri(target);
bool allClear = !await targetFile.exists(); bool allClear = !await targetFile.exists();
if (!allClear) { if (!allClear) {
@ -187,7 +186,7 @@ class InstallCommand extends Command {
} }
} }
await merge(new Directory.fromUri(packageDir.uri.resolve('files')), await merge(Directory.fromUri(packageDir.uri.resolve('files')),
Directory.current, ''); Directory.current, '');
print('Successfully installed $packageName@${projectPubspec.version}.'); print('Successfully installed $packageName@${projectPubspec.version}.');
} }

View file

@ -13,17 +13,17 @@ class KeyCommand extends Command {
run() async { run() async {
var secret = rs.randomAlphaNumeric(32); var secret = rs.randomAlphaNumeric(32);
print('Generated new development JWT secret: $secret'); print('Generated new development JWT secret: $secret');
await changeSecret(new File('config/default.yaml'), secret); await changeSecret(File('config/default.yaml'), secret);
secret = rs.randomAlphaNumeric(32); secret = rs.randomAlphaNumeric(32);
print('Generated new production JWT secret: $secret'); print('Generated new production JWT secret: $secret');
await changeSecret(new File('config/production.yaml'), secret); await changeSecret(File('config/production.yaml'), secret);
} }
changeSecret(File file, String secret) async { changeSecret(File file, String secret) async {
if (await file.exists()) { if (await file.exists()) {
var contents = await file.readAsString(); var contents = await file.readAsString();
contents = contents.replaceAll(new RegExp(r'jwt_secret:[^\n]+\n?'), ''); contents = contents.replaceAll(RegExp(r'jwt_secret:[^\n]+\n?'), '');
await file.writeAsString(contents.trim() + '\njwt_secret: "$secret"'); await file.writeAsString(contents.trim() + '\njwt_secret: "$secret"');
} }
} }

View file

@ -15,11 +15,11 @@ class MakeCommand extends Command {
'Generates common code for your project, such as projects and controllers.'; 'Generates common code for your project, such as projects and controllers.';
MakeCommand() { MakeCommand() {
addSubcommand(new ControllerCommand()); addSubcommand(ControllerCommand());
addSubcommand(new MigrationCommand()); addSubcommand(MigrationCommand());
addSubcommand(new ModelCommand()); addSubcommand(ModelCommand());
addSubcommand(new PluginCommand()); addSubcommand(PluginCommand());
addSubcommand(new TestCommand()); addSubcommand(TestCommand());
addSubcommand(new ServiceCommand()); addSubcommand(ServiceCommand());
} }
} }

View file

@ -1,9 +1,9 @@
import 'dart:io'; import 'dart:io';
final RegExp _leadingSlashes = new RegExp(r'^/+'); final RegExp _leadingSlashes = RegExp(r'^/+');
String resolvePub() { String resolvePub() {
var exec = new File(Platform.resolvedExecutable); var exec = File(Platform.resolvedExecutable);
var pubPath = exec.parent.uri.resolve('pub').path; var pubPath = exec.parent.uri.resolve('pub').path;
if (Platform.isWindows) if (Platform.isWindows)
pubPath = pubPath.replaceAll(_leadingSlashes, '') + '.bat'; pubPath = pubPath.replaceAll(_leadingSlashes, '') + '.bat';

View file

@ -29,17 +29,17 @@ class RenameCommand extends Command {
newName = prompts.get('Rename project to'); newName = prompts.get('Rename project to');
} }
newName = new ReCase(newName).snakeCase; newName = ReCase(newName).snakeCase;
var choice = prompts.getBool('Rename the project to `$newName`?'); var choice = prompts.getBool('Rename the project to `$newName`?');
if (choice) { if (choice) {
print('Renaming project to `$newName`...'); print('Renaming project to `$newName`...');
var pubspecFile = var pubspecFile =
new File.fromUri(Directory.current.uri.resolve('pubspec.yaml')); File.fromUri(Directory.current.uri.resolve('pubspec.yaml'));
if (!await pubspecFile.exists()) { if (!await pubspecFile.exists()) {
throw new Exception('No pubspec.yaml found in current directory.'); throw Exception('No pubspec.yaml found in current directory.');
} else { } else {
var pubspec = await loadPubspec(); var pubspec = await loadPubspec();
var oldName = pubspec.name; var oldName = pubspec.name;
@ -66,7 +66,7 @@ renamePubspec(Directory dir, String oldName, String newName) async {
if (await pubspecFile.exists()) { if (await pubspecFile.exists()) {
var contents = await pubspecFile.readAsString(), oldContents = contents; var contents = await pubspecFile.readAsString(), oldContents = contents;
contents = contents =
contents.replaceAll(new RegExp('name:\\s*$oldName'), 'name: $newName'); contents.replaceAll(RegExp('name:\\s*$oldName'), 'name: $newName');
if (contents != oldContents) { if (contents != oldContents) {
await pubspecFile.writeAsString(contents); await pubspecFile.writeAsString(contents);
@ -76,7 +76,7 @@ renamePubspec(Directory dir, String oldName, String newName) async {
// print(cyan // print(cyan
// .wrap('Note that this does not actually modify your `pubspec.yaml`.')); // .wrap('Note that this does not actually modify your `pubspec.yaml`.'));
// TODO: https://github.com/dart-lang/pubspec_parse/issues/17 // TODO: https://github.com/dart-lang/pubspec_parse/issues/17
// var newPubspec = new Pubspec.fromJson(pubspec.toJson()..['name'] = newName); // var newPubspec = Pubspec.fromJson(pubspec.toJson()..['name'] = newName);
// await newPubspec.save(dir); // await newPubspec.save(dir);
} }
@ -84,7 +84,7 @@ renameDartFiles(Directory dir, String oldName, String newName) async {
if (!await dir.exists()) return; if (!await dir.exists()) return;
// Try to replace MongoDB URL // Try to replace MongoDB URL
var configGlob = new Glob('config/**/*.yaml'); var configGlob = Glob('config/**/*.yaml');
try { try {
await for (var yamlFile in configGlob.list(root: dir.absolute.path)) { await for (var yamlFile in configGlob.list(root: dir.absolute.path)) {
@ -98,19 +98,19 @@ renameDartFiles(Directory dir, String oldName, String newName) async {
} }
} catch (_) {} } catch (_) {}
var entry = new File.fromUri(dir.uri.resolve('lib/$oldName.dart')); var entry = File.fromUri(dir.uri.resolve('lib/$oldName.dart'));
if (await entry.exists()) { if (await entry.exists()) {
await entry.rename(dir.uri.resolve('lib/$newName.dart').toFilePath()); await entry.rename(dir.uri.resolve('lib/$newName.dart').toFilePath());
print('Renaming library file `${entry.absolute.path}`...'); print('Renaming library file `${entry.absolute.path}`...');
} }
var fmt = new DartFormatter(); var fmt = DartFormatter();
await for (FileSystemEntity file in dir.list(recursive: true)) { await for (FileSystemEntity file in dir.list(recursive: true)) {
if (file is File && file.path.endsWith('.dart')) { if (file is File && file.path.endsWith('.dart')) {
var contents = await file.readAsString(); var contents = await file.readAsString();
var ast = parseCompilationUnit(contents); var ast = parseCompilationUnit(contents);
var visitor = new RenamingVisitor(oldName, newName) var visitor = RenamingVisitor(oldName, newName)
..visitCompilationUnit(ast); ..visitCompilationUnit(ast);
if (visitor.replace.isNotEmpty) { if (visitor.replace.isNotEmpty) {

View file

@ -12,7 +12,7 @@ class CustomServiceGenerator extends ServiceGenerator {
@override @override
void applyToLibrary(LibraryBuilder library, String name, String lower) { void applyToLibrary(LibraryBuilder library, String name, String lower) {
library.body.add(new Class((clazz) { library.body.add(Class((clazz) {
clazz clazz
..name = '${name}Service' ..name = '${name}Service'
..extend = refer('Service'); ..extend = refer('Service');

View file

@ -34,7 +34,7 @@ class RethinkServiceGenerator extends ServiceGenerator {
void applyToLibrary(LibraryBuilder library, String name, String lower) { void applyToLibrary(LibraryBuilder library, String name, String lower) {
library.directives.addAll([ library.directives.addAll([
'package:angel_rethink/angel_rethink.dart', 'package:angel_rethink/angel_rethink.dart',
'package:rethinkdb_driver/rethinkdb_driver.dart' 'package:rethinkdb_dart/rethinkdb_dart.dart'
].map((str) => new Directive.import(str))); ].map((str) => new Directive.import(str)));
} }

View file

@ -2,10 +2,10 @@ import 'dart:math';
const String _valid = const String _valid =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
final Random _rnd = new Random.secure(); final Random _rnd = Random.secure();
String randomAlphaNumeric(int length) { String randomAlphaNumeric(int length) {
var b = new StringBuffer(); var b = StringBuffer();
for (int i = 0; i < length; i++) { for (int i = 0; i < length; i++) {
b.writeCharCode(_valid.codeUnitAt(_rnd.nextInt(_valid.length))); b.writeCharCode(_valid.codeUnitAt(_rnd.nextInt(_valid.length)));

View file

@ -2,7 +2,7 @@ author: Tobe O <thosakwe@gmail.com>
description: Command-line tools for the Angel framework, including scaffolding. description: Command-line tools for the Angel framework, including scaffolding.
homepage: https://github.com/angel-dart/angel_cli homepage: https://github.com/angel-dart/angel_cli
name: angel_cli name: angel_cli
version: 2.1.7+1 version: 2.2.0
environment: environment:
sdk: ">=2.10.0 <2.12.0" sdk: ">=2.10.0 <2.12.0"
dependencies: dependencies:

View file

@ -3,8 +3,9 @@ import 'dart:io';
import 'package:args/args.dart'; import 'package:args/args.dart';
import 'package:io/ansi.dart'; import 'package:io/ansi.dart';
import 'package:io/io.dart'; import 'package:io/io.dart';
import 'package:dart_language_server/dart_language_server.dart'; //import 'package:dart_language_server/dart_language_server.dart';
import 'package:jael_language_server/jael_language_server.dart'; import 'package:jael_language_server/jael_language_server.dart';
import 'package:jael_language_server/src/protocol/language_server/server.dart';
main(List<String> args) async { main(List<String> args) async {
var argParser = new ArgParser() var argParser = new ArgParser()

View file

@ -1,6 +1,6 @@
import 'dart:async'; import 'dart:async';
import 'package:dart_language_server/src/protocol/language_server/interface.dart'; //import 'package:dart_language_server/src/protocol/language_server/interface.dart';
import 'package:dart_language_server/src/protocol/language_server/messages.dart'; //import 'package:dart_language_server/src/protocol/language_server/messages.dart';
import 'package:file/file.dart'; import 'package:file/file.dart';
import 'package:file/local.dart'; import 'package:file/local.dart';
import 'package:file/memory.dart'; import 'package:file/memory.dart';
@ -13,6 +13,8 @@ import 'package:string_scanner/string_scanner.dart';
import 'package:symbol_table/symbol_table.dart'; import 'package:symbol_table/symbol_table.dart';
import 'analyzer.dart'; import 'analyzer.dart';
import 'object.dart'; import 'object.dart';
import 'protocol/language_server/interface.dart';
import 'protocol/language_server/messages.dart';
class JaelLanguageServer extends LanguageServer { class JaelLanguageServer extends LanguageServer {
var _diagnostics = new StreamController<Diagnostics>(); var _diagnostics = new StreamController<Diagnostics>();

View file

@ -7,7 +7,7 @@ environment:
sdk: '>=2.10.0 <2.12.0' sdk: '>=2.10.0 <2.12.0'
dependencies: dependencies:
args: ^1.0.0 args: ^1.0.0
dart_language_server: ^0.1.3 # dart_language_server: ^0.1.16
file: ^5.0.0 file: ^5.0.0
io: ^0.3.2 io: ^0.3.2
jael: #^2.0.0 jael: #^2.0.0

View file

@ -16,14 +16,14 @@ class MongoService extends Service<String, Map<String, dynamic>> {
@deprecated @deprecated
final bool debug; final bool debug;
MongoService(DbCollection this.collection, MongoService(this.collection,
{this.allowRemoveAll = false, this.allowQuery = true, this.debug = true}) {this.allowRemoveAll = false, this.allowQuery = true, this.debug = true})
: super(); : super();
SelectorBuilder _makeQuery([Map<String, dynamic> params_]) { SelectorBuilder _makeQuery([Map<String, dynamic> params_]) {
Map params = Map.from(params_ ?? {}); var params = Map.from(params_ ?? {});
params = params..remove('provider'); params = params..remove('provider');
SelectorBuilder result = where.exists('_id'); var result = where.exists('_id');
// You can pass a SelectorBuilder as 'query'; // You can pass a SelectorBuilder as 'query';
if (params['query'] is SelectorBuilder) { if (params['query'] is SelectorBuilder) {
@ -36,12 +36,13 @@ class MongoService extends Service<String, Map<String, dynamic>> {
(allowQuery == true || !params.containsKey('provider'))) { (allowQuery == true || !params.containsKey('provider'))) {
if (params[key] is Map) { if (params[key] is Map) {
// If they send a map, then we'll sort by every key in the map // If they send a map, then we'll sort by every key in the map
for (String fieldName in params[key].keys.where((x) => x is String)) {
for (var fieldName in params[key].keys.where((x) => x is String)) {
var sorter = params[key][fieldName]; var sorter = params[key][fieldName];
if (sorter is num) { if (sorter is num && fieldName is String) {
result = result.sortBy(fieldName, descending: sorter == -1); result = result.sortBy(fieldName, descending: sorter == -1);
} else if (sorter is String) { } else if (sorter is String && fieldName is String) {
result = result.sortBy(fieldName, descending: sorter == "-1"); result = result.sortBy(fieldName, descending: sorter == '-1');
} else if (sorter is SelectorBuilder) { } else if (sorter is SelectorBuilder) {
result = result.and(sorter); result = result.and(sorter);
} }

View file

@ -27,7 +27,7 @@ HookedServiceEventListener belongsTo(Pattern servicePath,
} }
return (HookedServiceEvent e) async { return (HookedServiceEvent e) async {
var ref = e.service.app.service(servicePath); var ref = e.getService(servicePath);
if (ref == null) throw noService(servicePath); if (ref == null) throw noService(servicePath);
_getForeignKey(obj) { _getForeignKey(obj) {
@ -35,8 +35,9 @@ HookedServiceEventListener belongsTo(Pattern servicePath,
return getForeignKey(obj); return getForeignKey(obj);
else if (obj is Map) else if (obj is Map)
return obj[localId]; return obj[localId];
else if (obj is Extensible) //TODO: Undefined class
return obj.properties[localId]; //else if (obj is Extensible)
// return obj.properties[localId];
else if (localId == null || localId == 'userId') else if (localId == null || localId == 'userId')
return obj.userId; return obj.userId;
else else
@ -48,8 +49,9 @@ HookedServiceEventListener belongsTo(Pattern servicePath,
return assignForeignObject(foreign, obj); return assignForeignObject(foreign, obj);
else if (obj is Map) else if (obj is Map)
obj[foreignName] = foreign; obj[foreignName] = foreign;
else if (obj is Extensible) //TODO: Undefined class
obj.properties[foreignName] = foreign; //else if (obj is Extensible)
// obj.properties[foreignName] = foreign;
else else
reflect(obj).setField(new Symbol(foreignName), foreign); reflect(obj).setField(new Symbol(foreignName), foreign);
} }

View file

@ -27,7 +27,7 @@ HookedServiceEventListener belongsToMany(Pattern servicePath,
} }
return (HookedServiceEvent e) async { return (HookedServiceEvent e) async {
var ref = e.service.app.service(servicePath); var ref = e.getService(servicePath);
if (ref == null) throw noService(servicePath); if (ref == null) throw noService(servicePath);
_getForeignKey(obj) { _getForeignKey(obj) {
@ -35,8 +35,9 @@ HookedServiceEventListener belongsToMany(Pattern servicePath,
return getForeignKey(obj); return getForeignKey(obj);
else if (obj is Map) else if (obj is Map)
return obj[localId]; return obj[localId];
else if (obj is Extensible) //TODO: Undefined class
return obj.properties[localId]; //else if (obj is Extensible)
// return obj.properties[localId];
else if (localId == null || localId == 'userId') else if (localId == null || localId == 'userId')
return obj.userId; return obj.userId;
else else
@ -48,8 +49,9 @@ HookedServiceEventListener belongsToMany(Pattern servicePath,
return assignForeignObject(foreign, obj); return assignForeignObject(foreign, obj);
else if (obj is Map) else if (obj is Map)
obj[foreignName] = foreign; obj[foreignName] = foreign;
else if (obj is Extensible) //TODO: Undefined class
obj.properties[foreignName] = foreign; //else if (obj is Extensible)
// obj.properties[foreignName] = foreign;
else else
reflect(obj).setField(new Symbol(foreignName), foreign); reflect(obj).setField(new Symbol(foreignName), foreign);
} }

View file

@ -17,9 +17,8 @@ HookedServiceEventListener hasMany(Pattern servicePath,
String localKey, String localKey,
getLocalKey(obj), getLocalKey(obj),
assignForeignObjects(foreign, obj)}) { assignForeignObjects(foreign, obj)}) {
return (HookedServiceEvent e) async { return (HookedServiceEvent e) async {
var ref = e.service.app.service(servicePath); var ref = e.getService(servicePath);
var foreignName = var foreignName =
as?.isNotEmpty == true ? as : pluralize.plural(servicePath.toString()); as?.isNotEmpty == true ? as : pluralize.plural(servicePath.toString());
if (ref == null) throw noService(servicePath); if (ref == null) throw noService(servicePath);
@ -29,8 +28,9 @@ HookedServiceEventListener hasMany(Pattern servicePath,
return getLocalKey(obj); return getLocalKey(obj);
else if (obj is Map) else if (obj is Map)
return obj[localKey ?? 'id']; return obj[localKey ?? 'id'];
else if (obj is Extensible) //TODO: Undefined class
return obj.properties[localKey ?? 'id']; //else if (obj is Extensible)
// return obj.properties[localKey ?? 'id'];
else if (localKey == null || localKey == 'id') else if (localKey == null || localKey == 'id')
return obj.id; return obj.id;
else else
@ -42,8 +42,9 @@ HookedServiceEventListener hasMany(Pattern servicePath,
return assignForeignObjects(foreign, obj); return assignForeignObjects(foreign, obj);
else if (obj is Map) else if (obj is Map)
obj[foreignName] = foreign; obj[foreignName] = foreign;
else if (obj is Extensible) //TODO: Undefined class
obj.properties[foreignName] = foreign; //else if (obj is Extensible)
// obj.properties[foreignName] = foreign;
else else
reflect(obj).setField(new Symbol(foreignName), foreign); reflect(obj).setField(new Symbol(foreignName), foreign);
} }

View file

@ -29,8 +29,9 @@ HookedServiceEventListener hasManyThrough(String servicePath, String pivotPath,
return assignForeignObjects(foreign, obj); return assignForeignObjects(foreign, obj);
else if (obj is Map) else if (obj is Map)
obj[foreignName] = foreign; obj[foreignName] = foreign;
else if (obj is Extensible) //TODO: Undefined class
obj.properties[foreignName] = foreign; //else if (obj is Extensible)
// obj.properties[foreignName] = foreign;
else else
reflect(obj).setField(new Symbol(foreignName), foreign); reflect(obj).setField(new Symbol(foreignName), foreign);
} }
@ -40,8 +41,9 @@ HookedServiceEventListener hasManyThrough(String servicePath, String pivotPath,
return getLocalKey(obj); return getLocalKey(obj);
else if (obj is Map) else if (obj is Map)
return obj[localKey ?? 'id']; return obj[localKey ?? 'id'];
else if (obj is Extensible) //TODO: Undefined class
return obj.properties[localKey ?? 'id']; //else if (obj is Extensible)
// return obj.properties[localKey ?? 'id'];
else if (localKey == null || localKey == 'id') else if (localKey == null || localKey == 'id')
return obj.id; return obj.id;
else else
@ -53,8 +55,9 @@ HookedServiceEventListener hasManyThrough(String servicePath, String pivotPath,
return getPivotKey(obj); return getPivotKey(obj);
else if (obj is Map) else if (obj is Map)
return obj[pivotKey ?? 'id']; return obj[pivotKey ?? 'id'];
else if (obj is Extensible) //TODO: Undefined class
return obj.properties[pivotKey ?? 'id']; //else if (obj is Extensible)
// return obj.properties[pivotKey ?? 'id'];
else if (pivotKey == null || pivotKey == 'id') else if (pivotKey == null || pivotKey == 'id')
return obj.id; return obj.id;
else else

View file

@ -17,9 +17,8 @@ HookedServiceEventListener hasOne(Pattern servicePath,
String localKey, String localKey,
getLocalKey(obj), getLocalKey(obj),
assignForeignObject(foreign, obj)}) { assignForeignObject(foreign, obj)}) {
return (HookedServiceEvent e) async { return (HookedServiceEvent e) async {
var ref = e.service.app.service(servicePath); var ref = e.getService(servicePath);
var foreignName = as?.isNotEmpty == true var foreignName = as?.isNotEmpty == true
? as ? as
: pluralize.singular(servicePath.toString()); : pluralize.singular(servicePath.toString());
@ -30,8 +29,10 @@ HookedServiceEventListener hasOne(Pattern servicePath,
return getLocalKey(obj); return getLocalKey(obj);
else if (obj is Map) else if (obj is Map)
return obj[localKey ?? 'id']; return obj[localKey ?? 'id'];
else if (obj is Extensible)
return obj.properties[localKey ?? 'id']; //TODO: Undefined class
//else if (obj is Extensible)
// return obj.properties[localKey ?? 'id'];
else if (localKey == null || localKey == 'id') else if (localKey == null || localKey == 'id')
return obj.id; return obj.id;
else else
@ -43,8 +44,9 @@ HookedServiceEventListener hasOne(Pattern servicePath,
return assignForeignObject(foreign, obj); return assignForeignObject(foreign, obj);
else if (obj is Map) else if (obj is Map)
obj[foreignName] = foreign; obj[foreignName] = foreign;
else if (obj is Extensible) //TODO: Undefined class
obj.properties[foreignName] = foreign; //else if (obj is Extensible)
// obj.properties[foreignName] = foreign;
else else
reflect(obj).setField(new Symbol(foreignName), foreign); reflect(obj).setField(new Symbol(foreignName), foreign);
} }

View file

@ -9,5 +9,6 @@ dependencies:
angel_framework: #^1.0.0-dev angel_framework: #^1.0.0-dev
path: ../framework path: ../framework
dev_dependencies: dev_dependencies:
#angel_seeder: ^1.0.0 angel_seeder: #^1.0.0
path: ../seeder
test: ^1.15.7 test: ^1.15.7

View file

@ -27,11 +27,12 @@ main() {
})); }));
}))); })));
app.service('books').afterAll(relations.belongsTo('authors')); // TODO: Missing method afterAll
//app.findService ('books').afterAll(relations.belongsTo('authors'));
}); });
test('index', () async { test('index', () async {
var books = await app.service('books').index(); var books = await app.findService('books').index();
print(books); print(books);
expect(books, allOf(isList, isNotEmpty)); expect(books, allOf(isList, isNotEmpty));
@ -46,8 +47,8 @@ main() {
test('create', () async { test('create', () async {
var warAndPeace = await app var warAndPeace = await app
.service('books') .findService('books')
.create(new Book(title: 'War and Peace').toJson()); .create(Book(title: 'War and Peace').toJson());
print(warAndPeace); print(warAndPeace);
expect(warAndPeace.keys, contains('author')); expect(warAndPeace.keys, contains('author'));

View file

@ -1,5 +1,6 @@
import 'dart:convert';
import 'package:angel_framework/angel_framework.dart'; import 'package:angel_framework/angel_framework.dart';
import 'package:json_god/json_god.dart' as god; //import 'package:json_god/json_god.dart' as god;
@deprecated @deprecated
class CustomMapService extends Service { class CustomMapService extends Service {
@ -32,7 +33,7 @@ class CustomMapService extends Service {
@override @override
create(data, [params]) async { create(data, [params]) async {
Map d = data is Map ? data : god.serializeObject(data); Map d = data is Map ? data : jsonDecode(data);
d['id'] = _items.length.toString(); d['id'] = _items.length.toString();
_items.add(d); _items.add(d);
return d; return d;

View file

@ -1,5 +1,5 @@
import 'package:angel_framework/angel_framework.dart'; import 'package:angel_framework/angel_framework.dart';
import 'package:angel_relations/angel_relations.dart' as relations; //import 'package:angel_relations/angel_relations.dart' as relations;
import 'package:angel_seeder/angel_seeder.dart'; import 'package:angel_seeder/angel_seeder.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'common.dart'; import 'common.dart';
@ -27,13 +27,14 @@ main() {
})); }));
}))); })));
app // TODO: Missing afterAll method
.service('authors') // app
.afterAll(relations.hasMany('books', foreignKey: 'authorId')); // .findService('authors')
// .afterAll(relations.hasMany('books', foreignKey: 'authorId'));
}); });
test('index', () async { test('index', () async {
var authors = await app.service('authors').index(); var authors = await app.findService('authors').index();
print(authors); print(authors);
expect(authors, allOf(isList, isNotEmpty)); expect(authors, allOf(isList, isNotEmpty));
@ -51,7 +52,7 @@ main() {
test('create', () async { test('create', () async {
var tolstoy = await app var tolstoy = await app
.service('authors') .findService('authors')
.create(new Author(name: 'Leo Tolstoy').toJson()); .create(new Author(name: 'Leo Tolstoy').toJson());
print(tolstoy); print(tolstoy);

View file

@ -27,12 +27,13 @@ main() {
})); }));
}))); })));
app.service('authors').afterAll( // TODO: Missing afterAll method
relations.hasOne('books', as: 'book', foreignKey: 'authorId')); // app.findService('authors').afterAll(
// relations.hasOne('books', as: 'book', foreignKey: 'authorId'));
}); });
test('index', () async { test('index', () async {
var authors = await app.service('authors').index(); var authors = await app.findService('authors').index();
print(authors); print(authors);
expect(authors, allOf(isList, isNotEmpty)); expect(authors, allOf(isList, isNotEmpty));
@ -49,7 +50,7 @@ main() {
test('create', () async { test('create', () async {
var tolstoy = await app var tolstoy = await app
.service('authors') .findService('authors')
.create(new Author(name: 'Leo Tolstoy').toJson()); .create(new Author(name: 'Leo Tolstoy').toJson());
print(tolstoy); print(tolstoy);

View file

@ -1,5 +1,4 @@
import 'dart:async'; import 'dart:async';
import 'dart:typed_data';
import 'package:angel_framework/angel_framework.dart'; import 'package:angel_framework/angel_framework.dart';
import 'package:file/file.dart'; import 'package:file/file.dart';
import 'package:http_parser/http_parser.dart'; import 'package:http_parser/http_parser.dart';
@ -12,14 +11,16 @@ final RegExp _straySlashes = RegExp(r'(^/+)|(/+$)');
String _pathify(String path) { String _pathify(String path) {
var p = path.replaceAll(_straySlashes, ''); var p = path.replaceAll(_straySlashes, '');
Map<String, String> replace = {}; var replace = {};
for (Match match in _param.allMatches(p)) { for (Match match in _param.allMatches(p)) {
if (match[3] != null) replace[match[0]] = ':${match[1]}'; if (match[3] != null) replace[match[0]] = ':${match[1]}';
} }
replace.forEach((k, v) { replace.forEach((k, v) {
p = p.replaceAll(k, v); if (k is String && v is String) {
p = p.replaceAll(k, v);
}
}); });
return p; return p;
@ -64,7 +65,7 @@ class VirtualDirectory {
if (source != null) { if (source != null) {
_source = source; _source = source;
} else { } else {
String dirPath = app.environment.isProduction ? './build/web' : './web'; var dirPath = app.environment.isProduction ? './build/web' : './web';
_source = fileSystem.directory(dirPath); _source = fileSystem.directory(dirPath);
} }
} }
@ -148,7 +149,7 @@ class VirtualDirectory {
/// Serves the index file of a [directory], if it exists. /// Serves the index file of a [directory], if it exists.
Future<bool> serveDirectory(Directory directory, String relative, Future<bool> serveDirectory(Directory directory, String relative,
FileStat stat, RequestContext req, ResponseContext res) async { FileStat stat, RequestContext req, ResponseContext res) async {
for (String indexFileName in indexFileNames) { for (var indexFileName in indexFileNames) {
final index = final index =
fileSystem.file(directory.absolute.uri.resolve(indexFileName)); fileSystem.file(directory.absolute.uri.resolve(indexFileName));
if (await index.exists()) { if (await index.exists()) {
@ -168,34 +169,53 @@ class VirtualDirectory {
res.write('<li><a href="..">..</a></li>'); res.write('<li><a href="..">..</a></li>');
List<FileSystemEntity> entities = await directory var entities = await directory
.list(followLinks: false) .list(followLinks: false)
.toList() .toList()
.then((l) => List.from(l)); .then((l) => List.from(l));
entities.sort((a, b) { entities.sort((a, b) {
if (a is Directory) { if (a is Directory) {
if (b is Directory) return a.path.compareTo(b.path); if (b is Directory) {
return a.path.compareTo(b.path);
}
return -1; return -1;
} else if (a is File) { } else if (a is File) {
if (b is Directory) { if (b is Directory) {
return 1; return 1;
} else if (b is File) return a.path.compareTo(b.path); } else if (b is File) {
return a.path.compareTo(b.path);
}
return -1; return -1;
} else if (b is Link) return a.path.compareTo(b.path); } else if (a is Link) {
if (b is Directory) {
return 1;
} else if (b is Link) {
return a.path.compareTo(b.path);
}
return -1;
}
return 1; return 1;
}); });
for (var entity in entities) { for (var entity in entities) {
var stub = p.basename(entity.path); String stub;
var href = stub;
String type; String type;
if (entity is File) { if (entity is File) {
type = '[File]'; type = '[File]';
stub = p.basename(entity.path);
} else if (entity is Directory) { } else if (entity is Directory) {
type = '[Directory]'; type = '[Directory]';
} else if (entity is Link) type = '[Link]'; stub = p.basename(entity.path);
} else if (entity is Link) {
type = '[Link]';
stub = p.basename(entity.path);
} else {
//TODO: Handle unknown type
}
var href = stub;
if (relative.isNotEmpty) href = '/' + relative + '/' + stub; if (relative.isNotEmpty) href = '/' + relative + '/' + stub;
@ -214,7 +234,7 @@ class VirtualDirectory {
void _ensureContentTypeAllowed(String mimeType, RequestContext req) { void _ensureContentTypeAllowed(String mimeType, RequestContext req) {
var value = req.headers.value('accept'); var value = req.headers.value('accept');
bool acceptable = value == null || var acceptable = value == null ||
value?.isNotEmpty != true || value?.isNotEmpty != true ||
(mimeType?.isNotEmpty == true && value?.contains(mimeType) == true) || (mimeType?.isNotEmpty == true && value?.contains(mimeType) == true) ||
value?.contains('*/*') == true; value?.contains('*/*') == true;
@ -256,7 +276,7 @@ class VirtualDirectory {
header = RangeHeader(items); header = RangeHeader(items);
for (var item in header.items) { for (var item in header.items) {
bool invalid = false; var invalid = false;
if (item.start != -1) { if (item.start != -1) {
invalid = item.end != -1 && item.end < item.start; invalid = item.end != -1 && item.end < item.start;
@ -266,17 +286,17 @@ class VirtualDirectory {
if (invalid) { if (invalid) {
throw AngelHttpException( throw AngelHttpException(
Exception("Semantically invalid, or unbounded range."), Exception('Semantically invalid, or unbounded range.'),
statusCode: 416, statusCode: 416,
message: "Semantically invalid, or unbounded range."); message: 'Semantically invalid, or unbounded range.');
} }
// Ensure it's within range. // Ensure it's within range.
if (item.start >= totalFileSize || item.end >= totalFileSize) { if (item.start >= totalFileSize || item.end >= totalFileSize) {
throw AngelHttpException( throw AngelHttpException(
Exception("Given range $item is out of bounds."), Exception('Given range $item is out of bounds.'),
statusCode: 416, statusCode: 416,
message: "Given range $item is out of bounds."); message: 'Given range $item is out of bounds.');
} }
} }
@ -285,8 +305,10 @@ class VirtualDirectory {
statusCode: 416, message: '`Range` header may not be empty.'); statusCode: 416, message: '`Range` header may not be empty.');
} else if (header.items.length == 1) { } else if (header.items.length == 1) {
var item = header.items[0]; var item = header.items[0];
Stream<Uint8List> stream; Stream<List<int>> stream;
int len = 0, total = totalFileSize; var len = 0;
var total = totalFileSize;
if (item.start == -1) { if (item.start == -1) {
if (item.end == -1) { if (item.end == -1) {

View file

@ -3,8 +3,9 @@ import 'dart:io';
import 'package:args/args.dart'; import 'package:args/args.dart';
import 'package:io/ansi.dart'; import 'package:io/ansi.dart';
import 'package:io/io.dart'; import 'package:io/io.dart';
import 'package:dart_language_server/dart_language_server.dart'; //import 'package:dart_language_server/dart_language_server.dart';
import 'package:jael_language_server/jael_language_server.dart'; import 'package:vs_jael_language_server/jael_language_server.dart';
import 'package:vs_jael_language_server/src/protocol/language_server/server.dart';
main(List<String> args) async { main(List<String> args) async {
var argParser = new ArgParser() var argParser = new ArgParser()
@ -56,7 +57,7 @@ main(List<String> args) async {
); );
var zone = Zone.current.fork(specification: spec); var zone = Zone.current.fork(specification: spec);
await zone.run(() async { await zone.run(() async {
var stdio = new StdIOLanguageServer.start(jaelServer); var stdio = StdIOLanguageServer.start(jaelServer);
await stdio.onDone; await stdio.onDone;
}); });
} }

View file

@ -1,6 +1,6 @@
import 'dart:async'; import 'dart:async';
import 'package:dart_language_server/src/protocol/language_server/interface.dart'; //import 'package:dart_language_server/src/protocol/language_server/interface.dart';
import 'package:dart_language_server/src/protocol/language_server/messages.dart'; //import 'package:dart_language_server/src/protocol/language_server/messages.dart';
import 'package:file/file.dart'; import 'package:file/file.dart';
import 'package:file/local.dart'; import 'package:file/local.dart';
import 'package:file/memory.dart'; import 'package:file/memory.dart';
@ -11,9 +11,13 @@ import 'package:path/path.dart' as p;
import 'package:source_span/source_span.dart'; import 'package:source_span/source_span.dart';
import 'package:string_scanner/string_scanner.dart'; import 'package:string_scanner/string_scanner.dart';
import 'package:symbol_table/symbol_table.dart'; import 'package:symbol_table/symbol_table.dart';
import 'analyzer.dart';
import 'formatter.dart'; import 'protocol/language_server/interface.dart';
import 'object.dart'; import 'protocol/language_server/messages.dart';
import './analyzer.dart';
import './formatter.dart' as fmt;
import './object.dart';
class JaelLanguageServer extends LanguageServer { class JaelLanguageServer extends LanguageServer {
var _diagnostics = new StreamController<Diagnostics>(); var _diagnostics = new StreamController<Diagnostics>();
@ -502,7 +506,7 @@ class JaelLanguageServer extends LanguageServer {
var document = var document =
parseDocument(contents, sourceUrl: file.uri, onError: errors.add); parseDocument(contents, sourceUrl: file.uri, onError: errors.add);
if (errors.isNotEmpty) return null; if (errors.isNotEmpty) return null;
var formatter = new JaelFormatter( var formatter = fmt.JaelFormatter(
formattingOptions.tabSize, formattingOptions.insertSpaces); formattingOptions.tabSize, formattingOptions.insertSpaces);
var formatted = formatter.apply(document); var formatted = formatter.apply(document);
logger.info('Original:${contents}\nFormatted:\n$formatted'); logger.info('Original:${contents}\nFormatted:\n$formatted');

View file

@ -1,4 +1,4 @@
name: jael_language_server name: vs_jael_language_server
version: 0.0.0 version: 0.0.0
description: Language Server Protocol implementation for the Jael templating engine. description: Language Server Protocol implementation for the Jael templating engine.
author: Tobe Osakwe <thosakwe@gmail.com> author: Tobe Osakwe <thosakwe@gmail.com>
@ -7,11 +7,13 @@ environment:
sdk: ">=2.10.0 <2.12.0" sdk: ">=2.10.0 <2.12.0"
dependencies: dependencies:
args: ^1.0.0 args: ^1.0.0
dart_language_server: ^0.1.16 # dart_language_server: ^0.1.16
file: ^5.0.0 file: ^5.0.0
io: ^0.3.2 io: ^0.3.2
jael: ^2.0.0 jael: #^2.0.0
jael_preprocessor: ^2.0.0 path: ../../jael/jael
jael_preprocessor: #^2.0.0
path: ../../jael/jael_preprocessor
json_rpc_2: ^2.0.0 json_rpc_2: ^2.0.0
logging: ^0.11.3 logging: ^0.11.3
path: ^1.0.0 path: ^1.0.0