Metadata-Version: 2.4
Name: whyfail-cli
Version: 0.1.0
Summary: Run a command; when it fails, explain why and how to fix it.
Author: Kamran
License-Expression: MIT
Project-URL: Homepage, https://github.com/UnknownDevvIn/whyfail
Project-URL: Source, https://github.com/UnknownDevvIn/whyfail
Project-URL: Issues, https://github.com/UnknownDevvIn/whyfail/issues
Keywords: cli,errors,debug,diagnostics,developer-tools
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Software Development :: Debuggers
Classifier: Topic :: Utilities
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

<div align="center">

# whyfail

### Run a command. When it fails, **know why and what to do about it.**

`whyfail` re-runs the command you just ran, reads the error, and matches it against
known failure patterns — then tells you the cause and the fix. No copy-pasting errors.
No asking a chatbot. No config to start.

</div>

```console
$ whyfail cat missing.conf
cat: missing.conf: No such file or directory

------------------------------------------------------------
why: A file or directory the command needs does not exist.
fix: Check the path. Run with `ls -la` to see what's actually there.
```

[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![Python 3.8+](https://img.shields.io/badge/python-3.8%2B-blue)](https://www.python.org/downloads/)
[![CI](https://github.com/UnknownDevvIn/whyfail/actions/workflows/test.yml/badge.svg)](https://github.com/UnknownDevvIn/whyfail/actions/workflows/test.yml)
[![Status: Beta](https://img.shields.io/badge/status-beta-yellow)]()

---

## Why this exists

Every developer has this moment: you run a command, it fails, and the error is *just* familiar
enough that you know you've solved it before — but you can't remember how. So you grep the
internet, re-read the same StackOverflow page, and lose ten minutes.

Tools like `thefuck` assume the failure was a typo and re-run with guesses. `whyfail`
assumes the failure is real and tells you what it means. That's the missing half.

- **Zero config** — works the moment it's installed
- **No daemon, no state, no network** — pure local rules matching
- **Nothing hidden** — if no rule matches, you still get the raw error and exit code

## Install

```sh
pip install whyfail-cli        # or
pipx install whyfail-cli       # isolated, recommended for CLIs
uv tool install whyfail-cli    # if you're on uv
```

The distribution is `whyfail-cli` (the bare PyPI name `whyfail` belongs to an
unrelated project); the command you type stays **`whyfail`**.

No install needed to try it — the whole tool is one stdlib-only file:

```sh
python3 whyfail.py <command>
```

Requires Python 3.8+.

## Usage

```sh
whyfail <command> [args...]
whyfail -- <command>           # if your command starts with a dash
```

| Situation | What happens |
|---|---|
| Command succeeds | Output passes through untouched on its own streams, exit `0` — whyfail is silent |
| Command fails, rule matches | Raw output on its own streams, then "why:" + "fix:" on stderr; exits with the command's own exit code |
| Command fails, no rule matches | Raw output, plus a nudge to add a rule; exits with the command's own exit code |
| Command is killed by a signal | Exit `128 + signal` (shell convention), like the shell itself |
| Command doesn't exist | Diagnosed, exit `127` |
| Command exists but isn't runnable (`Permission denied` / `Exec format error`) | Diagnosed, exit `126` |
| `whyfail --help` | Usage text, exit `0` |
| No arguments / bare `--` | Usage text, exit `2` |

## What it recognizes

| Error you're seeing | what whyfail tells you |
|---|---|
| `EADDRINUSE` / "Address already in use" | Kill the process holding the port, or use another |
| `ModuleNotFoundError` | `pip install <module>` or fix `PYTHONPATH` |
| `No such file or directory` | Check the path — `ls -la` first |
| `Permission denied` | `chmod`/ownership fix — `sudo` only if you know it's safe |
| `command not found` | Install it or fix `PATH` (works for both `exec`-style and shell-style errors) |
| `Exec format error` | Add/check the shebang, or run it through its interpreter (`python3 <file>`) |
| Node/nvm version mismatch | Re-run `nvm use` |
| `SyntaxError` / "Unexpected token" | Fix the line the error points at |
| `ENOTFOUND` / DNS / request failed | Check network and proxy |
| Database does not exist | Create it (`createdb` / your ORM's migrate command) |
| npm `ERR!` blocks | `node_modules` + lockfile reset, then `npm install` |
| webpack "Can't resolve 'x'" | `npm install x` or check the import path |

## Custom rules — the real power

Every rule is a regex searched against the failed command's output. Add your own in
`~/.config/whyfail/rules.json` (or `$XDG_CONFIG_HOME/whyfail/rules.json`):

```json
[
  {
    "pattern": "ewp-token expired",
    "cause": "Your ephemeral token ran out; it's valid ~30 minutes.",
    "fix": "Re-auth:  ewp login   then retry."
  },
  {
    "pattern": "Cannot find module '([^']+)' from '([^']+)'",
    "cause": "The module {1} is not installed (required from {2}).",
    "fix": "npm install {1}"
  }
]
```

`{1}` is replaced by the first capture group, `{2}` by the second, and so on.
User rules are matched **before** built-ins, so you can override or extend anything.

Robust by design: entries without a `pattern`, non-string patterns, invalid
regexes and hostile `{0.x}` templates are skipped — never a crash. Because
Python's regex engine can't be interrupted, user-rule matching runs in a tiny
subprocess with a hard 3-second cap, so a pathological pattern can't hang the
tool either.

## How it works

1. `whyfail` runs the exact command you gave it, capturing stdout+stderr (undecodable bytes are replaced, never fatal).
2. On a non-zero exit, built-in rules are searched synchronously; user rules run in a killable subprocess with a 3s cap.
3. Every hit prints `why:` (cause) and `fix:` (fix). No hit? The raw error is still there, plus a nudge to write your own rule.

That's the entire lifecycle. No state to clean up, no server, nothing to forget to stop.

## Development

```sh
python3 -m venv .venv && ./.venv/bin/pip install -e .
./.venv/bin/python test_whyfail.py      # plain-assert suite, zero deps
```

## Tested and verified

The suite (`test_whyfail.py`) is plain asserts — no pytest, no mocks, no
framework — and every check drives the real code paths. **28 checks, all
passing**, including on a machine with a secretly hostile `~/.config/whyfail/`
present (the suite isolates `$XDG_CONFIG_HOME` for exactly that reason).

| What is tested | Proves |
|---|---|
| Real failing commands (`cat` missing file, broken imports, missing executables) | built-in rules match real output, not fixtures |
| Success passthrough, incl. a command warning on stderr | silent on success; neither stream is dropped or rerouted |
| Exit codes on every path | `0` success · command's own code on failure (e.g. `3` stays `3`) · `127` missing command · `126` not-runnable · `143` for SIGTERM deaths · `2` usage |
| `--`, bare `--`, `--help`, `-h`, no args | flag handling; bare `--` is a friendly usage message, never a traceback |
| Non-UTF-8 bytes in child output | invalid bytes are replaced, never a crash |
| Every built-in rule, with its own payload | all 13 rules hit their pattern and produce a fix |
| Capture-group interpolation `{1}` / `{2}` | formats the real group; out-of-range or optional-unmatched tokens stay raw (never `None`) |
| Malicious `rules.json` | non-dict entries, invalid regexes, `{1.__class__}` templates, missing/empty patterns — all skipped, still diagnoses fine |
| A 200,000-char pattern and ~90 KB of non-ASCII error text | no `E2BIG`/argv crashes (payload travels on stdin) |
| Catastrophic regex `(a+)+$` | timed out in a killable subprocess — no hang (Python's `re` can't be interrupted from threads) |

CI (Python 3.9–3.13, every push/PR) runs the suite, then **builds the sdist +
wheel and installs the wheel into a fresh venv and smokes the CLI** — so the
artifact users install is verified, not just the source tree.

## Roadmap

- Project-local `whyfail.json` rules
- Optional LLM fallback (`whyfail --llm`) when no rule matches — PRs welcome
- Shell-history hook: `whyfail !!` re-runs your last failed command

## Contributing

The fastest way to make whyfail better is a new rule: add a pattern row and the
one-line test that proves it (see the rules table and test file — it takes
minutes). PRs, issues, and rule ideas are all welcome. Please keep it
dependency-free and 3.8-compatible.

## License

MIT © Kamran
