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/trash_core.py
ADDED
|
@@ -0,0 +1,531 @@
|
|
|
1
|
+
"""Núcleo da lixeira do Codis (sem dependência de Tkinter).
|
|
2
|
+
|
|
3
|
+
Princípios
|
|
4
|
+
----------
|
|
5
|
+
* **Mesmo volume, sempre.** A lixeira de um arquivo vive em
|
|
6
|
+
``<raiz-do-projeto>/.codis_trash/``. Mover para a lixeira é um
|
|
7
|
+
``os.rename`` atômico - instantâneo mesmo para 100 GB - e **nunca** uma
|
|
8
|
+
cópia entre discos. Se por algum motivo o rename cruzar dispositivos
|
|
9
|
+
(``EXDEV``), a operação é recusada com :class:`CrossDeviceError` em vez de
|
|
10
|
+
copiar gigabytes silenciosamente.
|
|
11
|
+
* **Autocontida.** Cada ``.codis_trash`` tem o seu ``.meta.json``; copiar,
|
|
12
|
+
mover ou apagar o projeto leva a lixeira junto.
|
|
13
|
+
* **Invisível para o git.** A pasta recebe um ``.gitignore`` com ``*``, o que
|
|
14
|
+
a faz ignorar a si mesma sem tocar no ``.gitignore`` do usuário.
|
|
15
|
+
|
|
16
|
+
API principal: :class:`TrashStore` (uma pasta de lixeira) e
|
|
17
|
+
:class:`TrashRegistry` (descobre e agrega as lixeiras conhecidas).
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import contextlib
|
|
23
|
+
import datetime as _dt
|
|
24
|
+
import errno
|
|
25
|
+
import json
|
|
26
|
+
import logging
|
|
27
|
+
import os
|
|
28
|
+
import shutil
|
|
29
|
+
import threading
|
|
30
|
+
import uuid
|
|
31
|
+
from collections.abc import Callable, Iterable
|
|
32
|
+
from dataclasses import dataclass
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
from typing import Any
|
|
35
|
+
|
|
36
|
+
logger = logging.getLogger("Codis.Trash")
|
|
37
|
+
|
|
38
|
+
TRASH_DIRNAME = ".codis_trash"
|
|
39
|
+
META_NAME = ".meta.json"
|
|
40
|
+
_PROJECT_MARKERS = (".git", ".codis", ".hg", ".svn")
|
|
41
|
+
_META_VERSION = 2
|
|
42
|
+
|
|
43
|
+
_LOCKS: dict[str, threading.RLock] = {}
|
|
44
|
+
_LOCKS_GUARD = threading.Lock()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _lock_for(path: Path) -> threading.RLock:
|
|
48
|
+
key = str(path)
|
|
49
|
+
with _LOCKS_GUARD:
|
|
50
|
+
lock = _LOCKS.get(key)
|
|
51
|
+
if lock is None:
|
|
52
|
+
lock = _LOCKS[key] = threading.RLock()
|
|
53
|
+
return lock
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class TrashError(OSError):
|
|
57
|
+
"""Erro genérico de lixeira."""
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class CrossDeviceError(TrashError):
|
|
61
|
+
"""A lixeira ficaria em outro volume; mover exigiria copiar dados."""
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class NothingToDoError(TrashError):
|
|
65
|
+
"""Item inexistente na lixeira."""
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _dev(path: Path) -> int | None:
|
|
69
|
+
"""``st_dev`` do próprio *path* (sem seguir symlink) ou ``None``."""
|
|
70
|
+
try:
|
|
71
|
+
return os.lstat(path).st_dev
|
|
72
|
+
except OSError:
|
|
73
|
+
return None
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _is_relative_to(path: Path, base: Path) -> bool:
|
|
77
|
+
try:
|
|
78
|
+
path.relative_to(base)
|
|
79
|
+
except ValueError:
|
|
80
|
+
return False
|
|
81
|
+
return True
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _absolute(path: Path | str) -> Path:
|
|
85
|
+
"""Caminho absoluto *sem* resolver o último componente (preserva symlinks)."""
|
|
86
|
+
p = Path(path)
|
|
87
|
+
if not p.is_absolute():
|
|
88
|
+
p = Path.cwd() / p
|
|
89
|
+
return Path(os.path.normpath(p))
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def find_project_root(path: Path) -> Path | None:
|
|
93
|
+
"""Sobe a partir de ``path.parent`` procurando um marcador de projeto."""
|
|
94
|
+
for parent in _absolute(path).parents:
|
|
95
|
+
if any((parent / m).exists() for m in _PROJECT_MARKERS):
|
|
96
|
+
return parent
|
|
97
|
+
return None
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def trash_root_for(path: Path | str, workspace: Path | str | None = None) -> Path:
|
|
101
|
+
"""Escolhe a pasta que hospedará o ``.codis_trash`` de *path*.
|
|
102
|
+
|
|
103
|
+
Ordem:
|
|
104
|
+
|
|
105
|
+
1. A pasta de trabalho (*workspace*), se *path* estiver dentro dela
|
|
106
|
+
(se *path* for a própria pasta de trabalho, a pasta pai dela);
|
|
107
|
+
2. a raiz de projeto detectada (``.git``/``.codis``...);
|
|
108
|
+
3. a pasta que contém o arquivo.
|
|
109
|
+
|
|
110
|
+
Em qualquer caso a escolha é **rebaixada** até o ancestral mais alto que
|
|
111
|
+
esteja no *mesmo volume* do arquivo (cobre pontos de montagem dentro do
|
|
112
|
+
projeto), garantindo que o ``rename`` nunca cruze dispositivos.
|
|
113
|
+
"""
|
|
114
|
+
p = _absolute(path)
|
|
115
|
+
anchor: Path | None = None
|
|
116
|
+
if workspace:
|
|
117
|
+
ws = _absolute(workspace)
|
|
118
|
+
if p == ws:
|
|
119
|
+
anchor = ws.parent
|
|
120
|
+
elif _is_relative_to(p, ws):
|
|
121
|
+
anchor = ws
|
|
122
|
+
if anchor is None:
|
|
123
|
+
anchor = find_project_root(p) or p.parent
|
|
124
|
+
|
|
125
|
+
file_dev = _dev(p)
|
|
126
|
+
if file_dev is None:
|
|
127
|
+
return anchor
|
|
128
|
+
|
|
129
|
+
chain: list[Path] = []
|
|
130
|
+
cur = p.parent
|
|
131
|
+
while True:
|
|
132
|
+
chain.append(cur)
|
|
133
|
+
if cur == anchor or cur.parent == cur:
|
|
134
|
+
break
|
|
135
|
+
cur = cur.parent
|
|
136
|
+
for cand in reversed(chain):
|
|
137
|
+
if _dev(cand) == file_dev:
|
|
138
|
+
return cand
|
|
139
|
+
return p.parent
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _fmt_ts(ts: _dt.datetime | None = None) -> str:
|
|
143
|
+
return (ts or _dt.datetime.now()).isoformat(timespec="seconds")
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def tree_size(path: Path, *, limit_s: float | None = None, cancel: threading.Event | None = None) -> int | None:
|
|
147
|
+
"""Tamanho total em bytes (``None`` se estourar *limit_s* ou for cancelado).
|
|
148
|
+
|
|
149
|
+
Não segue symlinks; erros de permissão são ignorados.
|
|
150
|
+
"""
|
|
151
|
+
import time
|
|
152
|
+
|
|
153
|
+
deadline = (time.monotonic() + limit_s) if limit_s else None
|
|
154
|
+
try:
|
|
155
|
+
st = os.lstat(path)
|
|
156
|
+
except OSError:
|
|
157
|
+
return 0
|
|
158
|
+
if not os.path.isdir(path) or os.path.islink(path):
|
|
159
|
+
return st.st_size
|
|
160
|
+
total = 0
|
|
161
|
+
stack = [str(path)]
|
|
162
|
+
while stack:
|
|
163
|
+
if cancel is not None and cancel.is_set():
|
|
164
|
+
return None
|
|
165
|
+
if deadline is not None and time.monotonic() > deadline:
|
|
166
|
+
return None
|
|
167
|
+
cur = stack.pop()
|
|
168
|
+
try:
|
|
169
|
+
with os.scandir(cur) as it:
|
|
170
|
+
for entry in it:
|
|
171
|
+
try:
|
|
172
|
+
if entry.is_dir(follow_symlinks=False):
|
|
173
|
+
stack.append(entry.path)
|
|
174
|
+
else:
|
|
175
|
+
total += entry.stat(follow_symlinks=False).st_size
|
|
176
|
+
except OSError:
|
|
177
|
+
continue
|
|
178
|
+
except OSError:
|
|
179
|
+
continue
|
|
180
|
+
return total
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
@dataclass
|
|
184
|
+
class TrashEntry:
|
|
185
|
+
"""Um item na lixeira."""
|
|
186
|
+
|
|
187
|
+
id: str
|
|
188
|
+
original: str
|
|
189
|
+
name: str
|
|
190
|
+
is_dir: bool
|
|
191
|
+
deleted_at: str
|
|
192
|
+
size: int | None = None
|
|
193
|
+
store: Path | None = None
|
|
194
|
+
|
|
195
|
+
@property
|
|
196
|
+
def path(self) -> Path:
|
|
197
|
+
assert self.store is not None
|
|
198
|
+
return self.store / self.id
|
|
199
|
+
|
|
200
|
+
def to_json(self) -> dict[str, Any]:
|
|
201
|
+
return {
|
|
202
|
+
"id": self.id,
|
|
203
|
+
"original": self.original,
|
|
204
|
+
"name": self.name,
|
|
205
|
+
"is_dir": self.is_dir,
|
|
206
|
+
"deleted_at": self.deleted_at,
|
|
207
|
+
"size": self.size,
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
@classmethod
|
|
211
|
+
def from_json(cls, raw: dict[str, Any], store: Path) -> TrashEntry | None:
|
|
212
|
+
try:
|
|
213
|
+
return cls(
|
|
214
|
+
id=str(raw["id"]),
|
|
215
|
+
original=str(raw["original"]),
|
|
216
|
+
name=str(raw.get("name") or Path(str(raw["original"])).name),
|
|
217
|
+
is_dir=bool(raw.get("is_dir", False)),
|
|
218
|
+
deleted_at=str(raw.get("deleted_at", "")),
|
|
219
|
+
size=raw.get("size") if isinstance(raw.get("size"), int) else None,
|
|
220
|
+
store=store,
|
|
221
|
+
)
|
|
222
|
+
except (KeyError, TypeError):
|
|
223
|
+
return None
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
class TrashStore:
|
|
227
|
+
"""Uma pasta ``.codis_trash`` com seus metadados."""
|
|
228
|
+
|
|
229
|
+
def __init__(self, directory: Path) -> None:
|
|
230
|
+
self.dir = Path(directory)
|
|
231
|
+
self._meta = self.dir / META_NAME
|
|
232
|
+
|
|
233
|
+
@classmethod
|
|
234
|
+
def for_root(cls, root: Path | str) -> TrashStore:
|
|
235
|
+
return cls(Path(root) / TRASH_DIRNAME)
|
|
236
|
+
|
|
237
|
+
def _read(self) -> list[dict[str, Any]]:
|
|
238
|
+
try:
|
|
239
|
+
raw = json.loads(self._meta.read_text(encoding="utf-8"))
|
|
240
|
+
except FileNotFoundError:
|
|
241
|
+
return []
|
|
242
|
+
except (OSError, ValueError) as exc:
|
|
243
|
+
logger.warning("Metadados da lixeira ilegíveis (%s): %s", self._meta, exc)
|
|
244
|
+
bak = self._meta.with_suffix(".json.bak")
|
|
245
|
+
with contextlib.suppress(OSError):
|
|
246
|
+
self._meta.replace(bak)
|
|
247
|
+
return self._rebuild_from_disk()
|
|
248
|
+
if isinstance(raw, dict):
|
|
249
|
+
raw = raw.get("entries", [])
|
|
250
|
+
return [e for e in raw if isinstance(e, dict)] if isinstance(raw, list) else []
|
|
251
|
+
|
|
252
|
+
def _write(self, entries: list[dict[str, Any]]) -> None:
|
|
253
|
+
self.dir.mkdir(parents=True, exist_ok=True)
|
|
254
|
+
tmp = self._meta.with_suffix(f".tmp{os.getpid()}")
|
|
255
|
+
payload = {"version": _META_VERSION, "entries": entries}
|
|
256
|
+
tmp.write_text(json.dumps(payload, ensure_ascii=False, indent=1), encoding="utf-8")
|
|
257
|
+
os.replace(tmp, self._meta)
|
|
258
|
+
|
|
259
|
+
def _rebuild_from_disk(self) -> list[dict[str, Any]]:
|
|
260
|
+
"""Reconstrói metadados mínimos quando o JSON foi perdido/corrompido."""
|
|
261
|
+
out: list[dict[str, Any]] = []
|
|
262
|
+
with contextlib.suppress(OSError):
|
|
263
|
+
for child in self.dir.iterdir():
|
|
264
|
+
if child.name in (META_NAME, ".gitignore") or child.name.startswith(META_NAME):
|
|
265
|
+
continue
|
|
266
|
+
out.append(
|
|
267
|
+
{
|
|
268
|
+
"id": child.name,
|
|
269
|
+
"original": str(self.dir.parent / _strip_prefix(child.name)),
|
|
270
|
+
"name": _strip_prefix(child.name),
|
|
271
|
+
"is_dir": child.is_dir(),
|
|
272
|
+
"deleted_at": _fmt_ts(_dt.datetime.fromtimestamp(child.lstat().st_mtime)),
|
|
273
|
+
"size": None,
|
|
274
|
+
}
|
|
275
|
+
)
|
|
276
|
+
return out
|
|
277
|
+
|
|
278
|
+
def _ensure_dir(self) -> None:
|
|
279
|
+
self.dir.mkdir(parents=True, exist_ok=True)
|
|
280
|
+
gi = self.dir / ".gitignore"
|
|
281
|
+
if not gi.exists():
|
|
282
|
+
with contextlib.suppress(OSError):
|
|
283
|
+
gi.write_text("# Lixeira local do Codis - não versionar\n*\n", encoding="utf-8")
|
|
284
|
+
|
|
285
|
+
def entries(self) -> list[TrashEntry]:
|
|
286
|
+
"""Itens existentes (descarta metadados órfãos) - mais recentes primeiro."""
|
|
287
|
+
with _lock_for(self.dir):
|
|
288
|
+
out: list[TrashEntry] = []
|
|
289
|
+
for raw in self._read():
|
|
290
|
+
e = TrashEntry.from_json(raw, self.dir)
|
|
291
|
+
if e is not None and os.path.lexists(e.path):
|
|
292
|
+
out.append(e)
|
|
293
|
+
out.sort(key=lambda e: e.deleted_at, reverse=True)
|
|
294
|
+
return out
|
|
295
|
+
|
|
296
|
+
def get(self, entry_id: str) -> TrashEntry | None:
|
|
297
|
+
return next((e for e in self.entries() if e.id == entry_id), None)
|
|
298
|
+
|
|
299
|
+
def put(self, path: Path | str) -> TrashEntry:
|
|
300
|
+
"""Move *path* para esta lixeira com ``rename`` atômico."""
|
|
301
|
+
src = _absolute(path)
|
|
302
|
+
if not os.path.lexists(src):
|
|
303
|
+
raise FileNotFoundError(errno.ENOENT, "Arquivo inexistente", str(src))
|
|
304
|
+
if _is_relative_to(src, self.dir) or src == self.dir:
|
|
305
|
+
raise TrashError(f"'{src}' já está na lixeira.")
|
|
306
|
+
if _dev(src) != _dev(self.dir.parent):
|
|
307
|
+
raise CrossDeviceError(
|
|
308
|
+
errno.EXDEV,
|
|
309
|
+
"A lixeira ficaria em outro volume (mover exigiria copiar dados).",
|
|
310
|
+
str(src),
|
|
311
|
+
)
|
|
312
|
+
is_dir = os.path.isdir(src) and not os.path.islink(src)
|
|
313
|
+
try:
|
|
314
|
+
size = None if is_dir else os.lstat(src).st_size
|
|
315
|
+
except OSError:
|
|
316
|
+
size = None
|
|
317
|
+
tid = f"{_dt.datetime.now():%Y%m%d_%H%M%S}_{uuid.uuid4().hex[:8]}_{src.name}"
|
|
318
|
+
with _lock_for(self.dir):
|
|
319
|
+
self._ensure_dir()
|
|
320
|
+
dest = self.dir / tid
|
|
321
|
+
try:
|
|
322
|
+
os.rename(src, dest)
|
|
323
|
+
except OSError as exc:
|
|
324
|
+
if exc.errno == errno.EXDEV:
|
|
325
|
+
raise CrossDeviceError(errno.EXDEV, "Cruzaria volumes; recusado.", str(src)) from exc
|
|
326
|
+
raise
|
|
327
|
+
entry = TrashEntry(tid, str(src), src.name, is_dir, _fmt_ts(), size, self.dir)
|
|
328
|
+
entries = self._read()
|
|
329
|
+
entries.append(entry.to_json())
|
|
330
|
+
self._write(entries)
|
|
331
|
+
logger.debug("Lixeira: '%s' -> '%s'", src, dest)
|
|
332
|
+
return entry
|
|
333
|
+
|
|
334
|
+
def restore(self, entry_id: str, *, to: Path | str | None = None) -> Path:
|
|
335
|
+
"""Restaura para o caminho original (ou *to*). Retorna o destino final.
|
|
336
|
+
|
|
337
|
+
Se o destino existir, ganha o sufixo ``_restaurado[_N]``; pastas pai
|
|
338
|
+
ausentes são recriadas.
|
|
339
|
+
"""
|
|
340
|
+
with _lock_for(self.dir):
|
|
341
|
+
entry = next((TrashEntry.from_json(r, self.dir) for r in self._read() if r.get("id") == entry_id), None)
|
|
342
|
+
if entry is None or not os.path.lexists(entry.path):
|
|
343
|
+
self._drop(entry_id)
|
|
344
|
+
raise NothingToDoError(errno.ENOENT, "Item não está mais na lixeira.", entry_id)
|
|
345
|
+
dest = _absolute(to) if to else Path(entry.original)
|
|
346
|
+
dest = _free_name(dest)
|
|
347
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
348
|
+
try:
|
|
349
|
+
os.rename(entry.path, dest)
|
|
350
|
+
except OSError as exc:
|
|
351
|
+
if exc.errno != errno.EXDEV:
|
|
352
|
+
raise
|
|
353
|
+
shutil.move(str(entry.path), str(dest))
|
|
354
|
+
self._drop(entry_id)
|
|
355
|
+
return dest
|
|
356
|
+
|
|
357
|
+
def purge(self, entry_id: str, *, cancel: threading.Event | None = None) -> bool:
|
|
358
|
+
"""Exclui definitivamente um item. Pode demorar - rode fora da UI."""
|
|
359
|
+
with _lock_for(self.dir):
|
|
360
|
+
target = self.dir / entry_id
|
|
361
|
+
removed = _remove_tree(target, cancel)
|
|
362
|
+
if removed:
|
|
363
|
+
with _lock_for(self.dir):
|
|
364
|
+
self._drop(entry_id)
|
|
365
|
+
return removed
|
|
366
|
+
|
|
367
|
+
def empty(self, *, cancel: threading.Event | None = None, progress: Callable[[int, int], None] | None = None) -> int:
|
|
368
|
+
items = self.entries()
|
|
369
|
+
n = 0
|
|
370
|
+
for i, e in enumerate(items, 1):
|
|
371
|
+
if cancel is not None and cancel.is_set():
|
|
372
|
+
break
|
|
373
|
+
if self.purge(e.id, cancel=cancel):
|
|
374
|
+
n += 1
|
|
375
|
+
if progress:
|
|
376
|
+
progress(i, len(items))
|
|
377
|
+
return n
|
|
378
|
+
|
|
379
|
+
def _drop(self, entry_id: str) -> None:
|
|
380
|
+
entries = [r for r in self._read() if r.get("id") != entry_id]
|
|
381
|
+
self._write(entries)
|
|
382
|
+
|
|
383
|
+
def set_size(self, entry_id: str, size: int) -> None:
|
|
384
|
+
with _lock_for(self.dir):
|
|
385
|
+
entries = self._read()
|
|
386
|
+
for r in entries:
|
|
387
|
+
if r.get("id") == entry_id:
|
|
388
|
+
r["size"] = int(size)
|
|
389
|
+
self._write(entries)
|
|
390
|
+
|
|
391
|
+
def purge_expired(self, *, older_than_days: int = 0, max_bytes: int = 0, cancel: threading.Event | None = None) -> int:
|
|
392
|
+
"""Remove itens vencidos (``older_than_days``) e/ou acima do teto de tamanho.
|
|
393
|
+
|
|
394
|
+
``0`` desativa cada critério. O teto remove os mais antigos primeiro.
|
|
395
|
+
"""
|
|
396
|
+
removed = 0
|
|
397
|
+
entries = self.entries()
|
|
398
|
+
if older_than_days > 0:
|
|
399
|
+
limit = _dt.datetime.now() - _dt.timedelta(days=older_than_days)
|
|
400
|
+
for e in list(entries):
|
|
401
|
+
try:
|
|
402
|
+
when = _dt.datetime.fromisoformat(e.deleted_at)
|
|
403
|
+
except ValueError:
|
|
404
|
+
continue
|
|
405
|
+
if when < limit and self.purge(e.id, cancel=cancel):
|
|
406
|
+
removed += 1
|
|
407
|
+
entries.remove(e)
|
|
408
|
+
if max_bytes > 0:
|
|
409
|
+
sized = []
|
|
410
|
+
for e in entries:
|
|
411
|
+
if e.size is None:
|
|
412
|
+
e.size = tree_size(e.path, cancel=cancel)
|
|
413
|
+
if e.size is not None:
|
|
414
|
+
self.set_size(e.id, e.size)
|
|
415
|
+
sized.append(e)
|
|
416
|
+
total = sum(e.size or 0 for e in sized)
|
|
417
|
+
for e in reversed(sized):
|
|
418
|
+
if total <= max_bytes:
|
|
419
|
+
break
|
|
420
|
+
if self.purge(e.id, cancel=cancel):
|
|
421
|
+
total -= e.size or 0
|
|
422
|
+
removed += 1
|
|
423
|
+
return removed
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def _strip_prefix(tid: str) -> str:
|
|
427
|
+
"""``20260101_120000_abcd1234_nome.ext`` → ``nome.ext``."""
|
|
428
|
+
parts = tid.split("_", 3)
|
|
429
|
+
return parts[3] if len(parts) == 4 else tid
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def _free_name(dest: Path) -> Path:
|
|
433
|
+
if not os.path.lexists(dest):
|
|
434
|
+
return dest
|
|
435
|
+
stem, suffix = dest.stem, "".join(dest.suffixes)
|
|
436
|
+
if suffix:
|
|
437
|
+
stem = dest.name[: -len(suffix)]
|
|
438
|
+
n = 0
|
|
439
|
+
while True:
|
|
440
|
+
tag = "_restaurado" + (f"_{n}" if n else "")
|
|
441
|
+
cand = dest.with_name(f"{stem}{tag}{suffix}")
|
|
442
|
+
if not os.path.lexists(cand):
|
|
443
|
+
return cand
|
|
444
|
+
n += 1
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def _remove_tree(target: Path, cancel: threading.Event | None = None) -> bool:
|
|
448
|
+
"""Remove arquivo/pasta tolerando somente-leitura (comum no Windows)."""
|
|
449
|
+
if not os.path.lexists(target):
|
|
450
|
+
return True
|
|
451
|
+
|
|
452
|
+
def _onerror(func: Callable[..., Any], p: str, _exc: Any) -> None:
|
|
453
|
+
with contextlib.suppress(OSError):
|
|
454
|
+
os.chmod(p, 0o700)
|
|
455
|
+
func(p)
|
|
456
|
+
|
|
457
|
+
try:
|
|
458
|
+
if os.path.isdir(target) and not os.path.islink(target):
|
|
459
|
+
if cancel is not None and cancel.is_set():
|
|
460
|
+
return False
|
|
461
|
+
shutil.rmtree(target, onexc=_onerror)
|
|
462
|
+
else:
|
|
463
|
+
try:
|
|
464
|
+
os.unlink(target)
|
|
465
|
+
except PermissionError:
|
|
466
|
+
os.chmod(target, 0o700)
|
|
467
|
+
os.unlink(target)
|
|
468
|
+
except OSError as exc:
|
|
469
|
+
logger.warning("Falha ao remover '%s': %s", target, exc)
|
|
470
|
+
return False
|
|
471
|
+
return not os.path.lexists(target)
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
class TrashRegistry:
|
|
475
|
+
"""Descobre as lixeiras relevantes e oferece uma API única."""
|
|
476
|
+
|
|
477
|
+
def stores_for(self, workspace: Path | str | None, extra_roots: Iterable[Path | str] = ()) -> list[TrashStore]:
|
|
478
|
+
seen: set[str] = set()
|
|
479
|
+
out: list[TrashStore] = []
|
|
480
|
+
|
|
481
|
+
def _add(store: TrashStore) -> None:
|
|
482
|
+
key = str(store.dir)
|
|
483
|
+
if key not in seen and store.dir.is_dir():
|
|
484
|
+
seen.add(key)
|
|
485
|
+
out.append(store)
|
|
486
|
+
|
|
487
|
+
if workspace:
|
|
488
|
+
ws = Path(workspace)
|
|
489
|
+
_add(TrashStore.for_root(ws))
|
|
490
|
+
with contextlib.suppress(OSError):
|
|
491
|
+
for child in ws.iterdir():
|
|
492
|
+
if child.is_dir() and not child.name.startswith(".") and _dev(child) != _dev(ws):
|
|
493
|
+
_add(TrashStore.for_root(child))
|
|
494
|
+
for r in extra_roots:
|
|
495
|
+
_add(TrashStore.for_root(r))
|
|
496
|
+
return out
|
|
497
|
+
|
|
498
|
+
def entries(self, workspace: Path | str | None, **kw: Any) -> list[TrashEntry]:
|
|
499
|
+
items: list[TrashEntry] = []
|
|
500
|
+
for s in self.stores_for(workspace, **kw):
|
|
501
|
+
items.extend(s.entries())
|
|
502
|
+
items.sort(key=lambda e: e.deleted_at, reverse=True)
|
|
503
|
+
return items
|
|
504
|
+
|
|
505
|
+
def find(self, entry_id: str, workspace: Path | str | None) -> TrashEntry | None:
|
|
506
|
+
return next((e for e in self.entries(workspace) if e.id == entry_id), None)
|
|
507
|
+
|
|
508
|
+
def restore(self, entry: TrashEntry, *, to: Path | str | None = None) -> Path:
|
|
509
|
+
"""Restaura *entry* para o caminho original (ou *to*)."""
|
|
510
|
+
assert entry.store is not None
|
|
511
|
+
return TrashStore(entry.store).restore(entry.id, to=to)
|
|
512
|
+
|
|
513
|
+
def purge(self, entry: TrashEntry, *, cancel: threading.Event | None = None) -> bool:
|
|
514
|
+
assert entry.store is not None
|
|
515
|
+
return TrashStore(entry.store).purge(entry.id, cancel=cancel)
|
|
516
|
+
|
|
517
|
+
def empty(self, workspace: Path | str | None, *, cancel: threading.Event | None = None,
|
|
518
|
+
progress: Callable[[int, int], None] | None = None) -> int:
|
|
519
|
+
items = self.entries(workspace)
|
|
520
|
+
n = 0
|
|
521
|
+
for i, e in enumerate(items, 1):
|
|
522
|
+
if cancel is not None and cancel.is_set():
|
|
523
|
+
break
|
|
524
|
+
if self.purge(e, cancel=cancel):
|
|
525
|
+
n += 1
|
|
526
|
+
if progress:
|
|
527
|
+
progress(i, len(items))
|
|
528
|
+
return n
|
|
529
|
+
|
|
530
|
+
def total_count(self, workspace: Path | str | None) -> int:
|
|
531
|
+
return len(self.entries(workspace))
|
src/ui/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Paineis de interface do usuário (UI) do Codis."""
|