Parser: config to yaml parser

This commit is contained in:
Akemi Izuko 2024-05-26 22:09:00 -06:00
parent 69f342fcab
commit fe2d1cfa14
Signed by: akemi
GPG key ID: 8DE0764E1809E9FC

58
src/ssh_config_to_yaml.py Normal file
View file

@ -0,0 +1,58 @@
import argparse
import json
import re
import yaml
from pathlib import Path
parser = argparse.ArgumentParser(description="Process some integers.")
parser.add_argument("file", type=Path, help="yaml config")
parser.add_argument("--json", action="store_true", help="output parse as json")
parser.add_argument("--out", type=Path, help="write into file")
args = parser.parse_args()
def parse_sshconfig(lines):
parse = dict()
hostname = None
host = dict()
re_host = re.compile(r"^\s*Host (.+)$")
re_prop = re.compile(r"^\s*([A-Za-z]+)[ =](.+)$")
for line in lines:
m_host = re_host.match(line)
m_prop = re_prop.match(line)
if m_host:
if hostname is not None:
parse[hostname] = host
hostname = m_host[1]
host = dict()
elif m_prop and host.get(m_prop[1]):
host[m_prop[1]].append(m_prop[2])
elif m_prop:
host[m_prop[1]] = [m_prop[2]]
if hostname is not None:
parse[hostname] = host
return parse
# ╔───────────────────────────────────────────────────────────────────────────╗
# │ Mαiη |
# ╚───────────────────────────────────────────────────────────────────────────╝
with open(args.file, "r") as f:
lines = f.read().splitlines()
parse = parse_sshconfig(lines)
if args.json:
print(json.dumps(parse))
elif args.out:
with open(args.out, "w") as f:
f.write(yaml.dump(parse))
else:
print(yaml.dump(parse), end="")