mirror of
https://github.com/charmbracelet/glow
synced 2024-11-05 16:23:00 +00:00
Automatically read from stdin if stdin is a pipe
This commit is contained in:
parent
8fc9a300a4
commit
8138788b0a
1 changed files with 25 additions and 0 deletions
25
main.go
25
main.go
|
@ -177,12 +177,33 @@ func validateOptions(cmd *cobra.Command) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func stdinIsPipe() (bool, error) {
|
||||
stat, err := os.Stdin.Stat()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if stat.Mode()&os.ModeCharDevice == 0 || stat.Size() > 0 {
|
||||
return true, nil
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func execute(cmd *cobra.Command, args []string) error {
|
||||
initConfig()
|
||||
if err := validateOptions(cmd); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// if stdin is a pipe then use stdin for input. note that you can also
|
||||
// explicitly use a - to read from stdin.
|
||||
if yes, err := stdinIsPipe(); err != nil {
|
||||
return err
|
||||
} else if yes {
|
||||
src := &source{reader: os.Stdin}
|
||||
defer src.reader.Close()
|
||||
return executeCLI(cmd, src, os.Stdout)
|
||||
}
|
||||
|
||||
switch len(args) {
|
||||
|
||||
// TUI running on cwd
|
||||
|
@ -221,6 +242,10 @@ func executeArg(cmd *cobra.Command, arg string, w io.Writer) error {
|
|||
return err
|
||||
}
|
||||
defer src.reader.Close()
|
||||
return executeCLI(cmd, src, w)
|
||||
}
|
||||
|
||||
func executeCLI(cmd *cobra.Command, src *source, w io.Writer) error {
|
||||
b, err := ioutil.ReadAll(src.reader)
|
||||
if err != nil {
|
||||
return err
|
||||
|
|
Loading…
Reference in a new issue