From 5c41ed041d72ddb7b87e959599f5559cee9c1453 Mon Sep 17 00:00:00 2001 From: Yoshihiro OKUMURA Date: Thu, 11 May 2023 18:55:48 +0900 Subject: [PATCH] increase compatibility with windows 11. --- mdrsclient/__main__.py | 3 ++- mdrsclient/cache.py | 5 +++-- mdrsclient/utils.py | 24 ++++++++++++++++++++++++ 3 files changed, 29 insertions(+), 3 deletions(-) create mode 100644 mdrsclient/utils.py diff --git a/mdrsclient/__main__.py b/mdrsclient/__main__.py index 7a6a4b5..6a1c317 100644 --- a/mdrsclient/__main__.py +++ b/mdrsclient/__main__.py @@ -1,4 +1,5 @@ import argparse +import sys from mdrsclient.commands import ( ChaclCommand, @@ -48,7 +49,7 @@ def main() -> None: parser.print_help() except MDRSException as e: print(f"Error: {e}") - exit(2) + sys.exit(2) if __name__ == "__main__": diff --git a/mdrsclient/cache.py b/mdrsclient/cache.py index c2d06ce..d9ee219 100644 --- a/mdrsclient/cache.py +++ b/mdrsclient/cache.py @@ -1,5 +1,4 @@ import dataclasses -import fcntl import hashlib import json import os @@ -11,6 +10,7 @@ from pydantic.tools import parse_obj_as from mdrsclient.exceptions import UnexpectedException from mdrsclient.models import Laboratories, Token, User from mdrsclient.settings import CONFIG_DIRNAME +from mdrsclient.utils import FileLock @dataclass @@ -125,9 +125,10 @@ class CacheFile: def __save(self) -> None: self.__ensure_cache_dir() with open(self.__cache_file, "w") as f: - fcntl.flock(f, fcntl.LOCK_EX) + FileLock.lock(f) self.__data.update_digest() f.write(json.dumps(dataclasses.asdict(self.__data))) + FileLock.unlock(f) stat = os.stat(self.__cache_file) self.__serial = hash((stat.st_uid, stat.st_gid, stat.st_mode, stat.st_size, stat.st_mtime)) # ensure file is secure. diff --git a/mdrsclient/utils.py b/mdrsclient/utils.py new file mode 100644 index 0000000..97c066a --- /dev/null +++ b/mdrsclient/utils.py @@ -0,0 +1,24 @@ +import os +from typing import IO, Any + +if os.name == "nt": + import msvcrt + +elif os.name == "posix": + import fcntl + + +class FileLock: + @staticmethod + def lock(file: IO[Any]) -> None: + if os.name == "nt": + msvcrt.locking(file.fileno(), msvcrt.LK_LOCK, 1) + elif os.name == "posix": + fcntl.flock(file.fileno(), fcntl.LOCK_EX) + + @staticmethod + def unlock(file: IO[Any]) -> None: + if os.name == "nt": + msvcrt.locking(file.fileno(), msvcrt.LK_UNLCK, 1) + else: + fcntl.flock(file.fileno(), fcntl.LOCK_UN)