<commit_before>extern crate futures;
extern crate tokio_core;
extern crate tokio_proto;
extern crate tokio_service;
extern crate uuid;
extern crate clap;
extern crate es_proto;

use std::io;
use std::net::SocketAddr;
use std::thread;
use std::process;
use uuid::Uuid;

use futures::{Future, IntoFuture, Stream, Sink};
use futures::future::{BoxFuture, Either};
use tokio_core::reactor::{Core, Handle};
use tokio_service::Service;
use futures::sync::{oneshot, mpsc};

use clap::{Arg, App, SubCommand};

use es_proto::{EventStoreClient, Package, Message, Builder, ExpectedVersion, StreamVersion, UsernamePassword};

fn main() {

    let matches = App::new("test-client")
        .version("0.1.0")
        .about("Test client similar to EventStore.TestClient in EventStore binary distribution")
        .arg(Arg::with_name("hostname")
                .short("h")
                .long("host")
                .value_name("HOST")
                .takes_value(true)
                .help("The name of the host to connect to, default: 127.0.0.1"))
        .arg(Arg::with_name("port")
                .short("p")
                .long("port")
                .value_name("PORT")
                .takes_value(true)
                .help("The port to connect to, default: 1113"))
        .subcommand(SubCommand::with_name("ping")
                        .about("Send a ping to the host after possibly authenticating depending on the options"))
        .subcommand(SubCommand::with_name("write")
                        .about("Write single event to a given stream")
                        .arg(Arg::with_name("stream_id")
                                .value_name("STREAM-ID")
                                .required(true)
                                .index(1))
                        .arg(Arg::with_name("expected_version")
                                .value_name("EXPECTED_VERSION")
                                .required(true)
                                .index(2)
                                .help("Acceptable values: any|created|n where n >= -2"))
                        .arg(Arg::with_name("data")
                                .value_name("DATA")
                                .required(true)
                                .index(3)
                                .help("Raw bytes of data."))
                        .arg(Arg::with_name("metadata")
                                .value_name("METADATA")
                                .required(false)
                                .index(4)
                                .help("Raw bytes of metadata, optional."))
                        .arg(Arg::with_name("json")
                                .short("j")
                                .long("json")
                                .takes_value(false)
                                .help("Flags the data and metadata (when given) as json values"))
                        .arg(Arg::with_name("type")
                                .short("t")
                                .long("type")
                                .value_name("TYPE")
                                .takes_value(true)
                                .help("Marks the data as being of given type, required if data is json")))
        .get_matches();

    let addr = {
        let s = format!("{}:{}", matches.value_of("HOST").unwrap_or("127.0.0.1"), matches.value_of("PORT").unwrap_or("1113"));
        s.parse::<SocketAddr>().expect("Failed to parse host:port as SocketAddr")
    };

    let res = if let Some(_) = matches.subcommand_matches("ping") {
        ping(addr)
    } else if let Some(write) = matches.subcommand_matches("write") {
        unimplemented!()
    } else {
        println!("Subcommand is required.\n\n{}", matches.usage());
        process::exit(1);
    };

    /*
    let mut core = Core::new().unwrap();
    let handle = core.handle();

    let client = EventStoreClient::connect(&addr, &handle);

    let job = client.and_then(|client| {
        println!("connected!");
        let nak_auth = client.call(
            Builder::authenticate().build_package(Some(UsernamePassword::new("asdfasfdasf", "asdfasdffsa")), None)
        ).and_then(|resp| {
            assert_eq!(resp.message, Message::NotAuthenticated);
            Ok(())
        });

        let write_events = client.call(
            Builder::write_events()
                .stream_id("foobar")
                .expected_version(ExpectedVersion::Exact(StreamVersion::from_opt(3).unwrap()))
                .new_event()
                    .event_type("test_event")
                    .data(vec![0xaa, 0xbb, 0xcc, 0xdd])
                    .done()
                .new_event()
                    .event_type("test_other")
                    .data(b"{ \"json-example\": true }".into_iter().cloned().collect::<Vec<u8>>())
                    .done()
                .build_package(Some(UsernamePassword::new("admin", "changeit")), None))
            .and_then(|resp| {
                match resp.message {
                    Message::WriteEventsCompleted(Ok(ref x)) => println!("success: {:?}", x),
                    Message::WriteEventsCompleted(Err(ref x)) => println!("failure: {:?}", x),
                    Message::NotAuthenticated => println!("need to authenticate"),
                    y => println!("unexpected: {:?}", y)
                }
                Ok(())
            });

        nak_auth.join(write_events)
    });

    core.run(job).unwrap();
    */
}

fn ping(addr: SocketAddr) -> Result<(), io::Error> {
    use std::time::Instant;

    let mut core = Core::new().unwrap();
    let handle = core.handle();

    let started = Instant::now();

    let job = EventStoreClient::connect(&addr, &handle)
        .map(|client| (client, Instant::now()))
        .and_then(|(client, connected)| {

            let f = client.call(Builder::ping().build_package(None, None));
            let send_began = Instant::now();

            f.map(move |resp| (resp, connected, send_began))
        }).and_then(|(pong, connected, send_began)| {
            let received = Instant::now();
            match pong.message {
                Message::Pong => Ok((connected, send_began, received)),
                msg => Err(io::Error::new(io::ErrorKind::Other, format!("Unexpected response: {:?}", msg)))
            }
        }).and_then(move |(connected, send_began, received)| {
            let conn_in = connected - started;
            let send_began_in = send_began - connected;
            let rx_in = received - send_began;

            print_elapsed("connected in  ", conn_in);
            print_elapsed("ready to send ", send_began_in);
            print_elapsed("received in   ", rx_in);
            print_elapsed("total         ", started.elapsed());

            Ok(())
        });

    core.run(job)
}

use std::time::Duration;

fn print_elapsed(subject: &str, d: Duration) {
    println!("{} {}.{:06}ms", subject, d.as_secs() * 1000 + d.subsec_nanos() as u64 / 1_000_000, d.subsec_nanos() % 1_000_000);
}

/*
fn nice(addr: &SocketAddr, handle: &Handle) {
    let client = EventStoreClient::connect(&addr, &handle);
    client.and_then(|client| {

    });
}*/

/*
struct Client {
    tx: mpsc::Sender<(Package, oneshot::Sender<Result<Package, io::Error>>)>,
}

impl Client {
    fn new(addr: &SocketAddr, handle: &Handle) -> Client {
        let (tx, rx) = mpsc::channel::<(Package, oneshot::Sender<Result<Package, io::Error>>)>(4);
        let client = EventStoreClient::connect(addr, handle);
        let task = client.and_then(move |client| {
            rx.for_each(move |(pkg, tx)| {
                client.call(pkg).then(|res| {
                    let ret = match res {
                        Ok(_) => Ok(()),
                        Err(_) => Err(())
                    };
                    tx.complete(res);
                    ret
                })
            }).map_err(|_| io::Error::new(io::ErrorKind::Other, "dunno?"))
        });
        handle.spawn(task.then(|res| match res { Ok(_) => Ok(()), Err(_) => Err(()) }));
        Client { tx: tx }
    }

    fn call(&self, msg: Message) -> MessageFuture {
        let (tx, rx) = oneshot::channel();

        self.tx.send(());
    }
}*/

// connecting
// ready
// heartbeat
// disconnected
<commit_msg>main: add write command<commit_after>extern crate futures;
extern crate tokio_core;
extern crate tokio_proto;
extern crate tokio_service;
extern crate uuid;
extern crate clap;
extern crate es_proto;

use std::io;
use std::net::SocketAddr;
use std::thread;
use std::process;
use uuid::Uuid;

use futures::{Future, IntoFuture, Stream, Sink};
use futures::future::{BoxFuture, Either};
use tokio_core::reactor::{Core, Handle};
use tokio_service::Service;
use futures::sync::{oneshot, mpsc};

use clap::{Arg, App, SubCommand};

use es_proto::{EventStoreClient, Package, Message, Builder, ExpectedVersion, StreamVersion, UsernamePassword};

fn main() {

    let matches = App::new("testclient")
        .version("0.1.0")
        .about("Test client similar to EventStore.TestClient in EventStore binary distribution")
        .arg(Arg::with_name("hostname")
                .short("h")
                .long("host")
                .value_name("HOST")
                .takes_value(true)
                .help("The name of the host to connect to, default: 127.0.0.1"))
        .arg(Arg::with_name("port")
                .short("p")
                .long("port")
                .value_name("PORT")
                .takes_value(true)
                .help("The port to connect to, default: 1113"))
        .arg(Arg::with_name("verbose")
                 .short("v")
                 .long("verbose")
                 .takes_value(false)
                 .help("Output verbose timings"))
        .subcommand(SubCommand::with_name("ping")
                        .about("Send a ping to the host after possibly authenticating depending on the options"))
        .subcommand(SubCommand::with_name("write")
                        .about("Write single event to a given stream")
                        .arg(Arg::with_name("stream_id")
                                .value_name("STREAM-ID")
                                .required(true)
                                .index(1)
                                .help("Stream id to write to"))
                        .arg(Arg::with_name("expected_version")
                                .value_name("EXPECTED_VERSION")
                                .required(true)
                                .index(2)
                                .help("Acceptable values: any|created|n where n >= -2"))
                        .arg(Arg::with_name("type")
                                .value_name("TYPE")
                                .required(true)
                                .index(3)
                                .help("Type name of the event"))
                        .arg(Arg::with_name("data")
                                .value_name("DATA")
                                .required(true)
                                .index(4)
                                .help("Raw bytes of data."))
                        .arg(Arg::with_name("metadata")
                                .value_name("METADATA")
                                .required(false)
                                .index(5)
                                .help("Raw bytes of metadata, optional"))
                        .arg(Arg::with_name("json")
                                .short("j")
                                .long("json")
                                .takes_value(false)
                                .help("Flags the data and metadata (when given) as json values")))
        .get_matches();

    let addr = {
        let s = format!("{}:{}", matches.value_of("hostname").unwrap_or("127.0.0.1"), matches.value_of("port").unwrap_or("1113"));
        s.parse::<SocketAddr>().expect("Failed to parse host:port as SocketAddr")
    };

    let verbose = matches.is_present("verbose");

    let res = if let Some(matches) = matches.subcommand_matches("ping") {
        ping(addr, verbose)
    } else if let Some(w) = matches.subcommand_matches("write") {

        let mut builder = Builder::write_events();
        builder.stream_id(w.value_of("stream_id").unwrap().to_owned())
            .expected_version(match w.value_of("expected_version").unwrap() {
                "any" => ExpectedVersion::Any,
                "created" => ExpectedVersion::NewStream,
                n => ExpectedVersion::Exact(StreamVersion::from_opt(n.parse().unwrap()).expect("Stream version out of bounds"))
            })
            .require_master(w.is_present("require_master"));

        {
            let mut event = builder.new_event();

            event = event.data(w.value_of("data").unwrap().as_bytes().iter().cloned().collect::<Vec<_>>())
                .data_content_type(w.is_present("json"))
                .event_type(w.value_of("type").unwrap().to_owned());

            event = if let Some(x) = w.value_of("metadata") {
                event.metadata(x.as_bytes().iter().cloned().collect::<Vec<_>>())
                    .metadata_content_type(w.is_present("json"))
            } else {
                event
            };

            event.done();
        }

        write(addr, verbose, builder.build_package(None, None))
    } else {
        println!("Subcommand is required.\n\n{}", matches.usage());
        process::exit(1);
    };

    if let Err(e) = res {
        println!("Failure: {:?}", e);
        process::exit(1);
    }
}

