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

Extract uucore::line_ending::LineEnding #5120

Merged
merged 12 commits into from
Aug 20, 2023
5 changes: 3 additions & 2 deletions src/uu/basename/src/basename.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use clap::{crate_version, Arg, ArgAction, Command};
use std::path::{is_separator, PathBuf};
use uucore::display::Quotable;
use uucore::error::{UResult, UUsageError};
use uucore::line_ending::LineEnding;
use uucore::{format_usage, help_about, help_usage};

static ABOUT: &str = help_about!("basename.md");
Expand Down Expand Up @@ -54,9 +55,10 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
return Err(UUsageError::new(1, "missing operand".to_string()));
}

let line_ending = LineEnding::from_zero_flag(matches.get_flag(options::ZERO));

let opt_suffix = matches.get_one::<String>(options::SUFFIX).is_some();
let opt_multiple = matches.get_flag(options::MULTIPLE);
let opt_zero = matches.get_flag(options::ZERO);
let multiple_paths = opt_suffix || opt_multiple;
let name_args_count = matches
.get_many::<String>(options::NAME)
Expand Down Expand Up @@ -105,7 +107,6 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
.collect()
};

let line_ending = if opt_zero { "\0" } else { "\n" };
for path in paths {
print!("{}{}", basename(path, suffix), line_ending);
}
Expand Down
38 changes: 3 additions & 35 deletions src/uu/comm/src/comm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@
// spell-checker:ignore (ToDO) delim mkdelim

use std::cmp::Ordering;
use std::fmt::Display;
use std::fs::File;
use std::io::{self, stdin, BufRead, BufReader, Stdin};
use std::path::Path;
use uucore::error::{FromIo, UResult};
use uucore::line_ending::LineEnding;
use uucore::{format_usage, help_about, help_usage};

use clap::{crate_version, Arg, ArgAction, ArgMatches, Command};
Expand Down Expand Up @@ -40,38 +40,6 @@ fn column_width(col: &str, opts: &ArgMatches) -> usize {
}
}

#[repr(u8)]
#[derive(Clone, Copy)]
enum LineEnding {
Newline = b'\n',
Nul = 0,
}

impl From<LineEnding> for u8 {
fn from(line_ending: LineEnding) -> Self {
line_ending as Self
}
}

impl From<bool> for LineEnding {
fn from(is_zero_terminated: bool) -> Self {
if is_zero_terminated {
Self::Nul
} else {
Self::Newline
}
}
}

impl Display for LineEnding {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Newline => writeln!(f),
Self::Nul => write!(f, "\0"),
}
}
}

enum Input {
Stdin(Stdin),
FileIn(BufReader<File>),
Expand Down Expand Up @@ -168,7 +136,7 @@ fn comm(a: &mut LineReader, b: &mut LineReader, opts: &ArgMatches) {
}

if opts.get_flag(options::TOTAL) {
let line_ending = LineEnding::from(opts.get_flag(options::ZERO_TERMINATED));
let line_ending = LineEnding::from_zero_flag(opts.get_flag(options::ZERO_TERMINATED));
print!("{total_col_1}{delim}{total_col_2}{delim}{total_col_3}{delim}total{line_ending}");
}
}
Expand All @@ -190,7 +158,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let args = args.collect_lossy();

let matches = uu_app().try_get_matches_from(args)?;
let line_ending = LineEnding::from(matches.get_flag(options::ZERO_TERMINATED));
let line_ending = LineEnding::from_zero_flag(matches.get_flag(options::ZERO_TERMINATED));
let filename1 = matches.get_one::<String>(options::FILE_1).unwrap();
let filename2 = matches.get_one::<String>(options::FILE_2).unwrap();
let mut f1 = open_file(filename1, line_ending).map_err_context(|| filename1.to_string())?;
Expand Down
18 changes: 10 additions & 8 deletions src/uu/cut/src/cut.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use std::io::{stdin, stdout, BufReader, BufWriter, Read, Write};
use std::path::Path;
use uucore::display::Quotable;
use uucore::error::{FromIo, UResult, USimpleError};
use uucore::line_ending::LineEnding;

use self::searcher::Searcher;
use matcher::{ExactMatcher, Matcher, WhitespaceMatcher};
Expand All @@ -30,7 +31,7 @@ const AFTER_HELP: &str = help_section!("after help", "cut.md");

