[CMake] How to locate clang-format

Matt Wilbur wilburm at gmail.com
Wed Jan 1 23:13:13 EST 2014



On Wednesday, January 1, 2014 at 4:27 PM, Michi Henning wrote:

> I would like to add a target to format my code with clang-format. However, clang-format isn't installed as "clang-format" (at least not on Ubuntu). Instead, it installs itself as "clang-format-3.4", "clang-format-3.5", etc.
> 
> Is there a reasonable way to locate the binary with the largest version number >= than some minimum version? For example, I'd like to find clang-format-3.5 or later (even if the next version happens to be "clang-format-4.0"), and then create a symlink in the build tree for other scripts to use.
I am a CMake newbie (like, just this week), and this is only a partial solution (I think I could probably flesh it out if we knew what the version string would look like in all situations), but maybe something like this:

CMakeLists.txt:

set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR})
find_package(ClangFormat)

if(CLANG_FORMAT_FOUND)
        message("clang-format executable: ${CLANG_FORMAT_EXECUTABLE}")
        message("clang-format version: ${CLANG_FORMAT_VERSION}")
else()
        message("clang-format executable not found")
endif()


FindClangFormat.cmake (in the CMAKE_SOURCE_DIR):

string(REPLACE ":" ";" _PATH $ENV{PATH})
foreach(p ${_PATH})
        file(GLOB cand ${p}/clang-format*)
        if(cand)
                set(CLANG_FORMAT_EXECUTABLE ${cand})
                set(CLANG_FORMAT_FOUND ON)
                execute_process(COMMAND ${CLANG_FORMAT_EXECUTABLE} -version OUTPUT_VARIABLE clang_out )
                string(REGEX MATCH .*\(version[^\n]*\)\n version ${clang_out})
                set(CLANG_FORMAT_VERSION ${CMAKE_MATCH_1})
                break()
        else()
                set(CLANG_FORMAT_FOUND OFF)
        endif()

endforeach()

Matt

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.cmake.org/pipermail/cmake/attachments/20140101/538ff9ca/attachment.htm>


More information about the CMake mailing list