Skip to content

Commit 25588f2

Browse files
authored
refactor(core): core hygiene - remove duplicate validators, inline imports, add zh locale (fixes #696) (#712)
Co-authored-by: chelslava <chelslava@users.noreply.github.com>
1 parent 1da82fa commit 25588f2

12 files changed

Lines changed: 72 additions & 51 deletions

File tree

packages/core/src/rpaforge/bridge/handlers/debugger.py

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -164,13 +164,16 @@ def _handle_get_call_stack(self: Any, _params: dict[str, Any]) -> dict[str, Any]
164164

165165
return {"callStack": stack}
166166

167-
cls._handle_set_breakpoint = _handle_set_breakpoint # type: ignore[attr-defined]
168-
cls._handle_remove_breakpoint = _handle_remove_breakpoint # type: ignore[attr-defined]
169-
cls._handle_toggle_breakpoint = _handle_toggle_breakpoint # type: ignore[attr-defined]
170-
cls._handle_get_breakpoints = _handle_get_breakpoints # type: ignore[attr-defined]
171-
cls._handle_step_over = _handle_step_over # type: ignore[attr-defined]
172-
cls._handle_step_into = _handle_step_into # type: ignore[attr-defined]
173-
cls._handle_step_out = _handle_step_out # type: ignore[attr-defined]
174-
cls._handle_continue = _handle_continue # type: ignore[attr-defined]
175-
cls._handle_get_variables = _handle_get_variables # type: ignore[attr-defined]
176-
cls._handle_get_call_stack = _handle_get_call_stack # type: ignore[attr-defined]
167+
for name, method in (
168+
("_handle_set_breakpoint", _handle_set_breakpoint),
169+
("_handle_remove_breakpoint", _handle_remove_breakpoint),
170+
("_handle_toggle_breakpoint", _handle_toggle_breakpoint),
171+
("_handle_get_breakpoints", _handle_get_breakpoints),
172+
("_handle_step_over", _handle_step_over),
173+
("_handle_step_into", _handle_step_into),
174+
("_handle_step_out", _handle_step_out),
175+
("_handle_continue", _handle_continue),
176+
("_handle_get_variables", _handle_get_variables),
177+
("_handle_get_call_stack", _handle_get_call_stack),
178+
):
179+
setattr(cls, name, method)

packages/core/src/rpaforge/bridge/server.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
if hasattr(sys.stdout, "reconfigure"):
3131
sys.stdout.reconfigure(encoding="utf-8", newline="")
3232

33-
from rpaforge import config
33+
import rpaforge.config as config
3434
from rpaforge.bridge.handlers import BridgeHandlers
3535
from rpaforge.bridge.protocol import (
3636
JSONRPCError,

packages/core/src/rpaforge/codegen/python_generator.py

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -78,21 +78,23 @@ def _sanitize_identifier_impl(name: str) -> str:
7878

7979

8080
def _validate_variable_name(name: str) -> None:
81-
"""Validate variable name against Python reserved keywords.
81+
"""Validate variable name against format limits and Python reserved keywords.
8282
8383
Args:
8484
name: Variable name to validate
8585
8686
Raises:
87-
ValueError: If name is a Python reserved keyword or too long
87+
ValueError: If name is a Python reserved keyword or format is invalid
8888
"""
89-
if len(name) > MAX_VARIABLE_NAME_LENGTH:
90-
raise ValueError(
91-
f"Variable name length ({len(name)}) exceeds maximum ({MAX_VARIABLE_NAME_LENGTH})"
92-
)
93-
94-
if not re.match(r"^[a-zA-Z_][a-zA-Z0-9_]*$", name):
95-
raise ValueError(f"Invalid variable name format: {name}")
89+
try:
90+
from rpaforge.core.validation import ValidationError, validate_variable_name
91+
92+
validate_variable_name(name, limit=MAX_VARIABLE_NAME_LENGTH)
93+
except ValidationError as e:
94+
msg = str(e)
95+
if "exceeds maximum" in msg:
96+
raise ValueError(msg) from None
97+
raise ValueError(f"Invalid variable name format: {name}") from None
9698

9799
if keyword.iskeyword(name):
98100
raise ValueError(f"Variable name '{name}' is a Python reserved keyword")

packages/core/src/rpaforge/core/_worker_pool.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626

2727
import psutil
2828

29-
from rpaforge import config
29+
import rpaforge.config as config
3030
from rpaforge.i18n import _ as _t
3131

3232
logger = logging.getLogger(__name__)

packages/core/src/rpaforge/core/checkpoint.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
from pathlib import Path
1818
from typing import Any
1919

20-
from rpaforge import config
20+
import rpaforge.config as config
2121
from rpaforge.core.models import Breakpoint, CallFrame
2222

2323
logger = logging.getLogger("rpaforge")

packages/core/src/rpaforge/core/diagram_converter.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111
from typing import Any
1212

1313
from rpaforge.core.execution import ActivityCall, Process, Task, TryCatchGroup
14+
from rpaforge.core.safe_evaluator import safe_eval
15+
from rpaforge.core.validation import validate_variable_name
1416
from rpaforge.core.validator import (
1517
ProcessValidator,
1618
ValidationResult,
@@ -95,7 +97,6 @@ def _build_graph(
9597
def _extract_variables(self, diagram: dict[str, Any]) -> dict[str, Any]:
9698
variables: dict[str, Any] = {}
9799
nodes = {n["id"]: n for n in diagram.get("nodes", []) if "id" in n}
98-
from rpaforge.core.validation import validate_variable_name
99100

100101
for variable in diagram.get("variables", []):
101102
if not isinstance(variable, dict):
@@ -116,8 +117,6 @@ def _extract_variables(self, diagram: dict[str, Any]) -> dict[str, Any]:
116117
var_name = block_data.get("variableName", "")
117118
expr = block_data.get("expression", "")
118119
if var_name:
119-
from rpaforge.core.validation import validate_variable_name
120-
121120
try:
122121
validated_name = validate_variable_name(var_name)
123122
try:
@@ -215,8 +214,6 @@ def _push_if_branches(
215214
stack: list[tuple[str, set[str], str | None]],
216215
visited: set[str],
217216
) -> None:
218-
from rpaforge.core.safe_evaluator import safe_eval
219-
220217
successors = graph.get(node_id, [])
221218
true_target = next(
222219
(target for target, handle in successors if handle == "true"), None

packages/core/src/rpaforge/core/executor.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -232,8 +232,6 @@ def from_exception(
232232
context: ExecutionContext | None = None,
233233
) -> ExecutionError:
234234
"""Create ExecutionError with full context from an exception."""
235-
import datetime
236-
237235
error_context = ErrorContext(
238236
message=str(exc),
239237
activity=activity,

packages/core/src/rpaforge/core/runner.py

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,15 @@
88

99
import logging
1010
import threading
11+
import time
12+
import uuid
1113
from collections.abc import Callable
14+
from datetime import datetime, timezone
1215
from enum import Enum
1316
from pathlib import Path
1417
from typing import TYPE_CHECKING, Any
1518

16-
from rpaforge import config
19+
from rpaforge.config import get_runs_dir
1720
from rpaforge.core.audit import RunRecord, StepRecord
1821
from rpaforge.core.execution import (
1922
ActivityCall,
@@ -318,8 +321,6 @@ def _handle_activity_start(self, activity: ActivityCall) -> None:
318321
self._current_depth = len(self._call_stack) + 1
319322

320323
# Start tracking time for audit logging
321-
import time
322-
323324
self._step_start_time = time.time()
324325

325326
frame = CallFrame(
@@ -356,8 +357,6 @@ def _handle_activity_end(self, result: dict[str, Any] | None = None) -> None:
356357
frame = self._call_stack.pop()
357358
# Record step completion for audit log.
358359
if self._step_start_time is not None:
359-
import time
360-
361360
duration_ms = int((time.time() - self._step_start_time) * 1000)
362361
node_id = frame.node_id or ""
363362
result = result or {}
@@ -482,9 +481,6 @@ def _notify_resume(self) -> None:
482481

483482
def _init_audit_run(self, process: Process) -> None:
484483
"""Initialize audit run record."""
485-
import uuid
486-
from datetime import datetime, timezone
487-
488484
run_id = str(uuid.uuid4())
489485
now = datetime.now(timezone.utc).isoformat()
490486
self._current_run = RunRecord(
@@ -501,8 +497,6 @@ def _finalize_audit_run(self, result: ExecutionResult) -> None:
501497
if not self._current_run:
502498
return
503499

504-
from datetime import datetime, timezone
505-
506500
now = datetime.now(timezone.utc).isoformat()
507501
self._current_run.finished_at = now
508502

@@ -516,7 +510,7 @@ def _finalize_audit_run(self, result: ExecutionResult) -> None:
516510

517511
# Save to disk
518512
try:
519-
runs_dir = config.get_runs_dir()
513+
runs_dir = get_runs_dir()
520514
self._last_audit_path = self._current_run.save(runs_dir)
521515
self._cleanup_old_runs(runs_dir, keep=50)
522516
except Exception as e:

packages/core/src/rpaforge/core/validation.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from __future__ import annotations
22

3+
import re
34
from dataclasses import dataclass
45
from enum import Enum
56
from typing import Any
@@ -8,8 +9,6 @@
89
class ValidationError(Exception):
910
"""Raised when input validation fails."""
1011

11-
pass
12-
1312

1413
class LimitType(Enum):
1514
"""Types of input limits."""
@@ -117,8 +116,6 @@ def validate_variable_name(
117116
f"Variable name length ({len(name)}) exceeds maximum ({limit})"
118117
)
119118

120-
import re
121-
122119
if not re.match(r"^[a-zA-Z_][a-zA-Z0-9_]*$", name):
123120
raise ValidationError(
124121
f"Variable name '{name}' contains invalid characters. "

packages/core/src/rpaforge/core/validator.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,16 @@
99
from dataclasses import dataclass, field
1010
from typing import Any
1111

12-
13-
class ValidationError(Exception):
14-
"""Raised when input validation fails."""
15-
16-
pass
12+
from rpaforge.core.validation import ValidationError
13+
14+
__all__ = [
15+
"ValidationError",
16+
"ValidationErrorItem",
17+
"ValidationResult",
18+
"ProcessValidator",
19+
"validate_diagram",
20+
"validate_process",
21+
]
1722

1823

1924
class ValidationErrorItem:

0 commit comments

Comments
 (0)