1"""Mbed TLS build tree information and manipulation. 2""" 3 4# Copyright The Mbed TLS Contributors 5# SPDX-License-Identifier: Apache-2.0 6# 7# Licensed under the Apache License, Version 2.0 (the "License"); you may 8# not use this file except in compliance with the License. 9# You may obtain a copy of the License at 10# 11# http://www.apache.org/licenses/LICENSE-2.0 12# 13# Unless required by applicable law or agreed to in writing, software 14# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16# See the License for the specific language governing permissions and 17# limitations under the License. 18 19import os 20import inspect 21 22 23def looks_like_mbedtls_root(path: str) -> bool: 24 """Whether the given directory looks like the root of the Mbed TLS source tree.""" 25 return all(os.path.isdir(os.path.join(path, subdir)) 26 for subdir in ['include', 'library', 'programs', 'tests']) 27 28 29def chdir_to_root() -> None: 30 """Detect the root of the Mbed TLS source tree and change to it. 31 32 The current directory must be up to two levels deep inside an Mbed TLS 33 source tree. 34 """ 35 for d in [os.path.curdir, 36 os.path.pardir, 37 os.path.join(os.path.pardir, os.path.pardir)]: 38 if looks_like_mbedtls_root(d): 39 os.chdir(d) 40 return 41 raise Exception('Mbed TLS source tree not found') 42 43 44def guess_mbedtls_root(): 45 """Guess mbedTLS source code directory. 46 47 Return the first possible mbedTLS root directory 48 """ 49 dirs = set({}) 50 for frame in inspect.stack(): 51 path = os.path.dirname(frame.filename) 52 for d in ['.', os.path.pardir] \ 53 + [os.path.join(*([os.path.pardir]*i)) for i in range(2, 10)]: 54 d = os.path.abspath(os.path.join(path, d)) 55 if d in dirs: 56 continue 57 dirs.add(d) 58 if looks_like_mbedtls_root(d): 59 return d 60 raise Exception('Mbed TLS source tree not found') 61