Git Product home page Git Product logo

thefuck's Introduction

The Fuck Version Build Status Coverage MIT License

The Fuck is a magnificent app, inspired by a @liamosaur tweet, that corrects errors in previous console commands.

Is The Fuck too slow? Try the experimental instant mode!

gif with examples

More examples:

➜ 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
...
➜ git push
fatal: The current branch master has no upstream branch.
To push the current branch and set the remote as upstream, use

    git push --set-upstream origin master


➜ fuck
git push --set-upstream origin master [enter/↑/↓/ctrl+c]
Counting objects: 9, done.
...
➜ puthon
No command 'puthon' found, did you mean:
 Command 'python' from package 'python-minimal' (main)
 Command 'python' from package 'python3' (main)
zsh: command not found: puthon

➜ fuck
python [enter/↑/↓/ctrl+c]
Python 3.4.2 (default, Oct  8 2014, 13:08:17)
...
➜ git brnch
git: 'brnch' is not a git command. See 'git --help'.

Did you mean this?
    branch

➜ fuck
git branch [enter/↑/↓/ctrl+c]
* master
➜ lein rpl
'rpl' is not a task. See 'lein help'.

Did you mean this?
         repl

➜ fuck
lein repl [enter/↑/↓/ctrl+c]
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're not afraid of blindly running corrected commands, the require_confirmation settings option can be disabled:

➜ 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
[sudo] password for nvbn:
Reading package lists... Done
...

Contents

  1. Requirements
  2. Installations
  3. Updating
  4. How it works
  5. Creating your own rules
  6. Settings
  7. Third party packages with rules
  8. Experimental instant mode
  9. Developing
  10. License

Requirements

  • python (3.5+)
  • pip
  • python-dev

Installation

On macOS or Linux, you can install The Fuck via Homebrew:

brew install thefuck

On Ubuntu / Mint, install The Fuck with the following commands:

sudo apt update
sudo apt install python3-dev python3-pip python3-setuptools
pip3 install thefuck --user

On FreeBSD, install The Fuck with the following commands:

pkg install thefuck

On ChromeOS, install The Fuck using chromebrew with the following command:

crew install thefuck

On Arch based systems, install The Fuck with the following command:

sudo pacman -S thefuck

On other systems, install The Fuck by using pip:

pip install thefuck

Alternatively, you may use an OS package manager (OS X, Ubuntu, Arch).

# It is recommended that you place this command in your .bash_profile, .bashrc, .zshrc or other startup script:

eval $(thefuck --alias)
# You can use whatever you want as an alias, like for Mondays:
eval $(thefuck --alias FUCK)

Or in your shell config (Bash, Zsh, Fish, Powershell, tcsh).

Changes are only available in a new shell session. To make changes immediately available, run source ~/.bashrc (or your shell config file like .zshrc).

