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 |
| 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 | |
| 19 | import os |
| 20 | import inspect |
| 21 | |
| 22 | |
| 23 | def 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 | |
Gilles Peskine | 7ff4766 | 2022-09-18 21:17:09 +0200 | [diff] [blame] | 28 | def check_repo_path(): |
| 29 | """ |
| 30 | Check that the current working directory is the project root, and throw |
| 31 | an exception if not. |
| 32 | """ |
| 33 | if not all(os.path.isdir(d) for d in ["include", "library", "tests"]): |
| 34 | raise Exception("This script must be run from Mbed TLS root") |
Gilles Peskine | 40de3d3 | 2022-10-14 15:13:45 +0200 | [diff] [blame] | 35 | |
| 36 | def chdir_to_root() -> None: |
| 37 | """Detect the root of the Mbed TLS source tree and change to it. |
| 38 | |
| 39 | The current directory must be up to two levels deep inside an Mbed TLS |
| 40 | source tree. |
| 41 | """ |
| 42 | for d in [os.path.curdir, |
| 43 | os.path.pardir, |
| 44 | os.path.join(os.path.pardir, os.path.pardir)]: |
| 45 | if looks_like_mbedtls_root(d): |
| 46 | os.chdir(d) |
| 47 | return |
| 48 | raise Exception('Mbed TLS source tree not found') |
| 49 | |
| 50 | |
| 51 | def guess_mbedtls_root(): |
| 52 | """Guess mbedTLS source code directory. |
| 53 | |
| 54 | Return the first possible mbedTLS root directory |
| 55 | """ |
| 56 | dirs = set({}) |
| 57 | for frame in inspect.stack(): |
| 58 | path = os.path.dirname(frame.filename) |
| 59 | for d in ['.', os.path.pardir] \ |
| 60 | + [os.path.join(*([os.path.pardir]*i)) for i in range(2, 10)]: |
| 61 | d = os.path.abspath(os.path.join(path, d)) |
| 62 | if d in dirs: |
| 63 | continue |
| 64 | dirs.add(d) |
| 65 | if looks_like_mbedtls_root(d): |
| 66 | return d |
| 67 | raise Exception('Mbed TLS source tree not found') |