Coverage for sparkle/platform/file_help.py: 22%

18 statements  

« prev     ^ index     » next       coverage.py v7.6.4, created at 2024-11-05 14:48 +0000

1#!/usr/bin/env python3 

2# -*- coding: UTF-8 -*- 

3"""Helper functions for file manipulation.""" 

4from __future__ import annotations 

5from filelock import FileLock 

6from pathlib import Path 

7 

8 

9def add_remove_platform_item(item: any, 

10 file_target: Path, 

11 target: list | dict, 

12 key: str = None, 

13 remove: bool = False) -> None: 

14 """Add/remove item from a list or dictionary of the platform that must saved to disk. 

15 

16 Args: 

17 item: The item to be added to the data structure. 

18 file_target: Path to the file where we want to keep the disk storage. 

19 target: Either a list or dictionary to add the item to. 

20 key: Optional string, in case we use a dictionary. 

21 remove: If true, remove the item from platform. 

22 If the target is a dict, the key is used to remove the entry. 

23 """ 

24 # ast.literal_eval can't deal with Path objects 

25 if isinstance(item, Path): 

26 item = str(item) 

27 if isinstance(file_target, str): 

28 file_target = Path(file_target) 

29 # Add/Remove item to/from object 

30 if isinstance(target, dict): 

31 if remove: 

32 del target[key] 

33 else: 

34 target[key] = item 

35 else: 

36 if remove: 

37 target.remove(item) 

38 else: 

39 target.append(item) 

40 # (Over)Write data structure to path 

41 lock = FileLock(f"{file_target}.lock") 

42 with lock.acquire(timeout=60): 

43 file_target.open("w").write(str(target))