stdin.go
This file
Path
internal/stdin/stdin.go
91 lines · 1.6 KiB · Go
Last changed by
fix: lint issues (#909)Carlos Alexandro Beckerbefore adoption817c4bd
History of this fileTake it
1// Package stdin handles processing input from stdin.2package stdin34import (5 "bufio"6 "fmt"7 "io"8 "os"9 "strings"1011 "github.com/charmbracelet/x/ansi"12)1314type options struct {15 ansiStrip bool16 singleLine bool17}1819// Option is a read option.20type Option func(*options)2122// StripANSI optionally strips ansi sequences.23func StripANSI(b bool) Option {24 return func(o *options) {25 o.ansiStrip = b26 }27}2829// SingleLine reads a single line.30func SingleLine(b bool) Option {31 return func(o *options) {32 o.singleLine = b33 }34}3536// Read reads input from an stdin pipe.37func Read(opts ...Option) (string, error) {38 if IsEmpty() {39 return "", fmt.Errorf("stdin is empty")40 }4142 options := options{}43 for _, opt := range opts {44 opt(&options)45 }4647 reader := bufio.NewReader(os.Stdin)48 var b strings.Builder4950 if options.singleLine {51 line, _, err := reader.ReadLine()52 if err != nil {53 return "", fmt.Errorf("failed to read line: %w", err)54 }55 _, err = b.Write(line)56 if err != nil {57 return "", fmt.Errorf("failed to write: %w", err)58 }59 }6061 for !options.singleLine {62 r, _, err := reader.ReadRune()63 if err != nil && err == io.EOF {64 break65 }66 _, err = b.WriteRune(r)67 if err != nil {68 return "", fmt.Errorf("failed to write rune: %w", err)69 }70 }7172 s := strings.TrimSpace(b.String())73 if options.ansiStrip {74 return ansi.Strip(s), nil75 }76 return s, nil77}7879// IsEmpty returns whether stdin is empty.80func IsEmpty() bool {81 stat, err := os.Stdin.Stat()82 if err != nil {83 return true84 }8586 if stat.Mode()&os.ModeNamedPipe == 0 && stat.Size() == 0 {87 return true88 }8990 return false91}