lessc 17 KB

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