diff --git a/src/uu/head/src/head.rs b/src/uu/head/src/head.rs index 56d7e8452..ae5807c22 100644 --- a/src/uu/head/src/head.rs +++ b/src/uu/head/src/head.rs @@ -29,6 +29,7 @@ enum FilterMode { struct Settings { mode: FilterMode, verbose: bool, + zero_terminated: bool, } impl Default for Settings { @@ -36,6 +37,7 @@ impl Default for Settings { Settings { mode: FilterMode::Lines(10), verbose: false, + zero_terminated: false, } } } @@ -69,6 +71,7 @@ pub fn uumain(args: impl uucore::Args) -> i32 { ) .optflag("q", "quiet", "never print headers giving file names") .optflag("v", "verbose", "always print headers giving file names") + .optflag("z", "zero-terminated", "line delimiter is NUL, not newline") .optflag("h", "help", "display this help and exit") .optflag("V", "version", "output version information and exit") .parse(new_args); @@ -113,6 +116,7 @@ pub fn uumain(args: impl uucore::Args) -> i32 { let quiet = matches.opt_present("q"); let verbose = matches.opt_present("v"); + settings.zero_terminated = matches.opt_present("z"); let files = matches.free; // GNU implementation allows multiple declarations of "-q" and "-v" with the @@ -203,8 +207,14 @@ fn head(reader: &mut BufReader, settings: &Settings) -> bool { } } FilterMode::Lines(count) => { - for line in reader.lines().take(count) { - println!("{}", line.unwrap()); + if settings.zero_terminated { + for line in reader.split(0).take(count) { + print!("{}\0", String::from_utf8(line.unwrap()).unwrap()) + } + } else { + for line in reader.lines().take(count) { + println!("{}", line.unwrap()); + } } } FilterMode::NLines(count) => { diff --git a/tests/by-util/test_head.rs b/tests/by-util/test_head.rs index 4324290cb..eec82b51f 100644 --- a/tests/by-util/test_head.rs +++ b/tests/by-util/test_head.rs @@ -86,6 +86,14 @@ fn test_verbose() { .stdout_is_fixture("lorem_ipsum_verbose.expected"); } +#[test] +fn test_zero_terminated() { + new_ucmd!() + .args(&["-z", "zero_terminated.txt"]) + .run() + .stdout_is_fixture("zero_terminated.expected"); +} + #[test] #[ignore] fn test_spams_newline() { diff --git a/tests/fixtures/head/zero_terminated.expected b/tests/fixtures/head/zero_terminated.expected new file mode 100644 index 000000000..3c4cc058c Binary files /dev/null and b/tests/fixtures/head/zero_terminated.expected differ diff --git a/tests/fixtures/head/zero_terminated.txt b/tests/fixtures/head/zero_terminated.txt new file mode 100644 index 000000000..6c7968122 Binary files /dev/null and b/tests/fixtures/head/zero_terminated.txt differ