JsonManager.get_tracked_items()   A
last analyzed

Complexity

Conditions 5

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 18.6936

Importance

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