Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and

## [Unreleased]

### Added
- `--plain` prints one tab-separated line per socket (port, protocol, address, PID, source, name) for `grep` and `awk`. Combining it with `--json` is an error.

## [0.3.0] - 2026-11-12

### Added
Expand Down
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,25 @@ With `--kill`, every port gets a status line (`✓` stopped, `ℹ` left untouche
> [!TIP]
> Add `--dry-run` to `--kill` to see exactly what would be executed without stopping anything.

### 📄 Plain output

`--plain` prints one line per listening socket, without grouping, colour or shortening, for `grep`, `awk` and `cut`. Columns are separated by a tab, in this fixed order:

| # | Column | Example |
| :-: | --- | --- |
| 1 | port | `5432` |
| 2 | protocol (`tcp` or `udp`) | `tcp` |
| 3 | address | `0.0.0.0` |
| 4 | PID (`0` if the owner is not visible) | `812` |
| 5 | source that explained the socket (`docker`, `systemd`, `launchd`, `process`) | `docker` |
| 6 | process name (`-` if the owner is not visible) | `postgres` |

Lines are ordered by port, protocol, address and PID. A socket with a hidden owner gets its own line. A port with no listener prints nothing. Exit codes are unchanged, and `--plain` cannot be combined with `--json` (exit code 2).

```bash
portwhy --plain | awk -F'\t' '$5 == "docker" { print $1 }'
```

---

## 🚩 Flags
Expand All @@ -119,6 +138,7 @@ With `--kill`, every port gets a status line (`✓` stopped, `ℹ` left untouche
| 👀 | `--dry-run` | show what `--kill` would do without doing it |
| 🔎 | `--source <name>` | only show ports held by this source: `docker`, `systemd`, `launchd` or `process` (repeatable, comma-separated) |
| 🤖 | `--json` | print machine-readable JSON (`"version": 1`) |
| 📄 | `--plain` | print one tab-separated line per socket: port, protocol, address, PID, source, name (cannot be combined with `--json`) |
| 🎨 | `--no-color` | disable coloured output (`NO_COLOR`, `TERM=dumb` and non-TTY output are honoured too) |
| 🪟 | `--expanded` | show the overview of all ports in the airy layout, one row per port |
| ↔️ | `--wide` | use the full terminal width and keep long values intact |
Expand Down
1 change: 1 addition & 0 deletions internal/cli/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ func newRootCmd(d Deps) (*cobra.Command, *int) {
cmd.SetVersionTemplate("portwhy {{.Version}}\n")
f := cmd.Flags()
f.BoolVar(&flags.JSON, "json", false, "print machine-readable JSON")
f.BoolVar(&flags.Plain, "plain", false, "print one tab-separated line per socket: port, protocol, address, PID, source, name")
f.BoolVar(&flags.NoColor, "no-color", false, "disable coloured output")
f.BoolVarP(&flags.Kill, "kill", "k", false, "stop the cause of a busy port after confirmation")
f.BoolVarP(&flags.Yes, "yes", "y", false, "skip the confirmation prompt (requires --kill)")
Expand Down
10 changes: 9 additions & 1 deletion internal/cli/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ const (

// Flags are the command line options.
type Flags struct {
JSON bool
JSON bool
// Plain prints one tab-separated line per socket for grep and awk.
Plain bool
NoColor bool
Kill bool
Yes bool
Expand All @@ -45,6 +47,9 @@ func Run(ctx context.Context, d Deps, args []string, flags Flags) int {
if err != nil {
return fail(d, err)
}
if flags.Plain && flags.JSON {
return fail(d, errors.New("--plain and --json cannot be combined"))
}
if flags.Yes && !flags.Kill {
return fail(d, errors.New("--yes requires --kill"))
}
Expand Down Expand Up @@ -173,6 +178,9 @@ func write(d Deps, reports []report.PortReport, args []string, flags Flags, sour
if flags.JSON {
return render.JSON(d.Stdout, reports)
}
if flags.Plain {
return render.Plain(d.Stdout, reports)
}
if len(reports) == 0 {
_, err := fmt.Fprintln(d.Stdout, noBusyPortsMessage(sources))
return err
Expand Down
56 changes: 56 additions & 0 deletions internal/cli/run_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -752,6 +752,62 @@ func TestRootCmd_ExpandedFlagIsParsed(t *testing.T) {
}
}

func TestRun_PlainWritesOneLinePerSocket(t *testing.T) {
d, stdout, _ := testDeps(fakeSockets{sockets: []socket.Socket{listener(3001, 43), listener(3000, 42)}})

got := Run(context.Background(), d, nil, Flags{Plain: true})

if got != 0 {
t.Errorf("exit = %d, want 0", got)
}
want := "3000\ttcp\t127.0.0.1\t42\tprocess\tnode\n3001\ttcp\t127.0.0.1\t43\tprocess\tnode\n"
if stdout.String() != want {
t.Errorf("stdout = %q, want %q", stdout.String(), want)
}
}

func TestRun_PlainFreePortPrintsNothingExit1(t *testing.T) {
d, stdout, _ := testDeps(fakeSockets{})

got := Run(context.Background(), d, []string{"3000"}, Flags{Plain: true})

if got != 1 {
t.Errorf("exit = %d, want 1", got)
}
if stdout.Len() != 0 {
t.Errorf("stdout = %q, want empty", stdout.String())
}
}

func TestRun_PlainWithJSONExit2(t *testing.T) {
d, stdout, stderr := testDeps(fakeSockets{sockets: []socket.Socket{listener(3000, 42)}})

got := Run(context.Background(), d, []string{"3000"}, Flags{Plain: true, JSON: true})

if got != 2 {
t.Errorf("exit = %d, want 2", got)
}
if stdout.Len() != 0 {
t.Errorf("stdout = %q, want empty", stdout.String())
}
if !strings.Contains(stderr.String(), "--plain and --json cannot be combined") {
t.Errorf("stderr = %q, want it to explain the conflict", stderr.String())
}
}

func TestRootCmd_PlainFlagIsParsed(t *testing.T) {
d, stdout, _ := testDeps(fakeSockets{sockets: []socket.Socket{listener(3000, 42)}})
cmd, exit := newRootCmd(d)
cmd.SetArgs([]string{"--plain", "3000"})

if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
if *exit != 0 || !strings.HasPrefix(stdout.String(), "3000\ttcp\t") {
t.Errorf("exit = %d, stdout = %q", *exit, stdout.String())
}
}

func TestRun_KillNeedsStderrTTYForPrompt(t *testing.T) {
ft := &fakeTerminator{describe: "x"}
d, _ := killDeps(ft, &freeingSockets{})
Expand Down
86 changes: 86 additions & 0 deletions internal/render/plain.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package render

import (
"cmp"
"fmt"
"io"
"net/netip"
"slices"
"strconv"
"strings"

"github.com/JtheGunner/portwhy/internal/report"
"github.com/JtheGunner/portwhy/internal/textutil"
)

// plainEmpty stands in for a column without a value, such as the name of a
// process that is not visible, so every line keeps the same number of columns.
const plainEmpty = "-"

// plainRow is one line of the plain output.
type plainRow struct {
port uint16
proto string
addr string
pid int
source string
name string
ip netip.Addr
}

// Plain writes one tab-separated line per listening socket: port, protocol,
// address, PID, source, name. There is no header, grouping, colour or
// shortening. Sockets are ordered by port, protocol, address and PID. A socket whose
// owner is not visible gets its own line with PID 0 and the name "-". The
// column order is a public interface.
func Plain(w io.Writer, reports []report.PortReport) error {
var rows []plainRow
for _, r := range reports {
for _, f := range r.Findings {
row := plainRow{
port: f.Socket.Port,
proto: plainField(string(f.Socket.Protocol)),
addr: f.Socket.Addr.String(),
pid: f.Socket.PID,
source: plainField(string(f.Explanation.Source)),
name: plainEmpty,
ip: f.Socket.Addr,
}
if f.Process != nil {
row.name = plainField(f.Process.Name)
}
rows = append(rows, row)
}
}
slices.SortStableFunc(rows, func(a, b plainRow) int {
return cmp.Or(
cmp.Compare(a.port, b.port),
cmp.Compare(a.proto, b.proto),
a.ip.Compare(b.ip),
cmp.Compare(a.pid, b.pid),
)
})

var b strings.Builder
for _, row := range rows {
b.WriteString(strings.Join([]string{
strconv.Itoa(int(row.port)), row.proto, row.addr, strconv.Itoa(row.pid), row.source, row.name,
}, "\t"))
b.WriteByte('\n')
}
if _, err := io.WriteString(w, b.String()); err != nil {
return fmt.Errorf("write plain report: %w", err)
}
return nil
}

// plainField makes a value safe as a single tab-separated column: tabs and
// line breaks become spaces, other control characters (such as ESC) become '?',
// and an empty value becomes "-".
func plainField(s string) string {
s = textutil.Clean(strings.Join(strings.Fields(s), " "))
if s == "" {
return plainEmpty
}
return s
}
115 changes: 115 additions & 0 deletions internal/render/plain_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
package render

import (
"bytes"
"strings"
"testing"

"github.com/JtheGunner/portwhy/internal/detect"
"github.com/JtheGunner/portwhy/internal/report"
"github.com/JtheGunner/portwhy/internal/socket"
)

func renderPlain(t *testing.T, reports []report.PortReport) string {
t.Helper()
var buf bytes.Buffer
if err := Plain(&buf, reports); err != nil {
t.Fatal(err)
}
return buf.String()
}

func TestPlain_Golden(t *testing.T) {
golden(t, "plain.golden", []byte(renderPlain(t, overviewFixture())))
}

func TestPlain_OneLineWithSixTabSeparatedColumnsPerSocket(t *testing.T) {
out := renderPlain(t, overviewFixture())

lines := strings.Split(strings.TrimSuffix(out, "\n"), "\n")
if len(lines) != 15 {
t.Errorf("got %d lines, want one per socket (15):\n%s", len(lines), out)
}
for _, l := range lines {
if n := len(strings.Split(l, "\t")); n != 6 {
t.Errorf("line %q has %d columns, want 6", l, n)
}
}
if strings.Contains(out, "\x1b") {
t.Errorf("output contains colour codes:\n%s", out)
}
}

func TestPlain_HiddenOwnerGetsItsOwnLine(t *testing.T) {
out := renderPlain(t, reportOf(
finding(22, socket.TCP, "0.0.0.0", 0, "", detect.SourceProcess, "owner not visible"),
finding(22, socket.TCP, "::", 0, "", detect.SourceProcess, "owner not visible"),
))

want := "22\ttcp\t0.0.0.0\t0\tprocess\t-\n22\ttcp\t::\t0\tprocess\t-\n"
if out != want {
t.Errorf("got %q, want %q", out, want)
}
}

func TestPlain_OrdersByPortProtocolAddress(t *testing.T) {
out := renderPlain(t, reportOf(
finding(80, socket.UDP, "0.0.0.0", 1, "b", detect.SourceProcess, "b"),
finding(80, socket.TCP, "127.0.0.1", 2, "a", detect.SourceProcess, "a"),
finding(80, socket.TCP, "0.0.0.0", 3, "c", detect.SourceProcess, "c"),
finding(9, socket.TCP, "0.0.0.0", 4, "d", detect.SourceProcess, "d"),
))

want := "9\ttcp\t0.0.0.0\t4\tprocess\td\n" +
"80\ttcp\t0.0.0.0\t3\tprocess\tc\n" +
"80\ttcp\t127.0.0.1\t2\tprocess\ta\n" +
"80\tudp\t0.0.0.0\t1\tprocess\tb\n"
if out != want {
t.Errorf("got\n%s\nwant\n%s", out, want)
}
}

func TestPlain_KeepsLongNamesAndNeutralisesTabs(t *testing.T) {
long := strings.Repeat("x", 200)
out := renderPlain(t, reportOf(finding(80, socket.TCP, "0.0.0.0", 1, long+"\tsplit\nname", detect.SourceProcess, "t")))

want := "80\ttcp\t0.0.0.0\t1\tprocess\t" + long + " split name\n"
if out != want {
t.Errorf("got %q, want %q", out, want)
}
}

func TestPlain_ReplacesControlCharactersInNameAndSource(t *testing.T) {
out := renderPlain(t, reportOf(
finding(80, socket.TCP, "0.0.0.0", 1, "\x1b[31mred\x1b[0m", detect.Source("src\x07\u009b"), "t"),
))

if strings.Contains(out, "\x1b") || strings.ContainsAny(out, "\x07\u009b") {
t.Errorf("output contains control characters: %q", out)
}
want := "80\ttcp\t0.0.0.0\t1\tsrc??\t?[31mred?[0m\n"
if out != want {
t.Errorf("got %q, want %q", out, want)
}
if n := len(strings.Split(strings.TrimSuffix(out, "\n"), "\t")); n != 6 {
t.Errorf("got %d columns, want 6", n)
}
}

func TestPlain_KeepsUnicodeNames(t *testing.T) {
out := renderPlain(t, reportOf(
finding(80, socket.TCP, "0.0.0.0", 1, "LM Studio", detect.SourceProcess, "t"),
finding(81, socket.TCP, "0.0.0.0", 2, "café", detect.SourceProcess, "t"),
))

want := "80\ttcp\t0.0.0.0\t1\tprocess\tLM Studio\n81\ttcp\t0.0.0.0\t2\tprocess\tcafé\n"
if out != want {
t.Errorf("got %q, want %q", out, want)
}
}

func TestPlain_NoSocketsWritesNothing(t *testing.T) {
if out := renderPlain(t, nil); out != "" {
t.Errorf("got %q, want empty output", out)
}
}
15 changes: 15 additions & 0 deletions internal/render/testdata/plain.golden
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
22 tcp 0.0.0.0 0 process -
88 tcp 0.0.0.0 0 process -
137 tcp 0.0.0.0 0 process -
138 tcp 0.0.0.0 0 process -
445 tcp 0.0.0.0 0 process -
1900 udp 0.0.0.0 13250 process Spotify
3000 tcp 127.0.0.1 3983 process Antigravity
3100 tcp 127.0.0.1 3983 process Antigravity
3306 tcp 127.0.0.1 3983 process Antigravity
3890 tcp 127.0.0.1 3983 process Antigravity
5353 udp 0.0.0.0 13250 process Spotify
5432 tcp 0.0.0.0 812 docker postgres
9000 tcp 127.0.0.1 3884 launchd php-fpm
9000 tcp 127.0.0.1 5312 launchd php-fpm
9000 tcp 127.0.0.1 5313 launchd php-fpm
Loading