diff --git a/README.md b/README.md index acf284a..34b8a25 100644 --- a/README.md +++ b/README.md @@ -63,13 +63,14 @@ been running. That context is what turns "kill a random PID and hope" into - **Finds things** — `ports find postgres` → `5432` - **Knows your project** — `ports here` shows what's running for the directory you're in, so you (or your coding agent) reuse the dev server that's up instead of starting a second on :3001. Exit 1 when nothing is, so `ports here --port 3000 || npm run dev` just works. - **Waits for readiness** — `ports wait 3000 --http` blocks until the server actually answers, then prints its row; `--gone` waits until it's free. No sleep-and-retry loops. +- **Opens the page** — `ports open 3000` opens a running server in your browser, after asking it whether it speaks HTTPS or HTTP; `ports open shop` asks which when a project serves more than one - **Diagnoses** — `ports doctor 3000` explains why a port won't free or a row looks odd: uninterruptible sleep, a zombie, TIME_WAIT sockets, a Windows-side listener — findings and the command that fixes each, never an action taken on its own. Bare `ports doctor` checks the whole machine. - **Watches** — `ports --watch` redraws the table live until you interrupt it (still a foreground loop: it dies with its terminal, never a daemon) - **Speaks JSON** (`--json`) so scripts and coding agents can ask what's running ## Principles -- **Observer, never a runner** — it never starts, supervises, or installs anything. Read-only plus targeted kill. There are plenty of process managers; this is not one, and it never will be. +- **Observer, never a runner** — it never starts, supervises, or installs anything. Read-only plus targeted kill. There are plenty of process managers; this is not one, and it never will be. (`ports open` launches a browser, never a server: it hands a URL to the page you already have running, and stays on the observer side of that line.) - **Zero config** — no manifest, no daemon, nothing to declare. All context is inferred from the machine itself. Useful sixty seconds after install, on a machine in whatever state it's in. (An optional `ports-config.yaml` can extend detection with your own framework rules and project markers — an extension layer, never a requirement.) - **Local-first** — a single static binary. No cloud, no accounts, no telemetry. diff --git a/cmd/open.go b/cmd/open.go new file mode 100644 index 0000000..fda520e --- /dev/null +++ b/cmd/open.go @@ -0,0 +1,233 @@ +package cmd + +import ( + "errors" + "fmt" + "os" + "os/exec" + "runtime" + "slices" + "strings" + "sync" + "time" + + "github.com/pyjeebz/ports/internal/inspect" + "github.com/spf13/cobra" +) + +var openCmd = &cobra.Command{ + Use: "open ", + Short: "Open a running web server in the browser", + Long: `ports open opens what a listener serves in your default browser: + + $ ports open 3000 + → opening http://localhost:3000/ + +A port (3000 or :3000) opens that port; a name opens the web server +` + "`ports stop`" + ` would match — a project, framework, container, or +process. ports asks the listener first, HTTPS then HTTP, so the browser +gets the scheme it really speaks — and a port that isn't a web server +(a database, a debugger) is reported, not opened. + +A name with several web servers behind it opens a picker in a terminal; +off one, it's a usage error that lists the ports, so name one. + +$BROWSER is honoured; otherwise it's open on macOS, xdg-open on Linux, +wslview or explorer.exe in WSL, and the URL handler on Windows. ports +opens a browser, never a server: it's an observer still. + +Exit codes: 0 when the browser was asked to open the page, 1 when +nothing is listening, nothing answers HTTP, or no browser could be +started (the URL is printed either way), 2 for a bad invocation or a +name with several web servers off a terminal, 130 when the picker is +left.`, + Args: cobra.ExactArgs(1), + RunE: runOpen, +} + +func init() { + rootCmd.AddCommand(openCmd) +} + +// openURL is the seam the browser launch runs through — tests swap it. +var openURL = launchBrowser + +// webRow is a listener that answers HTTP, and the URL it answered on. +type webRow struct { + inspect.Service + url string +} + +func runOpen(cmd *cobra.Command, args []string) error { + port, isPort, err := portArg(args[0]) + if err != nil { + return err + } + services, err := inspect.Scan(buildInspectConfig()) + if err != nil { + return err + } + rows := match(services, func(s inspect.Service) bool { + if isPort { + return s.Port == port + } + return s.MatchesName(args[0]) + }) + if len(rows) == 0 { + if isPort && !inspect.Listening(port) { + return exitError{code: 1, msg: fmt.Sprintf("nothing listening on :%d", port)} + } + if isPort { + // listening, not yet attributable to a process: ask it anyway + rows = []inspect.Service{{Port: port}} + } else { + return exitError{code: 1, msg: fmt.Sprintf("nothing matching %q is listening — `ports` lists what is", args[0])} + } + } + + web := probeWeb(rows) + switch { + case len(web) == 0 && isPort: + name := inspect.ProcessName(rows[0]) + if name == "" { + name = "the listener" + } + return exitError{code: 1, msg: fmt.Sprintf("%s (:%d) doesn't answer HTTP within %s — it isn't a web server, or isn't serving yet; `ports doctor %d` looks closer", + name, port, inspect.WebProbeTimeout, port)} + case len(web) == 0: + return exitError{code: 1, msg: fmt.Sprintf("%q holds %s — none answers HTTP", args[0], portList(distinctPorts(rows)))} + case len(web) == 1: + return open(web[0].url) + } + + var ports []uint32 + for _, w := range web { + ports = append(ports, w.Port) + } + if !interactive() { + return exitError{code: 2, msg: fmt.Sprintf("%q answers HTTP on %s — name the port, e.g. `ports open %d`", args[0], portList(ports), ports[0])} + } + candidates := make([]inspect.Service, len(web)) + for i, w := range web { + candidates[i] = w.Service + } + s, err := pickOnTerminal(candidates, pickSpec{verb: "open"}) + if errors.Is(err, errPickCancelled) { + return exitError{code: 130, msg: "cancelled — nothing was opened"} + } + if err != nil { + return exitError{code: 1, msg: err.Error()} + } + fmt.Println() + return open(web[slices.IndexFunc(web, func(w webRow) bool { return w.Port == s.Port })].url) +} + +// probeWeb asks each distinct port, all at once, whether it answers HTTP +// — one row per port, in port order. +func probeWeb(rows []inspect.Service) []webRow { + seen := map[uint32]bool{} + var unique []inspect.Service + for _, s := range rows { + if !seen[s.Port] { + seen[s.Port] = true + unique = append(unique, s) + } + } + slices.SortStableFunc(unique, func(a, b inspect.Service) int { return int(a.Port) - int(b.Port) }) + urls := make([]string, len(unique)) + var wg sync.WaitGroup + for i, s := range unique { + wg.Add(1) + go func() { + defer wg.Done() + urls[i], _ = inspect.WebURL(s.Port, s.Addr) + }() + } + wg.Wait() + var web []webRow + for i, s := range unique { + if urls[i] != "" { + web = append(web, webRow{s, urls[i]}) + } + } + return web +} + +func distinctPorts(rows []inspect.Service) []uint32 { + var ports []uint32 + for _, s := range rows { + if !slices.Contains(ports, s.Port) { + ports = append(ports, s.Port) + } + } + slices.Sort(ports) + return ports +} + +func open(url string) error { + fmt.Printf("→ opening %s\n", url) + if err := openURL(url); err != nil { + return exitError{code: 1, msg: fmt.Sprintf("couldn't start a browser: %v — the page is at %s", err, url)} + } + return nil +} + +// browserCommand is how this machine opens a URL: $BROWSER first (its +// first entry, with %s for the URL or the URL appended), else the +// platform's own opener. +func browserCommand(url string) (*exec.Cmd, error) { + if b := strings.TrimSpace(strings.Split(os.Getenv("BROWSER"), string(os.PathListSeparator))[0]); b != "" { + parts := strings.Fields(b) + if strings.Contains(b, "%s") { + for i := range parts { + parts[i] = strings.ReplaceAll(parts[i], "%s", url) + } + } else { + parts = append(parts, url) + } + return exec.Command(parts[0], parts[1:]...), nil + } + switch runtime.GOOS { + case "darwin": + return exec.Command("open", url), nil + case "windows": + // not `start`: cmd.exe would read & in a URL as a command separator + return exec.Command("rundll32", "url.dll,FileProtocolHandler", url), nil + } + if inspect.OnWSL() { + if _, err := exec.LookPath("wslview"); err == nil { + return exec.Command("wslview", url), nil + } + return exec.Command("explorer.exe", url), nil + } + if _, err := exec.LookPath("xdg-open"); err != nil { + return nil, errors.New("no xdg-open here, and $BROWSER is unset") + } + return exec.Command("xdg-open", url), nil +} + +// launchBrowser starts the opener and lets it go. Openers usually hand +// off and exit at once; one that runs the browser in the foreground is +// left running. A quick failure — a bad $BROWSER, xdg-open with no +// desktop — is reported. +func launchBrowser(url string) error { + c, err := browserCommand(url) + if err != nil { + return err + } + if err := c.Start(); err != nil { + return err + } + done := make(chan error, 1) + go func() { done <- c.Wait() }() + select { + case err := <-done: + // explorer.exe exits 1 even when it opened the page + if err != nil && c.Args[0] != "explorer.exe" { + return fmt.Errorf("%s: %w", c.Args[0], err) + } + return nil + case <-time.After(2 * time.Second): + return nil // still running: the browser itself, in the foreground + } +} diff --git a/cmd/open_test.go b/cmd/open_test.go new file mode 100644 index 0000000..f68b3f4 --- /dev/null +++ b/cmd/open_test.go @@ -0,0 +1,37 @@ +package cmd + +import ( + "os" + "slices" + "testing" +) + +// $BROWSER wins: its first entry, with %s standing for the URL, or the +// URL appended when there's no %s. +func TestBrowserCommandHonoursBROWSER(t *testing.T) { + for _, c := range []struct { + env string + want []string + }{ + {"firefox", []string{"firefox", "http://localhost:3000/"}}, + {"firefox --new-tab", []string{"firefox", "--new-tab", "http://localhost:3000/"}}, + {"w3m %s -dump", []string{"w3m", "http://localhost:3000/", "-dump"}}, + // a list, in the platform's separator — ; on Windows, where : is in paths + {"lynx" + string(os.PathListSeparator) + "firefox", []string{"lynx", "http://localhost:3000/"}}, + } { + t.Setenv("BROWSER", c.env) + cmd, err := browserCommand("http://localhost:3000/") + if err != nil || !slices.Equal(cmd.Args, c.want) { + t.Errorf("BROWSER=%q: got %v, %v — want %v", c.env, cmd.Args, err, c.want) + } + } +} + +// A browser that can't start is an error with the URL kept, not a +// silent success. +func TestOpenReportsALaunchFailure(t *testing.T) { + t.Setenv("BROWSER", "/nonexistent/browser") + if err := launchBrowser("http://localhost:3000/"); err == nil { + t.Error("a missing $BROWSER should fail") + } +} diff --git a/cmd/picker.go b/cmd/picker.go index 4212589..1a996d4 100644 --- a/cmd/picker.go +++ b/cmd/picker.go @@ -25,11 +25,35 @@ func interactive() bool { return term.IsTerminal(int(os.Stdin.Fd())) && term.IsTerminal(int(os.Stdout.Fd())) } -// pickAndConfirm runs the picker on the real terminal, in raw mode for +// pickSpec is what a picker is choosing for: the verb in its title, and +// whether a choice is confirmed with y/N before it's acted on. blocked +// says why a row can't be chosen ("" when it can); those rows are dimmed +// and the cursor skips them. none is the error when every row is blocked. +type pickSpec struct { + verb string + confirm bool + blocked func(inspect.Service) string + none string +} + +// stopPick picks a process to stop, confirmed: a stop can't be undone. +// Another user's listener with no pid needs sudo; a Windows-side one +// seen from WSL has no pid here at all. +var stopPick = pickSpec{verb: "stop", confirm: true, blocked: func(s inspect.Service) string { + switch { + case s.Windows: + return "stop it from Windows" + case s.Unowned(): + return "needs sudo" + } + return "" +}, none: "nothing here can be stopped from this shell — other users' listeners need sudo, Windows ones Windows"} + +// pickOnTerminal runs the picker on the real terminal, in raw mode for // exactly as long as it's on screen — restored on return, on a panic, // and on SIGTERM/SIGQUIT, which would otherwise exit past the defer and // leave the shell with no echo. -func pickAndConfirm(rows []inspect.Service) (inspect.Service, error) { +func pickOnTerminal(rows []inspect.Service, spec pickSpec) (inspect.Service, error) { fd := int(os.Stdin.Fd()) saved, err := term.MakeRaw(fd) if err != nil { @@ -56,7 +80,7 @@ func pickAndConfirm(rows []inspect.Service) (inspect.Service, error) { if err != nil { width, height = 0, 0 } - return pick(rows, os.Stdin, os.Stdout, width, height) + return pick(rows, spec, os.Stdin, os.Stdout, width, height) } // sameTarget reports whether b is the stop target a was: the same @@ -86,30 +110,30 @@ func targetPorts(chosen inspect.Service, rows []inspect.Service) string { } // pick draws the rows, moves a cursor with ↑/↓ (or k/j), and on Enter -// asks to confirm, naming the target and every port it holds. Rows -// nothing here can stop — another user's listener with no pid — are -// dimmed and skipped. A list taller than the terminal scrolls in a +// chooses — after a y/N naming the target and every port it holds, when +// the spec confirms. Rows the spec blocks are dimmed and skipped. A list taller than the terminal scrolls in a // window; lines are cut to its width (0 for either means no limit). It // reads keys from in and draws to out with raw-mode \r\n line ends, so a // test can drive it with bytes. -func pick(rows []inspect.Service, in io.Reader, out io.Writer, width, height int) (inspect.Service, error) { +func pick(rows []inspect.Service, spec pickSpec, in io.Reader, out io.Writer, width, height int) (inspect.Service, error) { header, lines := inspect.TableRows(rows) - stoppable := make([]bool, len(rows)) + blocked := make([]string, len(rows)) first := -1 for i, s := range rows { - // a Windows-side listener seen from WSL has no pid here to stop - stoppable[i] = !s.Unowned() && !s.Windows - if stoppable[i] && first < 0 { + if spec.blocked != nil { + blocked[i] = spec.blocked(s) + } + if blocked[i] == "" && first < 0 { first = i } } if first < 0 { - return inspect.Service{}, errors.New("nothing here can be stopped from this shell — other users' listeners need sudo, Windows ones Windows") + return inspect.Service{}, errors.New(spec.none) } cur := first move := func(step int) { for i := cur + step; i >= 0 && i < len(rows); i += step { - if stoppable[i] { + if blocked[i] == "" { cur = i return } @@ -120,7 +144,7 @@ func pick(rows []inspect.Service, in io.Reader, out io.Writer, width, height int // and the confirm line. Too short a terminal for that gets no picker. visible := len(rows) if height > 0 && height < 7 { - return inspect.Service{}, errors.New("the terminal is too short for the picker — name a port or a name, e.g. `ports stop 3000`") + return inspect.Service{}, fmt.Errorf("the terminal is too short for the picker — name a port or a name, e.g. `ports %s 3000`", spec.verb) } if height > 0 { visible = min(len(rows), height-5) @@ -154,7 +178,7 @@ func pick(rows []inspect.Service, in io.Reader, out io.Writer, width, height int _, _ = fmt.Fprintf(out, format+"\r\n", a...) n++ } - say("%s", clip(" stop which? ↑/↓ to move, enter to choose, esc to leave")) + say("%s", clip(" "+spec.verb+" which? ↑/↓ to move, enter to choose, esc to leave")) say("%s", clip(" "+header)) if visible < len(rows) { say("\x1b[2m%s\x1b[0m", clip(more("↑", top))) @@ -163,10 +187,8 @@ func pick(rows []inspect.Service, in io.Reader, out io.Writer, width, height int switch { case i == cur: say("\x1b[7m%s\x1b[0m", clip("› "+lines[i])) - case !stoppable[i] && rows[i].Windows: - say("\x1b[2m%s\x1b[0m", clip(" "+lines[i]+" (stop it from Windows)")) - case !stoppable[i]: - say("\x1b[2m%s\x1b[0m", clip(" "+lines[i]+" (needs sudo)")) + case blocked[i] != "": + say("\x1b[2m%s\x1b[0m", clip(" "+lines[i]+" ("+blocked[i]+")")) default: say("%s", clip(" "+lines[i])) } @@ -190,6 +212,9 @@ func pick(rows []inspect.Service, in io.Reader, out io.Writer, width, height int move(1) case "enter": s := rows[cur] + if !spec.confirm { + return s, nil + } // whatever arrived with the Enter — a paste that runs on past // the newline — is not an answer: only a key pressed after the // question confirms. A paste split across reads can still slip @@ -197,7 +222,7 @@ func pick(rows []inspect.Service, in io.Reader, out io.Writer, width, height int for r.Buffered() > 0 { _, _ = r.ReadByte() } - _, _ = fmt.Fprintf(out, " stop %s (%s)? [y/N] ", inspect.ProcessName(s), targetPorts(s, rows)) + _, _ = fmt.Fprintf(out, " %s %s (%s)? [y/N] ", spec.verb, inspect.ProcessName(s), targetPorts(s, rows)) answer, err := readKey(r) _, _ = fmt.Fprint(out, "\r\n") if err != nil || answer != "y" { diff --git a/cmd/picker_test.go b/cmd/picker_test.go index c962206..5674c03 100644 --- a/cmd/picker_test.go +++ b/cmd/picker_test.go @@ -62,7 +62,7 @@ func TestPickMovesAndConfirms(t *testing.T) { {"up never lands on a row it can't stop", "\x1b[A\x1b[A\ry", 3000}, {"k after j", "jjk\rY", 5432}, } { - s, err := pick(pickRows(), keys(c.keys), io.Discard, 0, 0) + s, err := pick(pickRows(), stopPick, keys(c.keys), io.Discard, 0, 0) if err != nil || s.Port != c.want { t.Errorf("%s: got :%d, %v — want :%d", c.name, s.Port, err, c.want) } @@ -75,7 +75,7 @@ func TestPickCancels(t *testing.T) { for name, k := range map[string]string{ "esc": "\x1b", "q": "q", "ctrl-c": "\x03", "no": "\rn", "enter then enter": "\r\r", "eof": "", } { - if _, err := pick(pickRows(), keys(k), io.Discard, 0, 0); !errors.Is(err, errPickCancelled) { + if _, err := pick(pickRows(), stopPick, keys(k), io.Discard, 0, 0); !errors.Is(err, errPickCancelled) { t.Errorf("%s: got %v, want cancelled", name, err) } } @@ -85,7 +85,7 @@ func TestPickCancels(t *testing.T) { // can't stop marked, and the confirm naming what will stop. func TestPickDraws(t *testing.T) { var out strings.Builder - _, _ = pick(pickRows(), keys("j\rn"), &out, 0, 0) + _, _ = pick(pickRows(), stopPick, keys("j\rn"), &out, 0, 0) for _, want := range []string{"PORT", "PROCESS", "› 5432", "Next.js", "(needs sudo)", "stop PostgreSQL (:5432)? [y/N]"} { if !strings.Contains(out.String(), want) { t.Errorf("picker output missing %q:\n%q", want, out.String()) @@ -94,7 +94,7 @@ func TestPickDraws(t *testing.T) { } func TestPickNothingStoppable(t *testing.T) { - if _, err := pick(pickRows()[:1], keys("\ry"), io.Discard, 0, 0); err == nil || errors.Is(err, errPickCancelled) { + if _, err := pick(pickRows()[:1], stopPick, keys("\ry"), io.Discard, 0, 0); err == nil || !strings.Contains(err.Error(), "other users' listeners need sudo, Windows ones Windows") { t.Errorf("a list of only other users' rows should say so, got %v", err) } } @@ -102,7 +102,7 @@ func TestPickNothingStoppable(t *testing.T) { // A paste that runs on past the Enter — "\ry" in one read — is not a // yes: the confirm takes only a key pressed after it asks. func TestPickPasteNeverConfirms(t *testing.T) { - if _, err := pick(pickRows(), strings.NewReader("\ry"), io.Discard, 0, 0); !errors.Is(err, errPickCancelled) { + if _, err := pick(pickRows(), stopPick, strings.NewReader("\ry"), io.Discard, 0, 0); !errors.Is(err, errPickCancelled) { t.Errorf("a pasted \\ry confirmed: got %v, want cancelled", err) } } @@ -112,7 +112,7 @@ func TestPickPasteNeverConfirms(t *testing.T) { func TestPickConfirmNamesEveryPort(t *testing.T) { rows := append(pickRows(), inspect.Service{Port: 9229, Pid: 1, Process: "node", Framework: "Next.js"}) var out strings.Builder - _, _ = pick(rows, keys("\rn"), &out, 0, 0) + _, _ = pick(rows, stopPick, keys("\rn"), &out, 0, 0) if !strings.Contains(out.String(), "(:3000, :9229)? [y/N]") { t.Errorf("confirm should list both ports pid 1 holds:\n%q", out.String()) } @@ -126,7 +126,7 @@ func TestPickWindows(t *testing.T) { rows = append(rows, inspect.Service{Port: uint32(4000 + i), Pid: int32(100 + i), Process: "python", Framework: "FastAPI", Cmdline: strings.Repeat("x", 200)}) } var out strings.Builder - s, err := pick(rows, keys(strings.Repeat("j", 30)+"\ry"), &out, 60, 12) + s, err := pick(rows, stopPick, keys(strings.Repeat("j", 30)+"\ry"), &out, 60, 12) if err != nil || s.Port != 4030 { t.Fatalf("got :%d, %v — want :4030", s.Port, err) } @@ -190,7 +190,7 @@ func TestPickSkipsWindowsRows(t *testing.T) { {Port: 8000, Pid: 3, Process: "python", Framework: "FastAPI"}, } var out strings.Builder - s, err := pick(rows, keys("k\ry"), &out, 0, 0) + s, err := pick(rows, stopPick, keys("k\ry"), &out, 0, 0) if err != nil || s.Port != 8000 { t.Errorf("got :%d, %v — want :8000", s.Port, err) } @@ -201,7 +201,7 @@ func TestPickSkipsWindowsRows(t *testing.T) { // A terminal too short to hold a frame gets no picker, not a garbled one. func TestPickTooShort(t *testing.T) { - if _, err := pick(pickRows(), keys("\ry"), io.Discard, 80, 6); err == nil || errors.Is(err, errPickCancelled) { + if _, err := pick(pickRows(), stopPick, keys("\ry"), io.Discard, 80, 6); err == nil || errors.Is(err, errPickCancelled) { t.Errorf("a 6-line terminal should be refused, got %v", err) } } diff --git a/cmd/stop.go b/cmd/stop.go index 0005210..91ed69d 100644 --- a/cmd/stop.go +++ b/cmd/stop.go @@ -80,7 +80,7 @@ func pickToStop() error { return noneFound("nothing is listening — nothing to stop") } slices.SortStableFunc(services, func(a, b inspect.Service) int { return int(a.Port) - int(b.Port) }) - s, err := pickAndConfirm(services) + s, err := pickOnTerminal(services, stopPick) if errors.Is(err, errPickCancelled) { return exitError{code: 130, msg: err.Error()} } diff --git a/cmd/suggest.go b/cmd/suggest.go index 4206ca4..72668d1 100644 --- a/cmd/suggest.go +++ b/cmd/suggest.go @@ -114,6 +114,7 @@ var argNouns = map[string]struct{ noun, bare, example string }{ "free": {"a port", "port", "ports free 3000"}, "wait": {"a port or a name", "port or name", "ports wait 3000"}, "stop": {"a port or a name", "port or name", "ports stop 3000"}, + "open": {"a port or a name", "port or name", "ports open 3000"}, "doctor": {"a port", "port", "ports doctor 3000"}, "here": {"a directory", "directory", "ports here ~/projects/shop"}, "completion": {"a shell", "shell", "ports completion zsh"}, diff --git a/internal/inspect/web.go b/internal/inspect/web.go new file mode 100644 index 0000000..a58fdc2 --- /dev/null +++ b/internal/inspect/web.go @@ -0,0 +1,78 @@ +package inspect + +import ( + "crypto/tls" + "fmt" + "net" + "net/http" + "strings" + "time" +) + +// WebProbeTimeout is how long WebURL waits for a plain-HTTP answer: long +// enough for a cold dev server to compile its first page. +const WebProbeTimeout = 4 * time.Second + +// WebURL is the page a listener serves, found by asking it: one HEAD +// over HTTPS, then one over plain HTTP, on each address it answers from +// here (a bound address, or both loopbacks for a wildcard or loopback +// bind). Any answer counts — a 404 or a redirect is as much a web server +// as a 200. HTTPS is asked first because many HTTPS servers answer plain +// HTTP with a 400, which would read as http:// and hand the browser the +// wrong scheme. ok is false when nothing answers HTTP at all. +// +// Unlike the table's URL column, this sends a request — a plain server +// may log the HTTPS attempt as a bad request — so it's for `ports open`, +// asked about one target, never a listing. +func WebURL(port uint32, addr string) (url string, ok bool) { + hosts, shown := loopbacks, "localhost" + switch addr { + case "", "0.0.0.0", "::", "127.0.0.1", "::1", "*": + default: + hosts, shown = []string{addr}, strings.Replace(addr, "%", "%25", 1) + } + for _, scheme := range []string{"https", "http"} { + for _, host := range hosts { + if answers(probes[scheme], scheme, net.JoinHostPort(host, fmt.Sprint(port))) { + return fmt.Sprintf("%s://%s/", scheme, net.JoinHostPort(shown, fmt.Sprint(port))), true + } + } + } + return "", false +} + +// probes are the clients WebURL asks with: never following a redirect +// (the first answer is the proof), never through a proxy (it's a local +// port), and trusting any certificate — a dev server's is self-signed, +// and nothing is sent but a HEAD. A plain server fails the TLS handshake +// at once, so HTTPS needs only a short wait. +var probes = map[string]*http.Client{ + "https": probeClient(time.Second), + "http": probeClient(WebProbeTimeout), +} + +func probeClient(timeout time.Duration) *http.Client { + return &http.Client{ + Timeout: timeout, + CheckRedirect: func(_ *http.Request, _ []*http.Request) error { + return http.ErrUseLastResponse + }, + Transport: &http.Transport{ + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, //nolint:gosec // a HEAD to a local dev server + Proxy: nil, + }, + } +} + +func answers(client *http.Client, scheme, hostport string) bool { + resp, err := client.Head(scheme + "://" + hostport + "/") + if err != nil { + return false + } + _ = resp.Body.Close() + return true +} + +// OnWSL reports whether ports runs inside WSL, where a browser is +// Windows' to open. +func OnWSL() bool { return onWSL() } diff --git a/internal/inspect/web_test.go b/internal/inspect/web_test.go new file mode 100644 index 0000000..04aa64a --- /dev/null +++ b/internal/inspect/web_test.go @@ -0,0 +1,93 @@ +package inspect + +import ( + "fmt" + "net" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" + "time" +) + +func portOf(t *testing.T, addr string) uint32 { + t.Helper() + _, p, _ := net.SplitHostPort(addr) + n, err := strconv.Atoi(p) + if err != nil { + t.Fatal(err) + } + return uint32(n) +} + +// The scheme comes from asking: a plain server is http://, a TLS one is +// https:// — even though it would also answer plain HTTP with a 400. +func TestWebURLScheme(t *testing.T) { + ok := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(404) }) + plain := httptest.NewServer(ok) + defer plain.Close() + secure := httptest.NewTLSServer(ok) + defer secure.Close() + + if url, found := WebURL(portOf(t, plain.Listener.Addr().String()), "127.0.0.1"); !found || !strings.HasPrefix(url, "http://localhost:") { + t.Errorf("plain server: got %q, %v", url, found) + } + if url, found := WebURL(portOf(t, secure.Listener.Addr().String()), "127.0.0.1"); !found || !strings.HasPrefix(url, "https://localhost:") { + t.Errorf("TLS server: got %q, %v", url, found) + } +} + +// A listener that isn't a web server is no URL. +func TestWebURLNotHTTP(t *testing.T) { + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer func() { _ = l.Close() }() + go func() { + for { + c, err := l.Accept() + if err != nil { + return + } + _, _ = c.Write([]byte("+OK not http\r\n")) + _ = c.Close() + } + }() + if url, found := WebURL(portOf(t, l.Addr().String()), ""); found { + t.Errorf("a non-HTTP listener got %q", url) + } +} + +// A cold dev server compiles its first page before it answers; that's +// still a web server. +func TestWebURLWaitsForASlowServer(t *testing.T) { + slow := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + time.Sleep(1500 * time.Millisecond) + })) + defer slow.Close() + if url, found := WebURL(portOf(t, slow.Listener.Addr().String()), ""); !found || !strings.HasPrefix(url, "http://") { + t.Errorf("a server answering after 1.5s: got %q, %v", url, found) + } +} + +// A listener bound to one address is asked there, and the URL points +// there — not at localhost, where it doesn't answer. +func TestWebURLBoundAddress(t *testing.T) { + l, err := net.Listen("tcp", "127.0.0.2:0") + if err != nil { + t.Skip("no 127.0.0.2 here (macOS has only 127.0.0.1)") + } + srv := httptest.NewUnstartedServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + srv.Listener = l + srv.Start() + defer srv.Close() + port := portOf(t, l.Addr().String()) + if url, found := WebURL(port, "127.0.0.2"); !found || url != fmt.Sprintf("http://127.0.0.2:%d/", port) { + t.Errorf("a 127.0.0.2 bind: got %q, %v", url, found) + } + if url, found := WebURL(port, "fe80::1%eth9"); found { + t.Errorf("an address it isn't on answered: %q", url) + } +} diff --git a/test/integration/ports_test.go b/test/integration/ports_test.go index b4bafbe..582a78a 100644 --- a/test/integration/ports_test.go +++ b/test/integration/ports_test.go @@ -870,3 +870,111 @@ func TestStopPicker(t *testing.T) { } AssertOutputContains(t, stderr, "needs a port or a name") } + +// browserRecorder points $BROWSER at a script that writes the URL it's +// handed to a file, so `ports open` runs its real launch path without a +// browser. Returns a func that reads what was opened. +func browserRecorder(t *testing.T) func() string { + t.Helper() + if runtime.GOOS == "windows" { + t.Skip("the recorder is a shell script") + } + dir := t.TempDir() + got := filepath.Join(dir, "opened") + script := filepath.Join(dir, "browser") + if err := os.WriteFile(script, []byte("#!/bin/sh\necho \"$1\" > "+got+"\n"), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("BROWSER", script) + return func() string { + b, _ := os.ReadFile(got) + return strings.TrimSpace(string(b)) + } +} + +func TestOpen(t *testing.T) { + opened := browserRecorder(t) + web, err := FindFreePort() + if err != nil { + t.Fatal(err) + } + fixture := HTTPFixture(t, web) + defer fixture.Stop() + fixture.WaitReady(t) + + stdout, stderr, code := RunPorts(t, "open", strconv.Itoa(web)) + want := fmt.Sprintf("http://localhost:%d/", web) + if code != 0 || opened() != want { + t.Fatalf("open :%d exited %d, opened %q, want %q\n%s%s", web, code, opened(), want, stdout, stderr) + } + AssertOutputContains(t, stdout, "opening "+want) + + raw, err := FindFreePort() + if err != nil { + t.Fatal(err) + } + notWeb := ResetFixture(t, raw) + defer notWeb.Stop() + notWeb.WaitReady(t) + _, stderr, code = RunPorts(t, "open", strconv.Itoa(raw)) + if code != 1 { + t.Fatalf("open on a non-HTTP port exited %d, want 1: %s", code, stderr) + } + AssertOutputContains(t, stderr, "doesn't answer HTTP") + + free, err := FindFreePort() + if err != nil { + t.Fatal(err) + } + _, stderr, code = RunPorts(t, "open", strconv.Itoa(free)) + if code != 1 { + t.Fatalf("open on a free port exited %d, want 1", code) + } + AssertOutputContains(t, stderr, "nothing listening") +} + +// A name with two web servers behind it asks which — or, off a +// terminal, is a usage error naming both ports. +func TestOpenSeveral(t *testing.T) { + opened := browserRecorder(t) + a, err := FindFreePort() + if err != nil { + t.Fatal(err) + } + b, err := FindFreePort() + if err != nil || b == a { + t.Skip("couldn't find two free ports") + } + // a named folder: a temp dir's own name (001) would read as a port + dir := filepath.Join(t.TempDir(), "open-two") + if err := os.Mkdir(dir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "package.json"), []byte(`{"name": "fixture"}`), 0o644); err != nil { + t.Fatal(err) + } + server := fmt.Sprintf(`const http = require('http'); +for (const p of [%d, %d]) http.createServer((q, r) => r.end('ok')).listen(p); +`, a, b) + if err := os.WriteFile(filepath.Join(dir, "server.js"), []byte(server), 0o644); err != nil { + t.Fatal(err) + } + f := NewFixture(t, "node-two", dir, b, "node", "server.js") + defer f.Stop() + f.WaitReady(t) + project := filepath.Base(dir) + + _, stderr, code := RunPorts(t, "open", project) + if code != 2 { + t.Fatalf("open by a name with two web servers, off a terminal, exited %d, want 2: %s", code, stderr) + } + AssertOutputContains(t, stderr, fmt.Sprintf(":%d", a), fmt.Sprintf(":%d", b)) + + lo, hi := min(a, b), max(a, b) + out, code := RunPortsPTY(t, []string{"j", "\r"}, "open", project) + want := fmt.Sprintf("http://localhost:%d/", hi) + if code != 0 || opened() != want { + t.Fatalf("picker exited %d, opened %q, want %q (the second of :%d, :%d):\n%s", code, opened(), want, lo, hi, out) + } + AssertOutputContains(t, out, "open which?") +} diff --git a/web/content/docs/commands.mdx b/web/content/docs/commands.mdx index c7d87b8..2dc0c10 100644 --- a/web/content/docs/commands.mdx +++ b/web/content/docs/commands.mdx @@ -68,6 +68,27 @@ A port (`3000` or `:3000`) waits for any listener on it — anything numeric is Exits `0` when the condition is met, `1` when the timeout passes first — saying what it was waiting on and the command that moves things along — `2` for a bad invocation, and `130` when interrupted. ports wait only watches; it never starts anything. + + +## ports open \ + +Open what a listener serves in your default browser. + +```sh +$ ports open 3000 +→ opening http://localhost:3000/ + +$ ports open shop + open which? ↑/↓ to move, enter to choose, esc to leave + PORT PROCESS PROJECT UPTIME URL +› 3000 Next.js shop 2h http://localhost:3000 + 6006 Storybook shop 2h http://localhost:6006 +``` + +A port opens that port; a name opens the web server `ports stop` would match. ports asks the listener before it opens anything — one `HEAD` over HTTPS, then over HTTP — so the browser gets the scheme the server really speaks, and a port that isn't a web server (a database, a debugger, one still starting) is reported with exit `1` rather than opened. A cold dev server gets a few seconds to compile its first page before it answers; a plain-HTTP server may log the HTTPS attempt as a bad request. A name with several web servers behind it opens a picker in a terminal; off one — a script, an agent — it's a usage error (exit `2`) that lists the ports, so name one. + +`$BROWSER` is honoured (its first entry, split on spaces, no shell; `%s` stands for the URL). Otherwise ports uses `open` on macOS, `xdg-open` on Linux, `wslview` or `explorer.exe` inside WSL, and the URL handler on Windows. If no browser starts, the URL is printed and the exit is `1`. ports opens a browser, never a server. + @@ -224,10 +245,10 @@ The same three codes everywhere, grep-style — so `ports doctor 3000 && ./deplo | Code | Meaning | | ---- | ------- | | `0` | Clean — the table rendered, every stop succeeded, every doctor finding was ✓. | -| `1` | The invocation was fine, but there's something to report: `find` matched nothing, `here` found nothing running, `wait` timed out, a stop failed or `--expect` refused it, `stop` found only rows it had to skip, or doctor found something ⚠ or ✗. | -| `2` | The invocation itself was unusable — an unknown command or flag, a flag on a command that doesn't take it, a bad value (`--sort name`, `--format yaml`, a port outside 1–65535 like `70000` — never read as a name), a wrong argument count, or a config file that exists but doesn't parse. | +| `1` | The invocation was fine, but there's something to report: `find` matched nothing, `here` found nothing running, `wait` timed out, `open` found nothing answering HTTP or couldn't start a browser, a stop failed or `--expect` refused it, `stop` found only rows it had to skip, or doctor found something ⚠ or ✗. | +| `2` | The invocation itself was unusable — an unknown command or flag, a flag on a command that doesn't take it, a bad value (`--sort name`, `--format yaml`, a port outside 1–65535 like `70000` — never read as a name), a wrong argument count, a config file that exists but doesn't parse, or `open` given a name with several web servers and no terminal to ask on. | -An interrupted `ports wait` exits `130` — its condition was never met — and so does a stop picker left without choosing; an interrupted `ports --watch` exits `0`, since Ctrl-C is how a watch ends. Errors report on stderr; stdout stays clean for whatever's piping it — and with `--json`, a query that found nothing still prints `[]`. +An interrupted `ports wait` exits `130` — its condition was never met — and so does a stop or open picker left without choosing; an interrupted `ports --watch` exits `0`, since Ctrl-C is how a watch ends. Errors report on stderr; stdout stays clean for whatever's piping it — and with `--json`, a query that found nothing still prints `[]`. ## Scripts and agents