azrvus-dev-toolkit 0.1.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.
- azrvus_dev_toolkit-0.1.0.dist-info/METADATA +113 -0
- azrvus_dev_toolkit-0.1.0.dist-info/RECORD +45 -0
- azrvus_dev_toolkit-0.1.0.dist-info/WHEEL +4 -0
- azrvus_dev_toolkit-0.1.0.dist-info/entry_points.txt +2 -0
- azrvus_dev_toolkit-0.1.0.dist-info/licenses/LICENSE +21 -0
- dev_toolkit/__init__.py +163 -0
- dev_toolkit/_version.py +3 -0
- dev_toolkit/async_io.py +19 -0
- dev_toolkit/banner.py +37 -0
- dev_toolkit/cache.py +88 -0
- dev_toolkit/cli.py +60 -0
- dev_toolkit/cli_formatters.py +79 -0
- dev_toolkit/cli_spinner.py +87 -0
- dev_toolkit/color.py +34 -0
- dev_toolkit/concurrency.py +58 -0
- dev_toolkit/config.py +75 -0
- dev_toolkit/crypto_utils.py +21 -0
- dev_toolkit/decorators.py +47 -0
- dev_toolkit/dict_utils.py +77 -0
- dev_toolkit/encoding.py +19 -0
- dev_toolkit/env.py +23 -0
- dev_toolkit/env_validator.py +24 -0
- dev_toolkit/events.py +44 -0
- dev_toolkit/formatters.py +45 -0
- dev_toolkit/hash.py +37 -0
- dev_toolkit/http.py +22 -0
- dev_toolkit/io.py +40 -0
- dev_toolkit/jsonl.py +62 -0
- dev_toolkit/logger.py +36 -0
- dev_toolkit/masking.py +51 -0
- dev_toolkit/pagination.py +29 -0
- dev_toolkit/path_utils.py +84 -0
- dev_toolkit/process.py +65 -0
- dev_toolkit/random_utils.py +19 -0
- dev_toolkit/rate_limiter.py +77 -0
- dev_toolkit/retry.py +37 -0
- dev_toolkit/retry_utils.py +93 -0
- dev_toolkit/system.py +24 -0
- dev_toolkit/templating.py +28 -0
- dev_toolkit/text.py +45 -0
- dev_toolkit/timer.py +41 -0
- dev_toolkit/transforms.py +21 -0
- dev_toolkit/url_utils.py +35 -0
- dev_toolkit/validators.py +74 -0
- dev_toolkit/watcher.py +66 -0
dev_toolkit/jsonl.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Streaming validation of local UTF-8 evaluation datasets."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from collections.abc import Iterable, Iterator
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True)
|
|
10
|
+
class JsonlIssue:
|
|
11
|
+
"""An actionable error without dataset contents; line 0 denotes file errors."""
|
|
12
|
+
|
|
13
|
+
line: int
|
|
14
|
+
message: str
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _reject_constant(value: str) -> None:
|
|
18
|
+
raise ValueError("nonstandard JSON constant")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def validate_jsonl(
|
|
22
|
+
path: str | Path, required_keys: Iterable[str] = ()
|
|
23
|
+
) -> Iterator[JsonlIssue]:
|
|
24
|
+
"""Yield errors reading one line at a time, without retaining records.
|
|
25
|
+
|
|
26
|
+
Blank lines and empty files are invalid. Keys are top-level and presence-only;
|
|
27
|
+
null values are allowed. Missing/unreadable files and invalid UTF-8 yield errors.
|
|
28
|
+
JSON must be strict (NaN and Infinity are rejected). No record text is returned.
|
|
29
|
+
"""
|
|
30
|
+
keys = tuple(dict.fromkeys(required_keys))
|
|
31
|
+
line_number = 0
|
|
32
|
+
try:
|
|
33
|
+
with Path(path).open("rb") as stream:
|
|
34
|
+
for line_number, raw in enumerate(stream, 1):
|
|
35
|
+
try:
|
|
36
|
+
line = raw.decode("utf-8")
|
|
37
|
+
except UnicodeDecodeError:
|
|
38
|
+
yield JsonlIssue(line_number, "invalid UTF-8; save as UTF-8")
|
|
39
|
+
continue
|
|
40
|
+
if not line.strip():
|
|
41
|
+
yield JsonlIssue(line_number, "blank line; remove it or add an object")
|
|
42
|
+
continue
|
|
43
|
+
try:
|
|
44
|
+
record = json.loads(line, parse_constant=_reject_constant)
|
|
45
|
+
except json.JSONDecodeError as error:
|
|
46
|
+
yield JsonlIssue(
|
|
47
|
+
line_number, f"invalid JSON at column {error.colno}; check syntax"
|
|
48
|
+
)
|
|
49
|
+
continue
|
|
50
|
+
except (ValueError, RecursionError):
|
|
51
|
+
yield JsonlIssue(line_number, "invalid JSON; use finite, nested JSON")
|
|
52
|
+
continue
|
|
53
|
+
if not isinstance(record, dict):
|
|
54
|
+
yield JsonlIssue(line_number, "expected a JSON object")
|
|
55
|
+
continue
|
|
56
|
+
missing = [key for key in keys if key not in record]
|
|
57
|
+
if missing:
|
|
58
|
+
yield JsonlIssue(line_number, f"missing required keys: {missing!r}")
|
|
59
|
+
if line_number == 0:
|
|
60
|
+
yield JsonlIssue(0, "empty file; add at least one JSON object")
|
|
61
|
+
except OSError:
|
|
62
|
+
yield JsonlIssue(0, "cannot read input; check path and permissions")
|
dev_toolkit/logger.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Structured JSON logging utilities."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
import sys
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class JSONFormatter(logging.Formatter):
|
|
10
|
+
"""Custom formatter that outputs log records as JSON strings."""
|
|
11
|
+
|
|
12
|
+
def format(self, record: logging.LogRecord) -> str:
|
|
13
|
+
log_data: dict[str, Any] = {
|
|
14
|
+
"timestamp": self.formatTime(record, self.datefmt),
|
|
15
|
+
"level": record.levelname,
|
|
16
|
+
"message": record.getMessage(),
|
|
17
|
+
"module": record.module,
|
|
18
|
+
}
|
|
19
|
+
if record.exc_info:
|
|
20
|
+
log_data["exception"] = self.formatException(record.exc_info)
|
|
21
|
+
return json.dumps(log_data)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def get_json_logger(
|
|
25
|
+
name: str = "dev_toolkit", level: int = logging.INFO
|
|
26
|
+
) -> logging.Logger:
|
|
27
|
+
"""Configure and return a logger with JSON formatting."""
|
|
28
|
+
logger = logging.getLogger(name)
|
|
29
|
+
logger.setLevel(level)
|
|
30
|
+
|
|
31
|
+
if not logger.handlers:
|
|
32
|
+
handler = logging.StreamHandler(sys.stdout)
|
|
33
|
+
handler.setFormatter(JSONFormatter())
|
|
34
|
+
logger.addHandler(handler)
|
|
35
|
+
|
|
36
|
+
return logger
|
dev_toolkit/masking.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
__all__ = ["mask_email", "mask_secret_string", "sanitize_dict"]
|
|
7
|
+
|
|
8
|
+
_EMAIL_REGEX = re.compile(r"(^[\w.%+-]+)@([\w.-]+\.[a-zA-Z]{2,})")
|
|
9
|
+
_TOKEN_KEYS = {"password", "secret", "token", "api_key", "auth", "credential"}
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def mask_email(email: str, mask_char: str = "*", visible_chars: int = 2) -> str:
|
|
13
|
+
"""Mask an email address, keeping a few characters visible before the domain."""
|
|
14
|
+
match = _EMAIL_REGEX.match(email)
|
|
15
|
+
if not match:
|
|
16
|
+
return email
|
|
17
|
+
|
|
18
|
+
username, domain = match.groups()
|
|
19
|
+
if len(username) <= visible_chars:
|
|
20
|
+
masked_user = mask_char * len(username)
|
|
21
|
+
else:
|
|
22
|
+
masked_user = username[:visible_chars] + mask_char * (
|
|
23
|
+
len(username) - visible_chars
|
|
24
|
+
)
|
|
25
|
+
return f"{masked_user}@{domain}"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def mask_secret_string(secret: str, mask_char: str = "*", visible_end: int = 4) -> str:
|
|
29
|
+
"""Mask a token or password, keeping the last few characters visible."""
|
|
30
|
+
if len(secret) <= visible_end:
|
|
31
|
+
return mask_char * len(secret)
|
|
32
|
+
return mask_char * (len(secret) - visible_end) + secret[-visible_end:]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def sanitize_dict(data: dict[str, Any], mask_char: str = "*") -> dict[str, Any]:
|
|
36
|
+
"""Recursively traverse a dictionary and mask sensitive keys and values."""
|
|
37
|
+
sanitized: dict[str, Any] = {}
|
|
38
|
+
for key, value in data.items():
|
|
39
|
+
key_lower = key.lower()
|
|
40
|
+
if any(token in key_lower for token in _TOKEN_KEYS):
|
|
41
|
+
if isinstance(value, str):
|
|
42
|
+
sanitized[key] = mask_secret_string(value, mask_char=mask_char)
|
|
43
|
+
else:
|
|
44
|
+
sanitized[key] = "[REDACTED]"
|
|
45
|
+
elif isinstance(value, dict):
|
|
46
|
+
sanitized[key] = sanitize_dict(value, mask_char=mask_char)
|
|
47
|
+
elif isinstance(value, str) and _EMAIL_REGEX.match(value):
|
|
48
|
+
sanitized[key] = mask_email(value, mask_char=mask_char)
|
|
49
|
+
else:
|
|
50
|
+
sanitized[key] = value
|
|
51
|
+
return sanitized
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
__all__ = ["paginate"]
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def paginate(items: list[Any], page: int = 1, page_size: int = 10) -> dict[str, Any]:
|
|
9
|
+
"""Paginate a list of items and return items with metadata."""
|
|
10
|
+
page = max(page, 1)
|
|
11
|
+
page_size = max(page_size, 1)
|
|
12
|
+
|
|
13
|
+
total_items = len(items)
|
|
14
|
+
total_pages = (total_items + page_size - 1) // page_size if total_items > 0 else 1
|
|
15
|
+
|
|
16
|
+
start = (page - 1) * page_size
|
|
17
|
+
end = start + page_size
|
|
18
|
+
|
|
19
|
+
paginated_items = items[start:end]
|
|
20
|
+
|
|
21
|
+
return {
|
|
22
|
+
"items": paginated_items,
|
|
23
|
+
"page": page,
|
|
24
|
+
"page_size": page_size,
|
|
25
|
+
"total_items": total_items,
|
|
26
|
+
"total_pages": total_pages,
|
|
27
|
+
"has_next": page < total_pages,
|
|
28
|
+
"has_prev": page > 1,
|
|
29
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Filesystem path and directory pattern utilities."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Generator, Sequence
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def get_dir_size(directory: str | Path) -> int:
|
|
8
|
+
"""Recursively calculate total size in bytes for a directory."""
|
|
9
|
+
dir_path = Path(directory)
|
|
10
|
+
if not dir_path.exists() or not dir_path.is_dir():
|
|
11
|
+
raise ValueError(
|
|
12
|
+
f"Directory '{directory}' does not exist or is not a directory"
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
return sum(
|
|
16
|
+
f.stat().st_size
|
|
17
|
+
for f in dir_path.rglob("*")
|
|
18
|
+
if f.is_file() and not f.is_symlink()
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def replace_extension(path: str | Path, new_ext: str) -> Path:
|
|
23
|
+
"""Replace or set the file extension of a path."""
|
|
24
|
+
p = Path(path)
|
|
25
|
+
if not new_ext.startswith(".") and new_ext != "":
|
|
26
|
+
new_ext = f".{new_ext}"
|
|
27
|
+
return p.with_suffix(new_ext)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def find_files(
|
|
31
|
+
directory: str | Path,
|
|
32
|
+
patterns: Sequence[str] = ("*",),
|
|
33
|
+
exclude_dirs: Sequence[str] = (".git", "__pycache__", ".venv"),
|
|
34
|
+
) -> Generator[Path, None, None]:
|
|
35
|
+
"""Yield files matching any pattern while avoiding specified directories."""
|
|
36
|
+
dir_path = Path(directory)
|
|
37
|
+
if not dir_path.exists() or not dir_path.is_dir():
|
|
38
|
+
raise ValueError(
|
|
39
|
+
f"Directory '{directory}' does not exist or is not a directory"
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
exclude_set = set(exclude_dirs)
|
|
43
|
+
|
|
44
|
+
for item in dir_path.rglob("*"):
|
|
45
|
+
if any(part in exclude_set for part in item.parts):
|
|
46
|
+
continue
|
|
47
|
+
if item.is_file() and any(item.match(pat) for pat in patterns):
|
|
48
|
+
yield item
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def get_tree(
|
|
52
|
+
directory: str | Path,
|
|
53
|
+
max_depth: int = 2,
|
|
54
|
+
exclude_dirs: Sequence[str] = (".git", "__pycache__", ".venv"),
|
|
55
|
+
) -> str:
|
|
56
|
+
"""Generate a clean ASCII tree representation of a directory layout."""
|
|
57
|
+
dir_path = Path(directory)
|
|
58
|
+
if not dir_path.exists() or not dir_path.is_dir():
|
|
59
|
+
raise ValueError(
|
|
60
|
+
f"Directory '{directory}' does not exist or is not a directory"
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
lines = [f"{dir_path.name}/"]
|
|
64
|
+
exclude_set = set(exclude_dirs)
|
|
65
|
+
|
|
66
|
+
def _build_tree(current: Path, prefix: str, depth: int) -> None:
|
|
67
|
+
if depth > max_depth:
|
|
68
|
+
return
|
|
69
|
+
entries = sorted(
|
|
70
|
+
[e for e in current.iterdir() if e.name not in exclude_set],
|
|
71
|
+
key=lambda x: (not x.is_dir(), x.name.lower()),
|
|
72
|
+
)
|
|
73
|
+
for i, entry in enumerate(entries):
|
|
74
|
+
is_last = i == len(entries) - 1
|
|
75
|
+
connector = "└── " if is_last else "├── "
|
|
76
|
+
lines.append(
|
|
77
|
+
f"{prefix}{connector}{entry.name}{'/' if entry.is_dir() else ''}"
|
|
78
|
+
)
|
|
79
|
+
if entry.is_dir():
|
|
80
|
+
extension = " " if is_last else "│ "
|
|
81
|
+
_build_tree(entry, prefix + extension, depth + 1)
|
|
82
|
+
|
|
83
|
+
_build_tree(dir_path, "", 1)
|
|
84
|
+
return "\n".join(lines)
|
dev_toolkit/process.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Subprocess execution and command runner utilities."""
|
|
2
|
+
|
|
3
|
+
import dataclasses
|
|
4
|
+
import shlex
|
|
5
|
+
import subprocess
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclasses.dataclass(frozen=True)
|
|
10
|
+
class ProcessResult:
|
|
11
|
+
"""Dataclass holding command execution outputs and metadata."""
|
|
12
|
+
|
|
13
|
+
command: list[str]
|
|
14
|
+
returncode: int
|
|
15
|
+
stdout: str
|
|
16
|
+
stderr: str
|
|
17
|
+
|
|
18
|
+
@property
|
|
19
|
+
def success(self) -> bool:
|
|
20
|
+
"""Return True if the process completed with returncode 0."""
|
|
21
|
+
return self.returncode == 0
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def run_command(
|
|
25
|
+
cmd: list[str] | str,
|
|
26
|
+
cwd: str | Path | None = None,
|
|
27
|
+
timeout: float | None = None,
|
|
28
|
+
check: bool = False,
|
|
29
|
+
) -> ProcessResult:
|
|
30
|
+
"""Execute a system command safely and capture its output."""
|
|
31
|
+
if isinstance(cmd, str):
|
|
32
|
+
cmd_args = shlex.split(cmd)
|
|
33
|
+
else:
|
|
34
|
+
cmd_args = list(cmd)
|
|
35
|
+
|
|
36
|
+
if not cmd_args:
|
|
37
|
+
raise ValueError("Command cannot be empty")
|
|
38
|
+
|
|
39
|
+
try:
|
|
40
|
+
completed = subprocess.run(
|
|
41
|
+
cmd_args,
|
|
42
|
+
cwd=cwd,
|
|
43
|
+
capture_output=True,
|
|
44
|
+
text=True,
|
|
45
|
+
timeout=timeout,
|
|
46
|
+
check=False,
|
|
47
|
+
)
|
|
48
|
+
except subprocess.TimeoutExpired as err:
|
|
49
|
+
raise TimeoutError(
|
|
50
|
+
f"Command '{' '.join(cmd_args)}' timed out after {timeout} seconds"
|
|
51
|
+
) from err
|
|
52
|
+
|
|
53
|
+
result = ProcessResult(
|
|
54
|
+
command=cmd_args,
|
|
55
|
+
returncode=completed.returncode,
|
|
56
|
+
stdout=completed.stdout,
|
|
57
|
+
stderr=completed.stderr,
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
if check and not result.success:
|
|
61
|
+
raise RuntimeError(
|
|
62
|
+
f"Command '{' '.join(cmd_args)}' failed with exit code {result.returncode}:\n{result.stderr}"
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
return result
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import random
|
|
4
|
+
import string
|
|
5
|
+
import uuid
|
|
6
|
+
|
|
7
|
+
__all__ = ["generate_uuid", "random_string"]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def random_string(
|
|
11
|
+
length: int = 10, chars: str = string.ascii_letters + string.digits
|
|
12
|
+
) -> str:
|
|
13
|
+
"""Generate a random string of specified length from given characters."""
|
|
14
|
+
return "".join(random.choices(chars, k=length))
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def generate_uuid() -> str:
|
|
18
|
+
"""Generate a random UUID4 hex string."""
|
|
19
|
+
return uuid.uuid4().hex
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Rate limiting and execution throttling utilities."""
|
|
2
|
+
|
|
3
|
+
import functools
|
|
4
|
+
import threading
|
|
5
|
+
import time
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class TokenBucket:
|
|
11
|
+
"""Thread-safe token bucket rate limiter."""
|
|
12
|
+
|
|
13
|
+
def __init__(self, rate: float, capacity: float | None = None) -> None:
|
|
14
|
+
"""Initialize token bucket.
|
|
15
|
+
|
|
16
|
+
:param rate: Tokens added per second.
|
|
17
|
+
:param capacity: Maximum bucket capacity. Defaults to rate.
|
|
18
|
+
"""
|
|
19
|
+
if rate <= 0:
|
|
20
|
+
raise ValueError("Rate must be strictly positive")
|
|
21
|
+
|
|
22
|
+
self.rate = float(rate)
|
|
23
|
+
self.capacity = float(capacity) if capacity is not None else float(rate)
|
|
24
|
+
|
|
25
|
+
if self.capacity <= 0:
|
|
26
|
+
raise ValueError("Capacity must be strictly positive")
|
|
27
|
+
|
|
28
|
+
self.tokens = self.capacity
|
|
29
|
+
self.last_refill = time.monotonic()
|
|
30
|
+
self._lock = threading.Lock()
|
|
31
|
+
|
|
32
|
+
def _refill(self) -> None:
|
|
33
|
+
now = time.monotonic()
|
|
34
|
+
delta = now - self.last_refill
|
|
35
|
+
self.last_refill = now
|
|
36
|
+
self.tokens = min(self.capacity, self.tokens + delta * self.rate)
|
|
37
|
+
|
|
38
|
+
def consume(self, tokens: float = 1.0, block: bool = True) -> bool:
|
|
39
|
+
"""Consume a specified number of tokens from the bucket.
|
|
40
|
+
|
|
41
|
+
If block is True, sleeps until sufficient tokens are available.
|
|
42
|
+
Returns True if tokens were consumed, False otherwise.
|
|
43
|
+
"""
|
|
44
|
+
if tokens <= 0:
|
|
45
|
+
raise ValueError("Tokens to consume must be positive")
|
|
46
|
+
|
|
47
|
+
while True:
|
|
48
|
+
with self._lock:
|
|
49
|
+
self._refill()
|
|
50
|
+
if self.tokens >= tokens:
|
|
51
|
+
self.tokens -= tokens
|
|
52
|
+
return True
|
|
53
|
+
|
|
54
|
+
if not block:
|
|
55
|
+
return False
|
|
56
|
+
|
|
57
|
+
needed = tokens - self.tokens
|
|
58
|
+
wait_time = needed / self.rate
|
|
59
|
+
|
|
60
|
+
time.sleep(wait_time)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def rate_limit(
|
|
64
|
+
rate: float, capacity: float | None = None, tokens: float = 1.0
|
|
65
|
+
) -> Callable[..., Any]:
|
|
66
|
+
"""Decorator to rate-limit function execution using a TokenBucket."""
|
|
67
|
+
bucket = TokenBucket(rate=rate, capacity=capacity)
|
|
68
|
+
|
|
69
|
+
def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
|
|
70
|
+
@functools.wraps(func)
|
|
71
|
+
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
72
|
+
bucket.consume(tokens=tokens, block=True)
|
|
73
|
+
return func(*args, **kwargs)
|
|
74
|
+
|
|
75
|
+
return wrapper
|
|
76
|
+
|
|
77
|
+
return decorator
|
dev_toolkit/retry.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import functools
|
|
4
|
+
import time
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
__all__ = ["retry"]
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def retry(
|
|
12
|
+
exceptions: type[Exception] | tuple[type[Exception], ...] = Exception,
|
|
13
|
+
retries: int = 3,
|
|
14
|
+
delay: float = 1.0,
|
|
15
|
+
backoff: float = 2.0,
|
|
16
|
+
) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
|
|
17
|
+
"""Decorator to retry a function upon raising specified exceptions."""
|
|
18
|
+
|
|
19
|
+
def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
|
|
20
|
+
@functools.wraps(func)
|
|
21
|
+
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
22
|
+
current_delay = delay
|
|
23
|
+
attempt = 0
|
|
24
|
+
while attempt < retries:
|
|
25
|
+
try:
|
|
26
|
+
return func(*args, **kwargs)
|
|
27
|
+
except exceptions:
|
|
28
|
+
attempt += 1
|
|
29
|
+
if attempt >= retries:
|
|
30
|
+
raise
|
|
31
|
+
time.sleep(current_delay)
|
|
32
|
+
current_delay *= backoff
|
|
33
|
+
return func(*args, **kwargs)
|
|
34
|
+
|
|
35
|
+
return wrapper
|
|
36
|
+
|
|
37
|
+
return decorator
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import inspect
|
|
5
|
+
import random
|
|
6
|
+
import time
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from functools import wraps
|
|
9
|
+
from typing import Any, TypeVar
|
|
10
|
+
|
|
11
|
+
__all__ = ["retry_with_backoff"]
|
|
12
|
+
|
|
13
|
+
F = TypeVar("F", bound=Callable[..., Any])
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _calculate_delay(
|
|
17
|
+
attempt: int,
|
|
18
|
+
base_delay: float,
|
|
19
|
+
max_delay: float,
|
|
20
|
+
backoff_factor: float,
|
|
21
|
+
jitter: str,
|
|
22
|
+
) -> float:
|
|
23
|
+
delay = min(max_delay, base_delay * (backoff_factor**attempt))
|
|
24
|
+
|
|
25
|
+
if jitter == "full":
|
|
26
|
+
return random.uniform(0, delay)
|
|
27
|
+
elif jitter == "equal":
|
|
28
|
+
return (delay / 2) + random.uniform(0, delay / 2)
|
|
29
|
+
|
|
30
|
+
return delay
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def retry_with_backoff(
|
|
34
|
+
retries: int = 3,
|
|
35
|
+
base_delay: float = 1.0,
|
|
36
|
+
max_delay: float = 60.0,
|
|
37
|
+
backoff_factor: float = 2.0,
|
|
38
|
+
jitter: str = "none",
|
|
39
|
+
exceptions: tuple[type[BaseException], ...] = (Exception,),
|
|
40
|
+
on_retry: Callable[[BaseException, int, float], None] | None = None,
|
|
41
|
+
) -> Callable[[F], F]:
|
|
42
|
+
"""Decorator to retry synchronous or asynchronous functions with exponential backoff and jitter."""
|
|
43
|
+
|
|
44
|
+
def decorator(func: F) -> F:
|
|
45
|
+
if inspect.iscoroutinefunction(func):
|
|
46
|
+
|
|
47
|
+
@wraps(func)
|
|
48
|
+
async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
49
|
+
for attempt in range(retries + 1):
|
|
50
|
+
try:
|
|
51
|
+
return await func(*args, **kwargs)
|
|
52
|
+
except exceptions as exc:
|
|
53
|
+
if attempt == retries:
|
|
54
|
+
raise
|
|
55
|
+
|
|
56
|
+
delay = _calculate_delay(
|
|
57
|
+
attempt,
|
|
58
|
+
base_delay,
|
|
59
|
+
max_delay,
|
|
60
|
+
backoff_factor,
|
|
61
|
+
jitter,
|
|
62
|
+
)
|
|
63
|
+
if on_retry:
|
|
64
|
+
on_retry(exc, attempt + 1, delay)
|
|
65
|
+
|
|
66
|
+
await asyncio.sleep(delay)
|
|
67
|
+
|
|
68
|
+
return async_wrapper # type: ignore[return-value]
|
|
69
|
+
|
|
70
|
+
@wraps(func)
|
|
71
|
+
def sync_wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
72
|
+
for attempt in range(retries + 1):
|
|
73
|
+
try:
|
|
74
|
+
return func(*args, **kwargs)
|
|
75
|
+
except exceptions as exc:
|
|
76
|
+
if attempt == retries:
|
|
77
|
+
raise
|
|
78
|
+
|
|
79
|
+
delay = _calculate_delay(
|
|
80
|
+
attempt,
|
|
81
|
+
base_delay,
|
|
82
|
+
max_delay,
|
|
83
|
+
backoff_factor,
|
|
84
|
+
jitter,
|
|
85
|
+
)
|
|
86
|
+
if on_retry:
|
|
87
|
+
on_retry(exc, attempt + 1, delay)
|
|
88
|
+
|
|
89
|
+
time.sleep(delay)
|
|
90
|
+
|
|
91
|
+
return sync_wrapper # type: ignore[return-value]
|
|
92
|
+
|
|
93
|
+
return decorator
|
dev_toolkit/system.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""System utility functions for environment inspection."""
|
|
2
|
+
|
|
3
|
+
import platform
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def get_system_info() -> dict[str, str]:
|
|
8
|
+
"""Return key platform and Python environment metadata."""
|
|
9
|
+
return {
|
|
10
|
+
"os": platform.system(),
|
|
11
|
+
"os_release": platform.release(),
|
|
12
|
+
"architecture": platform.machine(),
|
|
13
|
+
"python_version": sys.version.split()[0],
|
|
14
|
+
"python_implementation": platform.python_implementation(),
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def print_system_summary() -> None:
|
|
19
|
+
"""Print formatted system information to stdout."""
|
|
20
|
+
info = get_system_info()
|
|
21
|
+
print("=== System Information ===")
|
|
22
|
+
for key, val in info.items():
|
|
23
|
+
formatted_key = key.replace("_", " ").title()
|
|
24
|
+
print(f"{formatted_key:<22}: {val}")
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
__all__ = ["render_string", "render_template_file"]
|
|
8
|
+
|
|
9
|
+
_TOKEN_REGEX = re.compile(r"\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def render_string(template: str, context: dict[str, Any]) -> str:
|
|
13
|
+
"""Render a template string by replacing {{ key }} tokens with context values."""
|
|
14
|
+
|
|
15
|
+
def _replacer(match: re.Match[str]) -> str:
|
|
16
|
+
key = match.group(1)
|
|
17
|
+
return str(context.get(key, match.group(0)))
|
|
18
|
+
|
|
19
|
+
return _TOKEN_REGEX.sub(_replacer, template)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def render_template_file(path: str | Path, context: dict[str, Any]) -> str:
|
|
23
|
+
"""Read a template file from disk and render it with the given context."""
|
|
24
|
+
file_path = Path(path)
|
|
25
|
+
if not file_path.exists():
|
|
26
|
+
raise FileNotFoundError(f"Template file not found: {file_path}")
|
|
27
|
+
content = file_path.read_text(encoding="utf-8")
|
|
28
|
+
return render_string(content, context)
|
dev_toolkit/text.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Text manipulation and normalization utilities."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def normalize_whitespace(text: str) -> str:
|
|
7
|
+
"""Replace multiple whitespace characters with a single space and strip leading/trailing spaces."""
|
|
8
|
+
return re.sub(r"\s+", " ", text).strip()
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def slugify(text: str) -> str:
|
|
12
|
+
"""Convert a string into a URL-friendly slug."""
|
|
13
|
+
text = text.lower().strip()
|
|
14
|
+
text = re.sub(r"[^\w\s-]", "", text)
|
|
15
|
+
text = re.sub(r"[\s_-]+", "-", text)
|
|
16
|
+
return re.sub(r"^-+|-+$", "", text)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def truncate_words(text: str, max_words: int, suffix: str = "...") -> str:
|
|
20
|
+
"""Truncate text to a maximum number of words."""
|
|
21
|
+
words = text.split()
|
|
22
|
+
if len(words) <= max_words:
|
|
23
|
+
return text
|
|
24
|
+
return " ".join(words[:max_words]) + suffix
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def camel_to_snake(text: str) -> str:
|
|
28
|
+
"""Convert CamelCase or lowerCamelCase string to snake_case."""
|
|
29
|
+
s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", text)
|
|
30
|
+
return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def snake_to_camel(text: str, uppercase_first: bool = False) -> str:
|
|
34
|
+
"""Convert snake_case string to camelCase or PascalCase."""
|
|
35
|
+
components = text.split("_")
|
|
36
|
+
if uppercase_first:
|
|
37
|
+
return "".join(x.title() for x in components)
|
|
38
|
+
return components[0] + "".join(x.title() for x in components[1:])
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def sanitize_filename(filename: str, replacement: str = "_") -> str:
|
|
42
|
+
"""Remove or replace characters that are invalid in file system paths."""
|
|
43
|
+
cleaned = re.sub(r'[\\/*?:"<>|]', replacement, filename)
|
|
44
|
+
cleaned = re.sub(r"\s+", " ", cleaned).strip()
|
|
45
|
+
return cleaned
|