use std::time::Instant;

fn ping(addr: SocketAddr, verbose: bool) -> Result<(), io::Error> {
    let mut core = Core::new().unwrap();
    let handle = core.handle();

    let started = Instant::now();

    let job = EventStoreClient::connect(&addr, &handle)
        .map(|client| (client, Instant::now()))
        .and_then(|(client, connected)| {

            let f = client.call(Builder::ping().build_package(None, None));
            let send_began = Instant::now();

            f.map(move |resp| (resp, connected, send_began))
        }).and_then(|(pong, connected, send_began)| {
            let received = Instant::now();
            match pong.message {
                Message::Pong => Ok((connected, send_began, received)),
                msg => Err(io::Error::new(io::ErrorKind::Other, format!("Unexpected response: {:?}", msg)))
            }
        }).and_then(move |(connected, send_began, received)| {
            if verbose {
                print_elapsed("connected in  ", connected - started);
                print_elapsed("ready to send ", send_began - connected);
                print_elapsed("received in   ", received - send_began);
                print_elapsed("total         ", started.elapsed());
            } else {
                print_elapsed("pong received in", started.elapsed());
            }

            Ok(())
        });

    core.run(job)
}

fn write(addr: SocketAddr, verbose: bool, pkg: Package) -> Result<(), io::Error> {
    let mut core = Core::new().unwrap();
    let handle = core.handle();

    let client = EventStoreClient::connect(&addr, &handle);
    let started = Instant::now();

    let job = client.and_then(|client| {
        client.call(pkg)
    }).and_then(|resp| {
        match resp.message {
            Message::WriteEventsCompleted(Ok(success)) => {
                print_elapsed("Success in", started.elapsed());
                if verbose {
                    println!("{:#?}", success);
                }
                Ok(())
            },
            Message::WriteEventsCompleted(Err(reason)) => {
                Err(io::Error::new(io::ErrorKind::Other, format!("Writing failed: {:?}", reason)))
            },
            x => {
                Err(io::Error::new(io::ErrorKind::Other, format!("Unexpected response: {:?}", x)))
            }
        }
    });

    core.run(job)
}

use std::time::Duration;

fn print_elapsed(subject: &str, d: Duration) {
    println!("{} {}.{:06}ms", subject, d.as_secs() * 1000 + d.subsec_nanos() as u64 / 1_000_000, d.subsec_nanos() % 1_000_000);
}

/*
fn nice(addr: &SocketAddr, handle: &Handle) {
    let client = EventStoreClient::connect(&addr, &handle);
    client.and_then(|client| {

    });
}*/

/*
struct Client {
    tx: mpsc::Sender<(Package, oneshot::Sender<Result<Package, io::Error>>)>,
}

impl Client {
    fn new(addr: &SocketAddr, handle: &Handle) -> Client {
        let (tx, rx) = mpsc::channel::<(Package, oneshot::Sender<Result<Package, io::Error>>)>(4);
        let client = EventStoreClient::connect(addr, handle);
        let task = client.and_then(move |client| {
            rx.for_each(move |(pkg, tx)| {
                client.call(pkg).then(|res| {
                    let ret = match res {
                        Ok(_) => Ok(()),
                        Err(_) => Err(())
                    };
                    tx.complete(res);
                    ret
                })
            }).map_err(|_| io::Error::new(io::ErrorKind::Other, "dunno?"))
        });
        handle.spawn(task.then(|res| match res { Ok(_) => Ok(()), Err(_) => Err(()) }));
        Client { tx: tx }
    }

    fn call(&self, msg: Message) -> MessageFuture {
        let (tx, rx) = oneshot::channel();

        self.tx.send(());
    }
}*/

// connecting
// ready
// heartbeat
// disconnected
<|endoftext|>


<commit_before>extern crate ansi_term;
#[macro_use]
extern crate clap;
extern crate hyper;
extern crate libzou;
extern crate num_cpus;

use clap::{App, Arg};
use libzou::cargo_helper::get_cargo_info;
use libzou::download::download_chunks;
use libzou::filesize::format_filesize;
use libzou::util::prompt_user;
use libzou::write::OutputFileWriter;
#[macro_use]
mod logs;
use std::fs::{File, remove_file};
use std::path::Path;
use std::process::exit;

static DEFAULT_FILENAME: &'static str = "index.html";

fn main() {

    // Parse arguments

    let argparse = App::new("Zou")
        .about("Zou, a simple and fast download accelerator, written in Rust.")
        .version(crate_version!())
        .arg(Arg::with_name("file")
                 .long("file")
                 .short("f")
                 .takes_value(true)
                 .help("The local file to save the remote content file"))
        .arg(Arg::with_name("threads")
                 .long("threads")
                 .short("t")
                 .takes_value(true)
                 .help("Threads which can use to download"))
        .arg(Arg::with_name("debug")
                 .long("debug")
                 .short("d")
                 .help("Active the debug mode"))
        .arg(Arg::with_name("force")
                 .long("force")
                 .help("Assume Yes to all queries and do not prompt"))
        .arg(Arg::with_name("url")
            .index(1)
            //.multiple(true)
            .required(true))
        .get_matches();

    // Get informations from arguments

    let url = argparse.value_of("url").unwrap();

    let file = argparse
        .value_of("file")
        .unwrap_or_else(|| url.split('/').last().unwrap_or(DEFAULT_FILENAME));

    // Check if multi-threaded download is possible
    let mut threads: usize = value_t!(argparse, "threads", usize)
        .and_then(|v| if v != 0 {
                      Ok(v)
                  } else {
                      Err(clap::Error::with_description("Cannot download a file using 0 thread",
                                                        clap::ErrorKind::InvalidValue))
                  })
        .unwrap_or(num_cpus::get_physical());

    if argparse.is_present("debug") {
        info!(&format!("version: {}", crate_version!()));
        info!(&format!("file: {}", file));
        info!(&format!("threads: {}", threads));
    }

    let local_path = Path::new(&file);

    if local_path.exists() {
        if local_path.is_dir() {
            epanic!("The local path to store the remote content is already exists, \
                        and is a directory!");
        }
        if !argparse.is_present("force") {
            let user_input = prompt_user("The path to store the file already exists! \
                                          Do you want to override it? [y/N]");
            if !(user_input == "y" || user_input == "Y") {
                exit(0);
            }
        } else {
            warning!("The path to store the file already exists! \
                                 It is going to be overriden.");
        }
    }

    let cargo_info = get_cargo_info(&url).expect("fail to parse url");
    info!(&format!("# Remote content length: {}",
                   format_filesize(cargo_info.content_length)));

    let local_file = File::create(local_path).expect("[ERROR] Cannot create a file !");

    local_file
        .set_len(cargo_info.content_length)
        .expect("Cannot extend file to download size!");
    let out_file = OutputFileWriter::new(local_file);

    // If the server does not accept PartialContent status, download the remote file
    // using only one thread
    if !cargo_info.accept_partialcontent {
        warning!("The remote server does not accept PartialContent status! \
                             Downloading the remote file using one thread.");
        threads = 1;
    }

    if download_chunks(cargo_info, out_file, threads as u64, &url) {
        ok!(&format!("Your download is available in {}",
                     local_path.to_str().unwrap()));
    } else {
        // If the file is not ok, delete it from the file system
        error!("Download failed! An error occured - erasing file... ");
        if remove_file(local_path).is_err() {
            error!("Cannot remove downloaded file!");
        }
    }

}
<commit_msg>Get mirrors list to bench' them<commit_after>extern crate ansi_term;
#[macro_use]
extern crate clap;
extern crate hyper;
extern crate libzou;
extern crate num_cpus;

use clap::{App, Arg};
use libzou::cargo_helper::get_cargo_info;
use libzou::download::download_chunks;
use libzou::filesize::format_filesize;
use libzou::util::prompt_user;
use libzou::write::OutputFileWriter;
#[macro_use]
mod logs;
use std::fs::{File, remove_file};
use std::path::Path;
use std::process::exit;

static DEFAULT_FILENAME: &'static str = "index.html";

