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.
- codis-1.1.1.dist-info/METADATA +194 -0
- codis-1.1.1.dist-info/RECORD +329 -0
- codis-1.1.1.dist-info/WHEEL +5 -0
- codis-1.1.1.dist-info/entry_points.txt +5 -0
- codis-1.1.1.dist-info/licenses/LICENSE +21 -0
- codis-1.1.1.dist-info/top_level.txt +2 -0
- run.py +190 -0
- src/__init__.py +1 -0
- src/__main__.py +81 -0
- src/_app_build.py +1507 -0
- src/_app_editor.py +1274 -0
- src/_app_kui.py +825 -0
- src/_app_lsp.py +625 -0
- src/_app_recovery.py +189 -0
- src/_app_settings.py +1385 -0
- src/_app_tools.py +2471 -0
- src/_app_webpreview.py +126 -0
- src/_font_safety.py +127 -0
- src/_shells.py +172 -0
- src/app.py +1488 -0
- src/chat/__init__.py +1 -0
- src/chat/adapters/__init__.py +33 -0
- src/chat/adapters/base.py +209 -0
- src/chat/adapters/discord.py +190 -0
- src/chat/adapters/http.py +78 -0
- src/chat/adapters/irc.py +360 -0
- src/chat/adapters/matrix.py +219 -0
- src/chat/adapters/mattermost.py +178 -0
- src/chat/adapters/mqtt.py +165 -0
- src/chat/adapters/slack.py +204 -0
- src/chat/adapters/telegram.py +117 -0
- src/chat/adapters/ws.py +154 -0
- src/chat/adapters/xmpp.py +337 -0
- src/chat/history.py +76 -0
- src/chat/models.py +207 -0
- src/chat/probe.py +79 -0
- src/chat/session.py +446 -0
- src/chat/util.py +125 -0
- src/collab/__init__.py +1 -0
- src/collab/net.py +411 -0
- src/collab/ot.py +311 -0
- src/collab/session.py +141 -0
- src/collab/tk_adapter.py +134 -0
- src/config.py +335 -0
- src/constants.py +2552 -0
- src/dep_catalog.py +446 -0
- src/diff/__init__.py +1 -0
- src/diff/engine.py +247 -0
- src/dpi.py +30 -0
- src/editor/__init__.py +1 -0
- src/editor/_pane_lsp.py +2937 -0
- src/editor/_pane_utils.py +171 -0
- src/editor/autocomplete.py +607 -0
- src/editor/code_folding.py +836 -0
- src/editor/color_preview.py +382 -0
- src/editor/complexity_lens.py +281 -0
- src/editor/diff_pane.py +623 -0
- src/editor/file_watcher.py +144 -0
- src/editor/focus_block.py +236 -0
- src/editor/heatmap.py +141 -0
- src/editor/inlay_hints.py +366 -0
- src/editor/inline_blame.py +429 -0
- src/editor/kdocs.py +3376 -0
- src/editor/large_file.py +488 -0
- src/editor/ligatures.py +180 -0
- src/editor/line_numbers.py +598 -0
- src/editor/minimap.py +691 -0
- src/editor/multi_cursor.py +269 -0
- src/editor/pane.py +2082 -0
- src/editor/rhythm.py +206 -0
- src/editor/save_hooks.py +43 -0
- src/editor/smart_selection.py +425 -0
- src/editor/smart_tips.py +719 -0
- src/editor/snippets.py +411 -0
- src/editor/sticky_note_gutter.py +410 -0
- src/editor/sticky_scroll.py +385 -0
- src/editor/suggest.py +464 -0
- src/editor/text_transforms.py +310 -0
- src/editor/vim_mode.py +1074 -0
- src/events/__init__.py +84 -0
- src/events/bus.py +427 -0
- src/events/correlator.py +244 -0
- src/events/kinds.py +125 -0
- src/events/pipeline.py +264 -0
- src/events/stream.py +416 -0
- src/events/window.py +204 -0
- src/extcompat/__init__.py +19 -0
- src/extcompat/code/__init__.py +13 -0
- src/extcompat/code/consent.py +162 -0
- src/extcompat/code/host.py +353 -0
- src/extcompat/code/hosts/py_host.py +763 -0
- src/extcompat/code/locate.py +105 -0
- src/extcompat/code/manager.py +325 -0
- src/extcompat/code/permissions.py +154 -0
- src/extcompat/code/sandbox.py +60 -0
- src/extcompat/colors.py +131 -0
- src/extcompat/common.py +184 -0
- src/extcompat/cson.py +269 -0
- src/extcompat/formats/__init__.py +22 -0
- src/extcompat/formats/_tm.py +189 -0
- src/extcompat/formats/_util.py +31 -0
- src/extcompat/formats/base16.py +66 -0
- src/extcompat/formats/brackets.py +172 -0
- src/extcompat/formats/eclipse.py +193 -0
- src/extcompat/formats/emacs.py +361 -0
- src/extcompat/formats/geany.py +147 -0
- src/extcompat/formats/generic.py +184 -0
- src/extcompat/formats/gtksource.py +117 -0
- src/extcompat/formats/helix.py +91 -0
- src/extcompat/formats/jetbrains.py +343 -0
- src/extcompat/formats/kate.py +130 -0
- src/extcompat/formats/micro.py +131 -0
- src/extcompat/formats/nano.py +111 -0
- src/extcompat/formats/notepadpp.py +140 -0
- src/extcompat/formats/pulsar.py +165 -0
- src/extcompat/formats/pyides.py +163 -0
- src/extcompat/formats/sublime.py +340 -0
- src/extcompat/jsonc.py +65 -0
- src/extcompat/lessish.py +128 -0
- src/extcompat/manager.py +122 -0
- src/extcompat/market/__init__.py +63 -0
- src/extcompat/market/sources.py +211 -0
- src/extcompat/model.py +88 -0
- src/extcompat/net.py +228 -0
- src/extcompat/openvsx.py +63 -0
- src/extcompat/readers.py +362 -0
- src/extcompat/registry.py +73 -0
- src/extcompat/safexml.py +63 -0
- src/extcompat/sexp.py +187 -0
- src/extcompat/sources.py +105 -0
- src/extcompat/store.py +276 -0
- src/extcompat/textmate.py +214 -0
- src/extcompat/themes.py +487 -0
- src/extcompat/yamlite.py +294 -0
- src/fileio.py +94 -0
- src/fs_ops.py +106 -0
- src/i18n.py +233 -0
- src/ia/__init__.py +1 -0
- src/ia/actions.py +295 -0
- src/ia/approval_gate.py +672 -0
- src/ia/checkpoints.py +308 -0
- src/ia/context_builder.py +921 -0
- src/ia/dialdiff.py +408 -0
- src/ia/iaspace.py +2078 -0
- src/ia/pair.py +296 -0
- src/ia/providers.py +954 -0
- src/ia/session.py +335 -0
- src/ia/toolbox.py +2524 -0
- src/launcher_actions.py +204 -0
- src/lint/__init__.py +1 -0
- src/lint/manager.py +1058 -0
- src/locales/.translate_manifest.json +64170 -0
- src/locales/de.json +4936 -0
- src/locales/en.json +4936 -0
- src/locales/es.json +4936 -0
- src/locales/fr.json +4936 -0
- src/locales/it.json +4936 -0
- src/locales/ja.json +4936 -0
- src/locales/ko.json +4936 -0
- src/locales/nl.json +4936 -0
- src/locales/pl.json +4936 -0
- src/locales/pt-BR.json +4936 -0
- src/locales/ru.json +4936 -0
- src/locales/tr.json +4936 -0
- src/locales/uk.json +4936 -0
- src/locales/zh-CN.json +4936 -0
- src/lsp/__init__.py +26 -0
- src/lsp/client.py +2300 -0
- src/lsp/dap_client.py +480 -0
- src/lsp/edits.py +84 -0
- src/lsp/framing.py +73 -0
- src/lsp/protocol.py +931 -0
- src/main.py +260 -0
- src/memtrim.py +91 -0
- src/plugins/__init__.py +1 -0
- src/plugins/api.py +1761 -0
- src/plugins/loader.py +571 -0
- src/plugins/process_runner.py +519 -0
- src/plugins/registry.py +342 -0
- src/plugins/safety.py +367 -0
- src/plugins/startup.py +195 -0
- src/plugins/store.py +1178 -0
- src/proc_registry.py +278 -0
- src/pyexec.py +394 -0
- src/recovery.py +259 -0
- src/stall_trace.py +92 -0
- src/standalone.py +1070 -0
- src/startup_profile.py +35 -0
- src/syntax/__init__.py +1 -0
- src/syntax/highlighter.py +776 -0
- src/syntax/patterns.py +584 -0
- src/system_profile.py +430 -0
- src/terminal/backends.py +658 -0
- src/terminal/internal.py +346 -0
- src/terminal/keys.py +138 -0
- src/terminal/palette.py +67 -0
- src/terminal/session.py +283 -0
- src/terminal/shells.py +79 -0
- src/terminal/view.py +489 -0
- src/terminal/vt.py +870 -0
- src/textfmt.py +22 -0
- src/theme/__init__.py +1 -0
- src/theme/base.py +1281 -0
- src/theme/colors.py +49 -0
- src/theme/manager.py +602 -0
- src/theme/utils.py +312 -0
- src/toolbox.py +329 -0
- src/trash_core.py +531 -0
- src/ui/__init__.py +1 -0
- src/ui/_perf_utils.py +285 -0
- src/ui/_persistence_utils.py +93 -0
- src/ui/accessibility.py +843 -0
- src/ui/activity_bar.py +860 -0
- src/ui/app_embed.py +434 -0
- src/ui/archive_panel.py +608 -0
- src/ui/bookmarks.py +314 -0
- src/ui/breadcrumb.py +383 -0
- src/ui/calculator_panel.py +982 -0
- src/ui/calendar_panel.py +1218 -0
- src/ui/chat_panel.py +1271 -0
- src/ui/chat_profile_dialog.py +278 -0
- src/ui/chat_render.py +128 -0
- src/ui/clock_panel.py +810 -0
- src/ui/code_outline.py +364 -0
- src/ui/code_runner.py +729 -0
- src/ui/code_stats.py +546 -0
- src/ui/collab_panel.py +1009 -0
- src/ui/color_picker.py +547 -0
- src/ui/command_palette.py +452 -0
- src/ui/cursor_manager.py +750 -0
- src/ui/custom_keywords_panel.py +413 -0
- src/ui/debug_panel.py +1037 -0
- src/ui/dependency_graph.py +692 -0
- src/ui/diff_panel.py +381 -0
- src/ui/docs_panel.py +514 -0
- src/ui/doom_embed.py +349 -0
- src/ui/dropdown.py +321 -0
- src/ui/easter_eggs.py +979 -0
- src/ui/env_manager.py +666 -0
- src/ui/extcode_bridge.py +215 -0
- src/ui/extcode_dialogs.py +412 -0
- src/ui/extcompat_dialog.py +583 -0
- src/ui/file_timeline.py +319 -0
- src/ui/file_tree.py +1208 -0
- src/ui/find_in_files.py +1355 -0
- src/ui/flowchart_panel.py +727 -0
- src/ui/formatter_panel.py +490 -0
- src/ui/git_auth.py +763 -0
- src/ui/git_clone_dialog.py +487 -0
- src/ui/git_panel.py +1483 -0
- src/ui/grab_safe.py +84 -0
- src/ui/internal_python_dialog.py +98 -0
- src/ui/k_ui/__init__.py +1305 -0
- src/ui/k_ui/_bgrenderer.py +317 -0
- src/ui/k_ui/_colors.py +213 -0
- src/ui/k_ui/_dock.py +545 -0
- src/ui/k_ui/_easter.py +290 -0
- src/ui/k_ui/_engine.py +5448 -0
- src/ui/k_ui/_perf.py +333 -0
- src/ui/k_ui/_tkutil.py +7 -0
- src/ui/k_ui/_tooltip.py +365 -0
- src/ui/k_ui/_widgets.py +1204 -0
- src/ui/k_ui/_world.py +837 -0
- src/ui/key_remapper.py +856 -0
- src/ui/launcher.py +1252 -0
- src/ui/lazy_panel.py +73 -0
- src/ui/macro_recorder.py +610 -0
- src/ui/menu_bar.py +898 -0
- src/ui/output_panel.py +321 -0
- src/ui/paint_canvas.py +1000 -0
- src/ui/paint_engine.py +535 -0
- src/ui/paint_panel.py +888 -0
- src/ui/panel_detach.py +112 -0
- src/ui/performance_panel.py +861 -0
- src/ui/pip_manager.py +1758 -0
- src/ui/plugin_panel.py +1586 -0
- src/ui/pomodoro_panel.py +447 -0
- src/ui/problems.py +566 -0
- src/ui/process_manager.py +1657 -0
- src/ui/project_templates.py +775 -0
- src/ui/recovery_dialog.py +122 -0
- src/ui/regex_playground.py +304 -0
- src/ui/remote_adapters.py +1398 -0
- src/ui/remote_browser.py +1224 -0
- src/ui/remote_profile_dialog.py +342 -0
- src/ui/render_panel.py +1293 -0
- src/ui/rest_client.py +549 -0
- src/ui/scratchpad.py +548 -0
- src/ui/search_bar.py +1274 -0
- src/ui/settings_editor.py +3349 -0
- src/ui/settings_window.py +1554 -0
- src/ui/snippets_panel.py +597 -0
- src/ui/sql_studio.py +1815 -0
- src/ui/status_bar.py +438 -0
- src/ui/tab_bar.py +654 -0
- src/ui/task_manager.py +1773 -0
- src/ui/terminal.py +525 -0
- src/ui/theme_preview_panel.py +851 -0
- src/ui/thread_safe_tk.py +152 -0
- src/ui/time_tracker.py +574 -0
- src/ui/tkbind.py +43 -0
- src/ui/todo_panel.py +358 -0
- src/ui/toolbox_panels.py +658 -0
- src/ui/trash_manager.py +657 -0
- src/ui/ui_scale.py +294 -0
- src/ui/ux_enhancements.py +41 -0
- src/ui/web_preview.py +397 -0
- src/ui/webdev.py +630 -0
- src/ui/welcome.py +567 -0
- src/ui/window_embed.py +1500 -0
- src/ui/wizard.py +1550 -0
- src/ui/workspace_switcher.py +418 -0
- src/ui/workspace_trust.py +370 -0
- src/ui/zen_audio.py +354 -0
- src/ui/zen_media.py +2271 -0
- src/ui/zen_media_client.py +303 -0
- src/ui/zen_media_host.py +329 -0
- src/ui/zen_player.py +907 -0
- src/ui/zen_player_widgets.py +700 -0
- src/updater/__init__.py +11 -0
- src/updater/assets.py +145 -0
- src/updater/backup.py +101 -0
- src/updater/channel.py +221 -0
- src/updater/dialog.py +492 -0
- src/updater/integrity.py +111 -0
- src/updater/manager.py +727 -0
- src/updater/result.py +114 -0
- src/venv_runtime.py +531 -0
- src/workspace_state.py +25 -0
src/plugins/registry.py
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
"""Tabelas de hooks e comandos usadas pelo app e pelos plugins. Sem Tkinter.
|
|
2
|
+
|
|
3
|
+
Tudo que um plugin registra carrega o id do dono, o que permite desfazer o registro
|
|
4
|
+
inteiro quando o plugin é desativado, e consultar depois quem registrou o quê.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import inspect
|
|
10
|
+
import itertools
|
|
11
|
+
import logging
|
|
12
|
+
import threading
|
|
13
|
+
from collections.abc import Callable
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
logger = logging.getLogger("Codis")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def call_flexible(fn: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:
|
|
21
|
+
"""Chama ``fn`` só com os argumentos posicionais que ela declara aceitar.
|
|
22
|
+
|
|
23
|
+
Assim ``lambda: ...`` e ``lambda path: ...`` servem para o mesmo evento.
|
|
24
|
+
"""
|
|
25
|
+
try:
|
|
26
|
+
params = inspect.signature(fn).parameters.values()
|
|
27
|
+
except (TypeError, ValueError):
|
|
28
|
+
return fn(*args, **kwargs)
|
|
29
|
+
if any(p.kind is inspect.Parameter.VAR_POSITIONAL for p in params):
|
|
30
|
+
return fn(*args, **kwargs)
|
|
31
|
+
slots = sum(1 for p in params if p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD))
|
|
32
|
+
return fn(*args[:slots], **kwargs)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(order=True)
|
|
36
|
+
class _Hook:
|
|
37
|
+
sort_key: tuple[int, int] = field(compare=True)
|
|
38
|
+
handler: Callable[..., Any] = field(compare=False)
|
|
39
|
+
owner: str = field(compare=False, default="")
|
|
40
|
+
lang: str = field(compare=False, default="")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class HookTable:
|
|
44
|
+
"""Assinaturas de eventos, ordenadas por prioridade (maior primeiro) e depois por registro."""
|
|
45
|
+
|
|
46
|
+
def __init__(self) -> None:
|
|
47
|
+
self._hooks: dict[str, list[_Hook]] = {}
|
|
48
|
+
self._seq = itertools.count()
|
|
49
|
+
self._lock = threading.RLock()
|
|
50
|
+
|
|
51
|
+
def add(
|
|
52
|
+
self,
|
|
53
|
+
event: str,
|
|
54
|
+
handler: Callable[..., Any],
|
|
55
|
+
*,
|
|
56
|
+
priority: int = 0,
|
|
57
|
+
owner: str = "",
|
|
58
|
+
lang: str = "",
|
|
59
|
+
) -> None:
|
|
60
|
+
"""Registra ``handler``; com ``lang``, só roda quando o evento traz essa linguagem."""
|
|
61
|
+
with self._lock:
|
|
62
|
+
items = self._hooks.setdefault(event, [])
|
|
63
|
+
items.append(_Hook((-priority, next(self._seq)), handler, owner, lang))
|
|
64
|
+
items.sort()
|
|
65
|
+
|
|
66
|
+
def remove(self, event: str, handler: Callable[..., Any]) -> bool:
|
|
67
|
+
"""Remove a primeira assinatura de ``handler`` em ``event``."""
|
|
68
|
+
with self._lock:
|
|
69
|
+
items = self._hooks.get(event, [])
|
|
70
|
+
for i, hook in enumerate(items):
|
|
71
|
+
if hook.handler is handler:
|
|
72
|
+
del items[i]
|
|
73
|
+
return True
|
|
74
|
+
return False
|
|
75
|
+
|
|
76
|
+
def remove_owner(self, owner: str) -> int:
|
|
77
|
+
"""Remove tudo o que ``owner`` registrou; retorna quantas assinaturas saíram."""
|
|
78
|
+
removed = 0
|
|
79
|
+
with self._lock:
|
|
80
|
+
for event, items in self._hooks.items():
|
|
81
|
+
keep = [h for h in items if h.owner != owner]
|
|
82
|
+
removed += len(items) - len(keep)
|
|
83
|
+
self._hooks[event] = keep
|
|
84
|
+
return removed
|
|
85
|
+
|
|
86
|
+
def handlers(self, event: str) -> list[Callable[..., Any]]:
|
|
87
|
+
"""Cópia dos handlers de ``event`` na ordem de execução."""
|
|
88
|
+
with self._lock:
|
|
89
|
+
return [h.handler for h in self._hooks.get(event, [])]
|
|
90
|
+
|
|
91
|
+
def get(self, event: str, default: Any = None) -> list[Callable[..., Any]]:
|
|
92
|
+
"""Compatível com ``dict.get``: lista (cópia) dos handlers."""
|
|
93
|
+
found = self.handlers(event)
|
|
94
|
+
return found if found else (default if default is not None else [])
|
|
95
|
+
|
|
96
|
+
def owners(self, event: str) -> list[str]:
|
|
97
|
+
"""Donos das assinaturas de ``event``, na ordem de execução."""
|
|
98
|
+
with self._lock:
|
|
99
|
+
return [h.owner for h in self._hooks.get(event, [])]
|
|
100
|
+
|
|
101
|
+
def events(self) -> list[str]:
|
|
102
|
+
"""Eventos que têm pelo menos uma assinatura."""
|
|
103
|
+
with self._lock:
|
|
104
|
+
return sorted(e for e, items in self._hooks.items() if items)
|
|
105
|
+
|
|
106
|
+
def fire(self, event: str, *args: Any, lang: str = "", **kwargs: Any) -> int:
|
|
107
|
+
"""Chama os handlers de ``event``. Uma exceção é registrada e os demais continuam."""
|
|
108
|
+
with self._lock:
|
|
109
|
+
snapshot = list(self._hooks.get(event, []))
|
|
110
|
+
called = 0
|
|
111
|
+
for hook in snapshot:
|
|
112
|
+
if hook.lang and hook.lang != lang:
|
|
113
|
+
continue
|
|
114
|
+
try:
|
|
115
|
+
call_flexible(hook.handler, *args, **kwargs)
|
|
116
|
+
called += 1
|
|
117
|
+
except Exception as exc:
|
|
118
|
+
logger.warning("Hook '%s' de %s falhou: %s", event, hook.owner or "app", exc)
|
|
119
|
+
return called
|
|
120
|
+
|
|
121
|
+
def veto(self, event: str, *args: Any, lang: str = "", **kwargs: Any) -> bool:
|
|
122
|
+
"""Roda os handlers de ``event`` até um devolver ``False``; ``True`` significa cancelar."""
|
|
123
|
+
with self._lock:
|
|
124
|
+
snapshot = list(self._hooks.get(event, []))
|
|
125
|
+
for hook in snapshot:
|
|
126
|
+
if hook.lang and hook.lang != lang:
|
|
127
|
+
continue
|
|
128
|
+
try:
|
|
129
|
+
if call_flexible(hook.handler, *args, **kwargs) is False:
|
|
130
|
+
return True
|
|
131
|
+
except Exception as exc:
|
|
132
|
+
logger.warning("Hook '%s' de %s falhou: %s", event, hook.owner or "app", exc)
|
|
133
|
+
return False
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@dataclass
|
|
137
|
+
class CommandInfo:
|
|
138
|
+
"""Um comando registrado, seja do núcleo ou de um plugin."""
|
|
139
|
+
|
|
140
|
+
id: str
|
|
141
|
+
label: str
|
|
142
|
+
handler: Callable[..., Any]
|
|
143
|
+
owner: str = "core"
|
|
144
|
+
doc: str = ""
|
|
145
|
+
category: str = ""
|
|
146
|
+
when: Callable[[], bool] | None = None
|
|
147
|
+
keys: list[str] = field(default_factory=list)
|
|
148
|
+
|
|
149
|
+
def available(self) -> bool:
|
|
150
|
+
if self.when is None:
|
|
151
|
+
return True
|
|
152
|
+
try:
|
|
153
|
+
return bool(self.when())
|
|
154
|
+
except Exception:
|
|
155
|
+
return False
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
@dataclass
|
|
159
|
+
class _Advice:
|
|
160
|
+
kind: str
|
|
161
|
+
fn: Callable[..., Any]
|
|
162
|
+
owner: str
|
|
163
|
+
priority: int
|
|
164
|
+
seq: int
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
class CommandTable:
|
|
168
|
+
"""Comandos por id, com ``before``/``after``/``around`` e consulta de documentação."""
|
|
169
|
+
|
|
170
|
+
def __init__(self) -> None:
|
|
171
|
+
self._commands: dict[str, CommandInfo] = {}
|
|
172
|
+
self._advice: dict[str, list[_Advice]] = {}
|
|
173
|
+
self._seq = itertools.count()
|
|
174
|
+
self._lock = threading.RLock()
|
|
175
|
+
|
|
176
|
+
def register(self, info: CommandInfo) -> None:
|
|
177
|
+
with self._lock:
|
|
178
|
+
self._commands[info.id] = info
|
|
179
|
+
|
|
180
|
+
def unregister(self, cmd_id: str, owner: str | None = None) -> bool:
|
|
181
|
+
with self._lock:
|
|
182
|
+
info = self._commands.get(cmd_id)
|
|
183
|
+
if info is None or (owner is not None and info.owner != owner):
|
|
184
|
+
return False
|
|
185
|
+
del self._commands[cmd_id]
|
|
186
|
+
return True
|
|
187
|
+
|
|
188
|
+
def remove_owner(self, owner: str) -> None:
|
|
189
|
+
with self._lock:
|
|
190
|
+
for cmd_id in [k for k, v in self._commands.items() if v.owner == owner]:
|
|
191
|
+
del self._commands[cmd_id]
|
|
192
|
+
for cmd_id, items in self._advice.items():
|
|
193
|
+
self._advice[cmd_id] = [a for a in items if a.owner != owner]
|
|
194
|
+
|
|
195
|
+
def get(self, cmd_id: str) -> CommandInfo | None:
|
|
196
|
+
with self._lock:
|
|
197
|
+
return self._commands.get(cmd_id)
|
|
198
|
+
|
|
199
|
+
def all(self, *, only_available: bool = False) -> list[CommandInfo]:
|
|
200
|
+
with self._lock:
|
|
201
|
+
items = sorted(self._commands.values(), key=lambda c: (c.category, c.label.lower()))
|
|
202
|
+
return [c for c in items if c.available()] if only_available else items
|
|
203
|
+
|
|
204
|
+
def add_key(self, cmd_id: str, key: str) -> None:
|
|
205
|
+
with self._lock:
|
|
206
|
+
info = self._commands.get(cmd_id)
|
|
207
|
+
if info is not None and key not in info.keys:
|
|
208
|
+
info.keys.append(key)
|
|
209
|
+
|
|
210
|
+
def wrap(
|
|
211
|
+
self, cmd_id: str, kind: str, fn: Callable[..., Any], *, owner: str = "", priority: int = 0
|
|
212
|
+
) -> Callable[[], None]:
|
|
213
|
+
"""Envolve um comando. Devolve uma função que desfaz o ``wrap``.
|
|
214
|
+
|
|
215
|
+
``kind``: ``"before"`` (``fn(*args)``; devolver ``False`` cancela), ``"after"``
|
|
216
|
+
(``fn(resultado, *args)``) ou ``"around"`` (``fn(proximo, *args)``).
|
|
217
|
+
"""
|
|
218
|
+
if kind not in ("before", "after", "around"):
|
|
219
|
+
raise ValueError(f"tipo de wrap inválido: {kind!r}")
|
|
220
|
+
advice = _Advice(kind, fn, owner, priority, next(self._seq))
|
|
221
|
+
with self._lock:
|
|
222
|
+
items = self._advice.setdefault(cmd_id, [])
|
|
223
|
+
items.append(advice)
|
|
224
|
+
items.sort(key=lambda a: (-a.priority, a.seq))
|
|
225
|
+
|
|
226
|
+
def undo() -> None:
|
|
227
|
+
with self._lock:
|
|
228
|
+
items = self._advice.get(cmd_id, [])
|
|
229
|
+
if advice in items:
|
|
230
|
+
items.remove(advice)
|
|
231
|
+
|
|
232
|
+
return undo
|
|
233
|
+
|
|
234
|
+
def run(self, cmd_id: str, *args: Any, **kwargs: Any) -> Any:
|
|
235
|
+
"""Executa o comando passando pelos ``wrap`` registrados.
|
|
236
|
+
|
|
237
|
+
Retorna ``None`` se o comando não existe, não está disponível ou foi cancelado.
|
|
238
|
+
"""
|
|
239
|
+
info = self.get(cmd_id)
|
|
240
|
+
if info is None or not info.available():
|
|
241
|
+
return None
|
|
242
|
+
with self._lock:
|
|
243
|
+
chain = list(self._advice.get(cmd_id, []))
|
|
244
|
+
|
|
245
|
+
for a in (x for x in chain if x.kind == "before"):
|
|
246
|
+
try:
|
|
247
|
+
if call_flexible(a.fn, *args, **kwargs) is False:
|
|
248
|
+
return None
|
|
249
|
+
except Exception as exc:
|
|
250
|
+
logger.warning("before de '%s' (%s) falhou: %s", cmd_id, a.owner, exc)
|
|
251
|
+
|
|
252
|
+
def core(*a: Any, **kw: Any) -> Any:
|
|
253
|
+
return call_flexible(info.handler, *a, **kw)
|
|
254
|
+
|
|
255
|
+
runner: Callable[..., Any] = core
|
|
256
|
+
for adv in reversed([x for x in chain if x.kind == "around"]):
|
|
257
|
+
runner = _bind_around(adv, runner, cmd_id)
|
|
258
|
+
result = runner(*args, **kwargs)
|
|
259
|
+
|
|
260
|
+
for a in (x for x in chain if x.kind == "after"):
|
|
261
|
+
try:
|
|
262
|
+
call_flexible(a.fn, result, *args, **kwargs)
|
|
263
|
+
except Exception as exc:
|
|
264
|
+
logger.warning("after de '%s' (%s) falhou: %s", cmd_id, a.owner, exc)
|
|
265
|
+
return result
|
|
266
|
+
|
|
267
|
+
def describe(self, cmd_id: str) -> dict[str, Any] | None:
|
|
268
|
+
"""Dados de um comando para exibir ao usuário: rótulo, dono, atalhos, documentação."""
|
|
269
|
+
info = self.get(cmd_id)
|
|
270
|
+
if info is None:
|
|
271
|
+
return None
|
|
272
|
+
with self._lock:
|
|
273
|
+
wrappers = [(a.kind, a.owner) for a in self._advice.get(cmd_id, [])]
|
|
274
|
+
return {
|
|
275
|
+
"id": info.id,
|
|
276
|
+
"label": info.label,
|
|
277
|
+
"owner": info.owner,
|
|
278
|
+
"doc": info.doc,
|
|
279
|
+
"category": info.category,
|
|
280
|
+
"keys": list(info.keys),
|
|
281
|
+
"available": info.available(),
|
|
282
|
+
"wrappers": wrappers,
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def _bind_around(adv: _Advice, nxt: Callable[..., Any], cmd_id: str) -> Callable[..., Any]:
|
|
287
|
+
def runner(*args: Any, **kwargs: Any) -> Any:
|
|
288
|
+
state = {"called": False, "result": None}
|
|
289
|
+
|
|
290
|
+
def proximo(*a: Any, **kw: Any) -> Any:
|
|
291
|
+
state["called"] = True
|
|
292
|
+
state["result"] = nxt(*(a or args), **(kw or kwargs))
|
|
293
|
+
return state["result"]
|
|
294
|
+
|
|
295
|
+
try:
|
|
296
|
+
return adv.fn(proximo, *args, **kwargs)
|
|
297
|
+
except Exception as exc:
|
|
298
|
+
logger.warning("around de '%s' (%s) falhou: %s", cmd_id, adv.owner, exc)
|
|
299
|
+
return state["result"] if state["called"] else nxt(*args, **kwargs)
|
|
300
|
+
|
|
301
|
+
return runner
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
@dataclass
|
|
305
|
+
class Extension:
|
|
306
|
+
"""Contribuição de um plugin a um ponto de extensão (formatador, menu de contexto...)."""
|
|
307
|
+
|
|
308
|
+
kind: str
|
|
309
|
+
key: str
|
|
310
|
+
fn: Callable[..., Any]
|
|
311
|
+
owner: str = ""
|
|
312
|
+
priority: int = 0
|
|
313
|
+
label: str = ""
|
|
314
|
+
when: Callable[[], bool] | None = None
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
class ExtensionPoints:
|
|
318
|
+
"""Contribuições agrupadas por tipo e chave (linguagem ou contexto), com dono."""
|
|
319
|
+
|
|
320
|
+
def __init__(self) -> None:
|
|
321
|
+
self._items: list[Extension] = []
|
|
322
|
+
self._lock = threading.RLock()
|
|
323
|
+
|
|
324
|
+
def add(self, ext: Extension) -> None:
|
|
325
|
+
with self._lock:
|
|
326
|
+
self._items.append(ext)
|
|
327
|
+
|
|
328
|
+
def remove(self, ext: Extension) -> None:
|
|
329
|
+
with self._lock:
|
|
330
|
+
if ext in self._items:
|
|
331
|
+
self._items.remove(ext)
|
|
332
|
+
|
|
333
|
+
def remove_owner(self, owner: str) -> None:
|
|
334
|
+
with self._lock:
|
|
335
|
+
self._items = [e for e in self._items if e.owner != owner]
|
|
336
|
+
|
|
337
|
+
def get(self, kind: str, key: str) -> list[Extension]:
|
|
338
|
+
"""Contribuições de ``kind`` para ``key``, da maior para a menor prioridade."""
|
|
339
|
+
with self._lock:
|
|
340
|
+
found = [e for e in self._items if e.kind == kind and e.key == key]
|
|
341
|
+
found.sort(key=lambda e: -e.priority)
|
|
342
|
+
return found
|
src/plugins/safety.py
ADDED
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
"""Verificações estáticas e extração segura de plugins. Sem Tkinter.
|
|
2
|
+
|
|
3
|
+
A análise aqui é um aviso ao usuário, não uma sandbox: um plugin roda no mesmo
|
|
4
|
+
processo do Codis e, no fim das contas, com as mesmas permissões dele. O que a
|
|
5
|
+
análise faz é apontar o que merece atenção antes de aceitar um plugin (imports
|
|
6
|
+
de rede, processos, chamadas dinâmicas) e garantir que a confiança dada a um
|
|
7
|
+
plugin vale para *todos* os arquivos dele, não só para o ponto de entrada.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import ast
|
|
13
|
+
import hashlib
|
|
14
|
+
import io
|
|
15
|
+
import re
|
|
16
|
+
import zipfile
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
BLOCKED_MODULES: frozenset[str] = frozenset(
|
|
22
|
+
{
|
|
23
|
+
"ctypes",
|
|
24
|
+
"subprocess",
|
|
25
|
+
"socket",
|
|
26
|
+
"ssl",
|
|
27
|
+
"multiprocessing",
|
|
28
|
+
"pty",
|
|
29
|
+
"termios",
|
|
30
|
+
"tty",
|
|
31
|
+
"winreg",
|
|
32
|
+
"winrm",
|
|
33
|
+
"_winapi",
|
|
34
|
+
"msvcrt",
|
|
35
|
+
"cffi",
|
|
36
|
+
"os",
|
|
37
|
+
"importlib",
|
|
38
|
+
"runpy",
|
|
39
|
+
"code",
|
|
40
|
+
"codeop",
|
|
41
|
+
"builtins",
|
|
42
|
+
"posix",
|
|
43
|
+
"nt",
|
|
44
|
+
}
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
WARN_MODULES: frozenset[str] = frozenset(
|
|
48
|
+
{
|
|
49
|
+
"pathlib",
|
|
50
|
+
"shutil",
|
|
51
|
+
"requests",
|
|
52
|
+
"urllib",
|
|
53
|
+
"http",
|
|
54
|
+
"ftplib",
|
|
55
|
+
"smtplib",
|
|
56
|
+
"imaplib",
|
|
57
|
+
"threading",
|
|
58
|
+
"concurrent",
|
|
59
|
+
"asyncio",
|
|
60
|
+
"pickle",
|
|
61
|
+
"shelve",
|
|
62
|
+
"marshal",
|
|
63
|
+
"sys",
|
|
64
|
+
"tempfile",
|
|
65
|
+
"webbrowser",
|
|
66
|
+
"sqlite3",
|
|
67
|
+
}
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
DANGEROUS_CALLS: frozenset[str] = frozenset({"eval", "exec", "compile", "__import__"})
|
|
71
|
+
_REFLECTION_CALLS: frozenset[str] = frozenset({"getattr", "setattr", "delattr"})
|
|
72
|
+
_INTERNAL_ATTRS: frozenset[str] = frozenset(
|
|
73
|
+
{
|
|
74
|
+
"__subclasses__",
|
|
75
|
+
"__globals__",
|
|
76
|
+
"__builtins__",
|
|
77
|
+
"__code__",
|
|
78
|
+
"__closure__",
|
|
79
|
+
"__bases__",
|
|
80
|
+
"__mro__",
|
|
81
|
+
"f_globals",
|
|
82
|
+
"f_builtins",
|
|
83
|
+
"gi_frame",
|
|
84
|
+
"tb_frame",
|
|
85
|
+
}
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
MAX_PLUGIN_BYTES = 50 * 1024 * 1024
|
|
89
|
+
MAX_PLUGIN_FILES = 2000
|
|
90
|
+
_IMPORT_FALLBACK = re.compile(r"^\s*(?:import|from)\s+([\w.]+)", re.MULTILINE)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclass
|
|
94
|
+
class Findings:
|
|
95
|
+
"""Resultado da análise estática de um ou mais arquivos."""
|
|
96
|
+
|
|
97
|
+
blocked: list[str] = field(default_factory=list)
|
|
98
|
+
warned: list[str] = field(default_factory=list)
|
|
99
|
+
calls: list[str] = field(default_factory=list)
|
|
100
|
+
|
|
101
|
+
def merge(self, other: Findings) -> None:
|
|
102
|
+
for mine, theirs in (
|
|
103
|
+
(self.blocked, other.blocked),
|
|
104
|
+
(self.warned, other.warned),
|
|
105
|
+
(self.calls, other.calls),
|
|
106
|
+
):
|
|
107
|
+
mine.extend(x for x in theirs if x not in mine)
|
|
108
|
+
|
|
109
|
+
@property
|
|
110
|
+
def flagged(self) -> list[str]:
|
|
111
|
+
"""Tudo o que impede o carregamento silencioso (imports bloqueados e chamadas dinâmicas)."""
|
|
112
|
+
return [*self.blocked, *self.calls]
|
|
113
|
+
|
|
114
|
+
def __bool__(self) -> bool:
|
|
115
|
+
return bool(self.blocked or self.warned or self.calls)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _classify(module: str, out: Findings) -> None:
|
|
119
|
+
root = module.split(".")[0]
|
|
120
|
+
if module in BLOCKED_MODULES or root in BLOCKED_MODULES:
|
|
121
|
+
if module not in out.blocked:
|
|
122
|
+
out.blocked.append(module)
|
|
123
|
+
elif (module in WARN_MODULES or root in WARN_MODULES) and module not in out.warned:
|
|
124
|
+
out.warned.append(module)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def scan_source(source: str) -> Findings:
|
|
128
|
+
"""Analisa o código de um arquivo.
|
|
129
|
+
|
|
130
|
+
Usa a AST; só cai para expressão regular quando o arquivo não compila, para
|
|
131
|
+
que um arquivo ilegível não escape da verificação. Imports citados em
|
|
132
|
+
comentários ou textos não contam.
|
|
133
|
+
"""
|
|
134
|
+
out = Findings()
|
|
135
|
+
try:
|
|
136
|
+
tree = ast.parse(source, mode="exec")
|
|
137
|
+
except (SyntaxError, ValueError):
|
|
138
|
+
for match in _IMPORT_FALLBACK.finditer(source):
|
|
139
|
+
_classify(match.group(1), out)
|
|
140
|
+
return out
|
|
141
|
+
|
|
142
|
+
for node in ast.walk(tree):
|
|
143
|
+
if isinstance(node, ast.Import):
|
|
144
|
+
for alias in node.names:
|
|
145
|
+
_classify(alias.name, out)
|
|
146
|
+
elif isinstance(node, ast.ImportFrom):
|
|
147
|
+
if node.level == 0 and node.module:
|
|
148
|
+
_classify(node.module, out)
|
|
149
|
+
elif isinstance(node, ast.Call):
|
|
150
|
+
label = _dynamic_call_label(node)
|
|
151
|
+
if label and label not in out.calls:
|
|
152
|
+
out.calls.append(label)
|
|
153
|
+
elif isinstance(node, ast.Attribute) and node.attr in _INTERNAL_ATTRS:
|
|
154
|
+
label = f"acesso a .{node.attr}"
|
|
155
|
+
if label not in out.calls:
|
|
156
|
+
out.calls.append(label)
|
|
157
|
+
return out
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _dynamic_call_label(node: ast.Call) -> str:
|
|
161
|
+
func = node.func
|
|
162
|
+
if isinstance(func, ast.Name):
|
|
163
|
+
if func.id in DANGEROUS_CALLS:
|
|
164
|
+
return f"{func.id}()"
|
|
165
|
+
if func.id in _REFLECTION_CALLS and len(node.args) >= 2:
|
|
166
|
+
name = node.args[1]
|
|
167
|
+
if isinstance(name, ast.Constant) and isinstance(name.value, str):
|
|
168
|
+
if name.value.startswith("__") and name.value.endswith("__"):
|
|
169
|
+
return f"{func.id}(..., {name.value!r})"
|
|
170
|
+
elif not isinstance(name, ast.Constant):
|
|
171
|
+
return f"{func.id}() com nome dinâmico"
|
|
172
|
+
elif isinstance(func, ast.Attribute) and func.attr in DANGEROUS_CALLS:
|
|
173
|
+
return f".{func.attr}()"
|
|
174
|
+
return ""
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def plugin_sources(path: Path) -> dict[str, str]:
|
|
178
|
+
"""Texto de todos os ``.py`` de um plugin (arquivo, pasta ou ZIP), por caminho relativo.
|
|
179
|
+
|
|
180
|
+
Arquivos acima do limite total são ignorados na leitura (o carregamento recusa
|
|
181
|
+
esses plugins por outro caminho).
|
|
182
|
+
"""
|
|
183
|
+
files: dict[str, str] = {}
|
|
184
|
+
total = 0
|
|
185
|
+
try:
|
|
186
|
+
if path.is_dir():
|
|
187
|
+
for item in sorted(path.rglob("*.py")):
|
|
188
|
+
if "__pycache__" in item.parts or not item.is_file():
|
|
189
|
+
continue
|
|
190
|
+
total += item.stat().st_size
|
|
191
|
+
if total > MAX_PLUGIN_BYTES or len(files) >= MAX_PLUGIN_FILES:
|
|
192
|
+
break
|
|
193
|
+
files[item.relative_to(path).as_posix()] = item.read_text("utf-8", errors="replace")
|
|
194
|
+
elif path.suffix == ".zip":
|
|
195
|
+
with zipfile.ZipFile(path) as zf:
|
|
196
|
+
for info in sorted(zf.infolist(), key=lambda i: i.filename):
|
|
197
|
+
if info.is_dir() or not info.filename.endswith(".py"):
|
|
198
|
+
continue
|
|
199
|
+
total += info.file_size
|
|
200
|
+
if total > MAX_PLUGIN_BYTES or len(files) >= MAX_PLUGIN_FILES:
|
|
201
|
+
break
|
|
202
|
+
files[info.filename] = zf.read(info).decode("utf-8", errors="replace")
|
|
203
|
+
elif path.suffix == ".py" and path.is_file():
|
|
204
|
+
files[path.name] = path.read_text("utf-8", errors="replace")
|
|
205
|
+
except (OSError, zipfile.BadZipFile, RuntimeError):
|
|
206
|
+
return files
|
|
207
|
+
return files
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def scan_plugin(path: Path) -> Findings:
|
|
211
|
+
"""Analisa todos os arquivos Python do plugin."""
|
|
212
|
+
out = Findings()
|
|
213
|
+
for source in plugin_sources(path).values():
|
|
214
|
+
out.merge(scan_source(source))
|
|
215
|
+
return out
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def fingerprint(path: Path) -> str | None:
|
|
219
|
+
"""SHA-256 do conteúdo de todos os ``.py`` do plugin; ``None`` se não houver código.
|
|
220
|
+
|
|
221
|
+
Qualquer arquivo alterado, incluindo módulos auxiliares, muda o resultado.
|
|
222
|
+
"""
|
|
223
|
+
files = plugin_sources(path)
|
|
224
|
+
if not files:
|
|
225
|
+
return None
|
|
226
|
+
digest = hashlib.sha256()
|
|
227
|
+
for name in sorted(files):
|
|
228
|
+
digest.update(name.encode("utf-8"))
|
|
229
|
+
digest.update(b"\0")
|
|
230
|
+
digest.update(files[name].encode("utf-8"))
|
|
231
|
+
digest.update(b"\0")
|
|
232
|
+
return digest.hexdigest()
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
# Manifesto
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def read_manifest_static(source: str) -> dict[str, Any]:
|
|
239
|
+
"""Lê o ``MANIFEST`` de um plugin sem executá-lo.
|
|
240
|
+
|
|
241
|
+
Aceita ``MANIFEST = PluginManifest(name=..., ...)`` ou um dicionário literal.
|
|
242
|
+
Só valores literais são lidos; qualquer outra coisa é ignorada.
|
|
243
|
+
"""
|
|
244
|
+
try:
|
|
245
|
+
tree = ast.parse(source, mode="exec")
|
|
246
|
+
except (SyntaxError, ValueError):
|
|
247
|
+
return {}
|
|
248
|
+
for node in tree.body:
|
|
249
|
+
value: ast.expr | None = None
|
|
250
|
+
if isinstance(node, ast.Assign) and any(
|
|
251
|
+
isinstance(t, ast.Name) and t.id == "MANIFEST" for t in node.targets
|
|
252
|
+
):
|
|
253
|
+
value = node.value
|
|
254
|
+
elif (
|
|
255
|
+
isinstance(node, ast.AnnAssign)
|
|
256
|
+
and isinstance(node.target, ast.Name)
|
|
257
|
+
and node.target.id == "MANIFEST"
|
|
258
|
+
):
|
|
259
|
+
value = node.value
|
|
260
|
+
if value is None:
|
|
261
|
+
continue
|
|
262
|
+
if isinstance(value, ast.Call):
|
|
263
|
+
return _literal_kwargs(value.keywords)
|
|
264
|
+
try:
|
|
265
|
+
data = ast.literal_eval(value)
|
|
266
|
+
except (ValueError, SyntaxError):
|
|
267
|
+
return {}
|
|
268
|
+
return data if isinstance(data, dict) else {}
|
|
269
|
+
return {}
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _literal_kwargs(keywords: list[ast.keyword]) -> dict[str, Any]:
|
|
273
|
+
out: dict[str, Any] = {}
|
|
274
|
+
for kw in keywords:
|
|
275
|
+
if kw.arg is None:
|
|
276
|
+
continue
|
|
277
|
+
try:
|
|
278
|
+
out[kw.arg] = ast.literal_eval(kw.value)
|
|
279
|
+
except (ValueError, SyntaxError):
|
|
280
|
+
continue
|
|
281
|
+
return out
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def version_tuple(text: str) -> tuple[int, ...]:
|
|
285
|
+
"""``"1.2.3"`` -> ``(1, 2, 3)``; partes não numéricas viram 0."""
|
|
286
|
+
parts: list[int] = []
|
|
287
|
+
for chunk in str(text or "0").split("."):
|
|
288
|
+
match = re.match(r"\d+", chunk.strip())
|
|
289
|
+
parts.append(int(match.group()) if match else 0)
|
|
290
|
+
return tuple(parts) or (0,)
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def compat_problem(
|
|
294
|
+
manifest: Any, app_version: str, api_version: str
|
|
295
|
+
) -> str:
|
|
296
|
+
"""Motivo pelo qual o plugin não pode rodar nesta versão do Codis, ou ``""``."""
|
|
297
|
+
min_codis = getattr(manifest, "min_codis", "") or ""
|
|
298
|
+
if min_codis and version_tuple(min_codis) > version_tuple(app_version):
|
|
299
|
+
return f"exige o Codis {min_codis} ou mais novo (esta é a {app_version})"
|
|
300
|
+
wanted = getattr(manifest, "api_version", "") or ""
|
|
301
|
+
if wanted and version_tuple(wanted)[0] > version_tuple(api_version)[0]:
|
|
302
|
+
return f"usa a API {wanted}, mais nova que a {api_version} deste Codis"
|
|
303
|
+
return ""
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
# Extração
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
class UnsafeArchiveError(RuntimeError):
|
|
310
|
+
"""O ZIP tem uma entrada que escaparia da pasta de destino ou é grande demais."""
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def common_prefix(names: list[str]) -> str:
|
|
314
|
+
"""Pasta única que contém tudo (``"plugin/"``), se houver, para ser descartada."""
|
|
315
|
+
entries = [n for n in names if n and not n.startswith("__MACOSX/")]
|
|
316
|
+
if not entries:
|
|
317
|
+
return ""
|
|
318
|
+
first = entries[0]
|
|
319
|
+
if "/" not in first:
|
|
320
|
+
return ""
|
|
321
|
+
candidate = first.split("/", 1)[0] + "/"
|
|
322
|
+
return candidate if all(n.startswith(candidate) for n in entries) else ""
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def extract_zip(
|
|
326
|
+
zf: zipfile.ZipFile,
|
|
327
|
+
dest: Path,
|
|
328
|
+
*,
|
|
329
|
+
max_bytes: int = MAX_PLUGIN_BYTES,
|
|
330
|
+
max_files: int = MAX_PLUGIN_FILES,
|
|
331
|
+
) -> None:
|
|
332
|
+
"""Extrai ``zf`` em ``dest`` recusando caminhos fora dele e arquivos desproporcionais.
|
|
333
|
+
|
|
334
|
+
O tamanho é conferido durante a leitura, não pelo cabeçalho do ZIP, que pode mentir.
|
|
335
|
+
"""
|
|
336
|
+
names = zf.namelist()
|
|
337
|
+
if len(names) > max_files:
|
|
338
|
+
raise UnsafeArchiveError("O plugin tem arquivos demais.")
|
|
339
|
+
prefix = common_prefix(names)
|
|
340
|
+
root = dest.resolve()
|
|
341
|
+
written = 0
|
|
342
|
+
for info in zf.infolist():
|
|
343
|
+
name = info.filename
|
|
344
|
+
if info.is_dir() or name.startswith("__MACOSX/"):
|
|
345
|
+
continue
|
|
346
|
+
rel = name[len(prefix):] if prefix and name.startswith(prefix) else name
|
|
347
|
+
if not rel:
|
|
348
|
+
continue
|
|
349
|
+
target = (root / rel).resolve()
|
|
350
|
+
if target != root and root not in target.parents:
|
|
351
|
+
raise UnsafeArchiveError(f"Entrada insegura no ZIP do plugin: {name!r}")
|
|
352
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
353
|
+
with zf.open(info) as src, open(target, "wb") as out:
|
|
354
|
+
while chunk := src.read(65536):
|
|
355
|
+
written += len(chunk)
|
|
356
|
+
if written > max_bytes:
|
|
357
|
+
raise UnsafeArchiveError("O plugin excede o tamanho máximo permitido.")
|
|
358
|
+
out.write(chunk)
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def is_zip_bytes(data: bytes) -> bool:
|
|
362
|
+
"""``True`` se ``data`` parece um ZIP legível."""
|
|
363
|
+
try:
|
|
364
|
+
with zipfile.ZipFile(io.BytesIO(data)):
|
|
365
|
+
return True
|
|
366
|
+
except zipfile.BadZipFile:
|
|
367
|
+
return False
|