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/units.py ADDED
@@ -0,0 +1,420 @@
1
+ """Unit parsing and formatting utilities for path_file."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from datetime import datetime, timedelta
7
+
8
+ from path_file.exceptions import InvalidDurationError, InvalidSizeError
9
+
10
+ # ──────────────────────────────────────────────────────────────────────────────
11
+ # SIZE PARSING & FORMATTING
12
+ # ──────────────────────────────────────────────────────────────────────────────
13
+
14
+ _SIZE_PATTERN = re.compile(
15
+ r"""^\s*
16
+ (?P<value>[\d.]+)
17
+ \s*
18
+ (?P<unit>[KMGT]?i?B?)?
19
+ \s*$""",
20
+ re.IGNORECASE | re.VERBOSE,
21
+ )
22
+
23
+ _SIZE_MULTIPLIERS: dict[str, int] = {
24
+ "b": 1,
25
+ "kb": 1024,
26
+ "kib": 1024,
27
+ "mb": 1024**2,
28
+ "mib": 1024**2,
29
+ "gb": 1024**3,
30
+ "gib": 1024**3,
31
+ "tb": 1024**4,
32
+ "tib": 1024**4,
33
+ "pb": 1024**5,
34
+ "pib": 1024**5,
35
+ }
36
+
37
+
38
+ def parse_size(size: str | int | float) -> int:
39
+ """
40
+ Parse a human-readable size string into bytes.
41
+
42
+ Args:
43
+ size: Size specification (e.g., "100", "1KB", "2.5MB", "1GB", 1024)
44
+
45
+ Returns:
46
+ Size in bytes as integer
47
+
48
+ Raises:
49
+ InvalidSizeError: If the size specification is invalid
50
+
51
+ Examples:
52
+ >>> parse_size("100")
53
+ 100
54
+ >>> parse_size("1KB")
55
+ 1024
56
+ >>> parse_size("2.5 MB")
57
+ 2621440
58
+ >>> parse_size("1GB")
59
+ 1073741824
60
+ >>> parse_size(512)
61
+ 512
62
+ """
63
+ if isinstance(size, (int, float)):
64
+ if size < 0:
65
+ raise InvalidSizeError(str(size), "Size cannot be negative")
66
+ return int(size)
67
+
68
+ if not isinstance(size, str):
69
+ raise InvalidSizeError(str(size), "Size must be string or number")
70
+
71
+ size = size.strip()
72
+ if not size:
73
+ raise InvalidSizeError("", "Empty size specification")
74
+
75
+ match = _SIZE_PATTERN.match(size)
76
+ if not match:
77
+ raise InvalidSizeError(size, "Use format like '100B', '1KB', '2.5MB', '1GB'")
78
+
79
+ value_str = match.group("value")
80
+ unit = (match.group("unit") or "B").lower()
81
+
82
+ try:
83
+ value = float(value_str)
84
+ except ValueError:
85
+ raise InvalidSizeError(size, f"Invalid number: {value_str}") from None
86
+
87
+ if value < 0:
88
+ raise InvalidSizeError(size, "Size cannot be negative")
89
+
90
+ multiplier = _SIZE_MULTIPLIERS.get(unit)
91
+ if multiplier is None:
92
+ raise InvalidSizeError(
93
+ size, f"Unknown unit: {unit}. Use B, KB, MB, GB, TB (or KiB, MiB, etc.)"
94
+ )
95
+
96
+ return int(value * multiplier)
97
+
98
+
99
+ def human_size(size: int, precision: int = 2, binary: bool = True) -> str:
100
+ """
101
+ Format bytes into human-readable string.
102
+
103
+ Args:
104
+ size: Size in bytes
105
+ precision: Decimal places for formatted output
106
+ binary: Use binary units (KiB, MiB) if True, decimal (KB, MB) if False
107
+
108
+ Returns:
109
+ Human-readable size string
110
+
111
+ Examples:
112
+ >>> human_size(1024)
113
+ '1.00 KiB'
114
+ >>> human_size(1536)
115
+ '1.50 KiB'
116
+ >>> human_size(1024**2)
117
+ '1.00 MiB'
118
+ >>> human_size(1024**3 * 2.5)
119
+ '2.50 GiB'
120
+ """
121
+ if size < 0:
122
+ return f"-{human_size(-size, precision, binary)}"
123
+
124
+ if size == 0:
125
+ return "0 B"
126
+
127
+ units = (
128
+ ["B", "KiB", "MiB", "GiB", "TiB", "PiB"] if binary else ["B", "KB", "MB", "GB", "TB", "PB"]
129
+ )
130
+ base = 1024 if binary else 1000
131
+
132
+ import math
133
+
134
+ exponent = min(int(math.log(size, base)), len(units) - 1)
135
+ value = size / (base**exponent)
136
+
137
+ if exponent == 0:
138
+ return f"{int(value)} {units[0]}"
139
+
140
+ return f"{value:.{precision}f} {units[exponent]}"
141
+
142
+
143
+ # ──────────────────────────────────────────────────────────────────────────────
144
+ # DURATION PARSING & FORMATTING
145
+ # ──────────────────────────────────────────────────────────────────────────────
146
+
147
+ _DURATION_PATTERN = re.compile(
148
+ r"""^\s*
149
+ (?P<value>[\d.]+)
150
+ \s*
151
+ (?P<unit>
152
+ (?:milli)?seconds?|secs?|s
153
+ |minutes?|mins?|m
154
+ |hours?|hrs?|h
155
+ |days?|d
156
+ |weeks?|wks?|w
157
+ |months?|mos?|mon
158
+ |years?|yrs?|y
159
+ )?
160
+ \s*$""",
161
+ re.IGNORECASE | re.VERBOSE,
162
+ )
163
+
164
+ _DURATION_UNITS: dict[str, float] = {
165
+ "s": 1,
166
+ "sec": 1,
167
+ "second": 1,
168
+ "seconds": 1,
169
+ "m": 60,
170
+ "min": 60,
171
+ "minute": 60,
172
+ "minutes": 60,
173
+ "h": 3600,
174
+ "hr": 3600,
175
+ "hour": 3600,
176
+ "hours": 3600,
177
+ "d": 86400,
178
+ "day": 86400,
179
+ "days": 86400,
180
+ "w": 604800,
181
+ "wk": 604800,
182
+ "week": 604800,
183
+ "weeks": 604800,
184
+ "mon": 2592000,
185
+ "month": 2592000,
186
+ "months": 2592000,
187
+ "y": 31536000,
188
+ "yr": 31536000,
189
+ "year": 31536000,
190
+ "years": 31536000,
191
+ }
192
+
193
+
194
+ def parse_duration(duration: str | int | float | timedelta) -> timedelta:
195
+ """
196
+ Parse a human-readable duration string into timedelta.
197
+
198
+ Args:
199
+ duration: Duration specification (e.g., "7 days", "1h", "30m", 3600)
200
+
201
+ Returns:
202
+ timedelta object
203
+
204
+ Raises:
205
+ InvalidDurationError: If the duration specification is invalid
206
+
207
+ Examples:
208
+ >>> parse_duration("7 days")
209
+ datetime.timedelta(days=7)
210
+ >>> parse_duration("1h")
211
+ datetime.timedelta(seconds=3600)
212
+ >>> parse_duration("30m")
213
+ datetime.timedelta(seconds=1800)
214
+ >>> parse_duration("1 week")
215
+ datetime.timedelta(days=7)
216
+ >>> parse_duration(3600)
217
+ datetime.timedelta(seconds=3600)
218
+ """
219
+ if isinstance(duration, timedelta):
220
+ return duration
221
+
222
+ if isinstance(duration, (int, float)):
223
+ if duration < 0:
224
+ raise InvalidDurationError(str(duration), "Duration cannot be negative")
225
+ return timedelta(seconds=duration)
226
+
227
+ if not isinstance(duration, str):
228
+ raise InvalidDurationError(str(duration), "Duration must be string or number")
229
+
230
+ duration = duration.strip()
231
+ if not duration:
232
+ raise InvalidDurationError("", "Empty duration specification")
233
+
234
+ match = _DURATION_PATTERN.match(duration)
235
+ if not match:
236
+ raise InvalidDurationError(duration, "Use format like '7 days', '1h', '30m', '1 week'")
237
+
238
+ value_str = match.group("value")
239
+ unit = (match.group("unit") or "s").lower()
240
+
241
+ try:
242
+ value = float(value_str)
243
+ except ValueError:
244
+ raise InvalidDurationError(duration, f"Invalid number: {value_str}") from None
245
+
246
+ if value < 0:
247
+ raise InvalidDurationError(duration, "Duration cannot be negative")
248
+
249
+ multiplier = _DURATION_UNITS.get(unit)
250
+ if multiplier is None:
251
+ raise InvalidDurationError(
252
+ duration,
253
+ f"Unknown unit: {unit}. Use s, m, h, d, w, month, year",
254
+ )
255
+
256
+ return timedelta(seconds=value * multiplier)
257
+
258
+
259
+ def human_duration(td: timedelta, short: bool = False) -> str:
260
+ """
261
+ Format timedelta into human-readable string.
262
+
263
+ Args:
264
+ td: timedelta object
265
+ short: Use short format (e.g., "3d 4h" instead of "3 days 4 hours")
266
+
267
+ Returns:
268
+ Human-readable duration string
269
+
270
+ Examples:
271
+ >>> human_duration(timedelta(days=3, hours=4))
272
+ '3 days 4 hours'
273
+ >>> human_duration(timedelta(hours=25), short=True)
274
+ '1d 1h'
275
+ """
276
+ total_seconds = int(td.total_seconds())
277
+ if total_seconds < 0:
278
+ return f"-{human_duration(timedelta(seconds=-total_seconds), short)}"
279
+
280
+ if total_seconds == 0:
281
+ return "0s" if short else "0 seconds"
282
+
283
+ parts = []
284
+ units = (
285
+ [
286
+ ("y", 31536000),
287
+ ("d", 86400),
288
+ ("h", 3600),
289
+ ("m", 60),
290
+ ("s", 1),
291
+ ]
292
+ if short
293
+ else [
294
+ ("year", 31536000),
295
+ ("day", 86400),
296
+ ("hour", 3600),
297
+ ("minute", 60),
298
+ ("second", 1),
299
+ ]
300
+ )
301
+
302
+ for unit_name, unit_seconds in units:
303
+ if total_seconds >= unit_seconds:
304
+ count = total_seconds // unit_seconds
305
+ total_seconds %= unit_seconds
306
+ if short:
307
+ parts.append(f"{count}{unit_name}")
308
+ else:
309
+ suffix = "s" if count != 1 else ""
310
+ parts.append(f"{count} {unit_name}{suffix}")
311
+
312
+ return " ".join(parts) if not short else "".join(parts)
313
+
314
+
315
+ # ──────────────────────────────────────────────────────────────────────────────
316
+ # DATETIME PARSING & FORMATTING
317
+ # ──────────────────────────────────────────────────────────────────────────────
318
+
319
+ _RELATIVE_DATE_PATTERN = re.compile(
320
+ r"""^\s*(?P<keyword>today|yesterday|tomorrow|now)\s*$""", re.IGNORECASE
321
+ )
322
+
323
+
324
+ def parse_datetime(dt: str | datetime) -> datetime:
325
+ """
326
+ Parse a datetime string into datetime object.
327
+
328
+ Args:
329
+ dt: Datetime string (ISO format, "today", "yesterday", etc.)
330
+
331
+ Returns:
332
+ datetime object (naive, local time)
333
+
334
+ Examples:
335
+ >>> parse_datetime("2024-01-15")
336
+ datetime.datetime(2024, 1, 15, 0, 0)
337
+ >>> parse_datetime("2024-01-15 10:30")
338
+ datetime.datetime(2024, 1, 15, 10, 30)
339
+ >>> parse_datetime("today")
340
+ datetime.datetime(2024, ..., 0, 0) # today at midnight
341
+ """
342
+ if isinstance(dt, datetime):
343
+ return dt
344
+
345
+ if not isinstance(dt, str):
346
+ raise ValueError(f"Expected string or datetime, got {type(dt).__name__}")
347
+
348
+ dt = dt.strip()
349
+ if not dt:
350
+ raise ValueError("Empty datetime string")
351
+
352
+ # Relative keywords
353
+ match = _RELATIVE_DATE_PATTERN.match(dt)
354
+ if match:
355
+ keyword = match.group("keyword").lower()
356
+ now = datetime.now()
357
+ if keyword == "today":
358
+ return datetime(now.year, now.month, now.day)
359
+ elif keyword == "yesterday":
360
+ return datetime(now.year, now.month, now.day) - timedelta(days=1)
361
+ elif keyword == "tomorrow":
362
+ return datetime(now.year, now.month, now.day) + timedelta(days=1)
363
+ elif keyword == "now":
364
+ return now
365
+
366
+ # Try ISO formats
367
+ formats = [
368
+ "%Y-%m-%d %H:%M:%S.%f",
369
+ "%Y-%m-%d %H:%M:%S",
370
+ "%Y-%m-%d %H:%M",
371
+ "%Y-%m-%d",
372
+ "%Y/%m/%d %H:%M:%S",
373
+ "%Y/%m/%d %H:%M",
374
+ "%Y/%m/%d",
375
+ "%d.%m.%Y %H:%M:%S",
376
+ "%d.%m.%Y %H:%M",
377
+ "%d.%m.%Y",
378
+ ]
379
+
380
+ for fmt in formats:
381
+ try:
382
+ return datetime.strptime(dt, fmt)
383
+ except ValueError:
384
+ continue
385
+
386
+ raise ValueError(
387
+ f"Unable to parse datetime: {dt}. "
388
+ "Use ISO format (YYYY-MM-DD HH:MM:SS) or 'today', 'yesterday', etc."
389
+ )
390
+
391
+
392
+ def human_ago(dt: datetime) -> str:
393
+ """
394
+ Format datetime as relative time from now.
395
+
396
+ Args:
397
+ dt: datetime object (naive, assumed local time)
398
+
399
+ Returns:
400
+ Human-readable relative time string
401
+
402
+ Examples:
403
+ >>> human_ago(datetime.now() - timedelta(days=3))
404
+ '3 days ago'
405
+ >>> human_ago(datetime.now() + timedelta(hours=2))
406
+ 'in 2 hours'
407
+ >>> human_ago(datetime.now() - timedelta(seconds=30))
408
+ 'just now'
409
+ """
410
+ now = datetime.now()
411
+ diff = dt - now
412
+ total_seconds = int(diff.total_seconds())
413
+
414
+ if abs(total_seconds) < 60:
415
+ return "just now"
416
+
417
+ if total_seconds < 0:
418
+ return f"{human_duration(timedelta(seconds=-total_seconds))} ago"
419
+ else:
420
+ return f"in {human_duration(timedelta(seconds=total_seconds))}"