From 5961f3201e574dd8836721a9ea6e61b36a10d59d Mon Sep 17 00:00:00 2001 From: Daisuke Maki Date: Mon, 15 Aug 2022 10:55:30 +0900 Subject: [PATCH] Implement --on-empty=exit --- interface.go | 6 ++++++ peco.go | 24 ++++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/interface.go b/interface.go index ec2ea3e..80a030c 100644 --- a/interface.go +++ b/interface.go @@ -52,6 +52,10 @@ const ( RegexpMatch = "Regexp" ) +const ( + OnEmptyExit = `exit` +) + type idgen struct { ch chan uint64 } @@ -84,6 +88,7 @@ type Peco struct { maxScanBufferSize int mutex sync.Mutex onCancel string + onEmpty string printQuery bool prompt string query Query @@ -411,6 +416,7 @@ type CLIOptions struct { OptInitialFilter string `long:"initial-filter" description:"specify the default filter"` OptPrompt string `long:"prompt" description:"specify the prompt string"` OptLayout string `long:"layout" description:"layout to be used. 'top-down' or 'bottom-up'. default is 'top-down'"` + OptOnEmpty string `long:"on-empty" description:"action to take when the input is finite (not a stream) and the buffer is empty. specify 'exit' to exit peco when the buffer is empty"` OptSelect1 bool `long:"select-1" description:"select first item and immediately exit if the input contains only 1 item"` OptOnCancel string `long:"on-cancel" description:"specify action on user cancel. 'success' or 'error'.\ndefault is 'success'. This may change in future versions"` OptSelectionPrefix string `long:"selection-prefix" description:"use a prefix instead of changing line color to indicate currently selected lines.\ndefault is to use colors. This option is experimental"` diff --git a/peco.go b/peco.go index 966d2be..980a79e 100644 --- a/peco.go +++ b/peco.go @@ -311,6 +311,12 @@ func (p *Peco) selectOneAndExitIfPossible() { } } +func (p *Peco) exitOnEmpty() { + if b := p.CurrentLineBuffer(); b.Size() == 0 { + p.Exit(errCollectResults{}) + } +} + func (p *Peco) Run(ctx context.Context) (err error) { if pdebug.Enabled { g := pdebug.Marker("Peco.Run").BindError(&err) @@ -393,6 +399,18 @@ func (p *Peco) Run(ctx context.Context) (err error) { }() } + if !src.IsInfinite() { + switch p.onEmpty { + case OnEmptyExit: + go func() { + <-p.source.SetupDone() + p.exitOnEmpty() + }() + default: + // DO NOTHING + } + } + readyOnce.Do(func() { close(p.readyCh) }) // This has tobe AFTER close(p.readyCh), otherwise the query is @@ -558,6 +576,12 @@ func (p *Peco) ApplyConfig(opts CLIOptions) error { } else { p.selectionPrefix = p.config.SelectionPrefix } + switch opts.OptOnEmpty { + case OnEmptyExit, "": + default: + return errors.Errorf("invalid --on-empty value %q", opts.OptOnEmpty) + } + p.onEmpty = opts.OptOnEmpty p.selectOneAndExit = opts.OptSelect1 p.printQuery = opts.OptPrintQuery p.initialQuery = opts.OptQuery