From 27b5b9de6af2282c49736c72f07e1ba09b0cd471 Mon Sep 17 00:00:00 2001 From: nvbn Date: Wed, 8 Jul 2015 21:33:30 +0300 Subject: [PATCH] #229 Use closest git command --- tests/rules/test_git_not_command.py | 19 ++++++++++++++++--- thefuck/rules/git_not_command.py | 15 +++++++++++++-- 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/tests/rules/test_git_not_command.py b/tests/rules/test_git_not_command.py index d93d1330..76f5817b 100644 --- a/tests/rules/test_git_not_command.py +++ b/tests/rules/test_git_not_command.py @@ -25,6 +25,16 @@ stats """ +@pytest.fixture +def git_not_command_closest(): + return '''git: 'tags' is not a git command. See 'git --help'. + +Did you mean one of these? + stage + tag +''' + + @pytest.fixture def git_command(): return "* master" @@ -37,8 +47,11 @@ def test_match(git_not_command, git_command, git_not_command_one_of_this): assert not match(Command('git branch', stderr=git_command), None) -def test_get_new_command(git_not_command, git_not_command_one_of_this): - assert get_new_command(Command('git brnch', stderr=git_not_command), None)\ - == 'git branch' +def test_get_new_command(git_not_command, git_not_command_one_of_this, + git_not_command_closest): + assert get_new_command(Command('git brnch', stderr=git_not_command), None) \ + == 'git branch' assert get_new_command(Command('git st', stderr=git_not_command_one_of_this), None) == 'git status' + assert get_new_command(Command('git tags', stderr=git_not_command_closest), + None) == 'git tag' diff --git a/thefuck/rules/git_not_command.py b/thefuck/rules/git_not_command.py index 4e9790b6..f851f10e 100644 --- a/thefuck/rules/git_not_command.py +++ b/thefuck/rules/git_not_command.py @@ -1,4 +1,6 @@ +from difflib import get_close_matches import re +from thefuck.utils import get_closest def match(command, settings): @@ -7,10 +9,19 @@ def match(command, settings): and 'Did you mean' in command.stderr) +def _get_all_git_matched_commands(stderr): + should_yield = False + for line in stderr.split('\n'): + if 'Did you mean' in line: + should_yield = True + elif should_yield and line: + yield line.strip() + + def get_new_command(command, settings): broken_cmd = re.findall(r"git: '([^']*)' is not a git command", command.stderr)[0] - new_cmd = re.findall(r'Did you mean[^\n]*\n\s*([^\n]*)', - command.stderr)[0] + new_cmd = get_closest(broken_cmd, + _get_all_git_matched_commands(command.stderr)) return command.script.replace(broken_cmd, new_cmd, 1)