Skip to content
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

feat: models_bundle 0.0.1 #25

Merged
merged 4 commits into from Nov 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/PULL_REQUEST_TEMPLATE.md
Expand Up @@ -11,7 +11,9 @@
<!--- Put an `x` in all the boxes that apply: -->

- [ ] model
- [ ] models_bundle
- [ ] feature_brick
- [ ] feature_brick_tests
- [ ] app_ui
- [ ] service
- [ ] service_package
Expand Down
2 changes: 2 additions & 0 deletions README.md
Expand Up @@ -19,6 +19,7 @@ A collection of bricks that enable developers to be more productive when writing
| Brick | Description | Version |
| -------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ------- |
| [model](https://brickhub.dev/bricks/model) | A brick to create your model with properties and all the supporting methods, copyWith, to/from json, equatable and more! | 0.5.1 |
| [models_bundle](https://brickhub.dev/bricks/models_bundle) | A brick to create multiple models including their properties and all the supporting methods/extensions! | 0.0.1 |
| [feature_brick](https://brickhub.dev/bricks/feature_brick) | A brick to create a feature using best practices and your state management of choice! | 0.6.0 |
| feature_brick_tests | A supporting brick to create your features tests with 100% coverage using best practices and your state management of choice! | 0.0.1 |
| [app_ui](https://brickhub.dev/bricks/app_ui) | A brick to create your UI package that holds all your app's Colors, Typography, Layout, Theme, and more! | 0.0.4 |
Expand All @@ -29,6 +30,7 @@ A collection of bricks that enable developers to be more productive when writing
## Documentation

- [Model](https://github.com/LukeMoody01/mason_bricks/tree/master/bricks/model)
- [Models Bundle](https://github.com/LukeMoody01/mason_bricks/tree/master/bricks/models_bundle)
- [Feature Brick](https://github.com/LukeMoody01/mason_bricks/tree/master/bricks/feature_brick)
- [Feature Brick Tests](https://github.com/LukeMoody01/mason_bricks/tree/master/bricks/feature_brick_tests)
- [App UI](https://github.com/LukeMoody01/mason_bricks/tree/master/bricks/app_ui)
Expand Down
3 changes: 3 additions & 0 deletions bricks/models_bundle/CHANGELOG.md
@@ -0,0 +1,3 @@
# 0.0.1

- Create initial models_bundle Brick
21 changes: 21 additions & 0 deletions bricks/models_bundle/LICENSE
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 Luke Moody

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
91 changes: 91 additions & 0 deletions bricks/models_bundle/README.md
@@ -0,0 +1,91 @@
# Models Bundle

A brick to create multiple models including their properties and all the supporting methods/extensions!

This brick is primarily meant to be used with a config template to generate multiple models using the existing [model brick](https://github.com/LukeMoody01/mason_bricks/tree/master/bricks/model)

## Table of Contents

- [How to use](#how-to-use-🚀)
- [Model from Config](#config)
- [Outputs](#outputs-📦)

## How to use 🚀

### Config

`mason make model -c models_bundle_config.json`

[Example Config](https://github.com/LukeMoody01/mason_bricks/tree/master/bricks/models_bundle/models_config_template.json):

```json
{
"models": [
{
"model_name": "chat",
"additionals": ["copyWith", "json", "equatable"],
"style": "json_serializable",
"relations": [{ "name": "person" }],
"properties": [
{ "name": "id", "type": "int" },
{ "name": "message", "type": "String" },
{ "name": "sentTime", "type": "DateTime" },
{ "name": "chatImage", "type": "String" },
{ "name": "isForwarded", "type": "bool" },
{ "name": "toUsers", "type": "List<Person>" }
]
},
{
"model_name": "person",
"additionals": ["copyWith", "json", "equatable"],
"style": "json_serializable",
"properties": [
{ "name": "id", "type": "int" },
{ "name": "firstName", "type": "String" },
{ "name": "lastName", "type": "String" },
{ "name": "age", "type": "int" },
{ "name": "isHappy", "type": "bool" },
{ "name": "favouriteNumber", "type": "int" },
{ "name": "nicknames", "type": "List<String>" },
{ "name": "countriesVisited", "type": "List<String>" },
{ "name": "organizationId", "type": "String" }
]
},
{
"model_name": "organization",
"additionals": ["copyWith", "json", "equatable"],
"style": "json_serializable",
"relations": [{ "name": "person" }],
"properties": [
{ "name": "id", "type": "int" },
{ "name": "name", "type": "String" },
{ "name": "users", "type": "List<Person>" },
{ "name": "address", "type": "String" }
]
},
...
]
}
```

## Variables for a Config ✨

| Variable | Description | Type |
| -------- | ------------------------------------- | ----- |
| `models` | The models you would like to generate | Array |

## Outputs 📦

`mason make model -c models_bundle_config.json`

```
├── models
│ ├── chat.dart
│ ├── chat.g.dart
│ ├── inbox_item.dart
│ ├── inbox_item.g.dart
│ ├── organization.dart
│ ├── organization.g.dart
│ └── organization.freezed.dart
└── ...
```
4 changes: 4 additions & 0 deletions bricks/models_bundle/brick.yaml
@@ -0,0 +1,4 @@
name: models_bundle
description: A brick to create multiple models including their properties and all the supporting methods/extensions!
version: 0.0.1
repository: https://github.com/LukeMoody01/mason_bricks/tree/master/bricks/models_bundle
3 changes: 3 additions & 0 deletions bricks/models_bundle/hooks/.gitignore
@@ -0,0 +1,3 @@
.dart_tool
.packages
pubspec.lock
36 changes: 36 additions & 0 deletions bricks/models_bundle/hooks/post_gen.dart
@@ -0,0 +1,36 @@
import 'dart:io';

import 'package:mason/mason.dart';

void run(HookContext context) async {
final usesFreezed = (context.vars['models'] as List)
.where((element) => element['style'] == 'freezed')
.length >
0;
final logger = context.logger;
final directory = Directory.current.path;
List<String> folders;

if (Platform.isWindows) {
folders = directory.split(r'\').toList();
} else {
folders = directory.split('/').toList();
}
final libIndex = folders.indexWhere((folder) => folder == 'lib');

if (usesFreezed &&
logger.confirm(
'Would you like to generate the freezed model?',
defaultValue: true,
)) {
final root = folders.sublist(0, libIndex).join('/').toString();
final buildRunnerProcess = await Process.start(
'flutter',
['pub', 'run', 'build_runner', 'build', '--delete-conflicting-outputs'],
runInShell: true,
workingDirectory: root,
);
await stdout.addStream(buildRunnerProcess.stdout);
await stderr.addStream(buildRunnerProcess.stderr);
}
}
110 changes: 110 additions & 0 deletions bricks/models_bundle/hooks/pre_gen.dart
@@ -0,0 +1,110 @@
import 'dart:io';

import 'package:mason/mason.dart';
import 'package:yaml/yaml.dart';

Future<void> run(HookContext context) async {
final usesFreezed = (context.vars['models'] as List)
.where((element) => element['style'] == 'freezed')
.length >
0;
final hasRelations = (context.vars['models'] as List)
.where((element) => (element['relations'] as List? ?? []).isNotEmpty)
.length >
0;

if (hasRelations || usesFreezed) await _validateDirectory(context);

final logger = context.logger;
final models = context.vars['models'];
final generator = await MasonGenerator.fromBrick(
Brick.version(name: 'model', version: '0.5.1'),
);

Map<String, dynamic> preGenVars = {};

for (var model in models) {
var progress = logger.progress('Creating ${model['model_name']}...');
await generator.hooks.preGen(
vars: {
"model_name": model['model_name'],
"additionals": model['additionals'],
"style": model['style'],
"properties": model['properties'],
"relations": model['relations'],
},
onVarsChanged: (vars) => preGenVars = vars,
);
await generator.generate(
DirectoryGeneratorTarget(Directory.current),
vars: preGenVars,
logger: context.logger,
);
progress.complete('Created ${model['model_name']}!');
}
}

/// Checks to see if the current output directory is in the
/// lib folder.
/// Adds the fullPath to the current working directory
Future<void> _validateDirectory(HookContext context) async {
final logger = context.logger;
final directory = Directory.current.path;

try {
List<String> folders;

if (Platform.isWindows) {
folders = directory.split(r'\').toList();
} else {
folders = directory.split('/').toList();
}
final libIndex = folders.indexWhere((folder) => folder == 'lib');
final modelPath = folders.sublist(libIndex + 1, folders.length).join('/');
final pubSpecFile =
File('${folders.sublist(0, libIndex).join('/')}/pubspec.yaml');
final content = await pubSpecFile.readAsString();
final yamlMap = loadYaml(content);
final packageName = yamlMap['name'];
context.vars = {
...context.vars,
'fullPath': ('$packageName/$modelPath/').replaceAll('//', '/'),
};
} on RangeError catch (_) {
logger.alert(
red.wrap(
'Could not find lib folder in $directory',
),
);
logger.alert(
red.wrap(
'Re-run this brick inside your lib folder',
),
);
throw Exception();
} on FileSystemException catch (_) {
logger.alert(
red.wrap(
'Could not find pubspec.yaml folder in ${directory.replaceAll('\\lib', '')}',
),
);

throw Exception();
} on PubspecNameException catch (_) {
logger.alert(
red.wrap(
'Could not read package name in pubspec.yaml',
),
);
logger.alert(
red.wrap(
'Does your pubspec have a name ?',
),
);
throw Exception();
} on Exception catch (e) {
throw e;
}
}

class PubspecNameException implements Exception {}
8 changes: 8 additions & 0 deletions bricks/models_bundle/hooks/pubspec.yaml
@@ -0,0 +1,8 @@
name: models_bundle_hooks

environment:
sdk: ">=2.12.0 <3.0.0"

dependencies:
mason: ^0.1.0-dev
yaml: ^3.1.1
81 changes: 81 additions & 0 deletions bricks/models_bundle/models_config_template.json
@@ -0,0 +1,81 @@
{
"models": [
{
"model_name": "chat",
"additionals": ["copyWith", "json", "equatable"],
"style": "json_serializable",
"relations": [{ "name": "person" }],
"properties": [
{ "name": "id", "type": "int" },
{ "name": "message", "type": "String" },
{ "name": "sentTime", "type": "DateTime" },
{ "name": "chatImage", "type": "String" },
{ "name": "isForwarded", "type": "bool" },
{ "name": "toUsers", "type": "List<Person>" }
]
},
{
"model_name": "person",
"additionals": ["copyWith", "json", "equatable"],
"style": "json_serializable",
"properties": [
{ "name": "id", "type": "int" },
{ "name": "firstName", "type": "String" },
{ "name": "lastName", "type": "String" },
{ "name": "age", "type": "int" },
{ "name": "isHappy", "type": "bool" },
{ "name": "favouriteNumber", "type": "int" },
{ "name": "nicknames", "type": "List<String>" },
{ "name": "countriesVisited", "type": "List<String>" },
{ "name": "organizationId", "type": "String" }
]
},
{
"model_name": "organization",
"additionals": ["copyWith", "json", "equatable"],
"style": "json_serializable",
"relations": [{ "name": "person" }],
"properties": [
{ "name": "id", "type": "int" },
{ "name": "name", "type": "String" },
{ "name": "users", "type": "List<Person>" },
{ "name": "address", "type": "String" }
]
},
{
"model_name": "analyticsDTO",
"additionals": ["json", "equatable"],
"style": "json_serializable",
"properties": [
{ "name": "id", "type": "int" },
{ "name": "messagesCount", "type": "int" },
{ "name": "usersCount", "type": "int" },
{ "name": "invitationCount", "type": "int" }
]
},
{
"model_name": "inboxItem",
"additionals": ["copyWith", "json", "equatable"],
"relations": [{ "name": "person" }, { "name": "chat" }],
"style": "json_serializable",
"properties": [
{ "name": "id", "type": "int" },
{ "name": "name", "type": "String" },
{ "name": "users", "type": "List<Person>" },
{ "name": "lastMessage", "type": "Chat" }
]
},
{
"model_name": "invitations",
"additionals": ["copyWith", "json", "equatable"],
"style": "json_serializable",
"relations": [{ "name": "person" }],
"properties": [
{ "name": "id", "type": "int" },
{ "name": "to", "type": "Person" },
{ "name": "from", "type": "Person" },
{ "name": "invitationMessage", "type": "String" }
]
}
]
}