# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, # You can obtain one at http://mozilla.org/MPL/2.0/.
import fnmatch import functools import json import os import re import subprocess import sys import tempfile import time import uuid from functools import partial from pprint import pprint
import mozpack.path as mozpath import sentry_sdk import yaml from mach.decorators import Command, CommandArgument, SubCommand from mach.registrar import Registrar from mozbuild.util import cpu_count from mozfile import load_source
# Set the path so that Sphinx can find jsdoc, unfortunately there isn't # a way to pass this to Sphinx itself at the moment.
os.environ["PATH"] = (
mozpath.join(command_context.topsrcdir, "node_modules", ".bin")
+ os.pathsep
+ _node_path()
+ os.pathsep
+ os.environ["PATH"]
)
import webbrowser
from livereload import Server
from moztreedocs.package import create_tarball
unique_id = f"{project()}/{str(uuid.uuid1())}"
outdir = outdir or os.path.join(command_context.topobjdir, "docs")
savedir = os.path.join(outdir, fmt)
if path isNone:
path = command_context.topsrcdir if os.environ.get("MOZ_AUTOMATION") != "1":
print( "\nBuilding the full documentation tree.\n" "Did you mean to only build part of the documentation?\n" "For a faster command, consider running:\n" " ./mach doc path/to/docs\n"
)
path = os.path.normpath(os.path.abspath(path))
docdir = _find_doc_dir(path) ifnot docdir:
print(_dump_sphinx_backtrace()) return die( "failed to generate documentation:\n"
f"{path}: could not find docs at this location"
)
if linkcheck: # We want to verify if the links are valid or not
fmt = "linkcheck" if no_autodoc: if disable_warnings_check: return die( "'--no-autodoc' flag may not be used with '--disable-warnings-check'"
)
toggle_no_autodoc()
status, warnings = _run_sphinx(docdir, savedir, fmt=fmt, jobs=jobs, verbose=verbose) if status != 0:
print(_dump_sphinx_backtrace()) return die(
f"failed to generate documentation:\n{path}: sphinx return code {status}"
) else:
print(f"\nGenerated documentation:\n{savedir}")
ifnot disable_warnings_check: with open(os.path.join(DOC_ROOT, "config.yml")) as fh:
docs_config = yaml.safe_load(fh)
log_results(fatal_errors, known_errors) if len(fatal_errors): return1
# Upload the artifact containing the link to S3 # This would be used by code-review to post the link to Phabricator if write_url isnotNone:
unique_link = BASE_LINK + unique_id + "/index.html" with open(write_url, "w") as fp:
fp.write(unique_link)
fp.flush()
print("Generated " + write_url)
if dump_trees isnotNone:
parent = os.path.dirname(dump_trees) if parent andnot os.path.isdir(parent):
os.makedirs(parent) with open(dump_trees, "w") as fh:
json.dump(manager().trees, fh)
if archive:
archive_path = os.path.join(outdir, f"{project()}.tar.gz")
create_tarball(archive_path, savedir)
print(f"Archived to {archive_path}")
if upload:
_s3_upload(savedir, project(), unique_id, version())
ifnot serve:
index_path = os.path.join(savedir, "index.html") if auto_open and os.path.isfile(index_path):
webbrowser.open(index_path) return
# Create livereload server. Any files modified in the specified docdir # will cause a re-build and refresh of the browser (if open). try:
host, port = http.split(":", 1)
port = int(port) except ValueError: return die(f"invalid address: {http}")
def _dump_sphinx_backtrace(): """ If there is a sphinx dump file, read andreturn
its content.
By default, it isn't displayed. """
pattern = "sphinx-err-*"
output = ""
tmpdir = "/tmp"
ifnot os.path.isdir(tmpdir): # Only run it on Linux return
files = os.listdir(tmpdir) for name in files: if fnmatch.fnmatch(name, pattern):
pathFile = os.path.join(tmpdir, name)
stat = os.stat(pathFile)
output += f"Name: {pathFile} / Creation date: {time.ctime(stat.st_mtime)}\n" with open(pathFile) as f:
output += f.read() return output
config = config or manager().conf_py_path # When running sphinx with sentry, it adds significant overhead # and makes the build generation very very very slow # So, disable it to generate the doc faster
sentry_sdk.init(None)
warn_fd, warn_path = tempfile.mkstemp()
os.close(warn_fd) try:
args = [ "-T", "-b",
fmt, "-c",
os.path.dirname(config), "-w",
warn_path,
docdir,
savedir,
] if jobs:
args.extend(["-j", jobs]) if verbose:
args.extend(["-v", "-v"])
print("Run sphinx with:")
print(args)
status = sphinx.cmd.build.build_main(args) with open(warn_path, encoding="utf-8") as warn_file:
warnings = warn_file.readlines() return status, warnings finally: try:
os.unlink(warn_path) except Exception as ex:
print(ex)
def _check_sphinx_warnings(warnings, docs_config):
allowed_warnings_regex = [
re.compile(item) for item in docs_config["allowed_warnings"]
] # warnings file contains other strings as well
errors = []
known_errors = [] for warning in warnings:
stripped = warning.strip() # Replace slashes so that we can do matching against the Windows paths # whilst not having to change the regexps.
stripped_and_slashes_changed = stripped.replace("\\", "/")
if len(stripped) and any(
x in stripped for x in ["ERROR", "CRITICAL", "WARNING"]
): ifnot (
any(
item.search(stripped_and_slashes_changed) for item in allowed_warnings_regex
)
):
errors.append(stripped) else:
known_errors.append(stripped)
# Prefer the Mozilla project name, falling back to Sphinx's # default variable if it isn't defined.
project = getattr(conf, "moz_project_name", None) ifnot project:
project = conf.project.replace(" ", "_")
def _node_path(): from mozbuild.nodeutil import find_node_executable
node, _ = find_node_executable()
return os.path.dirname(node)
def _find_doc_dir(path): if os.path.isfile(path): return
valid_doc_dirs = ("doc", "docs") for d in valid_doc_dirs:
p = os.path.join(path, d) if os.path.isdir(p):
path = p
for index_file in ["index.rst", "index.md"]: if os.path.exists(os.path.join(path, index_file)): return path
def _s3_upload(root, project, unique_id, version=None): # Workaround the issue # BlockingIOError: [Errno 11] write could not complete without blocking # https://github.com/travis-ci/travis-ci/issues/8920 import fcntl
from moztreedocs.package import distribution_files from moztreedocs.upload import s3_set_redirects, s3_upload
fcntl.fcntl(1, fcntl.F_SETFL, 0)
# Files are uploaded to multiple locations: # # <project>/latest # <project>/<version> # # This allows multiple projects and versions to be stored in the # S3 bucket.
files = list(distribution_files(root))
key_prefixes = [] if version:
key_prefixes.append(f"{project}/{version}")
# Until we redirect / to main/latest, upload the main docs # to the root. if project == "main":
key_prefixes.append("")
key_prefixes.append(unique_id)
with open(os.path.join(DOC_ROOT, "config.yml")) as fh:
redirects = yaml.safe_load(fh)["redirects"]
redirects = {k.strip("/"): v.strip("/") for k, v in redirects.items()}
all_redirects = {}
for prefix in key_prefixes:
s3_upload(files, prefix)
# Don't setup redirects for the "version" or "uuid" prefixes since # we are exceeding a 50 redirect limit and external things are # unlikely to link there anyway (see bug 1614908). if (version and prefix.endswith(version)) or prefix == unique_id: continue
redirect_prefix = prefix + "/"if prefix else""
all_redirects.update({
redirect_prefix + k: redirect_prefix + v for k, v in redirects.items()
})
print("Redirects currently staged")
pprint(all_redirects, indent=1)
s3_set_redirects(all_redirects)
unique_link = BASE_LINK + unique_id + "/index.html"
print("Uploaded documentation can be accessed here " + unique_link)
@SubCommand( "doc", "mach-telemetry",
description="Generate documentation from Glean metrics.yaml files",
) def generate_telemetry_docs(command_context):
args = [
sys.executable, "-mglean_parser", "translate", "-f", "markdown", "-o",
os.path.join(topsrcdir, "python/mach/docs/"),
os.path.join(topsrcdir, "python/mach/pings.yaml"),
os.path.join(topsrcdir, "python/mach/metrics.yaml"),
os.path.join(topsrcdir, "python/mozbuild/metrics.yaml"),
]
metrics_paths = [
handler.metrics_path for handler in Registrar.command_handlers.values() if handler.metrics_path isnotNone
]
args.extend([
os.path.join(command_context.topsrcdir, path) for path in set(metrics_paths)
])
subprocess.check_call(args)
@SubCommand( "doc", "show-targets",
description="List all reference targets. Requires the docs to have been built.",
)
@CommandArgument( "--format", default="html", dest="fmt", help="Documentation format used."
)
@CommandArgument( "--outdir", default=None, metavar="DESTINATION", help="Where output was written."
) def show_reference_targets(command_context, fmt="html", outdir=None):
command_context.activate_virtualenv()
command_context.virtualenv_manager.install_pip_requirements(
os.path.join(here, "requirements.txt")
)
ifnot os.path.exists(inv_path): return die( "object inventory not found: {inv_path}.\n" "Rebuild the docs and rerun this command"
)
sphinx.ext.intersphinx.inspect_main([inv_path])
@functools.cache def transform_error_regexp(): # Lazily created, because we need to wait to get the staging_dir.
# This regexp matches a couple of styles of message: # # path/to/simpletest.rst: WARNING: document isn't included in any toctree # path/to/index.rst:2: WARNING: Title underline too short. # # The distinction is that some of them give a line number and some of them don't. # We need to replace the path, and split the text of the message so # that we can insert a pipe for automation to detect. return re.compile(
re.escape(os.path.join(manager().staging_dir, "")) + r"(.*?)(:[0-9]*)?:\s*(.*)"
)
def transform_error(msg):
match = transform_error_regexp().match(msg) if match:
filePath = match.group(1) for staging_path, original_path in manager().trees.items(): if staging_path != os.path.dirname(filePath): continue
return { "linter": "source-test-doc-upload", "path": os.path.join(
str(manager().topsrcdir),
filePath.replace(staging_path, original_path),
), "relpath": filePath.replace(staging_path, original_path), # Remove the first character, as it'll be the : "lineno": (
int(match.group(2)[1:]) if match.group(2) isnotNoneelseNone
), "message": match.group(3),
}
def log_results(fatal_errors, known_errors): """
This will always output to stdout, but optionally also dump messages
to error_file in the JSON format needed for the review bot.
Ideally we should reuse mozlint's logger here. """
for m in known_errors:
result_details = transform_error(m)
print_result_to_stderr("KNOWN", result_details)
print(f"Known Failures: {len(known_errors)}")
for m in fatal_errors:
result_details = transform_error(m)
print_result_to_stderr("UNEXPECTED", result_details)
print(f"Failures: {len(fatal_errors)}")
Messung V0.5 in Prozent
¤ Dauer der Verarbeitung: 0.18 Sekunden
(vorverarbeitet am 2026-08-24)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.