Skip to content
Myr

Omit port number in `--listen` for automatic port assignment

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Close #3200

authored by Junegunn Choi · committed by Junegunn Choi · parent 3c34dd8 · Browse files · 6 files+77 added−24 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+77 added−24 removed

  • tests:+11 added−5 removed
  • other:+66 added−19 removed

6 files+77 added−24 removed

modified:man/man1/fzf.1+8 added-2 removed
736 unmodified lines
737.RS738e.g. \fBfzf --multi | fzf --sync\fR739.RE740.TP741.B "--listen=HTTP_PORT"741.B "--listen[=HTTP_PORT]"742Start HTTP server on the given port. It allows external processes to send743actions to perform via POST method.743actions to perform via POST method. If the port number is omitted or given as7440, fzf will choose the port automatically and export it as \fBFZF_PORT\fR745environment variable to the child processes started via \fBexecute\fR and746\fBexecute-silent\fR actions.747748e.g.749 \fB# Start HTTP server on port 6266750 fzf --listen 6266751752 # Send action to the server753 curl -XPOST localhost:6266 -d 'reload(seq 100)+change-prompt(hundred> )'754755 # Choose port automatically and export it as $FZF_PORT to the child process756 fzf --listen --bind 'start:execute-silent:echo $FZF_PORT > /tmp/fzf-port'757 \fR758.TP759.B "--version"760Display version information and exit
481 unmodified lines
modified:src/options.go+8 added-6 removed
114 unmodified lines
115 --expect=KEYS Comma-separated list of keys to complete fzf116 --read0 Read input delimited by ASCII NUL characters117 --print0 Print output delimited by ASCII NUL characters118 --sync Synchronous search for multi-staged filtering119 --listen=HTTP_PORT Start HTTP server to receive actions (POST /)119 --listen[=HTTP_PORT] Start HTTP server to receive actions (POST /)120 --version Display version information and exit121122 Environment variables123 FZF_DEFAULT_COMMAND Default command to use when input is tty
191 unmodified lines
315 BorderLabel labelOpts316 PreviewLabel labelOpts317 Unicode bool318 Tabstop int319 ListenPort int319 ListenPort *int320 ClearOnExit bool321 Version bool322}323
1431 unmodified lines
1755 nextString(allArgs, &i, "padding required (TRBL / TB,RL / T,RL,B / T,R,B,L)"))1756 case "--tabstop":1757 opts.Tabstop = nextInt(allArgs, &i, "tab stop required")1758 case "--listen":1759 opts.ListenPort = nextInt(allArgs, &i, "listen port required")1759 port := optionalNumeric(allArgs, &i, 0)1760 opts.ListenPort = &port1761 case "--no-listen":1761 opts.ListenPort = 01762 opts.ListenPort = nil1763 case "--clear":1764 opts.ClearOnExit = true1765 case "--no-clear":1766 opts.ClearOnExit = false
82 unmodified lines
1849 opts.Padding = parseMargin("padding", value)1850 } else if match, value := optString(arg, "--tabstop="); match {1851 opts.Tabstop = atoi(value)1852 } else if match, value := optString(arg, "--listen="); match {1852 opts.ListenPort = atoi(value)1853 port := atoi(value)1854 opts.ListenPort = &port1855 } else if match, value := optString(arg, "--hscroll-off="); match {1856 opts.HscrollOff = atoi(value)1857 } else if match, value := optString(arg, "--scroll-off="); match {1858 opts.ScrollOff = atoi(value)
21 unmodified lines
1880 if opts.Tabstop < 1 {1881 errorExit("tab stop must be a positive integer")1882 }18831882 if opts.ListenPort < 0 || opts.ListenPort > 65535 {1884 if opts.ListenPort != nil && (*opts.ListenPort < 0 || *opts.ListenPort > 65535) {1885 errorExit("invalid listen port")1886 }18871888 if len(opts.JumpLabels) == 0 {
168 unmodified lines
modified:src/server.go+17 added-5 removed
17 unmodified lines
18 httpReadTimeout = 10 * time.Second19 maxContentLength = 1024 * 102420)2122func startHttpServer(port int, channel chan []*action) error {23 if port == 0 {24 return nil22func startHttpServer(port int, channel chan []*action) (error, int) {23 if port < 0 {24 return nil, port25 }2627 listener, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", port))28 if err != nil {29 return fmt.Errorf("port not available: %d", port)29 return fmt.Errorf("port not available: %d", port), port30 }31 if port == 0 {32 addr := listener.Addr().String()33 parts := strings.SplitN(addr, ":", 2)34 if len(parts) < 2 {35 return fmt.Errorf("cannot extract port: %s", addr), port36 }37 var err error38 port, err = strconv.Atoi(parts[1])39 if err != nil {40 return err, port41 }42 }4344 go func() {45 for {46 conn, err := listener.Accept()
9 unmodified lines
56 }57 listener.Close()58 }()5948 return nil60 return nil, port61}6263// Here we are writing a simplistic HTTP server without using net/http64// package to reduce the size of the binary.
74 unmodified lines
modified:src/terminal.go+19 added-6 removed
201 unmodified lines
202 margin [4]sizeSpec203 padding [4]sizeSpec204 strong tui.Attr205 unicode bool206 listenPort int206 listenPort *int207 borderShape tui.BorderShape208 cleanExit bool209 paused bool210 border tui.Window
326 unmodified lines
537 delay = initialDelay538 }539 var previewBox *util.EventBox540 // We need to start previewer if HTTP server is enabled even when --preview option is not specified541 if len(opts.Preview.command) > 0 || hasPreviewAction(opts) || opts.ListenPort > 0 {541 if len(opts.Preview.command) > 0 || hasPreviewAction(opts) || opts.ListenPort != nil {542 previewBox = util.NewEventBox()543 }544 strongAttr := tui.Bold545 if !opts.Bold {
147 unmodified lines
693 }694695 _, t.hasLoadActions = t.keymap[tui.Load.AsEvent()]696697 if err := startHttpServer(t.listenPort, t.serverChan); err != nil {698 errorExit(err.Error())697 if t.listenPort != nil {698 err, port := startHttpServer(*t.listenPort, t.serverChan)699 if err != nil {700 errorExit(err.Error())701 }702 t.listenPort = &port703 }704705 return &t706}707708func (t *Terminal) environ() []string {709 env := os.Environ()710 if t.listenPort != nil {711 env = append(env, fmt.Sprintf("FZF_PORT=%d", *t.listenPort))712 }713 return env714}715716func borderLines(shape tui.BorderShape) int {717 switch shape {718 case tui.BorderHorizontal, tui.BorderRounded, tui.BorderSharp, tui.BorderBold, tui.BorderDouble:719 return 2
1539 unmodified lines
2259 return line2260 }2261 command := t.replacePlaceholder(template, forcePlus, string(t.input), list)2262 cmd := util.ExecCommand(command, false)2263 cmd.Env = t.environ()2264 t.executing.Set(true)2265 if !background {2266 cmd.Stdin = tui.TtyIn()2267 cmd.Stdout = os.Stdout
238 unmodified lines
2506 if items[0] != nil {2507 _, query := t.Input()2508 command := t.replacePlaceholder(commandTemplate, false, string(query), items)2509 cmd := util.ExecCommand(command, true)2510 env := t.environ()2511 if pwindow != nil {2512 height := pwindow.Height()2499 env := os.Environ()2513 lines := fmt.Sprintf("LINES=%d", height)2514 columns := fmt.Sprintf("COLUMNS=%d", pwindow.Width())2515 env = append(env, lines)2516 env = append(env, "FZF_PREVIEW_"+lines)2517 env = append(env, columns)2518 env = append(env, "FZF_PREVIEW_"+columns)2506 cmd.Env = env2519 }2520 cmd.Env = env25212522 out, _ := cmd.StdoutPipe()2523 cmd.Stderr = cmd.Stdout2524 reader := bufio.NewReader(out)
1082 unmodified lines
modified:test/test_go.rb+11 added-5 removed
2627 unmodified lines
2628 tmux.until { |lines| assert_includes lines, '>>2' }2629 end26302631 def test_listen2632 { '--listen 6266' => lambda { URI('http://localhost:6266') },2633 "--listen --sync --bind 'start:execute-silent:echo $FZF_PORT > /tmp/fzf-port'" =>2634 lambda { URI("http://localhost:#{File.read('/tmp/fzf-port').chomp}") } }.each do |opts, fn|2632 tmux.send_keys 'seq 10 | fzf --listen 6266', :Enter2633 tmux.until { |lines| assert_equal 10, lines.item_count }2634 Net::HTTP.post(URI('http://localhost:6266'), 'change-query(yo)+reload(seq 100)+change-prompt:hundred> ')2635 tmux.until { |lines| assert_equal 100, lines.item_count }2636 tmux.until { |lines| assert_equal 'hundred> yo', lines[-1] }2635 tmux.send_keys "seq 10 | fzf #{opts}", :Enter2636 tmux.until { |lines| assert_equal 10, lines.item_count }2637 Net::HTTP.post(fn.call, 'change-query(yo)+reload(seq 100)+change-prompt:hundred> ')2638 tmux.until { |lines| assert_equal 100, lines.item_count }2639 tmux.until { |lines| assert_equal 'hundred> yo', lines[-1] }2640 teardown2641 setup2642 end2643 end26442645 def test_toggle_alternative_preview_window2646 tmux.send_keys "seq 10 | #{FZF} --bind space:toggle-preview --preview-window '<100000(hidden,up,border-none)' --preview 'echo /{}/{}/'", :Enter
520 unmodified lines
modified:CHANGELOG.md+14 added
1CHANGELOG2=========340.39.05------6- If you use `--listen` option without a port number fzf will automatically7 allocate an available port and export it as `$FZF_PORT` environment8 variable.9 ```sh10 # Automatic port assignment11 fzf --listen --bind 'start:execute-silent:echo $FZF_PORT > /tmp/fzf-port'1213 # Say hello14 curl "localhost:$(cat /tmp/fzf-port)" -d 'preview:echo Hello, fzf is listening on $FZF_PORT.'15 ```16- Bug fixes17180.38.019------20- New actions21 - `become(...)` - Replace the current fzf process with the specified
1557 unmodified lines