
Pour ça on est obligé (si on utilise pyparsing) de générer la liste de tous les charactère unicode. Daniel fait remarquer que ça n'est pas joli d'instancier une chaine de 63Ko quand on veux parser quelque chose. On ne le fait tout de même que de façon paresseuse la première fois que l'on a besoin de parser quelquechose (dans filter2, filter3 est juste un proof of concept). Pour faire du human_to_ldap, on peut utiliser directement la fonction de filter.py qui n'est pas impacté par le problème, mais pour ressucite, on a pour le moment pas le choix puisqu'on utilise la fonction human_to_list qui n'est fournie que dans les modules filter2 et filter3.
53 lines
1.2 KiB
Python
53 lines
1.2 KiB
Python
#!/usr/bin/env python
|
|
"""Plus joli"""
|
|
|
|
import pyparsing
|
|
unicodePrintables = u''.join(unichr(c) for c in xrange(65536) if not unichr(c).isspace())
|
|
|
|
txt = pyparsing.Word("".join(c for c in unicodePrintables if c not in '=()|&'),exact=1)
|
|
|
|
ne = pyparsing.Literal('!=')
|
|
eq = pyparsing.Literal('=')
|
|
andop = pyparsing.oneOf('&')
|
|
orop = pyparsing.oneOf('|')
|
|
|
|
expr = pyparsing.operatorPrecedence( txt,
|
|
[
|
|
(ne, 2, pyparsing.opAssoc.RIGHT),
|
|
(eq, 2, pyparsing.opAssoc.RIGHT),
|
|
(andop, 2, pyparsing.opAssoc.LEFT),
|
|
(orop, 2, pyparsing.opAssoc.LEFT),]
|
|
)
|
|
|
|
def simplify(l):
|
|
if not isinstance(l, list):
|
|
return l
|
|
if len(l) == 1:
|
|
return simplify(l[0])
|
|
else:
|
|
return [simplify(i) for i in l]
|
|
|
|
def toprefix(l):
|
|
if not isinstance(l, list):
|
|
return l
|
|
op=l[1]
|
|
args=[toprefix(i) for i in l if i!=op]
|
|
return [op]+args
|
|
|
|
def toldapfilter(l):
|
|
if not isinstance(l, list):
|
|
return l
|
|
op=l[0]
|
|
if op == "=":
|
|
return "%s=%s" % (l[1], l[2])
|
|
elif op == "!=":
|
|
return "!(%s=%s)" % (l[1], l[2])
|
|
return op + ''.join(['(%s)' % toldapfilter(i) for i in l[1:]])
|
|
|
|
def human_to_list(data):
|
|
if data:
|
|
return toprefix(simplify(expr.parseString(data).asList()))
|
|
|
|
def human_to_ldap(data):
|
|
return "(%s)" % toldapfilter(human_to_list(data))
|
|
|