// retoor <retoor@molodetz.nl>
import "subprocess" for Subprocess, ProcessResult
System.print("=== Subprocess Module Demo ===\n")
System.print("--- Running Shell Commands ---")
var result = Subprocess.run("echo 'Hello from subprocess!'")
System.print("stdout: %(result.stdout.trim())")
System.print("exit code: %(result.exitCode)")
System.print("success: %(result.success)")
System.print("\n--- Running with Arguments List ---")
var lsResult = Subprocess.run(["/bin/ls", "-la", "/tmp"])
System.print("Directory listing (first 200 chars):")
var output = lsResult.stdout
if (output.count > 200) output = output[0...200] + "..."
System.print(output)
System.print("\n--- Getting Current Directory ---")
var pwdResult = Subprocess.run("pwd")
System.print("Current directory: %(pwdResult.stdout.trim())")
System.print("\n--- Environment Variables ---")
var envResult = Subprocess.run("echo $USER@$HOSTNAME")
System.print("User info: %(envResult.stdout.trim())")
System.print("\n--- Piped Commands ---")
var pipeResult = Subprocess.run("echo 'apple\nbanana\ncherry' | sort -r")
System.print("Sorted output:")
System.print(pipeResult.stdout)
System.print("--- Command with Stderr ---")
var errResult = Subprocess.run("ls /nonexistent_directory_12345 2>&1")
System.print("Output: %(errResult.stdout.trim())")
System.print("Exit code: %(errResult.exitCode)")
System.print("Success: %(errResult.success)")
System.print("\n--- Capturing Both Stdout and Stderr ---")
var mixedResult = Subprocess.run("echo 'stdout message' && echo 'stderr message' >&2")
System.print("stdout: %(mixedResult.stdout.trim())")
System.print("stderr: %(mixedResult.stderr.trim())")
System.print("\n--- Running Python (if available) ---")
var pyResult = Subprocess.run("python3 -c \"print('Hello from Python!')\" 2>/dev/null || echo 'Python not available'")
System.print("Python: %(pyResult.stdout.trim())")
System.print("\n--- Getting System Info ---")
var unameResult = Subprocess.run("uname -a")
System.print("System: %(unameResult.stdout.trim())")
System.print("\n--- Date and Time ---")
var dateResult = Subprocess.run("date '+\%Y-\%m-\%d \%H:\%M:\%S'")
System.print("Current time: %(dateResult.stdout.trim())")
System.print("\n--- Checking Exit Codes ---")
var trueResult = Subprocess.run("true")
var falseResult = Subprocess.run("false")
System.print("'true' exit code: %(trueResult.exitCode)")
System.print("'false' exit code: %(falseResult.exitCode)")
System.print("\n--- Practical Example: Git Status ---")
var gitResult = Subprocess.run("git status --short 2>/dev/null || echo 'Not a git repository'")
System.print("Git status:")
var gitOutput = gitResult.stdout.trim()
if (gitOutput.count == 0) {
System.print(" (clean working directory)")
} else {
System.print(gitOutput)
}