quantilica-cli 0.13.0__tar.gz → 0.14.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. {quantilica_cli-0.13.0 → quantilica_cli-0.14.0}/.github/workflows/test.yml +7 -2
  2. {quantilica_cli-0.13.0 → quantilica_cli-0.14.0}/CHANGELOG.md +8 -0
  3. quantilica_cli-0.14.0/PKG-INFO +83 -0
  4. quantilica_cli-0.14.0/README.md +58 -0
  5. {quantilica_cli-0.13.0 → quantilica_cli-0.14.0}/pyproject.toml +6 -2
  6. {quantilica_cli-0.13.0 → quantilica_cli-0.14.0}/src/quantilica/cli/cli.py +2 -0
  7. quantilica_cli-0.14.0/src/quantilica/cli/lake.py +418 -0
  8. quantilica_cli-0.14.0/tests/lake_build_fakes.py +95 -0
  9. quantilica_cli-0.14.0/tests/lake_fixtures.py +101 -0
  10. quantilica_cli-0.14.0/tests/test_lake_cli.py +471 -0
  11. quantilica_cli-0.13.0/PKG-INFO +0 -49
  12. quantilica_cli-0.13.0/README.md +0 -26
  13. {quantilica_cli-0.13.0 → quantilica_cli-0.14.0}/.githooks/pre-commit +0 -0
  14. {quantilica_cli-0.13.0 → quantilica_cli-0.14.0}/.githooks/pre-push +0 -0
  15. {quantilica_cli-0.13.0 → quantilica_cli-0.14.0}/.github/workflows/public-hygiene.yml +0 -0
  16. {quantilica_cli-0.13.0 → quantilica_cli-0.14.0}/.github/workflows/publish.yml +0 -0
  17. {quantilica_cli-0.13.0 → quantilica_cli-0.14.0}/.gitignore +0 -0
  18. {quantilica_cli-0.13.0 → quantilica_cli-0.14.0}/LICENSE +0 -0
  19. {quantilica_cli-0.13.0 → quantilica_cli-0.14.0}/src/quantilica/cli/__init__.py +0 -0
  20. {quantilica_cli-0.13.0 → quantilica_cli-0.14.0}/src/quantilica/cli/health.py +0 -0
  21. {quantilica_cli-0.13.0 → quantilica_cli-0.14.0}/src/quantilica/cli/manifests.py +0 -0
  22. {quantilica_cli-0.13.0 → quantilica_cli-0.14.0}/src/quantilica/cli/sdk.py +0 -0
  23. {quantilica_cli-0.13.0 → quantilica_cli-0.14.0}/src/quantilica/cli/sources.py +0 -0
  24. {quantilica_cli-0.13.0 → quantilica_cli-0.14.0}/src/quantilica/cli/ui.py +0 -0
  25. {quantilica_cli-0.13.0 → quantilica_cli-0.14.0}/src/quantilica/py.typed +0 -0
  26. {quantilica_cli-0.13.0 → quantilica_cli-0.14.0}/tests/__init__.py +0 -0
  27. {quantilica_cli-0.13.0 → quantilica_cli-0.14.0}/tests/test_health.py +0 -0
  28. {quantilica_cli-0.13.0 → quantilica_cli-0.14.0}/tests/test_manifests.py +0 -0
  29. {quantilica_cli-0.13.0 → quantilica_cli-0.14.0}/tests/test_package_hygiene.py +0 -0
  30. {quantilica_cli-0.13.0 → quantilica_cli-0.14.0}/tests/test_sdk.py +0 -0
  31. {quantilica_cli-0.13.0 → quantilica_cli-0.14.0}/tests/test_sdk_force_probe.py +0 -0
  32. {quantilica_cli-0.13.0 → quantilica_cli-0.14.0}/tests/test_sdk_mes_string.py +0 -0
  33. {quantilica_cli-0.13.0 → quantilica_cli-0.14.0}/tests/test_sdk_onda_a2.py +0 -0
  34. {quantilica_cli-0.13.0 → quantilica_cli-0.14.0}/tests/test_sources.py +0 -0
  35. {quantilica_cli-0.13.0 → quantilica_cli-0.14.0}/tests/test_ui.py +0 -0