fn main() {

    // Parse arguments

    let argparse = App::new("Zou")
        .about("Zou, a simple and fast download accelerator, written in Rust.")
        .version(crate_version!())
        .arg(Arg::with_name("file")
                 .long("file")
                 .short("f")
                 .takes_value(true)
                 .help("The local file to save the remote content file"))
        .arg(Arg::with_name("threads")
                 .long("threads")
                 .short("t")
                 .takes_value(true)
                 .help("Threads which can use to download"))
        .arg(Arg::with_name("debug")
                 .long("debug")
                 .short("d")
                 .help("Active the debug mode"))
        .arg(Arg::with_name("force")
                 .long("force")
                 .help("Assume Yes to all queries and do not prompt"))
        .arg(Arg::with_name("mirrors")
                 .long("mirrors")
                 .short("m")
                 .multiple(true)
                 .takes_value(true)
                 .help("Download using a list of mirrors - the list of mirrors is used WITH the original URL"))
        .arg(Arg::with_name("url")
            .index(1)
            //.multiple(true)
            .required(true))
        .get_matches();

    // Get informations from arguments

    let url = argparse.value_of("url").unwrap();

    let filename: &str = argparse
        .value_of("file")
        .unwrap_or_else(|| url.split('/').last().unwrap_or(DEFAULT_FILENAME));

    let mirrors: Option<Vec<&str>> = if !argparse.is_present("mirrors") {
        None
    } else {
        Some(argparse.values_of("mirrors").unwrap().collect())
    };

    // Check if multi-threaded download is possible
    let mut threads: usize = value_t!(argparse, "threads", usize)
        .and_then(|v| if v != 0 {
                      Ok(v)
                  } else {
                      Err(clap::Error::with_description("Cannot download a file using 0 thread",
                                                        clap::ErrorKind::InvalidValue))
                  })
        .unwrap_or(num_cpus::get_physical());

    if argparse.is_present("debug") {
        info!(&format!("version: {}", crate_version!()));
        info!(&format!("file: {}", filename));
        info!(&format!("threads: {}", threads));
    }

    let local_path = Path::new(&filename);

    if local_path.exists() {
        if local_path.is_dir() {
            epanic!("The local path to store the remote content is already exists, \
                        and is a directory!");
        }
        if !argparse.is_present("force") {
            let user_input = prompt_user("The path to store the file already exists! \
                                          Do you want to override it? [y/N]");
            if !(user_input == "y" || user_input == "Y") {
                exit(0);
            }
        } else {
            warning!("The path to store the file already exists! \
                                 It is going to be overriden.");
        }
    }

    let cargo_info = get_cargo_info(&url, mirrors).expect("fail to parse url");
    info!(&format!("Remote content length: {}",
                   format_filesize(cargo_info.content_length)));

    let local_file = File::create(local_path).expect("[ERROR] Cannot create a file !");

    local_file
        .set_len(cargo_info.content_length)
        .expect("Cannot extend local file !");
    let out_file = OutputFileWriter::new(local_file);

    // If the server does not accept PartialContent status, download the remote file
    // using only one thread
    if !cargo_info.accept_partialcontent {
        warning!("The remote server does not accept PartialContent status! \
                             Downloading the remote file using one thread.");
        threads = 1;
    }

    if download_chunks(cargo_info, out_file, threads as u64, &url) {
        ok!(&format!("Your download is available in {}",
                     local_path.to_str().unwrap()));
    } else {
        // If the file is not ok, delete it from the file system
        error!("Download failed! An error occured - erasing file... ");
        if remove_file(local_path).is_err() {
            error!("Cannot remove downloaded file!");
        }
    }

}
<|endoftext|>


<commit_before>use structopt::StructOpt;

#[derive(StructOpt)]
#[structopt(name = "gear", about = "A developer QOL tool")]
enum Gear {
    #[structopt(name = "run", about = "Run user-defined commands")]
    Run {
        #[structopt(help = "Name of command to run")]
        command: String,
        #[structopt(help = "Optional arguments to pass to the command")]
        args: Vec<String>,
    },
}

fn main() {
    let program = Gear::from_args();
}
<commit_msg>main match arm<commit_after>use structopt::StructOpt;

#[derive(StructOpt)]
#[structopt(name = "gear", about = "A developer QOL tool")]
enum Gear {
    #[structopt(name = "run", about = "Run user-defined commands")]
    Run {
        #[structopt(help = "Name of command to run")]
        command: String,
        #[structopt(help = "Optional arguments to pass to the command")]
        args: Vec<String>,
    },
}

fn main() {
    let program = Gear::from_args();
    match program {
        Gear::Run { command, args } => println!("Running {} with args {:?}", command, args),
    }
}
<|endoftext|>


<commit_before>extern crate clap;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate toml;

mod config;
mod jira_api;
mod jira_client;
mod jira_request;
mod workflow;

use clap::{App, SubCommand};

fn main() {
    let _ = workflow::new();
    let matches = App::new("jira")
        .version(env!("CARGO_PKG_VERSION"))
        .about("Alfred JIRA Workflow.")
        .subcommand(SubCommand::with_name("Search")
            .about("Search JIRA issues"))
        .get_matches();
}
<commit_msg>:art: Add crate hyper<commit_after>extern crate clap;
extern crate hyper;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate toml;

mod config;
mod jira_api;
mod jira_client;
mod jira_request;
mod workflow;

use clap::{App, SubCommand};

fn main() {
    let _ = workflow::new();
    let matches = App::new("jira")
        .version(env!("CARGO_PKG_VERSION"))
        .about("Alfred JIRA Workflow.")
        .subcommand(SubCommand::with_name("Search")
            .about("Search JIRA issues"))
        .get_matches();
}
<|endoftext|>


<commit_before>#![allow(unstable)]

extern crate git2;
extern crate "rustc-serialize" as rustc_serialize;

use std::old_io::File;
use std::os;
use git2::{Repository, Oid};
use git2::Error as GitError;
use rustc_serialize::json;

#[derive(Clone, RustcDecodable, RustcEncodable)]
struct Commit {
    hash: String,
    author: String,
    date: i64,
    message: String
}

fn fetch_commits(repo: &Repository, start: &Option<Oid>, query: &str, amount: usize) -> Result<Vec<Commit>, GitError> {
    let mut revs = try!(repo.revwalk());
    match *start {
        Some(commit_id) => try!(revs.push(commit_id)),
        _ => try!(revs.push_head()),
    }

    revs.set_sorting(git2::SORT_TOPOLOGICAL | git2::SORT_TIME);

    let commits = revs
    .filter_map(|commit_id| { repo.find_commit(commit_id).ok() })
    .filter_map(|commit| {
        match commit.message().and_then(|msg| { Some(msg.contains(query)) }) {
            Some(true) => Some(commit),
            _ => None
        }
    })
    .map(|commit| {
        let c = Commit {
            hash: commit.id().to_string(),
            author: commit.author().name()
                .or(commit.author().email())
                .unwrap_or("Some dude").trim().to_string(),
            date: commit.time().seconds(),
            message: commit.message().unwrap_or("").trim().to_string()
        };
				c
    })
    .take(amount)
    .collect();

    Result::Ok(commits)
}

fn main() {
    let args = os::args();
    let start = if args.len() >= 2 { Some(Oid::from_str(&args[1][]).unwrap()) } else { None };

    let cwd = os::getcwd().unwrap();
    let repo = Repository::open(&cwd.join("rust")).unwrap();

    let mut output = File::create(&cwd.join("log.json")).unwrap();

    let commits = fetch_commits(&repo, &start, "[breaking-change]", 100).unwrap();

    match write!(&mut output, "{}", json::as_pretty_json(&commits)) {
        Ok(_) => println!("wrote commits to `log.json`."),
        Err(e) => panic!("failed to write commits to file: {}", e),
    };
}
<commit_msg>Indent<commit_after>#![allow(unstable)]

extern crate git2;
extern crate "rustc-serialize" as rustc_serialize;

use std::old_io::File;
use std::os;
use git2::{Repository, Oid};
use git2::Error as GitError;
use rustc_serialize::json;

#[derive(Clone, RustcDecodable, RustcEncodable)]
struct Commit {
    hash: String,
    author: String,
    date: i64,
    message: String
}

fn fetch_commits(repo: &Repository, start: &Option<Oid>, query: &str, amount: usize) -> Result<Vec<Commit>, GitError> {
    let mut revs = try!(repo.revwalk());
    match *start {
        Some(commit_id) => try!(revs.push(commit_id)),
        _ => try!(revs.push_head()),
    }

    revs.set_sorting(git2::SORT_TOPOLOGICAL | git2::SORT_TIME);

    let commits = revs
    .filter_map(|commit_id| { repo.find_commit(commit_id).ok() })
    .filter_map(|commit| {
        match commit.message().and_then(|msg| { Some(msg.contains(query)) }) {
            Some(true) => Some(commit),
            _ => None
        }
    })
    .map(|commit| {
        let c = Commit {
            hash: commit.id().to_string(),
            author: commit.author().name()
                .or(commit.author().email())
                .unwrap_or("Some dude").trim().to_string(),
            date: commit.time().seconds(),
            message: commit.message().unwrap_or("").trim().to_string()
        };
        c
    })
    .take(amount)
    .collect();

    Result::Ok(commits)
}

fn main() {
    let args = os::args();
    let start = if args.len() >= 2 { Some(Oid::from_str(&args[1][]).unwrap()) } else { None };

    let cwd = os::getcwd().unwrap();
    let repo = Repository::open(&cwd.join("rust")).unwrap();

    let mut output = File::create(&cwd.join("log.json")).unwrap();

    let commits = fetch_commits(&repo, &start, "[breaking-change]", 100).unwrap();

    match write!(&mut output, "{}", json::as_pretty_json(&commits)) {
        Ok(_) => println!("wrote commits to `log.json`."),
        Err(e) => panic!("failed to write commits to file: {}", e),
    };
}
<|endoftext|>


<commit_before>extern crate byteorder;
extern crate rand;
extern crate sdl2;
extern crate time;

use std::env;
use std::fs::File;
use std::io::Read;
use std::path::Path;

mod cpu;
mod graphics;
mod input;
mod interconnect;
mod memory;
mod sound;
mod vm;

fn main() {
    // TODO: Use an actual argument parser when adding options in the future.
    if let Some(rom_file_name) = env::args().nth(1) {
        let rom = read_bin(rom_file_name);

        let mut vm = vm::VirtualMachine::new(rom);
        vm.run();
    } else {
        print_usage();
        std::process::exit(1);
    }
}

/// Prints the application name alongside the cargo version.
fn print_version() {
    println!("notch {}", env!("CARGO_PKG_VERSION"));
}

/// Prints usage information.
fn print_usage() {
    println!("Notch is a CHIP-8 virtual machine written in Rust.");
    println!("");
    println!("Usage: notch [ROM]");
    println!("");
    println!("To contribute or report bugs, please see:");
    println!("<https://github.com/Reshurum/notch>");
}

/// Reads a file into a vector of unsigned bytes.
fn read_bin<P: AsRef<Path>>(path: P) -> Vec<u8> {
    let mut buffer: Vec<u8> = Vec::new();
    let filename = format!("{}", path.as_ref().display());

    // Open and read the file if it exists.
    match File::open(path) {
        Ok(ref mut file) => {
            file.read_to_end(&mut buffer).unwrap();
        },
        Err(why) => {
            println!("notch: cannot open '{}': {}", filename, why);
            std::process::exit(2);
        },
    };

    buffer
}
<commit_msg>Added proper argument parsing<commit_after>extern crate byteorder;
extern crate getopts;
extern crate rand;
extern crate sdl2;
extern crate time;

