fix: Parse prompt input JSON using object or array chars (#538)

Fixes #492. There is no more single-quote parsing, and instead we use a JSON decoder for multiline values. This is a much better UX!
This commit is contained in:
Kyle Carberry
2022-03-23 20:12:40 -05:00
committed by GitHub
parent 305b67c668
commit 99ece25bb3
4 changed files with 60 additions and 16 deletions
+17 -5
View File
@@ -2,7 +2,9 @@ package cliui
import (
"bufio"
"encoding/json"
"fmt"
"io"
"os"
"os/signal"
"strings"
@@ -45,12 +47,22 @@ func Prompt(cmd *cobra.Command, opts PromptOptions) (string, error) {
} else {
reader := bufio.NewReader(cmd.InOrStdin())
line, err = reader.ReadString('\n')
// Multiline with single quotes!
if err == nil && strings.HasPrefix(line, "'") {
rest, err := reader.ReadString('\'')
// Check if the first line beings with JSON object or array chars.
// This enables multiline JSON to be pasted into an input, and have
// it parse properly.
if err == nil && (strings.HasPrefix(line, "{") || strings.HasPrefix(line, "[")) {
pipeReader, pipeWriter := io.Pipe()
defer pipeWriter.Close()
defer pipeReader.Close()
go func() {
_, _ = pipeWriter.Write([]byte(line))
_, _ = reader.WriteTo(pipeWriter)
}()
var rawMessage json.RawMessage
err := json.NewDecoder(pipeReader).Decode(&rawMessage)
if err == nil {
line += rest
line = strings.Trim(line, "'")
line = string(rawMessage)
}
}
}