From 8254e358a08068283c444218dbba4dc9a01c5e0e Mon Sep 17 00:00:00 2001 From: Raphael Roberts Date: Mon, 16 Dec 2019 01:48:08 -0600 Subject: [PATCH] Made the parser more verbose and added some comments for comprehension. --- .gitignore | 1 + ssh_config_utils/parser.py | 15 ++++++++++++++- tests/tests.py | 9 ++++++++- 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index b0fbba1..36c2c9b 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ __pycache__ .dir-locals.el .#* +*.egg-info diff --git a/ssh_config_utils/parser.py b/ssh_config_utils/parser.py index 208d858..8789e40 100644 --- a/ssh_config_utils/parser.py +++ b/ssh_config_utils/parser.py @@ -13,7 +13,17 @@ KEYWORDS_LOWER_TRANSLATE = dict(zip(KEYWORDS_LOWER, KEYWORDS)) HOST_SPLITTER = re.compile( r"host(?:.(?!\bhost\b))+", flags=re.MULTILINE | re.DOTALL | re.IGNORECASE ) -KEY_VALUE = re.compile(r"(?P\S+)(?:[ \t]+|[ \t]*=[ \t]*)(?P.*)") +KEY_VALUE = re.compile( + r""" +(?P\S+) #anything that isn't a space is part of the key +(?: + [ \t]+ #seperated by whitespace + | + [ \t]*=[ \t]* #seperated by equals +) +(?P.*)""", + re.VERBOSE, +) def CamelCase_to_snake(text): # noqa @@ -21,13 +31,16 @@ def CamelCase_to_snake(text): # noqa def parse_config_text(text): + # Step 0: strip leaing whitespaces and comments text_no_leading_whitespace = re.sub(r"^[ \t]+", "", text, flags=re.MULTILINE) text_no_comments = re.sub( r"^\#.*", "", text_no_leading_whitespace, flags=re.MULTILINE ) + # Step 1: split file by Host blocks hosts = HOST_SPLITTER.finditer(text_no_comments) for host in hosts: host_dict = {} + # Step 2: go line by line looking for key=value for line in host.group(0).split("\n"): match = KEY_VALUE.match(line) if match: diff --git a/tests/tests.py b/tests/tests.py index e69941a..cda0b1f 100644 --- a/tests/tests.py +++ b/tests/tests.py @@ -2,6 +2,7 @@ import os import sys import unittest import tempfile +from ssh_config_utils.parser import CamelCase_to_snake samples_dir = os.path.join(sys.path[0], "sample_configs") CONFIG_FILES = dict( @@ -25,4 +26,10 @@ class TestTempFile(ReadWriteTest): class TestParser(ReadWriteTest): - pass + def test_camel_case_to_snake_case(self): + initial_vals = "ThisIsCamelCase", "This" + expected_vals = "this_is_camel_case", "this" + + for initial, expected in zip(initial_vals, expected_vals): + with self.subTest(initial=initial, expected=expected): + self.assertEqual(CamelCase_to_snake(initial), expected)