hulk 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #!/usr/bin/env node
  2. /*
  3. * Copyright 2011 Twitter, Inc.
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. var hogan = require('../lib/hogan.js'),
  17. path = require('path'),
  18. fs = require('fs');
  19. var specials = ['/', '.', '*', '+', '?', '|','(', ')', '[', ']', '{', '}', '\\'],
  20. specialsRegExp = new RegExp('(\\' + specials.join('|\\') + ')', 'g'),
  21. templates;
  22. // Escape special regexp characters
  23. function esc(text) {
  24. return text.replace(specialsRegExp, '\\$1');
  25. }
  26. // Check for dirs and correct ext (<3 for windows)
  27. function extractFiles(args) {
  28. var usage = 'USAGE: hulk ./templates/*.mustaches\n' +
  29. 'NOTE: hulk supports the "*" wildcard and allows you to target specific extensions too',
  30. files = [];
  31. if (!args.length) {
  32. console.log(usage);
  33. process.exit(-1);
  34. }
  35. args.forEach(function (arg) {
  36. if (/\*/.test(arg)) {
  37. arg = arg.split('*');
  38. return files = files.concat(
  39. fs.readdirSync(arg[0] || '.')
  40. .map(function (f) {
  41. return new RegExp(esc(arg[1]) + '$').test(f) && path.join(arg[0], f);
  42. })
  43. .filter(function (f) {
  44. return f;
  45. })
  46. );
  47. }
  48. files.push(arg);
  49. })
  50. return files;
  51. }
  52. // Remove utf-8 byte order mark, http://en.wikipedia.org/wiki/Byte_order_mark
  53. function removeByteOrderMark(text) {
  54. if (text.charCodeAt(0) === 0xfeff) {
  55. return text.substring(1);
  56. }
  57. return text;
  58. }
  59. // Write a template foreach file that matches template extension
  60. templates = extractFiles(process.argv.slice(2))
  61. .map(function (file) {
  62. var openedFile = fs.readFileSync(file, 'utf-8'), name;
  63. if (!openedFile) return;
  64. name = file.replace(/\..*$/, '');
  65. openedFile = removeByteOrderMark(openedFile.trim());
  66. return 'templates.' + name + ' = new Hogan.Template(' + hogan.compile(openedFile, { asString: 1 }) + ');';
  67. })
  68. .filter(function (t) {
  69. return t;
  70. });
  71. // Output templates
  72. if (!templates.length) return;
  73. console.log('var templates = {};');
  74. console.log(templates.join('\n'));