<commit_before>extern crate rustc_serialize;
extern crate docopt;
#[macro_use]
extern crate aws_abacus;
#[macro_use]
extern crate log;
extern crate walkdir;
extern crate chrono;
use docopt::Docopt;
use std::path;
use aws_abacus::elb_log_files;
use chrono::{DateTime, UTC};

fn main() {
    let args: Args = Docopt::new(USAGE)
                            .and_then(|d| d.decode())
                            .unwrap_or_else(|e| e.exit());

    let log_location = &path::Path::new(&args.arg_log_location);
    debug!("Running summary on {}.", log_location.to_str().unwrap());

    let start: Option<DateTime<UTC>> = if args.flag_benchmark {
        Some(UTC::now())
    } else {
        None
    };

    let mut number_of_files = 0;
    let mut number_of_records = 0;
    let mut filenames = Vec::new();
    match elb_log_files::file_list(log_location, &mut filenames) {
        Ok(num_files) => {
            number_of_files = num_files;
            debug!("Found {} files.", number_of_files);
            number_of_records = elb_log_files::process_files(&filenames);
            debug!("Processed {} records in {} files.", number_of_records, num_files);
        },
        Err(e) => {
            println!("ERROR: {}", e);
        },
    };

    match start {
        Some(s) => {
            let end = UTC::now();
            let time = end - s;
            println!("Processed {} files having {} records in {} milliseconds.",
                number_of_files,
                number_of_records,
                time.num_milliseconds()
            );
        },
        None => {},
    };
}

const USAGE: &'static str = "
aws-abacus

Usage:
  aws-abacus <log-location>
  aws-abacus (-d | --debug | -b | --benchmark) <log-location>
  aws-abacus (-h | --help)

Options:
  -h --help     Show this screen.
  -d --debug    Turn on debug output
";

#[derive(Debug, RustcDecodable)]
struct Args {
    arg_log_location: String,
    flag_debug: bool,
    flag_benchmark: bool,
}
<commit_msg>Started work on an aggregating function.  Added a note about the desired result.<commit_after>extern crate rustc_serialize;
extern crate docopt;
#[macro_use]
extern crate aws_abacus;
#[macro_use]
extern crate log;
extern crate walkdir;
extern crate chrono;
use docopt::Docopt;
use std::path;
use aws_abacus::elb_log_files;
use chrono::{DateTime, UTC};
use aws_abacus::elb_log_files::ELBRecord;

fn main() {
    let args: Args = Docopt::new(USAGE)
                            .and_then(|d| d.decode())
                            .unwrap_or_else(|e| e.exit());

    let log_location = &path::Path::new(&args.arg_log_location);
    debug!("Running summary on {}.", log_location.to_str().unwrap());

    let start: Option<DateTime<UTC>> = if args.flag_benchmark {
        Some(UTC::now())
    } else {
        None
    };

    let mut number_of_files = 0;
    let mut number_of_records = 0;
    let mut filenames = Vec::new();
    match elb_log_files::file_list(log_location, &mut filenames) {
        Ok(num_files) => {
            number_of_files = num_files;
            debug!("Found {} files.", number_of_files);
            number_of_records = elb_log_files::process_files(&filenames);
            debug!("Processed {} records in {} files.", number_of_records, num_files);
        },
        Err(e) => {
            println!("ERROR: {}", e);
        },
    };

    match start {
        Some(s) => {
            let end = UTC::now();
            let time = end - s;
            println!("Processed {} files having {} records in {} milliseconds.",
                number_of_files,
                number_of_records,
                time.num_milliseconds()
            );
        },
        None => {},
    };
}

const USAGE: &'static str = "
aws-abacus

Usage:
  aws-abacus <log-location>
  aws-abacus (-d | --debug | -b | --benchmark) <log-location>
  aws-abacus (-h | --help)

Options:
  -h --help     Show this screen.
  -d --debug    Turn on debug output
";

#[derive(Debug, RustcDecodable)]
struct Args {
    arg_log_location: String,
    flag_debug: bool,
    flag_benchmark: bool,
}

//Need to produce system_name,yyyy-mm-dd,req_addr,count
fn aggregate_elb_record(record: ELBRecord, aggregated_records: Vec<ELBRecord>) {

}

#[cfg(test)]
mod tests {

    #[test]
	fn false_does_not_equal_true() {
		assert_eq!(true, false)
	}
}
<|endoftext|>


<commit_before>#[macro_use]
extern crate glium;
extern crate rand;
extern crate num;

mod world;
use world::terrain::Terrain;

mod draw;
use draw::shaders::ShaderManager;
use draw::matrix_stack::MatrixStack;
use draw::transform_pipeline::TransformPipeline;
use draw::frustum::Frustum;

mod math3d;

fn main() {
	use glium::{DisplayBuild, Surface};
	// can not do multisampling due to glutin bug with_multisampling(16)
	let display = glium::glutin::WindowBuilder::new().with_vsync().with_depth_buffer(24).build_glium().unwrap();

	// draw parametres
	let params = glium::DrawParameters {
		depth: glium::Depth {
			test:glium::DepthTest::IfLess,
			write:true,
			.. Default::default()
		},
		.. Default::default()
	};

	// set up the matrix stacks
	let mut model_view_matrix = MatrixStack::new();
	let mut projection_matrix = MatrixStack::new();

	// set up the transformation pipeline
	let mut transform_pipeline = TransformPipeline::new(&model_view_matrix,&projection_matrix);

	// view frustum
	let mut frustum = Frustum::<f32>::new();
	let display_size = display.get_window().unwrap().get_inner_size_pixels().unwrap();
	frustum.set_perspective(35f32,display_size.0 as f32/display_size.1 as f32,1f32,5000f32);

	// setup the shaders
	let mut shader_manager = ShaderManager::new(&display);

	// create terrain
	let mut terrain = Terrain::new(&display,&mut shader_manager,5);

    // listen for events produced in the window and wait to be received
    loop {
    	// get reference to the frame
    	let mut target = display.draw();

    	// clear the background
    	target.clear_color_and_depth((0.0, 0.0, 0.0, 1.0),1.0);

    	// draw the terrain
    	terrain.draw(&mut target,&params);
    	//target.draw(terrain.get_vertex_buffer(),terrain.get_index_buffer(),terrain.get_shader(),&glium::uniforms::EmptyUniforms,&params).unwrap();

    	//target.draw(&vertex_buffer,&indices,&program,&glium::uniforms::EmptyUniforms,&params).unwrap();

    	// finish drawing and destroy frame object
    	target.finish().unwrap();

	    for ev in display.poll_events(){
	    	match ev {
	    		glium::glutin::Event::Closed => return,
	    		_ => ()
	    	}
	    }
    }
}<commit_msg>Add resize handler<commit_after>#[macro_use]
extern crate glium;
extern crate rand;
extern crate num;

mod world;
use world::terrain::Terrain;

mod draw;
use draw::shaders::ShaderManager;
use draw::matrix_stack::MatrixStack;
use draw::transform_pipeline::TransformPipeline;
use draw::frustum::Frustum;

mod math3d;

fn main() {
	use glium::{DisplayBuild, Surface};
	// can not do multisampling due to glutin bug with_multisampling(16)
	let display = glium::glutin::WindowBuilder::new().with_vsync().with_depth_buffer(24).build_glium().unwrap();

	// draw parametres
	let params = glium::DrawParameters {
		depth: glium::Depth {
			test:glium::DepthTest::IfLess,
			write:true,
			.. Default::default()
		},
		.. Default::default()
	};

	// set up the matrix stacks
	let mut model_view_matrix = MatrixStack::new();
	let mut projection_matrix = MatrixStack::new();

	// set up the transformation pipeline
	let mut transform_pipeline = TransformPipeline::new(&model_view_matrix,&projection_matrix);

	// view frustum
	let mut frustum = Frustum::<f32>::new();
	let display_size = display.get_window().unwrap().get_inner_size_pixels().unwrap();
	frustum.set_perspective(35f32,display_size.0 as f32/display_size.1 as f32,1f32,5000f32);

	// setup the shaders
	let mut shader_manager = ShaderManager::new(&display);

	// create terrain
	let mut terrain = Terrain::new(&display,&mut shader_manager,5);

    // listen for events produced in the window and wait to be received
    loop {
    	// get reference to the frame
    	let mut target = display.draw();

    	// clear the background
    	target.clear_color_and_depth((0.0, 0.0, 0.0, 1.0),1.0);

    	// draw the terrain
    	terrain.draw(&mut target,&params);
    	//target.draw(terrain.get_vertex_buffer(),terrain.get_index_buffer(),terrain.get_shader(),&glium::uniforms::EmptyUniforms,&params).unwrap();

    	//target.draw(&vertex_buffer,&indices,&program,&glium::uniforms::EmptyUniforms,&params).unwrap();

    	// finish drawing and destroy frame object
    	target.finish().unwrap();

	    for ev in display.poll_events(){
	    	match ev {
	    		glium::glutin::Event::Closed => return,
	    		glium::glutin::Event::Resized(width, height) => {
	    			frustum.set_perspective(35f32,width as f32/height as f32,1f32,5000f32);
	    		},
	    		_ => ()
	    	}
	    }
    }
}<|endoftext|>


<commit_before>// error-pattern:yummy
#![feature(box_syntax)]
#![feature(rustc_private)]
#![allow(unknown_lints, missing_docs_in_private_items)]

use std::collections::HashMap;
use std::process;
use std::io::{self, Write};

extern crate cargo_metadata;

use std::path::{Path, PathBuf};

const CARGO_CLIPPY_HELP: &str = r#"Checks a package to catch common mistakes and improve your Rust code.

Usage:
    cargo clippy [options] [--] [<opts>...]

Common options:
    -h, --help               Print this message
    --features               Features to compile for the package
    -V, --version            Print version info and exit
    --all                    Run over all packages in the current workspace

Other options are the same as `cargo rustc`.

To allow or deny a lint from the command line you can use `cargo clippy --`
with:

    -W --warn OPT       Set lint warnings
    -A --allow OPT      Set lint allowed
    -D --deny OPT       Set lint denied
    -F --forbid OPT     Set lint forbidden

The feature `cargo-clippy` is automatically defined for convenience. You can use
it to allow or deny lints from the code, eg.:

    #[cfg_attr(feature = "cargo-clippy", allow(needless_lifetimes))]
"#;

#[allow(print_stdout)]
fn show_help() {
    println!("{}", CARGO_CLIPPY_HELP);
}

#[allow(print_stdout)]
fn show_version() {
    println!("{}", env!("CARGO_PKG_VERSION"));
}

