macrogen.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. import xml.etree.ElementTree as ET
  2. import re, sys, os
  3. replace = (
  4. ("Math\\.Max\\(", "Math.max("),
  5. ("Math\\.Min\\(", "Math.min("),
  6. ("Math\\.Sqrt\\(", "Math.sqrt("),
  7. ("Math\\.Abs\\(", "Math.abs("),
  8. ("Math\\.Pow\\(", "Math.pow("),
  9. ("Math\\.Ceiling", "Math.ceiling"),
  10. ("Math\\.Floor", "Math.floor"),
  11. ("var ", "let "),
  12. ("new List<List<([a-zA-Z]*)>>\(\)", "[]"),
  13. ("List<List<([a-zA-Z]*)>>", "$1[][]"),
  14. ("new List<([a-zA-Z]*)>\(\)", "[]"),
  15. ("List<([a-zA-Z]*)>", "$1[]"),
  16. ("IEnumerable<([a-zA-Z0-9]+)>", "$1[]"),
  17. ("\\.Count", ".length"),
  18. ("\\.Add\(", ".push("),
  19. ("\\.First\(\)", "[0]"),
  20. ("\\.Insert\((.*), (.*)\)", ".splice($1, 0, $2)"),
  21. ("\\.RemoveAt\(([a-z|0-9]+)\)", ".splice($1, 1)"),
  22. ("\\.Clear\(\);", " = [];"),
  23. ("\\.IndexOf", ".indexOf"),
  24. ("\\.ToArray\\(\\)", ""),
  25. ("\\.Contains\(([a-zA-Z0-9.]+)\)", ".indexOf($1) !== -1"),
  26. ("for each(?:[ ]*)\(([a-z|0-9]+) ([a-z|0-9]+) in ([a-z|0-9]+)\)", "for ($2 of $3)"),
  27. (", len([0-9]*) = ", ", len$1: number = "),
  28. (" == ", " === "),
  29. (" != ", " !== "),
  30. ("null", "undefined"),
  31. ("\\.ToLower\(\)", ".toLowerCase()"),
  32. ("Logger\\.DefaultLogger\\.LogError\(LogLevel\\.DEBUG,(?:[ ]*)", "Logging.debug("),
  33. ("# Logger\\.DefaultLogger\\.LogError\(LogLevel\\.NORMAL,(?:[ ]*)", "Logging.log("),
  34. ("Logger\\.DefaultLogger\\.LogError\(PhonicScore\\.Common\\.Enums\\.LogLevel\\.NORMAL,(?:[ ]*)", "Logging.log("),
  35. ("Fraction\\.CreateFractionFromFraction\(([a-z|0-9]+)\)", "$1.clone()"),
  36. ("(\d{1})f([,;)\]} ])", "$1$2"),
  37. ("number\\.MaxValue", "Number.MAX_VALUE"),
  38. ("Int32\\.MaxValue", "Number.MAX_VALUE"),
  39. ("number\\.MinValue", "Number.MIN_VALUE"),
  40. ("__as__<([A-Za-z|0-9]+)>\(([A-Za-z|0-9.]+), ([A-Za-z|0-9]+)\)", "($2 as $3)"),
  41. ("new Dictionary<number, number>\(\)", "{}"),
  42. (": Dictionary<number, number>", ": {[_: number]: number; }"),
  43. ("String\\.Empty", '""'),
  44. ("return\\n", "return;\n"),
  45. ("}(\n[ ]*)else ", "} else "),
  46. )
  47. def checkForIssues(filename, content):
  48. if ".Last()" in content:
  49. print(" !!! Warning: .Last() found !!!")
  50. def applyAll():
  51. root = sys.argv[1]
  52. filenames = []; recurse(root, filenames)
  53. print("Apply replacements to:")
  54. for filename in filenames:
  55. print(" >>> " + os.path.basename(filename))
  56. content = None
  57. with open(filename) as f:
  58. content = f.read()
  59. checkForIssues(filename, content)
  60. for rep in replace:
  61. content = re.sub(rep[0], pythonic(rep[1]), content)
  62. with open(filename, "w") as f:
  63. f.write(content)
  64. print("Done.")
  65. def recurse(folder, files):
  66. if os.path.isfile(folder):
  67. files.append(folder)
  68. if os.path.isdir(folder):
  69. files.extend(os.path.join(folder, i) for i in os.listdir(folder))
  70. def keycode(c):
  71. if len(c) > 1:
  72. return ";".join(keycode(i) for i in c)
  73. if c.isalpha():
  74. return str(ord(c.upper())) + ":" + ("1" if c.isupper() else "0")
  75. if c.isdigit():
  76. return str(48 + int(c)) + ":0"
  77. return {'!': '49:1', '#': '51:1', '%': '53:1', '$': '52:1', "'": '222:0', '&': '55:1', ')': '48:1', '(': '57:1', '+': '61:1', '*': '56:1', '-': '45:0', ',': '44:0', '/': '47:0', '.': '46:0', ';': '59:0', ':': '59:1', '=': '61:0', '@': '50:1', '[': '91:0', ']': '93:0', '\\': '92:0', '_': '45:1', '^': '54:1', 'a': '65:0', '<': '44:1', '>': '46', ' ': "32:0", "|": "92:1", "?": "47:1", "{": "91:1", "}": "93:1"}[c]
  78. def escape(s):
  79. return s
  80. return s.replace("&", "&amp;").replace(">", "&gt;").replace("<", "&lt;")
  81. def generate():
  82. N = 0
  83. macroName = "TypeScript'ing Replacements"
  84. macro = ET.Element("macro")
  85. macro.set("name", macroName)
  86. replace = (("ABCDEfGHIJKL", "ABCDEfGHIJKL"),) + replace
  87. for rep in replace:
  88. N += 1
  89. # result.append('<macro name="%d">' % N)
  90. ET.SubElement(macro, "action").set("id", "$SelectAll")
  91. ET.SubElement(macro, "action").set("id", "Replace")
  92. for s in rep[0]:
  93. t = ET.SubElement(macro, "typing")
  94. t.set("text-keycode", keycode(s))
  95. t.text = escape(s)
  96. ET.SubElement(macro, "shortuct").set("text", "TAB")
  97. for s in rep[1]:
  98. t = ET.SubElement(macro, "typing")
  99. t.set("text-keycode", keycode(s))
  100. t.text = escape(s)
  101. # result.append('<action id="EditorEnter" />' * 50)
  102. for i in range(50):
  103. ET.SubElement(macro, "shortuct").set("text", "ENTER")
  104. ET.SubElement(macro, "shortuct").set("text", "ESCAPE")
  105. path = '/Users/acondolu/Library/Preferences/WebStorm11/options/macros.xml'
  106. tree = None
  107. try:
  108. tree = ET.parse(path)
  109. except IOError:
  110. print("Cannot find macro file.")
  111. sys.exit(1)
  112. component = tree.getroot().find("component")
  113. assert component.get("name") == "ActionMacroManager"
  114. found = None
  115. for m in component.iter("macro"):
  116. if m.get("name") == macroName:
  117. found = m
  118. break
  119. if found is not None:
  120. component.remove(found)
  121. component.append(macro)
  122. tree.write(path)
  123. print("Macro written on " + path)
  124. def pythonic(s):
  125. return s.replace("$", "\\")
  126. if __name__ == "__main__":
  127. if len(sys.argv) != 2:
  128. print("Usage: python macrogen.py path/to/files")
  129. sys.exit(1)
  130. # generate()
  131. else:
  132. applyAll()