Prevent creating empty directories using install(DIRECTORY)

When using install(DIRECTORY … […]), how can I prevent empty directories from being created?

For instance, when installing all header files and template implementation files using

# Install the header files and template implementation files (.tcc).
install(DIRECTORY "src/"
		DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${TARGET_NAME}
		FILES_MATCHING
		PATTERN "*.h"
		PATTERN "*.tcc"
	)

the entire folder structure is reproduced, even though in some folders there might only be .cpp files in them and therfore they do not need to be created.

If I know the name of the folder to exclude, e.g. “FolderWithCppOnly” I can explicitly exclude it using

		PATTERN "FolderWithCppOnly" EXCLUDE

but I would have to manually add them one by one and keep track of name changes.

I also tried using regular expressions like so

            REGEX "\.h"
            REGEX "\.tcc"
            REGEX ".*[^(\.h)]$" EXCLUDE
            REGEX ".*[^(\.tcc)]$" EXCLUDE

but it does not work.

Is there a way to exclude all folders and only create them if there are actually matched files in them?

I think this probably needs a new keyword like IGNORE_EMPTY_DIRECTORIES due to compatibility reasons. Note that we’d also need to prune intermediates that we might not know are empty until later:

foo/
foo/bar/
foo/bar/ignored

will install foo/, bar/, ignore ignored, realize bar/ is empty, then realize foo/ is empty and need to remove it. Note that this is just algorithmically; the code can build up this TODO list and execute it later to avoid actually making and removing the intermediate results.

I created an issue: 22947