blob: 97551dd2bfde7852a2b1a82c1015a79a983d3033 [file] [log] [blame]
Gilles Peskine40de3d32022-10-14 15:13:45 +02001"""Mbed TLS build tree information and manipulation.
2"""
3
4# Copyright The Mbed TLS Contributors
Dave Rodgman7ff79652023-11-03 12:04:52 +00005# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
Gilles Peskine40de3d32022-10-14 15:13:45 +02006#
Gilles Peskine40de3d32022-10-14 15:13:45 +02007
8import os
9import inspect
10
11
12def 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 Peskine7ff47662022-09-18 21:17:09 +020017def 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 Peskine40de3d32022-10-14 15:13:45 +020024
25def 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
40def 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')