2023-12-01 07:00:15 +00:00
import fcntl
2023-12-31 14:17:12 +00:00
import json
2023-12-01 07:00:15 +00:00
from collections . abc import Generator
from contextlib import contextmanager
from pathlib import Path
2023-12-31 14:17:12 +00:00
from typing import Any
2024-03-08 16:23:18 +00:00
from clan_cli . jsonrpc import ClanJSONEncoder
2023-12-31 14:17:12 +00:00
2024-03-08 16:23:18 +00:00
from . dirs import user_history_file
2023-12-01 07:00:15 +00:00
@contextmanager
2024-04-15 19:06:03 +00:00
def locked_open ( filename : str | Path , mode : str = " r " ) - > Generator :
2023-12-01 07:00:15 +00:00
"""
This is a context manager that provides an advisory write lock on the file specified by ` filename ` when entering the context , and releases the lock when leaving the context . The lock is acquired using the ` fcntl ` module ' s `LOCK_EX` flag, which applies an exclusive write lock to the file.
"""
with open ( filename , mode ) as fd :
fcntl . flock ( fd , fcntl . LOCK_EX )
yield fd
fcntl . flock ( fd , fcntl . LOCK_UN )
2023-12-31 14:17:12 +00:00
def write_history_file ( data : Any ) - > None :
2024-04-15 19:06:03 +00:00
with locked_open ( user_history_file ( ) , " w+ " ) as f :
2024-03-08 16:23:18 +00:00
f . write ( json . dumps ( data , cls = ClanJSONEncoder , indent = 4 ) )
2023-12-31 14:17:12 +00:00
def read_history_file ( ) - > list [ dict ] :
2024-04-15 19:06:03 +00:00
with locked_open ( user_history_file ( ) , " r " ) as f :
2023-12-31 14:17:12 +00:00
content : str = f . read ( )
parsed : list [ dict ] = json . loads ( content )
return parsed