use std::env;
use std::fs::File;
use std::io::Read;
use std::path::Path;

use getopts::Options;

mod cpu;
mod graphics;
mod input;
mod interconnect;
mod memory;
mod sound;
mod vm;

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

    // Initialize the argument parser and parse them.
    let mut opts = Options::new();
    opts.optflag("v", "version", "print version information");
    opts.optflag("h", "help", "Print this message");
    let matches = match opts.parse(&args[1..]) {
        Ok(m) => m,
        Err(f) => {
            println!("{}\n", f.to_string());
            print_usage(opts);
            std::process::exit(1);
        },
    };

    // Argument flags.
    if matches.opt_present("v") {
        print_version();
        return;
    }
    if matches.opt_present("h") {
        print_usage(opts);
        return;
    }

    // Assume the first free argument is the rom filename.
    let rom_file_name = if !matches.free.is_empty() {
        matches.free[0].clone()
    } else {
        print_usage(opts);
        std::process::exit(1);
    };

    let rom = read_bin(&rom_file_name);
    println!("Loading rom: {}", rom_file_name);

    // Initialize the virtual machine and boot the rom.
    let mut vm = vm::VirtualMachine::new(rom);
    vm.run();
}

/// Reads a file into a vector of unsigned bytes.
fn read_bin<P: AsRef<Path>>(path: P) -> Vec<u8> {
    let mut buffer: Vec<u8> = Vec::new();
    let filename = format!("{}", path.as_ref().display());

    // Open and read the file if it exists.
    match File::open(path) {
        Ok(ref mut file) => {
            file.read_to_end(&mut buffer).unwrap();
        },
        Err(why) => {
            println!("notch: cannot open '{}': {}", filename, why);
            std::process::exit(2);
        },
    };

    buffer
}

/// Prints the application name alongside the cargo version.
fn print_version() {
    println!("notch {}", env!("CARGO_PKG_VERSION"));
}

/// Prints usage information.
fn print_usage(opts: Options) {
    println!("Notch is a CHIP-8 virtual machine written in Rust.");
    println!("");
    println!("{}", opts.usage("Usage: notch [OPTIONS] ROM"));
    println!("To contribute or report bugs, please see:");
    println!("<https://github.com/Reshurum/notch>");
}
<|endoftext|>


<commit_before>#![allow(dead_code)]

extern crate ncurses;
extern crate time;
#[macro_use]
extern crate log;

pub mod ui;
pub mod util;

use ncurses::*;
use ui::window::{Window, StatusWin, MapWin, LogWin};
use ui::input::{InputHandler};

use util::file_logger::{SimpleFileLogger};

/// Main function
fn main() {

    //Might need to actually check the return value at some point
    let _ = SimpleFileLogger::init();

    info!("Starting...");

    let mut max_x: i32 = 0;
    let mut max_y: i32 = 0;

    let locale_conf = LcCategory::all;

    // Necessary for utf8 support
    // before initscr
    ncurses::setlocale(locale_conf, "");

    // Start ncurses.
    ncurses::initscr();
    ncurses::cbreak();
    // Enable some additional keys, like arrow keys, or F1
    ncurses::keypad(stdscr, true);
    // Do not display typed character in terminal
    ncurses::noecho();

    ncurses::getmaxyx(stdscr, &mut max_y, &mut max_x);

    // Create 3 windows
    // width of the status column
    let status_width = 20;
    let log_height = 5;

    let mut status = Window::new(0, 0, max_y, status_width, Box::new(StatusWin));
    status.init();

    let mut map = Window::new(0,
                              status_width,
                              max_y - log_height,
                              max_x - status_width,
                              Box::new(MapWin));
    map.init();

    let mut log = Window::new(max_y - log_height,
                                 status_width,
                                 log_height,
                                 max_x - status_width,
                                 Box::new(LogWin));
    log.init();

    // Print to the map windows.
    map.write("Map".to_string());
    log.write("log".to_string());

    // Update the screen.
    map.refresh();
    status.refresh();
    log.refresh();

    //let mut x = 1;
    //let mut y = 1;

    loop {
        // Wait for a key press.
        let c : i32 = ncurses::getch();
        let ch :char = std::char::from_u32(c as u32).unwrap();

        //if ch == 'q' {
            //break;
        //} else {
            //status.mvaddch(y, x, ch as u64);
            //log.mvaddch(y, x, ch as u64);
            //map.mvaddch(y, x, ch as u64);
            //x += 1;
        //}

        let input = InputHandler::new();

        if ch == 'q'{
            break;
        }else{
            input.process_key(ch);
        }

        map.refresh();
        status.refresh();
        log.refresh();
    }

    // Terminate ncurses.
    map.delwin();
    status.delwin();
    log.delwin();

    ncurses::endwin();
}
<commit_msg>remove dead code<commit_after>#![allow(dead_code)]

extern crate ncurses;
extern crate time;
#[macro_use]
extern crate log;

pub mod ui;
pub mod util;

use ncurses::*;
use ui::window::{Window, StatusWin, MapWin, LogWin};
use ui::input::{InputHandler};

use util::file_logger::{SimpleFileLogger};

/// Main function
fn main() {

    //Might need to actually check the return value at some point
    let _ = SimpleFileLogger::init();

    info!("Starting...");

    let mut max_x: i32 = 0;
    let mut max_y: i32 = 0;

    let locale_conf = LcCategory::all;

    // Necessary for utf8 support
    // before initscr
    ncurses::setlocale(locale_conf, "");

    // Start ncurses.
    ncurses::initscr();
    ncurses::cbreak();
    // Enable some additional keys, like arrow keys, or F1
    ncurses::keypad(stdscr, true);
    // Do not display typed character in terminal
    ncurses::noecho();

    ncurses::getmaxyx(stdscr, &mut max_y, &mut max_x);

    // Create 3 windows
    // width of the status column
    let status_width = 20;
    let log_height = 5;

    let mut status = Window::new(0, 0, max_y, status_width, Box::new(StatusWin));
    status.init();

    let mut map = Window::new(0,
                              status_width,
                              max_y - log_height,
                              max_x - status_width,
                              Box::new(MapWin));
    map.init();

    let mut log = Window::new(max_y - log_height,
                                 status_width,
                                 log_height,
                                 max_x - status_width,
                                 Box::new(LogWin));
    log.init();

    // Print to the map windows.
    map.write("Map".to_string());
    log.write("log".to_string());

    // Update the screen.
    map.refresh();
    status.refresh();
    log.refresh();

    //let mut x = 1;
    //let mut y = 1;

    loop {
        // Wait for a key press.
        let c : i32 = ncurses::getch();
        let ch :char = std::char::from_u32(c as u32).unwrap();

        let input = InputHandler::new();

        if ch == 'q'{
            break;
        }else{
            input.process_key(ch);
        }

        map.refresh();
        status.refresh();
        log.refresh();
    }

    // Terminate ncurses.
    map.delwin();
    status.delwin();
    log.delwin();

    ncurses::endwin();
}
<|endoftext|>


<commit_before>extern crate hyper;
extern crate toml;

extern crate rustc_serialize;
use rustc_serialize::json;

use std::io::{Read, Write};
use std::thread;

use hyper::Client;
use hyper::server::{Server, Request, Response};
use hyper::status::StatusCode;

// required JSON keys are non-snakecase
#[allow(non_snake_case)]
#[derive(RustcDecodable)]
pub struct SymbolRequest {
    memoryMap: Vec<(String,String)>,
    // TODO check that key actually fits in 8-bit int
    stacks: Vec<Vec<(i8,i64)>>,
    symbolSources: Vec<String>,
    version: u8,
}

fn main() {
    let address = "0.0.0.0:8080";

    println!("Listening on {}", address);
    Server::http(address).unwrap().handle(server).unwrap();
}

/**
  * Receives single HTTP requests and demuxes to symbols file fetches from S3 bucket.
  */
fn server(mut req: Request, mut res: Response) {
    match req.method {
        hyper::Post => {
            let mut res = res.start().unwrap();

            let mut buffer = String::new();
            let _ = req.read_to_string(&mut buffer);
            println!("DEBUG raw POST: {:?}", &buffer);
            let decoded: SymbolRequest = json::decode(&buffer).unwrap();

            println!("DEBUG decoded memoryMap: {:?}", decoded.memoryMap);
            println!("DEBUG decoded stacks: {:?}", decoded.stacks);
            println!("DEBUG decoded symbolSources: {:?}", decoded.symbolSources);
            println!("DEBUG decoded version: {}", decoded.version);

            let symbol_url = get_config("symbol_urls.public");
            let symbols = client(symbol_url, decoded.memoryMap);
            let _ = res.write_all(symbols.as_bytes());

            res.end().unwrap();
        },
        _ => { *res.status_mut() = StatusCode::MethodNotAllowed },
    }
}

/**
  * Creates multiple client connections and aggregates result.
  */
fn client(url: String, memory_map: Vec<(String,String)>) -> String {
    let mut handles = vec![];
    // TODO decide min/max possible threads, possibly based on number of cores?
    for (debug_file, debug_id) in memory_map {
        let pdb = debug_file.find(".pdb").unwrap();
        let (symbol_name, _) = debug_file.split_at(pdb);
        let symbol_file = format!("{}.sym", symbol_name);
        let this_url = format!("{}/{}/{}/{}", url, debug_file, debug_id, symbol_file);
        handles.push(thread::spawn(move || {
            let c = Client::new();
            let mut res = c.get(&this_url).send().unwrap();
            let mut body = String::new();
            let _ = res.read_to_string(&mut body);

            (symbol_file, body)
        }));
    }

    let mut result = String::new();

    for handle in handles {
        let (k, body) = handle.join().unwrap();
        for c in format!("{:?} {:?}\n", k, body).chars() {
            result.push(c);
        }
    }

    result
}

fn get_config(value_name: &str) -> String {
    let toml = r#"
        [symbol_urls]
        public = "https://s3-us-west-2.amazonaws.com/org.mozilla.crash-stats.symbols-public/v1"
    "#;
    // TODO support multiple URLs
    let value: toml::Value = toml.parse().unwrap();

    value.lookup(value_name).unwrap().as_str().unwrap().to_string()
}
<commit_msg>better comment and var name<commit_after>extern crate hyper;
extern crate toml;

