Bug 1700051: part 36) Reduce accessibility of `SoftText::mBegin` to `private`. r...
[gecko.git] / tools / mach_commands.py
blob3b340bf891fd249754cfedb96bbb948f1a544de2
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):
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, 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(self, list_highlighters, highlighter, expires, verbose, path):
266 import requests
268 def verbose_print(*args, **kwargs):
269 """Print a string if `--verbose` flag is set"""
270 if verbose:
271 print(*args, **kwargs)
273 # Show known highlighters and exit.
274 if list_highlighters:
275 lexers = set(EXTENSION_TO_HIGHLIGHTER.values())
276 print("Available lexers:\n" " - %s" % "\n - ".join(sorted(lexers)))
277 return 0
279 # Get a correct expiry value.
280 try:
281 verbose_print("Setting expiry from %s" % expires)
282 expires = MACH_PASTEBIN_DURATIONS[expires]
283 verbose_print("Using %s as expiry" % expires)
284 except KeyError:
285 print(
286 "%s is not a valid duration.\n"
287 "(hint: try one of %s)"
288 % (expires, ", ".join(MACH_PASTEBIN_DURATIONS.keys()))
290 return 1
292 data = {
293 "format": "json",
294 "expires": expires,
297 # Get content to be pasted.
298 if path:
299 verbose_print("Reading content from %s" % path)
300 try:
301 with open(path, "r") as f:
302 content = f.read()
303 except IOError:
304 print("ERROR. No such file %s" % path)
305 return 1
307 lexer = guess_highlighter_from_path(path)
308 if lexer:
309 data["lexer"] = lexer
310 else:
311 verbose_print("Reading content from stdin")
312 content = sys.stdin.read()
314 # Assert the length of content to be posted does not exceed the maximum.
315 content_length = len(content)
316 verbose_print("Checking size of content is okay (%d)" % content_length)
317 if content_length > PASTEMO_MAX_CONTENT_LENGTH:
318 print(
319 "Paste content is too large (%d, maximum %d)"
320 % (content_length, PASTEMO_MAX_CONTENT_LENGTH)
322 return 1
324 data["content"] = content
326 # Highlight as specified language, overwriting value set from filename.
327 if highlighter:
328 verbose_print("Setting %s as highlighter" % highlighter)
329 data["lexer"] = highlighter
331 try:
332 verbose_print("Sending request to %s" % PASTEMO_URL)
333 resp = requests.post(PASTEMO_URL, data=data)
335 # Error code should always be 400.
336 # Response content will include a helpful error message,
337 # so print it here (for example, if an invalid highlighter is
338 # provided, it will return a list of valid highlighters).
339 if resp.status_code >= 400:
340 print("Error code %d: %s" % (resp.status_code, resp.content))
341 return 1
343 verbose_print("Pasted successfully")
345 response_json = resp.json()
347 verbose_print("Paste highlighted as %s" % response_json["lexer"])
348 print(response_json["url"])
350 return 0
351 except Exception as e:
352 print("ERROR. Paste failed.")
353 print("%s" % e)
354 return 1
357 class PypiBasedTool:
359 Helper for loading a tool that is hosted on pypi. The package is expected
360 to expose a `mach_interface` module which has `new_release_on_pypi`,
361 `parser`, and `run` functions.
364 def __init__(self, module_name, pypi_name=None):
365 self.name = module_name
366 self.pypi_name = pypi_name or module_name
368 def _import(self):
369 # Lazy loading of the tools mach interface.
370 # Note that only the mach_interface module should be used from this file.
371 import importlib
373 try:
374 return importlib.import_module("%s.mach_interface" % self.name)
375 except ImportError:
376 return None
378 def create_parser(self, subcommand=None):
379 # Create the command line parser.
380 # If the tool is not installed, or not up to date, it will
381 # first be installed.
382 cmd = MozbuildObject.from_environment()
383 cmd.activate_virtualenv()
384 tool = self._import()
385 if not tool:
386 # The tool is not here at all, install it
387 cmd.virtualenv_manager.install_pip_package(self.pypi_name)
388 print(
389 "%s was installed. please re-run your"
390 " command. If you keep getting this message please "
391 " manually run: 'pip install -U %s'." % (self.pypi_name, self.pypi_name)
393 else:
394 # Check if there is a new release available
395 release = tool.new_release_on_pypi()
396 if release:
397 print(release)
398 # there is one, so install it. Note that install_pip_package
399 # does not work here, so just run pip directly.
400 cmd.virtualenv_manager._run_pip(
401 ["install", "%s==%s" % (self.pypi_name, release)]
403 print(
404 "%s was updated to version %s. please"
405 " re-run your command." % (self.pypi_name, release)
407 else:
408 # Tool is up to date, return the parser.
409 if subcommand:
410 return tool.parser(subcommand)
411 else:
412 return tool.parser()
413 # exit if we updated or installed mozregression because
414 # we may have already imported mozregression and running it
415 # as this may cause issues.
416 sys.exit(0)
418 def run(self, **options):
419 tool = self._import()
420 tool.run(options)
423 def mozregression_create_parser():
424 # Create the mozregression command line parser.
425 # if mozregression is not installed, or not up to date, it will
426 # first be installed.
427 loader = PypiBasedTool("mozregression")
428 return loader.create_parser()
431 @CommandProvider
432 class MozregressionCommand(MachCommandBase):
433 @Command(
434 "mozregression",
435 category="misc",
436 description=("Regression range finder for nightly" " and inbound builds."),
437 parser=mozregression_create_parser,
439 def run(self, **options):
440 self.activate_virtualenv()
441 mozregression = PypiBasedTool("mozregression")
442 mozregression.run(**options)
445 @CommandProvider
446 class NodeCommands(MachCommandBase):
447 @Command(
448 "node",
449 category="devenv",
450 description="Run the NodeJS interpreter used for building.",
452 @CommandArgument("args", nargs=argparse.REMAINDER)
453 def node(self, args):
454 from mozbuild.nodeutil import find_node_executable
456 # Avoid logging the command
457 self.log_manager.terminal_handler.setLevel(logging.CRITICAL)
459 node_path, _ = find_node_executable()
461 return self.run_process(
462 [node_path] + args,
463 pass_thru=True, # Allow user to run Node interactively.
464 ensure_exit_code=False, # Don't throw on non-zero exit code.
467 @Command(
468 "npm",
469 category="devenv",
470 description="Run the npm executable from the NodeJS used for building.",
472 @CommandArgument("args", nargs=argparse.REMAINDER)
473 def npm(self, args):
474 from mozbuild.nodeutil import find_npm_executable
476 # Avoid logging the command
477 self.log_manager.terminal_handler.setLevel(logging.CRITICAL)
479 npm_path, _ = find_npm_executable()
481 return self.run_process(
482 [npm_path, "--scripts-prepend-node-path=auto"] + args,
483 pass_thru=True, # Avoid eating npm output/error messages
484 ensure_exit_code=False, # Don't throw on non-zero exit code.
488 def logspam_create_parser(subcommand):
489 # Create the logspam command line parser.
490 # if logspam is not installed, or not up to date, it will
491 # first be installed.
492 loader = PypiBasedTool("logspam", "mozilla-log-spam")
493 return loader.create_parser(subcommand)
496 from functools import partial
499 @CommandProvider
500 class LogspamCommand(MachCommandBase):
501 @Command(
502 "logspam",
503 category="misc",
504 description=("Warning categorizer for treeherder test runs."),
506 def logspam(self):
507 pass
509 @SubCommand("logspam", "report", parser=partial(logspam_create_parser, "report"))
510 def report(self, **options):
511 self.activate_virtualenv()
512 logspam = PypiBasedTool("logspam")
513 logspam.run(command="report", **options)
515 @SubCommand("logspam", "bisect", parser=partial(logspam_create_parser, "bisect"))
516 def bisect(self, **options):
517 self.activate_virtualenv()
518 logspam = PypiBasedTool("logspam")
519 logspam.run(command="bisect", **options)
521 @SubCommand("logspam", "file", parser=partial(logspam_create_parser, "file"))
522 def create(self, **options):
523 self.activate_virtualenv()
524 logspam = PypiBasedTool("logspam")
525 logspam.run(command="file", **options)