]> git.armaanb.net Git - lightcards.git/blob - lightcards/progress.py
Fix pickle implementation
[lightcards.git] / lightcards / progress.py
1 # Save and resume progress in lightcards
2 # Armaan Bhojwani 2021
3
4 import hashlib
5 import os
6 import pickle
7 import shutil
8
9 dired = f"{os.path.expanduser('~')}/.cache/lightcards/"
10
11
12 def name_gen(stra):
13     """Generate hash of stack for name of pickle file"""
14     return hashlib.md5(str([str(x) for x in stra]).encode("utf-8")).hexdigest()
15
16
17 def make_dirs(dired):
18     """mkdir -p equivalent"""
19     if not os.path.exists(dired):
20         os.makedirs(dired)
21
22
23 def dump(obj, stra):
24     """Write pickle file"""
25     make_dirs(dired)
26
27     pickle.dump(obj, open(f"{dired}/{name_gen(stra)}.p", "wb"))
28
29
30 def dive(stra):
31     """Get pickle file"""
32     file = f"{dired}/{name_gen(stra)}.p"
33     make_dirs(dired)
34     if os.path.exists(file):
35         return pickle.load(open(file, "rb"))
36     else:
37         return False
38
39
40 def purge(stra):
41     """Delete pickle file"""
42     file = f"{dired}/{name_gen(stra)}/"
43     if os.path.exists(file):
44         shutil.rmtree(file)