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