extern crate rustc_serialize;
use rustc_serialize::json;

use std::io::{Read, Write};
use std::thread;

use hyper::Client;
use hyper::server::{Server, Request, Response};
use hyper::status::StatusCode;

// required JSON keys are non-snakecase
#[allow(non_snake_case)]
#[derive(RustcDecodable)]
pub struct SymbolRequest {
    memoryMap: Vec<(String,String)>,
    // TODO check that key actually fits in 8-bit int
    stacks: Vec<Vec<(i8,i64)>>,
    symbolSources: Vec<String>,
    version: u8,
}

fn main() {
    let address = "0.0.0.0:8080";

    println!("Listening on {}", address);
    Server::http(address).unwrap().handle(server).unwrap();
}

/**
  * Receives single HTTP requests and demuxes to symbols file fetches from S3 bucket.
  */
fn server(mut req: Request, mut res: Response) {
    match req.method {
        hyper::Post => {
            let mut res = res.start().unwrap();

            let mut buffer = String::new();
            let _ = req.read_to_string(&mut buffer);
            println!("DEBUG raw POST: {:?}", &buffer);
            let decoded: SymbolRequest = json::decode(&buffer).unwrap();

            println!("DEBUG decoded memoryMap: {:?}", decoded.memoryMap);
            println!("DEBUG decoded stacks: {:?}", decoded.stacks);
            println!("DEBUG decoded symbolSources: {:?}", decoded.symbolSources);
            println!("DEBUG decoded version: {}", decoded.version);

            let symbol_url = get_config("symbol_urls.public");
            let symbols = client(symbol_url, decoded.memoryMap);
            let _ = res.write_all(symbols.as_bytes());

            res.end().unwrap();
        },
        _ => { *res.status_mut() = StatusCode::MethodNotAllowed },
    }
}

/**
  * Creates multiple client connections and aggregates result.
  */
fn client(url: String, memory_map: Vec<(String,String)>) -> String {
    let mut handles = vec![];
    for (debug_file, debug_id) in memory_map {
        let pdb = debug_file.find(".pdb").unwrap();
        let (symbol_name, _) = debug_file.split_at(pdb);
        let symbol_file = format!("{}.sym", symbol_name);
        let this_url = format!("{}/{}/{}/{}", url, debug_file, debug_id, symbol_file);
        // TODO decide min/max possible threads, possibly based on number of cores?
        handles.push(thread::spawn(move || {
            let c = Client::new();
            let mut res = c.get(&this_url).send().unwrap();
            let mut body = String::new();
            let _ = res.read_to_string(&mut body);

            (symbol_file, body)
        }));
    }

    let mut result = String::new();

    for handle in handles {
        let (symbol_file, body) = handle.join().unwrap();
        for c in format!("{:?} {:?}\n", symbol_file, body).chars() {
            result.push(c);
        }
    }

    result
}

fn get_config(value_name: &str) -> String {
    let toml = r#"
        [symbol_urls]
        public = "https://s3-us-west-2.amazonaws.com/org.mozilla.crash-stats.symbols-public/v1"
    "#;
    // TODO support multiple URLs
    let value: toml::Value = toml.parse().unwrap();

    value.lookup(value_name).unwrap().as_str().unwrap().to_string()
}
<|endoftext|>


<commit_before>extern crate llvm_sys as llvm;
extern crate libc;
extern crate docopt;
extern crate rustc_serialize;
extern crate libffi;
extern crate itertools;

mod ast;
mod codegen;
mod compileerror;
mod parser;
mod passes;

use std::path::Path;

use codegen::{CodeGenOptions, codegen, link, llvm_init};
use docopt::Docopt;
use parser::parse_file;
use passes::infer_and_check_types;

static USAGE: &'static str =  "
Usage: cobra [options] <input-file>
       cobra --help

options:
  --help                                       Show this message.
  -d, --debug                                  Debug mode.
  -O, --optimize                               Optimize the code.
  -o <output-file>, --output=<output-file>     Name of binary to create (by default input-file without the extensions)
";

#[derive(RustcDecodable, Debug)]
struct Args
{
    flag_debug: Option<bool>,
    flag_optimize: Option<bool>,
    arg_input_file: Option<String>,
    flag_output: Option<String>,
}

fn find_runtime_library() -> Option<String>
{
    let paths = [
        "/usr/lib/libcobraruntime.a",
        "/usr/local/lib/libcobraruntime.a",
        "../librt/libcobraruntime.a",
        "./librt/libcobraruntime.a",
        "./libcobraruntime.a",
    ];

    for p in &paths {
        if Path::new(*p).exists() {
            return Some((*p).into());
        }
    }

    None
}

fn default_output_file(input_file: &str) -> String
{
    Path::new(&input_file)
        .file_stem()
        .expect("Invalid input file")
        .to_str()
        .expect("Invalid input file")
        .into()
}

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

    let input_file = args.arg_input_file.expect("Missing input file argument");
    let output_file = args.flag_output.unwrap_or(default_output_file(&input_file));
    let debug_compiler = args.flag_debug.unwrap_or(false);
    let opts = CodeGenOptions{
        dump_ir: debug_compiler,
        build_dir: "build".into(),
        program_name: output_file,
        runtime_library: find_runtime_library().expect("Unable to find the cobra runtime library"),
        optimize: args.flag_optimize.unwrap_or(false),
    };

    //let output_file = args.flag_output.unwrap_or(default_output_file(&input_file));
    match parse_file(&input_file).and_then(|mut module| {
        //module.print(0);
        try!(infer_and_check_types(&mut module));
        llvm_init();
        let mut ctx = try!(codegen(&module, &opts));
        link(&mut ctx, &opts)
    })
    {
        Ok(_) => {},
        Err(e) => println!("Error: {}", e),
    }
}
<commit_msg>Attempt at build fix<commit_after>extern crate llvm_sys as llvm;
extern crate libffi;
extern crate libc;
extern crate docopt;
extern crate rustc_serialize;
extern crate itertools;

mod ast;
mod codegen;
mod compileerror;
mod parser;
mod passes;

use std::path::Path;

use codegen::{CodeGenOptions, codegen, link, llvm_init};
use docopt::Docopt;
use parser::parse_file;
use passes::infer_and_check_types;

static USAGE: &'static str =  "
Usage: cobra [options] <input-file>
       cobra --help

options:
  --help                                       Show this message.
  -d, --debug                                  Debug mode.
  -O, --optimize                               Optimize the code.
  -o <output-file>, --output=<output-file>     Name of binary to create (by default input-file without the extensions)
";

#[derive(RustcDecodable, Debug)]
struct Args
{
    flag_debug: Option<bool>,
    flag_optimize: Option<bool>,
    arg_input_file: Option<String>,
    flag_output: Option<String>,
}

fn find_runtime_library() -> Option<String>
{
    let paths = [
        "/usr/lib/libcobraruntime.a",
        "/usr/local/lib/libcobraruntime.a",
        "../librt/libcobraruntime.a",
        "./librt/libcobraruntime.a",
        "./libcobraruntime.a",
    ];

    for p in &paths {
        if Path::new(*p).exists() {
            return Some((*p).into());
        }
    }

    None
}

fn default_output_file(input_file: &str) -> String
{
    Path::new(&input_file)
        .file_stem()
        .expect("Invalid input file")
        .to_str()
        .expect("Invalid input file")
        .into()
}

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

    let input_file = args.arg_input_file.expect("Missing input file argument");
    let output_file = args.flag_output.unwrap_or(default_output_file(&input_file));
    let debug_compiler = args.flag_debug.unwrap_or(false);
    let opts = CodeGenOptions{
        dump_ir: debug_compiler,
        build_dir: "build".into(),
        program_name: output_file,
        runtime_library: find_runtime_library().expect("Unable to find the cobra runtime library"),
        optimize: args.flag_optimize.unwrap_or(false),
    };

    //let output_file = args.flag_output.unwrap_or(default_output_file(&input_file));
    match parse_file(&input_file).and_then(|mut module| {
        //module.print(0);
        try!(infer_and_check_types(&mut module));
        llvm_init();
        let mut ctx = try!(codegen(&module, &opts));
        link(&mut ctx, &opts)
    })
    {
        Ok(_) => {},
        Err(e) => println!("Error: {}", e),
    }
}
<|endoftext|>


<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;
extern crate env_logger;
use docopt::Docopt;
use std::path;
use aws_abacus::elb_log_files;
use chrono::{DateTime, UTC};
use aws_abacus::elb_log_files::ParsingResult;
use std::collections::HashMap;

fn main() {
    env_logger::init().unwrap();
    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();
    let mut agg: HashMap<AggregateELBRecord, i64> = HashMap::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, &mut |parsing_result: ParsingResult| {
                parsing_result_handler(parsing_result, &mut agg);
            });
            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 and produced {} aggregates.",
                number_of_files,
                number_of_records,
                time.num_milliseconds(),
                agg.len()
            );
        },
        None => {},
    };
}

#[derive(Clone, Debug, Eq, Hash, PartialEq)]
struct AggregateELBRecord {
    day: String,
    client_address: String,
    system_name: String,
    public_id: u64,
}

fn parsing_result_handler(parsing_result: ParsingResult, aggregation: &mut HashMap<AggregateELBRecord, i64>) -> () {
    match parsing_result {
        Ok(elb_record) => {
            let aer = AggregateELBRecord {
                day: "".to_owned(),
                client_address: "".to_owned(),
                system_name: "".to_owned(),
                public_id: elb_record.sent_bytes
            };
            aggregate_record(aer, aggregation);
        },

        Err(errors) => {

        }
    }
}

//Need to produce system_name,yyyy-mm-dd,req_addr,count
fn aggregate_record(aggregate_record: AggregateELBRecord, aggregation: &mut HashMap<AggregateELBRecord, i64>) -> () {
    let total = aggregation.entry(aggregate_record).or_insert(0);
    *total += 1;
}

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,
}

#[cfg(test)]
mod tests {

    use std::collections::HashMap;
    use ::AggregateELBRecord;
    use ::aggregate_record;

    const TEST_RECORD: &'static str = "2015-08-15T23:43:05.302180Z elb-name 172.16.1.6:54814 \
    172.16.1.5:9000 0.000039 0.145507 0.00003 200 200 0 7582 \
    \"GET http://some.domain.com:80/path0/path1?param0=p0&param1=p1 HTTP/1.1\"\
    ";

