1#
2# Copyright (c) 2024 Nordic Semiconductor ASA
3#
4# SPDX-License-Identifier: Apache-2.0
5#
6
7from subprocess import run
8from os import linesep, makedirs
9from re import sub, S
10from pathlib import Path
11from sys import argv
12from shutil import rmtree, copy2
13from tempfile import mkdtemp
14
15p_root = Path(__file__).absolute().parents[1]
16p_build = p_root / 'build'
17p_pet_sample = p_root / 'samples' / 'pet'
18p_pet_cmake = p_pet_sample / 'pet.cmake'
19p_pet_include = p_pet_sample / 'include'
20p_pet_src = p_pet_sample / 'src'
21
22def regenerate():
23    tmpdir = Path(mkdtemp())
24    p = run(['cmake', p_pet_sample, "-DREGENERATE_ZCBOR=Y", "-DCMAKE_MESSAGE_LOG_LEVEL=WARNING"], cwd=tmpdir)
25    rmtree(tmpdir)
26
27def check():
28    files = (list(p_pet_include.iterdir()) + list(p_pet_src.iterdir()) + [p_pet_cmake])
29    contents = "".join(p.read_text(encoding="utf-8") for p in files)
30    tmpdir = Path(mkdtemp())
31    list(makedirs(tmpdir / f.relative_to(p_pet_sample).parent, exist_ok=True) for f in files)
32    list(copy2(f, tmpdir / f.relative_to(p_pet_sample)) for f in files)
33    regenerate()
34    new_contents = "".join(p.read_text(encoding="utf-8") for p in files)
35    list(copy2(tmpdir / f.relative_to(p_pet_sample), f) for f in files)
36    rmtree(tmpdir)
37    return contents == new_contents
38
39if __name__ == "__main__":
40    if len(argv) > 1 and argv[1] == "--check":
41        if not check():
42            print("Check failed")
43            exit(9)
44    else:
45        regenerate()
46