lessc 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. #!/usr/bin/env node
  2. var path = require('path'),
  3. fs = require('../lib/less-node/fs'),
  4. os = require('os'),
  5. utils = require('../lib/less/utils'),
  6. Constants = require('../lib/less/constants'),
  7. errno,
  8. mkdirp;
  9. try {
  10. errno = require('errno');
  11. } catch (err) {
  12. errno = null;
  13. }
  14. var less = require('../lib/less-node'),
  15. pluginManager = new less.PluginManager(less),
  16. fileManager = new less.FileManager(),
  17. plugins = [],
  18. queuePlugins = [],
  19. args = process.argv.slice(1),
  20. silent = false,
  21. verbose = false,
  22. options = less.options;
  23. options.plugins = plugins;
  24. options.reUsePluginManager = true;
  25. var sourceMapOptions = {};
  26. var continueProcessing = true;
  27. // Calling process.exit does not flush stdout always. Instead of exiting the process, we set the process' exitCode,
  28. // close all handles and wait for the event loop to exit the process.
  29. // @see https://github.com/nodejs/node/issues/6409
  30. // Unfortunately, node 0.10.x does not support setting process.exitCode, so we need to call reallyExit() explicitly.
  31. // @see https://nodejs.org/api/process.html#process_process_exitcode
  32. // Additionally we also need to make sure that uncaughtExceptions are never swallowed.
  33. // @see https://github.com/less/less.js/issues/2881
  34. // This code can safely be removed if node 0.10.x is not supported anymore.
  35. process.on('exit', function() { process.reallyExit(process.exitCode); });
  36. process.on('uncaughtException', function(err) {
  37. console.error(err);
  38. process.exitCode = 1;
  39. });
  40. // This code will still be required because otherwise rejected promises would not be reported to the user
  41. process.on('unhandledRejection', function(err) {
  42. console.error(err);
  43. process.exitCode = 1;
  44. });
  45. var checkArgFunc = function(arg, option) {
  46. if (!option) {
  47. console.error(arg + ' option requires a parameter');
  48. continueProcessing = false;
  49. process.exitCode = 1;
  50. return false;
  51. }
  52. return true;
  53. };
  54. var checkBooleanArg = function(arg) {
  55. var onOff = /^((on|t|true|y|yes)|(off|f|false|n|no))$/i.exec(arg);
  56. if (!onOff) {
  57. console.error(' unable to parse ' + arg + ' as a boolean. use one of on/t/true/y/yes/off/f/false/n/no');
  58. continueProcessing = false;
  59. process.exitCode = 1;
  60. return false;
  61. }
  62. return Boolean(onOff[2]);
  63. };
  64. var parseVariableOption = function(option, variables) {
  65. var parts = option.split('=', 2);
  66. variables[parts[0]] = parts[1];
  67. };
  68. var sourceMapFileInline = false;
  69. function printUsage() {
  70. less.lesscHelper.printUsage();
  71. pluginManager.Loader.printUsage(plugins);
  72. continueProcessing = false;
  73. }
  74. function render() {
  75. if (!continueProcessing) {
  76. return;
  77. }
  78. var input = args[1];
  79. if (input && input != '-') {
  80. input = path.resolve(process.cwd(), input);
  81. }
  82. var output = args[2];
  83. var outputbase = args[2];
  84. if (output) {
  85. output = path.resolve(process.cwd(), output);
  86. }
  87. if (options.sourceMap) {
  88. sourceMapOptions.sourceMapInputFilename = input;
  89. if (!sourceMapOptions.sourceMapFullFilename) {
  90. if (!output && !sourceMapFileInline) {
  91. console.error('the sourcemap option only has an optional filename if the css filename is given');
  92. console.error('consider adding --source-map-map-inline which embeds the sourcemap into the css');
  93. process.exitCode = 1;
  94. return;
  95. }
  96. // its in the same directory, so always just the basename
  97. if (output) {
  98. sourceMapOptions.sourceMapOutputFilename = path.basename(output);
  99. sourceMapOptions.sourceMapFullFilename = output + '.map';
  100. }
  101. // its in the same directory, so always just the basename
  102. if ('sourceMapFullFilename' in sourceMapOptions) {
  103. sourceMapOptions.sourceMapFilename = path.basename(sourceMapOptions.sourceMapFullFilename);
  104. }
  105. } else if (options.sourceMap && !sourceMapFileInline) {
  106. var mapFilename = path.resolve(process.cwd(), sourceMapOptions.sourceMapFullFilename),
  107. mapDir = path.dirname(mapFilename),
  108. outputDir = path.dirname(output);
  109. // find the path from the map to the output file
  110. sourceMapOptions.sourceMapOutputFilename = path.join(
  111. path.relative(mapDir, outputDir), path.basename(output));
  112. // make the sourcemap filename point to the sourcemap relative to the css file output directory
  113. sourceMapOptions.sourceMapFilename = path.join(
  114. path.relative(outputDir, mapDir), path.basename(sourceMapOptions.sourceMapFullFilename));
  115. }
  116. }
  117. if (sourceMapOptions.sourceMapBasepath === undefined) {
  118. sourceMapOptions.sourceMapBasepath = input ? path.dirname(input) : process.cwd();
  119. }
  120. if (sourceMapOptions.sourceMapRootpath === undefined) {
  121. var pathToMap = path.dirname((sourceMapFileInline ? output : sourceMapOptions.sourceMapFullFilename) || '.'),
  122. pathToInput = path.dirname(sourceMapOptions.sourceMapInputFilename || '.');
  123. sourceMapOptions.sourceMapRootpath = path.relative(pathToMap, pathToInput);
  124. }
  125. if (!input) {
  126. console.error('lessc: no input files');
  127. console.error('');
  128. printUsage();
  129. process.exitCode = 1;
  130. return;
  131. }
  132. var ensureDirectory = function (filepath) {
  133. var dir = path.dirname(filepath),
  134. cmd,
  135. existsSync = fs.existsSync || path.existsSync;
  136. if (!existsSync(dir)) {
  137. if (mkdirp === undefined) {
  138. try {mkdirp = require('mkdirp');}
  139. catch (e) { mkdirp = null; }
  140. }
  141. cmd = mkdirp && mkdirp.sync || fs.mkdirSync;
  142. cmd(dir);
  143. }
  144. };
  145. if (options.depends) {
  146. if (!outputbase) {
  147. console.error('option --depends requires an output path to be specified');
  148. process.exitCode = 1;
  149. return;
  150. }
  151. process.stdout.write(outputbase + ': ');
  152. }
  153. if (!sourceMapFileInline) {
  154. var writeSourceMap = function(output, onDone) {
  155. output = output || '';
  156. var filename = sourceMapOptions.sourceMapFullFilename;
  157. ensureDirectory(filename);
  158. fs.writeFile(filename, output, 'utf8', function (err) {
  159. if (err) {
  160. var description = 'Error: ';
  161. if (errno && errno.errno[err.errno]) {
  162. description += errno.errno[err.errno].description;
  163. } else {
  164. description += err.code + ' ' + err.message;
  165. }
  166. console.error('lessc: failed to create file ' + filename);
  167. console.error(description);
  168. process.exitCode = 1;
  169. } else {
  170. less.logger.info('lessc: wrote ' + filename);
  171. }
  172. onDone();
  173. });
  174. };
  175. }
  176. var writeSourceMapIfNeeded = function(output, onDone) {
  177. if (options.sourceMap && !sourceMapFileInline) {
  178. writeSourceMap(output, onDone);
  179. } else {
  180. onDone();
  181. }
  182. };
  183. var writeOutput = function(output, result, onSuccess) {
  184. if (options.depends) {
  185. onSuccess();
  186. } else if (output) {
  187. ensureDirectory(output);
  188. fs.writeFile(output, result.css, {encoding: 'utf8'}, function (err) {
  189. if (err) {
  190. var description = 'Error: ';
  191. if (errno && errno.errno[err.errno]) {
  192. description += errno.errno[err.errno].description;
  193. } else {
  194. description += err.code + ' ' + err.message;
  195. }
  196. console.error('lessc: failed to create file ' + output);
  197. console.error(description);
  198. process.exitCode = 1;
  199. } else {
  200. less.logger.info('lessc: wrote ' + output);
  201. onSuccess();
  202. }
  203. });
  204. } else if (!options.depends) {
  205. process.stdout.write(result.css);
  206. onSuccess();
  207. }
  208. };
  209. var logDependencies = function(options, result) {
  210. if (options.depends) {
  211. var depends = '';
  212. for (var i = 0; i < result.imports.length; i++) {
  213. depends += result.imports[i] + ' ';
  214. }
  215. console.log(depends);
  216. }
  217. };
  218. var parseLessFile = function (e, data) {
  219. if (e) {
  220. console.error('lessc: ' + e.message);
  221. process.exitCode = 1;
  222. return;
  223. }
  224. data = data.replace(/^\uFEFF/, '');
  225. options.paths = [path.dirname(input)].concat(options.paths);
  226. options.filename = input;
  227. if (options.lint) {
  228. options.sourceMap = false;
  229. }
  230. sourceMapOptions.sourceMapFileInline = sourceMapFileInline;
  231. if (options.sourceMap) {
  232. options.sourceMap = sourceMapOptions;
  233. }
  234. less.logger.addListener({
  235. info: function(msg) {
  236. if (verbose) {
  237. console.log(msg);
  238. }
  239. },
  240. warn: function(msg) {
  241. // do not show warning if the silent option is used
  242. if (!silent) {
  243. console.warn(msg);
  244. }
  245. },
  246. error: function(msg) {
  247. console.error(msg);
  248. }
  249. });
  250. less.render(data, options)
  251. .then(function(result) {
  252. if (!options.lint) {
  253. writeOutput(output, result, function() {
  254. writeSourceMapIfNeeded(result.map, function() {
  255. logDependencies(options, result);
  256. });
  257. });
  258. }
  259. },
  260. function(err) {
  261. if (!options.silent) {
  262. console.error(err.toString({
  263. stylize: options.color && less.lesscHelper.stylize
  264. }));
  265. }
  266. process.exitCode = 1;
  267. });
  268. };
  269. if (input != '-') {
  270. fs.readFile(input, 'utf8', parseLessFile);
  271. } else {
  272. process.stdin.resume();
  273. process.stdin.setEncoding('utf8');
  274. var buffer = '';
  275. process.stdin.on('data', function(data) {
  276. buffer += data;
  277. });
  278. process.stdin.on('end', function() {
  279. parseLessFile(false, buffer);
  280. });
  281. }
  282. }
  283. function processPluginQueue() {
  284. var x = 0;
  285. function pluginError(name) {
  286. console.error('Unable to load plugin ' + name +
  287. ' please make sure that it is installed under or at the same level as less');
  288. process.exitCode = 1;
  289. }
  290. function pluginFinished(plugin) {
  291. x++;
  292. plugins.push(plugin);
  293. if (x === queuePlugins.length) {
  294. render();
  295. }
  296. }
  297. queuePlugins.forEach(function(queue) {
  298. var context = utils.clone(options);
  299. pluginManager.Loader.loadPlugin(queue.name, process.cwd(), context, less.environment, fileManager)
  300. .then(function(data) {
  301. pluginFinished({
  302. fileContent: data.contents,
  303. filename: data.filename,
  304. options: queue.options
  305. });
  306. })
  307. .catch(function() {
  308. pluginError(queue.name);
  309. });
  310. });
  311. }
  312. // self executing function so we can return
  313. (function() {
  314. args = args.filter(function (arg) {
  315. var match;
  316. match = arg.match(/^-I(.+)$/);
  317. if (match) {
  318. options.paths.push(match[1]);
  319. return false;
  320. }
  321. match = arg.match(/^--?([a-z][0-9a-z-]*)(?:=(.*))?$/i);
  322. if (match) {
  323. arg = match[1];
  324. } else {
  325. return arg;
  326. }
  327. switch (arg) {
  328. case 'v':
  329. case 'version':
  330. console.log('lessc ' + less.version.join('.') + ' (Less Compiler) [JavaScript]');
  331. continueProcessing = false;
  332. break;
  333. case 'verbose':
  334. verbose = true;
  335. break;
  336. case 's':
  337. case 'silent':
  338. silent = true;
  339. break;
  340. case 'l':
  341. case 'lint':
  342. options.lint = true;
  343. break;
  344. case 'strict-imports':
  345. options.strictImports = true;
  346. break;
  347. case 'h':
  348. case 'help':
  349. printUsage();
  350. break;
  351. case 'x':
  352. case 'compress':
  353. options.compress = true;
  354. break;
  355. case 'insecure':
  356. options.insecure = true;
  357. break;
  358. case 'M':
  359. case 'depends':
  360. options.depends = true;
  361. break;
  362. case 'max-line-len':
  363. if (checkArgFunc(arg, match[2])) {
  364. options.maxLineLen = parseInt(match[2], 10);
  365. if (options.maxLineLen <= 0) {
  366. options.maxLineLen = -1;
  367. }
  368. }
  369. break;
  370. case 'no-color':
  371. options.color = false;
  372. break;
  373. case 'ie-compat':
  374. options.ieCompat = true;
  375. break;
  376. case 'js':
  377. options.javascriptEnabled = true;
  378. break;
  379. case 'no-js':
  380. console.error('The "--no-js" argument is deprecated, as inline JavaScript ' +
  381. 'is disabled by default. Use "--js" to enable inline JavaScript (not recommended).');
  382. break;
  383. case 'include-path':
  384. if (checkArgFunc(arg, match[2])) {
  385. // ; supported on windows.
  386. // : supported on windows and linux, excluding a drive letter like C:\ so C:\file:D:\file parses to 2
  387. options.paths = match[2]
  388. .split(os.type().match(/Windows/) ? /:(?!\\)|;/ : ':')
  389. .map(function(p) {
  390. if (p) {
  391. return path.resolve(process.cwd(), p);
  392. }
  393. });
  394. }
  395. break;
  396. case 'line-numbers':
  397. if (checkArgFunc(arg, match[2])) {
  398. options.dumpLineNumbers = match[2];
  399. }
  400. break;
  401. case 'source-map':
  402. options.sourceMap = true;
  403. if (match[2]) {
  404. sourceMapOptions.sourceMapFullFilename = match[2];
  405. }
  406. break;
  407. case 'source-map-rootpath':
  408. if (checkArgFunc(arg, match[2])) {
  409. sourceMapOptions.sourceMapRootpath = match[2];
  410. }
  411. break;
  412. case 'source-map-basepath':
  413. if (checkArgFunc(arg, match[2])) {
  414. sourceMapOptions.sourceMapBasepath = match[2];
  415. }
  416. break;
  417. case 'source-map-inline':
  418. case 'source-map-map-inline':
  419. sourceMapFileInline = true;
  420. options.sourceMap = true;
  421. break;
  422. case 'source-map-include-source':
  423. case 'source-map-less-inline':
  424. sourceMapOptions.outputSourceFiles = true;
  425. break;
  426. case 'source-map-url':
  427. if (checkArgFunc(arg, match[2])) {
  428. sourceMapOptions.sourceMapURL = match[2];
  429. }
  430. break;
  431. case 'rp':
  432. case 'rootpath':
  433. if (checkArgFunc(arg, match[2])) {
  434. options.rootpath = match[2].replace(/\\/g, '/');
  435. }
  436. break;
  437. case 'relative-urls':
  438. console.warn('The --relative-urls option has been deprecated. Use --rewrite-urls=all.');
  439. options.rewriteUrls = Constants.RewriteUrls.ALL;
  440. break;
  441. case 'ru':
  442. case 'rewrite-urls':
  443. var m = match[2];
  444. if (m) {
  445. if (m === 'local') {
  446. options.rewriteUrls = Constants.RewriteUrls.LOCAL;
  447. } else if (m === 'off') {
  448. options.rewriteUrls = Constants.RewriteUrls.OFF;
  449. } else if (m === 'all') {
  450. options.rewriteUrls = Constants.RewriteUrls.ALL;
  451. } else {
  452. console.error('Unknown rewrite-urls argument ' + m);
  453. continueProcessing = false;
  454. process.exitCode = 1;
  455. }
  456. } else {
  457. options.rewriteUrls = Constants.RewriteUrls.ALL;
  458. }
  459. break;
  460. case 'sm':
  461. case 'strict-math':
  462. console.warn('The --strict-math option has been deprecated. Use --math=strict.');
  463. if (checkArgFunc(arg, match[2])) {
  464. if (checkBooleanArg(match[2])) {
  465. options.math = Constants.Math.STRICT_LEGACY;
  466. }
  467. }
  468. break;
  469. case 'm':
  470. case 'math':
  471. if (checkArgFunc(arg, match[2])) {
  472. options.math = match[2];
  473. }
  474. break;
  475. case 'su':
  476. case 'strict-units':
  477. if (checkArgFunc(arg, match[2])) {
  478. options.strictUnits = checkBooleanArg(match[2]);
  479. }
  480. break;
  481. case 'global-var':
  482. if (checkArgFunc(arg, match[2])) {
  483. if (!options.globalVars) {
  484. options.globalVars = {};
  485. }
  486. parseVariableOption(match[2], options.globalVars);
  487. }
  488. break;
  489. case 'modify-var':
  490. if (checkArgFunc(arg, match[2])) {
  491. if (!options.modifyVars) {
  492. options.modifyVars = {};
  493. }
  494. parseVariableOption(match[2], options.modifyVars);
  495. }
  496. break;
  497. case 'url-args':
  498. if (checkArgFunc(arg, match[2])) {
  499. options.urlArgs = match[2];
  500. }
  501. break;
  502. case 'plugin':
  503. var splitupArg = match[2].match(/^([^=]+)(=(.*))?/),
  504. name = splitupArg[1],
  505. pluginOptions = splitupArg[3];
  506. queuePlugins.push({ name: name, options: pluginOptions });
  507. break;
  508. default:
  509. queuePlugins.push({ name: arg, options: match[2], default: true });
  510. break;
  511. }
  512. });
  513. if (queuePlugins.length > 0) {
  514. processPluginQueue();
  515. }
  516. else {
  517. render();
  518. }
  519. })();