pub fn main() {
    // Check for version and help flags even when invoked as 'cargo-clippy'
    if std::env::args().any(|a| a == "--help" || a == "-h") {
        show_help();
        return;
    }
    if std::env::args().any(|a| a == "--version" || a == "-V") {
        show_version();
        return;
    }

    let mut manifest_path_arg = std::env::args()
        .skip(2)
        .skip_while(|val| !val.starts_with("--manifest-path"));
    let manifest_path_arg = manifest_path_arg.next().and_then(|val| {
        if val == "--manifest-path" {
            manifest_path_arg.next()
        } else if val.starts_with("--manifest-path=") {
            Some(val["--manifest-path=".len()..].to_owned())
        } else {
            None
        }
    });

    let mut metadata = if let Ok(metadata) = cargo_metadata::metadata(manifest_path_arg.as_ref().map(AsRef::as_ref)) {
        metadata
    } else {
        println!(
            "{:?}",
            cargo_metadata::metadata(manifest_path_arg.as_ref().map(AsRef::as_ref))
        );
        let _ = io::stderr().write_fmt(format_args!("error: Could not obtain cargo metadata.\n"));
        process::exit(101);
    };

    let manifest_path = manifest_path_arg.map(|arg| {
        PathBuf::from(arg)
            .canonicalize()
            .expect("manifest path could not be canonicalized")
    });

    let packages = if std::env::args().any(|a| a == "--all") {
        metadata.packages
    } else {
        let package_index = {
            if let Some(manifest_path) = manifest_path {
                metadata.packages.iter().position(|package| {
                    let package_manifest_path = Path::new(&package.manifest_path)
                        .canonicalize()
                        .expect("package manifest path could not be canonicalized");
                    package_manifest_path == manifest_path
                })
            } else {
                let package_manifest_paths: HashMap<_, _> = metadata
                    .packages
                    .iter()
                    .enumerate()
                    .map(|(i, package)| {
                        let package_manifest_path = Path::new(&package.manifest_path)
                            .parent()
                            .expect("could not find parent directory of package manifest")
                            .canonicalize()
                            .expect("package directory cannot be canonicalized");
                        (package_manifest_path, i)
                    })
                    .collect();

                let current_dir = std::env::current_dir()
                    .expect("could not read current directory")
                    .canonicalize()
                    .expect("current directory cannot be canonicalized");

                let mut current_path: &Path = &current_dir;

                // This gets the most-recent parent (the one that takes the fewest `cd ..`s to
                // reach).
                loop {
                    if let Some(&package_index) = package_manifest_paths.get(current_path) {
                        break Some(package_index);
                    } else {
                        // We'll never reach the filesystem root, because to get to this point in the
                        // code
                        // the call to `cargo_metadata::metadata` must have succeeded. So it's okay to
                        // unwrap the current path's parent.
                        current_path = current_path
                            .parent()
                            .unwrap_or_else(|| panic!("could not find parent of path {}", current_path.display()));
                    }
                }
            }
        }.expect("could not find matching package");

        vec![metadata.packages.remove(package_index)]
    };

    for package in packages {
        let manifest_path = package.manifest_path;

        for target in package.targets {
            let args = std::env::args()
                .skip(1)
                .filter(|a| a != "--all" && !a.starts_with("--manifest-path="));

            let args = std::iter::once(format!("--manifest-path={}", manifest_path)).chain(args);
            if let Some(first) = target.kind.get(0) {
                if target.kind.len() > 1 || first.ends_with("lib") {
                    println!("lib: {}", target.name);
                    if let Err(code) = process(std::iter::once("--lib".to_owned()).chain(args)) {
                        std::process::exit(code);
                    }
                } else if ["bin", "example", "test", "bench"].contains(&&**first) {
                    println!("{}: {}", first, target.name);
                    if let Err(code) = process(
                        vec![format!("--{}", first), target.name]
                            .into_iter()
                            .chain(args),
                    ) {
                        std::process::exit(code);
                    }
                }
            } else {
                panic!("badly formatted cargo metadata: target::kind is an empty array");
            }
        }
    }
}

fn process<I>(old_args: I) -> Result<(), i32>
where
    I: Iterator<Item = String>,
{
    let mut args = vec!["rustc".to_owned()];

    let mut found_dashes = false;
    for arg in old_args {
        found_dashes |= arg == "--";
        args.push(arg);
    }
    if !found_dashes {
        args.push("--".to_owned());
    }
    args.push("--emit=metadata".to_owned());
    args.push("--cfg".to_owned());
    args.push(r#"feature="cargo-clippy""#.to_owned());

    let mut path = std::env::current_exe()
        .expect("current executable path invalid")
        .with_file_name("clippy-driver");
    if cfg!(windows) {
        path.set_extension("exe");
    }
    let exit_status = std::process::Command::new("cargo")
        .args(&args)
        .env("RUSTC_WRAPPER", path)
        .spawn()
        .expect("could not run cargo")
        .wait()
        .expect("failed to wait for cargo?");

    if exit_status.success() {
        Ok(())
    } else {
        Err(exit_status.code().unwrap_or(-1))
    }
}
<commit_msg>Undo a temporary fix for a cargo bug<commit_after>// error-pattern:yummy
#![feature(box_syntax)]
#![feature(rustc_private)]
#![allow(unknown_lints, missing_docs_in_private_items)]

use std::collections::HashMap;
use std::process;
use std::io::{self, Write};

extern crate cargo_metadata;

use std::path::{Path, PathBuf};

const CARGO_CLIPPY_HELP: &str = r#"Checks a package to catch common mistakes and improve your Rust code.

Usage:
    cargo clippy [options] [--] [<opts>...]

Common options:
    -h, --help               Print this message
    --features               Features to compile for the package
    -V, --version            Print version info and exit
    --all                    Run over all packages in the current workspace

Other options are the same as `cargo rustc`.

To allow or deny a lint from the command line you can use `cargo clippy --`
with:

    -W --warn OPT       Set lint warnings
    -A --allow OPT      Set lint allowed
    -D --deny OPT       Set lint denied
    -F --forbid OPT     Set lint forbidden

The feature `cargo-clippy` is automatically defined for convenience. You can use
it to allow or deny lints from the code, eg.:

    #[cfg_attr(feature = "cargo-clippy", allow(needless_lifetimes))]
"#;

#[allow(print_stdout)]
fn show_help() {
    println!("{}", CARGO_CLIPPY_HELP);
}

#[allow(print_stdout)]
fn show_version() {
    println!("{}", env!("CARGO_PKG_VERSION"));
}

pub fn main() {
    // Check for version and help flags even when invoked as 'cargo-clippy'
    if std::env::args().any(|a| a == "--help" || a == "-h") {
        show_help();
        return;
    }
    if std::env::args().any(|a| a == "--version" || a == "-V") {
        show_version();
        return;
    }

    let mut manifest_path_arg = std::env::args()
        .skip(2)
        .skip_while(|val| !val.starts_with("--manifest-path"));
    let manifest_path_arg = manifest_path_arg.next().and_then(|val| {
        if val == "--manifest-path" {
            manifest_path_arg.next()
        } else if val.starts_with("--manifest-path=") {
            Some(val["--manifest-path=".len()..].to_owned())
        } else {
            None
        }
    });

    let mut metadata = if let Ok(metadata) = cargo_metadata::metadata(manifest_path_arg.as_ref().map(AsRef::as_ref)) {
        metadata
    } else {
        println!(
            "{:?}",
            cargo_metadata::metadata(manifest_path_arg.as_ref().map(AsRef::as_ref))
        );
        let _ = io::stderr().write_fmt(format_args!("error: Could not obtain cargo metadata.\n"));
        process::exit(101);
    };

    let manifest_path = manifest_path_arg.map(|arg| {
        PathBuf::from(arg)
            .canonicalize()
            .expect("manifest path could not be canonicalized")
    });

    let packages = if std::env::args().any(|a| a == "--all") {
        metadata.packages
    } else {
        let package_index = {
            if let Some(manifest_path) = manifest_path {
                metadata.packages.iter().position(|package| {
                    let package_manifest_path = Path::new(&package.manifest_path)
                        .canonicalize()
                        .expect("package manifest path could not be canonicalized");
                    package_manifest_path == manifest_path
                })
            } else {
                let package_manifest_paths: HashMap<_, _> = metadata
                    .packages
                    .iter()
                    .enumerate()
                    .map(|(i, package)| {
                        let package_manifest_path = Path::new(&package.manifest_path)
                            .parent()
                            .expect("could not find parent directory of package manifest")
                            .canonicalize()
                            .expect("package directory cannot be canonicalized");
                        (package_manifest_path, i)
                    })
                    .collect();

                let current_dir = std::env::current_dir()
                    .expect("could not read current directory")
                    .canonicalize()
                    .expect("current directory cannot be canonicalized");

                let mut current_path: &Path = &current_dir;

                // This gets the most-recent parent (the one that takes the fewest `cd ..`s to
                // reach).
                loop {
                    if let Some(&package_index) = package_manifest_paths.get(current_path) {
                        break Some(package_index);
                    } else {
                        // We'll never reach the filesystem root, because to get to this point in the
                        // code
                        // the call to `cargo_metadata::metadata` must have succeeded. So it's okay to
                        // unwrap the current path's parent.
                        current_path = current_path
                            .parent()
                            .unwrap_or_else(|| panic!("could not find parent of path {}", current_path.display()));
                    }
                }
            }
        }.expect("could not find matching package");

        vec![metadata.packages.remove(package_index)]
    };

    for package in packages {
        let manifest_path = package.manifest_path;

        for target in package.targets {
            let args = std::env::args()
                .skip(2)
                .filter(|a| a != "--all" && !a.starts_with("--manifest-path="));

            let args = std::iter::once(format!("--manifest-path={}", manifest_path)).chain(args);
            if let Some(first) = target.kind.get(0) {
                if target.kind.len() > 1 || first.ends_with("lib") {
                    println!("lib: {}", target.name);
                    if let Err(code) = process(std::iter::once("--lib".to_owned()).chain(args)) {
                        std::process::exit(code);
                    }
                } else if ["bin", "example", "test", "bench"].contains(&&**first) {
                    println!("{}: {}", first, target.name);
                    if let Err(code) = process(
                        vec![format!("--{}", first), target.name]
                            .into_iter()
                            .chain(args),
                    ) {
                        std::process::exit(code);
                    }
                }
            } else {
                panic!("badly formatted cargo metadata: target::kind is an empty array");
            }
        }
    }
}

fn process<I>(old_args: I) -> Result<(), i32>
where
    I: Iterator<Item = String>,
{
    let mut args = vec!["rustc".to_owned()];

    let mut found_dashes = false;
    for arg in old_args {
        found_dashes |= arg == "--";
        args.push(arg);
    }
    if !found_dashes {
        args.push("--".to_owned());
    }
    args.push("--emit=metadata".to_owned());
    args.push("--cfg".to_owned());
    args.push(r#"feature="cargo-clippy""#.to_owned());

    let mut path = std::env::current_exe()
        .expect("current executable path invalid")
        .with_file_name("clippy-driver");
    if cfg!(windows) {
        path.set_extension("exe");
    }
    let exit_status = std::process::Command::new("cargo")
        .args(&args)
        .env("RUSTC_WRAPPER", path)
        .spawn()
        .expect("could not run cargo")
        .wait()
        .expect("failed to wait for cargo?");

    if exit_status.success() {
        Ok(())
    } else {
        Err(exit_status.code().unwrap_or(-1))
    }
}
<|endoftext|>


<commit_before>// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#![feature(iter_arith, zero_one, custom_derive,
           custom_attribute, plugin, clone_from_slice, const_fn)]
#![plugin(serde_macros)]

extern crate devicemapper;
#[macro_use]
extern crate clap;
extern crate nix;
extern crate crc;
extern crate byteorder;
extern crate uuid;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate bytesize;

#[macro_use] extern crate custom_derive;
#[macro_use] extern crate newtype_derive;

pub static mut debug: bool = false;

macro_rules! dbgp {
    ($($arg:tt)*) => (
        unsafe {
            if ::debug {
                println!($($arg)*)
            }
        })
}

mod types;
mod consts;
mod froyo;
mod blockdev;
mod raid;
mod thin;
mod util;

use std::io::Write;
use std::error::Error;
use std::process::exit;
use std::path::{Path, PathBuf};

use clap::{App, Arg, SubCommand, ArgMatches};
use uuid::Uuid;
use bytesize::ByteSize;

use types::FroyoError;
use froyo::{Froyo, FroyoStatus};

// We are given BlockDevs to start.
// We allocate LinearDevs from each for the meta and data devices.
// We use all these to make RaidDevs.
// We create two RaidLinearDevs from these for meta and data devices.
// We use these to make a ThinPoolDev.
// From that, we allocate a ThinDev.

fn list(_args: &ArgMatches) -> Result<(), FroyoError> {
    let froyos = try!(Froyo::find_all());
    for f in &froyos {
        println!("{}", f.name);
    }

    Ok(())
}