To run fixed commands without confirmation, use the --yeah option (or just -y for short, or --hard if you're especially frustrated):

fuck --yeah

To fix commands recursively until succeeding, use the -r option:

fuck -r

Updating

pip3 install thefuck --upgrade

Note: Alias functionality was changed in v1.34 of The Fuck

Uninstall

To remove The Fuck, reverse the installation process:

  • erase or comment thefuck alias line from your Bash, Zsh, Fish, Powershell, tcsh, ... shell config
  • use your package manager (brew, pip3, pkg, crew, pip) to uninstall the binaries

How it works

The Fuck attempts to match the previous command with a rule. If a match is found, a new command is created using the matched rule and executed. The following rules are enabled by default:

  • adb_unknown_command – fixes misspelled commands like adb logcta;
  • ag_literal – adds -Q to ag when suggested;
  • aws_cli – fixes misspelled commands like aws dynamdb scan;
  • az_cli – fixes misspelled commands like az providers;
  • cargo – runs cargo build instead of cargo;
  • cargo_no_command – fixes wrong commands like cargo buid;
  • cat_dir – replaces cat with ls when you try to cat a directory;
  • cd_correction – spellchecks and corrects failed cd commands;
  • cd_cs – changes cs to cd;
  • cd_mkdir – creates directories before cd'ing into them;
  • cd_parent – changes cd.. to cd ..;
  • chmod_x – adds execution bit;
  • choco_install – appends common suffixes for chocolatey packages;
  • composer_not_command – fixes composer command name;
  • conda_mistype – fixes conda commands;
  • cp_create_destination – creates a new directory when you attempt to cp or mv to a non-existent one
  • cp_omitting_directory – adds -a when you cp directory;
  • cpp11 – adds missing -std=c++11 to g++ or clang++;
  • dirty_untar – fixes tar x command that untarred in the current directory;
  • dirty_unzip – fixes unzip command that unzipped in the current directory;
  • django_south_ghost – adds --delete-ghost-migrations to failed because ghosts django south migration;
  • django_south_merge – adds --merge to inconsistent django south migration;
  • docker_login – executes a docker login and repeats the previous command;
  • docker_not_command – fixes wrong docker commands like docker tags;
  • docker_image_being_used_by_container ‐ removes the container that is using the image before removing the image;
  • dry – fixes repetitions like git git push;
  • fab_command_not_found – fixes misspelled fabric commands;
  • fix_alt_space – replaces Alt+Space with Space character;
  • fix_file – opens a file with an error in your $EDITOR;
  • gem_unknown_command – fixes wrong gem commands;
  • git_add – fixes "pathspec 'foo' did not match any file(s) known to git.";
  • git_add_force – adds --force to git add <pathspec>... when paths are .gitignore'd;
  • git_bisect_usage – fixes git bisect strt, git bisect goood, git bisect rset, etc. when bisecting;
  • git_branch_delete – changes git branch -d to git branch -D;
  • git_branch_delete_checked_out – changes git branch -d to git checkout master && git branch -D when trying to delete a checked out branch;
  • git_branch_exists – offers git branch -d foo, git branch -D foo or git checkout foo when creating a branch that already exists;
  • git_branch_list – catches git branch list in place of git branch and removes created branch;
  • git_branch_0flag – fixes commands such as git branch 0v and git branch 0r removing the created branch;
  • git_checkout – fixes branch name or creates new branch;
  • git_clone_git_clone – replaces git clone git clone ... with git clone ...
  • git_clone_missing – adds git clone to URLs that appear to link to a git repository.
  • git_commit_add – offers git commit -a ... or git commit -p ... after previous commit if it failed because nothing was staged;
  • git_commit_amend – offers git commit --amend after previous commit;
  • git_commit_reset – offers git reset HEAD~ after previous commit;
  • git_diff_no_index – adds --no-index to previous git diff on untracked files;
  • git_diff_staged – adds --staged to previous git diff with unexpected output;
  • git_fix_stash – fixes git stash commands (misspelled subcommand and missing save);
  • git_flag_after_filename – fixes fatal: bad flag '...' after filename
  • git_help_aliased – fixes git help <alias> commands replacing with the aliased command;
  • git_hook_bypass – adds --no-verify flag previous to git am, git commit, or git push command;
  • git_lfs_mistype – fixes mistyped git lfs <command> commands;
  • git_main_master – fixes incorrect branch name between main and master
  • git_merge – adds remote to branch names;
  • git_merge_unrelated – adds --allow-unrelated-histories when required
  • git_not_command – fixes wrong git commands like git brnch;
  • git_pull – sets upstream before executing previous git pull;
  • git_pull_clone – clones instead of pulling when the repo does not exist;
  • git_pull_uncommitted_changes – stashes changes before pulling and pops them afterwards;
  • git_push – adds --set-upstream origin $branch to previous failed git push;
  • git_push_different_branch_names – fixes pushes when local branch name does not match remote branch name;
  • git_push_pull – runs git pull when push was rejected;
  • git_push_without_commits – creates an initial commit if you forget and only git add ., when setting up a new project;
  • git_rebase_no_changes – runs git rebase --skip instead of git rebase --continue when there are no changes;
  • git_remote_delete – replaces git remote delete remote_name with git remote remove remote_name;
  • git_rm_local_modifications – adds -f or --cached when you try to rm a locally modified file;
  • git_rm_recursive – adds -r when you try to rm a directory;
  • git_rm_staged – adds -f or --cached when you try to rm a file with staged changes
  • git_rebase_merge_dir – offers git rebase (--continue | --abort | --skip) or removing the .git/rebase-merge dir when a rebase is in progress;
  • git_remote_seturl_add – runs git remote add when git remote set_url on nonexistent remote;
  • git_stash – stashes your local modifications before rebasing or switching branch;
  • git_stash_pop – adds your local modifications before popping stash, then resets;
  • git_tag_force – adds --force to git tag <tagname> when the tag already exists;
  • git_two_dashes – adds a missing dash to commands like git commit -amend or git rebase -continue;
  • go_run – appends .go extension when compiling/running Go programs;
  • go_unknown_command – fixes wrong go commands, for example go bulid;
  • gradle_no_task – fixes not found or ambiguous gradle task;
  • gradle_wrapper – replaces gradle with ./gradlew;
  • grep_arguments_order – fixes grep arguments order for situations like grep -lir . test;
  • grep_recursive – adds -r when you try to grep directory;
  • grunt_task_not_found – fixes misspelled grunt commands;
  • gulp_not_task – fixes misspelled gulp tasks;
  • has_exists_script – prepends ./ when script/binary exists;
  • heroku_multiple_apps – adds --app <app> to heroku commands like heroku pg;
  • heroku_not_command – fixes wrong heroku commands like heroku log;
  • history – tries to replace command with the most similar command from history;
  • hostscli – tries to fix hostscli usage;
  • ifconfig_device_not_found – fixes wrong device names like wlan0 to wlp2s0;
  • java – removes .java extension when running Java programs;
  • javac – appends missing .java when compiling Java files;
  • lein_not_task – fixes wrong lein tasks like lein rpl;
  • long_form_help – changes -h to --help when the short form version is not supported
  • ln_no_hard_link – catches hard link creation on directories, suggest symbolic link;
  • ln_s_order – fixes ln -s arguments order;
  • ls_all – adds -A to ls when output is empty;
  • ls_lah – adds -lah to ls;
  • man – changes manual section;
  • man_no_space – fixes man commands without spaces, for example mandiff;
  • mercurial – fixes wrong hg commands;
  • missing_space_before_subcommand – fixes command with missing space like npminstall;
  • mkdir_p – adds -p when you try to create a directory without a parent;
  • mvn_no_command – adds clean package to mvn;
  • mvn_unknown_lifecycle_phase – fixes misspelled life cycle phases with mvn;
  • npm_missing_script – fixes npm custom script name in npm run-script <script>;
  • npm_run_script – adds missing run-script for custom npm scripts;
  • npm_wrong_command – fixes wrong npm commands like npm urgrade;
  • no_command – fixes wrong console commands, for example vom/vim;
  • no_such_file – creates missing directories with mv and cp commands;
  • omnienv_no_such_command – fixes wrong commands for goenv, nodenv, pyenv and rbenv (eg.: pyenv isntall or goenv list);
  • open – either prepends http:// to address passed to open or creates a new file or directory and passes it to open;
  • pip_install – fixes permission issues with pip install commands by adding --user or prepending sudo if necessary;
  • pip_unknown_command – fixes wrong pip commands, for example pip instatl/pip install;
  • php_s – replaces -s by -S when trying to run a local php server;
  • port_already_in_use – kills process that bound port;
  • prove_recursively – adds -r when called with directory;
  • python_command – prepends python when you try to run non-executable/without ./ python script;
  • python_execute – appends missing .py when executing Python files;
  • python_module_error – fixes ModuleNotFoundError by trying to pip install that module;
  • quotation_marks – fixes uneven usage of ' and " when containing args';
  • path_from_history – replaces not found path with a similar absolute path from history;
  • rails_migrations_pending – runs pending migrations;
  • react_native_command_unrecognized – fixes unrecognized react-native commands;
  • remove_shell_prompt_literal – removes leading shell prompt symbol $, common when copying commands from documentations;
  • remove_trailing_cedilla – removes trailing cedillas ç, a common typo for European keyboard layouts;
  • rm_dir – adds -rf when you try to remove a directory;
  • scm_correction – corrects wrong scm like hg log to git log;
  • sed_unterminated_s – adds missing '/' to sed's s commands;
  • sl_ls – changes sl to ls;
  • ssh_known_hosts – removes host from known_hosts on warning;
  • sudo – prepends sudo to the previous command if it failed because of permissions;
  • sudo_command_from_user_path – runs commands from users $PATH with sudo;
  • switch_lang – switches command from your local layout to en;
  • systemctl – correctly orders parameters of confusing systemctl;
  • terraform_init.py – runs terraform init before plan or apply;
  • terraform_no_command.py – fixes unrecognized terraform commands;
  • test.py – runs pytest instead of test.py;
  • touch – creates missing directories before "touching";
  • tsuru_login – runs tsuru login if not authenticated or session expired;
  • tsuru_not_command – fixes wrong tsuru commands like tsuru shell;
  • tmux – fixes tmux commands;
  • unknown_command – fixes hadoop hdfs-style "unknown command", for example adds missing '-' to the command on hdfs dfs ls;
  • unsudo – removes sudo from previous command if a process refuses to run on superuser privilege.
  • vagrant_up – starts up the vagrant instance;
  • whois – fixes whois command;
  • workon_doesnt_exists – fixes virtualenvwrapper env name os suggests to create new.
  • wrong_hyphen_before_subcommand – removes an improperly placed hyphen (apt-install -> apt install, git-log -> git log, etc.)
  • yarn_alias – fixes aliased yarn commands like yarn ls;
  • yarn_command_not_found – fixes misspelled yarn commands;
  • yarn_command_replaced – fixes replaced yarn commands;
  • yarn_help – makes it easier to open yarn documentation;

The following rules are enabled by default on specific platforms only:

  • apt_get – installs app from apt if it not installed (requires python-commandnotfound / python3-commandnotfound);
  • apt_get_search – changes trying to search using apt-get with searching using apt-cache;
  • apt_invalid_operation – fixes invalid apt and apt-get calls, like apt-get isntall vim;
  • apt_list_upgradable – helps you run apt list --upgradable after apt update;
  • apt_upgrade – helps you run apt upgrade after apt list --upgradable;
  • brew_cask_dependency – installs cask dependencies;
  • brew_install – fixes formula name for brew install;
  • brew_reinstall – turns brew install <formula> into brew reinstall <formula>;
  • brew_link – adds --overwrite --dry-run if linking fails;
  • brew_uninstall – adds --force to brew uninstall if multiple versions were installed;
  • brew_unknown_command – fixes wrong brew commands, for example brew docto/brew doctor;
  • brew_update_formula – turns brew update <formula> into brew upgrade <formula>;
  • dnf_no_such_command – fixes mistyped DNF commands;
  • nixos_cmd_not_found – installs apps on NixOS;
  • pacman – installs app with pacman if it is not installed (uses yay, pikaur or yaourt if available);
  • pacman_invalid_option – replaces lowercase pacman options with uppercase.
  • pacman_not_found – fixes package name with pacman, yay, pikaur or yaourt.
  • yum_invalid_operation – fixes invalid yum calls, like yum isntall vim;

The following commands are bundled with The Fuck, but are not enabled by default:

  • git_push_force – adds --force-with-lease to a git push (may conflict with git_push_pull);
  • rm_root – adds --no-preserve-root to rm -rf / command.

Creating your own rules

To add your own rule, create a file named your-rule-name.py in ~/.config/thefuck/rules. The rule file must contain two functions:

match(command: Command) -> bool
get_new_command(command: Command) -> str | list[str]

Additionally, rules can contain optional functions:

side_effect(old_command: Command, fixed_command: str) -> None

Rules can also contain the optional variables enabled_by_default, requires_output and priority.

Command has three attributes: script, output and script_parts. Your rule should not change Command.

Rules api changed in 3.0: To access a rule's settings, import it with from thefuck.conf import settings

settings is a special object assembled from ~/.config/thefuck/settings.py, and values from env (see more below).

A simple example rule for running a script with sudo:

def match(command):
    return ('permission denied' in command.output.lower()
            or 'EACCES' in command.output)


def get_new_command(command):
    return 'sudo {}'.format(command.script)

# Optional:
enabled_by_default = True

def side_effect(command, fixed_command):
    subprocess.call('chmod 777 .', shell=True)

priority = 1000  # Lower first, default is 1000

requires_output = True

More examples of rules, utility functions for rules, app/os-specific helpers.

Settings

Several The Fuck parameters can be changed in the file $XDG_CONFIG_HOME/thefuck/settings.py ($XDG_CONFIG_HOME defaults to ~/.config):

  • rules – list of enabled rules, by default thefuck.const.DEFAULT_RULES;
  • exclude_rules – list of disabled rules, by default [];
  • require_confirmation – requires confirmation before running new command, by default True;
  • wait_command – the max amount of time in seconds for getting previous command output;
  • no_colors – disable colored output;
  • priority – dict with rules priorities, rule with lower priority will be matched first;
  • debug – enables debug output, by default False;
  • history_limit – the numeric value of how many history commands will be scanned, like 2000;
  • alter_history – push fixed command to history, by default True;
  • wait_slow_command – max amount of time in seconds for getting previous command output if it in slow_commands list;
  • slow_commands – list of slow commands;
  • num_close_matches – the maximum number of close matches to suggest, by default 3.
  • excluded_search_path_prefixes – path prefixes to ignore when searching for commands, by default [].

An example of settings.py:

rules = ['sudo', 'no_command']
exclude_rules = ['git_push']
require_confirmation = True
wait_command = 10
no_colors = False
priority = {'sudo': 100, 'no_command': 9999}
debug = False
history_limit = 9999
wait_slow_command = 20
slow_commands = ['react-native', 'gradle']
num_close_matches = 5

Or via environment variables:

  • THEFUCK_RULES – list of enabled rules, like DEFAULT_RULES:rm_root or sudo:no_command;
  • THEFUCK_EXCLUDE_RULES – list of disabled rules, like git_pull:git_push;
  • THEFUCK_REQUIRE_CONFIRMATION – require confirmation before running new command, true/false;
  • THEFUCK_WAIT_COMMAND – the max amount of time in seconds for getting previous command output;
  • THEFUCK_NO_COLORS – disable colored output, true/false;
  • THEFUCK_PRIORITY – priority of the rules, like no_command=9999:apt_get=100, rule with lower priority will be matched first;
  • THEFUCK_DEBUG – enables debug output, true/false;
  • THEFUCK_HISTORY_LIMIT – how many history commands will be scanned, like 2000;
  • THEFUCK_ALTER_HISTORY – push fixed command to history true/false;
  • THEFUCK_WAIT_SLOW_COMMAND – the max amount of time in seconds for getting previous command output if it in slow_commands list;
  • THEFUCK_SLOW_COMMANDS – list of slow commands, like lein:gradle;
  • THEFUCK_NUM_CLOSE_MATCHES – the maximum number of close matches to suggest, like 5.
  • THEFUCK_EXCLUDED_SEARCH_PATH_PREFIXES – path prefixes to ignore when searching for commands, by default [].

For example:

export THEFUCK_RULES='sudo:no_command'
export THEFUCK_EXCLUDE_RULES='git_pull:git_push'
export THEFUCK_REQUIRE_CONFIRMATION='true'
export THEFUCK_WAIT_COMMAND=10
export THEFUCK_NO_COLORS='false'
export THEFUCK_PRIORITY='no_command=9999:apt_get=100'
export THEFUCK_HISTORY_LIMIT='2000'
export THEFUCK_NUM_CLOSE_MATCHES='5'

Third-party packages with rules

If you'd like to make a specific set of non-public rules, but would still like to share them with others, create a package named thefuck_contrib_* with the following structure:

thefuck_contrib_foo
  thefuck_contrib_foo
    rules
      __init__.py
      *third-party rules*
    __init__.py
    *third-party-utils*
  setup.py

The Fuck will find rules located in the rules module.

Experimental instant mode

The default behavior of The Fuck requires time to re-run previous commands. When in instant mode, The Fuck saves time by logging output with script, then reading the log.

gif with instant mode

Currently, instant mode only supports Python 3 with bash or zsh. zsh's autocorrect function also needs to be disabled in order for thefuck to work properly.

To enable instant mode, add --enable-experimental-instant-mode to the alias initialization in .bashrc, .bash_profile or .zshrc.

For example:

eval $(thefuck --alias --enable-experimental-instant-mode)

Developing

See CONTRIBUTING.md

License MIT

Project License can be found here.

thefuck's People

Contributors

abraham-chan avatar brobin avatar bugaevc avatar cjmartian avatar dhilipsiva avatar djh82 avatar duboviy avatar dvjn avatar epse avatar felixonmars avatar hugovk avatar ik1ne avatar josephfrazier avatar kimtree avatar lawben avatar ls0f avatar lukechilds avatar mattkotsenas avatar mcarton avatar mkreder avatar mlk avatar nvbn avatar nwinkler avatar qrqiuren avatar reitermarkus avatar sanketdg avatar scorphus avatar spycheese avatar tjhorner avatar waldyrious avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

thefuck's Issues

Fuck permission denied

On most recent version (1.1.8) I get this error on OSX 10.10.13 when calling fuck. I assume it has something to do with the $PATH walk on the most recent commit. If this is a permissions error, which it almost certainly is, can it be solved programmatically such that future users don't have to chmod 777 anything to get this CLI to work? Can look in more detail tomorrow, but for now this is all I have.

Traceback (most recent call last):
  File "/usr/local/bin/thefuck", line 9, in <module>
    load_entry_point('thefuck==1.18', 'console_scripts', 'thefuck')()
  File "/usr/local/lib/python2.7/site-packages/thefuck/main.py", line 136, in main
    matched_rule = get_matched_rule(command, rules, settings)
  File "/usr/local/lib/python2.7/site-packages/thefuck/main.py", line 93, in get_matched_rule
    if rule.match(command, settings):
  File "/usr/local/lib/python2.7/site-packages/thefuck/rules/no_command.py", line 16, in match
    _get_all_bins()))
  File "/usr/local/lib/python2.7/site-packages/thefuck/rules/no_command.py", line 10, in _get_all_bins
    if exe.is_file()]
  File "/usr/local/lib/python2.7/site-packages/pathlib.py", line 1202, in is_file
    return S_ISREG(self.stat().st_mode)
  File "/usr/local/lib/python2.7/site-packages/pathlib.py", line 1051, in stat
    return self._accessor.stat(self)
  File "/usr/local/lib/python2.7/site-packages/pathlib.py", line 346, in wrapped
    return strfunc(str(pathobj), *args)
