lessc 16 KB

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