1 | #!/usr/bin/env node
|
2 |
|
3 | 'use strict';
|
4 |
|
5 | const { about, fetchLatest, fetchRandom } = require('./');
|
6 | const argv = require('minimist')(process.argv.slice(2));
|
7 | const bold = require('ansi-bold');
|
8 | const cyan = require('ansi-cyan');
|
9 | const green = require('ansi-green');
|
10 | const html2text = require('html2plaintext');
|
11 | const locale = require('os-locale').sync().replace('_', '-');
|
12 | const pkg = require('./package.json');
|
13 | const wrapAnsi = require('wrap-ansi');
|
14 |
|
15 | const DATE = '\uD83D\uDCC5';
|
16 | const OPEN_BOOK = '\uD83D\uDCD6';
|
17 |
|
18 | const name = Object.keys(pkg.bin)[0];
|
19 | const isMacOS = process.platform === 'darwin';
|
20 |
|
21 | const flag = (argv, short, long) => ({ [long]: (short && argv[short]) || argv[long] });
|
22 |
|
23 | const formatDate = timestamp => (new Date(timestamp)).toLocaleDateString(locale);
|
24 | const normalize = url => url.replace(/\/$/, '');
|
25 | const date = timestamp => (isMacOS ? DATE : '@') + ' ' + formatDate(timestamp);
|
26 | const link = url => (isMacOS ? `${OPEN_BOOK} ` : '') + cyan(normalize(url));
|
27 | const removeBlankLines = str => str.replace(/(?:\r?\n)+/g, '\n');
|
28 |
|
29 | const format = haiku => wrap(`
|
30 | ${bold(html2text(haiku.title))}
|
31 |
|
32 | ${removeBlankLines(html2text(haiku.content))}
|
33 |
|
34 | ${date(haiku.createdAt)}
|
35 | ${link(haiku.link)}
|
36 | `);
|
37 |
|
38 | const help = `
|
39 | ${bold(name)} v${pkg.version}
|
40 |
|
41 | Usage:
|
42 | $ ${name} [command]
|
43 | $ ${name} latest Fetch latest haiku
|
44 | $ ${name} about Display contents of about page
|
45 |
|
46 | Options:
|
47 | --info Display https://haiku.ist/about page [boolean]
|
48 | -h, --help Show help [boolean]
|
49 | -v, --version Show version number [boolean]
|
50 |
|
51 | Homepage: ${green(pkg.homepage)}
|
52 | Report issue: ${green(pkg.bugs.url)}
|
53 | `;
|
54 |
|
55 | (async function program(options = getOptions(argv)) {
|
56 | const {
|
57 | command,
|
58 | info: showInfo,
|
59 | version: showVersion,
|
60 | help: showHelp
|
61 | } = options;
|
62 |
|
63 | if (showVersion) return console.log(pkg.version);
|
64 | if (showHelp) return console.log(help);
|
65 |
|
66 | if (showInfo || command === 'about') {
|
67 | const info = await about();
|
68 | return console.log(format(info));
|
69 | }
|
70 |
|
71 | const haiku = await ((command === 'latest') ? fetchLatest() : fetchRandom());
|
72 | console.log(format(haiku));
|
73 | }());
|
74 |
|
75 | function getOptions(argv) {
|
76 | const [command] = argv._;
|
77 | return {
|
78 | ...flag(argv, 'h', 'help'),
|
79 | ...flag(argv, 'v', 'version'),
|
80 | ...flag(argv, null, 'info'),
|
81 | command: (command || '').toLowerCase()
|
82 | };
|
83 | }
|
84 |
|
85 | function wrap(text, { columns = 80, ...options } = {}) {
|
86 | columns = Math.min(process.stdout.columns, columns);
|
87 | return wrapAnsi(text, columns, { hard: true, ...options });
|
88 | }
|