commit ddf991810b4e13478b2056236229aa5253d81269
parent 3fa25344f494e66071fd15f3719d796cf9ca3a67
Author: Carlosokumu <carlosokumu254@gmail.com>
Date: Mon, 1 Sep 2025 12:53:46 +0300
add helper functions
Diffstat:
| A | ungana/utils.py | | | 56 | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
1 file changed, 56 insertions(+), 0 deletions(-)
diff --git a/ungana/utils.py b/ungana/utils.py
@@ -0,0 +1,55 @@
+import argparse
+from datetime import datetime, timedelta
+import re
+import uuid
+
+
+def parse_duration(duration_str: str):
+ duration_str = duration_str.replace(",", "").strip()
+ hours, minutes = 0, 0
+ if "h" in duration_str:
+ parts = duration_str.split("h")
+ hours = int(parts[0]) if parts[0] else 0
+ if len(parts) > 1 and "m" in parts[1]:
+ minutes = int(parts[1].replace("m", "").strip() or 0)
+ elif "m" in duration_str:
+ minutes = int(duration_str.replace("m", "").strip() or 0)
+
+ return timedelta(hours=hours, minutes=minutes)
+
+def parse_datetime(dt_str: str) -> datetime:
+ formats = ["%Y-%m-%d %H:%M", "%d-%m-%Y %H:%M"]
+ for fmt in formats:
+ try:
+ return datetime.strptime(dt_str, fmt)
+ except ValueError:
+ continue
+ raise ValueError(f"Invalid datetime format: {dt_str}. Expected one of {formats}")
+
+
+def generate_uid(domain: str) -> str:
+ """Generate a globally unique UID using UUID + domain style."""
+ return f"{uuid.uuid4()}@{domain}"
+
+
+def validate_datetime(dt_str: str) -> str:
+ try:
+ dt = datetime.fromisoformat(dt_str)
+ return dt.isoformat()
+ except ValueError:
+ pass
+ try:
+ dt = datetime.strptime(dt_str, "%d-%m-%Y %H:%M")
+ return dt.isoformat()
+ except ValueError:
+ pass
+
+ raise argparse.ArgumentTypeError(f"Invalid datetime format: '{dt_str}'. ""Expected ISO format (YYYY-MM-DDTHH:MM:SS+ZZ:ZZ) or DD-MM-YYYY HH:MM")
+
+
+
+def validate_duration(duration_str: str) -> str:
+ """Validate duration format (e.g., '2h' or '30m')."""
+ if not re.match(r'^(\d+h)?(\d+m)?$', duration_str):
+ raise argparse.ArgumentTypeError(f"Invalid duration format: '{duration_str}'. Expected format like '2h' or '30m'" )
+ return duration_str
+\ No newline at end of file