main.js 6.3 KB

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