-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson_creator.py
More file actions
71 lines (58 loc) · 2.21 KB
/
Copy pathjson_creator.py
File metadata and controls
71 lines (58 loc) · 2.21 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import os
import sys
import json
import subprocess as sub
class JSONCreator:
def __init__(self):
home = os.getenv("HOME")
self.api_script = f"{home}/TerminalToDo/retrieve_information.sh"
self.json_path = f"{home}/TerminalToDo/last_known_state.json"
def _get_name(self) -> dict:
try:
raw_name = sub.run(
[self.api_script, "-n"], capture_output=True, text=True, check=True
)
dict_pair = {"page_name": raw_name.stdout.strip()}
return dict_pair
except sub.CalledProcessError:
sys.stdout.write("Failed: can not get name.")
@staticmethod
def _has_children(main_page_element: dict) -> bool:
return main_page_element["has_children"]
def check_connection(self):
try:
sub.run([self.api_script, "-n"], check=True, text=True, capture_output=True)
return True
except sub.CalledProcessError:
return False
def _get_page_json(self):
retr_result = sub.run(
[self.api_script, "-j"], capture_output=True, text=True, check=True
)
parsed_output = json.loads(retr_result.stdout)
for element in parsed_output:
if self._has_children(element):
got_children = sub.run(
[self.api_script, "-c", element["id"]],
capture_output=True,
text=True,
)
parsed_children = json.loads(got_children.stdout)
element["children_contents"] = parsed_children
name = self._get_name()
parsed_output.insert(0, name)
return parsed_output
def update_json(self):
if self.check_connection():
sys.stdout.write("Connection established, updating.")
updated_data = self._get_page_json()
with open("last_known_state.json", "w+") as file:
file.write(json.dumps(updated_data, indent=6))
else:
sys.stdout.write(
"No connection to the API.\n"
"Update failed.\n"
"Last known state will be displayed."
)
if __name__ == "__main__":
JSONCreator().update_json()