WriteOutput writes content to the specified output destination Handles stdout and file output with broken pipe detection
(content []byte, outputFile string, writer io.Writer)
| 94 | // WriteOutput writes content to the specified output destination |
| 95 | // Handles stdout and file output with broken pipe detection |
| 96 | func WriteOutput(content []byte, outputFile string, writer io.Writer) error { |
| 97 | // If output file is specified, write to file |
| 98 | if outputFile != "" { |
| 99 | // Security: Use 0600 permissions for output files (owner read/write only) |
| 100 | // G306: This is intentional - output files should be user-private |
| 101 | if err := os.WriteFile(outputFile, content, 0600); err != nil { // #nosec G306,G703 |
| 102 | return fmt.Errorf("failed to write to file %s: %w", outputFile, err) |
| 103 | } |
| 104 | return nil |
| 105 | } |
| 106 | |
| 107 | // Write to stdout (or provided writer) |
| 108 | _, err := writer.Write(content) |
| 109 | if err != nil { |
| 110 | // Check for broken pipe error |
| 111 | if IsBrokenPipe(err) { |
| 112 | // Broken pipe is not a critical error in Unix pipelines |
| 113 | // It just means the reader closed early (e.g., head, grep) |
| 114 | return nil |
| 115 | } |
| 116 | return fmt.Errorf("failed to write output: %w", err) |
| 117 | } |
| 118 | |
| 119 | return nil |
| 120 | } |
| 121 | |
| 122 | // IsBrokenPipe checks if an error is a broken pipe error |
| 123 | // This is common in Unix pipelines when the reader closes early |