1
0
mirror of https://github.com/nvbn/thefuck.git synced 2025-11-01 15:42:06 +00:00

Compare commits

...

23 Commits
1.13 ... 1.17

Author SHA1 Message Date
nvbn
8ed01fedbf Bump version 2015-04-21 06:34:03 +02:00
nvbn
ab8ac23749 Fix python 3 support 2015-04-21 06:33:51 +02:00
nvbn
e7d5d93056 #68 Add rule for switching layout 2015-04-21 06:26:15 +02:00
nvbn
5ccf163594 command.script now unicode 2015-04-21 06:24:40 +02:00
nvbn
0925c7966f Bump version 2015-04-21 05:34:44 +02:00
nvbn
dd01303663 Update list of rules in readme 2015-04-21 05:34:34 +02:00
nvbn
e822fade4c #10 Add require_confirmation option 2015-04-21 05:30:15 +02:00
nvbn
0dcefad7bb Merge branch 'NabeelValapra-master' 2015-04-20 22:00:47 +02:00
nvbn
7888315196 #52 Use cp -a, add tests 2015-04-20 22:00:37 +02:00
nvbn
3665a23b9a Merge branch 'master' of git://github.com/NabeelValapra/thefuck into NabeelValapra-master 2015-04-20 21:54:29 +02:00
nvbn
2db0a215b4 Fix fuck when more than one git command available 2015-04-20 21:48:54 +02:00
Vladimir Iakovlev
f6f6e2223c Merge pull request #62 from sjuvekar/master
A special case for 'Permission denied' error msg when trying to execute ...
2015-04-20 18:52:35 +02:00
Vladimir Iakovlev
d86bf8da40 Merge pull request #60 from pcmitsis/patch-1
Update Readme to contain a link to the license
2015-04-20 18:50:09 +02:00
Vladimir Iakovlev
a77ca37be2 Merge pull request #64 from nwinkler/mkdir-p
mkdir -p
2015-04-20 18:49:10 +02:00
Vladimir Iakovlev
3fb7a0c123 Merge pull request #63 from KAMiKAZOW/patch-1
tweet, not twit
2015-04-20 18:48:33 +02:00
Nils Winkler
c0c584b13a mkdir -p
When adding directories using `mkdir`, intermediate directories have to
exist, unless you specify the `-p` option:

    $ mkdir foo/bar/baz
    mkdir: foo/bar: No such file or directory
    $ fuck
    mkdir -p foo/bar/baz
2015-04-20 18:38:03 +02:00
Markus S.
a81d9af621 tweet, not twit 2015-04-20 18:19:34 +02:00
Sudeep Juvekar
1d878243ca A special case for 'Permission denied' error msg when trying to execute a
python scripy.

The script does not have execute permission and/or does not start with !#/usr/...
In that case, pre-pend the command with 'python' keyword.

Change-Id: Idf73ee9cf0a523f51c78672188a457b2fcedc1e6
2015-04-20 12:11:06 -04:00
Sudeep Juvekar
cb31a1f7d0 A special case for 'Permission denied' error msg when trying to execute a
python scripy.

The script does not have execute permission and/or does not start with !#/usr/...
In that case, pre-pend the command with 'python' keyword.

Change-Id: Idf73ee9cf0a523f51c78672188a457b2fcedc1e6
2015-04-20 12:00:08 -04:00
Sudeep Juvekar
17397bf30f A special case for 'Permission denied' error msg when trying to execute a
python scripy.

The script does not have execute permission and/or does not start with !#/usr/...
In that case, pre-pend the command with 'python' keyword.

Change-Id: Idf73ee9cf0a523f51c78672188a457b2fcedc1e6
2015-04-20 11:00:35 -04:00
Sudeep Juvekar
411aea67f7 A special case for 'Permission denied' error msg when trying to execute a
python scripy.

The script does not have execute permission and/or does not start with !#/usr/...
In that case, pre-pend the command with 'python' keyword.

Change-Id: Idf73ee9cf0a523f51c78672188a457b2fcedc1e6
2015-04-20 10:49:39 -04:00
Panagiotis Mitsis
0b0ad0558a Update Readme to contain a link to the license
A small reference to the license from the readme file.
2015-04-20 16:32:50 +02:00
Nabeel Valapra
f9f757f618 Added rule:cp_omitting_directory 2015-04-20 14:34:09 +05:30
17 changed files with 219 additions and 18 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 scary 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
@@ -133,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
@@ -167,9 +189,10 @@ def get_new_command(command, settings):
## Settings
The Fuck has 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`.
@@ -190,3 +213,4 @@ py.test
```
## License MIT
Project License can be found [here](LICENSE.md).

View File

