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.
path_file/rules.py ADDED
@@ -0,0 +1,481 @@
1
+ """Declarative rules engine for file automation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import operator
6
+ from collections.abc import Callable, Iterator
7
+ from dataclasses import dataclass, field
8
+ from datetime import datetime
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from path_file._internal._log import log_debug
13
+ from path_file.chain import FileChain
14
+ from path_file.entries import Entry
15
+ from path_file.exceptions import PathflowError
16
+ from path_file.units import parse_duration, parse_size
17
+
18
+ # ──────────────────────────────────────────────────────────────────────────────
19
+ # MINIMAL TOML PARSER (stdlib compatible for Python 3.10+)
20
+ # ──────────────────────────────────────────────────────────────────────────────
21
+
22
+
23
+ class SimpleTomlParser:
24
+ """Minimal TOML parser for rules files - supports only what we need."""
25
+
26
+ def __init__(self) -> None:
27
+ self.rules: list[dict[str, Any]] = []
28
+ self.current_rule: dict[str, Any] = {}
29
+ self.line_num = 0
30
+
31
+ def parse(self, content: str) -> list[dict[str, Any]]:
32
+ """Parse TOML content and return list of rule dicts."""
33
+ self.rules = []
34
+ self.current_rule = {}
35
+
36
+ for line_num, line in enumerate(content.splitlines(), 1):
37
+ self.line_num = line_num
38
+ line = line.strip()
39
+
40
+ if not line or line.startswith("#"):
41
+ continue
42
+
43
+ if line.startswith("[["):
44
+ # Save previous rule
45
+ if self.current_rule:
46
+ self.rules.append(self.current_rule)
47
+ self.current_rule = {}
48
+ continue
49
+
50
+ # Key = value
51
+ if "=" in line:
52
+ key, value = line.split("=", 1)
53
+ key = key.strip()
54
+ value = value.strip()
55
+ self.current_rule[key] = self._parse_value(value)
56
+
57
+ # Save last rule
58
+ if self.current_rule:
59
+ self.rules.append(self.current_rule)
60
+
61
+ return self.rules
62
+
63
+ def _parse_value(self, value: str) -> Any:
64
+ """Parse TOML value."""
65
+ # String
66
+ if value.startswith('"') and value.endswith('"'):
67
+ return value[1:-1]
68
+ if value.startswith("'") and value.endswith("'"):
69
+ return value[1:-1]
70
+
71
+ # Boolean
72
+ if value.lower() == "true":
73
+ return True
74
+ if value.lower() == "false":
75
+ return False
76
+
77
+ # Number
78
+ try:
79
+ if "." in value:
80
+ return float(value)
81
+ return int(value)
82
+ except ValueError:
83
+ pass
84
+
85
+ # Date/time (basic support)
86
+ # Return as string for now
87
+ return value
88
+
89
+
90
+ # ──────────────────────────────────────────────────────────────────────────────
91
+ # RULE DEFINITION
92
+ # ──────────────────────────────────────────────────────────────────────────────
93
+
94
+
95
+ @dataclass
96
+ class Rule:
97
+ """Single automation rule."""
98
+
99
+ match: str = "*" # Glob pattern
100
+ when: list[str] = field(default_factory=list) # Conditions
101
+ action: str = "none" # delete, move, copy, archive, compress, rename
102
+ dest: str | None = None # Destination for move/copy/archive
103
+ pattern: str | None = None # For rename action
104
+ overwrite: bool = False
105
+ confirm: bool = False
106
+ dry_run: bool = True # Safe by default
107
+
108
+ def to_dict(self) -> dict[str, Any]:
109
+ """Convert rule to a plain dictionary."""
110
+ return {
111
+ "match": self.match,
112
+ "when": list(self.when),
113
+ "action": self.action,
114
+ "dest": self.dest,
115
+ "pattern": self.pattern,
116
+ "overwrite": self.overwrite,
117
+ "confirm": self.confirm,
118
+ "dry_run": self.dry_run,
119
+ }
120
+
121
+ def matches(self, entry: Entry) -> bool:
122
+ """Check if entry matches this rule's conditions."""
123
+ # Check glob pattern
124
+ import fnmatch
125
+
126
+ if not fnmatch.fnmatch(entry.name, self.match):
127
+ return False
128
+
129
+ # Check conditions
130
+ return all(self._check_condition(entry, condition) for condition in self.when)
131
+
132
+ def _check_condition(self, entry: Entry, condition: str) -> bool:
133
+ """Evaluate a single condition string."""
134
+ # Format: "key operator value" or "key=value"
135
+ # Examples: "size > 1MB", "age > 7 days", "name contains 'temp'"
136
+
137
+ # Try to parse as key=value
138
+ if "=" in condition and not any(op in condition for op in [">", "<", ">=", "<="]):
139
+ key, value = condition.split("=", 1)
140
+ key = key.strip()
141
+ value = value.strip().strip("\"'")
142
+ return self._check_equality(entry, key, value)
143
+
144
+ # Shorthand conditions from from_string/from_dict:
145
+ # 'when_larger_than: 50MB' -> 'size > 50MB'
146
+ # 'when_older_than: 7 days' -> 'age > 7 days'
147
+ when_map = {
148
+ "when_larger_than": ("size", ">"),
149
+ "when_smaller_than": ("size", "<"),
150
+ "when_older_than": ("age", ">"),
151
+ "when_newer_than": ("age", "<"),
152
+ }
153
+ for prefix, (key, op) in when_map.items():
154
+ if condition.startswith(prefix):
155
+ rest = condition[len(prefix) :].lstrip(": ")
156
+ return self._check_comparison(entry, key, op, rest)
157
+
158
+ # Parse comparison
159
+ for op in [">=", "<=", ">", "<", "!="]:
160
+ if op in condition:
161
+ key, value = condition.split(op, 1)
162
+ key = key.strip()
163
+ value = value.strip().strip("\"'")
164
+ return self._check_comparison(entry, key, op, value)
165
+
166
+ return True
167
+
168
+ def _check_equality(self, entry: Entry, key: str, value: str) -> bool:
169
+ """Check equality condition."""
170
+ if key == "extension" or key == "ext":
171
+ return entry.suffix.lower() == value.lower()
172
+ if key == "name":
173
+ return entry.name.lower() == value.lower()
174
+ if key == "type":
175
+ if value == "file":
176
+ return entry.is_file
177
+ if value == "dir":
178
+ return entry.is_dir
179
+ if value == "symlink":
180
+ return entry.is_symlink
181
+ return False
182
+
183
+ def _check_comparison(self, entry: Entry, key: str, op: str, value: str) -> bool:
184
+ """Check comparison condition."""
185
+ # Get entry value
186
+ entry_val = self._get_entry_value(entry, key)
187
+ if entry_val is None:
188
+ return False
189
+
190
+ # Parse condition value
191
+ cond_val = self._parse_condition_value(key, value)
192
+ if cond_val is None:
193
+ return False
194
+
195
+ # Compare
196
+ comparisons: dict[str, Callable[[Any, Any], bool]] = {
197
+ ">": operator.gt,
198
+ "<": operator.lt,
199
+ ">=": operator.ge,
200
+ "<=": operator.le,
201
+ "!=": operator.ne,
202
+ }
203
+ compare = comparisons.get(op)
204
+ if compare is None:
205
+ return False
206
+
207
+ return compare(entry_val, cond_val)
208
+
209
+ def _get_entry_value(self, entry: Entry, key: str) -> Any:
210
+ """Get comparable value from entry."""
211
+ key = key.lower()
212
+ if key in ("size", "filesize"):
213
+ return entry.size
214
+ if key in ("age", "modified_age", "mtime_age"):
215
+ return (datetime.now() - entry.modified).total_seconds()
216
+ if key in ("created_age", "ctime_age"):
217
+ return (datetime.now() - entry.created).total_seconds()
218
+ if key in ("name", "filename"):
219
+ return entry.name.lower()
220
+ if key in ("extension", "ext"):
221
+ return entry.suffix.lower()
222
+ return None
223
+
224
+ def _parse_condition_value(self, key: str, value: str) -> Any:
225
+ """Parse condition value based on key type."""
226
+ key = key.lower()
227
+ if key in ("size", "filesize"):
228
+ return parse_size(value)
229
+ if key in ("age", "modified_age", "mtime_age", "created_age", "ctime_age"):
230
+ return parse_duration(value).total_seconds()
231
+ return value.lower()
232
+
233
+
234
+ # ──────────────────────────────────────────────────────────────────────────────
235
+ # RULES COLLECTION
236
+ # ──────────────────────────────────────────────────────────────────────────────
237
+
238
+
239
+ class Rules:
240
+ """Collection of automation rules."""
241
+
242
+ def __init__(self, rules: list[Rule]) -> None:
243
+ self.rules = rules
244
+
245
+ def __len__(self) -> int:
246
+ return len(self.rules)
247
+
248
+ def __iter__(self) -> Iterator[Rule]:
249
+ return iter(self.rules)
250
+
251
+ @classmethod
252
+ def from_file(cls, path: str | Path) -> Rules:
253
+ """Load rules from TOML file."""
254
+ path = Path(path)
255
+ content = path.read_text(encoding="utf-8")
256
+ return cls.from_string(content)
257
+
258
+ @classmethod
259
+ def from_string(cls, content: str) -> Rules:
260
+ """Parse rules from TOML string."""
261
+ parser = SimpleTomlParser()
262
+ rule_dicts = parser.parse(content)
263
+
264
+ rules = []
265
+ for rd in rule_dicts:
266
+ # Handle special when_* keys
267
+ when_conditions = rd.get("when", [])
268
+ if isinstance(when_conditions, str):
269
+ when_conditions = [when_conditions]
270
+ if "when_larger_than" in rd:
271
+ when_conditions.append(f"when_larger_than: {rd['when_larger_than']}")
272
+ if "when_older_than" in rd:
273
+ when_conditions.append(f"when_older_than: {rd['when_older_than']}")
274
+ if "when_smaller_than" in rd:
275
+ when_conditions.append(f"when_smaller_than: {rd['when_smaller_than']}")
276
+ if "when_newer_than" in rd:
277
+ when_conditions.append(f"when_newer_than: {rd['when_newer_than']}")
278
+
279
+ rule = Rule(
280
+ match=rd.get("match", "*"),
281
+ when=when_conditions,
282
+ action=rd.get("action", "none"),
283
+ dest=rd.get("dest"),
284
+ pattern=rd.get("pattern"),
285
+ overwrite=rd.get("overwrite", False),
286
+ confirm=rd.get("confirm", False),
287
+ dry_run=rd.get("dry_run", True),
288
+ )
289
+ rules.append(rule)
290
+
291
+ return cls(rules)
292
+
293
+ @classmethod
294
+ def from_dict(cls, data: dict[str, Any]) -> Rules:
295
+ """Create rules from dictionary."""
296
+ rules = []
297
+ for rd in data.get("rules", []):
298
+ # Handle special when_* keys
299
+ when_conditions = rd.get("when", [])
300
+ if "when_larger_than" in rd:
301
+ when_conditions.append(f"when_larger_than: {rd['when_larger_than']}")
302
+ if "when_older_than" in rd:
303
+ when_conditions.append(f"when_older_than: {rd['when_older_than']}")
304
+ if "when_smaller_than" in rd:
305
+ when_conditions.append(f"when_smaller_than: {rd['when_smaller_than']}")
306
+ if "when_newer_than" in rd:
307
+ when_conditions.append(f"when_newer_than: {rd['when_newer_than']}")
308
+
309
+ rule = Rule(
310
+ match=rd.get("match", "*"),
311
+ when=when_conditions,
312
+ action=rd.get("action", "none"),
313
+ dest=rd.get("dest"),
314
+ pattern=rd.get("pattern"),
315
+ overwrite=rd.get("overwrite", False),
316
+ confirm=rd.get("confirm", False),
317
+ dry_run=rd.get("dry_run", True),
318
+ )
319
+ rules.append(rule)
320
+ return cls(rules)
321
+
322
+ def apply(self, chain: FileChain) -> FileChain:
323
+ """
324
+ Apply rules to a file chain.
325
+
326
+ Returns a new chain with matched entries tagged for action.
327
+ """
328
+ # This is a placeholder - actual implementation would tag entries
329
+ # For now, we return a filtered chain
330
+ matched_entries = []
331
+ for entry in chain:
332
+ for rule in self.rules:
333
+ if rule.matches(entry):
334
+ # Tag entry with action
335
+ entry._rule_action = rule.action
336
+ entry._rule_dest = rule.dest
337
+ entry._rule_params = {
338
+ "pattern": rule.pattern,
339
+ "overwrite": rule.overwrite,
340
+ "confirm": rule.confirm,
341
+ "dry_run": rule.dry_run,
342
+ }
343
+ matched_entries.append(entry)
344
+ break # First matching rule wins
345
+
346
+ return FileChain.from_entries(matched_entries)
347
+
348
+ def run(self, chain: FileChain, dry_run: bool | None = None) -> list[dict[str, Any]]:
349
+ """Execute every matching rule against the chain entries (real execution)."""
350
+ results: list[dict[str, Any]] = []
351
+ for entry in chain:
352
+ for rule in self.rules:
353
+ if rule.matches(entry):
354
+ results.append(
355
+ _execute_rule_action(
356
+ entry, rule, dry_run if dry_run is not None else rule.dry_run
357
+ )
358
+ )
359
+ break # first matching rule wins
360
+ return results
361
+
362
+ def validate(self) -> list[str]:
363
+ """Validate rules and return list of errors."""
364
+ errors = []
365
+ if not self.rules:
366
+ errors.append("No rules defined")
367
+ for i, rule in enumerate(self.rules):
368
+ # Check action is valid
369
+ valid_actions = {
370
+ "none",
371
+ "delete",
372
+ "move",
373
+ "copy",
374
+ "archive",
375
+ "compress",
376
+ "rename",
377
+ "trash",
378
+ }
379
+ if rule.action not in valid_actions:
380
+ errors.append(f"Rule {i}: Invalid action '{rule.action}'")
381
+
382
+ # Check required fields
383
+ if rule.action in ("move", "copy", "archive") and not rule.dest:
384
+ errors.append(f"Rule {i}: Action '{rule.action}' requires 'dest'")
385
+
386
+ if rule.action == "rename" and not rule.pattern:
387
+ errors.append(f"Rule {i}: Action 'rename' requires 'pattern'")
388
+
389
+ # Validate glob pattern
390
+ try:
391
+ import fnmatch
392
+
393
+ fnmatch.fnmatch("test", rule.match)
394
+ except Exception as e:
395
+ errors.append(f"Rule {i}: Invalid match pattern: {e}")
396
+
397
+ return errors
398
+
399
+ def explain(self) -> str:
400
+ """Human-readable description of rules."""
401
+ lines = ["Rules:"]
402
+ for i, rule in enumerate(self.rules, 1):
403
+ lines.append(f" {i}. Match: {rule.match}")
404
+ if rule.when:
405
+ lines.append(f" When: {', '.join(rule.when)}")
406
+ lines.append(f" Action: {rule.action}")
407
+ if rule.dest:
408
+ lines.append(f" Dest: {rule.dest}")
409
+ if rule.pattern:
410
+ lines.append(f" Pattern: {rule.pattern}")
411
+ lines.append(f" Dry-run: {rule.dry_run}")
412
+ return "\n".join(lines)
413
+
414
+
415
+ # ──────────────────────────────────────────────────────────────────────────────
416
+ # RULE EXECUTION HELPERS
417
+ # ──────────────────────────────────────────────────────────────────────────────
418
+
419
+
420
+ def execute_rules(chain: FileChain, rules: Rules, dry_run: bool | None = None) -> list[Any]:
421
+ """Execute rules on a file chain."""
422
+ results = []
423
+
424
+ for entry in chain:
425
+ for rule in rules.rules:
426
+ if rule.matches(entry):
427
+ # Execute action
428
+ result = _execute_rule_action(
429
+ entry, rule, dry_run if dry_run is not None else rule.dry_run
430
+ )
431
+ results.append(result)
432
+ break
433
+
434
+ return results
435
+
436
+
437
+ def _execute_rule_action(entry: Entry, rule: Rule, dry_run: bool) -> dict[str, Any]:
438
+ """Execute a single rule action on an entry (real execution)."""
439
+ base = {
440
+ "entry": entry,
441
+ "action": rule.action,
442
+ "dry_run": dry_run,
443
+ }
444
+ if not rule.action or rule.action == "none":
445
+ base["status"] = "skipped"
446
+ base["result"] = None
447
+ return base
448
+
449
+ # Relative dest resolves against the matched file's directory
450
+ dest: str | Path | None = rule.dest
451
+ if dest is not None and rule.action in ("move", "copy", "archive"):
452
+ dest_path = Path(dest)
453
+ if not dest_path.is_absolute():
454
+ dest = entry.path.parent / dest_path
455
+
456
+ try:
457
+ chain = FileChain.from_paths([entry.path]).dry_run(dry_run)
458
+ if rule.action == "delete":
459
+ chain = chain.delete(confirm=rule.confirm)
460
+ elif rule.action == "trash":
461
+ chain = chain.trash(confirm=rule.confirm)
462
+ elif rule.action == "move":
463
+ chain = chain.move_to(dest, overwrite=rule.overwrite)
464
+ elif rule.action == "copy":
465
+ chain = chain.copy_to(dest, overwrite=rule.overwrite)
466
+ elif rule.action == "archive":
467
+ chain = chain.archive_to(dest)
468
+ elif rule.action == "compress":
469
+ chain = chain.compress()
470
+ elif rule.action == "rename":
471
+ chain = chain.rename(rule.pattern)
472
+ else:
473
+ raise PathflowError(f"Unknown rule action: {rule.action}")
474
+ result = chain.execute()
475
+ base["status"] = "executed"
476
+ base["result"] = result
477
+ except Exception as exc: # one bad rule must not kill the batch
478
+ log_debug(f"rule action failed for {entry.path}: {exc}")
479
+ base["status"] = "error"
480
+ base["error"] = str(exc)
481
+ return base