methods.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. const fs = require('fs');
  2. const csvParse = require('csv-parse/lib/sync');
  3. const Usability = {
  4. UNKNOWN: 0,
  5. USER: 1,
  6. BOT: 2,
  7. BOTH: 4,
  8. };
  9. class MethodInfo {
  10. constructor(name, usability, errors, friendly) {
  11. this.name = name;
  12. this.errors = errors;
  13. this.friendly = friendly;
  14. if (usability.toUpperCase() in Usability) {
  15. this.usability = Usability[usability.toUpperCase()];
  16. } else {
  17. throw new Error(
  18. `Usability must be either user, bot, both or unknown, not ${usability}`
  19. );
  20. }
  21. }
  22. }
  23. /**
  24. * Parses the input CSV file with columns (method, usability, errors)
  25. * and yields `MethodInfo` instances as a result.
  26. */
  27. const parseMethods = function*(csvFile, friendlyCsvFile, errorsDict) {
  28. const rawToFriendly = {};
  29. const f1 = csvParse(
  30. fs.readFileSync(friendlyCsvFile, { encoding: 'utf-8' })
  31. );
  32. for (const [ns, friendly, rawList] of f1.slice(1)) {
  33. for (const raw of rawList.split(' ')) {
  34. rawToFriendly[raw] = [ns, friendly];
  35. }
  36. }
  37. const f2 = csvParse(fs.readFileSync(csvFile, { encoding: 'utf-8' })).slice(
  38. 1
  39. );
  40. for (let line = 0; line < f2.length; line++) {
  41. let [method, usability, errors] = f2[line];
  42. errors = errors
  43. .split(' ')
  44. .filter(Boolean)
  45. .map(x => {
  46. if (x && !(x in errorsDict)) {
  47. throw new Error(
  48. `Method ${method} references unknown errors ${errors}`
  49. );
  50. }
  51. return errorsDict[x];
  52. });
  53. const friendly = rawToFriendly[method];
  54. delete rawToFriendly[method];
  55. yield new MethodInfo(method, usability, errors, friendly);
  56. }
  57. };
  58. module.exports = {
  59. Usability,
  60. MethodInfo,
  61. parseMethods,
  62. };