util.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. "use strict";
  2. const assert = require("assert");
  3. const fs = require("fs");
  4. const path = require("path");
  5. const process = require("process");
  6. const child_process = require("child_process");
  7. const CYAN_FMT = "\x1b[36m%s\x1b[0m";
  8. function hex(n, pad)
  9. {
  10. pad = pad || 0;
  11. let s = n.toString(16).toUpperCase();
  12. while(s.length < pad) s = "0" + s;
  13. return s;
  14. }
  15. function mkdirpSync(dir)
  16. {
  17. path.normalize(dir).split(path.sep).reduce((accum_path, dir) => {
  18. const new_dir = accum_path + dir + path.sep;
  19. if(!fs.existsSync(new_dir)) fs.mkdirSync(new_dir);
  20. return new_dir;
  21. }, "");
  22. }
  23. function get_switch_value(arg_switch)
  24. {
  25. const argv = process.argv;
  26. const switch_i = argv.indexOf(arg_switch);
  27. const val_i = switch_i + 1;
  28. if(switch_i > -1 && val_i < argv.length)
  29. {
  30. return argv[switch_i + 1];
  31. }
  32. return null;
  33. }
  34. function get_switch_exist(arg_switch)
  35. {
  36. return process.argv.includes(arg_switch);
  37. }
  38. function create_backup_file(src, dest)
  39. {
  40. try
  41. {
  42. fs.copyFileSync(src, dest);
  43. }
  44. catch(e)
  45. {
  46. if(e.code !== "ENOENT") throw e;
  47. fs.writeFileSync(dest, "");
  48. }
  49. }
  50. function create_diff_file(in1, in2, out)
  51. {
  52. const diff = child_process.spawnSync("git", ["diff", "--no-index", in1, in2]).stdout;
  53. fs.writeFileSync(out, diff);
  54. }
  55. function finalize_table(out_dir, name, contents)
  56. {
  57. const file_path = path.join(out_dir, `${name}.c`);
  58. const backup_file_path = path.join(out_dir, `${name}.c.bak`);
  59. const diff_file_path = path.join(out_dir, `${name}.c.diff`);
  60. create_backup_file(file_path, backup_file_path);
  61. fs.writeFileSync(file_path, contents);
  62. create_diff_file(backup_file_path, file_path, diff_file_path);
  63. console.log(CYAN_FMT, `[+] Wrote table ${name}. Remember to check ${diff_file_path}`);
  64. }
  65. module.exports = {
  66. hex,
  67. mkdirpSync,
  68. get_switch_value,
  69. get_switch_exist,
  70. finalize_table,
  71. };