From 25ca5084bb4ab2a2bf2095ca08fa32aa2c04b65a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jeffry=20W=C3=BCrmli?= Date: Thu, 12 Nov 2026 13:29:13 +0100 Subject: [PATCH 1/3] feat: add --plain flag with one tab-separated line per socket --- CHANGELOG.md | 3 + README.md | 20 +++++++ internal/cli/root.go | 1 + internal/cli/run.go | 10 +++- internal/cli/run_test.go | 56 +++++++++++++++++ internal/render/plain.go | 84 ++++++++++++++++++++++++++ internal/render/plain_test.go | 86 +++++++++++++++++++++++++++ internal/render/testdata/plain.golden | 15 +++++ 8 files changed, 274 insertions(+), 1 deletion(-) create mode 100644 internal/render/plain.go create mode 100644 internal/render/plain_test.go create mode 100644 internal/render/testdata/plain.golden diff --git a/CHANGELOG.md b/CHANGELOG.md index 65386cf..21d39b2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/README.md b/README.md index 1c99a6f..a578ec0 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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 ` | 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 | diff --git a/internal/cli/root.go b/internal/cli/root.go index 325bcc6..f1c45c5 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -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)") diff --git a/internal/cli/run.go b/internal/cli/run.go index 0403d5b..d0aa731 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -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 @@ -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")) } @@ -153,6 +158,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 diff --git a/internal/cli/run_test.go b/internal/cli/run_test.go index 88d710b..c208688 100644 --- a/internal/cli/run_test.go +++ b/internal/cli/run_test.go @@ -685,3 +685,59 @@ func TestRootCmd_ExpandedFlagIsParsed(t *testing.T) { t.Errorf("--expanded not applied:\n%s", stdout.String()) } } + +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()) + } +} diff --git a/internal/render/plain.go b/internal/render/plain.go new file mode 100644 index 0000000..bc71b74 --- /dev/null +++ b/internal/render/plain.go @@ -0,0 +1,84 @@ +package render + +import ( + "cmp" + "fmt" + "io" + "net/netip" + "slices" + "strconv" + "strings" + + "github.com/JtheGunner/portwhy/internal/report" +) + +// 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: 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, and an empty value becomes "-". +func plainField(s string) string { + s = strings.Join(strings.Fields(s), " ") + if s == "" { + return plainEmpty + } + return s +} diff --git a/internal/render/plain_test.go b/internal/render/plain_test.go new file mode 100644 index 0000000..efc39e0 --- /dev/null +++ b/internal/render/plain_test.go @@ -0,0 +1,86 @@ +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_NoSocketsWritesNothing(t *testing.T) { + if out := renderPlain(t, nil); out != "" { + t.Errorf("got %q, want empty output", out) + } +} diff --git a/internal/render/testdata/plain.golden b/internal/render/testdata/plain.golden new file mode 100644 index 0000000..91c4216 --- /dev/null +++ b/internal/render/testdata/plain.golden @@ -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 From 9c15ec361891b88bff8a57a67f7542fadaccb34f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jeffry=20W=C3=BCrmli?= Date: Thu, 12 Nov 2026 13:30:30 +0100 Subject: [PATCH 2/3] fix: sanitise control characters in plain output fields --- internal/render/plain.go | 8 +++++--- internal/render/plain_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/internal/render/plain.go b/internal/render/plain.go index bc71b74..660a3f3 100644 --- a/internal/render/plain.go +++ b/internal/render/plain.go @@ -10,6 +10,7 @@ import ( "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 @@ -38,7 +39,7 @@ func Plain(w io.Writer, reports []report.PortReport) error { for _, f := range r.Findings { row := plainRow{ port: f.Socket.Port, - proto: string(f.Socket.Protocol), + proto: plainField(string(f.Socket.Protocol)), addr: f.Socket.Addr.String(), pid: f.Socket.PID, source: plainField(string(f.Explanation.Source)), @@ -74,9 +75,10 @@ func Plain(w io.Writer, reports []report.PortReport) error { } // plainField makes a value safe as a single tab-separated column: tabs and -// line breaks become spaces, and an empty value becomes "-". +// line breaks become spaces, other control characters (such as ESC) become '?', +// and an empty value becomes "-". func plainField(s string) string { - s = strings.Join(strings.Fields(s), " ") + s = textutil.Clean(strings.Join(strings.Fields(s), " ")) if s == "" { return plainEmpty } diff --git a/internal/render/plain_test.go b/internal/render/plain_test.go index efc39e0..aeb2f0b 100644 --- a/internal/render/plain_test.go +++ b/internal/render/plain_test.go @@ -79,6 +79,35 @@ func TestPlain_KeepsLongNamesAndNeutralisesTabs(t *testing.T) { } } +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\x9b"), "t"), + )) + + if strings.Contains(out, "\x1b") || strings.ContainsAny(out, "\x07\x9b") { + 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) From fb17a7524e858654cdbf150d41c7d45d00bb2a5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jeffry=20W=C3=BCrmli?= Date: Thu, 12 Nov 2026 13:30:45 +0100 Subject: [PATCH 3/3] test: use valid UTF-8 literal in plain control character test --- internal/render/plain_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/render/plain_test.go b/internal/render/plain_test.go index aeb2f0b..e3fce78 100644 --- a/internal/render/plain_test.go +++ b/internal/render/plain_test.go @@ -81,10 +81,10 @@ func TestPlain_KeepsLongNamesAndNeutralisesTabs(t *testing.T) { 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\x9b"), "t"), + 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\x9b") { + 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"