Skip to content

Truly independent web browser

11.0 KB
Raw Blame
#!/usr/bin/env python3

# Copyright (c) 2026-present, the Ladybird developers.
#
# SPDX-License-Identifier: BSD-2-Clause

import argparse
import json
import os
import re
import subprocess
import sys
import urllib.request

from enum import Enum
from pathlib import Path

LADYBIRD_SOURCE_DIR = Path(__file__).resolve().parent.parent.parent

VCPKG = LADYBIRD_SOURCE_DIR / "vcpkg.json"
VCPKG_OVERLAYS_PORTS = LADYBIRD_SOURCE_DIR / "Meta" / "CMake" / "vcpkg" / "overlay-ports"
VCPKG_REPO = LADYBIRD_SOURCE_DIR / "Build" / "vcpkg-release"
VCPKG_BASELINE_URL = "https://raw.githubusercontent.com/microsoft/vcpkg/{}/versions/baseline.json"
FLATPAK_MANIFEST = LADYBIRD_SOURCE_DIR / "Meta" / "CMake" / "flatpak" / "org.ladybird.Ladybird.json"
LGPL_LIBRARIES = LADYBIRD_SOURCE_DIR / "Meta" / "CMake" / "lgpl-libraries.txt"
CARGO_LOCK = LADYBIRD_SOURCE_DIR / "Cargo.lock"
CARGO_SOURCES = LADYBIRD_SOURCE_DIR / "Meta" / "CMake" / "flatpak" / "cargo-sources.json"
GENERATE_CARGO_SOURCES = LADYBIRD_SOURCE_DIR / "Meta" / "CMake" / "flatpak" / "generate-cargo-sources.py"
SELF = "Ladybird"

# List of build tools that are not provided by the Flatpak SDK and therefore in the manifest
# For a vcpkg build these are installed on the host system
flatpak_build_tools = [
    "gn",
]

# List of libraries that are transitive dependencies
# These are in the manifest to fetch before building, but not explicitely versioned
flatpak_transitive_deps = [
    "libyuv",
]

# List of libraries that are in the Flatpak runtime and therefore not in the manifest
# See: https://docs.flatpak.org/en/latest/available-runtimes.html#check-software-available-in-runtimes
flatpak_runtime_libs = [
    "dbus",
    "fontconfig",
    "freetype",
    "harfbuzz",
    "libjpeg-turbo",
    "nghttp2",
    "qtbase",
    "qtpositioning",
    "qtserialport",
    "qtsvg",
    "sqlite3",
    "tiff",
    "vulkan",
    "vulkan-headers",
    "zlib",
]

# List of build tools that vcpkg installs for its own builds, which the Flatpak SDK provides
vcpkg_host_tools = [
    "vcpkg-tool-meson",
]

# List of libraries that are in vcpkg but not needed for the Linux platform
vcpkg_not_linux = [
    "dirent",
    "md4c",
    "mman",
    "pthread",
    "sparkle",
]


class DepMatch(Enum):
    Match = (0,)
    NoMatch = (1,)
    VersionMismatch = (2,)
    Excluded = (3,)


baseline_versions = {}


def get_baseline_version(vcpkg_repo: Path, baseline, name):
    if baseline not in baseline_versions:
        if vcpkg_repo.is_dir():
            # Clear GIT_DIR so git operates on the vcpkg repo, not the parent repo (pre-commit sets GIT_DIR)
            env = {k: v for k, v in os.environ.items() if k != "GIT_DIR"}
            try:
                result = subprocess.run(
                    ["git", "-C", vcpkg_repo, "show", f"{baseline}:versions/baseline.json"],
                    stdout=subprocess.PIPE,
                    stderr=subprocess.DEVNULL,
                    check=True,
                    env=env,
                    text=True,
                )
                baseline_versions[baseline] = json.loads(result.stdout)
            except (subprocess.CalledProcessError, json.JSONDecodeError):
                pass

        if baseline not in baseline_versions:
            url = VCPKG_BASELINE_URL.format(baseline)

            try:
                with urllib.request.urlopen(url) as response:
                    baseline_versions[baseline] = json.load(response)
            except Exception as error:
                print(f"Failed to fetch vcpkg baseline {baseline[:7]}: {error}")
                baseline_versions[baseline] = {}

    port = baseline_versions[baseline].get("default", {}).get(name)
    if port and "baseline" in port:
        return port["baseline"]

    print(f"{name} cannot be matched, vcpkg baseline revision: {baseline[:7]}")