fn status(args: &ArgMatches) -> Result<(), FroyoError> {
    let name = args.value_of("froyodevname").unwrap();
    match try!(Froyo::find(&name)) {
        Some(f) => {
            let status = match try!(f.status()) {
                FroyoStatus::Good(_) => "good",
                FroyoStatus::RaidFailed => "RAID failed",
                FroyoStatus::ThinPoolFailed => "Thin pool failed",
                FroyoStatus::ThinFailed => "Thin device failed",
            };

            let space = try!(f.free_redundant_space());
            let total = f.total_redundant_space();

            println!("Status: {}, {} of {} {} blocks free", status,
                     *space, *total,
                     ByteSize::b(f.data_block_size() as usize).to_string(true));
        },
        None => println!("Froyodev \"{}\" not found", name),
    }
    Ok(())
}

fn add(_args: &ArgMatches) -> Result<(), FroyoError> {
    println!("hello from add()");
    Ok(())
}

fn remove(_args: &ArgMatches) -> Result<(), FroyoError> {
    println!("hello from remove()");
    Ok(())
}

fn create(args: &ArgMatches) -> Result<(), FroyoError> {
    let name = args.value_of("froyodevname").unwrap();
    let dev_paths: Vec<_> = args.values_of("devices").unwrap().into_iter()
        .map(|dev| {
            if !Path::new(dev).is_absolute() {
                PathBuf::from(format!("/dev/{}", dev))
            } else {
                PathBuf::from(dev)
            }})
        .collect();
    let force = args.is_present("force");

    let froyo = try!(Froyo::create(name, &Uuid::new_v4().to_simple_string(), &dev_paths, force));

    try!(froyo.save_state());

    dbgp!("Froyodev {} created", froyo.name);

    Ok(())
}

fn dump_meta(args: &ArgMatches) -> Result<(), FroyoError> {
    let name = args.value_of("froyodevname").unwrap();
    match try!(Froyo::find(&name)) {
        Some(f) =>
            println!("{}", try!(f.to_metadata_pretty())),
        None => println!("Froyodev \"{}\" not found", name),
    }

    Ok(())
}

fn main() {

    let matches = App::new("froyo")
        .version(&crate_version!())
        .author("Andy Grover <andy@groveronline.com>")
        .about("Drobo + Free + YOLO")
        .arg(Arg::with_name("debug")
             .short("d")
             .long("debug")
             .help("Print additional output for debugging")
             )
        .subcommand(SubCommand::with_name("list")
                    .about("List all froyodevs")
                    .arg(Arg::with_name("long")
                         .short("l")
                         .long("long")
                         .help("Use a long listing format")
                         )
                    )
        .subcommand(SubCommand::with_name("status")
                    .about("Get the status of a single froyodev")
                    .arg(Arg::with_name("froyodevname")
                         .required(true)
                         .help("Froyodev to get info on")
                         .index(1)
                         )
                    )
        .subcommand(SubCommand::with_name("add")
                    .about("Add one or more additional block devices to a froyodev")
                    .arg(Arg::with_name("froyodevname")
                         .help("Froyodev to add the device to")
                         .required(true)
                         .index(1)
                         )
                    .arg(Arg::with_name("devices")
                         .help("device(s) to add")
                         .multiple(true)
                         .required(true)
                         .index(2)
                         )
                    )
        .subcommand(SubCommand::with_name("remove")
                    .about("Remove a block device from a froyodev")
                    .arg(Arg::with_name("froyodevname")
                         .help("Froyodev to remove the device from")
                         .required(true)
                         .index(1)
                         )
                    .arg(Arg::with_name("devices")
                         .help("Block device(s) to remove")
                         .multiple(true)
                         .required(true)
                         .index(2)
                         )
                    )
        .subcommand(SubCommand::with_name("create")
                    .about("Create a new froyodev")
                    .arg(Arg::with_name("force")
                         .short("f")
                         .long("force")
                         .help("Force")
                         )
                    .arg(Arg::with_name("froyodevname")
                         .help("Name of the new froyodev")
                         .required(true)
                         .index(1)
                         )
                    .arg(Arg::with_name("devices")
                         .help("Initial block device(s) to use")
                         .multiple(true)
                         .required(true)
                         .index(2)
                         )
                    )
        .subcommand(SubCommand::with_name("dump_meta")
                    .about("Output the JSON metadata for a froyodev")
                    .arg(Arg::with_name("froyodevname")
                         .help("Name of the froyodev")
                         .required(true)
                         .index(1)
                         )
                    )
        .get_matches();

    if matches.is_present("debug") {
        // must use unsafe to change a mut static, sigh
        unsafe { debug = true };
    }

    let r = match matches.subcommand() {
        ("list", Some(matches)) => list(matches),
        ("status", Some(matches)) => status(matches),
        ("add", Some(matches)) => add(matches),
        ("remove", Some(matches)) => remove(matches),
        ("create", Some(matches)) => create(matches),
        ("dump_meta", Some(matches)) => dump_meta(matches),
        ("", None) => {
            println!("No command given, try \"help\"");
            Ok(())
        }
        _ => unreachable!(),
    };

    if let Err(r) = r {
        match writeln!(&mut ::std::io::stderr(), "{}", r.description()) {
            Ok(_) => {},
            Err(x) => panic!("Unable to write to stderr: {}", x),
        }
        exit(1);
    }
}
<commit_msg>Fix status output a little<commit_after>// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#![feature(iter_arith, zero_one, custom_derive,
           custom_attribute, plugin, clone_from_slice, const_fn)]
#![plugin(serde_macros)]

extern crate devicemapper;
#[macro_use]
extern crate clap;
extern crate nix;
extern crate crc;
extern crate byteorder;
extern crate uuid;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate bytesize;

#[macro_use] extern crate custom_derive;
#[macro_use] extern crate newtype_derive;

pub static mut debug: bool = false;

macro_rules! dbgp {
    ($($arg:tt)*) => (
        unsafe {
            if ::debug {
                println!($($arg)*)
            }
        })
}

mod types;
mod consts;
mod froyo;
mod blockdev;
mod raid;
mod thin;
mod util;

use std::io::Write;
use std::error::Error;
use std::process::exit;
use std::path::{Path, PathBuf};

use clap::{App, Arg, SubCommand, ArgMatches};
use uuid::Uuid;
use bytesize::ByteSize;

use types::FroyoError;
use froyo::{Froyo, FroyoStatus};

// We are given BlockDevs to start.
// We allocate LinearDevs from each for the meta and data devices.
// We use all these to make RaidDevs.
// We create two RaidLinearDevs from these for meta and data devices.
// We use these to make a ThinPoolDev.
// From that, we allocate a ThinDev.

fn list(_args: &ArgMatches) -> Result<(), FroyoError> {
    let froyos = try!(Froyo::find_all());
    for f in &froyos {
        println!("{}", f.name);
    }

    Ok(())
}

fn status(args: &ArgMatches) -> Result<(), FroyoError> {
    let name = args.value_of("froyodevname").unwrap();
    match try!(Froyo::find(&name)) {
        Some(f) => {
            let status = match try!(f.status()) {
                FroyoStatus::Good(_) => "good",
                FroyoStatus::RaidFailed => "RAID failed",
                FroyoStatus::ThinPoolFailed => "Thin pool failed",
                FroyoStatus::ThinFailed => "Thin device failed",
            };

            let space = try!(f.free_redundant_space());
            let total = f.total_redundant_space();

            let percent = (*(total-space) * 100) / *total;

            println!("Status: {}, {}% used ({} of {} {} blocks free)",
                     status, percent,
                     *space, *total,
                     ByteSize::b(f.data_block_size() as usize).to_string(true));
        },
        None => println!("Froyodev \"{}\" not found", name),
    }
    Ok(())
}

fn add(_args: &ArgMatches) -> Result<(), FroyoError> {
    println!("hello from add()");
    Ok(())
}

fn remove(_args: &ArgMatches) -> Result<(), FroyoError> {
    println!("hello from remove()");
    Ok(())
}

fn create(args: &ArgMatches) -> Result<(), FroyoError> {
    let name = args.value_of("froyodevname").unwrap();
    let dev_paths: Vec<_> = args.values_of("devices").unwrap().into_iter()
        .map(|dev| {
            if !Path::new(dev).is_absolute() {
                PathBuf::from(format!("/dev/{}", dev))
            } else {
                PathBuf::from(dev)
            }})
        .collect();
    let force = args.is_present("force");

    let froyo = try!(Froyo::create(name, &Uuid::new_v4().to_simple_string(), &dev_paths, force));

    try!(froyo.save_state());

    dbgp!("Froyodev {} created", froyo.name);

    Ok(())
}

fn dump_meta(args: &ArgMatches) -> Result<(), FroyoError> {
    let name = args.value_of("froyodevname").unwrap();
    match try!(Froyo::find(&name)) {
        Some(f) =>
            println!("{}", try!(f.to_metadata_pretty())),
        None => println!("Froyodev \"{}\" not found", name),
    }

    Ok(())
}

fn main() {

    let matches = App::new("froyo")
        .version(&crate_version!())
        .author("Andy Grover <andy@groveronline.com>")
        .about("Drobo + Free + YOLO")
        .arg(Arg::with_name("debug")
             .short("d")
             .long("debug")
             .help("Print additional output for debugging")
             )
        .subcommand(SubCommand::with_name("list")
                    .about("List all froyodevs")
                    .arg(Arg::with_name("long")
                         .short("l")
                         .long("long")
                         .help("Use a long listing format")
                         )
                    )
        .subcommand(SubCommand::with_name("status")
                    .about("Get the status of a single froyodev")
                    .arg(Arg::with_name("froyodevname")
                         .required(true)
                         .help("Froyodev to get info on")
                         .index(1)
                         )
                    )
        .subcommand(SubCommand::with_name("add")
                    .about("Add one or more additional block devices to a froyodev")
                    .arg(Arg::with_name("froyodevname")
                         .help("Froyodev to add the device to")
                         .required(true)
                         .index(1)
                         )
                    .arg(Arg::with_name("devices")
                         .help("device(s) to add")
                         .multiple(true)
                         .required(true)
                         .index(2)
                         )
                    )
        .subcommand(SubCommand::with_name("remove")
                    .about("Remove a block device from a froyodev")
                    .arg(Arg::with_name("froyodevname")
                         .help("Froyodev to remove the device from")
                         .required(true)
                         .index(1)
                         )
                    .arg(Arg::with_name("devices")
                         .help("Block device(s) to remove")
                         .multiple(true)
                         .required(true)
                         .index(2)
                         )
                    )
        .subcommand(SubCommand::with_name("create")
                    .about("Create a new froyodev")
                    .arg(Arg::with_name("force")
                         .short("f")
                         .long("force")
                         .help("Force")
                         )
                    .arg(Arg::with_name("froyodevname")
                         .help("Name of the new froyodev")
                         .required(true)
                         .index(1)
                         )
                    .arg(Arg::with_name("devices")
                         .help("Initial block device(s) to use")
                         .multiple(true)
                         .required(true)
                         .index(2)
                         )
                    )
        .subcommand(SubCommand::with_name("dump_meta")
                    .about("Output the JSON metadata for a froyodev")
                    .arg(Arg::with_name("froyodevname")
                         .help("Name of the froyodev")
                         .required(true)
                         .index(1)
                         )
                    )
        .get_matches();

    if matches.is_present("debug") {
        // must use unsafe to change a mut static, sigh
        unsafe { debug = true };
    }

    let r = match matches.subcommand() {
        ("list", Some(matches)) => list(matches),
        ("status", Some(matches)) => status(matches),
        ("add", Some(matches)) => add(matches),
        ("remove", Some(matches)) => remove(matches),
        ("create", Some(matches)) => create(matches),
        ("dump_meta", Some(matches)) => dump_meta(matches),
        ("", None) => {
            println!("No command given, try \"help\"");
            Ok(())
        }
        _ => unreachable!(),
    };

    if let Err(r) = r {
        match writeln!(&mut ::std::io::stderr(), "{}", r.description()) {
            Ok(_) => {},
            Err(x) => panic!("Unable to write to stderr: {}", x),
        }
        exit(1);
    }
}
<|endoftext|>


<commit_before>extern crate kernel32;
extern crate user32;
extern crate winapi;
extern crate libc;
extern crate gdi32;

