From 9f4eaf4234e6a7074fca72a3a9229d75035daac8 Mon Sep 17 00:00:00 2001 From: Tomas Gavenciak Date: Tue, 23 Nov 2010 20:12:06 +0100 Subject: [PATCH] Added function config_escape For safe constructon configuration commands as strings, tested, documented. --- t/doc/config.rst | 9 ++++++++- t/moe/config_parser.py | 10 ++++++++++ t/moe/config_test.py | 4 ++++ 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/t/doc/config.rst b/t/doc/config.rst index 3216a46..87e825e 100644 --- a/t/doc/config.rst +++ b/t/doc/config.rst @@ -7,6 +7,7 @@ Moe configuration ================= .. contents:: + :local: ------------------- Configuration logic @@ -184,6 +185,8 @@ nested inside another. In this case the parent condition is checked first and th Internals ^^^^^^^^^ +These classes should not be used directly. + .. autoclass:: ConfigElem :members: @@ -192,7 +195,11 @@ Internals ---------------------------------------- -Config parser module `moe.config_parser` +Configuration parser ---------------------------------------- .. automodule:: moe.config_parser + +.. autoclass:: ConfigSyntaxError + +.. autofunction:: config_escape diff --git a/t/moe/config_parser.py b/t/moe/config_parser.py index b3131cc..838d76b 100644 --- a/t/moe/config_parser.py +++ b/t/moe/config_parser.py @@ -47,6 +47,16 @@ import traceback import moe.config as cf +def config_escape(s): + """ + Escape any ``{``, ``}``, ``"`` and ``\\`` in the given string, making it safe for parsing. + """ + s = s.replace('\\', '\\\\') + s = s.replace('{', '\\{') + s = s.replace('}', '\\}') + s = s.replace('"', '\\"') + return s + class ConfigSyntaxError(cf.ConfigError): def __init__(self, msg, source='', line=None, column=None): diff --git a/t/moe/config_test.py b/t/moe/config_test.py index f1c836d..d6eb51b 100644 --- a/t/moe/config_test.py +++ b/t/moe/config_test.py @@ -106,6 +106,10 @@ class TestParser(TestConfig): for v in 'abcd': assert len(s.var(v).operations) == 0 + def test_escape(s): + for tst in ['{B}"#\n\\"', '', '\\\n\\\\"\\{\\}', '"#"', s.s1, s.s2]: + s.parse('A="%s"; A+="0"'%config_escape(tst)) + assert s.val('A') == tst+'0' class TestConfigEval(TestConfig): -- 2.39.2