filter2.py 1.91 KB
Newer Older
1
#!/usr/bin/env python
2
# -*- coding: utf8 -*-
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
"""Plus rapide"""

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 prioritize(l):
	if not isinstance(l, list):
		return l
	l=simplify(l)
24
	for c in ['!=', '<', '>', '=', '&', '|']:
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
		i=0
		while i<len(l):
			if l[i] == c:
				tmp=[prioritize(l[i-1]), l[i], prioritize(l[i+1])]
				l[i-1]=tmp
				del(l[i+1])
				del(l[i])
				i-=1
			i+=1
	return simplify(l)
	
def collapse(l):
	"""retire les parentheses inutiles"""
	if not isinstance(l, list):
		return l
	if not isinstance(l[1], list):
		return [l[0], collapse(l[1]), collapse(l[2])]
	if l[0] == l[1][0]:
		return [l[0], collapse(l[1][1]), collapse(l[1][2]), collapse(l[2])]
	else:
		return [l[0], collapse(l[1]), collapse(l[2])]
		
		
def toldapfilter(l):
	if not isinstance(l, list):
		return l
	op=l[0]
	if op == "=":
		return "%s=%s" % (l[1], l[2])
54 55 56 57
	elif op == "<":
		return "!(%s>=%s)" % (l[1], l[2])
	elif op == ">":
		return "!(%s<=%s)" % (l[1], l[2])
58 59 60 61 62
	elif op == "!=":
		return "!(%s=%s)" % (l[1], l[2])
	return op + ''.join(['(%s)' % toldapfilter(i) for i in l[1:]])


63 64 65 66 67 68
# Import et definition de la grammaire de parsing de façon paresseuse
expr=None
def pypexpr():
    global expr
    if not expr:
        import pyparsing
69
        unicodePrintables = u''.join(unichr(c) for c in xrange(65536) if not unichr(c).isspace())
70 71
        txt = "".join(c for c in unicodePrintables if c not in '()&|<>!=')
        expr = pyparsing.nestedExpr("(", ")", pyparsing.Word(txt) | pyparsing.oneOf("& | < > != ="))
72
    return expr
73
	
74 75
def human_to_list(data):
    if data:
76
        return collapse(toprefix(prioritize(pypexpr().parseString("(%s)" % data).asList())))
77

78
def human_to_ldap(data):
79
	return u"(%s)" % toldapfilter(human_to_list(data))