-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
177 lines (154 loc) · 3.85 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
package main
import (
"bytes"
"errors"
"fmt"
"net/url"
"os"
"path"
"strings"
humanize "github.com/dustin/go-humanize"
flags "github.com/jessevdk/go-flags"
"github.com/ktr0731/go-fuzzyfinder"
"github.com/mattn/go-runewidth"
"github.com/sheepla/fzwiki/client"
"github.com/toqueteos/webbrowser"
"golang.org/x/net/html"
)
type exitCode int
// nolint:gochecknoglobals
var (
appVersion = "unknown"
appRevision = "unknown"
appName = "fzwiki"
envNameLang = "FZWIKI_LANG"
)
const (
exitCodeOK exitCode = iota
exitCodeErr
exitCodeErrFuzzyFinder
exitCodeErrWebBrowser
)
type options struct {
Version bool `short:"V" long:"version" description:"Show version"`
Open bool `short:"o" long:"open" description:"Open URL in your web browser"`
Language string `short:"l" long:"lang" description:"Language for wikipedia.org such as \"en\", \"ja\", ..."`
}
func main() {
code, err := run(os.Args[1:])
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
os.Exit(int(code))
}
func run(args []string) (exitCode, error) {
var opts options
parser := flags.NewParser(&opts, flags.Default)
parser.Name = appName
parser.Usage = "[OPTIONS] QUERY..."
args, err := parser.ParseArgs(args)
if err != nil {
if flags.WroteHelp(err) {
return exitCodeOK, nil
} else {
return exitCodeErr, fmt.Errorf("argument parsing failed: %w", err)
}
}
if opts.Version {
fmt.Printf("%s: v%s-rev%s\n", appName, appVersion, appRevision)
return exitCodeOK, nil
}
if len(args) == 0 {
return exitCodeErr, errors.New("must require arguments.")
}
var lang string
if opts.Language == "" {
lang = os.Getenv(envNameLang)
} else {
lang = opts.Language
}
result, err := searchArticles(strings.Join(args, " "), lang)
if err != nil {
return exitCodeErr, fmt.Errorf("failed to search articles: %w", err)
}
choices, err := find(result)
if err != nil {
if errors.Is(fuzzyfinder.ErrAbort, err) {
return exitCodeOK, nil
}
return exitCodeErr, fmt.Errorf("an error occurred on fuzzyfinder: %w", err)
}
for _, idx := range choices {
url := createPageURL(result.Query.Search[idx].Title, lang)
if opts.Open {
if err := webbrowser.Open(url); err != nil {
return exitCodeErrWebBrowser, fmt.Errorf("an error occurred on opening web browser: %w", err)
}
} else {
fmt.Println(url)
}
}
return exitCodeOK, nil
}
func html2text(content string) (string, error) {
doc, err := html.Parse(strings.NewReader(content))
if err != nil {
return "", err
}
var buf bytes.Buffer
render(doc, &buf)
return buf.String(), nil
}
func render(n *html.Node, buf *bytes.Buffer) {
if n.Type == html.TextNode {
buf.WriteString(n.Data)
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
render(c, buf)
}
}
func searchArticles(query, lang string) (*client.SearchResult, error) {
url := client.CreateSearchURL(query, lang)
return client.Execute(url)
}
func createPageURL(title, lang string) string {
if lang == "" {
lang = "en"
}
u := &url.URL{
Scheme: "https",
Path: path.Join("wiki", title),
Host: fmt.Sprintf("%s.wikipedia.org", lang),
}
return u.String()
}
func createPreview(i, w, h int, result *client.SearchResult) string {
title := result.Query.Search[i].Title
snippet := result.Query.Search[i].Snippet
timestamp := result.Query.Search[i].Timestamp
wordcount := result.Query.Search[i].Wordcount
if s, err := html2text(snippet); err == nil {
snippet = s
}
return fmt.Sprintf(
"%s\n\n%s\n\n%s, %s words",
title,
runewidth.Wrap(snippet, w/2-5),
humanize.Time(timestamp),
humanize.Comma(wordcount),
)
}
func find(result *client.SearchResult) (choices []int, err error) {
return fuzzyfinder.FindMulti(
result.Query.Search,
func(i int) string { return result.Query.Search[i].Title },
fuzzyfinder.WithPreviewWindow(
func(i, w, h int) string {
if i == -1 {
return ""
}
return createPreview(i, w, h, result)
},
),
)
}