    #[test]
	fn inserting_two_records_with_different_values_creates_two_entries_each_recorded_once() {
        let mut agg: HashMap<AggregateELBRecord, i64> = HashMap::new();

        let ar0 = AggregateELBRecord {
            day: "2015-08-15".to_owned(),
            client_address: "172.16.1.6:54814".to_owned(),
            system_name: "sys1".to_owned(),
            public_id: 8880
        };

        let ar1 = AggregateELBRecord {
            day: "2015-08-15".to_owned(),
            client_address: "172.16.1.6:54814".to_owned(),
            system_name: "sys1".to_owned(),
            public_id: 8888
        };

        aggregate_record(ar0, &mut agg);
        aggregate_record(ar1, &mut agg);

        assert_eq!(agg.len(), 2);
        for (_, total) in agg {
            assert_eq!(total, 1)
        }
	}

    #[test]
	fn inserting_two_records_with_the_same_values_increases_the_total_correctly() {
        let mut agg: HashMap<AggregateELBRecord, i64> = HashMap::new();

        let ar0 = AggregateELBRecord {
            day: "2015-08-15".to_owned(),
            client_address: "172.16.1.6:54814".to_owned(),
            system_name: "sys1".to_owned(),
            public_id: 8888
        };

        let ar1 = ar0.clone();
        let ar3 = ar0.clone();

        aggregate_record(ar0, &mut agg);
        aggregate_record(ar1, &mut agg);

        assert_eq!(agg[&ar3], 2);
	}
}
<commit_msg>Started working on converting ELBRecords to AggregateELBRecords.<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;
extern crate env_logger;
use docopt::Docopt;
use std::path;
use aws_abacus::elb_log_files;
use chrono::{DateTime, UTC};
use aws_abacus::elb_log_files::ParsingResult;
use std::collections::HashMap;

fn main() {
    env_logger::init().unwrap();
    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();
    let mut agg: HashMap<AggregateELBRecord, i64> = HashMap::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, &mut |parsing_result: ParsingResult| {
                parsing_result_handler(parsing_result, &mut agg);
            });
            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 and produced {} aggregates.",
                number_of_files,
                number_of_records,
                time.num_milliseconds(),
                agg.len()
            );
        },
        None => {},
    };
}

#[derive(Clone, Debug, Eq, Hash, PartialEq)]
struct AggregateELBRecord {
    day: String,
    client_address: String,
    system_name: String,
    // public_id: u64,
}

fn parsing_result_handler(parsing_result: ParsingResult, aggregation: &mut HashMap<AggregateELBRecord, i64>) -> () {
    match parsing_result {
        Ok(elb_record) => {
            //36labs,2016-01-07,173.70.188.85,3
            // println!("{}", elb_record.client_address.ip().to_string());
            let aer = AggregateELBRecord {
                day: elb_record.timestamp.format("%Y-%m-%d").to_string(),
                client_address: elb_record.client_address.ip().to_string(),
                system_name: "".to_owned(),
                // public_id: elb_record.sent_bytes
            };
            aggregate_record(aer, aggregation);
        },

        Err(errors) => {

        }
    }
}

//Need to produce system_name,yyyy-mm-dd,req_addr,count
fn aggregate_record(aggregate_record: AggregateELBRecord, aggregation: &mut HashMap<AggregateELBRecord, i64>) -> () {
    let total = aggregation.entry(aggregate_record).or_insert(0);
    *total += 1;
}

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,
}

#[cfg(test)]
mod tests {

    use std::collections::HashMap;
    use ::AggregateELBRecord;
    use ::aggregate_record;

    const TEST_RECORD: &'static str = "2015-08-15T23:43:05.302180Z elb-name 172.16.1.6:54814 \
    172.16.1.5:9000 0.000039 0.145507 0.00003 200 200 0 7582 \
    \"GET http://some.domain.com:80/path0/path1?param0=p0&param1=p1 HTTP/1.1\"\
    ";

    #[test]
	fn inserting_two_records_with_different_values_creates_two_entries_each_recorded_once() {
        let mut agg: HashMap<AggregateELBRecord, i64> = HashMap::new();

        let ar0 = AggregateELBRecord {
            day: "2015-08-15".to_owned(),
            client_address: "172.16.1.6:54814".to_owned(),
            system_name: "sys1".to_owned(),
            public_id: 8880
        };

        let ar1 = AggregateELBRecord {
            day: "2015-08-15".to_owned(),
            client_address: "172.16.1.6:54814".to_owned(),
            system_name: "sys1".to_owned(),
            public_id: 8888
        };

        aggregate_record(ar0, &mut agg);
        aggregate_record(ar1, &mut agg);

        assert_eq!(agg.len(), 2);
        for (_, total) in agg {
            assert_eq!(total, 1)
        }
	}

    #[test]
	fn inserting_two_records_with_the_same_values_increases_the_total_correctly() {
        let mut agg: HashMap<AggregateELBRecord, i64> = HashMap::new();

        let ar0 = AggregateELBRecord {
            day: "2015-08-15".to_owned(),
            client_address: "172.16.1.6:54814".to_owned(),
            system_name: "sys1".to_owned(),
            public_id: 8888
        };

        let ar1 = ar0.clone();
        let ar3 = ar0.clone();

        aggregate_record(ar0, &mut agg);
        aggregate_record(ar1, &mut agg);

        assert_eq!(agg[&ar3], 2);
	}
}
<|endoftext|>


<commit_before>#[macro_use] extern crate glium;
#[macro_use] extern crate nalgebra as na;
extern crate obj;

use std::path::Path;
use std::f32::consts::{FRAC_PI_2};

use obj::SimplePolygon;

use na::{Pnt3, Vec3, Mat3, Iso3, PerspMat3};
use na::{Eye};

const PI_4: f32 = std::f32::consts::FRAC_PI_4;

#[derive(Copy, Clone)]
struct Vert {
    position: [f32;3],
    normal: [f32;3],
    color: [f32;3],
}

implement_vertex!(Vert, position, normal, color);

fn setup_buffer(window: &glium::backend::glutin_backend::GlutinFacade) -> glium::vertex::VertexBuffer<Vert> {
    let p = Path::new("/home/hcs/code/rust/triangle/meshes/icosohedron.obj");
    let o = obj::load::<SimplePolygon>(p).unwrap();

    let green = [0f32, 1.0, 0.0];

    let size = o.position().len();
    let mut data = Vec::with_capacity(size);

    for ob in o.object_iter() {
        for g in ob.group_iter() {
            for tri in g.indices() {
                data.push(
                    Vert {
                        position: o.position()[tri[0].0],
                        normal: o.normal()[(tri[0].2).unwrap()],
                        color: green.clone(),
                    }
                );
                data.push(
                    Vert {
                        position: o.position()[tri[1].0],
                        normal: o.normal()[(tri[1].2).unwrap()],
                        color: green.clone(),
                    }
                );
                data.push(
                    Vert {
                        position: o.position()[tri[2].0],
                        normal: o.normal()[(tri[2].2).unwrap()],
                        color: green.clone(),
                    }
                );
            }
        }
    }

    glium::vertex::VertexBuffer::new(window, &data).unwrap()
}

fn setup_plane(window: &glium::backend::glutin_backend::GlutinFacade) -> glium::vertex::VertexBuffer<Vert> {
    let tr = [1f32, 1.0, 0.0];
    let tl = [-1f32, 1.0, 0.0];
    let bl = [-1f32, -1.0, 0.0];
    let br = [1f32, -1.0, 0.0];

    let n = [0f32, 0.0, 1.0];

    let white = [1f32, 1.0, 1.0];

    let data = &[
        Vert {
            position: tr,
            normal: n,
            color: white,
        },
        Vert {
            position: tl,
            normal: n,
            color: white,
        },
        Vert {
            position: bl,
            normal: n,
            color: white,
        },

        Vert {
            position: tr,
            normal: n,
            color: white,
        },
        Vert {
            position: bl,
            normal: n,
            color: white,
        },
        Vert {
            position: br,
            normal: n,
            color: white,
        },
    ];
    glium::vertex::VertexBuffer::new(window, data).unwrap()
}

fn setup_shaders(window: &glium::backend::glutin_backend::GlutinFacade) -> glium::program::Program {
    let v_shader = "
        #version 150

        uniform mat4 perspective;
        uniform mat4 mv;
        uniform mat4 m_invt;
        uniform vec3 light_dir;

        in vec3 position;
        in vec3 normal;
        in vec3 color;

        out vec3 f_color;

        void main() {
            gl_Position = perspective*mv*vec4(position, 1.0);

            vec3 mv_normal = normalize(vec3(m_invt * vec4(normal, 0.0)));
            float diffuse = 0.6*max( dot(mv_normal, light_dir), 0.1);

            f_color = diffuse*color;
        }
    ";
    let f_shader = "
        #version 150

        in vec3 f_color;

        void main() {
            gl_FragColor = vec4(f_color, 1.0);
        }
    ";
    glium::program::Program::from_source(window, v_shader, f_shader, None).unwrap()
}

