Skip to content

Commit

Permalink
support parse json from json file
Browse files Browse the repository at this point in the history
  • Loading branch information
moweiran committed Jan 3, 2024
1 parent fd4f07b commit b7c174d
Show file tree
Hide file tree
Showing 10 changed files with 94 additions and 70 deletions.
7 changes: 7 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,13 @@
"request": "launch",
"type": "dart",
"program": ".dart_tool/build/entrypoint/build.dart",
"args": ["build","-d"]
},
{
"name": "json_parse_model_with_params",
"request": "launch",
"type": "dart",
"program": ".dart_tool/build/entrypoint/build.dart",
"args": ["build","-d","--define" ,"json_parse_model:json=host=http://www.api.com/api" ,"--define" ,"json_parse_model:json=token=abcdeffgg"]
},
{
Expand Down
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## 1.1.1

- support json data source from json file

## 1.1.0

- add logging
Expand Down
33 changes: 21 additions & 12 deletions bin/json.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ import 'dart:io';

import 'package:args/command_runner.dart';

const String hostFlag = 'host';
const String tokenFlag = 'token';
const String verboseFlag = 'verbose';

void main(List<String> arguments) {
CommandRunner('json', "A dart implementation of json convert to model")
..addCommand(BuildCommand())
Expand All @@ -17,24 +21,29 @@ class BuildCommand extends Command {
String get name => "build";

BuildCommand() {
argParser.addOption(
'host',
abbr: 'o',
help: 'It\'s a http uri(eg:http://www.google.com/api).',
);
argParser.addOption(
'token',
abbr: 't',
help: 'It\'s a http header authorization value',
);
argParser
..addOption(
hostFlag,
abbr: 'o',
help: 'It\'s a http uri(eg:http://www.google.com/api).',
)
..addOption(
tokenFlag,
abbr: 't',
help: 'It\'s a http header authorization value',
)
..addFlag(
verboseFlag,
abbr: 'v',
help: 'Verbose output',
defaultsTo: false,
);
}

@override
FutureOr? run() async {
final host = argResults?['host'] ?? "";
final token = argResults?['token'] ?? "";
print(host);
print(token);
await Process.run('dart', [
'run',
'build_runner',
Expand Down
28 changes: 15 additions & 13 deletions lib/src/builder.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ import 'dart:async';
import 'package:build/build.dart';
import 'package:code_builder/code_builder.dart';
import 'package:dart_style/dart_style.dart';
import 'package:logging/logging.dart';

import 'http_parse.dart';
import 'json_parse_model_base.dart';
import 'logging.dart';
import 'source_parse.dart';

Logger logger = Logger('builder=>build');
JLogger jlogger = JLogger(true);

class Json2ModelPrintBuilder implements Builder {
final BuilderOptions options;
Expand All @@ -20,7 +20,8 @@ class Json2ModelPrintBuilder implements Builder {
@override
FutureOr<void> build(BuildStep buildStep) async {
try {
logger.info('options=${options.config}');
// logger.info('options=${options.config}');
jlogger.info('options=${options.config}');
final inputId = buildStep.inputId;
var contents = await buildStep.readAsString(inputId);
final sourceConfig = SourceParse.instance.parse(contents);
Expand All @@ -29,20 +30,21 @@ class Json2ModelPrintBuilder implements Builder {

var outputId = AssetId(inputId.package, sourceConfig.outpath);

var jsonMap = await HttpParse.instance.get(
sourceConfig.api,
host: options.config['host'],
token: options.config['token'],
);
var jsonMap = sourceConfig.source ??
await HttpParse.instance.get(
sourceConfig.api,
host: options.config['host'],
token: options.config['token'],
);
if (jsonMap == null) {
logger.info('$tag jsonMap is null');
jlogger.info('$tag jsonMap is null');
return;
}

if (jsonMap.isNotEmpty) {
final data = jsonMap['data'];
if (data is bool || data is String || data is int) {
logger.info('$tag is bool or string or int');
jlogger.info('$tag is bool or string or int');
} else if (data is List) {
if (data.first is Map<String, dynamic>) {
_buildClassCode(
Expand All @@ -51,7 +53,7 @@ class Json2ModelPrintBuilder implements Builder {
resultCodes: resultCodes,
);
} else {
logger.info('$tag is Map<bool> or Map<String> or Map<bool>');
jlogger.info('$tag is Map<bool> or Map<String> or Map<bool>');
}
} else if (data is Map<String, dynamic>) {
_buildClassCode(
Expand All @@ -63,11 +65,11 @@ class Json2ModelPrintBuilder implements Builder {
await buildStep.writeAsString(outputId,
'/// Generated by build_runner, don\'t modify it.\n${resultCodes.join("\n")}');
} else {
logger.info(
jlogger.info(
'please check your assets/json/xxx.json file exist or formatter!');
}
} catch (e, s) {
logger.info('error', e, s);
jlogger.error('error $e $s');
}
}

Expand Down
9 changes: 5 additions & 4 deletions lib/src/http_parse.dart
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@ class HttpParse {
host.isNotEmpty &&
token != null &&
token.isNotEmpty) {
logger.info('read buid config from options');
jlogger.info('read buid config from options');
buildConfig = JsonBuildConfig(host: host, token: token);
} else {
logger.info('read buid config from yaml file');
jlogger.info('read buid config from yaml file');
buildConfig ??= await loadConfigs();
}

Expand All @@ -36,10 +36,11 @@ class HttpParse {
var response = await http.get(uri, headers: {
HttpHeaders.authorizationHeader: 'Bearer ${buildConfig!.token}',
});
logger.info('$url =>\n ${response.body}');
// logger.info('$url =>\n ${response.body}');
jlogger.info('$url =>\n ${response.body}');
return json.decode(response.body);
} catch (e, s) {
logger.warning('httpParse', e, s);
jlogger.error('httpParse$e $s');
return null;
}
}
Expand Down
4 changes: 2 additions & 2 deletions lib/src/load_config.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@ import 'build_config.dart';
import 'builder.dart';

Future<JsonBuildConfig> loadConfigs() async {
logger.info('start load config');
jlogger.info('start load config');
final File file = File.fromUri(Uri.file("json2model.yaml"));
if (await file.exists()) {
final config = await file.readAsString();
final doc = loadYaml(config);
final jsonString = json.encode(doc);
return JsonBuildConfig.fromJson(json.decode(jsonString));
} else {
logger
jlogger
.info("Environment variable file doesn't exist at `json2model.yaml`.");
return JsonBuildConfig(host: '', token: '');
}
Expand Down
70 changes: 34 additions & 36 deletions lib/src/logging.dart
Original file line number Diff line number Diff line change
@@ -1,37 +1,35 @@
// Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:async';

import 'package:logging/logging.dart';

const Symbol logKey = #buildLog;

final _default = Logger('build.fallback');

/// The log instance for the currently running BuildStep.
///
/// Will be `null` when not running within a build.
Logger get log => Zone.current[logKey] as Logger? ?? _default;

/// Runs [fn] in an error handling [Zone].
///
/// Any calls to [print] will be logged with `log.warning`, and any errors will
/// be logged with `log.severe`.
///
/// Completes with the first error or result of `fn`, whichever comes first.
Future<T> scopeLogAsync<T>(Future<T> Function() fn, Logger log) {
var done = Completer<T>();
runZonedGuarded(fn, (e, st) {
log.severe('', e, st);
if (done.isCompleted) return;
done.completeError(e, st);
}, zoneSpecification: ZoneSpecification(print: (self, parent, zone, message) {
log.warning(message);
}), zoneValues: {logKey: log})?.then((result) {
if (done.isCompleted) return;
done.complete(result);
});
return done.future;
import 'package:cli_util/cli_logging.dart';

export 'package:cli_util/cli_logging.dart' show Progress;

/// Flutter Launcher Icons Logger
class JLogger {
late Logger _logger;

/// Returns true if this is a verbose logger
final bool isVerbose;

/// Gives access to internal logger
Logger get rawLogger => _logger;

/// Creates a instance of [JLogger].
/// In case [isVerbose] is `true`,
/// it logs all the [verbose] logs to console
JLogger(this.isVerbose) {
final ansi = Ansi(Ansi.terminalSupportsAnsi);
_logger =
isVerbose ? Logger.verbose(ansi: ansi) : Logger.standard(ansi: ansi);
}

/// Logs error messages
void error(Object? message) => _logger.stderr('⚠️$message');

/// Prints to console if [isVerbose] is true
void verbose(Object? message) => _logger.trace(message.toString());

/// Prints to console
void info(Object? message) => _logger.stdout(message.toString());

/// Shows progress in console
Progress progress(String message) => _logger.progress(message);
}
3 changes: 3 additions & 0 deletions lib/src/source_config.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,20 @@ class JsonSourceConfig {
final String api;
final String className;
final String outpath;
final Map<String, dynamic>? source;
JsonSourceConfig({
required this.api,
required this.className,
required this.outpath,
this.source,
});

factory JsonSourceConfig.fromJson(Map<String, dynamic> json) {
return JsonSourceConfig(
api: json['api'] ?? '',
className: json['className'] ?? '',
outpath: json['outpath'] as String,
source: json['source'],
);
}
}
2 changes: 1 addition & 1 deletion lib/src/source_parse.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ class SourceParse {
static final instance = SourceParse._();

JsonSourceConfig parse(String source) {
final result = (json.decode(source) as Map).cast<String, String>();
final result = (json.decode(source) as Map).cast<String, dynamic>();
return JsonSourceConfig.fromJson(result);
}
}
4 changes: 2 additions & 2 deletions pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name: json_parse_model
description: A package for convert from json to model by http api
version: 1.1.0
version: 1.1.1
repository: https://github.com/moweiran/json_parse_model.git

environment:
Expand All @@ -10,10 +10,10 @@ environment:
dependencies:
args: ^2.4.2
build: ^2.4.1
cli_util: ^0.4.1
code_builder: ^4.9.0
dart_style: ^2.3.4
http: ^1.1.2
logging: ^1.2.0
yaml: ^3.1.2
# path: ^1.8.0

Expand Down

0 comments on commit b7c174d

Please sign in to comment.