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