Skip to content

WIP linter for Effective Dart #31

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 24 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
546f878
setup pedantic lint rules for Effective Dart
RandomDalek Oct 9, 2019
cd185dc
fix avoid_init_to_null warning
RandomDalek Oct 9, 2019
1acdc3e
fix unnecessary_const and avoid_shadowing_type_parameters warnings
RandomDalek Oct 9, 2019
b2e2e4e
Merge pull request #1 from objectbox/dev
GregorySech Oct 9, 2019
2f55dd1
fix avoid_types_as_parameter_names warning
RandomDalek Oct 9, 2019
6e26d5a
Merge branch 'dev' of github.com:GregorySech/objectbox-dart into dev
RandomDalek Oct 9, 2019
e175a59
fix expected output after avoid_init_to_null change.
GregorySech Oct 9, 2019
d58fc2c
fix unused_import warning
GregorySech Oct 9, 2019
bfdec2b
fix curly_braces_in_flow_control_structures warning
GregorySech Oct 9, 2019
082acdd
fix unnecessary_new warning
GregorySech Oct 9, 2019
c06b4c1
fix prefer_contains warning
GregorySech Oct 9, 2019
3638dc1
fix prefer_is_empty warning
GregorySech Oct 9, 2019
17dfbfe
Merge branch 'dev' into dev
GregorySech Oct 9, 2019
187b1f2
setup dart_package_analyzer
GregorySech Oct 9, 2019
ae0a55b
Merge branch 'dev' of github.com:GregorySech/objectbox-dart into dev
GregorySech Oct 9, 2019
c5cea8c
move analysis actions to its own file.
GregorySech Oct 10, 2019
3fb312f
renaming analysis jobs
GregorySech Oct 10, 2019
a62df9f
fix unawaited_futures warning
GregorySech Oct 10, 2019
0961a73
fix renaming analysis jobs.
GregorySech Oct 10, 2019
1cc12f5
Update .github/workflows/analysis.yml
GregorySech Oct 12, 2019
e08a873
remove useless part according to action docs and merge jobs in one.
GregorySech Oct 12, 2019
583700c
calling pub get before analysis
GregorySech Oct 12, 2019
20b8efb
formatting
GregorySech Oct 12, 2019
df1a982
dart container is needed for pub get
GregorySech Oct 12, 2019
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions .github/workflows/analysis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
name: Analysis

on: [push, pull_request]

jobs:
packages_analysis:
runs-on: ubuntu-latest
container:
image: google/dart:latest
Comment on lines +8 to +9
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

steps:
- uses: actions/checkout@v1
- name: Install lib dependencies
run: pub get
- name: Install generator dependencies
working-directory: bin/objectbox_model_generator
run: pub get
- uses: axel-op/dart_package_analyzer@stable
with:
githubToken: ${{ secrets.GITHUB_TOKEN }}
maxScoreToComment: 99.99 # only a 100 score will not post a comment.
- uses: axel-op/dart_package_analyzer@stable
with:
githubToken: ${{ secrets.GITHUB_TOKEN }}
maxScoreToComment: 99.99 # only a 100 score will not post a comment.
relativePath: 'bin/objectbox_model_generator/'
2 changes: 1 addition & 1 deletion .github/workflows/dart.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,4 @@ jobs:
- name: Generate ObjectBox models
run: pub run build_runner build
- name: Run tests
run: pub run test
run: pub run test
1 change: 1 addition & 0 deletions analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
include: package:pedantic/analysis_options.yaml
2 changes: 1 addition & 1 deletion bin/objectbox_model_generator/lib/src/code_chunks.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import "package:objectbox/src/modelinfo/index.dart";