use winapi::windef::HWND;
use winapi::windef::HMENU;
use winapi::windef::HBRUSH;
use winapi::minwindef::HINSTANCE;

use winapi::minwindef::UINT;
use winapi::minwindef::DWORD;
use winapi::minwindef::WPARAM;
use winapi::minwindef::LPARAM;
use winapi::minwindef::LRESULT;
use winapi::minwindef::BOOL;
use winapi::winnt::LPCWSTR;

use winapi::winuser::WS_OVERLAPPEDWINDOW;
use winapi::winuser::WS_VISIBLE;
use winapi::winuser::WNDCLASSW;
use winapi::winuser::CF_BITMAP;

use std::os::windows::ffi::OsStrExt;
use std::ffi::OsStr;

const g_class_name: &'static str = "winshot";

// Rectangle represents screen coordinates
struct Rectangle {
	x: i32,
	y: i32,
	x2: i32,
	y2: i32,
}

// convert normal string to wide string
#[allow(dead_code)]
fn to_wstring(str: &str) -> *const u16 {
	let v: Vec<u16> = OsStr::new(str).encode_wide() . chain(Some(0).into_iter()).collect();
	v.as_ptr()
}

// This is our window message handler function. Currently,
// it only processes the WM_DESTROY message to exit our window properly on close event.
pub unsafe extern "system" fn window_proc(h_wnd: HWND, msg: UINT, w_param: WPARAM, l_param: LPARAM) -> LRESULT {
	use winapi::winuser::*;

	match msg {
		WM_DESTROY => {
			user32::PostQuitMessage(0);
			return 0 as LRESULT;
		},
		// TODO implement
		WM_MOUSEMOVE => {
			return 0 as LRESULT;
		},
		WM_LBUTTONDOWN => {
			return 0 as LRESULT;
		},
		WM_LBUTTONUP => {
			return 0 as LRESULT;
		},
		_ => {
			return user32::DefWindowProcW(h_wnd, msg, w_param, l_param);
		},
	}
}

// TODO figure out how the heck to use pointers
fn normalize_coords(rect: Rectangle) -> Rectangle {
    let Rectangle{mut x, mut y, mut x2, mut y2} = rect;

    if x > x2 {
        let tmp = x;
        x = x2;
        x2 = tmp;
    }
    if y > y2 {
        let tmp = y;
        y = y2;
        y2 = tmp;
    }

    Rectangle{x: x, y: y, x2: x2, y2: y2}
}

fn get_screen_rect() -> Rectangle {
	Rectangle{
		x /* left */: user32::GetSystemMetrics(winapi::winuser::SM_XVIRTUALSCREEN),
		y /* top */: user32::GetSystemMetrics(winapi::winuser::SM_YVIRTUALSCREEN),
		x2 /* right */: user32::GetSystemMetrics(winapi::winuser::SM_CXVIRTUALSCREEN) + user32::GetSystemMetrics(winapi::winuser::SM_XVIRTUALSCREEN),
		y2 /* bottom */: user32::GetSystemMetrics(winapi::winuser::SM_CYVIRTUALSCREEN) + user32::GetSystemMetrics(winapi::winuser::SM_CYVIRTUALSCREEN),
	}
}

fn capture_screen_clipboard(hwnd: HWND, mut rect: Rectangle) -> bool {
	// normalize coordinates
	let rect = normalize_coords(rect);
	let w = rect.x2 - rect.x;
	let h = rect.y2 - rect.y;

	let screen_dc = user32::GetDC(0 as HWND);
	let shot_dc = gdi32::CreateCompatibleDC(screen_dc);
	let shot_bitmap = gdi32::CreateCompatibleBitmap(screen_dc, w, h);
	let old_obj = gdi32::SelectObject(shot_dc, shot_bitmap);

	if !gdi32::BitBlt(shot_dc, 0, 0, w, h, screen_dc, rect.x, rect.y, 0 as DWORD) {
		println!("{:?}", "BitBlt failed? Perhaps.");
		return false;
	}

	let mut ret = false;
	if user32::OpenClipboard(hwnd) as BOOL == winapi::minwindef::TRUE {
		if user32::EmptyClipboard() as BOOL == winapi::minwindef::TRUE {
			if user32::SetClipboardData(CF_BITMAP, shot_bitmap) as BOOL == winapi::minwindef::TRUE {
				ret = true;
			}
			user32::CloseClipboard();
		}
	} else {
		println!("{:?}", "could not open clipboard");
	}

	// Clean up
	gdi32::DeleteDC(shot_dc);
	gdi32::DeleteDC(screen_dc);
	gdi32::SelectObject(shot_dc, old_obj);

	return ret;
}

fn main() {
	unsafe {
		let hInstance = kernel32::GetModuleHandleW(0 as LPCWSTR);
		let m_class_name = to_wstring(g_class_name);
		let wnd = WNDCLASSW {
			hInstance: hInstance,
			lpszClassName: m_class_name,
			lpszMenuName: 0 as LPCWSTR,
			lpfnWndProc: Some(window_proc),
			cbClsExtra: 0,
			cbWndExtra: 0,
			style: winapi::winuser::CS_HREDRAW | winapi::winuser::CS_VREDRAW,
			hbrBackground: 0,
			hCursor: user32::LoadCursorW(0 as HINSTANCE, winapi::winuser::IDC_CROSS),
			hIcon: user32::LoadIconW(0 as HINSTANCE, winapi::winuser::IDI_APPLICATION),
		};

		user32::RegisterClassW(&wnd);
		let rect = get_screen_rect();
		let exstyle = winapi::winuser::WS_EX_TRANSPARENT;
		let style = winapi::winuser::WS_POPUP;

		let win = user32::CreateWindowExW(exstyle,
			m_class_name,
			m_class_name,
			style,
			// dimensions
			0, 0, rect.x2, rect.y2,
			0 as HBRUSH, // no parent
			0 as HWND, // no menu
			hInstance, // module_instance
			0 as HMENU,
		);

		user32::ShowWindow(win, winapi::winuser::SW_SHOW);
		user32::ShowWindow(win, winapi::winuser::SW_SHOWMAXIMIZED);
		user32::SetForegroundWindow(win);

		capture_screen_clipboard(win, Rectangle{
			x: 0,
			y: 0,
			x2: 200,
			y2: 200,
		});
		user32::DestroyWindow(win);
	}
}<commit_msg>Use normal integers<commit_after>extern crate kernel32;
extern crate user32;
extern crate winapi;
extern crate libc;
extern crate gdi32;

use winapi::windef::HWND;
use winapi::windef::HMENU;
use winapi::windef::HBRUSH;
use winapi::minwindef::HINSTANCE;

use winapi::minwindef::UINT;
use winapi::minwindef::DWORD;
use winapi::minwindef::WPARAM;
use winapi::minwindef::LPARAM;
use winapi::minwindef::LRESULT;
use winapi::minwindef::BOOL;
use winapi::winnt::LPCWSTR;

use winapi::winuser::WS_OVERLAPPEDWINDOW;
use winapi::winuser::WS_VISIBLE;
use winapi::winuser::WNDCLASSW;
use winapi::winuser::CF_BITMAP;

use std::os::windows::ffi::OsStrExt;
use std::ffi::OsStr;

const g_class_name: &'static str = "winshot";

// Rectangle represents screen coordinates
struct Rectangle {
	x: i32,
	y: i32,
	x2: i32,
	y2: i32,
}

// convert normal string to wide string
#[allow(dead_code)]
fn to_wstring(str: &str) -> *const u16 {
	let v: Vec<u16> = OsStr::new(str).encode_wide() . chain(Some(0).into_iter()).collect();
	v.as_ptr()
}

// This is our window message handler function. Currently,
// it only processes the WM_DESTROY message to exit our window properly on close event.
pub unsafe extern "system" fn window_proc(h_wnd: HWND, msg: UINT, w_param: WPARAM, l_param: LPARAM) -> LRESULT {
	use winapi::winuser::*;

	match msg {
		WM_DESTROY => {
			user32::PostQuitMessage(0);
			return 0 as LRESULT;
		},
		// TODO implement
		WM_MOUSEMOVE => {
			return 0 as LRESULT;
		},
		WM_LBUTTONDOWN => {
			return 0 as LRESULT;
		},
		WM_LBUTTONUP => {
			return 0 as LRESULT;
		},
		_ => {
			return user32::DefWindowProcW(h_wnd, msg, w_param, l_param);
		},
	}
}

// TODO figure out how the heck to use pointers
fn normalize_coords(rect: Rectangle) -> Rectangle {
    let Rectangle{mut x, mut y, mut x2, mut y2} = rect;

    if x > x2 {
        let tmp = x;
        x = x2;
        x2 = tmp;
    }
    if y > y2 {
        let tmp = y;
        y = y2;
        y2 = tmp;
    }

    Rectangle{x: x, y: y, x2: x2, y2: y2}
}

fn get_screen_rect() -> Rectangle {
	Rectangle{
		x /* left */: user32::GetSystemMetrics(winapi::winuser::SM_XVIRTUALSCREEN),
		y /* top */: user32::GetSystemMetrics(winapi::winuser::SM_YVIRTUALSCREEN),
		x2 /* right */: user32::GetSystemMetrics(winapi::winuser::SM_CXVIRTUALSCREEN) + user32::GetSystemMetrics(winapi::winuser::SM_XVIRTUALSCREEN),
		y2 /* bottom */: user32::GetSystemMetrics(winapi::winuser::SM_CYVIRTUALSCREEN) + user32::GetSystemMetrics(winapi::winuser::SM_CYVIRTUALSCREEN),
	}
}

fn capture_screen_clipboard(hwnd: HWND, mut rect: Rectangle) -> bool {
	// normalize coordinates
	let rect = normalize_coords(rect);
	let w = rect.x2 - rect.x;
	let h = rect.y2 - rect.y;

	let screen_dc = user32::GetDC(0 as HWND);
	let shot_dc = gdi32::CreateCompatibleDC(screen_dc);
	let shot_bitmap = gdi32::CreateCompatibleBitmap(screen_dc, w, h);
	let old_obj = gdi32::SelectObject(shot_dc, shot_bitmap);

	if !gdi32::BitBlt(shot_dc, 0, 0, w, h, screen_dc, rect.x, rect.y, 0 as DWORD) {
		println!("{:?}", "BitBlt failed? Perhaps.");
		return false;
	}

	let mut ret = false;
	if user32::OpenClipboard(hwnd) != 0 {
		if user32::EmptyClipboard() != 0 {
			if user32::SetClipboardData(CF_BITMAP, shot_bitmap) != 0 {
				ret = true;
			}
			user32::CloseClipboard();
		}
	} else {
		println!("{:?}", "could not open clipboard");
	}

	// Clean up
	gdi32::DeleteDC(shot_dc);
	gdi32::DeleteDC(screen_dc);
	gdi32::SelectObject(shot_dc, old_obj);

	return ret;
}

fn main() {
	unsafe {
		let hInstance = kernel32::GetModuleHandleW(0 as LPCWSTR);
		let m_class_name = to_wstring(g_class_name);
		let wnd = WNDCLASSW {
			hInstance: hInstance,
			lpszClassName: m_class_name,
			lpszMenuName: 0 as LPCWSTR,
			lpfnWndProc: Some(window_proc),
			cbClsExtra: 0,
			cbWndExtra: 0,
			style: winapi::winuser::CS_HREDRAW | winapi::winuser::CS_VREDRAW,
			hbrBackground: 0,
			hCursor: user32::LoadCursorW(0 as HINSTANCE, winapi::winuser::IDC_CROSS),
			hIcon: user32::LoadIconW(0 as HINSTANCE, winapi::winuser::IDI_APPLICATION),
		};

		user32::RegisterClassW(&wnd);
		let rect = get_screen_rect();
		let exstyle = winapi::winuser::WS_EX_TRANSPARENT;
		let style = winapi::winuser::WS_POPUP;

		let win = user32::CreateWindowExW(exstyle,
			m_class_name,
			m_class_name,
			style,
			// dimensions
			0, 0, rect.x2, rect.y2,
			0 as HBRUSH, // no parent
			0 as HWND, // no menu
			hInstance, // module_instance
			0 as HMENU,
		);

		user32::ShowWindow(win, winapi::winuser::SW_SHOW);
		user32::ShowWindow(win, winapi::winuser::SW_SHOWMAXIMIZED);
		user32::SetForegroundWindow(win);

		capture_screen_clipboard(win, Rectangle{
			// TODO use real values later
			x: 0,
			y: 0,
			x2: 200,
			y2: 200,
		});
		user32::DestroyWindow(win);
	}
}<|endoftext|>


