diff --git a/dsc/src/util.rs b/dsc/src/util.rs index f2504b8a0..cc2c4d064 100644 --- a/dsc/src/util.rs +++ b/dsc/src/util.rs @@ -47,7 +47,7 @@ use schemars::{Schema, schema_for}; use serde::Deserialize; use std::collections::HashMap; use std::env; -use std::io::{IsTerminal, Read}; +use std::io::{IsTerminal, Read, stdout, Write}; use std::path::Path; use std::process::exit; use syntect::{ @@ -293,7 +293,11 @@ pub fn write_object(json: &str, format: Option<&OutputFormat>, include_separator } } else { - println!("{output}"); + let mut stdout_lock = stdout().lock(); + if writeln!(stdout_lock, "{output}").is_err() { + // likely caused by a broken pipe (e.g. 'head' command closed early) + exit(EXIT_SUCCESS); + } } } diff --git a/dsc/tests/dsc.exit_code.tests.ps1 b/dsc/tests/dsc.exit_code.tests.ps1 index 16c27905b..10f5a676a 100644 --- a/dsc/tests/dsc.exit_code.tests.ps1 +++ b/dsc/tests/dsc.exit_code.tests.ps1 @@ -15,4 +15,9 @@ Describe 'exit code tests' { $result.actualState.exitCode | Should -Be 0 $LASTEXITCODE | Should -Be 0 } + It 'Exiting early due to broken pipe is a success' { + $out = dsc resource list | Select-Object -First 1 | ConvertFrom-Json + $out.Count | Should -Be 1 + $LASTEXITCODE | Should -Be 0 + } }