OSError: [Errno 13] Permission denied: '/usr/sbin/weakpass_edit'

Output is always "No fucks given"

Default install on OS X with pip doesn't seem to do anything other than return "No fucks given," even with example rules imported. This might not be a code issue--there might be additional setup missing from the documentation.

add maven support

It would be great to support maven commands. See example below. (should be mvn clean install, see last lines of the stack trace)

$ mvn clean insta

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option PermSize=128m; support was removed in 8.0
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=256m; support was removed in 8.0
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Camel :: Example :: Twitter WebSocket 2.15.1
[INFO] ------------------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.536 s
[INFO] Finished at: 2015-04-18T23:15:13+03:00
[INFO] Final Memory: 22M/981M
[INFO] ------------------------------------------------------------------------
[ERROR] Unknown lifecycle phase "insta". You must specify a valid lifecycle phase or a goal in the format : or :[:]:. 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]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/LifecyclePhaseNotFoundException

$ fuck 

No fuck given

fuck this and fuck that

Thoughts on adding these features?

fuck this

  • fuck this <rule name> [hard] [<match rules>] <command spec>
  • Adds <rule name>.py to rules dir with match/command args
  • Somehow determines match rules if not provided
  • Prompts for confirmation after outputting generated file name & code
  • 'hard' argument skips confirmation

