Skip to content

Instantly share code, notes, and snippets.

@olleolleolle
Created December 3, 2013 21:35
Show Gist options
  • Select an option

  • Save olleolleolle/7777871 to your computer and use it in GitHub Desktop.

Select an option

Save olleolleolle/7777871 to your computer and use it in GitHub Desktop.
My very best and first Rust program. This was written for 0.8.
extern mod extra;
use extra::getopts;
use extra::fileinput;
use std::os;
use std::io;
fn main() {
let args = os::args();
let program = args[0].clone();
let opts = ~[
getopts::groups::optflag("h", "help", "Kind help text"),
getopts::groups::optflag("s", "squeeze", "TODO: haha - Squeeze multiple adjacent empty lines, causing the output to be single spaced"),
getopts::groups::optflag("b", "line-numbers", "Number the non-blank output lines, starting at 1")
];
let matches = match getopts::groups::getopts(args.tail(), opts) {
Ok(m) => { m }
Err(f) => { fail!(f.to_err_msg()) }
};
if matches.opt_present("help") {
print_usage(program, opts);
return;
}
let filename: &str = if !matches.free.is_empty() {
matches.free[0].clone()
} else {
print_usage(program, opts);
return;
};
do_work(filename, matches);
}
fn print_usage(program: &str, opts: &[getopts::groups::OptGroup]) {
println(getopts::groups::usage(program, opts));
}
fn do_work(filename: &str, matches: getopts::Matches) {
let mut i = 0;
fileinput::FileInput::from_vec(fileinput::make_path_option_vec(&[filename.into_owned()], true)).each_line( |line| {
if !line.is_empty() {
i += 1;
if matches.opt_present("line-numbers") {
io::print(fmt!("\t%d\t", i));
}
}
io::println(line);
true
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment