power_insn: refactor opcode matching
[openpower-isa.git] / src / openpower / decoder / test / crtl_path.py
1 # SPDX-License-Identifier: LGPL-3-or-later
2 # Copyright 2022 Jacob Lifshay
3
4
5 from contextlib import contextmanager
6 from itertools import count
7 import os
8 from pathlib import Path
9 import shutil
10 from tempfile import NamedTemporaryFile
11 from threading import local
12
13 __ctrl_path = local()
14
15
16 @contextmanager
17 def __try_lock_file(path):
18 path = Path(path)
19 try:
20 file = path.open("xb")
21 except FileExistsError:
22 yield False
23 return
24 try:
25 yield True
26 finally:
27 file.close()
28 path.unlink()
29
30
31 def get_crtl_path():
32 # type: () -> str
33 path = getattr(__ctrl_path, "path", None)
34 if path is not None:
35 assert isinstance(path, str), "invalid state"
36 return path
37 for i in range(10000):
38 path = f"crtl{i}"
39 with __try_lock_file(f"crtl{i}.lock") as locked:
40 if locked and next(Path(path).glob(".lock_*"), None) is None:
41 shutil.rmtree(path, ignore_errors=True)
42 Path(path).mkdir(parents=True, exist_ok=True)
43 tmpfile = NamedTemporaryFile(prefix=".lock_", dir=path)
44 __ctrl_path.tmpfile = tmpfile
45 __ctrl_path.path = path
46 return path
47 assert False, "can't create crtl* path"