-
Notifications
You must be signed in to change notification settings - Fork 12
/
define.go
278 lines (213 loc) · 6.44 KB
/
define.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
// Copyright © 2018 Trevor N. Suarez (Rican7)
// A command-line dictionary (thesaurus) app, written in Go.
package main
import (
"encoding/json"
"fmt"
"os"
"sort"
"strings"
"github.com/Rican7/define/internal/action"
"github.com/Rican7/define/internal/config"
defineio "github.com/Rican7/define/internal/io"
"github.com/Rican7/define/internal/io/printer"
"github.com/Rican7/define/internal/version"
"github.com/Rican7/define/registry"
"github.com/Rican7/define/source"
flag "github.com/ogier/pflag"
_ "github.com/Rican7/define/source/freedictionaryapi"
"github.com/Rican7/define/source/oxford"
_ "github.com/Rican7/define/source/webster"
)
const (
// Configuration defaults
defaultIndentationSize = 2
defaultPreferredSource = oxford.JSONKey
fallbackSearchResultLimit = 5
)
var (
stdErrWriter = defineio.NewPanicWriter(os.Stderr, defaultIndentationSize)
stdOutWriter = defineio.NewPanicWriter(os.Stdout, defaultIndentationSize)
flags *flag.FlagSet
act *action.Action
conf config.Configuration
src source.Source
)
func init() {
var err error
flags = flag.NewFlagSet(version.AppName, flag.ContinueOnError)
flags.SetOutput(stdErrWriter)
flags.Usage = func() {
printUsage(stdErrWriter)
quit(2)
}
act = action.Setup(flags)
// Configure our registered providers
providerConfs := registry.ConfigureProviders(flags)
var providerConfsList []registry.Configuration
if len(providerConfs) < 1 {
handleError(fmt.Errorf("no registered source providers"))
}
for _, providerConf := range providerConfs {
providerConfsList = append(providerConfsList, providerConf)
}
conf, err = config.NewFromRuntime(flags, providerConfs, config.Configuration{
IndentationSize: defaultIndentationSize,
PreferredSource: defaultPreferredSource,
})
// Re-initialize our writers once we have our indentation size configuration
stdErrWriter = defineio.NewPanicWriter(os.Stderr, conf.IndentationSize)
stdOutWriter = defineio.NewPanicWriter(os.Stdout, conf.IndentationSize)
flags.SetOutput(stdErrWriter)
// Finalize our configurations
registry.Finalize(providerConfsList...)
handleError(err)
if conf.Source != "" {
if providerConf, exists := providerConfs[conf.Source]; exists {
src, err = registry.Provide(providerConf)
} else {
handleError(fmt.Errorf("provider/source %q does not exist", conf.Source))
}
} else {
src, err = registry.ProvidePreferred(conf.PreferredSource, providerConfsList)
}
// Make sure our flags are parsed before entering main
handleError(err, flags.Parse(os.Args[1:]))
}
func formatErrorForPrinting(err error) string {
msg := err.Error()
msg = strings.ToTitle(msg[:1]) + msg[1:]
return msg
}
func printSourceError(source string, err error) {
msg := formatErrorForPrinting(err)
if len(msg) < 1 {
return
}
stdErrWriter.IndentWrites(func(writer *defineio.PanicWriter) {
if source != "" {
sourceMessage := fmt.Sprintf("Source %q encountered an error.", source)
writer.WriteNewLine()
writer.WriteStringLine(sourceMessage)
}
writer.WritePaddedStringLine(msg, 1)
})
}
func handleSourceError(source string, err ...error) {
for _, e := range err {
if e == nil {
continue
}
printSourceError(source, e)
quit(1)
}
}
func handleError(err ...error) {
handleSourceError("", err...)
}
func quit(code int) {
os.Exit(code)
}
func printConfig() {
encoded, err := json.MarshalIndent(conf, "", " ")
handleError(err)
stdOutWriter.WriteStringLine(string(encoded))
}
func printConfigDebug() {
stdOutWriter.IndentWrites(func(writer *defineio.PanicWriter) {
writer.WriteNewLine()
switch configFilePath := conf.FilePath(); configFilePath {
case "":
writer.WriteStringLine("No config file was loaded.")
default:
writer.WriteStringLine(fmt.Sprintf("A config file was loaded from %q", configFilePath))
}
writer.WritePaddedStringLine("The following locations are searched for config files (in this order):", 1)
for i, filePath := range config.FilePaths() {
writer.WriteStringLine(fmt.Sprintf("%d. %s", i+1, filePath))
}
writer.WriteNewLine()
})
}
func printSources() {
var sourceStrings []string
for conf, source := range registry.Providers() {
sourceStrings = append(sourceStrings, fmt.Sprintf("%q (%s)", source.Name(), conf.JSONKey()))
}
sort.Strings(sourceStrings)
stdOutWriter.IndentWrites(func(writer *defineio.PanicWriter) {
writer.WritePaddedStringLine("Available sources:", 1)
for i, source := range sourceStrings {
writer.WriteStringLine(fmt.Sprintf("%d. %s", i+1, source))
}
writer.WriteNewLine()
})
}
func printVersion() {
stdOutWriter.WriteStringLine(version.Printable())
}
func printUsage(writer *defineio.PanicWriter) {
writer.IndentWrites(func(w *defineio.PanicWriter) {
flags.SetOutput(w)
w.WritePaddedStringLine(fmt.Sprintf("Usage: %s [<options>...] <word>", version.AppName), 1)
w.WriteStringLine("Options:")
flags.PrintDefaults()
w.WriteNewLine()
})
}
func defineWord(word string) {
searcher, isSearcher := src.(source.Searcher)
dictionaryResults, err := src.Define(word)
var searchResults source.SearchResults
if err == nil {
// Validate our results
err = source.ValidateDictionaryResults(word, dictionaryResults)
}
emptyResultError, isEmptyDictionaryResult := err.(*source.EmptyResultError)
if isEmptyDictionaryResult && isSearcher {
searchResults, err = searcher.Search(word, fallbackSearchResultLimit)
if err == nil {
// Validate our results
err = source.ValidateSearchResults(word, searchResults)
}
}
handleSourceError(src.Name(), err)
resultPrinter := printer.NewResultPrinter(stdOutWriter)
switch isEmptyDictionaryResult {
case true:
stdOutWriter.IndentWrites(func(writer *defineio.PanicWriter) {
writer.WritePaddedStringLine(formatErrorForPrinting(emptyResultError), 1)
writer.WritePaddedStringLine("Did you mean one of these?", 1)
})
resultPrinter.PrintSearchResults(searchResults)
case false:
dictionaryResults.SortForPrimaryResult(word)
resultPrinter.PrintDictionaryResults(dictionaryResults)
}
resultPrinter.PrintSourceName(src)
}
func main() {
// Get the word from our first non-flag argument
word := flags.Arg(0)
// Decide what to perform
switch act.Type() {
case action.PrintConfig:
printConfig()
case action.DebugConfig:
printConfigDebug()
case action.ListSources:
printSources()
case action.PrintVersion:
printVersion()
case action.DefineWord:
fallthrough
default:
if word == "" {
// Show our usage
printUsage(stdOutWriter)
quit(1)
} else {
defineWord(word)
}
}
}