Warn when multiple 'on_page_read_source' handlers are added (#3503)

This commit is contained in:
Oleh Prypin
2023-12-08 21:42:42 +01:00
committed by GitHub
parent ccf011db79
commit ebaefd7451
2 changed files with 28 additions and 6 deletions

View File

@@ -506,9 +506,15 @@ class PluginCollection(dict, MutableMapping[str, BasePlugin]):
for sub in method.methods:
self._register_event(event_name, sub, plugin_name=plugin_name)
else:
utils.insort(
self.events[event_name], method, key=lambda m: -getattr(m, 'mkdocs_priority', 0)
)
events = self.events[event_name]
if event_name == 'page_read_source' and len(events) == 1:
plugin1 = self._event_origins.get(next(iter(events)), '<unknown>')
plugin2 = plugin_name or '<unknown>'
log.warning(
"Multiple 'on_page_read_source' handlers can't work "
f"(both plugins '{plugin1}' and '{plugin2}' registered one)."
)
utils.insort(events, method, key=lambda m: -getattr(m, 'mkdocs_priority', 0))
if plugin_name:
try:
self._event_origins[method] = plugin_name

View File

@@ -159,7 +159,13 @@ class TestPluginCollection(unittest.TestCase):
collection = plugins.PluginCollection()
collection['dummy'] = dummy = DummyPlugin()
collection['prio'] = prio = PrioPlugin()
with self.assertLogs('mkdocs', level='WARNING') as cm:
collection['prio'] = prio = PrioPlugin()
self.assertEqual(
'\n'.join(cm.output),
"WARNING:mkdocs.plugins:Multiple 'on_page_read_source' handlers can't work (both plugins 'dummy' and 'prio' registered one).",
)
self.assertEqual(
collection.events['page_content'],
[prio.on_page_content, dummy.on_page_content],
@@ -188,7 +194,12 @@ class TestPluginCollection(unittest.TestCase):
plugin1 = DummyPlugin()
collection['foo'] = plugin1
plugin2 = DummyPlugin()
collection['bar'] = plugin2
with self.assertLogs('mkdocs', level='WARNING') as cm:
collection['bar'] = plugin2
self.assertEqual(
'\n'.join(cm.output),
"WARNING:mkdocs.plugins:Multiple 'on_page_read_source' handlers can't work (both plugins 'foo' and 'bar' registered one).",
)
self.assertEqual(list(collection.items()), [('foo', plugin1), ('bar', plugin2)])
def test_run_event_on_collection(self):
@@ -208,7 +219,12 @@ class TestPluginCollection(unittest.TestCase):
collection['foo'] = plugin1
plugin2 = DummyPlugin()
plugin2.load_config({'foo': 'second'})
collection['bar'] = plugin2
with self.assertLogs('mkdocs', level='WARNING') as cm:
collection['bar'] = plugin2
self.assertEqual(
'\n'.join(cm.output),
"WARNING:mkdocs.plugins:Multiple 'on_page_read_source' handlers can't work (both plugins 'foo' and 'bar' registered one).",
)
self.assertEqual(
collection.on_page_content('page content', page=None, config={}, files=[]),
'second new page content',