forked from deanishe/awgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
workflow.go
407 lines (341 loc) · 11.3 KB
/
workflow.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
// Copyright (c) 2018 Dean Jackson <[email protected]>
// MIT Licence - http://opensource.org/licenses/MIT
package aw
import (
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"runtime/debug"
"sync"
"time"
"go.deanishe.net/fuzzy"
"github.com/deanishe/awgo/keychain"
"github.com/deanishe/awgo/util"
)
// AwGoVersion is the semantic version number of this library.
const AwGoVersion = "0.27.1"
// Default Workflow settings. Can be changed with the corresponding Options.
//
// See the Options and Workflow documentation for more information.
const (
DefaultLogPrefix = "\U0001F37A" // Beer mug
DefaultMaxLogSize = 1048576 // 1 MiB
DefaultMaxResults = 0 // No limit, i.e. send all results to Alfred
DefaultSessionName = "AW_SESSION_ID" // Workflow variable session ID is stored in
DefaultMagicPrefix = "workflow:" // Prefix to call "magic" actions
)
var (
startTime time.Time // Time execution started
// The workflow object operated on by top-level functions.
// wf *Workflow
// Flag, as we only want to set up logging once
// TODO: Better, more pluggable logging
logInitialized bool
)
// init creates the default Workflow.
func init() {
startTime = time.Now()
}
// Mockable function to run commands
type commandRunner func(name string, arg ...string) error
// Run command via exec.Command
func runCommand(name string, arg ...string) error {
return exec.Command(name, arg...).Run()
}
// Mockable exit function
var exitFunc = os.Exit
// Workflow provides a consolidated API for building Script Filters.
//
// As a rule, you should create a Workflow in init or main and call your main
// entry-point via Workflow.Run(), which catches panics, and logs & shows the
// error in Alfred.
//
// Script Filter
//
// To generate feedback for a Script Filter, use Workflow.NewItem() to create
// new Items and Workflow.SendFeedback() to send the results to Alfred.
//
// Run Script
//
// Use the TextErrors option, so any rescued panics are printed as text,
// not as JSON.
//
// Use ArgVars to set workflow variables, not Workflow/Feedback.
//
// See the _examples/ subdirectory for some full examples of workflows.
type Workflow struct {
sync.WaitGroup
// Interface to workflow's settings.
// Reads workflow variables by type and saves new values to info.plist.
Config *Config
// Call Alfred's AppleScript functions.
Alfred *Alfred
// Cache is a Cache pointing to the workflow's cache directory.
Cache *Cache
// Data is a Cache pointing to the workflow's data directory.
Data *Cache
// Session is a cache that stores session-scoped data. These data
// persist until the user closes Alfred or runs a different workflow.
Session *Session
// Access macOS Keychain. Passwords are saved using the workflow's
// bundle ID as the service name. Passwords are synced between
// devices if you have iCloud Keychain turned on.
Keychain *keychain.Keychain
// The response that will be sent to Alfred. Workflow provides
// convenience wrapper methods, so you don't normally have to
// interact with this directly.
Feedback *Feedback
// Updater fetches updates for the workflow.
Updater Updater
// magicActions contains the magic actions registered for this workflow.
// Several built-in actions are registered by default. See the docs for
// MagicAction for details.
magicActions *magicActions
logPrefix string // Written to debugger to force a newline
maxLogSize int // Maximum size of log file in bytes
magicPrefix string // Overrides DefaultMagicPrefix for magic actions.
maxResults int // max. results to send to Alfred. 0 means send all.
sortOptions []fuzzy.Option // Options for fuzzy filtering
textErrors bool // Show errors as plaintext, not Alfred JSON
helpURL string // URL to help page (shown if there's an error)
dir string // Directory workflow is in
cacheDir string // Workflow's cache directory
dataDir string // Workflow's data directory
sessionName string // Name of the variable sessionID is stored in
sessionID string // Random session ID
execFunc commandRunner // Run external commands
}
// New creates and initialises a new Workflow, passing any Options to
// Workflow.Configure().
//
// For available options, see the documentation for the Option type and the
// following functions.
//
// IMPORTANT: In order to be able to initialise the Workflow correctly,
// New must be run within a valid Alfred environment; specifically
// *at least* the following environment variables must be set:
//
// alfred_workflow_bundleid
// alfred_workflow_cache
// alfred_workflow_data
//
// If you aren't running from Alfred, or would like to specify a
// custom environment, use NewFromEnv().
func New(opts ...Option) *Workflow { return NewFromEnv(nil, opts...) }
// NewFromEnv creates a new Workflows from the specified Env.
// If env is nil, the system environment is used.
func NewFromEnv(env Env, opts ...Option) *Workflow {
if env == nil {
env = sysEnv{}
}
if err := validateEnv(env); err != nil {
panic(err)
}
wf := &Workflow{
Config: NewConfig(env),
Alfred: NewAlfred(env),
Feedback: &Feedback{},
logPrefix: DefaultLogPrefix,
maxLogSize: DefaultMaxLogSize,
maxResults: DefaultMaxResults,
sessionName: DefaultSessionName,
sortOptions: []fuzzy.Option{},
execFunc: runCommand,
}
wf.magicActions = &magicActions{
actions: map[string]MagicAction{},
wf: wf,
}
// default magic actions
wf.Configure(AddMagic(
logMA{wf},
cacheMA{wf},
clearCacheMA{wf},
dataMA{wf},
clearDataMA{wf},
resetMA{wf},
))
wf.Configure(opts...)
wf.Cache = NewCache(wf.CacheDir())
wf.Data = NewCache(wf.DataDir())
wf.Session = NewSession(wf.CacheDir(), wf.SessionID())
wf.Keychain = keychain.New(wf.BundleID())
wf.initializeLogging()
return wf
}
// --------------------------------------------------------------------
// Initialisation methods
// Configure applies one or more Options to Workflow. The returned Option reverts
// all Options passed to Configure.
func (wf *Workflow) Configure(opts ...Option) (previous Option) {
prev := make(options, len(opts))
for i, opt := range opts {
prev[i] = opt(wf)
}
return prev.apply
}
// initializeLogging ensures future log messages are written to
// workflow's log file.
func (wf *Workflow) initializeLogging() {
if logInitialized { // All Workflows use the same global logger
return
}
// Rotate log file if larger than MaxLogSize
fi, err := os.Stat(wf.LogFile())
if err == nil {
if fi.Size() >= int64(wf.maxLogSize) {
newlog := wf.LogFile() + ".1"
if err := os.Rename(wf.LogFile(), newlog); err != nil {
fmt.Fprintf(os.Stderr, "Error rotating log: %v\n", err)
}
fmt.Fprintln(os.Stderr, "Rotated log")
}
}
// Open log file
file, err := os.OpenFile(wf.LogFile(), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
if err != nil {
wf.Fatal(fmt.Sprintf("Couldn't open log file %s : %v",
wf.LogFile(), err))
}
// Attach logger to file
multi := io.MultiWriter(file, os.Stderr)
log.SetOutput(multi)
// Show filenames and line numbers if Alfred's debugger is open
if wf.Debug() {
log.SetFlags(log.Ltime | log.Lshortfile)
} else {
log.SetFlags(log.Ltime)
}
logInitialized = true
}
// --------------------------------------------------------------------
// API methods
// BundleID returns the workflow's bundle ID. This library will not
// work without a bundle ID, which is set in the workflow's main
// setup sheet in Alfred Preferences.
func (wf *Workflow) BundleID() string {
s := wf.Config.Get(EnvVarBundleID)
if s == "" {
wf.Fatal("No bundle ID set. You *must* set a bundle ID to use AwGo.")
}
return s
}
// Name returns the workflow's name as specified in the workflow's main
// setup sheet in Alfred Preferences.
func (wf *Workflow) Name() string { return wf.Config.Get(EnvVarName) }
// Version returns the workflow's version set in the workflow's configuration
// sheet in Alfred Preferences.
func (wf *Workflow) Version() string { return wf.Config.Get(EnvVarVersion) }
// SessionID returns the session ID for this run of the workflow.
// This is used internally for session-scoped caching.
//
// The session ID is persisted as a workflow variable. It and the session
// persist as long as the user is using the workflow in Alfred. That
// means that the session expires as soon as Alfred closes or the user
// runs a different workflow.
func (wf *Workflow) SessionID() string {
if wf.sessionID == "" {
ev := os.Getenv(wf.sessionName)
if ev != "" {
wf.sessionID = ev
} else {
wf.sessionID = NewSessionID()
}
}
return wf.sessionID
}
// Debug returns true if Alfred's debugger is open.
func (wf *Workflow) Debug() bool { return wf.Config.GetBool(EnvVarDebug) }
// Args returns command-line arguments passed to the program.
// It intercepts "magic args" and runs the corresponding actions, terminating
// the workflow. See MagicAction for full documentation.
func (wf *Workflow) Args() []string {
prefix := DefaultMagicPrefix
if wf.magicPrefix != "" {
prefix = wf.magicPrefix
}
return wf.magicActions.args(os.Args[1:], prefix)
}
// Run runs your workflow function, catching any errors.
// If the workflow panics, Run rescues and displays an error message in Alfred.
func (wf *Workflow) Run(fn func()) {
vstr := wf.Name()
if wf.Version() != "" {
vstr += "/" + wf.Version()
}
vstr = fmt.Sprintf(" %s (AwGo/%v) ", vstr, AwGoVersion)
// Print right after Alfred's introductory blurb in the debugger.
// Alfred strips whitespace.
if wf.logPrefix != "" {
fmt.Fprintln(os.Stderr, wf.logPrefix)
}
log.Println(util.Pad(vstr, "-", 50))
// Clear expired session data
wf.Add(1)
go func() {
defer wf.Done()
if err := wf.Session.Clear(false); err != nil {
log.Printf("[ERROR] clear session: %v", err)
}
}()
// Catch any `panic` and display an error in Alfred.
// Fatal(msg) will terminate the process (via log.Fatal).
defer func() {
if r := recover(); r != nil {
log.Println(util.Pad(" FATAL ERROR ", "-", 50))
log.Printf("%s : %s", r, debug.Stack())
log.Println(util.Pad(" END STACK TRACE ", "-", 50))
// log.Printf("Recovered : %x", r)
err, ok := r.(error)
if ok {
wf.outputErrorMsg(err.Error())
}
wf.outputErrorMsg(fmt.Sprintf("%v", r))
}
}()
// Call the workflow's main function.
fn()
wf.Wait()
finishLog(false)
}
// --------------------------------------------------------------------
// Helper methods
// outputErrorMsg prints and logs error, then exits process.
func (wf *Workflow) outputErrorMsg(msg string) {
if wf.textErrors {
fmt.Print(msg)
} else {
wf.Feedback.Clear()
wf.NewItem(msg).Icon(IconError)
wf.SendFeedback()
}
log.Printf("[ERROR] %s", msg)
// Show help URL or website URL
if wf.helpURL != "" {
log.Printf("Get help at %s", wf.helpURL)
}
finishLog(true)
}
// awDataDir is the directory for AwGo's own data.
func (wf *Workflow) awDataDir() string {
return util.MustExist(filepath.Join(wf.DataDir(), "_aw"))
}
// awCacheDir is the directory for AwGo's own cache.
func (wf *Workflow) awCacheDir() string {
return util.MustExist(filepath.Join(wf.CacheDir(), "_aw"))
}
// --------------------------------------------------------------------
// Package-level only
// finishLog outputs the workflow duration
func finishLog(fatal bool) {
s := util.Pad(fmt.Sprintf(" %v ", time.Since(startTime)), "-", 50)
if fatal {
log.Println(s)
exitFunc(1)
} else {
log.Println(s)
}
}