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

cksum: Add --raw argument #5803

Merged
merged 8 commits into from
Jan 10, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
52 changes: 49 additions & 3 deletions src/uu/cksum/src/cksum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@
// spell-checker:ignore (ToDO) fname, algo
use clap::{crate_version, value_parser, Arg, ArgAction, Command};
use hex::encode;
use std::error::Error;
use std::ffi::OsStr;
use std::fmt::Display;
use std::fs::File;
use std::io::{self, stdin, BufReader, Read};
use std::io::{self, stdin, stdout, BufReader, Read, Write};
use std::iter;
use std::path::Path;
use uucore::{
error::{FromIo, UResult},
error::{FromIo, UError, UResult},
format_usage, help_about, help_section, help_usage,
sum::{
div_ceil, Blake2b, Digest, DigestWriter, Md5, Sha1, Sha224, Sha256, Sha384, Sha512, Sm3,
Expand All @@ -36,6 +38,31 @@
const ALGORITHM_OPTIONS_BLAKE2B: &str = "blake2b";
const ALGORITHM_OPTIONS_SM3: &str = "sm3";

#[derive(Debug)]

Check warning on line 41 in src/uu/cksum/src/cksum.rs

View check run for this annotation

Codecov / codecov/patch

src/uu/cksum/src/cksum.rs#L41

Added line #L41 was not covered by tests
enum CkSumError {
RawMultipleFiles,
}

impl UError for CkSumError {
fn code(&self) -> i32 {
match self {
Self::RawMultipleFiles => 1,
}
}
}

impl Error for CkSumError {}

impl Display for CkSumError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::RawMultipleFiles => {
write!(f, "the --raw option is not supported with multiple files")
}
}
}
}

fn detect_algo(
program: &str,
length: Option<usize>,
Expand Down Expand Up @@ -110,6 +137,7 @@
output_bits: usize,
untagged: bool,
length: Option<usize>,
raw: bool,
}

/// Calculate checksum
Expand All @@ -123,7 +151,12 @@
where
I: Iterator<Item = &'a OsStr>,
{
for filename in files {
let files_vec: Vec<_> = files.collect();
D9nni marked this conversation as resolved.
Show resolved Hide resolved
if options.raw && files_vec.len() > 1 {
return Err(Box::new(CkSumError::RawMultipleFiles));
}

for filename in files_vec {
let filename = Path::new(filename);
let stdin_buf;
let file_buf;
Expand All @@ -141,6 +174,11 @@
let (sum, sz) = digest_read(&mut options.digest, &mut file, options.output_bits)
.map_err_context(|| "failed to read input".to_string())?;

if options.raw {
let bytes_str = sum.parse::<u32>().unwrap().to_be_bytes();
D9nni marked this conversation as resolved.
Show resolved Hide resolved
stdout().write_all(&bytes_str)?;
return Ok(());
}
// The BSD checksum output is 5 digit integer
let bsd_width = 5;
match (options.algo_name, not_file) {
Expand Down Expand Up @@ -238,6 +276,7 @@
pub const FILE: &str = "file";
pub const UNTAGGED: &str = "untagged";
pub const LENGTH: &str = "length";
pub const RAW: &str = "raw";
}

#[uucore::main]
Expand Down Expand Up @@ -298,6 +337,7 @@
output_bits: bits,
length,
untagged: matches.get_flag(options::UNTAGGED),
raw: matches.get_flag(options::RAW),
};

match matches.get_many::<String>(options::FILE) {
Expand Down Expand Up @@ -354,5 +394,11 @@
.help("digest length in bits; must not exceed the max for the blake2 algorithm and must be a multiple of 8")
.action(ArgAction::Set),
)
.arg(
Arg::new(options::RAW)
.long(options::RAW)
.help("emit a raw binary digest, not hexadecimal")
.action(ArgAction::SetTrue),
)
.after_help(AFTER_HELP)
}
22 changes: 22 additions & 0 deletions tests/by-util/test_cksum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,28 @@ fn test_length_is_zero() {
.stdout_is_fixture("length_is_zero.expected");
}

#[test]
fn test_raw_single_file() {
new_ucmd!()
.arg("--raw")
.arg("lorem_ipsum.txt")
.succeeds()
.no_stderr()
.stdout_is_fixture_bytes("raw_single_file.expected");
}

#[test]
fn test_raw_multiple_files() {
new_ucmd!()
.arg("--raw")
.arg("lorem_ipsum.txt")
.arg("alice_in_wonderland.txt")
.fails()
.no_stdout()
.stderr_contains("cksum: the --raw option is not supported with multiple files")
.code_is(1);
}

#[test]
fn test_blake2b_fail_on_directory() {
let (at, mut ucmd) = at_and_ucmd!();
Expand Down
1 change: 1 addition & 0 deletions tests/fixtures/cksum/raw_single_file.expected
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ŒPh
Loading