summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJohn Estabrook <jestabro@vyos.io>2022-10-25 13:42:30 -0500
committerJohn Estabrook <jestabro@vyos.io>2022-10-25 15:09:11 -0500
commit29b656f14d8bb7622ff861208d26cf8eb018670d (patch)
tree0b0b6237039add86523d801be6a0c191705954f6
parentc0594071c6c1062cc0069377b6666de89a172d0a (diff)
downloadvyos-1x-29b656f14d8bb7622ff861208d26cf8eb018670d.tar.gz
vyos-1x-29b656f14d8bb7622ff861208d26cf8eb018670d.zip
vyos.util: T4773: add camel_to_snake_case conversion
-rw-r--r--python/vyos/util.py7
-rw-r--r--src/tests/test_util.py14
2 files changed, 21 insertions, 0 deletions
diff --git a/python/vyos/util.py b/python/vyos/util.py
index 461df9a6e..e4e2a44ec 100644
--- a/python/vyos/util.py
+++ b/python/vyos/util.py
@@ -1105,3 +1105,10 @@ def sysctl_write(name, value):
call(f'sysctl -wq {name}={value}')
return True
return False
+
+# approach follows a discussion in:
+# https://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-snake-case
+def camel_to_snake_case(name: str) -> str:
+ pattern = r'\d+|[A-Z]?[a-z]+|\W|[A-Z]{2,}(?=[A-Z][a-z]|\d|\W|$)'
+ words = re.findall(pattern, name)
+ return '_'.join(map(str.lower, words))
diff --git a/src/tests/test_util.py b/src/tests/test_util.py
index 8ac9a500a..d8b2b7940 100644
--- a/src/tests/test_util.py
+++ b/src/tests/test_util.py
@@ -26,3 +26,17 @@ class TestVyOSUtil(TestCase):
def test_sysctl_read(self):
self.assertEqual(sysctl_read('net.ipv4.conf.lo.forwarding'), '1')
+
+ def test_camel_to_snake_case(self):
+ self.assertEqual(camel_to_snake_case('ConnectionTimeout'),
+ 'connection_timeout')
+ self.assertEqual(camel_to_snake_case('connectionTimeout'),
+ 'connection_timeout')
+ self.assertEqual(camel_to_snake_case('TCPConnectionTimeout'),
+ 'tcp_connection_timeout')
+ self.assertEqual(camel_to_snake_case('TCPPort'),
+ 'tcp_port')
+ self.assertEqual(camel_to_snake_case('UseHTTPProxy'),
+ 'use_http_proxy')
+ self.assertEqual(camel_to_snake_case('CustomerID'),
+ 'customer_id')