fn main() {
    use glium::{DisplayBuild,Surface};

    const WIDTH: u32 = 1280;
    const HEIGHT: u32 = 720;
    const ASPECT: f32 = 1.78;

	let params = glium::DrawParameters {
		backface_culling: glium::draw_parameters::BackfaceCullingMode::CullClockwise,
		depth: glium::Depth {
			test: glium::draw_parameters::DepthTest::IfLess,
			write: true,
			.. Default::default()
		},
		.. Default::default()
	};

    let window = glium::glutin::WindowBuilder::new()
        .with_dimensions(WIDTH, HEIGHT)
        .with_depth_buffer(24)
        .with_title(format!("Hello world"))
        .build_glium()
        .unwrap();

    let triangle = setup_buffer(&window);
    let plane = setup_plane(&window);
    let program = setup_shaders(&window);
    let indices = glium::index::NoIndices(glium::index::PrimitiveType::TrianglesList);

    let persp = PerspMat3::new(ASPECT, PI_4, 1.0, 100.0).to_mat();

    let mut position = Pnt3::new(0.0f32, 1.0f32, 5.0f32);
    let dir = Vec3::new(0.0f32, 0.0f32, -1.0f32);
    let up = Vec3::new(0.0f32, 1.0f32, 0.0f32);

    let mut t = 0f32;

    let mut exit = false;
    loop {
        for event in window.poll_events() {
            use glium::glutin::Event;
			use glium::glutin::VirtualKeyCode as KC;
            match event {
                Event::Closed => (exit = true),
				Event::KeyboardInput(state, _, key) => {
                    if state == glium::glutin::ElementState::Pressed {
                        match key.unwrap() {
                            KC::PageUp => {position = position + Vec3::new(0f32, 0.2f32, 0f32);},
                            KC::PageDown => {position = position + Vec3::new(0f32, -0.2f32, 0f32);},
							KC::Left => position = position + Vec3::new(-0.2f32, 0f32, 0f32),
							KC::Right => position = position + Vec3::new(0.2f32, 0f32, 0f32),
							KC::Up => position = position + Vec3::new(0f32, 0f32, -0.2f32),
							KC::Down => position = position + Vec3::new(0f32, 0f32, 0.2f32),
                            KC::Space => {println!("hello");}
                            KC::Escape => {exit = true;},
                            _ => ()
                        }
                    }
				}
                _ => ()
            }
        }

        t += 0.05;

        let mut frame = window.draw();
        frame.clear_color_and_depth((0.0, 0.0, 0.0, 1.0), 1.0);

        // camera
        let view = na::inv(&Iso3::look_at_z(&position, &(position + dir), &up)).unwrap();
        let view = na::to_homogeneous(&view);
        let light_dir = [0.5, 0.866025, 0f32];

        // draw tetrahedrons
        for i in 0..10 {
            let model = Iso3::new(Vec3::new(0f32, 0.0, -5f32*i as f32), Vec3::new(0f32, 1.0, 0.0) * t);
            let model = na::to_homogeneous(&model);
            let modelview = view*model;

            let uniforms = uniform! {
                perspective: persp.as_ref().clone(),
                mv: modelview.as_ref().clone(),
                m_invt: na::transpose(&na::inv(&model).unwrap()).as_ref().clone(),
                light_dir: light_dir,
            };

            frame.draw(&triangle, &indices, &program, &uniforms,
                                &params).unwrap();
        }

        // draw plane below tetrahedrons
        let scale = 50f32;
        let plane_scale = na::to_homogeneous(&(Mat3::<f32>::new_identity(3)*scale));
        let plane_rot = na::to_homogeneous(&(Iso3::new(Vec3::new(0f32, -1.0, 0.0), Vec3::new(1f32, 0.0, 0.0)*-FRAC_PI_2)));
        let plane_model = plane_rot*plane_scale;
        let modelview = view*plane_model;

        let uniforms = uniform! {
            perspective: persp.as_ref().clone(),
            mv: modelview.as_ref().clone(),
            m_invt: na::transpose(&na::inv(&plane_model).unwrap()).as_ref().clone(),
            light_dir: light_dir,
        };
        frame.draw(&plane, &indices, &program, &uniforms,
                            &params).unwrap();

        frame.finish().unwrap();
        window.swap_buffers().unwrap();

        if exit {
            break;
        }
    }
}
<commit_msg>Change names referring to triangle to icosohedron in code<commit_after>#[macro_use] extern crate glium;
#[macro_use] extern crate nalgebra as na;
extern crate obj;

use std::path::Path;
use std::f32::consts::{FRAC_PI_2};

use obj::SimplePolygon;

use na::{Pnt3, Vec3, Mat3, Iso3, PerspMat3};
use na::{Eye};

const PI_4: f32 = std::f32::consts::FRAC_PI_4;

#[derive(Copy, Clone)]
struct Vert {
    position: [f32;3],
    normal: [f32;3],
    color: [f32;3],
}

implement_vertex!(Vert, position, normal, color);

fn setup_icosohedron(window: &glium::backend::glutin_backend::GlutinFacade) -> glium::vertex::VertexBuffer<Vert> {
    let p = Path::new("/home/hcs/code/rust/triangle/meshes/icosohedron.obj");
    let o = obj::load::<SimplePolygon>(p).unwrap();

    let green = [0f32, 1.0, 0.0];

    let size = o.position().len();
    let mut data = Vec::with_capacity(size);

    for ob in o.object_iter() {
        for g in ob.group_iter() {
            for tri in g.indices() {
                data.push(
                    Vert {
                        position: o.position()[tri[0].0],
                        normal: o.normal()[(tri[0].2).unwrap()],
                        color: green.clone(),
                    }
                );
                data.push(
                    Vert {
                        position: o.position()[tri[1].0],
                        normal: o.normal()[(tri[1].2).unwrap()],
                        color: green.clone(),
                    }
                );
                data.push(
                    Vert {
                        position: o.position()[tri[2].0],
                        normal: o.normal()[(tri[2].2).unwrap()],
                        color: green.clone(),
                    }
                );
            }
        }
    }

    glium::vertex::VertexBuffer::new(window, &data).unwrap()
}

fn setup_plane(window: &glium::backend::glutin_backend::GlutinFacade) -> glium::vertex::VertexBuffer<Vert> {
    let tr = [1f32, 1.0, 0.0];
    let tl = [-1f32, 1.0, 0.0];
    let bl = [-1f32, -1.0, 0.0];
    let br = [1f32, -1.0, 0.0];

    let n = [0f32, 0.0, 1.0];

    let white = [1f32, 1.0, 1.0];

    let data = &[
        Vert {
            position: tr,
            normal: n,
            color: white,
        },
        Vert {
            position: tl,
            normal: n,
            color: white,
        },
        Vert {
            position: bl,
            normal: n,
            color: white,
        },

        Vert {
            position: tr,
            normal: n,
            color: white,
        },
        Vert {
            position: bl,
            normal: n,
            color: white,
        },
        Vert {
            position: br,
            normal: n,
            color: white,
        },
    ];
    glium::vertex::VertexBuffer::new(window, data).unwrap()
}

fn setup_shaders(window: &glium::backend::glutin_backend::GlutinFacade) -> glium::program::Program {
    let v_shader = "
        #version 150

        uniform mat4 perspective;
        uniform mat4 mv;
        uniform mat4 m_invt;
        uniform vec3 light_dir;

        in vec3 position;
        in vec3 normal;
        in vec3 color;

        out vec3 f_color;

        void main() {
            gl_Position = perspective*mv*vec4(position, 1.0);

            vec3 mv_normal = normalize(vec3(m_invt * vec4(normal, 0.0)));
            float diffuse = 0.6*max( dot(mv_normal, light_dir), 0.1);

            f_color = diffuse*color;
        }
    ";
    let f_shader = "
        #version 150

        in vec3 f_color;

        void main() {
            gl_FragColor = vec4(f_color, 1.0);
        }
    ";
    glium::program::Program::from_source(window, v_shader, f_shader, None).unwrap()
}

fn main() {
    use glium::{DisplayBuild,Surface};

    const WIDTH: u32 = 1280;
    const HEIGHT: u32 = 720;
    const ASPECT: f32 = 1.78;

	let params = glium::DrawParameters {
		backface_culling: glium::draw_parameters::BackfaceCullingMode::CullClockwise,
		depth: glium::Depth {
			test: glium::draw_parameters::DepthTest::IfLess,
			write: true,
			.. Default::default()
		},
		.. Default::default()
	};

    let window = glium::glutin::WindowBuilder::new()
        .with_dimensions(WIDTH, HEIGHT)
        .with_depth_buffer(24)
        .with_title(format!("Hello world"))
        .build_glium()
        .unwrap();

    let icosohedron = setup_icosohedron(&window);
    let plane = setup_plane(&window);
    let program = setup_shaders(&window);
    let indices = glium::index::NoIndices(glium::index::PrimitiveType::TrianglesList);

    let persp = PerspMat3::new(ASPECT, PI_4, 1.0, 100.0).to_mat();

    let mut position = Pnt3::new(0.0f32, 1.0f32, 5.0f32);
    let dir = Vec3::new(0.0f32, 0.0f32, -1.0f32);
    let up = Vec3::new(0.0f32, 1.0f32, 0.0f32);

    let mut t = 0f32;

    let mut exit = false;
    loop {
        for event in window.poll_events() {
            use glium::glutin::Event;
			use glium::glutin::VirtualKeyCode as KC;
            match event {
                Event::Closed => (exit = true),
				Event::KeyboardInput(state, _, key) => {
                    if state == glium::glutin::ElementState::Pressed {
                        match key.unwrap() {
                            KC::PageUp => {position = position + Vec3::new(0f32, 0.2f32, 0f32);},
                            KC::PageDown => {position = position + Vec3::new(0f32, -0.2f32, 0f32);},
							KC::Left => position = position + Vec3::new(-0.2f32, 0f32, 0f32),
							KC::Right => position = position + Vec3::new(0.2f32, 0f32, 0f32),
							KC::Up => position = position + Vec3::new(0f32, 0f32, -0.2f32),
							KC::Down => position = position + Vec3::new(0f32, 0f32, 0.2f32),
                            KC::Space => {println!("hello");}
                            KC::Escape => {exit = true;},
                            _ => ()
                        }
                    }
				}
                _ => ()
            }
        }

        t += 0.05;

        let mut frame = window.draw();
        frame.clear_color_and_depth((0.0, 0.0, 0.0, 1.0), 1.0);

        // camera
        let view = na::inv(&Iso3::look_at_z(&position, &(position + dir), &up)).unwrap();
        let view = na::to_homogeneous(&view);
        let light_dir = [0.5, 0.866025, 0f32];

        // draw tetrahedrons
        for i in 0..10 {
            let model = Iso3::new(Vec3::new(0f32, 0.0, -5f32*i as f32), Vec3::new(0f32, 1.0, 0.0) * t);
            let model = na::to_homogeneous(&model);
            let modelview = view*model;

            let uniforms = uniform! {
                perspective: persp.as_ref().clone(),
                mv: modelview.as_ref().clone(),
                m_invt: na::transpose(&na::inv(&model).unwrap()).as_ref().clone(),
                light_dir: light_dir,
            };

            frame.draw(&icosohedron, &indices, &program, &uniforms,
                                &params).unwrap();
        }

        // draw plane below icosohedron
        let scale = 50f32;
        let plane_scale = na::to_homogeneous(&(Mat3::<f32>::new_identity(3)*scale));
        let plane_rot = na::to_homogeneous(&(Iso3::new(Vec3::new(0f32, -1.0, 0.0), Vec3::new(1f32, 0.0, 0.0)*-FRAC_PI_2)));
        let plane_model = plane_rot*plane_scale;
        let modelview = view*plane_model;

        let uniforms = uniform! {
            perspective: persp.as_ref().clone(),
            mv: modelview.as_ref().clone(),
            m_invt: na::transpose(&na::inv(&plane_model).unwrap()).as_ref().clone(),
            light_dir: light_dir,
        };
        frame.draw(&plane, &indices, &program, &uniforms,
                            &params).unwrap();

        frame.finish().unwrap();
        window.swap_buffers().unwrap();

        if exit {
            break;
        }
    }
}
<|endoftext|>