fuck that

  • fuck that <rule name> [hard] [<match rule>]
  • To be used after running correct command
  • argument functionality same as with "fuck this ..."
  • command is generated from previously executed command

Things to think about

  • How to specify a rule/command without typing Python on command line
    • Grammar for defining where to match (script/stdout/stderr), what to match, and logical combinations
    • Grammar for command or just take command string?
    • easier to just accept Python from command line?
  • Automatically call 'fuck' after 'fuck this'?
  • Ditch the args except for rule name & open default editor with generated boilerplate rule with script/stdout/stderr included in comments at top of file?

Is it possible for tab completion to replace "fuck" with the command it is going to execute?

I'm not super familiar with implementing tab completion but think it would be handy to be able to preview the suggested command before running it. For example here is the workflow I would like:

$ git push<enter>
fatal: The current branch master has no upstream branch.
To push the current branch and set the remote as upstream, use

    git push --set-upstream origin master


$ fuck<tab>      # tab completion replaces the entire line
$ git push --set-upstream origin master<enter>
git push --set-upstream origin master
Counting objects: 9, done.

Does not work in Elementary OS Freya

OS version:

woverton@pc-wover-06:~$ cat /etc/lsb-release
DISTRIB_ID="elementary OS"
DISTRIB_RELEASE=0.3
DISTRIB_CODENAME=freya
DISTRIB_DESCRIPTION="elementary OS Freya"

