Browse Source

Made the parser more verbose and added some comments for comprehension.

neo
Raphael Roberts 6 years ago
parent
commit
8254e358a0
  1. 1
      .gitignore
  2. 15
      ssh_config_utils/parser.py
  3. 9
      tests/tests.py

1
.gitignore

@ -3,3 +3,4 @@ __pycache__
.dir-locals.el
.#*
*.egg-info

15
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<key>\S+)(?:[ \t]+|[ \t]*=[ \t]*)(?P<values>.*)")
KEY_VALUE = re.compile(
r"""
(?P<key>\S+) #anything that isn't a space is part of the key
(?:
[ \t]+ #seperated by whitespace
|
[ \t]*=[ \t]* #seperated by equals
)
(?P<values>.*)""",
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:

9
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)
Loading…
Cancel
Save