Parser: add property sorting

This commit is contained in:
Akemi Izuko 2024-05-26 21:49:15 -06:00
parent bd65674875
commit 69f342fcab
Signed by: akemi
GPG key ID: 8DE0764E1809E9FC
2 changed files with 19 additions and 14 deletions

View file

@ -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:

View file

@ -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="")