quantilica-cli 0.21.3__tar.gz → 0.22.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 (48) hide show
  1. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/CHANGELOG.md +51 -0
  2. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/PKG-INFO +3 -3
  3. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/pyproject.toml +7 -4
  4. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/src/quantilica/cli/catalog.py +5 -5
  5. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/src/quantilica/cli/health.py +27 -5
  6. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/src/quantilica/cli/registry.py +170 -28
  7. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/src/quantilica/cli/sources.py +286 -26
  8. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/tests/conftest.py +19 -0
  9. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/tests/test_registry_cli.py +5 -4
  10. quantilica_cli-0.22.0/tests/test_registry_v2.py +275 -0
  11. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/tests/test_sources_registro.py +12 -3
  12. quantilica_cli-0.22.0/tests/test_sources_registro_publico.py +336 -0
  13. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/.githooks/pre-commit +0 -0
  14. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/.githooks/pre-push +0 -0
  15. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/.github/workflows/public-hygiene.yml +0 -0
  16. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/.github/workflows/publish.yml +0 -0
  17. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/.github/workflows/test.yml +0 -0
  18. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/.gitignore +0 -0
  19. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/LICENSE +0 -0
  20. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/README.md +0 -0
  21. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/src/quantilica/cli/__init__.py +0 -0
  22. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/src/quantilica/cli/cli.py +0 -0
  23. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/src/quantilica/cli/docs.py +0 -0
  24. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/src/quantilica/cli/lake.py +0 -0
  25. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/src/quantilica/cli/manifests.py +0 -0
  26. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/src/quantilica/cli/sdk.py +0 -0
  27. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/src/quantilica/cli/ui.py +0 -0
  28. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/src/quantilica/py.typed +0 -0
  29. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/tests/__init__.py +0 -0
  30. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/tests/lake_build_fakes.py +0 -0
  31. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/tests/lake_fixtures.py +0 -0
  32. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/tests/test_catalog_cli.py +0 -0
  33. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/tests/test_catalog_registro.py +0 -0
  34. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/tests/test_catalog_sigla.py +0 -0
  35. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/tests/test_cli_apelidos.py +0 -0
  36. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/tests/test_docs_cli.py +0 -0
  37. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/tests/test_health.py +0 -0
  38. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/tests/test_lake_cli.py +0 -0
  39. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/tests/test_manifests.py +0 -0
  40. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/tests/test_package_hygiene.py +0 -0
  41. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/tests/test_sdk.py +0 -0
  42. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/tests/test_sdk_backfill.py +0 -0
  43. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/tests/test_sdk_force_probe.py +0 -0
  44. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/tests/test_sdk_mes_string.py +0 -0
  45. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/tests/test_sdk_onda_a2.py +0 -0
  46. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/tests/test_sdk_sync_exit.py +0 -0
  47. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/tests/test_sources.py +0 -0
  48. {quantilica_cli-0.21.3 → quantilica_cli-0.22.0}/tests/test_ui.py +0 -0