def check_for_match(vcpkg_repo: Path, vcpkg: dict, vcpkg_baseline, name: str, identifier: str) -> DepMatch:
    if name == SELF or name in flatpak_build_tools or name in flatpak_transitive_deps:
        return DepMatch.Excluded

    if name not in vcpkg:
        version = get_baseline_version(vcpkg_repo, vcpkg_baseline, name)

        if version:
            vcpkg[name] = version

    if name in vcpkg:
        version = vcpkg[name]
        normalized_version = re.sub(r"[^A-Za-z0-9]", "", version)
        normalized_identifier = re.sub(r"[^A-Za-z0-9]", "", identifier)
        if version not in identifier and normalized_version not in normalized_identifier:
            return DepMatch.VersionMismatch
        else:
            return DepMatch.Match
    else:
        return DepMatch.NoMatch


def check_vcpkg_vs_flatpak_versioning(vcpkg_repo: Path):
    def match_and_update(name: str, identifier: str) -> bool:
        dep_match = check_for_match(vcpkg_repo, vcpkg, vcpkg_baseline, name, identifier)

        if dep_match == DepMatch.Match or dep_match == DepMatch.Excluded:
            if name in vcpkg:
                del vcpkg[name]

            return False
        else:
            if dep_match == DepMatch.VersionMismatch:
                print(f"{name} version mismatch. vcpkg: {vcpkg[name]}, Flatpak: {source['tag']}")
                del vcpkg[name]
            elif dep_match == DepMatch.NoMatch:
                flatpak.append(name)

            return True

    vcpkg = {}
    flatpak = []
    mismatch_found = False

    with open(VCPKG) as input:
        vcpkg_json = json.load(input)
        vcpkg_baseline = vcpkg_json["builtin-baseline"]

        for package in vcpkg_json["overrides"]:
            # Add name/version pair, strip any '#' postfix from the version
            vcpkg[package["name"]] = str(package["version"]).split("#")[0]

    # Check the vcpkg overlay ports for packages not listed in overrides
    for entry in VCPKG_OVERLAYS_PORTS.iterdir():
        if not entry.is_dir():
            continue

        with open(entry / "vcpkg.json") as input:
            overlay = json.load(input)

            if "name" in overlay and overlay["name"] not in vcpkg and "version" in overlay:
                vcpkg[overlay["name"]] = overlay["version"]

    with open(FLATPAK_MANIFEST) as input:
        for module in json.load(input)["modules"]:
            name = module["name"]

            for source in module["sources"]:
                if "type" in source and source["type"] == "git":
                    if "tag" in source:
                        # Get the tag
                        # Replace '-' with '.': 76-1 vs 76.1
                        tag = str(source["tag"]).replace("-", ".")
                        mismatch_found |= match_and_update(name, tag)

                        break
                    elif "branch" in source or "x-branch" in source:
                        # Get the branch
                        # Strip '_' postfix, replace '/' with '_': chromium/7258_13 vs chromium_7258
                        branch = str(source.get("branch", source.get("x-branch"))).split("_")[0].replace("/", "_")
                        mismatch_found |= match_and_update(name, branch)

                        break
                elif "type" in source and source["type"] == "archive":
                    mismatch_found |= match_and_update(name, source["url"])

                    break
            else:
                if not (name == SELF or name in flatpak_build_tools or name in flatpak_transitive_deps):
                    flatpak.append(name)

        # Remove excluded dependencies from the vcpkg list
        for name in flatpak_runtime_libs + vcpkg_host_tools + vcpkg_not_linux:
            if name in vcpkg:
                del vcpkg[name]

        if len(vcpkg):
            mismatch_found = True
            print(f"There are {len(vcpkg)} vcpkg dependencies that have no match in flatpak")

            for name in vcpkg.keys():
                print(f"- {name}")

        if len(flatpak):
            mismatch_found = True
            print(f"There are {len(flatpak)} flatpak dependencies that have no match in vcpkg")

            for name in flatpak:
                print(f"- {name}")

    return mismatch_found


