pathflow-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.
@@ -0,0 +1,153 @@
1
+ """Simple logging setup using stdlib logging."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import sys
7
+ from types import TracebackType
8
+
9
+ # ──────────────────────────────────────────────────────────────────────────────
10
+ # LOGGER SETUP
11
+ # ──────────────────────────────────────────────────────────────────────────────
12
+
13
+ _DEFAULT_LEVEL = logging.WARNING
14
+ _LOGGER_NAME = "path_file"
15
+ _LOGGER: logging.Logger | None = None
16
+
17
+
18
+ def get_logger(name: str = _LOGGER_NAME) -> logging.Logger:
19
+ """
20
+ Get or create the path_file logger.
21
+
22
+ Args:
23
+ name: Logger name (default: 'path_file')
24
+
25
+ Returns:
26
+ Configured logger instance
27
+ """
28
+ global _LOGGER
29
+ if _LOGGER is None:
30
+ _LOGGER = _create_logger(name)
31
+ return _LOGGER
32
+
33
+
34
+ def _create_logger(name: str) -> logging.Logger:
35
+ """Create and configure logger."""
36
+ logger = logging.getLogger(name)
37
+ logger.setLevel(_DEFAULT_LEVEL)
38
+
39
+ # Avoid duplicate handlers
40
+ if logger.handlers:
41
+ return logger
42
+
43
+ # Console handler with simple format
44
+ handler = logging.StreamHandler(sys.stderr)
45
+ handler.setLevel(_DEFAULT_LEVEL)
46
+
47
+ formatter = logging.Formatter("%(levelname)s: %(message)s")
48
+ handler.setFormatter(formatter)
49
+ logger.addHandler(handler)
50
+
51
+ # Prevent propagation to root logger
52
+ logger.propagate = False
53
+
54
+ return logger
55
+
56
+
57
+ def set_verbosity(level: int) -> None:
58
+ """
59
+ Set logging verbosity level.
60
+
61
+ Args:
62
+ level: Logging level (logging.DEBUG, INFO, WARNING, ERROR, CRITICAL)
63
+ """
64
+ logger = get_logger()
65
+ logger.setLevel(level)
66
+ for handler in logger.handlers:
67
+ handler.setLevel(level)
68
+
69
+
70
+ def verbose() -> None:
71
+ """Enable verbose (INFO) logging."""
72
+ set_verbosity(logging.INFO)
73
+
74
+
75
+ def quiet() -> None:
76
+ """Enable quiet (CRITICAL only) logging."""
77
+ set_verbosity(logging.CRITICAL)
78
+
79
+
80
+ def debug() -> None:
81
+ """Enable debug logging."""
82
+ set_verbosity(logging.DEBUG)
83
+
84
+
85
+ # ──────────────────────────────────────────────────────────────────────────────
86
+ # CONTEXT MANAGERS
87
+ # ──────────────────────────────────────────────────────────────────────────────
88
+
89
+
90
+ class LogContext:
91
+ """Context manager for temporary log level changes."""
92
+
93
+ def __init__(self, level: int) -> None:
94
+ self.level = level
95
+ self.previous_level = _DEFAULT_LEVEL
96
+
97
+ def __enter__(self) -> None:
98
+ global _DEFAULT_LEVEL
99
+ self.previous_level = get_logger().level
100
+ set_verbosity(self.level)
101
+
102
+ def __exit__(
103
+ self,
104
+ exc_type: type[BaseException] | None,
105
+ exc_val: BaseException | None,
106
+ exc_tb: TracebackType | None,
107
+ ) -> None:
108
+ set_verbosity(self.previous_level)
109
+
110
+
111
+ def with_verbose() -> LogContext:
112
+ """Context manager for verbose logging."""
113
+ return LogContext(logging.INFO)
114
+
115
+
116
+ def with_quiet() -> LogContext:
117
+ """Context manager for quiet logging."""
118
+ return LogContext(logging.CRITICAL)
119
+
120
+
121
+ def with_debug() -> LogContext:
122
+ """Context manager for debug logging."""
123
+ return LogContext(logging.DEBUG)
124
+
125
+
126
+ # ──────────────────────────────────────────────────────────────────────────────
127
+ # CONVENIENCE FUNCTIONS
128
+ # ──────────────────────────────────────────────────────────────────────────────
129
+
130
+
131
+ def log_debug(msg: str, *args: object) -> None:
132
+ """Log debug message."""
133
+ get_logger().debug(msg, *args)
134
+
135
+
136
+ def log_info(msg: str, *args: object) -> None:
137
+ """Log info message."""
138
+ get_logger().info(msg, *args)
139
+
140
+
141
+ def log_warning(msg: str, *args: object) -> None:
142
+ """Log warning message."""
143
+ get_logger().warning(msg, *args)
144
+
145
+
146
+ def log_error(msg: str, *args: object) -> None:
147
+ """Log error message."""
148
+ get_logger().error(msg, *args)
149
+
150
+
151
+ def log_exception(msg: str, *args: object) -> None:
152
+ """Log exception with traceback."""
153
+ get_logger().exception(msg, *args)
@@ -0,0 +1,234 @@
1
+ """Internal parsing utilities with caching."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import functools
6
+ import re
7
+ from collections.abc import Callable
8
+ from datetime import datetime, timedelta
9
+ from pathlib import Path
10
+ from re import Pattern
11
+
12
+ from path_file.exceptions import InvalidDurationError, InvalidPatternError, InvalidSizeError
13
+ from path_file.units import parse_datetime, parse_duration, parse_size
14
+
15
+ # ──────────────────────────────────────────────────────────────────────────────
16
+ # REGEX CACHE
17
+ # ──────────────────────────────────────────────────────────────────────────────
18
+
19
+
20
+ @functools.lru_cache(maxsize=256)
21
+ def _compile_regex(pattern: str, flags: int = 0) -> Pattern[str]:
22
+ """Compile and cache regex pattern."""
23
+ try:
24
+ return re.compile(pattern, flags)
25
+ except re.error as e:
26
+ raise InvalidPatternError(pattern, f"Invalid regex: {e}") from e
27
+
28
+
29
+ # ──────────────────────────────────────────────────────────────────────────────
30
+ # PATTERN MATCHER
31
+ # ──────────────────────────────────────────────────────────────────────────────
32
+
33
+
34
+ class PatternMatcher:
35
+ """
36
+ Unified pattern matching for glob and regex patterns.
37
+
38
+ Supports:
39
+ - Glob patterns: *.txt, **/*.py, folder/*
40
+ - Regex patterns: wrapped in /.../ or prefixed with 're:'
41
+ - Plain strings: exact match
42
+ """
43
+
44
+ def __init__(self, pattern: str, case_sensitive: bool = False) -> None:
45
+ self.pattern = pattern
46
+ self.case_sensitive = case_sensitive
47
+ self._compiled: Pattern[str] | None = None
48
+ self._is_regex = False
49
+ self._parse_pattern()
50
+
51
+ def _parse_pattern(self) -> None:
52
+ """Parse pattern and determine type."""
53
+ # Regex: /pattern/flags or re:pattern
54
+ if self.pattern.startswith("/") and self.pattern.count("/") >= 2:
55
+ # /pattern/flags
56
+ parts = self.pattern.split("/")
57
+ if len(parts) >= 3:
58
+ pattern = "/".join(parts[1:-1])
59
+ flags_str = parts[-1]
60
+ flags = 0
61
+ if "i" in flags_str:
62
+ flags |= re.IGNORECASE
63
+ if "m" in flags_str:
64
+ flags |= re.MULTILINE
65
+ if "s" in flags_str:
66
+ flags |= re.DOTALL
67
+ self._compiled = _compile_regex(pattern, flags)
68
+ self._is_regex = True
69
+ return
70
+ elif self.pattern.startswith("re:"):
71
+ self._compiled = _compile_regex(
72
+ self.pattern[3:], 0 if self.case_sensitive else re.IGNORECASE
73
+ )
74
+ self._is_regex = True
75
+ return
76
+
77
+ # Glob pattern - convert to regex
78
+ self._is_regex = False
79
+
80
+ def match(self, text: str) -> bool:
81
+ """Match text against pattern."""
82
+ if self._is_regex and self._compiled:
83
+ return bool(self._compiled.search(text))
84
+
85
+ # Glob matching
86
+ return self._glob_match(text)
87
+
88
+ def _glob_match(self, text: str) -> bool:
89
+ """Match using glob-style pattern."""
90
+ import fnmatch
91
+
92
+ if self.case_sensitive:
93
+ return fnmatch.fnmatchcase(text, self.pattern) or fnmatch.fnmatchcase(
94
+ Path(text).name, self.pattern
95
+ )
96
+ else:
97
+ # Case-insensitive matching - use lower() on both sides
98
+ text_lower = text.lower()
99
+ pattern_lower = self.pattern.lower()
100
+ name_lower = Path(text).name.lower()
101
+ return fnmatch.fnmatch(text_lower, pattern_lower) or fnmatch.fnmatch(
102
+ name_lower, pattern_lower
103
+ )
104
+
105
+ def match_path(self, path: Path) -> bool:
106
+ """Match against path (both full path and name)."""
107
+ return self.match(str(path)) or self.match(path.name)
108
+
109
+
110
+ # ──────────────────────────────────────────────────────────────────────────────
111
+ # SIZE PARSER
112
+ # ──────────────────────────────────────────────────────────────────────────────
113
+
114
+
115
+ class SizeParser:
116
+ """Parse and validate size specifications."""
117
+
118
+ @staticmethod
119
+ def parse(size: str | int | float) -> int:
120
+ """Parse size to bytes."""
121
+ return parse_size(size)
122
+
123
+ @staticmethod
124
+ def parse_range(size_spec: str) -> tuple[int, int]:
125
+ """
126
+ Parse size range like '1MB-10MB' or '1MB..10MB'.
127
+ Returns (min_bytes, max_bytes).
128
+ """
129
+ for sep in ["..", "-", " to ", " TO "]:
130
+ if sep in size_spec:
131
+ parts = size_spec.split(sep)
132
+ if len(parts) == 2:
133
+ return (parse_size(parts[0].strip()), parse_size(parts[1].strip()))
134
+ raise InvalidSizeError(size_spec, "Use format like '1MB-10MB' or '1MB..10MB'")
135
+
136
+
137
+ # ──────────────────────────────────────────────────────────────────────────────
138
+ # DURATION PARSER
139
+ # ──────────────────────────────────────────────────────────────────────────────
140
+
141
+
142
+ class DurationParser:
143
+ """Parse and validate duration specifications."""
144
+
145
+ @staticmethod
146
+ def parse(duration: str | int | float | timedelta) -> timedelta:
147
+ """Parse duration to timedelta."""
148
+ return parse_duration(duration)
149
+
150
+ @staticmethod
151
+ def parse_range(duration_spec: str) -> tuple[timedelta, timedelta]:
152
+ """
153
+ Parse duration range like '1d-7d' or '1 hour..2 hours'.
154
+ Returns (min_timedelta, max_timedelta).
155
+ """
156
+ for sep in ["..", "-", " to ", " TO "]:
157
+ if sep in duration_spec:
158
+ parts = duration_spec.split(sep)
159
+ if len(parts) == 2:
160
+ return (
161
+ parse_duration(parts[0].strip()),
162
+ parse_duration(parts[1].strip()),
163
+ )
164
+ raise InvalidDurationError(duration_spec, "Use format like '1d-7d' or '1 hour..2 hours'")
165
+
166
+
167
+ # ──────────────────────────────────────────────────────────────────────────────
168
+ # DATETIME PARSER
169
+ # ──────────────────────────────────────────────────────────────────────────────
170
+
171
+
172
+ class DateTimeParser:
173
+ """Parse datetime specifications."""
174
+
175
+ @staticmethod
176
+ def parse(dt: str | datetime) -> datetime:
177
+ """Parse datetime string."""
178
+ return parse_datetime(dt)
179
+
180
+ @staticmethod
181
+ def parse_range(dt_spec: str) -> tuple[datetime, datetime]:
182
+ """Parse datetime range."""
183
+ for sep in ["..", "-", " to ", " TO "]:
184
+ if sep in dt_spec:
185
+ parts = dt_spec.split(sep)
186
+ if len(parts) == 2:
187
+ return (
188
+ parse_datetime(parts[0].strip()),
189
+ parse_datetime(parts[1].strip()),
190
+ )
191
+ raise ValueError(f"Invalid datetime range: {dt_spec}")
192
+
193
+
194
+ # ──────────────────────────────────────────────────────────────────────────────
195
+ # HELPER FUNCTIONS
196
+ # ──────────────────────────────────────────────────────────────────────────────
197
+
198
+
199
+ def make_glob_filter(pattern: str, case_sensitive: bool = False) -> Callable[[str], bool]:
200
+ """Create a filter function for glob pattern."""
201
+ matcher = PatternMatcher(pattern, case_sensitive)
202
+ return matcher.match
203
+
204
+
205
+ def make_regex_filter(pattern: str, flags: int = 0) -> Callable[[str], bool]:
206
+ """Create a filter function for regex pattern."""
207
+ compiled = _compile_regex(pattern, flags)
208
+ return lambda text: bool(compiled.search(text))
209
+
210
+
211
+ def make_size_filter(
212
+ min_size: int | None = None, max_size: int | None = None
213
+ ) -> Callable[[int], bool]:
214
+ """Create a filter function for size range."""
215
+
216
+ def _filter(size: int) -> bool:
217
+ if min_size is not None and size < min_size:
218
+ return False
219
+ return not (max_size is not None and size > max_size)
220
+
221
+ return _filter
222
+
223
+
224
+ def make_time_filter(
225
+ min_time: datetime | None = None, max_time: datetime | None = None
226
+ ) -> Callable[[datetime], bool]:
227
+ """Create a filter function for time range."""
228
+
229
+ def _filter(dt: datetime) -> bool:
230
+ if min_time is not None and dt < min_time:
231
+ return False
232
+ return not (max_time is not None and dt > max_time)
233
+
234
+ return _filter
@@ -0,0 +1,268 @@
1
+ """Safety utilities for destructive operations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import shutil
6
+ import sys
7
+ from pathlib import Path
8
+ from types import TracebackType
9
+
10
+ from path_file.exceptions import DestExistsError, DryRunRequiredError, PathflowError
11
+ from path_file.units import human_size
12
+
13
+ # ──────────────────────────────────────────────────────────────────────────────
14
+ # DESTRUCTIVE OPERATION CONFIRMATION
15
+ # ──────────────────────────────────────────────────────────────────────────────
16
+
17
+
18
+ def confirm_destructive(
19
+ action: str,
20
+ count: int,
21
+ total_size: int,
22
+ force: bool = False,
23
+ dry_run: bool | None = None,
24
+ ) -> bool:
25
+ """
26
+ Confirm a destructive operation.
27
+
28
+ Args:
29
+ action: Action name (delete, move, etc.)
30
+ count: Number of files affected
31
+ total_size: Total size in bytes
32
+ force: Skip confirmation (use with caution)
33
+ dry_run: If True, operation is dry-run (no confirmation needed)
34
+
35
+ Returns:
36
+ True if confirmed, False otherwise
37
+
38
+ Raises:
39
+ DryRunRequiredError: If not confirmed and not dry-run
40
+ """
41
+ if dry_run:
42
+ return True
43
+
44
+ if force:
45
+ return True
46
+
47
+ if count == 0:
48
+ return True
49
+
50
+ # Non-interactive environment (CI, scripts) - require explicit confirm
51
+ if not sys.stdin.isatty():
52
+ raise DryRunRequiredError(
53
+ action, count, "Non-interactive environment: use confirm=True or dry_run=True"
54
+ )
55
+
56
+ # Interactive confirmation
57
+ size_str = human_size(total_size)
58
+ prompt = (
59
+ f"\n⚠️ About to {action} {count} file(s) ({size_str}).\n"
60
+ f" This operation cannot be undone.\n"
61
+ f" Type 'yes' to confirm: "
62
+ )
63
+
64
+ try:
65
+ response = input(prompt).strip().lower()
66
+ return response in ("yes", "y")
67
+ except (EOFError, KeyboardInterrupt):
68
+ print("\nCancelled.")
69
+ return False
70
+
71
+
72
+ def require_confirm_or_dry_run(
73
+ action: str,
74
+ count: int,
75
+ total_size: int,
76
+ confirm: bool,
77
+ dry_run: bool,
78
+ ) -> None:
79
+ """
80
+ Validate that either confirm=True or dry_run=True for destructive ops.
81
+
82
+ Raises:
83
+ DryRunRequiredError: If neither confirm nor dry_run is True
84
+ """
85
+ if not confirm and not dry_run and count > 0:
86
+ raise DryRunRequiredError(action, count)
87
+
88
+
89
+ # ──────────────────────────────────────────────────────────────────────────────
90
+ # DESTINATION VALIDATION
91
+ # ──────────────────────────────────────────────────────────────────────────────
92
+
93
+
94
+ def validate_dest(
95
+ dest: str | Path,
96
+ create: bool = True,
97
+ overwrite: bool = False,
98
+ ) -> Path:
99
+ """
100
+ Validate and prepare destination path.
101
+
102
+ Args:
103
+ dest: Destination path
104
+ create: Create parent directories if they don't exist
105
+ overwrite: Allow overwriting existing destination
106
+
107
+ Returns:
108
+ Resolved destination Path
109
+
110
+ Raises:
111
+ DestExistsError: If destination exists and overwrite=False
112
+ PathflowError: If destination is invalid
113
+ """
114
+ dest = Path(dest).resolve()
115
+
116
+ if dest.exists():
117
+ if not overwrite:
118
+ raise DestExistsError(str(dest), "Use overwrite=True to replace existing destination")
119
+ # Remove existing
120
+ if dest.is_dir():
121
+ shutil.rmtree(dest)
122
+ else:
123
+ dest.unlink()
124
+
125
+ if create:
126
+ dest.parent.mkdir(parents=True, exist_ok=True)
127
+
128
+ return dest
129
+
130
+
131
+ def validate_source(source: str | Path) -> Path:
132
+ """
133
+ Validate source path exists.
134
+
135
+ Returns:
136
+ Resolved source Path
137
+
138
+ Raises:
139
+ FileNotFoundError: If source doesn't exist
140
+ """
141
+ source = Path(source).resolve()
142
+ if not source.exists():
143
+ from path_file.exceptions import FileNotFoundError
144
+
145
+ raise FileNotFoundError(str(source), "Check the path exists and you have read permissions")
146
+ return source
147
+
148
+
149
+ # ──────────────────────────────────────────────────────────────────────────────
150
+ # PATH SAFETY
151
+ # ──────────────────────────────────────────────────────────────────────────────
152
+
153
+
154
+ def safe_path(path: str | Path, base: Path | None = None) -> Path:
155
+ """
156
+ Resolve and validate path for safety.
157
+
158
+ Args:
159
+ path: Path to validate
160
+ base: Optional base directory to restrict to (sandbox mode)
161
+
162
+ Returns:
163
+ Resolved absolute Path
164
+
165
+ Raises:
166
+ PathflowError: If path tries to escape base directory
167
+ """
168
+ path = Path(path).resolve()
169
+
170
+ if base is not None:
171
+ base = Path(base).resolve()
172
+ try:
173
+ path.relative_to(base)
174
+ except ValueError:
175
+ raise PathflowError(
176
+ f"Path {path} escapes base directory {base}",
177
+ "Operation not allowed: path traversal detected",
178
+ ) from None
179
+
180
+ return path
181
+
182
+
183
+ def is_subpath(parent: Path, child: Path) -> bool:
184
+ """Check if child is a subpath of parent."""
185
+ try:
186
+ child.resolve().relative_to(parent.resolve())
187
+ return True
188
+ except ValueError:
189
+ return False
190
+
191
+
192
+ def is_same_file(path1: Path, path2: Path) -> bool:
193
+ """Check if two paths refer to the same file (handles symlinks)."""
194
+ try:
195
+ return path1.resolve().samefile(path2.resolve())
196
+ except (OSError, PermissionError):
197
+ return False
198
+
199
+
200
+ # ──────────────────────────────────────────────────────────────────────────────
201
+ # BACKUP & RESTORE
202
+ # ──────────────────────────────────────────────────────────────────────────────
203
+
204
+
205
+ class BackupManager:
206
+ """Manage backups for safe operations."""
207
+
208
+ def __init__(self, backup_dir: Path | None = None) -> None:
209
+ self.backup_dir = backup_dir or Path.home() / ".path_file" / "backups"
210
+ self.backup_dir.mkdir(parents=True, exist_ok=True)
211
+ self._backups: list[tuple[Path, Path]] = [] # (original, backup)
212
+
213
+ def backup(self, path: Path) -> Path:
214
+ """Create a backup of a file/directory."""
215
+ import uuid
216
+
217
+ backup_name = f"{path.name}.{uuid.uuid4().hex[:8]}.bak"
218
+ backup_path = self.backup_dir / backup_name
219
+
220
+ if path.is_dir():
221
+ shutil.copytree(path, backup_path)
222
+ else:
223
+ shutil.copy2(path, backup_path)
224
+
225
+ self._backups.append((path, backup_path))
226
+ return backup_path
227
+
228
+ def restore_all(self) -> None:
229
+ """Restore all backups."""
230
+ for original, backup in reversed(self._backups):
231
+ if backup.exists():
232
+ if original.exists():
233
+ if original.is_dir():
234
+ shutil.rmtree(original)
235
+ else:
236
+ original.unlink()
237
+ if backup.is_dir():
238
+ shutil.copytree(backup, original)
239
+ else:
240
+ shutil.copy2(backup, original)
241
+
242
+ def clear_backups(self) -> None:
243
+ """Remove all backup files."""
244
+ for _, backup in self._backups:
245
+ try:
246
+ if backup.is_dir():
247
+ shutil.rmtree(backup)
248
+ else:
249
+ backup.unlink()
250
+ except (OSError, PermissionError):
251
+ pass
252
+ self._backups.clear()
253
+
254
+ def __enter__(self) -> BackupManager:
255
+ return self
256
+
257
+ def __exit__(
258
+ self,
259
+ exc_type: type[BaseException] | None,
260
+ exc_val: BaseException | None,
261
+ exc_tb: TracebackType | None,
262
+ ) -> None:
263
+ if exc_type is not None:
264
+ # Error occurred - restore backups
265
+ self.restore_all()
266
+ else:
267
+ # Success - clean up backups
268
+ self.clear_backups()
path_file/_version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"