From 69f342fcab9fbc0716109105346044486506e466 Mon Sep 17 00:00:00 2001 From: Akemi Izuko Date: Sun, 26 May 2024 21:49:15 -0600 Subject: [PATCH] Parser: add property sorting --- README.md | 14 +++++++------- src/main.py | 19 ++++++++++++------- 2 files changed, 19 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 16b06b7..f94da7a 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,7 @@ ohaton: Hostname: ohaton.cs.ualberta.ca coronation: - # Using __uni_template here would make more sense outside an example + # Using __uni_template here would make more sense, but ohaton works too template: ohaton ssh_props: Hostname: coronation.cs.ualberta.ca @@ -111,17 +111,17 @@ Will generate: ```sshconfig Host ohaton: - ForwardX11 no + ForwardX11 false Hostname ohaton.cs.ualberta.ca - IdentitiesOnly yes + IdentitiesOnly true IdentityFile ~/.ssh/id_ed25519 Port 22 User emiliko Host coronation: - ForwardX11 no + ForwardX11 false Hostname coronation.cs.ualberta.ca - IdentitiesOnly yes + IdentitiesOnly true IdentityFile ~/.ssh/id_ed25519 Port: 22 User emiliko @@ -130,7 +130,7 @@ Host coronation: As a note, properties inherited from templates will be overwritten entirely, even if they're multi-valued. For example: -``` +```yaml __uni: ssh_props: LocalForward: @@ -163,7 +163,7 @@ different for loops can be declared under the `for` section. orca: ssh_props: Hostname: 10.42.43.1 - User emiliko + User: emiliko for: - variable: port range: diff --git a/src/main.py b/src/main.py index 121204c..b1a4496 100644 --- a/src/main.py +++ b/src/main.py @@ -107,7 +107,9 @@ def parse_props(host, props, hosts): template = props.get("template") if template and template not in hosts: - raise SyntaxError(f"Template `{template}` required by `{host}` is not declared above `{host}` in the yaml") + raise SyntaxError( + f"Template `{template}` required by `{host}` is not declared above `{host}` in the yaml" + ) elif template: for k, v in hosts[props.get("template")].items(): if k not in parsed: @@ -120,7 +122,7 @@ def remove_templates(expanded): hosts = dict(expanded) for host, props in data.items(): - if host.startswith('__'): + if host.startswith("__"): del hosts[host] return hosts @@ -160,14 +162,17 @@ def to_ssh_config_string(parse): s = str() for host, keys in parse.items(): - s += f"Host {host}\n" + lines = list() + for key, values in keys.items(): for value in values: if isinstance(value, bool): - s += f"\t{key} {'true' if value else 'no'}\n" + lines.append(f"\t{key} {'true' if value else 'false'}") else: - s += f"\t{key} {value}\n" - s += "\n" + lines.append(f"\t{key} {value}") + + # join the sorted lines on a new line character + s += f"Host {host}\n" + "\n".join(sorted(lines)) + "\n\n" return s @@ -183,7 +188,7 @@ parse = parse_yaml(data) if args.json: print(json.dumps(parse)) elif args.out: - with open(args.out, 'w') as f: + with open(args.out, "w") as f: f.write(to_ssh_config_string(parse)) else: print(to_ssh_config_string(parse), end="")