grype/internal/input.go
devfbe e1bdbc7d27
Fix reading syft json from stdin by redirect (#1299)
I figured out that running `cat syft.json | grype` works but
`grype < syft.json` does not work. This happens, because the
IsPipedInput method only checks if stdin is a pipe which will be false
if stdin is fed by a redirect.

The go idiomatic way to fix this is by just checking if the file
produced by stat has a size > 0.

Implemented this check, that will recognize stdin by redirect, in the
IsPipedInput() method. Renamed the method to IsStdinPipeOrRedirect().

Signed-off-by: Felix Becker <git@felixbecker.name>
Co-authored-by: Benjamin Neff <benjamin@coding4coffee.ch>
2023-05-16 19:41:43 +00:00

20 lines
802 B
Go

package internal
import (
"fmt"
"os"
)
// IsStdinPipeOrRedirect returns true if stdin is provided via pipe or redirect
func IsStdinPipeOrRedirect() (bool, error) {
fi, err := os.Stdin.Stat()
if err != nil {
return false, fmt.Errorf("unable to determine if there is piped input: %w", err)
}
// note: we should NOT use the absence of a character device here as the hint that there may be input expected
// on stdin, as running grype as a subprocess you would expect no character device to be present but input can
// be from either stdin or indicated by the CLI. Checking if stdin is a pipe is the most direct way to determine
// if there *may* be bytes that will show up on stdin that should be used for the analysis source.
return fi.Mode()&os.ModeNamedPipe != 0 || fi.Size() > 0, nil
}