Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions bazel/rules/rules_score/docs/tooling_architecture.rst
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,26 @@ environment variables:
PLANTUML_BIN_RLOC = ctx.executable._plantuml.short_path (rlocation key)
GRAPHVIZ_DOT = ctx.executable._graphviz.path (execroot-relative)
GRAPHVIZ_DOT_RLOC = ctx.executable._graphviz.short_path (rlocation key)
FTA_METAMODEL_DIR = ctx.files._fta_metamodel[0].dirname (execroot-relative)
PLANTUML_FONTCONFIG_DIR = ctx.files._plantuml_fontconfig[0].dirname (execroot-relative)

``FTA_METAMODEL_DIR`` and ``PLANTUML_FONTCONFIG_DIR`` only need the
execroot-relative directory (no ``*_RLOC`` variant); they aren't executables
so there's no runfiles-manifest entry to key a lookup on, and Python resolves
their contents by simple ``os.path.join`` once the directory itself has been
made absolute (see below).

``PLANTUML_FONTCONFIG_DIR`` points at
``//third_party/plantuml:fontconfig_fallback``: a ``fontconfig.properties.tpl``
template plus a bundled ``LiberationSans-Regular.ttf`` font.
``sphinx_conf_helpers.resolve_plantuml_fontconfig()`` substitutes the font's
absolute path into the template, writes the result to a temp file, and
``resolve_plantuml_command()`` passes it to PlantUML via
``--jvm_flag=-Dsun.awt.fontconfig=<path>``. This makes
``sun.awt.X11FontManager`` use the bundled font directly instead of querying
the native libfontconfig library / host-installed fonts, which otherwise
makes PlantUML crash with ``Fontconfig head is null, check your fonts or
fonts configuration`` in minimal containers/toolchains that have neither.

The rlocation keys (``*_RLOC``) are computed once at analysis time:

Expand Down
27 changes: 22 additions & 5 deletions bazel/rules/rules_score/private/sphinx_module.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,14 @@ sphinx_rule_attrs = dict(
doc = "Directory containing fta_metamodel.puml, passed to PlantUML via " +
"-Dplantuml.include.path so FTA diagrams can resolve !include fta_metamodel.puml.",
),
"_plantuml_fontconfig": attr.label(
default = Label("//third_party/plantuml:fontconfig_fallback"),
allow_files = True,
doc = "Directory containing fontconfig.properties.tpl and the bundled " +
"LiberationSans-Regular.ttf fallback font, passed to PlantUML via " +
"-Dsun.awt.fontconfig so it gets usable text metrics even when the " +
"execution environment has no native fontconfig library/fonts.",
),
"allow_persistent_workers": attr.bool(
default = False,
doc = "(experimental) If true, allow Bazel to run this pass's Sphinx build " +
Expand Down Expand Up @@ -233,19 +241,28 @@ def _hermetic_tool_env(ctx):
start, while cwd is still the execroot) and an analysis-time-stable
rlocation key (no exec-config hash) for diagnostic logging. See
docs/tooling_architecture.rst §"Hermetic tool path resolution".

