Bug 1713152 [wpt PR 29140] - Invalidate local attachment content-box background with...
[gecko.git] / tools / mach_commands.py
blobe61df3383b05d80ab3e0306ca9b05b9388d8eb26
1 # This Source Code Form is subject to the terms of the Mozilla Public
2 # License, v. 2.0. If a copy of the MPL was not distributed with this
3 # file, # You can obtain one at http://mozilla.org/MPL/2.0/.
5 from __future__ import absolute_import, print_function, unicode_literals
7 import argparse
8 from datetime import datetime, timedelta
9 import logging
10 from operator import itemgetter
11 import sys
13 from mach.decorators import (
14 CommandArgument,
15 CommandProvider,
16 Command,
17 SubCommand,
20 from mozbuild.base import MachCommandBase, MozbuildObject
23 def _get_busted_bugs(payload):
24 import requests
26 payload = dict(payload)
27 payload["include_fields"] = "id,summary,last_change_time,resolution"
28 payload["blocks"] = 1543241
29 response = requests.get("https://bugzilla.mozilla.org/rest/bug", payload)
30 response.raise_for_status()
31 return response.json().get("bugs", [])
34 @CommandProvider
35 class BustedProvider(MachCommandBase):
36 @Command(
37 "busted",
38 category="misc",
39 description="Query known bugs in our tooling, and file new ones.",
41 def busted_default(self, command_context):
42 unresolved = _get_busted_bugs({"resolution": "---"})
43 creation_time = datetime.now() - timedelta(days=15)
44 creation_time = creation_time.strftime("%Y-%m-%dT%H-%M-%SZ")
45 resolved = _get_busted_bugs({"creation_time": creation_time})
46 resolved = [bug for bug in resolved if bug["resolution"]]
47 all_bugs = sorted(
48 unresolved + resolved, key=itemgetter("last_change_time"), reverse=True
50 if all_bugs:
51 for bug in all_bugs:
52 print(
53 "[%s] Bug %s - %s"
54 % (
55 "UNRESOLVED"
56 if not bug["resolution"]
57 else "RESOLVED - %s" % bug["resolution"],
58 bug["id"],
59 bug["summary"],
62 else:
63 print("No known tooling issues found.")
65 @SubCommand("busted", "file", description="File a bug for busted tooling.")
66 @CommandArgument(
67 "against",
68 help=(
69 "The specific mach command that is busted (i.e. if you encountered "
70 "an error with `mach build`, run `mach busted file build`). If "
71 "the issue is not connected to any particular mach command, you "
72 "can also run `mach busted file general`."
75 def busted_file(self, command_context, against):
76 import webbrowser
78 if (
79 against != "general"
80 and against not in self._mach_context.commands.command_handlers
82 print(
83 "%s is not a valid value for `against`. `against` must be "
84 "the name of a `mach` command, or else the string "
85 '"general".' % against
87 return 1
89 if against == "general":
90 product = "Firefox Build System"
91 component = "General"
92 else:
93 import inspect
94 import mozpack.path as mozpath
96 # Look up the file implementing that command, then cross-refernce
97 # moz.build files to get the product/component.
98 handler = self._mach_context.commands.command_handlers[against]
99 method = getattr(handler.cls, handler.method)
100 sourcefile = mozpath.relpath(inspect.getsourcefile(method), self.topsrcdir)
101 reader = self.mozbuild_reader(config_mode="empty")
102 try:
103 res = reader.files_info([sourcefile])[sourcefile]["BUG_COMPONENT"]
104 product, component = res.product, res.component
105 except TypeError:
106 # The file might not have a bug set.
107 product = "Firefox Build System"
108 component = "General"
110 uri = (
111 "https://bugzilla.mozilla.org/enter_bug.cgi?"
112 "product=%s&component=%s&blocked=1543241" % (product, component)
114 webbrowser.open_new_tab(uri)
117 MACH_PASTEBIN_DURATIONS = {
118 "onetime": "onetime",
119 "hour": "3600",
120 "day": "86400",
121 "week": "604800",
122 "month": "2073600",
125 EXTENSION_TO_HIGHLIGHTER = {
126 ".hgrc": "ini",
127 "Dockerfile": "docker",
128 "Makefile": "make",
129 "applescript": "applescript",
130 "arduino": "arduino",
131 "bash": "bash",
132 "bat": "bat",
133 "c": "c",
134 "clojure": "clojure",
135 "cmake": "cmake",
136 "coffee": "coffee-script",
137 "console": "console",
138 "cpp": "cpp",
139 "cs": "csharp",
140 "css": "css",
141 "cu": "cuda",
142 "cuda": "cuda",
143 "dart": "dart",
144 "delphi": "delphi",
145 "diff": "diff",
146 "django": "django",
147 "docker": "docker",
148 "elixir": "elixir",
149 "erlang": "erlang",
150 "go": "go",
151 "h": "c",
152 "handlebars": "handlebars",
153 "haskell": "haskell",
154 "hs": "haskell",
155 "html": "html",
156 "ini": "ini",
157 "ipy": "ipythonconsole",
158 "ipynb": "ipythonconsole",
159 "irc": "irc",
160 "j2": "django",
161 "java": "java",
162 "js": "js",
163 "json": "json",
164 "jsx": "jsx",
165 "kt": "kotlin",
166 "less": "less",
167 "lisp": "common-lisp",
168 "lsp": "common-lisp",
169 "lua": "lua",
170 "m": "objective-c",
171 "make": "make",
172 "matlab": "matlab",
173 "md": "_markdown",
174 "nginx": "nginx",
175 "numpy": "numpy",
176 "patch": "diff",
177 "perl": "perl",
178 "php": "php",
179 "pm": "perl",
180 "postgresql": "postgresql",
181 "py": "python",
182 "rb": "rb",
183 "rs": "rust",
184 "rst": "rst",
185 "sass": "sass",
186 "scss": "scss",
187 "sh": "bash",
188 "sol": "sol",
189 "sql": "sql",
190 "swift": "swift",
191 "tex": "tex",
192 "typoscript": "typoscript",
193 "vim": "vim",
194 "xml": "xml",
195 "xslt": "xslt",
196 "yaml": "yaml",
197 "yml": "yaml",
201 def guess_highlighter_from_path(path):
202 """Return a known highlighter from a given path
204 Attempt to select a highlighter by checking the file extension in the mapping
205 of extensions to highlighter. If that fails, attempt to pass the basename of
206 the file. Return `_code` as the default highlighter if that fails.
208 import os
210 _name, ext = os.path.splitext(path)
212 if ext.startswith("."):
213 ext = ext[1:]
215 if ext in EXTENSION_TO_HIGHLIGHTER:
216 return EXTENSION_TO_HIGHLIGHTER[ext]
218 basename = os.path.basename(path)
220 return EXTENSION_TO_HIGHLIGHTER.get(basename, "_code")
223 PASTEMO_MAX_CONTENT_LENGTH = 250 * 1024 * 1024
225 PASTEMO_URL = "https://paste.mozilla.org/api/"
227 MACH_PASTEBIN_DESCRIPTION = """
228 Command line interface to paste.mozilla.org.
230 Takes either a filename whose content should be pasted, or reads
231 content from standard input. If a highlighter is specified it will
232 be used, otherwise the file name will be used to determine an
233 appropriate highlighter.
237 @CommandProvider
238 class PastebinProvider(MachCommandBase):
239 @Command("pastebin", category="misc", description=MACH_PASTEBIN_DESCRIPTION)
240 @CommandArgument(
241 "--list-highlighters",
242 action="store_true",
243 help="List known highlighters and exit",
245 @CommandArgument(
246 "--highlighter", default=None, help="Syntax highlighting to use for paste"
248 @CommandArgument(
249 "--expires",
250 default="week",
251 choices=sorted(MACH_PASTEBIN_DURATIONS.keys()),
252 help="Expire paste after given time duration (default: %(default)s)",
254 @CommandArgument(
255 "--verbose",
256 action="store_true",
257 help="Print extra info such as selected syntax highlighter",
259 @CommandArgument(
260 "path",
261 nargs="?",
262 default=None,
263 help="Path to file for upload to paste.mozilla.org",
265 def pastebin(
266 self, command_context, list_highlighters, highlighter, expires, verbose, path
268 import requests
270 def verbose_print(*args, **kwargs):
271 """Print a string if `--verbose` flag is set"""
272 if verbose:
273 print(*args, **kwargs)
275 # Show known highlighters and exit.
276 if list_highlighters:
277 lexers = set(EXTENSION_TO_HIGHLIGHTER.values())
278 print("Available lexers:\n" " - %s" % "\n - ".join(sorted(lexers)))
279 return 0
281 # Get a correct expiry value.
282 try:
283 verbose_print("Setting expiry from %s" % expires)
284 expires = MACH_PASTEBIN_DURATIONS[expires]
285 verbose_print("Using %s as expiry" % expires)
286 except KeyError:
287 print(
288 "%s is not a valid duration.\n"
289 "(hint: try one of %s)"
290 % (expires, ", ".join(MACH_PASTEBIN_DURATIONS.keys()))
292 return 1
294 data = {
295 "format": "json",
296 "expires": expires,
299 # Get content to be pasted.
300 if path:
301 verbose_print("Reading content from %s" % path)
302 try:
303 with open(path, "r") as f:
304 content = f.read()
305 except IOError:
306 print("ERROR. No such file %s" % path)
307 return 1
309 lexer = guess_highlighter_from_path(path)
310 if lexer:
311 data["lexer"] = lexer
312 else:
313 verbose_print("Reading content from stdin")
314 content = sys.stdin.read()
316 # Assert the length of content to be posted does not exceed the maximum.
317 content_length = len(content)
318 verbose_print("Checking size of content is okay (%d)" % content_length)
319 if content_length > PASTEMO_MAX_CONTENT_LENGTH:
320 print(
321 "Paste content is too large (%d, maximum %d)"
322 % (content_length, PASTEMO_MAX_CONTENT_LENGTH)
324 return 1
326 data["content"] = content
328 # Highlight as specified language, overwriting value set from filename.
329 if highlighter:
330 verbose_print("Setting %s as highlighter" % highlighter)
331 data["lexer"] = highlighter
333 try:
334 verbose_print("Sending request to %s" % PASTEMO_URL)
335 resp = requests.post(PASTEMO_URL, data=data)
337 # Error code should always be 400.
338 # Response content will include a helpful error message,
339 # so print it here (for example, if an invalid highlighter is
340 # provided, it will return a list of valid highlighters).
341 if resp.status_code >= 400:
342 print("Error code %d: %s" % (resp.status_code, resp.content))
343 return 1
345 verbose_print("Pasted successfully")
347 response_json = resp.json()
349 verbose_print("Paste highlighted as %s" % response_json["lexer"])
350 print(response_json["url"])
352 return 0
353 except Exception as e:
354 print("ERROR. Paste failed.")
355 print("%s" % e)
356 return 1
359 class PypiBasedTool:
361 Helper for loading a tool that is hosted on pypi. The package is expected
362 to expose a `mach_interface` module which has `new_release_on_pypi`,
363 `parser`, and `run` functions.
366 def __init__(self, module_name, pypi_name=None):
367 self.name = module_name
368 self.pypi_name = pypi_name or module_name
370 def _import(self):
371 # Lazy loading of the tools mach interface.
372 # Note that only the mach_interface module should be used from this file.
373 import importlib
375 try:
376 return importlib.import_module("%s.mach_interface" % self.name)
377 except ImportError:
378 return None
380 def create_parser(self, subcommand=None):
381 # Create the command line parser.
382 # If the tool is not installed, or not up to date, it will
383 # first be installed.
384 cmd = MozbuildObject.from_environment()
385 cmd.activate_virtualenv()
386 tool = self._import()
387 if not tool:
388 # The tool is not here at all, install it
389 cmd.virtualenv_manager.install_pip_package(self.pypi_name)
390 print(
391 "%s was installed. please re-run your"
392 " command. If you keep getting this message please "
393 " manually run: 'pip install -U %s'." % (self.pypi_name, self.pypi_name)
395 else:
396 # Check if there is a new release available
397 release = tool.new_release_on_pypi()
398 if release:
399 print(release)
400 # there is one, so install it. Note that install_pip_package
401 # does not work here, so just run pip directly.
402 cmd.virtualenv_manager._run_pip(
403 ["install", "%s==%s" % (self.pypi_name, release)]
405 print(
406 "%s was updated to version %s. please"
407 " re-run your command." % (self.pypi_name, release)
409 else:
410 # Tool is up to date, return the parser.
411 if subcommand:
412 return tool.parser(subcommand)
413 else:
414 return tool.parser()
415 # exit if we updated or installed mozregression because
416 # we may have already imported mozregression and running it
417 # as this may cause issues.
418 sys.exit(0)
420 def run(self, **options):
421 tool = self._import()
422 tool.run(options)
425 def mozregression_create_parser():
426 # Create the mozregression command line parser.
427 # if mozregression is not installed, or not up to date, it will
428 # first be installed.
429 loader = PypiBasedTool("mozregression")
430 return loader.create_parser()
433 @CommandProvider
434 class MozregressionCommand(MachCommandBase):
435 @Command(
436 "mozregression",
437 category="misc",
438 description=("Regression range finder for nightly" " and inbound builds."),
439 parser=mozregression_create_parser,
441 def run(self, command_context, **options):
442 self.activate_virtualenv()
443 mozregression = PypiBasedTool("mozregression")
444 mozregression.run(**options)
447 @CommandProvider
448 class NodeCommands(MachCommandBase):
449 @Command(
450 "node",
451 category="devenv",
452 description="Run the NodeJS interpreter used for building.",
454 @CommandArgument("args", nargs=argparse.REMAINDER)
455 def node(self, command_context, args):
456 from mozbuild.nodeutil import find_node_executable
458 # Avoid logging the command
459 self.log_manager.terminal_handler.setLevel(logging.CRITICAL)
461 node_path, _ = find_node_executable()
463 return self.run_process(
464 [node_path] + args,
465 pass_thru=True, # Allow user to run Node interactively.
466 ensure_exit_code=False, # Don't throw on non-zero exit code.
469 @Command(
470 "npm",
471 category="devenv",
472 description="Run the npm executable from the NodeJS used for building.",
474 @CommandArgument("args", nargs=argparse.REMAINDER)
475 def npm(self, command_context, args):
476 from mozbuild.nodeutil import find_npm_executable
478 # Avoid logging the command
479 self.log_manager.terminal_handler.setLevel(logging.CRITICAL)
481 npm_path, _ = find_npm_executable()
483 return self.run_process(
484 [npm_path, "--scripts-prepend-node-path=auto"] + args,
485 pass_thru=True, # Avoid eating npm output/error messages
486 ensure_exit_code=False, # Don't throw on non-zero exit code.
490 def logspam_create_parser(subcommand):
491 # Create the logspam command line parser.
492 # if logspam is not installed, or not up to date, it will
493 # first be installed.
494 loader = PypiBasedTool("logspam", "mozilla-log-spam")
495 return loader.create_parser(subcommand)
498 from functools import partial
501 @CommandProvider
502 class LogspamCommand(MachCommandBase):
503 @Command(
504 "logspam",
505 category="misc",
506 description=("Warning categorizer for treeherder test runs."),
508 def logspam(self, command_context):
509 pass
511 @SubCommand("logspam", "report", parser=partial(logspam_create_parser, "report"))
512 def report(self, command_context, **options):
513 self.activate_virtualenv()
514 logspam = PypiBasedTool("logspam")
515 logspam.run(command="report", **options)
517 @SubCommand("logspam", "bisect", parser=partial(logspam_create_parser, "bisect"))
518 def bisect(self, command_context, **options):
519 self.activate_virtualenv()
520 logspam = PypiBasedTool("logspam")
521 logspam.run(command="bisect", **options)
523 @SubCommand("logspam", "file", parser=partial(logspam_create_parser, "file"))
524 def create(self, command_context, **options):
525 self.activate_virtualenv()
526 logspam = PypiBasedTool("logspam")
527 logspam.run(command="file", **options)