macrogen.py 6.0 KB

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