hooks.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. # -*- coding:utf-8 -*-
  2. #
  3. # Copyright (C) 2008 The Android Open Source Project
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import json
  17. import os
  18. import re
  19. import sys
  20. import traceback
  21. from error import HookError
  22. from git_refs import HEAD
  23. from pyversion import is_python3
  24. if is_python3():
  25. import urllib.parse
  26. else:
  27. import imp
  28. import urlparse
  29. urllib = imp.new_module('urllib')
  30. urllib.parse = urlparse
  31. input = raw_input # noqa: F821
  32. class RepoHook(object):
  33. """A RepoHook contains information about a script to run as a hook.
  34. Hooks are used to run a python script before running an upload (for instance,
  35. to run presubmit checks). Eventually, we may have hooks for other actions.
  36. This shouldn't be confused with files in the 'repo/hooks' directory. Those
  37. files are copied into each '.git/hooks' folder for each project. Repo-level
  38. hooks are associated instead with repo actions.
  39. Hooks are always python. When a hook is run, we will load the hook into the
  40. interpreter and execute its main() function.
  41. """
  42. def __init__(self,
  43. hook_type,
  44. hooks_project,
  45. topdir,
  46. manifest_url,
  47. abort_if_user_denies=False):
  48. """RepoHook constructor.
  49. Params:
  50. hook_type: A string representing the type of hook. This is also used
  51. to figure out the name of the file containing the hook. For
  52. example: 'pre-upload'.
  53. hooks_project: The project containing the repo hooks. If you have a
  54. manifest, this is manifest.repo_hooks_project. OK if this is None,
  55. which will make the hook a no-op.
  56. topdir: Repo's top directory (the one containing the .repo directory).
  57. Scripts will run with CWD as this directory. If you have a manifest,
  58. this is manifest.topdir
  59. manifest_url: The URL to the manifest git repo.
  60. abort_if_user_denies: If True, we'll throw a HookError() if the user
  61. doesn't allow us to run the hook.
  62. """
  63. self._hook_type = hook_type
  64. self._hooks_project = hooks_project
  65. self._manifest_url = manifest_url
  66. self._topdir = topdir
  67. self._abort_if_user_denies = abort_if_user_denies
  68. # Store the full path to the script for convenience.
  69. if self._hooks_project:
  70. self._script_fullpath = os.path.join(self._hooks_project.worktree,
  71. self._hook_type + '.py')
  72. else:
  73. self._script_fullpath = None
  74. def _GetHash(self):
  75. """Return a hash of the contents of the hooks directory.
  76. We'll just use git to do this. This hash has the property that if anything
  77. changes in the directory we will return a different has.
  78. SECURITY CONSIDERATION:
  79. This hash only represents the contents of files in the hook directory, not
  80. any other files imported or called by hooks. Changes to imported files
  81. can change the script behavior without affecting the hash.
  82. Returns:
  83. A string representing the hash. This will always be ASCII so that it can
  84. be printed to the user easily.
  85. """
  86. assert self._hooks_project, "Must have hooks to calculate their hash."
  87. # We will use the work_git object rather than just calling GetRevisionId().
  88. # That gives us a hash of the latest checked in version of the files that
  89. # the user will actually be executing. Specifically, GetRevisionId()
  90. # doesn't appear to change even if a user checks out a different version
  91. # of the hooks repo (via git checkout) nor if a user commits their own revs.
  92. #
  93. # NOTE: Local (non-committed) changes will not be factored into this hash.
  94. # I think this is OK, since we're really only worried about warning the user
  95. # about upstream changes.
  96. return self._hooks_project.work_git.rev_parse('HEAD')
  97. def _GetMustVerb(self):
  98. """Return 'must' if the hook is required; 'should' if not."""
  99. if self._abort_if_user_denies:
  100. return 'must'
  101. else:
  102. return 'should'
  103. def _CheckForHookApproval(self):
  104. """Check to see whether this hook has been approved.
  105. We'll accept approval of manifest URLs if they're using secure transports.
  106. This way the user can say they trust the manifest hoster. For insecure
  107. hosts, we fall back to checking the hash of the hooks repo.
  108. Note that we ask permission for each individual hook even though we use
  109. the hash of all hooks when detecting changes. We'd like the user to be
  110. able to approve / deny each hook individually. We only use the hash of all
  111. hooks because there is no other easy way to detect changes to local imports.
  112. Returns:
  113. True if this hook is approved to run; False otherwise.
  114. Raises:
  115. HookError: Raised if the user doesn't approve and abort_if_user_denies
  116. was passed to the consturctor.
  117. """
  118. if self._ManifestUrlHasSecureScheme():
  119. return self._CheckForHookApprovalManifest()
  120. else:
  121. return self._CheckForHookApprovalHash()
  122. def _CheckForHookApprovalHelper(self, subkey, new_val, main_prompt,
  123. changed_prompt):
  124. """Check for approval for a particular attribute and hook.
  125. Args:
  126. subkey: The git config key under [repo.hooks.<hook_type>] to store the
  127. last approved string.
  128. new_val: The new value to compare against the last approved one.
  129. main_prompt: Message to display to the user to ask for approval.
  130. changed_prompt: Message explaining why we're re-asking for approval.
  131. Returns:
  132. True if this hook is approved to run; False otherwise.
  133. Raises:
  134. HookError: Raised if the user doesn't approve and abort_if_user_denies
  135. was passed to the consturctor.
  136. """
  137. hooks_config = self._hooks_project.config
  138. git_approval_key = 'repo.hooks.%s.%s' % (self._hook_type, subkey)
  139. # Get the last value that the user approved for this hook; may be None.
  140. old_val = hooks_config.GetString(git_approval_key)
  141. if old_val is not None:
  142. # User previously approved hook and asked not to be prompted again.
  143. if new_val == old_val:
  144. # Approval matched. We're done.
  145. return True
  146. else:
  147. # Give the user a reason why we're prompting, since they last told
  148. # us to "never ask again".
  149. prompt = 'WARNING: %s\n\n' % (changed_prompt,)
  150. else:
  151. prompt = ''
  152. # Prompt the user if we're not on a tty; on a tty we'll assume "no".
  153. if sys.stdout.isatty():
  154. prompt += main_prompt + ' (yes/always/NO)? '
  155. response = input(prompt).lower()
  156. print()
  157. # User is doing a one-time approval.
  158. if response in ('y', 'yes'):
  159. return True
  160. elif response == 'always':
  161. hooks_config.SetString(git_approval_key, new_val)
  162. return True
  163. # For anything else, we'll assume no approval.
  164. if self._abort_if_user_denies:
  165. raise HookError('You must allow the %s hook or use --no-verify.' %
  166. self._hook_type)
  167. return False
  168. def _ManifestUrlHasSecureScheme(self):
  169. """Check if the URI for the manifest is a secure transport."""
  170. secure_schemes = ('file', 'https', 'ssh', 'persistent-https', 'sso', 'rpc')
  171. parse_results = urllib.parse.urlparse(self._manifest_url)
  172. return parse_results.scheme in secure_schemes
  173. def _CheckForHookApprovalManifest(self):
  174. """Check whether the user has approved this manifest host.
  175. Returns:
  176. True if this hook is approved to run; False otherwise.
  177. """
  178. return self._CheckForHookApprovalHelper(
  179. 'approvedmanifest',
  180. self._manifest_url,
  181. 'Run hook scripts from %s' % (self._manifest_url,),
  182. 'Manifest URL has changed since %s was allowed.' % (self._hook_type,))
  183. def _CheckForHookApprovalHash(self):
  184. """Check whether the user has approved the hooks repo.
  185. Returns:
  186. True if this hook is approved to run; False otherwise.
  187. """
  188. prompt = ('Repo %s run the script:\n'
  189. ' %s\n'
  190. '\n'
  191. 'Do you want to allow this script to run')
  192. return self._CheckForHookApprovalHelper(
  193. 'approvedhash',
  194. self._GetHash(),
  195. prompt % (self._GetMustVerb(), self._script_fullpath),
  196. 'Scripts have changed since %s was allowed.' % (self._hook_type,))
  197. @staticmethod
  198. def _ExtractInterpFromShebang(data):
  199. """Extract the interpreter used in the shebang.
  200. Try to locate the interpreter the script is using (ignoring `env`).
  201. Args:
  202. data: The file content of the script.
  203. Returns:
  204. The basename of the main script interpreter, or None if a shebang is not
  205. used or could not be parsed out.
  206. """
  207. firstline = data.splitlines()[:1]
  208. if not firstline:
  209. return None
  210. # The format here can be tricky.
  211. shebang = firstline[0].strip()
  212. m = re.match(r'^#!\s*([^\s]+)(?:\s+([^\s]+))?', shebang)
  213. if not m:
  214. return None
  215. # If the using `env`, find the target program.
  216. interp = m.group(1)
  217. if os.path.basename(interp) == 'env':
  218. interp = m.group(2)
  219. return interp
  220. def _ExecuteHookViaReexec(self, interp, context, **kwargs):
  221. """Execute the hook script through |interp|.
  222. Note: Support for this feature should be dropped ~Jun 2021.
  223. Args:
  224. interp: The Python program to run.
  225. context: Basic Python context to execute the hook inside.
  226. kwargs: Arbitrary arguments to pass to the hook script.
  227. Raises:
  228. HookError: When the hooks failed for any reason.
  229. """
  230. # This logic needs to be kept in sync with _ExecuteHookViaImport below.
  231. script = """
  232. import json, os, sys
  233. path = '''%(path)s'''
  234. kwargs = json.loads('''%(kwargs)s''')
  235. context = json.loads('''%(context)s''')
  236. sys.path.insert(0, os.path.dirname(path))
  237. data = open(path).read()
  238. exec(compile(data, path, 'exec'), context)
  239. context['main'](**kwargs)
  240. """ % {
  241. 'path': self._script_fullpath,
  242. 'kwargs': json.dumps(kwargs),
  243. 'context': json.dumps(context),
  244. }
  245. # We pass the script via stdin to avoid OS argv limits. It also makes
  246. # unhandled exception tracebacks less verbose/confusing for users.
  247. cmd = [interp, '-c', 'import sys; exec(sys.stdin.read())']
  248. proc = subprocess.Popen(cmd, stdin=subprocess.PIPE)
  249. proc.communicate(input=script.encode('utf-8'))
  250. if proc.returncode:
  251. raise HookError('Failed to run %s hook.' % (self._hook_type,))
  252. def _ExecuteHookViaImport(self, data, context, **kwargs):
  253. """Execute the hook code in |data| directly.
  254. Args:
  255. data: The code of the hook to execute.
  256. context: Basic Python context to execute the hook inside.
  257. kwargs: Arbitrary arguments to pass to the hook script.
  258. Raises:
  259. HookError: When the hooks failed for any reason.
  260. """
  261. # Exec, storing global context in the context dict. We catch exceptions
  262. # and convert to a HookError w/ just the failing traceback.
  263. try:
  264. exec(compile(data, self._script_fullpath, 'exec'), context)
  265. except Exception:
  266. raise HookError('%s\nFailed to import %s hook; see traceback above.' %
  267. (traceback.format_exc(), self._hook_type))
  268. # Running the script should have defined a main() function.
  269. if 'main' not in context:
  270. raise HookError('Missing main() in: "%s"' % self._script_fullpath)
  271. # Call the main function in the hook. If the hook should cause the
  272. # build to fail, it will raise an Exception. We'll catch that convert
  273. # to a HookError w/ just the failing traceback.
  274. try:
  275. context['main'](**kwargs)
  276. except Exception:
  277. raise HookError('%s\nFailed to run main() for %s hook; see traceback '
  278. 'above.' % (traceback.format_exc(), self._hook_type))
  279. def _ExecuteHook(self, **kwargs):
  280. """Actually execute the given hook.
  281. This will run the hook's 'main' function in our python interpreter.
  282. Args:
  283. kwargs: Keyword arguments to pass to the hook. These are often specific
  284. to the hook type. For instance, pre-upload hooks will contain
  285. a project_list.
  286. """
  287. # Keep sys.path and CWD stashed away so that we can always restore them
  288. # upon function exit.
  289. orig_path = os.getcwd()
  290. orig_syspath = sys.path
  291. try:
  292. # Always run hooks with CWD as topdir.
  293. os.chdir(self._topdir)
  294. # Put the hook dir as the first item of sys.path so hooks can do
  295. # relative imports. We want to replace the repo dir as [0] so
  296. # hooks can't import repo files.
  297. sys.path = [os.path.dirname(self._script_fullpath)] + sys.path[1:]
  298. # Initial global context for the hook to run within.
  299. context = {'__file__': self._script_fullpath}
  300. # Add 'hook_should_take_kwargs' to the arguments to be passed to main.
  301. # We don't actually want hooks to define their main with this argument--
  302. # it's there to remind them that their hook should always take **kwargs.
  303. # For instance, a pre-upload hook should be defined like:
  304. # def main(project_list, **kwargs):
  305. #
  306. # This allows us to later expand the API without breaking old hooks.
  307. kwargs = kwargs.copy()
  308. kwargs['hook_should_take_kwargs'] = True
  309. # See what version of python the hook has been written against.
  310. data = open(self._script_fullpath).read()
  311. interp = self._ExtractInterpFromShebang(data)
  312. reexec = False
  313. if interp:
  314. prog = os.path.basename(interp)
  315. if prog.startswith('python2') and sys.version_info.major != 2:
  316. reexec = True
  317. elif prog.startswith('python3') and sys.version_info.major == 2:
  318. reexec = True
  319. # Attempt to execute the hooks through the requested version of Python.
  320. if reexec:
  321. try:
  322. self._ExecuteHookViaReexec(interp, context, **kwargs)
  323. except OSError as e:
  324. if e.errno == errno.ENOENT:
  325. # We couldn't find the interpreter, so fallback to importing.
  326. reexec = False
  327. else:
  328. raise
  329. # Run the hook by importing directly.
  330. if not reexec:
  331. self._ExecuteHookViaImport(data, context, **kwargs)
  332. finally:
  333. # Restore sys.path and CWD.
  334. sys.path = orig_syspath
  335. os.chdir(orig_path)
  336. def Run(self, user_allows_all_hooks, **kwargs):
  337. """Run the hook.
  338. If the hook doesn't exist (because there is no hooks project or because
  339. this particular hook is not enabled), this is a no-op.
  340. Args:
  341. user_allows_all_hooks: If True, we will never prompt about running the
  342. hook--we'll just assume it's OK to run it.
  343. kwargs: Keyword arguments to pass to the hook. These are often specific
  344. to the hook type. For instance, pre-upload hooks will contain
  345. a project_list.
  346. Raises:
  347. HookError: If there was a problem finding the hook or the user declined
  348. to run a required hook (from _CheckForHookApproval).
  349. """
  350. # No-op if there is no hooks project or if hook is disabled.
  351. if ((not self._hooks_project) or (self._hook_type not in
  352. self._hooks_project.enabled_repo_hooks)):
  353. return
  354. # Bail with a nice error if we can't find the hook.
  355. if not os.path.isfile(self._script_fullpath):
  356. raise HookError('Couldn\'t find repo hook: "%s"' % self._script_fullpath)
  357. # Make sure the user is OK with running the hook.
  358. if (not user_allows_all_hooks) and (not self._CheckForHookApproval()):
  359. return
  360. # Run the hook with the same version of python we're using.
  361. self._ExecuteHook(**kwargs)