mirror of
https://github.com/nicoverbruggen/phpmon.git
synced 2025-08-08 04:20:07 +02:00
In order to make this possible, I've added a new `sync()` method to the Shellable protocol, which now should allow us to run shell commands synchronously. Back to basics, as this was how *all* commands were run in legacy versions of PHP Monitor. The advantage here is that there is now a choice. Previously, you'd have to use the `system()` helper that I added. Usage of that helper is now discouraged, as is the synchronous shell method, but it may be useful for some methods where waiting for the outcome of the output is required. (Important: the `system()` helper is still required when determining what the preferred terminal is during the initialization of the `Paths` class.)
75 lines
1.8 KiB
Swift
75 lines
1.8 KiB
Swift
//
|
|
// System.swift
|
|
// PHP Monitor
|
|
//
|
|
// Created by Nico Verbruggen on 01/11/2022.
|
|
// Copyright © 2023 Nico Verbruggen. All rights reserved.
|
|
//
|
|
|
|
import Foundation
|
|
|
|
/**
|
|
Run a simple blocking Shell command on the user's own system.
|
|
*/
|
|
public func system(_ command: String) -> String {
|
|
let task = Process()
|
|
task.launchPath = "/bin/sh"
|
|
task.arguments = ["-c", command]
|
|
|
|
let pipe = Pipe()
|
|
task.standardOutput = pipe
|
|
task.launch()
|
|
|
|
let data = pipe.fileHandleForReading.readDataToEndOfFile()
|
|
let output: String = NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String
|
|
|
|
return output
|
|
}
|
|
|
|
/**
|
|
Same as the `system` command, but does not return the output.
|
|
*/
|
|
public func system_quiet(_ command: String) {
|
|
let task = Process()
|
|
task.launchPath = "/bin/sh"
|
|
task.arguments = ["-c", command]
|
|
|
|
let pipe = Pipe()
|
|
task.standardOutput = pipe
|
|
task.launch()
|
|
|
|
_ = pipe.fileHandleForReading.readDataToEndOfFile()
|
|
return
|
|
}
|
|
|
|
/**
|
|
Retrieves the username for the currently signed in user via `/usr/bin/id`.
|
|
This cannot fail or the application will crash.
|
|
*/
|
|
public func identity() -> String {
|
|
let task = Process()
|
|
task.launchPath = "/usr/bin/id"
|
|
task.arguments = ["-un"]
|
|
|
|
let pipe = Pipe()
|
|
task.standardOutput = pipe
|
|
task.launch()
|
|
|
|
guard let output = String(
|
|
data: pipe.fileHandleForReading.readDataToEndOfFile(),
|
|
encoding: String.Encoding.utf8
|
|
) else {
|
|
fatalError("Could not retrieve username via `id -un`!")
|
|
}
|
|
|
|
return output.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
}
|
|
|
|
/**
|
|
Retrieves the user's preferred shell.
|
|
*/
|
|
public func preferred_shell() -> String {
|
|
return system("dscl . -read ~/ UserShell | sed 's/UserShell: //'")
|
|
.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
}
|