cli.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. #!/usr/bin/env node
  2. /*
  3. The MIT License (MIT)
  4. Copyright (c) 2007-2013 Einar Lielmanis and contributors.
  5. Permission is hereby granted, free of charge, to any person
  6. obtaining a copy of this software and associated documentation files
  7. (the "Software"), to deal in the Software without restriction,
  8. including without limitation the rights to use, copy, modify, merge,
  9. publish, distribute, sublicense, and/or sell copies of the Software,
  10. and to permit persons to whom the Software is furnished to do so,
  11. subject to the following conditions:
  12. The above copyright notice and this permission notice shall be
  13. included in all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  15. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  16. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  17. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  18. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  19. ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  20. CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. SOFTWARE.
  22. Js-Beautify Command-line for node.js
  23. -------------------------------------
  24. Written by Daniel Stockman (daniel.stockman@gmail.com)
  25. */
  26. var debug = process.env.DEBUG_JSBEAUTIFY || process.env.JSBEAUTIFY_DEBUG ? function() {
  27. console.error.apply(console, arguments);
  28. } : function() {};
  29. var fs = require('fs'),
  30. cc = require('config-chain'),
  31. beautify = require('../index'),
  32. mkdirp = require('mkdirp'),
  33. nopt = require('nopt'),
  34. path = require('path'),
  35. knownOpts = {
  36. // Beautifier
  37. "indent_size": Number,
  38. "indent_char": String,
  39. "eol": String,
  40. "indent_level": Number,
  41. "indent_with_tabs": Boolean,
  42. "preserve_newlines": Boolean,
  43. "max_preserve_newlines": Number,
  44. "space_in_paren": Boolean,
  45. "space_in_empty_paren": Boolean,
  46. "jslint_happy": Boolean,
  47. "space_after_anon_function": Boolean,
  48. // TODO: expand-strict is obsolete, now identical to expand. Remove in future version
  49. "brace_style": ["collapse", "expand", "end-expand", "expand-strict", "none"],
  50. "break_chained_methods": Boolean,
  51. "keep_array_indentation": Boolean,
  52. "unescape_strings": Boolean,
  53. "wrap_line_length": Number,
  54. "wrap_attributes": ["auto", "force"],
  55. "wrap_attributes_indent_size": Number,
  56. "e4x": Boolean,
  57. "end_with_newline": Boolean,
  58. "comma_first": Boolean,
  59. // CSS-only
  60. "selector_separator_newline": Boolean,
  61. "newline_between_rules": Boolean,
  62. // HTML-only
  63. "max_char": Number, // obsolete since 1.3.5
  64. "unformatted": [String, Array],
  65. "indent_inner_html": [Boolean],
  66. "indent_scripts": ["keep", "separate", "normal"],
  67. "extra_liners": [String, Array],
  68. // CLI
  69. "version": Boolean,
  70. "help": Boolean,
  71. "files": [path, Array],
  72. "outfile": path,
  73. "replace": Boolean,
  74. "quiet": Boolean,
  75. "type": ["js", "css", "html"],
  76. "config": path
  77. },
  78. // dasherizeShorthands provides { "indent-size": ["--indent_size"] }
  79. // translation, allowing more convenient dashes in CLI arguments
  80. shortHands = dasherizeShorthands({
  81. // Beautifier
  82. "s": ["--indent_size"],
  83. "c": ["--indent_char"],
  84. "e": ["--eol"],
  85. "l": ["--indent_level"],
  86. "t": ["--indent_with_tabs"],
  87. "p": ["--preserve_newlines"],
  88. "m": ["--max_preserve_newlines"],
  89. "P": ["--space_in_paren"],
  90. "E": ["--space_in_empty_paren"],
  91. "j": ["--jslint_happy"],
  92. "a": ["--space_after_anon_function"],
  93. "b": ["--brace_style"],
  94. "B": ["--break_chained_methods"],
  95. "k": ["--keep_array_indentation"],
  96. "x": ["--unescape_strings"],
  97. "w": ["--wrap_line_length"],
  98. "X": ["--e4x"],
  99. "n": ["--end_with_newline"],
  100. "C": ["--comma_first"],
  101. // CSS-only
  102. "L": ["--selector_separator_newline"],
  103. "N": ["--newline_between_rules"],
  104. // HTML-only
  105. "A": ["--wrap_attributes"],
  106. "i": ["--wrap_attributes_indent_size"],
  107. "W": ["--max_char"], // obsolete since 1.3.5
  108. "U": ["--unformatted"],
  109. "I": ["--indent_inner_html"],
  110. "S": ["--indent_scripts"],
  111. "E": ["--extra_liners"],
  112. // non-dasherized hybrid shortcuts
  113. "good-stuff": [
  114. "--keep_array_indentation",
  115. "--keep_function_indentation",
  116. "--jslint_happy"
  117. ],
  118. "js": ["--type", "js"],
  119. "css": ["--type", "css"],
  120. "html": ["--type", "html"],
  121. // CLI
  122. "v": ["--version"],
  123. "h": ["--help"],
  124. "f": ["--files"],
  125. "o": ["--outfile"],
  126. "r": ["--replace"],
  127. "q": ["--quiet"]
  128. // no shorthand for "config"
  129. });
  130. function verifyExists(fullPath) {
  131. return fs.existsSync(fullPath) ? fullPath : null;
  132. }
  133. function findRecursive(dir, fileName) {
  134. var fullPath = path.join(dir, fileName);
  135. var nextDir = path.dirname(dir);
  136. var result = verifyExists(fullPath);
  137. if (!result && (nextDir !== dir)) {
  138. result = findRecursive(nextDir, fileName);
  139. }
  140. return result;
  141. }
  142. function getUserHome() {
  143. return process.env.HOME || process.env.USERPROFILE;
  144. }
  145. // var cli = require('js-beautify/cli'); cli.interpret();
  146. var interpret = exports.interpret = function(argv, slice) {
  147. var parsed = nopt(knownOpts, shortHands, argv, slice);
  148. if (parsed.version) {
  149. console.log(require('../../package.json').version);
  150. process.exit(0);
  151. } else if (parsed.help) {
  152. usage();
  153. process.exit(0);
  154. }
  155. var cfg = cc(
  156. parsed,
  157. cleanOptions(cc.env('jsbeautify_'), knownOpts),
  158. parsed.config,
  159. findRecursive(process.cwd(), '.jsbeautifyrc'),
  160. verifyExists(path.join(getUserHome() || "", ".jsbeautifyrc")),
  161. __dirname + '/../config/defaults.json'
  162. ).snapshot;
  163. try {
  164. // Verify arguments
  165. checkType(cfg);
  166. checkFiles(cfg);
  167. debug(cfg);
  168. // Process files synchronously to avoid EMFILE error
  169. cfg.files.forEach(processInputSync, {
  170. cfg: cfg
  171. });
  172. } catch (ex) {
  173. debug(cfg);
  174. // usage(ex);
  175. console.error(ex);
  176. console.error('Run `' + getScriptName() + ' -h` for help.');
  177. process.exit(1);
  178. }
  179. };
  180. // interpret args immediately when called as executable
  181. if (require.main === module) {
  182. interpret();
  183. }
  184. function usage(err) {
  185. var scriptName = getScriptName();
  186. var msg = [
  187. scriptName + '@' + require('../../package.json').version,
  188. '',
  189. 'CLI Options:',
  190. ' -f, --file Input file(s) (Pass \'-\' for stdin)',
  191. ' -r, --replace Write output in-place, replacing input',
  192. ' -o, --outfile Write output to file (default stdout)',
  193. ' --config Path to config file',
  194. ' --type [js|css|html] ["js"]',
  195. ' -q, --quiet Suppress logging to stdout',
  196. ' -h, --help Show this help',
  197. ' -v, --version Show the version',
  198. '',
  199. 'Beautifier Options:',
  200. ' -s, --indent-size Indentation size [4]',
  201. ' -c, --indent-char Indentation character [" "]',
  202. ' -t, --indent-with-tabs Indent with tabs, overrides -s and -c',
  203. ' -e, --eol Character(s) to use as line terminators. (default newline - "\\n")',
  204. ' -n, --end-with-newline End output with newline'
  205. ];
  206. switch (scriptName.split('-').shift()) {
  207. case "js":
  208. msg.push(' -l, --indent-level Initial indentation level [0]');
  209. msg.push(' -p, --preserve-newlines Preserve line-breaks (--no-preserve-newlines disables)');
  210. msg.push(' -m, --max-preserve-newlines Number of line-breaks to be preserved in one chunk [10]');
  211. msg.push(' -P, --space-in-paren Add padding spaces within paren, ie. f( a, b )');
  212. msg.push(' -E, --space-in-empty-paren Add a single space inside empty paren, ie. f( )');
  213. msg.push(' -j, --jslint-happy Enable jslint-stricter mode');
  214. msg.push(' -a, --space-after-anon-function Add a space before an anonymous function\'s parens, ie. function ()');
  215. msg.push(' -b, --brace-style [collapse|expand|end-expand|none] ["collapse"]');
  216. msg.push(' -B, --break-chained-methods Break chained method calls across subsequent lines');
  217. msg.push(' -k, --keep-array-indentation Preserve array indentation');
  218. msg.push(' -x, --unescape-strings Decode printable characters encoded in xNN notation');
  219. msg.push(' -w, --wrap-line-length Wrap lines at next opportunity after N characters [0]');
  220. msg.push(' -X, --e4x Pass E4X xml literals through untouched');
  221. msg.push(' --good-stuff Warm the cockles of Crockford\'s heart');
  222. msg.push(' -C, --comma-first Put commas at the beginning of new line instead of end');
  223. break;
  224. case "html":
  225. msg.push(' -b, --brace-style [collapse|expand|end-expand] ["collapse"]');
  226. msg.push(' -I, --indent-inner-html Indent body and head sections. Default is false.');
  227. msg.push(' -S, --indent-scripts [keep|separate|normal] ["normal"]');
  228. msg.push(' -w, --wrap-line-length Wrap lines at next opportunity after N characters [0]');
  229. msg.push(' -A, --wrap-attributes Wrap html tag attributes to new lines [auto|force] ["auto"]');
  230. msg.push(' -i, --wrap-attributes-indent-size Indent wrapped tags to after N characters [indent-level]');
  231. msg.push(' -p, --preserve-newlines Preserve line-breaks (--no-preserve-newlines disables)');
  232. msg.push(' -m, --max-preserve-newlines Number of line-breaks to be preserved in one chunk [10]');
  233. msg.push(' -U, --unformatted List of tags (defaults to inline) that should not be reformatted');
  234. msg.push(' -E, --extra_liners List of tags (defaults to [head,body,/html] that should have an extra newline');
  235. break;
  236. case "css":
  237. msg.push(' -L, --selector-separator-newline Add a newline between multiple selectors.')
  238. msg.push(' -N, --newline-between-rules Add a newline between CSS rules.')
  239. }
  240. if (err) {
  241. msg.push(err);
  242. msg.push('');
  243. console.error(msg.join('\n'));
  244. } else {
  245. console.log(msg.join('\n'));
  246. }
  247. }
  248. // main iterator, {cfg} passed as thisArg of forEach call
  249. function processInputSync(filepath) {
  250. var data = '',
  251. config = this.cfg,
  252. outfile = config.outfile,
  253. input;
  254. // -o passed with no value overwrites
  255. if (outfile === true || config.replace) {
  256. outfile = filepath;
  257. }
  258. if (filepath === '-') {
  259. input = process.stdin;
  260. input.resume();
  261. input.setEncoding('utf8');
  262. input.on('data', function(chunk) {
  263. data += chunk;
  264. });
  265. input.on('end', function() {
  266. makePretty(data, config, outfile, writePretty);
  267. });
  268. } else {
  269. var dir = path.dirname(outfile);
  270. mkdirp.sync(dir);
  271. data = fs.readFileSync(filepath, 'utf8');
  272. makePretty(data, config, outfile, writePretty);
  273. }
  274. }
  275. function makePretty(code, config, outfile, callback) {
  276. try {
  277. var fileType = getOutputType(outfile, config.type);
  278. var pretty = beautify[fileType](code, config);
  279. callback(null, pretty, outfile, config);
  280. } catch (ex) {
  281. callback(ex);
  282. }
  283. }
  284. function writePretty(err, pretty, outfile, config) {
  285. if (err) {
  286. console.error(err);
  287. process.exit(1);
  288. }
  289. if (outfile) {
  290. if (isFileDifferent(outfile, pretty)) {
  291. try {
  292. fs.writeFileSync(outfile, pretty, 'utf8');
  293. logToStdout('beautified ' + path.relative(process.cwd(), outfile), config);
  294. } catch (ex) {
  295. onOutputError(ex);
  296. }
  297. } else {
  298. logToStdout('beautified ' + path.relative(process.cwd(), outfile) + ' - unchanged', config);
  299. }
  300. } else {
  301. process.stdout.write(pretty);
  302. }
  303. }
  304. function isFileDifferent(filePath, expected) {
  305. try {
  306. return fs.readFileSync(filePath, 'utf8') !== expected;
  307. } catch (ex) {
  308. // failing to read is the same as different
  309. return true;
  310. }
  311. }
  312. // workaround the fact that nopt.clean doesn't return the object passed in :P
  313. function cleanOptions(data, types) {
  314. nopt.clean(data, types);
  315. return data;
  316. }
  317. // error handler for output stream that swallows errors silently,
  318. // allowing the loop to continue over unwritable files.
  319. function onOutputError(err) {
  320. if (err.code === 'EACCES') {
  321. console.error(err.path + " is not writable. Skipping!");
  322. } else {
  323. console.error(err);
  324. process.exit(0);
  325. }
  326. }
  327. // turn "--foo_bar" into "foo-bar"
  328. function dasherizeFlag(str) {
  329. return str.replace(/^\-+/, '').replace(/_/g, '-');
  330. }
  331. // translate weird python underscored keys into dashed argv,
  332. // avoiding single character aliases.
  333. function dasherizeShorthands(hash) {
  334. // operate in-place
  335. Object.keys(hash).forEach(function(key) {
  336. // each key value is an array
  337. var val = hash[key][0];
  338. // only dasherize one-character shorthands
  339. if (key.length === 1 && val.indexOf('_') > -1) {
  340. hash[dasherizeFlag(val)] = val;
  341. }
  342. });
  343. return hash;
  344. }
  345. function getOutputType(outfile, configType) {
  346. if (outfile && /\.(js|css|html)$/.test(outfile)) {
  347. return outfile.split('.').pop();
  348. }
  349. return configType;
  350. }
  351. function getScriptName() {
  352. return path.basename(process.argv[1]);
  353. }
  354. function checkType(parsed) {
  355. var scriptType = getScriptName().split('-').shift();
  356. debug("executable type:", scriptType);
  357. var parsedType = parsed.type;
  358. debug("parsed type:", parsedType);
  359. if (!parsedType) {
  360. debug("type defaulted:", scriptType);
  361. parsed.type = scriptType;
  362. }
  363. }
  364. function checkFiles(parsed) {
  365. var argv = parsed.argv;
  366. if (!parsed.files) {
  367. parsed.files = [];
  368. } else {
  369. if (argv.cooked.indexOf('-') > -1) {
  370. // strip stdin path eagerly added by nopt in '-f -' case
  371. parsed.files.some(removeDashedPath);
  372. }
  373. }
  374. if (argv.remain.length) {
  375. // assume any remaining args are files
  376. argv.remain.forEach(function(f) {
  377. parsed.files.push(path.resolve(f));
  378. });
  379. }
  380. if ('string' === typeof parsed.outfile && !parsed.files.length) {
  381. // use outfile as input when no other files passed in args
  382. parsed.files.push(parsed.outfile);
  383. // operation is now an implicit overwrite
  384. parsed.replace = true;
  385. }
  386. if (argv.original.indexOf('-') > -1) {
  387. // ensure '-' without '-f' still consumes stdin
  388. parsed.files.push('-');
  389. }
  390. if (!parsed.files.length) {
  391. throw 'Must define at least one file.';
  392. }
  393. debug('files.length ' + parsed.files.length);
  394. parsed.files.forEach(testFilePath);
  395. return parsed;
  396. }
  397. function removeDashedPath(filepath, i, arr) {
  398. var found = filepath.lastIndexOf('-') === (filepath.length - 1);
  399. if (found) {
  400. arr.splice(i, 1);
  401. }
  402. return found;
  403. }
  404. function testFilePath(filepath) {
  405. try {
  406. if (filepath !== "-") {
  407. fs.statSync(filepath);
  408. }
  409. } catch (err) {
  410. throw 'Unable to open path "' + filepath + '"';
  411. }
  412. }
  413. function logToStdout(str, config) {
  414. if (typeof config.quiet === "undefined" || !config.quiet) {
  415. console.log(str);
  416. }
  417. }