codis 1.1.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 (329) hide show
  1. codis-1.1.1.dist-info/METADATA +194 -0
  2. codis-1.1.1.dist-info/RECORD +329 -0
  3. codis-1.1.1.dist-info/WHEEL +5 -0
  4. codis-1.1.1.dist-info/entry_points.txt +5 -0
  5. codis-1.1.1.dist-info/licenses/LICENSE +21 -0
  6. codis-1.1.1.dist-info/top_level.txt +2 -0
  7. run.py +190 -0
  8. src/__init__.py +1 -0
  9. src/__main__.py +81 -0
  10. src/_app_build.py +1507 -0
  11. src/_app_editor.py +1274 -0
  12. src/_app_kui.py +825 -0
  13. src/_app_lsp.py +625 -0
  14. src/_app_recovery.py +189 -0
  15. src/_app_settings.py +1385 -0
  16. src/_app_tools.py +2471 -0
  17. src/_app_webpreview.py +126 -0
  18. src/_font_safety.py +127 -0
  19. src/_shells.py +172 -0
  20. src/app.py +1488 -0
  21. src/chat/__init__.py +1 -0
  22. src/chat/adapters/__init__.py +33 -0
  23. src/chat/adapters/base.py +209 -0
  24. src/chat/adapters/discord.py +190 -0
  25. src/chat/adapters/http.py +78 -0
  26. src/chat/adapters/irc.py +360 -0
  27. src/chat/adapters/matrix.py +219 -0
  28. src/chat/adapters/mattermost.py +178 -0
  29. src/chat/adapters/mqtt.py +165 -0
  30. src/chat/adapters/slack.py +204 -0
  31. src/chat/adapters/telegram.py +117 -0
  32. src/chat/adapters/ws.py +154 -0
  33. src/chat/adapters/xmpp.py +337 -0
  34. src/chat/history.py +76 -0
  35. src/chat/models.py +207 -0
  36. src/chat/probe.py +79 -0
  37. src/chat/session.py +446 -0
  38. src/chat/util.py +125 -0
  39. src/collab/__init__.py +1 -0
  40. src/collab/net.py +411 -0
  41. src/collab/ot.py +311 -0
  42. src/collab/session.py +141 -0
  43. src/collab/tk_adapter.py +134 -0
  44. src/config.py +335 -0
  45. src/constants.py +2552 -0
  46. src/dep_catalog.py +446 -0
  47. src/diff/__init__.py +1 -0
  48. src/diff/engine.py +247 -0
  49. src/dpi.py +30 -0
  50. src/editor/__init__.py +1 -0
  51. src/editor/_pane_lsp.py +2937 -0
  52. src/editor/_pane_utils.py +171 -0
  53. src/editor/autocomplete.py +607 -0
  54. src/editor/code_folding.py +836 -0
  55. src/editor/color_preview.py +382 -0
  56. src/editor/complexity_lens.py +281 -0
  57. src/editor/diff_pane.py +623 -0
  58. src/editor/file_watcher.py +144 -0
  59. src/editor/focus_block.py +236 -0
  60. src/editor/heatmap.py +141 -0
  61. src/editor/inlay_hints.py +366 -0
  62. src/editor/inline_blame.py +429 -0
  63. src/editor/kdocs.py +3376 -0
  64. src/editor/large_file.py +488 -0
  65. src/editor/ligatures.py +180 -0
  66. src/editor/line_numbers.py +598 -0
  67. src/editor/minimap.py +691 -0
  68. src/editor/multi_cursor.py +269 -0
  69. src/editor/pane.py +2082 -0
  70. src/editor/rhythm.py +206 -0
  71. src/editor/save_hooks.py +43 -0
  72. src/editor/smart_selection.py +425 -0
  73. src/editor/smart_tips.py +719 -0
  74. src/editor/snippets.py +411 -0
  75. src/editor/sticky_note_gutter.py +410 -0
  76. src/editor/sticky_scroll.py +385 -0
  77. src/editor/suggest.py +464 -0
  78. src/editor/text_transforms.py +310 -0
  79. src/editor/vim_mode.py +1074 -0
  80. src/events/__init__.py +84 -0
  81. src/events/bus.py +427 -0
  82. src/events/correlator.py +244 -0
  83. src/events/kinds.py +125 -0
  84. src/events/pipeline.py +264 -0
  85. src/events/stream.py +416 -0
  86. src/events/window.py +204 -0
  87. src/extcompat/__init__.py +19 -0
  88. src/extcompat/code/__init__.py +13 -0
  89. src/extcompat/code/consent.py +162 -0
  90. src/extcompat/code/host.py +353 -0
  91. src/extcompat/code/hosts/py_host.py +763 -0
  92. src/extcompat/code/locate.py +105 -0
  93. src/extcompat/code/manager.py +325 -0
  94. src/extcompat/code/permissions.py +154 -0
  95. src/extcompat/code/sandbox.py +60 -0
  96. src/extcompat/colors.py +131 -0
  97. src/extcompat/common.py +184 -0
  98. src/extcompat/cson.py +269 -0
  99. src/extcompat/formats/__init__.py +22 -0
  100. src/extcompat/formats/_tm.py +189 -0
  101. src/extcompat/formats/_util.py +31 -0
  102. src/extcompat/formats/base16.py +66 -0
  103. src/extcompat/formats/brackets.py +172 -0
  104. src/extcompat/formats/eclipse.py +193 -0
  105. src/extcompat/formats/emacs.py +361 -0
  106. src/extcompat/formats/geany.py +147 -0
  107. src/extcompat/formats/generic.py +184 -0
  108. src/extcompat/formats/gtksource.py +117 -0
  109. src/extcompat/formats/helix.py +91 -0
  110. src/extcompat/formats/jetbrains.py +343 -0
  111. src/extcompat/formats/kate.py +130 -0
  112. src/extcompat/formats/micro.py +131 -0
  113. src/extcompat/formats/nano.py +111 -0
  114. src/extcompat/formats/notepadpp.py +140 -0
  115. src/extcompat/formats/pulsar.py +165 -0
  116. src/extcompat/formats/pyides.py +163 -0
  117. src/extcompat/formats/sublime.py +340 -0
  118. src/extcompat/jsonc.py +65 -0
  119. src/extcompat/lessish.py +128 -0
  120. src/extcompat/manager.py +122 -0
  121. src/extcompat/market/__init__.py +63 -0
  122. src/extcompat/market/sources.py +211 -0
  123. src/extcompat/model.py +88 -0
  124. src/extcompat/net.py +228 -0
  125. src/extcompat/openvsx.py +63 -0
  126. src/extcompat/readers.py +362 -0
  127. src/extcompat/registry.py +73 -0
  128. src/extcompat/safexml.py +63 -0
  129. src/extcompat/sexp.py +187 -0
  130. src/extcompat/sources.py +105 -0
  131. src/extcompat/store.py +276 -0
  132. src/extcompat/textmate.py +214 -0
  133. src/extcompat/themes.py +487 -0
  134. src/extcompat/yamlite.py +294 -0
  135. src/fileio.py +94 -0
  136. src/fs_ops.py +106 -0
  137. src/i18n.py +233 -0
  138. src/ia/__init__.py +1 -0
  139. src/ia/actions.py +295 -0
  140. src/ia/approval_gate.py +672 -0
  141. src/ia/checkpoints.py +308 -0
  142. src/ia/context_builder.py +921 -0
  143. src/ia/dialdiff.py +408 -0
  144. src/ia/iaspace.py +2078 -0
  145. src/ia/pair.py +296 -0
  146. src/ia/providers.py +954 -0
  147. src/ia/session.py +335 -0
  148. src/ia/toolbox.py +2524 -0
  149. src/launcher_actions.py +204 -0
  150. src/lint/__init__.py +1 -0
  151. src/lint/manager.py +1058 -0
  152. src/locales/.translate_manifest.json +64170 -0
  153. src/locales/de.json +4936 -0
  154. src/locales/en.json +4936 -0
  155. src/locales/es.json +4936 -0
  156. src/locales/fr.json +4936 -0
  157. src/locales/it.json +4936 -0
  158. src/locales/ja.json +4936 -0
  159. src/locales/ko.json +4936 -0
  160. src/locales/nl.json +4936 -0
  161. src/locales/pl.json +4936 -0
  162. src/locales/pt-BR.json +4936 -0
  163. src/locales/ru.json +4936 -0
  164. src/locales/tr.json +4936 -0
  165. src/locales/uk.json +4936 -0
  166. src/locales/zh-CN.json +4936 -0
  167. src/lsp/__init__.py +26 -0
  168. src/lsp/client.py +2300 -0
  169. src/lsp/dap_client.py +480 -0
  170. src/lsp/edits.py +84 -0
  171. src/lsp/framing.py +73 -0
  172. src/lsp/protocol.py +931 -0
  173. src/main.py +260 -0
  174. src/memtrim.py +91 -0
  175. src/plugins/__init__.py +1 -0
  176. src/plugins/api.py +1761 -0
  177. src/plugins/loader.py +571 -0
  178. src/plugins/process_runner.py +519 -0
  179. src/plugins/registry.py +342 -0
  180. src/plugins/safety.py +367 -0
  181. src/plugins/startup.py +195 -0
  182. src/plugins/store.py +1178 -0
  183. src/proc_registry.py +278 -0
  184. src/pyexec.py +394 -0
  185. src/recovery.py +259 -0
  186. src/stall_trace.py +92 -0
  187. src/standalone.py +1070 -0
  188. src/startup_profile.py +35 -0
  189. src/syntax/__init__.py +1 -0
  190. src/syntax/highlighter.py +776 -0
  191. src/syntax/patterns.py +584 -0
  192. src/system_profile.py +430 -0
  193. src/terminal/backends.py +658 -0
  194. src/terminal/internal.py +346 -0
  195. src/terminal/keys.py +138 -0
  196. src/terminal/palette.py +67 -0
  197. src/terminal/session.py +283 -0
  198. src/terminal/shells.py +79 -0
  199. src/terminal/view.py +489 -0
  200. src/terminal/vt.py +870 -0
  201. src/textfmt.py +22 -0
  202. src/theme/__init__.py +1 -0
  203. src/theme/base.py +1281 -0
  204. src/theme/colors.py +49 -0
  205. src/theme/manager.py +602 -0
  206. src/theme/utils.py +312 -0
  207. src/toolbox.py +329 -0
  208. src/trash_core.py +531 -0
  209. src/ui/__init__.py +1 -0
  210. src/ui/_perf_utils.py +285 -0
  211. src/ui/_persistence_utils.py +93 -0
  212. src/ui/accessibility.py +843 -0
  213. src/ui/activity_bar.py +860 -0
  214. src/ui/app_embed.py +434 -0
  215. src/ui/archive_panel.py +608 -0
  216. src/ui/bookmarks.py +314 -0
  217. src/ui/breadcrumb.py +383 -0
  218. src/ui/calculator_panel.py +982 -0
  219. src/ui/calendar_panel.py +1218 -0
  220. src/ui/chat_panel.py +1271 -0
  221. src/ui/chat_profile_dialog.py +278 -0
  222. src/ui/chat_render.py +128 -0
  223. src/ui/clock_panel.py +810 -0
  224. src/ui/code_outline.py +364 -0
  225. src/ui/code_runner.py +729 -0
  226. src/ui/code_stats.py +546 -0
  227. src/ui/collab_panel.py +1009 -0
  228. src/ui/color_picker.py +547 -0
  229. src/ui/command_palette.py +452 -0
  230. src/ui/cursor_manager.py +750 -0
  231. src/ui/custom_keywords_panel.py +413 -0
  232. src/ui/debug_panel.py +1037 -0
  233. src/ui/dependency_graph.py +692 -0
  234. src/ui/diff_panel.py +381 -0
  235. src/ui/docs_panel.py +514 -0
  236. src/ui/doom_embed.py +349 -0
  237. src/ui/dropdown.py +321 -0
  238. src/ui/easter_eggs.py +979 -0
  239. src/ui/env_manager.py +666 -0
  240. src/ui/extcode_bridge.py +215 -0
  241. src/ui/extcode_dialogs.py +412 -0
  242. src/ui/extcompat_dialog.py +583 -0
  243. src/ui/file_timeline.py +319 -0
  244. src/ui/file_tree.py +1208 -0
  245. src/ui/find_in_files.py +1355 -0
  246. src/ui/flowchart_panel.py +727 -0
  247. src/ui/formatter_panel.py +490 -0
  248. src/ui/git_auth.py +763 -0
  249. src/ui/git_clone_dialog.py +487 -0
  250. src/ui/git_panel.py +1483 -0
  251. src/ui/grab_safe.py +84 -0
  252. src/ui/internal_python_dialog.py +98 -0
  253. src/ui/k_ui/__init__.py +1305 -0
  254. src/ui/k_ui/_bgrenderer.py +317 -0
  255. src/ui/k_ui/_colors.py +213 -0
  256. src/ui/k_ui/_dock.py +545 -0
  257. src/ui/k_ui/_easter.py +290 -0
  258. src/ui/k_ui/_engine.py +5448 -0
  259. src/ui/k_ui/_perf.py +333 -0
  260. src/ui/k_ui/_tkutil.py +7 -0
  261. src/ui/k_ui/_tooltip.py +365 -0
  262. src/ui/k_ui/_widgets.py +1204 -0
  263. src/ui/k_ui/_world.py +837 -0
  264. src/ui/key_remapper.py +856 -0
  265. src/ui/launcher.py +1252 -0
  266. src/ui/lazy_panel.py +73 -0
  267. src/ui/macro_recorder.py +610 -0
  268. src/ui/menu_bar.py +898 -0
  269. src/ui/output_panel.py +321 -0
  270. src/ui/paint_canvas.py +1000 -0
  271. src/ui/paint_engine.py +535 -0
  272. src/ui/paint_panel.py +888 -0
  273. src/ui/panel_detach.py +112 -0
  274. src/ui/performance_panel.py +861 -0
  275. src/ui/pip_manager.py +1758 -0
  276. src/ui/plugin_panel.py +1586 -0
  277. src/ui/pomodoro_panel.py +447 -0
  278. src/ui/problems.py +566 -0
  279. src/ui/process_manager.py +1657 -0
  280. src/ui/project_templates.py +775 -0
  281. src/ui/recovery_dialog.py +122 -0
  282. src/ui/regex_playground.py +304 -0
  283. src/ui/remote_adapters.py +1398 -0
  284. src/ui/remote_browser.py +1224 -0
  285. src/ui/remote_profile_dialog.py +342 -0
  286. src/ui/render_panel.py +1293 -0
  287. src/ui/rest_client.py +549 -0
  288. src/ui/scratchpad.py +548 -0
  289. src/ui/search_bar.py +1274 -0
  290. src/ui/settings_editor.py +3349 -0
  291. src/ui/settings_window.py +1554 -0
  292. src/ui/snippets_panel.py +597 -0
  293. src/ui/sql_studio.py +1815 -0
  294. src/ui/status_bar.py +438 -0
  295. src/ui/tab_bar.py +654 -0
  296. src/ui/task_manager.py +1773 -0
  297. src/ui/terminal.py +525 -0
  298. src/ui/theme_preview_panel.py +851 -0
  299. src/ui/thread_safe_tk.py +152 -0
  300. src/ui/time_tracker.py +574 -0
  301. src/ui/tkbind.py +43 -0
  302. src/ui/todo_panel.py +358 -0
  303. src/ui/toolbox_panels.py +658 -0
  304. src/ui/trash_manager.py +657 -0
  305. src/ui/ui_scale.py +294 -0
  306. src/ui/ux_enhancements.py +41 -0
  307. src/ui/web_preview.py +397 -0
  308. src/ui/webdev.py +630 -0
  309. src/ui/welcome.py +567 -0
  310. src/ui/window_embed.py +1500 -0
  311. src/ui/wizard.py +1550 -0
  312. src/ui/workspace_switcher.py +418 -0
  313. src/ui/workspace_trust.py +370 -0
  314. src/ui/zen_audio.py +354 -0
  315. src/ui/zen_media.py +2271 -0
  316. src/ui/zen_media_client.py +303 -0
  317. src/ui/zen_media_host.py +329 -0
  318. src/ui/zen_player.py +907 -0
  319. src/ui/zen_player_widgets.py +700 -0
  320. src/updater/__init__.py +11 -0
  321. src/updater/assets.py +145 -0
  322. src/updater/backup.py +101 -0
  323. src/updater/channel.py +221 -0
  324. src/updater/dialog.py +492 -0
  325. src/updater/integrity.py +111 -0
  326. src/updater/manager.py +727 -0
  327. src/updater/result.py +114 -0
  328. src/venv_runtime.py +531 -0
  329. src/workspace_state.py +25 -0
