From 4fd7251abab26c4bd7d839c7accc36a4c979141f Mon Sep 17 00:00:00 2001 From: Raphael Roberts Date: Tue, 19 Nov 2019 18:16:08 -0600 Subject: [PATCH] Finished GroupedConfigFile but need to work host line with extra names --- ssh_config_utils/config_file.py | 32 ++++++++++++++++++++++++++++++++ ssh_config_utils/host.py | 11 +++++++++-- 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/ssh_config_utils/config_file.py b/ssh_config_utils/config_file.py index 654e26e..d3ab062 100644 --- a/ssh_config_utils/config_file.py +++ b/ssh_config_utils/config_file.py @@ -16,12 +16,23 @@ class HostGroup: self.children[name] = child return child + def add_host(self, host): + self.children[host.name] = host + host.parent = self + @property def fullpath(self): if self.parent is None: return "" return ".".join(self.parent.fullpath(), self.name) + def hosts(self): + for child in self.children.values(): + if isinstance(child, HostGroup): + yield from child.hosts() + elif isinstance(child, Host): + yield Host + class ConfigFile: def __init__(self, global_host, hosts): @@ -91,3 +102,24 @@ class GroupedConfigFile(ConfigFile): def __init__(self, global_host, hosts): self.global_host = global_host self.root_group = HostGroup("") + host: Host + for host in hosts: + current = self.root_group + parts = host.name.split(".") + host.name = parts[-1] + for path in parts[:-1]: + current = current.add_child_group(path) + current.add_host(host) + + def format(self, **format_data): + hosts = sorted( + self.root_group.hosts(), + key=lambda host: host.name + if isinstance(host.name, str) + else " ".join(host.name), + ) + if self.global_host is not None: + hosts.insert(0, self.global_host) + return format_data["host_seperator"].join( + map(lambda host: host.format(**format_data), hosts) + ) diff --git a/ssh_config_utils/host.py b/ssh_config_utils/host.py index defa39c..59ce11f 100644 --- a/ssh_config_utils/host.py +++ b/ssh_config_utils/host.py @@ -3,7 +3,8 @@ from ssh_config_utils.parser import CamelCase_to_snake, KEYWORDS_LOWER_TRANSLATE class Host: - def __init__(self, name, options): + def __init__(self, name: str, options): + self.parent = None self.options = options self.name = name @@ -25,8 +26,14 @@ class Host: def __str__(self): return serialize_host(self.name, self.options, dict(indent=" " * 2)) + def fullname(self): + if self.parent is None: + return self.name + else: + return self.parent.fullpath() + def format(self, **format_data): - return serialize_host(self.name, self.options, format_data) + return serialize_host(self.fullname(), self.options, format_data) class GlobalHost(Host):