AlecAivazis / survey

A golang library for building interactive and accessible prompts with full support for windows and posix terminals.
MIT License
4.09k stars 355 forks source link

bufio.NewScanner(os.Stdin) seems to corrupt the output #182

Closed Maverobot closed 3 years ago

Maverobot commented 5 years ago

Operating system: Ubuntu 16.04 Terminal: xterm Go version: 1.12 Description: I am trying to create a cli program which feeds the piped infomation into a survey.MultiSelect. Issue: the option list seems to be refreshed with a low frequency and no option could be selected. I had to press Ctrl+c to stop the program. Sample code:

package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
    "strings"

    "gopkg.in/AlecAivazis/survey.v1"
)

func createQuestion(name string, message string, options []string) []*survey.Question {
    return []*survey.Question{
        {
            Name: name,
            Prompt: &survey.MultiSelect{
                Message: message,
                Options: options,
            },
        },
    }
}

func main() {
    // Get data options from pipe
    options := []string{
        "option 1",
        "option 2",
    }
    fi, err := os.Stdin.Stat()
    if err != nil {
        panic(err)
    }

    if fi.Mode()&os.ModeNamedPipe == 0 {
        fmt.Println("no pipe :(")
        return
    }

    scanner := bufio.NewScanner(os.Stdin)
    for scanner.Scan() {
        options = append(options, scanner.Text())
        fmt.Println(scanner.Text())
    }

    if err := scanner.Err(); err != nil {
        log.Println(err)
    }

    // ask the question
    answers := []string{}
    question := createQuestion("letter", "Select topics...", options)
    err = survey.Ask(question, &answers)

    if err != nil {
        fmt.Println(err.Error())
        return
    }
    // print the answers
    fmt.Printf("you chose: %s\n", strings.Join(answers, ", "))
}

Note: I just started to learn Golang a week ago. This issue might be caused by my own stupidity.

jobnte commented 5 years ago

Same here, it happens when I do go build then open the .exe in windows environment

felipesere commented 4 years ago

Interacting in any way with Stdin seems to break the core loop. I also see that survey no longer reacts to keyboard imput other than Ctrl-C when the input is corrupted.

mislav commented 3 years ago

Duplicate of https://github.com/AlecAivazis/survey/issues/328

Survey only works if stdin is connected to a terminal. Therefore, right now you cannot pipe something into your program if it's going to display prompts with Survey.