summaryrefslogtreecommitdiffstats
path: root/bin
diff options
context:
space:
mode:
authorMurilo Ijanc <[email protected]>2026-07-26 12:38:22 -0300
committerMurilo Ijanc <[email protected]>2026-07-26 12:38:22 -0300
commit8e719fc715eb7ae9aa1c842e633f15b5c6cd3688 (patch)
tree4afda3d13e1b772f2c9a5cf9ceea5e84c647ebdd /bin
downloaddart-931a90c71726a2a149de11f290aed4c7ef5a8194.tar.gz
Initial importv0.1.0
Diffstat (limited to 'bin')
-rw-r--r--bin/cepis.dart93
1 files changed, 93 insertions, 0 deletions
diff --git a/bin/cepis.dart b/bin/cepis.dart
new file mode 100644
index 0000000..8eec681
--- /dev/null
+++ b/bin/cepis.dart
@@ -0,0 +1,93 @@
+/// Command-line entry point: resolve CEPs from a terminal.
+///
+/// ```sh
+/// dart run cepis 01001000
+/// dart run cepis --base-url http://localhost:8080 01001000 20040020
+/// ```
+library;
+
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:cepis/cepis.dart';
+
+const String _usage = '''
+usage: cepis [--base-url URL] [--health] [CEP...]
+
+ --base-url URL where the API lives (default $defaultBaseUrl)
+ --health report the API's health instead of looking anything up
+ -h, --help show this message
+
+One CEP prints the full record, coordinate included. Several go through the
+batch endpoint, which carries no coordinate.''';
+
+Future<int> run(List<String> arguments) async {
+ var baseUrl = defaultBaseUrl;
+ var wantHealth = false;
+ final ceps = <String>[];
+
+ for (var i = 0; i < arguments.length; i++) {
+ final argument = arguments[i];
+ if (argument == '-h' || argument == '--help') {
+ stdout.writeln(_usage);
+ return 0;
+ } else if (argument == '--health') {
+ wantHealth = true;
+ } else if (argument == '--base-url') {
+ if (i + 1 >= arguments.length) {
+ stderr.writeln('cepis: --base-url needs a value');
+ return 2;
+ }
+ baseUrl = arguments[++i];
+ } else if (argument.startsWith('-')) {
+ stderr.writeln('cepis: unknown option $argument');
+ return 2;
+ } else {
+ ceps.add(argument);
+ }
+ }
+
+ if (!wantHealth && ceps.isEmpty) {
+ stderr.writeln(_usage);
+ return 2;
+ }
+
+ final client = Client(baseUrl: baseUrl);
+ try {
+ if (wantHealth) {
+ final report = await client.health();
+ stdout.writeln(_encode(report.raw));
+ return report.ok ? 0 : 1;
+ }
+
+ if (ceps.length == 1) {
+ final address = await client.lookup(ceps.single);
+ stdout.writeln(_encode(address.raw));
+ return 0;
+ }
+
+ final result = await client.lookupMany(ceps);
+ for (var i = 0; i < ceps.length; i++) {
+ final address = result[i];
+ stdout.writeln(
+ address == null
+ ? '${ceps[i]}\tnot found'
+ : '${ceps[i]}\t${address.logradouro}\t${address.localidade}\t'
+ '${address.uf}',
+ );
+ }
+ return 0;
+ } on CepisException catch (error) {
+ stderr.writeln('cepis: ${error.message}');
+ return 1;
+ } finally {
+ client.close();
+ }
+}
+
+String _encode(Map<String, dynamic> data) =>
+ const JsonEncoder.withIndent(' ').convert(data);
+
+Future<void> main(List<String> arguments) async {
+ exitCode = await run(arguments);
+}