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.
Files changed (96) hide show
  1. argos/__init__.py +5 -0
  2. argos/__main__.py +4 -0
  3. argos/adapters/__init__.py +9 -0
  4. argos/adapters/_libreoffice_worker.py +111 -0
  5. argos/adapters/ai.py +1506 -0
  6. argos/adapters/ai_remote.py +654 -0
  7. argos/adapters/attachment_conversion.py +132 -0
  8. argos/adapters/capabilities.py +31 -0
  9. argos/adapters/chart_render.py +72 -0
  10. argos/adapters/docx_pdf.py +2953 -0
  11. argos/adapters/limesurvey.py +1079 -0
  12. argos/adapters/model_call.py +274 -0
  13. argos/adapters/report_publication.py +1530 -0
  14. argos/adapters/url_fetch.py +146 -0
  15. argos/adapters/xlsx.py +454 -0
  16. argos/analytics.py +731 -0
  17. argos/assets.py +257 -0
  18. argos/audit_result.py +369 -0
  19. argos/booleans.py +105 -0
  20. argos/catalog.py +1205 -0
  21. argos/cli.py +606 -0
  22. argos/contracts.py +532 -0
  23. argos/core.py +325 -0
  24. argos/default_skills/README.md +23 -0
  25. argos/default_skills/criar-matriz-planejamento/SKILL.md +200 -0
  26. argos/default_skills/elaborar-survey-limesurvey/SKILL.md +106 -0
  27. argos/default_skills/operar-argos/SKILL.md +74 -0
  28. argos/default_skills/verificar-diretrizes-fiscalizacao/SKILL.md +129 -0
  29. argos/default_skills/verificar-diretrizes-fiscalizacao/assets/relatorio-avaliacao.md +54 -0
  30. argos/default_skills/verificar-diretrizes-fiscalizacao/references/contrato-saidas.md +36 -0
  31. argos/default_skills/verificar-diretrizes-fiscalizacao/references/papeis-das-pastas.md +37 -0
  32. argos/default_skills/verificar-diretrizes-fiscalizacao/references/roteiro-verificacoes.md +27 -0
  33. argos/default_skills/verificar-diretrizes-fiscalizacao/scripts/avaliacao.py +253 -0
  34. argos/engines/__init__.py +3 -0
  35. argos/engines/adjustments.py +571 -0
  36. argos/engines/analytics.py +195 -0
  37. argos/engines/audit.py +2730 -0
  38. argos/engines/evaluation.py +6088 -0
  39. argos/engines/index.py +1683 -0
  40. argos/engines/matrix.py +5736 -0
  41. argos/engines/matrix_html.py +698 -0
  42. argos/engines/model_request.py +201 -0
  43. argos/engines/report_document.py +137 -0
  44. argos/engines/reports.py +1200 -0
  45. argos/engines/survey.py +4445 -0
  46. argos/envfile.py +53 -0
  47. argos/errors.py +29 -0
  48. argos/evidence_staging.py +293 -0
  49. argos/executions.py +565 -0
  50. argos/findings_matrix.py +2549 -0
  51. argos/fingerprints.py +487 -0
  52. argos/index_dsl.py +2100 -0
  53. argos/matrix_markdown.py +475 -0
  54. argos/matrix_widths.py +280 -0
  55. argos/pipeline.py +1745 -0
  56. argos/products.py +220 -0
  57. argos/progress.py +221 -0
  58. argos/project.py +608 -0
  59. argos/report_config.py +158 -0
  60. argos/resources/ESPECIFICACAO_MARKDOWN_MATRIZ_ACHADOS.md +539 -0
  61. argos/resources/ESPECIFICACAO_MARKDOWN_MATRIZ_PLANEJAMENTO.md +1000 -0
  62. argos/resources/ESPECIFICACAO_UNIFICADA_MATRIZES_V1_3.md +1142 -0
  63. argos/resources/anexo-evidencias-base.docx +0 -0
  64. argos/resources/argos-index-dsl-v1.schema.json +539 -0
  65. argos/resources/argos-report-config-v1.schema.json +113 -0
  66. argos/resources/diretrizes-projeto.md +476 -0
  67. argos/resources/env.example +37 -0
  68. argos/resources/exemplos/matriz_achados_boilerplate.md +61 -0
  69. argos/resources/exemplos/matriz_achados_draft.md +106 -0
  70. argos/resources/exemplos/matriz_achados_larguras_v1_3.md +114 -0
  71. argos/resources/exemplos/matriz_achados_v1_3.md +107 -0
  72. argos/resources/exemplos/matriz_planejamento_boilerplate.md +64 -0
  73. argos/resources/exemplos/matriz_planejamento_larguras_v1_3.md +115 -0
  74. argos/resources/exemplos/matriz_planejamento_v1_3.md +108 -0
  75. argos/resources/template-base-estilos-sigiloso.docx +0 -0
  76. argos/resources/template-base-estilos.docx +0 -0
  77. argos/resources/template-matriz-planejamento.docx +0 -0
  78. argos/resources/template-relatorio-consolidado-comum.docx +0 -0
  79. argos/resources/template-relatorio-consolidado-institucional.docx +0 -0
  80. argos/response_profiles.py +856 -0
  81. argos/scheduler.py +142 -0
  82. argos/status.py +367 -0
  83. argos/store.py +1228 -0
  84. argos/survey_collection.py +832 -0
  85. argos/telemetry.py +84 -0
  86. argos/tui.py +1262 -0
  87. argos/tui.tcss +827 -0
  88. argos/tui_models.py +466 -0
  89. argos/tui_path.py +155 -0
  90. argos/tui_widgets.py +482 -0
  91. argos/version.py +3 -0
  92. argos_cli-0.3.1.dist-info/METADATA +570 -0
  93. argos_cli-0.3.1.dist-info/RECORD +96 -0
  94. argos_cli-0.3.1.dist-info/WHEEL +5 -0
  95. argos_cli-0.3.1.dist-info/entry_points.txt +2 -0
  96. argos_cli-0.3.1.dist-info/top_level.txt +1 -0
