@clipen/clipen-cli 1.0.6 → 1.0.8
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.
- package/README.md +5 -4
- package/apps/web/dist/assets/{index-CaxEZKLc.css → index-CJ80KHsQ.css} +1 -1
- package/apps/web/dist/assets/index-C_4u_hVf.js +16 -0
- package/apps/web/dist/index.html +2 -2
- package/bin/clipen.js +237 -78
- package/package.json +8 -2
- package/pyproject.toml +1 -1
- package/src/clipen/__init__.py +1 -1
- package/src/clipen/analysis/qwen_worker.py +13 -4
- package/src/clipen/analysis/setup.py +26 -1
- package/src/clipen/analysis/setup_cli.py +59 -10
- package/src/clipen/bootstrap.py +411 -176
- package/src/clipen/cli.py +40 -15
- package/src/clipen/controller/app.py +37 -17
- package/src/clipen/controller/server.py +65 -27
- package/src/clipen/editing/agent_repository.py +8 -0
- package/src/clipen/editing/alignment_setup.py +40 -15
- package/src/clipen/editing/change_report.py +17 -0
- package/src/clipen/editing/coordinator.py +6 -0
- package/src/clipen/editing/evidence_jobs.py +3 -1
- package/src/clipen/editing/history_changes.py +56 -27
- package/src/clipen/editing/production_catalog.py +3 -3
- package/src/clipen/editing/production_media.py +18 -0
- package/src/clipen/editing/production_progress.py +46 -3
- package/src/clipen/editing/production_tools.py +3 -1
- package/src/clipen/editing/versions.py +53 -10
- package/src/clipen/finishing/audio.py +59 -45
- package/src/clipen/i18n.py +155 -0
- package/src/clipen/locale_en.py +528 -0
- package/src/clipen/mcp_editing/__main__.py +8 -0
- package/src/clipen/own_python.py +43 -0
- package/src/clipen/projects/models.py +16 -1
- package/src/clipen/projects/picker.py +3 -1
- package/src/clipen/projects/storage.py +17 -1
- package/src/clipen/providers/claude_editing.py +3 -1
- package/src/clipen/providers/codex_editing.py +3 -1
- package/src/clipen/providers/editing_agent.py +36 -1
- package/src/clipen/providers/liveness.py +39 -0
- package/src/clipen/rendering/custom_components.py +104 -2
- package/src/clipen/rendering/custom_render.py +45 -0
- package/src/clipen/skills/builtin/display.en.json +89 -0
- package/src/clipen/skills/builtin/references/graphics.md +1 -2
- package/src/clipen/skills/catalog.py +22 -0
- package/src/clipen/terminal.py +344 -0
- package/src/clipen/workspace.py +97 -28
- package/apps/web/dist/assets/index-C3Zw0WaM.js +0 -14
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
"""Clipen's terminal look, shared by the installer and the running app.
|
|
2
|
+
|
|
3
|
+
Standard library only: the installer draws with it before any dependency exists. It uses the same
|
|
4
|
+
frame, symbols and colours as the npx launcher (@clack/prompts), so setup and launch read as one
|
|
5
|
+
product. Output that is not a terminal (a log, a pipe, a test) gets the same frame without colour or
|
|
6
|
+
animation.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
import re
|
|
13
|
+
import shutil
|
|
14
|
+
import sys
|
|
15
|
+
import threading
|
|
16
|
+
import time
|
|
17
|
+
import unicodedata
|
|
18
|
+
from contextlib import contextmanager
|
|
19
|
+
from typing import Iterator, Sequence, TextIO
|
|
20
|
+
|
|
21
|
+
from clipen.i18n import tr
|
|
22
|
+
|
|
23
|
+
try:
|
|
24
|
+
import termios
|
|
25
|
+
import tty
|
|
26
|
+
except ImportError: # Windows has no POSIX terminal control; prompts fall back to a typed answer.
|
|
27
|
+
termios = tty = None
|
|
28
|
+
|
|
29
|
+
_ANSI = re.compile(r"\033\[[0-9;?]*[A-Za-z]|\033\]8;;.*?\033\\")
|
|
30
|
+
_FRAMES = "◒◐◓◑"
|
|
31
|
+
_LOGO = (
|
|
32
|
+
" ██████╗██╗ ██╗██████╗ ███████╗███╗ ██╗",
|
|
33
|
+
"██╔════╝██║ ██║██╔══██╗██╔════╝████╗ ██║",
|
|
34
|
+
"██║ ██║ ██║██████╔╝█████╗ ██╔██╗ ██║",
|
|
35
|
+
"██║ ██║ ██║██╔═══╝ ██╔══╝ ██║╚██╗██║",
|
|
36
|
+
"╚██████╗███████╗██║██║ ███████╗██║ ╚████║",
|
|
37
|
+
" ╚═════╝╚══════╝╚═╝╚═╝ ╚══════╝╚═╝ ╚═══╝",
|
|
38
|
+
)
|
|
39
|
+
# The brand gold from the README badges, warming to amber down the logo.
|
|
40
|
+
_LOGO_COLOURS = ((246, 211, 122), (240, 198, 100), (233, 180, 76), (226, 160, 62), (218, 140, 52), (208, 120, 44))
|
|
41
|
+
_BRAND = (233, 180, 76)
|
|
42
|
+
# The npx launcher sets this when it has drawn the logo and opened the frame the installer continues.
|
|
43
|
+
FRAME_OPEN = "CLIPEN_FRAME_OPEN"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def display_width(text: str) -> int:
|
|
47
|
+
"""Columns the text takes in a terminal: CJK characters take two, colour codes none."""
|
|
48
|
+
width = 0
|
|
49
|
+
for character in _ANSI.sub("", text):
|
|
50
|
+
if unicodedata.combining(character):
|
|
51
|
+
continue
|
|
52
|
+
width += 2 if unicodedata.east_asian_width(character) in "WF" else 1
|
|
53
|
+
return width
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _clip(text: str, columns: int) -> str:
|
|
57
|
+
"""Cut the text to the given columns, keeping colour codes whole."""
|
|
58
|
+
if display_width(text) <= columns:
|
|
59
|
+
return text
|
|
60
|
+
pieces: list[str] = []
|
|
61
|
+
used = 0
|
|
62
|
+
position = 0
|
|
63
|
+
while position < len(text):
|
|
64
|
+
code = _ANSI.match(text, position)
|
|
65
|
+
if code:
|
|
66
|
+
pieces.append(code.group())
|
|
67
|
+
position = code.end()
|
|
68
|
+
continue
|
|
69
|
+
character = text[position]
|
|
70
|
+
width = 2 if unicodedata.east_asian_width(character) in "WF" else 1
|
|
71
|
+
if used + width > columns - 1:
|
|
72
|
+
pieces.append("…\033[0m" if "\033[" in text else "…")
|
|
73
|
+
break
|
|
74
|
+
pieces.append(character)
|
|
75
|
+
used += width
|
|
76
|
+
position += 1
|
|
77
|
+
return "".join(pieces)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _wrap(text: str, columns: int) -> list[str]:
|
|
81
|
+
"""Break a plain line so each piece fits the columns."""
|
|
82
|
+
lines: list[str] = []
|
|
83
|
+
current = ""
|
|
84
|
+
for character in text:
|
|
85
|
+
if current and display_width(current + character) > columns:
|
|
86
|
+
lines.append(current)
|
|
87
|
+
current = character.lstrip() if character == " " else character
|
|
88
|
+
else:
|
|
89
|
+
current += character
|
|
90
|
+
return [*lines, current]
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _is_terminal(stream: TextIO) -> bool:
|
|
94
|
+
try:
|
|
95
|
+
return stream.isatty()
|
|
96
|
+
except (AttributeError, ValueError):
|
|
97
|
+
return False
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class Terminal:
|
|
101
|
+
def __init__(self, stream: TextIO | None = None) -> None:
|
|
102
|
+
self.stream = stream if stream is not None else sys.stdout
|
|
103
|
+
self.live = _is_terminal(self.stream)
|
|
104
|
+
self.colour = bool(os.environ.get("FORCE_COLOR")) or (self.live and "NO_COLOR" not in os.environ)
|
|
105
|
+
|
|
106
|
+
# Colours ---------------------------------------------------------------------------------
|
|
107
|
+
|
|
108
|
+
def paint(self, code: str, text: str) -> str:
|
|
109
|
+
return f"\033[{code}m{text}\033[0m" if self.colour else text
|
|
110
|
+
|
|
111
|
+
def rgb(self, colour: tuple[int, int, int], text: str) -> str:
|
|
112
|
+
return self.paint("38;2;{};{};{}".format(*colour), text)
|
|
113
|
+
|
|
114
|
+
def brand(self, text: str) -> str:
|
|
115
|
+
return self.rgb(_BRAND, text)
|
|
116
|
+
|
|
117
|
+
def bold(self, text: str) -> str:
|
|
118
|
+
return self.paint("1", text)
|
|
119
|
+
|
|
120
|
+
def dim(self, text: str) -> str:
|
|
121
|
+
return self.paint("2", text)
|
|
122
|
+
|
|
123
|
+
def link(self, url: str) -> str:
|
|
124
|
+
"""A URL the terminal can open with a click."""
|
|
125
|
+
shown = self.paint("4;36", url)
|
|
126
|
+
return f"\033]8;;{url}\033\\{shown}\033]8;;\033\\" if self.live else shown
|
|
127
|
+
|
|
128
|
+
def columns(self) -> int:
|
|
129
|
+
return shutil.get_terminal_size((80, 24)).columns if self.live else 100
|
|
130
|
+
|
|
131
|
+
# Output ----------------------------------------------------------------------------------
|
|
132
|
+
|
|
133
|
+
def write(self, line: str = "") -> None:
|
|
134
|
+
self.stream.write(f"{line}\n")
|
|
135
|
+
self.stream.flush()
|
|
136
|
+
|
|
137
|
+
def _bar(self) -> str:
|
|
138
|
+
return self.paint("90", "│")
|
|
139
|
+
|
|
140
|
+
def _item(self, symbol: str, message: str) -> None:
|
|
141
|
+
first, *rest = message.split("\n")
|
|
142
|
+
self.write(self._bar())
|
|
143
|
+
self.write(f"{symbol} {first}")
|
|
144
|
+
for line in rest:
|
|
145
|
+
self.write(f"{self._bar()} {line}")
|
|
146
|
+
|
|
147
|
+
def logo(self, subtitle: str = "") -> None:
|
|
148
|
+
"""The CLIPEN wordmark, or a compact badge where it would not fit."""
|
|
149
|
+
if self.colour and self.columns() >= 50:
|
|
150
|
+
self.write()
|
|
151
|
+
for line, colour in zip(_LOGO, _LOGO_COLOURS):
|
|
152
|
+
self.write(f" {self.rgb(colour, line)}")
|
|
153
|
+
if subtitle:
|
|
154
|
+
self.write(f" {self.dim(subtitle)}")
|
|
155
|
+
self.write()
|
|
156
|
+
else:
|
|
157
|
+
self.write(f"Clipen {subtitle}".rstrip())
|
|
158
|
+
|
|
159
|
+
def intro(self, title: str) -> None:
|
|
160
|
+
self.write(f"{self.paint('90', '┌')} {self.paint('30;48;2;233;180;76', f' {title} ')}")
|
|
161
|
+
|
|
162
|
+
def outro(self, message: str) -> None:
|
|
163
|
+
self.write(self._bar())
|
|
164
|
+
self.write(f"{self.paint('90', '└')} {message}")
|
|
165
|
+
self.write()
|
|
166
|
+
|
|
167
|
+
def step(self, message: str) -> None:
|
|
168
|
+
self._item(self.paint("32", "◇"), message)
|
|
169
|
+
|
|
170
|
+
def info(self, message: str) -> None:
|
|
171
|
+
self._item(self.paint("34", "●"), message)
|
|
172
|
+
|
|
173
|
+
def warn(self, message: str) -> None:
|
|
174
|
+
self._item(self.paint("33", "▲"), message)
|
|
175
|
+
|
|
176
|
+
def error(self, message: str) -> None:
|
|
177
|
+
self._item(self.paint("31", "■"), message)
|
|
178
|
+
|
|
179
|
+
def note(self, title: str, lines: Sequence[str], footer: Sequence[str] = ()) -> None:
|
|
180
|
+
"""A framed block: what is about to happen, before the person is asked.
|
|
181
|
+
|
|
182
|
+
Footer lines are plain fine print, wrapped to the terminal and dimmed.
|
|
183
|
+
"""
|
|
184
|
+
limit = max(20, self.columns() - 6)
|
|
185
|
+
body = [piece for line in lines for piece in (_wrap(line, limit) if not _ANSI.search(line) else [line])]
|
|
186
|
+
if footer:
|
|
187
|
+
body += ([""] if body else []) + [self.dim(piece) for line in footer for piece in _wrap(line, limit)]
|
|
188
|
+
inner = max([display_width(line) for line in body] + [display_width(title) + 2])
|
|
189
|
+
grey = lambda text: self.paint("90", text) # noqa: E731
|
|
190
|
+
self.write(self._bar())
|
|
191
|
+
self.write(
|
|
192
|
+
f"{self.paint('32', '◇')} {self.bold(title)} {grey('─' * (inner + 1 - display_width(title)) + '╮')}"
|
|
193
|
+
)
|
|
194
|
+
self.write(grey("│") + " " * (inner + 4) + grey("│"))
|
|
195
|
+
for line in body:
|
|
196
|
+
self.write(f"{grey('│')} {line}{' ' * (inner - display_width(line))} {grey('│')}")
|
|
197
|
+
self.write(grey("│") + " " * (inner + 4) + grey("│"))
|
|
198
|
+
self.write(grey("├" + "─" * (inner + 4) + "╯"))
|
|
199
|
+
|
|
200
|
+
# Prompts ---------------------------------------------------------------------------------
|
|
201
|
+
|
|
202
|
+
def confirm(self, message: str, stdin: TextIO, *, default: bool = True) -> bool:
|
|
203
|
+
"""Yes or no; arrow keys in a terminal, a typed y/n anywhere else."""
|
|
204
|
+
if self.live and termios is not None and _is_terminal(stdin):
|
|
205
|
+
try:
|
|
206
|
+
descriptor = stdin.fileno()
|
|
207
|
+
except (AttributeError, OSError, ValueError):
|
|
208
|
+
descriptor = None
|
|
209
|
+
if descriptor is not None:
|
|
210
|
+
return self._confirm_keys(message, descriptor, default)
|
|
211
|
+
hint = "[Y/n]" if default else "[y/N]"
|
|
212
|
+
self.write(self._bar())
|
|
213
|
+
self.stream.write(f"{self.paint('36', '◆')} {message} {self.dim(hint)} ")
|
|
214
|
+
self.stream.flush()
|
|
215
|
+
answer = stdin.readline().strip().lower()
|
|
216
|
+
if not self.live: # A terminal echoes the Enter; anywhere else the next item needs its own line.
|
|
217
|
+
self.write()
|
|
218
|
+
return answer in {"y", "yes"} or (default and answer == "")
|
|
219
|
+
|
|
220
|
+
def _confirm_keys(self, message: str, descriptor: int, value: bool) -> bool:
|
|
221
|
+
def choices() -> str:
|
|
222
|
+
yes = (
|
|
223
|
+
tr(f"{self.paint('32', '●')} 是", f"{self.paint('32', '●')} Yes")
|
|
224
|
+
if value
|
|
225
|
+
else tr(f"{self.dim('○ 是')}", f"{self.dim('○ Yes')}")
|
|
226
|
+
)
|
|
227
|
+
no = (
|
|
228
|
+
tr(f"{self.paint('32', '●')} 否", f"{self.paint('32', '●')} No")
|
|
229
|
+
if not value
|
|
230
|
+
else tr(f"{self.dim('○ 否')}", f"{self.dim('○ No')}")
|
|
231
|
+
)
|
|
232
|
+
return f"{yes} {self.dim('/')} {no}"
|
|
233
|
+
|
|
234
|
+
def draw(first: bool) -> None:
|
|
235
|
+
if not first:
|
|
236
|
+
self.stream.write("\r\033[2A\033[J")
|
|
237
|
+
self.stream.write(
|
|
238
|
+
f"{self.paint('36', '◆')} {message}\n{self.paint('36', '│')} {choices()}\n{self.paint('36', '└')}"
|
|
239
|
+
)
|
|
240
|
+
self.stream.flush()
|
|
241
|
+
|
|
242
|
+
saved = termios.tcgetattr(descriptor)
|
|
243
|
+
self.write(self._bar())
|
|
244
|
+
self.stream.write("\033[?25l")
|
|
245
|
+
submitted = False
|
|
246
|
+
try:
|
|
247
|
+
tty.setcbreak(descriptor)
|
|
248
|
+
draw(True)
|
|
249
|
+
while True:
|
|
250
|
+
key = os.read(descriptor, 8)
|
|
251
|
+
if key in (b"\r", b"\n"):
|
|
252
|
+
break
|
|
253
|
+
if key in (b"y", b"Y", b"n", b"N"):
|
|
254
|
+
value = key in (b"y", b"Y")
|
|
255
|
+
break
|
|
256
|
+
if key in (b"\x1b",):
|
|
257
|
+
value = False
|
|
258
|
+
break
|
|
259
|
+
if key in (b"\x1b[C", b"\x1b[D", b"\x1b[A", b"\x1b[B", b"\t", b" ", b"h", b"l", b"j", b"k"):
|
|
260
|
+
value = not value
|
|
261
|
+
draw(False)
|
|
262
|
+
submitted = True
|
|
263
|
+
finally:
|
|
264
|
+
termios.tcsetattr(descriptor, termios.TCSADRAIN, saved)
|
|
265
|
+
self.stream.write("\r\033[2A\033[J")
|
|
266
|
+
symbol = self.paint("32", "◇") if submitted else self.paint("31", "■")
|
|
267
|
+
answer = (
|
|
268
|
+
tr(("是" if value else "否"), ("Yes" if value else "No")) if submitted else tr("已取消", "Cancelled")
|
|
269
|
+
)
|
|
270
|
+
self.stream.write(f"{symbol} {message}\n{self._bar()} {self.dim(answer)}\n\033[?25h")
|
|
271
|
+
self.stream.flush()
|
|
272
|
+
return value
|
|
273
|
+
|
|
274
|
+
# Progress --------------------------------------------------------------------------------
|
|
275
|
+
|
|
276
|
+
@contextmanager
|
|
277
|
+
def spinner(self, message: str) -> Iterator[Spinner]:
|
|
278
|
+
"""An animated line while work runs, closed with ◇ on success or ■ when it fails."""
|
|
279
|
+
spinner = Spinner(self, message)
|
|
280
|
+
self.write(self._bar())
|
|
281
|
+
spinner.start()
|
|
282
|
+
try:
|
|
283
|
+
yield spinner
|
|
284
|
+
except BaseException:
|
|
285
|
+
spinner.stop()
|
|
286
|
+
self.write(f"{self.paint('31', '■')} {spinner.current}")
|
|
287
|
+
raise
|
|
288
|
+
spinner.stop()
|
|
289
|
+
self.write(f"{self.paint('32', '◇')} {spinner.final or spinner.current}")
|
|
290
|
+
|
|
291
|
+
def progress_bar(self, percent: int, width: int = 24) -> str:
|
|
292
|
+
filled = max(0, min(width, percent * width // 100))
|
|
293
|
+
return self.brand("━" * filled) + self.paint("90", "─" * (width - filled))
|
|
294
|
+
|
|
295
|
+
def overwrite(self, line: str) -> None:
|
|
296
|
+
"""Redraw the current line in place (a live terminal only)."""
|
|
297
|
+
self.stream.write("\r\033[K" + _clip(line, self.columns() - 1))
|
|
298
|
+
self.stream.flush()
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
class Spinner:
|
|
302
|
+
def __init__(self, terminal: Terminal, message: str) -> None:
|
|
303
|
+
self._terminal = terminal
|
|
304
|
+
self.current = message
|
|
305
|
+
self.final: str | None = None
|
|
306
|
+
self._started = time.monotonic()
|
|
307
|
+
self._stopped = threading.Event()
|
|
308
|
+
self._thread: threading.Thread | None = None
|
|
309
|
+
|
|
310
|
+
def update(self, message: str) -> None:
|
|
311
|
+
self.current = message
|
|
312
|
+
|
|
313
|
+
def done(self, message: str) -> None:
|
|
314
|
+
"""What the line says once the work has finished."""
|
|
315
|
+
self.final = message
|
|
316
|
+
|
|
317
|
+
def start(self) -> None:
|
|
318
|
+
if not self._terminal.live:
|
|
319
|
+
return
|
|
320
|
+
self._terminal.stream.write("\033[?25l")
|
|
321
|
+
self._thread = threading.Thread(target=self._spin, name="clipen-spinner", daemon=True)
|
|
322
|
+
self._thread.start()
|
|
323
|
+
|
|
324
|
+
def stop(self) -> None:
|
|
325
|
+
self._stopped.set()
|
|
326
|
+
if self._thread is not None:
|
|
327
|
+
self._thread.join()
|
|
328
|
+
self._terminal.stream.write("\r\033[K\033[?25h")
|
|
329
|
+
self._terminal.stream.flush()
|
|
330
|
+
|
|
331
|
+
def _spin(self) -> None:
|
|
332
|
+
frame = 0
|
|
333
|
+
while True:
|
|
334
|
+
elapsed = int(time.monotonic() - self._started)
|
|
335
|
+
clock = (
|
|
336
|
+
tr(f"{elapsed // 60} 分 {elapsed % 60:02d} 秒", f"{elapsed // 60}m {elapsed % 60:02d}s")
|
|
337
|
+
if elapsed >= 60
|
|
338
|
+
else tr(f"{elapsed} 秒", f"{elapsed}s")
|
|
339
|
+
)
|
|
340
|
+
symbol = self._terminal.paint("35", _FRAMES[frame % len(_FRAMES)])
|
|
341
|
+
self._terminal.overwrite(f"{symbol} {self.current} {self._terminal.dim(clock)}")
|
|
342
|
+
frame += 1
|
|
343
|
+
if self._stopped.wait(0.08):
|
|
344
|
+
return
|
package/src/clipen/workspace.py
CHANGED
|
@@ -12,6 +12,8 @@ from dataclasses import dataclass
|
|
|
12
12
|
from datetime import datetime, timezone
|
|
13
13
|
from pathlib import Path
|
|
14
14
|
|
|
15
|
+
from clipen.i18n import tr
|
|
16
|
+
|
|
15
17
|
from .filesystem import restrict_permissions
|
|
16
18
|
from .projects.storage import PROJECT_SCHEMA_VERSION
|
|
17
19
|
|
|
@@ -72,9 +74,9 @@ def prepare_workspace(current_directory: Path) -> WorkspacePaths:
|
|
|
72
74
|
try:
|
|
73
75
|
root = current_directory.resolve(strict=True)
|
|
74
76
|
except OSError as error:
|
|
75
|
-
raise WorkspaceError("Clipen 無法讀取目前的工作目錄。") from error
|
|
77
|
+
raise WorkspaceError(tr("Clipen 無法讀取目前的工作目錄。", "Clipen cannot read the current folder.")) from error
|
|
76
78
|
if not root.is_dir():
|
|
77
|
-
raise WorkspaceError("目前路徑不是可用的資料夾。")
|
|
79
|
+
raise WorkspaceError(tr("目前路徑不是可用的資料夾。", "The current path is not a usable folder."))
|
|
78
80
|
|
|
79
81
|
managed = root / ".clipen"
|
|
80
82
|
created = not managed.exists()
|
|
@@ -83,32 +85,47 @@ def prepare_workspace(current_directory: Path) -> WorkspacePaths:
|
|
|
83
85
|
except FileExistsError:
|
|
84
86
|
pass
|
|
85
87
|
except OSError as error:
|
|
86
|
-
raise WorkspaceError(
|
|
88
|
+
raise WorkspaceError(
|
|
89
|
+
tr("Clipen 無法在目前目錄建立工作區。", "Clipen cannot set up a workspace in this folder.")
|
|
90
|
+
) from error
|
|
87
91
|
if managed.is_symlink() or not managed.is_dir():
|
|
88
|
-
raise WorkspaceError(
|
|
92
|
+
raise WorkspaceError(
|
|
93
|
+
tr("目前目錄中的 .clipen 不是安全的工作區資料夾。", "The .clipen here is not a safe workspace folder.")
|
|
94
|
+
)
|
|
89
95
|
restrict_permissions(managed, 0o700)
|
|
90
96
|
|
|
91
97
|
manifest = managed / "workspace.json"
|
|
92
98
|
if manifest.exists():
|
|
93
99
|
if manifest.is_symlink() or not manifest.is_file():
|
|
94
|
-
raise WorkspaceError("Clipen 工作區識別檔不安全。")
|
|
100
|
+
raise WorkspaceError(tr("Clipen 工作區識別檔不安全。", "The Clipen workspace ID file is not safe."))
|
|
95
101
|
try:
|
|
96
102
|
value = json.loads(manifest.read_text(encoding="utf-8"))
|
|
97
103
|
except (OSError, UnicodeError, json.JSONDecodeError) as error:
|
|
98
|
-
raise WorkspaceError(
|
|
104
|
+
raise WorkspaceError(
|
|
105
|
+
tr("Clipen 工作區識別檔已損壞。", "The Clipen workspace ID file is damaged.")
|
|
106
|
+
) from error
|
|
99
107
|
if not isinstance(value, dict) or value.get("schema") != _WORKSPACE_SCHEMA:
|
|
100
|
-
raise WorkspaceError(
|
|
108
|
+
raise WorkspaceError(
|
|
109
|
+
tr("這個工作區需要其他版本的 Clipen。", "This workspace needs a different version of Clipen.")
|
|
110
|
+
)
|
|
101
111
|
workspace_id = value.get("workspace_id")
|
|
102
112
|
if not isinstance(workspace_id, str) or re.fullmatch(r"wsp_[0-9a-f]{32}", workspace_id) is None:
|
|
103
|
-
raise WorkspaceError("Clipen 工作區識別檔已損壞。")
|
|
113
|
+
raise WorkspaceError(tr("Clipen 工作區識別檔已損壞。", "The Clipen workspace ID file is damaged."))
|
|
104
114
|
created = False
|
|
105
115
|
else:
|
|
106
116
|
try:
|
|
107
117
|
existing_entries = tuple(managed.iterdir())
|
|
108
118
|
except OSError as error:
|
|
109
|
-
raise WorkspaceError(
|
|
119
|
+
raise WorkspaceError(
|
|
120
|
+
tr("Clipen 無法檢查目前目錄的工作區。", "Clipen cannot check the workspace in this folder.")
|
|
121
|
+
) from error
|
|
110
122
|
if existing_entries:
|
|
111
|
-
raise WorkspaceError(
|
|
123
|
+
raise WorkspaceError(
|
|
124
|
+
tr(
|
|
125
|
+
"目前目錄已有無法識別的 .clipen 資料,Clipen 沒有修改它。",
|
|
126
|
+
"This folder has .clipen data Clipen does not recognise; it was left unchanged.",
|
|
127
|
+
)
|
|
128
|
+
)
|
|
112
129
|
created = True
|
|
113
130
|
workspace_id = "wsp_" + uuid.uuid4().hex
|
|
114
131
|
_atomic_json(
|
|
@@ -123,7 +140,9 @@ def prepare_workspace(current_directory: Path) -> WorkspacePaths:
|
|
|
123
140
|
projects = managed / "projects"
|
|
124
141
|
projects.mkdir(mode=0o700, exist_ok=True)
|
|
125
142
|
if projects.is_symlink() or not projects.is_dir():
|
|
126
|
-
raise WorkspaceError(
|
|
143
|
+
raise WorkspaceError(
|
|
144
|
+
tr("Clipen 工作區中的 projects 不安全。", "The projects folder in this workspace is not safe.")
|
|
145
|
+
)
|
|
127
146
|
restrict_permissions(projects, 0o700)
|
|
128
147
|
|
|
129
148
|
return WorkspacePaths(
|
|
@@ -136,46 +155,96 @@ def prepare_workspace(current_directory: Path) -> WorkspacePaths:
|
|
|
136
155
|
)
|
|
137
156
|
|
|
138
157
|
|
|
158
|
+
def _read_project(database: Path) -> tuple:
|
|
159
|
+
"""The integrity check, schema version and project id, read without changing the project.
|
|
160
|
+
|
|
161
|
+
Read-only first. A read-only connection cannot rebuild the WAL index SQLite keeps beside a
|
|
162
|
+
database, and on some disks (exFAT) a project Clipen closed normally then reads as a disk I/O
|
|
163
|
+
error; a query-only connection lets SQLite rebuild that index and leaves the data untouched."""
|
|
164
|
+
uri = database.resolve(strict=True).as_uri()
|
|
165
|
+
for mode in ("ro", "rw"):
|
|
166
|
+
connection = sqlite3.connect(f"{uri}?mode={mode}", uri=True, timeout=5)
|
|
167
|
+
try:
|
|
168
|
+
connection.execute("PRAGMA query_only = ON")
|
|
169
|
+
return (
|
|
170
|
+
connection.execute("PRAGMA quick_check").fetchone(),
|
|
171
|
+
connection.execute("PRAGMA user_version").fetchone(),
|
|
172
|
+
connection.execute("SELECT project_id FROM project LIMIT 1").fetchone(),
|
|
173
|
+
)
|
|
174
|
+
except sqlite3.OperationalError:
|
|
175
|
+
if mode == "rw":
|
|
176
|
+
raise
|
|
177
|
+
finally:
|
|
178
|
+
connection.close()
|
|
179
|
+
raise AssertionError("unreachable")
|
|
180
|
+
|
|
181
|
+
|
|
139
182
|
def inspect_workspace_projects(workspace: WorkspacePaths) -> WorkspaceInspection:
|
|
140
183
|
"""Verify every managed project before the provider or Controller starts."""
|
|
141
184
|
|
|
142
185
|
try:
|
|
143
186
|
entries = tuple(workspace.projects_root.iterdir())
|
|
144
187
|
except OSError as error:
|
|
145
|
-
raise WorkspaceError(
|
|
188
|
+
raise WorkspaceError(
|
|
189
|
+
tr("Clipen 無法檢查目前目錄的作品。", "Clipen cannot check the projects in this folder.")
|
|
190
|
+
) from error
|
|
146
191
|
|
|
147
192
|
project_count = 0
|
|
148
193
|
for entry in entries:
|
|
149
194
|
if entry.name.startswith("prj_") and _PROJECT_DIRECTORY.fullmatch(entry.name) is None:
|
|
150
|
-
raise WorkspaceError(
|
|
195
|
+
raise WorkspaceError(
|
|
196
|
+
tr(
|
|
197
|
+
f"偵測到無法識別的作品資料夾:{entry.name}。Clipen 沒有修改它。",
|
|
198
|
+
f"Found a project folder Clipen does not recognise: {entry.name}. It was left unchanged.",
|
|
199
|
+
)
|
|
200
|
+
)
|
|
151
201
|
if _PROJECT_DIRECTORY.fullmatch(entry.name) is None:
|
|
152
202
|
continue
|
|
153
203
|
if entry.is_symlink() or not entry.is_dir() or os.path.ismount(entry):
|
|
154
|
-
raise WorkspaceError(
|
|
204
|
+
raise WorkspaceError(
|
|
205
|
+
tr(
|
|
206
|
+
f"作品 {entry.name} 的資料夾不安全,Clipen 沒有修改它。",
|
|
207
|
+
f"The folder of project {entry.name} is not safe; it was left unchanged.",
|
|
208
|
+
)
|
|
209
|
+
)
|
|
155
210
|
database = entry / "project.sqlite3"
|
|
156
211
|
try:
|
|
157
212
|
info = database.lstat()
|
|
158
213
|
except OSError as error:
|
|
159
|
-
raise WorkspaceError(
|
|
214
|
+
raise WorkspaceError(
|
|
215
|
+
tr(f"作品 {entry.name} 缺少可讀取的資料庫。", f"Project {entry.name} has no readable database.")
|
|
216
|
+
) from error
|
|
160
217
|
if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
|
|
161
|
-
raise WorkspaceError(
|
|
218
|
+
raise WorkspaceError(
|
|
219
|
+
tr(
|
|
220
|
+
f"作品 {entry.name} 的資料庫不安全,Clipen 沒有修改它。",
|
|
221
|
+
f"The database of project {entry.name} is not safe; it was left unchanged.",
|
|
222
|
+
)
|
|
223
|
+
)
|
|
162
224
|
|
|
163
225
|
try:
|
|
164
|
-
|
|
165
|
-
connection = sqlite3.connect(uri, uri=True, timeout=5)
|
|
166
|
-
try:
|
|
167
|
-
connection.execute("PRAGMA query_only = ON")
|
|
168
|
-
check = connection.execute("PRAGMA quick_check").fetchone()
|
|
169
|
-
version = connection.execute("PRAGMA user_version").fetchone()
|
|
170
|
-
row = connection.execute("SELECT project_id FROM project LIMIT 1").fetchone()
|
|
171
|
-
finally:
|
|
172
|
-
connection.close()
|
|
226
|
+
check, version, row = _read_project(database)
|
|
173
227
|
except (OSError, sqlite3.Error) as error:
|
|
174
|
-
raise WorkspaceError(
|
|
228
|
+
raise WorkspaceError(
|
|
229
|
+
tr(
|
|
230
|
+
f"作品 {entry.name} 的資料庫已損壞或無法讀取。",
|
|
231
|
+
f"The database of project {entry.name} is damaged or unreadable.",
|
|
232
|
+
)
|
|
233
|
+
) from error
|
|
175
234
|
if check is None or check[0] != "ok" or row is None or row[0] != entry.name:
|
|
176
|
-
raise WorkspaceError(
|
|
235
|
+
raise WorkspaceError(
|
|
236
|
+
tr(
|
|
237
|
+
f"作品 {entry.name} 的資料內容不完整,Clipen 沒有修改它。",
|
|
238
|
+
f"Project {entry.name} is incomplete; it was left unchanged.",
|
|
239
|
+
)
|
|
240
|
+
)
|
|
177
241
|
if version is None or not isinstance(version[0], int) or not 1 <= version[0] <= PROJECT_SCHEMA_VERSION:
|
|
178
|
-
raise WorkspaceError(
|
|
242
|
+
raise WorkspaceError(
|
|
243
|
+
tr(
|
|
244
|
+
f"作品 {entry.name} 需要其他版本的 Clipen。",
|
|
245
|
+
f"Project {entry.name} needs a different version of Clipen.",
|
|
246
|
+
)
|
|
247
|
+
)
|
|
179
248
|
project_count += 1
|
|
180
249
|
|
|
181
250
|
return WorkspaceInspection(project_count)
|