<commit_before>//  rpc-perf - RPC Performance Testing
//  Copyright 2015 Twitter, Inc
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.

#![cfg_attr(feature = "unstable", feature(test))]
#[cfg(feature = "unstable")]
extern crate test;

#[allow(unknown_lints, useless_attribute)]
#[cfg_attr(feature = "cargo-clippy", deny(result_unwrap_used))]

#[macro_use] extern crate log;
extern crate log_panics;
extern crate bytes;
extern crate byteorder;
extern crate crc;
extern crate getopts;
extern crate mio;
extern crate mpmc;
extern crate pad;
extern crate time;
extern crate rand;
extern crate ratelimit;
extern crate slab;
extern crate tic;
extern crate toml;

mod common;
mod cfgtypes;
mod client;
mod connection;
mod logger;
mod net;
mod options;
mod stats;
mod codec;
mod request;

use client::Client;
use net::InternetProtocol;
use request::{config, workload};
use std::{env, process, thread};

const VERSION: &'static str = env!("CARGO_PKG_VERSION");

pub fn main() {
    let args: Vec<String> = env::args().collect();
    let program = &args[0];
    let opts = options::opts();

    let matches = match opts.parse(&args[1..]) {
        Ok(m) => m,
        Err(f) => {
            println!("ERROR {}", f);
            options::print_usage(program, &opts);
            process::exit(1);
        }
    };

    if matches.opt_present("help") {
        options::print_usage(program, &opts);
        return;
    }

    if matches.opt_present("version") {
        println!("rpc-perf {}", VERSION);
        return;
    }

    // initialize logging
    logger::set_log_level(matches.opt_count("verbose"));
    log_panics::init();

    info!("rpc-perf {} initializing...", VERSION);
    if cfg!(feature = "asm") {
        info!("feature: asm: enabled");
    } else {
        info!("feature: asm: disabled");
    }

    let servers: Vec<String> = matches.opt_strs("server");

    if servers.is_empty() {
        error!("require server parameter");
        options::print_usage(program, &opts);
        return;
    }

    let listen = matches.opt_str("listen");
    let waterfall = matches.opt_str("waterfall");
    let trace = matches.opt_str("trace");

    // Load workload configuration
    let config = match config::load_config(&matches) {
        Ok(cfg) => cfg,
        Err(e) => {
            error!("{}", e);
            return;
        }
    };

    let internet_protocol = match net::choose_layer_3(matches.opt_present("ipv4"),
                                                      matches.opt_present("ipv6")) {
        Ok(i) => i,
        Err(e) => {
            error!("{}", e);
            return;
        }
    };

    print_config(&config, &servers, internet_protocol);

    let stats_receiver = stats::stats_receiver_init(&config, listen, waterfall, trace);

    let mut send_queues = Vec::new();

    let mut client_config = Client::configure();

    client_config
        .set_pool_size(config.poolsize())
        .stats(stats_receiver.get_sender().clone())
        .set_clocksource(stats_receiver.get_clocksource().clone())
        .set_protocol(config.protocol_config.protocol.clone())
        .set_request_timeout(config.request_timeout())
        .set_connect_timeout(config.connect_timeout())
        .set_internet_protocol(internet_protocol);

    for server in servers {
        client_config.add_server(server);
    }

    info!("-----");
    info!("Connecting...");
    for i in 0..config.threads() {
        info!("Client: {}", i);

        let mut client = client_config.clone().build();
        send_queues.push(client.tx());

        let _ = thread::Builder::new()
            .name(format!("client{}", i).to_string())
            .spawn(move || { client.run(); });
    }

    info!("-----");
    info!("Workload:");

    let windows = config.windows();

    workload::launch_workloads(config.protocol_config.workloads,
                               &send_queues,
                               &stats_receiver.get_sender(),
                               &stats_receiver.get_clocksource());

    stats::run(stats_receiver, windows, matches.opt_present("service"));
}

fn print_config(config: &request::BenchmarkConfig,
                servers: &[String],
                internet_protocol: InternetProtocol) {
    info!("-----");
    info!("Config:");
    for server in servers {
        info!("Config: Server: {} Protocol: {}",
              server,
              config.protocol_config.protocol.name());
    }
    info!("Config: IP: {:?} TCP_NODELAY: {}",
          internet_protocol,
          config.tcp_nodelay());
    info!("Config: Threads: {} Poolsize: {}",
          config.threads(),
          config.poolsize());
    info!("Config: Windows: {} Duration: {}",
          config.windows(),
          config.duration());
    match config.request_timeout() {
        Some(v) => {
            info!("Config: Request Timeout: {} ms", v);
        }
        None => {
            info!("Config: Request Timeout: None");
        }
    }
    match config.connect_timeout() {
        Some(v) => {
            info!("Config: Connect Timeout: {} ms", v);
        }
        None => {
            info!("Config: Connect Timeout: None");
        }
    }
}
<commit_msg>rustfmt<commit_after>//  rpc-perf - RPC Performance Testing
//  Copyright 2015 Twitter, Inc
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.

#![cfg_attr(feature = "unstable", feature(test))]
#[cfg(feature = "unstable")]
extern crate test;

#[allow(unknown_lints, useless_attribute)]
#[cfg_attr(feature = "cargo-clippy", deny(result_unwrap_used))]
#[macro_use]
extern crate log;

extern crate bytes;
extern crate byteorder;
extern crate crc;
extern crate getopts;
extern crate log_panics;
extern crate mio;
extern crate mpmc;
extern crate pad;
extern crate time;
extern crate rand;
extern crate ratelimit;
extern crate slab;
extern crate tic;
extern crate toml;

mod common;
mod cfgtypes;
mod client;
mod connection;
mod logger;
mod net;
mod options;
mod stats;
mod codec;
mod request;

use client::Client;
use net::InternetProtocol;
use request::{config, workload};
use std::{env, process, thread};

const VERSION: &'static str = env!("CARGO_PKG_VERSION");

pub fn main() {
    let args: Vec<String> = env::args().collect();
    let program = &args[0];
    let opts = options::opts();

    let matches = match opts.parse(&args[1..]) {
        Ok(m) => m,
        Err(f) => {
            println!("ERROR {}", f);
            options::print_usage(program, &opts);
            process::exit(1);
        }
    };

    if matches.opt_present("help") {
        options::print_usage(program, &opts);
        return;
    }

    if matches.opt_present("version") {
        println!("rpc-perf {}", VERSION);
        return;
    }

    // initialize logging
    logger::set_log_level(matches.opt_count("verbose"));
    log_panics::init();

    info!("rpc-perf {} initializing...", VERSION);
    if cfg!(feature = "asm") {
        info!("feature: asm: enabled");
    } else {
        info!("feature: asm: disabled");
    }

    let servers: Vec<String> = matches.opt_strs("server");

    if servers.is_empty() {
        error!("require server parameter");
        options::print_usage(program, &opts);
        return;
    }

    let listen = matches.opt_str("listen");
    let waterfall = matches.opt_str("waterfall");
    let trace = matches.opt_str("trace");

    // Load workload configuration
    let config = match config::load_config(&matches) {
        Ok(cfg) => cfg,
        Err(e) => {
            error!("{}", e);
            return;
        }
    };

    let internet_protocol = match net::choose_layer_3(matches.opt_present("ipv4"),
                                                      matches.opt_present("ipv6")) {
        Ok(i) => i,
        Err(e) => {
            error!("{}", e);
            return;
        }
    };

    print_config(&config, &servers, internet_protocol);

    let stats_receiver = stats::stats_receiver_init(&config, listen, waterfall, trace);

    let mut send_queues = Vec::new();

    let mut client_config = Client::configure();

    client_config
        .set_pool_size(config.poolsize())
        .stats(stats_receiver.get_sender().clone())
        .set_clocksource(stats_receiver.get_clocksource().clone())
        .set_protocol(config.protocol_config.protocol.clone())
        .set_request_timeout(config.request_timeout())
        .set_connect_timeout(config.connect_timeout())
        .set_internet_protocol(internet_protocol);

    for server in servers {
        client_config.add_server(server);
    }

    info!("-----");
    info!("Connecting...");
    for i in 0..config.threads() {
        info!("Client: {}", i);

        let mut client = client_config.clone().build();
        send_queues.push(client.tx());

        let _ = thread::Builder::new()
            .name(format!("client{}", i).to_string())
            .spawn(move || { client.run(); });
    }

    info!("-----");
    info!("Workload:");

    let windows = config.windows();

    workload::launch_workloads(config.protocol_config.workloads,
                               &send_queues,
                               &stats_receiver.get_sender(),
                               &stats_receiver.get_clocksource());

    stats::run(stats_receiver, windows, matches.opt_present("service"));
}

fn print_config(config: &request::BenchmarkConfig,
                servers: &[String],
                internet_protocol: InternetProtocol) {
    info!("-----");
    info!("Config:");
    for server in servers {
        info!("Config: Server: {} Protocol: {}",
              server,
              config.protocol_config.protocol.name());
    }
    info!("Config: IP: {:?} TCP_NODELAY: {}",
          internet_protocol,
          config.tcp_nodelay());
    info!("Config: Threads: {} Poolsize: {}",
          config.threads(),
          config.poolsize());
    info!("Config: Windows: {} Duration: {}",
          config.windows(),
          config.duration());
    match config.request_timeout() {
        Some(v) => {
            info!("Config: Request Timeout: {} ms", v);
        }
        None => {
            info!("Config: Request Timeout: None");
        }
    }
    match config.connect_timeout() {
        Some(v) => {
            info!("Config: Connect Timeout: {} ms", v);
        }
        None => {
            info!("Config: Connect Timeout: None");
        }
    }
}
<|endoftext|>