profiling: improve 3.12 error message for calling lsprof twice
Python 3.12 prevent lsprof to be enabled if it is already enabled. This break
the use of lsprof in `hg serve` as both the initial `serve` command and the
request serving want to profile.
The "stat" profiler (the default) does not have this problem, so we focus on
improving the error message for now.
--- a/mercurial/profiling.py Wed Sep 11 00:41:37 2024 +0200
+++ b/mercurial/profiling.py Wed Sep 11 12:02:38 2024 +0200
@@ -7,6 +7,7 @@
import contextlib
+import sys
from .i18n import _
from .pycompat import (
@@ -54,7 +55,23 @@
)
)
p = lsprof.Profiler()
- p.enable(subcalls=True)
+ try:
+ p.enable(subcalls=True)
+ except ValueError as exc:
+ if str(exc) != "Another profiling tool is already active":
+ raise
+ if not hasattr(sys, "monitoring"):
+ raise
+ # python >=3.12 prevent more than one profiler to run at the same
+ # time, tries to improve the report to help the user understand
+ # what is going on.
+ other_tool_name = sys.monitoring.get_tool(sys.monitoring.PROFILER_ID)
+ if other_tool_name == "cProfile":
+ msg = 'cannot recursively call `lsprof`'
+ raise error.Abort(msg) from None
+ else:
+ m = 'failed to start "lsprofile"; another profiler already running: %s'
+ raise error.Abort(_(m) % other_tool_name) from None
try:
yield
finally: