Add formatting to json output

This commit is contained in:
LilyRose2798 2024-04-18 06:28:13 +10:00
parent 634fb8a64d
commit d907a9821f
2 changed files with 19 additions and 11 deletions

View File

@ -25,7 +25,7 @@ def start(config_path: str):
config = None
try:
config = WovenConfig.load(config_path)
config = WovenConfig.load_json_file(config_path)
except FileNotFoundError:
print(f"No file found at '{config_path}'")
except JSONDecodeError as e:
@ -37,10 +37,11 @@ def start(config_path: str):
if config is not None:
config_textbox = ctk.CTkTextbox(master = app)
config_textbox.place(relx = 0.5, rely = 0.0, anchor = ctk.N)
button = ctk.CTkButton(master = app, text = "Load config", command = lambda: print("button pressed"))
button.place(relx = 0.5, rely = 0.5, anchor = ctk.CENTER)
config_textbox.insert("0.0", config.to_json_str())
config_textbox.place(relx = 0.5, rely = 0.5, anchor = ctk.CENTER)
else:
button = ctk.CTkButton(master = app, text = "Load config", command = lambda: print("button pressed"))
button.place(relx = 0.5, rely = 0.5, anchor = ctk.CENTER)
app.mainloop()

View File

@ -5,7 +5,7 @@ from fabric import Connection, Config
from invoke.exceptions import UnexpectedExit
from pathlib import Path
from io import StringIO
from json import loads, dump, JSONDecodeError
from json import loads, dumps, JSONDecodeError
from os import devnull, PathLike
from sys import stdout, stderr, exit
from contextlib import redirect_stdout
@ -69,11 +69,18 @@ class WovenConfig:
return str(self.wireguardDir / f"{self._surround('*')}.{self.wireguardConfigExt}")
@staticmethod
def load(path: str | bytes | PathLike) -> WovenConfig:
return structure(loads(Path(path).read_text(encoding = "UTF-8")), WovenConfig)
def from_json_str(config: str) -> WovenConfig:
return structure(loads(config), WovenConfig)
@staticmethod
def load_json_file(path: str | bytes | PathLike) -> WovenConfig:
return WovenConfig.from_json_str(Path(path).read_text(encoding = "UTF-8"))
def save(self, path: str | bytes | PathLike) -> None:
Path(path).write_text(dump(unstructure(self)), encoding = "UTF-8")
def to_json_str(self) -> str:
return dumps(unstructure(self), indent = 4)
def save_json_file(self, path: str | bytes | PathLike) -> None:
Path(path).write_text(self.to_json_str(), encoding = "UTF-8")
def validate(self) -> None:
tunnel_count = comb(len(self.nodes), 2)
@ -221,7 +228,7 @@ def main():
with redirect_stdout(open(devnull, "w") if args.quiet else stdout):
try:
config = WovenConfig.load(args.config)
config = WovenConfig.load_json_file(args.config)
except FileNotFoundError:
print(f"No configuration file found at '{args.config}'", file = stderr)
exit(1)