argos-cli 0.3.1__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.
- argos/__init__.py +5 -0
- argos/__main__.py +4 -0
- argos/adapters/__init__.py +9 -0
- argos/adapters/_libreoffice_worker.py +111 -0
- argos/adapters/ai.py +1506 -0
- argos/adapters/ai_remote.py +654 -0
- argos/adapters/attachment_conversion.py +132 -0
- argos/adapters/capabilities.py +31 -0
- argos/adapters/chart_render.py +72 -0
- argos/adapters/docx_pdf.py +2953 -0
- argos/adapters/limesurvey.py +1079 -0
- argos/adapters/model_call.py +274 -0
- argos/adapters/report_publication.py +1530 -0
- argos/adapters/url_fetch.py +146 -0
- argos/adapters/xlsx.py +454 -0
- argos/analytics.py +731 -0
- argos/assets.py +257 -0
- argos/audit_result.py +369 -0
- argos/booleans.py +105 -0
- argos/catalog.py +1205 -0
- argos/cli.py +606 -0
- argos/contracts.py +532 -0
- argos/core.py +325 -0
- argos/default_skills/README.md +23 -0
- argos/default_skills/criar-matriz-planejamento/SKILL.md +200 -0
- argos/default_skills/elaborar-survey-limesurvey/SKILL.md +106 -0
- argos/default_skills/operar-argos/SKILL.md +74 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/SKILL.md +129 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/assets/relatorio-avaliacao.md +54 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/references/contrato-saidas.md +36 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/references/papeis-das-pastas.md +37 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/references/roteiro-verificacoes.md +27 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/scripts/avaliacao.py +253 -0
- argos/engines/__init__.py +3 -0
- argos/engines/adjustments.py +571 -0
- argos/engines/analytics.py +195 -0
- argos/engines/audit.py +2730 -0
- argos/engines/evaluation.py +6088 -0
- argos/engines/index.py +1683 -0
- argos/engines/matrix.py +5736 -0
- argos/engines/matrix_html.py +698 -0
- argos/engines/model_request.py +201 -0
- argos/engines/report_document.py +137 -0
- argos/engines/reports.py +1200 -0
- argos/engines/survey.py +4445 -0
- argos/envfile.py +53 -0
- argos/errors.py +29 -0
- argos/evidence_staging.py +293 -0
- argos/executions.py +565 -0
- argos/findings_matrix.py +2549 -0
- argos/fingerprints.py +487 -0
- argos/index_dsl.py +2100 -0
- argos/matrix_markdown.py +475 -0
- argos/matrix_widths.py +280 -0
- argos/pipeline.py +1745 -0
- argos/products.py +220 -0
- argos/progress.py +221 -0
- argos/project.py +608 -0
- argos/report_config.py +158 -0
- argos/resources/ESPECIFICACAO_MARKDOWN_MATRIZ_ACHADOS.md +539 -0
- argos/resources/ESPECIFICACAO_MARKDOWN_MATRIZ_PLANEJAMENTO.md +1000 -0
- argos/resources/ESPECIFICACAO_UNIFICADA_MATRIZES_V1_3.md +1142 -0
- argos/resources/anexo-evidencias-base.docx +0 -0
- argos/resources/argos-index-dsl-v1.schema.json +539 -0
- argos/resources/argos-report-config-v1.schema.json +113 -0
- argos/resources/diretrizes-projeto.md +476 -0
- argos/resources/env.example +37 -0
- argos/resources/exemplos/matriz_achados_boilerplate.md +61 -0
- argos/resources/exemplos/matriz_achados_draft.md +106 -0
- argos/resources/exemplos/matriz_achados_larguras_v1_3.md +114 -0
- argos/resources/exemplos/matriz_achados_v1_3.md +107 -0
- argos/resources/exemplos/matriz_planejamento_boilerplate.md +64 -0
- argos/resources/exemplos/matriz_planejamento_larguras_v1_3.md +115 -0
- argos/resources/exemplos/matriz_planejamento_v1_3.md +108 -0
- argos/resources/template-base-estilos-sigiloso.docx +0 -0
- argos/resources/template-base-estilos.docx +0 -0
- argos/resources/template-matriz-planejamento.docx +0 -0
- argos/resources/template-relatorio-consolidado-comum.docx +0 -0
- argos/resources/template-relatorio-consolidado-institucional.docx +0 -0
- argos/response_profiles.py +856 -0
- argos/scheduler.py +142 -0
- argos/status.py +367 -0
- argos/store.py +1228 -0
- argos/survey_collection.py +832 -0
- argos/telemetry.py +84 -0
- argos/tui.py +1262 -0
- argos/tui.tcss +827 -0
- argos/tui_models.py +466 -0
- argos/tui_path.py +155 -0
- argos/tui_widgets.py +482 -0
- argos/version.py +3 -0
- argos_cli-0.3.1.dist-info/METADATA +570 -0
- argos_cli-0.3.1.dist-info/RECORD +96 -0
- argos_cli-0.3.1.dist-info/WHEEL +5 -0
- argos_cli-0.3.1.dist-info/entry_points.txt +2 -0
- argos_cli-0.3.1.dist-info/top_level.txt +1 -0
argos/matrix_markdown.py
ADDED
|
@@ -0,0 +1,475 @@
|
|
|
1
|
+
"""Primitivas compartilhadas para leitura do Markdown das matrizes.
|
|
2
|
+
|
|
3
|
+
O módulo conhece a estrutura textual comum (front matter, campos YAML e
|
|
4
|
+
listas de tokens), mas não importa motores nem modelos de domínio.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
import json
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from decimal import Decimal, InvalidOperation
|
|
13
|
+
from typing import Any, Mapping, Pattern, Sequence
|
|
14
|
+
|
|
15
|
+
from .core import InputValidationError
|
|
16
|
+
from .project import yaml_module
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
_FIELD = re.compile(r"^([ ]*)([A-Za-z_][A-Za-z0-9_-]*):(?:[ \t]*(.*))?$")
|
|
20
|
+
_HEADING = re.compile(r"^#{1,6}[ \t]+")
|
|
21
|
+
_EXACT_DECIMAL_FRONT_MATTER_FIELDS = ("larguras_colunas_percentuais",)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class _YamlNumericScalar:
|
|
26
|
+
"""Valor YAML numérico com representação legada e decimal textual."""
|
|
27
|
+
|
|
28
|
+
legacy_value: int | float
|
|
29
|
+
exact_decimal: Decimal | None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _decimal_scalar(value: str) -> Decimal | None:
|
|
33
|
+
source = value.replace("_", "")
|
|
34
|
+
try:
|
|
35
|
+
return Decimal(source)
|
|
36
|
+
except InvalidOperation:
|
|
37
|
+
return None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def normalize_text(text: str) -> str:
|
|
41
|
+
"""Normaliza CRLF/CR e remove BOM sem alterar o conteúdo editorial."""
|
|
42
|
+
return text.replace("\r\n", "\n").replace("\r", "\n").lstrip("\ufeff")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _error(path: str, message: str, *, line: int | None = None) -> InputValidationError:
|
|
46
|
+
location = f"linha {line}, " if line is not None else ""
|
|
47
|
+
return InputValidationError(f"{location}{path}: {message}")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def load_yaml_document(
|
|
51
|
+
text: str,
|
|
52
|
+
*,
|
|
53
|
+
path: str,
|
|
54
|
+
line: int = 1,
|
|
55
|
+
exact_decimal_fields: Sequence[str] = (),
|
|
56
|
+
) -> Any:
|
|
57
|
+
"""Carrega YAML seguro, rejeitando chaves duplicadas e aliases cíclicos."""
|
|
58
|
+
yaml = yaml_module()
|
|
59
|
+
|
|
60
|
+
class UniqueKeyLoader(yaml.SafeLoader):
|
|
61
|
+
pass
|
|
62
|
+
|
|
63
|
+
def construct_yaml_int(loader, node):
|
|
64
|
+
legacy = yaml.SafeLoader.construct_yaml_int(loader, node)
|
|
65
|
+
return _YamlNumericScalar(legacy, _decimal_scalar(node.value))
|
|
66
|
+
|
|
67
|
+
def construct_yaml_float(loader, node):
|
|
68
|
+
legacy = yaml.SafeLoader.construct_yaml_float(loader, node)
|
|
69
|
+
return _YamlNumericScalar(legacy, _decimal_scalar(node.value))
|
|
70
|
+
|
|
71
|
+
UniqueKeyLoader.add_constructor("tag:yaml.org,2002:int", construct_yaml_int)
|
|
72
|
+
UniqueKeyLoader.add_constructor("tag:yaml.org,2002:float", construct_yaml_float)
|
|
73
|
+
|
|
74
|
+
def construct_mapping(loader, node, deep=False):
|
|
75
|
+
mapping: dict[Any, Any] = {}
|
|
76
|
+
for key_node, value_node in node.value:
|
|
77
|
+
key = loader.construct_object(key_node, deep=deep)
|
|
78
|
+
try:
|
|
79
|
+
duplicate = key in mapping
|
|
80
|
+
except TypeError as exc:
|
|
81
|
+
raise yaml.constructor.ConstructorError(
|
|
82
|
+
"while constructing a mapping",
|
|
83
|
+
node.start_mark,
|
|
84
|
+
"chave YAML deve ser escalar",
|
|
85
|
+
key_node.start_mark,
|
|
86
|
+
) from exc
|
|
87
|
+
if duplicate:
|
|
88
|
+
raise yaml.constructor.ConstructorError(
|
|
89
|
+
"while constructing a mapping",
|
|
90
|
+
node.start_mark,
|
|
91
|
+
f"chave duplicada: {key!r}",
|
|
92
|
+
key_node.start_mark,
|
|
93
|
+
)
|
|
94
|
+
mapping[key] = loader.construct_object(value_node, deep=deep)
|
|
95
|
+
return mapping
|
|
96
|
+
|
|
97
|
+
UniqueKeyLoader.add_constructor(
|
|
98
|
+
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
|
|
99
|
+
construct_mapping,
|
|
100
|
+
)
|
|
101
|
+
try:
|
|
102
|
+
value = yaml.load(text, Loader=UniqueKeyLoader)
|
|
103
|
+
except yaml.YAMLError as exc:
|
|
104
|
+
mark = getattr(exc, "problem_mark", None)
|
|
105
|
+
source_line = line + mark.line if mark is not None else line
|
|
106
|
+
detail = getattr(exc, "problem", None) or str(exc)
|
|
107
|
+
if "recursive" in detail.casefold():
|
|
108
|
+
detail = "aliases YAML cíclicos não são permitidos"
|
|
109
|
+
raise _error(path, f"YAML inválido: {detail}", line=source_line) from exc
|
|
110
|
+
|
|
111
|
+
active: set[int] = set()
|
|
112
|
+
|
|
113
|
+
def reject_cycles(item: Any, current: str) -> None:
|
|
114
|
+
if not isinstance(item, (dict, list)):
|
|
115
|
+
return
|
|
116
|
+
identity = id(item)
|
|
117
|
+
if identity in active:
|
|
118
|
+
raise _error(current, "aliases YAML cíclicos não são permitidos")
|
|
119
|
+
active.add(identity)
|
|
120
|
+
pairs = item.items() if isinstance(item, dict) else enumerate(item)
|
|
121
|
+
for key, child in pairs:
|
|
122
|
+
reject_cycles(child, f"{current}.{key}")
|
|
123
|
+
active.remove(identity)
|
|
124
|
+
|
|
125
|
+
reject_cycles(value, path)
|
|
126
|
+
|
|
127
|
+
exact_fields = frozenset(exact_decimal_fields)
|
|
128
|
+
|
|
129
|
+
def restore_numeric_types(item: Any, *, preserve_decimal: bool = False, root: bool = False) -> Any:
|
|
130
|
+
if isinstance(item, _YamlNumericScalar):
|
|
131
|
+
if preserve_decimal:
|
|
132
|
+
# Keep invalid/non-decimal numeric spellings as a private marker;
|
|
133
|
+
# the width contract rejects the unsupported scalar type.
|
|
134
|
+
return item.exact_decimal if item.exact_decimal is not None else item
|
|
135
|
+
return item.legacy_value
|
|
136
|
+
if isinstance(item, dict):
|
|
137
|
+
restored: dict[Any, Any] = {}
|
|
138
|
+
for key, child in item.items():
|
|
139
|
+
restored_key = restore_numeric_types(key)
|
|
140
|
+
preserve_child = preserve_decimal or (root and restored_key in exact_fields)
|
|
141
|
+
restored[restored_key] = restore_numeric_types(
|
|
142
|
+
child,
|
|
143
|
+
preserve_decimal=preserve_child,
|
|
144
|
+
)
|
|
145
|
+
return restored
|
|
146
|
+
if isinstance(item, list):
|
|
147
|
+
return [restore_numeric_types(child, preserve_decimal=preserve_decimal) for child in item]
|
|
148
|
+
return item
|
|
149
|
+
|
|
150
|
+
return restore_numeric_types(value, root=True)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def load_yaml_mapping(
|
|
154
|
+
text: str,
|
|
155
|
+
*,
|
|
156
|
+
path: str,
|
|
157
|
+
line: int = 1,
|
|
158
|
+
allow_empty: bool = False,
|
|
159
|
+
exact_decimal_fields: Sequence[str] = (),
|
|
160
|
+
) -> dict[str, Any]:
|
|
161
|
+
"""Carrega um mapa YAML com chaves textuais e duplicatas recusadas."""
|
|
162
|
+
value = load_yaml_document(
|
|
163
|
+
text,
|
|
164
|
+
path=path,
|
|
165
|
+
line=line,
|
|
166
|
+
exact_decimal_fields=exact_decimal_fields,
|
|
167
|
+
)
|
|
168
|
+
if value is None and allow_empty:
|
|
169
|
+
return {}
|
|
170
|
+
if not isinstance(value, Mapping):
|
|
171
|
+
raise _error(path, "deve ser um mapeamento YAML", line=line)
|
|
172
|
+
if any(not isinstance(key, str) for key in value):
|
|
173
|
+
raise _error(path, "as chaves devem ser textos", line=line)
|
|
174
|
+
return dict(value)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
@dataclass(frozen=True)
|
|
178
|
+
class FrontMatter:
|
|
179
|
+
"""Metadados YAML, corpo restante e número da primeira linha do corpo."""
|
|
180
|
+
|
|
181
|
+
metadata: dict[str, Any]
|
|
182
|
+
body: str
|
|
183
|
+
body_line: int
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def split_front_matter(markdown: str, *, required: bool, path: str = "documento") -> FrontMatter:
|
|
187
|
+
"""Separa front matter YAML delimitado por ``---`` na coluna um."""
|
|
188
|
+
text = normalize_text(markdown)
|
|
189
|
+
if not text.strip():
|
|
190
|
+
raise _error(path, "Markdown vazio", line=1)
|
|
191
|
+
lines = text.split("\n")
|
|
192
|
+
start = 0
|
|
193
|
+
while start < len(lines) and not lines[start].strip():
|
|
194
|
+
start += 1
|
|
195
|
+
if start >= len(lines) or lines[start].strip() != "---" or lines[start][:1].isspace():
|
|
196
|
+
if required:
|
|
197
|
+
raise _error(
|
|
198
|
+
path,
|
|
199
|
+
"front matter obrigatório ausente: o arquivo deve iniciar com '---' na coluna 1",
|
|
200
|
+
line=start + 1 if start < len(lines) else 1,
|
|
201
|
+
)
|
|
202
|
+
return FrontMatter({}, text, 1)
|
|
203
|
+
end = next(
|
|
204
|
+
(
|
|
205
|
+
index
|
|
206
|
+
for index in range(start + 1, len(lines))
|
|
207
|
+
if lines[index].rstrip() == "---" and not lines[index][:1].isspace()
|
|
208
|
+
),
|
|
209
|
+
None,
|
|
210
|
+
)
|
|
211
|
+
if end is None:
|
|
212
|
+
raise _error(path, "front matter sem delimitador de encerramento '---'", line=start + 1)
|
|
213
|
+
metadata = load_yaml_mapping(
|
|
214
|
+
"\n".join(lines[start + 1 : end]),
|
|
215
|
+
path=f"{path}.front_matter",
|
|
216
|
+
line=start + 2,
|
|
217
|
+
allow_empty=True,
|
|
218
|
+
exact_decimal_fields=_EXACT_DECIMAL_FRONT_MATTER_FIELDS,
|
|
219
|
+
)
|
|
220
|
+
return FrontMatter(metadata, "\n".join(lines[end + 1 :]), end + 2)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
@dataclass(frozen=True)
|
|
224
|
+
class FieldValue:
|
|
225
|
+
"""Um atributo de primeiro nível preservando sua linha e fonte YAML."""
|
|
226
|
+
|
|
227
|
+
name: str
|
|
228
|
+
source: str
|
|
229
|
+
line: int
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def field_values(
|
|
233
|
+
content: str,
|
|
234
|
+
*,
|
|
235
|
+
path: str,
|
|
236
|
+
line: int = 1,
|
|
237
|
+
allowed: Sequence[str] | None = None,
|
|
238
|
+
reject_unknown: bool = False,
|
|
239
|
+
) -> dict[str, FieldValue]:
|
|
240
|
+
"""Localiza atributos de primeiro nível e separa cada valor por escopo."""
|
|
241
|
+
text = normalize_text(content)
|
|
242
|
+
lines = text.split("\n")
|
|
243
|
+
positions: list[tuple[int, str, int]] = []
|
|
244
|
+
for index, raw in enumerate(lines):
|
|
245
|
+
if "\t" in raw:
|
|
246
|
+
raise _error(path, "tabulações não são permitidas; use espaços", line=line + index)
|
|
247
|
+
match = _FIELD.fullmatch(raw)
|
|
248
|
+
if match is None or match.group(1):
|
|
249
|
+
continue
|
|
250
|
+
name = match.group(2)
|
|
251
|
+
if allowed is not None and name not in allowed and reject_unknown:
|
|
252
|
+
raise _error(f"{path}.{name}", "atributo desconhecido", line=line + index)
|
|
253
|
+
positions.append((index, name, line + index))
|
|
254
|
+
|
|
255
|
+
result: dict[str, FieldValue] = {}
|
|
256
|
+
for position, (start, name, source_line) in enumerate(positions):
|
|
257
|
+
if name in result:
|
|
258
|
+
raise _error(f"{path}.{name}", "atributo repetido", line=source_line)
|
|
259
|
+
end = positions[position + 1][0] if position + 1 < len(positions) else len(lines)
|
|
260
|
+
end = next(
|
|
261
|
+
(
|
|
262
|
+
index
|
|
263
|
+
for index in range(start + 1, end)
|
|
264
|
+
if lines[index] == "---" or _HEADING.match(lines[index])
|
|
265
|
+
),
|
|
266
|
+
end,
|
|
267
|
+
)
|
|
268
|
+
match = _FIELD.fullmatch(lines[start])
|
|
269
|
+
assert match is not None
|
|
270
|
+
first_value = match.group(3) or ""
|
|
271
|
+
continuation = lines[start + 1 : end]
|
|
272
|
+
source = first_value + ("\n" + "\n".join(continuation) if continuation else "")
|
|
273
|
+
result[name] = FieldValue(name=name, source=source, line=source_line)
|
|
274
|
+
return result
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def extract_field(content: str, key: str, *, path: str, line: int = 1) -> FieldValue | None:
|
|
278
|
+
"""Extrai um campo no escopo atual, parando em outro atributo ou cabeçalho."""
|
|
279
|
+
lines = normalize_text(content).split("\n")
|
|
280
|
+
matching_positions: list[int] = []
|
|
281
|
+
for index, raw in enumerate(lines):
|
|
282
|
+
if "\t" in raw:
|
|
283
|
+
raise _error(path, "tabulações não são permitidas; use espaços", line=line + index)
|
|
284
|
+
match = _FIELD.fullmatch(raw)
|
|
285
|
+
if match is not None and not match.group(1) and match.group(2) == key:
|
|
286
|
+
matching_positions.append(index)
|
|
287
|
+
if not matching_positions:
|
|
288
|
+
return None
|
|
289
|
+
start = matching_positions[0]
|
|
290
|
+
end = len(lines)
|
|
291
|
+
for index in range(start + 1, len(lines)):
|
|
292
|
+
if lines[index] == "---" or _HEADING.match(lines[index]):
|
|
293
|
+
end = index
|
|
294
|
+
break
|
|
295
|
+
match = _FIELD.fullmatch(lines[index])
|
|
296
|
+
if match is not None and not match.group(1):
|
|
297
|
+
end = index
|
|
298
|
+
break
|
|
299
|
+
repeated = [position for position in matching_positions[1:] if position < end]
|
|
300
|
+
if repeated:
|
|
301
|
+
raise _error(f"{path}.{key}", "atributo repetido", line=line + repeated[0])
|
|
302
|
+
match = _FIELD.fullmatch(lines[start])
|
|
303
|
+
assert match is not None
|
|
304
|
+
first_value = match.group(3) or ""
|
|
305
|
+
source = first_value + ("\n" + "\n".join(lines[start + 1 : end]) if start + 1 < end else "")
|
|
306
|
+
return FieldValue(name=key, source=source, line=line + start)
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _flow_list_close(source: str) -> int | None:
|
|
310
|
+
"""Retorna o fechamento da lista externa, respeitando aspas e colchetes internos."""
|
|
311
|
+
depth = 0
|
|
312
|
+
quote: str | None = None
|
|
313
|
+
escaped = False
|
|
314
|
+
for index, character in enumerate(source):
|
|
315
|
+
if quote:
|
|
316
|
+
if escaped:
|
|
317
|
+
escaped = False
|
|
318
|
+
elif character == "\\":
|
|
319
|
+
escaped = True
|
|
320
|
+
elif character == quote:
|
|
321
|
+
quote = None
|
|
322
|
+
continue
|
|
323
|
+
if character in "'\"":
|
|
324
|
+
quote = character
|
|
325
|
+
elif character == "[":
|
|
326
|
+
depth += 1
|
|
327
|
+
elif character == "]":
|
|
328
|
+
depth -= 1
|
|
329
|
+
if depth == 0:
|
|
330
|
+
return index
|
|
331
|
+
return None
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _quote_nested_token_lists(source: str, *, field_name: str, path: str, line: int) -> str:
|
|
335
|
+
"""Cita tokens com colchetes internos em listas YAML flow de campos declarados."""
|
|
336
|
+
lines = source.split("\n")
|
|
337
|
+
for index, raw in enumerate(lines):
|
|
338
|
+
match = re.fullmatch(rf"(?P<indent>[ ]*){re.escape(field_name)}:[ \t]*(?P<value>.*)", raw)
|
|
339
|
+
if match is None:
|
|
340
|
+
continue
|
|
341
|
+
value = match.group("value").strip()
|
|
342
|
+
if not value.startswith("["):
|
|
343
|
+
continue
|
|
344
|
+
close = _flow_list_close(value)
|
|
345
|
+
if close is None:
|
|
346
|
+
continue # O carregador YAML comum reportará a lista malformada.
|
|
347
|
+
list_source = value[: close + 1]
|
|
348
|
+
suffix = value[close + 1 :].strip()
|
|
349
|
+
if suffix and not suffix.startswith("#"):
|
|
350
|
+
continue
|
|
351
|
+
tokens = parse_token_list(list_source, path=f"{path}.{field_name}")
|
|
352
|
+
encoded = json.dumps(tokens, ensure_ascii=False)
|
|
353
|
+
comment = f" {suffix}" if suffix else ""
|
|
354
|
+
lines[index] = f"{match.group('indent')}{field_name}: {encoded}{comment}"
|
|
355
|
+
return "\n".join(lines)
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def parse_field_value(
|
|
359
|
+
field: FieldValue,
|
|
360
|
+
*,
|
|
361
|
+
path: str,
|
|
362
|
+
nested_token_lists: Sequence[str] = (),
|
|
363
|
+
) -> Any:
|
|
364
|
+
"""Interpreta o valor YAML de um atributo mantendo seu escopo isolado."""
|
|
365
|
+
source = field.source
|
|
366
|
+
for name in nested_token_lists:
|
|
367
|
+
source = _quote_nested_token_lists(
|
|
368
|
+
source,
|
|
369
|
+
field_name=name,
|
|
370
|
+
path=path,
|
|
371
|
+
line=field.line,
|
|
372
|
+
)
|
|
373
|
+
wrapped = "__matrix_value__: " + source
|
|
374
|
+
value = load_yaml_mapping(wrapped, path=path, line=field.line)
|
|
375
|
+
return value.get("__matrix_value__")
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def scalar_field(content: str, key: str, *, path: str, line: int = 1) -> Any:
|
|
379
|
+
"""Lê um escalar YAML citado, simples, literal ou dobrado de um campo."""
|
|
380
|
+
field = extract_field(content, key, path=path, line=line)
|
|
381
|
+
if field is None:
|
|
382
|
+
return None
|
|
383
|
+
return parse_field_value(field, path=f"{path}.{key}")
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def parse_token_list(
|
|
387
|
+
value: Any,
|
|
388
|
+
*,
|
|
389
|
+
path: str,
|
|
390
|
+
pattern: Pattern[str] | None = None,
|
|
391
|
+
nonempty: bool = False,
|
|
392
|
+
unique: bool = True,
|
|
393
|
+
) -> list[str]:
|
|
394
|
+
"""Interpreta tokens separados pela vírgula externa, preservando colchetes internos."""
|
|
395
|
+
if isinstance(value, str):
|
|
396
|
+
source = value.strip()
|
|
397
|
+
if source.startswith("["):
|
|
398
|
+
if not source.endswith("]"):
|
|
399
|
+
raise _error(path, "lista de tokens sem colchete de fechamento")
|
|
400
|
+
source = source[1:-1]
|
|
401
|
+
tokens: list[str] = []
|
|
402
|
+
start = 0
|
|
403
|
+
depth = 0
|
|
404
|
+
quote: str | None = None
|
|
405
|
+
escaped = False
|
|
406
|
+
for index, character in enumerate(source):
|
|
407
|
+
if quote:
|
|
408
|
+
if escaped:
|
|
409
|
+
escaped = False
|
|
410
|
+
elif character == "\\":
|
|
411
|
+
escaped = True
|
|
412
|
+
elif character == quote:
|
|
413
|
+
quote = None
|
|
414
|
+
continue
|
|
415
|
+
if character in "'\"":
|
|
416
|
+
quote = character
|
|
417
|
+
elif character == "[":
|
|
418
|
+
depth += 1
|
|
419
|
+
elif character == "]":
|
|
420
|
+
depth -= 1
|
|
421
|
+
if depth < 0:
|
|
422
|
+
raise _error(path, "colchete interno sem abertura")
|
|
423
|
+
elif character == "," and depth == 0:
|
|
424
|
+
tokens.append(source[start:index].strip())
|
|
425
|
+
start = index + 1
|
|
426
|
+
if quote:
|
|
427
|
+
raise _error(path, "aspas não fechadas na lista de tokens")
|
|
428
|
+
if depth:
|
|
429
|
+
raise _error(path, "colchete interno sem fechamento")
|
|
430
|
+
if source.strip():
|
|
431
|
+
tokens.append(source[start:].strip())
|
|
432
|
+
raw_items = tokens
|
|
433
|
+
elif isinstance(value, list):
|
|
434
|
+
raw_items = value
|
|
435
|
+
else:
|
|
436
|
+
raise _error(path, "deve ser uma lista de identificadores")
|
|
437
|
+
|
|
438
|
+
if nonempty and not raw_items:
|
|
439
|
+
raise _error(path, "a lista não pode ficar vazia")
|
|
440
|
+
result: list[str] = []
|
|
441
|
+
for index, item in enumerate(raw_items):
|
|
442
|
+
if not isinstance(item, str) or not item.strip():
|
|
443
|
+
raise _error(f"{path}[{index}]", "identificador deve ser texto não vazio")
|
|
444
|
+
token = item.strip()
|
|
445
|
+
if len(token) >= 2 and token[0] in "'\"" and token[-1] == token[0]:
|
|
446
|
+
decoded = load_yaml_document(token, path=f"{path}[{index}]")
|
|
447
|
+
if not isinstance(decoded, str):
|
|
448
|
+
raise _error(f"{path}[{index}]", "identificador entre aspas deve ser texto")
|
|
449
|
+
token = decoded.strip()
|
|
450
|
+
if pattern is not None and pattern.fullmatch(token) is None:
|
|
451
|
+
raise _error(f"{path}[{index}]", f"identificador fora do padrão: {token!r}")
|
|
452
|
+
result.append(token)
|
|
453
|
+
if unique and len(result) != len(set(result)):
|
|
454
|
+
raise _error(path, "não pode repetir identificadores")
|
|
455
|
+
return result
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
def parse_compact_list(block: str) -> list[str]:
|
|
459
|
+
"""Agrupa itens ``- ID: texto`` e suas linhas indentadas de continuação."""
|
|
460
|
+
items: list[str] = []
|
|
461
|
+
current: str | None = None
|
|
462
|
+
for line in normalize_text(block).split("\n"):
|
|
463
|
+
if not line.strip():
|
|
464
|
+
continue
|
|
465
|
+
bullet = re.match(r"^\s*-\s+(.+)$", line)
|
|
466
|
+
if bullet:
|
|
467
|
+
if current is not None:
|
|
468
|
+
items.append(current)
|
|
469
|
+
current = bullet.group(1).strip()
|
|
470
|
+
elif current is not None:
|
|
471
|
+
current += " " + line.strip()
|
|
472
|
+
if current is not None:
|
|
473
|
+
items.append(current)
|
|
474
|
+
return items
|
|
475
|
+
|