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: rewrite prefix after carriage return #6989

Merged
merged 4 commits into from
Jan 11, 2024
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
29 changes: 26 additions & 3 deletions crates/turborepo-ui/src/prefixed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,12 +128,19 @@ impl<W: Write> PrefixedWriter<W> {

impl<W: Write> Write for PrefixedWriter<W> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.writer.write_all(self.prefix.as_bytes())?;

for chunk in buf.split_inclusive(|c| *c == b'\r') {
// Before we write the chunk we write the prefix as either:
// - this is the first iteration and we haven't written the prefix
// - the previous chunk ended with a \r and the cursor is currently as the start
// of the line so we want to rewrite the prefix over the existing prefix in
// the line
self.writer.write_all(self.prefix.as_bytes())?;
self.writer.write_all(chunk)?;
}
// We do end up writing more bytes than this to the underlying writer, but we
// cannot report this to the callers as the amount of bytes we report
// written must be less than or equal to the number of bytes in the buffer.
self.writer.write(buf)
Ok(buf.len())
}

fn flush(&mut self) -> std::io::Result<()> {
Expand Down Expand Up @@ -192,4 +199,20 @@ mod test {
writer.write_all(b"cool!").unwrap();
assert_eq!(String::from_utf8(buffer).unwrap(), expected);
}

#[test_case("\ra whole message \n", "turbo > \rturbo > a whole message \n" ; "basic prefix cr")]
#[test_case("no return", "turbo > no return" ; "no return")]
#[test_case("foo\rbar\rbaz", "turbo > foo\rturbo > bar\rturbo > baz" ; "multiple crs")]
#[test_case("foo\r", "turbo > foo\r" ; "trailing cr")]
fn test_prefixed_writer_cr(input: &str, expected: &str) {
let mut buffer = Vec::new();
let mut writer = PrefixedWriter::new(
UI::new(false),
Style::new().apply_to("turbo > "),
&mut buffer,
);

writer.write_all(input.as_bytes()).unwrap();
assert_eq!(String::from_utf8(buffer).unwrap(), expected);
}
}