Skip to content
Myr

Add GET endpoints for getting the state of the finder

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

* GET / (or GET /current) * GET /query

authored by Junegunn Choi · committed by Junegunn Choi · parent de0da86 · Browse files · 6 files+66 added−22 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+66 added−22 removed

  • tests:+5 added−2 removed
  • other:+61 added−20 removed

6 files+66 added−22 removed

modified:man/man1/fzf.1+11 added-3 removed
720 unmodified lines
721e.g. \fBfzf --multi | fzf --sync\fR722.RE723.TP724.B "--listen=HTTP_PORT"725Start HTTP server on the given port to receive actions via POST requests.725Start HTTP server on the given port. It allows external processes to send726actions to perform via POST method, or retrieve the current state of the727finder.728729e.g.730 \fB# Start HTTP server on port 6266731 fzf --listen 6266732731 # Send action to the server732 curl -XPOST localhost:6266 -d 'reload(seq 100)+change-prompt(hundred> )'733 # Send action to the server via POST method734 curl localhost:6266 -d 'reload(seq 100)+change-prompt(hundred> )'735736 # Retrieve the current item737 curl localhost:6266738739 # Retrieve the query string740 curl localhost:6266/query741 \fR742743The port number is exported as \fB$FZF_LISTEN_PORT\fR on the child processes.744.TP
428 unmodified lines
modified:src/options.go+1 added-1 removed
111 unmodified lines
112 --expect=KEYS Comma-separated list of keys to complete fzf113 --read0 Read input delimited by ASCII NUL characters114 --print0 Print output delimited by ASCII NUL characters115 --sync Synchronous search for multi-staged filtering116 --listen=HTTP_PORT Start HTTP server to receive actions (POST /)116 --listen=HTTP_PORT Start HTTP server to receive actions117 --version Display version information and exit118119 Environment variables120 FZF_DEFAULT_COMMAND Default command to use when input is tty
1850 unmodified lines
modified:src/server.go+22 added-9 removed
4 unmodified lines
5 "bytes"6 "errors"7 "fmt"8 "net"9 "regexp"10 "strconv"11 "strings"12 "time"13)1415const (16 crlf = "\r\n"17 httpPattern = "^(GET|POST) (/[^ ]*) HTTP"18 httpOk = "HTTP/1.1 200 OK" + crlf19 httpBadRequest = "HTTP/1.1 400 Bad Request" + crlf20 httpReadTimeout = 10 * time.Second21 maxContentLength = 1024 * 102422)2322func startHttpServer(port int, channel chan []*action) error {24var (25 httpRegexp *regexp.Regexp26)2728func startHttpServer(port int, requestChan chan []*action, responseChan chan string) error {29 if port == 0 {30 return nil31 }32
1 unmodified line
34 if err != nil {35 return fmt.Errorf("port not available: %d", port)36 }3738 httpRegexp = regexp.MustCompile(httpPattern)39 go func() {40 for {41 conn, err := listener.Accept()42 if err != nil {
2 unmodified lines
45 } else {46 continue47 }48 }42 conn.Write([]byte(handleHttpRequest(conn, channel)))49 conn.Write([]byte(handleHttpRequest(conn, requestChan, responseChan)))50 conn.Close()51 }52 listener.Close()53 }()
6 unmodified lines
60//61// * No --listen: 2.8MB62// * --listen with net/http: 5.7MB63// * --listen w/o net/http: 3.3MB57func handleHttpRequest(conn net.Conn, channel chan []*action) string {64func handleHttpRequest(conn net.Conn, requestChan chan []*action, responseChan chan string) string {65 contentLength := 066 body := ""67 response := func(header string, message string) string {68 return header + fmt.Sprintf("Content-Length: %d%s", len(message), crlf+crlf+message)69 }70 bad := func(message string) string {61 message += "\n"62 return httpBadRequest + fmt.Sprintf("Content-Length: %d%s", len(message), crlf+crlf+message)71 return response(httpBadRequest, strings.TrimSpace(message)+"\n")72 }73 conn.SetReadDeadline(time.Now().Add(httpReadTimeout))74 scanner := bufio.NewScanner(conn)75 scanner.Split(func(data []byte, atEOF bool) (int, []byte, error) {
12 unmodified lines
88 for scanner.Scan() {89 text := scanner.Text()90 switch section {91 case 0:83 if !strings.HasPrefix(text, "POST / HTTP") {84 return bad("invalid request method")92 httpMatch := httpRegexp.FindStringSubmatch(text)93 if len(httpMatch) != 3 {94 return bad("invalid HTTP request: " + text)95 }96 if httpMatch[1] == "GET" {97 requestChan <- []*action{{t: actEvaluate, a: httpMatch[2][1:]}}98 return response(httpOk, <-responseChan)99 }100 section++101 case 1:102 if text == crlf {103 if contentLength == 0 {
29 unmodified lines
133 }134 if len(actions) == 0 {135 return bad("no action specified")136 }123124 channel <- actions137 requestChan <- actions138 return httpOk139}
modified:src/terminal.go+16 added-4 removed
199 unmodified lines
200 suppress bool201 sigstop bool202 startChan chan fitpad203 killChan chan int204 serverChan chan []*action204 serverRequestChan chan []*action205 serverResponseChan chan string206 slab *util.Slab207 theme *tui.ColorTheme208 tui tui.Renderer209 executing *util.AtomicBool
66 unmodified lines
276 actClose277 actDeleteChar278 actDeleteCharEOF279 actEndOfLine280 actEvaluate281 actForwardChar282 actForwardWord283 actKillLine284 actKillWord
315 unmodified lines
600 slab: util.MakeSlab(slab16Size, slab32Size),601 theme: opts.Theme,602 startChan: make(chan fitpad, 1),603 killChan: make(chan int),602 serverChan: make(chan []*action),604 serverRequestChan: make(chan []*action),605 serverResponseChan: make(chan string),606 tui: renderer,607 initFunc: func() { renderer.Init() },608 executing: util.NewAtomicBool(false)}609 t.prompt, t.promptLen = t.parsePrompt(opts.Prompt)
13 unmodified lines
623 }624 t.separator, t.separatorLen = t.ansiLabelPrinter(bar, &tui.ColSeparator, true)625 }626624 if err := startHttpServer(t.listenPort, t.serverChan); err != nil {627 if err := startHttpServer(t.listenPort, t.serverRequestChan, t.serverResponseChan); err != nil {628 errorExit(err.Error())629 }630631 return &t
1901 unmodified lines
2533 }2534 select {2535 case event = <-eventChan:2536 needBarrier = true2534 case actions = <-t.serverChan:2537 case actions = <-t.serverRequestChan:2538 event = tui.Invalid.AsEvent()2539 needBarrier = false2540 }2541 }
74 unmodified lines
2616 case actExecute, actExecuteSilent:2617 t.executeCommand(a.a, false, a.t == actExecuteSilent)2618 case actExecuteMulti:2619 t.executeCommand(a.a, true, false)2620 case actEvaluate:2621 response := ""2622 switch a.a {2623 case "", "current":2624 response = t.currentItem().AsString(t.ansi)2625 case "query":2626 response = string(t.input)2627 }2628 t.serverResponseChan <- response2629 case actInvalid:2630 t.mutex.Unlock()2631 return false2632 case actTogglePreview:
581 unmodified lines
modified:test/test_go.rb+5 added-2 removed
2438 unmodified lines
24392440 def test_listen2441 tmux.send_keys 'seq 10 | fzf --listen 6266', :Enter2442 tmux.until { |lines| assert_equal 10, lines.item_count }2443 Net::HTTP.post(URI('http://localhost:6266'), 'change-query(yo)+reload(seq 100)+change-prompt:hundred> ')2443 Net::HTTP.post(URI('http://localhost:6266'), 'change-query(00)+reload(seq 100)+change-prompt:hundred> ')2444 tmux.until { |lines| assert_equal 100, lines.item_count }2445 tmux.until { |lines| assert_equal 'hundred> yo', lines[-1] }2445 tmux.until { |lines| assert_equal 'hundred> 00', lines[-1] }2446 assert_equal '100', Net::HTTP.get(URI('http://localhost:6266'))2447 assert_equal '100', Net::HTTP.get(URI('http://localhost:6266/current'))2448 assert_equal '00', Net::HTTP.get(URI('http://localhost:6266/query'))2449 end2450end24512452module TestShell
480 unmodified lines
modified:CHANGELOG.md+11 added-3 removed
1 unmodified line
2=========340.36.05------6- Added `--listen=HTTP_PORT` option to receive actions from external processes6- Added `--listen=HTTP_PORT` option to start HTTP server. It allows external7 processes to send actions to perform via POST method, or retrieve the8 current state of the finder.9 ```sh10 # Start HTTP server on port 626611 fzf --listen 62661211 # Send actions to the server12 curl -XPOST localhost:6266 -d 'reload(seq 100)+change-prompt(hundred> )'13 # Send action to the server via POST method14 curl localhost:6266 -d 'reload(seq 100)+change-prompt(hundred> )'1516 # Retrieve the current item17 curl localhost:62661819 # Retrieve the query string20 curl localhost:6266/query21 ```22- Added `next-selected` and `prev-selected` actions to move between selected23 items24 ```sh
1407 unmodified lines