Coverage for sparkle/platform/file_help.py: 22%
18 statements
« prev ^ index » next coverage.py v7.10.7, created at 2025-09-29 10:17 +0000
« prev ^ index » next coverage.py v7.10.7, created at 2025-09-29 10:17 +0000
1#!/usr/bin/env python3
2# -*- coding: UTF-8 -*-
3"""Helper functions for file manipulation."""
5from __future__ import annotations
6from filelock import FileLock
7from pathlib import Path
10def add_remove_platform_item(
11 item: any,
12 file_target: Path,
13 target: list | dict,
14 key: str = None,
15 remove: bool = False,
16) -> None:
17 """Add/remove item from a list or dictionary of the platform that must saved to disk.
19 Args:
20 item: The item to be added to the data structure.
21 file_target: Path to the file where we want to keep the disk storage.
22 target: Either a list or dictionary to add the item to.
23 key: Optional string, in case we use a dictionary.
24 remove: If true, remove the item from platform.
25 If the target is a dict, the key is used to remove the entry.
26 """
27 # ast.literal_eval can't deal with Path objects
28 if isinstance(item, Path):
29 item = str(item)
30 if isinstance(file_target, str):
31 file_target = Path(file_target)
32 # Add/Remove item to/from object
33 if isinstance(target, dict):
34 if remove:
35 del target[key]
36 else:
37 target[key] = item
38 else:
39 if remove:
40 target.remove(item)
41 else:
42 target.append(item)
43 # (Over)Write data structure to path
44 lock = FileLock(f"{file_target}.lock")
45 with lock.acquire(timeout=60):
46 file_target.open("w").write(str(target))