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/extcompat/sources.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Acesso de leitura ao conteúdo de uma extensão: a pasta e, se pedido, os ``.jar`` dentro dela.
|
|
2
|
+
|
|
3
|
+
Plugins do JetBrains e do Eclipse guardam temas, templates e gramáticas dentro de ``.jar``
|
|
4
|
+
(um zip). O ``Bundle`` apresenta tudo como um conjunto único de caminhos relativos, sem extrair
|
|
5
|
+
nada para o disco: só as entradas pedidas são lidas, e com limite de tamanho.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import fnmatch
|
|
11
|
+
import os
|
|
12
|
+
import zipfile
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from .common import MAX_FILE_BYTES, decode
|
|
16
|
+
|
|
17
|
+
MAX_ENTRIES = 20000
|
|
18
|
+
MAX_JARS = 40
|
|
19
|
+
_SKIP_DIRS = {"node_modules", ".git", "__pycache__"}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Bundle:
|
|
23
|
+
def __init__(self, root: Path, *, jars: bool = False) -> None:
|
|
24
|
+
self.root = root
|
|
25
|
+
self._files: dict[str, Path] = {}
|
|
26
|
+
self._jar_entries: dict[str, tuple[Path, str]] = {}
|
|
27
|
+
self._scan(jars)
|
|
28
|
+
|
|
29
|
+
def _scan(self, with_jars: bool) -> None:
|
|
30
|
+
jar_paths: list[Path] = []
|
|
31
|
+
for base, dirs, files in os.walk(self.root, followlinks=False):
|
|
32
|
+
dirs[:] = [d for d in dirs if d not in _SKIP_DIRS]
|
|
33
|
+
for name in files:
|
|
34
|
+
path = Path(base) / name
|
|
35
|
+
if path.is_symlink():
|
|
36
|
+
continue
|
|
37
|
+
if len(self._files) >= MAX_ENTRIES:
|
|
38
|
+
return
|
|
39
|
+
rel = path.relative_to(self.root).as_posix()
|
|
40
|
+
self._files[rel] = path
|
|
41
|
+
if with_jars and name.lower().endswith(".jar") and len(jar_paths) < MAX_JARS:
|
|
42
|
+
jar_paths.append(path)
|
|
43
|
+
for jar in jar_paths:
|
|
44
|
+
self._index_jar(jar)
|
|
45
|
+
|
|
46
|
+
def _index_jar(self, jar: Path) -> None:
|
|
47
|
+
try:
|
|
48
|
+
with zipfile.ZipFile(jar) as zf:
|
|
49
|
+
for info in zf.infolist():
|
|
50
|
+
name = info.filename
|
|
51
|
+
if info.is_dir() or name.startswith(("/", "..")) or ".." in name.split("/"):
|
|
52
|
+
continue
|
|
53
|
+
if len(self._files) + len(self._jar_entries) >= MAX_ENTRIES:
|
|
54
|
+
return
|
|
55
|
+
self._jar_entries.setdefault(name, (jar, name))
|
|
56
|
+
except (zipfile.BadZipFile, OSError):
|
|
57
|
+
return
|
|
58
|
+
|
|
59
|
+
def names(self) -> list[str]:
|
|
60
|
+
return sorted({*self._files, *self._jar_entries})
|
|
61
|
+
|
|
62
|
+
def has(self, rel: str) -> bool:
|
|
63
|
+
return rel in self._files or rel in self._jar_entries
|
|
64
|
+
|
|
65
|
+
def read(self, rel: str) -> bytes | None:
|
|
66
|
+
path = self._files.get(rel)
|
|
67
|
+
try:
|
|
68
|
+
if path is not None:
|
|
69
|
+
if path.stat().st_size > MAX_FILE_BYTES:
|
|
70
|
+
return None
|
|
71
|
+
return path.read_bytes()
|
|
72
|
+
entry = self._jar_entries.get(rel)
|
|
73
|
+
if entry is None:
|
|
74
|
+
return None
|
|
75
|
+
with zipfile.ZipFile(entry[0]) as zf:
|
|
76
|
+
info = zf.getinfo(entry[1])
|
|
77
|
+
if info.file_size > MAX_FILE_BYTES:
|
|
78
|
+
return None
|
|
79
|
+
with zf.open(info) as handle:
|
|
80
|
+
return handle.read(MAX_FILE_BYTES + 1)[:MAX_FILE_BYTES]
|
|
81
|
+
except (OSError, KeyError, zipfile.BadZipFile):
|
|
82
|
+
return None
|
|
83
|
+
|
|
84
|
+
def text(self, rel: str) -> str | None:
|
|
85
|
+
raw = self.read(rel)
|
|
86
|
+
return None if raw is None else decode(raw)
|
|
87
|
+
|
|
88
|
+
def glob(self, *patterns: str) -> list[str]:
|
|
89
|
+
"""Caminhos que casam com algum padrão ``fnmatch`` (sem diferenciar maiúsculas)."""
|
|
90
|
+
lowered = [p.lower() for p in patterns]
|
|
91
|
+
return [n for n in self.names() if any(fnmatch.fnmatchcase(n.lower(), p) for p in lowered)]
|
|
92
|
+
|
|
93
|
+
def with_suffix(self, *suffixes: str) -> list[str]:
|
|
94
|
+
wanted = tuple(s.lower() for s in suffixes)
|
|
95
|
+
return [n for n in self.names() if n.lower().endswith(wanted)]
|
|
96
|
+
|
|
97
|
+
def resolve(self, ref: str, *suffixes: str) -> str | None:
|
|
98
|
+
"""Caminho real para uma referência de plugin (``/themes/x`` ou ``themes/x.json``)."""
|
|
99
|
+
ref = ref.strip().lstrip("/")
|
|
100
|
+
if self.has(ref):
|
|
101
|
+
return ref
|
|
102
|
+
for suffix in suffixes:
|
|
103
|
+
if self.has(ref + suffix):
|
|
104
|
+
return ref + suffix
|
|
105
|
+
return None
|
src/extcompat/store.py
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
"""Instalação, listagem e remoção de extensões importadas (``~/.codis/extensions``)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
10
|
+
import shutil
|
|
11
|
+
import tarfile
|
|
12
|
+
import tempfile
|
|
13
|
+
import zipfile
|
|
14
|
+
from collections.abc import Callable, Iterator
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from . import formats, registry # noqa: F401 - importar `formats` registra os leitores
|
|
18
|
+
from .model import Extension
|
|
19
|
+
from .readers import detect_kind, read_extension
|
|
20
|
+
|
|
21
|
+
logger = logging.getLogger("Codis.ExtCompat")
|
|
22
|
+
|
|
23
|
+
MAX_UNPACKED_BYTES = 120 * 1024 * 1024
|
|
24
|
+
MAX_FILES = 8000
|
|
25
|
+
_SKIP_DIRS = {"node_modules", ".git", ".github", "__pycache__"}
|
|
26
|
+
_ZIP_SUFFIXES = (".vsix", ".zip", ".sublime-package", ".jar")
|
|
27
|
+
_TAR_SUFFIXES = (".tar", ".tar.gz", ".tgz")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class InstallError(Exception):
|
|
31
|
+
"""Falha ao instalar; a mensagem é mostrada ao usuário."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _default_known() -> set[str]:
|
|
35
|
+
from src.constants import EXT_LANG, LANG_KEYWORDS, LANG_LABEL
|
|
36
|
+
|
|
37
|
+
return {*EXT_LANG.values(), *LANG_LABEL, *LANG_KEYWORDS}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _safe_id(raw: str) -> str:
|
|
41
|
+
cleaned = re.sub(r"[^a-z0-9._-]+", "-", raw.lower()).strip(".-")
|
|
42
|
+
if not cleaned:
|
|
43
|
+
raise InstallError("a extensão não tem um identificador utilizável")
|
|
44
|
+
return cleaned
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _extract(archive: Path, dest: Path) -> None:
|
|
48
|
+
"""Extrai com proteção contra caminhos que escapam, links simbólicos e bombas de zip."""
|
|
49
|
+
total = 0
|
|
50
|
+
count = 0
|
|
51
|
+
try:
|
|
52
|
+
zf = zipfile.ZipFile(archive)
|
|
53
|
+
except (zipfile.BadZipFile, OSError) as exc:
|
|
54
|
+
raise InstallError(f"arquivo inválido: {exc}") from exc
|
|
55
|
+
with zf:
|
|
56
|
+
for info in zf.infolist():
|
|
57
|
+
count += 1
|
|
58
|
+
if count > MAX_FILES:
|
|
59
|
+
raise InstallError("o pacote tem arquivos demais")
|
|
60
|
+
if (info.external_attr >> 16) & 0o170000 == 0o120000:
|
|
61
|
+
continue # link simbólico
|
|
62
|
+
target = (dest / info.filename).resolve()
|
|
63
|
+
try:
|
|
64
|
+
target.relative_to(dest.resolve())
|
|
65
|
+
except ValueError as exc:
|
|
66
|
+
raise InstallError("o pacote tenta gravar fora da pasta de destino") from exc
|
|
67
|
+
if info.is_dir():
|
|
68
|
+
target.mkdir(parents=True, exist_ok=True)
|
|
69
|
+
continue
|
|
70
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
71
|
+
with zf.open(info) as src, open(target, "wb") as out:
|
|
72
|
+
while chunk := src.read(65536):
|
|
73
|
+
total += len(chunk)
|
|
74
|
+
if total > MAX_UNPACKED_BYTES:
|
|
75
|
+
raise InstallError("o pacote descompactado é grande demais")
|
|
76
|
+
out.write(chunk)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _extract_tar(archive: Path, dest: Path) -> None:
|
|
80
|
+
"""Extrai um ``.tar`` (pacotes do MELPA, por exemplo) só com arquivos e pastas comuns."""
|
|
81
|
+
total = 0
|
|
82
|
+
count = 0
|
|
83
|
+
try:
|
|
84
|
+
tf = tarfile.open(archive) # noqa: SIM115 - fechado pelo ``with`` abaixo
|
|
85
|
+
except (tarfile.TarError, OSError) as exc:
|
|
86
|
+
raise InstallError(f"arquivo inválido: {exc}") from exc
|
|
87
|
+
with tf:
|
|
88
|
+
for member in tf:
|
|
89
|
+
count += 1
|
|
90
|
+
if count > MAX_FILES:
|
|
91
|
+
raise InstallError("o pacote tem arquivos demais")
|
|
92
|
+
if not (member.isfile() or member.isdir()):
|
|
93
|
+
continue # links, dispositivos e afins
|
|
94
|
+
target = (dest / member.name).resolve()
|
|
95
|
+
try:
|
|
96
|
+
target.relative_to(dest.resolve())
|
|
97
|
+
except ValueError as exc:
|
|
98
|
+
raise InstallError("o pacote tenta gravar fora da pasta de destino") from exc
|
|
99
|
+
if member.isdir():
|
|
100
|
+
target.mkdir(parents=True, exist_ok=True)
|
|
101
|
+
continue
|
|
102
|
+
handle = tf.extractfile(member)
|
|
103
|
+
if handle is None:
|
|
104
|
+
continue
|
|
105
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
106
|
+
with handle, open(target, "wb") as out:
|
|
107
|
+
while chunk := handle.read(65536):
|
|
108
|
+
total += len(chunk)
|
|
109
|
+
if total > MAX_UNPACKED_BYTES:
|
|
110
|
+
raise InstallError("o pacote descompactado é grande demais")
|
|
111
|
+
out.write(chunk)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _copy_tree(src: Path, dest: Path) -> None:
|
|
115
|
+
total = 0
|
|
116
|
+
count = 0
|
|
117
|
+
for base, dirs, files in os.walk(src, followlinks=False):
|
|
118
|
+
dirs[:] = [d for d in dirs if d not in _SKIP_DIRS]
|
|
119
|
+
rel = Path(base).relative_to(src)
|
|
120
|
+
(dest / rel).mkdir(parents=True, exist_ok=True)
|
|
121
|
+
for name in files:
|
|
122
|
+
path = Path(base) / name
|
|
123
|
+
if path.is_symlink():
|
|
124
|
+
continue
|
|
125
|
+
count += 1
|
|
126
|
+
total += path.stat().st_size
|
|
127
|
+
if count > MAX_FILES or total > MAX_UNPACKED_BYTES:
|
|
128
|
+
raise InstallError("a pasta é grande demais para uma extensão")
|
|
129
|
+
shutil.copy2(path, dest / rel / name)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _locate_root(staging: Path) -> Path:
|
|
133
|
+
"""O ``.vsix`` guarda a extensão em ``extension/``; zips comuns podem ter uma pasta única.
|
|
134
|
+
|
|
135
|
+
As pastas mais internas vêm primeiro: a detecção olha subpastas, e a pasta de staging
|
|
136
|
+
sozinha reconheceria qualquer arquivo de tema que estivesse em um nível abaixo.
|
|
137
|
+
"""
|
|
138
|
+
candidates = [staging / "extension"]
|
|
139
|
+
entries = list(staging.iterdir())
|
|
140
|
+
children = [c for c in entries if c.is_dir()]
|
|
141
|
+
if len(children) == 1 and len(entries) == 1: # pasta única: o zip veio embrulhado nela
|
|
142
|
+
candidates += [children[0] / "extension", children[0]]
|
|
143
|
+
candidates.append(staging)
|
|
144
|
+
for cand in candidates:
|
|
145
|
+
if cand.is_dir() and detect_kind(cand):
|
|
146
|
+
return cand
|
|
147
|
+
return staging
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class ExtensionStore:
|
|
151
|
+
"""Guarda as extensões instaladas e quais estão ligadas."""
|
|
152
|
+
|
|
153
|
+
def __init__(self, root: Path | None = None, known: Callable[[], set[str]] | None = None) -> None:
|
|
154
|
+
if root is None:
|
|
155
|
+
from src.constants import EXTENSIONS_DIR
|
|
156
|
+
|
|
157
|
+
root = EXTENSIONS_DIR
|
|
158
|
+
self.root = root
|
|
159
|
+
self._known = known or _default_known
|
|
160
|
+
self._cache: dict[str, Extension] = {}
|
|
161
|
+
|
|
162
|
+
# --- estado ligado/desligado -------------------------------------------------
|
|
163
|
+
|
|
164
|
+
@property
|
|
165
|
+
def _state_file(self) -> Path:
|
|
166
|
+
return self.root / "state.json"
|
|
167
|
+
|
|
168
|
+
def _disabled(self) -> set[str]:
|
|
169
|
+
try:
|
|
170
|
+
data = json.loads(self._state_file.read_text(encoding="utf-8"))
|
|
171
|
+
return {str(x) for x in data.get("disabled", [])}
|
|
172
|
+
except (OSError, ValueError, AttributeError):
|
|
173
|
+
return set()
|
|
174
|
+
|
|
175
|
+
def is_enabled(self, ext_id: str) -> bool:
|
|
176
|
+
return ext_id not in self._disabled()
|
|
177
|
+
|
|
178
|
+
def set_enabled(self, ext_id: str, enabled: bool) -> None:
|
|
179
|
+
disabled = self._disabled()
|
|
180
|
+
disabled.discard(ext_id) if enabled else disabled.add(ext_id)
|
|
181
|
+
self.root.mkdir(parents=True, exist_ok=True)
|
|
182
|
+
tmp = self._state_file.with_suffix(".tmp")
|
|
183
|
+
tmp.write_text(json.dumps({"disabled": sorted(disabled)}, indent=2), encoding="utf-8")
|
|
184
|
+
tmp.replace(self._state_file)
|
|
185
|
+
|
|
186
|
+
# --- consulta ---------------------------------------------------------------------
|
|
187
|
+
|
|
188
|
+
def _dirs(self) -> Iterator[Path]:
|
|
189
|
+
if self.root.is_dir():
|
|
190
|
+
for child in sorted(self.root.iterdir()):
|
|
191
|
+
if child.is_dir() and not child.name.startswith("."):
|
|
192
|
+
yield child
|
|
193
|
+
|
|
194
|
+
def installed(self) -> list[Extension]:
|
|
195
|
+
result: list[Extension] = []
|
|
196
|
+
for directory in self._dirs():
|
|
197
|
+
ext = self._cache.get(directory.name)
|
|
198
|
+
if ext is None:
|
|
199
|
+
try:
|
|
200
|
+
ext = read_extension(directory, self._known())
|
|
201
|
+
except Exception as exc:
|
|
202
|
+
logger.warning("Extensão %s ilegível: %s", directory.name, exc)
|
|
203
|
+
continue
|
|
204
|
+
ext.id = directory.name
|
|
205
|
+
self._cache[directory.name] = ext
|
|
206
|
+
result.append(ext)
|
|
207
|
+
return result
|
|
208
|
+
|
|
209
|
+
def get(self, ext_id: str) -> Extension | None:
|
|
210
|
+
return next((e for e in self.installed() if e.id == ext_id), None)
|
|
211
|
+
|
|
212
|
+
# --- instalação -------------------------------------------------------------------
|
|
213
|
+
|
|
214
|
+
def install(self, source: Path) -> Extension:
|
|
215
|
+
"""Instala de uma pasta, de um pacote compactado ou de um arquivo avulso (tema, esquema, snippets)."""
|
|
216
|
+
source = Path(source)
|
|
217
|
+
if not source.exists():
|
|
218
|
+
raise InstallError(f"não encontrei: {source}")
|
|
219
|
+
self.root.mkdir(parents=True, exist_ok=True)
|
|
220
|
+
staging = Path(tempfile.mkdtemp(prefix=".staging-", dir=self.root))
|
|
221
|
+
try:
|
|
222
|
+
if source.is_dir():
|
|
223
|
+
(staging / source.resolve().name).mkdir()
|
|
224
|
+
_copy_tree(source, staging / source.resolve().name)
|
|
225
|
+
elif source.name.lower().endswith(_ZIP_SUFFIXES):
|
|
226
|
+
_extract(source, staging)
|
|
227
|
+
elif source.name.lower().endswith(_TAR_SUFFIXES):
|
|
228
|
+
_extract_tar(source, staging)
|
|
229
|
+
elif source.suffix.lower() in (".vim", ".lua"):
|
|
230
|
+
(staging / source.stem / "colors").mkdir(parents=True)
|
|
231
|
+
shutil.copy2(source, staging / source.stem / "colors" / source.name)
|
|
232
|
+
elif any(source.name.lower().endswith(sfx) for sfx in registry.file_suffixes()):
|
|
233
|
+
wrapper = staging / (source.name.split(".")[0] or "extensao")
|
|
234
|
+
wrapper.mkdir()
|
|
235
|
+
shutil.copy2(source, wrapper / source.name)
|
|
236
|
+
else:
|
|
237
|
+
raise InstallError(
|
|
238
|
+
"formato não suportado (use uma pasta, um pacote .vsix/.zip/.jar/.sublime-package/.tar "
|
|
239
|
+
"ou um arquivo de tema, esquema de cores ou snippets)"
|
|
240
|
+
)
|
|
241
|
+
ext_root = _locate_root(staging)
|
|
242
|
+
try:
|
|
243
|
+
ext = read_extension(ext_root, self._known())
|
|
244
|
+
except (ValueError, OSError) as exc:
|
|
245
|
+
raise InstallError(str(exc)) from exc
|
|
246
|
+
if ext.empty:
|
|
247
|
+
detail = "; ".join(ext.ignored) or "nenhuma contribuição declarativa"
|
|
248
|
+
raise InstallError(f"nada que o Codis consiga usar nesta extensão ({detail})")
|
|
249
|
+
ext_id = _safe_id(ext.id)
|
|
250
|
+
final = self.root / ext_id
|
|
251
|
+
old = self.root / f".old-{ext_id}"
|
|
252
|
+
if old.exists():
|
|
253
|
+
shutil.rmtree(old, ignore_errors=True)
|
|
254
|
+
if final.exists():
|
|
255
|
+
final.rename(old)
|
|
256
|
+
shutil.move(str(ext_root), str(final))
|
|
257
|
+
shutil.rmtree(old, ignore_errors=True)
|
|
258
|
+
finally:
|
|
259
|
+
shutil.rmtree(staging, ignore_errors=True)
|
|
260
|
+
self._cache.pop(ext_id, None)
|
|
261
|
+
installed = self.get(ext_id)
|
|
262
|
+
if installed is None:
|
|
263
|
+
raise InstallError("a extensão foi copiada mas não pôde ser lida")
|
|
264
|
+
return installed
|
|
265
|
+
|
|
266
|
+
def remove(self, ext_id: str) -> bool:
|
|
267
|
+
target = self.root / _safe_id(ext_id)
|
|
268
|
+
if not target.is_dir():
|
|
269
|
+
return False
|
|
270
|
+
shutil.rmtree(target, ignore_errors=True)
|
|
271
|
+
self._cache.pop(ext_id, None)
|
|
272
|
+
with contextlib.suppress(OSError):
|
|
273
|
+
disabled = self._disabled()
|
|
274
|
+
if ext_id in disabled:
|
|
275
|
+
self.set_enabled(ext_id, True)
|
|
276
|
+
return True
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
"""Tradução de gramáticas TextMate (``.tmLanguage.json`` e ``.tmLanguage`` plist) para o realce do Codis.
|
|
2
|
+
|
|
3
|
+
O Codis realça com uma lista de ``(tag, regex)`` aplicada linha a linha; uma gramática
|
|
4
|
+
TextMate é uma máquina de estados. A tradução é de melhor esforço: regras ``match`` viram
|
|
5
|
+
tokens, e regras ``begin``/``end`` viram um token que cobre do início ao fim. O que não
|
|
6
|
+
cabe (``end`` com referência ao ``begin``, regex que o Python não entende) é descartado.
|
|
7
|
+
Como o realce roda na thread da interface, padrões com risco de backtracking explosivo
|
|
8
|
+
também são recusados.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import plistlib
|
|
15
|
+
import re
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from .jsonc import as_dict, loads_jsonc
|
|
19
|
+
|
|
20
|
+
MAX_TOKENS = 300
|
|
21
|
+
MAX_PATTERN_LEN = 1500
|
|
22
|
+
# Tamanho máximo de um trecho delimitado; evita que uma aspa solta pinte o arquivo inteiro.
|
|
23
|
+
_SPAN_LIMIT = {"default": 2000, "comment_block": 8000}
|
|
24
|
+
_MAX_DEPTH = 6
|
|
25
|
+
|
|
26
|
+
# Escopo (prefixo) -> tag do realce do Codis. A primeira correspondência vence.
|
|
27
|
+
_SCOPE_TAGS: tuple[tuple[str, str], ...] = (
|
|
28
|
+
("comment.block", "comment_block"),
|
|
29
|
+
("comment", "comment_line"),
|
|
30
|
+
("string.regexp", "regexp"),
|
|
31
|
+
("string.template", "string_tmpl"),
|
|
32
|
+
("string", "string"),
|
|
33
|
+
("constant.numeric", "number"),
|
|
34
|
+
("constant.character.escape", "escape"),
|
|
35
|
+
("constant.language", "bool"),
|
|
36
|
+
("constant.other", "bool"),
|
|
37
|
+
("constant", "bool"),
|
|
38
|
+
("keyword.operator", "operator"),
|
|
39
|
+
("keyword.control.directive", "directive"),
|
|
40
|
+
("keyword", "keyword"),
|
|
41
|
+
("storage", "storage"),
|
|
42
|
+
("entity.name.function.decorator", "decorator"),
|
|
43
|
+
("meta.decorator", "decorator"),
|
|
44
|
+
("meta.function-call", "func_call"),
|
|
45
|
+
("entity.name.function", "func_def"),
|
|
46
|
+
("support.function", "builtin"),
|
|
47
|
+
("support.class", "builtin"),
|
|
48
|
+
("support.constant", "builtin"),
|
|
49
|
+
("support.type", "class_name"),
|
|
50
|
+
("entity.name.type", "class_name"),
|
|
51
|
+
("entity.name.class", "class_name"),
|
|
52
|
+
("entity.other.inherited-class", "class_name"),
|
|
53
|
+
("entity.name.tag", "tag_open"),
|
|
54
|
+
("entity.other.attribute-name", "attr_name"),
|
|
55
|
+
("markup.heading", "heading"),
|
|
56
|
+
("markup.bold", "bold"),
|
|
57
|
+
("markup.italic", "italic"),
|
|
58
|
+
("markup.underline.link", "link"),
|
|
59
|
+
("markup.quote", "blockquote"),
|
|
60
|
+
("variable", "variable"),
|
|
61
|
+
("invalid", "bool"),
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
_POSIX = {
|
|
65
|
+
"alpha": "a-zA-Z", "digit": "0-9", "alnum": "a-zA-Z0-9", "upper": "A-Z", "lower": "a-z",
|
|
66
|
+
"space": r"\s", "word": r"\w", "xdigit": "0-9a-fA-F", "punct": r"!-/:-@\[-`{-~",
|
|
67
|
+
"blank": r" \t",
|
|
68
|
+
}
|
|
69
|
+
_PROP = {
|
|
70
|
+
"alpha": r"[^\W\d_]", "alnum": r"[^\W_]", "digit": r"\d", "upper": r"[A-Z]",
|
|
71
|
+
"lower": r"[a-z]", "space": r"\s", "word": r"\w", "l": r"[^\W\d_]", "lu": r"[A-Z]",
|
|
72
|
+
"ll": r"[a-z]", "n": r"\d", "nd": r"\d",
|
|
73
|
+
}
|
|
74
|
+
# Quantificador aplicado a um grupo que já termina em quantificador: ``(a+)+``, ``(.*)*``.
|
|
75
|
+
_NESTED_QUANT = re.compile(r"\((?:[^()\\]|\\.)*[+*]\)[+*{]")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def load_grammar(raw: bytes | str) -> dict[str, Any]:
|
|
79
|
+
"""Lê uma gramática em JSON/JSONC ou em plist XML."""
|
|
80
|
+
data = raw if isinstance(raw, bytes) else raw.encode("utf-8")
|
|
81
|
+
stripped = data.lstrip()
|
|
82
|
+
if stripped.startswith(b"<"):
|
|
83
|
+
return plistlib.loads(data)
|
|
84
|
+
return loads_jsonc(data.decode("utf-8-sig", errors="replace"))
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def scope_to_tag(scope: str) -> str | None:
|
|
88
|
+
for prefix, tag in _SCOPE_TAGS:
|
|
89
|
+
if scope == prefix or scope.startswith(prefix + "."):
|
|
90
|
+
return tag
|
|
91
|
+
return None
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def translate_regex(pattern: str) -> str | None:
|
|
95
|
+
"""Converte Oniguruma em regex do Python; ``None`` se não for confiável."""
|
|
96
|
+
if not pattern or len(pattern) > MAX_PATTERN_LEN:
|
|
97
|
+
return None
|
|
98
|
+
p = pattern.replace("\\G", "")
|
|
99
|
+
flags = ""
|
|
100
|
+
lead = re.match(r"\(\?([imsx]+)\)", p)
|
|
101
|
+
if lead:
|
|
102
|
+
flags = lead.group(1).replace("x", "")
|
|
103
|
+
p = p[lead.end():]
|
|
104
|
+
p = re.sub(r"\(\?<([A-Za-z_]\w*)>", "(?:", p) # grupo nomeado vira não capturante
|
|
105
|
+
p = re.sub(r"\(\?P?<([A-Za-z_]\w*)>", "(?:", p)
|
|
106
|
+
p = p.replace("\\h", "[0-9a-fA-F]").replace("\\H", "[^0-9a-fA-F]")
|
|
107
|
+
p = p.replace("\\z", r"\Z").replace("\\Z", r"(?=\n?\Z)")
|
|
108
|
+
p = re.sub(r"\\p\{\^?(\w+)\}", lambda m: _PROP.get(m.group(1).lower(), r"\w"), p)
|
|
109
|
+
p = re.sub(
|
|
110
|
+
r"\[:(\^?)(\w+):\]",
|
|
111
|
+
lambda m: _POSIX.get(m.group(2), "") if not m.group(1) else "",
|
|
112
|
+
p,
|
|
113
|
+
)
|
|
114
|
+
if _NESTED_QUANT.search(p):
|
|
115
|
+
return None
|
|
116
|
+
if flags:
|
|
117
|
+
p = f"(?{flags}:{p})"
|
|
118
|
+
try:
|
|
119
|
+
re.compile(p, re.MULTILINE)
|
|
120
|
+
except (re.error, RecursionError):
|
|
121
|
+
return None
|
|
122
|
+
return p
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _keywords_in(pattern: str) -> list[str]:
|
|
126
|
+
words: list[str] = []
|
|
127
|
+
for group in re.findall(r"\((?:\?:)?([\w|]+)\)", pattern):
|
|
128
|
+
if "|" in group:
|
|
129
|
+
words.extend(w for w in group.split("|") if len(w) >= 2 and w.isidentifier())
|
|
130
|
+
return words
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
class _Collector:
|
|
134
|
+
def __init__(self, repository: dict[str, Any]) -> None:
|
|
135
|
+
self.repo = repository
|
|
136
|
+
self.delimited: list[tuple[str, str]] = []
|
|
137
|
+
self.plain: list[tuple[str, str]] = []
|
|
138
|
+
self.keywords: list[str] = []
|
|
139
|
+
self._seen: set[str] = set()
|
|
140
|
+
|
|
141
|
+
def walk(self, rules: Any, depth: int = 0, trail: tuple[str, ...] = ()) -> None:
|
|
142
|
+
if not isinstance(rules, list) or depth > _MAX_DEPTH:
|
|
143
|
+
return
|
|
144
|
+
for rule in rules:
|
|
145
|
+
if not isinstance(rule, dict):
|
|
146
|
+
continue
|
|
147
|
+
include = rule.get("include")
|
|
148
|
+
if isinstance(include, str):
|
|
149
|
+
if include.startswith("#") and include[1:] not in trail:
|
|
150
|
+
target = self.repo.get(include[1:])
|
|
151
|
+
if isinstance(target, dict):
|
|
152
|
+
self.walk([target], depth + 1, (*trail, include[1:]))
|
|
153
|
+
continue
|
|
154
|
+
scope = str(rule.get("name") or rule.get("contentName") or "")
|
|
155
|
+
tag = scope_to_tag(scope) if scope else None
|
|
156
|
+
if "match" in rule and tag:
|
|
157
|
+
self._add_match(tag, rule["match"])
|
|
158
|
+
elif "begin" in rule and "end" in rule and tag:
|
|
159
|
+
self._add_span(tag, rule["begin"], rule["end"])
|
|
160
|
+
if isinstance(rule.get("patterns"), list):
|
|
161
|
+
self.walk(rule["patterns"], depth + 1, trail)
|
|
162
|
+
|
|
163
|
+
def _add_match(self, tag: str, match: Any) -> None:
|
|
164
|
+
if not isinstance(match, str):
|
|
165
|
+
return
|
|
166
|
+
pat = translate_regex(match)
|
|
167
|
+
if pat and pat not in self._seen:
|
|
168
|
+
self._seen.add(pat)
|
|
169
|
+
self.plain.append((tag, pat))
|
|
170
|
+
if tag in ("keyword", "storage", "bool", "builtin"):
|
|
171
|
+
self.keywords.extend(_keywords_in(match))
|
|
172
|
+
|
|
173
|
+
def _add_span(self, tag: str, begin: Any, end: Any) -> None:
|
|
174
|
+
if not (isinstance(begin, str) and isinstance(end, str)) or re.search(r"\\\d", end):
|
|
175
|
+
return
|
|
176
|
+
b = translate_regex(begin)
|
|
177
|
+
if b is None:
|
|
178
|
+
return
|
|
179
|
+
if end.strip() in ("$", "\\n", "(?=$)", "$\\n?"):
|
|
180
|
+
body = f"{b}[^\\n]*"
|
|
181
|
+
else:
|
|
182
|
+
e = translate_regex(end)
|
|
183
|
+
if e is None:
|
|
184
|
+
return
|
|
185
|
+
limit = _SPAN_LIMIT["comment_block"] if tag == "comment_block" else _SPAN_LIMIT["default"]
|
|
186
|
+
body = f"{b}[\\s\\S]{{0,{limit}}}?(?:{e})"
|
|
187
|
+
if body not in self._seen and len(body) <= MAX_PATTERN_LEN * 2:
|
|
188
|
+
self._seen.add(body)
|
|
189
|
+
self.delimited.append((tag, body))
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def grammar_to_tokens(grammar: dict[str, Any]) -> tuple[list[tuple[str, str]], list[str]]:
|
|
193
|
+
"""Devolve ``(tokens, palavras-chave)``; tokens com nomes únicos, prontos para ``register_language``."""
|
|
194
|
+
repo = as_dict(grammar.get("repository"))
|
|
195
|
+
collector = _Collector(repo)
|
|
196
|
+
collector.walk(grammar.get("patterns"))
|
|
197
|
+
ordered = collector.delimited + collector.plain
|
|
198
|
+
counts: dict[str, int] = {}
|
|
199
|
+
tokens: list[tuple[str, str]] = []
|
|
200
|
+
for tag, pat in ordered[:MAX_TOKENS]:
|
|
201
|
+
counts[tag] = counts.get(tag, 0) + 1
|
|
202
|
+
name = tag if counts[tag] == 1 else f"{tag}_{counts[tag]}"
|
|
203
|
+
tokens.append((name, pat))
|
|
204
|
+
keywords = sorted(set(collector.keywords))[:500]
|
|
205
|
+
try:
|
|
206
|
+
re.compile("|".join(f"(?P<{n}>{p})" for n, p in tokens), re.MULTILINE)
|
|
207
|
+
except re.error:
|
|
208
|
+
# Uma combinação inválida (rara) derruba só a gramática, não a extensão.
|
|
209
|
+
return [], keywords
|
|
210
|
+
return tokens, keywords
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def dumps_debug(tokens: list[tuple[str, str]]) -> str: # pragma: no cover - auxiliar de depuração
|
|
214
|
+
return json.dumps(tokens, ensure_ascii=False, indent=1)
|