<commit_before>#[macro_use]
extern crate clap;
use clap::{App, Arg, SubCommand};
extern crate glob;
extern crate reqwest;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate toml;

#[macro_use]
extern crate lazy_static;

mod structs;
mod ghclient;
mod statics;
use statics::CLIENT;

fn main() {
    let user_arg = Arg::with_name("USER").required(true)
                                         .index(1)
                                         .help("user name");
    let conf_arg = Arg::with_name("CONF").required(true)
                                         .index(1)
                                         .help("conf path");
    let app = App::new(crate_name!()).version(crate_version!())
                                     .author(crate_authors!())
                                     .about(crate_description!())
                                     .subcommand(SubCommand::with_name("key").about("Gets user public key")
                                                                             .arg(user_arg))
                                     .subcommand(SubCommand::with_name("pam").about("Executes pam check"))
                                     .subcommand(SubCommand::with_name("cleanup").about("Cleans caches up"))
                                     .subcommand(SubCommand::with_name("check").about("Check configuration")
                                                                               .arg(conf_arg))
                                     .get_matches();

    match app.subcommand() {
        ("key", Some(sub)) => CLIENT.print_user_public_key(sub.value_of("USER").unwrap())
                                    .unwrap(),
        ("check", Some(sub)) => match structs::Config::new(std::path::Path::new(sub.value_of("CONF").unwrap())) {
            Ok(_) => std::process::exit(0),
            Err(_) => std::process::exit(11),
        },
        ("cleanup", Some(_)) => CLIENT.clear_all_caches().unwrap(),
        ("pam", Some(_)) => match std::env::var("PAM_USER") {
            Ok(user) => {
                if CLIENT.check_pam(&user).unwrap() {
                    std::process::exit(0);
                } else {
                    std::process::exit(1)
                }
            }
            Err(e) => println!("PAM_USER: {}", e),
        },
        (&_, _) => println!("{}", app.usage()),
    }
}
<commit_msg>Improve error handling<commit_after>#[macro_use]
extern crate clap;
use clap::{App, Arg, SubCommand};
extern crate glob;
extern crate reqwest;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate toml;

#[macro_use]
extern crate lazy_static;

mod structs;
mod ghclient;
mod statics;
use statics::CLIENT;

fn main() {
    let user_arg = Arg::with_name("USER").required(true)
                                         .index(1)
                                         .help("user name");
    let conf_arg = Arg::with_name("CONF").required(true)
                                         .index(1)
                                         .help("conf path");
    let app = App::new(crate_name!()).version(crate_version!())
                                     .author(crate_authors!())
                                     .about(crate_description!())
                                     .subcommand(SubCommand::with_name("key").about("Gets user public key")
                                                                             .arg(user_arg))
                                     .subcommand(SubCommand::with_name("pam").about("Executes pam check"))
                                     .subcommand(SubCommand::with_name("cleanup").about("Cleans caches up"))
                                     .subcommand(SubCommand::with_name("check").about("Check configuration")
                                                                               .arg(conf_arg))
                                     .get_matches();

    match app.subcommand() {
        ("key", Some(sub)) => match CLIENT.print_user_public_key(sub.value_of("USER").unwrap()) {
            Ok(_) => std::process::exit(0),
            Err(_) => std::process::exit(21),
        },
        ("check", Some(sub)) => match structs::Config::new(std::path::Path::new(sub.value_of("CONF").unwrap())) {
            Ok(_) => std::process::exit(0),
            Err(_) => std::process::exit(11),
        },
        ("cleanup", Some(_)) => CLIENT.clear_all_caches().unwrap(),
        ("pam", Some(_)) => match std::env::var("PAM_USER") {
            Ok(user) => {
                if CLIENT.check_pam(&user).unwrap() {
                    std::process::exit(0);
                } else {
                    std::process::exit(1)
                }
            }
            Err(e) => println!("PAM_USER: {}", e),
        },
        (&_, _) => println!("{}", app.usage()),
    }
}
<|endoftext|>


<commit_before>extern crate docopt;
extern crate nalgebra;
extern crate riscan_pro;
extern crate rustc_serialize;

use docopt::Docopt;
use nalgebra::{Iterable, Transpose};
use riscan_pro::{Matrix, Project, ScanPosition};
use rustc_serialize::json::{Json, ToJson};
use std::collections::HashMap;

const USAGE: &'static str = "
RiSCAN PRO utilities.

Usage:
    riscan-pro export-filters <project> [<scan-position>]
    riscan-pro socs-to-glcs <project> [<scan-position>] [<x> <y> <z>]
    riscan-pro scan-positions <project>
    riscan-pro (-h | --help)

Options:
    -h --help                       Show this screen.
";

#[derive(Debug, RustcDecodable)]
struct Args {
    cmd_export_filters: bool,
    cmd_socs_to_glcs: bool,
    cmd_scan_positions: bool,
    arg_project: String,
    arg_scan_position: Option<String>,
    arg_x: Option<f64>,
    arg_y: Option<f64>,
    arg_z: Option<f64>,
}

fn main() {
    let args: Args = Docopt::new(USAGE).and_then(|d| d.decode()).unwrap_or_else(|e| e.exit());
    if args.cmd_socs_to_glcs {
        let scan_position = if let Some(scan_position) = args.arg_scan_position {
            let project = Project::from_path(args.arg_project).unwrap();
            project.scan_position(&scan_position).unwrap().clone()
        } else {
            ScanPosition::from_path(args.arg_project).unwrap()
        };
        let glcs = scan_position.socs_to_glcs((args.arg_x.unwrap_or(0.),
                                               args.arg_y.unwrap_or(0.),
                                               args.arg_z.unwrap_or(0.)));
        println!("{:.2}, {:.2}, {:.2}", glcs.0, glcs.1, glcs.2);
    } else if args.cmd_scan_positions {
        let project = Project::from_path(args.arg_project).unwrap();
        for scan_position in project.scan_positions() {
            let glcs = scan_position.socs_to_glcs((0., 0., 0.));
            println!("{:.2} {:.2}", glcs.0, glcs.1);
        }
    } else if args.cmd_export_filters {
        let scan_position = if let Some(scan_position) = args.arg_scan_position {
            let project = Project::from_path(args.arg_project).unwrap();
            project.scan_position(&scan_position).unwrap().clone()
        } else {
            ScanPosition::from_path(args.arg_project).unwrap()
        };
        let mut filters = Vec::new();
        filters.push(filters_transformation(scan_position.sop()));
        filters.push(filters_transformation(scan_position.pop()));
        println!("{}", filters.to_json());
    }
}

fn filters_transformation(matrix: Matrix) -> Json {
    let mut filter = HashMap::new();
    filter.insert("type".to_string(), "filters.transformation".to_json());
    filter.insert("matrix".to_string(),
                  matrix.transpose()
                      .iter()
                      .map(|n| format!("{}", n))
                      .collect::<Vec<_>>()
                      .join(" ")
                      .to_json());
    filter.to_json()
}
<commit_msg>Print scan position name<commit_after>extern crate docopt;
extern crate nalgebra;
extern crate riscan_pro;
extern crate rustc_serialize;

use docopt::Docopt;
use nalgebra::{Iterable, Transpose};
use riscan_pro::{Matrix, Project, ScanPosition};
use rustc_serialize::json::{Json, ToJson};
use std::collections::HashMap;

const USAGE: &'static str = "
RiSCAN PRO utilities.

Usage:
    riscan-pro export-filters <project> [<scan-position>]
    riscan-pro socs-to-glcs <project> [<scan-position>] [<x> <y> <z>]
    riscan-pro scan-positions <project>
    riscan-pro (-h | --help)

Options:
    -h --help                       Show this screen.
";

#[derive(Debug, RustcDecodable)]
struct Args {
    cmd_export_filters: bool,
    cmd_socs_to_glcs: bool,
    cmd_scan_positions: bool,
    arg_project: String,
    arg_scan_position: Option<String>,
    arg_x: Option<f64>,
    arg_y: Option<f64>,
    arg_z: Option<f64>,
}

fn main() {
    let args: Args = Docopt::new(USAGE).and_then(|d| d.decode()).unwrap_or_else(|e| e.exit());
    if args.cmd_socs_to_glcs {
        let scan_position = if let Some(scan_position) = args.arg_scan_position {
            let project = Project::from_path(args.arg_project).unwrap();
            project.scan_position(&scan_position).unwrap().clone()
        } else {
            ScanPosition::from_path(args.arg_project).unwrap()
        };
        let glcs = scan_position.socs_to_glcs((args.arg_x.unwrap_or(0.),
                                               args.arg_y.unwrap_or(0.),
                                               args.arg_z.unwrap_or(0.)));
        println!("{:.2}, {:.2}, {:.2}", glcs.0, glcs.1, glcs.2);
    } else if args.cmd_scan_positions {
        let project = Project::from_path(args.arg_project).unwrap();
        for scan_position in project.scan_positions() {
            let glcs = scan_position.socs_to_glcs((0., 0., 0.));
            println!("{} {:.2} {:.2}", scan_position.name(), glcs.0, glcs.1);
        }
    } else if args.cmd_export_filters {
        let scan_position = if let Some(scan_position) = args.arg_scan_position {
            let project = Project::from_path(args.arg_project).unwrap();
            project.scan_position(&scan_position).unwrap().clone()
        } else {
            ScanPosition::from_path(args.arg_project).unwrap()
        };
        let mut filters = Vec::new();
        filters.push(filters_transformation(scan_position.sop()));
        filters.push(filters_transformation(scan_position.pop()));
        println!("{}", filters.to_json());
    }
}

fn filters_transformation(matrix: Matrix) -> Json {
    let mut filter = HashMap::new();
    filter.insert("type".to_string(), "filters.transformation".to_json());
    filter.insert("matrix".to_string(),
                  matrix.transpose()
                      .iter()
                      .map(|n| format!("{}", n))
                      .collect::<Vec<_>>()
                      .join(" ")
                      .to_json());
    filter.to_json()
}
<|endoftext|>


<commit_before>extern crate iron;
#[macro_use]
extern crate router;
extern crate staticfile;
extern crate mount;
extern crate urlencoded;
extern crate rustc_serialize;
extern crate html5ever;
extern crate regex;
extern crate uuid;
extern crate chrono;

use std::net::SocketAddrV4;
use std::net::Ipv4Addr;
use std::path::Path;
use iron::prelude::*;
use iron::status;
use iron::mime::Mime;
use staticfile::Static;
use mount::Mount;
use router::{Router};
use urlencoded::UrlEncodedQuery;
use urlencoded::UrlEncodedBody;
use std::str::FromStr;
use uuid::Uuid;

#[macro_use]
extern crate string_cache;
extern crate pink_spider;

use pink_spider::error::Error;
use pink_spider::scraper::extract;
use pink_spider::model::{Track, Entry, Provider, PaginatedCollection};
use rustc_serialize::json::{ToJson, Json};
use pink_spider::youtube;
use pink_spider::soundcloud;

pub fn index_entries(req: &mut Request) -> IronResult<Response> {
    let (page, per_page) = pagination_params(req);
    let entries          = Entry::find(page, per_page);
    let json_obj: Json   = entries.to_json();
    let json_str: String = json_obj.to_string();
    Ok(Response::with((status::Ok, application_json(), json_str)))
}

