-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
105 lines (92 loc) · 1.97 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
package main
import (
"fmt"
"io"
"log"
"net/textproto"
"os"
"os/exec"
"strings"
"github.com/mattn/go-isatty"
"github.com/quite/word/config"
"golang.org/x/net/dict"
)
func hasDict(dicts []dict.Dict, name string) bool {
for _, dict := range dicts {
if dict.Name == name {
return true
}
}
return false
}
var conf *config.Config
func main() {
var err error
conf, err = config.New()
if err != nil {
panic(err)
}
var out io.WriteCloser = os.Stdout
if isatty.IsTerminal(os.Stdout.Fd()) {
// https://stackoverflow.com/a/54198703/945568
var cmd *exec.Cmd
cmd, out = runPager()
defer func() {
out.Close()
cmd.Wait()
}()
}
var c *dict.Client
if c, err = dict.Dial("tcp", fmt.Sprintf("%s:%d", conf.Host, conf.Port)); err != nil {
panic(err)
}
defer c.Close()
dicts, err := c.Dicts()
if err != nil {
panic(err)
}
if len(os.Args) != 2 {
fmt.Printf("expected 1 arg: word to look up\n")
fmt.Printf("\ndatabases on %s:%d:\n", conf.Host, conf.Port)
for _, dict := range dicts {
fmt.Printf(" %s\n %s\n", dict.Name, dict.Desc)
}
fmt.Printf("\ndatabases configured: %s\n", strings.Join(conf.Databases, " "))
os.Exit(2)
}
word := os.Args[1]
for _, name := range conf.Databases {
if hasDict(dicts, name) {
defs, err := c.Define(name, word)
if err != nil {
if err.(*textproto.Error).Code != 552 {
panic(err)
}
}
for _, def := range defs {
// TODO custom?
fmt.Fprintf(out, "\n# %s\n\n%s\n\n", name, strings.TrimSpace(string(def.Text)))
}
}
}
}
func runPager() (*exec.Cmd, io.WriteCloser) {
pager := []string{"less"}
if env := os.Getenv("PAGER"); env != "" {
pager = strings.Split(os.Getenv("PAGER"), " ")
}
if conf.Pager != "" {
pager = strings.Split(conf.Pager, " ")
}
cmd := exec.Command(pager[0], pager[1:]...)
out, err := cmd.StdinPipe()
if err != nil {
log.Fatal(err)
}
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
log.Fatal(err)
}
return cmd, out
}