core-utils 0.1.2

A reimplementation of the GNU core utils in the Rust programming language
// Copyright (C) 2015, Alberto Corona <ac@albertocorona.com>
// All rights reserved. This file is part of core-utils, distributed under the
// GPL v3 license. For full terms please see the LICENSE file.

#![crate_type = "bin"]
#![crate_name = "nproc"]

static UTIL: Prog = Prog { name: "nproc", vers: "0.1.0", yr: "2015" };

extern crate pgetopts;
extern crate num_cpus;
extern crate rpf;

use pgetopts::{Options};
use rpf::{Status,Styled,Prog};

use std::env;

fn print_usage(opts: Options) {
    print!("{}: {} {}", UTIL.name.bold(), "Usage".bold(), "[OPTION]".underline());
    println!("{}", opts.options());
}

fn main() {
    let args: Vec<String> = env::args().collect();
    let mut opts = Options::new();

    opts.optflag("h", "help", "Print help information");
    opts.optflag("", "version", "Print version information");
    opts.optopt("i", "ignore", "Number of processing units to ignore", "NUM");

    let matches = match opts.parse(&args[1..]) {
        Ok(m) => { m },
        Err(e) => {
            Status::OptError.err(UTIL.name, e.to_string());
            panic!(e.to_string())
        }
    };

    let num: u32 = num_cpus::get() as u32;
    if matches.opt_present("h") {
        print_usage(opts);
    } else if matches.opt_present("version") {
        UTIL.copyright("Copyright (C) 2015 core-utils developers\n\
                       License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\n\
                       This is free software: you are free to change and redistribute it.\n\
                       There is NO WARRANTY, to the extent permitted by law.\n\n",
                       vec!["Alberto Corona"]);
    } else if matches.opt_present("i") {
        let ignore = match matches.opts_str(&[String::from("i")]) {
            Some(s) => { s.parse::<u32>().unwrap_or(0) },
            None => { panic!() },
        };
        if ignore > num {
            println!("0");
        } else {
            println!("{}", num - ignore);
        }
    } else {
        println!("{}", num);
    }
}