struct Options {
out_delim: Option<String>,
zero_terminated: bool,
line_ending: LineEnding,
}

enum Delimiter {
Expand All @@ -42,7 +43,7 @@ struct FieldOptions {
delimiter: Delimiter,
out_delimiter: Option<String>,
only_delimited: bool,
zero_terminated: bool,
line_ending: LineEnding,
}

enum Mode {
Expand All @@ -68,7 +69,7 @@ fn list_to_ranges(list: &str, complement: bool) -> Result<Vec<Range>, String> {
}

fn cut_bytes<R: Read>(reader: R, ranges: &[Range], opts: &Options) -> UResult<()> {
let newline_char = if opts.zero_terminated { b'\0' } else { b'\n' };
let newline_char = opts.line_ending.into();
let mut buf_in = BufReader::new(reader);
let mut out = stdout_writer();
let delim = opts
Expand Down Expand Up @@ -259,7 +260,7 @@ fn cut_fields_implicit_out_delim<R: Read, M: Matcher>(
}

fn cut_fields<R: Read>(reader: R, ranges: &[Range], opts: &FieldOptions) -> UResult<()> {
let newline_char = if opts.zero_terminated { b'\0' } else { b'\n' };
let newline_char = opts.line_ending.into();
match opts.delimiter {
Delimiter::String(ref delim) => {
let matcher = ExactMatcher::new(delim.as_bytes());
Expand Down Expand Up @@ -376,7 +377,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
.unwrap_or_default()
.to_owned(),
),
zero_terminated: matches.get_flag(options::ZERO_TERMINATED),
line_ending: LineEnding::from_zero_flag(matches.get_flag(options::ZERO_TERMINATED)),
},
)
}),
Expand All @@ -391,7 +392,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
.unwrap_or_default()
.to_owned(),
),
zero_terminated: matches.get_flag(options::ZERO_TERMINATED),
line_ending: LineEnding::from_zero_flag(matches.get_flag(options::ZERO_TERMINATED)),
},
)
}),
Expand All @@ -411,6 +412,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let only_delimited = matches.get_flag(options::ONLY_DELIMITED);
let whitespace_delimited = matches.get_flag(options::WHITESPACE_DELIMITED);
let zero_terminated = matches.get_flag(options::ZERO_TERMINATED);
let line_ending = LineEnding::from_zero_flag(zero_terminated);

match matches.get_one::<String>(options::DELIMITER).map(|s| s.as_str()) {
Some(_) if whitespace_delimited => {
Expand Down Expand Up @@ -441,7 +443,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
delimiter: Delimiter::String(delim),
out_delimiter: out_delim,
only_delimited,
zero_terminated,
line_ending,
},
))
}
Expand All @@ -455,7 +457,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
},
out_delimiter: out_delim,
only_delimited,
zero_terminated,
line_ending,
},
)),
}
Expand Down
9 changes: 3 additions & 6 deletions src/uu/dirname/src/dirname.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use clap::{crate_version, Arg, ArgAction, Command};
use std::path::Path;
use uucore::display::print_verbatim;
use uucore::error::{UResult, UUsageError};
use uucore::line_ending::LineEnding;
use uucore::{format_usage, help_about, help_section, help_usage};

const ABOUT: &str = help_about!("dirname.md");
Expand All @@ -26,11 +27,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {

let matches = uu_app().after_help(AFTER_HELP).try_get_matches_from(args)?;

let separator = if matches.get_flag(options::ZERO) {
"\0"
} else {
"\n"
};
let line_ending = LineEnding::from_zero_flag(matches.get_flag(options::ZERO));

let dirnames: Vec<String> = matches
.get_many::<String>(options::DIR)
Expand Down Expand Up @@ -59,7 +56,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
}
}
}
print!("{separator}");
print!("{line_ending}");
}
}

