|
| 1 | +function killport --description 'Kill the process listening on a specific port' |
| 2 | + set -l options h/help f/force |
| 3 | + argparse -n killport $options -- $argv |
| 4 | + or return |
| 5 | + |
| 6 | + if set -q _flag_help |
| 7 | + echo "Usage: killport [OPTIONS] PORT" |
| 8 | + echo "Kill the process listening on the specified port" |
| 9 | + echo "" |
| 10 | + echo "Options:" |
| 11 | + echo " -h, --help Show this help message" |
| 12 | + echo " -f, --force Skip confirmation prompt" |
| 13 | + return 0 |
| 14 | + end |
| 15 | + |
| 16 | + if test (count $argv) -ne 1 |
| 17 | + echo "killport: exactly one port number required" >&2 |
| 18 | + echo "Usage: killport [OPTIONS] PORT" >&2 |
| 19 | + return 1 |
| 20 | + end |
| 21 | + |
| 22 | + set -l port $argv[1] |
| 23 | + |
| 24 | + # Validate port number |
| 25 | + if not string match -qr '^\d+$' -- $port |
| 26 | + echo "killport: invalid port number '$port'" >&2 |
| 27 | + return 1 |
| 28 | + end |
| 29 | + |
| 30 | + if test $port -lt 1 -o $port -gt 65535 |
| 31 | + echo "killport: port must be between 1 and 65535" >&2 |
| 32 | + return 1 |
| 33 | + end |
| 34 | + |
| 35 | + # Find process using the port |
| 36 | + set -l pid (lsof -ti :$port 2>/dev/null) |
| 37 | + |
| 38 | + if test -z "$pid" |
| 39 | + echo "killport: no process found listening on port $port" >&2 |
| 40 | + return 1 |
| 41 | + end |
| 42 | + |
| 43 | + # Get process details |
| 44 | + set -l process_info (ps -p $pid -o comm= 2>/dev/null) |
| 45 | + |
| 46 | + if test -z "$process_info" |
| 47 | + set process_info "Unknown" |
| 48 | + end |
| 49 | + |
| 50 | + # Confirm before killing (unless --force is set) |
| 51 | + if not set -q _flag_force |
| 52 | + if command -v gum >/dev/null |
| 53 | + if not gum confirm "Kill process: $process_info [PID: $pid] on port $port?" |
| 54 | + echo "Cancelled" |
| 55 | + return 0 |
| 56 | + end |
| 57 | + else |
| 58 | + # Fallback to read if gum is not available |
| 59 | + read -P "Kill process: $process_info [PID: $pid] on port $port? [y/N] " -l response |
| 60 | + if not string match -qir '^y(es)?$' -- $response |
| 61 | + echo "Cancelled" |
| 62 | + return 0 |
| 63 | + end |
| 64 | + end |
| 65 | + end |
| 66 | + |
| 67 | + # Kill the process |
| 68 | + if kill $pid 2>/dev/null |
| 69 | + echo "Killed: $process_info [PID: $pid] on port $port" |
| 70 | + else |
| 71 | + # Try with force if regular kill failed |
| 72 | + if kill -9 $pid 2>/dev/null |
| 73 | + echo "Force killed: $process_info [PID: $pid] on port $port" |
| 74 | + else |
| 75 | + echo "killport: failed to kill PID $pid" >&2 |
| 76 | + return 1 |
| 77 | + end |
| 78 | + end |
| 79 | +end |
0 commit comments