Hi I want to write an app that includes a few buttons for scripts I use daily. I want to click a button and Terminal to open with a script (or multiple scripts) running, like:
let scripts = [
"cd ~/Documents/Websites/someApp/",
"ng serve --port 4300 -o"
]
performInTerminal(scripts)
I know how to... Open Terminal:
private func openTerminal(){
let url = NSURL(fileURLWithPath: "/System/Applications/Utilities/Terminal.app", isDirectory: true) as URL
let path = "/bin"
let configuration = NSWorkspace.OpenConfiguration()
configuration.arguments = [path]
NSWorkspace.shared.openApplication(at: url, configuration: configuration, completionHandler: nil)
}
and how to ... Perform a Script:
Unfortunately this doesn't seem to work with anything other than ls
and it has no connection to the terminal window, which makes sense.
private func performScript(_ args: String...){
let process = Process()
process.launchPath = "/usr/bin/env"
process.arguments = args
process.launch()
process.waitUntilExit()
}
Any ideas on how to merge those two?
UPDATE
I now added the function using Apple Script:
private func performInTerminal(_ scripts:[String]){
let concatScript = scripts.joined(separator: "; ")
let source = """
tell application "Terminal"
if not (exists window 1) then reopen
activate
do script "\(concatScript)"
end tell
"""
let appleScript = NSAppleScript(source: source)
var possibleError: NSDictionary?
appleScript?.executeAndReturnError(&possibleError)
if let error = possibleError {
for key in error.allKeys{
if let key = key as? String{
print("\(key): \(error.value(forKey: key)!)")
}
}
}
}
Problem now are Entitlements:
With the following in AppName.entitlements
it works, but It requests permissions every time:
<key>com.apple.security.temporary-exception.apple-events</key>
<array>
<string>com.apple.Terminal</string>
</array>
With the following I get -10004: Terminal got an error: A privilege violation occurred.
:
<key>com.apple.security.scripting-targets</key>
<dict>
<key>com.apple.Terminal</key>
<array>
<string>*</string>
</array>
</dict>