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
Provenance
- Commit
fcd7e87- Tree
7d39262- Author
Junegunn Choi <junegunn.c@gmail.com>- Committer
Junegunn Choi <junegunn.c@gmail.com>- Parent
3c34dd8
6 files changed+77 added−24 removed
modified:man/man1/fzf.1+8 added-2 removed
736 unmodified lines737 .RS738 e.g. \fBfzf --multi | fzf --sync\fR739 .RE740 .TP741-.B "--listen=HTTP_PORT"741+.B "--listen[=HTTP_PORT]"742 Start HTTP server on the given port. It allows external processes to send743-actions to perform via POST method.743+actions to perform via POST method. If the port number is omitted or given as744+0, fzf will choose the port automatically and export it as \fBFZF_PORT\fR745+environment variable to the child processes started via \fBexecute\fR and746+\fBexecute-silent\fR actions.747 748 e.g.749 \fB# Start HTTP server on port 6266750 fzf --listen 6266751 752 # Send action to the server753 curl -XPOST localhost:6266 -d 'reload(seq 100)+change-prompt(hundred> )'754+755+ # 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"760 Display version information and exit481 unmodified linesmodified:src/options.go+8 added-6 removed
114 unmodified lines115 --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 exit121 122 Environment variables123 FZF_DEFAULT_COMMAND Default command to use when input is tty191 unmodified lines315 BorderLabel labelOpts316 PreviewLabel labelOpts317 Unicode bool318 Tabstop int319- ListenPort int319+ ListenPort *int320 ClearOnExit bool321 Version bool322 }323 1431 unmodified lines1755 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 = false82 unmodified lines1849 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 lines1880 if opts.Tabstop < 1 {1881 errorExit("tab stop must be a positive integer")1882 }1883 1882- if opts.ListenPort < 0 || opts.ListenPort > 65535 {1884+ if opts.ListenPort != nil && (*opts.ListenPort < 0 || *opts.ListenPort > 65535) {1885 errorExit("invalid listen port")1886 }1887 1888 if len(opts.JumpLabels) == 0 {168 unmodified linesmodified:src/server.go+17 added-5 removed
17 unmodified lines18 httpReadTimeout = 10 * time.Second19 maxContentLength = 1024 * 102420 )21 22-func startHttpServer(port int, channel chan []*action) error {23- if port == 0 {24- return nil22+func startHttpServer(port int, channel chan []*action) (error, int) {23+ if port < 0 {24+ return nil, port25 }26 27 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+ }43 44 go func() {45 for {46 conn, err := listener.Accept()9 unmodified lines56 }57 listener.Close()58 }()59 48- return nil60+ return nil, port61 }62 63 // Here we are writing a simplistic HTTP server without using net/http64 // package to reduce the size of the binary.74 unmodified linesmodified:src/terminal.go+19 added-6 removed
201 unmodified lines202 margin [4]sizeSpec203 padding [4]sizeSpec204 strong tui.Attr205 unicode bool206- listenPort int206+ listenPort *int207 borderShape tui.BorderShape208 cleanExit bool209 paused bool210 border tui.Window326 unmodified lines537 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 lines693 }694 695 _, t.hasLoadActions = t.keymap[tui.Load.AsEvent()]696 697- 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 }704 705 return &t706 }707 708+func (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+}715+716 func borderLines(shape tui.BorderShape) int {717 switch shape {718 case tui.BorderHorizontal, tui.BorderRounded, tui.BorderSharp, tui.BorderBold, tui.BorderDouble:719 return 21539 unmodified lines2259 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.Stdout238 unmodified lines2506 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 = env2521 2522 out, _ := cmd.StdoutPipe()2523 cmd.Stderr = cmd.Stdout2524 reader := bufio.NewReader(out)1082 unmodified linesmodified:test/test_go.rb+11 added-5 removed
2627 unmodified lines2628 tmux.until { |lines| assert_includes lines, '>>2' }2629 end2630 2631 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 end2644 2645 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 /{}/{}/'", :Enter520 unmodified linesmodified:CHANGELOG.md+14 added
1 CHANGELOG2 =========3 4+0.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'12+13+ # Say hello14+ curl "localhost:$(cat /tmp/fzf-port)" -d 'preview:echo Hello, fzf is listening on $FZF_PORT.'15+ ```16+- Bug fixes17+18 0.38.019 ------20 - New actions21 - `become(...)` - Replace the current fzf process with the specified1557 unmodified lines