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
Provenance
- Commit
750b2a6- Tree
90ccd73- Author
Junegunn Choi <junegunn.c@gmail.com>- Committer
Junegunn Choi <junegunn.c@gmail.com>- Parent
de0da86
6 files changed+66 added−22 removed
modified:man/man1/fzf.1+11 added-3 removed
720 unmodified lines721 e.g. \fBfzf --multi | fzf --sync\fR722 .RE723 .TP724 .B "--listen=HTTP_PORT"725-Start HTTP server on the given port to receive actions via POST requests.725+Start HTTP server on the given port. It allows external processes to send726+actions to perform via POST method, or retrieve the current state of the727+finder.728 729 e.g.730 \fB# Start HTTP server on port 6266731 fzf --listen 6266732 731- # 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> )'735+736+ # Retrieve the current item737+ curl localhost:6266738+739+ # Retrieve the query string740+ curl localhost:6266/query741 \fR742 743 The port number is exported as \fB$FZF_LISTEN_PORT\fR on the child processes.744 .TP428 unmodified linesmodified:src/options.go+1 added-1 removed
111 unmodified lines112 --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 exit118 119 Environment variables120 FZF_DEFAULT_COMMAND Default command to use when input is tty1850 unmodified linesmodified:src/server.go+22 added-9 removed
4 unmodified lines5 "bytes"6 "errors"7 "fmt"8 "net"9+ "regexp"10 "strconv"11 "strings"12 "time"13 )14 15 const (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 )23 22-func startHttpServer(port int, channel chan []*action) error {24+var (25+ httpRegexp *regexp.Regexp26+)27+28+func startHttpServer(port int, requestChan chan []*action, responseChan chan string) error {29 if port == 0 {30 return nil31 }32 1 unmodified line34 if err != nil {35 return fmt.Errorf("port not available: %d", port)36 }37 38+ httpRegexp = regexp.MustCompile(httpPattern)39 go func() {40 for {41 conn, err := listener.Accept()42 if err != nil {2 unmodified lines45 } 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 lines60 //61 // * No --listen: 2.8MB62 // * --listen with net/http: 5.7MB63 // * --listen w/o net/http: 3.3MB57-func handleHttpRequest(conn net.Conn, channel chan []*action) string {64+func 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 lines88 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 lines133 }134 if len(actions) == 0 {135 return bad("no action specified")136 }123-124- channel <- actions137+ requestChan <- actions138 return httpOk139 }modified:src/terminal.go+16 added-4 removed
199 unmodified lines200 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.AtomicBool66 unmodified lines276 actClose277 actDeleteChar278 actDeleteCharEOF279 actEndOfLine280+ actEvaluate281 actForwardChar282 actForwardWord283 actKillLine284 actKillWord315 unmodified lines600 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 lines623 }624 t.separator, t.separatorLen = t.ansiLabelPrinter(bar, &tui.ColSeparator, true)625 }626 624- 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 }630 631 return &t1901 unmodified lines2533 }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 lines2616 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 linesmodified:test/test_go.rb+5 added-2 removed
2438 unmodified lines2439 2440 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 end2450 end2451 2452 module TestShell480 unmodified linesmodified:CHANGELOG.md+11 added-3 removed
1 unmodified line2 =========3 4 0.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 626612 11- # 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> )'15+16+ # Retrieve the current item17+ curl localhost:626618+19+ # Retrieve the query string20+ curl localhost:6266/query21 ```22 - Added `next-selected` and `prev-selected` actions to move between selected23 items24 ```sh1407 unmodified lines