-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
229 lines (191 loc) · 5.08 KB
/
main.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
package main
import (
"context"
_ "embed"
"fmt"
"log"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"text/template"
"time"
"github.com/mitchellh/go-homedir"
"github.com/urfave/cli"
)
var failMsg = "⚠️ Unable to Get Weather"
var home = func() string {
home, err := homedir.Dir()
if err != nil {
log.Fatal("unable to determine home directory:", err)
}
return home
}()
var cliFlags = []cli.Flag{
cli.StringFlag{
Name: "country",
Usage: "a country code eg: CA or US",
},
cli.StringFlag{
Name: "city",
Usage: "a city name",
},
cli.StringFlag{
Name: "key",
Usage: "openweathermap.com api key",
},
cli.StringFlag{
Name: "unit",
Value: "metric",
Usage: "metric or imperial unit",
},
cli.Int64Flag{
Name: "sleep",
Value: 300,
Usage: "number of seconds to wait before updating weather",
},
cli.StringFlag{
Name: "file",
Value: filepath.Join(home, ".weatherterm"),
Usage: "file to write weather to, if empty writes to stdout, by default writes to ~/.weatherterm",
},
}
func main() {
app := cli.NewApp()
app.Name = "weatherterm"
app.Usage = "A weather application for the terminal"
app.Commands = []cli.Command{
{
Name: "run",
Usage: "Run the weatherterm application",
Flags: cliFlags,
Action: run,
},
{
Name: "install",
Usage: "Install the weatherterm service",
Flags: cliFlags,
Action: install,
},
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
// run executes the weatherterm application.
func run(c *cli.Context) error {
unitType, err := GetUnit(c.String("unit"))
if err != nil {
writeWeatherReport(failMsg, c.String("file"))
return err
}
city, err := GetCity(c.String("country"), c.String("city"))
if err != nil {
writeWeatherReport(failMsg, c.String("file"))
return err
}
openWeatherClient := OpenWeather{APIKey: c.String("key")}
weatherReport, err := reportWeather(openWeatherClient, city, unitType)
if err != nil {
writeWeatherReport(failMsg, c.String("file"))
return err
}
writeWeatherReport(weatherReport, c.String("file"))
quitChan := make(chan os.Signal, 1)
signal.Notify(quitChan, os.Interrupt, syscall.SIGTERM, syscall.SIGINT)
for {
select {
case <-quitChan:
log.Println("received shutdown signal, exiting...")
return nil
case <-time.After(time.Duration(c.Int64("sleep")) * time.Second):
weatherReport, err := reportWeather(openWeatherClient, city, unitType)
if err != nil {
writeWeatherReport(failMsg, c.String("file"))
return err
}
writeWeatherReport(weatherReport, c.String("file"))
}
}
}
// install installs the weatherterm service.
func install(c *cli.Context) error {
err := installWeatherTermService(
home,
c.String("country"),
c.String("city"),
c.String("key"),
c.String("unit"),
c.Int64("sleep"),
c.String("file"),
)
if err != nil {
return err
}
log.Println("WeatherTerm service installed successfully")
return nil
}
func reportWeather(openWeatherClient OpenWeather, city City, unit Unit) (string, error) {
weather, err := openWeatherClient.Report(context.Background(), city, unit)
if err != nil {
return "", err
}
weatherStr := fmt.Sprintf("%s %g%s %s", ThermometerIcon, weather.Temperature, weather.UnitIcon(), weather.Icon)
windStr := fmt.Sprintf("%s %g%s %s", WindIcon, weather.Wind.Speed, WindSpeedUnit, weather.Wind.Direction)
weatherReport := fmt.Sprintf("%s %s", weatherStr, windStr)
return weatherReport, nil
}
// writeWeatherReport writes the weather to a stdout or file.
func writeWeatherReport(msg string, file string) {
if strings.EqualFold(file, "") {
log.Println(msg)
} else {
err := os.WriteFile(file, []byte(msg), 0644)
if err != nil {
log.Fatalf("unable to write weather to file: %s", err)
}
}
}
//go:embed com.weatherterm.plist
var weatherTermServiceTmpl string
func installWeatherTermService(home, countryCode, cityName, apiKey, unit string, sleepTime int64, file string) error {
binaryPath, err := os.Executable()
if err != nil {
return fmt.Errorf("unable to determine binary path: %w", err)
}
data := map[string]interface{}{
"BinaryPath": binaryPath,
"CountryCode": countryCode,
"CityName": cityName,
"APIKey": apiKey,
"Unit": unit,
"SleepTime": sleepTime,
"File": file,
}
tmpl, err := template.New("weatherTermService").Parse(weatherTermServiceTmpl)
if err != nil {
return fmt.Errorf("unable to parse template: %w", err)
}
// Create the LaunchAgents directory if it doesn't exist
launchAgentsDir := filepath.Join(home, "Library/LaunchAgents")
err = os.MkdirAll(launchAgentsDir, 0755)
if err != nil {
return fmt.Errorf("unable to create LaunchAgents directory: %w", err)
}
// Write the rendered template to the com.weatherterm.plist file
plistPath := filepath.Join(launchAgentsDir, "com.weatherterm.plist")
weatherFile, err := os.Create(plistPath)
if err != nil {
return fmt.Errorf("unable to create plist file: %w", err)
}
defer func() {
_ = weatherFile.Close()
}()
err = tmpl.Execute(weatherFile, data)
if err != nil {
return fmt.Errorf("unable to render plist template: %w", err)
}
return nil
}