1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-07-31 21:17:46 +00:00

Update for namespaced enums

This commit is contained in:
Michael Gehring 2014-11-19 21:50:37 +01:00
parent 274b624a34
commit cd409c6d3f
16 changed files with 219 additions and 218 deletions

View file

@ -55,13 +55,13 @@ pub fn uumain(args: Vec<String>) -> int {
let progname = args[0].clone(); let progname = args[0].clone();
let usage = usage("Base64 encode or decode FILE, or standard input, to standard output.", opts); let usage = usage("Base64 encode or decode FILE, or standard input, to standard output.", opts);
let mode = if matches.opt_present("help") { let mode = if matches.opt_present("help") {
Help Mode::Help
} else if matches.opt_present("version") { } else if matches.opt_present("version") {
Version Mode::Version
} else if matches.opt_present("decode") { } else if matches.opt_present("decode") {
Decode Mode::Decode
} else { } else {
Encode Mode::Encode
}; };
let ignore_garbage = matches.opt_present("ignore-garbage"); let ignore_garbage = matches.opt_present("ignore-garbage");
let line_wrap = match matches.opt_str("wrap") { let line_wrap = match matches.opt_str("wrap") {
@ -86,10 +86,10 @@ pub fn uumain(args: Vec<String>) -> int {
}; };
match mode { match mode {
Decode => decode(input, ignore_garbage), Mode::Decode => decode(input, ignore_garbage),
Encode => encode(input, line_wrap), Mode::Encode => encode(input, line_wrap),
Help => help(progname.as_slice(), usage.as_slice()), Mode::Help => help(progname.as_slice(), usage.as_slice()),
Version => version() Mode::Version => version()
} }
0 0

View file

@ -57,12 +57,12 @@ pub fn uumain(args: Vec<String>) -> int {
return 0; return 0;
} }
let mut number_mode = NumberNone; let mut number_mode = NumberingMode::NumberNone;
if matches.opt_present("n") { if matches.opt_present("n") {
number_mode = NumberAll; number_mode = NumberingMode::NumberAll;
} }
if matches.opt_present("b") { if matches.opt_present("b") {
number_mode = NumberNonEmpty; number_mode = NumberingMode::NumberNonEmpty;
} }
let show_nonprint = matches.opts_present(["A".to_string(), "e".to_string(), let show_nonprint = matches.opts_present(["A".to_string(), "e".to_string(),
"t".to_string(), "v".to_string()]); "t".to_string(), "v".to_string()]);
@ -118,7 +118,7 @@ fn write_lines(files: Vec<String>, number: NumberingMode, squeeze_blank: bool,
}; };
if in_buf[pos] == '\n' as u8 { if in_buf[pos] == '\n' as u8 {
if !at_line_start || !squeeze_blank { if !at_line_start || !squeeze_blank {
if at_line_start && number == NumberAll { if at_line_start && number == NumberingMode::NumberAll {
(write!(&mut writer, "{0:6u}\t", line_counter)).unwrap(); (write!(&mut writer, "{0:6u}\t", line_counter)).unwrap();
line_counter += 1; line_counter += 1;
} }
@ -133,7 +133,7 @@ fn write_lines(files: Vec<String>, number: NumberingMode, squeeze_blank: bool,
at_line_start = true; at_line_start = true;
continue; continue;
} }
if at_line_start && number != NumberNone { if at_line_start && number != NumberingMode::NumberNone {
(write!(&mut writer, "{0:6u}\t", line_counter)).unwrap(); (write!(&mut writer, "{0:6u}\t", line_counter)).unwrap();
line_counter += 1; line_counter += 1;
} }
@ -191,7 +191,7 @@ fn write_bytes(files: Vec<String>, number: NumberingMode, squeeze_blank: bool,
} }
if byte == '\n' as u8 { if byte == '\n' as u8 {
if !at_line_start || !squeeze_blank { if !at_line_start || !squeeze_blank {
if at_line_start && number == NumberAll { if at_line_start && number == NumberingMode::NumberAll {
(write!(&mut writer, "{0:6u}\t", line_counter)).unwrap(); (write!(&mut writer, "{0:6u}\t", line_counter)).unwrap();
line_counter += 1; line_counter += 1;
} }
@ -206,7 +206,7 @@ fn write_bytes(files: Vec<String>, number: NumberingMode, squeeze_blank: bool,
at_line_start = true; at_line_start = true;
continue; continue;
} }
if at_line_start && number != NumberNone { if at_line_start && number != NumberingMode::NumberNone {
(write!(&mut writer, "{0:6u}\t", line_counter)).unwrap(); (write!(&mut writer, "{0:6u}\t", line_counter)).unwrap();
line_counter += 1; line_counter += 1;
at_line_start = false; at_line_start = false;
@ -267,7 +267,7 @@ fn exec(files: Vec<String>, number: NumberingMode, show_nonprint: bool,
if show_nonprint || show_tabs { if show_nonprint || show_tabs {
write_bytes(files, number, squeeze_blank, show_ends, show_nonprint, show_tabs); write_bytes(files, number, squeeze_blank, show_ends, show_nonprint, show_tabs);
} else if number != NumberNone || squeeze_blank || show_ends { } else if number != NumberingMode::NumberNone || squeeze_blank || show_ends {
write_lines(files, number, squeeze_blank, show_ends); write_lines(files, number, squeeze_blank, show_ends);
} else { } else {
write_fast(files); write_fast(files);

View file

@ -52,8 +52,8 @@ enum LineReader {
impl LineReader { impl LineReader {
fn read_line(&mut self) -> IoResult<String> { fn read_line(&mut self) -> IoResult<String> {
match self { match self {
&Stdin(ref mut r) => r.read_line(), &LineReader::Stdin(ref mut r) => r.read_line(),
&FileIn(ref mut r) => r.read_line(), &LineReader::FileIn(ref mut r) => r.read_line(),
} }
} }
} }

View file

@ -47,17 +47,17 @@ pub fn uumain(args: Vec<String>) -> int {
let progname = &args[0]; let progname = &args[0];
let usage = usage("Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.", opts); let usage = usage("Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.", opts);
let mode = if matches.opt_present("version") { let mode = if matches.opt_present("version") {
Version Mode::Version
} else if matches.opt_present("help") { } else if matches.opt_present("help") {
Help Mode::Help
} else { } else {
Copy Mode::Copy
}; };
match mode { match mode {
Copy => copy(matches), Mode::Copy => copy(matches),
Help => help(progname.as_slice(), usage.as_slice()), Mode::Help => help(progname.as_slice(), usage.as_slice()),
Version => version(), Mode::Version => version(),
} }
0 0

View file

@ -99,7 +99,7 @@ impl<R: Reader> Bytes::Select for BufReader<R> {
} }
let newline_idx = match self.end - self.start { let newline_idx = match self.end - self.start {
0 => return Bytes::EndOfFile, 0 => return Bytes::Selected::EndOfFile,
buf_used if bytes < buf_used => { buf_used if bytes < buf_used => {
// because the output delimiter should only be placed between // because the output delimiter should only be placed between
// segments check if the byte after bytes is a newline // segments check if the byte after bytes is a newline
@ -114,7 +114,7 @@ impl<R: Reader> Bytes::Select for BufReader<R> {
self.start += bytes; self.start += bytes;
return Bytes::Complete(segment); return Bytes::Selected::Complete(segment);
} }
} }
} }
@ -129,7 +129,7 @@ impl<R: Reader> Bytes::Select for BufReader<R> {
self.start = 0; self.start = 0;
self.end = 0; self.end = 0;
return Bytes::Partial(segment); return Bytes::Selected::Partial(segment);
} }
} }
} }
@ -139,6 +139,6 @@ impl<R: Reader> Bytes::Select for BufReader<R> {
let segment = self.buffer.slice(self.start, new_start); let segment = self.buffer.slice(self.start, new_start);
self.start = new_start; self.start = new_start;
Bytes::NewlineFound(segment) Bytes::Selected::NewlineFound(segment)
} }
} }

View file

@ -55,7 +55,8 @@ fn list_to_ranges(list: &str, complement: bool) -> Result<Vec<Range>, String> {
fn cut_bytes<R: Reader>(reader: R, fn cut_bytes<R: Reader>(reader: R,
ranges: &Vec<Range>, ranges: &Vec<Range>,
opts: &Options) -> int { opts: &Options) -> int {
use buffer::Bytes::{Select, NewlineFound, Complete, Partial, EndOfFile}; use buffer::Bytes::Select;
use buffer::Bytes::Selected::{NewlineFound, Complete, Partial, EndOfFile};
let mut buf_read = buffer::BufReader::new(reader); let mut buf_read = buffer::BufReader::new(reader);
let mut out = BufferedWriter::new(stdio::stdout_raw()); let mut out = BufferedWriter::new(stdio::stdout_raw());
@ -404,13 +405,13 @@ fn cut_files(mut filenames: Vec<String>, mode: Mode) -> int {
if stdin_read { continue } if stdin_read { continue }
exit_code |= match mode { exit_code |= match mode {
Bytes(ref ranges, ref opts) => { Mode::Bytes(ref ranges, ref opts) => {
cut_bytes(stdio::stdin_raw(), ranges, opts) cut_bytes(stdio::stdin_raw(), ranges, opts)
} }
Characters(ref ranges, ref opts) => { Mode::Characters(ref ranges, ref opts) => {
cut_characters(stdio::stdin_raw(), ranges, opts) cut_characters(stdio::stdin_raw(), ranges, opts)
} }
Fields(ref ranges, ref opts) => { Mode::Fields(ref ranges, ref opts) => {
cut_fields(stdio::stdin_raw(), ranges, opts) cut_fields(stdio::stdin_raw(), ranges, opts)
} }
}; };
@ -433,11 +434,11 @@ fn cut_files(mut filenames: Vec<String>, mode: Mode) -> int {
}; };
exit_code |= match mode { exit_code |= match mode {
Bytes(ref ranges, ref opts) => cut_bytes(file, ranges, opts), Mode::Bytes(ref ranges, ref opts) => cut_bytes(file, ranges, opts),
Characters(ref ranges, ref opts) => { Mode::Characters(ref ranges, ref opts) => {
cut_characters(file, ranges, opts) cut_characters(file, ranges, opts)
} }
Fields(ref ranges, ref opts) => cut_fields(file, ranges, opts) Mode::Fields(ref ranges, ref opts) => cut_fields(file, ranges, opts)
}; };
} }
} }
@ -499,13 +500,13 @@ pub fn uumain(args: Vec<String>) -> int {
matches.opt_str("fields")) { matches.opt_str("fields")) {
(Some(byte_ranges), None, None) => { (Some(byte_ranges), None, None) => {
list_to_ranges(byte_ranges.as_slice(), complement).map(|ranges| list_to_ranges(byte_ranges.as_slice(), complement).map(|ranges|
Bytes(ranges, Mode::Bytes(ranges,
Options { out_delim: matches.opt_str("output-delimiter") }) Options { out_delim: matches.opt_str("output-delimiter") })
) )
} }
(None, Some(char_ranges), None) => { (None, Some(char_ranges), None) => {
list_to_ranges(char_ranges.as_slice(), complement).map(|ranges| list_to_ranges(char_ranges.as_slice(), complement).map(|ranges|
Characters(ranges, Mode::Characters(ranges,
Options { out_delim: matches.opt_str("output-delimiter") }) Options { out_delim: matches.opt_str("output-delimiter") })
) )
} }
@ -520,7 +521,7 @@ pub fn uumain(args: Vec<String>) -> int {
if delim.as_slice().char_len() != 1 { if delim.as_slice().char_len() != 1 {
Err("the delimiter must be a single character".to_string()) Err("the delimiter must be a single character".to_string())
} else { } else {
Ok(Fields(ranges, Ok(Mode::Fields(ranges,
FieldOptions { FieldOptions {
delimiter: delim, delimiter: delim,
out_delimeter: out_delim, out_delimeter: out_delim,
@ -528,7 +529,7 @@ pub fn uumain(args: Vec<String>) -> int {
})) }))
} }
} }
None => Ok(Fields(ranges, None => Ok(Mode::Fields(ranges,
FieldOptions { FieldOptions {
delimiter: "\t".to_string(), delimiter: "\t".to_string(),
out_delimeter: out_delim, out_delimeter: out_delim,

View file

@ -40,16 +40,16 @@ impl Line {
// when we know that it's a FormatLine, as in the ParagraphStream iterator // when we know that it's a FormatLine, as in the ParagraphStream iterator
fn get_formatline(self) -> FileLine { fn get_formatline(self) -> FileLine {
match self { match self {
FormatLine(fl) => fl, Line::FormatLine(fl) => fl,
NoFormatLine(..) => panic!("Found NoFormatLine when expecting FormatLine") Line::NoFormatLine(..) => panic!("Found NoFormatLine when expecting FormatLine")
} }
} }
// when we know that it's a NoFormatLine, as in the ParagraphStream iterator // when we know that it's a NoFormatLine, as in the ParagraphStream iterator
fn get_noformatline(self) -> (String, bool) { fn get_noformatline(self) -> (String, bool) {
match self { match self {
NoFormatLine(s, b) => (s, b), Line::NoFormatLine(s, b) => (s, b),
FormatLine(..) => panic!("Found FormatLine when expecting NoFormatLine") Line::FormatLine(..) => panic!("Found FormatLine when expecting NoFormatLine")
} }
} }
} }
@ -154,34 +154,34 @@ impl<'a> Iterator<Line> for FileLines<'a> {
// Err(true) indicates that this was a linebreak, // Err(true) indicates that this was a linebreak,
// which is important to know when detecting mail headers // which is important to know when detecting mail headers
if n.as_slice().is_whitespace() { if n.as_slice().is_whitespace() {
return Some(NoFormatLine("\n".to_string(), true)); return Some(Line::NoFormatLine("\n".to_string(), true));
} }
// if this line does not match the prefix, // if this line does not match the prefix,
// emit the line unprocessed and iterate again // emit the line unprocessed and iterate again
let (pmatch, poffset) = self.match_prefix(n.as_slice()); let (pmatch, poffset) = self.match_prefix(n.as_slice());
if !pmatch { if !pmatch {
return Some(NoFormatLine(n, false)); return Some(Line::NoFormatLine(n, false));
} else if n.as_slice().slice_from(poffset + self.opts.prefix.len()).is_whitespace() { } else if n.as_slice().slice_from(poffset + self.opts.prefix.len()).is_whitespace() {
// if the line matches the prefix, but is blank after, // if the line matches the prefix, but is blank after,
// don't allow lines to be combined through it (that is, // don't allow lines to be combined through it (that is,
// treat it like a blank line, except that since it's // treat it like a blank line, except that since it's
// not truly blank we will not allow mail headers on the // not truly blank we will not allow mail headers on the
// following line) // following line)
return Some(NoFormatLine(n, false)); return Some(Line::NoFormatLine(n, false));
} }
// skip if this line matches the anti_prefix // skip if this line matches the anti_prefix
// (NOTE definition of match_anti_prefix is TRUE if we should process) // (NOTE definition of match_anti_prefix is TRUE if we should process)
if !self.match_anti_prefix(n.as_slice()) { if !self.match_anti_prefix(n.as_slice()) {
return Some(NoFormatLine(n, false)); return Some(Line::NoFormatLine(n, false));
} }
// figure out the indent, prefix, and prefixindent ending points // figure out the indent, prefix, and prefixindent ending points
let prefix_end = poffset + self.opts.prefix.len(); let prefix_end = poffset + self.opts.prefix.len();
let (indent_end, prefix_len, indent_len) = self.compute_indent(n.as_slice(), prefix_end); let (indent_end, prefix_len, indent_len) = self.compute_indent(n.as_slice(), prefix_end);
Some(FormatLine(FileLine { Some(Line::FormatLine(FileLine {
line : n, line : n,
indent_end : indent_end, indent_end : indent_end,
pfxind_end : poffset, pfxind_end : poffset,
@ -259,8 +259,8 @@ impl<'a> Iterator<Result<Paragraph, String>> for ParagraphStream<'a> {
match self.lines.peek() { match self.lines.peek() {
None => return None, None => return None,
Some(l) => match l { Some(l) => match l {
&FormatLine(_) => false, &Line::FormatLine(_) => false,
&NoFormatLine(_, _) => true &Line::NoFormatLine(_, _) => true
} }
}; };
@ -292,8 +292,8 @@ impl<'a> Iterator<Result<Paragraph, String>> for ParagraphStream<'a> {
None => break, None => break,
Some(l) => { Some(l) => {
match l { match l {
&FormatLine(ref x) => x, &Line::FormatLine(ref x) => x,
&NoFormatLine(..) => break &Line::NoFormatLine(..) => break
} }
} }
}; };

View file

@ -66,17 +66,17 @@ pub fn uumain(args: Vec<String>) -> int {
}; };
let mode = if matches.opt_present("version") { let mode = if matches.opt_present("version") {
Version Mode::Version
} else if matches.opt_present("help") { } else if matches.opt_present("help") {
Help Mode::Help
} else { } else {
HostId Mode::HostId
}; };
match mode { match mode {
HostId => hostid(), Mode::HostId => hostid(),
Help => help(NAME, usage.as_slice()), Mode::Help => help(NAME, usage.as_slice()),
Version => version(), Mode::Version => version(),
} }
0 0

View file

@ -74,23 +74,23 @@ pub fn uumain(args: Vec<String>) -> int {
}; };
let mode = if matches.opt_present("version") { let mode = if matches.opt_present("version") {
Version Mode::Version
} else if matches.opt_present("help") { } else if matches.opt_present("help") {
Help Mode::Help
} else if matches.opt_present("table") { } else if matches.opt_present("table") {
Table Mode::Table
} else if matches.opt_present("list") { } else if matches.opt_present("list") {
List Mode::List
} else { } else {
Kill Mode::Kill
}; };
match mode { match mode {
Kill => return kill(matches.opt_str("signal").unwrap_or(obs_signal.unwrap_or("9".to_string())).as_slice(), matches.free), Mode::Kill => return kill(matches.opt_str("signal").unwrap_or(obs_signal.unwrap_or("9".to_string())).as_slice(), matches.free),
Table => table(), Mode::Table => table(),
List => list(matches.opt_str("list")), Mode::List => list(matches.opt_str("list")),
Help => help(NAME, usage.as_slice()), Mode::Help => help(NAME, usage.as_slice()),
Version => version(), Mode::Version => version(),
} }
0 0

View file

@ -94,23 +94,23 @@ pub fn uumain(args: Vec<String>) -> int {
* To default to no-clobber in that situation seems safer: * To default to no-clobber in that situation seems safer:
*/ */
let overwrite_mode = if matches.opt_present("no-clobber") { let overwrite_mode = if matches.opt_present("no-clobber") {
NoClobber OverwriteMode::NoClobber
} else if matches.opt_present("interactive") { } else if matches.opt_present("interactive") {
Interactive OverwriteMode::Interactive
} else { } else {
Force OverwriteMode::Force
}; };
let backup_mode = if matches.opt_present("b") { let backup_mode = if matches.opt_present("b") {
SimpleBackup BackupMode::SimpleBackup
} else if matches.opt_present("backup") { } else if matches.opt_present("backup") {
match matches.opt_str("backup") { match matches.opt_str("backup") {
None => SimpleBackup, None => BackupMode::SimpleBackup,
Some(mode) => match mode.as_slice() { Some(mode) => match mode.as_slice() {
"simple" | "never" => SimpleBackup, "simple" | "never" => BackupMode::SimpleBackup,
"numbered" | "t" => NumberedBackup, "numbered" | "t" => BackupMode::NumberedBackup,
"existing" | "nil" => ExistingBackup, "existing" | "nil" => BackupMode::ExistingBackup,
"none" | "off" => NoBackup, "none" | "off" => BackupMode::NoBackup,
x => { x => {
show_error!("invalid argument {} for backup type\n\ show_error!("invalid argument {} for backup type\n\
Try 'mv --help' for more information.", x); Try 'mv --help' for more information.", x);
@ -119,10 +119,10 @@ pub fn uumain(args: Vec<String>) -> int {
} }
} }
} else { } else {
NoBackup BackupMode::NoBackup
}; };
if overwrite_mode == NoClobber && backup_mode != NoBackup { if overwrite_mode == OverwriteMode::NoClobber && backup_mode != BackupMode::NoBackup {
show_error!("options --backup and --no-clobber are mutually exclusive\n\ show_error!("options --backup and --no-clobber are mutually exclusive\n\
Try 'mv --help' for more information."); Try 'mv --help' for more information.");
return 1; return 1;
@ -276,21 +276,21 @@ fn rename(from: &Path, to: &Path, b: &Behaviour) -> IoResult<()> {
if to.exists() { if to.exists() {
match b.overwrite { match b.overwrite {
NoClobber => return Ok(()), OverwriteMode::NoClobber => return Ok(()),
Interactive => { OverwriteMode::Interactive => {
print!("{}: overwrite {}? ", NAME, to.display()); print!("{}: overwrite {}? ", NAME, to.display());
if !read_yes() { if !read_yes() {
return Ok(()); return Ok(());
} }
}, },
Force => {} OverwriteMode::Force => {}
}; };
backup_path = match b.backup { backup_path = match b.backup {
NoBackup => None, BackupMode::NoBackup => None,
SimpleBackup => Some(simple_backup_path(to, &b.suffix)), BackupMode::SimpleBackup => Some(simple_backup_path(to, &b.suffix)),
NumberedBackup => Some(numbered_backup_path(to)), BackupMode::NumberedBackup => Some(numbered_backup_path(to)),
ExistingBackup => Some(existing_backup_path(to, &b.suffix)) BackupMode::ExistingBackup => Some(existing_backup_path(to, &b.suffix))
}; };
if let Some(ref p) = backup_path { if let Some(ref p) = backup_path {
try!(fs::rename(to, p)); try!(fs::rename(to, p));

View file

@ -4,12 +4,12 @@ extern crate regex;
// parse_style parses a style string into a NumberingStyle. // parse_style parses a style string into a NumberingStyle.
fn parse_style(chars: &[char]) -> Result<::NumberingStyle, String> { fn parse_style(chars: &[char]) -> Result<::NumberingStyle, String> {
match chars { match chars {
['a'] => { Ok(::NumberForAll) }, ['a'] => { Ok(::NumberingStyle::NumberForAll) },
['t'] => { Ok(::NumberForNonEmpty) }, ['t'] => { Ok(::NumberingStyle::NumberForNonEmpty) },
['n'] => { Ok(::NumberForNone) }, ['n'] => { Ok(::NumberingStyle::NumberForNone) },
['p', rest..] => { ['p', rest..] => {
match regex::Regex::new(String::from_chars(rest).as_slice()) { match regex::Regex::new(String::from_chars(rest).as_slice()) {
Ok(re) => Ok(::NumberForRegularExpression(re)), Ok(re) => Ok(::NumberingStyle::NumberForRegularExpression(re)),
Err(_) => Err(String::from_str("Illegal regular expression")), Err(_) => Err(String::from_str("Illegal regular expression")),
} }
} }
@ -32,9 +32,9 @@ pub fn parse_options(settings: &mut ::Settings, opts: &getopts::Matches) -> Vec<
match opts.opt_str("n") { match opts.opt_str("n") {
None => {}, None => {},
Some(val) => match val.as_slice() { Some(val) => match val.as_slice() {
"ln" => { settings.number_format = ::Left; }, "ln" => { settings.number_format = ::NumberFormat::Left; },
"rn" => { settings.number_format = ::Right; }, "rn" => { settings.number_format = ::NumberFormat::Right; },
"rz" => { settings.number_format = ::RightZero; }, "rz" => { settings.number_format = ::NumberFormat::RightZero; },
_ => { errs.push(String::from_str("Illegal value for -n")); }, _ => { errs.push(String::from_str("Illegal value for -n")); },
} }
} }

View file

@ -93,15 +93,15 @@ pub fn uumain(args: Vec<String>) -> int {
// A mutable settings object, initialized with the defaults. // A mutable settings object, initialized with the defaults.
let mut settings = Settings { let mut settings = Settings {
header_numbering: NumberForNone, header_numbering: NumberingStyle::NumberForNone,
body_numbering: NumberForAll, body_numbering: NumberingStyle::NumberForAll,
footer_numbering: NumberForNone, footer_numbering: NumberingStyle::NumberForNone,
section_delimiter: ['\\', ':'], section_delimiter: ['\\', ':'],
starting_line_number: 1, starting_line_number: 1,
line_increment: 1, line_increment: 1,
join_blank_lines: 1, join_blank_lines: 1,
number_width: 6, number_width: 6,
number_format: Right, number_format: NumberFormat::Right,
renumber: true, renumber: true,
number_separator: String::from_str("\t"), number_separator: String::from_str("\t"),
}; };
@ -167,12 +167,12 @@ fn nl<T: Reader> (reader: &mut BufferedReader<T>, settings: &Settings) {
let mut line_no_threshold = std::num::pow(10u64, line_no_width); let mut line_no_threshold = std::num::pow(10u64, line_no_width);
let mut empty_line_count: u64 = 0; let mut empty_line_count: u64 = 0;
let fill_char = match settings.number_format { let fill_char = match settings.number_format {
RightZero => '0', NumberFormat::RightZero => '0',
_ => ' ' _ => ' '
}; };
// Initially, we use the body's line counting settings // Initially, we use the body's line counting settings
let mut regex_filter = match settings.body_numbering { let mut regex_filter = match settings.body_numbering {
NumberForRegularExpression(ref re) => re, NumberingStyle::NumberForRegularExpression(ref re) => re,
_ => REGEX_DUMMY, _ => REGEX_DUMMY,
}; };
let mut line_filter = pass_regex; let mut line_filter = pass_regex;
@ -239,16 +239,16 @@ fn nl<T: Reader> (reader: &mut BufferedReader<T>, settings: &Settings) {
&settings.body_numbering &settings.body_numbering
} }
} { } {
NumberForAll => { NumberingStyle::NumberForAll => {
line_filter = pass_all; line_filter = pass_all;
}, },
NumberForNonEmpty => { NumberingStyle::NumberForNonEmpty => {
line_filter = pass_nonempty; line_filter = pass_nonempty;
}, },
NumberForNone => { NumberingStyle::NumberForNone => {
line_filter = pass_none; line_filter = pass_none;
} }
NumberForRegularExpression(ref re) => { NumberingStyle::NumberForRegularExpression(ref re) => {
line_filter = pass_regex; line_filter = pass_regex;
regex_filter = re; regex_filter = re;
} }
@ -285,7 +285,7 @@ fn nl<T: Reader> (reader: &mut BufferedReader<T>, settings: &Settings) {
} }
let fill = String::from_char(w, fill_char); let fill = String::from_char(w, fill_char);
match settings.number_format { match settings.number_format {
Left => { NumberFormat::Left => {
println!("{1}{0}{2}{3}", fill, line_no, settings.number_separator, line) println!("{1}{0}{2}{3}", fill, line_no, settings.number_separator, line)
}, },
_ => { _ => {

View file

@ -83,27 +83,27 @@ pub fn uumain(args: Vec<String>) -> int {
let force = matches.opt_present("force"); let force = matches.opt_present("force");
let interactive = let interactive =
if matches.opt_present("i") { if matches.opt_present("i") {
InteractiveAlways InteractiveMode::InteractiveAlways
} else if matches.opt_present("I") { } else if matches.opt_present("I") {
InteractiveOnce InteractiveMode::InteractiveOnce
} else if matches.opt_present("interactive") { } else if matches.opt_present("interactive") {
match matches.opt_str("interactive").unwrap().as_slice() { match matches.opt_str("interactive").unwrap().as_slice() {
"none" => InteractiveNone, "none" => InteractiveMode::InteractiveNone,
"once" => InteractiveOnce, "once" => InteractiveMode::InteractiveOnce,
"always" => InteractiveAlways, "always" => InteractiveMode::InteractiveAlways,
val => { val => {
crash!(1, "Invalid argument to interactive ({})", val) crash!(1, "Invalid argument to interactive ({})", val)
} }
} }
} else { } else {
InteractiveNone InteractiveMode::InteractiveNone
}; };
let one_fs = matches.opt_present("one-file-system"); let one_fs = matches.opt_present("one-file-system");
let preserve_root = !matches.opt_present("no-preserve-root"); let preserve_root = !matches.opt_present("no-preserve-root");
let recursive = matches.opt_present("recursive"); let recursive = matches.opt_present("recursive");
let dir = matches.opt_present("dir"); let dir = matches.opt_present("dir");
let verbose = matches.opt_present("verbose"); let verbose = matches.opt_present("verbose");
if interactive == InteractiveOnce && (recursive || matches.free.len() > 3) { if interactive == InteractiveMode::InteractiveOnce && (recursive || matches.free.len() > 3) {
let msg = let msg =
if recursive { if recursive {
"Remove all arguments recursively? " "Remove all arguments recursively? "
@ -169,7 +169,7 @@ fn remove(files: Vec<String>, force: bool, interactive: InteractiveMode, one_fs:
fn remove_dir(path: &Path, name: &str, interactive: InteractiveMode, verbose: bool) -> Result<(), int> { fn remove_dir(path: &Path, name: &str, interactive: InteractiveMode, verbose: bool) -> Result<(), int> {
let response = let response =
if interactive == InteractiveAlways { if interactive == InteractiveMode::InteractiveAlways {
prompt_file(path, name) prompt_file(path, name)
} else { } else {
true true
@ -189,7 +189,7 @@ fn remove_dir(path: &Path, name: &str, interactive: InteractiveMode, verbose: bo
fn remove_file(path: &Path, name: &str, interactive: InteractiveMode, verbose: bool) -> Result<(), int> { fn remove_file(path: &Path, name: &str, interactive: InteractiveMode, verbose: bool) -> Result<(), int> {
let response = let response =
if interactive == InteractiveAlways { if interactive == InteractiveMode::InteractiveAlways {
prompt_file(path, name) prompt_file(path, name)
} else { } else {
true true

View file

@ -76,7 +76,7 @@ With no FILE, or when FILE is -, read standard input.",
return 1; return 1;
} }
match parse_range(range) { match parse_range(range) {
Ok(m) => InputRange(m), Ok(m) => Mode::InputRange(m),
Err((msg, code)) => { Err((msg, code)) => {
show_error!("{}", msg); show_error!("{}", msg);
return code; return code;
@ -85,12 +85,12 @@ With no FILE, or when FILE is -, read standard input.",
} }
None => { None => {
if echo { if echo {
Echo Mode::Echo
} else { } else {
if matches.free.len() == 0 { if matches.free.len() == 0 {
matches.free.push("-".to_string()); matches.free.push("-".to_string());
} }
Default Mode::Default
} }
} }
}; };
@ -122,9 +122,9 @@ With no FILE, or when FILE is -, read standard input.",
fn shuf(input: Vec<String>, mode: Mode, repeat: bool, zero: bool, count: uint, output: Option<String>, random: Option<String>) -> IoResult<()> { fn shuf(input: Vec<String>, mode: Mode, repeat: bool, zero: bool, count: uint, output: Option<String>, random: Option<String>) -> IoResult<()> {
match mode { match mode {
Echo => shuf_lines(input, repeat, zero, count, output, random), Mode::Echo => shuf_lines(input, repeat, zero, count, output, random),
InputRange(range) => shuf_lines(range.map(|num| num.to_string()).collect(), repeat, zero, count, output, random), Mode::InputRange(range) => shuf_lines(range.map(|num| num.to_string()).collect(), repeat, zero, count, output, random),
Default => { Mode::Default => {
let lines: Vec<String> = input.into_iter().flat_map(|filename| { let lines: Vec<String> = input.into_iter().flat_map(|filename| {
let slice = filename.as_slice(); let slice = filename.as_slice();
let mut file_buf; let mut file_buf;
@ -159,8 +159,8 @@ enum WrappedRng {
impl WrappedRng { impl WrappedRng {
fn next_u32(&mut self) -> u32 { fn next_u32(&mut self) -> u32 {
match self { match self {
&RngFile(ref mut r) => r.next_u32(), &WrappedRng::RngFile(ref mut r) => r.next_u32(),
&RngDefault(ref mut r) => r.next_u32(), &WrappedRng::RngDefault(ref mut r) => r.next_u32(),
} }
} }
} }
@ -171,8 +171,8 @@ fn shuf_lines(mut lines: Vec<String>, repeat: bool, zero: bool, count: uint, out
None => box io::stdout() as Box<Writer> None => box io::stdout() as Box<Writer>
}; };
let mut rng = match random { let mut rng = match random {
Some(name) => RngFile(rand::reader::ReaderRng::new(try!(io::File::open(&Path::new(name))))), Some(name) => WrappedRng::RngFile(rand::reader::ReaderRng::new(try!(io::File::open(&Path::new(name))))),
None => RngDefault(rand::task_rng()), None => WrappedRng::RngDefault(rand::task_rng()),
}; };
let mut len = lines.len(); let mut len = lines.len();
let max = if repeat { count } else { cmp::min(count, len) }; let max = if repeat { count } else { cmp::min(count, len) };

View file

@ -53,23 +53,23 @@ fn one(args: &[&[u8]]) -> bool {
fn two(args: &[&[u8]], error: &mut bool) -> bool { fn two(args: &[&[u8]], error: &mut bool) -> bool {
match args[0] { match args[0] {
b"!" => !one(args.slice_from(1)), b"!" => !one(args.slice_from(1)),
b"-b" => path(args[1], BlockSpecial), b"-b" => path(args[1], PathCondition::BlockSpecial),
b"-c" => path(args[1], CharacterSpecial), b"-c" => path(args[1], PathCondition::CharacterSpecial),
b"-d" => path(args[1], Directory), b"-d" => path(args[1], PathCondition::Directory),
b"-e" => path(args[1], Exists), b"-e" => path(args[1], PathCondition::Exists),
b"-f" => path(args[1], Regular), b"-f" => path(args[1], PathCondition::Regular),
b"-g" => path(args[1], GroupIDFlag), b"-g" => path(args[1], PathCondition::GroupIDFlag),
b"-h" => path(args[1], SymLink), b"-h" => path(args[1], PathCondition::SymLink),
b"-L" => path(args[1], SymLink), b"-L" => path(args[1], PathCondition::SymLink),
b"-n" => one(args.slice_from(1)), b"-n" => one(args.slice_from(1)),
b"-p" => path(args[1], FIFO), b"-p" => path(args[1], PathCondition::FIFO),
b"-r" => path(args[1], Readable), b"-r" => path(args[1], PathCondition::Readable),
b"-S" => path(args[1], Socket), b"-S" => path(args[1], PathCondition::Socket),
b"-s" => path(args[1], NonEmpty), b"-s" => path(args[1], PathCondition::NonEmpty),
b"-t" => isatty(args[1]), b"-t" => isatty(args[1]),
b"-u" => path(args[1], UserIDFlag), b"-u" => path(args[1], PathCondition::UserIDFlag),
b"-w" => path(args[1], Writable), b"-w" => path(args[1], PathCondition::Writable),
b"-x" => path(args[1], Executable), b"-x" => path(args[1], PathCondition::Executable),
b"-z" => !one(args.slice_from(1)), b"-z" => !one(args.slice_from(1)),
_ => { _ => {
*error = true; *error = true;
@ -82,12 +82,12 @@ fn three(args: &[&[u8]], error: &mut bool) -> bool {
match args[1] { match args[1] {
b"=" => args[0] == args[2], b"=" => args[0] == args[2],
b"!=" => args[0] != args[2], b"!=" => args[0] != args[2],
b"-eq" => integers(args[0], args[2], Equal), b"-eq" => integers(args[0], args[2], IntegerCondition::Equal),
b"-ne" => integers(args[0], args[2], Unequal), b"-ne" => integers(args[0], args[2], IntegerCondition::Unequal),
b"-gt" => integers(args[0], args[2], Greater), b"-gt" => integers(args[0], args[2], IntegerCondition::Greater),
b"-ge" => integers(args[0], args[2], GreaterEqual), b"-ge" => integers(args[0], args[2], IntegerCondition::GreaterEqual),
b"-lt" => integers(args[0], args[2], Less), b"-lt" => integers(args[0], args[2], IntegerCondition::Less),
b"-le" => integers(args[0], args[2], LessEqual), b"-le" => integers(args[0], args[2], IntegerCondition::LessEqual),
_ => match args[0] { _ => match args[0] {
b"!" => !two(args.slice_from(1), error), b"!" => !two(args.slice_from(1), error),
_ => { _ => {
@ -129,12 +129,12 @@ fn integers(a: &[u8], b: &[u8], cond: IntegerCondition) -> bool {
_ => return false, _ => return false,
}; };
match cond { match cond {
Equal => a == b, IntegerCondition::Equal => a == b,
Unequal => a != b, IntegerCondition::Unequal => a != b,
Greater => a > b, IntegerCondition::Greater => a > b,
GreaterEqual => a >= b, IntegerCondition::GreaterEqual => a >= b,
Less => a < b, IntegerCondition::Less => a < b,
LessEqual => a <= b, IntegerCondition::LessEqual => a <= b,
} }
} }
@ -207,7 +207,7 @@ fn parse_expr(mut args: &[&[u8]], error: &mut bool) -> bool {
let lhs = dispatch(&mut args, error); let lhs = dispatch(&mut args, error);
if args.len() > 0 { if args.len() > 0 {
parse_expr_helper(&hashmap, &mut args, lhs, Unknown, error) parse_expr_helper(&hashmap, &mut args, lhs, Precedence::Unknown, error)
} else { } else {
lhs lhs
} }
@ -238,14 +238,14 @@ fn parse_expr_helper<'a>(hashmap: &HashMap<&'a [u8], Precedence>,
rhs = parse_expr_helper(hashmap, args, rhs, subprec, error); rhs = parse_expr_helper(hashmap, args, rhs, subprec, error);
} }
lhs = match prec { lhs = match prec {
UnOp | BUnOp => { Precedence::UnOp | Precedence::BUnOp => {
*error = true; *error = true;
false false
} }
And => lhs && rhs, Precedence::And => lhs && rhs,
Or => lhs || rhs, Precedence::Or => lhs || rhs,
BinOp => three(&[if lhs { b" " } else { b"" }, op, if rhs { b" " } else { b"" }], error), Precedence::BinOp => three(&[if lhs { b" " } else { b"" }, op, if rhs { b" " } else { b"" }], error),
Paren => unimplemented!(), // TODO: implement parentheses Precedence::Paren => unimplemented!(), // TODO: implement parentheses
_ => unreachable!() _ => unreachable!()
}; };
if args.len() > 0 { if args.len() > 0 {
@ -262,41 +262,41 @@ fn parse_expr_helper<'a>(hashmap: &HashMap<&'a [u8], Precedence>,
fn setup_hashmap<'a>() -> HashMap<&'a [u8], Precedence> { fn setup_hashmap<'a>() -> HashMap<&'a [u8], Precedence> {
let mut hashmap = HashMap::<&'a [u8], Precedence>::new(); let mut hashmap = HashMap::<&'a [u8], Precedence>::new();
hashmap.insert(b"-b", UnOp); hashmap.insert(b"-b", Precedence::UnOp);
hashmap.insert(b"-c", UnOp); hashmap.insert(b"-c", Precedence::UnOp);
hashmap.insert(b"-d", UnOp); hashmap.insert(b"-d", Precedence::UnOp);
hashmap.insert(b"-e", UnOp); hashmap.insert(b"-e", Precedence::UnOp);
hashmap.insert(b"-f", UnOp); hashmap.insert(b"-f", Precedence::UnOp);
hashmap.insert(b"-g", UnOp); hashmap.insert(b"-g", Precedence::UnOp);
hashmap.insert(b"-h", UnOp); hashmap.insert(b"-h", Precedence::UnOp);
hashmap.insert(b"-L", UnOp); hashmap.insert(b"-L", Precedence::UnOp);
hashmap.insert(b"-n", UnOp); hashmap.insert(b"-n", Precedence::UnOp);
hashmap.insert(b"-p", UnOp); hashmap.insert(b"-p", Precedence::UnOp);
hashmap.insert(b"-r", UnOp); hashmap.insert(b"-r", Precedence::UnOp);
hashmap.insert(b"-S", UnOp); hashmap.insert(b"-S", Precedence::UnOp);
hashmap.insert(b"-s", UnOp); hashmap.insert(b"-s", Precedence::UnOp);
hashmap.insert(b"-t", UnOp); hashmap.insert(b"-t", Precedence::UnOp);
hashmap.insert(b"-u", UnOp); hashmap.insert(b"-u", Precedence::UnOp);
hashmap.insert(b"-w", UnOp); hashmap.insert(b"-w", Precedence::UnOp);
hashmap.insert(b"-x", UnOp); hashmap.insert(b"-x", Precedence::UnOp);
hashmap.insert(b"-z", UnOp); hashmap.insert(b"-z", Precedence::UnOp);
hashmap.insert(b"=", BinOp); hashmap.insert(b"=", Precedence::BinOp);
hashmap.insert(b"!=", BinOp); hashmap.insert(b"!=", Precedence::BinOp);
hashmap.insert(b"-eq", BinOp); hashmap.insert(b"-eq", Precedence::BinOp);
hashmap.insert(b"-ne", BinOp); hashmap.insert(b"-ne", Precedence::BinOp);
hashmap.insert(b"-gt", BinOp); hashmap.insert(b"-gt", Precedence::BinOp);
hashmap.insert(b"-ge", BinOp); hashmap.insert(b"-ge", Precedence::BinOp);
hashmap.insert(b"-lt", BinOp); hashmap.insert(b"-lt", Precedence::BinOp);
hashmap.insert(b"-le", BinOp); hashmap.insert(b"-le", Precedence::BinOp);
hashmap.insert(b"!", BUnOp); hashmap.insert(b"!", Precedence::BUnOp);
hashmap.insert(b"-a", And); hashmap.insert(b"-a", Precedence::And);
hashmap.insert(b"-o", Or); hashmap.insert(b"-o", Precedence::Or);
hashmap.insert(b"(", Paren); hashmap.insert(b"(", Precedence::Paren);
hashmap.insert(b")", Paren); hashmap.insert(b")", Precedence::Paren);
hashmap hashmap
} }
@ -346,7 +346,7 @@ fn path(path: &[u8], cond: PathCondition) -> bool {
let path = unsafe { path.to_c_str_unchecked() }; let path = unsafe { path.to_c_str_unchecked() };
let mut stat = unsafe { std::mem::zeroed() }; let mut stat = unsafe { std::mem::zeroed() };
if cond == SymLink { if cond == PathCondition::SymLink {
if unsafe { lstat(path.as_ptr(), &mut stat) } == 0 { if unsafe { lstat(path.as_ptr(), &mut stat) } == 0 {
if stat.st_mode & S_IFMT == S_IFLNK { if stat.st_mode & S_IFMT == S_IFLNK {
return true; return true;
@ -359,20 +359,20 @@ fn path(path: &[u8], cond: PathCondition) -> bool {
} }
let file_type = stat.st_mode & S_IFMT; let file_type = stat.st_mode & S_IFMT;
match cond { match cond {
BlockSpecial => file_type == S_IFBLK, PathCondition::BlockSpecial => file_type == S_IFBLK,
CharacterSpecial => file_type == S_IFCHR, PathCondition::CharacterSpecial => file_type == S_IFCHR,
Directory => file_type == S_IFDIR, PathCondition::Directory => file_type == S_IFDIR,
Exists => true, PathCondition::Exists => true,
Regular => file_type == S_IFREG, PathCondition::Regular => file_type == S_IFREG,
GroupIDFlag => stat.st_mode & S_ISGID != 0, PathCondition::GroupIDFlag => stat.st_mode & S_ISGID != 0,
SymLink => true, PathCondition::SymLink => true,
FIFO => file_type == S_IFIFO, PathCondition::FIFO => file_type == S_IFIFO,
Readable => perm(stat, Read), PathCondition::Readable => perm(stat, Permission::Read),
Socket => file_type == S_IFSOCK, PathCondition::Socket => file_type == S_IFSOCK,
NonEmpty => stat.st_size > 0, PathCondition::NonEmpty => stat.st_size > 0,
UserIDFlag => stat.st_mode & S_ISUID != 0, PathCondition::UserIDFlag => stat.st_mode & S_ISUID != 0,
Writable => perm(stat, Write), PathCondition::Writable => perm(stat, Permission::Write),
Executable => perm(stat, Execute), PathCondition::Executable => perm(stat, Permission::Execute),
} }
} }

View file

@ -109,7 +109,7 @@ fn truncate(no_create: bool, _: bool, reference: Option<String>, size: Option<St
} }
}; };
match fs::stat(rfile.path()) { match fs::stat(rfile.path()) {
Ok(stat) => (stat.size, Reference), Ok(stat) => (stat.size, TruncateMode::Reference),
Err(f) => { Err(f) => {
show_error!("{}", f.to_string()); show_error!("{}", f.to_string());
return Err(1); return Err(1);
@ -132,13 +132,13 @@ fn truncate(no_create: bool, _: bool, reference: Option<String>, size: Option<St
} }
}; };
let tsize = match mode { let tsize = match mode {
Reference => refsize, TruncateMode::Reference => refsize,
Extend => fsize + refsize, TruncateMode::Extend => fsize + refsize,
Reduce => fsize - refsize, TruncateMode::Reduce => fsize - refsize,
AtMost => if fsize > refsize { refsize } else { fsize }, TruncateMode::AtMost => if fsize > refsize { refsize } else { fsize },
AtLeast => if fsize < refsize { refsize } else { fsize }, TruncateMode::AtLeast => if fsize < refsize { refsize } else { fsize },
RoundDown => fsize - fsize % refsize, TruncateMode::RoundDown => fsize - fsize % refsize,
RoundUp => fsize + fsize % refsize TruncateMode::RoundUp => fsize + fsize % refsize
}; };
match file.truncate(tsize as i64) { match file.truncate(tsize as i64) {
Ok(_) => {} Ok(_) => {}
@ -160,17 +160,17 @@ fn truncate(no_create: bool, _: bool, reference: Option<String>, size: Option<St
fn parse_size(size: &str) -> (u64, TruncateMode) { fn parse_size(size: &str) -> (u64, TruncateMode) {
let mode = match size.char_at(0) { let mode = match size.char_at(0) {
'+' => Extend, '+' => TruncateMode::Extend,
'-' => Reduce, '-' => TruncateMode::Reduce,
'<' => AtMost, '<' => TruncateMode::AtMost,
'>' => AtLeast, '>' => TruncateMode::AtLeast,
'/' => RoundDown, '/' => TruncateMode::RoundDown,
'*' => RoundUp, '*' => TruncateMode::RoundUp,
_ => Reference /* assume that the size is just a number */ _ => TruncateMode::Reference /* assume that the size is just a number */
}; };
let bytes = { let bytes = {
let mut slice = let mut slice =
if mode == Reference { if mode == TruncateMode::Reference {
let size: &str = size; let size: &str = size;
size size
} else { } else {