Архитектурный шаблон "Мрак в моделях" на нескольких языках и платформах
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

96 lignes
1.9KB

  1. #!/usr/bin/env node
  2. if (process.argv.length < 4) {
  3. console.error("Usage: toSwift SRC DST");
  4. process.exit(1);
  5. }
  6. var fs = require("fs");
  7. let fileSrc = process.argv[2];
  8. let fileDst = process.argv[3];
  9. let globalReplacements = {
  10. "function": "func",
  11. "number": "Float",
  12. "):": ") ->",
  13. "interface": "protocol",
  14. };
  15. console.log(`Converting '${fileSrc}' to '${fileDst}'`);
  16. var linesDst = [];
  17. let linesSrc = fs.readFileSync(fileSrc).toString().split(/\r?\n/);
  18. for (let i in linesSrc) {
  19. let ln = linesSrc[i];
  20. linesDst.push(convert(ln));
  21. }
  22. let contentsDst = linesDst.join("\r\n");
  23. fs.writeFileSync(fileDst, contentsDst);
  24. // Functions making decisions.
  25. function convert(line) {
  26. var result = line;
  27. for (let src in globalReplacements) {
  28. let dst = globalReplacements[src];
  29. result = result.replace(src, dst);
  30. }
  31. result = protocolReplace(result);
  32. result = typeArrayReplace(result);
  33. return result;
  34. }
  35. var isProtocol = false;
  36. // interface -> protocol
  37. function protocolReplace(line) {
  38. if (line.includes("protocol")) {
  39. isProtocol = true;
  40. }
  41. if (line == "}") {
  42. isProtocol = false;
  43. }
  44. if (!isProtocol) {
  45. return line;
  46. }
  47. var result = line;
  48. if (isProtocol) {
  49. result = protocolReplaceVariable(result);
  50. }
  51. return result;
  52. }
  53. // a: Number -> var a: Float { get }
  54. function protocolReplaceVariable(line) {
  55. let parts = line.split(": ");
  56. if (parts.length == 2) {
  57. let type = parts[1];
  58. let name = parts[0].trim();
  59. let spaceLength = parts[0].length - name.length;
  60. let spaces = " ".repeat(spaceLength);
  61. return `${spaces}var ${name}: ${type} { get }`;
  62. }
  63. return line;
  64. }
  65. // Type[] -> [Type]
  66. function typeArrayReplace(line) {
  67. let parts = line.split(" ");
  68. for (var i in parts) {
  69. let part = parts[i];
  70. if (
  71. part != "[]" &&
  72. part.endsWith("[]")
  73. ) {
  74. let type = part.substring(0, part.length - 2)
  75. let swiftType = `[${type}]`;
  76. return line.replace(part, swiftType);
  77. }
  78. }
  79. return line;
  80. }