summaryrefslogtreecommitdiffstats
path: root/src/cepis/__main__.py
blob: 9478a75366a3aecafb2dcc99368185940b91cba4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
"""Minimal CLI: `python -m cepis 01001000`.

It exists for one concrete case — quickly confirming a local instance answers
before pointing code at it::

    python -m cepis --base-url http://localhost:8080 01001000

A single CEP goes through the unit lookup, which carries `geo`; several go
through the batch, which is one request instead of N and has no `geo`.

It is not the library's main interface; for that, import :mod:`cepis`.
"""

from __future__ import annotations

import argparse
import dataclasses
import json
import sys

from . import DEFAULT_URL, CepisError, Client


def main(argv: list[str] | None = None) -> int:
    """Run the CLI. Returns the process exit code."""
    parser = argparse.ArgumentParser(
        prog="python -m cepis",
        description="Look CEPs up against the cep.is API.",
    )
    parser.add_argument("cep", nargs="+", help="one or more CEPs, masked or not")
    parser.add_argument(
        "--base-url",
        default=DEFAULT_URL,
        help=f"API URL (default: {DEFAULT_URL}) — use it to point at a local instance",
    )
    parser.add_argument(
        "--timeout", type=float, default=10.0, help="per-socket timeout, in seconds"
    )
    args = parser.parse_args(argv)

    client = Client(base_url=args.base_url, timeout=args.timeout)

    try:
        if len(args.cep) == 1:
            addresses = [client.lookup(args.cep[0])]
        else:
            addresses = client.lookup_many(args.cep)
    except CepisError as exc:
        print(f"error: {exc}", file=sys.stderr)
        return 1

    output = [None if a is None else dataclasses.asdict(a) for a in addresses]
    for item in output:
        if item is not None:
            item.pop("raw", None)
    print(json.dumps(output if len(output) > 1 else output[0], ensure_ascii=False, indent=2))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())