main.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. #!/usr/bin/env node
  2. /**
  3. * Marked CLI
  4. * Copyright (c) 2011-2013, Christopher Jeffrey (MIT License)
  5. */
  6. import { promises } from 'node:fs';
  7. import { dirname, resolve } from 'node:path';
  8. import { homedir } from 'node:os';
  9. import { createRequire } from 'node:module';
  10. import { marked } from '../lib/marked.esm.js';
  11. const { access, readFile, writeFile } = promises;
  12. const require = createRequire(import.meta.url);
  13. /**
  14. * @param {Process} nodeProcess inject process so it can be mocked in tests.
  15. */
  16. export async function main(nodeProcess) {
  17. /**
  18. * Man Page
  19. */
  20. async function help() {
  21. const { spawn } = await import('child_process');
  22. const { fileURLToPath } = await import('url');
  23. const options = {
  24. cwd: nodeProcess.cwd(),
  25. env: nodeProcess.env,
  26. stdio: 'inherit'
  27. };
  28. const __dirname = dirname(fileURLToPath(import.meta.url));
  29. const helpText = await readFile(resolve(__dirname, '../man/marked.1.md'), 'utf8');
  30. // eslint-disable-next-line promise/param-names
  31. await new Promise(res => {
  32. spawn('man', [resolve(__dirname, '../man/marked.1')], options)
  33. .on('error', () => {
  34. console.log(helpText);
  35. })
  36. .on('close', res);
  37. });
  38. }
  39. async function version() {
  40. const pkg = require('../package.json');
  41. console.log(pkg.version);
  42. }
  43. /**
  44. * Main
  45. */
  46. async function start(argv) {
  47. const files = [];
  48. const options = {};
  49. let input;
  50. let output;
  51. let string;
  52. let arg;
  53. let tokens;
  54. let config;
  55. let opt;
  56. let noclobber;
  57. function getArg() {
  58. let arg = argv.shift();
  59. if (arg.indexOf('--') === 0) {
  60. // e.g. --opt
  61. arg = arg.split('=');
  62. if (arg.length > 1) {
  63. // e.g. --opt=val
  64. argv.unshift(arg.slice(1).join('='));
  65. }
  66. arg = arg[0];
  67. } else if (arg[0] === '-') {
  68. if (arg.length > 2) {
  69. // e.g. -abc
  70. argv = arg.substring(1).split('').map(function(ch) {
  71. return '-' + ch;
  72. }).concat(argv);
  73. arg = argv.shift();
  74. } else {
  75. // e.g. -a
  76. }
  77. } else {
  78. // e.g. foo
  79. }
  80. return arg;
  81. }
  82. while (argv.length) {
  83. arg = getArg();
  84. switch (arg) {
  85. case '-o':
  86. case '--output':
  87. output = argv.shift();
  88. break;
  89. case '-i':
  90. case '--input':
  91. input = argv.shift();
  92. break;
  93. case '-s':
  94. case '--string':
  95. string = argv.shift();
  96. break;
  97. case '-t':
  98. case '--tokens':
  99. tokens = true;
  100. break;
  101. case '-c':
  102. case '--config':
  103. config = argv.shift();
  104. break;
  105. case '-n':
  106. case '--no-clobber':
  107. noclobber = true;
  108. break;
  109. case '-h':
  110. case '--help':
  111. return await help();
  112. case '-v':
  113. case '--version':
  114. return await version();
  115. default:
  116. if (arg.indexOf('--') === 0) {
  117. opt = camelize(arg.replace(/^--(no-)?/, ''));
  118. if (!marked.defaults.hasOwnProperty(opt)) {
  119. continue;
  120. }
  121. if (arg.indexOf('--no-') === 0) {
  122. options[opt] = typeof marked.defaults[opt] !== 'boolean'
  123. ? null
  124. : false;
  125. } else {
  126. options[opt] = typeof marked.defaults[opt] !== 'boolean'
  127. ? argv.shift()
  128. : true;
  129. }
  130. } else {
  131. files.push(arg);
  132. }
  133. break;
  134. }
  135. }
  136. async function getData() {
  137. if (!input) {
  138. if (files.length <= 2) {
  139. if (string) {
  140. return string;
  141. }
  142. return await getStdin();
  143. }
  144. input = files.pop();
  145. }
  146. return await readFile(input, 'utf8');
  147. }
  148. function resolveFile(file) {
  149. return resolve(file.replace(/^~/, homedir));
  150. }
  151. function fileExists(file) {
  152. return access(resolveFile(file)).then(() => true, () => false);
  153. }
  154. async function runConfig(file) {
  155. const configFile = resolveFile(file);
  156. let markedConfig;
  157. try {
  158. // try require for json
  159. markedConfig = require(configFile);
  160. } catch (err) {
  161. if (err.code !== 'ERR_REQUIRE_ESM') {
  162. throw err;
  163. }
  164. // must import esm
  165. markedConfig = await import('file:///' + configFile);
  166. }
  167. if (markedConfig.default) {
  168. markedConfig = markedConfig.default;
  169. }
  170. if (typeof markedConfig === 'function') {
  171. markedConfig(marked);
  172. } else {
  173. marked.use(markedConfig);
  174. }
  175. }
  176. const data = await getData();
  177. if (config) {
  178. if (!await fileExists(config)) {
  179. throw Error(`Cannot load config file '${config}'`);
  180. }
  181. await runConfig(config);
  182. } else {
  183. const defaultConfig = [
  184. '~/.marked.json',
  185. '~/.marked.js',
  186. '~/.marked/index.js'
  187. ];
  188. for (const configFile of defaultConfig) {
  189. if (await fileExists(configFile)) {
  190. await runConfig(configFile);
  191. break;
  192. }
  193. }
  194. }
  195. const html = tokens
  196. ? JSON.stringify(marked.lexer(data, options), null, 2)
  197. : await marked.parse(data, options);
  198. if (output) {
  199. if (noclobber && await fileExists(output)) {
  200. nodeProcess.stderr.write('marked: output file \'' + output + '\' already exists, disable the \'-n\' / \'--no-clobber\' flag to overwrite\n');
  201. nodeProcess.exit(1);
  202. }
  203. return await writeFile(output, html);
  204. }
  205. nodeProcess.stdout.write(html + '\n');
  206. }
  207. /**
  208. * Helpers
  209. */
  210. function getStdin() {
  211. return new Promise((resolve, reject) => {
  212. const stdin = nodeProcess.stdin;
  213. let buff = '';
  214. stdin.setEncoding('utf8');
  215. stdin.on('data', function(data) {
  216. buff += data;
  217. });
  218. stdin.on('error', function(err) {
  219. reject(err);
  220. });
  221. stdin.on('end', function() {
  222. resolve(buff);
  223. });
  224. stdin.resume();
  225. });
  226. }
  227. /**
  228. * @param {string} text
  229. */
  230. function camelize(text) {
  231. return text.replace(/(\w)-(\w)/g, function(_, a, b) {
  232. return a + b.toUpperCase();
  233. });
  234. }
  235. try {
  236. await start(nodeProcess.argv.slice());
  237. nodeProcess.exit(0);
  238. } catch (err) {
  239. if (err.code === 'ENOENT') {
  240. nodeProcess.stderr.write('marked: output to ' + err.path + ': No such directory');
  241. }
  242. nodeProcess.stderr.write(err);
  243. return nodeProcess.exit(1);
  244. }
  245. }