1
0
mirror of https://github.com/nvbn/thefuck.git synced 2025-03-13 22:28:33 +00:00
This commit is contained in:
Nabeel Valapra 2015-04-22 17:49:35 +05:30
commit 0d0fadacfb
10 changed files with 199 additions and 122 deletions

View File

@ -1,8 +1,8 @@
# The Fuck [![Build Status](https://travis-ci.org/nvbn/thefuck.svg)](https://travis-ci.org/nvbn/thefuck)
Magnificent app which corrects your previous console command,
inspired by [@liamosaur](https://twitter.com/liamosaur/status/506975850596536320)
twit.
inspired by a [@liamosaur](https://twitter.com/liamosaur/)
[tweet](https://twitter.com/liamosaur/status/506975850596536320).
Few examples:
@ -65,11 +65,27 @@ Did you mean this?
repl
➜ fuck
lein repl
nREPL server started on port 54848 on host 127.0.0.1 - nrepl://127.0.0.1:54848
REPL-y 0.3.1
...
```
If you are scared to blindly run changed command, there's `require_confirmation`
[settings](#settings) option:
```bash
➜ apt-get install vim
E: Could not open lock file /var/lib/dpkg/lock - open (13: Permission denied)
E: Unable to lock the administration directory (/var/lib/dpkg/), are you root?
➜ fuck
sudo apt-get install vim [Enter/Ctrl+C]
[sudo] password for nvbn:
Reading package lists... Done
...
```
## Requirements
- pip
@ -90,7 +106,7 @@ If it fails try to use `easy_install`:
sudo easy_install thefuck
```
And add to `.bashrc` or `.zshrc`:
And add to `.bashrc` or `.zshrc` or `.bash_profile`(for OSX):
```bash
alias fuck='$(thefuck $(fc -ln -1))'
@ -106,7 +122,19 @@ function fuck
end
```
Changes will available only in a new shell session.
Or in your Powershell `$PROFILE` on Windows:
```powershell
function fuck {
$fuck = $(thefuck (get-history -count 1).commandline)
if($fuck.startswith("echo")) {
$fuck.substring(5)
}
else { iex "$fuck" }
}
```
Changes will be available only in a new shell session.
## Update
@ -121,11 +149,17 @@ The Fuck tries to match rule for the previous command, create new command
using matched rule and run it. Rules enabled by default:
* `cd_parent` – changes `cd..` to `cd ..`;
* `cp_omitting_directory` – adds `-a` when you `cp` directory;
* `git_no_command` – fixes wrong git commands like `git brnch`;
* `git_push` – adds `--set-upstream origin $branch` to previous failed `git push`;
* `has_exists_script` – prepends `./` when script/binary exists;
* `lein_not_task` – fixes wrong `lein` tasks like `lein rpl`;
* `mkdir_p` – adds `-p` when you trying to create directory without parent;
* `no_command` – fixes wrong console commands, for example `vom/vim`;
* `python_command` – prepends `python` when you trying to run not executable/without `./` python script;
* `rm_dir` – adds `-rf` when you trying to remove directory;
* `sudo` – prepends `sudo` to previous command if it failed because of permissions;
* `lein_not_task` – fixes wrong `lein` tasks like `lein rpl`.
* `switch_layout` – switches command from your local layout to en.
## Creating your own rules
@ -134,7 +168,7 @@ in `~/.thefuck/rules`. Rule should contain two functions:
`match(command: Command, settings: Settings) -> bool`
and `get_new_command(command: Command, settings: Settings) -> str`.
`Command` have three attributes: `script`, `stdout` and `stderr`.
`Command` has three attributes: `script`, `stdout` and `stderr`.
`Settings` is `~/.thefuck/settings.py`.
@ -155,12 +189,12 @@ def get_new_command(command, settings):
## Settings
The Fuck have a few settings parameters:
The Fuck has a few settings parameters, they can be changed in `~/.thefuck/settings.py`:
* `rules` – list of enabled rules, by default all;
* `require_confirmation` – require confirmation before running new command, by default `False`;
* `wait_command` – max amount of time in seconds for getting previous command output;
* `command_not_found` – path to `command_not_found` binary,
by default `/usr/lib/command-not-found`.
* `no_colors` – disable colored output.
## Developing
@ -178,3 +212,4 @@ py.test
```
## License MIT
Project License can be found [here](LICENSE.md).

View File

@ -1,16 +1,20 @@
from setuptools import setup, find_packages
VERSION = '1.26'
setup(name='thefuck',
version=1.12,
version=VERSION,
description="Magnificent app which corrects your previous console command",
author='Vladimir Iakovlev',
author_email='nvbn.rm@gmail.com',
url='https://github.com/nvbn/thefuck',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
packages=find_packages(exclude=['ez_setup', 'examples',
'tests', 'release']),
include_package_data=True,
zip_safe=False,
install_requires=['pathlib', 'psutil'],
install_requires=['pathlib', 'psutil', 'colorama'],
entry_points={'console_scripts': [
'thefuck = thefuck.main:main']})

View File

@ -12,17 +12,33 @@ branch
"""
@pytest.fixture
def git_not_command_one_of_this():
return """git: 'st' is not a git command. See 'git --help'.
Did you mean one of these?
status
reset
stage
stash
stats
"""
@pytest.fixture
def git_command():
return "* master"
def test_match(git_not_command, git_command):
def test_match(git_not_command, git_command, git_not_command_one_of_this):
assert match(Command('git brnch', '', git_not_command), None)
assert match(Command('git st', '', git_not_command_one_of_this), None)
assert not match(Command('ls brnch', '', git_not_command), None)
assert not match(Command('git branch', '', git_command), None)
def test_get_new_command(git_not_command):
def test_get_new_command(git_not_command, git_not_command_one_of_this):
assert get_new_command(Command('git brnch', '', git_not_command), None)\
== 'git branch'
assert get_new_command(
Command('git st', '', git_not_command_one_of_this), None) == 'git status'

View File

@ -1,62 +1,19 @@
from subprocess import PIPE
from mock import patch, Mock
import pytest
from thefuck.rules.no_command import match, get_new_command
from thefuck.main import Command
@pytest.fixture
def command_found():
return b'''No command 'aptget' found, did you mean:
Command 'apt-get' from package 'apt' (main)
aptget: command not found
'''
@pytest.fixture
def command_not_found():
return b'''No command 'vom' found, but there are 19 similar ones
vom: command not found
'''
def test_match():
with patch('thefuck.rules.no_command._get_all_bins',
return_value=['vim', 'apt-get']):
assert match(Mock(stderr='vom: not found', script='vom file.py'), None)
assert not match(Mock(stderr='qweqwe: not found', script='qweqwe'), None)
assert not match(Mock(stderr='some text', script='vom file.py'), None)
@pytest.fixture
def bins_exists(request):
p = patch('thefuck.rules.no_command.which',
return_value=True)
p.start()
request.addfinalizer(p.stop)
@pytest.fixture
def settings():
class _Settings(object):
pass
return _Settings
@pytest.mark.usefixtures('bins_exists')
def test_match(command_found, command_not_found, settings):
with patch('thefuck.rules.no_command.Popen') as Popen:
Popen.return_value.stderr.read.return_value = command_found
assert match(Command('aptget install vim', '', ''), settings)
Popen.assert_called_once_with('/usr/lib/command-not-found aptget',
shell=True, stderr=PIPE)
Popen.return_value.stderr.read.return_value = command_not_found
assert not match(Command('ls', '', ''), settings)
with patch('thefuck.rules.no_command.Popen') as Popen:
Popen.return_value.stderr.read.return_value = command_found
assert match(Command('sudo aptget install vim', '', ''),
Mock(command_not_found='test'))
Popen.assert_called_once_with('test aptget',
shell=True, stderr=PIPE)
@pytest.mark.usefixtures('bins_exists')
def test_get_new_command(command_found):
with patch('thefuck.rules.no_command._get_output',
return_value=command_found.decode()):
assert get_new_command(Command('aptget install vim', '', ''), settings)\
== 'apt-get install vim'
assert get_new_command(Command('sudo aptget install vim', '', ''), settings) \
== 'sudo apt-get install vim'
def test_get_new_command():
with patch('thefuck.rules.no_command._get_all_bins',
return_value=['vim', 'apt-get']):
assert get_new_command(
Mock(stderr='vom: not found',
script='vom file.py'),
None) == 'vim file.py'

View File

@ -24,7 +24,7 @@ def test_load_rule():
return_value=Mock(
match=match,
get_new_command=get_new_command)) as load_source:
assert main.load_rule(Path('/rules/bash.py')) == main.Rule(match, get_new_command)
assert main.load_rule(Path('/rules/bash.py')) == main.Rule('bash', match, get_new_command)
load_source.assert_called_once_with('bash', '/rules/bash.py')
@ -35,14 +35,14 @@ def test_get_rules():
glob.return_value = [PosixPath('bash.py'), PosixPath('lisp.py')]
assert main.get_rules(
Path('~'),
Mock(rules=None)) == [main.Rule('bash', 'bash'),
main.Rule('lisp', 'lisp'),
main.Rule('bash', 'bash'),
main.Rule('lisp', 'lisp')]
Mock(rules=None)) == [main.Rule('bash', 'bash', 'bash'),
main.Rule('lisp', 'lisp', 'lisp'),
main.Rule('bash', 'bash', 'bash'),
main.Rule('lisp', 'lisp', 'lisp')]
assert main.get_rules(
Path('~'),
Mock(rules=['bash'])) == [main.Rule('bash', 'bash'),
main.Rule('bash', 'bash')]
Mock(rules=['bash'])) == [main.Rule('bash', 'bash', 'bash'),
main.Rule('bash', 'bash', 'bash')]
def test_get_command():
@ -61,12 +61,43 @@ def test_get_command():
stdout=PIPE,
stderr=PIPE,
env={'LANG': 'C'})
assert main.get_command(Mock(), ['']) is None
def test_get_matched_rule():
rules = [main.Rule(lambda x, _: x.script == 'cd ..', None),
main.Rule(lambda *_: False, None)]
def test_get_matched_rule(capsys):
rules = [main.Rule('', lambda x, _: x.script == 'cd ..', None),
main.Rule('', lambda *_: False, None),
main.Rule('rule', Mock(side_effect=OSError('Denied')), None)]
assert main.get_matched_rule(main.Command('ls', '', ''),
rules, None) is None
rules, Mock(no_colors=True)) is None
assert main.get_matched_rule(main.Command('cd ..', '', ''),
rules, None) == rules[0]
rules, Mock(no_colors=True)) == rules[0]
assert capsys.readouterr()[1].split('\n')[0]\
== '[WARN] Rule rule:'
def test_run_rule(capsys):
with patch('thefuck.main.confirm', return_value=True):
main.run_rule(main.Rule('', None, lambda *_: 'new-command'),
None, None)
assert capsys.readouterr() == ('new-command\n', '')
with patch('thefuck.main.confirm', return_value=False):
main.run_rule(main.Rule('', None, lambda *_: 'new-command'),
None, None)
assert capsys.readouterr() == ('', '')
def test_confirm(capsys):
# When confirmation not required:
assert main.confirm('command', Mock(require_confirmation=False))
assert capsys.readouterr() == ('', 'command\n')
# When confirmation required and confirmed:
with patch('thefuck.main.sys.stdin.read', return_value='\n'):
assert main.confirm('command', Mock(require_confirmation=True,
no_colors=True))
assert capsys.readouterr() == ('', 'command [enter/ctrl+c]')
# When confirmation required and ctrl+c:
with patch('thefuck.main.sys.stdin.read', side_effect=KeyboardInterrupt):
assert not main.confirm('command', Mock(require_confirmation=True,
no_colors=True))
assert capsys.readouterr() == ('', 'command [enter/ctrl+c]Aborted\n')

View File

@ -6,10 +6,12 @@ from subprocess import Popen, PIPE
import os
import sys
from psutil import Process, TimeoutExpired
import colorama
from thefuck import logs
Command = namedtuple('Command', ('script', 'stdout', 'stderr'))
Rule = namedtuple('Rule', ('match', 'get_new_command'))
Rule = namedtuple('Rule', ('name', 'match', 'get_new_command'))
def setup_user_dir():
@ -28,6 +30,8 @@ def get_settings(user_dir):
str(user_dir.joinpath('settings.py')))
settings.__dict__.setdefault('rules', None)
settings.__dict__.setdefault('wait_command', 3)
settings.__dict__.setdefault('require_confirmation', False)
settings.__dict__.setdefault('no_colors', False)
return settings
@ -42,7 +46,8 @@ def is_rule_enabled(settings, rule):
def load_rule(rule):
"""Imports rule module and returns it."""
rule_module = load_source(rule.name[:-3], str(rule))
return Rule(rule_module.match, rule_module.get_new_command)
return Rule(rule.name[:-3], rule_module.match,
rule_module.get_new_command)
def get_rules(user_dir, settings):
@ -51,7 +56,7 @@ def get_rules(user_dir, settings):
.joinpath('rules')\
.glob('*.py')
user = user_dir.joinpath('rules').glob('*.py')
return [load_rule(rule) for rule in list(bundled) + list(user)
return [load_rule(rule) for rule in sorted(list(bundled)) + list(user)
if rule.name != '__init__.py' and is_rule_enabled(settings, rule)]
@ -75,7 +80,14 @@ def wait_output(settings, popen):
def get_command(settings, args):
"""Creates command from `args` and executes it."""
script = ' '.join(args[1:])
if sys.version_info[0] < 3:
script = ' '.join(arg.decode('utf-8') for arg in args[1:])
else:
script = ' '.join(args[1:])
if not script:
return
result = Popen(script, shell=True, stdout=PIPE, stderr=PIPE,
env=dict(os.environ, LANG='C'))
if wait_output(settings, result):
@ -86,15 +98,33 @@ def get_command(settings, args):
def get_matched_rule(command, rules, settings):
"""Returns first matched rule for command."""
for rule in rules:
if rule.match(command, settings):
return rule
try:
if rule.match(command, settings):
return rule
except Exception:
logs.rule_failed(rule, sys.exc_info(), settings)
def confirm(new_command, settings):
"""Returns `True` when running of new command confirmed."""
if not settings.require_confirmation:
logs.show_command(new_command, settings)
return True
logs.confirm_command(new_command, settings)
try:
sys.stdin.read(1)
return True
except KeyboardInterrupt:
logs.failed('Aborted', settings)
return False
def run_rule(rule, command, settings):
"""Runs command from rule for passed command."""
new_command = rule.get_new_command(command, settings)
sys.stderr.write(new_command + '\n')
print(new_command)
if confirm(new_command, settings):
print(new_command)
def is_second_run(command):
@ -103,13 +133,14 @@ def is_second_run(command):
def main():
colorama.init()
user_dir = setup_user_dir()
settings = get_settings(user_dir)
command = get_command(settings, sys.argv)
if command:
if is_second_run(command):
print("echo Can't fuck twice")
logs.failed("Can't fuck twice", settings)
return
rules = get_rules(user_dir, settings)
@ -118,4 +149,4 @@ def main():
run_rule(matched_rule, command, settings)
return
print('echo No fuck given')
logs.failed('No fuck given', settings)

View File

@ -1,10 +1,10 @@
import re
def match(command, settings):
if 'cp: omitting directory' in command.stderr.lower():
return True
return False
return command.script.startswith('cp ') \
and 'cp: omitting directory' in command.stderr.lower()
def get_new_command(command, settings):
return command.script.replace('cp', 'cp -r')
return re.sub(r'^cp', 'cp -a', command.script)

View File

@ -4,13 +4,13 @@ import re
def match(command, settings):
return ('git' in command.script
and " is not a git command. See 'git --help'." in command.stderr
and 'Did you mean this?' in command.stderr)
and 'Did you mean' in command.stderr)
def get_new_command(command, settings):
broken_cmd = re.findall(r"git: '([^']*)' is not a git command",
command.stderr)[0]
new_cmd = re.findall(r'Did you mean this\?\n\s*([^\n]*)',
new_cmd = re.findall(r'Did you mean[^\n]*\n\s*([^\n]*)',
command.stderr)[0]
return command.script.replace(broken_cmd, new_cmd, 1)

View File

@ -1,30 +1,30 @@
from subprocess import Popen, PIPE
import re
from thefuck.utils import which, wrap_settings
from difflib import get_close_matches
import os
from pathlib import Path
local_settings = {'command_not_found': '/usr/lib/command-not-found'}
def _safe(fn, fallback):
try:
return fn()
except OSError:
return fallback
def _get_output(command, settings):
name = command.script.split(' ')[command.script.startswith('sudo')]
check_script = '{} {}'.format(settings.command_not_found, name)
result = Popen(check_script, shell=True, stderr=PIPE)
return result.stderr.read().decode('utf-8')
def _get_all_bins():
return [exe.name
for path in os.environ.get('PATH', '').split(':')
for exe in _safe(lambda: list(Path(path).iterdir()), [])
if not _safe(exe.is_dir, True)]
@wrap_settings(local_settings)
def match(command, settings):
if which(settings.command_not_found):
output = _get_output(command, settings)
return "No command" in output and "from package" in output
return 'not found' in command.stderr and \
bool(get_close_matches(command.script.split(' ')[0],
_get_all_bins()))
@wrap_settings(local_settings)
def get_new_command(command, settings):
output = _get_output(command, settings)
broken_name = re.findall(r"No command '([^']*)' found",
output)[0]
fixed_name = re.findall(r"Command '([^']*)' from package",
output)[0]
return command.script.replace(broken_name, fixed_name, 1)
old_command = command.script.split(' ')[0]
new_command = get_close_matches(old_command,
_get_all_bins())[0]
return ' '.join([new_command] + command.script.split(' ')[1:])

View File

@ -3,7 +3,10 @@ patterns = ['permission denied',
'pkg: Insufficient privileges',
'you cannot perform this operation unless you are root',
'non-root users cannot',
'Operation not permitted']
'Operation not permitted',
'root privilege',
'This command has to be run under the root user.',
'You need to be root to perform this command.']
def match(command, settings):
@ -14,4 +17,4 @@ def match(command, settings):
def get_new_command(command, settings):
return 'sudo {}'.format(command.script)
return u'sudo {}'.format(command.script)