pub fn index_tracks(req: &mut Request) -> IronResult<Response> {
    let (page, per_page) = pagination_params(req);
    let tracks  = Track::find(page, per_page);
    let json_obj: Json   = tracks.to_json();
    let json_str: String = json_obj.to_string();
    Ok(Response::with((status::Ok, application_json(), json_str)))
}

pub fn index_tracks_by_entry(req: &mut Request) -> IronResult<Response> {
    let ref entry_id = req.extensions.get::<Router>().unwrap().find("entry_id").unwrap();
    let uuid = try!(Uuid::parse_str(entry_id).map_err(|_| Error::Unprocessable));
    let items = Track::find_by_entry_id(uuid);
    let col = PaginatedCollection {
        page:     0,
        per_page: items.len() as i64,
        total:    items.len() as i64,
        items:    items,
    };
    let json_obj: Json   = col.to_json();
    let json_str: String = json_obj.to_string();
    Ok(Response::with((status::Ok, application_json(), json_str)))
}

pub fn playlistify(req: &mut Request) -> IronResult<Response> {
    pub fn playlistify2(req: &mut Request) -> Result<Response, Error> {
        let ref params  = try!(req.get_ref::<UrlEncodedQuery>());
        let url         = try!(params.get("url").ok_or(Error::BadRequest));
        let defaults    = &vec!("false".to_string());
        let force_param = params.get("force").unwrap_or(defaults);
        let force       = force_param.len() > 0 && &force_param[0] == "true";
        let entry       = try!(find_or_playlistify_entry(&url[0], force));
        let json_obj    = entry.to_json() as Json;
        let json_str    = json_obj.to_string() as String;
        Ok(Response::with((status::Ok, application_json(), json_str)))
    }
    playlistify2(req).map_err(|err| IronError::from(err))
}

pub fn find_or_playlistify_entry(url: &str, force: bool) -> Result<Entry, Error> {
    match Entry::find_by_url(url) {
        Ok(entry) => {
            println!("Get entry from database cache: {}", url);
            if force {
                println!("Update entry: {}", url);
                let entry = try!(playlistify_entry(entry));
                Ok(entry)
            } else {
                Ok(entry)
            }
        },
        Err(_) => {
            let entry = try!(Entry::create_by_url(url.to_string()));
            let entry = try!(playlistify_entry(entry));
            println!("Create new entry to database cache: {}", url);
            Ok(entry)
        },
    }
}

pub fn playlistify_entry(entry: Entry) -> Result<Entry, Error> {
    let mut e = entry.clone();
    let product = try!(extract(&entry.url));
    match product.og_obj {
        Some(og_obj) => {
            e.title       = Some(og_obj.title);
            e.description = og_obj.description;
            e.locale      = og_obj.locale;
            e.visual_url  = og_obj.images.first().map(|i| i.url.clone());
        },
        None => (),
    }
    for t in product.tracks {
        let mut track = try!(Track::find_or_create(t.provider, t.identifier.to_string()));
        track.title = t.title;
        let track = match t.provider {
            Provider::YouTube => match youtube::fetch_video(&t.identifier) {
                Ok(video) => track.update_with_yt_video(&video),
                Err(_)    => track.disable(),
            },
            Provider::SoundCloud => match soundcloud::fetch_track(&t.identifier) {
                Ok(sc_track) => track.update_with_sc_track(&sc_track),
                Err(_)       => track.disable(),
            },
            _ => &mut track,
        };
        try!(track.save());
        match entry.tracks.iter().find(|&t| t.id == track.id) {
            Some(_) => (),
            None    => e.add_track(track.clone())
        }
    }
    try!(e.save());
    Ok(e)
}

pub fn show_track_by_id(req: &mut Request) -> IronResult<Response> {
    let ref track_id = req.extensions.get::<Router>().unwrap()
                          .find("track_id").unwrap();
    match Track::find_by_id(track_id) {
        Ok(track) => {
            Ok(Response::with((status::Ok,
                               application_json(),
                               track.to_json().to_string())))
        },
        Err(e) => Ok(e.as_response())
    }
}

pub fn show_track(req: &mut Request) -> IronResult<Response> {
    let provider   = req.extensions.get::<Router>().unwrap().find("provider").unwrap();
    let identifier = req.extensions.get::<Router>().unwrap().find("id").unwrap();
    let p = &Provider::new(provider.to_string());
    match Track::find_by(p, identifier) {
        Ok(track) => {
            Ok(Response::with((status::Ok,
                               application_json(),
                               track.to_json().to_string())))
        },
        Err(e) => Ok(e.as_response())
    }
}

pub fn update_track(req: &mut Request) -> IronResult<Response> {
    let mut track = try!(Track::find_by_id(&query_as_string(req, "track_id")));
    match param_as_string(req, "title") {
        Some(title) => track.title = title,
        None        => println!("no title")
    }
    match param_as_string(req, "url") {
        Some(url) => track.url = url,
        None      => println!("no url")
    }
    try!(track.save());
    let res = track.to_json().to_string();
    Ok(Response::with((status::Ok, application_json(), res)))
}

fn param_as_string(req: &mut Request, key: &str) -> Option<String> {
    match req.get_ref::<UrlEncodedBody>() {
        Ok(ref params) => match params.get(key) {
            Some(val) => Some(val[0].clone()),
            None      => None
        },
        Err(_) => None
    }
}

fn query_as_string(req: &mut Request, key: &str) -> String {
    return req.extensions.get::<Router>().unwrap()
        .find(key).unwrap().to_string();
}

fn pagination_params(req: &mut Request) -> (i64, i64) {
    match req.get_ref::<UrlEncodedQuery>() {
        Ok(ref params) =>
            (params.get("page").unwrap()[0].to_string().parse::<i64>().unwrap(),
             params.get("per_page").unwrap()[0].to_string().parse::<i64>().unwrap()),
        Err(_) =>
            (0, 10)
    }
}

fn application_json() -> Mime {
    Mime::from_str("application/json").ok().unwrap()
}

pub fn main() {
    let path = Path::new("public");
    let mut mount = Mount::new();
    mount.mount("/web/", Static::new(Path::new(path)));
    let router = router!(
        playlistify:           get  "/playlistify"              => playlistify,
        show_track_by_id:      get  "/tracks/:track_id"         => show_track_by_id,
        update_track:          post "/tracks/:track_id"         => update_track,
        show_track:            get  "/tracks/:provider/:id"     => show_track,
        index_entries:         get  "/entries"                  => index_entries,
        index_tracks:          get  "/tracks"                   => index_tracks,
        index_tracks_by_entry: get  "/entries/:entry_id/tracks" => index_tracks_by_entry,
        web:                   get  "/*"                        => mount,
    );
    let port_str = match std::env::var("PORT") {
        Ok(n)    => n,
        Err(_) => "8080".to_string()
    };
    let port: u16 = match port_str.trim().parse() {
        Ok(n) => n,
        Err(_) => {
            println!("Faild to parse port");
            return;
        }
    };
    println!("PORT {}", port_str);
    let ip = Ipv4Addr::new(0, 0, 0, 0);
    Iron::new(router).http(SocketAddrV4::new(ip, port)).unwrap();
}
<commit_msg>Update track api also fetches detail properties from third party api<commit_after>extern crate iron;
#[macro_use]
extern crate router;
extern crate staticfile;
extern crate mount;
extern crate urlencoded;
extern crate rustc_serialize;
extern crate html5ever;
extern crate regex;
extern crate uuid;
extern crate chrono;

use std::net::SocketAddrV4;
use std::net::Ipv4Addr;
use std::path::Path;
use iron::prelude::*;
use iron::status;
use iron::mime::Mime;
use staticfile::Static;
use mount::Mount;
use router::{Router};
use urlencoded::UrlEncodedQuery;
use urlencoded::UrlEncodedBody;
use std::str::FromStr;
use uuid::Uuid;

#[macro_use]
extern crate string_cache;
extern crate pink_spider;

use pink_spider::error::Error;
use pink_spider::scraper::extract;
use pink_spider::model::{Track, Entry, Provider, PaginatedCollection};
use rustc_serialize::json::{ToJson, Json};
use pink_spider::youtube;
use pink_spider::soundcloud;

pub fn index_entries(req: &mut Request) -> IronResult<Response> {
    let (page, per_page) = pagination_params(req);
    let entries          = Entry::find(page, per_page);
    let json_obj: Json   = entries.to_json();
    let json_str: String = json_obj.to_string();
    Ok(Response::with((status::Ok, application_json(), json_str)))
}

pub fn index_tracks(req: &mut Request) -> IronResult<Response> {
    let (page, per_page) = pagination_params(req);
    let tracks  = Track::find(page, per_page);
    let json_obj: Json   = tracks.to_json();
    let json_str: String = json_obj.to_string();
    Ok(Response::with((status::Ok, application_json(), json_str)))
}

pub fn index_tracks_by_entry(req: &mut Request) -> IronResult<Response> {
    let ref entry_id = req.extensions.get::<Router>().unwrap().find("entry_id").unwrap();
    let uuid = try!(Uuid::parse_str(entry_id).map_err(|_| Error::Unprocessable));
    let items = Track::find_by_entry_id(uuid);
    let col = PaginatedCollection {
        page:     0,
        per_page: items.len() as i64,
        total:    items.len() as i64,
        items:    items,
    };
    let json_obj: Json   = col.to_json();
    let json_str: String = json_obj.to_string();
    Ok(Response::with((status::Ok, application_json(), json_str)))
}

pub fn playlistify(req: &mut Request) -> IronResult<Response> {
    pub fn playlistify2(req: &mut Request) -> Result<Response, Error> {
        let ref params  = try!(req.get_ref::<UrlEncodedQuery>());
        let url         = try!(params.get("url").ok_or(Error::BadRequest));
        let defaults    = &vec!("false".to_string());
        let force_param = params.get("force").unwrap_or(defaults);
        let force       = force_param.len() > 0 && &force_param[0] == "true";
        let entry       = try!(find_or_playlistify_entry(&url[0], force));
        let json_obj    = entry.to_json() as Json;
        let json_str    = json_obj.to_string() as String;
        Ok(Response::with((status::Ok, application_json(), json_str)))
    }
    playlistify2(req).map_err(|err| IronError::from(err))
}

pub fn find_or_playlistify_entry(url: &str, force: bool) -> Result<Entry, Error> {
    match Entry::find_by_url(url) {
        Ok(entry) => {
            println!("Get entry from database cache: {}", url);
            if force {
                println!("Update entry: {}", url);
                let entry = try!(playlistify_entry(entry));
                Ok(entry)
            } else {
                Ok(entry)
            }
        },
        Err(_) => {
            let entry = try!(Entry::create_by_url(url.to_string()));
            let entry = try!(playlistify_entry(entry));
            println!("Create new entry to database cache: {}", url);
            Ok(entry)
        },
    }
}

pub fn playlistify_entry(entry: Entry) -> Result<Entry, Error> {
    let mut e = entry.clone();
    let product = try!(extract(&entry.url));
    match product.og_obj {
        Some(og_obj) => {
            e.title       = Some(og_obj.title);
            e.description = og_obj.description;
            e.locale      = og_obj.locale;
            e.visual_url  = og_obj.images.first().map(|i| i.url.clone());
        },
        None => (),
    }
    for t in product.tracks {
        let mut track = try!(Track::find_or_create(t.provider, t.identifier.to_string()));
        track.title = t.title;
        let track = match t.provider {
            Provider::YouTube => match youtube::fetch_video(&t.identifier) {
                Ok(video) => track.update_with_yt_video(&video),
                Err(_)    => track.disable(),
            },
            Provider::SoundCloud => match soundcloud::fetch_track(&t.identifier) {
                Ok(sc_track) => track.update_with_sc_track(&sc_track),
                Err(_)       => track.disable(),
            },
            _ => &mut track,
        };
        try!(track.save());
        match entry.tracks.iter().find(|&t| t.id == track.id) {
            Some(_) => (),
            None    => e.add_track(track.clone())
        }
    }
    try!(e.save());
    Ok(e)
}

