hooks.py 19 KB

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