PRESUBMIT.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. # Copyright 2016 The Chromium Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. """Presubmit script for ui/accessibility."""
  5. import json
  6. import os
  7. import re
  8. USE_PYTHON3 = True
  9. AX_MOJOM = 'ui/accessibility/ax_enums.mojom'
  10. AUTOMATION_IDL = 'extensions/common/api/automation.idl'
  11. AX_TS_FILE = 'chrome/browser/resources/accessibility/accessibility.ts'
  12. AX_MODE_HEADER = 'ui/accessibility/ax_mode.h'
  13. def InitialLowerCamelCase(unix_name):
  14. words = unix_name.split('_')
  15. return words[0] + ''.join(word.capitalize() for word in words[1:])
  16. def CamelToLowerHacker(str):
  17. out = ''
  18. for i in range(len(str)):
  19. if str[i] >= 'A' and str[i] <= 'Z' and out:
  20. out += '_'
  21. out += str[i]
  22. return out.lower()
  23. # Given a full path to an IDL or MOJOM file containing enum definitions,
  24. # parse the file for enums and return a dict mapping the enum name
  25. # to a list of values for that enum.
  26. def GetEnumsFromFile(fullpath, get_raw_enum_value=False):
  27. enum_name = None
  28. enums = {}
  29. for line in open(fullpath).readlines():
  30. # Strip out comments
  31. line = re.sub('//.*', '', line)
  32. # Strip out mojo annotations.
  33. line = re.sub('\[(.*)\]', '', line)
  34. # Look for lines of the form "enum ENUM_NAME {" and get the enum_name
  35. m = re.search('enum ([\w]+) {', line)
  36. if m:
  37. enum_name = m.group(1)
  38. continue
  39. # Look for a "}" character signifying the end of an enum
  40. if line.find('}') >= 0:
  41. enum_name = None
  42. continue
  43. if not enum_name:
  44. continue
  45. # We're now inside of a enum definition.
  46. # First, if requested, add the raw line.
  47. if get_raw_enum_value:
  48. enums.setdefault(enum_name, [])
  49. enums[enum_name].append(line)
  50. continue
  51. # Add the first string consisting of alphanumerics plus underscore ("\w") to
  52. # the list of values for that enum.
  53. m = re.search('([\w]+)', line)
  54. if m:
  55. enums.setdefault(enum_name, [])
  56. enum_value = m.group(1)
  57. if (enum_value[0] == 'k' and
  58. enum_value[1] == enum_value[1].upper()):
  59. enum_value = CamelToLowerHacker(enum_value[1:])
  60. if enum_value == 'none' or enum_value == 'last':
  61. continue
  62. enums[enum_name].append(enum_value)
  63. return enums
  64. def CheckMatchingEnum(ax_enums,
  65. ax_enum_name,
  66. automation_enums,
  67. automation_enum_name,
  68. errs,
  69. output_api,
  70. strict_ordering=False,
  71. allow_extra_destination_enums=False):
  72. if ax_enum_name not in ax_enums:
  73. errs.append(output_api.PresubmitError(
  74. 'Expected %s to have an enum named %s' % (AX_MOJOM, ax_enum_name)))
  75. return
  76. if automation_enum_name not in automation_enums:
  77. errs.append(output_api.PresubmitError(
  78. 'Expected %s to have an enum named %s' % (
  79. AUTOMATION_IDL, automation_enum_name)))
  80. return
  81. src = ax_enums[ax_enum_name]
  82. dst = automation_enums[automation_enum_name]
  83. if strict_ordering and len(src) != len(dst):
  84. errs.append(output_api.PresubmitError(
  85. 'Expected %s to have the same number of items as %s' % (
  86. automation_enum_name, ax_enum_name)))
  87. return
  88. if strict_ordering:
  89. for index, value in enumerate(src):
  90. lower_value = InitialLowerCamelCase(value)
  91. if lower_value != dst[index]:
  92. errs.append(output_api.PresubmitError(
  93. ('At index %s in enums, unexpected ordering around %s.%s ' +
  94. 'and %s.%s in %s and %s') % (
  95. index, ax_enum_name, lower_value,
  96. automation_enum_name, dst[index],
  97. AX_MOJOM, AUTOMATION_IDL)))
  98. return
  99. return
  100. for value in src:
  101. lower_value = InitialLowerCamelCase(value)
  102. if lower_value in dst:
  103. dst.remove(lower_value) # Any remaining at end are extra and a mismatch.
  104. else:
  105. errs.append(output_api.PresubmitError(
  106. 'Found %s.%s in %s, but did not find %s.%s in %s' % (
  107. ax_enum_name, value, AX_MOJOM,
  108. automation_enum_name, InitialLowerCamelCase(value),
  109. AUTOMATION_IDL)))
  110. # Should be no remaining items
  111. if not allow_extra_destination_enums:
  112. for value in dst:
  113. errs.append(output_api.PresubmitError(
  114. 'Found %s.%s in %s, but did not find %s.%s in %s' % (
  115. automation_enum_name, value, AUTOMATION_IDL,
  116. ax_enum_name, InitialLowerCamelCase(value),
  117. AX_MOJOM)))
  118. def CheckEnumsMatch(input_api, output_api):
  119. repo_root = input_api.change.RepositoryRoot()
  120. ax_enums = GetEnumsFromFile(os.path.join(repo_root, AX_MOJOM))
  121. automation_enums = GetEnumsFromFile(os.path.join(repo_root, AUTOMATION_IDL))
  122. # Focused state only exists in automation.
  123. automation_enums['StateType'].remove('focused')
  124. # Offscreen state only exists in automation.
  125. automation_enums['StateType'].remove('offscreen')
  126. errs = []
  127. CheckMatchingEnum(ax_enums, 'Role', automation_enums, 'RoleType', errs,
  128. output_api)
  129. CheckMatchingEnum(ax_enums, 'State', automation_enums, 'StateType', errs,
  130. output_api, strict_ordering=True)
  131. CheckMatchingEnum(ax_enums, 'Action', automation_enums, 'ActionType', errs,
  132. output_api, strict_ordering=True)
  133. CheckMatchingEnum(ax_enums, 'Event', automation_enums, 'EventType', errs,
  134. output_api, allow_extra_destination_enums=True)
  135. CheckMatchingEnum(ax_enums, 'NameFrom', automation_enums, 'NameFromType',
  136. errs, output_api)
  137. CheckMatchingEnum(ax_enums, 'DescriptionFrom', automation_enums,
  138. 'DescriptionFromType', errs, output_api)
  139. CheckMatchingEnum(ax_enums, 'Restriction', automation_enums,
  140. 'Restriction', errs, output_api)
  141. CheckMatchingEnum(ax_enums, 'DefaultActionVerb', automation_enums,
  142. 'DefaultActionVerb', errs, output_api)
  143. CheckMatchingEnum(ax_enums, 'MarkerType', automation_enums,
  144. 'MarkerType', errs, output_api)
  145. CheckMatchingEnum(ax_enums, 'Command', automation_enums,
  146. 'IntentCommandType', errs, output_api)
  147. CheckMatchingEnum(ax_enums, 'InputEventType', automation_enums,
  148. 'IntentInputEventType', errs, output_api)
  149. CheckMatchingEnum(ax_enums, 'TextBoundary', automation_enums,
  150. 'IntentTextBoundaryType', errs, output_api)
  151. CheckMatchingEnum(ax_enums, 'MoveDirection', automation_enums,
  152. 'IntentMoveDirectionType', errs, output_api)
  153. CheckMatchingEnum(ax_enums, 'SortDirection', automation_enums,
  154. 'SortDirectionType', errs, output_api)
  155. CheckMatchingEnum(ax_enums, 'HasPopup', automation_enums,
  156. 'HasPopup', errs, output_api)
  157. CheckMatchingEnum(ax_enums, 'AriaCurrentState', automation_enums,
  158. 'AriaCurrentState', errs, output_api)
  159. return errs
  160. def CheckAXEnumsOrdinals(input_api, output_api):
  161. repo_root = input_api.change.RepositoryRoot()
  162. ax_enums = GetEnumsFromFile(
  163. os.path.join(repo_root, AX_MOJOM), get_raw_enum_value=True)
  164. # Find all enums containing enum values with ordinals and save each enum value
  165. # as a pair e.g. (kEnumValue, 100).
  166. enums_with_ordinal_values = {}
  167. for enum_name in ax_enums:
  168. for enum_value in ax_enums[enum_name]:
  169. m = re.search("([\w]+) = ([\d]+)", enum_value)
  170. if not m:
  171. continue
  172. enums_with_ordinal_values.setdefault(enum_name, [])
  173. enums_with_ordinal_values[enum_name].append(m.groups(1))
  174. # Now, do the validation for each enum.
  175. errs = []
  176. for enum_name in enums_with_ordinal_values:
  177. # This is expected to not be continuous.
  178. if enum_name == "MarkerType":
  179. continue
  180. enum = enums_with_ordinal_values[enum_name]
  181. enum.sort(key = lambda item: int(item[1]))
  182. index = 0
  183. for enum_value in enum:
  184. if index == int(enum_value[1]):
  185. index += 1
  186. continue
  187. errs.append(output_api.PresubmitError(
  188. "Unexpected enum %s ordinal: %s = %s. Expected %d." % (
  189. enum_name, enum_value[0], enum_value[1], index)))
  190. return errs
  191. # Given a full path to c++ header, return an array of the first static
  192. # constexpr defined. (Note there can be more than one defined in a C++
  193. # header)
  194. def GetConstexprFromFile(fullpath):
  195. values = []
  196. for line in open(fullpath).readlines():
  197. # Strip out comments
  198. line = re.sub('//.*', '', line)
  199. # Look for lines of the form "static constexpr <type> NAME "
  200. m = re.search('static constexpr [\w]+ ([\w]+)', line)
  201. if m:
  202. value = m.group(1)
  203. # Skip first/last sentinels
  204. if value == 'kFirstModeFlag' or value == 'kLastModeFlag':
  205. continue
  206. values.append(value)
  207. return values
  208. # Given a full path to js file, return the AXMode consts
  209. # defined
  210. def GetAccessibilityModesFromFile(fullpath):
  211. values = []
  212. inside = False
  213. for line in open(fullpath).readlines():
  214. if not inside:
  215. # Look for the block of code that defines the AXMode enum.
  216. m = re.search('^enum AXMode {$', line)
  217. if m:
  218. inside = True
  219. continue
  220. # Look for a "}" character signifying the end of the enum.
  221. m = re.search('^}$', line)
  222. if m:
  223. return values
  224. m = re.search('([\w]+) = ', line)
  225. if m:
  226. values.append(m.group(1))
  227. continue
  228. return values
  229. # Make sure that the modes defined in the C++ header match those defined in
  230. # the js file. Note that this doesn't guarantee that the values are the same,
  231. # but does make sure if we add or remove we can signal to the developer that
  232. # they should be aware that this dependency exists.
  233. def CheckModesMatch(input_api, output_api):
  234. errs = []
  235. repo_root = input_api.change.RepositoryRoot()
  236. ax_modes_in_header = GetConstexprFromFile(
  237. os.path.join(repo_root,AX_MODE_HEADER))
  238. ax_modes_in_js = GetAccessibilityModesFromFile(
  239. os.path.join(repo_root, AX_TS_FILE))
  240. # In TypeScript enum values are NAMED_LIKE_THIS. Transform them to make them
  241. # comparable to the C++ naming scheme.
  242. ax_modes_in_js = list(
  243. map(lambda s: ('k' + s.replace('_', '')).lower(), ax_modes_in_js))
  244. # The following AxMode values are not used in the UI, and are purposefully
  245. # omitted.
  246. unused_ax_modes = [
  247. 'kAXModeBasic',
  248. 'kAXModeWebContentsOnly',
  249. 'kAXModeComplete',
  250. 'kAXModeCompleteNoHTML',
  251. ]
  252. for value in ax_modes_in_header:
  253. if value in unused_ax_modes:
  254. continue
  255. equivalent_value = value.lower()
  256. if equivalent_value not in ax_modes_in_js:
  257. errs.append(output_api.PresubmitError(
  258. 'Found %s in %s, but did not find an equivalent value in %s' % (
  259. value, AX_MODE_HEADER, AX_TS_FILE)))
  260. return errs
  261. def CheckChangeOnUpload(input_api, output_api):
  262. errs = []
  263. for path in input_api.LocalPaths():
  264. path = path.replace('\\', '/')
  265. if AX_MOJOM == path:
  266. errs.extend(CheckEnumsMatch(input_api, output_api))
  267. errs.extend(CheckAXEnumsOrdinals(input_api, output_api))
  268. if AX_MODE_HEADER == path:
  269. errs.extend(CheckModesMatch(input_api, output_api))
  270. return errs
  271. def CheckChangeOnCommit(input_api, output_api):
  272. errs = []
  273. for path in input_api.LocalPaths():
  274. path = path.replace('\\', '/')
  275. if AX_MOJOM == path:
  276. errs.extend(CheckEnumsMatch(input_api, output_api))
  277. if AX_MODE_HEADER == path:
  278. errs.extend(CheckModesMatch(input_api, output_api))
  279. return errs