pub fn show_track_by_id(req: &mut Request) -> IronResult<Response> {
    let ref track_id = req.extensions.get::<Router>().unwrap()
                          .find("track_id").unwrap();
    match Track::find_by_id(track_id) {
        Ok(track) => {
            Ok(Response::with((status::Ok,
                               application_json(),
                               track.to_json().to_string())))
        },
        Err(e) => Ok(e.as_response())
    }
}

pub fn show_track(req: &mut Request) -> IronResult<Response> {
    let provider   = req.extensions.get::<Router>().unwrap().find("provider").unwrap();
    let identifier = req.extensions.get::<Router>().unwrap().find("id").unwrap();
    let p = &Provider::new(provider.to_string());
    match Track::find_by(p, identifier) {
        Ok(track) => {
            Ok(Response::with((status::Ok,
                               application_json(),
                               track.to_json().to_string())))
        },
        Err(e) => Ok(e.as_response())
    }
}

pub fn update_track(req: &mut Request) -> IronResult<Response> {
    let mut track = try!(Track::find_by_id(&query_as_string(req, "track_id")));
    match param_as_string(req, "title") {
        Some(title) => track.title = title,
        None        => (),
    }
    match param_as_string(req, "url") {
        Some(url) => track.url = url,
        None      => (),
    }
    let track = match track.provider {
        Provider::YouTube => match youtube::fetch_video(&track.identifier) {
            Ok(video) => track.update_with_yt_video(&video),
            Err(_)    => track.disable(),
        },
        Provider::SoundCloud => match soundcloud::fetch_track(&track.identifier) {
            Ok(sc_track) => track.update_with_sc_track(&sc_track),
            Err(_)       => track.disable(),
        },
        _ => &mut track,
    };
    try!(track.save());
    let res = track.to_json().to_string();
    Ok(Response::with((status::Ok, application_json(), res)))
}

fn param_as_string(req: &mut Request, key: &str) -> Option<String> {
    match req.get_ref::<UrlEncodedBody>() {
        Ok(ref params) => match params.get(key) {
            Some(val) => Some(val[0].clone()),
            None      => None
        },
        Err(_) => None
    }
}

fn query_as_string(req: &mut Request, key: &str) -> String {
    return req.extensions.get::<Router>().unwrap()
        .find(key).unwrap().to_string();
}

fn pagination_params(req: &mut Request) -> (i64, i64) {
    match req.get_ref::<UrlEncodedQuery>() {
        Ok(ref params) =>
            (params.get("page").unwrap()[0].to_string().parse::<i64>().unwrap(),
             params.get("per_page").unwrap()[0].to_string().parse::<i64>().unwrap()),
        Err(_) =>
            (0, 10)
    }
}

fn application_json() -> Mime {
    Mime::from_str("application/json").ok().unwrap()
}

pub fn main() {
    let path = Path::new("public");
    let mut mount = Mount::new();
    mount.mount("/web/", Static::new(Path::new(path)));
    let router = router!(
        playlistify:           get  "/playlistify"              => playlistify,
        show_track_by_id:      get  "/tracks/:track_id"         => show_track_by_id,
        update_track:          post "/tracks/:track_id"         => update_track,
        show_track:            get  "/tracks/:provider/:id"     => show_track,
        index_entries:         get  "/entries"                  => index_entries,
        index_tracks:          get  "/tracks"                   => index_tracks,
        index_tracks_by_entry: get  "/entries/:entry_id/tracks" => index_tracks_by_entry,
        web:                   get  "/*"                        => mount,
    );
    let port_str = match std::env::var("PORT") {
        Ok(n)    => n,
        Err(_) => "8080".to_string()
    };
    let port: u16 = match port_str.trim().parse() {
        Ok(n) => n,
        Err(_) => {
            println!("Faild to parse port");
            return;
        }
    };
    println!("PORT {}", port_str);
    let ip = Ipv4Addr::new(0, 0, 0, 0);
    Iron::new(router).http(SocketAddrV4::new(ip, port)).unwrap();
}
<|endoftext|>


<commit_before>extern crate jsrs_parser;

mod eval;

use std::io;
use std::collections::HashMap;
use eval::eval_string;

fn main() {
    let mut state = HashMap::new();

    loop {
        // read input
        let mut input = String::new();
        io::stdin().read_line(&mut input).unwrap();
        if input.len() == 0 {
            break;
        }

        println!("{:?}", eval_string(&input, &mut state));
        println!("{:?}", state);
    }
}
<commit_msg>add prompts/labels to interpreter for readability<commit_after>extern crate jsrs_parser;

mod eval;

use std::io::{self, Write};
use std::collections::HashMap;
use eval::eval_string;

fn main() {
    let mut state = HashMap::new();
    let stdin = io::stdin();
    let mut stdout = io::stdout();

    loop {
        // prompt
        print!(">> ");
        stdout.flush().unwrap();

        // read input
        let mut input = String::new();
        stdin.read_line(&mut input).unwrap();
        if input.len() == 0 {
            break;
        }

        println!("=> {:?}", eval_string(&input, &mut state));
        println!("** {:?}", state);
    }
}
<|endoftext|>


<commit_before>#[macro_use]
extern crate clap;
use clap::App;

fn main() {
    let _yaml = load_yaml!("cli.yml");
    let matches = App::from_yaml(_yaml).get_matches();
    if let Some(_) = matches.subcommand_matches("config") {
        let config = configuration::configuration();
        println!("{:?}", config);
    }
}

mod configuration {
    extern crate config;

    use config::{Config, Environment};
    use std::vec::Vec;
    use std::path::{Path, PathBuf};

    #[derive(Debug)]
    pub struct List {
        isbn: bool,
        table: bool
    }

    #[derive(Debug)]
    pub struct Isbndb {
        key: String,
        limit: u8
    }

    #[derive(Debug)]
    pub struct Import {
        hash: bool,
        relocate: bool,
        overwrite: bool,
        prune: bool,
        replacements: Vec<String>
    }

    #[derive(Debug)]
    pub struct Configuration {
        debug: bool,
        directory: PathBuf,
        library: PathBuf,
        import: Import,
        list: List,
        isbndb: Option<Isbndb>
    }

    impl Configuration {
        fn new(backing: Config) -> Configuration {
            Configuration {
                debug: backing.get_bool("debug").ok().unwrap_or(false),
                directory:
                PathBuf::from(backing.get_str("directory")
                              .unwrap_or("~/Books".to_string())),
                library:
                PathBuf::from(backing.get_str("library")
                              .unwrap_or("library.db".to_string())),
                import: Import {
                    hash: backing.get_bool("input.hash")
                        .unwrap_or(false),
                    relocate: backing.get_bool("input.move")
                        .unwrap_or(false),
                    overwrite: backing.get_bool("input.overwrite")
                        .unwrap_or(false),
                    prune: backing.get_bool("input.prune")
                        .unwrap_or(false),
                    replacements: vec![
                        String::from("[<>:\"?*|]"),
                        String::from("[/]"),
                        String::from("[\u{00}-\u{1f}]")
                    ]
                },
                list: List {
                    isbn: false,
                    table: false
                },
                isbndb: None
            }
        }

        pub fn debug(&self) -> bool {
            self.debug
        }

        pub fn library(&self) -> &Path {
            self.library.as_path()
        }
    }

    pub fn configuration() -> Configuration {
        let mut backing = Config::default();
        backing.merge(Environment::with_prefix("ROOTS")
                      .separator("_")).unwrap();
        Configuration {
                debug: backing.get_bool("debug").ok().unwrap_or(false),
                directory:
                PathBuf::from(backing.get_str("directory")
                              .unwrap_or("~/Books".to_string())),
                library:
                PathBuf::from(backing.get_str("library")
                              .unwrap_or("library.db".to_string())),
                import: Import {
                    hash: backing.get_bool("import.hash")
                        .unwrap_or(false),
                    relocate: backing.get_bool("import.move")
                        .unwrap_or(false),
                    overwrite: backing.get_bool("import.overwrite")
                        .unwrap_or(false),
                    prune: backing.get_bool("import.prune")
                        .unwrap_or(false),
                    replacements: vec![
                        String::from("[<>:\"?*|]"),
                        String::from("[/]"),
                        String::from("[\u{00}-\u{1f}]")
                    ]
                },
                list: List {
                    isbn: backing.get_bool("list.isbn").unwrap_or(false),
                    table: backing.get_bool("list.table").unwrap_or(false)
                },
                isbndb: None
            }
    }
}
<commit_msg>implement commands<commit_after>#[macro_use]
extern crate clap;

mod command {
    #[derive(Debug)]
    pub enum Command {
        Config {
            path: bool,
            default: bool
        },
        Fields,
        Import {
            path: String
        },
        List {
            author: bool,
            isbn: bool,
            table: bool
        },
        Update
    }
}

mod interface {

    use clap::{App, AppSettings, Arg, SubCommand};
    use super::command::Command;

