forked from KorySchneider/wikit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·288 lines (235 loc) · 7.08 KB
/
index.js
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
#!/usr/bin/env node
'use strict';
const path = require('path');
const fs = require('fs');
const wiki = require('wtf_wikipedia');
const inquirer = require('inquirer');
const ora = require('ora');
const opn = require('opn');
const htmlToText = require('html-to-text');
const Configstore = require('configstore');
const pkg = require(path.join(__dirname, '/package.json'));
const conf = new Configstore(pkg.name, { lang: 'en' });
const languages = JSON.parse(fs.readFileSync(
path.join(__dirname, 'data/languages.json')
));
const argv = require('minimist')(process.argv.slice(2));
// Print version if requested
if (argv.version || argv.v) printVersionAndExit();
// If no query, print usage and exit
if (argv._.length == 0) printUsageAndExit();
// Flags
let _openInBrowser = false;
let _browser = null;
let _lineLength = process.stdout.columns - 10; // Terminal width - 10
let _lang = conf.get('lang');
let _disambig = false;
// Maintain comfortable line length
if (_lineLength > 80) _lineLength = 80;
// Parse flags
if (argv.b) {
_openInBrowser = true;
}
if (argv.browser) {
_openInBrowser = true;
_browser = argv.browser;
}
if (argv.lang || argv.l) {
_lang = argv.lang || argv.l;
if (!validLanguageCode(_lang)) {
console.log(`Unrecognized language code: ${_lang}`);
process.exit(1);
}
}
if (argv.d) {
_disambig = true;
_openInBrowser = false;
}
if (argv.D) {
_disambig = true;
_openInBrowser = true;
}
if (argv.line) {
if (parseInt(argv.line) > 0) {
_lineLength = parseInt(argv.line);
} else {
console.log(`Invalid line length: ${argv.line}`);
process.exit(1);
}
}
// Format query
let query = argv._.join(' ').trim();
if (_disambig) query += ` (${getDisambigTranslation(_lang)})`;
// Execute
if (_openInBrowser) openInBrowser(query);
else printWikiSummary(query);
// ===== Functions =====
function printWikiSummary(queryText) {
let spinner = ora({ text: 'Searching...', spinner: 'dots4' }).start();
queryText = queryText.replace(/_/g, ' ');
wiki.fetch(queryText, _lang, (err, doc) => {
spinner.stop();
if (err) handleError(err);
if (doc) {
const summary = doc.sections()[0].text();
// Handle ambiguous results
if (_disambig || isDisambiguationPage(doc) || summary.includes('may refer to:')) {
handleAmbiguousResults(doc, queryText);
return;
}
// Output all
if (argv.all || argv.a) {
const sections = doc.sections().map(section => {
const text = section.text();
if (text) {
return {
'title': formatSectionTitle(section.title()),
'text': lineWrap(text, _lineLength),
}
}
});
const output = sections
.map(section => {
if (section && section.title && section.text) {
return `${section.title}\n${section.text}\n\n`;
}
})
.join('');
console.log(output);
if (argv.link) printLink(_lang, queryText);
return;
}
// Output summary
if (summary) {
console.log(lineWrap(summary, _lineLength));
if (argv.link) printLink(_lang, queryText);
return;
} else {
console.log(`Something went wrong, opening in browser...\n(Error code: 0 | Query: "${queryText}")`);
console.log('Submit bugs at https://github.com/koryschneider/wikit/issues/new');
openInBrowser(queryText);
}
} else {
console.log(`${query} not found :^(`);
}
}).catch(err => handleError(err));
}
function handleAmbiguousResults(doc, queryText) {
_disambig = false;
const choices = [];
doc.sections().forEach(section => {
section.links().forEach(link => {
if (link.page) choices.push(link.page);
});
});
inquirer.prompt([
{
name: 'selection',
type: 'list',
message: `Ambiguous results, "${queryText}" may refer to:`,
choices: choices,
pageSize: 15,
}
]).then(answers => {
printWikiSummary(answers.selection);
}).catch(err => {
console.log('Error:', err);
});
}
function lineWrap(text, max) {
// remove stray html elements
text = htmlToText.fromString(text, {
wordwrap: false,
uppercaseHeadings: false,
ignoreHref: true,
});
text = text.trim().replace(/\n\n/g, '\n');
text = text.trim().replace(/\n/g, ' '); // replace newlines with spaces
let formattedText = ' ';
while (text.length > max) {
let nextSpaceIndex = -1;
for (let i=max; i < text.length; i++) {
if (text[i] == ' ') {
nextSpaceIndex = i;
break;
}
}
if (nextSpaceIndex < 0) nextSpaceIndex = max; // No space char was found
formattedText += text.slice(0, nextSpaceIndex) + '\n';
text = text.slice(nextSpaceIndex, text.length);
}
// add remaining text
formattedText += (text.startsWith(' '))
? text
: ' ' + text;
return formattedText;
}
function openInBrowser(query) {
const format = (s) => s.trim().replace(/ /g, '+'); // replace spaces with +'s
let url = `https://${_lang}.wikipedia.org/w/index.php?title=Special:Search&search=`;
url += format(query);
if (_browser)
opn(url, { app: _browser });
else
opn(url);
}
function validLanguageCode(code) {
if (Object.keys(languages).includes(code)) return true;
return false;
}
function isDisambiguationPage(doc) {
let disambigPage = false;
doc.categories().forEach(category => {
if (category.toLowerCase().includes(getDisambigTranslation(_lang).toLowerCase())) {
disambigPage = true;
}
});
return disambigPage;
}
function getDisambigTranslation(lang) {
let translation = languages[[lang]].disambig;
if (translation) return translation;
else return 'disambiguation';
}
function printUsageAndExit() {
console.log(`
Usage: $ wikit <query> [-flags]
Quotes are not required for multi-word queries.
Flags:
--lang <LANG> Specify language;
-l <LANG> LANG is an HTML ISO language code
--all Print all sections of the article
-a Recommended to pipe into a reader e.g. less
-b Open Wikipedia article in default browser
--browser <BROWSER> Open article in specific BROWSER
-d Open disambiguation CLI menu
-D Open disambiguation page in browser
--line <NUM> Set line wrap length to NUM (minimum 15)
--link Print a link to the full article after the summary
--version / -v Print installed version number
Examples:
$ wikit nodejs
$ wikit empire state building --link
$ wikit linux -b
$ wikit jugo --lang es
`);
process.exit(1);
}
function printVersionAndExit() {
console.log(pkg.version);
process.exit(0);
}
function handleError(error) {
console.log('Error:', error);
console.log('Please report errors at https://github.com/koryschneider/wikit/issues/new');
}
function formatSectionTitle(title) {
let output = ` ${title}\n `;
for (let i = 0; i < title.length; i++) {
output += '-';
}
return output;
}
function printLink(lang, title) {
console.log(`\n https://${lang}.wikipedia.org/wiki/${encodeURIComponent(title)}`);
}