argos/tui_models.py ADDED
@@ -0,0 +1,466 @@
1
+ """Modelos de apresentação da TUI do Argos.
2
+
3
+ Este módulo é um adapter pequeno entre os contratos do núcleo e a tela. Ele
4
+ não executa operações nem decide políticas de auditoria: transforma o
5
+ ``OperationCatalog`` e o estado observável do ``WorkspaceStore`` em dados
6
+ imutáveis que os widgets podem renderizar e testar sem I/O de interface.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import sqlite3
13
+ from dataclasses import dataclass
14
+ from pathlib import Path
15
+ from typing import Any, Iterable
16
+
17
+ from .core import ArgosError, OperationCatalog, OperationSpec, WorkspaceLocation, split_operation_id
18
+ from .core import AuditSession
19
+ from .status import AWAITING_INPUT, COMPLETED, FAILED, RUNNING, UNKNOWN
20
+
21
+
22
+ AREA_PLANNING = "Planejamento"
23
+ AREA_EXECUTION = "Execução"
24
+ AREA_ANALYSIS = "Análise"
25
+ AREA_REPORT = "Relatório"
26
+ AREA_OTHER = "Outros"
27
+
28
+ OPERATION_AREAS = (
29
+ AREA_PLANNING,
30
+ AREA_EXECUTION,
31
+ AREA_ANALYSIS,
32
+ AREA_REPORT,
33
+ AREA_OTHER,
34
+ )
35
+
36
+ # Área e fase de cada objeto (parte do id antes do ponto). Objetos fora do mapa,
37
+ # como os de catálogos de teste, caem pelo grupo da operação.
38
+ _OBJECT_AREAS = {
39
+ "matriz": AREA_PLANNING,
40
+ "survey": AREA_PLANNING,
41
+ "catalogo": AREA_PLANNING,
42
+ "ajustar": AREA_EXECUTION,
43
+ "auditar": AREA_EXECUTION,
44
+ "evidencias": AREA_EXECUTION,
45
+ "indice": AREA_ANALYSIS,
46
+ "revisao": AREA_ANALYSIS,
47
+ "contraditorio": AREA_ANALYSIS,
48
+ "comparar": AREA_ANALYSIS,
49
+ "documento": AREA_REPORT,
50
+ "graficos": AREA_REPORT,
51
+ "status": AREA_OTHER,
52
+ "controle": AREA_OTHER,
53
+ "pipeline": AREA_OTHER,
54
+ }
55
+ _GROUP_AREAS = {
56
+ "preparação": AREA_PLANNING,
57
+ "preparacao": AREA_PLANNING,
58
+ "surveys": AREA_PLANNING,
59
+ "transformações": AREA_EXECUTION,
60
+ "transformacoes": AREA_EXECUTION,
61
+ "auditoria": AREA_EXECUTION,
62
+ "cálculos": AREA_ANALYSIS,
63
+ "calculos": AREA_ANALYSIS,
64
+ "avaliações": AREA_ANALYSIS,
65
+ "avaliacoes": AREA_ANALYSIS,
66
+ "documentos": AREA_REPORT,
67
+ "relatórios": AREA_REPORT,
68
+ "relatorios": AREA_REPORT,
69
+ }
70
+ _AREA_PHASES = {
71
+ AREA_PLANNING: "Planejamento",
72
+ AREA_EXECUTION: "Coleta de dados",
73
+ AREA_ANALYSIS: "Análise",
74
+ AREA_REPORT: "Relatório",
75
+ AREA_OTHER: "Encerramento",
76
+ }
77
+ # Curadoria: objetos que abrem cada seção, antes do restante na ordem do catálogo.
78
+ _AREA_PRIORITY = {
79
+ AREA_PLANNING: ("matriz", "survey", "catalogo"),
80
+ AREA_EXECUTION: ("ajustar", "auditar", "evidencias"),
81
+ AREA_ANALYSIS: ("indice", "revisao", "contraditorio"),
82
+ AREA_REPORT: ("documento", "graficos"),
83
+ AREA_OTHER: ("status", "controle", "pipeline"),
84
+ }
85
+
86
+ STAGE_PLANNING = "planning"
87
+ STAGE_COLLECTION = "collection"
88
+ STAGE_ANALYSIS = "analysis"
89
+ STAGE_FINDINGS = "findings"
90
+ STAGE_REPORT = "report"
91
+ STAGE_CLOSURE = "closure"
92
+
93
+
94
+ @dataclass(frozen=True)
95
+ class OperationView:
96
+ """Visão navegável de uma especificação do catálogo.
97
+
98
+ ``spec`` continua sendo a fonte dos parâmetros, validações e recursos.
99
+ As propriedades delegadas mantêm a interface de apresentação curta sem
100
+ duplicar o contrato de ``OperationSpec``.
101
+ """
102
+
103
+ spec: OperationSpec
104
+ area: str
105
+ phase: str
106
+
107
+ @property
108
+ def id(self) -> str:
109
+ return self.spec.id
110
+
111
+ @property
112
+ def object(self) -> str:
113
+ return split_operation_id(self.spec.id)[0]
114
+
115
+ @property
116
+ def name(self) -> str:
117
+ return self.spec.name
118
+
119
+ @property
120
+ def description(self) -> str:
121
+ return self.spec.description
122
+
123
+ @property
124
+ def parameters(self):
125
+ return self.spec.parameters
126
+
127
+ @property
128
+ def version(self) -> str:
129
+ return self.spec.version
130
+
131
+ @property
132
+ def searchable_text(self) -> str:
133
+ return " ".join((self.id, self.name, self.description, self.spec.group, self.area, self.phase)).casefold()
134
+
135
+ def as_dict(self) -> dict[str, Any]:
136
+ """Expõe o mínimo útil para integrações futuras da tela."""
137
+
138
+ return {
139
+ "id": self.id,
140
+ "name": self.name,
141
+ "description": self.description,
142
+ "category": self.area,
143
+ "phase": self.phase,
144
+ "version": self.version,
145
+ "parameters": self.parameters,
146
+ }
147
+
148
+
149
+ @dataclass(frozen=True)
150
+ class OperationDirectory:
151
+ """Catálogo de apresentação construído a partir do catálogo real."""
152
+
153
+ entries: tuple[OperationView, ...]
154
+ objects: tuple[str, ...] = ()
155
+
156
+ @classmethod
157
+ def from_catalog(cls, catalog: OperationCatalog) -> "OperationDirectory":
158
+ return cls(tuple(cls._view(spec) for spec in catalog.all()), catalog.objects())
159
+
160
+ @staticmethod
161
+ def _view(spec: OperationSpec) -> OperationView:
162
+ area = _OBJECT_AREAS.get(split_operation_id(spec.id)[0])
163
+ if area is None:
164
+ area = _GROUP_AREAS.get(spec.group.casefold().strip(), AREA_OTHER)
165
+ return OperationView(spec=spec, area=area, phase=_AREA_PHASES[area])
166
+
167
+ def for_object(self, objeto: str) -> tuple[OperationView, ...]:
168
+ return tuple(entry for entry in self.entries if entry.object == objeto)
169
+
170
+ def all(self) -> tuple[OperationView, ...]:
171
+ return self.entries
172
+
173
+ def get(self, operation_id: str) -> OperationView:
174
+ for entry in self.entries:
175
+ if entry.id == operation_id:
176
+ return entry
177
+ raise ArgosError(f"operação desconhecida: {operation_id}")
178
+
179
+ def for_area(self, area: str) -> tuple[OperationView, ...]:
180
+ return tuple(entry for entry in self.entries if entry.area == area)
181
+
182
+ def prioritized(self, area: str) -> tuple[OperationView, ...]:
183
+ """Ordena a seção por uma curadoria estável e depois pelo catálogo.
184
+
185
+ A curadoria é por objeto: as ações de um objeto ficam juntas.
186
+ """
187
+
188
+ priority = _AREA_PRIORITY.get(area, ())
189
+ entries = self.for_area(area)
190
+ rank = {objeto: position for position, objeto in enumerate(priority)}
191
+ order = {objeto: position for position, objeto in enumerate(self.objects)}
192
+ return tuple(
193
+ sorted(
194
+ entries,
195
+ key=lambda entry: (
196
+ rank.get(entry.object, len(rank)),
197
+ order.get(entry.object, len(order)),
198
+ ),
199
+ )
200
+ )
201
+
202
+ def search(self, text: str, *, area: str | None = None) -> tuple[OperationView, ...]:
203
+ needle = text.casefold().strip()
204
+ order = {objeto: position for position, objeto in enumerate(self.objects)}
205
+ matches = (
206
+ entry
207
+ for entry in self.entries
208
+ if (area in (None, "", "Todas", "all") or entry.area == area)
209
+ and (not needle or needle in entry.searchable_text)
210
+ )
211
+ # Agrupado por objeto; dentro do objeto, a ordem do catálogo.
212
+ return tuple(sorted(matches, key=lambda entry: order.get(entry.object, len(order))))
213
+
214
+ def featured(
215
+ self,
216
+ area: str,
217
+ *,
218
+ current_phase: str | None = None,
219
+ limit: int | None = None,
220
+ ) -> tuple[OperationView, ...]:
221
+ """Seleciona um recorte curto sem esconder o restante do catálogo."""
222
+
223
+ entries = self.prioritized(area)
224
+ if limit is None:
225
+ limit = 3
226
+ return entries[: max(0, limit)]
227
+
228
+
229
+ @dataclass(frozen=True)
230
+ class AuditStage:
231
+ key: str
232
+ title: str
233
+ status: str = "pending"
234
+ detail: str = "Pendente"
235
+ progress: int | None = None
236
+ completed_at: str | None = None
237
+
238
+
239
+ STAGE_DEFINITIONS = (
240
+ (STAGE_PLANNING, "Planejamento", AREA_PLANNING),
241
+ (STAGE_COLLECTION, "Coleta de dados", AREA_EXECUTION),
242
+ (STAGE_ANALYSIS, "Análise", AREA_ANALYSIS),
243
+ # O catálogo atual não tem uma operação exclusiva de achados; manter a
244
+ # etapa pendente evita atribuir a ela o estado de uma análise genérica.
245
+ (STAGE_FINDINGS, "Achados", None),
246
+ (STAGE_REPORT, "Relatório", AREA_REPORT),
247
+ (STAGE_CLOSURE, "Encerramento", AREA_OTHER),
248
+ )
249
+
250
+
251
+ @dataclass(frozen=True)
252
+ class AuditSnapshot:
253
+ """Estado renderizável da fiscalização, sem dados inventados."""
254
+
255
+ loaded: bool
256
+ number: str = ""
257
+ name: str = ""
258
+ identifier: str = ""
259
+ description: str | None = None
260
+ client: str | None = None
261
+ started_at: str | None = None
262
+ due_at: str | None = None
263
+ current_phase: str | None = None
264
+ progress: int | None = None
265
+ completed_stages: int = 0
266
+ pending_stages: int = 0
267
+ critical_issues: int = 0
268
+ stages: tuple[AuditStage, ...] = ()
269
+
270
+ @classmethod
271
+ def empty(cls) -> "AuditSnapshot":
272
+ return cls(
273
+ loaded=False,
274
+ stages=tuple(AuditStage(key=key, title=title) for key, title, _area in STAGE_DEFINITIONS),
275
+ )
276
+
277
+ @classmethod
278
+ def from_session(
279
+ cls,
280
+ session: AuditSession,
281
+ directory: OperationDirectory,
282
+ ) -> "AuditSnapshot":
283
+ executions = session.store.list_executions(limit=1000)
284
+ from .status import inspect_product_states
285
+
286
+ freshness = inspect_product_states(
287
+ session.store,
288
+ catalog=session.engine.catalog,
289
+ project_root=session.project_root,
290
+ project_overrides=session.engine.executions.project_overrides,
291
+ scenario=None,
292
+ )
293
+ freshness_by_execution: dict[str, list[dict[str, Any]]] = {}
294
+ for item in freshness:
295
+ execution_id = str(item["artifact"].get("execution_id") or "")
296
+ freshness_by_execution.setdefault(execution_id, []).append(item)
297
+ stages: list[AuditStage] = []
298
+ for key, title, area in STAGE_DEFINITIONS:
299
+ relevant = [execution for execution in executions if _execution_area(execution, directory) == area]
300
+ stage = _stage_from_executions(key, title, relevant)
301
+ if stage.status == "completed" and relevant:
302
+ latest_states = freshness_by_execution.get(str(relevant[0]["id"]), ())
303
+ stale = [item for item in latest_states if not item["current"]]
304
+ if stale:
305
+ reasons = sorted(
306
+ {
307
+ reason
308
+ for item in stale
309
+ for reason in item.get("reasons", ())
310
+ }
311
+ )
312
+ stage = AuditStage(
313
+ key=stage.key,
314
+ title=stage.title,
315
+ status="outdated",
316
+ detail="Produto desatualizado · " + ", ".join(reasons),
317
+ completed_at=stage.completed_at,
318
+ )
319
+ stages.append(stage)
320
+
321
+ completed = sum(stage.status == "completed" for stage in stages)
322
+ pending = sum(stage.status != "completed" for stage in stages)
323
+ critical = sum(str(execution.get("status")) in {FAILED, UNKNOWN} for execution in executions)
324
+ current = next((stage for stage in stages if stage.status == "current"), None)
325
+ if current is None:
326
+ current = next(
327
+ (
328
+ stage
329
+ for stage in stages
330
+ if stage.status in {"review", "outdated", "blocked", "error", "pending"}
331
+ ),
332
+ stages[-1] if stages else None,
333
+ )
334
+ progress = round(completed / len(stages) * 100) if executions and stages else None
335
+ started_at = min(
336
+ (str(item["created_at"]) for item in executions if item.get("created_at")),
337
+ default=None,
338
+ )
339
+ return cls(
340
+ loaded=True,
341
+ number=session.store.numero,
342
+ name=session.store.nome,
343
+ identifier=getattr(session.store, "fiscalizacao_id", ""),
344
+ started_at=started_at,
345
+ current_phase=current.title if current else None,
346
+ progress=progress,
347
+ completed_stages=completed,
348
+ pending_stages=pending,
349
+ critical_issues=critical,
350
+ stages=tuple(stages),
351
+ )
352
+
353
+
354
+ def _execution_area(execution: dict[str, Any], directory: OperationDirectory) -> str:
355
+ try:
356
+ return directory.get(str(execution.get("operation_id"))).area
357
+ except ArgosError:
358
+ return AREA_OTHER
359
+
360
+
361
+ def _stage_from_executions(
362
+ key: str,
363
+ title: str,
364
+ executions: Iterable[dict[str, Any]],
365
+ ) -> AuditStage:
366
+ items = list(executions)
367
+ if not items:
368
+ return AuditStage(key=key, title=title)
369
+ latest = items[0]
370
+ latest_status = str(latest.get("status") or "")
371
+ operation_id = str(latest.get("operation_id") or "operação")
372
+ if latest_status == RUNNING:
373
+ return AuditStage(
374
+ key=key,
375
+ title=title,
376
+ status="current",
377
+ detail=f"Em andamento · {operation_id}",
378
+ )
379
+ if latest_status in {FAILED, UNKNOWN}:
380
+ return AuditStage(
381
+ key=key,
382
+ title=title,
383
+ status="error",
384
+ detail=f"Erro · {operation_id}",
385
+ )
386
+ if latest_status == AWAITING_INPUT:
387
+ result = _execution_result(latest)
388
+ pending = result.get("pending") or ()
389
+ if any("review" in str(item.get("type") or "").casefold() for item in pending if isinstance(item, dict)):
390
+ return AuditStage(
391
+ key=key,
392
+ title=title,
393
+ status="review",
394
+ detail=f"Aguardando revisão humana · {operation_id}",
395
+ )
396
+ return AuditStage(
397
+ key=key,
398
+ title=title,
399
+ status="blocked",
400
+ detail=f"Aguardando insumos · {operation_id}",
401
+ )
402
+ if latest_status == COMPLETED:
403
+ return AuditStage(
404
+ key=key,
405
+ title=title,
406
+ status="completed",
407
+ detail="Concluída",
408
+ completed_at=str(latest.get("finished_at") or "") or None,
409
+ )
410
+ return AuditStage(key=key, title=title, detail="Pendente")
411
+
412
+
413
+ def _execution_result(execution: dict[str, Any]) -> dict[str, Any]:
414
+ try:
415
+ result = json.loads(str(execution.get("result_json") or "{}"))
416
+ except (TypeError, ValueError):
417
+ return {}
418
+ return dict(result) if isinstance(result, dict) else {}
419
+
420
+
421
+ @dataclass(frozen=True)
422
+ class AuditIdentity:
423
+ number: str
424
+ name: str
425
+ updated_at: str | None = None
426
+
427
+
428
+ @dataclass(frozen=True)
429
+ class AuditIdentityRequest:
430
+ mode: str
431
+ workspace_root: Path
432
+ number: str | None = None
433
+ name: str | None = None
434
+ project_root: Path | None = None
435
+ objective: str = ""
436
+ process_number: str = ""
437
+ git: bool = False
438
+
439
+
440
+ def list_registered_audits(workspace_root: str | Path) -> tuple[AuditIdentity, ...]:
441
+ """Lê identidades recentes sem abrir uma sessão ou trocar fiscalização."""
442
+
443
+ db_path = WorkspaceLocation.from_path(workspace_root).db_path
444
+ if not db_path.exists():
445
+ return ()
446
+ try:
447
+ with sqlite3.connect(db_path) as connection:
448
+ rows = connection.execute(
449
+ "SELECT numero, nome, updated_at FROM fiscalizacao ORDER BY updated_at DESC, numero"
450
+ ).fetchall()
451
+ except sqlite3.Error as exc:
452
+ raise ArgosError(f"não foi possível ler auditorias recentes: {exc}") from exc
453
+ return tuple(
454
+ AuditIdentity(number=str(row[0]), name=str(row[1]), updated_at=str(row[2] or "") or None) for row in rows
455
+ )
456
+
457
+
458
+ def format_date(value: str | None) -> str:
459
+ """Formata timestamps do SQLite para uma linha curta de terminal."""
460
+
461
+ if not value:
462
+ return "—"
463
+ try:
464
+ return value.replace("T", " ").split("+", 1)[0][:16]
465
+ except AttributeError:
466
+ return "—"
argos/tui_path.py ADDED
@@ -0,0 +1,155 @@
1
+ """Entrada de paths com autocomplete local para a TUI.
2
+
3
+ O módulo mantém a interface pequena: ``PathInput.complete_path`` aceita a
4
+ sugestão corrente e o restante da implementação esconde a resolução de
5
+ caminhos, filtragem do filesystem e ciclo de candidatos. O mesmo seam é usado
6
+ por workspaces e pelos parâmetros ``path`` do catálogo de operações.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import re
13
+ from pathlib import Path
14
+
15
+ from textual.widgets import Input
16
+
17
+
18
+ class PathInput(Input):
19
+ """``Input`` com sugestão fantasma e conclusão estilo shell.
20
+
21
+ A sugestão é apenas visual até ``complete_path`` ser chamado. A primeira
22
+ conclusão amplia o prefixo comum dos candidatos; chamadas seguintes de
23
+ ``complete_path`` percorrem os candidatos encontrados. A entrada não
24
+ acessa a rede nem executa processos externos.
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ *,
30
+ base_path: str | Path,
31
+ include_directories: bool = True,
32
+ include_files: bool = True,
33
+ allowed_suffixes: tuple[str, ...] = (),
34
+ multiple: bool = False,
35
+ **kwargs,
36
+ ) -> None:
37
+ self.base_path = Path(base_path).expanduser().resolve()
38
+ self.include_directories = include_directories
39
+ self.include_files = include_files
40
+ self.allowed_suffixes = tuple(suffix.casefold() for suffix in allowed_suffixes)
41
+ self.multiple = multiple
42
+ self._completion_base = ""
43
+ self._completion_candidates: tuple[str, ...] = ()
44
+ self._completion_index = -1
45
+ super().__init__(**kwargs)
46
+
47
+ def _watch_value(self, value: str) -> None:
48
+ super()._watch_value(value)
49
+ self._reset_completion(value)
50
+
51
+ def _reset_completion(self, value: str) -> None:
52
+ self._completion_base = value
53
+ self._completion_candidates = self._find_candidates(value)
54
+ self._completion_index = -1
55
+ self._set_suggestion()
56
+
57
+ def complete_path(self) -> bool:
58
+ """Aceita ou percorre a sugestão; retorna se havia candidato."""
59
+
60
+ if not self._completion_candidates or self.cursor_position != len(self.value):
61
+ return False
62
+
63
+ current = self.value
64
+ candidates = self._completion_candidates
65
+ base = self._completion_base
66
+ if current == self._completion_base:
67
+ common = os.path.commonprefix(candidates)
68
+ if len(common) > len(current):
69
+ self._set_completed_value(common)
70
+ self._completion_base = base
71
+ self._completion_candidates = candidates
72
+ self._completion_index = -1
73
+ self._set_suggestion()
74
+ return True
75
+
76
+ next_index = (self._completion_index + 1) % len(candidates)
77
+ candidate = candidates[next_index]
78
+ self._set_completed_value(candidate)
79
+ self._completion_base = base
80
+ self._completion_candidates = candidates
81
+ self._completion_index = next_index
82
+ self._set_suggestion()
83
+ return True
84
+
85
+ def _set_completed_value(self, value: str) -> None:
86
+ self.value = value
87
+ self.cursor_position = len(value)
88
+
89
+ def _set_suggestion(self) -> None:
90
+ suggestion = ""
91
+ if self._completion_candidates:
92
+ candidate = self._completion_candidates[(self._completion_index + 1) % len(self._completion_candidates)]
93
+ if candidate.startswith(self.value) and candidate != self.value:
94
+ suggestion = candidate
95
+ self._suggestion = suggestion
96
+
97
+ def _find_candidates(self, value: str) -> tuple[str, ...]:
98
+ token = self._current_token(value)
99
+ if token is None:
100
+ return ()
101
+ token_start, raw_token = token
102
+ parent_token, leaf = _parent_and_leaf(raw_token)
103
+ parent = _resolve_path(parent_token, self.base_path)
104
+ try:
105
+ entries = list(parent.iterdir())
106
+ except (FileNotFoundError, NotADirectoryError, PermissionError, OSError):
107
+ return ()
108
+
109
+ candidates: list[str] = []
110
+ prefix = value[:token_start] + parent_token
111
+ show_hidden = leaf.startswith(".")
112
+ for entry in entries:
113
+ if not entry.name.startswith(leaf):
114
+ continue
115
+ if entry.name.startswith(".") and not show_hidden:
116
+ continue
117
+ try:
118
+ is_directory = entry.is_dir()
119
+ except OSError:
120
+ continue
121
+ if is_directory and not self.include_directories:
122
+ continue
123
+ if not is_directory and not self.include_files:
124
+ continue
125
+ if self.allowed_suffixes and not is_directory and entry.suffix.casefold() not in self.allowed_suffixes:
126
+ continue
127
+ suffix = "/" if is_directory else ""
128
+ candidates.append(prefix + entry.name + suffix)
129
+ return tuple(sorted(candidates, key=lambda item: (item.casefold(), item)))
130
+
131
+ def _current_token(self, value: str) -> tuple[int, str] | None:
132
+ if self.cursor_position != len(value):
133
+ return None
134
+ if not self.multiple:
135
+ return 0, value
136
+ match = re.search(r"(?:^|\s)(\S*)$", value)
137
+ if match is None:
138
+ return None
139
+ return match.start(1), match.group(1)
140
+
141
+
142
+ def _parent_and_leaf(token: str) -> tuple[str, str]:
143
+ slash = token.rfind("/")
144
+ if slash < 0:
145
+ return "", token
146
+ return token[: slash + 1], token[slash + 1 :]
147
+
148
+
149
+ def _resolve_path(value: str, base_path: Path) -> Path:
150
+ if not value:
151
+ return base_path
152
+ expanded = Path(value).expanduser()
153
+ if expanded.is_absolute():
154
+ return expanded
155
+ return base_path / expanded