[Cubicweb] [PATCH] Syntax error on newly created cube

Victor ADAM victor.adam at derpymail.org
Sun Nov 16 19:49:25 CET 2014

When creating a new cube, user input is not properly escaped. This can
end up generating syntactically invalid Python files. For example, if
the user-provided description is “corsaire de l'espace”, the generated
__pkginfo__.py will contain:
description = 'corsaire de l'espace'
which is a syntax error because of the stray single quote.

One solution to this problem would be to use %r instead of '%s' inside
all .py.tmpl files. Another solution (the one I implemented) is to alter
fill_templated_file to escape all strings before filling a Python file.
Note that the .spec and README files do not require this escaping.

Here is the patch:

--- toolsutils.py.bak   2014-11-16 18:41:04.195187889 +0100
+++ toolsutils.py       2014-11-16 19:29:36.108499718 +0100
@@ -149,9 +149,17 @@
                 shutil.copyfile(fpath, tfpath)

+def escape(string):
+    """add backslashes to the given string, making it suitable for embedding
+    inside Python simgle quotes.
+    """
+    return re.sub(r"(?=[\\'])", r"\\", string)
 def fill_templated_file(fpath, tfpath, context):
     fobj = file(tfpath, 'w')
     templated = file(fpath).read()
+    if tfpath.endswith('.py'):
+        context = dict(zip(context.keys(), map(escape,  context.values())))
     fobj.write(templated % context)

More information about the Cubicweb mailing list