lessc.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. import path from 'path';
  2. import fs from './less-node/fs';
  3. import os from 'os';
  4. import * as utils from './less/utils';
  5. import * as Constants from './less/constants';
  6. let errno;
  7. let mkdirp;
  8. try {
  9. errno = require('errno');
  10. } catch (err) {
  11. errno = null;
  12. }
  13. import less from './less-node';
  14. const pluginManager = new less.PluginManager(less);
  15. const fileManager = new less.FileManager();
  16. const plugins = [];
  17. const queuePlugins = [];
  18. let args = process.argv.slice(1);
  19. let silent = false;
  20. let verbose = false;
  21. const options = less.options;
  22. options.plugins = plugins;
  23. options.reUsePluginManager = true;
  24. const sourceMapOptions = {};
  25. let 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', () => { process.reallyExit(process.exitCode); });
  35. process.on('uncaughtException', 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', err => {
  41. console.error(err);
  42. process.exitCode = 1;
  43. });
  44. const checkArgFunc = (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. const checkBooleanArg = arg => {
  54. const 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. const parseVariableOption = (option, variables) => {
  64. const parts = option.split('=', 2);
  65. variables[parts[0]] = parts[1];
  66. };
  67. let 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. let input = args[1];
  78. if (input && input != '-') {
  79. input = path.resolve(process.cwd(), input);
  80. }
  81. let output = args[2];
  82. const 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. const mapFilename = path.resolve(process.cwd(), sourceMapOptions.sourceMapFullFilename);
  106. const mapDir = path.dirname(mapFilename);
  107. const 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. const pathToMap = path.dirname((sourceMapFileInline ? output : sourceMapOptions.sourceMapFullFilename) || '.');
  121. const 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. const ensureDirectory = filepath => {
  132. const dir = path.dirname(filepath);
  133. let cmd;
  134. const 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 = (output = '', onDone) => {
  154. const filename = sourceMapOptions.sourceMapFullFilename;
  155. ensureDirectory(filename);
  156. fs.writeFile(filename, output, 'utf8', err => {
  157. if (err) {
  158. let description = 'Error: ';
  159. if (errno && errno.errno[err.errno]) {
  160. description += errno.errno[err.errno].description;
  161. } else {
  162. description += `${err.code} ${err.message}`;
  163. }
  164. console.error(`lessc: failed to create file ${filename}`);
  165. console.error(description);
  166. process.exitCode = 1;
  167. } else {
  168. less.logger.info(`lessc: wrote ${filename}`);
  169. }
  170. onDone();
  171. });
  172. };
  173. }
  174. const writeSourceMapIfNeeded = (output, onDone) => {
  175. if (options.sourceMap && !sourceMapFileInline) {
  176. writeSourceMap(output, onDone);
  177. } else {
  178. onDone();
  179. }
  180. };
  181. const writeOutput = (output, result, onSuccess) => {
  182. if (options.depends) {
  183. onSuccess();
  184. } else if (output) {
  185. ensureDirectory(output);
  186. fs.writeFile(output, result.css, {encoding: 'utf8'}, err => {
  187. if (err) {
  188. let description = 'Error: ';
  189. if (errno && errno.errno[err.errno]) {
  190. description += errno.errno[err.errno].description;
  191. } else {
  192. description += `${err.code} ${err.message}`;
  193. }
  194. console.error(`lessc: failed to create file ${output}`);
  195. console.error(description);
  196. process.exitCode = 1;
  197. } else {
  198. less.logger.info(`lessc: wrote ${output}`);
  199. onSuccess();
  200. }
  201. });
  202. } else if (!options.depends) {
  203. process.stdout.write(result.css);
  204. onSuccess();
  205. }
  206. };
  207. const logDependencies = (options, result) => {
  208. if (options.depends) {
  209. let depends = '';
  210. for (let i = 0; i < result.imports.length; i++) {
  211. depends += `${result.imports[i]} `;
  212. }
  213. console.log(depends);
  214. }
  215. };
  216. const parseLessFile = (e, data) => {
  217. if (e) {
  218. console.error(`lessc: ${e.message}`);
  219. process.exitCode = 1;
  220. return;
  221. }
  222. data = data.replace(/^\uFEFF/, '');
  223. options.paths = [path.dirname(input)].concat(options.paths);
  224. options.filename = input;
  225. if (options.lint) {
  226. options.sourceMap = false;
  227. }
  228. sourceMapOptions.sourceMapFileInline = sourceMapFileInline;
  229. if (options.sourceMap) {
  230. options.sourceMap = sourceMapOptions;
  231. }
  232. less.logger.addListener({
  233. info: function(msg) {
  234. if (verbose) {
  235. console.log(msg);
  236. }
  237. },
  238. warn: function(msg) {
  239. // do not show warning if the silent option is used
  240. if (!silent) {
  241. console.warn(msg);
  242. }
  243. },
  244. error: function(msg) {
  245. console.error(msg);
  246. }
  247. });
  248. less.render(data, options)
  249. .then(result => {
  250. if (!options.lint) {
  251. writeOutput(output, result, () => {
  252. writeSourceMapIfNeeded(result.map, () => {
  253. logDependencies(options, result);
  254. });
  255. });
  256. }
  257. },
  258. err => {
  259. if (!options.silent) {
  260. console.error(err.toString({
  261. stylize: options.color && less.lesscHelper.stylize
  262. }));
  263. }
  264. process.exitCode = 1;
  265. });
  266. };
  267. if (input != '-') {
  268. fs.readFile(input, 'utf8', parseLessFile);
  269. } else {
  270. process.stdin.resume();
  271. process.stdin.setEncoding('utf8');
  272. let buffer = '';
  273. process.stdin.on('data', data => {
  274. buffer += data;
  275. });
  276. process.stdin.on('end', () => {
  277. parseLessFile(false, buffer);
  278. });
  279. }
  280. }
  281. function processPluginQueue() {
  282. let x = 0;
  283. function pluginError(name) {
  284. console.error(`Unable to load plugin ${name} please make sure that it is installed under or at the same level as less`);
  285. process.exitCode = 1;
  286. }
  287. function pluginFinished(plugin) {
  288. x++;
  289. plugins.push(plugin);
  290. if (x === queuePlugins.length) {
  291. render();
  292. }
  293. }
  294. queuePlugins.forEach(queue => {
  295. const context = utils.clone(options);
  296. pluginManager.Loader.loadPlugin(queue.name, process.cwd(), context, less.environment, fileManager)
  297. .then(data => {
  298. pluginFinished({
  299. fileContent: data.contents,
  300. filename: data.filename,
  301. options: queue.options
  302. });
  303. })
  304. .catch(() => {
  305. pluginError(queue.name);
  306. });
  307. });
  308. }
  309. // self executing function so we can return
  310. (() => {
  311. args = args.filter(arg => {
  312. let match;
  313. match = arg.match(/^-I(.+)$/);
  314. if (match) {
  315. options.paths.push(match[1]);
  316. return false;
  317. }
  318. match = arg.match(/^--?([a-z][0-9a-z-]*)(?:=(.*))?$/i);
  319. if (match) {
  320. arg = match[1];
  321. } else {
  322. return arg;
  323. }
  324. switch (arg) {
  325. case 'v':
  326. case 'version':
  327. console.log(`lessc ${less.version.join('.')} (Less Compiler) [JavaScript]`);
  328. continueProcessing = false;
  329. break;
  330. case 'verbose':
  331. verbose = true;
  332. break;
  333. case 's':
  334. case 'silent':
  335. silent = true;
  336. break;
  337. case 'l':
  338. case 'lint':
  339. options.lint = true;
  340. break;
  341. case 'strict-imports':
  342. options.strictImports = true;
  343. break;
  344. case 'h':
  345. case 'help':
  346. printUsage();
  347. break;
  348. case 'x':
  349. case 'compress':
  350. options.compress = true;
  351. break;
  352. case 'insecure':
  353. options.insecure = true;
  354. break;
  355. case 'M':
  356. case 'depends':
  357. options.depends = true;
  358. break;
  359. case 'max-line-len':
  360. if (checkArgFunc(arg, match[2])) {
  361. options.maxLineLen = parseInt(match[2], 10);
  362. if (options.maxLineLen <= 0) {
  363. options.maxLineLen = -1;
  364. }
  365. }
  366. break;
  367. case 'no-color':
  368. options.color = false;
  369. break;
  370. case 'js':
  371. options.javascriptEnabled = true;
  372. break;
  373. case 'no-js':
  374. console.error('The "--no-js" argument is deprecated, as inline JavaScript ' +
  375. 'is disabled by default. Use "--js" to enable inline JavaScript (not recommended).');
  376. break;
  377. case 'include-path':
  378. if (checkArgFunc(arg, match[2])) {
  379. // ; supported on windows.
  380. // : supported on windows and linux, excluding a drive letter like C:\ so C:\file:D:\file parses to 2
  381. options.paths = match[2]
  382. .split(os.type().match(/Windows/) ? /:(?!\\)|;/ : ':')
  383. .map(p => {
  384. if (p) {
  385. return path.resolve(process.cwd(), p);
  386. }
  387. });
  388. }
  389. break;
  390. case 'line-numbers':
  391. if (checkArgFunc(arg, match[2])) {
  392. options.dumpLineNumbers = match[2];
  393. }
  394. break;
  395. case 'source-map':
  396. options.sourceMap = true;
  397. if (match[2]) {
  398. sourceMapOptions.sourceMapFullFilename = match[2];
  399. }
  400. break;
  401. case 'source-map-rootpath':
  402. if (checkArgFunc(arg, match[2])) {
  403. sourceMapOptions.sourceMapRootpath = match[2];
  404. }
  405. break;
  406. case 'source-map-basepath':
  407. if (checkArgFunc(arg, match[2])) {
  408. sourceMapOptions.sourceMapBasepath = match[2];
  409. }
  410. break;
  411. case 'source-map-inline':
  412. case 'source-map-map-inline':
  413. sourceMapFileInline = true;
  414. options.sourceMap = true;
  415. break;
  416. case 'source-map-include-source':
  417. case 'source-map-less-inline':
  418. sourceMapOptions.outputSourceFiles = true;
  419. break;
  420. case 'source-map-url':
  421. if (checkArgFunc(arg, match[2])) {
  422. sourceMapOptions.sourceMapURL = match[2];
  423. }
  424. break;
  425. case 'rp':
  426. case 'rootpath':
  427. if (checkArgFunc(arg, match[2])) {
  428. options.rootpath = match[2].replace(/\\/g, '/');
  429. }
  430. break;
  431. case 'relative-urls':
  432. console.warn('The --relative-urls option has been deprecated. Use --rewrite-urls=all.');
  433. options.rewriteUrls = Constants.RewriteUrls.ALL;
  434. break;
  435. case 'ru':
  436. case 'rewrite-urls':
  437. const m = match[2];
  438. if (m) {
  439. if (m === 'local') {
  440. options.rewriteUrls = Constants.RewriteUrls.LOCAL;
  441. } else if (m === 'off') {
  442. options.rewriteUrls = Constants.RewriteUrls.OFF;
  443. } else if (m === 'all') {
  444. options.rewriteUrls = Constants.RewriteUrls.ALL;
  445. } else {
  446. console.error(`Unknown rewrite-urls argument ${m}`);
  447. continueProcessing = false;
  448. process.exitCode = 1;
  449. }
  450. } else {
  451. options.rewriteUrls = Constants.RewriteUrls.ALL;
  452. }
  453. break;
  454. case 'sm':
  455. case 'strict-math':
  456. console.warn('The --strict-math option has been deprecated. Use --math=strict.');
  457. if (checkArgFunc(arg, match[2])) {
  458. if (checkBooleanArg(match[2])) {
  459. options.math = Constants.Math.STRICT_LEGACY;
  460. }
  461. }
  462. break;
  463. case 'm':
  464. case 'math':
  465. if (checkArgFunc(arg, match[2])) {
  466. options.math = match[2];
  467. }
  468. break;
  469. case 'su':
  470. case 'strict-units':
  471. if (checkArgFunc(arg, match[2])) {
  472. options.strictUnits = checkBooleanArg(match[2]);
  473. }
  474. break;
  475. case 'global-var':
  476. if (checkArgFunc(arg, match[2])) {
  477. if (!options.globalVars) {
  478. options.globalVars = {};
  479. }
  480. parseVariableOption(match[2], options.globalVars);
  481. }
  482. break;
  483. case 'modify-var':
  484. if (checkArgFunc(arg, match[2])) {
  485. if (!options.modifyVars) {
  486. options.modifyVars = {};
  487. }
  488. parseVariableOption(match[2], options.modifyVars);
  489. }
  490. break;
  491. case 'url-args':
  492. if (checkArgFunc(arg, match[2])) {
  493. options.urlArgs = match[2];
  494. }
  495. break;
  496. case 'plugin':
  497. const splitupArg = match[2].match(/^([^=]+)(=(.*))?/);
  498. const name = splitupArg[1];
  499. const pluginOptions = splitupArg[3];
  500. queuePlugins.push({ name, options: pluginOptions });
  501. break;
  502. default:
  503. queuePlugins.push({ name: arg, options: match[2], default: true });
  504. break;
  505. }
  506. });
  507. if (queuePlugins.length > 0) {
  508. processPluginQueue();
  509. }
  510. else {
  511. render();
  512. }
  513. })();