validate()

validate() 方法可用于将包二进制文件标记为“无效”,或不适用于当前配置。例如,如果有一个头文件库在 Windows 中不起作用,可以使用如下的 conanfile.py

from conan import ConanFile
from conan.errors import ConanInvalidConfiguration

class Pkg(ConanFile):
    name = "pkg"
    version = "1.0"
    package_type = "header-library"
    settings = "os"

    def validate(self):
        if self.settings.os == "Windows":
            raise ConanInvalidConfiguration("Windows not supported")

    def package_id(self):
        self.info.clear()  # header-only

如果尝试在 Windows 中创建此包,它将失败;但在 Linux 中创建则会成功。

$ conan create . -s os=Windows # FAILS
...
ERROR: There are invalid packages:
pkg/1.0: Invalid: Windows not supported
$ conan create . -s os=Linux # WORKS

如果尝试在 Windows 中使用它,它将再次失败。

$ conan install --requires=pkg/1.0 -s os=Windows # FAILS
...
ERROR: There are invalid packages:
pkg/1.0: Invalid: Windows not supported

ConanInvalidConfiguration 导致错误时,Conan 应用程序的退出代码将是 6

可以使用 conan graph info 命令检查给定依赖图的有效性,而不会引发错误。

$ conan graph info --requires=pkg/1.0 -s os=Windows --filter=binary
conanfile:
ref: conanfile
binary: None
pkg/1.0#cfc18fcc7a50ead278a7c1820be74e56:
ref: pkg/1.0#cfc18fcc7a50ead278a7c1820be74e56
binary: Invalid

validate() 方法在整个依赖图计算完成后进行评估。这意味着它可以利用 self.dependencies 信息来引发错误。

from conan import ConanFile
from conan.errors import ConanInvalidConfiguration

class Pkg(ConanFile):
    requires = "dep/0.1"

    def validate(self):
        if self.dependencies["dep"].options.myoption == 2:
            raise ConanInvalidConfiguration("Option 2 of 'dep' not supported")

注意

最佳实践

configure() 方法在依赖图完成之前进行评估,因此它无法获取依赖项 options 的实际值。如果需要检查这些依赖项选项值,应该在 validate() 方法中进行,而不是 configure()