perf: cache suggested commands (#4497)

Calls to `suggest_commands` would result in repeated calls to
the Levenshtein distance routine, which whilst optimally
implemented is still expensive. The change proposes to cache the
result instead.
This commit is contained in:
Gabriele N. Tornetta 2021-10-07 16:22:51 +01:00 committed by GitHub
parent 18261c3ace
commit 096926d6c8
Failed to generate hash of commit
3 changed files with 27 additions and 3 deletions

View file

@ -0,0 +1,23 @@
**Added:**
* <news item>
**Changed:**
* Suggested commands are cached for better performance.
**Deprecated:**
* <news item>
**Removed:**
* <news item>
**Fixed:**
* <news item>
**Security:**
* <news item>

View file

@ -488,9 +488,9 @@ class SubprocSpec:
)
e = "xonsh: subprocess mode: command not found: {0}".format(cmd0)
env = XSH.env
sug = xt.suggest_commands(cmd0, env, XSH.aliases)
sug = xt.suggest_commands(cmd0, env)
if len(sug.strip()) > 0:
e += "\n" + xt.suggest_commands(cmd0, env, XSH.aliases)
e += "\n" + xt.suggest_commands(cmd0, env)
raise xt.XonshError(e)
return p

View file

@ -884,7 +884,8 @@ def command_not_found(cmd, env):
return rtn
def suggest_commands(cmd, env, aliases):
@functools.lru_cache()
def suggest_commands(cmd, env):
"""Suggests alternative commands given an environment and aliases."""
if not env.get("SUGGEST_COMMANDS"):
return ""