You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

100 lines
2.3KB

  1. #!/usr/bin/env node
  2. /*
  3. erlccache — (c) 2010 Jan Lehnardt <jan@apache.org>
  4. use instead of erlc and your builds will magically speed up
  5. somebody needs to turn this into proper node code, or sh or whatever
  6. MIT License
  7. */
  8. // CUSTOMIZE HERE
  9. var erlc = "/Users/jan/.local/bin/erlc";
  10. var dir = "/Users/jan/.erlccache/";
  11. // STOP CUSTOMIZING
  12. var sys = require("sys");
  13. var child_process = require("child_process");
  14. var crypto = require("crypto");
  15. var fs = require("fs");
  16. var args = process.argv.slice(2).toString();
  17. var cmd = erlc + " " + args;
  18. // execute a shell command
  19. function exec(cmd, fun) {
  20. fun = fun || function (error, stdout, stderr) {
  21. sys.print("stdout: " + stdout);
  22. sys.print("stderr: " + stderr);
  23. if (error !== null) {
  24. sys.puts("exec error: " + error);
  25. }
  26. };
  27. child_process.exec(cmd, fun);
  28. }
  29. // get the .erl file out of cmd
  30. function erl_parse_file(cmd) {
  31. var file = cmd.match(/[\w]+\.erl\s*/).toString();
  32. return file;
  33. }
  34. // find location of .beam file given the cmd
  35. function erl_beamfile(cmd) {
  36. return process.cwd() + "/" + erl_parse_file(cmd).replace(/.erl/, ".beam");
  37. }
  38. // create a sha1 hex digest from the cmd .erl file
  39. function cache_hash(cmd) {
  40. var hash = crypto.createHash("sha1");
  41. var file = erl_parse_file(cmd);
  42. hash.update(fs.readFileSync(file, "binary"));
  43. return hash.digest("hex");
  44. }
  45. // copy(from, to); -- synchronous
  46. function cache_file_copy(from, to) {
  47. fs.writeFileSync(to, fs.readFileSync(from, "binary"), "binary");
  48. }
  49. // see if the filename in cmd is cached, if not compile and cache
  50. function cache_hit(cmd) {
  51. // make cache dir if it doesn't exist
  52. try {
  53. fs.statSync(dir);
  54. } catch(e) {
  55. fs.mkdirSync(dir, 0700);
  56. }
  57. // hash cmd
  58. var hash = cache_hash(cmd);
  59. try {
  60. fs.statSync(dir + hash);
  61. } catch(e) {
  62. // compile
  63. exec(cmd, function(error, stdout, stderr) {
  64. if(!error) {
  65. var beamfile = erl_beamfile(cmd);
  66. // add beam file to dir + hash(cmd)
  67. cache_file_copy(beamfile, dir + hash);
  68. }
  69. });
  70. return false;
  71. }
  72. return true
  73. }
  74. // copy the cached beamfile to the final destination as if erlc did it
  75. function cache_copy(cmd) {
  76. var beamfile = erl_beamfile(cmd);
  77. var cachefile = dir + cache_hash(cmd);
  78. cache_file_copy(cachefile, beamfile);
  79. }
  80. if(cache_hit(cmd)) {
  81. cache_copy(cmd);
  82. }
  83. //done