-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.js
executable file
·244 lines (199 loc) · 5.02 KB
/
cli.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
#!/usr/bin/env node
import { readFile, writeFile } from 'node:fs/promises';
import { resolve } from 'node:path';
import opsh from 'opsh';
import {
slurp,
toDataUrl,
getHtmlToMdProcessor,
getMdToMdProcessor,
getMdToHtmlProcessor,
getMdToTextProcessor,
getHtmlToTextProcessor,
getHtmlToHtmlProcessor
} from './index.js';
async function getPackage() {
return JSON.parse(
await readFile(new URL('./package.json', import.meta.url))
);
}
const commands = [
'markdown',
'markup',
'remarkdown',
'demarkdown',
'remarkup',
'demarkup'
];
const args = opsh(process.argv.slice(2), [
'h',
'help',
'v',
'version',
'data-url',
'write',
'silent'
]);
const [command, ...operands] = args.operands;
if (args.options.h || args.options.help) {
await outputHelp();
process.exit();
}
if (args.options.v || args.options.version) {
const pkg = await getPackage();
console.log(pkg.version);
process.exit();
}
if (!command) {
await outputHelp();
process.exit();
}
if (!commands.includes(command)) {
console.error(
`Invalid command '${command}'. Expected one of: ${commands.join(', ')}.`
);
process.exit(1);
}
function cast(val) {
if (val === 'true') return true;
if (val === 'false') return false;
const num = parseFloat(val);
if (!Number.isNaN(num)) return num;
return val;
}
function namespacedOptions(namespace) {
const matcher = new RegExp(String.raw`${namespace}\.(.+)`);
return Object.keys(args.options).reduce((obj, k) => {
const m = k.match(matcher);
if (m) {
obj[m[1]] = cast(args.options[k]);
}
return obj;
}, {});
}
const MD_DEFAULTS = {
fences: true,
emphasis: '_',
strong: '_',
resourceLink: true,
rule: '-'
};
const mdOptions = { ...MD_DEFAULTS, ...namespacedOptions('md') };
if (!operands.length) {
operands.push('-');
}
const htmlOptions = {
sanitize: !args.options['no-sanitize']
};
const transformer = args.options.transform || args.options.t;
const transformFn = transformer
? (await import(resolve(transformer))).default
: undefined;
let processor;
let postProcessor = v => v;
switch (command) {
case 'markdown':
processor = getHtmlToMdProcessor(mdOptions);
break;
case 'remarkdown':
processor = getMdToMdProcessor(mdOptions, transformFn);
break;
case 'markup':
processor = getMdToHtmlProcessor(htmlOptions);
if (args.options['data-url']) {
postProcessor = toDataUrl;
}
break;
case 'demarkdown':
processor = getMdToTextProcessor();
break;
case 'demarkup':
processor = getHtmlToTextProcessor();
break;
case 'remarkup':
processor = getHtmlToHtmlProcessor(htmlOptions);
if (args.options['data-url']) {
postProcessor = toDataUrl;
}
break;
}
const results = await Promise.all(
operands
.map(it => (it === '-' ? slurp(process.stdin) : readFile(it, 'utf8')))
.map(promise =>
promise
.then(content => processor.process(content))
.then(result => postProcessor(String(result)))
)
);
if (args.options.write) {
operands.forEach((operand, idx) => {
if (operand === '-') {
if (!args.options.silent) {
console.warn('Using --write, `stdin` skipped.');
}
return;
}
writeFile(operand, results[idx]);
});
} else if (!args.options.silent) {
console.log(results.join('\n'));
}
async function outputHelp() {
const pkg = await getPackage();
console.log(`${pkg.name} ${pkg.version}`);
console.log(`${pkg.description}`);
console.log(`Homepage: ${pkg.homepage}`);
console.log(`
Usage:
trimd [command] [options] [file, ...]
Operands are one or more files provided by file path.
Using '-' (dash) as an operand reads from the standard input ('stdin').
When no operands are provided, input is read from 'stdin'.
Output is provided to the standard output ('stdout').
General options:
-h, --help
Output help information.
-v, --version
Output program version.
--write
Write results to the original files instead of
outputting to 'stdout'. When using --write,
the result of processing 'stdin' is ignored.
--silent
Suppress the output of commands.
Commands:
markdown
Convert HTML to Markdown.
remarkdown
Normalize Markdown.
markup
Convert Markdown to HMTL.
demarkdown
Convert Markdown to plain text.
demarkup
Convert HTML to plain text.
remarkup
Simplify HTML by converting it to Markdown and back.
Markdown-specific options:
--md.<option>=<value>
Markdown options forwarded to 'remark-stringify'.
-t <transform>,
--transform=<transform>
Path to a JavaScript file containing a function
to transform the Markdown, operating on an MDAST tree.
Applies to 'remarkdown'.
HTML-specific options:
--data-url
Output the resulting HTML as a base64-encoded 'data:' URL.
Applies to the 'markup' and 'remarkup' commands.
--no-sanitize
Skip the HTML sanitization step.
Should only be used when the input is known to be safe.
Examples:
Convert HTML to Markdown:
trimd markdown my-file.html
Convert Markdown to HTML:
trimd markup README.md
`);
}