Using Fuck

woverton@pc-wover-06:~$ apt-get update
E: Could not open lock file /var/lib/apt/lists/lock - open (13: Permission denied)
E: Unable to lock directory /var/lib/apt/lists/
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?
woverton@pc-wover-06:~$ fuck
Traceback (most recent call last):
  File "/usr/local/bin/thefuck", line 5, in <module>
    from pkg_resources import load_entry_point
  File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 2749, in <module>
    working_set = WorkingSet._build_master()
  File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 444, in _build_master
    ws.require(__requires__)
  File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 725, in require
    needed = self.resolve(parse_requirements(requirements))
  File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 628, in resolve
    raise DistributionNotFound(req)
pkg_resources.DistributionNotFound: psutil
woverton@pc-wover-06:~$

doesn't seem to work with more complex commands with non-standard shells

I'm using fish shell.

This works:

> pacman -S python
error: you cannot perform this operation unless you are root.
> fuck
sudo pacman -S python
[sudo] password for v:

This fails:

> pacman -S (echo python)
error: you cannot perform this operation unless you are root.
> fuck
No fuck given 

I suspect it's trying to execute it with bash to get the output

result = Popen(script, shell=True, stdout=PIPE, stderr=PIPE,

Is there a way to make sure it executes with the correct shell?

cd to mkdir

I'm trying to create a fuck for cd: no such file or directory: <directory_name> which gets converted to mkdir <directory_name>.
I wrote following for match function but is says No fuck given

def match(command, settings):
    return ("cd: no such file or directory:" in command.stderr)

I tried printing stderr which contains /bin/sh: 1: cd: can't cd to <directory_name>. Why is it so and where do I get "cd: no such file or directory:"

add a fuck

I wish to add my own fuck. Any help as to where do I do that and how? Particularly I wish to add fuck for cd command whenever directory is not found i automatically creates one using mkdir. I also want to do so when given a parameter to fuck say fuck hard

Install instructions for Fish are wrong

The install instructions for Fish says to define

function fuck
    eval (thefuck (history | head -n1))
end

This won't work, because history will include the currently-executing command in its output, which means that this will always evaluate to eval (thefuck fuck). It's also rather wasteful, as history dumps a bunch of history. There's also the curious property wherein if thefuck emits multiple lines, they'll end up being joined into a single line, as command substitution splits lines into arguments, and eval joins multiple arguments with spaces instead of newlines.

Both of these issues can be fixed by rewriting it as

function fuck
    thefuck $history[2] | source
end

Doesn't work on Fedora 21

[jurikolo@t2001542 ~]$ rpm -q python
python-2.7.8-8.fc21.x86_64
[jurikolo@t2001542 ~]$ rpm -q python3
python3-3.4.1-16.fc21.x86_64
[jurikolo@t2001542 ~]$ rpm -q python-pip
python-pip-1.5.6-3.fc21.noarch
[jurikolo@t2001542 ~]$ sudo pip install thefuck
Downloading/unpacking thefuck
Downloading thefuck-1.23.tar.gz
Running setup.py (path:/tmp/pip-build-DiyXNk/thefuck/setup.py) egg_info for package thefuck

Downloading/unpacking pathlib (from thefuck)
Downloading pathlib-1.0.1.tar.gz (49kB): 49kB downloaded
Running setup.py (path:/tmp/pip-build-DiyXNk/pathlib/setup.py) egg_info for package pathlib

Downloading/unpacking psutil (from thefuck)
Downloading psutil-2.2.1.tar.gz (223kB): 223kB downloaded
Running setup.py (path:/tmp/pip-build-DiyXNk/psutil/setup.py) egg_info for package psutil

warning: no previously-included files matching '*' found under directory 'docs/_build'

Installing collected packages: thefuck, pathlib, psutil
Running setup.py install for thefuck

Installing thefuck script to /usr/bin

Running setup.py install for pathlib

Running setup.py install for psutil
building '_psutil_linux' extension
gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -DPSUTIL_VERSION=221 -I/usr/include/python2.7 -c psutil/_psutil_linux.c -o build/temp.linux-x86_64-2.7/psutil/_psutil_linux.o
psutil/_psutil_linux.c:12:20: fatal error: Python.h: No such file or directory
#include <Python.h>
^
compilation terminated.
error: command 'gcc' failed with exit status 1
Complete output from command /usr/bin/python -c "import setuptools, tokenize;file='/tmp/pip-build-DiyXNk/psutil/setup.py';exec(compile(getattr(tokenize, 'open', open)(file).read().replace('\r\n', '\n'), file, 'exec'))" install --record /tmp/pip-EWe0Tg-record/install-record.txt --single-version-externally-managed --compile:
running install

running build

running build_py

creating build

creating build/lib.linux-x86_64-2.7

creating build/lib.linux-x86_64-2.7/psutil

copying psutil/_pswindows.py -> build/lib.linux-x86_64-2.7/psutil

copying psutil/_pslinux.py -> build/lib.linux-x86_64-2.7/psutil

copying psutil/_psposix.py -> build/lib.linux-x86_64-2.7/psutil

copying psutil/_psbsd.py -> build/lib.linux-x86_64-2.7/psutil

copying psutil/_pssunos.py -> build/lib.linux-x86_64-2.7/psutil

copying psutil/_psosx.py -> build/lib.linux-x86_64-2.7/psutil

copying psutil/_common.py -> build/lib.linux-x86_64-2.7/psutil

copying psutil/_compat.py -> build/lib.linux-x86_64-2.7/psutil

copying psutil/init.py -> build/lib.linux-x86_64-2.7/psutil

running build_ext

building '_psutil_linux' extension

creating build/temp.linux-x86_64-2.7

creating build/temp.linux-x86_64-2.7/psutil

gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -DPSUTIL_VERSION=221 -I/usr/include/python2.7 -c psutil/_psutil_linux.c -o build/temp.linux-x86_64-2.7/psutil/_psutil_linux.o

psutil/_psutil_linux.c:12:20: fatal error: Python.h: No such file or directory

#include <Python.h>

                ^

compilation terminated.

error: command 'gcc' failed with exit status 1


Cleaning up...
Command /usr/bin/python -c "import setuptools, tokenize;file='/tmp/pip-build-DiyXNk/psutil/setup.py';exec(compile(getattr(tokenize, 'open', open)(file).read().replace('\r\n', '\n'), file, 'exec'))" install --record /tmp/pip-EWe0Tg-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /tmp/pip-build-DiyXNk/psutil
Storing debug log for failure in /root/.pip/pip.log
[jurikolo@t2001542 ~]$
[jurikolo@t2001542 ~]$
[jurikolo@t2001542 ~]$
[jurikolo@t2001542 ~]$ sudo easy_install thefuck
Searching for thefuck
Best match: thefuck 1.23
Adding thefuck 1.23 to easy-install.pth file
Installing thefuck script to /usr/bin

Using /usr/lib/python2.7/site-packages
Processing dependencies for thefuck
Searching for psutil
Reading https://pypi.python.org/simple/psutil/
Best match: psutil 2.2.1
Downloading https://pypi.python.org/packages/source/p/psutil/psutil-2.2.1.tar.gz#md5=1a2b58cd9e3a53528bb6148f0c4d5244
Processing psutil-2.2.1.tar.gz
Writing /tmp/easy_install-bOMCvU/psutil-2.2.1/setup.cfg
Running psutil-2.2.1/setup.py -q bdist_egg --dist-dir /tmp/easy_install-bOMCvU/psutil-2.2.1/egg-dist-tmp-zl8pT0
warning: no previously-included files matching '*' found under directory 'docs/_build'
psutil/_psutil_linux.c:12:20: fatal error: Python.h: No such file or directory
#include <Python.h>
^
compilation terminated.
error: Setup script exited with error: command 'gcc' failed with exit status 1

Running fuck just after nano freezes the shell

$ nano whateverfile, quitting Nano, and immediately running fuck freezes the entire shell (zsh with ohmyzsh) on OSX 10.10 (developer preview FWIW – I never bothered to install the stable version).

image

feature request: common git branch typos

Jonathans-MacBook-Pro:studio jong$ git checkout amster
error: pathspec 'amster' did not match any file(s) known to git.
Jonathans-MacBook-Pro:studio jong$ fuck
No fuck given

What command line interpreter used for rules

Hello,

I want to create a new rule based on the cd command, but I noticed that the returned error is not the same when I use bash or sh.

With bash :

$ cd foo
bash: cd: foo: No such file or directory

With sh :

$ cd foo
sh: 1: cd: can't cd to foo

And when I print command.stderr in the match() function, the stderr is the sh style. So my question is : when we create a new rule, should we use this stderr style to test errors?

Thank you 😃

Support other languages/locales than English

I was searching why it was no giving a fuck when I was trying to use it.
Then I saw this PR:
https://github.com/nvbn/thefuck/pull/30/files

It seems that thefuck is checking for hard coded errors messages so obviously it can't work with other languages than English and the current approach can't allow it.

Any idea how to detect permission errors in a language agnostic way?
For git it should be possible to use the last line of the ouput which contains only the corrected command and nothing language specific.

TheFuck doesn't see my zsh aliases :(

Rules in which get_new_command returns a zsh alias result in command not found errors. Example:

> alias
[...]
baz='echo "it worked!"'
[...]

> cat .thefuck/rules/aliastest.py
def match(command, settings):
    return (command.script == 'foo')

def get_new_command(command, settings):
    return 'baz'

> foo
zsh: command not found: foo

> fuck
baz
zsh: command not found: baz

Remove need for the shell alias

In your doc you mention that one needs to create an alias in order to make thefuck work.

Is there a reason why you did not implement it the way that thefuck directly launches the new command without echoing it back to the subshell? This way it would be easier to setup.

running "fuck" twice almost gave me a heartattack

who@where:~$ fuck
No fuck given
who@where:~$ fuck
fsck from util-linux 2.20.1
e2fsck 1.42.9 (4-Feb-2014)
/dev/sda6 is mounted.

WARNING!!!  The filesystem is mounted.   If you continue you ***WILL***
cause ***SEVERE*** filesystem damage.

Do you really want to continue<n>? no
check aborted.

does not work well with zsh...

I really love this pretty app..

but in my zsh , when I input a command like puthon, it told me

puthon
zsh: command not found: puthon

so thefuck seems did not work... Could you tell me how can I configure zsh ?

Thanks

README.md easy_intall typo

Installation
...
If it fails try to use easy_install:

sudo easy_intall thefuck

should be:

sudo easy_install thefuck

also, running "fuck" did not solve this typo in the README.md ;)

