repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_long_form_help.py
tests/rules/test_long_form_help.py
import pytest from thefuck.rules.long_form_help import match, get_new_command from thefuck.types import Command @pytest.mark.parametrize('output', [ 'Try \'grep --help\' for more information.']) def test_match(output): assert match(Command('grep -h', output)) def test_not_match(): assert not match(Command('', '')) @pytest.mark.parametrize('before, after', [ ('grep -h', 'grep --help'), ('tar -h', 'tar --help'), ('docker run -h', 'docker run --help'), ('cut -h', 'cut --help')]) def test_get_new_command(before, after): assert get_new_command(Command(before, '')) == after
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_git_push_different_branch_names.py
tests/rules/test_git_push_different_branch_names.py
import pytest from thefuck.rules.git_push_different_branch_names import get_new_command, match from thefuck.types import Command output = """fatal: The upstream branch of your current branch does not match the name of your current branch. To push to the upstream branch on the remote, use git push origin HEAD:%s To push to the branch of the same name on the remote, use git push origin %s To choose either option permanently, see push.default in 'git help config'. """ def error_msg(localbranch, remotebranch): return output % (remotebranch, localbranch) def test_match(): assert match(Command('git push', error_msg('foo', 'bar'))) @pytest.mark.parametrize('command', [ Command('vim', ''), Command('git status', error_msg('foo', 'bar')), Command('git push', '') ]) def test_not_match(command): assert not match(command) def test_get_new_command(): new_command = get_new_command(Command('git push', error_msg('foo', 'bar'))) assert new_command == 'git push origin HEAD:bar'
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/__init__.py
tests/rules/__init__.py
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_git_branch_delete.py
tests/rules/test_git_branch_delete.py
import pytest from thefuck.rules.git_branch_delete import match, get_new_command from thefuck.types import Command @pytest.fixture def output(): return '''error: The branch 'branch' is not fully merged. If you are sure you want to delete it, run 'git branch -D branch'. ''' def test_match(output): assert match(Command('git branch -d branch', output)) assert not match(Command('git branch -d branch', '')) assert not match(Command('ls', output)) def test_get_new_command(output): assert get_new_command(Command('git branch -d branch', output))\ == "git branch -D branch"
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_cat_dir.py
tests/rules/test_cat_dir.py
import pytest from thefuck.rules.cat_dir import match, get_new_command from thefuck.types import Command @pytest.fixture def isdir(mocker): return mocker.patch('thefuck.rules.cat_dir' '.os.path.isdir') @pytest.mark.parametrize('command', [ Command('cat foo', 'cat: foo: Is a directory\n'), Command('cat /foo/bar/', 'cat: /foo/bar/: Is a directory\n'), Command('cat cat/', 'cat: cat/: Is a directory\n'), ]) def test_match(command, isdir): isdir.return_value = True assert match(command) @pytest.mark.parametrize('command', [ Command('cat foo', 'foo bar baz'), Command('cat foo bar', 'foo bar baz'), Command('notcat foo bar', 'some output'), ]) def test_not_match(command, isdir): isdir.return_value = False assert not match(command) @pytest.mark.parametrize('command, new_command', [ (Command('cat foo', 'cat: foo: Is a directory\n'), 'ls foo'), (Command('cat /foo/bar/', 'cat: /foo/bar/: Is a directory\n'), 'ls /foo/bar/'), (Command('cat cat', 'cat: cat: Is a directory\n'), 'ls cat'), ]) def test_get_new_command(command, new_command): isdir.return_value = True assert get_new_command(command) == new_command
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_vagrant_up.py
tests/rules/test_vagrant_up.py
import pytest from thefuck.rules.vagrant_up import match, get_new_command from thefuck.types import Command @pytest.mark.parametrize('command', [ Command('vagrant ssh', 'VM must be running to open SSH connection. Run `vagrant up`\nto start the virtual machine.'), Command('vagrant ssh devbox', 'VM must be running to open SSH connection. Run `vagrant up`\nto start the virtual machine.'), Command('vagrant rdp', 'VM must be created before running this command. Run `vagrant up` first.'), Command('vagrant rdp devbox', 'VM must be created before running this command. Run `vagrant up` first.')]) def test_match(command): assert match(command) @pytest.mark.parametrize('command', [ Command('vagrant ssh', ''), Command('vagrant ssh jeff', 'The machine with the name \'jeff\' was not found configured for this Vagrant environment.'), Command('vagrant ssh', 'A Vagrant environment or target machine is required to run this command. Run `vagrant init` to create a new Vagrant environment. Or, get an ID of a target machine from `vagrant global-status` to run this command on. A final option is to change to a directory with a Vagrantfile and to try again.'), Command('', '')]) def test_not_match(command): assert not match(command) @pytest.mark.parametrize('command, new_command', [ (Command('vagrant ssh', 'VM must be running to open SSH connection. Run `vagrant up`\nto start the virtual machine.'), 'vagrant up && vagrant ssh'), (Command('vagrant ssh devbox', 'VM must be running to open SSH connection. Run `vagrant up`\nto start the virtual machine.'), ['vagrant up devbox && vagrant ssh devbox', 'vagrant up && vagrant ssh devbox']), (Command('vagrant rdp', 'VM must be created before running this command. Run `vagrant up` first.'), 'vagrant up && vagrant rdp'), (Command('vagrant rdp devbox', 'VM must be created before running this command. Run `vagrant up` first.'), ['vagrant up devbox && vagrant rdp devbox', 'vagrant up && vagrant rdp devbox'])]) def test_get_new_command(command, new_command): assert get_new_command(command) == new_command
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_git_commit_amend.py
tests/rules/test_git_commit_amend.py
import pytest from thefuck.rules.git_commit_amend import match, get_new_command from thefuck.types import Command @pytest.mark.parametrize('script, output', [ ('git commit -m "test"', 'test output'), ('git commit', '')]) def test_match(output, script): assert match(Command(script, output)) @pytest.mark.parametrize('script', [ 'git branch foo', 'git checkout feature/test_commit', 'git push']) def test_not_match(script): assert not match(Command(script, '')) @pytest.mark.parametrize('script', [ ('git commit -m "test commit"'), ('git commit')]) def test_get_new_command(script): assert get_new_command(Command(script, '')) == 'git commit --amend'
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_chmod_x.py
tests/rules/test_chmod_x.py
import pytest from thefuck.types import Command from thefuck.rules.chmod_x import match, get_new_command @pytest.fixture def file_exists(mocker): return mocker.patch('os.path.exists', return_value=True) @pytest.fixture def file_access(mocker): return mocker.patch('os.access', return_value=False) @pytest.mark.usefixtures('file_exists', 'file_access') @pytest.mark.parametrize('script, output', [ ('./gradlew build', 'gradlew: Permission denied'), ('./install.sh --help', 'install.sh: permission denied')]) def test_match(script, output): assert match(Command(script, output)) @pytest.mark.parametrize('script, output, exists, callable', [ ('./gradlew build', 'gradlew: Permission denied', True, True), ('./gradlew build', 'gradlew: Permission denied', False, False), ('./gradlew build', 'gradlew: error', True, False), ('gradlew build', 'gradlew: Permission denied', True, False)]) def test_not_match(file_exists, file_access, script, output, exists, callable): file_exists.return_value = exists file_access.return_value = callable assert not match(Command(script, output)) @pytest.mark.parametrize('script, result', [ ('./gradlew build', 'chmod +x gradlew && ./gradlew build'), ('./install.sh --help', 'chmod +x install.sh && ./install.sh --help')]) def test_get_new_command(script, result): assert get_new_command(Command(script, '')) == result
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_yarn_command_replaced.py
tests/rules/test_yarn_command_replaced.py
import pytest from thefuck.types import Command from thefuck.rules.yarn_command_replaced import match, get_new_command output = ('error `install` has been replaced with `add` to add new ' 'dependencies. Run "yarn add {}" instead.').format @pytest.mark.parametrize('command', [ Command('yarn install redux', output('redux')), Command('yarn install moment', output('moment')), Command('yarn install lodash', output('lodash'))]) def test_match(command): assert match(command) @pytest.mark.parametrize('command', [ Command('yarn install', '')]) def test_not_match(command): assert not match(command) @pytest.mark.parametrize('command, new_command', [ (Command('yarn install redux', output('redux')), 'yarn add redux'), (Command('yarn install moment', output('moment')), 'yarn add moment'), (Command('yarn install lodash', output('lodash')), 'yarn add lodash')]) def test_get_new_command(command, new_command): assert get_new_command(command) == new_command
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_gulp_not_task.py
tests/rules/test_gulp_not_task.py
import pytest from io import BytesIO from thefuck.types import Command from thefuck.rules.gulp_not_task import match, get_new_command def output(task): return '''[00:41:11] Using gulpfile gulpfile.js [00:41:11] Task '{}' is not in your gulpfile [00:41:11] Please check the documentation for proper gulpfile formatting '''.format(task) def test_match(): assert match(Command('gulp srve', output('srve'))) @pytest.mark.parametrize('script, stdout', [ ('gulp serve', ''), ('cat srve', output('srve'))]) def test_not_march(script, stdout): assert not match(Command(script, stdout)) def test_get_new_command(mocker): mock = mocker.patch('subprocess.Popen') mock.return_value.stdout = BytesIO(b'serve \nbuild \ndefault \n') command = Command('gulp srve', output('srve')) assert get_new_command(command) == ['gulp serve', 'gulp default']
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_javac.py
tests/rules/test_javac.py
import pytest from thefuck.rules.javac import match, get_new_command from thefuck.types import Command @pytest.mark.parametrize('command', [ Command('javac foo', ''), Command('javac bar', '')]) def test_match(command): assert match(command) @pytest.mark.parametrize('command, new_command', [ (Command('javac foo', ''), 'javac foo.java'), (Command('javac bar', ''), 'javac bar.java')]) def test_get_new_command(command, new_command): assert get_new_command(command) == new_command
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_python_module_error.py
tests/rules/test_python_module_error.py
import pytest from thefuck.rules.python_module_error import get_new_command, match from thefuck.types import Command @pytest.fixture def module_error_output(filename, module_name): return """Traceback (most recent call last): File "{0}", line 1, in <module> import {1} ModuleNotFoundError: No module named '{1}'""".format( filename, module_name ) @pytest.mark.parametrize( "test", [ Command("python hello_world.py", "Hello World"), Command( "./hello_world.py", """Traceback (most recent call last): File "hello_world.py", line 1, in <module> pritn("Hello World") NameError: name 'pritn' is not defined""", ), ], ) def test_not_match(test): assert not match(test) positive_tests = [ ( "python some_script.py", "some_script.py", "more_itertools", "pip install more_itertools && python some_script.py", ), ( "./some_other_script.py", "some_other_script.py", "a_module", "pip install a_module && ./some_other_script.py", ), ] @pytest.mark.parametrize( "script, filename, module_name, corrected_script", positive_tests ) def test_match(script, filename, module_name, corrected_script, module_error_output): assert match(Command(script, module_error_output)) @pytest.mark.parametrize( "script, filename, module_name, corrected_script", positive_tests ) def test_get_new_command( script, filename, module_name, corrected_script, module_error_output ): assert get_new_command(Command(script, module_error_output)) == corrected_script
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_apt_upgrade.py
tests/rules/test_apt_upgrade.py
import pytest from thefuck.rules.apt_upgrade import get_new_command, match from thefuck.types import Command match_output = ''' Listing... Done heroku/stable 6.15.2-1 amd64 [upgradable from: 6.14.43-1] resolvconf/zesty-updates,zesty-updates 1.79ubuntu4.1 all [upgradable from: 1.79ubuntu4] squashfs-tools/zesty-updates 1:4.3-3ubuntu2.17.04.1 amd64 [upgradable from: 1:4.3-3ubuntu2] unattended-upgrades/zesty-updates,zesty-updates 0.93.1ubuntu2.4 all [upgradable from: 0.93.1ubuntu2.3] ''' no_match_output = ''' Listing... Done ''' def test_match(): assert match(Command('apt list --upgradable', match_output)) assert match(Command('sudo apt list --upgradable', match_output)) @pytest.mark.parametrize('command', [ Command('apt list --upgradable', no_match_output), Command('sudo apt list --upgradable', no_match_output) ]) def test_not_match(command): assert not match(command) def test_get_new_command(): new_command = get_new_command(Command('apt list --upgradable', match_output)) assert new_command == 'apt upgrade' new_command = get_new_command(Command('sudo apt list --upgradable', match_output)) assert new_command == 'sudo apt upgrade'
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_terraform_init.py
tests/rules/test_terraform_init.py
import pytest from thefuck.rules.terraform_init import match, get_new_command from thefuck.types import Command @pytest.mark.parametrize('script, output', [ ('terraform plan', 'Error: Initialization required. ' 'Please see the error message above.'), ('terraform plan', 'This module is not yet installed. Run "terraform init" ' 'to install all modules required by this configuration.'), ('terraform apply', 'Error: Initialization required. ' 'Please see the error message above.'), ('terraform apply', 'This module is not yet installed. Run "terraform init" ' 'to install all modules required by this configuration.')]) def test_match(script, output): assert match(Command(script, output)) @pytest.mark.parametrize('script, output', [ ('terraform --version', 'Terraform v0.12.2'), ('terraform plan', 'No changes. Infrastructure is up-to-date.'), ('terraform apply', 'Apply complete! Resources: 0 added, 0 changed, 0 destroyed.'), ]) def test_not_match(script, output): assert not match(Command(script, output=output)) @pytest.mark.parametrize('command, new_command', [ (Command('terraform plan', ''), 'terraform init && terraform plan'), (Command('terraform apply', ''), 'terraform init && terraform apply'), ]) def test_get_new_command(command, new_command): assert get_new_command(command) == new_command
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_git_rm_staged.py
tests/rules/test_git_rm_staged.py
import pytest from thefuck.rules.git_rm_staged import match, get_new_command from thefuck.types import Command @pytest.fixture def output(target): return ('error: the following file has changes staged in the index:\n {}\n(use ' '--cached to keep the file, or -f to force removal)').format(target) @pytest.mark.parametrize('script, target', [ ('git rm foo', 'foo'), ('git rm foo bar', 'bar')]) def test_match(output, script, target): assert match(Command(script, output)) @pytest.mark.parametrize('script', ['git rm foo', 'git rm foo bar', 'git rm']) def test_not_match(script): assert not match(Command(script, '')) @pytest.mark.parametrize('script, target, new_command', [ ('git rm foo', 'foo', ['git rm --cached foo', 'git rm -f foo']), ('git rm foo bar', 'bar', ['git rm --cached foo bar', 'git rm -f foo bar'])]) def test_get_new_command(output, script, target, new_command): assert get_new_command(Command(script, output)) == new_command
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_path_from_history.py
tests/rules/test_path_from_history.py
import pytest from thefuck.rules.path_from_history import match, get_new_command from thefuck.types import Command @pytest.fixture(autouse=True) def history(mocker): return mocker.patch( 'thefuck.rules.path_from_history.get_valid_history_without_current', return_value=['cd /opt/java', 'ls ~/work/project/']) @pytest.fixture(autouse=True) def path_exists(mocker): path_mock = mocker.patch('thefuck.rules.path_from_history.Path') exists_mock = path_mock.return_value.expanduser.return_value.exists exists_mock.return_value = True return exists_mock @pytest.mark.parametrize('script, output', [ ('ls project', 'no such file or directory: project'), ('cd project', "can't cd to project"), ]) def test_match(script, output): assert match(Command(script, output)) @pytest.mark.parametrize('script, output', [ ('myapp cats', 'no such file or directory: project'), ('cd project', ""), ]) def test_not_match(script, output): assert not match(Command(script, output)) @pytest.mark.parametrize('script, output, result', [ ('ls project', 'no such file or directory: project', 'ls ~/work/project'), ('cd java', "can't cd to java", 'cd /opt/java'), ]) def test_get_new_command(script, output, result): new_command = get_new_command(Command(script, output)) assert new_command[0] == result
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_git_pull_clone.py
tests/rules/test_git_pull_clone.py
import pytest from thefuck.rules.git_pull_clone import match, get_new_command from thefuck.types import Command git_err = ''' fatal: Not a git repository (or any parent up to mount point /home) Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set). ''' @pytest.mark.parametrize('command', [ Command('git pull git@github.com:mcarton/thefuck.git', git_err)]) def test_match(command): assert match(command) @pytest.mark.parametrize('command, output', [ (Command('git pull git@github.com:mcarton/thefuck.git', git_err), 'git clone git@github.com:mcarton/thefuck.git')]) def test_get_new_command(command, output): assert get_new_command(command) == output
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_ag_literal.py
tests/rules/test_ag_literal.py
import pytest from thefuck.rules.ag_literal import get_new_command, match from thefuck.types import Command @pytest.fixture def output(): return ('ERR: Bad regex! pcre_compile() failed at position 1: missing )\n' 'If you meant to search for a literal string, run ag with -Q\n') @pytest.mark.parametrize('script', ['ag \\(']) def test_match(script, output): assert match(Command(script, output)) @pytest.mark.parametrize('script', ['ag foo']) def test_not_match(script): assert not match(Command(script, '')) @pytest.mark.parametrize('script, new_cmd', [ ('ag \\(', 'ag -Q \\(')]) def test_get_new_command(script, new_cmd, output): assert get_new_command((Command(script, output))) == new_cmd
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_pacman_not_found.py
tests/rules/test_pacman_not_found.py
import pytest from mock import patch from thefuck.rules import pacman_not_found from thefuck.rules.pacman_not_found import match, get_new_command from thefuck.types import Command PKGFILE_OUTPUT_LLC = '''extra/llvm 3.6.0-5 /usr/bin/llc extra/llvm35 3.5.2-13/usr/bin/llc''' @pytest.mark.skipif(not getattr(pacman_not_found, 'enabled_by_default', True), reason='Skip if pacman is not available') @pytest.mark.parametrize('command', [ Command('yay -S llc', 'error: target not found: llc'), Command('pikaur -S llc', 'error: target not found: llc'), Command('yaourt -S llc', 'error: target not found: llc'), Command('pacman llc', 'error: target not found: llc'), Command('sudo pacman llc', 'error: target not found: llc')]) def test_match(command): assert match(command) @pytest.mark.parametrize('command', [ Command('yay -S llc', 'error: target not found: llc'), Command('pikaur -S llc', 'error: target not found: llc'), Command('yaourt -S llc', 'error: target not found: llc'), Command('pacman llc', 'error: target not found: llc'), Command('sudo pacman llc', 'error: target not found: llc')]) @patch('thefuck.specific.archlinux.subprocess') def test_match_mocked(subp_mock, command): subp_mock.check_output.return_value = PKGFILE_OUTPUT_LLC assert match(command) @pytest.mark.skipif(not getattr(pacman_not_found, 'enabled_by_default', True), reason='Skip if pacman is not available') @pytest.mark.parametrize('command, fixed', [ (Command('yay -S llc', 'error: target not found: llc'), ['yay -S extra/llvm', 'yay -S extra/llvm35']), (Command('pikaur -S llc', 'error: target not found: llc'), ['pikaur -S extra/llvm', 'pikaur -S extra/llvm35']), (Command('yaourt -S llc', 'error: target not found: llc'), ['yaourt -S extra/llvm', 'yaourt -S extra/llvm35']), (Command('pacman -S llc', 'error: target not found: llc'), ['pacman -S extra/llvm', 'pacman -S extra/llvm35']), (Command('sudo pacman -S llc', 'error: target not found: llc'), ['sudo pacman -S extra/llvm', 'sudo pacman -S extra/llvm35'])]) def test_get_new_command(command, fixed): assert get_new_command(command) == fixed @pytest.mark.parametrize('command, fixed', [ (Command('yay -S llc', 'error: target not found: llc'), ['yay -S extra/llvm', 'yay -S extra/llvm35']), (Command('pikaur -S llc', 'error: target not found: llc'), ['pikaur -S extra/llvm', 'pikaur -S extra/llvm35']), (Command('yaourt -S llc', 'error: target not found: llc'), ['yaourt -S extra/llvm', 'yaourt -S extra/llvm35']), (Command('pacman -S llc', 'error: target not found: llc'), ['pacman -S extra/llvm', 'pacman -S extra/llvm35']), (Command('sudo pacman -S llc', 'error: target not found: llc'), ['sudo pacman -S extra/llvm', 'sudo pacman -S extra/llvm35'])]) @patch('thefuck.specific.archlinux.subprocess') def test_get_new_command_mocked(subp_mock, command, fixed): subp_mock.check_output.return_value = PKGFILE_OUTPUT_LLC assert get_new_command(command) == fixed
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_rails_migrations_pending.py
tests/rules/test_rails_migrations_pending.py
import pytest from thefuck.rules.rails_migrations_pending import match, get_new_command from thefuck.types import Command output_env_development = ''' Migrations are pending. To resolve this issue, run: rails db:migrate RAILS_ENV=development ''' output_env_test = ''' Migrations are pending. To resolve this issue, run: bin/rails db:migrate RAILS_ENV=test ''' @pytest.mark.parametrize( "command", [ Command("", output_env_development), Command("", output_env_test), ], ) def test_match(command): assert match(command) @pytest.mark.parametrize( "command", [ Command("Environment data not found in the schema. To resolve this issue, run: \n\n", ""), ], ) def test_not_match(command): assert not match(command) @pytest.mark.parametrize( "command, new_command", [ (Command("bin/rspec", output_env_development), "rails db:migrate RAILS_ENV=development && bin/rspec"), (Command("bin/rspec", output_env_test), "bin/rails db:migrate RAILS_ENV=test && bin/rspec"), ], ) def test_get_new_command(command, new_command): assert get_new_command(command) == new_command
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_git_branch_exists.py
tests/rules/test_git_branch_exists.py
import pytest from thefuck.rules.git_branch_exists import match, get_new_command from thefuck.types import Command @pytest.fixture def output(src_branch_name): return "fatal: A branch named '{}' already exists.".format(src_branch_name) @pytest.fixture def new_command(branch_name): return [cmd.format(branch_name) for cmd in [ 'git branch -d {0} && git branch {0}', 'git branch -d {0} && git checkout -b {0}', 'git branch -D {0} && git branch {0}', 'git branch -D {0} && git checkout -b {0}', 'git checkout {0}']] @pytest.mark.parametrize('script, src_branch_name, branch_name', [ ('git branch foo', 'foo', 'foo'), ('git checkout bar', 'bar', 'bar'), ('git checkout -b "let\'s-push-this"', '"let\'s-push-this"', '"let\'s-push-this"')]) def test_match(output, script, branch_name): assert match(Command(script, output)) @pytest.mark.parametrize('script', [ 'git branch foo', 'git checkout bar', 'git checkout -b "let\'s-push-this"']) def test_not_match(script): assert not match(Command(script, '')) @pytest.mark.parametrize('script, src_branch_name, branch_name', [ ('git branch foo', 'foo', 'foo'), ('git checkout bar', 'bar', 'bar'), ('git checkout -b "let\'s-push-this"', "let's-push-this", "let\\'s-push-this")]) def test_get_new_command(output, new_command, script, src_branch_name, branch_name): assert get_new_command(Command(script, output)) == new_command
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_git_lfs_mistype.py
tests/rules/test_git_lfs_mistype.py
import pytest from thefuck.rules.git_lfs_mistype import match, get_new_command from thefuck.types import Command @pytest.fixture def mistype_response(): return """ Error: unknown command "evn" for "git-lfs" Did you mean this? env ext Run 'git-lfs --help' for usage. """ def test_match(mistype_response): assert match(Command('git lfs evn', mistype_response)) err_response = 'bash: git: command not found' assert not match(Command('git lfs env', err_response)) assert not match(Command('docker lfs env', mistype_response)) def test_get_new_command(mistype_response): assert (get_new_command(Command('git lfs evn', mistype_response)) == ['git lfs env', 'git lfs ext'])
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_wrong_hyphen_before_subcommand.py
tests/rules/test_wrong_hyphen_before_subcommand.py
import pytest from thefuck.rules.wrong_hyphen_before_subcommand import match, get_new_command from thefuck.types import Command @pytest.fixture(autouse=True) def get_all_executables(mocker): mocker.patch( "thefuck.rules.wrong_hyphen_before_subcommand.get_all_executables", return_value=["git", "apt", "apt-get", "ls", "pwd"], ) @pytest.mark.parametrize("script", ["git-log", "apt-install python"]) def test_match(script): assert match(Command(script, "")) @pytest.mark.parametrize("script", ["ls -la", "git2-make", "apt-get install python"]) def test_not_match(script): assert not match(Command(script, "")) @pytest.mark.parametrize( "script, new_command", [("git-log", "git log"), ("apt-install python", "apt install python")], ) def test_get_new_command(script, new_command): assert get_new_command(Command(script, "")) == new_command
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_composer_not_command.py
tests/rules/test_composer_not_command.py
import pytest from thefuck.rules.composer_not_command import match, get_new_command from thefuck.types import Command @pytest.fixture def composer_not_command(): # that weird spacing is part of the actual command output return ( '\n' '\n' ' \n' ' [InvalidArgumentException] \n' ' Command "udpate" is not defined. \n' ' Did you mean this? \n' ' update \n' ' \n' '\n' '\n' ) @pytest.fixture def composer_not_command_one_of_this(): # that weird spacing is part of the actual command output return ( '\n' '\n' ' \n' ' [InvalidArgumentException] \n' ' Command "pdate" is not defined. \n' ' Did you mean one of these? \n' ' selfupdate \n' ' self-update \n' ' update \n' ' \n' '\n' '\n' ) @pytest.fixture def composer_require_instead_of_install(): return 'Invalid argument package. Use "composer require package" instead to add packages to your composer.json.' def test_match(composer_not_command, composer_not_command_one_of_this, composer_require_instead_of_install): assert match(Command('composer udpate', composer_not_command)) assert match(Command('composer pdate', composer_not_command_one_of_this)) assert match(Command('composer install package', composer_require_instead_of_install)) assert not match(Command('ls update', composer_not_command)) def test_get_new_command(composer_not_command, composer_not_command_one_of_this, composer_require_instead_of_install): assert (get_new_command(Command('composer udpate', composer_not_command)) == 'composer update') assert (get_new_command(Command('composer pdate', composer_not_command_one_of_this)) == 'composer selfupdate') assert (get_new_command(Command('composer install package', composer_require_instead_of_install)) == 'composer require package')
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_man_no_space.py
tests/rules/test_man_no_space.py
from thefuck.rules.man_no_space import match, get_new_command from thefuck.types import Command def test_match(): assert match(Command('mandiff', 'mandiff: command not found')) assert not match(Command('', '')) def test_get_new_command(): assert get_new_command(Command('mandiff', '')) == 'man diff'
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_git_diff_staged.py
tests/rules/test_git_diff_staged.py
import pytest from thefuck.rules.git_diff_staged import match, get_new_command from thefuck.types import Command @pytest.mark.parametrize('command', [ Command('git diff foo', ''), Command('git diff', '')]) def test_match(command): assert match(command) @pytest.mark.parametrize('command', [ Command('git diff --staged', ''), Command('git tag', ''), Command('git branch', ''), Command('git log', '')]) def test_not_match(command): assert not match(command) @pytest.mark.parametrize('command, new_command', [ (Command('git diff', ''), 'git diff --staged'), (Command('git diff foo', ''), 'git diff --staged foo')]) def test_get_new_command(command, new_command): assert get_new_command(command) == new_command
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_git_bisect_usage.py
tests/rules/test_git_bisect_usage.py
import pytest from thefuck.types import Command from thefuck.rules.git_bisect_usage import match, get_new_command @pytest.fixture def output(): return ("usage: git bisect [help|start|bad|good|new|old" "|terms|skip|next|reset|visualize|replay|log|run]") @pytest.mark.parametrize('script', [ 'git bisect strt', 'git bisect rset', 'git bisect goood']) def test_match(output, script): assert match(Command(script, output)) @pytest.mark.parametrize('script', [ 'git bisect', 'git bisect start', 'git bisect good']) def test_not_match(script): assert not match(Command(script, '')) @pytest.mark.parametrize('script, new_cmd, ', [ ('git bisect goood', ['good', 'old', 'log']), ('git bisect strt', ['start', 'terms', 'reset']), ('git bisect rset', ['reset', 'next', 'start'])]) def test_get_new_command(output, script, new_cmd): new_cmd = ['git bisect %s' % cmd for cmd in new_cmd] assert get_new_command(Command(script, output)) == new_cmd
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_mvn_unknown_lifecycle_phase.py
tests/rules/test_mvn_unknown_lifecycle_phase.py
import pytest from thefuck.rules.mvn_unknown_lifecycle_phase import match, get_new_command from thefuck.types import Command @pytest.mark.parametrize('command', [ Command('mvn cle', '[ERROR] Unknown lifecycle phase "cle". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal>. Available lifecycle phases are: validate, initialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, test-compile, process-test-classes, test, prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, install, deploy, pre-clean, clean, post-clean, pre-site, site, post-site, site-deploy. -> [Help 1]')]) def test_match(command): assert match(command) @pytest.mark.parametrize('command', [ Command('mvn clean', """ [INFO] Scanning for projects...[INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building test 0.2 [INFO] ------------------------------------------------------------------------ [INFO] [INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ test --- [INFO] Deleting /home/mlk/code/test/target [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 0.477s [INFO] Finished at: Wed Aug 26 13:05:47 BST 2015 [INFO] Final Memory: 6M/240M [INFO] ------------------------------------------------------------------------ """), # noqa Command('mvn --help', ''), Command('mvn -v', '') ]) def test_not_match(command): assert not match(command) @pytest.mark.parametrize('command, new_command', [ (Command('mvn cle', '[ERROR] Unknown lifecycle phase "cle". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal>. Available lifecycle phases are: validate, initialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, test-compile, process-test-classes, test, prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, install, deploy, pre-clean, clean, post-clean, pre-site, site, post-site, site-deploy. -> [Help 1]'), ['mvn clean', 'mvn compile']), (Command('mvn claen package', '[ERROR] Unknown lifecycle phase "claen". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal>. Available lifecycle phases are: validate, initialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, test-compile, process-test-classes, test, prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, install, deploy, pre-clean, clean, post-clean, pre-site, site, post-site, site-deploy. -> [Help 1]'), ['mvn clean package'])]) def test_get_new_command(command, new_command): assert get_new_command(command) == new_command
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_cp_omitting_directory.py
tests/rules/test_cp_omitting_directory.py
import pytest from thefuck.rules.cp_omitting_directory import match, get_new_command from thefuck.types import Command @pytest.mark.parametrize('script, output', [ ('cp dir', 'cp: dor: is a directory'), ('cp dir', "cp: omitting directory 'dir'")]) def test_match(script, output): assert match(Command(script, output)) @pytest.mark.parametrize('script, output', [ ('some dir', 'cp: dor: is a directory'), ('some dir', "cp: omitting directory 'dir'"), ('cp dir', '')]) def test_not_match(script, output): assert not match(Command(script, output)) def test_get_new_command(): assert get_new_command(Command('cp dir', '')) == 'cp -a dir'
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_history.py
tests/rules/test_history.py
import pytest from thefuck.rules.history import match, get_new_command from thefuck.types import Command @pytest.fixture(autouse=True) def history_without_current(mocker): return mocker.patch( 'thefuck.rules.history.get_valid_history_without_current', return_value=['ls cat', 'diff x']) @pytest.mark.parametrize('script', ['ls cet', 'daff x']) def test_match(script): assert match(Command(script, '')) @pytest.mark.parametrize('script', ['apt-get', 'nocommand y']) def test_not_match(script): assert not match(Command(script, '')) @pytest.mark.parametrize('script, result', [ ('ls cet', 'ls cat'), ('daff x', 'diff x')]) def test_get_new_command(script, result): assert get_new_command(Command(script, '')) == result
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_gradle_not_task.py
tests/rules/test_gradle_not_task.py
import pytest from io import BytesIO from thefuck.rules.gradle_no_task import match, get_new_command from thefuck.types import Command gradle_tasks = b''' :tasks ------------------------------------------------------------ All tasks runnable from root project ------------------------------------------------------------ Android tasks ------------- androidDependencies - Displays the Android dependencies of the project. signingReport - Displays the signing info for each variant. sourceSets - Prints out all the source sets defined in this project. Build tasks ----------- assemble - Assembles all variants of all applications and secondary packages. assembleAndroidTest - Assembles all the Test applications. assembleDebug - Assembles all Debug builds. assembleRelease - Assembles all Release builds. build - Assembles and tests this project. buildDependents - Assembles and tests this project and all projects that depend on it. buildNeeded - Assembles and tests this project and all projects it depends on. compileDebugAndroidTestSources compileDebugSources compileDebugUnitTestSources compileReleaseSources compileReleaseUnitTestSources extractDebugAnnotations - Extracts Android annotations for the debug variant into the archive file extractReleaseAnnotations - Extracts Android annotations for the release variant into the archive file mockableAndroidJar - Creates a version of android.jar that's suitable for unit tests. Build Setup tasks ----------------- init - Initializes a new Gradle build. [incubating] wrapper - Generates Gradle wrapper files. [incubating] Help tasks ---------- components - Displays the components produced by root project 'org.rerenderer_example.snake'. [incubating] dependencies - Displays all dependencies declared in root project 'org.rerenderer_example.snake'. dependencyInsight - Displays the insight into a specific dependency in root project 'org.rerenderer_example.snake'. help - Displays a help message. model - Displays the configuration model of root project 'org.rerenderer_example.snake'. [incubating] projects - Displays the sub-projects of root project 'org.rerenderer_example.snake'. properties - Displays the properties of root project 'org.rerenderer_example.snake'. tasks - Displays the tasks runnable from root project 'org.rerenderer_example.snake' (some of the displayed tasks may belong to subprojects). Install tasks ------------- installDebug - Installs the Debug build. installDebugAndroidTest - Installs the android (on device) tests for the Debug build. installRelease - Installs the Release build. uninstallAll - Uninstall all applications. uninstallDebug - Uninstalls the Debug build. uninstallDebugAndroidTest - Uninstalls the android (on device) tests for the Debug build. uninstallRelease - Uninstalls the Release build. React tasks ----------- bundleDebugJsAndAssets - bundle JS and assets for Debug. bundleReleaseJsAndAssets - bundle JS and assets for Release. Verification tasks ------------------ check - Runs all checks. clean - Deletes the build directory. connectedAndroidTest - Installs and runs instrumentation tests for all flavors on connected devices. connectedCheck - Runs all device checks on currently connected devices. connectedDebugAndroidTest - Installs and runs the tests for debug on connected devices. deviceAndroidTest - Installs and runs instrumentation tests using all Device Providers. deviceCheck - Runs all device checks using Device Providers and Test Servers. lint - Runs lint on all variants. lintDebug - Runs lint on the Debug build. lintRelease - Runs lint on the Release build. test - Run unit tests for all variants. testDebugUnitTest - Run unit tests for the debug build. testReleaseUnitTest - Run unit tests for the release build. Other tasks ----------- assembleDefault copyDownloadableDepsToLibs jarDebugClasses jarReleaseClasses To see all tasks and more detail, run gradlew tasks --all To see more detail about a task, run gradlew help --task <task> BUILD SUCCESSFUL Total time: 1.936 secs ''' output_not_found = ''' FAILURE: Build failed with an exception. * What went wrong: Task '{}' not found in root project 'org.rerenderer_example.snake'. * Try: Run gradlew tasks to get a list of available tasks. Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. '''.format output_ambiguous = ''' FAILURE: Build failed with an exception. * What went wrong: Task '{}' is ambiguous in root project 'org.rerenderer_example.snake'. Candidates are: 'assembleRelease', 'assembleReleaseUnitTest'. * Try: Run gradlew tasks to get a list of available tasks. Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. '''.format @pytest.fixture(autouse=True) def tasks(mocker): patch = mocker.patch('thefuck.rules.gradle_no_task.Popen') patch.return_value.stdout = BytesIO(gradle_tasks) return patch @pytest.mark.parametrize('command', [ Command('./gradlew assembler', output_ambiguous('assembler')), Command('./gradlew instar', output_not_found('instar')), Command('gradle assembler', output_ambiguous('assembler')), Command('gradle instar', output_not_found('instar'))]) def test_match(command): assert match(command) @pytest.mark.parametrize('command', [ Command('./gradlew assemble', ''), Command('gradle assemble', ''), Command('npm assembler', output_ambiguous('assembler')), Command('npm instar', output_not_found('instar'))]) def test_not_match(command): assert not match(command) @pytest.mark.parametrize('command, result', [ (Command('./gradlew assembler', output_ambiguous('assembler')), './gradlew assemble'), (Command('./gradlew instardebug', output_not_found('instardebug')), './gradlew installDebug'), (Command('gradle assembler', output_ambiguous('assembler')), 'gradle assemble'), (Command('gradle instardebug', output_not_found('instardebug')), 'gradle installDebug')]) def test_get_new_command(command, result): assert get_new_command(command)[0] == result
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_git_branch_0flag.py
tests/rules/test_git_branch_0flag.py
import pytest from thefuck.rules.git_branch_0flag import get_new_command, match from thefuck.types import Command @pytest.fixture def output_branch_exists(): return "fatal: A branch named 'bar' already exists." @pytest.mark.parametrize( "script", [ "git branch 0a", "git branch 0d", "git branch 0f", "git branch 0r", "git branch 0v", "git branch 0d foo", "git branch 0D foo", ], ) def test_match(script, output_branch_exists): assert match(Command(script, output_branch_exists)) @pytest.mark.parametrize( "script", [ "git branch -a", "git branch -r", "git branch -v", "git branch -d foo", "git branch -D foo", ], ) def test_not_match(script, output_branch_exists): assert not match(Command(script, "")) @pytest.mark.parametrize( "script, new_command", [ ("git branch 0a", "git branch -D 0a && git branch -a"), ("git branch 0v", "git branch -D 0v && git branch -v"), ("git branch 0d foo", "git branch -D 0d && git branch -d foo"), ("git branch 0D foo", "git branch -D 0D && git branch -D foo"), ("git branch 0l 'maint-*'", "git branch -D 0l && git branch -l 'maint-*'"), ("git branch 0u upstream", "git branch -D 0u && git branch -u upstream"), ], ) def test_get_new_command_branch_exists(script, output_branch_exists, new_command): assert get_new_command(Command(script, output_branch_exists)) == new_command @pytest.fixture def output_not_valid_object(): return "fatal: Not a valid object name: 'bar'." @pytest.mark.parametrize( "script, new_command", [ ("git branch 0l 'maint-*'", "git branch -l 'maint-*'"), ("git branch 0u upstream", "git branch -u upstream"), ], ) def test_get_new_command_not_valid_object(script, output_not_valid_object, new_command): assert get_new_command(Command(script, output_not_valid_object)) == new_command
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_git_stash.py
tests/rules/test_git_stash.py
import pytest from thefuck.rules.git_stash import match, get_new_command from thefuck.types import Command cherry_pick_error = ( 'error: Your local changes would be overwritten by cherry-pick.\n' 'hint: Commit your changes or stash them to proceed.\n' 'fatal: cherry-pick failed') rebase_error = ( 'Cannot rebase: Your index contains uncommitted changes.\n' 'Please commit or stash them.') @pytest.mark.parametrize('command', [ Command('git cherry-pick a1b2c3d', cherry_pick_error), Command('git rebase -i HEAD~7', rebase_error)]) def test_match(command): assert match(command) @pytest.mark.parametrize('command', [ Command('git cherry-pick a1b2c3d', ''), Command('git rebase -i HEAD~7', '')]) def test_not_match(command): assert not match(command) @pytest.mark.parametrize('command, new_command', [ (Command('git cherry-pick a1b2c3d', cherry_pick_error), 'git stash && git cherry-pick a1b2c3d'), (Command('git rebase -i HEAD~7', rebase_error), 'git stash && git rebase -i HEAD~7')]) def test_get_new_command(command, new_command): assert get_new_command(command) == new_command
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_tsuru_not_command.py
tests/rules/test_tsuru_not_command.py
import pytest from thefuck.types import Command from thefuck.rules.tsuru_not_command import match, get_new_command @pytest.mark.parametrize('command', [ Command('tsuru log', ( 'tsuru: "tchururu" is not a tsuru command. See "tsuru help".\n' '\nDid you mean?\n' '\tapp-log\n' '\tlogin\n' '\tlogout\n' )), Command('tsuru app-l', ( 'tsuru: "tchururu" is not a tsuru command. See "tsuru help".\n' '\nDid you mean?\n' '\tapp-list\n' '\tapp-log\n' )), Command('tsuru user-list', ( 'tsuru: "tchururu" is not a tsuru command. See "tsuru help".\n' '\nDid you mean?\n' '\tteam-user-list\n' )), Command('tsuru targetlist', ( 'tsuru: "tchururu" is not a tsuru command. See "tsuru help".\n' '\nDid you mean?\n' '\ttarget-list\n' )), ]) def test_match(command): assert match(command) @pytest.mark.parametrize('command', [ Command('tsuru tchururu', ( 'tsuru: "tchururu" is not a tsuru command. See "tsuru help".\n' '\nDid you mean?\n' )), Command('tsuru version', 'tsuru version 0.16.0.'), Command('tsuru help', ( 'tsuru version 0.16.0.\n' '\nUsage: tsuru command [args]\n' )), Command('tsuru platform-list', ( '- java\n' '- logstashgiro\n' '- newnode\n' '- nodejs\n' '- php\n' '- python\n' '- python3\n' '- ruby\n' '- ruby20\n' '- static\n' )), Command('tsuru env-get', 'Error: App thefuck not found.'), ]) def test_not_match(command): assert not match(command) @pytest.mark.parametrize('command, new_commands', [ (Command('tsuru log', ( 'tsuru: "log" is not a tsuru command. See "tsuru help".\n' '\nDid you mean?\n' '\tapp-log\n' '\tlogin\n' '\tlogout\n' )), ['tsuru login', 'tsuru logout', 'tsuru app-log']), (Command('tsuru app-l', ( 'tsuru: "app-l" is not a tsuru command. See "tsuru help".\n' '\nDid you mean?\n' '\tapp-list\n' '\tapp-log\n' )), ['tsuru app-log', 'tsuru app-list']), (Command('tsuru user-list', ( 'tsuru: "user-list" is not a tsuru command. See "tsuru help".\n' '\nDid you mean?\n' '\tteam-user-list\n' )), ['tsuru team-user-list']), (Command('tsuru targetlist', ( 'tsuru: "targetlist" is not a tsuru command. See "tsuru help".\n' '\nDid you mean?\n' '\ttarget-list\n' )), ['tsuru target-list']), ]) def test_get_new_command(command, new_commands): assert get_new_command(command) == new_commands
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_grep_recursive.py
tests/rules/test_grep_recursive.py
# -*- coding: utf-8 -*- from thefuck.rules.grep_recursive import match, get_new_command from thefuck.types import Command def test_match(): assert match(Command('grep blah .', 'grep: .: Is a directory')) assert match(Command(u'grep café .', 'grep: .: Is a directory')) assert not match(Command('', '')) def test_get_new_command(): assert get_new_command(Command('grep blah .', '')) == 'grep -r blah .' assert get_new_command(Command(u'grep café .', '')) == u'grep -r café .'
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_git_merge.py
tests/rules/test_git_merge.py
import pytest from thefuck.rules.git_merge import match, get_new_command from thefuck.types import Command output = 'merge: local - not something we can merge\n\n' \ 'Did you mean this?\n\tremote/local' def test_match(): assert match(Command('git merge test', output)) assert not match(Command('git merge master', '')) assert not match(Command('ls', output)) @pytest.mark.parametrize('command, new_command', [ (Command('git merge local', output), 'git merge remote/local'), (Command('git merge -m "test" local', output), 'git merge -m "test" remote/local'), (Command('git merge -m "test local" local', output), 'git merge -m "test local" remote/local')]) def test_get_new_command(command, new_command): assert get_new_command(command) == new_command
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_git_remote_seturl_add.py
tests/rules/test_git_remote_seturl_add.py
import pytest from thefuck.rules.git_remote_seturl_add import match, get_new_command from thefuck.types import Command @pytest.mark.parametrize('command', [ Command('git remote set-url origin url', "fatal: No such remote")]) def test_match(command): assert match(command) @pytest.mark.parametrize('command', [ Command('git remote set-url origin url', ""), Command('git remote add origin url', ''), Command('git remote remove origin', ''), Command('git remote prune origin', ''), Command('git remote set-branches origin branch', '')]) def test_not_match(command): assert not match(command) @pytest.mark.parametrize('command, new_command', [ (Command('git remote set-url origin git@github.com:nvbn/thefuck.git', ''), 'git remote add origin git@github.com:nvbn/thefuck.git')]) def test_get_new_command(command, new_command): assert get_new_command(command) == new_command
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_apt_get.py
tests/rules/test_apt_get.py
import pytest from thefuck.rules.apt_get import match, get_new_command from thefuck.types import Command @pytest.mark.parametrize('command, packages', [ (Command('vim', 'vim: command not found'), [('vim', 'main'), ('vim-tiny', 'main')]), (Command('sudo vim', 'vim: command not found'), [('vim', 'main'), ('vim-tiny', 'main')]), (Command('vim', "The program 'vim' is currently not installed. You can install it by typing: sudo apt install vim"), [('vim', 'main'), ('vim-tiny', 'main')])]) def test_match(mocker, command, packages): mocker.patch('thefuck.rules.apt_get.which', return_value=None) mocker.patch('thefuck.rules.apt_get._get_packages', create=True, return_value=packages) assert match(command) @pytest.mark.parametrize('command, packages, which', [ (Command('a_bad_cmd', 'a_bad_cmd: command not found'), [], None), (Command('vim', ''), [], None), (Command('', ''), [], None), (Command('vim', 'vim: command not found'), ['vim'], '/usr/bin/vim'), (Command('sudo vim', 'vim: command not found'), ['vim'], '/usr/bin/vim')]) def test_not_match(mocker, command, packages, which): mocker.patch('thefuck.rules.apt_get.which', return_value=which) mocker.patch('thefuck.rules.apt_get._get_packages', create=True, return_value=packages) assert not match(command) @pytest.mark.parametrize('command, new_command, packages', [ (Command('vim', ''), 'sudo apt-get install vim && vim', [('vim', 'main'), ('vim-tiny', 'main')]), (Command('convert', ''), 'sudo apt-get install imagemagick && convert', [('imagemagick', 'main'), ('graphicsmagick-imagemagick-compat', 'universe')]), (Command('sudo vim', ''), 'sudo apt-get install vim && sudo vim', [('vim', 'main'), ('vim-tiny', 'main')]), (Command('sudo convert', ''), 'sudo apt-get install imagemagick && sudo convert', [('imagemagick', 'main'), ('graphicsmagick-imagemagick-compat', 'universe')])]) def test_get_new_command(mocker, command, new_command, packages): mocker.patch('thefuck.rules.apt_get._get_packages', create=True, return_value=packages) assert get_new_command(command) == new_command
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_fix_alt_space.py
tests/rules/test_fix_alt_space.py
# -*- encoding: utf-8 -*- from thefuck.rules.fix_alt_space import match, get_new_command from thefuck.types import Command def test_match(): """The character before 'grep' is Alt+Space, which happens frequently on the Mac when typing the pipe character (Alt+7), and holding the Alt key pressed for longer than necessary. """ assert match(Command(u'ps -ef | grep foo', u'-bash:  grep: command not found')) assert not match(Command('ps -ef | grep foo', '')) assert not match(Command('', '')) def test_get_new_command(): """ Replace the Alt+Space character by a simple space """ assert (get_new_command(Command(u'ps -ef | grep foo', '')) == 'ps -ef | grep foo')
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_php_s.py
tests/rules/test_php_s.py
import pytest from thefuck.rules.php_s import get_new_command, match from thefuck.types import Command @pytest.mark.parametrize('command', [ Command('php -s localhost:8000', ''), Command('php -t pub -s 0.0.0.0:8080', '') ]) def test_match(command): assert match(command) @pytest.mark.parametrize('command', [ Command('php -S localhost:8000', ''), Command('vim php -s', '') ]) def test_not_match(command): assert not match(command) @pytest.mark.parametrize('command, new_command', [ (Command('php -s localhost:8000', ''), 'php -S localhost:8000'), (Command('php -t pub -s 0.0.0.0:8080', ''), 'php -t pub -S 0.0.0.0:8080') ]) def test_get_new_command(command, new_command): assert get_new_command(command) == new_command
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_cd_mkdir.py
tests/rules/test_cd_mkdir.py
import pytest from thefuck.rules.cd_mkdir import match, get_new_command from thefuck.types import Command @pytest.mark.parametrize('command', [ Command('cd foo', 'cd: foo: No such file or directory'), Command('cd foo/bar/baz', 'cd: foo: No such file or directory'), Command('cd foo/bar/baz', 'cd: can\'t cd to foo/bar/baz'), Command('cd /foo/bar/', 'cd: The directory "/foo/bar/" does not exist')]) def test_match(command): assert match(command) @pytest.mark.parametrize('command', [ Command('cd foo', ''), Command('', '')]) def test_not_match(command): assert not match(command) @pytest.mark.parametrize('command, new_command', [ (Command('cd foo', ''), 'mkdir -p foo && cd foo'), (Command('cd foo/bar/baz', ''), 'mkdir -p foo/bar/baz && cd foo/bar/baz')]) def test_get_new_command(command, new_command): assert get_new_command(command) == new_command
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_ln_no_hard_link.py
tests/rules/test_ln_no_hard_link.py
# -*- coding: utf-8 -*- import pytest from thefuck.rules.ln_no_hard_link import match, get_new_command from thefuck.types import Command error = "hard link not allowed for directory" @pytest.mark.parametrize('script, output', [ ("ln barDir barLink", "ln: ‘barDir’: {}"), ("sudo ln a b", "ln: ‘a’: {}"), ("sudo ln -nbi a b", "ln: ‘a’: {}")]) def test_match(script, output): command = Command(script, output.format(error)) assert match(command) @pytest.mark.parametrize('script, output', [ ('', ''), ("ln a b", "... hard link"), ("sudo ln a b", "... hard link"), ("a b", error)]) def test_not_match(script, output): command = Command(script, output) assert not match(command) @pytest.mark.parametrize('script, result', [ ("ln barDir barLink", "ln -s barDir barLink"), ("sudo ln barDir barLink", "sudo ln -s barDir barLink"), ("sudo ln -nbi a b", "sudo ln -s -nbi a b"), ("ln -nbi a b && ls", "ln -s -nbi a b && ls"), ("ln a ln", "ln -s a ln"), ("sudo ln a ln", "sudo ln -s a ln")]) def test_get_new_command(script, result): command = Command(script, '') assert get_new_command(command) == result
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_npm_missing_script.py
tests/rules/test_npm_missing_script.py
import pytest from io import BytesIO from thefuck.types import Command from thefuck.rules.npm_missing_script import match, get_new_command output = ''' npm ERR! Linux 4.4.0-31-generic npm ERR! argv "/opt/node/bin/node" "/opt/node/bin/npm" "run" "dvelop" npm ERR! node v4.4.7 npm ERR! npm v2.15.8 npm ERR! missing script: {} npm ERR! npm ERR! If you need help, you may report this error at: npm ERR! <https://github.com/npm/npm/issues> npm ERR! Please include the following file with any support request: npm ERR! /home/nvbn/exp/code_view/client_web/npm-debug.log '''.format run_script_stdout = b''' Lifecycle scripts included in code-view-web: test jest available via `npm run-script`: build cp node_modules/ace-builds/src-min/ -a resources/ace/ && webpack --progress --colors -p --config ./webpack.production.config.js develop cp node_modules/ace-builds/src/ -a resources/ace/ && webpack-dev-server --progress --colors watch-test jest --verbose --watch ''' @pytest.fixture(autouse=True) def run_script(mocker): patch = mocker.patch('thefuck.specific.npm.Popen') patch.return_value.stdout = BytesIO(run_script_stdout) return patch.return_value @pytest.mark.parametrize('command', [ Command('npm ru wach', output('wach')), Command('npm run live-tes', output('live-tes')), Command('npm run-script sahare', output('sahare'))]) def test_match(command): assert match(command) @pytest.mark.parametrize('command', [ Command('npm wach', output('wach')), Command('vim live-tes', output('live-tes')), Command('npm run-script sahare', '')]) def test_not_match(command): assert not match(command) @pytest.mark.parametrize('script, output, result', [ ('npm ru wach-tests', output('wach-tests'), 'npm ru watch-test'), ('npm -i run-script dvelop', output('dvelop'), 'npm -i run-script develop'), ('npm -i run-script buld -X POST', output('buld'), 'npm -i run-script build -X POST')]) def test_get_new_command(script, output, result): command = Command(script, output) assert get_new_command(command)[0] == result
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_unsudo.py
tests/rules/test_unsudo.py
import pytest from thefuck.rules.unsudo import match, get_new_command from thefuck.types import Command @pytest.mark.parametrize('output', [ 'you cannot perform this operation as root']) def test_match(output): assert match(Command('sudo ls', output)) def test_not_match(): assert not match(Command('', '')) assert not match(Command('sudo ls', 'Permission denied')) assert not match(Command('ls', 'you cannot perform this operation as root')) @pytest.mark.parametrize('before, after', [ ('sudo ls', 'ls'), ('sudo pacaur -S helloworld', 'pacaur -S helloworld')]) def test_get_new_command(before, after): assert get_new_command(Command(before, '')) == after
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_yum_invalid_operation.py
tests/rules/test_yum_invalid_operation.py
from io import BytesIO import pytest from thefuck.rules.yum_invalid_operation import match, get_new_command, _get_operations from thefuck.types import Command yum_help_text = '''Loaded plugins: extras_suggestions, langpacks, priorities, update-motd Usage: yum [options] COMMAND List of Commands: check Check for problems in the rpmdb check-update Check for available package updates clean Remove cached data deplist List a package's dependencies distribution-synchronization Synchronize installed packages to the latest available versions downgrade downgrade a package erase Remove a package or packages from your system fs Acts on the filesystem data of the host, mainly for removing docs/lanuages for minimal hosts. fssnapshot Creates filesystem snapshots, or lists/deletes current snapshots. groups Display, or use, the groups information help Display a helpful usage message history Display, or use, the transaction history info Display details about a package or group of packages install Install a package or packages on your system langavailable Check available languages langinfo List languages information langinstall Install appropriate language packs for a language langlist List installed languages langremove Remove installed language packs for a language list List a package or groups of packages load-transaction load a saved transaction from filename makecache Generate the metadata cache provides Find what package provides the given value reinstall reinstall a package repo-pkgs Treat a repo. as a group of packages, so we can install/remove all of them repolist Display the configured software repositories search Search package details for the given string shell Run an interactive yum shell swap Simple way to swap packages, instead of using shell update Update a package or packages on your system update-minimal Works like upgrade, but goes to the 'newest' package match which fixes a problem that affects your system updateinfo Acts on repository update information upgrade Update packages taking obsoletes into account version Display a version for the machine and/or available repos. Options: -h, --help show this help message and exit -t, --tolerant be tolerant of errors -C, --cacheonly run entirely from system cache, don't update cache -c [config file], --config=[config file] config file location -R [minutes], --randomwait=[minutes] maximum command wait time -d [debug level], --debuglevel=[debug level] debugging output level --showduplicates show duplicates, in repos, in list/search commands -e [error level], --errorlevel=[error level] error output level --rpmverbosity=[debug level name] debugging output level for rpm -q, --quiet quiet operation -v, --verbose verbose operation -y, --assumeyes answer yes for all questions --assumeno answer no for all questions --version show Yum version and exit --installroot=[path] set install root --enablerepo=[repo] enable one or more repositories (wildcards allowed) --disablerepo=[repo] disable one or more repositories (wildcards allowed) -x [package], --exclude=[package] exclude package(s) by name or glob --disableexcludes=[repo] disable exclude from main, for a repo or for everything --disableincludes=[repo] disable includepkgs for a repo or for everything --obsoletes enable obsoletes processing during updates --noplugins disable Yum plugins --nogpgcheck disable gpg signature checking --disableplugin=[plugin] disable plugins by name --enableplugin=[plugin] enable plugins by name --skip-broken skip packages with depsolving problems --color=COLOR control whether color is used --releasever=RELEASEVER set value of $releasever in yum config and repo files --downloadonly don't update, just download --downloaddir=DLDIR specifies an alternate directory to store packages --setopt=SETOPTS set arbitrary config and repo options --bugfix Include bugfix relevant packages, in updates --security Include security relevant packages, in updates --advisory=ADVS, --advisories=ADVS Include packages needed to fix the given advisory, in updates --bzs=BZS Include packages needed to fix the given BZ, in updates --cves=CVES Include packages needed to fix the given CVE, in updates --sec-severity=SEVS, --secseverity=SEVS Include security relevant packages matching the severity, in updates Plugin Options: --samearch-priorities Priority-exclude packages based on name + arch ''' yum_unsuccessful_search_text = '''Warning: No matches found for: {} No matches found ''' yum_successful_vim_search_text = '''================================================== N/S matched: vim =================================================== protobuf-vim.x86_64 : Vim syntax highlighting for Google Protocol Buffers descriptions vim-X11.x86_64 : The VIM version of the vi editor for the X Window System - GVim vim-common.x86_64 : The common files needed by any version of the VIM editor vim-enhanced.x86_64 : A version of the VIM editor which includes recent enhancements vim-filesystem.x86_64 : VIM filesystem layout vim-filesystem.noarch : VIM filesystem layout vim-minimal.x86_64 : A minimal version of the VIM editor Name and summary matches only, use "search all" for everything. ''' yum_invalid_op_text = '''Loaded plugins: extras_suggestions, langpacks, priorities, update-motd No such command: {}. Please use /usr/bin/yum --help ''' yum_operations = [ 'check', 'check-update', 'clean', 'deplist', 'distribution-synchronization', 'downgrade', 'erase', 'fs', 'fssnapshot', 'groups', 'help', 'history', 'info', 'install', 'langavailable', 'langinfo', 'langinstall', 'langlist', 'langremove', 'list', 'load-transaction', 'makecache', 'provides', 'reinstall', 'repo-pkgs', 'repolist', 'search', 'shell', 'swap', 'update', 'update-minimal', 'updateinfo', 'upgrade', 'version', ] @pytest.mark.parametrize('command', [ 'saerch', 'uninstall', ]) def test_match(command): assert match(Command('yum {}'.format(command), yum_invalid_op_text.format(command))) @pytest.mark.parametrize('command, output', [ ('vim', ''), ('yum', yum_help_text,), ('yum help', yum_help_text,), ('yum search asdf', yum_unsuccessful_search_text.format('asdf'),), ('yum search vim', yum_successful_vim_search_text) ]) def test_not_match(command, output): assert not match(Command(command, output)) @pytest.fixture def yum_help(mocker): mock = mocker.patch('subprocess.Popen') mock.return_value.stdout = BytesIO(bytes(yum_help_text.encode('utf-8'))) return mock @pytest.mark.usefixtures('no_memoize', 'yum_help') def test_get_operations(): assert _get_operations() == yum_operations @pytest.mark.usefixtures('no_memoize', 'yum_help') @pytest.mark.parametrize('script, output, result', [ ('yum uninstall', yum_invalid_op_text.format('uninstall'), 'yum remove',), ('yum saerch asdf', yum_invalid_op_text.format('saerch'), 'yum search asdf',), ('yum hlep', yum_invalid_op_text.format('hlep'), 'yum help',), ]) def test_get_new_command(script, output, result): assert get_new_command(Command(script, output))[0] == result
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_yarn_alias.py
tests/rules/test_yarn_alias.py
import pytest from thefuck.rules.yarn_alias import match, get_new_command from thefuck.types import Command output_remove = 'error Did you mean `yarn remove`?' output_etl = 'error Command "etil" not found. Did you mean "etl"?' output_list = 'error Did you mean `yarn list`?' @pytest.mark.parametrize('command', [ Command('yarn rm', output_remove), Command('yarn etil', output_etl), Command('yarn ls', output_list)]) def test_match(command): assert match(command) @pytest.mark.parametrize('command, new_command', [ (Command('yarn rm', output_remove), 'yarn remove'), (Command('yarn etil', output_etl), 'yarn etl'), (Command('yarn ls', output_list), 'yarn list')]) def test_get_new_command(command, new_command): assert get_new_command(command) == new_command
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_cd_cs.py
tests/rules/test_cd_cs.py
from thefuck.rules.cd_cs import match, get_new_command from thefuck.types import Command def test_match(): assert match(Command('cs', 'cs: command not found')) assert match(Command('cs /etc/', 'cs: command not found')) def test_get_new_command(): assert get_new_command(Command('cs /etc/', 'cs: command not found')) == 'cd /etc/'
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_django_south_merge.py
tests/rules/test_django_south_merge.py
import pytest from thefuck.rules.django_south_merge import match, get_new_command from thefuck.types import Command @pytest.fixture def output(): return '''Running migrations for app: ! Migration app:0003_auto... should not have been applied before app:0002_auto__add_field_query_due_date_ but was. Traceback (most recent call last): File "/home/nvbn/work/.../bin/python", line 42, in <module> exec(compile(__file__f.read(), __file__, "exec")) File "/home/nvbn/work/.../app/manage.py", line 34, in <module> execute_from_command_line(sys.argv) File "/home/nvbn/work/.../lib/django/core/management/__init__.py", line 443, in execute_from_command_line utility.execute() File "/home/nvbn/work/.../lib/django/core/management/__init__.py", line 382, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/nvbn/work/.../lib/django/core/management/base.py", line 196, in run_from_argv self.execute(*args, **options.__dict__) File "/home/nvbn/work/.../lib/django/core/management/base.py", line 232, in execute output = self.handle(*args, **options) File "/home/nvbn/work/.../app/lib/south/management/commands/migrate.py", line 108, in handle ignore_ghosts = ignore_ghosts, File "/home/nvbn/work/.../app/lib/south/migration/__init__.py", line 207, in migrate_app raise exceptions.InconsistentMigrationHistory(problems) south.exceptions.InconsistentMigrationHistory: Inconsistent migration history The following options are available: --merge: will just attempt the migration ignoring any potential dependency conflicts. ''' def test_match(output): assert match(Command('./manage.py migrate', output)) assert match(Command('python manage.py migrate', output)) assert not match(Command('./manage.py migrate', '')) assert not match(Command('app migrate', output)) assert not match(Command('./manage.py test', output)) def test_get_new_command(): assert (get_new_command(Command('./manage.py migrate auth', '')) == './manage.py migrate auth --merge')
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_git_branch_delete_checked_out.py
tests/rules/test_git_branch_delete_checked_out.py
import pytest from thefuck.rules.git_branch_delete_checked_out import match, get_new_command from thefuck.types import Command @pytest.fixture def output(): return "error: Cannot delete branch 'foo' checked out at '/bar/foo'" @pytest.mark.parametrize("script", ["git branch -d foo", "git branch -D foo"]) def test_match(script, output): assert match(Command(script, output)) @pytest.mark.parametrize("script", ["git branch -d foo", "git branch -D foo"]) def test_not_match(script): assert not match(Command(script, "Deleted branch foo (was a1b2c3d).")) @pytest.mark.parametrize( "script, new_command", [ ("git branch -d foo", "git checkout master && git branch -D foo"), ("git branch -D foo", "git checkout master && git branch -D foo"), ], ) def test_get_new_command(script, new_command, output): assert get_new_command(Command(script, output)) == new_command
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/rules/test_open.py
tests/rules/test_open.py
import pytest from thefuck.rules.open import is_arg_url, match, get_new_command from thefuck.types import Command @pytest.fixture def output(script): return 'The file {} does not exist.\n'.format(script.split(' ', 1)[1]) @pytest.mark.parametrize('script', [ 'open foo.com', 'open foo.edu', 'open foo.info', 'open foo.io', 'open foo.ly', 'open foo.me', 'open foo.net', 'open foo.org', 'open foo.se', 'open www.foo.ru']) def test_is_arg_url(script): assert is_arg_url(Command(script, '')) @pytest.mark.parametrize('script', ['open foo', 'open bar.txt', 'open egg.doc']) def test_not_is_arg_url(script): assert not is_arg_url(Command(script, '')) @pytest.mark.parametrize('script', [ 'open foo.com', 'xdg-open foo.com', 'gnome-open foo.com', 'kde-open foo.com', 'open nonest']) def test_match(script, output): assert match(Command(script, output)) @pytest.mark.parametrize('script, new_command', [ ('open foo.io', ['open http://foo.io']), ('xdg-open foo.io', ['xdg-open http://foo.io']), ('gnome-open foo.io', ['gnome-open http://foo.io']), ('kde-open foo.io', ['kde-open http://foo.io']), ('open nonest', ['touch nonest && open nonest', 'mkdir nonest && open nonest'])]) def test_get_new_command(script, new_command, output): assert get_new_command(Command(script, output)) == new_command
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/specific/test_npm.py
tests/specific/test_npm.py
from io import BytesIO import pytest from thefuck.specific.npm import get_scripts run_script_stdout = b''' Lifecycle scripts included in code-view-web: test jest available via `npm run-script`: build cp node_modules/ace-builds/src-min/ -a resources/ace/ && webpack --progress --colors -p --config ./webpack.production.config.js develop cp node_modules/ace-builds/src/ -a resources/ace/ && webpack-dev-server --progress --colors watch-test jest --verbose --watch ''' @pytest.mark.usefixtures('no_memoize') def test_get_scripts(mocker): patch = mocker.patch('thefuck.specific.npm.Popen') patch.return_value.stdout = BytesIO(run_script_stdout) assert get_scripts() == ['build', 'develop', 'watch-test']
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/specific/test_sudo.py
tests/specific/test_sudo.py
import pytest from thefuck.specific.sudo import sudo_support from thefuck.types import Command @pytest.mark.parametrize('return_value, command, called, result', [ ('ls -lah', 'sudo ls', 'ls', 'sudo ls -lah'), ('ls -lah', 'ls', 'ls', 'ls -lah'), (['ls -lah'], 'sudo ls', 'ls', ['sudo ls -lah']), (True, 'sudo ls', 'ls', True), (True, 'ls', 'ls', True), (False, 'sudo ls', 'ls', False), (False, 'ls', 'ls', False)]) def test_sudo_support(return_value, command, called, result): def fn(command): assert command == Command(called, '') return return_value assert sudo_support(fn)(Command(command, '')) == result
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/specific/test_git.py
tests/specific/test_git.py
import pytest from thefuck.specific.git import git_support from thefuck.types import Command @pytest.mark.parametrize('called, command, output', [ ('git co', 'git checkout', "19:22:36.299340 git.c:282 trace: alias expansion: co => 'checkout'"), ('git com file', 'git commit --verbose file', "19:23:25.470911 git.c:282 trace: alias expansion: com => 'commit' '--verbose'"), ('git com -m "Initial commit"', 'git commit -m "Initial commit"', "19:22:36.299340 git.c:282 trace: alias expansion: com => 'commit'"), ('git br -d some_branch', 'git branch -d some_branch', "19:22:36.299340 git.c:282 trace: alias expansion: br => 'branch'")]) def test_git_support(called, command, output): @git_support def fn(command): return command.script assert fn(Command(called, output)) == command @pytest.mark.parametrize('command, is_git', [ ('git pull', True), ('hub pull', True), ('git push --set-upstream origin foo', True), ('hub push --set-upstream origin foo', True), ('ls', False), ('cat git', False), ('cat hub', False)]) @pytest.mark.parametrize('output', ['', None]) def test_git_support_match(command, is_git, output): @git_support def fn(command): return True assert fn(Command(command, output)) == is_git
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/specific/__init__.py
tests/specific/__init__.py
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/output_readers/test_rerun.py
tests/output_readers/test_rerun.py
# -*- encoding: utf-8 -*- import pytest import sys from mock import Mock, patch from psutil import AccessDenied, TimeoutExpired from thefuck.output_readers import rerun class TestRerun(object): def setup_method(self, test_method): self.patcher = patch('thefuck.output_readers.rerun.Process') process_mock = self.patcher.start() self.proc_mock = process_mock.return_value = Mock() def teardown_method(self, test_method): self.patcher.stop() @patch('thefuck.output_readers.rerun._wait_output', return_value=False) @patch('thefuck.output_readers.rerun.Popen') def test_get_output(self, popen_mock, wait_output_mock): popen_mock.return_value.stdout.read.return_value = b'output' assert rerun.get_output('', '') is None wait_output_mock.assert_called_once() @patch('thefuck.output_readers.rerun.Popen') def test_get_output_invalid_continuation_byte(self, popen_mock): output = b'ls: illegal option -- \xc3\nusage: ls [-@ABC...] [file ...]\n' expected = u'ls: illegal option -- \ufffd\nusage: ls [-@ABC...] [file ...]\n' popen_mock.return_value.stdout.read.return_value = output actual = rerun.get_output('', '') assert actual == expected @pytest.mark.skipif(sys.platform == 'win32', reason="skip when running on Windows") @patch('thefuck.output_readers.rerun._wait_output') def test_get_output_unicode_misspell(self, wait_output_mock): rerun.get_output(u'pácman', u'pácman') wait_output_mock.assert_called_once() def test_wait_output_is_slow(self, settings): assert rerun._wait_output(Mock(), True) self.proc_mock.wait.assert_called_once_with(settings.wait_slow_command) def test_wait_output_is_not_slow(self, settings): assert rerun._wait_output(Mock(), False) self.proc_mock.wait.assert_called_once_with(settings.wait_command) @patch('thefuck.output_readers.rerun._kill_process') def test_wait_output_timeout(self, kill_process_mock): self.proc_mock.wait.side_effect = TimeoutExpired(3) self.proc_mock.children.return_value = [] assert not rerun._wait_output(Mock(), False) kill_process_mock.assert_called_once_with(self.proc_mock) @patch('thefuck.output_readers.rerun._kill_process') def test_wait_output_timeout_children(self, kill_process_mock): self.proc_mock.wait.side_effect = TimeoutExpired(3) self.proc_mock.children.return_value = [Mock()] * 2 assert not rerun._wait_output(Mock(), False) assert kill_process_mock.call_count == 3 def test_kill_process(self): proc = Mock() rerun._kill_process(proc) proc.kill.assert_called_once_with() @patch('thefuck.output_readers.rerun.logs') def test_kill_process_access_denied(self, logs_mock): proc = Mock() proc.kill.side_effect = AccessDenied() rerun._kill_process(proc) proc.kill.assert_called_once_with() logs_mock.debug.assert_called_once()
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/shells/test_tcsh.py
tests/shells/test_tcsh.py
# -*- coding: utf-8 -*- import pytest from thefuck.shells.tcsh import Tcsh @pytest.mark.usefixtures('isfile', 'no_memoize', 'no_cache') class TestTcsh(object): @pytest.fixture def shell(self): return Tcsh() @pytest.fixture(autouse=True) def Popen(self, mocker): mock = mocker.patch('thefuck.shells.tcsh.Popen') mock.return_value.stdout.read.return_value = ( b'fuck\teval $(thefuck $(fc -ln -1))\n' b'l\tls -CF\n' b'la\tls -A\n' b'll\tls -alF') return mock @pytest.mark.parametrize('before, after', [ ('pwd', 'pwd'), ('fuck', 'eval $(thefuck $(fc -ln -1))'), ('awk', 'awk'), ('ll', 'ls -alF')]) def test_from_shell(self, before, after, shell): assert shell.from_shell(before) == after def test_to_shell(self, shell): assert shell.to_shell('pwd') == 'pwd' def test_and_(self, shell): assert shell.and_('ls', 'cd') == 'ls && cd' def test_or_(self, shell): assert shell.or_('ls', 'cd') == 'ls || cd' def test_get_aliases(self, shell): assert shell.get_aliases() == {'fuck': 'eval $(thefuck $(fc -ln -1))', 'l': 'ls -CF', 'la': 'ls -A', 'll': 'ls -alF'} def test_app_alias(self, shell): assert 'setenv TF_SHELL tcsh' in shell.app_alias('fuck') assert 'alias fuck' in shell.app_alias('fuck') assert 'alias FUCK' in shell.app_alias('FUCK') assert 'thefuck' in shell.app_alias('fuck') def test_get_history(self, history_lines, shell): history_lines(['ls', 'rm']) assert list(shell.get_history()) == ['ls', 'rm'] def test_how_to_configure(self, shell, config_exists): config_exists.return_value = True assert shell.how_to_configure().can_configure_automatically def test_how_to_configure_when_config_not_found(self, shell, config_exists): config_exists.return_value = False assert not shell.how_to_configure().can_configure_automatically def test_info(self, shell, Popen): Popen.return_value.stdout.read.side_effect = [ b'tcsh 6.20.00 (Astron) 2016-11-24 (unknown-unknown-bsd44) \n'] assert shell.info() == 'Tcsh 6.20.00' assert Popen.call_args[0][0] == ['tcsh', '--version'] @pytest.mark.parametrize('side_effect, exception', [ ([b'\n'], IndexError), (OSError, OSError)]) def test_get_version_error(self, side_effect, exception, shell, Popen): Popen.return_value.stdout.read.side_effect = side_effect with pytest.raises(exception): shell._get_version() assert Popen.call_args[0][0] == ['tcsh', '--version']
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/shells/test_powershell.py
tests/shells/test_powershell.py
# -*- coding: utf-8 -*- import pytest from thefuck.shells import Powershell @pytest.mark.usefixtures('isfile', 'no_memoize', 'no_cache') class TestPowershell(object): @pytest.fixture def shell(self): return Powershell() @pytest.fixture(autouse=True) def Popen(self, mocker): mock = mocker.patch('thefuck.shells.powershell.Popen') return mock def test_and_(self, shell): assert shell.and_('ls', 'cd') == '(ls) -and (cd)' def test_app_alias(self, shell): assert 'function fuck' in shell.app_alias('fuck') assert 'function FUCK' in shell.app_alias('FUCK') assert 'thefuck' in shell.app_alias('fuck') def test_how_to_configure(self, shell): assert not shell.how_to_configure().can_configure_automatically @pytest.mark.parametrize('side_effect, expected_version, call_args', [ ([b'''Major Minor Build Revision ----- ----- ----- -------- 5 1 17763 316 \n'''], 'PowerShell 5.1.17763.316', ['powershell.exe']), ([IOError, b'PowerShell 6.1.2\n'], 'PowerShell 6.1.2', ['powershell.exe', 'pwsh'])]) def test_info(self, side_effect, expected_version, call_args, shell, Popen): Popen.return_value.stdout.read.side_effect = side_effect assert shell.info() == expected_version assert Popen.call_count == len(call_args) assert all([Popen.call_args_list[i][0][0][0] == call_arg for i, call_arg in enumerate(call_args)]) def test_get_version_error(self, shell, Popen): Popen.return_value.stdout.read.side_effect = RuntimeError with pytest.raises(RuntimeError): shell._get_version() assert Popen.call_args[0][0] == ['powershell.exe', '$PSVersionTable.PSVersion']
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/shells/test_fish.py
tests/shells/test_fish.py
# -*- coding: utf-8 -*- import pytest from thefuck.const import ARGUMENT_PLACEHOLDER from thefuck.shells import Fish @pytest.mark.usefixtures('isfile', 'no_memoize', 'no_cache') class TestFish(object): @pytest.fixture def shell(self): return Fish() @pytest.fixture(autouse=True) def Popen(self, mocker): mock = mocker.patch('thefuck.shells.fish.Popen') mock.return_value.stdout.read.side_effect = [( b'cd\nfish_config\nfuck\nfunced\nfuncsave\ngrep\nhistory\nll\nls\n' b'man\nmath\npopd\npushd\nruby'), (b'alias fish_key_reader /usr/bin/fish_key_reader\nalias g git\n' b'alias alias_with_equal_sign=echo\ninvalid_alias'), b'func1\nfunc2', b''] return mock @pytest.mark.parametrize('key, value', [ ('TF_OVERRIDDEN_ALIASES', 'cut,git,sed'), # legacy ('THEFUCK_OVERRIDDEN_ALIASES', 'cut,git,sed'), ('THEFUCK_OVERRIDDEN_ALIASES', 'cut, git, sed'), ('THEFUCK_OVERRIDDEN_ALIASES', ' cut,\tgit,sed\n'), ('THEFUCK_OVERRIDDEN_ALIASES', '\ncut,\n\ngit,\tsed\r')]) def test_get_overridden_aliases(self, shell, os_environ, key, value): os_environ[key] = value overridden = shell._get_overridden_aliases() assert set(overridden) == {'cd', 'cut', 'git', 'grep', 'ls', 'man', 'open', 'sed'} @pytest.mark.parametrize('before, after', [ ('cd', 'cd'), ('pwd', 'pwd'), ('fuck', 'fish -ic "fuck"'), ('find', 'find'), ('funced', 'fish -ic "funced"'), ('grep', 'grep'), ('awk', 'awk'), ('math "2 + 2"', r'fish -ic "math \"2 + 2\""'), ('man', 'man'), ('open', 'open'), ('vim', 'vim'), ('ll', 'fish -ic "ll"'), ('ls', 'ls'), ('g', 'git')]) def test_from_shell(self, before, after, shell): assert shell.from_shell(before) == after def test_to_shell(self, shell): assert shell.to_shell('pwd') == 'pwd' def test_and_(self, shell): assert shell.and_('foo', 'bar') == 'foo; and bar' def test_or_(self, shell): assert shell.or_('foo', 'bar') == 'foo; or bar' def test_get_aliases(self, shell): assert shell.get_aliases() == {'fish_config': 'fish_config', 'fuck': 'fuck', 'funced': 'funced', 'funcsave': 'funcsave', 'history': 'history', 'll': 'll', 'math': 'math', 'popd': 'popd', 'pushd': 'pushd', 'ruby': 'ruby', 'g': 'git', 'fish_key_reader': '/usr/bin/fish_key_reader', 'alias_with_equal_sign': 'echo'} assert shell.get_aliases() == {'func1': 'func1', 'func2': 'func2'} def test_app_alias(self, shell): assert 'function fuck' in shell.app_alias('fuck') assert 'function FUCK' in shell.app_alias('FUCK') assert 'thefuck' in shell.app_alias('fuck') assert 'TF_SHELL=fish' in shell.app_alias('fuck') assert 'TF_ALIAS=fuck PYTHONIOENCODING' in shell.app_alias('fuck') assert 'PYTHONIOENCODING=utf-8 thefuck' in shell.app_alias('fuck') assert ARGUMENT_PLACEHOLDER in shell.app_alias('fuck') def test_app_alias_alter_history(self, settings, shell): settings.alter_history = True assert ( 'builtin history delete --exact --case-sensitive -- $fucked_up_command\n' in shell.app_alias('FUCK') ) assert 'builtin history merge\n' in shell.app_alias('FUCK') settings.alter_history = False assert 'builtin history delete' not in shell.app_alias('FUCK') assert 'builtin history merge' not in shell.app_alias('FUCK') def test_get_history(self, history_lines, shell): history_lines(['- cmd: ls', ' when: 1432613911', '- cmd: rm', ' when: 1432613916']) assert list(shell.get_history()) == ['ls', 'rm'] @pytest.mark.parametrize('entry, entry_utf8', [ ('ls', '- cmd: ls\n when: 1430707243\n'), (u'echo café', '- cmd: echo café\n when: 1430707243\n')]) def test_put_to_history(self, entry, entry_utf8, builtins_open, mocker, shell): mocker.patch('thefuck.shells.fish.time', return_value=1430707243.3517463) shell.put_to_history(entry) builtins_open.return_value.__enter__.return_value. \ write.assert_called_once_with(entry_utf8) def test_how_to_configure(self, shell, config_exists): config_exists.return_value = True assert shell.how_to_configure().can_configure_automatically def test_how_to_configure_when_config_not_found(self, shell, config_exists): config_exists.return_value = False assert not shell.how_to_configure().can_configure_automatically def test_get_version(self, shell, Popen): Popen.return_value.stdout.read.side_effect = [b'fish, version 3.5.9\n'] assert shell._get_version() == '3.5.9' assert Popen.call_args[0][0] == ['fish', '--version'] @pytest.mark.parametrize('side_effect, exception', [ ([b'\n'], IndexError), (OSError('file not found'), OSError), ]) def test_get_version_error(self, side_effect, exception, shell, Popen): Popen.return_value.stdout.read.side_effect = side_effect with pytest.raises(exception): shell._get_version() assert Popen.call_args[0][0] == ['fish', '--version']
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/shells/conftest.py
tests/shells/conftest.py
import pytest @pytest.fixture def builtins_open(mocker): return mocker.patch('six.moves.builtins.open') @pytest.fixture def isfile(mocker): return mocker.patch('os.path.isfile', return_value=True) @pytest.fixture @pytest.mark.usefixtures('isfile') def history_lines(mocker): def aux(lines): mock = mocker.patch('io.open') mock.return_value.__enter__ \ .return_value.readlines.return_value = lines return aux @pytest.fixture def config_exists(mocker): path_mock = mocker.patch('thefuck.shells.generic.Path') return path_mock.return_value \ .expanduser.return_value \ .exists
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/shells/test_zsh.py
tests/shells/test_zsh.py
# -*- coding: utf-8 -*- import os import pytest from thefuck.shells.zsh import Zsh @pytest.mark.usefixtures('isfile', 'no_memoize', 'no_cache') class TestZsh(object): @pytest.fixture def shell(self): return Zsh() @pytest.fixture(autouse=True) def Popen(self, mocker): mock = mocker.patch('thefuck.shells.zsh.Popen') return mock @pytest.fixture(autouse=True) def shell_aliases(self): os.environ['TF_SHELL_ALIASES'] = ( 'fuck=\'eval $(thefuck $(fc -ln -1 | tail -n 1))\'\n' 'l=\'ls -CF\'\n' 'la=\'ls -A\'\n' 'll=\'ls -alF\'') @pytest.mark.parametrize('before, after', [ ('fuck', 'eval $(thefuck $(fc -ln -1 | tail -n 1))'), ('pwd', 'pwd'), ('ll', 'ls -alF')]) def test_from_shell(self, before, after, shell): assert shell.from_shell(before) == after def test_to_shell(self, shell): assert shell.to_shell('pwd') == 'pwd' def test_and_(self, shell): assert shell.and_('ls', 'cd') == 'ls && cd' def test_or_(self, shell): assert shell.or_('ls', 'cd') == 'ls || cd' def test_get_aliases(self, shell): assert shell.get_aliases() == { 'fuck': 'eval $(thefuck $(fc -ln -1 | tail -n 1))', 'l': 'ls -CF', 'la': 'ls -A', 'll': 'ls -alF'} def test_app_alias(self, shell): assert 'fuck () {' in shell.app_alias('fuck') assert 'FUCK () {' in shell.app_alias('FUCK') assert 'thefuck' in shell.app_alias('fuck') assert 'PYTHONIOENCODING' in shell.app_alias('fuck') def test_app_alias_variables_correctly_set(self, shell): alias = shell.app_alias('fuck') assert "fuck () {" in alias assert 'TF_SHELL=zsh' in alias assert "TF_ALIAS=fuck" in alias assert 'PYTHONIOENCODING=utf-8' in alias assert 'TF_SHELL_ALIASES=$(alias)' in alias def test_get_history(self, history_lines, shell): history_lines([': 1432613911:0;ls', ': 1432613916:0;rm']) assert list(shell.get_history()) == ['ls', 'rm'] def test_how_to_configure(self, shell, config_exists): config_exists.return_value = True assert shell.how_to_configure().can_configure_automatically def test_how_to_configure_when_config_not_found(self, shell, config_exists): config_exists.return_value = False assert not shell.how_to_configure().can_configure_automatically def test_info(self, shell, Popen): Popen.return_value.stdout.read.side_effect = [b'3.5.9'] assert shell.info() == 'ZSH 3.5.9' def test_get_version_error(self, shell, Popen): Popen.return_value.stdout.read.side_effect = OSError with pytest.raises(OSError): shell._get_version() assert Popen.call_args[0][0] == ['zsh', '-c', 'echo $ZSH_VERSION']
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/shells/__init__.py
tests/shells/__init__.py
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/shells/test_bash.py
tests/shells/test_bash.py
# -*- coding: utf-8 -*- import os import pytest from thefuck.shells import Bash @pytest.mark.usefixtures('isfile', 'no_memoize', 'no_cache') class TestBash(object): @pytest.fixture def shell(self): return Bash() @pytest.fixture(autouse=True) def Popen(self, mocker): mock = mocker.patch('thefuck.shells.bash.Popen') return mock @pytest.fixture(autouse=True) def shell_aliases(self): os.environ['TF_SHELL_ALIASES'] = ( 'alias fuck=\'eval $(thefuck $(fc -ln -1))\'\n' 'alias l=\'ls -CF\'\n' 'alias la=\'ls -A\'\n' 'alias ll=\'ls -alF\'') @pytest.mark.parametrize('before, after', [ ('pwd', 'pwd'), ('fuck', 'eval $(thefuck $(fc -ln -1))'), ('awk', 'awk'), ('ll', 'ls -alF')]) def test_from_shell(self, before, after, shell): assert shell.from_shell(before) == after def test_to_shell(self, shell): assert shell.to_shell('pwd') == 'pwd' def test_and_(self, shell): assert shell.and_('ls', 'cd') == 'ls && cd' def test_or_(self, shell): assert shell.or_('ls', 'cd') == 'ls || cd' def test_get_aliases(self, shell): assert shell.get_aliases() == {'fuck': 'eval $(thefuck $(fc -ln -1))', 'l': 'ls -CF', 'la': 'ls -A', 'll': 'ls -alF'} def test_app_alias(self, shell): assert 'fuck () {' in shell.app_alias('fuck') assert 'FUCK () {' in shell.app_alias('FUCK') assert 'thefuck' in shell.app_alias('fuck') assert 'PYTHONIOENCODING' in shell.app_alias('fuck') def test_app_alias_variables_correctly_set(self, shell): alias = shell.app_alias('fuck') assert "fuck () {" in alias assert 'TF_SHELL=bash' in alias assert "TF_ALIAS=fuck" in alias assert 'PYTHONIOENCODING=utf-8' in alias assert 'TF_SHELL_ALIASES=$(alias)' in alias def test_get_history(self, history_lines, shell): history_lines(['ls', 'rm']) assert list(shell.get_history()) == ['ls', 'rm'] def test_split_command(self, shell): command = 'git log -p' command_parts = ['git', 'log', '-p'] assert shell.split_command(command) == command_parts def test_how_to_configure(self, shell, config_exists): config_exists.return_value = True assert shell.how_to_configure().can_configure_automatically def test_how_to_configure_when_config_not_found(self, shell, config_exists): config_exists.return_value = False assert not shell.how_to_configure().can_configure_automatically def test_info(self, shell, Popen): Popen.return_value.stdout.read.side_effect = [b'3.5.9'] assert shell.info() == 'Bash 3.5.9' def test_get_version_error(self, shell, Popen): Popen.return_value.stdout.read.side_effect = OSError with pytest.raises(OSError): shell._get_version() assert Popen.call_args[0][0] == ['bash', '-c', 'echo $BASH_VERSION']
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/shells/test_generic.py
tests/shells/test_generic.py
# -*- coding: utf-8 -*- import pytest from thefuck.shells import Generic class TestGeneric(object): @pytest.fixture def shell(self): return Generic() def test_from_shell(self, shell): assert shell.from_shell('pwd') == 'pwd' def test_to_shell(self, shell): assert shell.to_shell('pwd') == 'pwd' def test_and_(self, shell): assert shell.and_('ls', 'cd') == 'ls && cd' def test_or_(self, shell): assert shell.or_('ls', 'cd') == 'ls || cd' def test_get_aliases(self, shell): assert shell.get_aliases() == {} def test_app_alias(self, shell): assert 'alias fuck' in shell.app_alias('fuck') assert 'alias FUCK' in shell.app_alias('FUCK') assert 'thefuck' in shell.app_alias('fuck') assert 'TF_ALIAS=fuck PYTHONIOENCODING' in shell.app_alias('fuck') assert 'PYTHONIOENCODING=utf-8 thefuck' in shell.app_alias('fuck') def test_get_history(self, history_lines, shell): history_lines(['ls', 'rm']) # We don't know what to do in generic shell with history lines, # so just ignore them: assert list(shell.get_history()) == [] def test_split_command(self, shell): assert shell.split_command('ls') == ['ls'] assert shell.split_command(u'echo café') == [u'echo', u'café'] def test_how_to_configure(self, shell): assert shell.how_to_configure() is None @pytest.mark.parametrize('side_effect, expected_info, warn', [ ([u'3.5.9'], u'Generic Shell 3.5.9', False), ([OSError], u'Generic Shell', True), ]) def test_info(self, side_effect, expected_info, warn, shell, mocker): warn_mock = mocker.patch('thefuck.shells.generic.warn') shell._get_version = mocker.Mock(side_effect=side_effect) assert shell.info() == expected_info assert warn_mock.called is warn assert shell._get_version.called
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/functional/test_tcsh.py
tests/functional/test_tcsh.py
import pytest from tests.functional.plots import with_confirmation, without_confirmation, \ refuse_with_confirmation, select_command_with_arrows containers = ((u'thefuck/python3', u'', u'tcsh'), (u'thefuck/python2', u'', u'tcsh')) @pytest.fixture(params=containers) def proc(request, spawnu, TIMEOUT): proc = spawnu(*request.param) proc.sendline(u'tcsh') proc.sendline(u'setenv PYTHONIOENCODING utf8') proc.sendline(u'eval `thefuck --alias`') return proc @pytest.mark.functional def test_with_confirmation(proc, TIMEOUT): with_confirmation(proc, TIMEOUT) @pytest.mark.functional def test_select_command_with_arrows(proc, TIMEOUT): select_command_with_arrows(proc, TIMEOUT) @pytest.mark.functional def test_refuse_with_confirmation(proc, TIMEOUT): refuse_with_confirmation(proc, TIMEOUT) @pytest.mark.functional def test_without_confirmation(proc, TIMEOUT): without_confirmation(proc, TIMEOUT) # TODO: ensure that history changes.
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/functional/plots.py
tests/functional/plots.py
def _set_confirmation(proc, require): proc.sendline(u'mkdir -p ~/.thefuck') proc.sendline( u'echo "require_confirmation = {}" > ~/.thefuck/settings.py'.format( require)) def with_confirmation(proc, TIMEOUT): """Ensures that command can be fixed when confirmation enabled.""" _set_confirmation(proc, True) proc.sendline(u'ehco test') proc.sendline(u'fuck') assert proc.expect([TIMEOUT, u'echo test']) assert proc.expect([TIMEOUT, u'enter']) assert proc.expect_exact([TIMEOUT, u'ctrl+c']) proc.send('\n') assert proc.expect([TIMEOUT, u'test']) def history_changed(proc, TIMEOUT, *to): """Ensures that history changed.""" proc.send('\033[A') pattern = [TIMEOUT] pattern.extend(to) assert proc.expect(pattern) def history_not_changed(proc, TIMEOUT): """Ensures that history not changed.""" proc.send('\033[A') assert proc.expect([TIMEOUT, u'fuck']) def select_command_with_arrows(proc, TIMEOUT): """Ensures that command can be selected with arrow keys.""" _set_confirmation(proc, True) proc.sendline(u'git h') assert proc.expect([TIMEOUT, u"git: 'h' is not a git command."]) proc.sendline(u'fuck') assert proc.expect([TIMEOUT, u'git show']) proc.send('\033[B') assert proc.expect([TIMEOUT, u'git push']) proc.send('\033[B') assert proc.expect([TIMEOUT, u'git help', u'git hook']) proc.send('\033[A') assert proc.expect([TIMEOUT, u'git push']) proc.send('\033[B') assert proc.expect([TIMEOUT, u'git help', u'git hook']) proc.send('\n') assert proc.expect([TIMEOUT, u'usage', u'fatal: not a git repository']) def refuse_with_confirmation(proc, TIMEOUT): """Ensures that fix can be refused when confirmation enabled.""" _set_confirmation(proc, True) proc.sendline(u'ehco test') proc.sendline(u'fuck') assert proc.expect([TIMEOUT, u'echo test']) assert proc.expect([TIMEOUT, u'enter']) assert proc.expect_exact([TIMEOUT, u'ctrl+c']) proc.send('\003') assert proc.expect([TIMEOUT, u'Aborted']) def without_confirmation(proc, TIMEOUT): """Ensures that command can be fixed when confirmation disabled.""" _set_confirmation(proc, False) proc.sendline(u'ehco test') proc.sendline(u'fuck') assert proc.expect([TIMEOUT, u'echo test']) assert proc.expect([TIMEOUT, u'test']) def how_to_configure(proc, TIMEOUT): proc.sendline(u'fuck') assert proc.expect([TIMEOUT, u"alias isn't configured"])
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/functional/test_fish.py
tests/functional/test_fish.py
import pytest from tests.functional.plots import with_confirmation, without_confirmation, \ refuse_with_confirmation, select_command_with_arrows containers = ((u'thefuck/python3', u'', u'fish'), (u'thefuck/python2', u'', u'fish')) @pytest.fixture(params=containers) def proc(request, spawnu, TIMEOUT): proc = spawnu(*request.param) proc.sendline(u'thefuck --alias > ~/.config/fish/config.fish') proc.sendline(u'fish') return proc @pytest.mark.functional def test_with_confirmation(proc, TIMEOUT): with_confirmation(proc, TIMEOUT) @pytest.mark.functional def test_select_command_with_arrows(proc, TIMEOUT): select_command_with_arrows(proc, TIMEOUT) @pytest.mark.functional def test_refuse_with_confirmation(proc, TIMEOUT): refuse_with_confirmation(proc, TIMEOUT) @pytest.mark.functional def test_without_confirmation(proc, TIMEOUT): without_confirmation(proc, TIMEOUT) # TODO: ensure that history changes.
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/functional/conftest.py
tests/functional/conftest.py
import pytest from pytest_docker_pexpect.docker import run as pexpect_docker_run, \ stats as pexpect_docker_stats @pytest.fixture(autouse=True) def build_container_mock(mocker): return mocker.patch('pytest_docker_pexpect.docker.build_container') def run_side_effect(*args, **kwargs): container_id = pexpect_docker_run(*args, **kwargs) pexpect_docker_stats(container_id) return container_id @pytest.fixture(autouse=True) def run_mock(mocker): return mocker.patch('pytest_docker_pexpect.docker.run', side_effect=run_side_effect)
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/functional/test_zsh.py
tests/functional/test_zsh.py
import pytest from tests.functional.plots import with_confirmation, without_confirmation, \ refuse_with_confirmation, history_changed, history_not_changed, \ select_command_with_arrows, how_to_configure python_3 = (u'thefuck/python3', u'', u'sh') python_2 = (u'thefuck/python2', u'', u'sh') init_zshrc = u'''echo ' export SHELL=/usr/bin/zsh export HISTFILE=~/.zsh_history echo > $HISTFILE export SAVEHIST=100 export HISTSIZE=100 eval $(thefuck --alias {}) setopt INC_APPEND_HISTORY echo "instant mode ready: $THEFUCK_INSTANT_MODE" ' > ~/.zshrc''' @pytest.fixture(params=[(python_3, False), (python_3, True), (python_2, False)]) def proc(request, spawnu, TIMEOUT): container, instant_mode = request.param proc = spawnu(*container) proc.sendline(init_zshrc.format( u'--enable-experimental-instant-mode' if instant_mode else '')) proc.sendline(u"zsh") if instant_mode: assert proc.expect([TIMEOUT, u'instant mode ready: True']) return proc @pytest.mark.functional def test_with_confirmation(proc, TIMEOUT): with_confirmation(proc, TIMEOUT) history_changed(proc, TIMEOUT, u'echo test') @pytest.mark.functional def test_select_command_with_arrows(proc, TIMEOUT): select_command_with_arrows(proc, TIMEOUT) history_changed(proc, TIMEOUT, u'git help', u'git hook') @pytest.mark.functional def test_refuse_with_confirmation(proc, TIMEOUT): refuse_with_confirmation(proc, TIMEOUT) history_not_changed(proc, TIMEOUT) @pytest.mark.functional def test_without_confirmation(proc, TIMEOUT): without_confirmation(proc, TIMEOUT) history_changed(proc, TIMEOUT, u'echo test') @pytest.mark.functional def test_how_to_configure_alias(proc, TIMEOUT): proc.sendline(u'unfunction fuck') how_to_configure(proc, TIMEOUT)
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/functional/__init__.py
tests/functional/__init__.py
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/tests/functional/test_bash.py
tests/functional/test_bash.py
import pytest from tests.functional.plots import with_confirmation, without_confirmation, \ refuse_with_confirmation, history_changed, history_not_changed, \ select_command_with_arrows, how_to_configure python_3 = (u'thefuck/python3', u'', u'sh') python_2 = (u'thefuck/python2', u'', u'sh') init_bashrc = u'''echo ' export SHELL=/bin/bash export PS1="$ " echo > $HISTFILE eval $(thefuck --alias {}) echo "instant mode ready: $THEFUCK_INSTANT_MODE" ' > ~/.bashrc''' @pytest.fixture(params=[(python_3, False), (python_3, True), (python_2, False)]) def proc(request, spawnu, TIMEOUT): container, instant_mode = request.param proc = spawnu(*container) proc.sendline(init_bashrc.format( u'--enable-experimental-instant-mode' if instant_mode else '')) proc.sendline(u"bash") if instant_mode: assert proc.expect([TIMEOUT, u'instant mode ready: True']) return proc @pytest.mark.functional def test_with_confirmation(proc, TIMEOUT): with_confirmation(proc, TIMEOUT) history_changed(proc, TIMEOUT, u'echo test') @pytest.mark.functional def test_select_command_with_arrows(proc, TIMEOUT): select_command_with_arrows(proc, TIMEOUT) history_changed(proc, TIMEOUT, u'git help', u'git hook') @pytest.mark.functional def test_refuse_with_confirmation(proc, TIMEOUT): refuse_with_confirmation(proc, TIMEOUT) history_not_changed(proc, TIMEOUT) @pytest.mark.functional def test_without_confirmation(proc, TIMEOUT): without_confirmation(proc, TIMEOUT) history_changed(proc, TIMEOUT, u'echo test') @pytest.mark.functional def test_how_to_configure_alias(proc, TIMEOUT): proc.sendline('unset -f fuck') how_to_configure(proc, TIMEOUT)
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/thefuck/corrector.py
thefuck/corrector.py
import sys from .conf import settings from .types import Rule from .system import Path from . import logs def get_loaded_rules(rules_paths): """Yields all available rules. :type rules_paths: [Path] :rtype: Iterable[Rule] """ for path in rules_paths: if path.name != '__init__.py': rule = Rule.from_path(path) if rule and rule.is_enabled: yield rule def get_rules_import_paths(): """Yields all rules import paths. :rtype: Iterable[Path] """ # Bundled rules: yield Path(__file__).parent.joinpath('rules') # Rules defined by user: yield settings.user_dir.joinpath('rules') # Packages with third-party rules: for path in sys.path: for contrib_module in Path(path).glob('thefuck_contrib_*'): contrib_rules = contrib_module.joinpath('rules') if contrib_rules.is_dir(): yield contrib_rules def get_rules(): """Returns all enabled rules. :rtype: [Rule] """ paths = [rule_path for path in get_rules_import_paths() for rule_path in sorted(path.glob('*.py'))] return sorted(get_loaded_rules(paths), key=lambda rule: rule.priority) def organize_commands(corrected_commands): """Yields sorted commands without duplicates. :type corrected_commands: Iterable[thefuck.types.CorrectedCommand] :rtype: Iterable[thefuck.types.CorrectedCommand] """ try: first_command = next(corrected_commands) yield first_command except StopIteration: return without_duplicates = { command for command in sorted( corrected_commands, key=lambda command: command.priority) if command != first_command} sorted_commands = sorted( without_duplicates, key=lambda corrected_command: corrected_command.priority) logs.debug(u'Corrected commands: {}'.format( ', '.join(u'{}'.format(cmd) for cmd in [first_command] + sorted_commands))) for command in sorted_commands: yield command def get_corrected_commands(command): """Returns generator with sorted and unique corrected commands. :type command: thefuck.types.Command :rtype: Iterable[thefuck.types.CorrectedCommand] """ corrected_commands = ( corrected for rule in get_rules() if rule.is_match(command) for corrected in rule.get_corrected_commands(command)) return organize_commands(corrected_commands)
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/thefuck/exceptions.py
thefuck/exceptions.py
class EmptyCommand(Exception): """Raised when empty command passed to `thefuck`.""" class NoRuleMatched(Exception): """Raised when no rule matched for some command.""" class ScriptNotInLog(Exception): """Script not found in log."""
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/thefuck/argument_parser.py
thefuck/argument_parser.py
import sys from argparse import ArgumentParser, SUPPRESS from .const import ARGUMENT_PLACEHOLDER from .utils import get_alias class Parser(object): """Argument parser that can handle arguments with our special placeholder. """ def __init__(self): self._parser = ArgumentParser(prog='thefuck', add_help=False) self._add_arguments() def _add_arguments(self): """Adds arguments to parser.""" self._parser.add_argument( '-v', '--version', action='store_true', help="show program's version number and exit") self._parser.add_argument( '-a', '--alias', nargs='?', const=get_alias(), help='[custom-alias-name] prints alias for current shell') self._parser.add_argument( '-l', '--shell-logger', action='store', help='log shell output to the file') self._parser.add_argument( '--enable-experimental-instant-mode', action='store_true', help='enable experimental instant mode, use on your own risk') self._parser.add_argument( '-h', '--help', action='store_true', help='show this help message and exit') self._add_conflicting_arguments() self._parser.add_argument( '-d', '--debug', action='store_true', help='enable debug output') self._parser.add_argument( '--force-command', action='store', help=SUPPRESS) self._parser.add_argument( 'command', nargs='*', help='command that should be fixed') def _add_conflicting_arguments(self): """It's too dangerous to use `-y` and `-r` together.""" group = self._parser.add_mutually_exclusive_group() group.add_argument( '-y', '--yes', '--yeah', '--hard', action='store_true', help='execute fixed command without confirmation') group.add_argument( '-r', '--repeat', action='store_true', help='repeat on failure') def _prepare_arguments(self, argv): """Prepares arguments by: - removing placeholder and moving arguments after it to beginning, we need this to distinguish arguments from `command` with ours; - adding `--` before `command`, so our parse would ignore arguments of `command`. """ if ARGUMENT_PLACEHOLDER in argv: index = argv.index(ARGUMENT_PLACEHOLDER) return argv[index + 1:] + ['--'] + argv[:index] elif argv and not argv[0].startswith('-') and argv[0] != '--': return ['--'] + argv else: return argv def parse(self, argv): arguments = self._prepare_arguments(argv[1:]) return self._parser.parse_args(arguments) def print_usage(self): self._parser.print_usage(sys.stderr) def print_help(self): self._parser.print_help(sys.stderr)
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/thefuck/const.py
thefuck/const.py
# -*- encoding: utf-8 -*- class _GenConst(object): def __init__(self, name): self._name = name def __repr__(self): return u'<const: {}>'.format(self._name) KEY_UP = _GenConst('↑') KEY_DOWN = _GenConst('↓') KEY_CTRL_C = _GenConst('Ctrl+C') KEY_CTRL_N = _GenConst('Ctrl+N') KEY_CTRL_P = _GenConst('Ctrl+P') KEY_MAPPING = {'\x0e': KEY_CTRL_N, '\x03': KEY_CTRL_C, '\x10': KEY_CTRL_P} ACTION_SELECT = _GenConst('select') ACTION_ABORT = _GenConst('abort') ACTION_PREVIOUS = _GenConst('previous') ACTION_NEXT = _GenConst('next') ALL_ENABLED = _GenConst('All rules enabled') DEFAULT_RULES = [ALL_ENABLED] DEFAULT_PRIORITY = 1000 DEFAULT_SETTINGS = {'rules': DEFAULT_RULES, 'exclude_rules': [], 'wait_command': 3, 'require_confirmation': True, 'no_colors': False, 'debug': False, 'priority': {}, 'history_limit': None, 'alter_history': True, 'wait_slow_command': 15, 'slow_commands': ['lein', 'react-native', 'gradle', './gradlew', 'vagrant'], 'repeat': False, 'instant_mode': False, 'num_close_matches': 3, 'env': {'LC_ALL': 'C', 'LANG': 'C', 'GIT_TRACE': '1'}, 'excluded_search_path_prefixes': []} ENV_TO_ATTR = {'THEFUCK_RULES': 'rules', 'THEFUCK_EXCLUDE_RULES': 'exclude_rules', 'THEFUCK_WAIT_COMMAND': 'wait_command', 'THEFUCK_REQUIRE_CONFIRMATION': 'require_confirmation', 'THEFUCK_NO_COLORS': 'no_colors', 'THEFUCK_DEBUG': 'debug', 'THEFUCK_PRIORITY': 'priority', 'THEFUCK_HISTORY_LIMIT': 'history_limit', 'THEFUCK_ALTER_HISTORY': 'alter_history', 'THEFUCK_WAIT_SLOW_COMMAND': 'wait_slow_command', 'THEFUCK_SLOW_COMMANDS': 'slow_commands', 'THEFUCK_REPEAT': 'repeat', 'THEFUCK_INSTANT_MODE': 'instant_mode', 'THEFUCK_NUM_CLOSE_MATCHES': 'num_close_matches', 'THEFUCK_EXCLUDED_SEARCH_PATH_PREFIXES': 'excluded_search_path_prefixes'} SETTINGS_HEADER = u"""# The Fuck settings file # # The rules are defined as in the example bellow: # # rules = ['cd_parent', 'git_push', 'python_command', 'sudo'] # # The default values are as follows. Uncomment and change to fit your needs. # See https://github.com/nvbn/thefuck#settings for more information. # """ ARGUMENT_PLACEHOLDER = 'THEFUCK_ARGUMENT_PLACEHOLDER' CONFIGURATION_TIMEOUT = 60 USER_COMMAND_MARK = u'\u200B' * 10 LOG_SIZE_IN_BYTES = 1024 * 1024 LOG_SIZE_TO_CLEAN = 10 * 1024 DIFF_WITH_ALIAS = 0.5 SHELL_LOGGER_SOCKET_ENV = 'SHELL_LOGGER_SOCKET' SHELL_LOGGER_LIMIT = 5
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/thefuck/ui.py
thefuck/ui.py
# -*- encoding: utf-8 -*- import sys from .conf import settings from .exceptions import NoRuleMatched from .system import get_key from .utils import get_alias from . import logs, const def read_actions(): """Yields actions for pressed keys.""" while True: key = get_key() # Handle arrows, j/k (qwerty), and n/e (colemak) if key in (const.KEY_UP, const.KEY_CTRL_N, 'k', 'e'): yield const.ACTION_PREVIOUS elif key in (const.KEY_DOWN, const.KEY_CTRL_P, 'j', 'n'): yield const.ACTION_NEXT elif key in (const.KEY_CTRL_C, 'q'): yield const.ACTION_ABORT elif key in ('\n', '\r'): yield const.ACTION_SELECT class CommandSelector(object): """Helper for selecting rule from rules list.""" def __init__(self, commands): """:type commands: Iterable[thefuck.types.CorrectedCommand]""" self._commands_gen = commands try: self._commands = [next(self._commands_gen)] except StopIteration: raise NoRuleMatched self._realised = False self._index = 0 def _realise(self): if not self._realised: self._commands += list(self._commands_gen) self._realised = True def next(self): self._realise() self._index = (self._index + 1) % len(self._commands) def previous(self): self._realise() self._index = (self._index - 1) % len(self._commands) @property def value(self): """:rtype thefuck.types.CorrectedCommand""" return self._commands[self._index] def select_command(corrected_commands): """Returns: - the first command when confirmation disabled; - None when ctrl+c pressed; - selected command. :type corrected_commands: Iterable[thefuck.types.CorrectedCommand] :rtype: thefuck.types.CorrectedCommand | None """ try: selector = CommandSelector(corrected_commands) except NoRuleMatched: logs.failed('No fucks given' if get_alias() == 'fuck' else 'Nothing found') return if not settings.require_confirmation: logs.show_corrected_command(selector.value) return selector.value logs.confirm_text(selector.value) for action in read_actions(): if action == const.ACTION_SELECT: sys.stderr.write('\n') return selector.value elif action == const.ACTION_ABORT: logs.failed('\nAborted') return elif action == const.ACTION_PREVIOUS: selector.previous() logs.confirm_text(selector.value) elif action == const.ACTION_NEXT: selector.next() logs.confirm_text(selector.value)
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/thefuck/utils.py
thefuck/utils.py
import atexit import os import pickle import re import shelve import sys import six from decorator import decorator from difflib import get_close_matches as difflib_get_close_matches from functools import wraps from .logs import warn, exception from .conf import settings from .system import Path DEVNULL = open(os.devnull, 'w') if six.PY2: import anydbm shelve_open_error = anydbm.error else: import dbm shelve_open_error = dbm.error def memoize(fn): """Caches previous calls to the function.""" memo = {} @wraps(fn) def wrapper(*args, **kwargs): if not memoize.disabled: key = pickle.dumps((args, kwargs)) if key not in memo: memo[key] = fn(*args, **kwargs) value = memo[key] else: # Memoize is disabled, call the function value = fn(*args, **kwargs) return value return wrapper memoize.disabled = False @memoize def which(program): """Returns `program` path or `None`.""" try: from shutil import which return which(program) except ImportError: def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None def default_settings(params): """Adds default values to settings if it not presented. Usage: @default_settings({'apt': '/usr/bin/apt'}) def match(command): print(settings.apt) """ def _default_settings(fn, command): for k, w in params.items(): settings.setdefault(k, w) return fn(command) return decorator(_default_settings) def get_closest(word, possibilities, cutoff=0.6, fallback_to_first=True): """Returns closest match or just first from possibilities.""" possibilities = list(possibilities) try: return difflib_get_close_matches(word, possibilities, 1, cutoff)[0] except IndexError: if fallback_to_first: return possibilities[0] def get_close_matches(word, possibilities, n=None, cutoff=0.6): """Overrides `difflib.get_close_match` to control argument `n`.""" if n is None: n = settings.num_close_matches return difflib_get_close_matches(word, possibilities, n, cutoff) def include_path_in_search(path): return not any(path.startswith(x) for x in settings.excluded_search_path_prefixes) @memoize def get_all_executables(): from thefuck.shells import shell def _safe(fn, fallback): try: return fn() except OSError: return fallback tf_alias = get_alias() tf_entry_points = ['thefuck', 'fuck'] bins = [exe.name.decode('utf8') if six.PY2 else exe.name for path in os.environ.get('PATH', '').split(os.pathsep) if include_path_in_search(path) for exe in _safe(lambda: list(Path(path).iterdir()), []) if not _safe(exe.is_dir, True) and exe.name not in tf_entry_points] aliases = [alias.decode('utf8') if six.PY2 else alias for alias in shell.get_aliases() if alias != tf_alias] return bins + aliases def replace_argument(script, from_, to): """Replaces command line argument.""" replaced_in_the_end = re.sub(u' {}$'.format(re.escape(from_)), u' {}'.format(to), script, count=1) if replaced_in_the_end != script: return replaced_in_the_end else: return script.replace( u' {} '.format(from_), u' {} '.format(to), 1) @decorator def eager(fn, *args, **kwargs): return list(fn(*args, **kwargs)) @eager def get_all_matched_commands(stderr, separator='Did you mean'): if not isinstance(separator, list): separator = [separator] should_yield = False for line in stderr.split('\n'): for sep in separator: if sep in line: should_yield = True break else: if should_yield and line: yield line.strip() def replace_command(command, broken, matched): """Helper for *_no_command rules.""" new_cmds = get_close_matches(broken, matched, cutoff=0.1) return [replace_argument(command.script, broken, new_cmd.strip()) for new_cmd in new_cmds] @memoize def is_app(command, *app_names, **kwargs): """Returns `True` if command is call to one of passed app names.""" at_least = kwargs.pop('at_least', 0) if kwargs: raise TypeError("got an unexpected keyword argument '{}'".format(kwargs.keys())) if len(command.script_parts) > at_least: return os.path.basename(command.script_parts[0]) in app_names return False def for_app(*app_names, **kwargs): """Specifies that matching script is for one of app names.""" def _for_app(fn, command): if is_app(command, *app_names, **kwargs): return fn(command) else: return False return decorator(_for_app) class Cache(object): """Lazy read cache and save changes at exit.""" def __init__(self): self._db = None def _init_db(self): try: self._setup_db() except Exception: exception("Unable to init cache", sys.exc_info()) self._db = {} def _setup_db(self): cache_dir = self._get_cache_dir() cache_path = Path(cache_dir).joinpath('thefuck').as_posix() try: self._db = shelve.open(cache_path) except shelve_open_error + (ImportError,): # Caused when switching between Python versions warn("Removing possibly out-dated cache") os.remove(cache_path) self._db = shelve.open(cache_path) atexit.register(self._db.close) def _get_cache_dir(self): default_xdg_cache_dir = os.path.expanduser("~/.cache") cache_dir = os.getenv("XDG_CACHE_HOME", default_xdg_cache_dir) # Ensure the cache_path exists, Python 2 does not have the exist_ok # parameter try: os.makedirs(cache_dir) except OSError: if not os.path.isdir(cache_dir): raise return cache_dir def _get_mtime(self, path): try: return str(os.path.getmtime(path)) except OSError: return '0' def _get_key(self, fn, depends_on, args, kwargs): parts = (fn.__module__, repr(fn).split('at')[0], depends_on, args, kwargs) return str(pickle.dumps(parts)) def get_value(self, fn, depends_on, args, kwargs): if self._db is None: self._init_db() depends_on = [Path(name).expanduser().absolute().as_posix() for name in depends_on] key = self._get_key(fn, depends_on, args, kwargs) etag = '.'.join(self._get_mtime(path) for path in depends_on) if self._db.get(key, {}).get('etag') == etag: return self._db[key]['value'] else: value = fn(*args, **kwargs) self._db[key] = {'etag': etag, 'value': value} return value _cache = Cache() def cache(*depends_on): """Caches function result in temporary file. Cache will be expired when modification date of files from `depends_on` will be changed. Only functions should be wrapped in `cache`, not methods. """ def cache_decorator(fn): @memoize @wraps(fn) def wrapper(*args, **kwargs): if cache.disabled: return fn(*args, **kwargs) else: return _cache.get_value(fn, depends_on, args, kwargs) return wrapper return cache_decorator cache.disabled = False def get_installation_version(): try: from importlib.metadata import version return version('thefuck') except ImportError: import pkg_resources return pkg_resources.require('thefuck')[0].version def get_alias(): return os.environ.get('TF_ALIAS', 'fuck') @memoize def get_valid_history_without_current(command): def _not_corrected(history, tf_alias): """Returns all lines from history except that comes before `fuck`.""" previous = None for line in history: if previous is not None and line != tf_alias: yield previous previous = line if history: yield history[-1] from thefuck.shells import shell history = shell.get_history() tf_alias = get_alias() executables = set(get_all_executables())\ .union(shell.get_builtin_commands()) return [line for line in _not_corrected(history, tf_alias) if not line.startswith(tf_alias) and not line == command.script and line.split(' ')[0] in executables] def format_raw_script(raw_script): """Creates single script from a list of script parts. :type raw_script: [basestring] :rtype: basestring """ if six.PY2: script = ' '.join(arg.decode('utf-8') for arg in raw_script) else: script = ' '.join(raw_script) return script.lstrip()
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/thefuck/__init__.py
thefuck/__init__.py
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/thefuck/types.py
thefuck/types.py
import os import sys from . import logs from .shells import shell from .conf import settings, load_source from .const import DEFAULT_PRIORITY, ALL_ENABLED from .exceptions import EmptyCommand from .utils import get_alias, format_raw_script from .output_readers import get_output class Command(object): """Command that should be fixed.""" def __init__(self, script, output): """Initializes command with given values. :type script: basestring :type output: basestring """ self.script = script self.output = output @property def stdout(self): logs.warn('`stdout` is deprecated, please use `output` instead') return self.output @property def stderr(self): logs.warn('`stderr` is deprecated, please use `output` instead') return self.output @property def script_parts(self): if not hasattr(self, '_script_parts'): try: self._script_parts = shell.split_command(self.script) except Exception: logs.debug(u"Can't split command script {} because:\n {}".format( self, sys.exc_info())) self._script_parts = [] return self._script_parts def __eq__(self, other): if isinstance(other, Command): return (self.script, self.output) == (other.script, other.output) else: return False def __repr__(self): return u'Command(script={}, output={})'.format( self.script, self.output) def update(self, **kwargs): """Returns new command with replaced fields. :rtype: Command """ kwargs.setdefault('script', self.script) kwargs.setdefault('output', self.output) return Command(**kwargs) @classmethod def from_raw_script(cls, raw_script): """Creates instance of `Command` from a list of script parts. :type raw_script: [basestring] :rtype: Command :raises: EmptyCommand """ script = format_raw_script(raw_script) if not script: raise EmptyCommand expanded = shell.from_shell(script) output = get_output(script, expanded) return cls(expanded, output) class Rule(object): """Rule for fixing commands.""" def __init__(self, name, match, get_new_command, enabled_by_default, side_effect, priority, requires_output): """Initializes rule with given fields. :type name: basestring :type match: (Command) -> bool :type get_new_command: (Command) -> (basestring | [basestring]) :type enabled_by_default: boolean :type side_effect: (Command, basestring) -> None :type priority: int :type requires_output: bool """ self.name = name self.match = match self.get_new_command = get_new_command self.enabled_by_default = enabled_by_default self.side_effect = side_effect self.priority = priority self.requires_output = requires_output def __eq__(self, other): if isinstance(other, Rule): return ((self.name, self.match, self.get_new_command, self.enabled_by_default, self.side_effect, self.priority, self.requires_output) == (other.name, other.match, other.get_new_command, other.enabled_by_default, other.side_effect, other.priority, other.requires_output)) else: return False def __repr__(self): return 'Rule(name={}, match={}, get_new_command={}, ' \ 'enabled_by_default={}, side_effect={}, ' \ 'priority={}, requires_output={})'.format( self.name, self.match, self.get_new_command, self.enabled_by_default, self.side_effect, self.priority, self.requires_output) @classmethod def from_path(cls, path): """Creates rule instance from path. :type path: pathlib.Path :rtype: Rule """ name = path.name[:-3] if name in settings.exclude_rules: logs.debug(u'Ignoring excluded rule: {}'.format(name)) return with logs.debug_time(u'Importing rule: {};'.format(name)): try: rule_module = load_source(name, str(path)) except Exception: logs.exception(u"Rule {} failed to load".format(name), sys.exc_info()) return priority = getattr(rule_module, 'priority', DEFAULT_PRIORITY) return cls(name, rule_module.match, rule_module.get_new_command, getattr(rule_module, 'enabled_by_default', True), getattr(rule_module, 'side_effect', None), settings.priority.get(name, priority), getattr(rule_module, 'requires_output', True)) @property def is_enabled(self): """Returns `True` when rule enabled. :rtype: bool """ return ( self.name in settings.rules or self.enabled_by_default and ALL_ENABLED in settings.rules ) def is_match(self, command): """Returns `True` if rule matches the command. :type command: Command :rtype: bool """ if command.output is None and self.requires_output: return False try: with logs.debug_time(u'Trying rule: {};'.format(self.name)): if self.match(command): return True except Exception: logs.rule_failed(self, sys.exc_info()) def get_corrected_commands(self, command): """Returns generator with corrected commands. :type command: Command :rtype: Iterable[CorrectedCommand] """ new_commands = self.get_new_command(command) if not isinstance(new_commands, list): new_commands = (new_commands,) for n, new_command in enumerate(new_commands): yield CorrectedCommand(script=new_command, side_effect=self.side_effect, priority=(n + 1) * self.priority) class CorrectedCommand(object): """Corrected by rule command.""" def __init__(self, script, side_effect, priority): """Initializes instance with given fields. :type script: basestring :type side_effect: (Command, basestring) -> None :type priority: int """ self.script = script self.side_effect = side_effect self.priority = priority def __eq__(self, other): """Ignores `priority` field.""" if isinstance(other, CorrectedCommand): return (other.script, other.side_effect) == \ (self.script, self.side_effect) else: return False def __hash__(self): return (self.script, self.side_effect).__hash__() def __repr__(self): return u'CorrectedCommand(script={}, side_effect={}, priority={})'.format( self.script, self.side_effect, self.priority) def _get_script(self): """Returns fixed commands script. If `settings.repeat` is `True`, appends command with second attempt of running fuck in case fixed command fails again. """ if settings.repeat: repeat_fuck = '{} --repeat {}--force-command {}'.format( get_alias(), '--debug ' if settings.debug else '', shell.quote(self.script)) return shell.or_(self.script, repeat_fuck) else: return self.script def run(self, old_cmd): """Runs command from rule for passed command. :type old_cmd: Command """ if self.side_effect: self.side_effect(old_cmd, self.script) if settings.alter_history: shell.put_to_history(self.script) # This depends on correct setting of PYTHONIOENCODING by the alias: logs.debug(u'PYTHONIOENCODING: {}'.format( os.environ.get('PYTHONIOENCODING', '!!not-set!!'))) sys.stdout.write(self._get_script())
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/thefuck/conf.py
thefuck/conf.py
import os import sys from warnings import warn from six import text_type from . import const from .system import Path try: import importlib.util def load_source(name, pathname, _file=None): module_spec = importlib.util.spec_from_file_location(name, pathname) module = importlib.util.module_from_spec(module_spec) module_spec.loader.exec_module(module) return module except ImportError: from imp import load_source class Settings(dict): def __getattr__(self, item): return self.get(item) def __setattr__(self, key, value): self[key] = value def init(self, args=None): """Fills `settings` with values from `settings.py` and env.""" from .logs import exception self._setup_user_dir() self._init_settings_file() try: self.update(self._settings_from_file()) except Exception: exception("Can't load settings from file", sys.exc_info()) try: self.update(self._settings_from_env()) except Exception: exception("Can't load settings from env", sys.exc_info()) self.update(self._settings_from_args(args)) def _init_settings_file(self): settings_path = self.user_dir.joinpath('settings.py') if not settings_path.is_file(): with settings_path.open(mode='w') as settings_file: settings_file.write(const.SETTINGS_HEADER) for setting in const.DEFAULT_SETTINGS.items(): settings_file.write(u'# {} = {}\n'.format(*setting)) def _get_user_dir_path(self): """Returns Path object representing the user config resource""" xdg_config_home = os.environ.get('XDG_CONFIG_HOME', '~/.config') user_dir = Path(xdg_config_home, 'thefuck').expanduser() legacy_user_dir = Path('~', '.thefuck').expanduser() # For backward compatibility use legacy '~/.thefuck' if it exists: if legacy_user_dir.is_dir(): warn(u'Config path {} is deprecated. Please move to {}'.format( legacy_user_dir, user_dir)) return legacy_user_dir else: return user_dir def _setup_user_dir(self): """Returns user config dir, create it when it doesn't exist.""" user_dir = self._get_user_dir_path() rules_dir = user_dir.joinpath('rules') if not rules_dir.is_dir(): rules_dir.mkdir(parents=True) self.user_dir = user_dir def _settings_from_file(self): """Loads settings from file.""" settings = load_source( 'settings', text_type(self.user_dir.joinpath('settings.py'))) return {key: getattr(settings, key) for key in const.DEFAULT_SETTINGS.keys() if hasattr(settings, key)} def _rules_from_env(self, val): """Transforms rules list from env-string to python.""" val = val.split(':') if 'DEFAULT_RULES' in val: val = const.DEFAULT_RULES + [rule for rule in val if rule != 'DEFAULT_RULES'] return val def _priority_from_env(self, val): """Gets priority pairs from env.""" for part in val.split(':'): try: rule, priority = part.split('=') yield rule, int(priority) except ValueError: continue def _val_from_env(self, env, attr): """Transforms env-strings to python.""" val = os.environ[env] if attr in ('rules', 'exclude_rules'): return self._rules_from_env(val) elif attr == 'priority': return dict(self._priority_from_env(val)) elif attr in ('wait_command', 'history_limit', 'wait_slow_command', 'num_close_matches'): return int(val) elif attr in ('require_confirmation', 'no_colors', 'debug', 'alter_history', 'instant_mode'): return val.lower() == 'true' elif attr in ('slow_commands', 'excluded_search_path_prefixes'): return val.split(':') else: return val def _settings_from_env(self): """Loads settings from env.""" return {attr: self._val_from_env(env, attr) for env, attr in const.ENV_TO_ATTR.items() if env in os.environ} def _settings_from_args(self, args): """Loads settings from args.""" if not args: return {} from_args = {} if args.yes: from_args['require_confirmation'] = not args.yes if args.debug: from_args['debug'] = args.debug if args.repeat: from_args['repeat'] = args.repeat return from_args settings = Settings(const.DEFAULT_SETTINGS)
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/thefuck/logs.py
thefuck/logs.py
# -*- encoding: utf-8 -*- from contextlib import contextmanager from datetime import datetime import sys from traceback import format_exception import colorama from .conf import settings from . import const def color(color_): """Utility for ability to disabling colored output.""" if settings.no_colors: return '' else: return color_ def warn(title): sys.stderr.write(u'{warn}[WARN] {title}{reset}\n'.format( warn=color(colorama.Back.RED + colorama.Fore.WHITE + colorama.Style.BRIGHT), reset=color(colorama.Style.RESET_ALL), title=title)) def exception(title, exc_info): sys.stderr.write( u'{warn}[WARN] {title}:{reset}\n{trace}' u'{warn}----------------------------{reset}\n\n'.format( warn=color(colorama.Back.RED + colorama.Fore.WHITE + colorama.Style.BRIGHT), reset=color(colorama.Style.RESET_ALL), title=title, trace=''.join(format_exception(*exc_info)))) def rule_failed(rule, exc_info): exception(u'Rule {}'.format(rule.name), exc_info) def failed(msg): sys.stderr.write(u'{red}{msg}{reset}\n'.format( msg=msg, red=color(colorama.Fore.RED), reset=color(colorama.Style.RESET_ALL))) def show_corrected_command(corrected_command): sys.stderr.write(u'{prefix}{bold}{script}{reset}{side_effect}\n'.format( prefix=const.USER_COMMAND_MARK, script=corrected_command.script, side_effect=u' (+side effect)' if corrected_command.side_effect else u'', bold=color(colorama.Style.BRIGHT), reset=color(colorama.Style.RESET_ALL))) def confirm_text(corrected_command): sys.stderr.write( (u'{prefix}{clear}{bold}{script}{reset}{side_effect} ' u'[{green}enter{reset}/{blue}↑{reset}/{blue}↓{reset}' u'/{red}ctrl+c{reset}]').format( prefix=const.USER_COMMAND_MARK, script=corrected_command.script, side_effect=' (+side effect)' if corrected_command.side_effect else '', clear='\033[1K\r', bold=color(colorama.Style.BRIGHT), green=color(colorama.Fore.GREEN), red=color(colorama.Fore.RED), reset=color(colorama.Style.RESET_ALL), blue=color(colorama.Fore.BLUE))) def debug(msg): if settings.debug: sys.stderr.write(u'{blue}{bold}DEBUG:{reset} {msg}\n'.format( msg=msg, reset=color(colorama.Style.RESET_ALL), blue=color(colorama.Fore.BLUE), bold=color(colorama.Style.BRIGHT))) @contextmanager def debug_time(msg): started = datetime.now() try: yield finally: debug(u'{} took: {}'.format(msg, datetime.now() - started)) def how_to_configure_alias(configuration_details): print(u"Seems like {bold}fuck{reset} alias isn't configured!".format( bold=color(colorama.Style.BRIGHT), reset=color(colorama.Style.RESET_ALL))) if configuration_details: print( u"Please put {bold}{content}{reset} in your " u"{bold}{path}{reset} and apply " u"changes with {bold}{reload}{reset} or restart your shell.".format( bold=color(colorama.Style.BRIGHT), reset=color(colorama.Style.RESET_ALL), **configuration_details._asdict())) if configuration_details.can_configure_automatically: print( u"Or run {bold}fuck{reset} a second time to configure" u" it automatically.".format( bold=color(colorama.Style.BRIGHT), reset=color(colorama.Style.RESET_ALL))) print(u'More details - https://github.com/nvbn/thefuck#manual-installation') def already_configured(configuration_details): print( u"Seems like {bold}fuck{reset} alias already configured!\n" u"For applying changes run {bold}{reload}{reset}" u" or restart your shell.".format( bold=color(colorama.Style.BRIGHT), reset=color(colorama.Style.RESET_ALL), reload=configuration_details.reload)) def configured_successfully(configuration_details): print( u"{bold}fuck{reset} alias configured successfully!\n" u"For applying changes run {bold}{reload}{reset}" u" or restart your shell.".format( bold=color(colorama.Style.BRIGHT), reset=color(colorama.Style.RESET_ALL), reload=configuration_details.reload)) def version(thefuck_version, python_version, shell_info): sys.stderr.write( u'The Fuck {} using Python {} and {}\n'.format(thefuck_version, python_version, shell_info))
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/thefuck/system/__init__.py
thefuck/system/__init__.py
import sys if sys.platform == 'win32': from .win32 import * # noqa: F401,F403 else: from .unix import * # noqa: F401,F403
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/thefuck/system/win32.py
thefuck/system/win32.py
import os import msvcrt import win_unicode_console from .. import const def init_output(): import colorama win_unicode_console.enable() colorama.init() def get_key(): ch = msvcrt.getwch() if ch in ('\x00', '\xe0'): # arrow or function key prefix? ch = msvcrt.getwch() # second call returns the actual key code if ch in const.KEY_MAPPING: return const.KEY_MAPPING[ch] if ch == 'H': return const.KEY_UP if ch == 'P': return const.KEY_DOWN return ch def open_command(arg): return 'cmd /c start ' + arg try: from pathlib import Path except ImportError: from pathlib2 import Path def _expanduser(self): return self.__class__(os.path.expanduser(str(self))) # pathlib's expanduser fails on windows, see http://bugs.python.org/issue19776 Path.expanduser = _expanduser
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/thefuck/system/unix.py
thefuck/system/unix.py
import os import sys import tty import termios import colorama from distutils.spawn import find_executable from .. import const init_output = colorama.init def getch(): fd = sys.stdin.fileno() old = termios.tcgetattr(fd) try: tty.setraw(fd) return sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old) def get_key(): ch = getch() if ch in const.KEY_MAPPING: return const.KEY_MAPPING[ch] elif ch == '\x1b': next_ch = getch() if next_ch == '[': last_ch = getch() if last_ch == 'A': return const.KEY_UP elif last_ch == 'B': return const.KEY_DOWN return ch def open_command(arg): if find_executable('xdg-open'): return 'xdg-open ' + arg return 'open ' + arg try: from pathlib import Path except ImportError: from pathlib2 import Path def _expanduser(self): return self.__class__(os.path.expanduser(str(self))) if not hasattr(Path, 'expanduser'): Path.expanduser = _expanduser
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/thefuck/entrypoints/shell_logger.py
thefuck/entrypoints/shell_logger.py
import array import fcntl from functools import partial import mmap import os import pty import signal import sys import termios import tty from .. import logs, const def _read(f, fd): data = os.read(fd, 1024) try: f.write(data) except ValueError: position = const.LOG_SIZE_IN_BYTES - const.LOG_SIZE_TO_CLEAN f.move(0, const.LOG_SIZE_TO_CLEAN, position) f.seek(position) f.write(b'\x00' * const.LOG_SIZE_TO_CLEAN) f.seek(position) return data def _set_pty_size(master_fd): buf = array.array('h', [0, 0, 0, 0]) fcntl.ioctl(pty.STDOUT_FILENO, termios.TIOCGWINSZ, buf, True) fcntl.ioctl(master_fd, termios.TIOCSWINSZ, buf) def _spawn(shell, master_read): """Create a spawned process. Modified version of pty.spawn with terminal size support. """ pid, master_fd = pty.fork() if pid == pty.CHILD: os.execlp(shell, shell) try: mode = tty.tcgetattr(pty.STDIN_FILENO) tty.setraw(pty.STDIN_FILENO) restore = True except tty.error: # This is the same as termios.error restore = False _set_pty_size(master_fd) signal.signal(signal.SIGWINCH, lambda *_: _set_pty_size(master_fd)) try: pty._copy(master_fd, master_read, pty._read) except OSError: if restore: tty.tcsetattr(pty.STDIN_FILENO, tty.TCSAFLUSH, mode) os.close(master_fd) return os.waitpid(pid, 0)[1] def shell_logger(output): """Logs shell output to the `output`. Works like unix script command with `-f` flag. """ if not os.environ.get('SHELL'): logs.warn("Shell logger doesn't support your platform.") sys.exit(1) fd = os.open(output, os.O_CREAT | os.O_TRUNC | os.O_RDWR) os.write(fd, b'\x00' * const.LOG_SIZE_IN_BYTES) buffer = mmap.mmap(fd, const.LOG_SIZE_IN_BYTES, mmap.MAP_SHARED, mmap.PROT_WRITE) return_code = _spawn(os.environ['SHELL'], partial(_read, buffer)) sys.exit(return_code)
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/thefuck/entrypoints/alias.py
thefuck/entrypoints/alias.py
import six from ..conf import settings from ..logs import warn from ..shells import shell from ..utils import which def _get_alias(known_args): if six.PY2: warn("The Fuck will drop Python 2 support soon, more details " "https://github.com/nvbn/thefuck/issues/685") alias = shell.app_alias(known_args.alias) if known_args.enable_experimental_instant_mode: if six.PY2: warn("Instant mode requires Python 3") elif not which('script'): warn("Instant mode requires `script` app") else: return shell.instant_mode_alias(known_args.alias) return alias def print_alias(known_args): settings.init(known_args) print(_get_alias(known_args))
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/thefuck/entrypoints/fix_command.py
thefuck/entrypoints/fix_command.py
from pprint import pformat import os import sys from difflib import SequenceMatcher from .. import logs, types, const from ..conf import settings from ..corrector import get_corrected_commands from ..exceptions import EmptyCommand from ..ui import select_command from ..utils import get_alias, get_all_executables def _get_raw_command(known_args): if known_args.force_command: return [known_args.force_command] elif not os.environ.get('TF_HISTORY'): return known_args.command else: history = os.environ['TF_HISTORY'].split('\n')[::-1] alias = get_alias() executables = get_all_executables() for command in history: diff = SequenceMatcher(a=alias, b=command).ratio() if diff < const.DIFF_WITH_ALIAS or command in executables: return [command] return [] def fix_command(known_args): """Fixes previous command. Used when `thefuck` called without arguments.""" settings.init(known_args) with logs.debug_time('Total'): logs.debug(u'Run with settings: {}'.format(pformat(settings))) raw_command = _get_raw_command(known_args) try: command = types.Command.from_raw_script(raw_command) except EmptyCommand: logs.debug('Empty command, nothing to do') return corrected_commands = get_corrected_commands(command) selected_command = select_command(corrected_commands) if selected_command: selected_command.run(command) else: sys.exit(1)
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/thefuck/entrypoints/main.py
thefuck/entrypoints/main.py
# Initialize output before importing any module, that can use colorama. from ..system import init_output init_output() import os # noqa: E402 import sys # noqa: E402 from .. import logs # noqa: E402 from ..argument_parser import Parser # noqa: E402 from ..utils import get_installation_version # noqa: E402 from ..shells import shell # noqa: E402 from .alias import print_alias # noqa: E402 from .fix_command import fix_command # noqa: E402 def main(): parser = Parser() known_args = parser.parse(sys.argv) if known_args.help: parser.print_help() elif known_args.version: logs.version(get_installation_version(), sys.version.split()[0], shell.info()) # It's important to check if an alias is being requested before checking if # `TF_HISTORY` is in `os.environ`, otherwise it might mess with subshells. # Check https://github.com/nvbn/thefuck/issues/921 for reference elif known_args.alias: print_alias(known_args) elif known_args.command or 'TF_HISTORY' in os.environ: fix_command(known_args) elif known_args.shell_logger: try: from .shell_logger import shell_logger # noqa: E402 except ImportError: logs.warn('Shell logger supports only Linux and macOS') else: shell_logger(known_args.shell_logger) else: parser.print_usage()
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/thefuck/entrypoints/__init__.py
thefuck/entrypoints/__init__.py
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/thefuck/entrypoints/not_configured.py
thefuck/entrypoints/not_configured.py
# Initialize output before importing any module, that can use colorama. from ..system import init_output init_output() import getpass # noqa: E402 import os # noqa: E402 import json # noqa: E402 from tempfile import gettempdir # noqa: E402 import time # noqa: E402 import six # noqa: E402 from psutil import Process # noqa: E402 from .. import logs, const # noqa: E402 from ..shells import shell # noqa: E402 from ..conf import settings # noqa: E402 from ..system import Path # noqa: E402 def _get_shell_pid(): """Returns parent process pid.""" proc = Process(os.getpid()) try: return proc.parent().pid except TypeError: return proc.parent.pid def _get_not_configured_usage_tracker_path(): """Returns path of special file where we store latest shell pid.""" return Path(gettempdir()).joinpath(u'thefuck.last_not_configured_run_{}'.format( getpass.getuser(), )) def _record_first_run(): """Records shell pid to tracker file.""" info = {'pid': _get_shell_pid(), 'time': time.time()} mode = 'wb' if six.PY2 else 'w' with _get_not_configured_usage_tracker_path().open(mode) as tracker: json.dump(info, tracker) def _get_previous_command(): history = shell.get_history() if history: return history[-1] else: return None def _is_second_run(): """Returns `True` when we know that `fuck` called second time.""" tracker_path = _get_not_configured_usage_tracker_path() if not tracker_path.exists(): return False current_pid = _get_shell_pid() with tracker_path.open('r') as tracker: try: info = json.load(tracker) except ValueError: return False if not (isinstance(info, dict) and info.get('pid') == current_pid): return False return (_get_previous_command() == 'fuck' or time.time() - info.get('time', 0) < const.CONFIGURATION_TIMEOUT) def _is_already_configured(configuration_details): """Returns `True` when alias already in shell config.""" path = Path(configuration_details.path).expanduser() with path.open('r') as shell_config: return configuration_details.content in shell_config.read() def _configure(configuration_details): """Adds alias to shell config.""" path = Path(configuration_details.path).expanduser() with path.open('a') as shell_config: shell_config.write(u'\n') shell_config.write(configuration_details.content) shell_config.write(u'\n') def main(): """Shows useful information about how-to configure alias on a first run and configure automatically on a second. It'll be only visible when user type fuck and when alias isn't configured. """ settings.init() configuration_details = shell.how_to_configure() if ( configuration_details and configuration_details.can_configure_automatically ): if _is_already_configured(configuration_details): logs.already_configured(configuration_details) return elif _is_second_run(): _configure(configuration_details) logs.configured_successfully(configuration_details) return else: _record_first_run() logs.how_to_configure_alias(configuration_details)
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/thefuck/rules/git_commit_reset.py
thefuck/rules/git_commit_reset.py
from thefuck.specific.git import git_support @git_support def match(command): return ('commit' in command.script_parts) @git_support def get_new_command(command): return 'git reset HEAD~'
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/thefuck/rules/docker_image_being_used_by_container.py
thefuck/rules/docker_image_being_used_by_container.py
from thefuck.utils import for_app from thefuck.shells import shell @for_app('docker') def match(command): ''' Matches a command's output with docker's output warning you that you need to remove a container before removing an image. ''' return 'image is being used by running container' in command.output def get_new_command(command): ''' Prepends docker container rm -f {container ID} to the previous docker image rm {image ID} command ''' container_id = command.output.strip().split(' ') return shell.and_('docker container rm -f {}', '{}').format(container_id[-1], command.script)
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/thefuck/rules/cd_cs.py
thefuck/rules/cd_cs.py
# -*- encoding: utf-8 -*- # Redirects cs to cd when there is a typo # Due to the proximity of the keys - d and s - this seems like a common typo # ~ > cs /etc/ # cs: command not found # ~ > fuck # cd /etc/ [enter/↑/↓/ctrl+c] # /etc > def match(command): if command.script_parts[0] == 'cs': return True def get_new_command(command): return 'cd' + ''.join(command.script[2:]) priority = 900
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/thefuck/rules/cargo.py
thefuck/rules/cargo.py
def match(command): return command.script == 'cargo' def get_new_command(command): return 'cargo build'
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/thefuck/rules/cargo_no_command.py
thefuck/rules/cargo_no_command.py
import re from thefuck.utils import replace_argument, for_app @for_app('cargo', at_least=1) def match(command): return ('no such subcommand' in command.output.lower() and 'Did you mean' in command.output) def get_new_command(command): broken = command.script_parts[1] fix = re.findall(r'Did you mean `([^`]*)`', command.output)[0] return replace_argument(command.script, broken, fix)
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/thefuck/rules/cd_mkdir.py
thefuck/rules/cd_mkdir.py
import re from thefuck.utils import for_app from thefuck.specific.sudo import sudo_support from thefuck.shells import shell @sudo_support @for_app('cd') def match(command): return ( command.script.startswith('cd ') and any(( 'no such file or directory' in command.output.lower(), 'cd: can\'t cd to' in command.output.lower(), 'does not exist' in command.output.lower() ))) @sudo_support def get_new_command(command): repl = shell.and_('mkdir -p \\1', 'cd \\1') return re.sub(r'^cd (.*)', repl, command.script)
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/thefuck/rules/git_pull_uncommitted_changes.py
thefuck/rules/git_pull_uncommitted_changes.py
from thefuck.shells import shell from thefuck.specific.git import git_support @git_support def match(command): return ('pull' in command.script and ('You have unstaged changes' in command.output or 'contains uncommitted changes' in command.output)) @git_support def get_new_command(command): return shell.and_('git stash', 'git pull', 'git stash pop')
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/thefuck/rules/git_push_pull.py
thefuck/rules/git_push_pull.py
from thefuck.shells import shell from thefuck.utils import replace_argument from thefuck.specific.git import git_support @git_support def match(command): return ('push' in command.script and '! [rejected]' in command.output and 'failed to push some refs to' in command.output and ('Updates were rejected because the tip of your' ' current branch is behind' in command.output or 'Updates were rejected because the remote ' 'contains work that you do' in command.output)) @git_support def get_new_command(command): return shell.and_(replace_argument(command.script, 'push', 'pull'), command.script)
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/thefuck/rules/git_hook_bypass.py
thefuck/rules/git_hook_bypass.py
from thefuck.utils import replace_argument from thefuck.specific.git import git_support hooked_commands = ("am", "commit", "push") @git_support def match(command): return any( hooked_command in command.script_parts for hooked_command in hooked_commands ) @git_support def get_new_command(command): hooked_command = next( hooked_command for hooked_command in hooked_commands if hooked_command in command.script_parts ) return replace_argument( command.script, hooked_command, hooked_command + " --no-verify" ) priority = 1100 requires_output = False
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/thefuck/rules/tsuru_not_command.py
thefuck/rules/tsuru_not_command.py
import re from thefuck.utils import get_all_matched_commands, replace_command, for_app @for_app('tsuru') def match(command): return (' is not a tsuru command. See "tsuru help".' in command.output and '\nDid you mean?\n\t' in command.output) def get_new_command(command): broken_cmd = re.findall(r'tsuru: "([^"]*)" is not a tsuru command', command.output)[0] return replace_command(command, broken_cmd, get_all_matched_commands(command.output))
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false
nvbn/thefuck
https://github.com/nvbn/thefuck/blob/c7e7e1d884d3bb241ea6448f72a989434c2a35ec/thefuck/rules/go_run.py
thefuck/rules/go_run.py
from thefuck.utils import for_app # Appends .go when compiling go files # # Example: # > go run foo # error: go run: no go files listed @for_app('go') def match(command): return (command.script.startswith('go run ') and not command.script.endswith('.go')) def get_new_command(command): return command.script + '.go'
python
MIT
c7e7e1d884d3bb241ea6448f72a989434c2a35ec
2026-01-04T14:38:15.457096Z
false