macrogen.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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.ceil"),
  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. ("\\.IdInMusicSheet", ".idInMusicSheet"),
  47. ("F_2D", "F2D"),
  48. )
  49. def checkForIssues(filename, content):
  50. if ".Last()" in content:
  51. print(" !!! Warning: .Last() found !!!")
  52. def applyAll():
  53. root = sys.argv[1]
  54. filenames = []; recurse(root, filenames)
  55. print("Apply replacements to:")
  56. for filename in filenames:
  57. print(" >>> " + os.path.basename(filename))
  58. content = None
  59. with open(filename) as f:
  60. content = f.read()
  61. checkForIssues(filename, content)
  62. for rep in replace:
  63. content = re.sub(rep[0], pythonic(rep[1]), content)
  64. with open(filename, "w") as f:
  65. f.write(content)
  66. print("Done.")
  67. def recurse(folder, files):
  68. if os.path.isfile(folder):
  69. files.append(folder)
  70. if os.path.isdir(folder):
  71. files.extend(os.path.join(folder, i) for i in os.listdir(folder))
  72. def keycode(c):
  73. if len(c) > 1:
  74. return ";".join(keycode(i) for i in c)
  75. if c.isalpha():
  76. return str(ord(c.upper())) + ":" + ("1" if c.isupper() else "0")
  77. if c.isdigit():
  78. return str(48 + int(c)) + ":0"
  79. 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]
  80. def escape(s):
  81. return s
  82. return s.replace("&", "&amp;").replace(">", "&gt;").replace("<", "&lt;")
  83. def generate():
  84. N = 0
  85. macroName = "TypeScript'ing Replacements"
  86. macro = ET.Element("macro")
  87. macro.set("name", macroName)
  88. replace = (("ABCDEfGHIJKL", "ABCDEfGHIJKL"),) + replace
  89. for rep in replace:
  90. N += 1
  91. # result.append('<macro name="%d">' % N)
  92. ET.SubElement(macro, "action").set("id", "$SelectAll")
  93. ET.SubElement(macro, "action").set("id", "Replace")
  94. for s in rep[0]:
  95. t = ET.SubElement(macro, "typing")
  96. t.set("text-keycode", keycode(s))
  97. t.text = escape(s)
  98. ET.SubElement(macro, "shortuct").set("text", "TAB")
  99. for s in rep[1]:
  100. t = ET.SubElement(macro, "typing")
  101. t.set("text-keycode", keycode(s))
  102. t.text = escape(s)
  103. # result.append('<action id="EditorEnter" />' * 50)
  104. for i in range(50):
  105. ET.SubElement(macro, "shortuct").set("text", "ENTER")
  106. ET.SubElement(macro, "shortuct").set("text", "ESCAPE")
  107. path = '/Users/acondolu/Library/Preferences/WebStorm11/options/macros.xml'
  108. tree = None
  109. try:
  110. tree = ET.parse(path)
  111. except IOError:
  112. print("Cannot find macro file.")
  113. sys.exit(1)
  114. component = tree.getroot().find("component")
  115. assert component.get("name") == "ActionMacroManager"
  116. found = None
  117. for m in component.iter("macro"):
  118. if m.get("name") == macroName:
  119. found = m
  120. break
  121. if found is not None:
  122. component.remove(found)
  123. component.append(macro)
  124. tree.write(path)
  125. print("Macro written on " + path)
  126. def pythonic(s):
  127. return s.replace("$", "\\")
  128. if __name__ == "__main__":
  129. if len(sys.argv) != 2:
  130. print("Usage: python macrogen.py path/to/files")
  131. sys.exit(1)
  132. # generate()
  133. else:
  134. applyAll()