-
Notifications
You must be signed in to change notification settings - Fork 0
/
applescriptHandler.go
62 lines (50 loc) · 1.33 KB
/
applescriptHandler.go
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
package main
import (
"fmt"
"os/exec"
"strings"
)
// OpenApp opens an application using AppleScript
func OpenApp(appName string, reschan chan string, errchan chan error) func() {
return func() {
script := fmt.Sprintf(`
tell application "%s"
activate
end tell
`, appName)
err := executeAppleScript(script)
if err != nil {
errchan <- fmt.Errorf("Could not open app '%s': '%v'", appName, err)
return
}
reschan <- fmt.Sprintf("Successfully opened app: '%s'", appName)
return
}
}
// CloseApp closes an application using AppleScript
func CloseApp(appName string, reschan chan string, errchan chan error) func() {
return func() {
script := fmt.Sprintf(`
tell application "%s"
quit
end tell
`, appName)
err := executeAppleScript(script)
if err != nil {
errchan <- fmt.Errorf("Could not close app '%s': '%v'", appName, err)
return
}
reschan <- fmt.Sprintf("Successfully closed app: '%s'", appName)
return
}
}
// executeAppleScript takes in a fully parsed Apple-Script and executes the command using osascript
func executeAppleScript(command string) error {
cmd := exec.Command("osascript", "-e", command)
output, err := cmd.CombinedOutput()
prettyOutput := strings.Replace(string(output), "\n", "", -1)
if err != nil {
return fmt.Errorf("Could not execute script: %s ; %v", prettyOutput, err)
}
return nil
}