Query available version(s) of package before find_package()

Let’s say that I want to do something like this:

find_package(pkg REQUIRED COMPONENTS x y z)

However, the components that I need depend on what version of pkg I get, because (for example) the maintainers have shuffled things around between versions, or perhaps they only recently split their package into multiple components.

I don’t want to force a specific version of pkg in my find_package() call, because my users expect to be able to use my software in a wide range of environments.

How can I find out what version(s) of pkg are available before I do the find_package() call? Should my CMakeLists.txt run cmake as a COMMAND to do a test configuration that runs find_package(pkg QUIET), and then use the discovered version information to call the main find_package(pkg COMPONENTS ...) with the version-specific list of components?

As a suggestion, would it not make sense to simply use fall through logic?

You first write find_package with the most likely, or most desired version (since cmake 3.19 you can use ranges, otherwise you need to do it newest version first).
If the find_package fails, then you provide the next find_package with the support for the older component. And so on.
If your code needs to know then you can define compiler flags inside those if statements as well.

Of course, you can’t put the REQUIRED in the first package calls. But ‘worst case’ you can put a message(FATAL_ERROR “”) at the end if none of the find_packages found something.

The biggest downside I see is that it will be slower for the variations further down list.