konecty-sdk-python 2.3.1__py3-none-any.whl → 2.4.0__py3-none-any.whl
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.
- KonectySdkPython/cli/__init__.py +2 -0
- KonectySdkPython/cli/backup.py +8 -3
- KonectySdkPython/cli/metas/__init__.py +4 -0
- KonectySdkPython/cli/metas/aplicar.py +249 -0
- KonectySdkPython/cli/metas/artefato.py +115 -0
- KonectySdkPython/cli/metas/arvore.py +120 -0
- KonectySdkPython/cli/metas/comandos.py +192 -0
- KonectySdkPython/cli/metas/deriva.py +76 -0
- KonectySdkPython/cli/metas/diff.py +116 -0
- KonectySdkPython/cli/metas/erros.py +16 -0
- KonectySdkPython/cli/metas/gerar_delta.py +166 -0
- KonectySdkPython/cli/metas/linter.py +167 -0
- KonectySdkPython/cli/metas/montar.py +449 -0
- KonectySdkPython/cli/metas/patch.py +91 -0
- KonectySdkPython/cli/metas/repositorio.py +101 -0
- KonectySdkPython/lib/client.py +112 -2
- KonectySdkPython/lib/exceptions.py +49 -1
- KonectySdkPython/lib/feature_types/pivot_jobs.py +52 -0
- KonectySdkPython/lib/http.py +23 -1
- KonectySdkPython/lib/services/admin.py +122 -8
- KonectySdkPython/lib/services/mcp_status.py +43 -0
- KonectySdkPython/lib/services/pivot_jobs.py +97 -0
- {konecty_sdk_python-2.3.1.dist-info → konecty_sdk_python-2.4.0.dist-info}/METADATA +11 -1
- {konecty_sdk_python-2.3.1.dist-info → konecty_sdk_python-2.4.0.dist-info}/RECORD +26 -10
- {konecty_sdk_python-2.3.1.dist-info → konecty_sdk_python-2.4.0.dist-info}/WHEEL +1 -1
- {konecty_sdk_python-2.3.1.dist-info → konecty_sdk_python-2.4.0.dist-info}/entry_points.txt +0 -0
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"""Comandos `konecty-cli metas ...`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import logging
|
|
7
|
+
import os
|
|
8
|
+
import tempfile
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Optional
|
|
11
|
+
|
|
12
|
+
import click
|
|
13
|
+
|
|
14
|
+
from ...lib.client import KonectyClient
|
|
15
|
+
|
|
16
|
+
from .aplicar import aplicar
|
|
17
|
+
from .deriva import deriva
|
|
18
|
+
from .diff import diff
|
|
19
|
+
from .erros import AplicacaoRecusadaError, LoteRecusadoError, MetasInvalidasError
|
|
20
|
+
from .gerar_delta import gerar_delta
|
|
21
|
+
from .linter import linter
|
|
22
|
+
from .montar import BASE_REPO_PADRAO, montar, obter_base
|
|
23
|
+
from .repositorio import ler_config
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@click.group(name="metas")
|
|
27
|
+
def metas_group() -> None:
|
|
28
|
+
"""Metadado de base + delta por cliente: montar, gerar-delta, linter, diff, aplicar, deriva."""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@metas_group.command(name="montar")
|
|
32
|
+
@click.argument("repo", type=click.Path(exists=True, file_okay=False, path_type=Path))
|
|
33
|
+
@click.option("--ambiente", required=True, type=click.Choice(["dev", "prod"]), help="Lê env/<ambiente>.env")
|
|
34
|
+
@click.option("--saida", required=True, type=click.Path(file_okay=False, path_type=Path), help="Pasta do artefato")
|
|
35
|
+
@click.option("--versao", default=None, help="Versão do cliente no manifesto (padrão: 'versao' do metadados.yaml)")
|
|
36
|
+
@click.option(
|
|
37
|
+
"--base-dir",
|
|
38
|
+
default=None,
|
|
39
|
+
type=click.Path(exists=True, file_okay=False, path_type=Path),
|
|
40
|
+
help="metadata/base já extraída (pula o download da tag)",
|
|
41
|
+
)
|
|
42
|
+
@click.option("--base-repo", default=BASE_REPO_PADRAO, show_default=True, help="Repositório Git com as tags base-metas/*")
|
|
43
|
+
@click.option("--tar", "gerar_tar", is_flag=True, help="Também gera <cliente>-<versão>-<ambiente>.tar.gz")
|
|
44
|
+
@click.option(
|
|
45
|
+
"--arvore",
|
|
46
|
+
default=None,
|
|
47
|
+
type=click.Path(file_okay=False, path_type=Path),
|
|
48
|
+
help="Também grava a montagem no layout da base (<Módulo>/document.json, hook/*.js...), para testes",
|
|
49
|
+
)
|
|
50
|
+
def montar_command(
|
|
51
|
+
repo: Path,
|
|
52
|
+
ambiente: str,
|
|
53
|
+
saida: Path,
|
|
54
|
+
versao: Optional[str],
|
|
55
|
+
base_dir: Optional[Path],
|
|
56
|
+
base_repo: str,
|
|
57
|
+
gerar_tar: bool,
|
|
58
|
+
arvore: Optional[Path],
|
|
59
|
+
) -> None:
|
|
60
|
+
"""Monta o artefato (itens.json, namespace.json, manifesto.json) de REPO."""
|
|
61
|
+
try:
|
|
62
|
+
manifesto = montar(
|
|
63
|
+
repo, ambiente, saida, versao=versao, base_dir=base_dir, base_repo=base_repo, tar=gerar_tar, arvore=arvore
|
|
64
|
+
)
|
|
65
|
+
except MetasInvalidasError as erro:
|
|
66
|
+
raise click.ClickException(str(erro)) from None
|
|
67
|
+
click.echo(
|
|
68
|
+
f"artefato {manifesto['cliente']} {manifesto['versaoCliente']} ({ambiente}) em {saida}: "
|
|
69
|
+
f"{len(manifesto['documentos'])} documentos, delta {manifesto['deltaBytes']} bytes "
|
|
70
|
+
f"({manifesto['deltaPct']}%), sha256 {manifesto['sha256Total']}"
|
|
71
|
+
)
|
|
72
|
+
if arvore is not None:
|
|
73
|
+
click.echo(f"árvore montada em {arvore}")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@metas_group.command(name="gerar-delta")
|
|
77
|
+
@click.argument("base_dir", type=click.Path(exists=True, file_okay=False, path_type=Path))
|
|
78
|
+
@click.argument("copia", type=click.Path(exists=True, file_okay=False, path_type=Path))
|
|
79
|
+
@click.option("--saida", required=True, type=click.Path(file_okay=False, path_type=Path), help="Repositório do cliente")
|
|
80
|
+
@click.option("--cliente", required=True, help="Nome do cliente no metadados.yaml")
|
|
81
|
+
@click.option("--base", "base_tag", required=True, help="Tag da base em uso (base-metas/vX.Y.Z)")
|
|
82
|
+
@click.option("--konecty", default=None, help="Versão mínima do Konecty (ex.: '>=3.19.0')")
|
|
83
|
+
def gerar_delta_command(
|
|
84
|
+
base_dir: Path, copia: Path, saida: Path, cliente: str, base_tag: str, konecty: Optional[str]
|
|
85
|
+
) -> None:
|
|
86
|
+
"""Migra a cópia completa COPIA para delta sobre BASE_DIR (metadata/base daquela tag)."""
|
|
87
|
+
try:
|
|
88
|
+
resumo = gerar_delta(base_dir, copia, saida, cliente=cliente, base_tag=base_tag, konecty=konecty)
|
|
89
|
+
except MetasInvalidasError as erro:
|
|
90
|
+
raise click.ClickException(str(erro)) from None
|
|
91
|
+
click.echo(
|
|
92
|
+
f"delta em {saida}: {len(resumo.patches)} patches, {len(resumo.novos)} metas novos, "
|
|
93
|
+
f"{len(resumo.hooks)} hooks, {len(resumo.modulos)} módulos só do cliente, "
|
|
94
|
+
f"{len(resumo.removidos)} removidos, {resumo.iguais} iguais à base"
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@metas_group.command(name="linter")
|
|
99
|
+
@click.argument("repo", type=click.Path(exists=True, file_okay=False, path_type=Path))
|
|
100
|
+
@click.option(
|
|
101
|
+
"--base-dir",
|
|
102
|
+
default=None,
|
|
103
|
+
type=click.Path(exists=True, file_okay=False, path_type=Path),
|
|
104
|
+
help="metadata/base já extraída (pula o download da tag)",
|
|
105
|
+
)
|
|
106
|
+
@click.option("--base-repo", default=BASE_REPO_PADRAO, show_default=True, help="Repositório Git com as tags base-metas/*")
|
|
107
|
+
def linter_command(repo: Path, base_dir: Optional[Path], base_repo: str) -> None:
|
|
108
|
+
"""Acusa delta redundante e conflito com a base. Sai com 1 se houver erro."""
|
|
109
|
+
try:
|
|
110
|
+
with tempfile.TemporaryDirectory(prefix="metas-base-") as temporario:
|
|
111
|
+
raiz = base_dir or obter_base(ler_config(repo).base, base_repo, Path(temporario))
|
|
112
|
+
achados = linter(repo, raiz)
|
|
113
|
+
except MetasInvalidasError as erro:
|
|
114
|
+
raise click.ClickException(str(erro)) from None
|
|
115
|
+
for achado in achados:
|
|
116
|
+
click.echo(str(achado))
|
|
117
|
+
erros = sum(1 for achado in achados if achado.nivel == "erro")
|
|
118
|
+
avisos = len(achados) - erros
|
|
119
|
+
click.echo(f"linter: {erros} erros, {avisos} avisos")
|
|
120
|
+
if erros:
|
|
121
|
+
raise SystemExit(1)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@metas_group.command(name="diff")
|
|
125
|
+
@click.argument("artefato_a", type=click.Path(exists=True, file_okay=False, path_type=Path))
|
|
126
|
+
@click.argument("artefato_b", type=click.Path(exists=True, file_okay=False, path_type=Path))
|
|
127
|
+
@click.option("--markdown", is_flag=True, help="Saída em Markdown, para comentário de PR")
|
|
128
|
+
def diff_command(artefato_a: Path, artefato_b: Path, markdown: bool) -> None:
|
|
129
|
+
"""Diff de ARTEFATO_A para ARTEFATO_B, por documento e por chave."""
|
|
130
|
+
try:
|
|
131
|
+
click.echo(diff(artefato_a, artefato_b, markdown=markdown), nl=False)
|
|
132
|
+
except MetasInvalidasError as erro:
|
|
133
|
+
raise click.ClickException(str(erro)) from None
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _client_do_ambiente(url: Optional[str]) -> KonectyClient:
|
|
137
|
+
url = url or os.environ.get("KONECTY_URL")
|
|
138
|
+
token = os.environ.get("KONECTY_TOKEN")
|
|
139
|
+
if not url:
|
|
140
|
+
raise click.ClickException("informe --url ou KONECTY_URL")
|
|
141
|
+
if not token:
|
|
142
|
+
raise click.ClickException("KONECTY_TOKEN não definido")
|
|
143
|
+
return KonectyClient(base_url=url, token=token)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _configurar_log() -> None:
|
|
147
|
+
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
@metas_group.command(name="aplicar")
|
|
151
|
+
@click.argument("pasta", type=click.Path(exists=True, file_okay=False, path_type=Path))
|
|
152
|
+
@click.option("--url", default=None, help="URL do Konecty (padrão: KONECTY_URL)")
|
|
153
|
+
def aplicar_command(pasta: Path, url: Optional[str]) -> None:
|
|
154
|
+
"""Aplica o artefato de PASTA no tenant (token em KONECTY_TOKEN, ambiente em TENANT_ENV).
|
|
155
|
+
|
|
156
|
+
Sai com 2 quando o sha256 ou o ambiente não conferem (nada é enviado) e com 1 quando o
|
|
157
|
+
Konecty recusa o lote ou não responde depois das tentativas.
|
|
158
|
+
"""
|
|
159
|
+
_configurar_log()
|
|
160
|
+
client = _client_do_ambiente(url)
|
|
161
|
+
try:
|
|
162
|
+
resultado = asyncio.run(
|
|
163
|
+
aplicar(pasta, client, tenant_env=os.environ.get("TENANT_ENV"), origem=os.environ.get("GIT_COMMIT"))
|
|
164
|
+
)
|
|
165
|
+
except AplicacaoRecusadaError as erro:
|
|
166
|
+
click.echo(f"Erro: {erro}", err=True)
|
|
167
|
+
raise SystemExit(2) from None
|
|
168
|
+
except (LoteRecusadoError, MetasInvalidasError) as erro:
|
|
169
|
+
raise click.ClickException(str(erro)) from None
|
|
170
|
+
click.echo(
|
|
171
|
+
f"aplicados={resultado.aplicados} criados={len(resultado.criados)} "
|
|
172
|
+
f"alterados={len(resultado.atualizados)} metadataVersion={'gravado' if resultado.versao_gravada else 'inalterado'}"
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
@metas_group.command(name="deriva")
|
|
177
|
+
@click.argument("pasta", type=click.Path(exists=True, file_okay=False, path_type=Path))
|
|
178
|
+
@click.option("--url", default=None, help="URL do Konecty (padrão: KONECTY_URL)")
|
|
179
|
+
@click.option("--tenant", default=None, help="Rótulo tenant da métrica (padrão: <cliente>-<ambiente>)")
|
|
180
|
+
def deriva_command(pasta: Path, url: Optional[str], tenant: Optional[str]) -> None:
|
|
181
|
+
"""Mede a divergência entre o tenant e o artefato de PASTA, só com dryRun (nunca escreve)."""
|
|
182
|
+
_configurar_log()
|
|
183
|
+
client = _client_do_ambiente(url)
|
|
184
|
+
try:
|
|
185
|
+
resultado = asyncio.run(deriva(pasta, client, tenant_env=os.environ.get("TENANT_ENV"), tenant=tenant))
|
|
186
|
+
except AplicacaoRecusadaError as erro:
|
|
187
|
+
click.echo(f"Erro: {erro}", err=True)
|
|
188
|
+
raise SystemExit(2) from None
|
|
189
|
+
except (LoteRecusadoError, MetasInvalidasError) as erro:
|
|
190
|
+
raise click.ClickException(str(erro)) from None
|
|
191
|
+
for linha in resultado.linhas():
|
|
192
|
+
click.echo(linha)
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""`metas deriva`: o quanto o tenant diverge do artefato aplicado (MBD-14). Nunca escreve.
|
|
2
|
+
|
|
3
|
+
Faz só o `dryRun` do lote (`hookMode: 'replace'`, como o `aplicar`) e publica:
|
|
4
|
+
|
|
5
|
+
- a métrica como linha de log no formato de exposição do Prometheus, que o Loki transforma em
|
|
6
|
+
métrica: `konecty_metadata_drift_documents{tenant="<tenant>"} <n>`;
|
|
7
|
+
- a lista por documento e chave (documento ausente no tenant conta como divergente).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import asyncio
|
|
13
|
+
import logging
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any, Dict, List, Optional, Sequence
|
|
17
|
+
|
|
18
|
+
from ...lib.exceptions import KonectyMetaBulkError
|
|
19
|
+
from .aplicar import ESPERAS_PADRAO, Dormir, chamar_com_retry, conferir_artefato, erro_do_lote
|
|
20
|
+
from .artefato import ler_artefato
|
|
21
|
+
|
|
22
|
+
logger = logging.getLogger("konecty.cli.metas.deriva")
|
|
23
|
+
|
|
24
|
+
METRICA = "konecty_metadata_drift_documents"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class Deriva:
|
|
29
|
+
tenant: str
|
|
30
|
+
ausentes: List[str] = field(default_factory=list)
|
|
31
|
+
divergentes: Dict[str, List[str]] = field(default_factory=dict)
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def documentos(self) -> int:
|
|
35
|
+
return len(self.ausentes) + len(self.divergentes)
|
|
36
|
+
|
|
37
|
+
def linha_metrica(self) -> str:
|
|
38
|
+
rotulo = self.tenant.replace("\\", "\\\\").replace('"', '\\"')
|
|
39
|
+
return f'{METRICA}{{tenant="{rotulo}"}} {self.documentos}'
|
|
40
|
+
|
|
41
|
+
def linhas(self) -> List[str]:
|
|
42
|
+
saida = [self.linha_metrica()]
|
|
43
|
+
saida += [f"ausente no tenant: {meta_id}" for meta_id in self.ausentes]
|
|
44
|
+
saida += [f"diverge: {meta_id}: {', '.join(chaves)}" for meta_id, chaves in self.divergentes.items()]
|
|
45
|
+
return saida
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
async def deriva(
|
|
49
|
+
pasta: Path,
|
|
50
|
+
client: Any,
|
|
51
|
+
*,
|
|
52
|
+
tenant_env: Optional[str],
|
|
53
|
+
tenant: Optional[str] = None,
|
|
54
|
+
esperas: Sequence[float] = ESPERAS_PADRAO,
|
|
55
|
+
dormir: Optional[Dormir] = None,
|
|
56
|
+
) -> Deriva:
|
|
57
|
+
artefato = ler_artefato(Path(pasta))
|
|
58
|
+
conferir_artefato(artefato, tenant_env)
|
|
59
|
+
nome = tenant or f"{artefato.manifesto.get('cliente')}-{artefato.manifesto.get('ambiente')}"
|
|
60
|
+
todos = [str(item["_id"]) for item in artefato.itens]
|
|
61
|
+
try:
|
|
62
|
+
resposta = await chamar_com_retry(
|
|
63
|
+
lambda: client.apply_meta_bulk(artefato.itens, dry_run=True, hook_mode="replace"),
|
|
64
|
+
"dryRun da deriva",
|
|
65
|
+
esperas,
|
|
66
|
+
dormir or asyncio.sleep,
|
|
67
|
+
)
|
|
68
|
+
except KonectyMetaBulkError as erro:
|
|
69
|
+
raise erro_do_lote(erro, todos, artefato.manifesto.get("origens") or {}) from None
|
|
70
|
+
plano = resposta.get("plan") or {}
|
|
71
|
+
resultado = Deriva(tenant=nome, ausentes=sorted(plano.get("created") or []))
|
|
72
|
+
for atualizado in sorted(plano.get("updated") or [], key=lambda u: str(u.get("_id"))):
|
|
73
|
+
resultado.divergentes[str(atualizado.get("_id"))] = list(atualizado.get("keys") or [])
|
|
74
|
+
for linha in resultado.linhas():
|
|
75
|
+
logger.info("%s", linha)
|
|
76
|
+
return resultado
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""`metas diff`: compara dois artefatos por documento e por chave (MBD-04).
|
|
2
|
+
|
|
3
|
+
As chaves são as de topo do meta; `fields` desce um nível (`fields.<campo>`), que é onde mora a
|
|
4
|
+
maior parte das mudanças. Hooks aparecem pelo nome do campo (`scriptAfterSave`), marcados como hook.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any, Dict, List
|
|
12
|
+
|
|
13
|
+
from .arvore import HOOK_FIELDS
|
|
14
|
+
from .artefato import Artefato, ler_artefato
|
|
15
|
+
|
|
16
|
+
CHAVES_DETALHADAS = ("fields",)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class Diferenca:
|
|
21
|
+
criados: List[str] = field(default_factory=list)
|
|
22
|
+
removidos: List[str] = field(default_factory=list)
|
|
23
|
+
alterados: Dict[str, List[str]] = field(default_factory=dict)
|
|
24
|
+
namespace: List[str] = field(default_factory=list)
|
|
25
|
+
|
|
26
|
+
@property
|
|
27
|
+
def vazia(self) -> bool:
|
|
28
|
+
return not (self.criados or self.removidos or self.alterados or self.namespace)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def chaves_alteradas(a: Dict[str, Any], b: Dict[str, Any]) -> List[str]:
|
|
32
|
+
chaves: List[str] = []
|
|
33
|
+
for chave in sorted(set(a) | set(b)):
|
|
34
|
+
if chave in a and chave in b and a[chave] == b[chave] and type(a[chave]) is type(b[chave]):
|
|
35
|
+
continue
|
|
36
|
+
va, vb = a.get(chave), b.get(chave)
|
|
37
|
+
if chave in CHAVES_DETALHADAS and isinstance(va, dict) and isinstance(vb, dict):
|
|
38
|
+
for sub in sorted(set(va) | set(vb)):
|
|
39
|
+
if va.get(sub) != vb.get(sub) or (sub in va) != (sub in vb):
|
|
40
|
+
chaves.append(f"{chave}.{sub}")
|
|
41
|
+
continue
|
|
42
|
+
chaves.append(chave)
|
|
43
|
+
return chaves
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def comparar(a: Artefato, b: Artefato) -> Diferenca:
|
|
47
|
+
ia, ib = a.por_id, b.por_id
|
|
48
|
+
diferenca = Diferenca(
|
|
49
|
+
criados=sorted(set(ib) - set(ia)),
|
|
50
|
+
removidos=sorted(set(ia) - set(ib)),
|
|
51
|
+
namespace=chaves_alteradas(a.namespace, b.namespace),
|
|
52
|
+
)
|
|
53
|
+
for meta_id in sorted(set(ia) & set(ib)):
|
|
54
|
+
chaves = chaves_alteradas(ia[meta_id], ib[meta_id])
|
|
55
|
+
if chaves:
|
|
56
|
+
diferenca.alterados[meta_id] = chaves
|
|
57
|
+
return diferenca
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _rotulo(chave: str) -> str:
|
|
61
|
+
return f"{chave} (hook)" if chave in HOOK_FIELDS else chave
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _versao(artefato: Artefato) -> str:
|
|
65
|
+
m = artefato.manifesto
|
|
66
|
+
return f"{m.get('cliente', '?')} {m.get('versaoCliente', '?')} sobre {m.get('base', '?')} ({m.get('ambiente', '?')})"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def formatar_texto(diferenca: Diferenca, a: Artefato, b: Artefato) -> str:
|
|
70
|
+
linhas = [f"de: {_versao(a)}", f"para: {_versao(b)}"]
|
|
71
|
+
if diferenca.vazia:
|
|
72
|
+
linhas.append("sem diferença")
|
|
73
|
+
return "\n".join(linhas) + "\n"
|
|
74
|
+
linhas += [f"+ {meta_id}" for meta_id in diferenca.criados]
|
|
75
|
+
linhas += [f"- {meta_id}" for meta_id in diferenca.removidos]
|
|
76
|
+
linhas += [
|
|
77
|
+
f"~ {meta_id}: {', '.join(_rotulo(c) for c in chaves)}" for meta_id, chaves in diferenca.alterados.items()
|
|
78
|
+
]
|
|
79
|
+
if diferenca.namespace:
|
|
80
|
+
linhas.append(f"~ Namespace: {', '.join(diferenca.namespace)}")
|
|
81
|
+
linhas.append(
|
|
82
|
+
f"{len(diferenca.criados)} criados, {len(diferenca.removidos)} removidos, "
|
|
83
|
+
f"{len(diferenca.alterados)} alterados" + (", Namespace alterado" if diferenca.namespace else "")
|
|
84
|
+
)
|
|
85
|
+
return "\n".join(linhas) + "\n"
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _celula(texto: str) -> str:
|
|
89
|
+
return texto.replace("|", "\\|")
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def formatar_markdown(diferenca: Diferenca, a: Artefato, b: Artefato) -> str:
|
|
93
|
+
linhas = ["### Diff do metadado montado", "", f"- de: `{_versao(a)}`", f"- para: `{_versao(b)}`", ""]
|
|
94
|
+
if diferenca.vazia:
|
|
95
|
+
linhas.append("Sem diferença.")
|
|
96
|
+
return "\n".join(linhas) + "\n"
|
|
97
|
+
linhas.append(
|
|
98
|
+
f"**{len(diferenca.criados)}** criados, **{len(diferenca.removidos)}** removidos, "
|
|
99
|
+
f"**{len(diferenca.alterados)}** alterados" + (", Namespace alterado" if diferenca.namespace else "") + "."
|
|
100
|
+
)
|
|
101
|
+
linhas += ["", "| Documento | Mudança | Chaves |", "|---|---|---|"]
|
|
102
|
+
linhas += [f"| `{_celula(m)}` | criado | |" for m in diferenca.criados]
|
|
103
|
+
linhas += [f"| `{_celula(m)}` | removido | |" for m in diferenca.removidos]
|
|
104
|
+
for meta_id, chaves in diferenca.alterados.items():
|
|
105
|
+
lista = ", ".join(f"`{_celula(_rotulo(c))}`" for c in chaves)
|
|
106
|
+
linhas.append(f"| `{_celula(meta_id)}` | alterado | {lista} |")
|
|
107
|
+
if diferenca.namespace:
|
|
108
|
+
lista = ", ".join(f"`{_celula(c)}`" for c in diferenca.namespace)
|
|
109
|
+
linhas.append(f"| `Namespace` | alterado | {lista} |")
|
|
110
|
+
return "\n".join(linhas) + "\n"
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def diff(pasta_a: Path, pasta_b: Path, *, markdown: bool = False) -> str:
|
|
114
|
+
a, b = ler_artefato(pasta_a), ler_artefato(pasta_b)
|
|
115
|
+
diferenca = comparar(a, b)
|
|
116
|
+
return formatar_markdown(diferenca, a, b) if markdown else formatar_texto(diferenca, a, b)
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Erros do `konecty-cli metas`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class MetasInvalidasError(Exception):
|
|
7
|
+
"""A árvore de metas, o delta ou o artefato não monta. A mensagem nomeia o arquivo de origem."""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class AplicacaoRecusadaError(Exception):
|
|
11
|
+
"""O artefato não pode ir para este tenant (sha256 ou ambiente). Nada foi enviado ao Konecty."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class LoteRecusadoError(Exception):
|
|
15
|
+
"""O Konecty recusou o lote ou não respondeu depois das tentativas. O lote é transacional:
|
|
16
|
+
nada foi gravado."""
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""`metas gerar-delta`: migra uma cópia completa de metadado para base + delta (MBD-10).
|
|
2
|
+
|
|
3
|
+
A partir da `metadata/base` e da cópia do cliente, escreve no repositório do cliente:
|
|
4
|
+
|
|
5
|
+
- `delta/<caminho da base>.json`: Merge Patch de cada meta que a cópia muda (só se mudar);
|
|
6
|
+
- `delta/<caminho da cópia>.json`: meta novo num módulo da base, inteiro;
|
|
7
|
+
- `delta/<Módulo>/hook/<nome>.js|.json`: hook diferente da base (`.js` inteiro, `.json` patch);
|
|
8
|
+
hook que a base tem e a cópia não vira `"<nome>": null` no patch do `document.json`;
|
|
9
|
+
- `modulos/<Módulo>/...`: módulo que a base não tem, copiado como está;
|
|
10
|
+
- `metadados.yaml`: `cliente`, `base`, `removidos` (os `_id` da base ausentes na cópia, E2).
|
|
11
|
+
|
|
12
|
+
O `Namespace.json` da cópia não é migrado: ele carrega valores por ambiente e segredos, que vão
|
|
13
|
+
para `env/<ambiente>.env` e `delta/Namespace.json` à mão.
|
|
14
|
+
|
|
15
|
+
Garantia: `montar(gerar_delta(base, cópia)) == ler_arvore(cópia)`, documento a documento.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import json
|
|
21
|
+
import logging
|
|
22
|
+
import shutil
|
|
23
|
+
from dataclasses import dataclass, field
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
from typing import Any, Dict, List, Optional
|
|
26
|
+
|
|
27
|
+
from .arvore import HOOK_FIELDS, NAMESPACE_ARQUIVO, Arvore, ler_arvore
|
|
28
|
+
from .erros import MetasInvalidasError
|
|
29
|
+
from .patch import gerar_patch
|
|
30
|
+
from .repositorio import ARQUIVO_CONFIG, ConfigCliente, escrever_config
|
|
31
|
+
|
|
32
|
+
logger = logging.getLogger("konecty.cli.metas.gerar_delta")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass
|
|
36
|
+
class ResumoDelta:
|
|
37
|
+
patches: List[str] = field(default_factory=list)
|
|
38
|
+
novos: List[str] = field(default_factory=list)
|
|
39
|
+
hooks: List[str] = field(default_factory=list)
|
|
40
|
+
modulos: List[str] = field(default_factory=list)
|
|
41
|
+
removidos: List[str] = field(default_factory=list)
|
|
42
|
+
iguais: int = 0
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _json(valor: Any) -> str:
|
|
46
|
+
return json.dumps(valor, ensure_ascii=False, indent=2) + "\n"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _gravar(raiz: Path, relativo: Path, texto: str) -> None:
|
|
50
|
+
destino = raiz / relativo
|
|
51
|
+
destino.parent.mkdir(parents=True, exist_ok=True)
|
|
52
|
+
destino.write_text(texto, encoding="utf-8")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _sem_hooks(meta: Dict[str, Any]) -> Dict[str, Any]:
|
|
56
|
+
return {k: v for k, v in meta.items() if k not in HOOK_FIELDS}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _hooks_do_delta(
|
|
60
|
+
saida: Path, modulo_dir: Path, base_meta: Dict[str, Any], copia_meta: Dict[str, Any], patch: Dict[str, Any]
|
|
61
|
+
) -> List[str]:
|
|
62
|
+
"""Escreve os hooks que diferem; põe `null` no patch para o hook que a cópia tirou."""
|
|
63
|
+
escritos: List[str] = []
|
|
64
|
+
for hook in HOOK_FIELDS:
|
|
65
|
+
if hook not in copia_meta:
|
|
66
|
+
if hook in base_meta:
|
|
67
|
+
patch[hook] = None
|
|
68
|
+
continue
|
|
69
|
+
valor = copia_meta[hook]
|
|
70
|
+
if hook in base_meta and base_meta[hook] == valor and type(base_meta[hook]) is type(valor):
|
|
71
|
+
continue
|
|
72
|
+
if isinstance(valor, str):
|
|
73
|
+
relativo = modulo_dir / "hook" / f"{hook}.js"
|
|
74
|
+
_gravar(saida / "delta", relativo, valor)
|
|
75
|
+
else:
|
|
76
|
+
relativo = modulo_dir / "hook" / f"{hook}.json"
|
|
77
|
+
_gravar(saida / "delta", relativo, _json(gerar_patch(base_meta.get(hook), valor)))
|
|
78
|
+
escritos.append(relativo.as_posix())
|
|
79
|
+
return escritos
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _copiar_modulo(copia_raiz: Path, arvore: Arvore, meta_id: str, saida: Path) -> None:
|
|
83
|
+
relativo = arvore.origens[meta_id]
|
|
84
|
+
destino = saida / "modulos" / relativo
|
|
85
|
+
destino.parent.mkdir(parents=True, exist_ok=True)
|
|
86
|
+
shutil.copyfile(copia_raiz / relativo, destino)
|
|
87
|
+
if relativo.name != "document.json":
|
|
88
|
+
return
|
|
89
|
+
pasta_hook = (copia_raiz / relativo).parent / "hook"
|
|
90
|
+
if not pasta_hook.is_dir():
|
|
91
|
+
return
|
|
92
|
+
for arquivo in sorted(pasta_hook.iterdir()):
|
|
93
|
+
if arquivo.suffix in (".js", ".json") and arquivo.stem in HOOK_FIELDS:
|
|
94
|
+
alvo = destino.parent / "hook" / arquivo.name
|
|
95
|
+
alvo.parent.mkdir(parents=True, exist_ok=True)
|
|
96
|
+
shutil.copyfile(arquivo, alvo)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def gerar_delta(
|
|
100
|
+
base_dir: Path,
|
|
101
|
+
copia_dir: Path,
|
|
102
|
+
saida: Path,
|
|
103
|
+
*,
|
|
104
|
+
cliente: str,
|
|
105
|
+
base_tag: str,
|
|
106
|
+
konecty: Optional[str] = None,
|
|
107
|
+
) -> ResumoDelta:
|
|
108
|
+
base_dir, copia_dir, saida = Path(base_dir), Path(copia_dir), Path(saida)
|
|
109
|
+
for existente in (ARQUIVO_CONFIG, "delta", "modulos"):
|
|
110
|
+
if (saida / existente).exists():
|
|
111
|
+
raise MetasInvalidasError(f"{saida / existente} já existe: gerar-delta não sobrescreve")
|
|
112
|
+
base = ler_arvore(base_dir, placeholders="manter")
|
|
113
|
+
copia = ler_arvore(copia_dir, placeholders="manter")
|
|
114
|
+
modulos_base = {base.modulo(meta_id) for meta_id in base}
|
|
115
|
+
caminhos_base = {origem: meta_id for meta_id, origem in base.origens.items()}
|
|
116
|
+
resumo = ResumoDelta()
|
|
117
|
+
saida.mkdir(parents=True, exist_ok=True)
|
|
118
|
+
|
|
119
|
+
for meta_id in sorted(copia):
|
|
120
|
+
modulo = copia.modulo(meta_id)
|
|
121
|
+
meta = copia[meta_id]
|
|
122
|
+
if modulo not in modulos_base:
|
|
123
|
+
_copiar_modulo(copia_dir, copia, meta_id, saida)
|
|
124
|
+
if modulo not in resumo.modulos:
|
|
125
|
+
resumo.modulos.append(modulo)
|
|
126
|
+
continue
|
|
127
|
+
|
|
128
|
+
if meta_id in base:
|
|
129
|
+
relativo = base.origens[meta_id]
|
|
130
|
+
base_meta = base[meta_id]
|
|
131
|
+
else:
|
|
132
|
+
relativo = copia.origens[meta_id]
|
|
133
|
+
if relativo in caminhos_base:
|
|
134
|
+
raise MetasInvalidasError(
|
|
135
|
+
f"{copia_dir / relativo}: _id {meta_id} ocupa o caminho de {caminhos_base[relativo]} na base"
|
|
136
|
+
)
|
|
137
|
+
base_meta = {}
|
|
138
|
+
|
|
139
|
+
hooks: List[str] = []
|
|
140
|
+
if relativo.name == "document.json":
|
|
141
|
+
patch = gerar_patch(_sem_hooks(base_meta), _sem_hooks(meta))
|
|
142
|
+
hooks = _hooks_do_delta(saida, relativo.parent, base_meta, meta, patch)
|
|
143
|
+
resumo.hooks.extend(hooks)
|
|
144
|
+
else:
|
|
145
|
+
patch = gerar_patch(base_meta, meta)
|
|
146
|
+
|
|
147
|
+
if meta_id not in base:
|
|
148
|
+
_gravar(saida / "delta", relativo, _json(patch))
|
|
149
|
+
resumo.novos.append(meta_id)
|
|
150
|
+
elif patch or hooks:
|
|
151
|
+
if patch:
|
|
152
|
+
_gravar(saida / "delta", relativo, _json(patch))
|
|
153
|
+
resumo.patches.append(meta_id)
|
|
154
|
+
else:
|
|
155
|
+
resumo.iguais += 1
|
|
156
|
+
|
|
157
|
+
resumo.removidos = sorted(meta_id for meta_id in base if meta_id not in copia)
|
|
158
|
+
if (copia_dir / NAMESPACE_ARQUIVO).is_file():
|
|
159
|
+
logger.warning(
|
|
160
|
+
"Namespace.json da cópia não migrado: leve os valores para env/<ambiente>.env e delta/Namespace.json"
|
|
161
|
+
)
|
|
162
|
+
escrever_config(
|
|
163
|
+
saida,
|
|
164
|
+
ConfigCliente(cliente=cliente, base=base_tag, konecty=konecty, removidos=resumo.removidos),
|
|
165
|
+
)
|
|
166
|
+
return resumo
|