| 1 |
#!/usr/bin/env python3 |
| 2 |
# SPDX-FileCopyrightText: 2023 Sandro Knauß <[email protected]> |
| 3 |
# SPDX-License-Identifier: LGPL-2.1-or-later |
| 4 |
|
| 5 |
import argparse |
| 6 |
import collections |
| 7 |
import contextlib |
| 8 |
from dataclasses import dataclass |
| 9 |
import itertools |
| 10 |
import json |
| 11 |
import logging |
| 12 |
import os |
| 13 |
import pathlib |
| 14 |
import re |
| 15 |
import subprocess |
| 16 |
import sys |
| 17 |
import typing |
| 18 |
import yaml |
| 19 |
|
| 20 |
from debian import deb822 |
| 21 |
|
| 22 |
from . import pkgkde |
| 23 |
|
| 24 |
logging.basicConfig(format='%(levelname).1s: dh_qmldeps ' |
| 25 |
'%(module)s:%(lineno)d: %(message)s') |
| 26 |
log = logging.getLogger('dh_qmldeps') |
| 27 |
|
| 28 |
PATHS = [pathlib.Path(__file__).parent.with_name("datalib"), |
| 29 |
pathlib.Path('/usr/share/pkg-kde-tools/lib') |
| 30 |
] |
| 31 |
|
| 32 |
deb822_log_filter = contextlib.nullcontext |
| 33 |
|
| 34 |
def deb_host_multiarch(): |
| 35 |
try: |
| 36 |
return os.environ["DEB_HOST_MULTIARCH"] |
| 37 |
except KeyError: |
| 38 |
return subprocess.check_output(["dpkg-architecture", "-qDEB_HOST_MULTIARCH"]).strip().decode() |
| 39 |
|
| 40 |
|
| 41 |
@dataclass |
| 42 |
class QtConfig: |
| 43 |
"""Config class to be able to switch configs for different QT versions.""" |
| 44 |
version: str |
| 45 |
qmlimportscanner: str |
| 46 |
basepath: str |
| 47 |
|
| 48 |
def get_basepath(self): |
| 49 |
DEB_HOST_MULTIARCH = deb_host_multiarch() |
| 50 |
return self.basepath.format(DEB_HOST_MULTIARCH=DEB_HOST_MULTIARCH) |
| 51 |
|
| 52 |
@property |
| 53 |
def substvar_basename(self): |
| 54 |
return f"qml{self.version}" |
| 55 |
|
| 56 |
@property |
| 57 |
def qt_name(self): |
| 58 |
return f"qt{self.version}" |
| 59 |
|
| 60 |
def substvar_name(self, name): |
| 61 |
return f"{self.substvar_basename}:{name}" |
| 62 |
|
| 63 |
def get_config(): |
| 64 |
"""Read config file and return a dict with version: QtConfig""" |
| 65 |
config_name = "qt_version_info.yml" |
| 66 |
for path in PATHS: |
| 67 |
p = path/config_name |
| 68 |
if p.exists(): |
| 69 |
c = yaml.load(p.read_text(), yaml.BaseLoader) |
| 70 |
for qt_version in c: |
| 71 |
c[qt_version] = QtConfig(version=qt_version,**c[qt_version]) |
| 72 |
return c |
| 73 |
|
| 74 |
raise FileNotFoundError(f"Did't find '{config_name}' in {PATHS}") |
| 75 |
|
| 76 |
|
| 77 |
def iter_part_over_version(part: str, version: str): |
| 78 |
""" iter over version variants. |
| 79 |
|
| 80 |
>>> gen = iter_part_over_version("test", "1.2") |
| 81 |
>>> list(gen) |
| 82 |
["test.1.2", |
| 83 |
"test.1", |
| 84 |
"test" |
| 85 |
] |
| 86 |
""" |
| 87 |
pos = None |
| 88 |
|
| 89 |
v = version |
| 90 |
while pos != -1: |
| 91 |
v = v[:pos] |
| 92 |
pos = v.rfind(".") |
| 93 |
yield f"{part}.{v}" |
| 94 |
yield part |
| 95 |
|
| 96 |
def iter_tail(parts: list, version: str): |
| 97 |
"""iter over all version parants of the tail part of the parts. |
| 98 |
|
| 99 |
>>> gen = iter_tail(["a","b"], "1") |
| 100 |
>>> list(gen) |
| 101 |
[["a.1","b.1], |
| 102 |
["a.1", "b"], |
| 103 |
["a", "b.1"], |
| 104 |
["a", "b"] |
| 105 |
] |
| 106 |
""" |
| 107 |
|
| 108 |
item = parts[0] |
| 109 |
tail = parts[1:] |
| 110 |
for i in iter_part_over_version(item, version): |
| 111 |
if tail: |
| 112 |
for t in iter_tail(tail, version): |
| 113 |
yield[i, *t] |
| 114 |
else: |
| 115 |
yield [i,] |
| 116 |
|
| 117 |
|
| 118 |
@dataclass |
| 119 |
class QMLModule: |
| 120 |
name: str |
| 121 |
relpath: str |
| 122 |
debian_pkg: str |
| 123 |
|
| 124 |
|
| 125 |
class QMLModules: |
| 126 |
"""Dict of QML modules with QML module name as key and QMLModule as value.""" |
| 127 |
def __init__(self, base_path: pathlib.Path, apt_file:bool): |
| 128 |
self.base_path = base_path |
| 129 |
self._fill_modules(apt_file) |
| 130 |
|
| 131 |
def _fill_modules(self, apt_file:bool): |
| 132 |
modules = collections.defaultdict(dict) |
| 133 |
try: |
| 134 |
output = subprocess.check_output(["dpkg-query", "-S", self.base_path/"**/qmldir"], text=True) |
| 135 |
for line in output.splitlines(): |
| 136 |
package, *_ ,path = line.split(":") |
| 137 |
path = pathlib.Path(path.strip()) |
| 138 |
name = self._qmlname(path) |
| 139 |
module = QMLModule(name, self._relpath(path), package) |
| 140 |
modules[module.name][module.relpath] = module |
| 141 |
except subprocess.CalledProcessError: |
| 142 |
pass |
| 143 |
|
| 144 |
if apt_file: |
| 145 |
_ = str(self.base_path/"*/qmldir") |
| 146 |
search_path = _.replace("*",".*") |
| 147 |
output = subprocess.check_output(["apt-file", "search", "-x", search_path], text=True) |
| 148 |
for line in output.splitlines(): |
| 149 |
package, *_ ,path = line.split(":") |
| 150 |
path = pathlib.Path(path.strip()) |
| 151 |
name = self._qmlname(path) |
| 152 |
module = QMLModule(name, self._relpath(path), package) |
| 153 |
modules[module.name][module.relpath] = module |
| 154 |
|
| 155 |
|
| 156 |
glob = str(self.base_path.relative_to("/")/"**/qmldir") |
| 157 |
for package in pkgkde.DebianControl(pathlib.Path("debian/control")).packages: |
| 158 |
package_path = pathlib.Path(f"debian/{package}") |
| 159 |
for path in package_path.glob(glob): |
| 160 |
# Make path abolute like it would be if installed |
| 161 |
path = pathlib.Path("/")/path.relative_to(package_path) |
| 162 |
name = self._qmlname(path) |
| 163 |
module = QMLModule(name, self._relpath(path), package) |
| 164 |
modules[module.name][module.relpath] = module |
| 165 |
|
| 166 |
self.modules = dict(modules) |
| 167 |
|
| 168 |
def _relpath(self, path: pathlib.Path): |
| 169 |
"""strip self.basepath from path and remove the qmldir at the end.""" |
| 170 |
parts = path.parts |
| 171 |
start = len(self.base_path.parts) |
| 172 |
end = -1 if parts[-1] == "qmldir" else None |
| 173 |
return "/".join(parts[start:end]) |
| 174 |
|
| 175 |
def _qmlname(self, path: pathlib.Path): |
| 176 |
"""tranlate a path to QML name. |
| 177 |
|
| 178 |
e.g. /usr/lib/x86_64-linux-gnu/qt5/qml/org/kde/kirigami.2/templates/qmldir |
| 179 |
-> "org.kde.kirigami.templates" |
| 180 |
""" |
| 181 |
relpath = self._relpath(path) |
| 182 |
name = re.sub(r"(\.[0-9])+(/|$)",r"\g<2>", relpath) |
| 183 |
return name.replace("/",".") |
| 184 |
|
| 185 |
def best_matching_module(self, module_name:str, version: str): |
| 186 |
"""the best matching QML module for a specific version. |
| 187 |
|
| 188 |
QML Modules can be installed in different versions e.g. |
| 189 |
|
| 190 |
QtQuick.Controls 2.X -> .../qml/QtQuick/Controls.2 |
| 191 |
QtQuick.Controls 1.X -> .../qml/QtQuick/Controls |
| 192 |
|
| 193 |
but there is also KDE Kirigami, that does do the version different: |
| 194 |
|
| 195 |
org.kde.kirigami.templates 2.X .../kirigami.2/templates |
| 196 |
|
| 197 |
implements "the selection of different versions of a module in |
| 198 |
subdirectories of its own": |
| 199 |
|
| 200 |
https://doc.qt.io/qt-6/qtqml-modules-identifiedmodules.html#locally-installed-identified-modules |
| 201 |
|
| 202 |
""" |
| 203 |
module_variants = self.modules[module_name] |
| 204 |
if len(module_variants) == 1: |
| 205 |
return next(iter(module_variants.values())) |
| 206 |
|
| 207 |
best_matching_module_path = next(i for i in iter_tail(module_name.split("."), version) if "/".join(i) in module_variants) |
| 208 |
return module_variants["/".join(best_matching_module_path)] |
| 209 |
|
| 210 |
|
| 211 |
def get_overrides() -> dict[str, str]: |
| 212 |
"""translate the qmldeps.overrides to an dict.""" |
| 213 |
qml_overrides_path = pathlib.Path("debian/qmldeps.overrides") |
| 214 |
overrides = dict() |
| 215 |
if not qml_overrides_path.exists(): |
| 216 |
return overrides |
| 217 |
|
| 218 |
for line in qml_overrides_path.read_text().splitlines(): |
| 219 |
parts = line.split(" ") |
| 220 |
overrides[parts[0]] = " ".join(parts[1:]) |
| 221 |
|
| 222 |
return overrides |
| 223 |
|
| 224 |
|
| 225 |
def get_optional() -> dict[str, str]: |
| 226 |
"""Translate the qmldeps.optional to an set of QML modules.""" |
| 227 |
qml_optional_path = pathlib.Path("debian/qmldeps.optional") |
| 228 |
optional = dict() |
| 229 |
if not qml_optional_path.exists(): |
| 230 |
return optional |
| 231 |
|
| 232 |
for line in qml_optional_path.read_text().splitlines(): |
| 233 |
parts = line.split(" ") |
| 234 |
optional[parts[0]] = " ".join(parts[1:]) |
| 235 |
|
| 236 |
return optional |
| 237 |
|
| 238 |
|
| 239 |
class Status: |
| 240 |
"""track the status. |
| 241 |
the failed propery tells, if the detection failed somewhere""" |
| 242 |
def __init__(self): |
| 243 |
self.failed = False |
| 244 |
|
| 245 |
status = Status() |
| 246 |
|
| 247 |
|
| 248 |
def detect_qml_deps_in_qmldir(qmldir: pathlib.Path, qml_modules: QMLModules) -> set[QMLModule]: |
| 249 |
"""transform import and depends line in qmldir files to QMLModules""" |
| 250 |
pkgs = set() |
| 251 |
importline = re.compile(r"^\s*(import|depends)\s+(?P<name>[^ \t]+)(\s+(?P<version>.+))?\s*$") |
| 252 |
for line in qmldir.read_text().splitlines(): |
| 253 |
if m := importline.match(line): |
| 254 |
name = m.group("name") |
| 255 |
version = m.group("version") |
| 256 |
if version == "auto": |
| 257 |
version="1" |
| 258 |
elif version is None: |
| 259 |
version="1" |
| 260 |
try: |
| 261 |
module = qml_modules.best_matching_module(name, version) |
| 262 |
except KeyError: |
| 263 |
log.error(f"Missing QML module {name}") |
| 264 |
status.failed = True |
| 265 |
else: |
| 266 |
pkgs.add(module.debian_pkg) |
| 267 |
return pkgs |
| 268 |
|
| 269 |
|
| 270 |
def is_var_missing_in_control(pkg, var_name): |
| 271 |
""" Checks if ${var_name} is in Depends/Recommends/Suggests""" |
| 272 |
var = f"${{{var_name}}}" |
| 273 |
for field in ("Depends", "Recommends", "Suggests"): |
| 274 |
if var in pkg.get(field, ""): |
| 275 |
return False |
| 276 |
return True |
| 277 |
|
| 278 |
|
| 279 |
def is_var_complete_demoted(pkg, var_name, fieldname): |
| 280 |
""" Checks if ${var_name} exists in demoted field""" |
| 281 |
var = f"${{{var_name}}}" |
| 282 |
demoted = False |
| 283 |
for _fieldname in ("Depends", "Recommends", "Suggests"): |
| 284 |
if _fieldname == fieldname: |
| 285 |
demoted = True |
| 286 |
continue |
| 287 |
if not demoted: |
| 288 |
continue |
| 289 |
if var in pkg.get(_fieldname, ""): |
| 290 |
return True |
| 291 |
return False |
| 292 |
|
| 293 |
|
| 294 |
|
| 295 |
def partial_demotion(pkg, dependencies, fieldname): |
| 296 |
""" Remove the depenencies that are demoted in debian/control. |
| 297 |
This was the default behaviour for Debhelper < 14.""" |
| 298 |
demotion = False |
| 299 |
demoted = False |
| 300 |
for _fieldname in ("Depends", "Recommends", "Suggests"): |
| 301 |
if _fieldname == fieldname: |
| 302 |
demotion = True |
| 303 |
continue |
| 304 |
if not demotion: |
| 305 |
continue |
| 306 |
|
| 307 |
if field := pkg.get(_fieldname, ""): |
| 308 |
with deb822_log_filter(): |
| 309 |
field = deb822.PkgRelation.parse_relations(field) |
| 310 |
depends = set(i["name"] for i in itertools.chain.from_iterable(field)) |
| 311 |
if dependencies & depends: |
| 312 |
log.warning(f"Detected dependencies ({dependencies&depends}) are demoted from {fieldname} to {_fieldname}. To be future proof with debhelper level 14, add -d {_fieldname} with the corresponding qml files.") |
| 313 |
dependencies -= depends |
| 314 |
demoted = True |
| 315 |
return demoted |
| 316 |
|
| 317 |
def main(command_line_arguments: typing.List[str]): |
| 318 |
global deb822_log_filter |
| 319 |
parser = argparse.ArgumentParser() |
| 320 |
parser.add_argument( |
| 321 |
'-v', '--verbose', action='store_true', |
| 322 |
default=os.environ.get('DH_VERBOSE') == '1', |
| 323 |
help='turn verbose mode on') |
| 324 |
parser.add_argument( |
| 325 |
'--show', action='store_true', |
| 326 |
help='Show dependecies on stdout.') |
| 327 |
parser.add_argument( |
| 328 |
'-d', dest='fieldname', |
| 329 |
default="Depends", |
| 330 |
choices=['Depends', 'Recommends', 'Suggests'], |
| 331 |
help='Add dependencies to be added to the control file dependency field dependency-field.') |
| 332 |
parser.add_argument( |
| 333 |
'-p', '--package', |
| 334 |
help='package name to act on') |
| 335 |
parser.add_argument( |
| 336 |
'--qt', |
| 337 |
default="6", |
| 338 |
help='choose QT version') |
| 339 |
parser.add_argument( |
| 340 |
'--apt-file', action='store_true', |
| 341 |
help="use apt-file to search for QML modules") |
| 342 |
parser.add_argument( |
| 343 |
'qis', nargs='+', |
| 344 |
help="arguments for qmlimportscanner.") |
| 345 |
|
| 346 |
options, unused_args = parser.parse_known_args(command_line_arguments) |
| 347 |
|
| 348 |
if options.verbose: |
| 349 |
log.setLevel(logging.DEBUG) |
| 350 |
log.debug(f'{command_line_arguments=}') |
| 351 |
log.debug(f'{options=}') |
| 352 |
log.debug(f'{unused_args=}') |
| 353 |
deb822_log_filter = contextlib.nullcontext |
| 354 |
else: |
| 355 |
log.setLevel(logging.INFO) |
| 356 |
deb822_log_filter = pkgkde.deb822_filter_rel_raw_warning |
| 357 |
|
| 358 |
status.failed = False |
| 359 |
|
| 360 |
config = get_config() |
| 361 |
config_qt = config[options.qt] |
| 362 |
qml_modules = QMLModules(pathlib.Path(config_qt.get_basepath()), options.apt_file) |
| 363 |
|
| 364 |
# override the QML module resolution with a predefined list of Debian packages. |
| 365 |
for name, pkg in get_overrides().items(): |
| 366 |
module = QMLModule(name, "override", pkg.strip()) |
| 367 |
qml_modules.modules[name] = {"override": module} |
| 368 |
|
| 369 |
# If those QML modules already exists, do not modify them. |
| 370 |
# If not add an override with no Debian pkg. |
| 371 |
for name, pkg in get_optional().items(): |
| 372 |
if name not in qml_modules.modules: |
| 373 |
module = QMLModule(name, "optional", pkg.strip()) |
| 374 |
qml_modules.modules[name] = {"optional": module} |
| 375 |
|
| 376 |
qmlimportscanner = config_qt.qmlimportscanner |
| 377 |
if not pathlib.Path(qmlimportscanner).exists(): |
| 378 |
qmlimportscanner = "debian/tmp/"+qmlimportscanner |
| 379 |
if not pathlib.Path(qmlimportscanner).exists(): |
| 380 |
log.error(f"Missing {config_qt.qmlimportscanner}.") |
| 381 |
sys.exit(2) |
| 382 |
|
| 383 |
log.debug(f"Run {' '.join([qmlimportscanner, *options.qis])}") |
| 384 |
output = subprocess.check_output([qmlimportscanner, *options.qis]) |
| 385 |
|
| 386 |
qmldirs = [] |
| 387 |
mode = None |
| 388 |
for entry in options.qis: |
| 389 |
if entry.startswith("-"): |
| 390 |
mode = entry |
| 391 |
elif mode == "-rootPath": |
| 392 |
qmldirs.append(pathlib.Path(entry+"/qmldir")) |
| 393 |
elif mode == "-qmlFiles" and entry.endswith("/qmldir"): |
| 394 |
qmldirs.append(pathlib.Path(entry)) |
| 395 |
|
| 396 |
pkgs = set() |
| 397 |
|
| 398 |
for qmldir in qmldirs: |
| 399 |
pkgs |= detect_qml_deps_in_qmldir(qmldir, qml_modules) |
| 400 |
|
| 401 |
for dep in json.loads(output): |
| 402 |
if dep["type"] != "module": |
| 403 |
continue |
| 404 |
name = dep.get("name") |
| 405 |
version = dep.get("version") |
| 406 |
|
| 407 |
try: |
| 408 |
module = qml_modules.best_matching_module(name, version) |
| 409 |
except KeyError: |
| 410 |
log.error(f"Missing QML module {name}") |
| 411 |
status.failed = True |
| 412 |
else: |
| 413 |
pkgs.add(module.debian_pkg) |
| 414 |
|
| 415 |
try: |
| 416 |
dc = pkgkde.DebianControl(pathlib.Path("debian/control")) |
| 417 |
if dc.isSinglePackage(): |
| 418 |
pkg_name = next(iter(dc.packages.keys())) |
| 419 |
else: |
| 420 |
pkg_name = options.package |
| 421 |
except FileNotFoundError: |
| 422 |
pkg_name = None |
| 423 |
|
| 424 |
if not pkg_name in dc.packages: |
| 425 |
log.error(f"Unknown package name {pkg_name}") |
| 426 |
pkg_name = None |
| 427 |
status.failed = True |
| 428 |
|
| 429 |
pkgs -= set([pkg_name, ""]) |
| 430 |
|
| 431 |
if pkg_name: |
| 432 |
if not pkgs: |
| 433 |
if not status.failed: |
| 434 |
log.info("No QML depedencies detected.") |
| 435 |
return |
| 436 |
else: |
| 437 |
sys.exit(1) |
| 438 |
|
| 439 |
pkg = dc.packages[pkg_name] |
| 440 |
if options.show: |
| 441 |
print("depends on:") |
| 442 |
print(", ".join(sorted(pkgs))) |
| 443 |
|
| 444 |
var_name = config_qt.substvar_name(options.fieldname) |
| 445 |
|
| 446 |
substvar_data = {var_name: pkgs} |
| 447 |
|
| 448 |
if pkgkde.active_compat_level() < 14: |
| 449 |
if is_var_missing_in_control(pkg, var_name): |
| 450 |
depends_var = config_qt.substvar_name("Depends") |
| 451 |
if not is_var_missing_in_control(pkg, depends_var): |
| 452 |
substvar_data[depends_var] = pkgs |
| 453 |
log.warning(f"{var_name} is missing in Depends/Recommends/Suggests. pkg-kde-tools >= 0.22.0 supports mutliple fields. In order to not break builds, the detected dependencies are added to {depends_var}, too.") |
| 454 |
else: |
| 455 |
log.error(f"cannot insert qml dependency (missing {var_name} in Depends/Recommends/Suggests)") |
| 456 |
status.failed = True |
| 457 |
|
| 458 |
if is_var_complete_demoted(pkg, var_name, options.fieldname): |
| 459 |
log.warning("The full demotion will not work anymore with Debhelper 14. Please use -d parameter to tell dh_qmldeps the correct dependency fieldname.") |
| 460 |
|
| 461 |
partial_demotion(pkg, pkgs, options.fieldname) |
| 462 |
|
| 463 |
substvars_path = pathlib.Path(f"debian/{pkg_name}.substvars") |
| 464 |
log.debug(f"{substvars_path}: add {substvar_data}") |
| 465 |
pkgkde.set_substvar(substvars_path, substvar_data) |
| 466 |
else: |
| 467 |
print("depends on:") |
| 468 |
print(", ".join(sorted(pkgs))) |
| 469 |
|
| 470 |
if status.failed: |
| 471 |
sys.exit(1) |
| 472 |
|
| 473 |
if __name__ == '__main__': |
| 474 |
main(sys.argv[1:]) |