PS: Thanks for adding joy to the command line!

terminal get stuck when no previous commands are given.

I installed this and relaunched. Then I act like title.

 $  fuck

The terminal got stuck.

I quitted the terminal, and relaunched twice.

$  fuck
No fuck given

It worked well.

I am using OS X 10.10.3 + iterm(zsh) + python 2.7.6

`thefuck/thefuck/rules/no_command.py` is not cross-platform

thefuck/thefuck/rules/no_command.py blindly looks for /usr/lib/command-not-found which does not exist on Windows, OS X, or a great many Linux distributions (Debian, for example).

I'd like to suggest a more cross-platform method of finding the correct command:

  • enumerate the list of executables (almost certainly by walking $PATH [or running hash if you have a $SHELL instance])
    • This would be a great chance to also run alias in $SHELL and get the list of aliases, too.
  • find the lowest Levenshtein distance from original_command amongst the list
  • return it

This should make this glorious project even more useful to all the sysadmins on SpecialSnowflakeCustomLinuxDistro and maybe even those stuck on Windows.

fish function in readme is wrong

This doesn't work for me:

function fuck
    thefuck $history[2] | source
end

This works for me:

function fuck
    thefuck $history[1] | source
end

Add support mistakes in homebrew command

For example:
1.

➜ brew docto
Error: Unknown command: docto
➜ brew install elsticsearch
Error: No available formula for elsticsearch
Searching formulae...
Searching taps...

