util.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. function finalize_table_rust(out_dir, name, contents)
  66. {
  67. const file_path = path.join(out_dir, name);
  68. fs.writeFileSync(file_path, contents);
  69. console.log(CYAN_FMT, `[+] Wrote table ${name}.`);
  70. }
  71. module.exports = {
  72. hex,
  73. mkdirpSync,
  74. get_switch_value,
  75. get_switch_exist,
  76. finalize_table,
  77. finalize_table_rust,
  78. };