The returned files list (first return value) must be added to the calling
action's `inputs` -- it covers both the FTA metamodel include and the
PlantUML fontconfig fallback (font + template), neither of which is
otherwise reachable from the `tools` attr's executables alone.
"""
gv_short = ctx.executable._graphviz.short_path
graphviz_rloc = gv_short[3:] if gv_short.startswith("../") else ctx.workspace_name + "/" + gv_short
pl_short = ctx.executable._plantuml.short_path
plantuml_rloc = pl_short[3:] if pl_short.startswith("../") else ctx.workspace_name + "/" + pl_short
fta_metamodel_files = ctx.files._fta_metamodel
fta_metamodel_dir = fta_metamodel_files[0].dirname if fta_metamodel_files else ""
return fta_metamodel_files, {
fontconfig_files = ctx.files._plantuml_fontconfig
fontconfig_dir = fontconfig_files[0].dirname if fontconfig_files else ""
hermetic_files = fta_metamodel_files + fontconfig_files
return hermetic_files, {
"PLANTUML_BIN": ctx.executable._plantuml.path,
"PLANTUML_BIN_RLOC": plantuml_rloc,
"GRAPHVIZ_DOT": ctx.executable._graphviz.path,
"GRAPHVIZ_DOT_RLOC": graphviz_rloc,
"FTA_METAMODEL_DIR": fta_metamodel_dir,
"PLANTUML_FONTCONFIG_DIR": fontconfig_dir,
}

def _needs_output_prefix(name):
Expand Down Expand Up @@ -309,9 +326,9 @@ def _score_needs_impl(ctx):
worker_enabled = worker_enabled,
)

fta_metamodel_files, action_env = _hermetic_tool_env(ctx)
hermetic_tool_files, action_env = _hermetic_tool_env(ctx)
ctx.actions.run(
inputs = needs_inputs + fta_metamodel_files,
inputs = needs_inputs + hermetic_tool_files,
outputs = [needs_output],
arguments = [args],
env = action_env,
Expand Down Expand Up @@ -506,10 +523,10 @@ def _score_html_impl(ctx):

# Use the hermetic graphviz wrapper that executes `/usr/bin/dot` inside the
# docs_runtime sysroot via exec_in_sysroot.
fta_metamodel_files, action_env = _hermetic_tool_env(ctx)
hermetic_tool_files, action_env = _hermetic_tool_env(ctx)

ctx.actions.run(
inputs = html_inputs + fta_metamodel_files,
inputs = html_inputs + hermetic_tool_files,
outputs = [sphinx_html_output],
arguments = [args],
env = action_env,
Expand Down
94 changes: 82 additions & 12 deletions bazel/rules/rules_score/src/sphinx_conf_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@
theme, etc.):

- Hermetic PlantUML / Graphviz / FTA-metamodel resolution. The env vars this
reads (PLANTUML_BIN, GRAPHVIZ_DOT, FTA_METAMODEL_DIR) are set
unconditionally by `_hermetic_tool_env()` in sphinx_module.bzl for every
SphinxNeedsBuild/SphinxHtmlBuild action, regardless of which toolchain or
conf_template is in effect - so this works for any consumer without extra
Bazel wiring. See docs/tooling_architecture.rst
§"Hermetic tool path resolution".
reads (PLANTUML_BIN, GRAPHVIZ_DOT, FTA_METAMODEL_DIR,
PLANTUML_FONTCONFIG_DIR) are set unconditionally by `_hermetic_tool_env()`
in sphinx_module.bzl for every SphinxNeedsBuild/SphinxHtmlBuild action,
regardless of which toolchain or conf_template is in effect - so this
works for any consumer without extra Bazel wiring. See
docs/tooling_architecture.rst §"Hermetic tool path resolution".
- sphinx-needs external-needs loading, re-exported from bazel_sphinx_needs
rather than re-derived (see that module's docstring for the JSON format).
- The sphinx-needs type/option/link schema loaded from the upstream S-CORE
Expand All @@ -36,6 +36,7 @@

import logging
import os
import tempfile
from typing import Any, Dict, List, Optional

from bazel_sphinx_needs import (
Expand Down Expand Up @@ -154,14 +155,80 @@ def resolve_fta_metamodel_dir() -> str:
return resolved


def resolve_plantuml_fontconfig() -> Optional[str]:
"""Resolve a ready-to-use sun.awt.FontConfiguration properties file from
PLANTUML_FONTCONFIG_DIR, or None (with a warning) if it can't be built.

OpenJDK on Linux normally builds its logical-font (Serif, SansSerif, ...)
mapping by querying the native libfontconfig library and the host's
installed fonts. In a minimal container/toolchain with neither, that
query fails, and -- because there's also no fontconfig.properties bundled
with the JDK to fall back to -- PlantUML crashes the first time it asks
for any font metric with "Fontconfig head is null, check your fonts or
fonts configuration" (surfaced early by Run.forceOpenJdkResourceLoad).
-Djava.awt.headless=true does not avoid this; the failing font-manager
init happens regardless of headless mode.

