unbabelizer 1.0.0__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.
- unbabelizer/__init__.py +0 -0
- unbabelizer/__main__.py +4 -0
- unbabelizer/app.py +292 -0
- unbabelizer/cli.py +32 -0
- unbabelizer/config.py +141 -0
- unbabelizer/log.py +35 -0
- unbabelizer/modals/__init__.py +0 -0
- unbabelizer/modals/confirm_inevitable.py +72 -0
- unbabelizer/modals/po_edit_sc.py +180 -0
- unbabelizer/modals/po_review_sc.py +264 -0
- unbabelizer/modals/po_translation_sc.py +198 -0
- unbabelizer/types.py +88 -0
- unbabelizer/utils.py +198 -0
- unbabelizer-1.0.0.dist-info/METADATA +149 -0
- unbabelizer-1.0.0.dist-info/RECORD +19 -0
- unbabelizer-1.0.0.dist-info/WHEEL +5 -0
- unbabelizer-1.0.0.dist-info/entry_points.txt +2 -0
- unbabelizer-1.0.0.dist-info/licenses/LICENSE +21 -0
- unbabelizer-1.0.0.dist-info/top_level.txt +1 -0
unbabelizer/__init__.py
ADDED
|
File without changes
|
unbabelizer/__main__.py
ADDED
unbabelizer/app.py
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
from enum import Enum
|
|
3
|
+
from gettext import gettext as _
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from textual import work
|
|
8
|
+
from textual.app import App, ComposeResult
|
|
9
|
+
from textual.binding import Binding
|
|
10
|
+
from textual.containers import Container
|
|
11
|
+
from textual.widgets import Footer, Header, ProgressBar, Select, SelectionList, Static
|
|
12
|
+
|
|
13
|
+
from .config import Config
|
|
14
|
+
from .log import Logger
|
|
15
|
+
from .modals.confirm_inevitable import ConfirmInevitable
|
|
16
|
+
from .modals.po_review_sc import POReviewScreen
|
|
17
|
+
from .modals.po_translation_sc import Translator
|
|
18
|
+
from .types import SubCommand
|
|
19
|
+
from .utils import NotifyException, apply_styles, run_babel_cmd, wait_for_element
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class AppSubCommand(Enum):
|
|
23
|
+
EXTRACT_UPDATE = SubCommand("extract_update", _("Extract and Update"), False, True)
|
|
24
|
+
TRANSLATE = SubCommand("translate", _("Translate"), True, False)
|
|
25
|
+
REVIEW = SubCommand("review", _("Review"), True, True)
|
|
26
|
+
COMPILE = SubCommand("compile", _("Compile"), False, True)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class UnbabelizerApp(App[None]):
|
|
30
|
+
"""The main application class for unbabelizer."""
|
|
31
|
+
|
|
32
|
+
BINDINGS = [
|
|
33
|
+
Binding(key="r", action="run_workflow", description=_("Run Workflow"), show=True),
|
|
34
|
+
Binding(key="q", action="quit", description=_("Quit"), show=True),
|
|
35
|
+
Binding(key="c", action="clear", description=_("Clear translation files"), show=True),
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
def __init__(self, config: Config):
|
|
39
|
+
"""Initialize the unbabelizerApp with the given configuration.
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
config (Config): The configuration for the application.
|
|
43
|
+
"""
|
|
44
|
+
super().__init__()
|
|
45
|
+
self._app_logger = Logger()
|
|
46
|
+
self._config = config
|
|
47
|
+
self._config.locale_dir.mkdir(parents=True, exist_ok=True)
|
|
48
|
+
self._lock = asyncio.Lock()
|
|
49
|
+
self._current_lang_idx = 0
|
|
50
|
+
self.logger.debug(
|
|
51
|
+
"unbabelizerApp initialized with config:", extra={"config": self._config, "context": "unbabelizerApp.init"}
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def logger(self) -> Logger:
|
|
56
|
+
"""Return the application logger."""
|
|
57
|
+
return self._app_logger
|
|
58
|
+
|
|
59
|
+
@property
|
|
60
|
+
def potfile_path(self) -> Path:
|
|
61
|
+
"""Path to the .pot file."""
|
|
62
|
+
return self._config.locale_dir / "base.pot"
|
|
63
|
+
|
|
64
|
+
@property
|
|
65
|
+
def pofile_path(self) -> Path:
|
|
66
|
+
"""Path to the .po file for the target language."""
|
|
67
|
+
return (
|
|
68
|
+
self._config.locale_dir
|
|
69
|
+
/ self._config.dest_lang[self._current_lang_idx]
|
|
70
|
+
/ "LC_MESSAGES"
|
|
71
|
+
/ f"{self._config.domain}.po"
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
def compose(self) -> ComposeResult:
|
|
75
|
+
"""Compose the UI elements for the main application."""
|
|
76
|
+
yield Header()
|
|
77
|
+
yield apply_styles(
|
|
78
|
+
Container(
|
|
79
|
+
Static(_("Target language")),
|
|
80
|
+
Select(
|
|
81
|
+
[(l, l) for l in self._config.dest_lang],
|
|
82
|
+
prompt=_("Select target language"),
|
|
83
|
+
value=self._config.dest_lang[self._current_lang_idx],
|
|
84
|
+
),
|
|
85
|
+
Static(_("Translation Workflow")),
|
|
86
|
+
SelectionList(
|
|
87
|
+
AppSubCommand.EXTRACT_UPDATE.value.selection_list_item,
|
|
88
|
+
AppSubCommand.TRANSLATE.value.selection_list_item,
|
|
89
|
+
AppSubCommand.REVIEW.value.selection_list_item,
|
|
90
|
+
AppSubCommand.COMPILE.value.selection_list_item,
|
|
91
|
+
),
|
|
92
|
+
apply_styles(
|
|
93
|
+
ProgressBar(total=100, show_eta=True, show_percentage=True),
|
|
94
|
+
vertical="bottom",
|
|
95
|
+
width="1fr",
|
|
96
|
+
height="1fr",
|
|
97
|
+
),
|
|
98
|
+
),
|
|
99
|
+
vertical="top",
|
|
100
|
+
width="1fr",
|
|
101
|
+
height="1fr",
|
|
102
|
+
)
|
|
103
|
+
yield Footer()
|
|
104
|
+
|
|
105
|
+
async def on_mount(self):
|
|
106
|
+
"""Handle the mount event for the application."""
|
|
107
|
+
(await wait_for_element(self.query_one, selector=SelectionList)).focus()
|
|
108
|
+
|
|
109
|
+
async def on_select_changed(self, message: Select.Changed):
|
|
110
|
+
"""Handle changes to the target language selection."""
|
|
111
|
+
if message.value not in self._config.dest_lang:
|
|
112
|
+
self.logger.warning(
|
|
113
|
+
"Selected language not in configured destination languages",
|
|
114
|
+
extra={"selected_language": message.value, "context": "unbabelizerApp.on_select_changed"},
|
|
115
|
+
)
|
|
116
|
+
return
|
|
117
|
+
|
|
118
|
+
self._current_lang_idx = self._config.dest_lang.index(f"{message.value}")
|
|
119
|
+
self.logger.info(
|
|
120
|
+
"Target language changed",
|
|
121
|
+
extra={
|
|
122
|
+
"new_language": self._config.dest_lang[self._current_lang_idx],
|
|
123
|
+
"context": "unbabelizerApp.on_select_changed",
|
|
124
|
+
},
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
async def action_clear(self):
|
|
128
|
+
"""Clear all .po and .mo files in the locale directory."""
|
|
129
|
+
|
|
130
|
+
def callback(result: Any):
|
|
131
|
+
if result is not True:
|
|
132
|
+
return
|
|
133
|
+
|
|
134
|
+
self.logger.info("Clearing translation files...", extra={"context": "unbabelizerApp.clear"})
|
|
135
|
+
with NotifyException(self):
|
|
136
|
+
for path in self._config.locale_dir.rglob("*"):
|
|
137
|
+
if path.is_file():
|
|
138
|
+
self.logger.debug("Removing file", extra={"path": path, "context": "unbabelizerApp.clear"})
|
|
139
|
+
path.unlink()
|
|
140
|
+
|
|
141
|
+
for path in self._config.locale_dir.rglob("*"):
|
|
142
|
+
if path.is_dir() and not any(path.iterdir()):
|
|
143
|
+
self.logger.debug(
|
|
144
|
+
"Removing empty directory", extra={"path": path, "context": "unbabelizerApp.clear"}
|
|
145
|
+
)
|
|
146
|
+
path.rmdir()
|
|
147
|
+
|
|
148
|
+
self.notify(_("All translation files cleared."), timeout=3, title=_("✅ Success"))
|
|
149
|
+
self.logger.info("Translation files cleared.", extra={"context": "unbabelizerApp.clear"})
|
|
150
|
+
|
|
151
|
+
await self.push_screen(ConfirmInevitable(), callback=callback)
|
|
152
|
+
|
|
153
|
+
async def action_run_workflow(self):
|
|
154
|
+
"""Run the selected workflow actions."""
|
|
155
|
+
self.logger.info("Running workflow actions...", extra={"context": "unbabelizerApp.run_workflow"})
|
|
156
|
+
selection_list = await wait_for_element(self.query_one, selector=SelectionList)
|
|
157
|
+
selections = [f"{option}" for option in selection_list.selected]
|
|
158
|
+
self.logger.debug(
|
|
159
|
+
"Selected actions:", extra={"selections": selections, "context": "unbabelizerApp.run_workflow"}
|
|
160
|
+
)
|
|
161
|
+
progress_bar = await wait_for_element(self.query_one, selector=ProgressBar)
|
|
162
|
+
progress_bar.update(total=100, progress=0)
|
|
163
|
+
actions = {
|
|
164
|
+
AppSubCommand.EXTRACT_UPDATE.value.name: self.flow_extract_and_update,
|
|
165
|
+
AppSubCommand.TRANSLATE.value.name: self.flow_translate_pofile,
|
|
166
|
+
AppSubCommand.REVIEW.value.name: self.flow_review_pofile,
|
|
167
|
+
AppSubCommand.COMPILE.value.name: self.flow_compile_translations,
|
|
168
|
+
}
|
|
169
|
+
for action in actions:
|
|
170
|
+
if action in selections:
|
|
171
|
+
self.logger.info(f"Starting action: {action}", extra={"context": "unbabelizerApp.run_workflow"})
|
|
172
|
+
actions[action]()
|
|
173
|
+
progress_bar.advance(100 // (len(selections) or 1))
|
|
174
|
+
|
|
175
|
+
progress_bar.update(total=100, progress=100)
|
|
176
|
+
|
|
177
|
+
async def action_quit(self):
|
|
178
|
+
"""Quit the application."""
|
|
179
|
+
self.logger.info("Quitting application...", extra={"context": "unbabelizerApp.quit"})
|
|
180
|
+
self.exit()
|
|
181
|
+
|
|
182
|
+
@work(group="main")
|
|
183
|
+
async def flow_extract_and_update(self):
|
|
184
|
+
"""Extract messages and update or initiate .po files."""
|
|
185
|
+
self.logger.info(
|
|
186
|
+
"Extracting and updating translations...", extra={"context": "unbabelizerApp.flow_extract_and_update"}
|
|
187
|
+
)
|
|
188
|
+
await self._lock.acquire()
|
|
189
|
+
|
|
190
|
+
# Extraction (overwrite existing .pot file)
|
|
191
|
+
mapping_file = self._config.locale_dir / "babel_mapping.txt"
|
|
192
|
+
self.logger.debug(
|
|
193
|
+
"Creating temporary Babel mapping file",
|
|
194
|
+
extra={"path": mapping_file, "context": "unbabelizerApp.flow_extract_and_update"},
|
|
195
|
+
)
|
|
196
|
+
mapping_file.touch()
|
|
197
|
+
mapping_file.write_text(self._config.mapping_file.strip() + "\n")
|
|
198
|
+
self.logger.debug(
|
|
199
|
+
"Babel mapping file content:",
|
|
200
|
+
extra={"content": mapping_file.read_text(), "context": "unbabelizerApp.flow_extract_and_update"},
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
self.logger.debug(
|
|
204
|
+
"Running Babel extract command",
|
|
205
|
+
extra={"context": "unbabelizerApp.flow_extract_and_update"},
|
|
206
|
+
)
|
|
207
|
+
run_babel_cmd(
|
|
208
|
+
["extract"]
|
|
209
|
+
+ ["--project", self._config.title]
|
|
210
|
+
+ ["--version", self._config.version]
|
|
211
|
+
+ ["--copyright-holder", self._config.author]
|
|
212
|
+
+ ["--last-translator", self._config.email]
|
|
213
|
+
+ ["--no-location"]
|
|
214
|
+
+ ["--sort-output"]
|
|
215
|
+
+ ["-F", str(mapping_file.resolve())]
|
|
216
|
+
+ ["-o", str(self.potfile_path)]
|
|
217
|
+
+ ["--ignore-dirs", *(ex for ex in self._config.exclude_patterns)]
|
|
218
|
+
+ ["--input-paths", *(str(i.resolve()) for i in self._config.input_paths)]
|
|
219
|
+
)
|
|
220
|
+
mapping_file.unlink()
|
|
221
|
+
|
|
222
|
+
if self.pofile_path.exists():
|
|
223
|
+
self.logger.debug(
|
|
224
|
+
"Updating existing .po file",
|
|
225
|
+
extra={"path": self.pofile_path, "context": "unbabelizerApp.flow_extract_and_update"},
|
|
226
|
+
)
|
|
227
|
+
# Update existing .po file
|
|
228
|
+
run_babel_cmd(
|
|
229
|
+
["update"]
|
|
230
|
+
+ ["-D", self._config.domain]
|
|
231
|
+
+ ["-i", str(self.potfile_path)]
|
|
232
|
+
+ ["-d", str(self._config.locale_dir)]
|
|
233
|
+
+ ["-l", self._config.dest_lang[self._current_lang_idx]]
|
|
234
|
+
+ ["-w", str(self._config.line_width)]
|
|
235
|
+
+ ["--init-missing"]
|
|
236
|
+
)
|
|
237
|
+
else:
|
|
238
|
+
self.logger.debug(
|
|
239
|
+
"Creating new .po file",
|
|
240
|
+
extra={"path": self.pofile_path, "context": "unbabelizerApp.flow_extract_and_update"},
|
|
241
|
+
)
|
|
242
|
+
# Initialize new .po file
|
|
243
|
+
run_babel_cmd(
|
|
244
|
+
["init"]
|
|
245
|
+
+ ["-i", str(self.potfile_path)]
|
|
246
|
+
+ ["-d", str(self._config.locale_dir)]
|
|
247
|
+
+ ["-l", self._config.dest_lang[self._current_lang_idx]]
|
|
248
|
+
+ ["-w", str(self._config.line_width)]
|
|
249
|
+
+ ["-D", self._config.domain]
|
|
250
|
+
)
|
|
251
|
+
self.logger.info(
|
|
252
|
+
"Extraction and update completed.",
|
|
253
|
+
extra={
|
|
254
|
+
"pot_path": self.potfile_path,
|
|
255
|
+
"po_path": self.pofile_path,
|
|
256
|
+
"context": "unbabelizerApp.flow_extract_and_update",
|
|
257
|
+
},
|
|
258
|
+
)
|
|
259
|
+
self._lock.release()
|
|
260
|
+
self.notify(_("Extraction and update completed."), timeout=3, title=_("✅ Success"))
|
|
261
|
+
|
|
262
|
+
@work(group="main")
|
|
263
|
+
async def flow_compile_translations(self):
|
|
264
|
+
"""Compile .po files into .mo files."""
|
|
265
|
+
self.logger.info("Compiling translations...", extra={"context": "unbabelizerApp.flow_compile_translations"})
|
|
266
|
+
await self._lock.acquire()
|
|
267
|
+
run_babel_cmd(["compile"] + ["-D", self._config.domain] + ["-d", str(self._config.locale_dir)])
|
|
268
|
+
self._lock.release()
|
|
269
|
+
self.logger.info("Compilation completed.", extra={"context": "unbabelizerApp.flow_compile_translations"})
|
|
270
|
+
self.notify(_("Compilation completed."), timeout=3, title=_("✅ Success"))
|
|
271
|
+
|
|
272
|
+
@work(group="main")
|
|
273
|
+
async def flow_translate_pofile(self):
|
|
274
|
+
"""Translate the .po file using Google Translate."""
|
|
275
|
+
self.logger.info("Pushing translation screen", extra={"context": "unbabelizerApp.flow_translate_po"})
|
|
276
|
+
await self._lock.acquire()
|
|
277
|
+
await self.push_screen(
|
|
278
|
+
Translator(self.pofile_path, self._config.src_lang, self._config.dest_lang[self._current_lang_idx]),
|
|
279
|
+
callback=lambda _: self._lock.release(),
|
|
280
|
+
)
|
|
281
|
+
self.logger.info("Translation screen pushed", extra={"context": "unbabelizerApp.flow_translate_po"})
|
|
282
|
+
|
|
283
|
+
@work(group="main")
|
|
284
|
+
async def flow_review_pofile(self):
|
|
285
|
+
"""Review and edit the .po file."""
|
|
286
|
+
self.logger.info("Pushing PO review screen", extra={"context": "unbabelizerApp.flow_review_po"})
|
|
287
|
+
await self._lock.acquire()
|
|
288
|
+
await self.push_screen(
|
|
289
|
+
POReviewScreen(self.pofile_path),
|
|
290
|
+
callback=lambda _: self._lock.release(),
|
|
291
|
+
)
|
|
292
|
+
self.logger.info("PO review screen dismissed", extra={"context": "unbabelizerApp.flow_review_po"})
|
unbabelizer/cli.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import gettext
|
|
2
|
+
import sys
|
|
3
|
+
import traceback
|
|
4
|
+
from gettext import gettext as _
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
gettext.bindtextdomain(
|
|
8
|
+
"messages",
|
|
9
|
+
(Path(__file__).parent / "locales").resolve(),
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
from .app import UnbabelizerApp
|
|
14
|
+
from .config import Config, logger
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def main(args: list[str] | None = None):
|
|
18
|
+
"""Entry point for the unbabelizer CLI application."""
|
|
19
|
+
try:
|
|
20
|
+
config = Config.build(args)
|
|
21
|
+
logger.info("Running unbabelizerApp with config:", extra={"context": "cli.main", "config": config})
|
|
22
|
+
app = UnbabelizerApp(config)
|
|
23
|
+
logger.info("Starting unbabelizerApp...")
|
|
24
|
+
app.run()
|
|
25
|
+
logger.info("unbabelizerApp has terminated gracefully.")
|
|
26
|
+
except Exception as e:
|
|
27
|
+
logger.error(
|
|
28
|
+
"An unhandled exception occurred: %s",
|
|
29
|
+
str(e),
|
|
30
|
+
extra={"context": "cli.main", "trace": traceback.format_exc()},
|
|
31
|
+
)
|
|
32
|
+
sys.exit(1)
|
unbabelizer/config.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import sys
|
|
3
|
+
import tomllib
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any, Dict, List
|
|
6
|
+
|
|
7
|
+
import jmespath
|
|
8
|
+
from pydantic import BaseModel, Field
|
|
9
|
+
|
|
10
|
+
from .log import Logger
|
|
11
|
+
|
|
12
|
+
logger = Logger()
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Config(BaseModel):
|
|
16
|
+
"""unbabelizer loads configuration from pyproject.toml and command line arguments."""
|
|
17
|
+
|
|
18
|
+
author: str = Field(
|
|
19
|
+
description="Author of the project",
|
|
20
|
+
json_schema_extra={"pyproject.toml": "project.authors[0].name"},
|
|
21
|
+
)
|
|
22
|
+
email: str = Field(
|
|
23
|
+
description="Email of the author",
|
|
24
|
+
json_schema_extra={"pyproject.toml": "project.authors[0].email"},
|
|
25
|
+
)
|
|
26
|
+
version: str = Field(
|
|
27
|
+
description="Version of the project",
|
|
28
|
+
json_schema_extra={"pyproject.toml": "project.version"},
|
|
29
|
+
)
|
|
30
|
+
title: str = Field(description="Title of the project", json_schema_extra={"pyproject.toml": "project.name"})
|
|
31
|
+
locale_dir: Path = Field(
|
|
32
|
+
default=Path("locale"),
|
|
33
|
+
description="Directory for locale files",
|
|
34
|
+
json_schema_extra={"pyproject.toml": "tool.unbabelizer.locale_dir"},
|
|
35
|
+
)
|
|
36
|
+
input_paths: List[Path] = Field(
|
|
37
|
+
default=[Path.cwd()],
|
|
38
|
+
description="Paths to search for source files",
|
|
39
|
+
json_schema_extra={"pyproject.toml": "tool.unbabelizer.input_paths"},
|
|
40
|
+
)
|
|
41
|
+
exclude_patterns: List[str] = Field(
|
|
42
|
+
default=[],
|
|
43
|
+
description="Paths to exclude from searching",
|
|
44
|
+
json_schema_extra={"pyproject.toml": "tool.unbabelizer.exclude_patterns"},
|
|
45
|
+
)
|
|
46
|
+
src_lang: str = Field(
|
|
47
|
+
default="en",
|
|
48
|
+
description="Source language code",
|
|
49
|
+
json_schema_extra={"pyproject.toml": "tool.unbabelizer.src_lang"},
|
|
50
|
+
)
|
|
51
|
+
dest_lang: List[str] = Field(
|
|
52
|
+
description="Destination language code",
|
|
53
|
+
json_schema_extra={"pyproject.toml": "tool.unbabelizer.dest_lang"},
|
|
54
|
+
)
|
|
55
|
+
domain: str = Field(
|
|
56
|
+
default="messages",
|
|
57
|
+
description="Domain for the .po files",
|
|
58
|
+
json_schema_extra={"pyproject.toml": "tool.unbabelizer.domain"},
|
|
59
|
+
)
|
|
60
|
+
mapping_file: str = Field(
|
|
61
|
+
default="[python: **.py]\nencoding = utf-8\n",
|
|
62
|
+
description="Content of the Babel mapping file",
|
|
63
|
+
json_schema_extra={"pyproject.toml": "tool.unbabelizer.mapping_file_content"},
|
|
64
|
+
)
|
|
65
|
+
line_width: int = Field(
|
|
66
|
+
default=120,
|
|
67
|
+
description="Line width for .po files",
|
|
68
|
+
json_schema_extra={"pyproject.toml": "tool.unbabelizer.line_width"},
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
@classmethod
|
|
72
|
+
def source_cli_args(cls, args: List[str]) -> Dict[str, Any]:
|
|
73
|
+
"""Parse command line arguments to create a Config instance."""
|
|
74
|
+
parser = argparse.ArgumentParser(description="unbabelizer configuration")
|
|
75
|
+
for name, field in cls.model_fields.items():
|
|
76
|
+
description = field.description or ""
|
|
77
|
+
flag = f"--{name.replace('_', '-')}"
|
|
78
|
+
match name:
|
|
79
|
+
case "input_paths" | "exclude_patterns" | "dest_lang":
|
|
80
|
+
parser.add_argument(flag, type=str, nargs="+", help=description, default=None)
|
|
81
|
+
case "locale_dir":
|
|
82
|
+
parser.add_argument(flag, type=Path, help=description, default=None)
|
|
83
|
+
case "line_width":
|
|
84
|
+
parser.add_argument(flag, type=int, help=description, default=None)
|
|
85
|
+
case "mapping_file_content":
|
|
86
|
+
parser.add_argument(flag, type=argparse.FileType("r"), help=description, default=None)
|
|
87
|
+
case _:
|
|
88
|
+
parser.add_argument(flag, type=str, help=description, default=None)
|
|
89
|
+
parsed_args = parser.parse_args(args)
|
|
90
|
+
field_values = {k: v for k, v in vars(parsed_args).items() if v is not None}
|
|
91
|
+
logger.debug("Parsed CLI args", extra={"context": "Config.source_cli_args", "data": field_values})
|
|
92
|
+
return field_values
|
|
93
|
+
|
|
94
|
+
@classmethod
|
|
95
|
+
def source_pyproject_toml(cls, file_path: Path) -> Dict[str, Any]:
|
|
96
|
+
"""Load configuration from pyproject.toml using jmespath."""
|
|
97
|
+
if not file_path.exists() or not file_path.is_file():
|
|
98
|
+
return {}
|
|
99
|
+
|
|
100
|
+
pyproject_data = tomllib.loads(file_path.read_text())
|
|
101
|
+
logger.debug(
|
|
102
|
+
"Loaded pyproject.toml data:", extra={"context": "Config.source_pyproject_toml", "data": pyproject_data}
|
|
103
|
+
)
|
|
104
|
+
field_values: Dict[str, Any] = {}
|
|
105
|
+
for name, field in cls.model_fields.items():
|
|
106
|
+
schema = ( # pyright: ignore[reportUnknownVariableType]
|
|
107
|
+
field.json_schema_extra # pyright: ignore[reportUnknownMemberType]
|
|
108
|
+
if isinstance(field.json_schema_extra, dict)
|
|
109
|
+
else {}
|
|
110
|
+
)
|
|
111
|
+
jmespath_query = schema.get( # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType]
|
|
112
|
+
"pyproject.toml", name
|
|
113
|
+
)
|
|
114
|
+
value = jmespath.search( # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType]
|
|
115
|
+
jmespath_query, pyproject_data
|
|
116
|
+
)
|
|
117
|
+
logger.debug(
|
|
118
|
+
"JMESPath query result",
|
|
119
|
+
extra={ # pyright: ignore[reportUnknownArgumentType]
|
|
120
|
+
"context": "Config.source_pyproject_toml",
|
|
121
|
+
"field": name,
|
|
122
|
+
"query": jmespath_query,
|
|
123
|
+
"value": value,
|
|
124
|
+
},
|
|
125
|
+
)
|
|
126
|
+
field_values[name] = value
|
|
127
|
+
|
|
128
|
+
field_values = {k: v for k, v in field_values.items() if v is not None}
|
|
129
|
+
logger.debug(
|
|
130
|
+
"Extracted config data from pyproject.toml",
|
|
131
|
+
extra={"context": "Config.source_pyproject_toml", "data": field_values},
|
|
132
|
+
)
|
|
133
|
+
return field_values
|
|
134
|
+
|
|
135
|
+
@classmethod
|
|
136
|
+
def build(cls, args: List[str] | None) -> "Config":
|
|
137
|
+
"""Validate and create a Config instance from source data."""
|
|
138
|
+
config_data = cls.source_pyproject_toml(Path("pyproject.toml"))
|
|
139
|
+
config_data.update(cls.source_cli_args(args or sys.argv[1:]))
|
|
140
|
+
logger.info("Validated config data", extra={"context": "Config.build", "data": config_data})
|
|
141
|
+
return cls.model_validate(config_data)
|
unbabelizer/log.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import logging.handlers
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from .types import SingletonType
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Logger(logging.LoggerAdapter[Any], metaclass=SingletonType):
|
|
10
|
+
"""A singleton logger class for the application."""
|
|
11
|
+
|
|
12
|
+
def __init__(self, log_name: str = "unbabelizer", log_level: int = logging.DEBUG):
|
|
13
|
+
logger = logging.getLogger(log_name)
|
|
14
|
+
logger.setLevel(log_level)
|
|
15
|
+
|
|
16
|
+
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
|
|
17
|
+
|
|
18
|
+
log_dir = Path.home() / ".unbabelizer"
|
|
19
|
+
log_dir.mkdir(parents=True, exist_ok=True)
|
|
20
|
+
|
|
21
|
+
fh = logging.handlers.RotatingFileHandler(
|
|
22
|
+
log_dir / "unbabelizer.log",
|
|
23
|
+
maxBytes=20 * 1024**2, # 20 MB
|
|
24
|
+
backupCount=1,
|
|
25
|
+
)
|
|
26
|
+
fh.setLevel(log_level)
|
|
27
|
+
fh.setFormatter(formatter)
|
|
28
|
+
logger.addHandler(fh)
|
|
29
|
+
|
|
30
|
+
super().__init__(logger)
|
|
31
|
+
|
|
32
|
+
def process(self, msg: str, kwargs: Any):
|
|
33
|
+
if "extra" in kwargs:
|
|
34
|
+
msg = f"{msg} - {str(kwargs['extra'])}"
|
|
35
|
+
return msg, kwargs
|
|
File without changes
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
from gettext import gettext as _
|
|
2
|
+
|
|
3
|
+
from textual.app import ComposeResult
|
|
4
|
+
from textual.binding import Binding
|
|
5
|
+
from textual.containers import Container, Horizontal
|
|
6
|
+
from textual.screen import ModalScreen
|
|
7
|
+
from textual.widgets import Button, Footer, Header, Static
|
|
8
|
+
|
|
9
|
+
from ..log import Logger
|
|
10
|
+
from ..utils import apply_styles, wait_for_element
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class ConfirmInevitable(ModalScreen[bool]):
|
|
14
|
+
"""A simple confirmation dialog modal."""
|
|
15
|
+
|
|
16
|
+
BINDINGS = [
|
|
17
|
+
Binding(key="left", action="focus_ok", description=_("Cancel"), show=False),
|
|
18
|
+
Binding(key="right", action="focus_cancel", description=_("OK"), show=False),
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
@property
|
|
22
|
+
def logger(self) -> Logger:
|
|
23
|
+
"""Return the application logger."""
|
|
24
|
+
return getattr(
|
|
25
|
+
self.app, # pyright: ignore[reportUnknownMemberType, reportUnknownArgumentType]
|
|
26
|
+
"logger",
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
def compose(self) -> ComposeResult:
|
|
30
|
+
"""Compose the modal's layout."""
|
|
31
|
+
yield Header()
|
|
32
|
+
yield apply_styles(
|
|
33
|
+
Container(
|
|
34
|
+
apply_styles(Static(_("Are you sure? This action cannot be undone.")), width="1fr"),
|
|
35
|
+
apply_styles(
|
|
36
|
+
Horizontal(
|
|
37
|
+
Button(_("OK"), id="ok", variant="default"),
|
|
38
|
+
Button(_("Cancel"), id="cancel", variant="primary"),
|
|
39
|
+
),
|
|
40
|
+
width="1fr",
|
|
41
|
+
height="1fr",
|
|
42
|
+
),
|
|
43
|
+
),
|
|
44
|
+
width="1fr",
|
|
45
|
+
height="1fr",
|
|
46
|
+
)
|
|
47
|
+
yield Footer()
|
|
48
|
+
|
|
49
|
+
async def on_mount(self):
|
|
50
|
+
"""Focus the Cancel button when the modal is mounted."""
|
|
51
|
+
(await wait_for_element(self.query_one, selector="#cancel", expect_type=Button)).focus()
|
|
52
|
+
|
|
53
|
+
async def on_button_pressed(self, event: Button.Pressed):
|
|
54
|
+
"""Handle button press events."""
|
|
55
|
+
if event.button.id == "ok":
|
|
56
|
+
self.logger.debug(
|
|
57
|
+
"User confirmed inevitable action.", extra={"context": "ConfirmInevitable.on_button_pressed"}
|
|
58
|
+
)
|
|
59
|
+
self.dismiss(True)
|
|
60
|
+
elif event.button.id == "cancel":
|
|
61
|
+
self.logger.debug(
|
|
62
|
+
"User canceled inevitable action.", extra={"context": "ConfirmInevitable.on_button_pressed"}
|
|
63
|
+
)
|
|
64
|
+
self.dismiss(False)
|
|
65
|
+
|
|
66
|
+
async def action_focus_ok(self):
|
|
67
|
+
"""Focus the OK button."""
|
|
68
|
+
(await wait_for_element(self.query_one, selector="#ok", expect_type=Button)).focus()
|
|
69
|
+
|
|
70
|
+
async def action_focus_cancel(self):
|
|
71
|
+
"""Focus the Cancel button."""
|
|
72
|
+
(await wait_for_element(self.query_one, selector="#cancel", expect_type=Button)).focus()
|