macrogen.py 5.9 KB

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