@@ -7,6 +7,57 @@ e este projeto adere ao [Semantic Versioning](https://semver.org/lang/pt-BR/).
7
7
 
8
8
  ## [Não lançado]
9
9
 
10
+ ## [0.22.0] - 2026-11-14
11
+
12
+ ### Adicionado
13
+
14
+ - `quantilica registry export` exporta o registro v2: `module` (do entry point),
15
+ `repo` (de `[project.urls] Repository`/`Source`; ausente, assume
16
+ `https://github.com/Quantilica/<distribuição>` e avisa no stderr), `version`
17
+ e `lake_entry_point`, mais o `sha256` do conteúdo. Os campos da v1 seguem com
18
+ o mesmo nome e formato.
19
+ - `registry export --ecossistema registro.toml` junta a camada dos fatos do
20
+ ecossistema (`docs_pasta`, `vitrine`, `ci_integracao`, `json_leve`, `mascote`,
21
+ `health_url`, `historico`), validada por
22
+ `quantilica.core.registry.carrega_registro_ecossistema`.
23
+ - `registry export --strict` também falha com distribuição fora da regra
24
+ `<id>-fetcher` que o `historico` não explica e, com `--ecossistema`, com
25
+ fetcher sem seção no arquivo.
26
+ - `registro_publico()`: baixa `index.quantilica.com/registry.json`, confere o
27
+ `sha256` e guarda em `~/.cache/quantilica/registry.json` (validade de 24 h;
28
+ vencido e sem rede, vale o cache). `--refresh` em `install`, `uninstall` e
29
+ `doctor` ignora o cache. A escrita é atômica (arquivo temporário único e
30
+ `os.replace`). Depois de uma falha de rede, um marcador `registry.fail` ao
31
+ lado do cache evita nova tentativa por 10 min, para que cada processo (em
32
+ especial o `quantilica health`) não espere o timeout de 5 s; `--refresh`
33
+ ignora o marcador.
34
+ - O registro público só é aceito com `version` 1 ou 2; qualquer outra conta como
35
+ "sem registro" (vale o cache e, depois, a reserva offline).
36
+
37
+ ### Alterado
38
+
39
+ - Piso de dependência `quantilica-core>=0.21.0` (e no extra `docs`): o cli importa
40
+ `IdentidadePacote` e o registro v2 do core 0.21.0.
41
+ - `resolve_dist` consulta, nesta ordem, o fetcher instalado, o registro público
42
+ (id, apelidos e ids do `historico`) e a reserva offline. `SOURCES_REGISTRY`
43
+ virou `_RESERVA_OFFLINE` (o nome antigo segue como alias), congelada: não
44
+ recebe entradas novas.
45
+ - `resolve_dist` de um nome antigo de distribuição renomeada (`sidra-fetcher`)
46
+ agora resolve para a nova (`ibge-sidra-fetcher`), com aviso no stderr. Antes
47
+ passava como veio, e `install` e `doctor` discordavam (ambos migram para a
48
+ nova). As wheels congeladas continuam no índice para reprodução.
49
+ - `DISTRIBUICOES_RENOMEADAS` passa a ser a reserva; os renomes vêm do
50
+ `historico` do registro público (`distribuicoes_renomeadas()`).
51
+ - `quantilica health` sonda os `health_url` do registro público (nome da sonda =
52
+ id do fetcher); `HEALTH_SOURCES` é a reserva, usada sem registro ou quando ele
53
+ não declara nenhuma sonda.
54
+
55
+ ## [0.21.4] - 2026-11-14
56
+
57
+ ### Alterado
58
+
59
+ - Lotes do `quantilica catalog sync` de até 90 MB (antes 4 MB): o portal 1.1.2 aceita 100 MiB na rota de sync. O lake atual volta a ir num envio só.
60
+
10
61
  ## [0.21.3] - 2026-11-13
11
62
 
12
63
  ### Corrigido
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: quantilica-cli
3
- Version: 0.21.3
3
+ Version: 0.22.0
4
4
  Summary: Unified CLI for Quantilica open data fetchers
5
5
  Author-email: "Komesu, D.K." <daniel@dkko.me>
6
6
  License-Expression: MIT
@@ -16,11 +16,11 @@ Classifier: Programming Language :: Python :: 3.12
16
16
  Classifier: Programming Language :: Python :: 3.13
17
17
  Classifier: Typing :: Typed
18
18
  Requires-Python: >=3.12
19
- Requires-Dist: quantilica-core>=0.20.0
19
+ Requires-Dist: quantilica-core>=0.21.0
20
20
  Requires-Dist: rich>=13.0.0
21
21
  Requires-Dist: typer>=0.15.0
22
22
  Provides-Extra: docs
23
- Requires-Dist: quantilica-core[docs]>=0.18.0; extra == 'docs'
23
+ Requires-Dist: quantilica-core[docs]>=0.21.0; extra == 'docs'
24
24
  Provides-Extra: lake
25
25
  Requires-Dist: pyarrow>=15.0.0; extra == 'lake'
26
26
  Requires-Dist: quantilica-analytics>=0.11.0; extra == 'lake'
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "quantilica-cli"
3
- version = "0.21.3"
3
+ version = "0.22.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,7 +20,7 @@ classifiers = [
20
20
  "Programming Language :: Python :: 3.13",
21
21
  ]
