From a8b6698849995c5d15ec499b95ba85c2a2e71a94 Mon Sep 17 00:00:00 2001 From: Valentin Lorentz Date: Sat, 23 Nov 2019 18:48:58 +0100 Subject: [PATCH] Add config supybot.reply.format.list.maximumItems to limit the size of format('%L', ...). --- src/conf.py | 23 +++++++++++++++++++++++ test/test_utils.py | 13 +++++++++++++ 2 files changed, 36 insertions(+) diff --git a/src/conf.py b/src/conf.py index a1dae0736..720725f9b 100644 --- a/src/conf.py +++ b/src/conf.py @@ -481,6 +481,29 @@ def timeElapsed(*args, **kwargs): return originalTimeElapsed(*args, **kwargs) utils.timeElapsed = timeElapsed +registerGroup(supybot.reply.format, 'list') +registerChannelValue(supybot.reply.format.list, 'maximumItems', + registry.NonNegativeInteger(0, _("""Maximum number of items in a list + before the end is replaced with 'and others'. Set to 0 to always + show the entire list."""))) + +originalCommaAndify = utils.str.commaAndify +def commaAndify(seq, *args, **kwargs): + maximum_items = supybot.reply.format.list.maximumItems.getSpecific( + channel=dynamic.channel, + network=getattr(dynamic.irc, 'network', None))() + if maximum_items: + seq = list(seq) + initial_length = len(seq) + if len(seq) > maximum_items: + seq = seq[:maximum_items] + nb_skipped = initial_length - maximum_items + 1 + # Even though nb_skipped is always >= 2, some languages require + # nItems for proper pluralization. + seq[-1] = utils.str.nItems(nb_skipped, _('other')) + return originalCommaAndify(seq, *args, **kwargs) +utils.str.commaAndify = commaAndify + registerGlobalValue(supybot.reply, 'maximumLength', registry.Integer(512*256, _("""Determines the absolute maximum length of the bot's reply -- no reply will be passed through the bot with a length diff --git a/test/test_utils.py b/test/test_utils.py index 1d511723d..86908163e 100644 --- a/test/test_utils.py +++ b/test/test_utils.py @@ -33,6 +33,7 @@ from supybot.test import * import sys import time import pickle +import supybot.conf as conf import supybot.utils as utils from supybot.utils.structures import * import supybot.utils.minisix as minisix @@ -357,6 +358,18 @@ class StrTest(SupyTestCase): L.append((3,)) self.assertRaises(TypeError, utils.str.commaAndify, L) + def testCommaAndifyConfig(self): + f = utils.str.commaAndify + L = ['foo', 'bar'] + with conf.supybot.reply.format.list.maximumItems.context(3): + self.assertEqual(f(L), 'foo and bar') + L.append('baz') + self.assertEqual(f(L), 'foo, bar, and baz') + L.append('qux') + self.assertEqual(f(L), 'foo, bar, and 2 others') + L.append('quux') + self.assertEqual(f(L), 'foo, bar, and 3 others') + def testUnCommaThe(self): f = utils.str.unCommaThe self.assertEqual(f('foo bar'), 'foo bar')