# The build options that make a library shared, by the build systems of the modules, and those that make it static.
SHARED_BUILD_OPTIONS = ("--enable-shared", "-DBUILD_SHARED_LIBS=ON", "-DBUILD_SHARED=ON", "-Ddefault_library=shared")
STATIC_BUILD_OPTIONS = ("--disable-shared", "--enable-static", "-DBUILD_SHARED_LIBS=OFF", "-DBUILD_SHARED=OFF")


def check_lgpl_modules_build_shared_libraries():
    """Every module under the LGPL has to build a shared library, so that the library can be relinked."""
    with open(LGPL_LIBRARIES) as input:
        lgpl_libraries = {line.strip() for line in input if line.strip() and not line.startswith("#")}
    with open(FLATPAK_MANIFEST) as input:
        modules = [module for module in json.load(input)["modules"] if module["name"] in lgpl_libraries]

    failed = False
    for module in modules:
        options = " ".join([*module.get("config-opts", []), *module.get("build-commands", [])]).split()
        # A CMake cache entry may name its type, as in -DBUILD_SHARED:BOOL=ON.
        options = [re.sub(r"^(-D[^:=]+):[A-Za-z]+=", r"\1=", option) for option in options]
        # Autotools-style builds make static libraries too unless told not to.
        static_by_default = "--enable-shared" in options and "--disable-static" not in options
        if (
            static_by_default
            or any(option in STATIC_BUILD_OPTIONS for option in options)
            or not any(option in SHARED_BUILD_OPTIONS for option in options)
        ):
            failed = True
            print(
                f"The Flatpak module {module['name']} is under the LGPL, so it has to build a shared library only, with "
                f"one of {', '.join(SHARED_BUILD_OPTIONS)} (--enable-shared together with --disable-static) and none "
                f"of {', '.join(STATIC_BUILD_OPTIONS)}"
            )
    return failed


def check_cargo_sources_match_cargo_lock():
    return subprocess.run([sys.executable, GENERATE_CARGO_SOURCES, "--check"]).returncode != 0


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--vcpkg-repo", required=False, type=Path, default=VCPKG_REPO)
    parser.add_argument(
        "file_list", type=Path, nargs="*", default=[VCPKG, FLATPAK_MANIFEST, LGPL_LIBRARIES, CARGO_LOCK]
    )
    args = parser.parse_args()

    vcpkg_repo = args.vcpkg_repo.resolve()
    requested = [f.resolve() for f in args.file_list]
    file_list = [f for f in requested if f.exists()]
    did_fail = False

    if VCPKG in file_list or FLATPAK_MANIFEST in file_list:
        did_fail = check_vcpkg_vs_flatpak_versioning(vcpkg_repo)

    if FLATPAK_MANIFEST in file_list or LGPL_LIBRARIES in file_list:
        did_fail |= check_lgpl_modules_build_shared_libraries()

    if any(path in requested for path in (CARGO_LOCK, CARGO_SOURCES, GENERATE_CARGO_SOURCES)):
        did_fail |= check_cargo_sources_match_cargo_lock()

    # TODO: Add linting of Flatpak and AppStream manifest
    # See #5594, bullet point "Missing lint job in CI to ensure Flatpak and AppStream manifests are up to snuff"

    if did_fail:
        sys.exit(1)


if __name__ == "__main__":
    main()