Gilles Peskine | 40de3d3 | 2022-10-14 15:13:45 +0200 | [diff] [blame] | 1 | """Mbed TLS build tree information and manipulation. |
| 2 | """ |
| 3 | |
| 4 | # Copyright The Mbed TLS Contributors |
Dave Rodgman | 7ff7965 | 2023-11-03 12:04:52 +0000 | [diff] [blame] | 5 | # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later |
Gilles Peskine | 40de3d3 | 2022-10-14 15:13:45 +0200 | [diff] [blame] | 6 | # |
Gilles Peskine | 40de3d3 | 2022-10-14 15:13:45 +0200 | [diff] [blame] | 7 | |
| 8 | import os |
| 9 | import inspect |
| 10 | |
| 11 | |
| 12 | def looks_like_mbedtls_root(path: str) -> bool: |
| 13 | """Whether the given directory looks like the root of the Mbed TLS source tree.""" |
| 14 | return all(os.path.isdir(os.path.join(path, subdir)) |
| 15 | for subdir in ['include', 'library', 'programs', 'tests']) |
| 16 | |
Gilles Peskine | 7ff4766 | 2022-09-18 21:17:09 +0200 | [diff] [blame] | 17 | def check_repo_path(): |
| 18 | """ |
| 19 | Check that the current working directory is the project root, and throw |
| 20 | an exception if not. |
| 21 | """ |
| 22 | if not all(os.path.isdir(d) for d in ["include", "library", "tests"]): |
| 23 | raise Exception("This script must be run from Mbed TLS root") |
Gilles Peskine | 40de3d3 | 2022-10-14 15:13:45 +0200 | [diff] [blame] | 24 | |
| 25 | def chdir_to_root() -> None: |
| 26 | """Detect the root of the Mbed TLS source tree and change to it. |
| 27 | |
| 28 | The current directory must be up to two levels deep inside an Mbed TLS |
| 29 | source tree. |
| 30 | """ |
| 31 | for d in [os.path.curdir, |
| 32 | os.path.pardir, |
| 33 | os.path.join(os.path.pardir, os.path.pardir)]: |
| 34 | if looks_like_mbedtls_root(d): |
| 35 | os.chdir(d) |
| 36 | return |
| 37 | raise Exception('Mbed TLS source tree not found') |
| 38 | |
| 39 | |
| 40 | def guess_mbedtls_root(): |
| 41 | """Guess mbedTLS source code directory. |
| 42 | |
| 43 | Return the first possible mbedTLS root directory |
| 44 | """ |
| 45 | dirs = set({}) |
| 46 | for frame in inspect.stack(): |
| 47 | path = os.path.dirname(frame.filename) |
| 48 | for d in ['.', os.path.pardir] \ |
| 49 | + [os.path.join(*([os.path.pardir]*i)) for i in range(2, 10)]: |
| 50 | d = os.path.abspath(os.path.join(path, d)) |
| 51 | if d in dirs: |
| 52 | continue |
| 53 | dirs.add(d) |
| 54 | if looks_like_mbedtls_root(d): |
| 55 | return d |
| 56 | raise Exception('Mbed TLS source tree not found') |