add_test.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. const fs = require("fs");
  2. const crypto = require("crypto");
  3. const execSync = require("child_process").execSync;
  4. const testManifest = "test/test_manifest.json";
  5. const pdfFolder = "test/pdfs/";
  6. const gitIgnore = "test/pdfs/.gitignore";
  7. if (process.argv.length < 3) {
  8. console.log("\nUsage: node add_test.js FILE\n");
  9. console.log(
  10. ` Add a PDF as a reference test. FILE must be located in ${pdfFolder}`
  11. );
  12. process.exit(1);
  13. }
  14. const file = process.argv[2];
  15. if (!file.startsWith(pdfFolder)) {
  16. throw new Error(`PDF file must be in '${pdfFolder}' directory.`);
  17. }
  18. if (!fs.existsSync(file)) {
  19. throw new Error(`PDF file does not exist '${file}'.`);
  20. }
  21. function calculateMD5(pdfFile, callback) {
  22. const hash = crypto.createHash("md5");
  23. const stream = fs.createReadStream(pdfFile);
  24. stream.on("data", function (data) {
  25. hash.update(data);
  26. });
  27. stream.on("error", function (err) {
  28. callback(err);
  29. });
  30. stream.on("end", function () {
  31. const result = hash.digest("hex");
  32. callback(null, result);
  33. });
  34. }
  35. function getRandomArbitrary(min, max) {
  36. return Math.floor(Math.random() * (max - min) + min);
  37. }
  38. calculateMD5(file, (err, md5) => {
  39. if (err) {
  40. throw new Error(err);
  41. }
  42. let contents = fs.readFileSync(gitIgnore, "utf8").split("\n");
  43. const randomLine = getRandomArbitrary(10, contents.length - 2);
  44. contents.splice(
  45. randomLine,
  46. 0,
  47. "!" + file.substring(file.lastIndexOf("/") + 1)
  48. );
  49. fs.writeFileSync("test/pdfs/.gitignore", contents.join("\n"));
  50. contents = fs.readFileSync(testManifest, "utf8");
  51. const pdf = file.substring(file.lastIndexOf("/") + 1, file.length - 4);
  52. const randomPoint = getRandomArbitrary(100, contents.length - 20);
  53. const bracket = contents.indexOf("},\n", randomPoint);
  54. const out =
  55. contents.substring(0, bracket) +
  56. "},\n" +
  57. ` { "id": "${pdf}",\n` +
  58. ` "file": "pdfs/${pdf}.pdf",\n` +
  59. ` "md5": "${md5}",\n` +
  60. ' "rounds": 1,\n' +
  61. ' "type": "eq"\n' +
  62. " " +
  63. contents.substring(bracket);
  64. fs.writeFileSync("test/test_manifest.json", out);
  65. execSync(`git add ${testManifest} ${gitIgnore}`);
  66. execSync(`git add ${file}`);
  67. });