From 5049157b026f69ded6170f12bcb1620380920d25 Mon Sep 17 00:00:00 2001 From: h7x4 Date: Sun, 13 Jul 2025 16:27:11 +0200 Subject: [PATCH] cli/query_word: add `--json` flag --- lib/cli/commands/query_word.dart | 47 ++++++++++++++++++++++++++------ 1 file changed, 39 insertions(+), 8 deletions(-) diff --git a/lib/cli/commands/query_word.dart b/lib/cli/commands/query_word.dart index 92fe635..45219da 100644 --- a/lib/cli/commands/query_word.dart +++ b/lib/cli/commands/query_word.dart @@ -1,3 +1,4 @@ +import 'dart:convert'; import 'dart:io'; import 'package:jadb/_data_ingestion/open_local_db.dart'; @@ -15,6 +16,12 @@ class QueryWord extends Command { QueryWord() { addLibsqliteArg(argParser); addJadbArg(argParser); + + argParser.addFlag( + 'json', + abbr: 'j', + help: 'Output results in JSON format', + ); } Future run() async { @@ -42,13 +49,25 @@ class QueryWord extends Command { final int? maybeId = int.tryParse(searchWord); if (maybeId != null && maybeId >= 1000000) { - await _searchId(db, maybeId); + await _searchId( + db, + maybeId, + argResults!.flag('json'), + ); } else { - await _searchWord(db, searchWord); + await _searchWord( + db, + searchWord, + argResults!.flag('json'), + ); } } - Future _searchId(DatabaseExecutor db, int id) async { + Future _searchId( + DatabaseExecutor db, + int id, + bool jsonOutput, + ) async { final time = Stopwatch()..start(); final result = await JaDBConnection(db).jadbGetWordById(id); time.stop(); @@ -56,13 +75,21 @@ class QueryWord extends Command { if (result == null) { print("Invalid ID"); } else { - print(result.toString()); + if (jsonOutput) { + print(JsonEncoder.withIndent(' ').convert(result)); + } else { + print(result.toString()); + } } print("Query took ${time.elapsedMilliseconds}ms"); } - Future _searchWord(DatabaseExecutor db, String searchWord) async { + Future _searchWord( + DatabaseExecutor db, + String searchWord, + bool jsonOutput, + ) async { final time = Stopwatch()..start(); final count = await JaDBConnection(db).jadbSearchWordCount(searchWord); time.stop(); @@ -76,9 +103,13 @@ class QueryWord extends Command { } else if (result.isEmpty) { print("No matches"); } else { - for (final e in result) { - print(e.toString()); - print(""); + if (jsonOutput) { + print(JsonEncoder.withIndent(' ').convert(result)); + } else { + for (final e in result) { + print(e.toString()); + print(""); + } } }