-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
398 lines (334 loc) · 16.6 KB
/
Copy pathcli.py
File metadata and controls
398 lines (334 loc) · 16.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
#!/usr/bin/env python3
"""
Universal Command Wrapper (UCW) - SMCP Plugin
SMCP-compatible plugin for generating Python wrappers for system commands.
"""
import argparse
import json
import sys
from pathlib import Path
from typing import Dict, Any
from __init__ import UniversalCommandWrapper
def main():
"""Main SMCP plugin entry point."""
parser = argparse.ArgumentParser(
description="Universal Command Wrapper (UCW) - SMCP Plugin for generating Python wrappers for system commands"
)
# Global options
parser.add_argument("--standalone", "--human", action="store_true",
help="Use human-readable output instead of JSON (for standalone usage)")
parser.add_argument("--describe", action="store_true", help=argparse.SUPPRESS)
subparsers = parser.add_subparsers(dest="command", help="Available commands")
# Add commands
setup_wrap_command(subparsers)
setup_parse_command(subparsers)
setup_execute_command(subparsers)
args = parser.parse_args()
if getattr(args, "describe", False):
print(json.dumps({
"contract_version": "1.0",
"plugin": {"name": "ucw", "version": "0.1.0", "description": "Universal Command Wrapper - wrap, parse, execute system commands"},
"commands": [
{"name": "wrap", "description": "Wrap a system command", "parameters": [{"name": "command_name", "type": "string", "description": "Name of the command to wrap", "required": True}, {"name": "output", "type": "string", "description": "Output file path", "required": False}, {"name": "update", "type": "boolean", "description": "Update existing file", "required": False}, {"name": "platform", "type": "string", "description": "Target platform", "required": False, "default": "auto"}, {"name": "timeout_help", "type": "integer", "description": "Timeout for help in seconds", "required": False, "default": 10}, {"name": "timeout_exec", "type": "integer", "description": "Timeout for execution in seconds", "required": False, "default": 30}]},
{"name": "parse", "description": "Parse command help text", "parameters": [{"name": "command_name", "type": "string", "description": "Name of the command to parse", "required": True}, {"name": "platform", "type": "string", "description": "Target platform", "required": False, "default": "auto"}, {"name": "timeout_help", "type": "integer", "description": "Timeout for help in seconds", "required": False, "default": 10}, {"name": "timeout_exec", "type": "integer", "description": "Timeout for execution in seconds", "required": False, "default": 30}]},
{"name": "execute", "description": "Execute a command", "parameters": [{"name": "command_name", "type": "string", "description": "Name of the command to execute", "required": True}, {"name": "args", "type": "array", "description": "Positional arguments", "required": False}, {"name": "options", "type": "string", "description": "JSON string of options", "required": False, "default": "{}"}, {"name": "platform", "type": "string", "description": "Target platform", "required": False, "default": "auto"}, {"name": "timeout_help", "type": "integer", "description": "Timeout for help in seconds", "required": False, "default": 10}, {"name": "timeout_exec", "type": "integer", "description": "Timeout for execution in seconds", "required": False, "default": 30}]}
]
}))
sys.exit(0)
if not args.command:
parser.print_help()
sys.exit(1)
try:
# Execute the appropriate command and return JSON result
if args.command == "wrap":
result = execute_wrap_command(args)
elif args.command == "parse":
result = execute_parse_command(args)
elif args.command == "execute":
result = execute_execute_command(args)
else:
result = {"status": "error", "error": f"Unknown command: {args.command}"}
# Output result based on mode
if args.standalone:
print_human_readable(result)
else:
# Output JSON result for SMCP compatibility
print(json.dumps(result, indent=2))
# Exit with error code if there was an error
if result.get("status") == "error":
sys.exit(1)
except Exception as e:
error_result = {"status": "error", "error": str(e)}
if args.standalone:
print(f"Error: {error_result['error']}")
else:
print(json.dumps(error_result, indent=2))
sys.exit(1)
def print_human_readable(result: Dict[str, Any]):
"""Print result in human-readable format for standalone usage."""
if result.get("status") == "error":
print(f"Error: {result['error']}")
return
if result.get("status") != "success":
print(f"Unknown status: {result.get('status', 'unknown')}")
return
# Handle wrap command results
if "message" in result and "spec" in result:
print(result["message"])
if "output_file" in result:
print(f"Output file: {result['output_file']}")
if result.get("update_mode"):
print("Mode: Updated existing file")
else:
print("Mode: Created new file")
return
# Show command specification
spec = result["spec"]
print(f"\nCommand: {spec['name']}")
print(f"Usage: {spec['usage']}")
if spec.get("description"):
print(f"Description: {spec['description']}")
# Show positional arguments
if spec.get("positional_args"):
print(f"\nPositional arguments:")
for i, arg in enumerate(spec["positional_args"]):
req_str = "required" if arg["required"] else "optional"
var_str = " (variadic)" if arg["variadic"] else ""
print(f" {i+1}. {arg['name']} ({req_str}, {arg['type_hint']}){var_str}")
# Show options
if spec.get("options"):
print(f"\nAvailable options:")
for option in spec["options"]:
value_indicator = " <value>" if option["takes_value"] else ""
print(f" {option['flag']}{value_indicator}: {option['description'] or 'No description'}")
# Handle parse command results
elif "spec" in result:
spec = result["spec"]
print(f"Parsed command: {spec['name']}")
print(f"Usage: {spec['usage']}")
if spec.get("description"):
print(f"Description: {spec['description']}")
# Show positional arguments
if spec.get("positional_args"):
print(f"\nPositional arguments:")
for i, arg in enumerate(spec["positional_args"]):
req_str = "required" if arg["required"] else "optional"
var_str = " (variadic)" if arg["variadic"] else ""
print(f" {i+1}. {arg['name']} ({req_str}, {arg['type_hint']}){var_str}")
# Show options
if spec.get("options"):
print(f"\nAvailable options:")
for option in spec["options"]:
value_indicator = " <value>" if option["takes_value"] else ""
print(f" {option['flag']}{value_indicator}: {option['description'] or 'No description'}")
# Handle execute command results
elif "execution" in result:
exec_info = result["execution"]
print(f"Executed command: {result['command']}")
print(f"Command line: {exec_info['command_line']}")
print(f"Return code: {exec_info['return_code']}")
print(f"Success: {exec_info['success']}")
print(f"Elapsed time: {exec_info['elapsed']:.3f}s")
if exec_info.get("stdout"):
print(f"\nOutput:")
print(exec_info["stdout"].rstrip())
if exec_info.get("stderr"):
print(f"\nErrors:")
print(exec_info["stderr"].rstrip())
# Handle other success messages
elif "message" in result:
print(result["message"])
else:
print("Command completed successfully")
def setup_wrap_command(subparsers):
"""Setup the wrap command."""
parser = subparsers.add_parser("wrap", help="Wrap a system command")
parser.add_argument("command_name", help="Name of the command to wrap")
parser.add_argument("--output", "-o", help="Output file path")
parser.add_argument("--update", "-u", action="store_true",
help="Update existing file")
parser.add_argument("--platform", choices=["windows", "posix", "linux", "auto"],
default="auto", help="Target platform")
parser.add_argument("--timeout-help", type=int, default=10,
help="Timeout for help commands in seconds (default: 10)")
parser.add_argument("--timeout-exec", type=int, default=30,
help="Timeout for command execution in seconds (default: 30)")
def setup_parse_command(subparsers):
"""Setup the parse command."""
parser = subparsers.add_parser("parse", help="Parse command help text", description="Parse command help text")
parser.add_argument("command_name", help="Name of the command to parse")
parser.add_argument("--platform", choices=["windows", "posix", "linux", "auto"],
default="auto", help="Target platform")
parser.add_argument("--timeout-help", type=int, default=10,
help="Timeout for help commands in seconds (default: 10)")
parser.add_argument("--timeout-exec", type=int, default=30,
help="Timeout for command execution in seconds (default: 30)")
def setup_execute_command(subparsers):
"""Setup the execute command."""
parser = subparsers.add_parser("execute", help="Execute a command", description="Execute a command")
parser.add_argument("command_name", help="Name of the command to execute")
parser.add_argument("--args", nargs="*", help="Positional arguments")
parser.add_argument("--options", default="{}", help="JSON string of options")
parser.add_argument("--platform", choices=["windows", "posix", "linux", "auto"],
default="auto", help="Target platform")
parser.add_argument("--timeout-help", type=int, default=10,
help="Timeout for help commands in seconds (default: 10)")
parser.add_argument("--timeout-exec", type=int, default=30,
help="Timeout for command execution in seconds (default: 30)")
def execute_wrap_command(args) -> Dict[str, Any]:
"""Execute the wrap command."""
try:
# Validate timeout values
if args.timeout_help <= 0 or args.timeout_exec <= 0:
return {"status": "error", "error": "Timeout values must be positive"}
# Initialize UCW
platform_name = args.platform if args.platform != "auto" else None
ucw = UniversalCommandWrapper(
platform_name=platform_name,
timeout_help=args.timeout_help,
timeout_exec=args.timeout_exec
)
if args.output:
# Generate file
try:
file_path = ucw.write_wrapper(
args.command_name,
output=args.output,
update=args.update
)
return {
"status": "success",
"message": f"Generated wrapper for '{args.command_name}' in {file_path}",
"command": args.command_name,
"output_file": file_path,
"update_mode": args.update
}
except (OSError, IOError) as e:
return {"status": "error", "error": str(e)}
else:
# Generate in-memory wrapper
wrapper = ucw.write_wrapper(args.command_name)
# Prepare result data
result = {
"status": "success",
"message": f"Generated wrapper for '{args.command_name}'",
"command": args.command_name,
"spec": {
"name": wrapper.spec.name,
"usage": wrapper.spec.usage,
"description": wrapper.spec.description,
"positional_args": [],
"options": []
}
}
# Add positional arguments
if wrapper.spec.positional_args:
result["spec"]["positional_args"] = [
{
"name": arg.name,
"required": arg.required,
"variadic": arg.variadic,
"type_hint": arg.type_hint
}
for arg in wrapper.spec.positional_args
]
# Add options
if wrapper.spec.options:
result["spec"]["options"] = [
{
"flag": option.flag,
"takes_value": option.takes_value,
"description": option.description,
"type_hint": option.type_hint
}
for option in wrapper.spec.options
]
return result
except Exception as e:
return {"status": "error", "error": str(e)}
def execute_parse_command(args) -> Dict[str, Any]:
"""Execute the parse command."""
try:
# Validate timeout values
if args.timeout_help <= 0 or args.timeout_exec <= 0:
return {"status": "error", "error": "Timeout values must be positive"}
# Initialize UCW
platform_name = args.platform if args.platform != "auto" else None
ucw = UniversalCommandWrapper(
platform_name=platform_name,
timeout_help=args.timeout_help,
timeout_exec=args.timeout_exec
)
# Parse command
spec = ucw.parse_command(args.command_name)
return {
"status": "success",
"command": args.command_name,
"spec": {
"name": spec.name,
"usage": spec.usage,
"description": spec.description,
"positional_args": [
{
"name": arg.name,
"required": arg.required,
"variadic": arg.variadic,
"type_hint": arg.type_hint
}
for arg in spec.positional_args
],
"options": [
{
"flag": option.flag,
"takes_value": option.takes_value,
"description": option.description,
"type_hint": option.type_hint
}
for option in spec.options
]
}
}
except Exception as e:
return {"status": "error", "error": str(e)}
def execute_execute_command(args) -> Dict[str, Any]:
"""Execute the execute command."""
try:
# Validate timeout values
if args.timeout_help <= 0 or args.timeout_exec <= 0:
return {"status": "error", "error": "Timeout values must be positive"}
# Initialize UCW
platform_name = args.platform if args.platform != "auto" else None
ucw = UniversalCommandWrapper(
platform_name=platform_name,
timeout_help=args.timeout_help,
timeout_exec=args.timeout_exec
)
# Parse command and build wrapper
spec = ucw.parse_command(args.command_name)
wrapper = ucw.build_wrapper(spec)
# Parse options if provided
options = {}
if args.options:
try:
options = json.loads(args.options)
except json.JSONDecodeError as e:
return {"status": "error", "error": f"Invalid JSON options: {e}"}
# Execute command
positional_args = args.args if args.args is not None else []
result = wrapper.run(*positional_args, **options)
return {
"status": "success",
"command": args.command_name,
"execution": {
"command_line": result.command,
"return_code": result.return_code,
"success": result.success,
"elapsed": result.elapsed,
"stdout": result.stdout,
"stderr": result.stderr
}
}
except Exception as e:
return {"status": "error", "error": str(e)}
if __name__ == "__main__":
main()