How about i18n?

I'm a Linux user and working with shell commands every day. My system's default language is Chinese, so the output messages of some commonly used tools (git, gcc, etc.) were translated into Chinese in the i18n mechanism of the software itself. So I think it is considerable to match i18n messages.

Do you have any ideas to implement this feature? It may be gossip to write strings of all languages in the match function. Can there be any more beautiful ways to make it?

Running alias

I create a simple rule for my own usage here : https://gist.github.com/fzerorubigd/c8b53fa3231f28f40092

Some time, I type command in another keyboard layout, (as you can see, persian) and I want to use fuck to fix that (I already build a command not found handler, but fuck is better :) )
the problem is, if I use an alias, then the result is detected, but it can not execute it :

$ alias tst=ls
$ فسف 
zsh: command not found: فسف
$ fuck
tst
zsh: command not found: tst

I use zsh 5.0.7 and python 3.4.3 (Archlinux) with thefuck from comunity (and also tested against the master branch and the pip version)

Issue with decoding/non-English terminal

I'll just leave it here

Traceback (most recent call last):
File "/usr/local/bin/thefuck", line 9, in
load_entry_point('thefuck==1.9', 'console_scripts', 'thefuck')()
File "/usr/local/lib/python2.7/dist-packages/thefuck/main.py", line 93, in main
matched_rule = get_matched_rule(command, rules, settings)
File "/usr/local/lib/python2.7/dist-packages/thefuck/main.py", line 69, in get_matched_rule
if rule.match(command, settings):
File "/usr/local/lib/python2.7/dist-packages/thefuck/utils.py", line 41, in wrapper
return fn(command, settings)
File "/usr/local/lib/python2.7/dist-packages/thefuck/rules/no_command.py", line 19, in match
output = _get_output(command, settings)
File "/usr/local/lib/python2.7/dist-packages/thefuck/rules/no_command.py", line 13, in _get_output
return result.stderr.read().decode()
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 24: ordinal not in range(128)

