unbuild.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. var fs = require('fs');
  2. var nodePath = require('path');
  3. var dir = __dirname + '/../';
  4. var read = function(path){
  5. return fs.readFileSync(nodePath.join(dir, path)).toString();
  6. }
  7. var write = function(path, data){
  8. return fs.writeFileSync(nodePath.join(dir, path), data);
  9. }
  10. var rm = require('./fsrm');
  11. var mk = function(path){
  12. path = nodePath.join(dir, path);
  13. if(fs.existsSync(path)){ return }
  14. fs.mkdirSync(path);
  15. }
  16. var between = function(text, start, end){
  17. end = end || start;
  18. var s = text.indexOf(start);
  19. if(s < 0){ return ''}
  20. s += start.length;
  21. var e = text.indexOf(end, s);
  22. if(e < 0){ return '' }
  23. var code = text.slice(s, e);
  24. return {s: s, t: code, e: e};
  25. }
  26. var next = function(start, end){
  27. end = end || start;
  28. if(!next.text){
  29. next.text = start;
  30. return;
  31. }
  32. var code = between(next.text, start, end);
  33. next.text = next.text.slice(code.e + end.length);
  34. return code.t;
  35. }
  36. var path = function(p){
  37. var code = next(',', ')');
  38. var path;
  39. try{path = eval(code);
  40. }catch(e){console.log("fail", e)};
  41. if(!path){ return }
  42. if('.js' !== path.slice(-3)){
  43. path += '.js';
  44. }
  45. return nodePath.join('./'+(p||'src'), path);
  46. }
  47. var undent = function(code, n){
  48. var regex = /\n\t\t/g;
  49. if(1 === n){
  50. regex = /\n\t/g;
  51. }
  52. return code.replace(regex, '\n');
  53. }
  54. ;(function(){
  55. var arg = process.argv[2] || 'gun';
  56. if('gun' === arg){
  57. rm('./src');
  58. mk('./src');
  59. mk('./src/polyfill');
  60. mk('./src/adapters');
  61. } else {
  62. rm('./'+arg);
  63. mk('./'+arg);
  64. }
  65. var f = read(arg+'.js');
  66. var code = next(f);
  67. code = next("/* UNBUILD */");
  68. if('gun' === arg){
  69. write('src/polyfill/unbuild.js', undent(code, 1));
  70. arg = '';
  71. }
  72. (function recurse(c){
  73. code = next(";USE(function(module){", "})(USE");
  74. if(!code){ return }
  75. var file = path(arg);
  76. if(!file){ return }
  77. code = code.replace(/\bUSE\(/g, 'require(');
  78. write(file, undent(code));
  79. recurse();
  80. }());
  81. }());