Clover/tools/commandline_tool.py
Jarian Cottingham 7e8d31af6e Clover created
2026-01-13 00:07:41 -06:00

91 lines
2.4 KiB
Python

"""
Command line execution tool for Clover - A terminal assistant for AI-powered project management
"""
import subprocess
import sys
import os
from pathlib import Path
def commandline(command, allow_execution=True):
"""
Execute a system command with user permission.
Args:
command (str): The command to execute
allow_execution (bool): Whether execution is allowed (default: True)
Returns:
str: Output of the command or permission prompt
Raises:
PermissionError: If execution is not permitted
subprocess.CalledProcessError: If command execution fails
"""
if not allow_execution:
return f"Command execution denied. Would execute: {command}"
try:
print(f"Executing command: {command}")
# Execute the command
result = subprocess.run(
command,
shell=True,
check=True,
text=True,
capture_output=True,
timeout=300 # 5 minute timeout
)
return result.stdout
except subprocess.CalledProcessError as e:
error_msg = f"Command failed with return code {e.returncode}\n"
if e.stderr:
error_msg += f"Error output: {e.stderr}"
return error_msg
except subprocess.TimeoutExpired:
return "Command timed out after 300 seconds"
except Exception as e:
return f"Error executing command '{command}': {str(e)}"
def safe_execute(command, permission_prompt=True):
"""
Safely execute a system command with optional permission prompt.
Args:
command (str): The command to execute
permission_prompt (bool): Whether to prompt for permission
Returns:
str: Command output or permission denial message
"""
if permission_prompt:
print(f"Permission needed to run: {command}")
response = input("Allow execution? (y/N): ")
if response.lower() not in ['y', 'yes']:
return "Execution denied by user"
return commandline(command)
# Example usage function
def example_usage():
"""
Example of how to use the command line tool.
"""
print("Command Line Tool Examples:")
# Example 1: Safe execution with prompt
result = safe_execute("echo 'Hello, Clover!'")
print(f"Result: {result}")
# Example 2: Direct execution
result = commandline("ls -la")
print(f"Directory listing: {result}")
if __name__ == "__main__":
example_usage()