Skip to content

Commit 85549e7

Browse files
committed
checksum: Adapt checksum computation to hashsum
1 parent b9552b4 commit 85549e7

File tree

5 files changed

+158
-201
lines changed

5 files changed

+158
-201
lines changed

src/uu/cksum/src/cksum.rs

Lines changed: 2 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ use clap::{Arg, ArgAction, Command};
1010
use std::ffi::{OsStr, OsString};
1111
use std::iter;
1212
use uucore::checksum::compute::{
13-
ChecksumComputeOptions, DigestFormat, OutputFormat, ReadingMode, perform_checksum_computation,
13+
ChecksumComputeOptions, figure_out_output_format, perform_checksum_computation,
1414
};
1515
use uucore::checksum::validate::{
1616
ChecksumValidateOptions, ChecksumVerbose, perform_checksum_validation,
@@ -84,43 +84,6 @@ fn handle_tag_text_binary_flags<S: AsRef<OsStr>>(
8484
Ok((tag, binary))
8585
}
8686

87-
/// Use already-processed arguments to decide the output format.
88-
fn figure_out_output_format(
89-
algo: SizedAlgoKind,
90-
tag: bool,
91-
binary: bool,
92-
raw: bool,
93-
base64: bool,
94-
) -> OutputFormat {
95-
// Raw output format takes precedence over anything else.
96-
if raw {
97-
return OutputFormat::Raw;
98-
}
99-
100-
// Then, if the algo is legacy, takes precedence over the rest
101-
if algo.is_legacy() {
102-
return OutputFormat::Legacy;
103-
}
104-
105-
let digest_format = if base64 {
106-
DigestFormat::Base64
107-
} else {
108-
DigestFormat::Hexadecimal
109-
};
110-
111-
// After that, decide between tagged and untagged output
112-
if tag {
113-
OutputFormat::Tagged(digest_format)
114-
} else {
115-
let reading_mode = if binary {
116-
ReadingMode::Binary
117-
} else {
118-
ReadingMode::Text
119-
};
120-
OutputFormat::Untagged(digest_format, reading_mode)
121-
}
122-
}
123-
12487
/// Sanitize the `--length` argument depending on `--algorithm` and `--length`.
12588
fn maybe_sanitize_length(
12689
algo_cli: Option<AlgoKind>,
@@ -223,6 +186,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
223186
digest: algo.create_digest(),
224187
output_format,
225188
line_ending,
189+
no_names: false,
226190
};
227191

228192
perform_checksum_computation(opts, files)?;

src/uu/hashsum/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ path = "src/hashsum.rs"
1919

2020
[dependencies]
2121
clap = { workspace = true }
22-
uucore = { workspace = true, features = ["checksum", "sum"] }
22+
uucore = { workspace = true, features = ["checksum", "encoding", "sum"] }
2323
fluent = { workspace = true }
2424

2525
[[bin]]

src/uu/hashsum/src/hashsum.rs

Lines changed: 32 additions & 121 deletions
Original file line numberDiff line numberDiff line change
@@ -5,47 +5,26 @@
55

66
// spell-checker:ignore (ToDO) algo, algoname, bitlen, regexes, nread, nonames
77

8-
use clap::ArgAction;
9-
use clap::builder::ValueParser;
10-
use clap::value_parser;
11-
use clap::{Arg, ArgMatches, Command};
128
use std::ffi::{OsStr, OsString};
13-
use std::fs::File;
14-
use std::io::{BufReader, Read, stdin};
159
use std::iter;
1610
use std::num::ParseIntError;
1711
use std::path::Path;
1812

13+
use clap::builder::ValueParser;
14+
use clap::{Arg, ArgAction, ArgMatches, Command, value_parser};
15+
16+
use uucore::checksum::compute::{
17+
ChecksumComputeOptions, figure_out_output_format, perform_checksum_computation,
18+
};
1919
use uucore::checksum::validate::{
2020
ChecksumValidateOptions, ChecksumVerbose, perform_checksum_validation,
2121
};
22-
use uucore::checksum::{
23-
AlgoKind, ChecksumError, SizedAlgoKind, calculate_blake2b_length, digest_reader,
24-
escape_filename,
25-
};
26-
use uucore::error::{UResult, strip_errno};
27-
use uucore::sum::Digest;
22+
use uucore::checksum::{AlgoKind, ChecksumError, SizedAlgoKind, calculate_blake2b_length};
23+
use uucore::error::UResult;
24+
use uucore::line_ending::LineEnding;
2825
use uucore::{format_usage, translate};
2926

3027
const NAME: &str = "hashsum";
31-
// Using the same read buffer size as GNU
32-
const READ_BUFFER_SIZE: usize = 32 * 1024;
33-
34-
struct Options<'a> {
35-
algo: SizedAlgoKind,
36-
digest: Box<dyn Digest + 'static>,
37-
binary: bool,
38-
binary_name: &'a str,
39-
//check: bool,
40-
tag: bool,
41-
nonames: bool,
42-
//status: bool,
43-
//quiet: bool,
44-
//strict: bool,
45-
//warn: bool,
46-
zero: bool,
47-
//ignore_missing: bool,
48-
}
4928

