Fixed bugs in option parsing.

This commit is contained in:
Jeremy Fincher 2003-11-14 15:49:13 +00:00
parent 7a9482a176
commit d4e5047ebf
2 changed files with 15 additions and 47 deletions

View File

@ -80,6 +80,11 @@ class OptionList(object):
return '(%s' % ''.join(ret) #)
elif token == ')':
if len(ret) > 1:
if '|' in ret:
L = map(''.join,utils.itersplit(lambda x: x=='|', ret))
return random.choice(L)
else:
return ''.join(ret)
return [x for x in ret if x != '|']
elif len(ret) == 1:
return '(%s)' % ret[0]
@ -105,35 +110,13 @@ class OptionList(object):
break
elif token == '(':
ret.append(self._insideParens(lexer))
elif token == ')':
if ret: #(
ret[-1] += ')'
else: #(
ret.append(')')
elif token == '|':
ret.append(token)
else:
if ret and ret[-1] == '|':
pipe = ret.pop()
first = ret.pop()
ret.append(pipe.join([first, token]))
else:
ret.append(token)
return ret
return ''.join(ret)
def tokenize(s):
def pickOptions(s):
return OptionList().tokenize(s)
def pick(L, recursed=False):
L = L[:]
for (i, elt) in enumerate(L):
if isinstance(elt, list):
L[i] = pick(elt, recursed=True)
if recursed:
return random.choice(L)
else:
return L
class MoobotFactoids(callbacks.PrivmsgCommandAndRegexp):
priority = 98
addressedRegexps = ['changeFactoid', 'augmentFactoid',
@ -173,7 +156,7 @@ class MoobotFactoids(callbacks.PrivmsgCommandAndRegexp):
def parseFactoid(self, irc, msg, fact):
type = "define" # Default is to just spit the factoid back as a
# definition of what the key is (i.e., "foo is bar")
newfact = ''.join(pick(tokenize(fact)))
newfact = pickOptions(fact)
if newfact.startswith("<reply>"):
newfact = newfact.replace("<reply>", "", 1)
newfact = newfact.strip()

View File

@ -40,27 +40,12 @@ if sqlite is not None:
MoobotFactoids = Owner.loadPluginModule('MoobotFactoids')
MF = MoobotFactoids
class OptionListTestCase(unittest.TestCase):
def testEmptyParens(self):
self.assertEqual(MF.tokenize('()'), ['()'])
def testNoBarParens(self):
self.assertEqual(MF.tokenize('(foo)'), ['(foo)'])
def testDanglingParens(self):
self.assertEqual(MF.tokenize('(foo'), ['(foo'])
self.assertEqual(MF.tokenize('(foo|bar'),['(foo|bar'])
self.assertEqual(MF.tokenize('foo)'), ['foo)'])
self.assertEqual(MF.tokenize('foo|bar)'),['foo|bar)'])
def testPipesOutsideParens(self):
self.assertEqual(MF.tokenize('1|2'), ['1|2'])
def testStandardBehavior(self):
self.assertEqual(MF.tokenize('(foo|bar)'), [['foo', 'bar']])
self.assertEqual(MF.tokenize('(foo|bar|baz)'),
[['foo','bar','baz']])
self.assertEqual(MF.tokenize('(foo|(bar|baz))'),
[['foo', ['bar', 'baz']]])
def testPickOptions(self):
for i in xrange(10):
self.failUnless(MF.pickOptions('(a|b)') in ['a', 'b'])
self.failUnless(MF.pickOptions('a') == 'a')
self.failUnless(MF.pickOptions('(a|b (c|d))') in
['a', 'b c', 'b d'])
class FactoidsTestCase(PluginTestCase, PluginDocumentation):
plugins = ('MoobotFactoids', 'User', 'Utilities')