class CodeChunks {
static String modelInfoLoader(String allModelsJsonFilename) => """
Map<int, ModelEntity> _allOBXModelEntities = null;
Map<int, ModelEntity> _allOBXModelEntities;

void _loadOBXModelEntities() {
if (FileSystemEntity.typeSync("objectbox-model.json") == FileSystemEntityType.notFound)
Expand Down
38 changes: 22 additions & 16 deletions bin/objectbox_model_generator/lib/src/generator.dart
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,19 @@ class EntityGenerator extends GeneratorForAnnotation<obx.Entity> {
List<String> entityHeaderDone = [];

Future<ModelInfo> _loadModelInfo() async {
if ((await FileSystemEntity.type(ALL_MODELS_JSON)) == FileSystemEntityType.notFound)
if ((await FileSystemEntity.type(ALL_MODELS_JSON)) == FileSystemEntityType.notFound) {
return ModelInfo.createDefault();
return ModelInfo.fromMap(json.decode(await (new File(ALL_MODELS_JSON).readAsString())));
}
return ModelInfo.fromMap(json.decode(await (File(ALL_MODELS_JSON).readAsString())));
}

@override
Future<String> generateForAnnotatedElement(
Element elementBare, ConstantReader annotation, BuildStep buildStep) async {
try {
if (elementBare is! ClassElement)
if (elementBare is! ClassElement) {
throw InvalidGenerationSourceError("in target ${elementBare.name}: annotated element isn't a class");
}
var element = elementBare as ClassElement;

// load existing model from JSON file if possible
Expand All @@ -38,13 +40,13 @@ class EntityGenerator extends GeneratorForAnnotation<obx.Entity> {

// optionally add header for loading the .g.json file
var ret = "";
if (entityHeaderDone.indexOf(inputFileId) == -1) {
if (!entityHeaderDone.contains(inputFileId)) {
ret += CodeChunks.modelInfoLoader(ALL_MODELS_JSON);
entityHeaderDone.add(inputFileId);
}

// process basic entity (note that allModels.createEntity is not used, as the entity will be merged)
ModelEntity readEntity = new ModelEntity(IdUid.empty(), null, element.name, [], allModels);
ModelEntity readEntity = ModelEntity(IdUid.empty(), null, element.name, [], allModels);
var entityUid = annotation.read("uid");
if (entityUid != null && !entityUid.isNull) readEntity.id.uid = entityUid.intValue;

Expand All @@ -58,21 +60,24 @@ class EntityGenerator extends GeneratorForAnnotation<obx.Entity> {
var annotElmt = f.metadata[0].element as ConstructorElement;
var annotType = annotElmt.returnType.toString();
var annotVal = f.metadata[0].computeConstantValue();
var fieldTypeAnnot = null; // for the future, with custom type sizes allowed: annotVal.getField("type");
fieldType = fieldTypeAnnot == null ? null : fieldTypeAnnot.toIntValue();
var fieldTypeAnnot; // for the future, with custom type sizes allowed: annotVal.getField("type");
fieldType = fieldTypeAnnot?.toIntValue();
propUid = annotVal.getField("uid").toIntValue();

// find property flags
if (annotType == "Id") {
if (hasIdProperty)
if (hasIdProperty) {
throw InvalidGenerationSourceError(
"in target ${elementBare.name}: has more than one properties annotated with @Id");
if (fieldType != null)
}
if (fieldType != null) {
throw InvalidGenerationSourceError(
"in target ${elementBare.name}: programming error: @Id property may not specify a type");
if (f.type.toString() != "int")
}
if (f.type.toString() != "int") {
throw InvalidGenerationSourceError(
"in target ${elementBare.name}: field with @Id property has type '${f.type.toString()}', but it must be 'int'");
}

fieldType = OBXPropertyType.Long;
flags |= OBXPropertyFlag.ID;
Expand All @@ -89,30 +94,31 @@ class EntityGenerator extends GeneratorForAnnotation<obx.Entity> {

if (fieldType == null) {
var fieldTypeStr = f.type.toString();
if (fieldTypeStr == "int")
if (fieldTypeStr == "int") {
fieldType = OBXPropertyType.Int;
else if (fieldTypeStr == "String")
} else if (fieldTypeStr == "String") {
fieldType = OBXPropertyType.String;
else {
} else {
print(
"warning: skipping field '${f.name}' in entity '${element.name}', as it has the unsupported type '$fieldTypeStr'");
continue;
}
}

// create property (do not use readEntity.createProperty in order to avoid generating new ids)
ModelProperty prop = new ModelProperty(IdUid.empty(), f.name, fieldType, flags, readEntity);
ModelProperty prop = ModelProperty(IdUid.empty(), f.name, fieldType, flags, readEntity);
if (propUid != null) prop.id.uid = propUid;
readEntity.properties.add(prop);
}

// some checks on the entity's integrity
if (!hasIdProperty)
if (!hasIdProperty) {
throw InvalidGenerationSourceError("in target ${elementBare.name}: has no properties annotated with @Id");
}

// merge existing model and annotated model that was just read, then write new final model to file
mergeEntity(allModels, readEntity);
new File(ALL_MODELS_JSON).writeAsString(new JsonEncoder.withIndent(" ").convert(allModels.toMap()));
await File(ALL_MODELS_JSON).writeAsString(JsonEncoder.withIndent(" ").convert(allModels.toMap()));
readEntity = allModels.findEntityByName(element.name);
if (readEntity == null) return ret;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// EntityGenerator
// **************************************************************************

Map<int, ModelEntity> _allOBXModelEntities = null;
Map<int, ModelEntity> _allOBXModelEntities;

void _loadOBXModelEntities() {
if (FileSystemEntity.typeSync("objectbox-model.json") ==
Expand Down
2 changes: 1 addition & 1 deletion bin/objectbox_model_generator/test/generator_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import "helpers.dart";
void main() async {
group("generator", () {
tearDown(() {
new File("objectbox-model.json").deleteSync();
File("objectbox-model.json").deleteSync();
});

testGeneratorOutput("single_entity");
Expand Down
14 changes: 8 additions & 6 deletions bin/objectbox_model_generator/test/helpers.dart
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,9 @@ class _SingleFileAssetReader extends AssetReader {
AssetId id;

_SingleFileAssetReader(this.id) {
if (id.package != "objectbox_model_generator")
if (id.package != "objectbox_model_generator") {
throw Exception("asset package needs to be 'objectbox_model_generator', but got '${id.package}'");
}
}

Future<bool> canRead(AssetId id) async => true; //this.id == id;
Expand All @@ -46,10 +47,11 @@ class _SingleFileAssetReader extends AssetReader {

String path = id.path;
if (id.package == "objectbox") path = "../../" + path;
if (id.package == "objectbox_model_generator" && id.path.startsWith("test/cases") && id.path.endsWith(".dart"))
if (id.package == "objectbox_model_generator" && id.path.startsWith("test/cases") && id.path.endsWith(".dart")) {
path += "_testcase";
}
if (FileSystemEntity.typeSync(path) == FileSystemEntityType.notFound) throw AssetNotFoundException(id);
return await (new File(path).readAsString());
return await (File(path).readAsString());
}
}

Expand All @@ -66,11 +68,11 @@ Future<String> _buildGeneratorOutput(String caseName) async {
void testGeneratorOutput(String caseName) {
test(caseName, () async {
String built = await _buildGeneratorOutput(caseName);
String expected = await new File("test/cases/$caseName/$caseName.g.dart_expected").readAsString();
String expected = await File("test/cases/$caseName/$caseName.g.dart_expected").readAsString();
expect(built, equals(expected));

String jsonBuilt = await new File("objectbox-model.json").readAsString();
String jsonExpected = await new File("test/cases/$caseName/objectbox-model.json_expected").readAsString();
String jsonBuilt = await File("objectbox-model.json").readAsString();
String jsonExpected = await File("test/cases/$caseName/objectbox-model.json_expected").readAsString();
expect(jsonBuilt, equals(jsonExpected));
});
}
1 change: 0 additions & 1 deletion examples/flutter/objectbox_demo_desktop/lib/main.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import 'package:flutter/foundation.dart' show debugDefaultTargetPlatformOverride;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import "package:objectbox/objectbox.dart";
part "main.g.dart";

Expand Down
6 changes: 3 additions & 3 deletions lib/src/annotations.dart
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
class Entity {
final int uid;
const Entity({this.uid = null});
const Entity({this.uid});
}

class Property {
final int uid;
const Property({this.uid = null});
const Property({this.uid});
}

class Id {
final int uid;
const Id({this.uid = null});
const Id({this.uid});
}
9 changes: 5 additions & 4 deletions lib/src/bindings/bindings.dart
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,15 @@ class _ObjectBoxBindings {

_ObjectBoxBindings() {
var libName = "objectbox";
if (Platform.isWindows)
if (Platform.isWindows) {
libName += ".dll";
else if (Platform.isMacOS)
} else if (Platform.isMacOS) {
libName = "lib" + libName + ".dylib";
else if (Platform.isLinux || Platform.isAndroid)
} else if (Platform.isLinux || Platform.isAndroid) {
libName = "lib" + libName + ".so";
else
} else {
throw Exception("unsupported platform detected");
}
objectbox = DynamicLibrary.open(libName);

// common functions
Expand Down
10 changes: 5 additions & 5 deletions lib/src/bindings/flatbuffers.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import "../modelinfo/index.dart";

class _OBXFBEntity {
_OBXFBEntity._(this._bc, this._bcOffset);
static const fb.Reader<_OBXFBEntity> reader = const _OBXFBEntityReader();
static const fb.Reader<_OBXFBEntity> reader = _OBXFBEntityReader();
factory _OBXFBEntity(Uint8List bytes) {
fb.BufferContext rootRef = new fb.BufferContext.fromBytes(bytes);
fb.BufferContext rootRef = fb.BufferContext.fromBytes(bytes);
return reader.read(rootRef, 0);
}

Expand All @@ -24,7 +24,7 @@ class _OBXFBEntityReader extends fb.TableReader<_OBXFBEntity> {
const _OBXFBEntityReader();

@override
_OBXFBEntity createObject(fb.BufferContext bc, int offset) => new _OBXFBEntity._(bc, offset);
_OBXFBEntity createObject(fb.BufferContext bc, int offset) => _OBXFBEntity._(bc, offset);
}

class OBXFlatbuffersManager<T> {
Expand All @@ -34,7 +34,7 @@ class OBXFlatbuffersManager<T> {
OBXFlatbuffersManager(this._modelEntity, this._entityBuilder);

ByteBuffer marshal(propVals) {
var builder = new fb.Builder(initialSize: 1024);
var builder = fb.Builder(initialSize: 1024);

// write all strings
Map<String, int> offsets = {};
Expand Down Expand Up @@ -85,7 +85,7 @@ class OBXFlatbuffersManager<T> {
T unmarshal(ByteBuffer buffer) {
if (buffer.size == 0 || buffer.address == 0) return null;
Map<String, dynamic> propVals = {};
var entity = new _OBXFBEntity(buffer.data);
var entity = _OBXFBEntity(buffer.data);

_modelEntity.properties.forEach((p) {
var propReader;
Expand Down
19 changes: 13 additions & 6 deletions lib/src/bindings/structs.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ class IDArray {

IDArray(List<int> ids) {
_idsPtr = Pointer<Uint64>.allocate(count: ids.length);
for (int i = 0; i < ids.length; ++i) _idsPtr.elementAt(i).store(ids[i]);
for (int i = 0; i < ids.length; ++i) {
_idsPtr.elementAt(i).store(ids[i]);
}
_structPtr = Pointer<Uint64>.allocate(count: 2);
_structPtr.store(_idsPtr.address);
_structPtr.elementAt(1).store(ids.length);
Expand All @@ -29,7 +31,9 @@ class ByteBuffer {

ByteBuffer.allocate(Uint8List dartData, [bool align = true]) {
_ptr = Pointer<Uint8>.allocate(count: align ? ((dartData.length + 3.0) ~/ 4.0) * 4 : dartData.length);
for (int i = 0; i < dartData.length; ++i) _ptr.elementAt(i).store(dartData[i]);
for (int i = 0; i < dartData.length; ++i) {
_ptr.elementAt(i).store(dartData[i]);
}
_size = dartData.length;
}

Expand All @@ -45,8 +49,10 @@ class ByteBuffer {
get size => _size;

Uint8List get data {
var buffer = new Uint8List(size);
for (int i = 0; i < size; ++i) buffer[i] = _ptr.elementAt(i).load<int>();
var buffer = Uint8List(size);
for (int i = 0; i < size; ++i) {
buffer[i] = _ptr.elementAt(i).load<int>();
}
return buffer;
}

Expand Down Expand Up @@ -75,9 +81,10 @@ class ByteBufferArray {
_buffers = [];
Pointer<Uint64> bufferPtrs = Pointer<Uint64>.fromAddress(bytesArray.load<int>()); // bytesArray.bytes
int numBuffers = bytesArray.elementAt(1).load<int>(); // bytesArray.count
for (int i = 0; i < numBuffers; ++i) // loop through instances of "struct OBX_bytes"
for (int i = 0; i < numBuffers; ++i) {
_buffers.add(ByteBuffer.fromOBXBytes(
bufferPtrs.elementAt(2 * i))); // 2 * i, because each instance of "struct OBX_bytes" has .data and .size
bufferPtrs.elementAt(2 * i)));
} // 2 * i, because each instance of "struct OBX_bytes" has .data and .size
}

_SerializedByteBufferArray toOBXBytesArray() {
Expand Down
Loading