lessc 18 KB

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