@@ -2,7 +2,7 @@ from setuptools import setup, find_packages
setup(name='thefuck',
version=1.13,
version=1.17,
description="Magnificent app which corrects your previous console command",
author='Vladimir Iakovlev',
author_email='nvbn.rm@gmail.com',

View File

@@ -0,0 +1,14 @@
from mock import Mock
from thefuck.rules.cp_omitting_directory import match, get_new_command
def test_match():
assert match(Mock(script='cp dir', stderr="cp: omitting directory 'dir'"),
None)
assert not match(Mock(script='some dir',
stderr="cp: omitting directory 'dir'"), None)
assert not match(Mock(script='cp dir', stderr=""), None)
def test_get_new_command():
assert get_new_command(Mock(script='cp dir'), None) == 'cp -a dir'

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

@@ -0,0 +1,13 @@
from thefuck.main import Command
from thefuck.rules.mkdir_p import match, get_new_command
def test_match():
assert match(Command('mkdir foo/bar/baz', '', 'mkdir: foo/bar: No such file or directory'), None)
assert not match(Command('mkdir foo/bar/baz', '', ''), None)
assert not match(Command('mkdir foo/bar/baz', '', 'foo bar baz'), None)
assert not match(Command('', '', ''), None)
def test_get_new_command():
assert get_new_command(Command('mkdir foo/bar/baz', '', ''), None) == 'mkdir -p foo/bar/baz'

View File

@@ -0,0 +1,9 @@
from thefuck.main import Command
from thefuck.rules.python_command import match, get_new_command
def test_match():
assert match(Command('temp.py', '', 'Permission denied'), None)
assert not match(Command('', '', ''), None)
def test_get_new_command():
assert get_new_command(Command('./test_sudo.py', '', ''), None) == 'python ./test_sudo.py'

View File

@@ -0,0 +1,18 @@
# -*- encoding: utf-8 -*-
from mock import Mock
from thefuck.rules import switch_lang
def test_match():
assert switch_lang.match(Mock(stderr='command not found: фзе-пуе',
script=u'фзе-пуе'), None)
assert not switch_lang.match(Mock(stderr='command not found: pat-get',
script=u'pat-get'), None)
assert not switch_lang.match(Mock(stderr='some info',
script=u'фзе-пуе'), None)
def test_get_new_command():
assert switch_lang.get_new_command(
Mock(script=u'фзе-пуе штыефдд мшь'), None) == 'apt-get install vim'

View File

@@ -53,8 +53,8 @@ def test_get_command():
return_value=True):
Popen.return_value.stdout.read.return_value = b'stdout'
Popen.return_value.stderr.read.return_value = b'stderr'
assert main.get_command(Mock(), ['thefuck', 'apt-get',
'search', 'vim']) \
assert main.get_command(Mock(), [b'thefuck', b'apt-get',
b'search', b'vim']) \
== main.Command('apt-get search vim', 'stdout', 'stderr')
Popen.assert_called_once_with('apt-get search vim',
shell=True,
@@ -70,3 +70,28 @@ def test_get_matched_rule():
rules, None) is None
assert main.get_matched_rule(main.Command('cd ..', '', ''),
rules, None) == rules[0]
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))
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))
assert capsys.readouterr() == ('', 'command [Enter/Ctrl+C]Aborted\n')

View File

@@ -28,6 +28,7 @@ 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)
return settings
@@ -51,7 +52,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 +76,10 @@ 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:])
result = Popen(script, shell=True, stdout=PIPE, stderr=PIPE,
env=dict(os.environ, LANG='C'))
if wait_output(settings, result):
@@ -90,11 +94,27 @@ def get_matched_rule(command, rules, settings):
return rule
def confirm(new_command, settings):
"""Returns `True` when running of new command confirmed."""
if not settings.require_confirmation:
sys.stderr.write(new_command + '\n')
return True
sys.stderr.write(new_command + ' [Enter/Ctrl+C]')
sys.stderr.flush()
try:
sys.stdin.read(1)
return True
except KeyboardInterrupt:
sys.stderr.write('Aborted\n')
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):

View File

@@ -0,0 +1,10 @@
import re
def match(command, settings):
return command.script.startswith('cp ') \
and 'cp: omitting directory' in command.stderr.lower()
def get_new_command(command, settings):
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

@@ -7,5 +7,5 @@ def match(command, settings):
def get_new_command(command, settings):
return './{}'.format(command.script)
return u'./{}'.format(command.script)

9
thefuck/rules/mkdir_p.py Normal file
View File

@@ -0,0 +1,9 @@
import re
def match(command, settings):
return ('mkdir' in command.script
and 'No such file or directory' in command.stderr)
def get_new_command(command, settings):
return re.sub('^mkdir (.*)', 'mkdir -p \\1', command.script)

View File

@@ -8,7 +8,7 @@ local_settings = {'command_not_found': '/usr/lib/command-not-found'}
def _get_output(command, settings):
name = command.script.split(' ')[command.script.startswith('sudo')]
check_script = '{} {}'.format(settings.command_not_found, name)
check_script = u'{} {}'.format(settings.command_not_found, name)
result = Popen(check_script, shell=True, stderr=PIPE)
return result.stderr.read().decode('utf-8')

View File

@@ -0,0 +1,14 @@
# add 'python' suffix to the command if
# 1) The script does not have execute permission or
# 2) is interpreted as shell script
def match(command, settings):
toks = command.script.split()
return (len(toks) > 0
and toks[0].endswith('.py')
and ('Permission denied' in command.stderr or
'command not found' in command.stderr))
def get_new_command(command, settings):
return 'python ' + command.script

View File

@@ -14,4 +14,4 @@ def match(command, settings):
def get_new_command(command, settings):
return 'sudo {}'.format(command.script)
return u'sudo {}'.format(command.script)

View File

@@ -0,0 +1,29 @@
# -*- encoding: utf-8 -*-
target_layout = '''qwertyuiop[]asdfghjkl;'zxcvbnm,./QWERTYUIOP{}ASDFGHJKL:"ZXCVBNM<>?'''
source_layouts = [u'''йцукенгшщзхъфывапролджэячсмитьбю.ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ,''']
def _get_matched_layout(command):
for source_layout in source_layouts:
if all([ch in source_layout or ch in '-_'
for ch in command.script.split(' ')[0]]):
return source_layout
def match(command, settings):
return 'not found' in command.stderr and _get_matched_layout(command)
def _switch(ch, layout):
if ch in layout:
return target_layout[layout.index(ch)]
else:
return ch
def get_new_command(command, settings):
matched_layout = _get_matched_layout(command)
return ''.join(_switch(ch, matched_layout) for ch in command.script)