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
@@ -0,0 +1,63 @@
1
+ """Catálogos de extensões consultados sob demanda (Open VSX, JetBrains, Pulsar, MELPA, GitHub)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import threading
6
+ from collections.abc import Callable
7
+ from dataclasses import dataclass, field
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from ..net import Net
12
+
13
+
14
+ @dataclass
15
+ class Listing:
16
+ source: str
17
+ key: str # identificador dentro do catálogo
18
+ title: str
19
+ version: str = ""
20
+ description: str = ""
21
+ author: str = ""
22
+ downloads: int = 0
23
+ page: str = ""
24
+ extra: dict[str, Any] = field(default_factory=dict)
25
+
26
+
27
+ class Source:
28
+ """Um catálogo. ``hosts`` é tudo o que ele pode contatar, redirecionamentos inclusos."""
29
+
30
+ id = ""
31
+ label = ""
32
+ formats = "" # o que se espera encontrar
33
+ hosts: tuple[str, ...] = ()
34
+ base = ""
35
+
36
+ def __init__(self, net: Net | None = None, base: str | None = None) -> None:
37
+ self.net = net or Net(self.hosts)
38
+ if base:
39
+ self.base = base.rstrip("/")
40
+
41
+ def search(self, query: str, limit: int = 20) -> list[Listing]:
42
+ raise NotImplementedError
43
+
44
+ def download(self, item: Listing) -> Path:
45
+ raise NotImplementedError
46
+
47
+
48
+ def search_many(
49
+ sources: list[Source], query: str, limit: int, on_done: Callable[[Source, list[Listing] | None, Exception | None], None]
50
+ ) -> list[threading.Thread]:
51
+ """Consulta os catálogos em paralelo; ``on_done`` roda em thread de apoio, uma vez por catálogo."""
52
+
53
+ def run(src: Source) -> None:
54
+ try:
55
+ result, error = src.search(query, limit), None
56
+ except Exception as exc: # cada catálogo falha sozinho; o erro vai para a interface
57
+ result, error = None, exc
58
+ on_done(src, result, error)
59
+
60
+ threads = [threading.Thread(target=run, args=(s,), daemon=True, name=f"market-{s.id}") for s in sources]
61
+ for t in threads:
62
+ t.start()
63
+ return threads
@@ -0,0 +1,211 @@
1
+ """Os catálogos conhecidos. Todos só leem e baixam; nada é instalado sem o usuário escolher."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import tempfile
7
+ import time
8
+ import urllib.parse
9
+ from pathlib import Path
10
+ from typing import Any, ClassVar
11
+
12
+ from ..net import Net, NetError
13
+ from ..openvsx import ALLOWED_HOSTS as OPENVSX_HOSTS
14
+ from ..openvsx import OpenVSX
15
+ from . import Listing, Source
16
+
17
+ MAX_DOWNLOAD = 80 * 1024 * 1024
18
+ _SAFE = re.compile(r"^[\w.@+-]+$")
19
+
20
+
21
+ def _tmp(name: str) -> Path:
22
+ safe = re.sub(r"[^\w.+-]", "_", name)[:80] or "extensao"
23
+ return Path(tempfile.mkdtemp(prefix="codis-mkt-")) / safe
24
+
25
+
26
+ def _int(value: Any) -> int:
27
+ try:
28
+ return int(value)
29
+ except (TypeError, ValueError):
30
+ return 0
31
+
32
+
33
+ class OpenVsxSource(Source):
34
+ id = "openvsx"
35
+ label = "Open VSX"
36
+ formats = "VS Code (temas, snippets, linguagens, código)"
37
+ hosts = OPENVSX_HOSTS
38
+
39
+ base = "https://open-vsx.org/api"
40
+
41
+ def __init__(self, net: Net | None = None, base: str | None = None) -> None:
42
+ super().__init__(net, base)
43
+ self._client = OpenVSX(self.base, self.hosts)
44
+ self._client.net = self.net
45
+
46
+ def search(self, query: str, limit: int = 20) -> list[Listing]:
47
+ return [
48
+ Listing(self.id, r["id"], r["title"], r["version"], r["description"], r["namespace"], _int(r["downloads"]),
49
+ f"https://open-vsx.org/extension/{r['namespace']}/{r['name']}", {"r": r})
50
+ for r in self._client.search(query, limit)
51
+ ]
52
+
53
+ def download(self, item: Listing) -> Path:
54
+ r = item.extra["r"]
55
+ return self._client.download(r["namespace"], r["name"], None, r.get("download_url", ""))
56
+
57
+
58
+ class JetBrainsSource(Source):
59
+ id = "jetbrains"
60
+ label = "JetBrains Marketplace"
61
+ formats = "IntelliJ IDEA, PyCharm e demais (temas, esquemas, live templates)"
62
+ hosts = ("plugins.jetbrains.com", "downloads.marketplace.jetbrains.com")
63
+ base = "https://plugins.jetbrains.com"
64
+
65
+ def search(self, query: str, limit: int = 20) -> list[Listing]:
66
+ qs = urllib.parse.urlencode({"search": query, "max": max(1, min(limit, 50)), "orderBy": "downloads"})
67
+ data = self.net.get_json(f"{self.base}/api/search/plugins?{qs}")
68
+ items = data.get("plugins") if isinstance(data, dict) else data
69
+ out: list[Listing] = []
70
+ for it in items if isinstance(items, list) else []:
71
+ if not isinstance(it, dict) or not it.get("id"):
72
+ continue
73
+ out.append(Listing(
74
+ self.id, str(it["id"]), str(it.get("name") or it["id"]), "", str(it.get("preview") or it.get("description") or ""),
75
+ str(it.get("vendor") or it.get("organization") or ""), _int(it.get("downloads")),
76
+ self.base + str(it.get("link") or f"/plugin/{it['id']}"), {"id": it["id"]},
77
+ ))
78
+ return out
79
+
80
+ def download(self, item: Listing) -> Path:
81
+ plugin_id = str(item.extra["id"])
82
+ if not plugin_id.isdigit():
83
+ raise NetError("identificador de plugin inválido")
84
+ updates = self.net.get_json(f"{self.base}/api/plugins/{plugin_id}/updates?size=1")
85
+ first = updates[0] if isinstance(updates, list) and updates else None
86
+ if not isinstance(first, dict) or not first.get("id"):
87
+ raise NetError("o Marketplace não listou versões deste plugin")
88
+ url = f"{self.base}/plugin/download?updateId={int(first['id'])}"
89
+ return self.net.download(url, _tmp(f"jetbrains-{plugin_id}.zip"), MAX_DOWNLOAD)
90
+
91
+
92
+ class PulsarSource(Source):
93
+ id = "pulsar"
94
+ label = "Pulsar Package Registry"
95
+ formats = "Pulsar/Atom (temas, gramáticas, snippets)"
96
+ hosts = ("api.pulsar-edit.dev", "web.pulsar-edit.dev", "github.com", "api.github.com", "codeload.github.com")
97
+ base = "https://api.pulsar-edit.dev/api"
98
+
99
+ def search(self, query: str, limit: int = 20) -> list[Listing]:
100
+ data = self.net.get_json(f"{self.base}/packages/search?{urllib.parse.urlencode({'q': query})}")
101
+ out: list[Listing] = []
102
+ for it in (data if isinstance(data, list) else [])[:limit]:
103
+ if not isinstance(it, dict) or not _SAFE.match(str(it.get("name") or "")):
104
+ continue
105
+ meta = it.get("metadata") if isinstance(it.get("metadata"), dict) else {}
106
+ version = str((it.get("releases") or {}).get("latest") or meta.get("version") or "")
107
+ out.append(Listing(
108
+ self.id, it["name"], it["name"], version, str(meta.get("description") or ""), "", _int(it.get("downloads")),
109
+ f"https://web.pulsar-edit.dev/packages/{it['name']}", {"name": it["name"], "version": version},
110
+ ))
111
+ return out
112
+
113
+ def download(self, item: Listing) -> Path:
114
+ name, version = item.extra["name"], item.extra.get("version") or ""
115
+ if not version or not _SAFE.match(version):
116
+ data = self.net.get_json(f"{self.base}/packages/{name}")
117
+ version = str(((data or {}).get("releases") or {}).get("latest") or "")
118
+ if not _SAFE.match(version):
119
+ raise NetError("versão do pacote não informada pelo registro")
120
+ url = f"{self.base}/packages/{name}/versions/{version}/tarball"
121
+ return self.net.download(url, _tmp(f"{name}-{version}.tar.gz"), MAX_DOWNLOAD)
122
+
123
+
124
+ class MelpaSource(Source):
125
+ id = "melpa"
126
+ label = "MELPA (Emacs)"
127
+ formats = "Emacs (temas, modos, snippets)"
128
+ hosts = ("melpa.org", "stable.melpa.org")
129
+ base = "https://melpa.org"
130
+ _cache: ClassVar[tuple[float, dict[str, Any], str] | None] = None
131
+
132
+ def _archive(self) -> dict[str, Any]:
133
+ cached = MelpaSource._cache
134
+ if cached and cached[2] == self.base and time.monotonic() - cached[0] < 600:
135
+ return cached[1]
136
+ data = self.net.get_json(f"{self.base}/archive.json", limit=16 * 1024 * 1024)
137
+ if not isinstance(data, dict):
138
+ raise NetError("resposta inválida do MELPA")
139
+ MelpaSource._cache = (time.monotonic(), data, self.base)
140
+ return data
141
+
142
+ def search(self, query: str, limit: int = 20) -> list[Listing]:
143
+ words = query.lower().split()
144
+ out: list[Listing] = []
145
+ for name, info in self._archive().items():
146
+ if not isinstance(info, dict) or not _SAFE.match(name):
147
+ continue
148
+ desc = str(info.get("desc") or "")
149
+ hay = f"{name} {desc}".lower()
150
+ if all(w in hay for w in words):
151
+ ver = ".".join(str(x) for x in info.get("ver") or [])
152
+ kind = str((info.get("props") or {}).get("kind") or "single")
153
+ out.append(Listing(self.id, name, name, ver, desc, "", 0, f"https://melpa.org/#/{name}", {"ver": ver, "kind": kind}))
154
+ out.sort(key=lambda it: (not it.key.endswith("-theme"), len(it.key)))
155
+ return out[:limit]
156
+
157
+ def download(self, item: Listing) -> Path:
158
+ ver = str(item.extra["ver"])
159
+ if not _SAFE.match(ver):
160
+ raise NetError("versão inválida")
161
+ suffix = "tar" if item.extra.get("kind") == "tar" else "el"
162
+ url = f"{self.base}/packages/{item.key}-{ver}.{suffix}"
163
+ return self.net.download(url, _tmp(f"{item.key}-{ver}.{suffix}"), MAX_DOWNLOAD)
164
+
165
+
166
+ class GitHubSource(Source):
167
+ """Repositórios do GitHub: serve a qualquer editor cujo tema ou extensão esteja publicado lá."""
168
+
169
+ id = "github"
170
+ label = "GitHub"
171
+ formats = "qualquer formato reconhecido (Sublime, Zed, Vim, Geany, Notepad++, Kate...)"
172
+ hosts = ("api.github.com", "codeload.github.com", "github.com")
173
+ base = "https://api.github.com"
174
+ download_base = "https://codeload.github.com"
175
+ _REPO = re.compile(r"^(?:https?://github\.com/)?([\w-][\w.-]*/[\w-][\w.-]*?)(?:\.git)?/?$")
176
+
177
+ def __init__(self, net: Net | None = None, base: str | None = None, download_base: str | None = None) -> None:
178
+ super().__init__(net, base)
179
+ if download_base:
180
+ self.download_base = download_base.rstrip("/")
181
+
182
+ def search(self, query: str, limit: int = 20) -> list[Listing]:
183
+ direct = self._REPO.match(query.strip())
184
+ if direct:
185
+ data = self.net.get_json(f"{self.base}/repos/{direct.group(1)}")
186
+ repos = [data] if isinstance(data, dict) else []
187
+ else:
188
+ qs = urllib.parse.urlencode({"q": query, "per_page": max(1, min(limit, 30)), "sort": "stars"})
189
+ data = self.net.get_json(f"{self.base}/search/repositories?{qs}")
190
+ repos = data.get("items") if isinstance(data, dict) else []
191
+ out: list[Listing] = []
192
+ for r in repos or []:
193
+ if isinstance(r, dict) and self._REPO.match(str(r.get("full_name") or "")):
194
+ out.append(Listing(
195
+ self.id, r["full_name"], r["full_name"], str(r.get("default_branch") or ""), str(r.get("description") or ""),
196
+ str((r.get("owner") or {}).get("login") or ""), _int(r.get("stargazers_count")),
197
+ str(r.get("html_url") or ""), {"branch": r.get("default_branch") or "main"},
198
+ ))
199
+ return out
200
+
201
+ def download(self, item: Listing) -> Path:
202
+ branch = str(item.extra.get("branch") or "main")
203
+ parts = branch.split("/")
204
+ if not _SAFE.match(branch.replace("/", "_")) or ".." in parts or "" in parts or not self._REPO.match(item.key):
205
+ raise NetError("repositório ou ramo inválido")
206
+ url = f"{self.download_base}/{item.key}/zip/refs/heads/{branch}"
207
+ return self.net.download(url, _tmp(f"{item.key.replace('/', '_')}.zip"), MAX_DOWNLOAD)
208
+
209
+
210
+ def default_sources() -> list[Source]:
211
+ return [OpenVsxSource(), JetBrainsSource(), PulsarSource(), MelpaSource(), GitHubSource()]
src/extcompat/model.py ADDED
@@ -0,0 +1,88 @@
1
+ """Estruturas de dados da camada de compatibilidade (sem Tkinter)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+
10
+ @dataclass
11
+ class ThemeSpec:
12
+ """Tema já traduzido: ``fields`` usa os nomes dos campos de ``src.theme.base.Theme``."""
13
+
14
+ id: str
15
+ name: str
16
+ dark: bool
17
+ fields: dict[str, str]
18
+
19
+
20
+ @dataclass
21
+ class SnippetSpec:
22
+ lang: str
23
+ prefix: str
24
+ body: str
25
+ description: str = ""
26
+
27
+
28
+ @dataclass
29
+ class LanguageSpec:
30
+ """Linguagem traduzida; ``patterns`` é a lista ``(tag, regex)`` do realce de sintaxe."""
31
+
32
+ id: str
33
+ label: str
34
+ extensions: list[str] = field(default_factory=list)
35
+ comment: str | None = None
36
+ comment_block: tuple[str, str] | None = None
37
+ bracket_pairs: list[tuple[str, str]] = field(default_factory=list)
38
+ patterns: list[tuple[str, str]] = field(default_factory=list)
39
+ keywords: list[str] = field(default_factory=list)
40
+
41
+
42
+ @dataclass
43
+ class CodeCommand:
44
+ """Comando que a extensão anuncia para a paleta (``id`` é o nome que o código registra)."""
45
+
46
+ id: str
47
+ title: str
48
+ category: str = ""
49
+ args: dict[str, Any] = field(default_factory=dict)
50
+
51
+
52
+ @dataclass
53
+ class CodeInfo:
54
+ """O que dá para executar numa extensão, se o usuário permitir: runtime externo e comandos."""
55
+
56
+ runtime: str # "node" ou "python"
57
+ entry: str # arquivo de entrada (Node) ou pasta do pacote (Python), relativo à extensão
58
+ commands: list[CodeCommand] = field(default_factory=list)
59
+
60
+
61
+ @dataclass
62
+ class Extension:
63
+ """Uma extensão importada. ``kind`` é o formato de origem (veja ``registry``)."""
64
+
65
+ id: str
66
+ name: str
67
+ version: str
68
+ kind: str
69
+ path: Path
70
+ publisher: str = ""
71
+ description: str = ""
72
+ themes: list[ThemeSpec] = field(default_factory=list)
73
+ snippets: list[SnippetSpec] = field(default_factory=list)
74
+ languages: list[LanguageSpec] = field(default_factory=list)
75
+ ignored: list[str] = field(default_factory=list)
76
+ warnings: list[str] = field(default_factory=list)
77
+ code: CodeInfo | None = None
78
+
79
+ @property
80
+ def empty(self) -> bool:
81
+ return not (self.themes or self.snippets or self.languages or self.code)
82
+
83
+ def counts(self) -> dict[str, int]:
84
+ return {
85
+ "themes": len(self.themes),
86
+ "snippets": len(self.snippets),
87
+ "languages": len(self.languages),
88
+ }
src/extcompat/net.py ADDED
@@ -0,0 +1,228 @@
1
+ """Acesso à rede dos catálogos de extensões: hosts permitidos, limites e falhas explicadas.
2
+
3
+ Só é usado quando o usuário pede uma busca ou um download. Cada pedido valida o host (também
4
+ nos redirecionamentos), tem limite de tamanho e prazo total, tenta primeiro os IPv4 (um IPv6
5
+ sem rota não deixa mais a busca presa) e, se o certificado do servidor não puder ser verificado
6
+ pelo Python (comum no Windows com certificados raiz desatualizados), tenta o pacote ``certifi``
7
+ e depois o ``curl`` do sistema, que usa o repositório de certificados do próprio sistema. A
8
+ verificação do certificado nunca é desligada.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import contextlib
14
+ import functools
15
+ import http.client
16
+ import json
17
+ import os
18
+ import shutil
19
+ import socket
20
+ import ssl
21
+ import subprocess
22
+ import tempfile
23
+ import time
24
+ import urllib.error
25
+ import urllib.parse
26
+ import urllib.request
27
+ from pathlib import Path
28
+ from typing import Any
29
+
30
+ from .store import InstallError
31
+
32
+ USER_AGENT = "Codis-ExtCompat/1.1"
33
+ MAX_JSON_BYTES = 8 * 1024 * 1024
34
+ _LOCAL = ("127.0.0.1", "localhost")
35
+
36
+
37
+ class NetError(InstallError):
38
+ """Falha de rede explicada em linguagem simples."""
39
+
40
+
41
+ def host_allowed(url: str, hosts: tuple[str, ...]) -> bool:
42
+ parsed = urllib.parse.urlparse(url)
43
+ host = parsed.hostname or ""
44
+ if not host:
45
+ return False
46
+ if parsed.scheme != "https" and not (parsed.scheme == "http" and host in _LOCAL):
47
+ return False
48
+ return any(host == h or host.endswith("." + h) for h in hosts)
49
+
50
+
51
+ class _Connection(http.client.HTTPSConnection):
52
+ """Conexão que tenta IPv4 antes de IPv6 e limita o tempo de cada tentativa."""
53
+
54
+ def __init__(self, *args: Any, connect_timeout: float = 6.0, **kwargs: Any) -> None:
55
+ super().__init__(*args, **kwargs)
56
+ self._connect_timeout = connect_timeout
57
+
58
+ def connect(self) -> None:
59
+ last: OSError | None = None
60
+ infos = socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM)
61
+ infos.sort(key=lambda i: 0 if i[0] == socket.AF_INET else 1)
62
+ sock: socket.socket | None = None
63
+ for family, kind, proto, _, addr in infos:
64
+ candidate = socket.socket(family, kind, proto)
65
+ try:
66
+ candidate.settimeout(self._connect_timeout)
67
+ candidate.connect(addr)
68
+ candidate.settimeout(self.timeout if isinstance(self.timeout, (int, float)) else None)
69
+ sock = candidate
70
+ break
71
+ except OSError as exc:
72
+ last = exc
73
+ candidate.close()
74
+ if sock is None:
75
+ raise last or OSError("nenhum endereço para conectar")
76
+ self.sock = sock
77
+ if self._tunnel_host:
78
+ self._tunnel()
79
+ self.sock = self._context.wrap_socket(self.sock, server_hostname=self._tunnel_host or self.host) # type: ignore[attr-defined]
80
+
81
+
82
+ class _HTTPSHandler(urllib.request.HTTPSHandler):
83
+ def __init__(self, context: ssl.SSLContext) -> None:
84
+ super().__init__(context=context)
85
+ self._ctx = context
86
+
87
+ def https_open(self, req: urllib.request.Request) -> http.client.HTTPResponse:
88
+ return self.do_open(functools.partial(_Connection, context=self._ctx), req)
89
+
90
+
91
+ class _Redirects(urllib.request.HTTPRedirectHandler):
92
+ """Cada redirecionamento também precisa cair em um host permitido."""
93
+
94
+ def __init__(self, hosts: tuple[str, ...]) -> None:
95
+ self._hosts = hosts
96
+
97
+ def redirect_request(self, req, fp, code, msg, headers, newurl): # type: ignore[no-untyped-def]
98
+ if not host_allowed(newurl, self._hosts):
99
+ raise NetError(f"redirecionamento para endereço não permitido: {urllib.parse.urlparse(newurl).hostname}")
100
+ return super().redirect_request(req, fp, code, msg, headers, newurl)
101
+
102
+
103
+ def _is_certificate_problem(exc: BaseException) -> bool:
104
+ reason = getattr(exc, "reason", exc)
105
+ return isinstance(reason, ssl.SSLError) or isinstance(exc, ssl.SSLError) or "CERTIFICATE_VERIFY_FAILED" in str(exc)
106
+
107
+
108
+ class Net:
109
+ def __init__(self, hosts: tuple[str, ...], *, timeout: float = 15.0, deadline: float = 45.0) -> None:
110
+ self.hosts = hosts
111
+ self.timeout = timeout
112
+ self.deadline = deadline
113
+
114
+ # --- API -----------------------------------------------------------------------------
115
+
116
+ def check(self, url: str) -> None:
117
+ if not host_allowed(url, self.hosts):
118
+ host = urllib.parse.urlparse(url).hostname or url
119
+ raise NetError(f"endereço não permitido: {host} (fora da lista deste catálogo: {', '.join(self.hosts)})")
120
+
121
+ def get_json(self, url: str, limit: int = MAX_JSON_BYTES) -> Any:
122
+ raw = self.fetch(url, limit, accept="application/json")
123
+ try:
124
+ return json.loads(raw.decode("utf-8-sig"))
125
+ except ValueError as exc:
126
+ raise NetError(f"resposta inválida de {urllib.parse.urlparse(url).hostname}") from exc
127
+
128
+ def get_text(self, url: str, limit: int = MAX_JSON_BYTES) -> str:
129
+ return self.fetch(url, limit).decode("utf-8", errors="replace")
130
+
131
+ def download(self, url: str, dest: Path, limit: int) -> Path:
132
+ dest.parent.mkdir(parents=True, exist_ok=True)
133
+ dest.write_bytes(self.fetch(url, limit, accept="application/octet-stream"))
134
+ return dest
135
+
136
+ def fetch(self, url: str, limit: int, accept: str = "*/*") -> bytes:
137
+ self.check(url)
138
+ problem: BaseException | None = None
139
+ for ctx in self._contexts():
140
+ try:
141
+ return self._read(url, ctx, limit, accept)
142
+ except NetError:
143
+ raise
144
+ except urllib.error.HTTPError as exc:
145
+ raise NetError(f"{urllib.parse.urlparse(url).hostname} respondeu HTTP {exc.code}") from exc
146
+ except (urllib.error.URLError, ssl.SSLError, OSError, http.client.HTTPException) as exc:
147
+ if not _is_certificate_problem(exc):
148
+ raise NetError(self._describe(url, exc)) from exc
149
+ problem = exc
150
+ data = self._curl(url, limit, accept)
151
+ if data is not None:
152
+ return data
153
+ raise NetError(self._describe(url, problem)) from problem
154
+
155
+ # --- implementação -----------------------------------------------------------------
156
+
157
+ @staticmethod
158
+ def _contexts() -> list[ssl.SSLContext]:
159
+ contexts = [ssl.create_default_context()]
160
+ with contextlib.suppress(ImportError, OSError, ssl.SSLError):
161
+ import certifi # opcional
162
+
163
+ contexts.append(ssl.create_default_context(cafile=certifi.where()))
164
+ return contexts
165
+
166
+ def _read(self, url: str, ctx: ssl.SSLContext, limit: int, accept: str) -> bytes:
167
+ opener = urllib.request.build_opener(_HTTPSHandler(ctx), _Redirects(self.hosts))
168
+ request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, "Accept": accept})
169
+ started = time.monotonic()
170
+ with opener.open(request, timeout=self.timeout) as resp:
171
+ self.check(resp.geturl())
172
+ chunks: list[bytes] = []
173
+ total = 0
174
+ while chunk := resp.read(65536):
175
+ total += len(chunk)
176
+ if total > limit:
177
+ raise NetError("o arquivo excede o limite de tamanho")
178
+ if time.monotonic() - started > self.deadline:
179
+ raise NetError(f"tempo esgotado ao baixar de {urllib.parse.urlparse(url).hostname}")
180
+ chunks.append(chunk)
181
+ return b"".join(chunks)
182
+
183
+ def _curl(self, url: str, limit: int, accept: str) -> bytes | None:
184
+ """Último recurso para falhas de certificado: o ``curl`` do sistema, que confia nos certificados dele."""
185
+ curl = shutil.which("curl")
186
+ if curl is None or not url.startswith("https://"):
187
+ return None
188
+ with tempfile.TemporaryDirectory(prefix="codis-curl-", ignore_cleanup_errors=True) as tmp:
189
+ out = Path(tmp) / "body"
190
+ cmd = [curl, "-fsSL", "--max-time", str(int(self.deadline)), "--max-filesize", str(limit),
191
+ "--proto", "=https", "--proto-redir", "=https", "--max-redirs", "5", "-A", USER_AGENT,
192
+ "-H", f"Accept: {accept}", "-o", str(out), "-w", "%{url_effective}"]
193
+ if os.name == "nt":
194
+ cmd.append("--ssl-no-revoke") # servidor de revogação inacessível é comum em redes corporativas
195
+ cmd.append(url)
196
+ try:
197
+ done = subprocess.run( # noqa: S603 - argv fixo, sem shell
198
+ cmd, capture_output=True, text=True, timeout=self.deadline + 5, check=False,
199
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
200
+ )
201
+ except (OSError, subprocess.SubprocessError):
202
+ return None
203
+ if done.returncode != 0 or not out.is_file():
204
+ return None
205
+ if done.stdout.strip() and not host_allowed(done.stdout.strip(), self.hosts):
206
+ raise NetError("redirecionamento para endereço não permitido")
207
+ if out.stat().st_size > limit:
208
+ raise NetError("o arquivo excede o limite de tamanho")
209
+ return out.read_bytes()
210
+
211
+ @staticmethod
212
+ def _describe(url: str, exc: BaseException | None) -> str:
213
+ host = urllib.parse.urlparse(url).hostname or url
214
+ reason = getattr(exc, "reason", exc)
215
+ if exc is not None and _is_certificate_problem(exc):
216
+ return (
217
+ f"não consegui verificar o certificado SSL de {host} ({reason}). Causas comuns: certificados raiz do "
218
+ "Windows desatualizados (rode o Windows Update ou abra o site uma vez no navegador), antivírus ou "
219
+ "firewall que inspeciona HTTPS, ou proxy corporativo. Instalar o pacote 'certifi' (pip install certifi) "
220
+ "também costuma resolver. A verificação não foi desativada."
221
+ )
222
+ if isinstance(reason, socket.gaierror):
223
+ return f"não encontrei o endereço {host}: sem internet ou DNS bloqueado?"
224
+ if isinstance(reason, (TimeoutError, socket.timeout)):
225
+ return f"tempo esgotado ao falar com {host}"
226
+ if isinstance(reason, ConnectionRefusedError):
227
+ return f"{host} recusou a conexão"
228
+ return f"não consegui acessar {host}: {reason}"
@@ -0,0 +1,63 @@
1
+ """Busca e download de extensões no Open VSX (open-vsx.org), só quando o usuário pede."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tempfile
6
+ import urllib.parse
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from .net import Net
11
+ from .store import InstallError
12
+
13
+ BASE_URL = "https://open-vsx.org/api"
14
+ # Os arquivos das extensões ficam em um armazenamento separado, para onde o download é redirecionado:
15
+ # openvsx.eclipsecontent.org hoje, e o blob do Azure em versões antigas do serviço.
16
+ ALLOWED_HOSTS = ("open-vsx.org", "openvsx.eclipsecontent.org", "openvsxorg.blob.core.windows.net")
17
+ MAX_DOWNLOAD_BYTES = 60 * 1024 * 1024
18
+
19
+
20
+ class OpenVSX:
21
+ def __init__(
22
+ self,
23
+ base_url: str = BASE_URL,
24
+ allowed_hosts: tuple[str, ...] = ALLOWED_HOSTS,
25
+ timeout: float = 15.0,
26
+ ) -> None:
27
+ self.base_url = base_url.rstrip("/")
28
+ self.net = Net(allowed_hosts, timeout=timeout)
29
+
30
+ def search(self, query: str, size: int = 20) -> list[dict[str, Any]]:
31
+ qs = urllib.parse.urlencode({"query": query, "size": max(1, min(size, 50)), "sortBy": "relevance"})
32
+ data = self.net.get_json(f"{self.base_url}/-/search?{qs}")
33
+ out: list[dict[str, Any]] = []
34
+ for item in data.get("extensions") or [] if isinstance(data, dict) else []:
35
+ if isinstance(item, dict) and item.get("namespace") and item.get("name"):
36
+ files = item.get("files") if isinstance(item.get("files"), dict) else {}
37
+ out.append(
38
+ {
39
+ "id": f"{item['namespace']}.{item['name']}",
40
+ "namespace": item["namespace"],
41
+ "name": item["name"],
42
+ "title": item.get("displayName") or item["name"],
43
+ "version": item.get("version", ""),
44
+ "description": item.get("description", ""),
45
+ "downloads": item.get("downloadCount", 0),
46
+ "download_url": files.get("download", ""),
47
+ }
48
+ )
49
+ return out
50
+
51
+ def download(self, namespace: str, name: str, version: str | None = None, url: str = "") -> Path:
52
+ """Baixa o ``.vsix`` para uma pasta temporária e devolve o caminho."""
53
+ for part in (namespace, name, version or ""):
54
+ if part and not all(c.isalnum() or c in "._-" for c in part):
55
+ raise InstallError("identificador de extensão inválido")
56
+ if not url:
57
+ path = f"{self.base_url}/{namespace}/{name}" + (f"/{version}" if version else "")
58
+ meta = self.net.get_json(path)
59
+ url = (meta.get("files") or {}).get("download") if isinstance(meta, dict) else ""
60
+ if not isinstance(url, str) or not url:
61
+ raise InstallError("o Open VSX não informou o arquivo de download")
62
+ tmp = Path(tempfile.mkdtemp(prefix="codis-ovsx-")) / f"{namespace}.{name}.vsix"
63
+ return self.net.download(url, tmp, MAX_DOWNLOAD_BYTES)