PLANTUML_FONTCONFIG_DIR (set by sphinx_module.bzl's _hermetic_tool_env())
points at a directory containing `fontconfig.properties.tpl` (a
sun.awt.FontConfiguration properties template with a `{font_path}`
placeholder) and the bundled `LiberationSans-Regular.ttf` fallback font -- see
//third_party/plantuml:fontconfig_fallback. This substitutes the font's
resolved absolute path into the template and writes the result to a
fresh temp file, since the template and font, while always siblings on
disk, can't reference each other by a fixed relative path: the JVM
resolves a properties file's `filename.*` values against its own current
working directory, not the properties file's location, and that
directory varies with the Bazel sandbox/runfiles layout of whichever
action executes PlantUML.

Returns:
Absolute path to the generated properties file, or None if
PLANTUML_FONTCONFIG_DIR is unset or fontconfig.properties.tpl is
missing from it (a warning is logged either way).
"""
raw = os.environ.get("PLANTUML_FONTCONFIG_DIR", "")
if not raw:
logger.warning(
"PLANTUML_FONTCONFIG_DIR is not set; PlantUML may crash with "
"\"Fontconfig head is null\" in environments without a native "
"fontconfig library and fonts installed."
)
return None

fontconfig_dir = os.path.abspath(raw)
template_path = os.path.join(fontconfig_dir, "fontconfig.properties.tpl")
font_path = os.path.join(fontconfig_dir, "LiberationSans-Regular.ttf")
try:
with open(template_path, "r", encoding="utf-8") as f:
template = f.read()
except OSError as e:
logger.warning("Failed to read PlantUML fontconfig template %s: %s", template_path, e)
return None

resolved = template.replace("{font_path}", font_path)
with tempfile.NamedTemporaryFile(
mode="w",
suffix=".properties",
prefix="plantuml-fontconfig-",
delete=False,
encoding="utf-8",
) as out:
out.write(resolved)
properties_path = out.name

logger.debug("plantuml fontconfig fallback resolved: %s (font: %s)", properties_path, font_path)
return properties_path


def resolve_plantuml_command(required: bool = True, graphviz_dot_path: Optional[str] = None) -> Optional[str]:
"""Build the full `plantuml` conf.py setting.

Combines PLANTUML_BIN with the FTA metamodel include path and the
hermetic Graphviz dot, exactly matching the default template's
configuration. Pair this with `plantuml_output_format = "svg_obj"` in
conf.py (a fixed literal, not tool-path dependent, so it isn't derived
here).
Combines PLANTUML_BIN with the FTA metamodel include path, the hermetic
Graphviz dot, and the hermetic fontconfig fallback, exactly matching the
default template's configuration. Pair this with
`plantuml_output_format = "svg_obj"` in conf.py (a fixed literal, not
tool-path dependent, so it isn't derived here).

Args:
required: See `resolve_graphviz_dot`. Also governs whether a missing
Expand Down Expand Up @@ -195,10 +262,13 @@ def resolve_plantuml_command(required: bool = True, graphviz_dot_path: Optional[
fta_dir = resolve_fta_metamodel_dir()
include_flag = " --jvm_flag=-Dplantuml.include.path=%s" % fta_dir if fta_dir else ""

fontconfig_properties = resolve_plantuml_fontconfig()
fontconfig_flag = " --jvm_flag=-Dsun.awt.fontconfig=%s" % fontconfig_properties if fontconfig_properties else ""

dot_path = graphviz_dot_path if graphviz_dot_path is not None else resolve_graphviz_dot(required=required)
layout_flag = " -graphvizdot %s" % dot_path if dot_path else ""

return "%s%s%s" % (plantuml_path, include_flag, layout_flag)
return "%s%s%s%s" % (plantuml_path, include_flag, fontconfig_flag, layout_flag)


def init_hermetic_tools(app: Any, config: Any) -> None:
Expand Down
21 changes: 21 additions & 0 deletions third_party/plantuml/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,24 @@ java_binary(
"@blueprint_maven_dependencies//:net_sourceforge_plantuml_plantuml",
],
)

# Fallback font + sun.awt.FontConfiguration template so PlantUML gets usable
# text metrics even when the execution environment has no native fontconfig
# library and/or no installed fonts at all (e.g. a minimal Docker build
# image). Without this, the JVM's AWT font manager fails hard the first time
# PlantUML asks for a font metric ("Fontconfig head is null, check your
# fonts or fonts configuration") regardless of -Djava.awt.headless.
# Consumed by sphinx_module.bzl's _hermetic_tool_env() /
# sphinx_conf_helpers.resolve_plantuml_fontconfig(), which resolves
# fontconfig.properties.tpl's {font_path} placeholder to
# LiberationSans-Regular.ttf's absolute runtime path and passes the result
# via -Dsun.awt.fontconfig.
# See LiberationSans-LICENSE.txt for the font's (SIL OFL 1.1) license.
filegroup(
name = "fontconfig_fallback",
srcs = [
"LiberationSans-Regular.ttf",
"fontconfig.properties.tpl",
],
visibility = ["//visibility:public"],
)
103 changes: 103 additions & 0 deletions third_party/plantuml/LiberationSans-LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
Liberation Sans (LiberationSans-Regular.ttf) is vendored here as a fallback
font for sun.awt.FontConfiguration (see fontconfig.properties.tpl and
sphinx_conf_helpers.resolve_plantuml_fontconfig()), so PlantUML gets usable
text metrics even in environments without a native fontconfig library or
any installed fonts.

Source: https://github.com/liberationfonts
Upstream-Name: Liberation Fonts

Copyright:
Digitized data copyright (c) 2010 Google Corporation with Reserved Font
Name Arimo, Tinos and Cousine.
Copyright (c) 2012 Red Hat, Inc. with Reserved Font Name Liberation.

Licensed under the SIL Open Font License, Version 1.1, reproduced below and
also available at https://openfontlicense.org / http://scripts.sil.org/OFL.

-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------

PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.

The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply to any
document created using the fonts or their derivatives.

DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.

"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).

"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).

"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.

"Author" refers to any designer, engineer, programmer, technical writer or
other person who contributed to the Font Software.

PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining a
copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:

1) Neither the Font Software nor any of its individual components, in
Original or Modified Versions, may be sold by itself.

2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.

3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the
corresponding Copyright Holder. This restriction only applies to the
primary font name as presented to the users.

4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.

5) The Font Software, modified or unmodified, in part or in whole, must be
distributed entirely under this license, and must not be distributed
under any other license. The requirement for fonts to remain under
this license does not apply to any document created using the Font
Software.

TERMINATION
This license becomes null and void if any of the above conditions are not
met.

DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER
DEALINGS IN THE FONT SOFTWARE.
Binary file added third_party/plantuml/LiberationSans-Regular.ttf
Binary file not shown.
42 changes: 42 additions & 0 deletions third_party/plantuml/fontconfig.properties.tpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# *******************************************************************************
# Copyright (c) 2026 Contributors to the Eclipse Foundation
#
# See the NOTICE file(s) distributed with this work for additional
# information regarding copyright ownership.
#
# This program and the accompanying materials are made available under the
# terms of the Apache License Version 2.0 which is available at
# https://www.apache.org/licenses/LICENSE-2.0
#
# SPDX-License-Identifier: Apache-2.0
# *******************************************************************************
#
# Minimal sun.awt.FontConfiguration properties file, mapping every logical
# Java font (Serif, SansSerif, Monospaced, Dialog, DialogInput) to the single
# bundled LiberationSans-Regular.ttf fallback font.
#
# Why this exists: OpenJDK on Linux normally builds its logical-font mapping
# by querying the native libfontconfig library and the host's installed
# fonts. In a minimal container/toolchain that has neither, that query fails
# and BOTH the native path and this file's absence cause
# sun.awt.FontConfiguration to throw "Fontconfig head is null, check your
# fonts or fonts configuration" the first time any AWT font metric is
# requested (see PlantUML's Run.forceOpenJdkResourceLoad, which calls
# Font.getStringBounds() specifically to surface this early). Pointing the
# JVM at this file via -Dsun.awt.fontconfig=<resolved path> makes
# sun.awt.X11FontManager use it directly instead of querying the native
# library, so PlantUML gets usable (if visually approximate) text metrics
# regardless of what fonts, if any, the host/container provides.
#
# {font_path} is substituted at Sphinx-config time (see
# sphinx_conf_helpers.resolve_plantuml_fontconfig) with the absolute,
# execroot-resolved path to the bundled LiberationSans-Regular.ttf runfile -- it cannot
# be a path literal here because the actual on-disk location depends on the
# Bazel sandbox/runfiles layout of whichever action executes PlantUML.
version=1

sequence.allfonts=default

allfonts.default=default

filename.default={font_path}