coreutils/dirname/dirname.rs

73 lines
2.1 KiB
Rust
Raw Normal View History

2014-03-31 16:40:21 +00:00
#![crate_id(name="dirname", vers="1.0.0", author="Derek Chiang")]
2013-12-03 09:29:32 +00:00
/*
* This file is part of the uutils coreutils package.
*
* (c) Derek Chiang <derekchiang93@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
2013-12-03 09:29:32 +00:00
use std::os;
2014-02-04 07:33:53 +00:00
use std::io::print;
2013-12-03 09:29:32 +00:00
static VERSION: &'static str = "1.0.0";
#[allow(dead_code)]
fn main() { os::set_exit_status(uumain(os::args())); }
2014-05-28 11:43:37 +00:00
pub fn uumain(args: Vec<String>) -> int {
2014-05-16 08:32:58 +00:00
let program = args.get(0).clone();
2014-05-30 08:35:54 +00:00
let opts = [
getopts::optflag("z", "zero", "separate output with NUL rather than newline"),
getopts::optflag("", "help", "display this help and exit"),
getopts::optflag("", "version", "output version information and exit"),
2013-12-03 09:29:32 +00:00
];
let matches = match getopts::getopts(args.tail(), opts) {
2013-12-03 09:29:32 +00:00
Ok(m) => m,
2014-06-15 10:50:40 +00:00
Err(f) => fail!("Invalid options\n{}", f)
2013-12-03 09:29:32 +00:00
};
if matches.opt_present("help") {
println!("dirname {:s} - strip last component from file name", VERSION);
println!("");
println!("Usage:");
2013-12-03 09:29:32 +00:00
println!(" {0:s} [OPTION] NAME...", program);
println!("");
print(getopts::usage("Output each NAME with its last non-slash component and trailing slashes
2013-12-03 23:39:23 +00:00
removed; if NAME contains no /'s, output '.' (meaning the current
2014-05-17 10:32:14 +00:00
directory).", opts).as_slice());
return 0;
2013-12-03 09:29:32 +00:00
}
if matches.opt_present("version") {
println!("dirname version: {:s}", VERSION);
return 0;
2013-12-03 09:29:32 +00:00
}
let separator = match matches.opt_present("zero") {
true => "\0",
false => "\n"
};
if !matches.free.is_empty() {
for path in matches.free.iter() {
let p = std::path::Path::new(path.clone());
let d = std::str::from_utf8(p.dirname());
if d.is_some() {
print(d.unwrap());
}
2013-12-03 09:29:32 +00:00
print(separator);
}
} else {
println!("{0:s}: missing operand", program);
println!("Try '{0:s} --help' for more information.", program);
}
0
2013-12-03 09:29:32 +00:00
}