forked from deckarep/gosx-notifier
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathterminal-app-zip.go
126 lines (102 loc) · 2.33 KB
/
terminal-app-zip.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package gosxnotifier
import (
"archive/zip"
"errors"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"runtime"
)
const (
zipPath = "terminal-notifier.temp.zip"
executablePath = "terminal-notifier.app/Contents/MacOS/terminal-notifier"
tempDirSuffix = "gosxnotifier"
)
var (
rootPath string
FinalPath string
)
func supportedOS() bool {
if runtime.GOOS == "darwin" {
return true
} else {
log.Print("OS does not support terminal-notifier")
return false
}
}
func init() {
if supportedOS() {
err := installTerminalNotifier()
if err != nil {
log.Fatal("Could not install Terminal Notifier to a temp directory")
} else {
FinalPath = filepath.Join(rootPath, executablePath)
}
}
}
func exists(file string) bool {
if _, err := os.Stat(file); os.IsNotExist(err) {
return false
}
return true
}
func installTerminalNotifier() error {
rootPath = filepath.Join(os.TempDir(), tempDirSuffix)
//if terminal-notifier.app already installed no-need to re-install
if exists(filepath.Join(rootPath, executablePath)) {
return nil
}
err := ioutil.WriteFile(zipPath, terminalnotifier(), 0700)
if err != nil {
return errors.New("could not write terminal-notifier file")
}
defer os.Remove(zipPath)
err = unpackZipArchive(zipPath, rootPath)
if err != nil {
return errors.New("could not unpack zip terminal-notifier file")
}
err = os.Chmod(filepath.Join(rootPath, executablePath), 0755)
if err != nil {
return errors.New("could not make terminal-notfier executable")
}
return nil
}
func unpackZipArchive(filename, tempPath string) error {
reader, err := zip.OpenReader(filename)
if err != nil {
return err
}
defer reader.Close()
for _, zipFile := range reader.Reader.File {
name := zipFile.Name
mode := zipFile.Mode()
if mode.IsDir() {
if err = os.MkdirAll(filepath.Join(tempPath, name), 0755); err != nil {
return err
}
} else {
if err = unpackZippedFile(name, tempPath, zipFile); err != nil {
return err
}
}
}
return nil
}
func unpackZippedFile(filename, tempPath string, zipFile *zip.File) error {
writer, err := os.Create(filepath.Join(tempPath, filename))
if err != nil {
return err
}
defer writer.Close()
reader, err := zipFile.Open()
if err != nil {
return err
}
defer reader.Close()
if _, err = io.Copy(writer, reader); err != nil {
return err
}
return nil
}