src/lint/manager.py ADDED
@@ -0,0 +1,1058 @@
1
+ """Codis - LintManager: execução assíncrona de linters externos.
2
+
3
+ Integração com o barramento de eventos (RESA)
4
+ ---------------------------------------------
5
+ O LintManager publica eventos no ``EventBus`` global ao longo do ciclo de vida
6
+ de cada análise:
7
+
8
+ ``EventKind.LINT_STARTED``
9
+ Emitido quando uma análise é efetivamente iniciada em thread separada.
10
+ Payload: ``{path, lang}``
11
+
12
+ ``EventKind.LINT_RESULT``
13
+ Emitido quando a análise conclui com uma lista de diagnósticos (pode ser
14
+ vazia). Payload: ``{path, lang, diags}``
15
+
16
+ ``EventKind.LINT_CANCELLED``
17
+ Emitido quando a análise é interrompida antes de completar.
18
+ Payload: ``{path, lang}``
19
+
20
+ ``EventKind.LINT_ERROR``
21
+ Emitido quando ocorre uma exceção irrecuperável durante a análise.
22
+ Payload: ``{path, lang, error}``
23
+
24
+ O callback ``deliver`` passado ao construtor coexiste com os eventos.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import contextlib
30
+ import json
31
+ import logging
32
+ import os
33
+ import re
34
+ import shutil
35
+ import subprocess
36
+ import sys
37
+ import tempfile
38
+ import threading
39
+ import tkinter as tk
40
+ from collections.abc import Callable
41
+ from dataclasses import dataclass, field
42
+ from pathlib import Path
43
+ from typing import TYPE_CHECKING, Any
44
+
45
+ from src.config import ConfigManager
46
+ from src.constants import LINT_CSS, LINT_DELAY, LINT_HTML, LINT_JS, LINT_PHP, LINT_PY
47
+
48
+ if TYPE_CHECKING:
49
+ pass
50
+
51
+
52
+ def _get_bus():
53
+ """Retorna a instância global do EventBus, ou ``None`` se indisponível (importação circular)."""
54
+ try:
55
+ from src.events import bus
56
+
57
+ return bus
58
+ except Exception:
59
+ return None
60
+
61
+
62
+ logger = logging.getLogger("Codis")
63
+
64
+
65
+ def _json_array_from_output(raw: str) -> Any:
66
+ """Interpreta a saída JSON de uma ferramenta de lint, ignorando ruído antes do ``[``.
67
+
68
+ Saída vazia vale por lista vazia (nenhum problema encontrado).
69
+ """
70
+ raw = raw.strip()
71
+ if not raw:
72
+ return []
73
+ start = raw.find("[")
74
+ if start > 0:
75
+ raw = raw[start:]
76
+ return json.loads(raw)
77
+
78
+
79
+ @dataclass
80
+ class Diag:
81
+ """Um diagnóstico de lint (erro, aviso, info ou hint)."""
82
+
83
+ line: int
84
+ col: int
85
+ end_col: int
86
+ severity: int
87
+ message: str
88
+ rule: str = ""
89
+ source: str = ""
90
+ fix: dict | None = None
91
+ related: list[dict] = field(default_factory=list)
92
+
93
+ SEVERITY_LABELS = {1: "error", 2: "warning", 3: "info", 4: "hint"}
94
+ SEVERITY_ICONS = {1: "E", 2: "W", 3: "I", 4: "H"}
95
+
96
+ @property
97
+ def icon(self) -> str:
98
+ """Ícone Unicode correspondente à severidade do diagnóstico."""
99
+ return self.SEVERITY_ICONS.get(self.severity, "?")
100
+
101
+ @property
102
+ def is_error(self) -> bool:
103
+ """Retorna ``True`` se o diagnóstico tem severidade de erro (nível 1)."""
104
+ return self.severity == 1
105
+
106
+
107
+ class LintManager:
108
+ """
109
+ Roda múltiplos linters em thread daemon.
110
+
111
+ Para JavaScript/TypeScript:
112
+ - ESLint (com suporte a configs .eslintrc, eslint.config.js, etc.)
113
+ - Prettier (apenas verificação)
114
+
115
+ Para Python:
116
+ - py_compile (sintaxe)
117
+ - pyflakes (problemas semânticos simples)
118
+ - pylint (análise aprofundada, se disponível)
119
+ - mypy (verificação de tipos, se disponível)
120
+ - flake8 (estilo + erros, se disponível)
121
+
122
+ Para CSS/SCSS:
123
+ - stylelint (se disponível)
124
+
125
+ """
126
+
127
+ def __init__(
128
+ self, deliver: Callable[[list[Diag]], None], cfg: ConfigManager | None = None
129
+ ) -> None:
130
+ """
131
+ Inicializa o LintManager.
132
+
133
+ Args:
134
+ deliver: Callback invocado com a lista de diagnósticos ao fim de cada análise.
135
+ cfg: Instância do ConfigManager para ler configurações de linters.
136
+ """
137
+ self._deliver = deliver
138
+ self._cfg = cfg
139
+ self._root: tk.Misc | None = None
140
+ self._job: str | None = None
141
+ self._tool_cache: dict[str, str | None] = {}
142
+ self._cancel_event = threading.Event()
143
+ self._current_thread: threading.Thread | None = None
144
+ self._log_callback: Callable[[str, str, str], None] | None = None
145
+
146
+ def attach(self, root: tk.Misc) -> None:
147
+ """Vincula o LintManager à raiz Tk para poder agendar callbacks."""
148
+ self._root = root
149
+
150
+ def set_log_callback(self, callback: Callable[[str, str, str], None]) -> None:
151
+ """Registra um callback de log chamado durante análise: (mensagem, nível, fonte)."""
152
+ self._log_callback = callback
153
+
154
+ def schedule(self, path: Path | None, content: str, lang: str) -> None:
155
+ """Agenda análise de lint com debounce; análises anteriores são canceladas."""
156
+ if not self._root:
157
+ return
158
+ if not (self._cfg.get("lint_enabled") if self._cfg else True):
159
+ return
160
+ if self._job:
161
+ self._root.after_cancel(self._job)
162
+ self._job = self._root.after(
163
+ LINT_DELAY,
164
+ lambda: self._start_thread(path, content, lang),
165
+ )
166
+
167
+ def _start_thread(self, path: Path | None, content: str, lang: str) -> None:
168
+ """Cancela a thread de lint em curso (se houver) e inicia uma nova."""
169
+ self._cancel_event.set()
170
+ self._cancel_event = threading.Event()
171
+ t = threading.Thread(
172
+ target=self._run,
173
+ args=(path, content, lang, self._cancel_event),
174
+ daemon=True,
175
+ )
176
+ self._current_thread = t
177
+ t.start()
178
+
179
+ def cancel(self) -> None:
180
+ """Cancela imediatamente qualquer análise agendada ou em andamento."""
181
+ if self._root and self._job:
182
+ self._root.after_cancel(self._job)
183
+ self._job = None
184
+ self._cancel_event.set()
185
+
186
+ def _run(
187
+ self, path: Path | None, content: str, lang: str, cancel: threading.Event
188
+ ) -> None:
189
+ """Executa os linters em thread daemon e entrega os diagnósticos via callback e EventBus."""
190
+ if cancel.is_set():
191
+ if _get_bus():
192
+ _get_bus().emit(
193
+ "lint.cancelled",
194
+ {"path": str(path) if path else "", "lang": lang},
195
+ source="LintManager",
196
+ )
197
+ return
198
+ if _get_bus():
199
+ _get_bus().emit(
200
+ "lint.started",
201
+ {"path": str(path) if path else "", "lang": lang},
202
+ source="LintManager",
203
+ )
204
+ try:
205
+ diags: list[Diag] = []
206
+ if lang in LINT_JS:
207
+ diags = self._lint_js(path, content, cancel)
208
+ elif lang in LINT_PY:
209
+ diags = self._lint_python(path, content, cancel)
210
+ elif lang in LINT_CSS:
211
+ diags = self._stylelint(path, cancel)
212
+ elif lang in LINT_HTML:
213
+ diags = self._lint_html(path, content, cancel)
214
+ elif lang in LINT_PHP:
215
+ diags = self._lint_php(path, content, cancel)
216
+ except (OSError, ValueError, RuntimeError) as exc:
217
+ logger.debug("Lint run error: %s", exc)
218
+ if _get_bus():
219
+ _get_bus().emit(
220
+ "lint.error",
221
+ {
222
+ "path": str(path) if path else "",
223
+ "lang": lang,
224
+ "error": str(exc),
225
+ },
226
+ source="LintManager",
227
+ )
228
+ diags = []
229
+ if cancel.is_set():
230
+ if _get_bus():
231
+ _get_bus().emit(
232
+ "lint.cancelled",
233
+ {"path": str(path) if path else "", "lang": lang},
234
+ source="LintManager",
235
+ )
236
+ return
237
+
238
+ if _get_bus():
239
+ _get_bus().emit(
240
+ "lint.result",
241
+ {
242
+ "path": str(path) if path else "",
243
+ "lang": lang,
244
+ "diags": diags,
245
+ },
246
+ source="LintManager",
247
+ )
248
+
249
+ if self._root:
250
+ self._root.after(0, lambda: self._deliver(diags))
251
+
252
+ def _find_tool(self, name: str, config_key: str | None = None) -> str | None:
253
+ """Resolve caminho de uma ferramenta (com cache)."""
254
+ if name in self._tool_cache:
255
+ return self._tool_cache[name]
256
+
257
+ if config_key and self._cfg is not None:
258
+ configured = self._cfg.get(config_key, "")
259
+ if configured and shutil.which(configured):
260
+ self._tool_cache[name] = configured
261
+ return configured
262
+ result = shutil.which(name)
263
+
264
+ if not result:
265
+ local = Path.cwd() / "node_modules" / ".bin" / name
266
+ if sys.platform == "win32":
267
+ local = local.with_suffix(".cmd")
268
+ if local.exists():
269
+ result = str(local)
270
+ self._tool_cache[name] = result
271
+ return result
272
+
273
+ @staticmethod
274
+ def _run_proc(
275
+ cmd: list[str],
276
+ cwd: Path | None = None,
277
+ input_text: str | None = None,
278
+ timeout: int = 20,
279
+ ) -> tuple[int, str, str]:
280
+ """Executa um subprocesso e retorna (returncode, stdout, stderr)."""
281
+ try:
282
+ kwargs: dict[str, Any] = {
283
+ "capture_output": True,
284
+ "text": True,
285
+ "timeout": timeout,
286
+ "encoding": "utf-8",
287
+ "errors": "replace",
288
+ }
289
+ if cwd:
290
+ kwargs["cwd"] = str(cwd)
291
+ if input_text is not None:
292
+ kwargs["input"] = input_text
293
+ if sys.platform == "win32":
294
+ kwargs["creationflags"] = subprocess.CREATE_NO_WINDOW
295
+ kwargs["shell"] = True
296
+ r = subprocess.run(cmd, check=False, **kwargs)
297
+ return r.returncode, r.stdout, r.stderr
298
+ except subprocess.TimeoutExpired:
299
+ return -1, "", "timeout"
300
+ except (OSError, ValueError) as exc:
301
+ return -1, "", str(exc)
302
+
303
+ def _lint_js(
304
+ self, path: Path | None, content: str, cancel: threading.Event
305
+ ) -> list[Diag]:
306
+ """Executa o ESLint e retorna os diagnósticos.
307
+
308
+ Args:
309
+ path: Caminho do arquivo.
310
+ content: Conteúdo do arquivo.
311
+
312
+ Returns:
313
+ Lista de objetos Diag.
314
+ """
315
+ if cancel.is_set():
316
+ return []
317
+ if not (self._cfg.get("lint_js") if self._cfg else True):
318
+ return []
319
+ diags = self._eslint(path, content, cancel)
320
+ return diags
321
+
322
+ def _eslint(
323
+ self, path: Path | None, content: str, cancel: threading.Event
324
+ ) -> list[Diag]:
325
+ """
326
+ Executa ESLint via stdin com fallback por arquivo.
327
+ BUGS CORRIGIDOS:
328
+ 1. `cwd` era NameError (undefined) - silenciado pelo except -> lista vazia.
329
+ 3. rc=1 é normal quando há erros de lint no ESLint v8+ FlatConfig.
330
+ """
331
+ eslint = self._find_tool("eslint", "eslint_path")
332
+ if not eslint:
333
+ if self._root and hasattr(self, "_log_callback"):
334
+ self._root.after(
335
+ 0,
336
+ lambda: self._log_callback(
337
+ "⚠ ESLint não encontrado. Instale: npm i -g eslint",
338
+ "ESLint",
339
+ "warn",
340
+ ),
341
+ )
342
+ return []
343
+
344
+ cwd: Path | None = path.parent if path else None
345
+
346
+ def _log(msg: str, lvl: str = "info") -> None:
347
+ if self._root and hasattr(self, "_log_callback"):
348
+ self._root.after(
349
+ 0, lambda m=msg, l_=lvl: self._log_callback(
350
+ m, "ESLint", l_)
351
+ )
352
+
353
+ filename = str(path) if path else "untitled.js"
354
+ cmd = [eslint, "--format", "json",
355
+ "--stdin-filename", filename, "--stdin"]
356
+
357
+ try:
358
+ _log(f"▶ ESLint (stdin): {filename}", "info")
359
+ rc, stdout, stderr = self._run_proc(
360
+ cmd, cwd=cwd, input_text=content, timeout=25
361
+ )
362
+ if cancel.is_set():
363
+ return []
364
+ if rc == 2:
365
+ _log(f"✖ ESLint erro fatal (rc=2): {stderr[:200]}", "error")
366
+ raise RuntimeError(f"ESLint fatal (rc=2): {stderr[:200]}")
367
+ if stderr.strip():
368
+ _log(f" stderr: {stderr.strip()[:300]}", "warn")
369
+ result = self._parse_eslint(_json_array_from_output(stdout))
370
+ _log(f"✔ ESLint concluído - {len(result)} diagnóstico(s)", "info")
371
+ return result
372
+ except (json.JSONDecodeError, ValueError):
373
+ pass
374
+ except (OSError, RuntimeError) as exc:
375
+ _log(f"✖ ESLint stdin error: {exc}", "error")
376
+ logger.debug("ESLint stdin error: %s", exc)
377
+
378
+ if not path:
379
+ return []
380
+ cmd2 = [eslint, "--format", "json", str(path)]
381
+ try:
382
+ _log(f"▶ ESLint (file): {path.name}", "info")
383
+ rc, stdout, stderr = self._run_proc(cmd2, cwd=cwd, timeout=25)
384
+ if cancel.is_set():
385
+ return []
386
+ if rc == 2:
387
+ return []
388
+ result = self._parse_eslint(_json_array_from_output(stdout))
389
+ _log(f"✔ ESLint concluído - {len(result)} diagnóstico(s)", "info")
390
+ return result
391
+ except (OSError, json.JSONDecodeError, ValueError) as exc:
392
+ _log(f"✖ ESLint file error: {exc}", "error")
393
+ logger.debug("ESLint file error: %s", exc)
394
+ return []
395
+
396
+ @staticmethod
397
+ def _parse_eslint(data: Any) -> list[Diag]:
398
+ """Parseia a saída JSON do ESLint para objetos Diag.
399
+
400
+ Args:
401
+ output: Saída JSON do ESLint.
402
+
403
+ Returns:
404
+ Lista de Diag.
405
+ """
406
+ out: list[Diag] = []
407
+ for file_result in data if isinstance(data, list) else []:
408
+ for m in file_result.get("messages", []):
409
+ sev_raw = m.get("severity", 1)
410
+
411
+ sev = 1 if sev_raw == 2 else 2
412
+ fix = m.get("fix")
413
+ out.append(
414
+ Diag(
415
+ line=m.get("line", 1),
416
+ col=max(0, m.get("column", 1) - 1),
417
+ end_col=max(
418
+ 0, m.get("endColumn", m.get("column", 1)) - 1),
419
+ severity=sev,
420
+ message=m.get("message", ""),
421
+ rule=m.get("ruleId") or "",
422
+ source="eslint",
423
+ fix=fix,
424
+ )
425
+ )
426
+ return out
427
+
428
+ def _lint_html(
429
+ self, path: Path | None, content: str, cancel: threading.Event
430
+ ) -> list[Diag]:
431
+ """Executa validação HTML via tidy-html5 (se disponível) e retorna diagnósticos."""
432
+ if cancel.is_set():
433
+ return []
434
+ tidy = self._find_tool("tidy")
435
+ if not tidy:
436
+ return self._lint_html_basic(content)
437
+ with tempfile.NamedTemporaryFile(
438
+ mode="w", suffix=".html", delete=False, encoding="utf-8"
439
+ ) as tmp:
440
+ tmp.write(content)
441
+ tmp_path = tmp.name
442
+ try:
443
+ _, _, stderr = self._run_proc(
444
+ [tidy, "-quiet", "-errors", "--gnu-emacs", "yes", tmp_path],
445
+ timeout=15,
446
+ )
447
+ if cancel.is_set():
448
+ return []
449
+ diags: list[Diag] = []
450
+
451
+ pattern = re.compile(
452
+ r"(?:line\s+(\d+)\s+column\s+(\d+)\s+-\s+)?(Warning|Error|Info):?\s+(.+)",
453
+ re.IGNORECASE,
454
+ )
455
+ for ln in stderr.splitlines():
456
+ m = pattern.search(ln)
457
+ if not m:
458
+ continue
459
+ line_n = int(m.group(1)) if m.group(1) else 1
460
+ col_n = int(m.group(2)) if m.group(2) else 0
461
+ level = m.group(3).lower()
462
+ msg = m.group(4).strip()
463
+ sev = 1 if level == "error" else (
464
+ 2 if level == "warning" else 3)
465
+ diags.append(
466
+ Diag(
467
+ line=line_n,
468
+ col=col_n,
469
+ end_col=col_n + 1,
470
+ severity=sev,
471
+ message=msg,
472
+ rule="tidy",
473
+ source="tidy",
474
+ )
475
+ )
476
+ return diags[:200]
477
+ except Exception as exc:
478
+ logger.debug("tidy html lint error: %s", exc)
479
+ return []
480
+ finally:
481
+ with contextlib.suppress(OSError):
482
+ os.unlink(tmp_path)
483
+
484
+ def _lint_html_basic(self, content: str) -> list[Diag]:
485
+ """Validação HTML heurística sem ferramentas externas."""
486
+ diags: list[Diag] = []
487
+
488
+ stack: list[tuple[str, int]] = []
489
+ void_tags = {
490
+ "area",
491
+ "base",
492
+ "br",
493
+ "col",
494
+ "embed",
495
+ "hr",
496
+ "img",
497
+ "input",
498
+ "link",
499
+ "meta",
500
+ "param",
501
+ "source",
502
+ "track",
503
+ "wbr",
504
+ }
505
+ tag_re = re.compile(r"<(/?)([A-Za-z][A-Za-z0-9]*)[^>]*(/?)>")
506
+ for line_n, line in enumerate(content.splitlines(), 1):
507
+ for m in tag_re.finditer(line):
508
+ closing = m.group(1) == "/"
509
+ tag_name = m.group(2).lower()
510
+ self_cl = m.group(3) == "/"
511
+ if tag_name in void_tags or self_cl:
512
+ continue
513
+ if closing:
514
+ if stack and stack[-1][0] == tag_name:
515
+ stack.pop()
516
+ else:
517
+ diags.append(
518
+ Diag(
519
+ line=line_n,
520
+ col=m.start(),
521
+ end_col=m.end(),
522
+ severity=2,
523
+ message=f"Tag de fechamento inesperada: </{tag_name}>",
524
+ rule="html-mismatch",
525
+ source="codis-html",
526
+ )
527
+ )
528
+ else:
529
+ stack.append((tag_name, line_n))
530
+ for tag_name, line_n in stack[-10:]:
531
+ diags.append(
532
+ Diag(
533
+ line=line_n,
534
+ col=0,
535
+ end_col=0,
536
+ severity=2,
537
+ message=f"Tag não fechada: <{tag_name}>",
538
+ rule="html-unclosed",
539
+ source="codis-html",
540
+ )
541
+ )
542
+ return diags[:200]
543
+
544
+ def _lint_php(
545
+ self, path: Path | None, content: str, cancel: threading.Event
546
+ ) -> list[Diag]:
547
+ """Executa php -l (lint syntax) se disponível."""
548
+ if cancel.is_set():
549
+ return []
550
+ php = self._find_tool("php")
551
+ if not php:
552
+ return []
553
+ with tempfile.NamedTemporaryFile(
554
+ mode="w", suffix=".php", delete=False, encoding="utf-8"
555
+ ) as tmp:
556
+ tmp.write(content)
557
+ tmp_path = tmp.name
558
+ try:
559
+ _, stdout, stderr = self._run_proc(
560
+ [php, "-l", tmp_path], timeout=10)
561
+ if cancel.is_set():
562
+ return []
563
+ diags: list[Diag] = []
564
+ err_re = re.compile(
565
+ r"(Parse|Fatal) error:\s+(.+?)\s+in\s+.+?\s+on\s+line\s+(\d+)"
566
+ )
567
+ for ln in (stdout + stderr).splitlines():
568
+ m = err_re.search(ln)
569
+ if m:
570
+ diags.append(
571
+ Diag(
572
+ line=int(m.group(3)),
573
+ col=0,
574
+ end_col=0,
575
+ severity=1,
576
+ message=m.group(2).strip(),
577
+ rule="php-syntax",
578
+ source="php",
579
+ )
580
+ )
581
+ return diags
582
+ except Exception as exc:
583
+ logger.debug("php lint error: %s", exc)
584
+ return []
585
+ finally:
586
+ with contextlib.suppress(OSError):
587
+ os.unlink(tmp_path)
588
+
589
+ def format_prettier(self, path: Path, content: str) -> str | None:
590
+ """Formata usando Prettier. Retorna texto formatado ou None."""
591
+ prettier = self._find_tool("prettier", "prettier_path")
592
+ if not prettier:
593
+ return None
594
+ cwd = path.parent
595
+ ext = path.suffix.lstrip(".")
596
+ parser_map = {
597
+ "js": "babel",
598
+ "mjs": "babel",
599
+ "cjs": "babel",
600
+ "jsx": "babel",
601
+ "ts": "typescript",
602
+ "tsx": "typescript",
603
+ "json": "json",
604
+ "jsonc": "json",
605
+ "json5": "json5",
606
+ "css": "css",
607
+ "scss": "scss",
608
+ "less": "less",
609
+ "html": "html",
610
+ "htm": "html",
611
+ "vue": "html",
612
+ "svelte": "html",
613
+ "md": "markdown",
614
+ "mdx": "mdx",
615
+ "yaml": "yaml",
616
+ "yml": "yaml",
617
+ "graphql": "graphql",
618
+ "gql": "graphql",
619
+ }
620
+ parser = parser_map.get(ext)
621
+ if not parser:
622
+ return None
623
+ cmd = [prettier, "--stdin-filepath", str(path), "--parser", parser]
624
+ rc, stdout, stderr = self._run_proc(
625
+ cmd, cwd=cwd, input_text=content, timeout=15
626
+ )
627
+ if rc == 0 and stdout:
628
+ return stdout
629
+ logger.debug("Prettier error: %s", stderr[:200])
630
+ return None
631
+
632
+ def _lint_python(
633
+ self, path: Path | None, content: str, cancel: threading.Event
634
+ ) -> list[Diag]:
635
+ """Executa os linters Python (pylint, flake8, mypy) e retorna os diagnósticos.
636
+
637
+ Args:
638
+ path: Caminho do arquivo.
639
+ content: Conteúdo do arquivo.
640
+
641
+ Returns:
642
+ Lista de objetos Diag.
643
+ """
644
+ if not (self._cfg.get("lint_python") if self._cfg else True):
645
+ return []
646
+ diags: list[Diag] = []
647
+
648
+ def _log(msg: str, lvl: str = "info") -> None:
649
+ if self._root and hasattr(self, "_log_callback"):
650
+ self._root.after(
651
+ 0, lambda m=msg, l_=lvl: self._log_callback(
652
+ m, "Python", l_)
653
+ )
654
+
655
+ fname = path.name if path else "untitled.py"
656
+ _log(f"▶ Python lint: {fname}", "info")
657
+
658
+ syntax_diags = self._py_syntax(content)
659
+ diags.extend(syntax_diags)
660
+ if syntax_diags:
661
+ _log(
662
+ f"✖ Erro de sintaxe em {fname}: {syntax_diags[0].message}", "error")
663
+ return diags
664
+ if cancel.is_set():
665
+ return diags
666
+
667
+ if not path:
668
+ return diags
669
+
670
+ if cancel.is_set():
671
+ return diags
672
+ pf = self._pyflakes(path, cancel)
673
+ diags.extend(pf)
674
+ if pf:
675
+ _log(f" pyflakes: {len(pf)} aviso(s)", "warn")
676
+
677
+ if cancel.is_set():
678
+ return diags
679
+ flake8_diags = self._flake8(path, cancel)
680
+
681
+ existing_msgs = {(d.line, d.message[:30]) for d in diags}
682
+ for d in flake8_diags:
683
+ if (d.line, d.message[:30]) not in existing_msgs:
684
+ diags.append(d)
685
+ existing_msgs.add((d.line, d.message[:30]))
686
+ if flake8_diags:
687
+ _log(f" flake8: {len(flake8_diags)} problema(s)", "warn")
688
+
689
+ if self._cfg and self._cfg.get("mypy_path") and not cancel.is_set():
690
+ mypy_diags = self._mypy(path, cancel)
691
+ for d in mypy_diags:
692
+ if (d.line, d.message[:30]) not in existing_msgs:
693
+ diags.append(d)
694
+ if mypy_diags:
695
+ _log(f" mypy: {len(mypy_diags)} problema(s)", "warn")
696
+
697
+ _log(
698
+ f"✔ Python lint concluído - {len(diags)} diagnóstico(s) em {fname}", "info"
699
+ )
700
+ return diags
701
+
702
+ @staticmethod
703
+ def _py_syntax(content: str) -> list[Diag]:
704
+ """Verifica sintaxe Python via py_compile."""
705
+ import py_compile
706
+
707
+ tmp = None
708
+ try:
709
+ with tempfile.NamedTemporaryFile(
710
+ suffix=".py",
711
+ mode="w",
712
+ encoding="utf-8",
713
+ delete=False,
714
+ prefix="codis_lint_",
715
+ ) as f:
716
+ f.write(content)
717
+ tmp = f.name
718
+ try:
719
+ py_compile.compile(tmp, doraise=True)
720
+ except py_compile.PyCompileError as exc:
721
+ msg = str(exc)
722
+ m = re.search(r"line (\d+)", msg)
723
+ line = int(m.group(1)) if m else 1
724
+ clean = re.sub(
725
+ r"\s*\(.*?\)\s*$", "", msg.split("\n", maxsplit=1)[0]
726
+ ).strip()
727
+ clean = re.sub(r"Sorry.*?::", "", clean).strip()
728
+ return [
729
+ Diag(
730
+ line=line,
731
+ col=0,
732
+ end_col=0,
733
+ severity=1,
734
+ message=clean or "Syntax error",
735
+ source="py_compile",
736
+ )
737
+ ]
738
+ except OSError as exc:
739
+ logger.debug("py_syntax error: %s", exc)
740
+ finally:
741
+ if tmp:
742
+ with contextlib.suppress(OSError):
743
+ os.unlink(tmp)
744
+ return []
745
+
746
+ def _pyflakes(self, path: Path, cancel: threading.Event) -> list[Diag]:
747
+ pyflakes = self._find_tool("pyflakes")
748
+ if not pyflakes:
749
+ return []
750
+ _, stdout, stderr = self._run_proc([pyflakes, str(path)], timeout=15)
751
+ if cancel.is_set():
752
+ return []
753
+ out: list[Diag] = []
754
+ pattern = re.compile(r"^.+:(\d+):(\d+):\s*(.+)$")
755
+ pattern2 = re.compile(r"^.+:(\d+):\s*(.+)$")
756
+ for line in (stdout + stderr).splitlines():
757
+ m = pattern.match(line)
758
+ if m:
759
+ out.append(
760
+ Diag(
761
+ line=int(m.group(1)),
762
+ col=int(m.group(2)) - 1,
763
+ end_col=0,
764
+ severity=2,
765
+ message=m.group(3).strip(),
766
+ source="pyflakes",
767
+ )
768
+ )
769
+ continue
770
+ m2 = pattern2.match(line)
771
+ if m2:
772
+ out.append(
773
+ Diag(
774
+ line=int(m2.group(1)),
775
+ col=0,
776
+ end_col=0,
777
+ severity=2,
778
+ message=m2.group(2).strip(),
779
+ source="pyflakes",
780
+ )
781
+ )
782
+ return out
783
+
784
+ def _flake8(self, path: Path, cancel: threading.Event) -> list[Diag]:
785
+ flake8 = self._find_tool("flake8", "flake8_path")
786
+ if not flake8:
787
+ return []
788
+ _, stdout, _ = self._run_proc(
789
+ [
790
+ flake8,
791
+ "--format=default",
792
+ "--max-line-length=120",
793
+ "--extend-ignore=E501",
794
+ str(path),
795
+ ],
796
+ timeout=15,
797
+ )
798
+ if cancel.is_set():
799
+ return []
800
+ out: list[Diag] = []
801
+ pattern = re.compile(r"^.+:(\d+):(\d+):\s*([EWF]\d+)\s+(.+)$")
802
+ sev_map = {"E": 1, "F": 1, "W": 2, "C": 2, "N": 3, "B": 2}
803
+ for line in stdout.splitlines():
804
+ m = pattern.match(line)
805
+ if not m:
806
+ continue
807
+ code, msg = m.group(3), m.group(4)
808
+ sev = sev_map.get(code[0], 2)
809
+ out.append(
810
+ Diag(
811
+ line=int(m.group(1)),
812
+ col=max(0, int(m.group(2)) - 1),
813
+ end_col=0,
814
+ severity=sev,
815
+ message=f"{code} {msg}",
816
+ rule=code,
817
+ source="flake8",
818
+ )
819
+ )
820
+ return out
821
+
822
+ def _mypy(self, path: Path, cancel: threading.Event) -> list[Diag]:
823
+ mypy = self._find_tool("mypy", "mypy_path")
824
+ if not mypy:
825
+ return []
826
+ _, stdout, _ = self._run_proc(
827
+ [
828
+ mypy,
829
+ "--no-error-summary",
830
+ "--show-column-numbers",
831
+ "--ignore-missing-imports",
832
+ str(path),
833
+ ],
834
+ timeout=20,
835
+ )
836
+ if cancel.is_set():
837
+ return []
838
+ out: list[Diag] = []
839
+ pattern = re.compile(
840
+ r"^.+:(\d+):(\d+):\s*(error|warning|note):\s*(.+)$")
841
+ sev_map = {"error": 1, "warning": 2, "note": 3}
842
+ for line in stdout.splitlines():
843
+ m = pattern.match(line)
844
+ if m:
845
+ out.append(
846
+ Diag(
847
+ line=int(m.group(1)),
848
+ col=max(0, int(m.group(2)) - 1),
849
+ end_col=0,
850
+ severity=sev_map.get(m.group(3), 2),
851
+ message=m.group(4).strip(),
852
+ source="mypy",
853
+ )
854
+ )
855
+ return out
856
+
857
+ def _stylelint(
858
+ self, path: Path | None, cancel: threading.Event
859
+ ) -> list[Diag]:
860
+ """Executa stylelint no arquivo especificado e retorna diagnósticos CSS."""
861
+ stylelint = self._find_tool("stylelint")
862
+ if not stylelint:
863
+ return []
864
+ if not path:
865
+ return []
866
+ cwd = path.parent
867
+ _, stdout, _ = self._run_proc(
868
+ [stylelint, "--formatter", "json", str(path)],
869
+ cwd=cwd,
870
+ timeout=15,
871
+ )
872
+ if cancel.is_set():
873
+ return []
874
+ out: list[Diag] = []
875
+ try:
876
+ data = json.loads(stdout.strip() or "[]")
877
+ for file_res in data if isinstance(data, list) else []:
878
+ for w in file_res.get("warnings", []):
879
+ sev = 1 if w.get("severity") == "error" else 2
880
+ out.append(
881
+ Diag(
882
+ line=w.get("line", 1),
883
+ col=max(0, w.get("column", 1) - 1),
884
+ end_col=0,
885
+ severity=sev,
886
+ message=w.get("text", ""),
887
+ rule=w.get("rule", ""),
888
+ source="stylelint",
889
+ )
890
+ )
891
+ except (json.JSONDecodeError, ValueError) as exc:
892
+ logger.debug("stylelint parse error: %s", exc)
893
+ return out
894
+
895
+ def format_python(self, content: str) -> str | None:
896
+ """Formata Python com black ou autopep8. Retorna o conteúdo formatado ou None."""
897
+ black = self._find_tool("black")
898
+ if black:
899
+ tmp = None
900
+ try:
901
+ with tempfile.NamedTemporaryFile(
902
+ suffix=".py",
903
+ mode="w",
904
+ encoding="utf-8",
905
+ delete=False,
906
+ prefix="codis_fmt_",
907
+ ) as f:
908
+ f.write(content)
909
+ tmp = f.name
910
+ rc, _, _ = self._run_proc(
911
+ [black, "--quiet", "--line-length", "120", tmp],
912
+ timeout=15,
913
+ )
914
+ if rc == 0:
915
+ return Path(tmp).read_text(encoding="utf-8")
916
+ except OSError as exc:
917
+ logger.debug("black format error: %s", exc)
918
+ finally:
919
+ if tmp:
920
+ with contextlib.suppress(OSError):
921
+ os.unlink(tmp)
922
+
923
+ autopep8 = self._find_tool("autopep8")
924
+ if autopep8:
925
+ rc, stdout, _ = self._run_proc(
926
+ [autopep8, "--max-line-length", "120", "-"],
927
+ input_text=content,
928
+ timeout=15,
929
+ )
930
+ if rc == 0 and stdout:
931
+ return stdout
932
+ return None
933
+
934
+ @staticmethod
935
+ def apply_eslint_fix(content: str, fix: dict) -> str:
936
+ """Aplica uma única correção ESLint ao conteúdo usando offsets originais.
937
+
938
+ Usado apenas para fixes individuais (clique direito -> Corrigir).
939
+ Para múltiplos fixes simultâneos, use ``apply_all_eslint_fixes``.
940
+
941
+ Args:
942
+ content: Conteúdo original do arquivo.
943
+ fix: Dict ESLint com ``range`` ([start, end]) e ``text``.
944
+
945
+ Returns:
946
+ Conteúdo com a correção aplicada, ou o original em caso de erro.
947
+ """
948
+ if not fix:
949
+ return content
950
+ try:
951
+ rng = fix.get("range", [0, 0])
952
+ text = fix.get("text", "")
953
+ start, end = int(rng[0]), int(rng[1])
954
+ if start < 0 or end < start or end > len(content):
955
+ return content
956
+ return content[:start] + text + content[end:]
957
+ except (IndexError, TypeError, KeyError, ValueError):
958
+ return content
959
+
960
+ def apply_all_eslint_fixes(
961
+ self, path: Path, content: str, diags: list[Diag]
962
+ ) -> str:
963
+ """Aplica todas as correções ESLint delegando ao próprio ESLint (--fix-dry-run).
964
+
965
+ Estratégia (a mesma usada pelo VSCode com a extensão ESLint):
966
+
967
+ 1. **``--fix-dry-run`` via stdin** (ESLint >= 5): passa o conteúdo pelo
968
+ stdin e recebe de volta o arquivo corrigido no campo ``output`` do JSON.
969
+ Não toca o disco. É a abordagem mais segura e a que o ESLint usa
970
+ internamente para garantir que todos os fixes sejam aplicados de forma
971
+ atômica e correta.
972
+
973
+ 2. **Fallback via arquivo temporário** (ESLint antigo ou --fix-dry-run
974
+ indisponível): grava o conteúdo num arquivo .js temporário, executa
975
+ ``eslint --fix`` sobre ele e lê o resultado de volta. O arquivo
976
+ original nunca é tocado.
977
+
978
+ 3. **Último recurso**: se o ESLint não estiver disponível, aplica cada
979
+ fix individualmente em ordem reversa - menos confiável, mas melhor
980
+ que nada para um único fix isolado.
981
+
982
+ Args:
983
+ path: Caminho original do arquivo (usado como ``--stdin-filename``
984
+ para que o ESLint encontre a config correta).
985
+ content: Conteúdo atual do arquivo no editor.
986
+ diags: Lista de diagnósticos; apenas os que têm ``fix`` são usados
987
+ para decidir se há algo a corrigir.
988
+
989
+ Returns:
990
+ Conteúdo com todas as correções aplicadas, ou o original se nada
991
+ puder ser corrigido.
992
+ """
993
+ if not any(d.fix for d in diags):
994
+ return content
995
+
996
+ eslint = self._find_tool("eslint", "eslint_path")
997
+ if not eslint:
998
+ fixable = sorted(
999
+ [d for d in diags if d.fix],
1000
+ key=lambda d: d.fix.get("range", [0])[0],
1001
+ reverse=True,
1002
+ )
1003
+ result = content
1004
+ for d in fixable:
1005
+ result = self.apply_eslint_fix(result, d.fix)
1006
+ return result
1007
+
1008
+ cwd = path.parent if path else None
1009
+ filename = str(path) if path else "untitled.js"
1010
+
1011
+ cmd_dry = [
1012
+ eslint,
1013
+ "--fix-dry-run",
1014
+ "--format",
1015
+ "json",
1016
+ "--stdin-filename",
1017
+ filename,
1018
+ "--stdin",
1019
+ ]
1020
+ with contextlib.suppress(OSError, json.JSONDecodeError, ValueError, IndexError):
1021
+ rc, stdout, _stderr = self._run_proc(
1022
+ cmd_dry, cwd=cwd, input_text=content, timeout=30
1023
+ )
1024
+ if rc in (0, 1):
1025
+ data = _json_array_from_output(stdout)
1026
+ if isinstance(data, list) and data:
1027
+ output = data[0].get("output")
1028
+ if output and isinstance(output, str):
1029
+ return output
1030
+ if rc in (0, 1):
1031
+ return content
1032
+
1033
+ suffix = path.suffix if path else ".js"
1034
+ tmp_path: Path | None = None
1035
+ try:
1036
+ with tempfile.NamedTemporaryFile(
1037
+ mode="w",
1038
+ suffix=suffix,
1039
+ delete=False,
1040
+ encoding="utf-8",
1041
+ errors="replace",
1042
+ ) as tmp:
1043
+ tmp.write(content)
1044
+ tmp_path = Path(tmp.name)
1045
+
1046
+ cmd_fix = [eslint, "--fix", str(tmp_path)]
1047
+ rc2, _out2, _err2 = self._run_proc(cmd_fix, cwd=cwd, timeout=30)
1048
+ if rc2 in (0, 1) and tmp_path.exists():
1049
+ fixed = tmp_path.read_text(encoding="utf-8", errors="replace")
1050
+ return fixed
1051
+ except (OSError, ValueError):
1052
+ pass
1053
+ finally:
1054
+ if tmp_path and tmp_path.exists():
1055
+ with contextlib.suppress(OSError):
1056
+ tmp_path.unlink()
1057
+
1058
+ return content