From b12c637729156263a3fbfdc2d76d80f1d42a79c1 Mon Sep 17 00:00:00 2001 From: Scott K Logan Date: Wed, 4 Dec 2024 13:54:33 -0600 Subject: [PATCH] Improve TOML library compatibility (#44) Python 3.11 adds a TOML parser to the standard library. For older versions of Python, the 'tomli' package is nearly perfectly compatible. For platforms which don't package tomli or a new enough version of Python (i.e. Ubuntu Focal), we can fall back to 'toml'. --- colcon_cargo/package_identification/cargo.py | 18 +++++++++++++++--- setup.cfg | 3 ++- stdeb.cfg | 2 +- test/spell_check.words | 2 ++ 4 files changed, 20 insertions(+), 5 deletions(-) diff --git a/colcon_cargo/package_identification/cargo.py b/colcon_cargo/package_identification/cargo.py index 367b399..d93e261 100644 --- a/colcon_cargo/package_identification/cargo.py +++ b/colcon_cargo/package_identification/cargo.py @@ -5,7 +5,18 @@ from colcon_core.package_identification \ import PackageIdentificationExtensionPoint from colcon_core.plugin_system import satisfies_version -import toml + +try: + # Python 3.11+ + from tomllib import loads as toml_loads + from tomllib import TOMLDecodeError +except ImportError: + try: + from tomli import loads as toml_loads + from tomli import TOMLDecodeError + except ImportError: + from toml import loads as toml_loads + from toml import TomlDecodeError as TOMLDecodeError logger = colcon_logger.getChild(__name__) WORKSPACE = 'WORKSPACE' @@ -52,8 +63,9 @@ def extract_data(cargo_toml): """ content = {} try: - content = toml.load(str(cargo_toml)) - except toml.TomlDecodeError: + with cargo_toml.open('rb') as f: + content = toml_loads(f.read().decode()) + except TOMLDecodeError: logger.error('Decoding error when processing "%s"' % cargo_toml.absolute()) return diff --git a/setup.cfg b/setup.cfg index 5ada5cf..c52136b 100644 --- a/setup.cfg +++ b/setup.cfg @@ -25,7 +25,8 @@ keywords = colcon python_requires = >=3.6 install_requires = colcon-core - toml + # toml is also supported but deprecated + tomli>=1.0.0; python_version < "3.11" packages = find: zip_safe = true diff --git a/stdeb.cfg b/stdeb.cfg index ea0a5f3..4b4eefa 100644 --- a/stdeb.cfg +++ b/stdeb.cfg @@ -1,6 +1,6 @@ [colcon-cargo] No-Python2: -Depends3: python3-colcon-core, python3-toml +Depends3: python3-colcon-core, python3 (>= 3.11) | python3-tomli (>= 1) | python3-toml Suite: focal jammy noble bookworm trixie X-Python3-Version: >= 3.6 Debian-Version: 100 diff --git a/test/spell_check.words b/test/spell_check.words index 1d31f2a..b8a247c 100644 --- a/test/spell_check.words +++ b/test/spell_check.words @@ -37,6 +37,8 @@ thomas tmpdir todo toml +tomli +tomllib toprettyxml tostring xmlstr