Some Unicode error in Ubuntu 14.10

$ apt-get update
E: Не удалось открыть файл блокировки /var/lib/apt/lists/lock - open (13: Отказано в доступе)
E: Невозможно заблокировать каталог /var/lib/apt/lists/
E: Не удалось открыть файл блокировки /var/lib/dpkg/lock - open (13: Отказано в доступе)
E: Не удалось выполнить блокировку управляющего каталога (/var/lib/dpkg/); у вас есть права суперпользователя?
$ fuck
Traceback (most recent call last):
  File "/usr/local/bin/thefuck", line 9, in <module>
    load_entry_point('thefuck==1.7', 'console_scripts', 'thefuck')()
  File "/usr/local/lib/python2.7/dist-packages/thefuck/main.py", line 91, in main
    matched_rule = get_matched_rule(command, rules, settings)
  File "/usr/local/lib/python2.7/dist-packages/thefuck/main.py", line 67, in get_matched_rule
    if rule.match(command, settings):
  File "/usr/local/lib/python2.7/dist-packages/thefuck/utils.py", line 41, in wrapper
    return fn(command, settings)
  File "/usr/local/lib/python2.7/dist-packages/thefuck/rules/no_command.py", line 19, in match
    output = _get_output(command, settings)
  File "/usr/local/lib/python2.7/dist-packages/thefuck/rules/no_command.py", line 13, in _get_output
    return result.stderr.read().decode()
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.