Skip to content

Commit

Permalink
feat: Quit REPL when Ctrl-D is pressed on an empty prompt (#1674)
Browse files Browse the repository at this point in the history
Signed-off-by: Andrew Haines <haines@cerbos.dev>
  • Loading branch information
haines committed Jul 4, 2023
1 parent 07df282 commit 49faf0a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
33 changes: 25 additions & 8 deletions cmd/cerbos/repl/internal/repl.go
Expand Up @@ -108,7 +108,16 @@ func (r *REPL) Loop() error {
r.output.Println()

for {
input := r.readInput()
input, err := r.readInput()
if err != nil {
if errors.Is(err, errExit) {
return nil
}

r.output.PrintErr("Failed to read input", err)
continue
}

if input == "" {
continue
}
Expand All @@ -126,25 +135,33 @@ func (r *REPL) Loop() error {
}
}

func (r *REPL) readInput() string {
func (r *REPL) readInput() (string, error) {
var input strings.Builder
currPrompt := prompt

stack := &runeStack{}
for {
line, err := r.reader.Prompt(currPrompt)
if err != nil {
if errors.Is(err, io.EOF) || errors.Is(err, liner.ErrPromptAborted) {
return ""
if errors.Is(err, io.EOF) {
if stack.IsEmpty() {
return "", errExit
}

r.output.Println()
return "", nil
}

r.output.PrintErr("Failed to read input", err)
return ""
if errors.Is(err, liner.ErrPromptAborted) {
return "", nil
}

return "", err
}

line = strings.TrimSpace(line)
if line == "" {
return input.String()
return input.String(), nil
}

l, terminated := isTerminated(line, stack)
Expand All @@ -154,7 +171,7 @@ func (r *REPL) readInput() string {
currPrompt = secondaryPrompt
} else {
input.WriteString(l)
return input.String()
return input.String(), nil
}
}
}
Expand Down
1 change: 1 addition & 0 deletions cmd/cerbos/repl/repl.go
Expand Up @@ -31,6 +31,7 @@ func (c *Cmd) Run(k *kong.Kong) error {
histFile := getHistoryFile(c.History)

reader := liner.NewLiner()
reader.SetCtrlCAborts(true)
reader.SetMultiLineMode(true)

defer func() {
Expand Down

0 comments on commit 49faf0a

Please sign in to comment.