| 1 |
// This file is part of the uutils coreutils package. |
| 2 |
// |
| 3 |
// For the full copyright and license information, please view the LICENSE |
| 4 |
// file that was distributed with this source code. |
| 5 |
|
| 6 |
// spell-checker:ignore (ToDO) delim mkdelim pairable |
| 7 |
|
| 8 |
use std::cmp::Ordering; |
| 9 |
use std::ffi::OsString; |
| 10 |
use std::fs::File; |
| 11 |
use std::io::{self, BufRead, BufReader, BufWriter, StdinLock, Write, stderr, stdin}; |
| 12 |
use std::path::Path; |
| 13 |
use uucore::display::Quotable; |
| 14 |
use uucore::error::{FromIo, UResult, USimpleError}; |
| 15 |
use uucore::format_usage; |
| 16 |
use uucore::fs::{are_files_identical, paths_refer_to_same_file}; |
| 17 |
use uucore::i18n::collator::{ |
| 18 |
AlternateHandling, CollatorOptions, locale_cmp, should_use_locale_collation, try_init_collator, |
| 19 |
}; |
| 20 |
use uucore::line_ending::LineEnding; |
| 21 |
use uucore::translate; |
| 22 |
|
| 23 |
use clap::{Arg, ArgAction, ArgMatches, Command}; |
| 24 |
|
| 25 |
mod options { |
| 26 |
pub const COLUMN_1: &str = "1"; |
| 27 |
pub const COLUMN_2: &str = "2"; |
| 28 |
pub const COLUMN_3: &str = "3"; |
| 29 |
pub const DELIMITER: &str = "output-delimiter"; |
| 30 |
pub const DELIMITER_DEFAULT: &str = "\t"; |
| 31 |
pub const FILE_1: &str = "FILE1"; |
| 32 |
pub const FILE_2: &str = "FILE2"; |
| 33 |
pub const TOTAL: &str = "total"; |
| 34 |
pub const ZERO_TERMINATED: &str = "zero-terminated"; |
| 35 |
pub const CHECK_ORDER: &str = "check-order"; |
| 36 |
pub const NO_CHECK_ORDER: &str = "nocheck-order"; |
| 37 |
} |
| 38 |
|
| 39 |
#[derive(Debug, Clone, Copy)] |
| 40 |
enum FileNumber { |
| 41 |
One, |
| 42 |
Two, |
| 43 |
} |
| 44 |
|
| 45 |
impl FileNumber { |
| 46 |
fn as_str(self) -> &'static str { |
| 47 |
match self { |
| 48 |
Self::One => "1", |
| 49 |
Self::Two => "2", |
| 50 |
} |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
struct OrderChecker { |
| 55 |
last_line: Vec<u8>, |
| 56 |
file_num: FileNumber, |
| 57 |
check_order: bool, |
| 58 |
has_error: bool, |
| 59 |
use_locale: bool, |
| 60 |
} |
| 61 |
|
| 62 |
/// Compare two lines the way the input was ordered. |
| 63 |
/// |
| 64 |
/// `sort` orders with the locale collation, and so do `join` and `ls`. Reading |
| 65 |
/// that order back with a byte comparison rejects input that is in order and |
| 66 |
/// puts lines in the wrong column, so `comm` has to measure it the same way. |
| 67 |
fn line_cmp(a: &[u8], b: &[u8], use_locale: bool) -> Ordering { |
| 68 |
if use_locale { |
| 69 |
locale_cmp(a, b) |
| 70 |
} else { |
| 71 |
a.cmp(b) |
| 72 |
} |
| 73 |
} |
| 74 |
|
| 75 |
enum Input { |
| 76 |
Stdin(StdinLock<'static>), |
| 77 |
FileIn(BufReader<File>), |
| 78 |
} |
| 79 |
|
| 80 |
impl Input { |
| 81 |
fn stdin() -> Self { |
| 82 |
Self::Stdin(stdin().lock()) |
| 83 |
} |
| 84 |
|
| 85 |
fn from_file(f: File) -> Self { |
| 86 |
Self::FileIn(BufReader::new(f)) |
| 87 |
} |
| 88 |
} |
| 89 |
|
| 90 |
struct LineReader { |
| 91 |
line_ending: LineEnding, |
| 92 |
input: Input, |
| 93 |
} |
| 94 |
|
| 95 |
impl LineReader { |
| 96 |
fn new(input: Input, line_ending: LineEnding) -> Self { |
| 97 |
Self { line_ending, input } |
| 98 |
} |
| 99 |
|
| 100 |
fn read_line(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> { |
| 101 |
let line_ending = self.line_ending.into(); |
| 102 |
|
| 103 |
let result = match &mut self.input { |
| 104 |
Input::Stdin(r) => r.read_until(line_ending, buf), |
| 105 |
Input::FileIn(r) => r.read_until(line_ending, buf), |
| 106 |
}; |
| 107 |
|
| 108 |
if !buf.ends_with(&[line_ending]) { |
| 109 |
buf.push(line_ending); |
| 110 |
} |
| 111 |
|
| 112 |
result |
| 113 |
} |
| 114 |
} |
| 115 |
|
| 116 |
impl OrderChecker { |
| 117 |
fn new(file_num: FileNumber, check_order: bool, use_locale: bool) -> Self { |
| 118 |
Self { |
| 119 |
last_line: Vec::new(), |
| 120 |
file_num, |
| 121 |
check_order, |
| 122 |
has_error: false, |
| 123 |
use_locale, |
| 124 |
} |
| 125 |
} |
| 126 |
|
| 127 |
fn verify_order(&mut self, current_line: &[u8]) -> bool { |
| 128 |
if self.last_line.is_empty() { |
| 129 |
self.last_line = current_line.to_vec(); |
| 130 |
return true; |
| 131 |
} |
| 132 |
|
| 133 |
let is_ordered = line_cmp(current_line, &self.last_line, self.use_locale) != Ordering::Less; |
| 134 |
if !is_ordered && !self.has_error { |
| 135 |
let _ = writeln!( |
| 136 |
stderr(), |
| 137 |
"{}", |
| 138 |
translate!("comm-error-file-not-sorted", "file_num" => self.file_num.as_str()) |
| 139 |
); |
| 140 |
self.has_error = true; |
| 141 |
} |
| 142 |
|
| 143 |
self.last_line = current_line.to_vec(); |
| 144 |
is_ordered || !self.check_order |
| 145 |
} |
| 146 |
} |
| 147 |
|
| 148 |
fn write_line_with_delimiter<W: Write>(writer: &mut W, delim: &[u8], line: &[u8]) -> UResult<()> { |
| 149 |
writer |
| 150 |
.write_all(delim) |
| 151 |
.map_err_context(|| translate!("comm-error-write"))?; |
| 152 |
writer |
| 153 |
.write_all(line) |
| 154 |
.map_err_context(|| translate!("comm-error-write"))?; |
| 155 |
Ok(()) |
| 156 |
} |
| 157 |
|
| 158 |
fn comm( |
| 159 |
a: &mut LineReader, |
| 160 |
b: &mut LineReader, |
| 161 |
filename1: &OsString, |
| 162 |
filename2: &OsString, |
| 163 |
delim: &str, |
| 164 |
opts: &ArgMatches, |
| 165 |
) -> UResult<()> { |
| 166 |
let width_col_1 = usize::from(!opts.get_flag(options::COLUMN_1)); |
| 167 |
let width_col_2 = usize::from(!opts.get_flag(options::COLUMN_2)); |
| 168 |
|
| 169 |
let delim_col_2 = delim.repeat(width_col_1); |
| 170 |
let delim_col_3 = delim.repeat(width_col_1 + width_col_2); |
| 171 |
|
| 172 |
let mut writer = BufWriter::new(io::stdout().lock()); |
| 173 |
|
| 174 |
let ra = &mut Vec::new(); |
| 175 |
let mut na = a |
| 176 |
.read_line(ra) |
| 177 |
.map_err_context(|| filename1.maybe_quote().to_string())?; |
| 178 |
let rb = &mut Vec::new(); |
| 179 |
let mut nb = b |
| 180 |
.read_line(rb) |
| 181 |
.map_err_context(|| filename2.maybe_quote().to_string())?; |
| 182 |
|
| 183 |
let mut total_col_1 = 0; |
| 184 |
let mut total_col_2 = 0; |
| 185 |
let mut total_col_3 = 0; |
| 186 |
|
| 187 |
let check_order = opts.get_flag(options::CHECK_ORDER); |
| 188 |
let no_check_order = opts.get_flag(options::NO_CHECK_ORDER); |
| 189 |
|
| 190 |
// Determine if we should perform order checking |
| 191 |
let should_check_order = !no_check_order |
| 192 |
&& (check_order |
| 193 |
|| !(paths_refer_to_same_file(filename1.as_os_str(), filename2.as_os_str(), true) |
| 194 |
|| are_files_identical(Path::new(filename1), Path::new(filename2)) |
| 195 |
.unwrap_or(false))); |
| 196 |
|
| 197 |
let use_locale = should_use_locale_collation(); |
| 198 |
let mut checker1 = OrderChecker::new(FileNumber::One, check_order, use_locale); |
| 199 |
let mut checker2 = OrderChecker::new(FileNumber::Two, check_order, use_locale); |
| 200 |
let mut input_error = false; |
| 201 |
|
| 202 |
while na != 0 || nb != 0 { |
| 203 |
let ord = match (na, nb) { |
| 204 |
(0, _) => Ordering::Greater, |
| 205 |
(_, 0) => Ordering::Less, |
| 206 |
(_, _) => line_cmp(ra, rb, use_locale), |
| 207 |
}; |
| 208 |
|
| 209 |
match ord { |
| 210 |
Ordering::Less => { |
| 211 |
if should_check_order && !checker1.verify_order(ra) { |
| 212 |
break; |
| 213 |
} |
| 214 |
if !opts.get_flag(options::COLUMN_1) { |
| 215 |
writer |
| 216 |
.write_all(ra) |
| 217 |
.map_err_context(|| translate!("comm-error-write"))?; |
| 218 |
} |
| 219 |
ra.clear(); |
| 220 |
na = a |
| 221 |
.read_line(ra) |
| 222 |
.map_err_context(|| filename1.maybe_quote().to_string())?; |
| 223 |
total_col_1 += 1; |
| 224 |
} |
| 225 |
Ordering::Greater => { |
| 226 |
if should_check_order && !checker2.verify_order(rb) { |
| 227 |
break; |
| 228 |
} |
| 229 |
if !opts.get_flag(options::COLUMN_2) { |
| 230 |
write_line_with_delimiter(&mut writer, delim_col_2.as_bytes(), rb)?; |
| 231 |
} |
| 232 |
rb.clear(); |
| 233 |
nb = b |
| 234 |
.read_line(rb) |
| 235 |
.map_err_context(|| filename2.maybe_quote().to_string())?; |
| 236 |
total_col_2 += 1; |
| 237 |
} |
| 238 |
Ordering::Equal => { |
| 239 |
if should_check_order && (!checker1.verify_order(ra) || !checker2.verify_order(rb)) |
| 240 |
{ |
| 241 |
break; |
| 242 |
} |
| 243 |
if !opts.get_flag(options::COLUMN_3) { |
| 244 |
write_line_with_delimiter(&mut writer, delim_col_3.as_bytes(), ra)?; |
| 245 |
} |
| 246 |
ra.clear(); |
| 247 |
rb.clear(); |
| 248 |
na = a |
| 249 |
.read_line(ra) |
| 250 |
.map_err_context(|| filename1.maybe_quote().to_string())?; |
| 251 |
nb = b |
| 252 |
.read_line(rb) |
| 253 |
.map_err_context(|| filename2.maybe_quote().to_string())?; |
| 254 |
total_col_3 += 1; |
| 255 |
} |
| 256 |
} |
| 257 |
|
| 258 |
// Track if we've seen any order errors |
| 259 |
if (checker1.has_error || checker2.has_error) && !input_error && !check_order { |
| 260 |
input_error = true; |
| 261 |
} |
| 262 |
} |
| 263 |
|
| 264 |
if opts.get_flag(options::TOTAL) { |
| 265 |
let line_ending = LineEnding::from_zero_flag(opts.get_flag(options::ZERO_TERMINATED)); |
| 266 |
write!( |
| 267 |
writer, |
| 268 |
"{total_col_1}{delim}{total_col_2}{delim}{total_col_3}{delim}{}{line_ending}", |
| 269 |
translate!("comm-total") |
| 270 |
) |
| 271 |
.map_err_context(|| translate!("comm-error-write"))?; |
| 272 |
} |
| 273 |
|
| 274 |
writer |
| 275 |
.flush() |
| 276 |
.map_err_context(|| translate!("comm-error-write"))?; |
| 277 |
|
| 278 |
if should_check_order && (checker1.has_error || checker2.has_error) { |
| 279 |
// Print the input error message once at the end |
| 280 |
if input_error { |
| 281 |
let _ = writeln!(stderr(), "{}", translate!("comm-error-input-not-sorted")); |
| 282 |
} |
| 283 |
Err(USimpleError::new(1, "")) |
| 284 |
} else { |
| 285 |
Ok(()) |
| 286 |
} |
| 287 |
} |
| 288 |
|
| 289 |
fn open_file(name: &OsString, line_ending: LineEnding) -> io::Result<LineReader> { |
| 290 |
if name == "-" { |
| 291 |
Ok(LineReader::new(Input::stdin(), line_ending)) |
| 292 |
} else { |
| 293 |
// some platforms shows different read error |
| 294 |
// try to override the error message, but failure of it is not serious |
| 295 |
#[cfg(any(target_os = "wasi", windows))] |
| 296 |
if std::fs::metadata(name).is_ok_and(|m| m.is_dir()) { |
| 297 |
return Err(io::Error::other(translate!("comm-error-is-directory"))); |
| 298 |
} |
| 299 |
let f = File::open(name)?; |
| 300 |
Ok(LineReader::new(Input::from_file(f), line_ending)) |
| 301 |
} |
| 302 |
} |
| 303 |
|
| 304 |
#[uucore::main] |
| 305 |
pub fn uumain(args: impl uucore::Args) -> UResult<()> { |
| 306 |
let matches = uucore::clap_localization::handle_clap_result(uu_app(), args)?; |
| 307 |
|
| 308 |
let mut collator_opts = CollatorOptions::default(); |
| 309 |
collator_opts.alternate_handling = Some(AlternateHandling::Shifted); |
| 310 |
let _ = try_init_collator(collator_opts); |
| 311 |
|
| 312 |
let line_ending = LineEnding::from_zero_flag(matches.get_flag(options::ZERO_TERMINATED)); |
| 313 |
let filename1 = matches.get_one::<OsString>(options::FILE_1).unwrap(); |
| 314 |
let filename2 = matches.get_one::<OsString>(options::FILE_2).unwrap(); |
| 315 |
let mut f1 = open_file(filename1, line_ending) |
| 316 |
.map_err_context(|| filename1.maybe_quote().to_string())?; |
| 317 |
let mut f2 = open_file(filename2, line_ending) |
| 318 |
.map_err_context(|| filename2.maybe_quote().to_string())?; |
| 319 |
|
| 320 |
// Due to default_value(), there must be at least one value here, thus unwrap() must not panic. |
| 321 |
let all_delimiters = matches |
| 322 |
.get_many::<String>(options::DELIMITER) |
| 323 |
.unwrap() |
| 324 |
.map(String::from) |
| 325 |
.collect::<Vec<_>>(); |
| 326 |
for delim in &all_delimiters[1..] { |
| 327 |
// Note that this check is very different from ".conflicts_with_self(true).action(ArgAction::Set)", |
| 328 |
// as this accepts duplicate *identical* arguments. |
| 329 |
if delim != &all_delimiters[0] { |
| 330 |
// Note: This intentionally deviate from the GNU error message by inserting the word "conflicting". |
| 331 |
return Err(USimpleError::new( |
| 332 |
1, |
| 333 |
translate!("comm-error-multiple-conflicting-delimiters"), |
| 334 |
)); |
| 335 |
} |
| 336 |
} |
| 337 |
let delim = match &*all_delimiters[0] { |
| 338 |
"" => "\0", |
| 339 |
delim => delim, |
| 340 |
}; |
| 341 |
|
| 342 |
comm(&mut f1, &mut f2, filename1, filename2, delim, &matches) |
| 343 |
} |
| 344 |
|
| 345 |
pub fn uu_app() -> Command { |
| 346 |
Command::new("comm") |
| 347 |
.version(uucore::crate_version!()) |
| 348 |
.help_template(uucore::localized_help_template("comm")) |
| 349 |
.about(translate!("comm-about")) |
| 350 |
.override_usage(format_usage(&translate!("comm-usage"))) |
| 351 |
.infer_long_args(true) |
| 352 |
.args_override_self(true) |
| 353 |
.arg( |
| 354 |
Arg::new(options::COLUMN_1) |
| 355 |
.short('1') |
| 356 |
.help(translate!("comm-help-column-1")) |
| 357 |
.action(ArgAction::SetTrue), |
| 358 |
) |
| 359 |
.arg( |
| 360 |
Arg::new(options::COLUMN_2) |
| 361 |
.short('2') |
| 362 |
.help(translate!("comm-help-column-2")) |
| 363 |
.action(ArgAction::SetTrue), |
| 364 |
) |
| 365 |
.arg( |
| 366 |
Arg::new(options::COLUMN_3) |
| 367 |
.short('3') |
| 368 |
.help(translate!("comm-help-column-3")) |
| 369 |
.action(ArgAction::SetTrue), |
| 370 |
) |
| 371 |
.arg( |
| 372 |
Arg::new(options::DELIMITER) |
| 373 |
.long(options::DELIMITER) |
| 374 |
.help(translate!("comm-help-delimiter")) |
| 375 |
.value_name("STR") |
| 376 |
.default_value(options::DELIMITER_DEFAULT) |
| 377 |
.allow_hyphen_values(true) |
| 378 |
.action(ArgAction::Append) |
| 379 |
.hide_default_value(true), |
| 380 |
) |
| 381 |
.arg( |
| 382 |
Arg::new(options::ZERO_TERMINATED) |
| 383 |
.long(options::ZERO_TERMINATED) |
| 384 |
.short('z') |
| 385 |
.overrides_with(options::ZERO_TERMINATED) |
| 386 |
.help(translate!("comm-help-zero-terminated")) |
| 387 |
.action(ArgAction::SetTrue), |
| 388 |
) |
| 389 |
.arg( |
| 390 |
Arg::new(options::FILE_1) |
| 391 |
.required(true) |
| 392 |
.value_hint(clap::ValueHint::FilePath) |
| 393 |
.value_parser(clap::value_parser!(OsString)), |
| 394 |
) |
| 395 |
.arg( |
| 396 |
Arg::new(options::FILE_2) |
| 397 |
.required(true) |
| 398 |
.value_hint(clap::ValueHint::FilePath) |
| 399 |
.value_parser(clap::value_parser!(OsString)), |
| 400 |
) |
| 401 |
.arg( |
| 402 |
Arg::new(options::TOTAL) |
| 403 |
.long(options::TOTAL) |
| 404 |
.help(translate!("comm-help-total")) |
| 405 |
.action(ArgAction::SetTrue), |
| 406 |
) |
| 407 |
.arg( |
| 408 |
Arg::new(options::CHECK_ORDER) |
| 409 |
.long(options::CHECK_ORDER) |
| 410 |
.help(translate!("comm-help-check-order")) |
| 411 |
.action(ArgAction::SetTrue), |
| 412 |
) |
| 413 |
.arg( |
| 414 |
Arg::new(options::NO_CHECK_ORDER) |
| 415 |
.long(options::NO_CHECK_ORDER) |
| 416 |
.help(translate!("comm-help-no-check-order")) |
| 417 |
.action(ArgAction::SetTrue) |
| 418 |
.conflicts_with(options::CHECK_ORDER), |
| 419 |
) |
| 420 |
} |