lessc.js 18 KB

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