22
22
  dependencies = [
23
- "quantilica-core>=0.20.0",
23
+ "quantilica-core>=0.21.0",
24
24
  "rich>=13.0.0",
25
25
  "typer>=0.15.0",
26
26
  ]
@@ -29,7 +29,7 @@ dependencies = [
29
29
  # Motor de `quantilica lake build` e `quantilica lake audit`.
30
30
  lake = ["quantilica-analytics>=0.11.0", "pyarrow>=15.0.0"]
31
31
  # `quantilica docs`: verificação da documentação dos dados dos fetchers.
32
- docs = ["quantilica-core[docs]>=0.18.0"]
32
+ docs = ["quantilica-core[docs]>=0.21.0"]
33
33
 
34
34
  [project.scripts]
35
35
  quantilica = "quantilica.cli.cli:main"
@@ -60,7 +60,10 @@ build-backend = "hatchling.build"
60
60
  [tool.pytest.ini_options]
61
61
  testpaths = ["tests"]
62
62
  addopts = ["-p", "no:cacheprovider"]
63
- markers = ["indice_real: o teste usa a consulta real de publicação no índice"]
63
+ markers = [
64
+ "indice_real: o teste usa a consulta real de publicação no índice",
65
+ "registro_real: o teste exercita registro_publico (download e cache) em vez de isolá-lo",
66
+ ]
64
67
 
65
68
  [tool.ruff]
66
69
  line-length = 88
@@ -534,11 +534,11 @@ def send_catalog_payload(
534
534
  raise RuntimeError(f"Erro de conexão com o portal em {url}: {exc}") from exc
535
535
 
536
536
 
537
- # O portal recusa corpos acima de 5 MiB em /admin/catalog/sync (413). O lake
538
- # inteiro passa disso (8,5 MB em 13/11/2026), então o envio vai em lotes, cada
539
- # fonte inteira num lote só. O sync do portal é upsert: lotes não apagam nada
540
- # do que veio nos anteriores.
541
- LOTE_MAX_BYTES = 4_000_000
537
+ # O portal aceita até 100 MiB em /admin/catalog/sync (desde a 1.1.2; antes, 5 MiB)
538
+ # e o Cloudflare corta em 100 MB. Lotes de até 90 MB: o lake inteiro (8,5 MB em
539
+ # 13/11/2026) vai num lote só, e a divisão por fonte fica para quando crescer. O
540
+ # sync do portal é upsert: lotes não apagam nada do que veio nos anteriores.
541
+ LOTE_MAX_BYTES = 90_000_000
542
542
 
543
543
 
544
544
  def _tamanho_json(obj: Any) -> int:
@@ -22,7 +22,10 @@ console = Console()
22
22
  DEFAULT_TIMEOUT = 5.0
23
23
  USER_AGENT = "quantilica-cli (health)"
24
24
 
25
- # Lista canônica de fontes sondadas (nome, URL de sonda leve).
25
+ # Reserva offline das fontes sondadas (nome, URL de sonda leve). A lista vem do
26
+ # ``health_url`` de cada fetcher no registro público (``health_sources``); esta
27
+ # só vale sem registro (sem rede e sem cache) ou enquanto ele não declara
28
+ # nenhuma sonda. Não recebe entradas novas.
26
29
  HEALTH_SOURCES: list[tuple[str, str]] = [
27
30
  ("bcb", "https://api.bcb.gov.br/dados/serie/bcdata.sgs.1/dados?formato=json"),
28
31
  ("sidra", "https://servicodados.ibge.gov.br/api/v3/calendario"),
@@ -35,6 +38,25 @@ HEALTH_SOURCES: list[tuple[str, str]] = [
35
38
  ]
36
39
 
37
40
 
41
+ def health_sources() -> list[tuple[str, str]]:
42
+ """Fontes sondadas: ``health_url`` do registro público, senão a reserva.
43
+
44
+ No registro público o nome da sonda é o id do fetcher (``ibge-sidra``).
45
+ """
46
+ from quantilica.cli.sources import registro_publico
47
+
48
+ doc = registro_publico()
49
+ if doc is not None:
50
+ derivadas = sorted(
51
+ (f["id"], f["health_url"])
52
+ for f in doc.get("fetchers", [])
53
+ if isinstance(f.get("health_url"), str) and f["health_url"]
54
+ )
55
+ if derivadas:
56
+ return derivadas
57
+ return list(HEALTH_SOURCES)
58
+
59
+
38
60
  def _make_client(timeout: float) -> httpx2.Client:
39
61
  """Cria o cliente HTTP usado pelas sondas.
40
62
 
@@ -108,10 +130,11 @@ def _run_probes(timeout: float, fail_fast: bool) -> list[dict[str, object]]:
108
130
  Returns:
109
131
  A lista de resultados por fonte.
110
132
  """
133
+ sources = health_sources()
111
134
  with _make_client(timeout=timeout) as client:
112
135
  if fail_fast:
113
136
  results = []
114
- for name, url in HEALTH_SOURCES:
137
+ for name, url in sources:
115
138
  result = _probe(client, name, url)
116
139
  results.append(result)
117
140
  if result["status"] != "ok":
@@ -119,11 +142,10 @@ def _run_probes(timeout: float, fail_fast: bool) -> list[dict[str, object]]:
119
142
  return results
120
143
 
121
144
  with concurrent.futures.ThreadPoolExecutor(
122
- max_workers=len(HEALTH_SOURCES)
145
+ max_workers=max(len(sources), 1)
123
146
  ) as pool:
124
147
  futures = [
125
- (name, pool.submit(_probe, client, name, url))
126
- for name, url in HEALTH_SOURCES
148
+ (name, pool.submit(_probe, client, name, url)) for name, url in sources
127
149
  ]
128
150
  return [future.result() for _, future in futures]
129
151
 
@@ -1,7 +1,10 @@
1
1
  """Comando ``quantilica registry`` — o registro dos fetchers instalados.
2
2
 
3
3
  Descobre os entry points ``quantilica.fetchers`` (e ``quantilica.lake``) e monta
4
- o ``registry.json`` com :func:`quantilica.core.registry.build_registry`.
4
+ o ``registry.json`` (versão 2) com
5
+ :func:`quantilica.core.registry.build_registry`. A identidade de empacotamento
6
+ (distribuição, módulo, repositório, versão) sai dos metadados da distribuição
7
+ instalada; os fatos do ecossistema entram por ``--ecossistema registro.toml``.
5
8
  """
6
9
 
7
10
  from __future__ import annotations
@@ -9,22 +12,33 @@ from __future__ import annotations
9
12
  import contextlib
10
13
  import json
11
14
  import sys
12
- from dataclasses import dataclass
15
+ from dataclasses import dataclass, field
13
16
  from importlib.metadata import entry_points
17
+ from pathlib import Path
14
18
  from typing import Annotated, Any
15
19
 
16
20
  import typer
17
21
  from quantilica.core.registry import (
22
+ REGISTRY_VERSION,
18
23
  FetcherInfo,
24
+ IdentidadePacote,
25
+ RegistroEcossistema,
19
26
  RegistryError,
20
27
  build_registry,
28
+ carrega_registro_ecossistema,
29
+ check_identidade,
21
30
  check_unique,
31
+ registry_sha256,
22
32
  )
23
33
  from rich.console import Console
34
+ from rich.markup import escape
24
35
  from rich.table import Table
25
36
 
26
37
  FETCHER_GROUP = "quantilica.fetchers"
27
38
  LAKE_GROUP = "quantilica.lake"
39
+ REPO_URL_PADRAO = "https://github.com/Quantilica/{distribution}"
40
+ # Rótulos de ``[project.urls]`` que apontam o repositório, em ordem de preferência.
41
+ _REPO_LABELS = ("repository", "source", "source code")
28
42
 
29
43
  app = typer.Typer(
30
44
  help="Registro dos fetchers instalados (ids, apelidos, fatos da fonte).",
@@ -52,23 +66,44 @@ class DiscoveredFetcher:
52
66
  lake: bool = False
53
67
  lake_source_id: str | None = None
54
68
  error: str | None = None
69
+ module: str | None = None
70
+ repo: str | None = None
71
+ version: str | None = None
72
+ lake_entry_point: str | None = None
73
+ warnings: list[str] = field(default_factory=list)
55
74
 
56
- def to_dict(self) -> dict[str, Any]:
57
- """Info do fetcher mais os campos de execução."""
75
+ def identidade(self) -> IdentidadePacote:
76
+ """A identidade de empacotamento (camada 2 do registro)."""
77
+ return IdentidadePacote(
78
+ distribution=self.distribution,
79
+ module=self.module,
80
+ repo=self.repo,
81
+ entry_point=self.entry_point,
82
+ lake_entry_point=self.lake_entry_point,
83
+ source_id=self.source_id,
84
+ lake_source_id=self.lake_source_id,
85
+ version=self.version,
86
+ )
87
+
88
+ def extras(self) -> dict[str, Any]:
89
+ """Campos de execução que acompanham a identidade no registro."""
58
90
  return {
59
- **self.info.to_dict(),
60
91
  "info_declared": self.info_declared,
61
- "entry_point": self.entry_point,
62
- "distribution": self.distribution,
63
- "source_id": self.source_id,
64
92
  "freshness_policy": self.freshness_policy,
65
93
  "default_output": self.default_output,
66
94
  "groups": self.groups,
67
95
  "lake": self.lake,
68
- "lake_source_id": self.lake_source_id,
69
96
  "error": self.error,
70
97
  }
71
98
 
99
+ def to_dict(self) -> dict[str, Any]:
100
+ """Info do fetcher, identidade e campos de execução."""
101
+ return {
102
+ **self.info.to_dict(),
103
+ **self.identidade().to_dict(),
104
+ **self.extras(),
105
+ }
106
+
72
107
 
73
108
  def _fallback_info(ep_name: str, dist: str | None) -> FetcherInfo:
74
109
  from quantilica.cli.sdk import derive_fetcher_info
@@ -86,18 +121,57 @@ def _find_fetcher_app(obj: Any) -> Any | None:
86
121
  return candidate if isinstance(candidate, FetcherApp) else None
87
122
 
88
123
 
124
+ def _project_urls(dist: Any) -> dict[str, str]:
125
+ """``[project.urls]`` da distribuição, com o rótulo em minúsculas."""
126
+ try:
127
+ raw = dist.metadata.get_all("Project-URL") or []
128
+ except Exception:
129
+ return {}
130
+ urls: dict[str, str] = {}
131
+ for item in raw:
132
+ label, sep, url = str(item).partition(",")
133
+ if sep and url.strip():
134
+ urls.setdefault(label.strip().lower(), url.strip())
135
+ return urls
136
+
137
+
138
+ def _module_of(ep: Any) -> str | None:
139
+ """Pacote de topo do entry point (``a_fetcher.plugin:app`` -> ``a_fetcher``)."""
140
+ value = getattr(ep, "value", None)
141
+ if not isinstance(value, str) or not value.strip():
142
+ return None
143
+ return value.partition(":")[0].strip().split(".")[0] or None
144
+
145
+
146
+ def _repo_of(dist: Any, name: str | None) -> tuple[str | None, str | None]:
147
+ """URL do repositório e o aviso, quando cai no padrão."""
148
+ if name is None:
149
+ return None, None
150
+ urls = _project_urls(dist)
151
+ for label in _REPO_LABELS:
152
+ if label in urls:
153
+ return urls[label].rstrip("/"), None
154
+ return (
155
+ REPO_URL_PADRAO.format(distribution=name),
156
+ f"{name}: sem [project.urls] Repository/Source; repo assumido como "
157
+ f"{REPO_URL_PADRAO.format(distribution=name)}",
158
+ )
159
+
160
+
89
161
  def discover_fetchers() -> list[DiscoveredFetcher]:
90
162
  """Carrega os entry points de fetchers e devolve o que cada um declara.
91
163
 
92
164
  Nunca levanta por causa de um plugin quebrado: o erro vai em ``error``.
93
165
  A saída padrão durante o carregamento é desviada para o stderr (módulos de
94
- fetchers podem imprimir ao importar).
166
+ fetchers podem imprimir ao importar). A identidade de empacotamento
167
+ (``module``, ``repo``, ``version``) sai dos metadados da distribuição.
95
168
  """
96
169
  lake_eps = list(entry_points(group=LAKE_GROUP))
97
170
  found: list[DiscoveredFetcher] = []
98
171
  with contextlib.redirect_stdout(sys.stderr):
99
172
  for ep in entry_points(group=FETCHER_GROUP):
100
- dist = ep.dist.name if ep.dist is not None else None
173
+ dist_obj = ep.dist
174
+ dist = dist_obj.name if dist_obj is not None else None
101
175
  try:
102
176
  fetcher = _find_fetcher_app(ep.load())
103
177
  error = None
@@ -127,6 +201,11 @@ def discover_fetchers() -> list[DiscoveredFetcher]:
127
201
  distribution=dist,
128
202
  error=error,
129
203
  )
204
+ item.module = _module_of(ep)
205
+ item.version = getattr(dist_obj, "version", None)
206
+ item.repo, aviso = _repo_of(dist_obj, dist)
207
+ if aviso:
208
+ item.warnings.append(aviso)
130
209
  for lep in lake_eps:
131
210
  ldist = lep.dist.name if lep.dist is not None else None
132
211
  if (dist is not None and ldist == dist) or lep.name in (
@@ -134,23 +213,41 @@ def discover_fetchers() -> list[DiscoveredFetcher]:
134
213
  ):
135
214
  item.lake = True
136
215
  item.lake_source_id = lep.name
216
+ item.lake_entry_point = lep.name
137
217
  break
138
218
  found.append(item)
139
219
  return found
140
220
 
141
221
 
142
- def build_export(found: list[DiscoveredFetcher]) -> tuple[dict[str, Any], str | None]:
143
- """Monta o registro; devolve também a mensagem de duplicidade, se houver."""
222
+ def build_export(
223
+ found: list[DiscoveredFetcher],
224
+ ecossistema: dict[str, RegistroEcossistema] | None = None,
225
+ ) -> tuple[dict[str, Any], str | None]:
226
+ """Monta o registro v2; devolve também a mensagem de duplicidade, se houver.
227
+
228
+ Com duplicidade de id/apelido o registro sai sem a camada do ecossistema
229
+ (o ``--strict`` falha de qualquer forma).
230
+ """
144
231
  infos = [d.info for d in found]
145
- problem: str | None = None
146
232
  try:
147
- registry = build_registry(infos)
233
+ check_unique(infos)
148
234
  except RegistryError as exc:
149
- problem = str(exc)
150
- registry = {"version": 1, "fetchers": []}
151
- extras = sorted(found, key=lambda d: (d.info.id, d.entry_point))
152
- registry["fetchers"] = [d.to_dict() for d in extras]
153
- return registry, problem
235
+ registry = {
236
+ "version": REGISTRY_VERSION,
237
+ "fetchers": [
238
+ d.to_dict()
239
+ for d in sorted(found, key=lambda d: (d.info.id, d.entry_point))
240
+ ],
241
+ }
242
+ registry["sha256"] = registry_sha256(registry)
243
+ return registry, str(exc)
244
+ registry = build_registry(
245
+ infos,
246
+ {d.info.id: d.identidade() for d in found},
247
+ ecossistema,
248
+ {d.info.id: d.extras() for d in found},
249
+ )
250
+ return registry, None
154
251
 
155
252
 
156
253
  @app.command("export")
@@ -162,21 +259,48 @@ def cmd_export(
162
259
  bool,
163
260
  typer.Option(
164
261
  "--strict",
165
- help="Falha se algum fetcher não declarar info, não carregar "
166
- "ou houver id/apelido duplicado.",
262
+ help="Falha se algum fetcher não declarar info, não carregar, "
263
+ "houver id/apelido duplicado, a distribuição fugir da regra "
264
+ "<id>-fetcher sem historico que a explique ou (com --ecossistema) "
265
+ "faltar a seção de algum fetcher.",
167
266
  ),
168
267
  ] = False,
268
+ ecossistema: Annotated[
269
+ Path | None,
270
+ typer.Option(
271
+ "--ecossistema",
272
+ help="registro.toml com os fatos do ecossistema (docs_pasta, "
273
+ "vitrine, historico...); junta a terceira camada ao registro.",
274
+ dir_okay=False,
275
+ ),
276
+ ] = None,
169
277
  ) -> None:
170
278
  """Exporta o registro dos fetchers instalados (entry points)."""
171
279
  found = discover_fetchers()
172
- registry, duplicate = build_export(found)
173
- if duplicate is None:
174
- with contextlib.suppress(RegistryError):
175
- check_unique(d.info for d in found)
280
+ err = Console(stderr=True)
281
+ eco: dict[str, RegistroEcossistema] | None = None
282
+ if ecossistema is not None:
283
+ try:
284
+ eco = carrega_registro_ecossistema(ecossistema)
285
+ registry, duplicate = build_export(found, eco)
286
+ except RegistryError as exc:
287
+ err.print(f"[red]Registro do ecossistema:[/red] {exc}", markup=True)
288
+ raise typer.Exit(1) from exc
289
+ else:
290
+ registry, duplicate = build_export(found)
176
291
  undeclared = [d.info.id for d in found if not d.info_declared]
177
292
  errors = [f"{d.entry_point}: {d.error}" for d in found if d.error]
293
+ fora_da_regra = check_identidade(
294
+ (d.info for d in found),
295
+ {d.info.id: d.identidade() for d in found},
296
+ eco,
297
+ )
298
+ sem_secao = (
299
+ sorted(d.info.id for d in found if d.info.id not in eco)
300
+ if eco is not None
301
+ else []
302
+ )
178
303
 
179
- err = Console(stderr=True)
180
304
  if as_json:
181
305
  sys.stdout.write(json.dumps(registry, ensure_ascii=False, indent=2) + "\n")
182
306
  else:
@@ -212,6 +336,24 @@ def cmd_export(
212
336
  err.print(f"[red]Duplicidade:[/red] {duplicate}", markup=True)
213
337
  for line in errors:
214
338
  err.print(f"[red]Falha ao carregar[/red] {line}", markup=True, highlight=False)
339
+ for d in found:
340
+ for aviso in d.warnings:
341
+ err.print(
342
+ f"[yellow]Aviso:[/yellow] {escape(aviso)}",
343
+ markup=True,
344
+ highlight=False,
345
+ )
346
+ for line in fora_da_regra:
347
+ err.print(
348
+ f"[red]Identidade:[/red] {escape(line)}", markup=True, highlight=False
349
+ )
350
+ if sem_secao:
351
+ err.print(
352
+ f"[yellow]{len(sem_secao)} fetcher(s) sem seção no registro do "
353
+ "ecossistema:[/yellow] " + ", ".join(sem_secao),
354
+ markup=True,
355
+ highlight=False,
356
+ )
215
357
  if undeclared:
216
358
  err.print(
217
359
  f"[yellow]{len(undeclared)} fetcher(s) sem info declarada:[/yellow] "
@@ -219,7 +361,7 @@ def cmd_export(
219
361
  markup=True,
220
362
  highlight=False,
221
363
  )
222
- if strict and (duplicate or undeclared or errors):
364
+ if strict and (duplicate or undeclared or errors or fora_da_regra or sem_secao):
223
365
  raise typer.Exit(1)
224
366
 
225
367