@@ -9,12 +9,16 @@ on:
9
9
 
10
10
  jobs:
11
11
  test:
12
- name: Test (Python ${{ matrix.python-version }})
13
- runs-on: ubuntu-latest
12
+ name: Test (${{ matrix.os }}, Python ${{ matrix.python-version }})
13
+ runs-on: ${{ matrix.os }}
14
14
  strategy:
15
15
  fail-fast: false
16
16
  matrix:
17
+ os: [ubuntu-latest]
17
18
  python-version: ["3.12", "3.13"]
19
+ include:
20
+ - os: windows-latest
21
+ python-version: "3.12"
18
22
 
19
23
  steps:
20
24
  - uses: actions/checkout@v4
@@ -31,6 +35,7 @@ jobs:
31
35
  # (2026-08-23: rtn e inmet). Três tentativas removem o flake sem
32
36
  # esconder erro real de resolução.
33
37
  - name: Install dependencies
38
+ shell: bash
34
39
  run: |
35
40
  for i in 1 2 3; do
36
41
  if uv sync --group dev --python ${{ matrix.python-version }} \
@@ -5,6 +5,14 @@ Todas as mudanças notáveis deste projeto serão documentadas neste arquivo.
5
5
  O formato segue [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/),
6
6
  e este projeto adere ao [Semantic Versioning](https://semver.org/lang/pt-BR/).
7
7
 
8
+ ## [0.14.0] - 2026-10-30
9
+
10
+ ### Adicionado
11
+
12
+ - `quantilica lake select|build|audit`: monta e audita o lake a partir de um bruto local. `select` cria a visão com a versão vigente de cada arquivo (`--mode hardlink|symlink|copy`, `--exclude ARQ` com `sha256` ou caminhos); `build` converte a visão em Parquet por fonte e dataset, em processos separados e com retomada (`--sources`, `--workers`, `--memory`, `--threads`, `--scratch`, `--force`, `--retry-errors`, `--no-disk-check`, `--allow-sleep`), e sai com código 1 se houver erro e 130 se for interrompido; `audit` confere rodapés, proveniência, cobertura, estrutura e leitores (`--input`, `--ledger`, `--sources`, `--no-readers`, `--no-integrity`, `--exceptions`, `--rehash`, `--workers`, `--json`, `--json-file`) e sai com código 1 se houver achados. O ledger é opcional.
13
+ - Extra `lake` (`pip install "quantilica-cli[lake]"`): traz o `quantilica-analytics`, que `build` e `audit` carregam só quando rodam; sem ele, avisam o que instalar e saem com código 1. `select` só precisa do `quantilica-core` (a partir da versão que traz `materialize_view`).
14
+ - CI: o job de testes também roda no Windows (Python 3.12).
15
+
8
16
  ## [0.13.0] - 2026-10-27
9
17
 
10
18
  ### Adicionado
@@ -0,0 +1,83 @@
1
+ Metadata-Version: 2.5
2
+ Name: quantilica-cli
3
+ Version: 0.14.0
4
+ Summary: Unified CLI for Quantilica open data fetchers
5
+ Author-email: "Komesu, D.K." <daniel@dkko.me>
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Keywords: brazil,cli,open-data,quantilica
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Environment :: Console
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Typing :: Typed
18
+ Requires-Python: >=3.12
19
+ Requires-Dist: quantilica-core>=0.15.0
20
+ Requires-Dist: rich>=13.0.0
21
+ Requires-Dist: typer>=0.15.0
22
+ Provides-Extra: lake
23
+ Requires-Dist: quantilica-analytics>=0.8.0; extra == 'lake'
24
+ Description-Content-Type: text/markdown
25
+
26
+ # quantilica-cli
27
+
28
+ CLI unificada para o ecossistema Quantilica de dados abertos brasileiros.
29
+ For full documentation, please visit [https://docs.quantilica.com](https://docs.quantilica.com).
30
+
31
+ ## Instalação
32
+
33
+ ```bash
34
+ pip install quantilica-cli
35
+ ```
36
+
37
+ Instale os fetchers desejados separadamente:
38
+
39
+ ```bash
40
+ pip install comex-fetcher inmet-fetcher rtn-fetcher
41
+ ```
42
+
43
+ ## Uso
44
+
45
+ ```bash
46
+ quantilica --help
47
+ quantilica list-sources
48
+ quantilica comex sync 2024
49
+ quantilica inmet sync 2020 2021
50
+ quantilica td sync --dataset prices
51
+ ```
52
+
53
+ ## Lake
54
+
55
+ `quantilica lake` monta e audita o lake de Parquet a partir de um bruto local, sem
56
+ depender de banco de dados nem do ledger do acervo (ele é opcional). O fluxo é
57
+ bruto local → `select` → `build` → `audit`:
58
+
59
+ ```bash
60
+ # 1. visão só com a versão vigente de cada arquivo (hardlink; cai em symlink e em cópia)
61
+ quantilica lake select --raw /dados/bruto --out /dados/vigente --exclude excluir.txt
62
+
63
+ # 2. conversão em Parquet, por fonte e dataset, em processos separados; retoma de onde parou
64
+ quantilica lake build --input /dados/vigente --lake /dados/lake --workers 4 --memory 12GB
65
+
66
+ # 3. auditoria: rodapés, proveniência (sha256), cobertura, estrutura e leitores
67
+ quantilica lake audit --lake /dados/lake --input /dados/vigente --json-file auditoria.json
68
+ ```
69
+
70
+ - `select` só precisa do `quantilica-core`. `build` e `audit` usam o
71
+ `quantilica-analytics`, que entra com `pip install "quantilica-cli[lake]"`; sem ele
72
+ esses dois comandos avisam o que instalar e saem com código 1.
73
+ - `--exclude` e `--exceptions` aceitam um arquivo texto com um item por linha (linhas
74
+ vazias e iniciadas por `#` são ignoradas): `sha256` ou caminho relativo no `select`,
75
+ caminho relativo ou padrão `fnmatch` no `audit`.
76
+ - `build` sai com código 1 se alguma tarefa falhar, e com 130 se for interrompido
77
+ (Ctrl+C); rodar de novo retoma e `--retry-errors` refaz só o que falhou. O andamento
78
+ sai em stderr.
79
+ - `audit` sai com 0 se o lake for aprovado e com 1 se houver achados. `--json` imprime
80
+ o relatório em JSON no stdout (o andamento fica em stderr); `--json-file ARQ` o grava.
81
+ - `--ledger ARQ` (opcional, só em `audit`) confere a proveniência também contra uma
82
+ exportação do ledger; sem ele, a conferência usa o `sha256` dos manifestos ou do
83
+ próprio arquivo.
@@ -0,0 +1,58 @@
1
+ # quantilica-cli
2
+
3
+ CLI unificada para o ecossistema Quantilica de dados abertos brasileiros.
4
+ For full documentation, please visit [https://docs.quantilica.com](https://docs.quantilica.com).
5
+
6
+ ## Instalação
7
+
8
+ ```bash
9
+ pip install quantilica-cli
10
+ ```
11
+
12
+ Instale os fetchers desejados separadamente:
13
+
14
+ ```bash
15
+ pip install comex-fetcher inmet-fetcher rtn-fetcher
16
+ ```
17
+
18
+ ## Uso
19
+
20
+ ```bash
21
+ quantilica --help
22
+ quantilica list-sources
23
+ quantilica comex sync 2024
24
+ quantilica inmet sync 2020 2021
25
+ quantilica td sync --dataset prices
26
+ ```
27
+
28
+ ## Lake
29
+
30
+ `quantilica lake` monta e audita o lake de Parquet a partir de um bruto local, sem
31
+ depender de banco de dados nem do ledger do acervo (ele é opcional). O fluxo é
32
+ bruto local → `select` → `build` → `audit`:
33
+
34
+ ```bash
35
+ # 1. visão só com a versão vigente de cada arquivo (hardlink; cai em symlink e em cópia)
36
+ quantilica lake select --raw /dados/bruto --out /dados/vigente --exclude excluir.txt
37
+
38
+ # 2. conversão em Parquet, por fonte e dataset, em processos separados; retoma de onde parou
39
+ quantilica lake build --input /dados/vigente --lake /dados/lake --workers 4 --memory 12GB
40
+
41
+ # 3. auditoria: rodapés, proveniência (sha256), cobertura, estrutura e leitores
42
+ quantilica lake audit --lake /dados/lake --input /dados/vigente --json-file auditoria.json
43
+ ```
44
+
45
+ - `select` só precisa do `quantilica-core`. `build` e `audit` usam o
46
+ `quantilica-analytics`, que entra com `pip install "quantilica-cli[lake]"`; sem ele
47
+ esses dois comandos avisam o que instalar e saem com código 1.
48
+ - `--exclude` e `--exceptions` aceitam um arquivo texto com um item por linha (linhas
49
+ vazias e iniciadas por `#` são ignoradas): `sha256` ou caminho relativo no `select`,
50
+ caminho relativo ou padrão `fnmatch` no `audit`.
51
+ - `build` sai com código 1 se alguma tarefa falhar, e com 130 se for interrompido
52
+ (Ctrl+C); rodar de novo retoma e `--retry-errors` refaz só o que falhou. O andamento
53
+ sai em stderr.
54
+ - `audit` sai com 0 se o lake for aprovado e com 1 se houver achados. `--json` imprime
55
+ o relatório em JSON no stdout (o andamento fica em stderr); `--json-file ARQ` o grava.
56
+ - `--ledger ARQ` (opcional, só em `audit`) confere a proveniência também contra uma
57
+ exportação do ledger; sem ele, a conferência usa o `sha256` dos manifestos ou do
58
+ próprio arquivo.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "quantilica-cli"
3
- version = "0.13.0"
3
+ version = "0.14.0"
4
4
  description = "Unified CLI for Quantilica open data fetchers"
5
5
  readme = "README.md"
6
6
  authors = [{ name = "Komesu, D.K.", email = "daniel@dkko.me" }]
@@ -20,11 +20,15 @@ classifiers = [
20
20
  "Programming Language :: Python :: 3.13",
21
21
  ]
22
22
  dependencies = [
23
- "quantilica-core>=0.11.0",
23
+ "quantilica-core>=0.15.0",
24
24
  "rich>=13.0.0",
25
25
  "typer>=0.15.0",
26
26
  ]
27
27
 
28
+ [project.optional-dependencies]
29
+ # Motor de `quantilica lake build` e `quantilica lake audit`.
30
+ lake = ["quantilica-analytics>=0.8.0"]
31
+
28
32
  [project.scripts]
29
33
  quantilica = "quantilica.cli.cli:main"
30
34
 
@@ -14,6 +14,7 @@ from rich.table import Table
14
14
 
15
15
  from quantilica.cli import __version__
16
16
  from quantilica.cli.health import cmd_health
17
+ from quantilica.cli.lake import app as lake_app
17
18
  from quantilica.cli.manifests import app as manifests_app
18
19
  from quantilica.cli.sources import (
19
20
  app as sources_app,
@@ -33,6 +34,7 @@ app = typer.Typer(
33
34
  help="Quantilica — ferramentas de dados abertos brasileiros.",
34
35
  no_args_is_help=True,
35
36
  )
37
+ app.add_typer(lake_app, name="lake")
36
38
  app.add_typer(manifests_app, name="manifests")
37
39
  app.add_typer(sources_app, name="sources")
38
40
 
@@ -0,0 +1,418 @@
1
+ """Comandos `quantilica lake` — selecionar, construir e auditar o lake.
2
+
3
+ Fluxo: bruto local -> ``select`` (visão só com a versão vigente de cada
4
+ arquivo) -> ``build`` (visão -> Parquet) -> ``audit`` (prova que o lake está
5
+ completo e íntegro). O ledger do acervo é opcional em todas as etapas.
6
+
7
+ ``select`` só depende do ``quantilica-core``. ``build`` e ``audit`` usam o
8
+ ``quantilica-analytics`` (extra ``lake``), importado só quando o comando roda,
9
+ de modo que ``--help`` funciona sem ele.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import logging
15
+ from collections.abc import Iterator
16
+ from contextlib import contextmanager
17
+ from enum import StrEnum
18
+ from pathlib import Path
19
+ from typing import Annotated
20
+
21
+ import typer
22
+ from rich.console import Console
23
+ from rich.logging import RichHandler
24
+ from rich.markup import escape
25
+
26
+ app = typer.Typer(
27
+ help="Montar e auditar o lake: bruto local → select → build → audit.",
28
+ no_args_is_help=True,
29
+ )
30
+
31
+ console = Console()
32
+ err_console = Console(stderr=True)
33
+
34
+ ANALYTICS_HINT = (
35
+ 'pip install "quantilica-cli[lake]" (ou: pip install quantilica-analytics)'
36
+ )
37
+ CORE_HINT = "pip install --upgrade quantilica-core"
38
+
39
+ EXIT_FAILURE = 1
40
+ EXIT_USAGE = 2
41
+ EXIT_INTERRUPTED = 130
42
+
43
+
44
+ class LinkMode(StrEnum):
45
+ """Como os arquivos entram na visão (ver ``materialize_view``)."""
46
+
47
+ hardlink = "hardlink"
48
+ symlink = "symlink"
49
+ copy = "copy"
50
+
51
+
52
+ def _fail(message: str, code: int = EXIT_FAILURE) -> typer.Exit:
53
+ """Escreve ``message`` em stderr e devolve a saída a ser levantada."""
54
+ err_console.print(f"[red]Erro:[/red] {escape(message)}", highlight=False)
55
+ return typer.Exit(code)
56
+
57
+
58
+ def _missing_analytics(command: str, exc: ImportError) -> typer.Exit:
59
+ return _fail(
60
+ f"'quantilica lake {command}' requer o quantilica-analytics "
61
+ f"({exc}). Instale com: {ANALYTICS_HINT}"
62
+ )
63
+
64
+
65
+ def _split_sources(value: str | None) -> list[str] | None:
66
+ """Converte ``"a,b"`` em ``["a", "b"]``; vazio vira ``None`` (todas)."""
67
+ if value is None:
68
+ return None
69
+ sources = [part.strip() for part in value.split(",") if part.strip()]
70
+ if not sources:
71
+ raise _fail("--sources está vazio: informe fontes separadas por vírgula.", 2)
72
+ return sources
73
+
74
+
75
+ def _read_list(path: Path) -> list[str]:
76
+ """Lê um arquivo texto com um item por linha (vazias e ``#`` ignoradas)."""
77
+ try:
78
+ text = path.read_text(encoding="utf-8")
79
+ except (OSError, UnicodeDecodeError) as exc:
80
+ raise _fail(f"não consegui ler {path}: {exc}") from exc
81
+ items: list[str] = []
82
+ for line in text.splitlines():
83
+ line = line.strip()
84
+ if line and not line.startswith("#"):
85
+ items.append(line)
86
+ return items
87
+
88
+
89
+ @contextmanager
90
+ def _log_to_stderr() -> Iterator[None]:
91
+ """Mostra o andamento (INFO do logger ``quantilica``) em stderr.
92
+
93
+ O logger ``quantilica`` (core e analytics) ganha um handler próprio e deixa
94
+ de propagar para a raiz, cujo handler escreve em stdout e sujaria a saída
95
+ ``--json``. O estado anterior é restaurado ao sair.
96
+ """
97
+ logger = logging.getLogger("quantilica")
98
+ saved = (logger.handlers, logger.level, logger.propagate)
99
+ logger.handlers = [
100
+ RichHandler(
101
+ console=err_console,
102
+ show_path=False,
103
+ show_time=True,
104
+ show_level=False,
105
+ rich_tracebacks=True,
106
+ )
107
+ ]
108
+ logger.setLevel(logging.INFO)
109
+ logger.propagate = False
110
+ try:
111
+ yield
112
+ finally:
113
+ logger.handlers, logger.level, logger.propagate = saved
114
+
115
+
116
+ @app.command("select")
117
+ def select(
118
+ raw: Annotated[
119
+ Path,
120
+ typer.Option(
121
+ "--raw",
122
+ help="Diretório do bruto (uma pasta por fonte)",
123
+ exists=True,
124
+ file_okay=False,
125
+ ),
126
+ ],
127
+ out: Annotated[
128
+ Path,
129
+ typer.Option(
130
+ "--out",
131
+ help="Diretório da visão vigente (usado só para a visão)",
132
+ file_okay=False,
133
+ ),
134
+ ],
135
+ mode: Annotated[
136
+ LinkMode,
137
+ typer.Option(
138
+ "--mode",
139
+ help="Como os arquivos entram na visão; se falhar, recua "
140
+ "hardlink → symlink → cópia",
141
+ ),
142
+ ] = LinkMode.hardlink,
143
+ exclude: Annotated[
144
+ Path | None,
145
+ typer.Option(
146
+ "--exclude",
147
+ help="Arquivo texto com um sha256 ou caminho relativo por linha "
148
+ "(vazias e # ignoradas) que não devem ir ao lake",
149
+ exists=True,
150
+ dir_okay=False,
151
+ ),
152
+ ] = None,
153
+ ) -> None:
154
+ """Cria a visão vigente: só a versão mais recente de cada arquivo bruto."""
155
+ try:
156
+ from quantilica.core.lake import materialize_view
157
+ except ImportError as exc:
158
+ raise _fail(
159
+ f"'quantilica lake select' requer um quantilica-core mais novo "
160
+ f"({exc}). Atualize com: {CORE_HINT}"
161
+ ) from None
162
+
163
+ excluded = _read_list(exclude) if exclude is not None else None
164
+ try:
165
+ summary = materialize_view(raw, out, mode=mode.value, exclude=excluded)
166
+ except (ValueError, OSError) as exc:
167
+ raise _fail(str(exc)) from exc
168
+
169
+ console.print(f"[green]✓[/green] Visão em [dim]{out}[/dim]", highlight=False)
170
+ typer.echo(f" arquivos: {summary.files}")
171
+ typer.echo(
172
+ f" criados: hardlink={summary.hardlink} symlink={summary.symlink} "
173
+ f"copy={summary.copy}"
174
+ )
175
+ typer.echo(f" mantidos: {summary.kept}")
176
+ typer.echo(f" excluídos: {summary.excluded}")
177
+ typer.echo(f" removidos: {summary.removed}")
178
+
179
+
180
+ @app.command("build")
181
+ def build(
182
+ input: Annotated[
183
+ Path,
184
+ typer.Option(
185
+ "-i",
186
+ "--input",
187
+ help="Visão vigente (saída de 'lake select'): uma pasta por fonte",
188
+ exists=True,
189
+ file_okay=False,
190
+ ),
191
+ ],
192
+ lake: Annotated[
193
+ Path,
194
+ typer.Option(
195
+ "--lake",
196
+ "-o",
197
+ help="Raiz do lake; o estado da construção fica em <lake>/.build/",
198
+ file_okay=False,
199
+ ),
200
+ ],
201
+ sources: Annotated[
202
+ str | None,
203
+ typer.Option(
204
+ "--sources",
205
+ help="Fontes a construir, separadas por vírgula (padrão: todas "
206
+ "as que têm conversor)",
207
+ ),
208
+ ] = None,
209
+ workers: Annotated[
210
+ int | None,
211
+ typer.Option("--workers", min=1, help="Processos em paralelo"),
212
+ ] = None,
213
+ memory: Annotated[
214
+ str | None,
215
+ typer.Option("--memory", help="Limite de memória do DuckDB por tarefa (12GB)"),
216
+ ] = None,
217
+ threads: Annotated[
218
+ int | None,
219
+ typer.Option("--threads", min=1, help="Threads do DuckDB por tarefa"),
220
+ ] = None,
221
+ scratch: Annotated[
222
+ Path | None,
223
+ typer.Option(
224
+ "--scratch",
225
+ help="Diretório temporário (extração e DuckDB); use um disco rápido",
226
+ file_okay=False,
227
+ ),
228
+ ] = None,
229
+ force: Annotated[
230
+ bool,
231
+ typer.Option("--force", help="Refaz todas as tarefas e reconverte tudo"),
232
+ ] = False,
233
+ retry_errors: Annotated[
234
+ bool,
235
+ typer.Option(
236
+ "--retry-errors", help="Refaz também as tarefas que falharam antes"
237
+ ),
238
+ ] = False,
239
+ no_disk_check: Annotated[
240
+ bool,
241
+ typer.Option(
242
+ "--no-disk-check", help="Não compara o espaço livre com a estimativa"
243
+ ),
244
+ ] = False,
245
+ allow_sleep: Annotated[
246
+ bool,
247
+ typer.Option(
248
+ "--allow-sleep", help="Não impede a suspensão do sistema durante a obra"
249
+ ),
250
+ ] = False,
251
+ ) -> None:
252
+ """Converte a visão vigente em Parquet; retoma de onde parou."""
253
+ try:
254
+ from quantilica.analytics.lake_build import (
255
+ InsufficientDiskError,
256
+ LakeBuildError,
257
+ lake_build,
258
+ )
259
+ except ImportError as exc:
260
+ raise _missing_analytics("build", exc) from None
261
+
262
+ wanted = _split_sources(sources)
263
+ try:
264
+ with _log_to_stderr():
265
+ summary = lake_build(
266
+ input,
267
+ lake,
268
+ sources=wanted,
269
+ workers=workers,
270
+ memory=memory,
271
+ threads=threads,
272
+ scratch=scratch,
273
+ force=force,
274
+ retry_errors=retry_errors,
275
+ check_disk=not no_disk_check,
276
+ prevent_sleep=not allow_sleep,
277
+ )
278
+ except KeyboardInterrupt:
279
+ err_console.print(
280
+ "[yellow]Interrompido.[/yellow] O que terminou ficou registrado; "
281
+ "rode o mesmo comando de novo para retomar."
282
+ )
283
+ raise typer.Exit(EXIT_INTERRUPTED) from None
284
+ except InsufficientDiskError as exc:
285
+ raise _fail(f"espaço em disco insuficiente: {exc}") from exc
286
+ except LakeBuildError as exc:
287
+ raise _fail(str(exc)) from exc
288
+
289
+ typer.echo(summary.format())
290
+ if summary.has_errors:
291
+ raise _fail("a construção terminou com erros (veja acima).")
292
+ console.print(f"[green]✓[/green] Lake em [dim]{lake}[/dim].", highlight=False)
293
+
294
+
295
+ @app.command("audit")
296
+ def audit(
297
+ lake: Annotated[
298
+ Path,
299
+ typer.Option(
300
+ "--lake",
301
+ help="Raiz do lake a auditar",
302
+ exists=True,
303
+ file_okay=False,
304
+ ),
305
+ ],
306
+ input: Annotated[
307
+ Path | None,
308
+ typer.Option(
309
+ "-i",
310
+ "--input",
311
+ help="Visão vigente (ou bruto) de onde o lake saiu; habilita as "
312
+ "checagens de proveniência e cobertura",
313
+ exists=True,
314
+ file_okay=False,
315
+ ),
316
+ ] = None,
317
+ ledger: Annotated[
318
+ Path | None,
319
+ typer.Option(
320
+ "--ledger",
321
+ help="Exportação do ledger (opcional) para conferir a proveniência",
322
+ exists=True,
323
+ dir_okay=False,
324
+ ),
325
+ ] = None,
326
+ sources: Annotated[
327
+ str | None,
328
+ typer.Option(
329
+ "--sources", help="Auditar só estas fontes (separadas por vírgula)"
330
+ ),
331
+ ] = None,
332
+ no_readers: Annotated[
333
+ bool,
334
+ typer.Option(
335
+ "--no-readers",
336
+ help="Não roda check_dataset (DuckDB, Polars, PyArrow); é a etapa cara",
337
+ ),
338
+ ] = False,
339
+ no_integrity: Annotated[
340
+ bool,
341
+ typer.Option(
342
+ "--no-integrity",
343
+ help="Lê só o rodapé dos Parquets, não o último row group",
344
+ ),
345
+ ] = False,
346
+ exceptions: Annotated[
347
+ Path | None,
348
+ typer.Option(
349
+ "--exceptions",
350
+ help="Arquivo texto com caminhos brutos (aceita padrões fnmatch) "
351
+ "sabidamente sem Parquet, como os corrompidos na fonte",
352
+ exists=True,
353
+ dir_okay=False,
354
+ ),
355
+ ] = None,
356
+ rehash: Annotated[
357
+ bool,
358
+ typer.Option(
359
+ "--rehash",
360
+ help="Recalcula o sha256 do bruto em vez de confiar no manifesto",
361
+ ),
362
+ ] = False,
363
+ workers: Annotated[
364
+ int | None,
365
+ typer.Option("--workers", min=1, help="Threads que leem os rodapés"),
366
+ ] = None,
367
+ json_stdout: Annotated[
368
+ bool,
369
+ typer.Option(
370
+ "--json", help="Imprime o relatório em JSON no stdout, no lugar do texto"
371
+ ),
372
+ ] = False,
373
+ json_file: Annotated[
374
+ Path | None,
375
+ typer.Option(
376
+ "--json-file",
377
+ help="Grava o relatório em JSON neste arquivo (o texto continua no "
378
+ "stdout, a menos que --json também seja dado)",
379
+ dir_okay=False,
380
+ ),
381
+ ] = None,
382
+ ) -> None:
383
+ """Audita o lake; sai com 0 se aprovado e com 1 se houver achados."""
384
+ try:
385
+ from quantilica.analytics.lake_audit import lake_audit
386
+ except ImportError as exc:
387
+ raise _missing_analytics("audit", exc) from None
388
+
389
+ wanted = _split_sources(sources)
390
+ known = _read_list(exceptions) if exceptions is not None else ()
391
+ try:
392
+ with _log_to_stderr():
393
+ report = lake_audit(
394
+ lake,
395
+ input_dir=input,
396
+ ledger=ledger,
397
+ sources=wanted,
398
+ readers=not no_readers,
399
+ integrity=not no_integrity,
400
+ known_exceptions=known,
401
+ rehash=rehash,
402
+ workers=workers,
403
+ )
404
+ except KeyboardInterrupt:
405
+ err_console.print("[yellow]Interrompido.[/yellow]")
406
+ raise typer.Exit(EXIT_INTERRUPTED) from None
407
+ except (OSError, ValueError) as exc:
408
+ raise _fail(str(exc)) from exc
409
+
410
+ if json_file is not None:
411
+ try:
412
+ json_file.write_text(report.to_json() + "\n", encoding="utf-8")
413
+ except OSError as exc:
414
+ raise _fail(f"não consegui gravar {json_file}: {exc}") from exc
415
+ err_console.print(f"Relatório JSON em [dim]{json_file}[/dim]", highlight=False)
416
+ typer.echo(report.to_json() if json_stdout else report.to_text())
417
+ if not report.ok:
418
+ raise typer.Exit(EXIT_FAILURE)