everynow 0.4.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.
everynow/__init__.py ADDED
@@ -0,0 +1,50 @@
1
+ """
2
+ everynow — Modern everyday Python utilities (maxed out)
3
+ Lightweight • Fully typed • Async-capable • Zero hard dependencies
4
+ """
5
+
6
+ from .config import Config, load_config, auto_config
7
+ from .retry import retry, aretry, RetryError, retry_call
8
+ from .terminal import (
9
+ progress, spinner, success, error, warning, info, debug, status,
10
+ table, confirm, ask, rule, clear,
11
+ )
12
+ from .cache import cache, acache, Cache, cached_property
13
+ from .files import (
14
+ ensure_dir, safe_write, atomic_write, human_size, find_files,
15
+ read_text, write_json, read_json, file_hash, temp_dir,
16
+ )
17
+ from .log import get_logger, setup_logging
18
+ from .http import get, post, request, aget, apost, arequest, HttpError, HttpResponse
19
+ from .validate import (
20
+ require, one_of, between, is_email, is_url, is_phone, length, matches, ensure,
21
+ )
22
+ from .timing import Timer, timer, timed, benchmark
23
+ from .rate import RateLimiter, rate_limit
24
+
25
+ __version__ = "0.4.0"
26
+
27
+ __all__ = [
28
+ # config
29
+ "Config", "load_config", "auto_config",
30
+ # retry
31
+ "retry", "aretry", "retry_call", "RetryError",
32
+ # terminal
33
+ "progress", "spinner", "success", "error", "warning", "info", "debug",
34
+ "status", "table", "confirm", "ask", "rule", "clear",
35
+ # cache
36
+ "cache", "acache", "Cache", "cached_property",
37
+ # files
38
+ "ensure_dir", "safe_write", "atomic_write", "human_size", "find_files",
39
+ "read_text", "write_json", "read_json", "file_hash", "temp_dir",
40
+ # log
41
+ "get_logger", "setup_logging",
42
+ # http
43
+ "get", "post", "request", "aget", "apost", "arequest", "HttpError", "HttpResponse",
44
+ # validate
45
+ "require", "one_of", "between", "is_email", "is_url", "is_phone", "length", "matches", "ensure",
46
+ # timing
47
+ "Timer", "timer", "timed", "benchmark",
48
+ # rate
49
+ "RateLimiter", "rate_limit",
50
+ ]
everynow/cache.py ADDED
@@ -0,0 +1,152 @@
1
+ """
2
+ TTL cache — sync + async support + optional disk persistence.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import functools
8
+ import hashlib
9
+ import pickle
10
+ import time
11
+ from pathlib import Path
12
+ from typing import Any, Callable, Optional, TypeVar, Union
13
+
14
+ F = TypeVar("F", bound=Callable[..., Any])
15
+
16
+
17
+ class Cache:
18
+ def __init__(
19
+ self,
20
+ ttl: Optional[float] = 300.0,
21
+ maxsize: int = 512,
22
+ persist_path: Optional[Union[str, Path]] = None,
23
+ ):
24
+ self.ttl = ttl
25
+ self.maxsize = maxsize
26
+ self.persist_path = Path(persist_path) if persist_path else None
27
+ self._store: dict[str, tuple[Any, Optional[float]]] = {}
28
+ if self.persist_path and self.persist_path.exists():
29
+ self._load()
30
+
31
+ def _key(self, *parts: Any) -> str:
32
+ return hashlib.sha256(pickle.dumps(parts, protocol=4)).hexdigest()
33
+
34
+ def get(self, key: str, default: Any = None) -> Any:
35
+ item = self._store.get(key)
36
+ if item is None:
37
+ return default
38
+ value, expires = item
39
+ if expires is not None and time.time() > expires:
40
+ self._store.pop(key, None)
41
+ return default
42
+ return value
43
+
44
+ def set(self, key: str, value: Any, ttl: Optional[float] = None) -> None:
45
+ effective = ttl if ttl is not None else self.ttl
46
+ expires = time.time() + effective if effective is not None else None
47
+ self._store[key] = (value, expires)
48
+ if len(self._store) > self.maxsize:
49
+ self._store.pop(next(iter(self._store)), None)
50
+ if self.persist_path:
51
+ self._save()
52
+
53
+ def clear(self) -> None:
54
+ self._store.clear()
55
+ if self.persist_path and self.persist_path.exists():
56
+ try:
57
+ self.persist_path.unlink()
58
+ except OSError:
59
+ pass
60
+
61
+ def __len__(self) -> int:
62
+ return len(self._store)
63
+
64
+ def _save(self) -> None:
65
+ if not self.persist_path:
66
+ return
67
+ self.persist_path.parent.mkdir(parents=True, exist_ok=True)
68
+ now = time.time()
69
+ clean = {k: v for k, v in self._store.items() if v[1] is None or v[1] > now}
70
+ try:
71
+ with open(self.persist_path, "wb") as f:
72
+ pickle.dump(clean, f, protocol=4)
73
+ except Exception:
74
+ pass
75
+
76
+ def _load(self) -> None:
77
+ try:
78
+ with open(self.persist_path, "rb") as f:
79
+ data = pickle.load(f)
80
+ now = time.time()
81
+ self._store = {k: v for k, v in data.items() if v[1] is None or v[1] > now}
82
+ except Exception:
83
+ self._store = {}
84
+
85
+
86
+ _default = Cache(ttl=300.0)
87
+
88
+
89
+ def cache(
90
+ ttl: Optional[float] = 300.0,
91
+ key: Optional[Callable[..., str]] = None,
92
+ cache_instance: Optional[Cache] = None,
93
+ ) -> Callable[[F], F]:
94
+ """Sync cache decorator."""
95
+ store = cache_instance or _default
96
+
97
+ def decorator(func: F) -> F:
98
+ @functools.wraps(func)
99
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
100
+ k = key(*args, **kwargs) if key else store._key(
101
+ func.__module__, func.__qualname__, args, tuple(sorted(kwargs.items()))
102
+ )
103
+ hit = store.get(k)
104
+ if hit is not None:
105
+ return hit
106
+ result = func(*args, **kwargs)
107
+ store.set(k, result, ttl=ttl)
108
+ return result
109
+
110
+ wrapper.cache_clear = store.clear # type: ignore
111
+ return wrapper # type: ignore
112
+
113
+ return decorator
114
+
115
+
116
+ def acache(
117
+ ttl: Optional[float] = 300.0,
118
+ key: Optional[Callable[..., str]] = None,
119
+ cache_instance: Optional[Cache] = None,
120
+ ) -> Callable[[F], F]:
121
+ """Async cache decorator."""
122
+ store = cache_instance or _default
123
+
124
+ def decorator(func: F) -> F:
125
+ @functools.wraps(func)
126
+ async def wrapper(*args: Any, **kwargs: Any) -> Any:
127
+ k = key(*args, **kwargs) if key else store._key(
128
+ func.__module__, func.__qualname__, args, tuple(sorted(kwargs.items()))
129
+ )
130
+ hit = store.get(k)
131
+ if hit is not None:
132
+ return hit
133
+ result = await func(*args, **kwargs)
134
+ store.set(k, result, ttl=ttl)
135
+ return result
136
+
137
+ wrapper.cache_clear = store.clear # type: ignore
138
+ return wrapper # type: ignore
139
+
140
+ return decorator
141
+
142
+
143
+ def cached_property(func: Callable[..., Any]) -> property:
144
+ attr = f"_cached_{func.__name__}"
145
+
146
+ @functools.wraps(func)
147
+ def getter(self: Any) -> Any:
148
+ if not hasattr(self, attr):
149
+ setattr(self, attr, func(self))
150
+ return getattr(self, attr)
151
+
152
+ return property(getter)
everynow/config.py ADDED
@@ -0,0 +1,175 @@
1
+ """
2
+ Modern configuration system.
3
+ .env + YAML/TOML/JSON + environment overrides + deep merge.
4
+ Zero hard dependencies (YAML/TOML optional).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ from pathlib import Path
12
+ from typing import Any, Dict, Iterable, Mapping, Optional, Union
13
+
14
+ try:
15
+ import tomllib
16
+ except ImportError:
17
+ try:
18
+ import tomli as tomllib # type: ignore
19
+ except ImportError:
20
+ tomllib = None # type: ignore
21
+
22
+ try:
23
+ import yaml
24
+ except ImportError:
25
+ yaml = None # type: ignore
26
+
27
+
28
+ class Config(dict):
29
+ """Dict-like config with attribute access and nested support."""
30
+
31
+ def __getattr__(self, name: str) -> Any:
32
+ try:
33
+ value = self[name]
34
+ if isinstance(value, dict) and not isinstance(value, Config):
35
+ return Config(value)
36
+ return value
37
+ except KeyError as e:
38
+ raise AttributeError(f"Config has no key '{name}'") from e
39
+
40
+ def __setattr__(self, name: str, value: Any) -> None:
41
+ if name.startswith("_"):
42
+ super().__setattr__(name, value)
43
+ else:
44
+ self[name] = value
45
+
46
+ def __delattr__(self, name: str) -> None:
47
+ try:
48
+ del self[name]
49
+ except KeyError as e:
50
+ raise AttributeError(f"Config has no key '{name}'") from e
51
+
52
+ def require(self, key: str) -> Any:
53
+ if key not in self:
54
+ raise KeyError(f"Required config key missing: '{key}'")
55
+ return self[key]
56
+
57
+ def to_dict(self) -> Dict[str, Any]:
58
+ def _convert(obj: Any) -> Any:
59
+ if isinstance(obj, Config):
60
+ return {k: _convert(v) for k, v in obj.items()}
61
+ if isinstance(obj, dict):
62
+ return {k: _convert(v) for k, v in obj.items()}
63
+ if isinstance(obj, list):
64
+ return [_convert(i) for i in obj]
65
+ return obj
66
+ return _convert(self)
67
+
68
+
69
+ def _parse_dotenv(path: Path) -> Dict[str, str]:
70
+ data: Dict[str, str] = {}
71
+ if not path.exists():
72
+ return data
73
+ for raw in path.read_text(encoding="utf-8").splitlines():
74
+ line = raw.strip()
75
+ if not line or line.startswith("#") or "=" not in line:
76
+ continue
77
+ key, _, value = line.partition("=")
78
+ key = key.strip()
79
+ value = value.strip()
80
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in {'"', "'"}:
81
+ value = value[1:-1]
82
+ value = value.replace("\\n", "\n").replace("\\t", "\t")
83
+ if key:
84
+ data[key] = value
85
+ return data
86
+
87
+
88
+ def _load_file(path: Path) -> Dict[str, Any]:
89
+ if not path.exists():
90
+ return {}
91
+ suffix = path.suffix.lower()
92
+ text = path.read_text(encoding="utf-8")
93
+
94
+ if suffix == ".json":
95
+ return json.loads(text) or {}
96
+ if suffix in {".yaml", ".yml"}:
97
+ if yaml is None:
98
+ raise ImportError("PyYAML required for YAML. pip install pyyaml")
99
+ return yaml.safe_load(text) or {}
100
+ if suffix == ".toml":
101
+ if tomllib is None:
102
+ raise ImportError("tomli required for TOML on Python < 3.11. pip install tomli")
103
+ return tomllib.loads(text) or {}
104
+ if suffix == ".env" or path.name == ".env":
105
+ return _parse_dotenv(path)
106
+ try:
107
+ return json.loads(text) or {}
108
+ except json.JSONDecodeError:
109
+ return {}
110
+
111
+
112
+ def _deep_merge(base: Dict[str, Any], override: Dict[str, Any]) -> Dict[str, Any]:
113
+ result = base.copy()
114
+ for key, value in override.items():
115
+ if key in result and isinstance(result[key], dict) and isinstance(value, dict):
116
+ result[key] = _deep_merge(result[key], value)
117
+ else:
118
+ result[key] = value
119
+ return result
120
+
121
+
122
+ def _apply_env(data: Dict[str, Any], prefix: str, sep: str = "__") -> Dict[str, Any]:
123
+ if not prefix:
124
+ return data
125
+ prefix = prefix.upper()
126
+ result = data.copy()
127
+ for env_key, env_value in os.environ.items():
128
+ if not env_key.startswith(prefix):
129
+ continue
130
+ raw = env_key[len(prefix):]
131
+ if not raw:
132
+ continue
133
+ parts = [p.lower() for p in raw.split(sep) if p]
134
+ if not parts:
135
+ continue
136
+ current = result
137
+ for part in parts[:-1]:
138
+ if part not in current or not isinstance(current[part], dict):
139
+ current[part] = {}
140
+ current = current[part]
141
+ current[parts[-1]] = env_value
142
+ return result
143
+
144
+
145
+ def load_config(
146
+ *paths: Union[str, Path],
147
+ env_prefix: str = "",
148
+ defaults: Optional[Mapping[str, Any]] = None,
149
+ nested_separator: str = "__",
150
+ ) -> Config:
151
+ """
152
+ Load config from files + environment.
153
+
154
+ Precedence (later wins): defaults → files → env vars
155
+ """
156
+ result: Dict[str, Any] = {}
157
+ if defaults:
158
+ result = _deep_merge(result, dict(defaults))
159
+ for p in paths:
160
+ result = _deep_merge(result, _load_file(Path(p).expanduser().resolve()))
161
+ if env_prefix:
162
+ result = _apply_env(result, env_prefix, nested_separator)
163
+ return Config(result)
164
+
165
+
166
+ def auto_config(
167
+ env_prefix: str = "APP_",
168
+ search_paths: Optional[Iterable[Union[str, Path]]] = None,
169
+ ) -> Config:
170
+ candidates = list(search_paths) if search_paths else [
171
+ ".env", "config.toml", "config.yaml", "config.yml", "config.json",
172
+ "settings.toml", "settings.yaml", "app.toml", "app.yaml",
173
+ ]
174
+ existing = [p for p in candidates if Path(p).expanduser().exists()]
175
+ return load_config(*existing, env_prefix=env_prefix)
everynow/files.py ADDED
@@ -0,0 +1,108 @@
1
+ """
2
+ Safe file and path utilities.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import hashlib
8
+ import json
9
+ import os
10
+ import shutil
11
+ import tempfile
12
+ from contextlib import contextmanager
13
+ from pathlib import Path
14
+ from typing import Any, Generator, Iterable, Optional, Union
15
+
16
+
17
+ def ensure_dir(path: Union[str, Path]) -> Path:
18
+ p = Path(path).expanduser().resolve()
19
+ p.mkdir(parents=True, exist_ok=True)
20
+ return p
21
+
22
+
23
+ def human_size(num_bytes: int, binary: bool = True) -> str:
24
+ units = ["B", "KiB", "MiB", "GiB", "TiB", "PiB"] if binary else ["B", "KB", "MB", "GB", "TB", "PB"]
25
+ step = 1024.0 if binary else 1000.0
26
+ size = float(abs(num_bytes))
27
+ for unit in units:
28
+ if size < step:
29
+ return f"{int(size)} {unit}" if unit == "B" else f"{size:.1f} {unit}"
30
+ size /= step
31
+ return f"{size:.1f} {units[-1]}"
32
+
33
+
34
+ def safe_write(
35
+ path: Union[str, Path],
36
+ content: Union[str, bytes],
37
+ encoding: str = "utf-8",
38
+ backup: bool = False,
39
+ ) -> Path:
40
+ p = Path(path).expanduser().resolve()
41
+ ensure_dir(p.parent)
42
+ if backup and p.exists():
43
+ shutil.copy2(p, p.with_suffix(p.suffix + ".bak"))
44
+ data = content.encode(encoding) if isinstance(content, str) else content
45
+ fd, tmp = tempfile.mkstemp(dir=str(p.parent), prefix=f".{p.name}.")
46
+ try:
47
+ with os.fdopen(fd, "wb") as f:
48
+ f.write(data)
49
+ os.replace(tmp, p)
50
+ except Exception:
51
+ if os.path.exists(tmp):
52
+ os.unlink(tmp)
53
+ raise
54
+ return p
55
+
56
+
57
+ def atomic_write(path: Union[str, Path], content: Union[str, bytes], encoding: str = "utf-8") -> Path:
58
+ return safe_write(path, content, encoding=encoding, backup=False)
59
+
60
+
61
+ def read_text(path: Union[str, Path], encoding: str = "utf-8") -> str:
62
+ return Path(path).expanduser().read_text(encoding=encoding)
63
+
64
+
65
+ def write_json(path: Union[str, Path], data: Any, indent: int = 2, ensure_ascii: bool = False) -> Path:
66
+ return safe_write(path, json.dumps(data, indent=indent, ensure_ascii=ensure_ascii) + "\n")
67
+
68
+
69
+ def read_json(path: Union[str, Path]) -> Any:
70
+ return json.loads(read_text(path))
71
+
72
+
73
+ def file_hash(path: Union[str, Path], algorithm: str = "sha256", chunk_size: int = 65536) -> str:
74
+ h = hashlib.new(algorithm)
75
+ with open(Path(path).expanduser(), "rb") as f:
76
+ while chunk := f.read(chunk_size):
77
+ h.update(chunk)
78
+ return h.hexdigest()
79
+
80
+
81
+ def find_files(
82
+ root: Union[str, Path],
83
+ patterns: Optional[Iterable[str]] = None,
84
+ exclude_dirs: Optional[Iterable[str]] = None,
85
+ follow_symlinks: bool = False,
86
+ ) -> Generator[Path, None, None]:
87
+ root_p = Path(root).expanduser().resolve()
88
+ patterns = list(patterns) if patterns else ["*"]
89
+ exclude = set(exclude_dirs or [".git", "__pycache__", "node_modules", ".venv", "venv", ".mypy_cache"])
90
+ for dirpath, dirnames, filenames in os.walk(root_p, followlinks=follow_symlinks):
91
+ dirnames[:] = [d for d in dirnames if d not in exclude]
92
+ current = Path(dirpath)
93
+ for name in filenames:
94
+ fp = current / name
95
+ for pat in patterns:
96
+ if fp.match(pat) or Path(name).match(pat):
97
+ yield fp
98
+ break
99
+
100
+
101
+ @contextmanager
102
+ def temp_dir(prefix: str = "everynow_", delete: bool = True) -> Generator[Path, None, None]:
103
+ path = Path(tempfile.mkdtemp(prefix=prefix))
104
+ try:
105
+ yield path
106
+ finally:
107
+ if delete and path.exists():
108
+ shutil.rmtree(path, ignore_errors=True)
everynow/http.py ADDED
@@ -0,0 +1,158 @@
1
+ """
2
+ Lightweight HTTP client — sync + async.
3
+ Uses only the standard library. Built-in retry.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import asyncio
9
+ import json
10
+ import ssl
11
+ import urllib.error
12
+ import urllib.parse
13
+ import urllib.request
14
+ from dataclasses import dataclass
15
+ from typing import Any, Dict, Optional, Union
16
+
17
+ from .retry import retry, RetryError
18
+
19
+
20
+ class HttpError(Exception):
21
+ def __init__(self, message: str, status: Optional[int] = None, body: Optional[str] = None):
22
+ super().__init__(message)
23
+ self.status = status
24
+ self.body = body
25
+
26
+
27
+ @dataclass
28
+ class HttpResponse:
29
+ status: int
30
+ headers: Dict[str, str]
31
+ body: bytes
32
+ url: str
33
+
34
+ def text(self, encoding: str = "utf-8") -> str:
35
+ return self.body.decode(encoding, errors="replace")
36
+
37
+ def json(self) -> Any:
38
+ return json.loads(self.text())
39
+
40
+ @property
41
+ def ok(self) -> bool:
42
+ return 200 <= self.status < 300
43
+
44
+
45
+ def _build_request(
46
+ method: str,
47
+ url: str,
48
+ *,
49
+ params: Optional[Dict[str, Any]] = None,
50
+ data: Optional[Union[Dict[str, Any], str, bytes]] = None,
51
+ headers: Optional[Dict[str, str]] = None,
52
+ json_data: Optional[Any] = None,
53
+ ) -> urllib.request.Request:
54
+ if params:
55
+ query = urllib.parse.urlencode(params, doseq=True)
56
+ url = f"{url}?{query}" if "?" not in url else f"{url}&{query}"
57
+
58
+ body: Optional[bytes] = None
59
+ req_headers = {"User-Agent": "everynow/0.4"}
60
+
61
+ if json_data is not None:
62
+ body = json.dumps(json_data).encode("utf-8")
63
+ req_headers["Content-Type"] = "application/json"
64
+ elif isinstance(data, dict):
65
+ body = urllib.parse.urlencode(data).encode("utf-8")
66
+ req_headers["Content-Type"] = "application/x-www-form-urlencoded"
67
+ elif isinstance(data, str):
68
+ body = data.encode("utf-8")
69
+ elif isinstance(data, bytes):
70
+ body = data
71
+
72
+ if headers:
73
+ req_headers.update(headers)
74
+
75
+ return urllib.request.Request(url, data=body, headers=req_headers, method=method.upper())
76
+
77
+
78
+ def request(
79
+ method: str,
80
+ url: str,
81
+ *,
82
+ params: Optional[Dict[str, Any]] = None,
83
+ data: Optional[Union[Dict[str, Any], str, bytes]] = None,
84
+ json: Optional[Any] = None,
85
+ headers: Optional[Dict[str, str]] = None,
86
+ timeout: float = 30.0,
87
+ retries: int = 3,
88
+ verify: bool = True,
89
+ ) -> HttpResponse:
90
+ """Sync HTTP request with automatic retry."""
91
+
92
+ @retry(tries=retries, delay=0.5, backoff=1.8, exceptions=(urllib.error.URLError, TimeoutError, ConnectionError))
93
+ def _do() -> HttpResponse:
94
+ req = _build_request(method, url, params=params, data=data, headers=headers, json_data=json)
95
+ ctx = ssl.create_default_context() if verify else ssl._create_unverified_context()
96
+ try:
97
+ with urllib.request.urlopen(req, timeout=timeout, context=ctx) as resp:
98
+ return HttpResponse(
99
+ status=resp.status,
100
+ headers=dict(resp.headers),
101
+ body=resp.read(),
102
+ url=resp.geturl(),
103
+ )
104
+ except urllib.error.HTTPError as e:
105
+ body = e.read() if hasattr(e, "read") else b""
106
+ raise HttpError(
107
+ f"HTTP {e.code}: {e.reason}",
108
+ status=e.code,
109
+ body=body.decode("utf-8", errors="replace"),
110
+ ) from e
111
+
112
+ try:
113
+ return _do()
114
+ except RetryError as e:
115
+ raise HttpError(str(e), body=str(e.last_exception)) from e
116
+
117
+
118
+ def get(url: str, **kwargs: Any) -> HttpResponse:
119
+ return request("GET", url, **kwargs)
120
+
121
+
122
+ def post(url: str, **kwargs: Any) -> HttpResponse:
123
+ return request("POST", url, **kwargs)
124
+
125
+
126
+ async def arequest(
127
+ method: str,
128
+ url: str,
129
+ *,
130
+ params: Optional[Dict[str, Any]] = None,
131
+ data: Optional[Union[Dict[str, Any], str, bytes]] = None,
132
+ json: Optional[Any] = None,
133
+ headers: Optional[Dict[str, str]] = None,
134
+ timeout: float = 30.0,
135
+ retries: int = 3,
136
+ verify: bool = True,
137
+ ) -> HttpResponse:
138
+ """Async HTTP request with automatic retry."""
139
+ return await asyncio.to_thread(
140
+ request,
141
+ method,
142
+ url,
143
+ params=params,
144
+ data=data,
145
+ json=json,
146
+ headers=headers,
147
+ timeout=timeout,
148
+ retries=retries,
149
+ verify=verify,
150
+ )
151
+
152
+
153
+ async def aget(url: str, **kwargs: Any) -> HttpResponse:
154
+ return await arequest("GET", url, **kwargs)
155
+
156
+
157
+ async def apost(url: str, **kwargs: Any) -> HttpResponse:
158
+ return await arequest("POST", url, **kwargs)