Expand Down
13 changes: 5 additions & 8 deletions src/uu/du/src/du.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
use uucore::display::{print_verbatim, Quotable};
use uucore::error::FromIo;
use uucore::error::{set_exit_code, UError, UResult};
use uucore::line_ending::LineEnding;
use uucore::parse_glob;
use uucore::parse_size::{parse_size, ParseSizeError};
use uucore::{
Expand Down Expand Up @@ -600,11 +601,7 @@
let time_format_str =
parse_time_style(matches.get_one::<String>("time-style").map(|s| s.as_str()))?;

let line_separator = if matches.get_flag(options::NULL) {
"\0"
} else {
"\n"
};
let line_ending = LineEnding::from_zero_flag(matches.get_flag(options::NULL));

let excludes = build_exclude_patterns(&matches)?;

Expand Down Expand Up @@ -656,12 +653,12 @@
let time_str = tm.format(time_format_str).to_string();
print!("{}\t{}\t", convert_size(size), time_str);
print_verbatim(stat.path).unwrap();
print!("{line_separator}");
print!("{line_ending}");
}
} else if !summarize || index == len - 1 {
print!("{}\t", convert_size(size));
print_verbatim(stat.path).unwrap();
print!("{line_separator}");
print!("{line_ending}");
}
if options.total && index == (len - 1) {
// The last element will be the total size of the the path under
Expand All @@ -681,7 +678,7 @@

if options.total {
print!("{}\ttotal", convert_size(grand_total));
print!("{line_separator}");
print!("{line_ending}");

Check warning on line 681 in src/uu/du/src/du.rs

View check run for this annotation

Codecov / codecov/patch

src/uu/du/src/du.rs#L681

Added line #L681 was not covered by tests
}

Ok(())
Expand Down
15 changes: 8 additions & 7 deletions src/uu/env/src/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ use std::os::unix::process::ExitStatusExt;
use std::process;
use uucore::display::Quotable;
use uucore::error::{UClapError, UResult, USimpleError, UUsageError};
use uucore::line_ending::LineEnding;
use uucore::{format_usage, help_about, help_section, help_usage, show_warning};

const ABOUT: &str = help_about!("env.md");
Expand All @@ -31,7 +32,7 @@ const AFTER_HELP: &str = help_section!("after help", "env.md");

struct Options<'a> {
ignore_env: bool,
null: bool,
line_ending: LineEnding,
running_directory: Option<&'a str>,
files: Vec<&'a str>,
unsets: Vec<&'a str>,
Expand All @@ -41,11 +42,11 @@ struct Options<'a> {

// print name=value env pairs on screen
// if null is true, separate pairs with a \0, \n otherwise
fn print_env(null: bool) {
fn print_env(line_ending: LineEnding) {
let stdout_raw = io::stdout();
let mut stdout = stdout_raw.lock();
for (n, v) in env::vars() {
write!(stdout, "{}={}{}", n, v, if null { '\0' } else { '\n' }).unwrap();
write!(stdout, "{}={}{}", n, v, line_ending).unwrap();
}
}

Expand All @@ -64,7 +65,7 @@ fn parse_name_value_opt<'a>(opts: &mut Options<'a>, opt: &'a str) -> UResult<boo
}

fn parse_program_opt<'a>(opts: &mut Options<'a>, opt: &'a str) -> UResult<()> {
if opts.null {
if opts.line_ending == LineEnding::Nul {
Err(UUsageError::new(
125,
"cannot specify --null (-0) with command".to_string(),
Expand Down Expand Up @@ -181,7 +182,7 @@ fn run_env(args: impl uucore::Args) -> UResult<()> {
let matches = app.try_get_matches_from(args).with_exit_code(125)?;

let ignore_env = matches.get_flag("ignore-environment");
let null = matches.get_flag("null");
let line_ending = LineEnding::from_zero_flag(matches.get_flag("null"));
let running_directory = matches.get_one::<String>("chdir").map(|s| s.as_str());
let files = match matches.get_many::<String>("file") {
Some(v) => v.map(|s| s.as_str()).collect(),
Expand All @@ -194,7 +195,7 @@ fn run_env(args: impl uucore::Args) -> UResult<()> {

let mut opts = Options {
ignore_env,
null,
line_ending,
running_directory,
files,
unsets,
Expand Down Expand Up @@ -302,7 +303,7 @@ fn run_env(args: impl uucore::Args) -> UResult<()> {

if opts.program.is_empty() {
// no program provided, so just dump all env vars to stdout
print_env(opts.null);
print_env(opts.line_ending);
} else {
// we need to execute a command
let (prog, args) = build_command(&mut opts.program);
Expand Down
Loading
Loading