    pub fn parse_command_line() -> Command {
        let matches = App::new("root")
            .bin_name("root")
            .version(crate_version!())
            .version_short("v")
            .about("roots e-book manager")
            .setting(AppSettings::VersionlessSubcommands)
            .setting(AppSettings::SubcommandRequiredElseHelp)
            .subcommand(SubCommand::with_name("config")
                        .about("Shows the configuration")
                        .arg(Arg::with_name("path")
                             .short("p")
                             .long("path")
                             .conflicts_with("default")
                             .help("Display the configuration file path"))
                        .arg(Arg::with_name("default")
                             .short("d")
                             .long("default")
                             .conflicts_with("path")
                             .help("Display configuration defaults")))
            .subcommand(SubCommand::with_name("fields")
                        .about("Shows fields that can be used in queries"))
            .subcommand(SubCommand::with_name("import")
                        .about("Imports new e-books")
                        .usage(
"root import <path>

EXAMPLES:
    root import ~/Downloads/
       -> imports books from ~/Downloads/")
                        .arg(Arg::with_name("path")
                             .help("Path to directory containing e-books")
                             .required(true)))
            .subcommand(SubCommand::with_name("list")
                        .about("Queries the library")
                        .usage(
"root list [FLAGS]

EXAMPLES:
    root list author:forster
      -> All titles by Forster

    root list --author howards end
      -> All authors of matching titles

    root list --isbn
      -> All known titles with ISBNs")
                        .arg(Arg::with_name("author")
                             .short("a")
                             .long("author")
                             .help("Show a list of matching authors"))
                        .arg(Arg::with_name("isbn")
                             .short("i")
                             .long("isbn")
                             .help("Show the ISBN number of each title"))
                        .arg(Arg::with_name("table")
                             .short("t")
                             .long("table")
                             .help("Print the matches in a table")))
            .subcommand(SubCommand::with_name("update")
                        .about("Updates the library"))
            .get_matches();
        match matches.subcommand() {
            ("config", Some(config)) => {
                Command::Config {
                    path: config.is_present("path"),
                    default: config.is_present("default")
                }
            },
            ("fields", _) => {
                Command::Fields
            },
            ("import", Some(import)) => {
                Command::Import {
                    path: import.value_of("path")
                        .map(|v| String::from(v))
                        .unwrap()
                }
            },
            ("list", Some(list)) => {
                Command::List {
                    author: list.is_present("author"),
                    isbn: list.is_present("isbn"),
                    table: list.is_present("table")
                }
            },
            ("update", _) => {
                Command::Update
            }
            _ => unreachable!()
        }
    }
}

mod configuration {
    extern crate config;

    use config::{Config, Environment};
    use std::vec::Vec;
    use std::path::PathBuf;

    #[derive(Debug)]
    struct List {
        isbn: bool,
        table: bool
    }

    #[derive(Debug)]
    struct Isbndb {
        key: String,
        limit: u8
    }

    #[derive(Debug)]
    struct Import {
        hash: bool,
        relocate: bool,
        overwrite: bool,
        prune: bool,
        replacements: Vec<String>
    }

    #[derive(Debug)]
    pub struct Configuration {
        debug: bool,
        directory: PathBuf,
        library: PathBuf,
        import: Import,
        list: List,
        isbndb: Option<Isbndb>
    }

    pub fn configuration() -> Configuration {
        let mut backing = Config::default();
        backing.merge(Environment::with_prefix("ROOTS")
                      .separator("_")).unwrap();
        Configuration {
                debug: backing.get_bool("debug").ok().unwrap_or(false),
                directory:
                PathBuf::from(backing.get_str("directory")
                              .unwrap_or("~/Books".to_string())),
                library:
                PathBuf::from(backing.get_str("library")
                              .unwrap_or("library.db".to_string())),
                import: Import {
                    hash: backing.get_bool("import.hash")
                        .unwrap_or(false),
                    relocate: backing.get_bool("import.move")
                        .unwrap_or(false),
                    overwrite: backing.get_bool("import.overwrite")
                        .unwrap_or(false),
                    prune: backing.get_bool("import.prune")
                        .unwrap_or(false),
                    replacements: vec![
                        String::from("[<>:\"?*|]"),
                        String::from("[/]"),
                        String::from("[\u{00}-\u{1f}]")
                    ]
                },
                list: List {
                    isbn: backing.get_bool("list.isbn").unwrap_or(false),
                    table: backing.get_bool("list.table").unwrap_or(false)
                },
                isbndb: None
            }
    }
}

fn main() {
    let env = configuration::configuration();
    let cmd = interface::parse_command_line();
    match cmd {
        command::Command::Config{path, ..} =>
            if path {
                println!("pooping today")
            } else {
                println!("not pooping today")
            }
        _ => println!("no poop ever")
    }
    println!("{:?}", cmd);
    println!("{:?}", env)
}
<|endoftext|>


<commit_before>extern crate chrono;

pub mod location;
pub mod temperature;
pub mod model;

pub use location::{Location, GpsCoordinates};
use model::ModelParams;
use chrono::*;
use std::io::{self, Read, Write, BufRead};

fn flush() {
    io::stdout().flush().unwrap();
}

fn main() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();

    // User input.

    println!("==== PARAMÈTRES D'ENTRÉE ====");
    print!("latitude (en degrés) : ");
    flush();
    let lat: f64 = lines.next().unwrap().unwrap().parse().unwrap();

    print!("longitude (en degrés) : ");
    flush();
    let long: f64 = lines.next().unwrap().unwrap().parse().unwrap();

    print!("date et heure locale (e.g. \"28/11/2016 21:00:09 +09:00\"): ");
    flush();

    let local_time_string = lines.next().unwrap().unwrap();
    println!("");

    // Model.

    let local_time = DateTime::parse_from_str(&local_time_string, "%d/%m/%Y %H:%M:%S %z").unwrap();

    let coords = GpsCoordinates {
        lat: lat,
        long: long,
    };

    let input = ModelParams {
        coords: coords,
        date_time: local_time,
    };

    let start = Local::now();
    let irradiance: f64 = model::irradiance(input);
    let duration = Local::now() - start;

    print!("\n");
    println!("==== RÉSULTAT ====");

    println!("l'irradiance est de {:.2} watts par mètre carré (calculée en {} µs)",
             irradiance,
             duration.num_microseconds().unwrap());
}
<commit_msg>fix warning<commit_after>extern crate chrono;

pub mod location;
pub mod temperature;
pub mod model;

pub use location::{Location, GpsCoordinates};
use model::ModelParams;
use chrono::*;
use std::io::{self, Write, BufRead};

fn flush() {
    io::stdout().flush().unwrap();
}

fn main() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();

    // User input.

    println!("==== PARAMÈTRES D'ENTRÉE ====");
    print!("latitude (en degrés) : ");
    flush();
    let lat: f64 = lines.next().unwrap().unwrap().parse().unwrap();

    print!("longitude (en degrés) : ");
    flush();
    let long: f64 = lines.next().unwrap().unwrap().parse().unwrap();

    print!("date et heure locale (e.g. \"28/11/2016 21:00:09 +09:00\"): ");
    flush();

    let local_time_string = lines.next().unwrap().unwrap();
    println!("");

    // Model.

    let local_time = DateTime::parse_from_str(&local_time_string, "%d/%m/%Y %H:%M:%S %z").unwrap();

    let coords = GpsCoordinates {
        lat: lat,
        long: long,
    };

    let input = ModelParams {
        coords: coords,
        date_time: local_time,
    };

    let start = Local::now();
    let irradiance: f64 = model::irradiance(input);
    let duration = Local::now() - start;

    print!("\n");
    println!("==== RÉSULTAT ====");

    println!("l'irradiance est de {:.2} watts par mètre carré (calculée en {} µs)",
             irradiance,
             duration.num_microseconds().unwrap());
}
<|endoftext|>


<commit_before>fn main() {
    println!("Hello, world!");
}
<commit_msg>Add functions to load dataset<commit_after>use std::string::String;
use std::collections::HashMap;
use std::vec::Vec;
use std::fs::{File};
use std::env;
use std::path::{Path};
use std::io::{self, BufReader, BufRead};

type Bag = HashMap<usize, usize>;

fn load_bags<P: AsRef<Path>>(path: P) -> io::Result<(Vec<usize>, Vec<Bag>)> {
    let mut bags = Vec::new();
    let mut labels = Vec::new();
    let file = try!(File::open(path));
    let file = BufReader::new(file);
    for line in file.lines() {
        let line = line.unwrap();
        let mut iter = line.split_whitespace();
        let label = iter.next().unwrap().parse::<usize>().unwrap();
        let mut bag = Bag::new();
        for elm in iter {
            let mut iter = elm.split(':');
            let index = iter.next().unwrap().parse::<usize>().unwrap();
            let value = iter.next().unwrap().parse::<usize>().unwrap();
            bag.insert(index, value);
        }
        labels.push(label);
        bags.push(bag);
    }
    Ok((labels, bags))
}

fn load_text_vocabulary<P: AsRef<Path>>(path: P) -> io::Result<Vec<String>> {
    let mut vocab = Vec::new();
    let file = try!(File::open(path));
    let file = BufReader::new(file);
    for line in file.lines() {
        let line = line.unwrap();
        vocab.push(line);
    }
    Ok(vocab)
}

fn main() {
    let args: Vec<String> = env::args().collect();
    let (labels, dataset) = load_bags(&args[1]).unwrap();
    let vocab: Option<Vec<String>> = if args.len() < 3 {
        None
    }
    else {
        Some(load_text_vocabulary(&args[2]).unwrap())
    };
    println!("{:?}", labels);
    println!("{:?}", dataset);
    println!("{:?}", vocab);
}
<|endoftext|>


<commit_before>#![feature(non_ascii_idents)]
// use variable names from paper, namely registers M
#![allow(non_snake_case)]

mod hll;

fn main() {
    let mut x = hll::HLL::ctor(0.13);

    x.insert("foo");
    println!("{}", x.count());
}
<commit_msg>explain myself<commit_after>// use the literal ρ character rather than copping out with
// a variable named 'rho'
#![feature(non_ascii_idents)]
// use variable names from paper, namely registers M
#![allow(non_snake_case)]

mod hll;

fn main() {
    let mut x = hll::HLL::ctor(0.13);

    x.insert("foo");
    println!("{}", x.count());
}
<|endoftext|>


<commit_before>use std::net::TcpStream;
use std::io::prelude::*;
use std::thread;
use std::str;
use std::sync::mpsc::channel;

const COMMAND_BUF_SIZE: usize = 4096;
struct IrcMessage {
	msg: [u8; COMMAND_BUF_SIZE],
	length: usize,
}

fn main() {
	let connection_result = TcpStream::connect("127.0.0.1:6667");
	if connection_result.is_err() {
		return;
	}

	let connection = connection_result.unwrap();
	let (tx, rx) = channel::<IrcMessage>();
	let mut write_conn = connection.try_clone().unwrap();
	thread::spawn(move || {
		loop {
			let write_data = rx.recv().unwrap();
			let _ = write_conn.write(&write_data.msg[0..write_data.length]);
		}
	});

	let mut bytes = connection.bytes();
	let mut command_buf: [u8; COMMAND_BUF_SIZE] = [0; COMMAND_BUF_SIZE];
	let mut buf_ind = 0;
	let mut command_end = false;
	loop {
		match bytes.next() {
			Some(x) => {
				if x.is_err() {
					break;
				}
				let next_char = x.unwrap();
				command_buf[buf_ind] = next_char;
				buf_ind = buf_ind + 1;
				if command_end && next_char == 10 {
					tx.send(IrcMessage { msg: command_buf, length: buf_ind }).unwrap();
					parse_command(&command_buf[0..(buf_ind-2)]);
					buf_ind = 0;
					command_end = false;
				} else if next_char == 102 {
					command_end = true;
				} else {
					command_end = false;
				}

				if buf_ind >= COMMAND_BUF_SIZE {
					buf_ind = 0;
				}
			},
			None => break,
		}
	}
}

fn parse_command(command: &[u8]) {
	let command_str = str::from_utf8(command);
	if command_str.is_err() {
		return;
	}
	println!("{}", command_str.unwrap());
}
<commit_msg>Move Irc reading and writing to structs<commit_after>use std::net::TcpStream;
use std::io;
use std::io::prelude::*;
use std::thread;
use std::str;

const COMMAND_BUF_SIZE: usize = 4096;

struct IrcMessage {
	msg: [u8; COMMAND_BUF_SIZE],
	length: usize,
}

struct IrcReader {
	stream: TcpStream,

}

impl IrcReader {
	pub fn new(base_stream: &TcpStream) -> std::io::Result<IrcReader> {
		let stream = try!(base_stream.try_clone());
		Ok(IrcReader {
			stream: stream,
		})
	}
}

impl Iterator for IrcReader {
	type Item = IrcMessage;
	fn next(&mut self) -> Option<IrcMessage> {
		let mut command_buf: [u8; COMMAND_BUF_SIZE] = [0; COMMAND_BUF_SIZE];
		let mut buf_ind = 0;
		let mut command_end = false;
		let stream = &self.stream;
		let mut bytes = stream.bytes();
		loop {
			match bytes.next() {
				Some(x) => {
					if x.is_err() {
						return None;
					}
					let next_char = x.unwrap();
					command_buf[buf_ind] = next_char;
					buf_ind = buf_ind + 1;
					if command_end && next_char == 10 {
						return Some(IrcMessage { msg: command_buf, length: buf_ind - 2 });
					} else if next_char == 102 {
						command_end = true;
					} else {
						command_end = false;
					}

					if buf_ind >= COMMAND_BUF_SIZE {
						buf_ind = 0;
					}

				},
				None => {
					return None;
				}
			}
		}
	}
}

struct IrcWriter {
	stream: TcpStream,
}

impl IrcWriter {
	pub fn new(base_stream: &TcpStream) -> std::io::Result<IrcWriter> {
		let stream = try!(base_stream.try_clone());
		Ok(IrcWriter {
			stream: stream,
		})
	}

	pub fn write(&mut self, bytes: &[u8]) {
		let _ = &self.stream.write(&bytes);
	}
}

fn main() {
	let connection_result = TcpStream::connect("127.0.0.1:6667");
	if connection_result.is_err() {
		return;
	}

	let connection = connection_result.unwrap();
	let reader = IrcReader::new(&connection).unwrap();
	let mut writer = IrcWriter::new(&connection).unwrap();

	thread::spawn(move || {
		let mut stdin = io::stdin();
		let mut buf = String::new();
		loop {
			let _= stdin.read_line(&mut buf).unwrap();
			writer.write(&buf.as_bytes());
		}
	});

	for irc_msg in reader {
		parse_command(&irc_msg.msg[0..irc_msg.length]);
	}
}

fn parse_command(command: &[u8]) {
	let command_str = str::from_utf8(command);
	if command_str.is_err() {
		return;
	}
	println!("{}", command_str.unwrap());
}
<|endoftext|>