diff --git a/conan/tools/files/conandata.py b/conan/tools/files/conandata.py index 0b01824bbc5..95e6273d313 100644 --- a/conan/tools/files/conandata.py +++ b/conan/tools/files/conandata.py @@ -41,7 +41,7 @@ def recursive_dict_update(d, u): save(path, new_content) -def trim_conandata(conanfile): +def trim_conandata(conanfile, raise_if_missing=True): """ Tool to modify the ``conandata.yml`` once it is exported, to limit it to the current version only @@ -50,7 +50,11 @@ def trim_conandata(conanfile): raise ConanException("The 'trim_conandata()' can only be used in the 'export()' method") path = os.path.join(conanfile.export_folder, "conandata.yml") if not os.path.exists(path): - raise ConanException("conandata.yml file doesn't exist") + if raise_if_missing: + raise ConanException("conandata.yml file doesn't exist") + else: + conanfile.output.warning("conandata.yml file doesn't exist") + return conandata = load(path) conandata = yaml.safe_load(conandata) diff --git a/conans/test/integration/conanfile/conan_data_test.py b/conans/test/integration/conanfile/conan_data_test.py index 89f10d65912..c9388da801d 100644 --- a/conans/test/integration/conanfile/conan_data_test.py +++ b/conans/test/integration/conanfile/conan_data_test.py @@ -4,6 +4,7 @@ import textwrap import unittest +import pytest import yaml from conans.model.recipe_ref import RecipeReference @@ -375,3 +376,22 @@ def post_export(conanfile): assert "1.1" not in data2 assert data1 == data2 assert "pkg/1.0: Exported: pkg/1.0#03af39add1c7c9d68dcdb10b6968a14d" in c.out + + +@pytest.mark.parametrize("raise_if_missing", [True, False]) +def test_trim_conandata_as_hook_without_conandata(raise_if_missing): + c = TestClient() + c.save_home({"extensions/hooks/hook_trim.py": textwrap.dedent(f""" + from conan.tools.files import trim_conandata + + def post_export(conanfile): + trim_conandata(conanfile, raise_if_missing={raise_if_missing}) + """)}) + + c.save({"conanfile.py": GenConanfile("pkg")}) + if raise_if_missing: + with pytest.raises(Exception, match="conandata.yml file doesn't exist") as exception: + c.run("export . --version=1.0") + else: + c.run("export . --version=1.0") + assert c.exported_recipe_revision() == "a9ec2e5fbb166568d4670a9cd1ef4b26"