Skip to content
Draft
Show file tree
Hide file tree
Changes from all 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
4 changes: 0 additions & 4 deletions src/uu/cksum/locales/en-US.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,3 @@ cksum-help-quiet = don't print OK for each successfully verified file
cksum-help-ignore-missing = don't fail or report status for missing files
cksum-help-zero = end each output line with NUL, not newline, and disable file name escaping
cksum-help-debug = print CPU hardware capability detection info used by cksum
# Error messages
cksum-error-is-directory = { $file }: Is a directory
cksum-error-failed-to-read-input = failed to read input
4 changes: 0 additions & 4 deletions src/uu/cksum/locales/fr-FR.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,3 @@ cksum-help-quiet = ne pas afficher OK pour chaque fichier vérifié avec succès
cksum-help-ignore-missing = ne pas échouer ou signaler le statut pour les fichiers manquants
cksum-help-zero = terminer chaque ligne de sortie avec NUL, pas un saut de ligne, et désactiver l'échappement des noms de fichiers
cksum-help-debug = afficher les informations de débogage sur la détection de la prise en charge matérielle du processeur
# Messages d'erreur
cksum-error-is-directory = { $file } : Est un répertoire
cksum-error-failed-to-read-input = échec de la lecture de l'entrée
19 changes: 19 additions & 0 deletions src/uucore/locales/en-US.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ error-io = I/O error
error-permission-denied = Permission denied
error-file-not-found = No such file or directory
error-invalid-argument = Invalid argument
error-is-a-directory = { $file }: Is a directory
# Common actions
action-copying = copying
Expand All @@ -54,3 +55,21 @@ safe-traversal-error-unlink-failed = failed to unlink '{ $path }': { $source }
safe-traversal-error-invalid-fd = invalid file descriptor
safe-traversal-current-directory = <current directory>
safe-traversal-directory = <directory>
# checksum-related messages
checksum-no-properly-formatted = { $checksum_file }: no properly formatted checksum lines found
checksum-no-file-verified = { $checksum_file }: no file was verified
checksum-error-failed-to-read-input = failed to read input
checksum-bad-format = { $count ->
[1] { $count } line is improperly formatted
*[other] { $count } lines are improperly formatted
}
checksum-failed-cksum = { $count ->
[1] { $count } computed checksum did NOT match
*[other] { $count } computed checksums did NOT match
}
checksum-failed-open-file = { $count ->
[1] { $count } listed file could not be read
*[other] { $count } listed files could not be read
}
checksum-error-algo-bad-format = { $file }: { $line }: improperly formatted { $algo } checksum line
19 changes: 19 additions & 0 deletions src/uucore/locales/fr-FR.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ error-io = Erreur E/S
error-permission-denied = Permission refusée
error-file-not-found = Aucun fichier ou répertoire de ce type
error-invalid-argument = Argument invalide
error-is-a-directory = { $file }: Est un répertoire
# Actions communes
action-copying = copie
Expand All @@ -54,3 +55,21 @@ safe-traversal-error-unlink-failed = échec de la suppression de '{ $path }' : {
safe-traversal-error-invalid-fd = descripteur de fichier invalide
safe-traversal-current-directory = <répertoire courant>
safe-traversal-directory = <répertoire>
# Messages relatifs au module checksum
checksum-no-properly-formatted = { $checksum_file }: aucune ligne correctement formattée n'a été trouvée
checksum-no-file-verified = { $checksum_file }: aucun fichier n'a été vérifié
checksum-error-failed-to-read-input = échec de la lecture de l'entrée
checksum-bad-format = { $count ->
[1] { $count } ligne invalide
*[other] { $count } lignes invalides
}
checksum-failed-cksum = { $count ->
[1] { $count } somme de hachage ne correspond PAS
*[other] { $count } sommes de hachage ne correspondent PAS
}
checksum-failed-open-file = { $count ->
[1] { $count } fichier passé n'a pas pu être lu
*[other] { $count } fichiers passés n'ont pas pu être lu
}
checksum-error-algo-bad-format = { $file }: { $line }: ligne invalide pour { $algo }
64 changes: 26 additions & 38 deletions src/uucore/src/lib/features/checksum/compute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ use std::path::Path;
use crate::checksum::{ChecksumError, SizedAlgoKind, digest_reader, escape_filename};
use crate::error::{FromIo, UResult, USimpleError};
use crate::line_ending::LineEnding;
use crate::{encoding, show, translate};
use crate::sum::DigestOutput;
use crate::{show, translate};

/// Use the same buffer size as GNU when reading a file to create a checksum
/// from it: 32 KiB.
Expand Down Expand Up @@ -139,10 +140,11 @@ pub fn figure_out_output_format(
fn print_legacy_checksum(
options: &ChecksumComputeOptions,
filename: &OsStr,
sum: &str,
sum: &DigestOutput,
size: usize,
) -> UResult<()> {
debug_assert!(options.algo_kind.is_legacy());
debug_assert!(matches!(sum, DigestOutput::U16(_) | DigestOutput::Crc(_)));

let (escaped_filename, prefix) = if options.line_ending == LineEnding::Nul {
(filename.to_string_lossy().to_string(), "")
Expand All @@ -153,25 +155,23 @@ fn print_legacy_checksum(
print!("{prefix}");

// Print the sum
match options.algo_kind {
SizedAlgoKind::Sysv => print!(
"{} {}",
sum.parse::<u16>().unwrap(),
match (options.algo_kind, sum) {
(SizedAlgoKind::Sysv, DigestOutput::U16(sum)) => print!(
"{prefix}{sum} {}",
size.div_ceil(options.algo_kind.bitlen()),
),
SizedAlgoKind::Bsd => {
(SizedAlgoKind::Bsd, DigestOutput::U16(sum)) => {
// The BSD checksum output is 5 digit integer
let bsd_width = 5;
print!(
"{:0bsd_width$} {:bsd_width$}",
sum.parse::<u16>().unwrap(),
"{prefix}{sum:0bsd_width$} {:bsd_width$}",
size.div_ceil(options.algo_kind.bitlen()),
);
}
SizedAlgoKind::Crc | SizedAlgoKind::Crc32b => {
print!("{sum} {size}");
(SizedAlgoKind::Crc | SizedAlgoKind::Crc32b, DigestOutput::Crc(sum)) => {
print!("{prefix}{sum} {size}");
}
_ => unreachable!("Not a legacy algorithm"),
(algo, output) => unreachable!("Bug: Invalid legacy checksum ({algo:?}, {output:?})"),
}

// Print the filename after a space if not stdin
Expand Down Expand Up @@ -257,9 +257,7 @@ where
if filepath.is_dir() {
show!(USimpleError::new(
1,
// TODO: Rework translation, which is broken since this code moved to uucore
// translate!("cksum-error-is-directory", "file" => filepath.display())
format!("{}: Is a directory", filepath.display())
translate!("error-is-a-directory", "file" => filepath.display())
));
continue;
}
Expand All @@ -284,49 +282,39 @@ where

let mut digest = options.algo_kind.create_digest();

let (sum_hex, sz) = digest_reader(
&mut digest,
&mut file,
options.binary,
options.algo_kind.bitlen(),
)
.map_err_context(|| translate!("cksum-error-failed-to-read-input"))?;
let (digest_output, sz) = digest_reader(&mut digest, &mut file, options.binary)
.map_err_context(|| translate!("checksum-error-failed-to-read-input"))?;

// Encodes the sum if df is Base64, leaves as-is otherwise.
let encode_sum = |sum: String, df: DigestFormat| {
let encode_sum = |sum: DigestOutput, df: DigestFormat| {
if df.is_base64() {
encoding::for_cksum::BASE64.encode(&hex::decode(sum).unwrap())
sum.to_base64()
} else {
sum
sum.to_hex()
}
};

match options.output_format {
OutputFormat::Raw => {
let bytes = match options.algo_kind {
SizedAlgoKind::Crc | SizedAlgoKind::Crc32b => {
sum_hex.parse::<u32>().unwrap().to_be_bytes().to_vec()
}
SizedAlgoKind::Sysv | SizedAlgoKind::Bsd => {
sum_hex.parse::<u16>().unwrap().to_be_bytes().to_vec()
}
_ => hex::decode(sum_hex).unwrap(),
};
// Cannot handle multiple files anyway, output immediately.
io::stdout().write_all(&bytes)?;
digest_output.write_raw(io::stdout())?;
return Ok(());
}
OutputFormat::Legacy => {
print_legacy_checksum(&options, filename, &sum_hex, sz)?;
print_legacy_checksum(&options, filename, &digest_output, sz)?;
}
OutputFormat::Tagged(digest_format) => {
print_tagged_checksum(&options, filename, &encode_sum(sum_hex, digest_format))?;
print_tagged_checksum(
&options,
filename,
&encode_sum(digest_output, digest_format)?,
)?;
}
OutputFormat::Untagged(digest_format, reading_mode) => {
print_untagged_checksum(
&options,
filename,
&encode_sum(sum_hex, digest_format),
&encode_sum(digest_output, digest_format)?,
reading_mode,
)?;
}
Expand Down
16 changes: 4 additions & 12 deletions src/uucore/src/lib/features/checksum/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ use thiserror::Error;
use crate::error::{UError, UResult};
use crate::show_error;
use crate::sum::{
Blake2b, Blake3, Bsd, CRC32B, Crc, Digest, DigestWriter, Md5, Sha1, Sha3_224, Sha3_256,
Sha3_384, Sha3_512, Sha224, Sha256, Sha384, Sha512, Shake128, Shake256, Sm3, SysV,
Blake2b, Blake3, Bsd, CRC32B, Crc, Digest, DigestOutput, DigestWriter, Md5, Sha1, Sha3_224,
Sha3_256, Sha3_384, Sha3_512, Sha224, Sha256, Sha384, Sha512, Shake128, Shake256, Sm3, SysV,
};

pub mod compute;
Expand Down Expand Up @@ -420,8 +420,7 @@ pub fn digest_reader<T: Read>(
digest: &mut Box<dyn Digest>,
reader: &mut T,
binary: bool,
output_bits: usize,
) -> io::Result<(String, usize)> {
) -> io::Result<(DigestOutput, usize)> {
digest.reset();

// Read bytes from `reader` and write those bytes to `digest`.
Expand All @@ -440,14 +439,7 @@ pub fn digest_reader<T: Read>(
let output_size = std::io::copy(reader, &mut digest_writer)? as usize;
digest_writer.finalize();

if digest.output_bits() > 0 {
Ok((digest.result_str(), output_size))
} else {
// Assume it's SHAKE. result_str() doesn't work with shake (as of 8/30/2016)
let mut bytes = vec![0; output_bits.div_ceil(8)];
digest.hash_finalize(&mut bytes);
Ok((hex::encode(bytes), output_size))
}
Ok((digest.result(), output_size))
}

/// Calculates the length of the digest.
Expand Down
Loading
Loading