5029
/// Creates a hasher instance based on the command-line flags.
5130
///
@@ -186,9 +165,9 @@ pub fn uumain(mut args: impl uucore::Args) -> UResult<()> {
186165
};
187166
let check = matches.get_flag("check");
188167
let status = matches.get_flag("status");
189-
let quiet = matches.get_flag("quiet") || status;
168+
let quiet = matches.get_flag("quiet");
190169
let strict = matches.get_flag("strict");
191-
let warn = matches.get_flag("warn") && !status;
170+
let warn = matches.get_flag("warn");
192171
let ignore_missing = matches.get_flag("ignore-missing");
193172

194173
if ignore_missing && !check {
@@ -232,33 +211,37 @@ pub fn uumain(mut args: impl uucore::Args) -> UResult<()> {
232211
return Err(ChecksumError::StrictNotCheck.into());
233212
}
234213

235-
let nonames = *matches
214+
let no_names = *matches
236215
.try_get_one("no-names")
237216
.unwrap_or(None)
238217
.unwrap_or(&false);
239-
let zero = matches.get_flag("zero");
218+
let line_ending = LineEnding::from_zero_flag(matches.get_flag("zero"));
240219

241220
let algo = SizedAlgoKind::from_unsized(algo_kind, length)?;
242221

243-
let opts = Options {
244-
algo,
222+
let opts = ChecksumComputeOptions {
223+
algo_kind: algo,
245224
digest: algo.create_digest(),
246-
binary,
247-
binary_name: &binary_name,
248-
tag: matches.get_flag("tag"),
249-
nonames,
250-
//status,
251-
//quiet,
252-
//warn,
253-
zero,
254-
//ignore_missing,
225+
output_format: figure_out_output_format(
226+
algo,
227+
matches.get_flag(options::TAG),
228+
binary,
229+
/* raw */ false,
230+
/* base64: */ false,
231+
),
232+
line_ending,
233+
no_names,
255234
};
256235

236+
let files = matches.get_many::<OsString>(options::FILE).map_or_else(
237+
// No files given, read from stdin.
238+
|| Box::new(iter::once(OsStr::new("-"))) as Box<dyn Iterator<Item = &OsStr>>,
239+
// At least one file given, read from them.
240+
|files| Box::new(files.map(OsStr::new)) as Box<dyn Iterator<Item = &OsStr>>,
241+
);
242+
257243
// Show the hashsum of the input
258-
match matches.get_many::<OsString>(options::FILE) {
259-
Some(files) => hashsum(opts, files.map(|f| f.as_os_str())),
260-
None => hashsum(opts, iter::once(OsStr::new("-"))),
261-
}
244+
perform_checksum_computation(opts, files)
262245
}
263246

264247
mod options {
@@ -498,75 +481,3 @@ fn uu_app(binary_name: &str) -> (Command, bool) {
498481

499482
(command, is_hashsum_bin)
500483
}
501-
502-
#[allow(clippy::cognitive_complexity)]
503-
fn hashsum<'a, I>(mut options: Options, files: I) -> UResult<()>
504-
where
505-
I: Iterator<Item = &'a OsStr>,
506-
{
507-
let binary_marker = if options.binary { "*" } else { " " };
508-
let mut err_found = None;
509-
for filename in files {
510-
let filename = Path::new(filename);
511-
512-
let mut file = BufReader::with_capacity(
513-
READ_BUFFER_SIZE,
514-
if filename == OsStr::new("-") {
515-
Box::new(stdin()) as Box<dyn Read>
516-
} else {
517-
let file_buf = match File::open(filename) {
518-
Ok(f) => f,
519-
Err(e) => {
520-
eprintln!(
521-
"{}: {}: {}",
522-
options.binary_name,
523-
filename.to_string_lossy(),
524-
strip_errno(&e)
525-
);
526-
err_found = Some(ChecksumError::Io(e));
527-
continue;
528-
}
529-
};
530-
Box::new(file_buf) as Box<dyn Read>
531-
},
532-
);
533-
534-
let sum = match digest_reader(
535-
&mut options.digest,
536-
&mut file,
537-
options.binary,
538-
options.algo.bitlen(),
539-
) {
540-
Ok((sum, _)) => sum,
541-
Err(e) => {
542-
eprintln!(
543-
"{}: {}: {}",
544-
options.binary_name,
545-
filename.to_string_lossy(),
546-
strip_errno(&e)
547-
);
548-
err_found = Some(ChecksumError::Io(e));
549-
continue;
550-
}
551-
};
552-
553-
let (escaped_filename, prefix) = escape_filename(filename);
554-
if options.tag {
555-
println!(
556-
"{prefix}{} ({escaped_filename}) = {sum}",
557-
options.algo.to_tag()
558-
);
559-
} else if options.nonames {
560-
println!("{sum}");
561-
} else if options.zero {
562-
// with zero, we don't escape the filename
563-
print!("{sum} {binary_marker}{}\0", filename.display());
564-
} else {
565-
println!("{prefix}{sum} {binary_marker}{escaped_filename}");
566-
}
567-
}
568-
match err_found {
569-
None => Ok(()),
570-
Some(e) => Err(Box::new(e)),
571-
}
572-
}

0 commit comments

Comments
 (0)