mirror of
https://github.com/coder/coder.git
synced 2026-09-24 15:04:27 +08:00
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:
+17
-5
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user