-
Notifications
You must be signed in to change notification settings - Fork 25
/
plumber.go
86 lines (75 loc) · 1.68 KB
/
plumber.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
package main
import (
"os"
"os/exec"
"regexp"
"runtime"
"strings"
)
type (
PlumbAction func(msg *Plumbmsg) error
PlumbRule func(msg *Plumbmsg) PlumbAction
)
type Plumbmsg struct {
src, dst string
wdir string
kind string
Attr
Data []byte
}
type Attr map[string]string
func (p *Plumbmsg) Arg() string {
return strings.TrimSpace(string(p.Data))
}
var httpLink = NewRegexp("^http(s?)://", openBrowser)
func NewRegexp(expr string, action PlumbAction) *regexpRule {
return ®expRule{regexp.MustCompile(expr), action}
}
var openBrowser = PlumbAction(func(p *Plumbmsg) (err error) {
for _, browser := range browsers() {
full := append(strings.Fields(browser), p.Arg())
cmd := exec.Command(full[0], full[1:]...)
err = cmd.Start()
if err == nil {
break
}
}
return err
})
type regexpRule struct {
*regexp.Regexp
action PlumbAction
}
func (r *regexpRule) Plumb(msg *Plumbmsg) (matched bool, error error) {
if r.Match(msg.Data) {
return true, r.action(msg)
}
return false, nil
}
func matches(match bool, err error) bool {
if match && err == nil {
return true
}
if err != nil {
logf("plumber: %s", err)
}
return match
}
// browsers returns a list of commands to attempt for web visualization.
func browsers() []string {
cmds := []string{"chrome", "google-chrome", "firefox"}
switch runtime.GOOS {
case "darwin":
return append(cmds, "/usr/bin/open")
case "windows":
return append(cmds, "cmd /c start")
default:
userBrowser := os.Getenv("BROWSER")
if userBrowser != "" {
cmds = append([]string{userBrowser, "sensible-browser"}, cmds...)
} else {
cmds = append([]string{"sensible-browser"}, cmds...)
}
return append(cmds, "xdg-open")
}
}