Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix prettylog piping #644

Merged
merged 2 commits into from
Feb 1, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 23 additions & 15 deletions cmd/prettylog/prettylog.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,31 +15,39 @@ func isInputFromPipe() bool {
return fileInfo.Mode()&os.ModeCharDevice == 0
}

func main() {
func processInput(reader io.Reader) error {
writer := zerolog.NewConsoleWriter()

scanner := bufio.NewScanner(reader)
for scanner.Scan() {
bytesToWrite := scanner.Bytes()
_, err := writer.Write(bytesToWrite)
if err != nil {
if errors.Is(err, io.EOF) {
break
}

fmt.Printf("%s\n", bytesToWrite)
}
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you please make this a function and reuse it for the code below (for file arg)?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I thought about this, but it's slightly different in terms of how the errors are treated. What do you think would be the best way to do in both cases if error occurs, crash the app and display the error message, or display the output as is?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Showing the line as-is is probably sensible for such a tool.

}

return scanner.Err()
}

func main() {

if isInputFromPipe() {
_, _ = io.Copy(writer, os.Stdin)
_ = processInput(os.Stdin)
} else if len(os.Args) > 1 {
for _, filename := range os.Args[1:] {
// Scan each line from filename and write it into writer
r, err := os.Open(filename)
reader, err := os.Open(filename)
if err != nil {
fmt.Printf("%s open: %v", filename, err)
os.Exit(1)
}
scanner := bufio.NewScanner(r)
for scanner.Scan() {
_, err = writer.Write(scanner.Bytes())
if err != nil {
if errors.Is(err, io.EOF) {
break
}
fmt.Printf("%s write: %v", filename, err)
os.Exit(1)
}
}
if err := scanner.Err(); err != nil {

if err := processInput(reader); err != nil {
fmt.Printf("%s scan: %v", filename, err)
os.Exit(1)
}
Expand Down
Loading