| Total Complexity | 9 |
| Total Lines | 47 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 1 | #!/usr/bin/python |
||
| 2 | # -*- coding: utf-8 -*- |
||
| 3 | |||
| 4 | import json |
||
| 5 | import os |
||
| 6 | from json import JSONDecodeError |
||
| 7 | |||
| 8 | |||
| 9 | class JsonManager: |
||
| 10 | """ |
||
| 11 | Class used for the file handling and parsing of the tracker.json |
||
| 12 | """ |
||
| 13 | |||
| 14 | json_path = os.path.abspath( |
||
| 15 | os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir, os.path.pardir, "tracker.json")) |
||
| 16 | |||
| 17 | @staticmethod |
||
| 18 | def save_tracked_items(items: list): |
||
| 19 | """Dump the tracked items into the json file |
||
| 20 | |||
| 21 | :param items: |
||
| 22 | :return: |
||
| 23 | """ |
||
| 24 | json.dump(items, open(JsonManager.json_path, "w", encoding="utf-8")) |
||
| 25 | |||
| 26 | @staticmethod |
||
| 27 | def get_tracked_items(required_keys=None) -> list: |
||
| 28 | """Load the tracked items from the json file |
||
| 29 | |||
| 30 | :param required_keys: |
||
| 31 | :return: |
||
| 32 | """ |
||
| 33 | if required_keys is None: |
||
| 34 | required_keys = [] |
||
| 35 | |||
| 36 | # return an empty list if file doesn't exist |
||
| 37 | if not os.path.exists(JsonManager.json_path) or not os.path.isfile(JsonManager.json_path): |
||
| 38 | return [] |
||
| 39 | |||
| 40 | # if file is not a valid json file return an empty list, else the parsed list |
||
| 41 | try: |
||
| 42 | items = json.load(open(JsonManager.json_path, "r", encoding="utf-8")) # type: list |
||
| 43 | # don't include items which don't have all required keys |
||
| 44 | return [item for item in items if all([key in item for key in required_keys])] |
||
| 45 | except JSONDecodeError: |
||
| 46 | return [] |
||
| 47 |