devkitx 1.0.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,489 @@
1
+ """String manipulation utilities for DevKitX.
2
+
3
+ This module provides comprehensive string manipulation functions including
4
+ case conversions, validation, sanitization, and text processing utilities.
5
+ """
6
+
7
+ import re
8
+ from string import Template
9
+ from typing import Any
10
+
11
+ __all__ = [
12
+ "to_snake_case",
13
+ "to_camel_case",
14
+ "to_pascal_case",
15
+ "to_kebab_case",
16
+ "template_safe_substitute",
17
+ "validate_email",
18
+ "validate_url",
19
+ "sanitize_filename",
20
+ "normalize_whitespace",
21
+ "extract_urls",
22
+ "truncate_text",
23
+ ]
24
+
25
+
26
+ def to_snake_case(text: str) -> str:
27
+ """Convert text to snake_case.
28
+
29
+ Converts PascalCase, camelCase, kebab-case, and space-separated text to snake_case.
30
+
31
+ Args:
32
+ text: Input text to convert
33
+
34
+ Returns:
35
+ Text converted to snake_case
36
+
37
+ Examples:
38
+ >>> to_snake_case("HelloWorld")
39
+ 'hello_world'
40
+ >>> to_snake_case("helloWorld")
41
+ 'hello_world'
42
+ >>> to_snake_case("hello-world")
43
+ 'hello_world'
44
+ >>> to_snake_case("hello world")
45
+ 'hello_world'
46
+ """
47
+ if not text:
48
+ return ""
49
+
50
+ # Insert underscores before uppercase letters that follow lowercase letters or digits
51
+ text = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", text)
52
+
53
+ # Insert underscores between consecutive uppercase letters and following lowercase letters
54
+ text = re.sub(r"(?<=[A-Z])(?=[A-Z][a-z])", "_", text)
55
+
56
+ # Replace hyphens and spaces with underscores
57
+ text = re.sub(r"[-\s]+", "_", text)
58
+
59
+ # Convert to lowercase and remove multiple consecutive underscores
60
+ text = re.sub(r"_+", "_", text.lower())
61
+
62
+ # Remove leading/trailing underscores
63
+ return text.strip("_")
64
+
65
+
66
+ def to_camel_case(text: str) -> str:
67
+ """Convert text to camelCase.
68
+
69
+ Converts snake_case, kebab-case, PascalCase, and space-separated text to camelCase.
70
+
71
+ Args:
72
+ text: Input text to convert
73
+
74
+ Returns:
75
+ Text converted to camelCase
76
+
77
+ Examples:
78
+ >>> to_camel_case("hello_world")
79
+ 'helloWorld'
80
+ >>> to_camel_case("hello-world")
81
+ 'helloWorld'
82
+ >>> to_camel_case("hello world")
83
+ 'helloWorld'
84
+ >>> to_camel_case("HelloWorld")
85
+ 'helloWorld'
86
+ """
87
+ if not text:
88
+ return ""
89
+
90
+ # Split on common delimiters and camelCase boundaries
91
+ words = re.split(r"[-_\s]+|(?<=[a-z])(?=[A-Z])", text)
92
+
93
+ # Filter out empty strings
94
+ words = [word for word in words if word]
95
+
96
+ if not words:
97
+ return ""
98
+
99
+ # First word lowercase, rest capitalized
100
+ result = words[0].lower()
101
+ for word in words[1:]:
102
+ result += word.capitalize()
103
+
104
+ return result
105
+
106
+
107
+ def to_pascal_case(text: str) -> str:
108
+ """Convert text to PascalCase.
109
+
110
+ Converts snake_case, kebab-case, camelCase, and space-separated text to PascalCase.
111
+
112
+ Args:
113
+ text: Input text to convert
114
+
115
+ Returns:
116
+ Text converted to PascalCase
117
+
118
+ Examples:
119
+ >>> to_pascal_case("hello_world")
120
+ 'HelloWorld'
121
+ >>> to_pascal_case("hello-world")
122
+ 'HelloWorld'
123
+ >>> to_pascal_case("hello world")
124
+ 'HelloWorld'
125
+ >>> to_pascal_case("helloWorld")
126
+ 'HelloWorld'
127
+ """
128
+ if not text:
129
+ return ""
130
+
131
+ # Split on common delimiters and camelCase boundaries
132
+ words = re.split(r"[-_\s]+|(?<=[a-z])(?=[A-Z])", text)
133
+
134
+ # Filter out empty strings and capitalize each word
135
+ return "".join(word.capitalize() for word in words if word)
136
+
137
+
138
+ def to_kebab_case(text: str) -> str:
139
+ """Convert text to kebab-case.
140
+
141
+ Converts snake_case, PascalCase, camelCase, and space-separated text to kebab-case.
142
+
143
+ Args:
144
+ text: Input text to convert
145
+
146
+ Returns:
147
+ Text converted to kebab-case
148
+
149
+ Examples:
150
+ >>> to_kebab_case("HelloWorld")
151
+ 'hello-world'
152
+ >>> to_kebab_case("hello_world")
153
+ 'hello-world'
154
+ >>> to_kebab_case("hello world")
155
+ 'hello-world'
156
+ >>> to_kebab_case("helloWorld")
157
+ 'hello-world'
158
+ """
159
+ if not text:
160
+ return ""
161
+
162
+ # Insert hyphens before uppercase letters that follow lowercase letters or digits
163
+ text = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "-", text)
164
+
165
+ # Insert hyphens between consecutive uppercase letters and following lowercase letters
166
+ text = re.sub(r"(?<=[A-Z])(?=[A-Z][a-z])", "-", text)
167
+
168
+ # Replace underscores and spaces with hyphens
169
+ text = re.sub(r"[_\s]+", "-", text)
170
+
171
+ # Convert to lowercase and remove multiple consecutive hyphens
172
+ text = re.sub(r"-+", "-", text.lower())
173
+
174
+ # Remove leading/trailing hyphens
175
+ return text.strip("-")
176
+
177
+
178
+ def template_safe_substitute(template: str, **kwargs: Any) -> str:
179
+ """Safely substitute variables in a template string.
180
+
181
+ Uses Python's string.Template for safe substitution. Missing variables are left as-is.
182
+
183
+ Args:
184
+ template: Template string with $variable or ${variable} placeholders
185
+ **kwargs: Variables to substitute
186
+
187
+ Returns:
188
+ Template with variables substituted
189
+
190
+ Examples:
191
+ >>> template_safe_substitute("Hello $name!", name="World")
192
+ 'Hello World!'
193
+ >>> template_safe_substitute("$greeting $name", greeting="Hi", name="Alice")
194
+ 'Hi Alice'
195
+ >>> template_safe_substitute("Hello $name and $missing", name="Bob")
196
+ 'Hello Bob and $missing'
197
+ """
198
+ if not isinstance(template, str):
199
+ return str(template)
200
+
201
+ try:
202
+ tmpl = Template(template)
203
+ # Use safe_substitute to leave missing variables as-is
204
+ return tmpl.safe_substitute(**kwargs)
205
+ except (ValueError, KeyError):
206
+ # If template is malformed, return original
207
+ return template
208
+
209
+
210
+ def validate_email(email: str) -> bool:
211
+ """Validate email address format.
212
+
213
+ Uses a comprehensive regex pattern to validate email addresses according to RFC 5322.
214
+
215
+ Args:
216
+ email: Email address to validate
217
+
218
+ Returns:
219
+ True if email is valid, False otherwise
220
+
221
+ Examples:
222
+ >>> validate_email("user@example.com")
223
+ True
224
+ >>> validate_email("invalid.email")
225
+ False
226
+ >>> validate_email("user+tag@example.co.uk")
227
+ True
228
+ """
229
+ if not email or not isinstance(email, str):
230
+ return False
231
+
232
+ # Additional checks for edge cases
233
+ if len(email) > 254: # RFC 5321 limit
234
+ return False
235
+
236
+ if ".." in email: # No consecutive dots
237
+ return False
238
+
239
+ if email.startswith(".") or email.endswith("."): # No leading/trailing dots
240
+ return False
241
+
242
+ if "@" not in email or email.count("@") != 1:
243
+ return False
244
+
245
+ local_part, domain = email.split("@")
246
+
247
+ if len(local_part) > 64: # RFC 5321 local part limit
248
+ return False
249
+
250
+ if not local_part or not domain:
251
+ return False
252
+
253
+ # Check for invalid characters in local part
254
+ if not re.match(r"^[a-zA-Z0-9._%+-]+$", local_part):
255
+ return False
256
+
257
+ # Check domain format
258
+ if domain.startswith(".") or domain.endswith("."):
259
+ return False
260
+
261
+ if ".." in domain:
262
+ return False
263
+
264
+ # Domain must have at least one dot and valid TLD
265
+ if "." not in domain:
266
+ return False
267
+
268
+ # Check domain pattern
269
+ domain_pattern = r"^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
270
+ return bool(re.match(domain_pattern, domain))
271
+
272
+
273
+ def validate_url(url: str) -> bool:
274
+ """Validate URL format.
275
+
276
+ Validates URLs with common schemes (http, https, ftp, ftps).
277
+
278
+ Args:
279
+ url: URL to validate
280
+
281
+ Returns:
282
+ True if URL is valid, False otherwise
283
+
284
+ Examples:
285
+ >>> validate_url("https://example.com")
286
+ True
287
+ >>> validate_url("http://localhost:8080/path")
288
+ True
289
+ >>> validate_url("invalid-url")
290
+ False
291
+ >>> validate_url("ftp://files.example.com/file.txt")
292
+ True
293
+ """
294
+ if not url or not isinstance(url, str):
295
+ return False
296
+
297
+ # URL regex pattern supporting common schemes
298
+ pattern = r"^(https?|ftp)://[^\s/$.?#].[^\s]*$"
299
+
300
+ # Basic length check
301
+ if len(url) > 2048: # Common URL length limit
302
+ return False
303
+
304
+ return bool(re.match(pattern, url, re.IGNORECASE))
305
+
306
+
307
+ def sanitize_filename(filename: str) -> str:
308
+ """Sanitize filename for cross-platform compatibility.
309
+
310
+ Removes or replaces characters that are invalid in filenames on Windows, macOS, or Linux.
311
+
312
+ Args:
313
+ filename: Filename to sanitize
314
+
315
+ Returns:
316
+ Sanitized filename safe for use on all platforms
317
+
318
+ Examples:
319
+ >>> sanitize_filename("file<name>.txt")
320
+ 'file_name_.txt'
321
+ >>> sanitize_filename("my/file\\name.doc")
322
+ 'my_file_name.doc'
323
+ >>> sanitize_filename("CON.txt") # Windows reserved name
324
+ 'CON_.txt'
325
+ """
326
+ if not isinstance(filename, str):
327
+ return ""
328
+
329
+ if not filename:
330
+ return "file"
331
+
332
+ # Remove or replace invalid characters
333
+ # Invalid chars: < > : " | ? * \ /
334
+ invalid_chars = r'[<>:"|?*\\/]'
335
+ sanitized = re.sub(invalid_chars, "_", filename)
336
+
337
+ # Remove control characters (0-31)
338
+ sanitized = re.sub(r"[\x00-\x1f]", "", sanitized)
339
+
340
+ # Remove leading/trailing spaces and dots
341
+ sanitized = sanitized.strip(" .")
342
+
343
+ # Handle Windows reserved names
344
+ reserved_names = {
345
+ "CON",
346
+ "PRN",
347
+ "AUX",
348
+ "NUL",
349
+ "COM1",
350
+ "COM2",
351
+ "COM3",
352
+ "COM4",
353
+ "COM5",
354
+ "COM6",
355
+ "COM7",
356
+ "COM8",
357
+ "COM9",
358
+ "LPT1",
359
+ "LPT2",
360
+ "LPT3",
361
+ "LPT4",
362
+ "LPT5",
363
+ "LPT6",
364
+ "LPT7",
365
+ "LPT8",
366
+ "LPT9",
367
+ }
368
+
369
+ name_part = sanitized.split(".")[0].upper()
370
+ if name_part in reserved_names:
371
+ sanitized = sanitized + "_"
372
+
373
+ # Ensure filename is not empty and not too long
374
+ if not sanitized:
375
+ sanitized = "file"
376
+
377
+ # Limit length to 255 characters (common filesystem limit)
378
+ if len(sanitized) > 255:
379
+ name, ext = sanitized.rsplit(".", 1) if "." in sanitized else (sanitized, "")
380
+ max_name_len = 255 - len(ext) - (1 if ext else 0)
381
+ sanitized = name[:max_name_len] + ("." + ext if ext else "")
382
+
383
+ return sanitized
384
+
385
+
386
+ def normalize_whitespace(text: str) -> str:
387
+ """Normalize whitespace in text.
388
+
389
+ Replaces multiple consecutive whitespace characters with single spaces,
390
+ and strips leading/trailing whitespace.
391
+
392
+ Args:
393
+ text: Text to normalize
394
+
395
+ Returns:
396
+ Text with normalized whitespace
397
+
398
+ Examples:
399
+ >>> normalize_whitespace(" hello world ")
400
+ 'hello world'
401
+ >>> normalize_whitespace("line1\\n\\n\\nline2")
402
+ 'line1 line2'
403
+ >>> normalize_whitespace("tab\\t\\ttab")
404
+ 'tab tab'
405
+ """
406
+ if not isinstance(text, str):
407
+ return str(text)
408
+
409
+ # Replace all whitespace sequences with single spaces
410
+ normalized = re.sub(r"\s+", " ", text)
411
+
412
+ # Strip leading and trailing whitespace
413
+ return normalized.strip()
414
+
415
+
416
+ def extract_urls(text: str) -> list[str]:
417
+ """Extract URLs from text.
418
+
419
+ Finds URLs with common schemes (http, https, ftp, ftps) in the given text.
420
+
421
+ Args:
422
+ text: Text to extract URLs from
423
+
424
+ Returns:
425
+ List of URLs found in text
426
+
427
+ Examples:
428
+ >>> extract_urls("Visit https://example.com for more info")
429
+ ['https://example.com']
430
+ >>> extract_urls("Check http://site1.com and https://site2.org")
431
+ ['http://site1.com', 'https://site2.org']
432
+ >>> extract_urls("No URLs here")
433
+ []
434
+ """
435
+ if not isinstance(text, str):
436
+ return []
437
+
438
+ # URL pattern for common schemes
439
+ url_pattern = r'https?://[^\s<>"{}|\\^`\[\]]+|ftp://[^\s<>"{}|\\^`\[\]]+'
440
+
441
+ urls = re.findall(url_pattern, text, re.IGNORECASE)
442
+
443
+ # Filter out URLs that end with punctuation that's likely not part of the URL
444
+ cleaned_urls = []
445
+ for url in urls:
446
+ # Remove trailing punctuation that's commonly not part of URLs
447
+ url = re.sub(r'[.,;:!?)\]}>"\']$', "", url)
448
+ if url:
449
+ cleaned_urls.append(url)
450
+
451
+ return cleaned_urls
452
+
453
+
454
+ def truncate_text(text: str, max_length: int, suffix: str = "...") -> str:
455
+ """Truncate text to maximum length with suffix.
456
+
457
+ If text is longer than max_length, truncates it and adds suffix.
458
+ The total length including suffix will not exceed max_length.
459
+
460
+ Args:
461
+ text: Text to truncate
462
+ max_length: Maximum length of result
463
+ suffix: Suffix to append if truncated
464
+
465
+ Returns:
466
+ Truncated text with suffix if needed
467
+
468
+ Examples:
469
+ >>> truncate_text("Hello World", 10)
470
+ 'Hello W...'
471
+ >>> truncate_text("Short", 10)
472
+ 'Short'
473
+ >>> truncate_text("Long text here", 8, ">>")
474
+ 'Long t>>'
475
+ """
476
+ if not isinstance(text, str):
477
+ text = str(text)
478
+
479
+ if max_length <= 0:
480
+ return ""
481
+
482
+ if len(text) <= max_length:
483
+ return text
484
+
485
+ if len(suffix) >= max_length:
486
+ return suffix[:max_length]
487
+
488
+ truncate_at = max_length - len(suffix)
489
+ return text[:truncate_at] + suffix