1# SPDX-License-Identifier: Apache-2.0
2#
3# Copyright (c) 2022, Nordic Semiconductor ASA
4
5# FindDTC module for locating devicetree compiler, DTC.
6#
7# The module defines the following variables:
8#
9# 'DTC'
10# Path to devicetree compiler, dtc.
11# Set to 'DTC-NOTFOUND' if dtc was not found.
12#
13# 'Dtc_FOUND', 'DTC_FOUND'
14# True if the devicetree compiler, dtc, was found.
15#
16# 'DTC_VERSION_STRING'
17# The version of devicetree compiler, dtc.
18
19find_program(
20  DTC
21  dtc
22  )
23
24if(DTC)
25  # Parse the 'dtc --version' output to find the installed version.
26  execute_process(
27    COMMAND
28    ${DTC} --version
29    OUTPUT_VARIABLE dtc_version_output
30    ERROR_VARIABLE  dtc_error_output
31    RESULT_VARIABLE dtc_status
32    )
33
34  set(DTC_VERSION_STRING)
35  if(${dtc_status} EQUAL 0)
36    string(REGEX MATCH "Version: DTC v?([0-9]+[.][0-9]+[.][0-9]+).*" out_var ${dtc_version_output})
37    set(DTC_VERSION_STRING ${CMAKE_MATCH_1})
38  endif()
39endif()
40
41find_package_handle_standard_args(Dtc
42                                  REQUIRED_VARS DTC
43                                  VERSION_VAR DTC_VERSION_STRING
44)
45
46if(NOT Dtc_FOUND)
47  # DTC was found but version requirement is not met, or dtc was not working.
48  # Treat it as DTC was never found by resetting the result from `find_program()`
49  set(DTC DTC-NOTFOUND CACHE FILEPATH "Path to a program" FORCE)
50endif()
51