~javiljoen/shopping-list

ref: 163831ee17ed2f4e28df89cee0c793ec7f19e4d5 shopping-list/src/groceries/txtdb.py -rw-r--r-- 1.1 KiB
163831eeJA Viljoen Update dependencies 1 year, 1 month ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
from groceries import todotxt


class TextFile:
    def __init__(self, file_path):
        self._path = file_path

        if not file_path.exists():
            self._init()

    def _load(self):
        with self._path.open("r") as fh:
            items = todotxt.load(fh)

        return {i.name: i for i in items}

    def _write(self, items):
        with self._path.open("w") as fh:
            todotxt.dump(items, fh)

    def _init(self):
        self._path.touch()

    def insert(self, item):
        db = self._load()
        db[item.name] = item
        self._write(db.values())

    def select_all(self):
        db = self._load()
        return list(db.values())

    def select(self, item_name):
        db = self._load()
        return db.get(item_name)

    def update(self, item_name, item):
        db = self._load()

        if item_name not in db:
            raise LookupError(item_name)

        db[item_name] = item
        self._write(db.values())

    def delete(self, item_name):
        db = self._load()

        if item_name not in db:
            raise LookupError(item_name)

        del db[item_name]
        self._write(db.values())