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,457 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ from . import (
8
+ json_utils,
9
+ file_utils,
10
+ string_utils,
11
+ config_utils,
12
+ system_utils,
13
+ security_utils,
14
+ time_utils,
15
+ validation_utils,
16
+ )
17
+
18
+
19
+ def add_json_commands(subparsers: argparse._SubParsersAction) -> None:
20
+ """Add JSON-related CLI commands."""
21
+ json_parser = subparsers.add_parser("json", help="JSON utilities")
22
+ json_sub = json_parser.add_subparsers(dest="json_cmd", required=True)
23
+
24
+ # Flatten JSON command
25
+ flatten_parser = json_sub.add_parser("flatten", help="Flatten JSON file to stdout")
26
+ flatten_parser.add_argument("path", type=Path, help="Path to JSON file")
27
+
28
+ # Pretty print JSON command
29
+ pretty_parser = json_sub.add_parser("pretty", help="Pretty print JSON file")
30
+ pretty_parser.add_argument("path", type=Path, help="Path to JSON file")
31
+
32
+
33
+ def add_file_commands(subparsers: argparse._SubParsersAction) -> None:
34
+ """Add file-related CLI commands."""
35
+ file_parser = subparsers.add_parser("file", help="File utilities")
36
+ file_sub = file_parser.add_subparsers(dest="file_cmd", required=True)
37
+
38
+ # Find file command
39
+ find_parser = file_sub.add_parser("find", help="Find files by name under a root directory")
40
+ find_parser.add_argument("name", help="Filename or glob pattern")
41
+ find_parser.add_argument(
42
+ "--root", type=Path, default=Path("."), help="Root directory to search"
43
+ )
44
+
45
+
46
+ def add_string_commands(subparsers: argparse._SubParsersAction) -> None:
47
+ """Add string manipulation CLI commands."""
48
+ string_parser = subparsers.add_parser("string", help="String manipulation utilities")
49
+ string_sub = string_parser.add_subparsers(dest="string_cmd", required=True)
50
+
51
+ # Case conversion command
52
+ convert_parser = string_sub.add_parser("convert", help="Convert string case")
53
+ convert_parser.add_argument("text", help="Text to convert")
54
+ convert_parser.add_argument(
55
+ "--to",
56
+ choices=["snake", "camel", "pascal", "kebab"],
57
+ required=True,
58
+ help="Target case format",
59
+ )
60
+
61
+ # Validation command
62
+ validate_parser = string_sub.add_parser("validate", help="Validate string format")
63
+ validate_parser.add_argument("text", help="Text to validate")
64
+ validate_parser.add_argument(
65
+ "--type", choices=["email", "url"], required=True, help="Validation type"
66
+ )
67
+
68
+ # Sanitize command
69
+ sanitize_parser = string_sub.add_parser("sanitize", help="Sanitize filename")
70
+ sanitize_parser.add_argument("filename", help="Filename to sanitize")
71
+
72
+
73
+ def add_config_commands(subparsers: argparse._SubParsersAction) -> None:
74
+ """Add configuration management CLI commands."""
75
+ config_parser = subparsers.add_parser("config", help="Configuration management utilities")
76
+ config_sub = config_parser.add_subparsers(dest="config_cmd", required=True)
77
+
78
+ # Load config command
79
+ load_parser = config_sub.add_parser("load", help="Load and display configuration")
80
+ load_parser.add_argument("path", type=Path, help="Path to configuration file")
81
+ load_parser.add_argument(
82
+ "--format",
83
+ choices=["json", "yaml", "toml", "env"],
84
+ help="Configuration format (auto-detected if not specified)",
85
+ )
86
+
87
+ # Merge configs command
88
+ merge_parser = config_sub.add_parser("merge", help="Merge multiple configuration files")
89
+ merge_parser.add_argument("files", nargs="+", type=Path, help="Configuration files to merge")
90
+ merge_parser.add_argument("--output", type=Path, help="Output file (stdout if not specified)")
91
+
92
+
93
+ def add_system_commands(subparsers: argparse._SubParsersAction) -> None:
94
+ """Add system utilities CLI commands."""
95
+ system_parser = subparsers.add_parser("system", help="System utilities")
96
+ system_sub = system_parser.add_subparsers(dest="system_cmd", required=True)
97
+
98
+ # System info command
99
+ info_parser = system_sub.add_parser("info", help="Display system information")
100
+ info_parser.add_argument(
101
+ "--format", choices=["json", "table"], default="table", help="Output format"
102
+ )
103
+
104
+ # Run command
105
+ run_parser = system_sub.add_parser("run", help="Run system command with timeout")
106
+ run_parser.add_argument("cmd", nargs="+", help="Command to run")
107
+ run_parser.add_argument("--timeout", type=float, help="Timeout in seconds")
108
+
109
+ # Find executable command
110
+ find_exec_parser = system_sub.add_parser("find-exec", help="Find executable in PATH")
111
+ find_exec_parser.add_argument("name", help="Executable name")
112
+
113
+
114
+ def add_security_commands(subparsers: argparse._SubParsersAction) -> None:
115
+ """Add security utilities CLI commands."""
116
+ security_parser = subparsers.add_parser("security", help="Security utilities")
117
+ security_sub = security_parser.add_subparsers(dest="security_cmd", required=True)
118
+
119
+ # Hash command
120
+ hash_parser = security_sub.add_parser("hash", help="Hash data")
121
+ hash_parser.add_argument("data", help="Data to hash")
122
+ hash_parser.add_argument(
123
+ "--algorithm", choices=["sha256", "sha512", "md5"], default="sha256", help="Hash algorithm"
124
+ )
125
+
126
+ # Generate secret command
127
+ secret_parser = security_sub.add_parser("generate-secret", help="Generate secret key")
128
+ secret_parser.add_argument("--length", type=int, default=32, help="Secret length")
129
+
130
+ # Generate UUID command
131
+ security_sub.add_parser("generate-uuid", help="Generate UUID")
132
+
133
+
134
+ def add_time_commands(subparsers: argparse._SubParsersAction) -> None:
135
+ """Add time utilities CLI commands."""
136
+ time_parser = subparsers.add_parser("time", help="Time utilities")
137
+ time_sub = time_parser.add_subparsers(dest="time_cmd", required=True)
138
+
139
+ # Parse date command
140
+ parse_parser = time_sub.add_parser("parse", help="Parse date string")
141
+ parse_parser.add_argument("date_string", help="Date string to parse")
142
+ parse_parser.add_argument("--format", help="Expected date format")
143
+
144
+ # Format duration command
145
+ duration_parser = time_sub.add_parser("duration", help="Format duration")
146
+ duration_parser.add_argument("seconds", type=float, help="Duration in seconds")
147
+
148
+ # Business day command
149
+ business_parser = time_sub.add_parser("business-day", help="Check if date is business day")
150
+ business_parser.add_argument("date", help="Date to check (YYYY-MM-DD)")
151
+
152
+
153
+ def add_validation_commands(subparsers: argparse._SubParsersAction) -> None:
154
+ """Add validation utilities CLI commands."""
155
+ validation_parser = subparsers.add_parser("validate", help="Validation utilities")
156
+ validation_sub = validation_parser.add_subparsers(dest="validation_cmd", required=True)
157
+
158
+ # Range validation command
159
+ range_parser = validation_sub.add_parser("range", help="Validate number range")
160
+ range_parser.add_argument("value", type=float, help="Value to validate")
161
+ range_parser.add_argument("--min", type=float, required=True, help="Minimum value")
162
+ range_parser.add_argument("--max", type=float, required=True, help="Maximum value")
163
+
164
+ # Length validation command
165
+ length_parser = validation_sub.add_parser("length", help="Validate string length")
166
+ length_parser.add_argument("text", help="Text to validate")
167
+ length_parser.add_argument("--min", type=int, default=0, help="Minimum length")
168
+ length_parser.add_argument("--max", type=int, help="Maximum length")
169
+
170
+
171
+ def execute_json_commands(args: argparse.Namespace) -> int:
172
+ """Execute JSON-related commands."""
173
+ if args.json_cmd == "flatten":
174
+ data = json_utils.load_json(args.path)
175
+ print(json_utils.pretty_json(json_utils.flatten_json(data)))
176
+ return 0
177
+ elif args.json_cmd == "pretty":
178
+ data = json_utils.load_json(args.path)
179
+ print(json_utils.pretty_json(data))
180
+ return 0
181
+ return 1
182
+
183
+
184
+ def execute_file_commands(args: argparse.Namespace) -> int:
185
+ """Execute file-related commands."""
186
+ if args.file_cmd == "find":
187
+ for p in file_utils.find_file(args.name, args.root):
188
+ print(p)
189
+ return 0
190
+ return 1
191
+
192
+
193
+ def execute_string_commands(args: argparse.Namespace) -> int:
194
+ """Execute string manipulation commands."""
195
+ if args.string_cmd == "convert":
196
+ text = args.text
197
+ if args.to == "snake":
198
+ result = string_utils.to_snake_case(text)
199
+ elif args.to == "camel":
200
+ result = string_utils.to_camel_case(text)
201
+ elif args.to == "pascal":
202
+ result = string_utils.to_pascal_case(text)
203
+ elif args.to == "kebab":
204
+ result = string_utils.to_kebab_case(text)
205
+ else:
206
+ return 1
207
+ print(result)
208
+ return 0
209
+ elif args.string_cmd == "validate":
210
+ text = args.text
211
+ if args.type == "email":
212
+ result = string_utils.validate_email(text)
213
+ elif args.type == "url":
214
+ result = string_utils.validate_url(text)
215
+ else:
216
+ return 1
217
+ print("Valid" if result else "Invalid")
218
+ return 0
219
+ elif args.string_cmd == "sanitize":
220
+ result = string_utils.sanitize_filename(args.filename)
221
+ print(result)
222
+ return 0
223
+ return 1
224
+
225
+
226
+ def execute_config_commands(args: argparse.Namespace) -> int:
227
+ """Execute configuration management commands."""
228
+ if args.config_cmd == "load":
229
+ try:
230
+ if args.format == "json" or (not args.format and args.path.suffix == ".json"):
231
+ data = json_utils.load_json(args.path)
232
+ elif args.format == "yaml" or (
233
+ not args.format and args.path.suffix in [".yaml", ".yml"]
234
+ ):
235
+ data = config_utils.load_yaml_config(args.path)
236
+ elif args.format == "toml" or (not args.format and args.path.suffix == ".toml"):
237
+ data = config_utils.load_toml_config(args.path)
238
+ elif args.format == "env" or (not args.format and args.path.suffix == ".env"):
239
+ data = config_utils.load_dotenv(args.path)
240
+ else:
241
+ print(f"Unsupported format or file extension: {args.path.suffix}")
242
+ return 1
243
+ print(json_utils.pretty_json(data))
244
+ return 0
245
+ except Exception as e:
246
+ print(f"Error loading config: {e}")
247
+ return 1
248
+ elif args.config_cmd == "merge":
249
+ try:
250
+ merged = {}
251
+ for file_path in args.files:
252
+ if file_path.suffix == ".json":
253
+ data = json_utils.load_json(file_path)
254
+ elif file_path.suffix in [".yaml", ".yml"]:
255
+ data = config_utils.load_yaml_config(file_path)
256
+ elif file_path.suffix == ".toml":
257
+ data = config_utils.load_toml_config(file_path)
258
+ else:
259
+ print(f"Unsupported file format: {file_path}")
260
+ return 1
261
+
262
+ # Import data_utils for deep_merge
263
+ from . import data_utils
264
+
265
+ merged = data_utils.deep_merge(merged, data)
266
+
267
+ result = json_utils.pretty_json(merged)
268
+ if args.output:
269
+ args.output.write_text(result)
270
+ print(f"Merged configuration saved to {args.output}")
271
+ else:
272
+ print(result)
273
+ return 0
274
+ except Exception as e:
275
+ print(f"Error merging configs: {e}")
276
+ return 1
277
+ return 1
278
+
279
+
280
+ def execute_system_commands(args: argparse.Namespace) -> int:
281
+ """Execute system utilities commands."""
282
+ if args.system_cmd == "info":
283
+ try:
284
+ info = system_utils.get_system_info()
285
+ python_info = system_utils.get_python_info()
286
+ combined_info = {**info, **python_info}
287
+
288
+ if args.format == "json":
289
+ print(json_utils.pretty_json(combined_info))
290
+ else:
291
+ # Table format
292
+ for key, value in combined_info.items():
293
+ print(f"{key:20}: {value}")
294
+ return 0
295
+ except Exception as e:
296
+ print(f"Error getting system info: {e}")
297
+ return 1
298
+ elif args.system_cmd == "run":
299
+ try:
300
+ result = system_utils.run_command(args.cmd, timeout=args.timeout)
301
+ print(result.stdout)
302
+ if result.stderr:
303
+ print(f"STDERR: {result.stderr}", file=sys.stderr)
304
+ return result.returncode
305
+ except Exception as e:
306
+ print(f"Error running command: {e}")
307
+ return 1
308
+ elif args.system_cmd == "find-exec":
309
+ try:
310
+ path = system_utils.find_executable(args.name)
311
+ if path:
312
+ print(path)
313
+ return 0
314
+ else:
315
+ print(f"Executable '{args.name}' not found")
316
+ return 1
317
+ except Exception as e:
318
+ print(f"Error finding executable: {e}")
319
+ return 1
320
+ return 1
321
+
322
+
323
+ def execute_security_commands(args: argparse.Namespace) -> int:
324
+ """Execute security utilities commands."""
325
+ if args.security_cmd == "hash":
326
+ try:
327
+ result = security_utils.hash_data(args.data, args.algorithm)
328
+ print(result)
329
+ return 0
330
+ except Exception as e:
331
+ print(f"Error hashing data: {e}")
332
+ return 1
333
+ elif args.security_cmd == "generate-secret":
334
+ try:
335
+ secret = security_utils.generate_secret_key(args.length)
336
+ print(secret)
337
+ return 0
338
+ except Exception as e:
339
+ print(f"Error generating secret: {e}")
340
+ return 1
341
+ elif args.security_cmd == "generate-uuid":
342
+ try:
343
+ uuid = security_utils.generate_uuid()
344
+ print(uuid)
345
+ return 0
346
+ except Exception as e:
347
+ print(f"Error generating UUID: {e}")
348
+ return 1
349
+ return 1
350
+
351
+
352
+ def execute_time_commands(args: argparse.Namespace) -> int:
353
+ """Execute time utilities commands."""
354
+ if args.time_cmd == "parse":
355
+ try:
356
+ formats = [args.format] if args.format else None
357
+ parsed_date = time_utils.parse_date(args.date_string, formats)
358
+ print(parsed_date.isoformat())
359
+ return 0
360
+ except Exception as e:
361
+ print(f"Error parsing date: {e}")
362
+ return 1
363
+ elif args.time_cmd == "duration":
364
+ try:
365
+ formatted = time_utils.format_duration(args.seconds)
366
+ print(formatted)
367
+ return 0
368
+ except Exception as e:
369
+ print(f"Error formatting duration: {e}")
370
+ return 1
371
+ elif args.time_cmd == "business-day":
372
+ try:
373
+ from datetime import datetime
374
+
375
+ date = datetime.fromisoformat(args.date)
376
+ is_business = time_utils.is_business_day(date)
377
+ print("Yes" if is_business else "No")
378
+ return 0
379
+ except Exception as e:
380
+ print(f"Error checking business day: {e}")
381
+ return 1
382
+ return 1
383
+
384
+
385
+ def execute_validation_commands(args: argparse.Namespace) -> int:
386
+ """Execute validation utilities commands."""
387
+ if args.validation_cmd == "range":
388
+ try:
389
+ is_valid = validation_utils.validate_range(args.value, args.min, args.max)
390
+ print("Valid" if is_valid else "Invalid")
391
+ return 0
392
+ except Exception as e:
393
+ print(f"Error validating range: {e}")
394
+ return 1
395
+ elif args.validation_cmd == "length":
396
+ try:
397
+ is_valid = validation_utils.validate_length(args.text, args.min, args.max)
398
+ print("Valid" if is_valid else "Invalid")
399
+ return 0
400
+ except Exception as e:
401
+ print(f"Error validating length: {e}")
402
+ return 1
403
+ return 1
404
+
405
+
406
+ def main(argv: list[str] | None = None) -> int:
407
+ """Main CLI entry point with command categories."""
408
+ parser = argparse.ArgumentParser(
409
+ prog="devkitx", description="Comprehensive developer quality-of-life utilities"
410
+ )
411
+ subparsers = parser.add_subparsers(
412
+ dest="command", required=True, help="Available command categories"
413
+ )
414
+
415
+ # Register all command categories
416
+ add_json_commands(subparsers)
417
+ add_file_commands(subparsers)
418
+ add_string_commands(subparsers)
419
+ add_config_commands(subparsers)
420
+ add_system_commands(subparsers)
421
+ add_security_commands(subparsers)
422
+ add_time_commands(subparsers)
423
+ add_validation_commands(subparsers)
424
+
425
+ args = parser.parse_args(argv)
426
+
427
+ # Execute commands based on category
428
+ try:
429
+ if args.command == "json":
430
+ return execute_json_commands(args)
431
+ elif args.command == "file":
432
+ return execute_file_commands(args)
433
+ elif args.command == "string":
434
+ return execute_string_commands(args)
435
+ elif args.command == "config":
436
+ return execute_config_commands(args)
437
+ elif args.command == "system":
438
+ return execute_system_commands(args)
439
+ elif args.command == "security":
440
+ return execute_security_commands(args)
441
+ elif args.command == "time":
442
+ return execute_time_commands(args)
443
+ elif args.command == "validate":
444
+ return execute_validation_commands(args)
445
+ else:
446
+ print(f"Unknown command: {args.command}")
447
+ return 1
448
+ except KeyboardInterrupt:
449
+ print("\nOperation cancelled by user")
450
+ return 130
451
+ except Exception as e:
452
+ print(f"Unexpected error: {e}")
453
+ return 1
454
+
455
+
456
+ if __name__ == "__main__":
457
+ raise SystemExit(main())