<commit_before>extern crate clap;
extern crate walkdir;
extern crate twox_hash;

use std::collections::HashMap;
use std::collections::HashSet;
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::os::linux::fs::MetadataExt;

use clap::{App, Arg, ArgMatches};
use walkdir::WalkDir;
use twox_hash::XxHash;
use std::hash::Hasher;

#[derive(Default)]
struct Stats {
    file_count: u64,
    total_size: u64,
    duplicate_count: u64,
}

fn parse_args<'a>() -> ArgMatches<'a> {
    App::new("dupr")
        .version("0.1.0")
        .author("Mike Sampson")
        .about("Duplicate file finder")
        .arg(
            Arg::with_name("DIR")
                .help("Directory to process")
                .required(true),
        )
        .arg(Arg::with_name("summary").short("s").long("summary").help(
            "Print out summary information after duplicates",
        ))
        .get_matches()
}

fn collect_paths(path: &str, stats: &mut Stats) -> HashMap<u64, Vec<PathBuf>> {

    let mut length_paths = HashMap::new();
    let spinner = ["|", "/", "-", "\\"];

    for (idx, entry) in WalkDir::new(path).into_iter().enumerate() {
        eprint!("\rBuilding file list {}", spinner[idx % spinner.len()]);
        let entry = match entry {
            Ok(e) => e,
            Err(err) => {
                eprintln!("dupr: {}", err);
                continue;
            }
        };

        if !entry.file_type().is_file() {
            continue;
        }

        let metadata = match entry.metadata() {
            Ok(e) => e,
            Err(err) => {
                eprintln!("dupr: {}", err);
                continue;
            }
        };

        if metadata.len() == 0 {
            continue;
        }

        stats.file_count += 1;
        stats.total_size += metadata.len();

        let path = entry.path().to_path_buf();

        length_paths
            .entry(metadata.len())
            .or_insert(Vec::new())
            .push(path);
    }
    eprint!("\r");
    length_paths
}

fn main() {
    let matches = parse_args();

    let mut stats: Stats = Default::default();

    let files = collect_paths(matches.value_of("DIR").unwrap(), &mut stats);

    let mut len_hash_path = HashMap::new();

    // iterate over length buckets when no. files > 1
    for (len, paths) in files.iter().filter(|&(_, v)| v.len() > 1) {

        let mut hardlinks = HashSet::new();

        for path in paths {
            // only save if not a hardlink to existing file
            let metadata = match path.metadata() {
                Ok(m) => m,
                Err(err) => {
                    eprintln!("dupr: {}", err);
                    continue;
                }
            };

            let dev_inode = (metadata.st_dev(), metadata.st_ino());

            if hardlinks.contains(&dev_inode) {
                continue;
            }

            hardlinks.insert(dev_inode);

            len_hash_path
                .entry((len, hash_file(&path)))
                .or_insert(Vec::new())
                .push(path);
        }
    }

    for paths in len_hash_path.values().filter(|p| p.len() > 1) {
        for path in paths {
            println!("{}", path.display());
        }
        println!();
    }

    if matches.is_present("summary") {
        println!(
            "Processed {} files with a total size of {} bytes. {} duplicates found.",
            stats.file_count,
            stats.total_size,
            stats.duplicate_count
        );
    }
}

fn hash_file<P: AsRef<Path>>(path: P) -> u64 {
    let mut file = File::open(path).unwrap();

    let mut hash = XxHash::with_seed(0);

    let mut buffer = [0; 32 * 1024];

    while let Ok(n) = file.read(&mut buffer) {
        if n == 0 {
            break;
        }
        hash.write(&buffer[0..n]);
    }

    hash.finish()
}
<commit_msg>Add noempty option<commit_after>extern crate clap;
extern crate walkdir;
extern crate twox_hash;

use std::collections::HashMap;
use std::collections::HashSet;
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::os::linux::fs::MetadataExt;

use clap::{App, Arg, ArgMatches};
use walkdir::WalkDir;
use twox_hash::XxHash;
use std::hash::Hasher;

#[derive(Default)]
struct Stats {
    file_count: u64,
    total_size: u64,
    duplicate_count: u64,
}

fn parse_args<'a>() -> ArgMatches<'a> {
    App::new("dupr")
        .version("0.1.0")
        .author("Mike Sampson")
        .about("Duplicate file finder")
        .arg(
            Arg::with_name("DIR")
                .help("Directory to process")
                .required(true),
        )
        .arg(Arg::with_name("noempty").short("n").long("noempty").help(
            "Exclude zero length files",
        ))
        .arg(Arg::with_name("summary").short("s").long("summary").help(
            "Print out summary information after duplicates",
        ))
        .get_matches()
}

fn collect_paths(path: &str, noempty: bool, stats: &mut Stats) -> HashMap<u64, Vec<PathBuf>> {

    let mut length_paths = HashMap::new();
    let spinner = ["|", "/", "-", "\\"];

    for (idx, entry) in WalkDir::new(path).into_iter().enumerate() {
        eprint!("\rBuilding file list {}", spinner[idx % spinner.len()]);
        let entry = match entry {
            Ok(e) => e,
            Err(err) => {
                eprintln!("dupr: {}", err);
                continue;
            }
        };

        if !entry.file_type().is_file() {
            continue;
        }

        let metadata = match entry.metadata() {
            Ok(e) => e,
            Err(err) => {
                eprintln!("dupr: {}", err);
                continue;
            }
        };

        if noempty && metadata.len() == 0 {
            continue;
        }

        stats.file_count += 1;
        stats.total_size += metadata.len();

        let path = entry.path().to_path_buf();

        length_paths
            .entry(metadata.len())
            .or_insert(Vec::new())
            .push(path);
    }
    eprint!("\r");
    length_paths
}

fn main() {
    let matches = parse_args();

    let mut stats: Stats = Default::default();

    let files = collect_paths(matches.value_of("DIR").unwrap(), matches.is_present("noempty"), &mut stats);

    let mut len_hash_path = HashMap::new();

    // iterate over length buckets when no. files > 1
    for (len, paths) in files.iter().filter(|&(_, v)| v.len() > 1) {

        let mut hardlinks = HashSet::new();

        for path in paths {
            // only save if not a hardlink to existing file
            let metadata = match path.metadata() {
                Ok(m) => m,
                Err(err) => {
                    eprintln!("dupr: {}", err);
                    continue;
                }
            };

            let dev_inode = (metadata.st_dev(), metadata.st_ino());

            if hardlinks.contains(&dev_inode) {
                continue;
            }

            hardlinks.insert(dev_inode);

            len_hash_path
                .entry((len, hash_file(&path)))
                .or_insert(Vec::new())
                .push(path);
        }
    }

    for paths in len_hash_path.values().filter(|p| p.len() > 1) {
        for path in paths {
            println!("{}", path.display());
        }
        println!();
    }

    if matches.is_present("summary") {
        println!(
            "Processed {} files with a total size of {} bytes. {} duplicates found.",
            stats.file_count,
            stats.total_size,
            stats.duplicate_count
        );
    }
}

fn hash_file<P: AsRef<Path>>(path: P) -> u64 {
    let mut file = File::open(path).unwrap();

    let mut hash = XxHash::with_seed(0);

    let mut buffer = [0; 32 * 1024];

    while let Ok(n) = file.read(&mut buffer) {
        if n == 0 {
            break;
        }
        hash.write(&buffer[0..n]);
    }

    hash.finish()
}
<|endoftext|>


<commit_before>extern crate orbclient;

use orbclient::window::EventIter;

use std::time::Instant;

struct RenderContext {
    window: Box<orbclient::Window>,
    scan_buffer: Vec<u32> //TODO(dustin): do i need Vec<32> here? [i32]
}

impl RenderContext {
    pub fn new(width: u32, height: u32, title: &str) -> RenderContext {
        let orb_window = orbclient::Window::new_flags(100, 100, width, height, title, true).unwrap();
        RenderContext{scan_buffer: vec![0; (height * 2) as usize], window: orb_window}
    }

    pub fn events(&mut self) -> EventIter {
        self.window.events()
    }

    pub fn draw_scan_buffer(&mut self, y_coord: u32, x_min: u32, x_max: u32 ) {
        self.scan_buffer.insert((y_coord * 2) as usize, x_min);
        self.scan_buffer.insert((y_coord * 2 + 1 ) as usize, x_max);

    }

    pub fn clear(&mut self) {
        self.window.set(orbclient::Color { data: 0xFF000000 });
    }

    pub fn sync(&mut self) {
        self.window.sync();
    }

    pub fn fill_shape(&mut self, y_min: u32, y_max: u32) {

        for y_idx in y_min..y_max {
            let x_min = self.scan_buffer.get((y_idx * 2) as usize).unwrap().clone();
            let x_max = self.scan_buffer.get((y_idx * 2 + 1) as usize).unwrap().clone();

            for x_idx in x_min..x_max {
                self.window.pixel(x_idx as i32, y_idx as i32, orbclient::Color { data: 0xFFFFFFFF });
            }
        }
    }
}

fn main() {

    let mut render_context = RenderContext::new(500, 400, "pixelcannon");
    let mut start = Instant::now();

    'event: loop {

        {
            let end = Instant::now();
            let delta = end.duration_since(start);
            start = Instant::now();

            println!("{} ms", delta.as_secs() * 1000 + (delta.subsec_nanos() as u64)/1000000);

            render_context.clear();
            for scan in 100..200 {
                render_context.draw_scan_buffer(scan, 300 - scan, 300 + scan);
            }
            render_context.fill_shape(100, 200);
            render_context.sync();
        }

        for orbital_event in render_context.events() {
            match orbital_event.to_option() {
                orbclient::EventOption::Quit(_quit_event) => break 'event,
                _ => (),
            };
        }

    }
}
<commit_msg>convert triangle<commit_after>extern crate orbclient;

use orbclient::window::EventIter;

use std::time::Instant;

struct Vertex {
    x: f32,
    y: f32
}

struct RenderContext {
    window: Box<orbclient::Window>,
    scan_buffer: Vec<u32> //TODO(dustin): do i need Vec<32> here? [i32]
}

impl RenderContext {
    pub fn new(width: u32, height: u32, title: &str) -> RenderContext {
        let orb_window = orbclient::Window::new_flags(100, 100, width, height, title, true).unwrap();
        RenderContext{scan_buffer: vec![0; (height * 2) as usize], window: orb_window}
    }

    pub fn events(&mut self) -> EventIter {
        self.window.events()
    }

    pub fn clear(&mut self) {
        self.window.set(orbclient::Color { data: 0xFF000000 });
    }

    pub fn sync(&mut self) {
        self.window.sync();
    }

    pub fn fill_convex_shape(&mut self, y_min: u32, y_max: u32) {

        for y_idx in y_min..y_max {
            let x_min = self.scan_buffer.get((y_idx * 2) as usize).unwrap().clone();
            let x_max = self.scan_buffer.get((y_idx * 2 + 1) as usize).unwrap().clone();

            for x_idx in x_min..x_max {
                self.window.pixel(x_idx as i32, y_idx as i32, orbclient::Color { data: 0xFFFFFFFF });
            }
        }
    }

    pub fn convert_triangle(&mut self, min_vert: &Vertex, mid_vert: &Vertex, max_vert: &Vertex, side: i32) {
		self.convert_line(min_vert, max_vert, 0 + side);
		self.convert_line(min_vert, mid_vert, 1 - side);
		self.convert_line(mid_vert, max_vert, 1 - side);
	}

	fn convert_line(&mut self, min_vert: &Vertex, max_vert: &Vertex, side: i32) {
        let start_y = min_vert.y;
        let start_x = min_vert.x;
        let end_y = max_vert.y;
        let end_x = max_vert.x;

        let dist_y = end_y - start_y;
        let dist_x = end_x - start_x;

		if dist_y <= 0f32 {
			return;
		}

		let setp_x = dist_x as f32 / dist_y as f32;
		let mut current_x = start_x;

        for y_coord in start_y as i32..end_y as i32 {
            self.scan_buffer.insert((y_coord * 2 + side) as usize, current_x as u32);
            current_x += setp_x;
        }
	}

}

fn main() {

    let mut render_context = RenderContext::new(500, 400, "pixelcannon");
    let mut start = Instant::now();

    let min_vert = Vertex{x: 100f32, y: 50f32};
    let mid_vert = Vertex{x: 200f32, y: 200f32};
    let max_vert = Vertex{x: 70f32, y: 300f32};

    'event: loop {

        {
            let end = Instant::now();
            let delta = end.duration_since(start);
            let delta_ms = delta.as_secs() * 1000 + (delta.subsec_nanos() as u64)/1000000;
            start = Instant::now();
            // println!("{} ms", delta_ms);

            render_context.clear();
            render_context.convert_triangle(&min_vert, &mid_vert, &max_vert, 0);
            render_context.fill_convex_shape(50, 300);
            render_context.sync();
        }

        for orbital_event in render_context.events() {
            match orbital_event.to_option() {
                orbclient::EventOption::Quit(_quit_event) => break 'event,
                _ => (),
            };
        }

    }
}
<|endoftext|>


<commit_before>extern crate chattium_oxide_lib;
extern crate yaml_file_handler;
extern crate hyper;
extern crate clap;

mod io;
mod options;

use io::read_unprompted;
use options::Options;
use hyper::client::Client;
use std::io::{stderr, Write};
use chattium_oxide_lib::{ChatMessage, ChatUser};
use chattium_oxide_lib::json::ToJsonnable;

fn main() {
	let client = Client::new();
	let options = Options::parse();

	while let Ok(Some(rmessage)) = read_unprompted() {
		match ChatMessage::new(ChatUser::me(options.name.clone()), rmessage).to_json_string() {
			Ok(json) =>
				match client.post(&*&options.server).body(&*&json).send() {
					Ok(response) => println!("Server responded with status {}", response.status),
					Err(error) => {let _ = stderr().write_fmt(format_args!("POSTing the message failed: {}", error));},
				},
			Err(error) => {let _ = stderr().write_fmt(format_args!("Couldn't serialize message: {}", error));},
		}
	}
}
<commit_msg>Add newlines after error messages<commit_after>extern crate chattium_oxide_lib;
extern crate yaml_file_handler;
extern crate hyper;
extern crate clap;

mod io;
mod options;

use io::read_unprompted;
use options::Options;
use hyper::client::Client;
use std::io::{stderr, Write};
use chattium_oxide_lib::{ChatMessage, ChatUser};
use chattium_oxide_lib::json::ToJsonnable;

fn main() {
	let client = Client::new();
	let options = Options::parse();

	while let Ok(Some(rmessage)) = read_unprompted() {
		match ChatMessage::new(ChatUser::me(options.name.clone()), rmessage).to_json_string() {
			Ok(json) =>
				match client.post(&*&options.server).body(&*&json).send() {
					Ok(response) => println!("Server responded with status {}", response.status),
					Err(error) => {let _ = stderr().write_fmt(format_args!("POSTing the message failed: {}\n", error));},
				},
			Err(error) => {let _ = stderr().write_fmt(format_args!("Couldn't serialize message: {}\n", error));},
		}
	}
}
<|endoftext|>


<commit_before>extern crate wm_daemons;
use wm_daemons::config::{load_config, load_config_path};
use wm_daemons::dbus_listen::{CallbackMap, match_method};

#[macro_use]
extern crate clap;
use clap::{Arg, App};

extern crate config;
use self::config::types::Config;

extern crate dbus;
use self::dbus::{Connection, BusType};

use std::error::Error;
use std::path::Path;

fn try_main() -> Result<(), Box<Error>> {
    let matches = App::new("ruskey")
        .version(&crate_version!()[..])
        .author("Ben Boeckel <mathstuf@gmail.com>")
        .about("Implement the SecretService API for keepass databases")
        .arg(Arg::with_name("CONFIG")
                .short("c")
                .long("config")
                .help("Path to the configuration file")
                .takes_value(true))
        .arg(Arg::with_name("DATABASE_NAME")
                .short("n")
                .long("name")
                .help("Name of the database")
                .takes_value(true))
        .arg(Arg::with_name("DATABASE")
                .short("d")
                .long("database")
                .help("Path to the database")
                .takes_value(true))
        .get_matches();

    let conf = try!(if matches.is_present("CONFIG") {
            load_config_path(Path::new(matches.value_of("CONFIG").unwrap()))
        } else {
            load_config("ruskey", "config")
        });

    let conn = try!(Connection::get_private(BusType::Session));

    let cbs: CallbackMap<Config> = vec![
        // TODO
    ];

    let match_str = "";
    try!(conn.add_match(match_str));

    conn.iter(100).fold(conf, |inner_conf, item| {
        match_method(inner_conf, &cbs, item)
    });

    Ok(())
}

fn main() {
    if let Err(err) = try_main() {
        panic!("{}", err.description());
    }
}
<commit_msg>main: use a context struct for iteration<commit_after>extern crate wm_daemons;
use wm_daemons::config::{load_config, load_config_path};
use wm_daemons::dbus_listen::{CallbackMap, match_method};

#[macro_use]
extern crate clap;
use clap::{Arg, App};

extern crate config;
use self::config::types::Config;

extern crate dbus;
use self::dbus::{Connection, BusType};

use std::error::Error;
use std::path::Path;

struct Context {
    conf: &Config,
}

fn try_main() -> Result<(), Box<Error>> {
    let matches = App::new("ruskey")
        .version(&crate_version!()[..])
        .author("Ben Boeckel <mathstuf@gmail.com>")
        .about("Implement the SecretService API for keepass databases")
        .arg(Arg::with_name("CONFIG")
                .short("c")
                .long("config")
                .help("Path to the configuration file")
                .takes_value(true))
        .arg(Arg::with_name("DATABASE_NAME")
                .short("n")
                .long("name")
                .help("Name of the database")
                .takes_value(true))
        .arg(Arg::with_name("DATABASE")
                .short("d")
                .long("database")
                .help("Path to the database")
                .takes_value(true))
        .get_matches();

    let conf = try!(if matches.is_present("CONFIG") {
            load_config_path(Path::new(matches.value_of("CONFIG").unwrap()))
        } else {
            load_config("ruskey", "config")
        });

    let conn = try!(Connection::get_private(BusType::Session));

    let cbs: CallbackMap<Context> = vec![
        // TODO
    ];
    let ctx = Context {
        conf: &conf,
    };

    let match_str = "";
    try!(conn.add_match(match_str));

    conn.iter(100).fold(ctx, |inner_ctx, item| {
        match_method(inner_ctx, &cbs, item)
    });

    Ok(())
}

fn main() {
    if let Err(err) = try_main() {
        panic!("{}", err.description());
    }
}
<|endoftext|>


<commit_before>#![feature(plugin)]
#![feature(test)]

#![plugin(peg_syntax_ext)]

#[macro_use]
extern crate nom;
extern crate clap;
extern crate termion;
extern crate byteorder;
extern crate env_logger;

#[macro_use]
extern crate log;

mod db;

use db::server::Server;
use db::database::{Database, QueryResult};
use clap::{Arg, App, SubCommand};

use std::io::{self, Read};
use std::io::{Write, stdout, stdin};

use termion::input::TermRead;
use termion::{color, style};

fn main() {
    println!("Starting the worst database ever created!!");
    let server = Server::new();
    let app = App::new("StreamingDB")
                  .version("v1.0")
                  .author("Jon Haddad, <jon@jonhaddad.com>")
                  .subcommand(SubCommand::with_name("test"))
                  .get_matches();

    if let Some(matches) = app.subcommand_matches("test") {
        run_test_repl();
    }

}

fn run_test_repl() {
    println!("Running test repl");
    let mut db = Database::new();
    let mut stdin = stdin();
    let mut stdout = stdout();
    let prompt = "embedded>";

    let _ = env_logger::init();

    loop {

        write!(stdout, "{}[?] {}{} ", color::Fg(color::Green), style::Reset, prompt).unwrap();
        stdout.lock().flush().unwrap();

        match TermRead::read_line(&mut stdin) {
            Ok(Some(buffer)) => {
                let x= match db.execute(&buffer) {
                    Ok(QueryResult::StreamCreated) =>
                        String::from("Stream Created.\n"),
                    Ok(QueryResult::Insert(id)) =>
                        format!("Inserted {}", id),
                    _ => String::from("Fail?")

                };
                println!("{}", x);
            },
            Ok(None) => {},
            Err(e) => {}
        }
    }

}
<commit_msg>support for exit<commit_after>#![feature(plugin)]
#![feature(test)]

#![plugin(peg_syntax_ext)]

#[macro_use]
extern crate nom;
extern crate clap;
extern crate termion;
extern crate byteorder;
extern crate env_logger;

#[macro_use]
extern crate log;

mod db;

use db::server::Server;
use db::database::{Database, QueryResult};
use clap::{Arg, App, SubCommand};

use std::io::{self, Read};
use std::io::{Write, stdout, stdin};

use termion::input::TermRead;
use termion::{color, style};

fn main() {
    println!("Starting the worst database ever created!! (exit to exit)");
    let server = Server::new();
    let app = App::new("StreamingDB")
                  .version("v1.0")
                  .author("Jon Haddad, <jon@jonhaddad.com>")
                  .subcommand(SubCommand::with_name("test"))
                  .get_matches();

    if let Some(matches) = app.subcommand_matches("test") {
        run_test_repl();
    }

}

fn run_test_repl() {
    println!("Running test repl");
    let mut db = Database::new();
    let mut stdin = stdin();
    let mut stdout = stdout();
    let prompt = "embedded>";

    let _ = env_logger::init();

    loop {

        write!(stdout, "{}[?] {}{} ", color::Fg(color::Green), style::Reset, prompt).unwrap();
        stdout.lock().flush().unwrap();

        match TermRead::read_line(&mut stdin) {
            Ok(Some(buffer)) => {
                if buffer == "exit" {
                    write!(stdout, "Exiting\r\n");
                    stdout.lock().flush().unwrap();
                    return;
                }
                let x= match db.execute(&buffer) {
                    Ok(QueryResult::StreamCreated) =>
                        String::from("Stream Created.\n"),
                    Ok(QueryResult::Insert(id)) =>
                        format!("Inserted {}", id),
                    _ => String::from("Fail?")

                };
                println!("{}", x);
            },
            Ok(None) => {},
            Err(e) => {}
        }
    }

}
<|endoftext|>


<commit_before>//#![feature(alloc_system)]
//extern crate alloc_system;   // strip down size of binary executable

extern crate id3;
extern crate tree_magic;  // mime types

use std::io;
use std::env;     // args
use std::fs::{self, DirEntry};  // directory
use std::path::Path;  // path, clear

use id3::Tag;

/// The function that runs from the starting point
fn visit_dirs(dir: &Path, cb: &Fn(&DirEntry) -> io::Result<()> ) -> io::Result<()> {
    if dir.is_dir() {
        for entry in fs::read_dir(dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_dir() {
                visit_dirs(&path, cb)?;
            } else {
                cb(&entry)?;
            }
        }
    }
    Ok(())
}

fn visit_files(cb: &DirEntry) -> io::Result<()> {
    let filetype = tree_magic::from_filepath(&cb.path());
    match filetype.as_ref() {
        "text/plain" => {},
        "audio/mpeg" => visit_audio_files(&cb.path()),
        _ => println!("[{:?}]{:?}",filetype, cb.path()),
    }
	Ok(())
}

fn visit_audio_files(cb: &Path) {
    let tag = Tag::read_from_path(cb).unwrap();
    println!("{:?}",tag.artist().unwrap())
}

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

    let mut path = ".";
    if args.len() > 1 {
        path = &args[1];
    }
    let real_path = Path::new(path);
    match visit_dirs(real_path, &visit_files) {
        _ => println!("Finished!")
    }
}
<commit_msg>3.device<commit_after>//#![feature(alloc_system)]
//extern crate alloc_system;   // strip down size of binary executable

extern crate id3;
extern crate tree_magic;  // mime types

use std::io;
use std::env;     // args
use std::fs::{self, DirEntry};  // directory
use std::path::Path;  // path, clear

use id3::Tag;

/// The function that runs from the starting point
fn visit_dirs(dir: &Path, cb: &Fn(&DirEntry) -> io::Result<()> ) -> io::Result<()> {
    if dir.is_dir() {
        for entry in fs::read_dir(dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_dir() {
                visit_dirs(&path, cb)?;
            } else {
                cb(&entry)?;
            }
        }
    }
    Ok(())
}

/// the function to check all files separately
fn visit_files(cb: &DirEntry) -> io::Result<()> {
    let filetype = tree_magic::from_filepath(&cb.path());
    match filetype.as_ref() {
        "text/plain" => {},
        "audio/mpeg" => visit_audio_files(&cb.path()),
        _ => println!("[{:?}]{:?}",filetype, cb.path()),
    }
	Ok(())
}

fn visit_audio_files(cb: &Path) {
    let tag = Tag::read_from_path(cb).unwrap();
    println!("{:?}",tag.artist().unwrap())
}

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

    let mut path = ".";
    if args.len() > 1 {
        path = &args[1];
    }
    let real_path = Path::new(path);
    match visit_dirs(real_path, &visit_files) {
        _ => println!("Finished!")
    }
}
<|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/. */

/// Simple server that manages foxbox registrations.
/// Two end points are available:
/// POST /register => to register a match between public IP and mesage.
/// GET /ping => to get the list of public IP matches.
///
/// Boxes are supposed to register themselves at regular intervals so we
/// discard data which is too old periodically.

extern crate docopt;
extern crate env_logger;
extern crate iron;
extern crate iron_cors;
#[macro_use]
extern crate log;
extern crate mount;
extern crate params;
extern crate redis;
extern crate router;
extern crate rusqlite;
extern crate rustc_serialize;

use docopt::Docopt;
use iron::{ Chain, Iron, Protocol };
use iron::method::Method;
use iron_cors::CORS;
use mount::Mount;
use std::path::PathBuf;

mod errors;
mod db;
mod routes;

#[cfg(test)]
mod db_test_context;

const USAGE: &'static str = "
Usage: registration_server [-d <db-hostname>] [--db-port <db-port>] [--db-pass <db-pass>] [-h <hostname>] [-p <port>] [--cert-directory <dir>]

Options:
    -d, --db-host <host>          Set Redis database hostname.
        --db-port <db-port>       Set Redis database port.
        --db-pass <db-pass>       Set Redis database password.
    -h, --host <host>             Set local hostname.
    -p, --port <port>             Set port to listen on for http connections.
        --cert-directory <dir>    Certificate directory.
";

#[derive(RustcDecodable)]
struct Args {
    flag_db_host: Option<String>,
    flag_db_port: Option<u16>,
    flag_db_pass: Option<String>,
    flag_host: Option<String>,
    flag_port: Option<u16>,
    flag_cert_directory: Option<String>,
}

fn main() {
    env_logger::init().unwrap();

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

    let port = args.flag_port.unwrap_or(4242);
    let host = args.flag_host.unwrap_or("0.0.0.0".to_string());
    let using_tls = args.flag_cert_directory.is_some();
    let db_host = args.flag_db_host.unwrap_or("localhost".to_string());
    let db_port = args.flag_db_port.unwrap_or(6379);
    let db_pass = args.flag_db_pass;

    info!("Redis server on {}:{}", db_host, db_port);

    let mut mount = Mount::new();
    mount.mount("/", routes::create(db_host.clone(), db_port, db_pass.clone()));

    let mut chain = Chain::new(mount);
    let cors = CORS::new(vec![
        (vec![Method::Get], "ping".to_owned()),
        (vec![Method::Post], "register".to_owned()),
    ]);
    chain.link_after(cors);

    let iron = Iron::new(chain);
    info!("Starting server on {}:{}", host, port);
    let addr = format!("{}:{}", host, port);

    if !using_tls {
        iron.http(addr.as_ref() as &str)
            .unwrap();
    } else {
        info!("Starting TLS server");
        let certificate_directory = args.flag_cert_directory.unwrap();
        let certificate_directory = PathBuf::from(certificate_directory);

        let mut private_key = certificate_directory.clone();
        private_key.push("privkey.pem");

        let mut cert = certificate_directory.clone();
        cert.push("cert.pem");

        info!("Using cert: '{:?}' pk: '{:?}'", cert, private_key);

        let protocol = Protocol::Https {
            certificate: cert,
            key: private_key,
        };
        iron.listen_with(addr.as_ref() as &str, 8, protocol, None).unwrap();
    }
}

// TODO: add iron tests.

#[test]
fn options_are_good() {
    // short form options
    {
        let argv = || vec!["registration_server", "-p", "1234", "-h", "foobar"];

        let args: Args = Docopt::new(USAGE)
            .and_then(|d| d.argv(argv().into_iter()).decode())
            .unwrap();

        assert_eq!(args.flag_host, Some("foobar".to_string()));
        assert_eq!(args.flag_port, Some(1234));
    }
}
<commit_msg>Use the fullchain cert<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/. */

/// Simple server that manages foxbox registrations.
/// Two end points are available:
/// POST /register => to register a match between public IP and mesage.
/// GET /ping => to get the list of public IP matches.
///
/// Boxes are supposed to register themselves at regular intervals so we
/// discard data which is too old periodically.

extern crate docopt;
extern crate env_logger;
extern crate iron;
extern crate iron_cors;
#[macro_use]
extern crate log;
extern crate mount;
extern crate params;
extern crate redis;
extern crate router;
extern crate rusqlite;
extern crate rustc_serialize;

use docopt::Docopt;
use iron::{ Chain, Iron, Protocol };
use iron::method::Method;
use iron_cors::CORS;
use mount::Mount;
use std::path::PathBuf;

mod errors;
mod db;
mod routes;

#[cfg(test)]
mod db_test_context;

const USAGE: &'static str = "
Usage: registration_server [-d <db-hostname>] [--db-port <db-port>] [--db-pass <db-pass>] [-h <hostname>] [-p <port>] [--cert-directory <dir>]

Options:
    -d, --db-host <host>          Set Redis database hostname.
        --db-port <db-port>       Set Redis database port.
        --db-pass <db-pass>       Set Redis database password.
    -h, --host <host>             Set local hostname.
    -p, --port <port>             Set port to listen on for http connections.
        --cert-directory <dir>    Certificate directory.
";

#[derive(RustcDecodable)]
struct Args {
    flag_db_host: Option<String>,
    flag_db_port: Option<u16>,
    flag_db_pass: Option<String>,
    flag_host: Option<String>,
    flag_port: Option<u16>,
    flag_cert_directory: Option<String>,
}

fn main() {
    env_logger::init().unwrap();

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

    let port = args.flag_port.unwrap_or(4242);
    let host = args.flag_host.unwrap_or("0.0.0.0".to_string());
    let using_tls = args.flag_cert_directory.is_some();
    let db_host = args.flag_db_host.unwrap_or("localhost".to_string());
    let db_port = args.flag_db_port.unwrap_or(6379);
    let db_pass = args.flag_db_pass;

    info!("Redis server on {}:{}", db_host, db_port);

    let mut mount = Mount::new();
    mount.mount("/", routes::create(db_host.clone(), db_port, db_pass.clone()));

    let mut chain = Chain::new(mount);
    let cors = CORS::new(vec![
        (vec![Method::Get], "ping".to_owned()),
        (vec![Method::Post], "register".to_owned()),
    ]);
    chain.link_after(cors);

    let iron = Iron::new(chain);
    info!("Starting server on {}:{}", host, port);
    let addr = format!("{}:{}", host, port);

    if !using_tls {
        iron.http(addr.as_ref() as &str)
            .unwrap();
    } else {
        info!("Starting TLS server");
        let certificate_directory = args.flag_cert_directory.unwrap();
        let certificate_directory = PathBuf::from(certificate_directory);

        let mut private_key = certificate_directory.clone();
        private_key.push("privkey.pem");

        let mut cert = certificate_directory.clone();
        cert.push("fullchain.pem");

        info!("Using cert: '{:?}' pk: '{:?}'", cert, private_key);

        let protocol = Protocol::Https {
            certificate: cert,
            key: private_key,
        };
        iron.listen_with(addr.as_ref() as &str, 8, protocol, None).unwrap();
    }
}

// TODO: add iron tests.

#[test]
fn options_are_good() {
    // short form options
    {
        let argv = || vec!["registration_server", "-p", "1234", "-h", "foobar"];

        let args: Args = Docopt::new(USAGE)
            .and_then(|d| d.argv(argv().into_iter()).decode())
            .unwrap();

        assert_eq!(args.flag_host, Some("foobar".to_string()));
        assert_eq!(args.flag_port, Some(1234));
    }
}
<|endoftext|>


<commit_before>#![feature(semaphore)]

extern crate irc;
extern crate toml;
extern crate rustc_serialize;

use irc::client::prelude::*;

#[derive(Clone, RustcDecodable, RustcEncodable, Default, PartialEq, Debug)]
struct EvalbotCfg {
    pub chan_output_prefix: String,
    pub max_channel_lines: usize,
    pub max_channel_line_len: usize,
    pub playpen_timeout: usize,
    pub eval_threads: usize,
    pub irc_config: Config
}

unsafe impl Send for EvalbotCfg {}

fn read_cfg() -> Result<EvalbotCfg, String> {
    use std::io::prelude::*;
    use std::fs::File;
    use rustc_serialize::Decodable;

    let mut f = try!(File::open("evalbot.toml")
                     .map_err(|x| format!("could not open evalbot.toml: {}", x)));
    let mut s = String::new();

    try!(f.read_to_string(&mut s)
         .map_err(|x| format!("could not read evalbot.toml: {}", x)));

    let value = try!(s.parse::<toml::Value>()
                     .map_err(|x| format!("could not parse evalbot.toml: {:?}", x)));

    EvalbotCfg::decode(&mut toml::Decoder::new(value))
         .map_err(|x| format!("could not decode evalbot.toml: {}", x))
}

#[derive(Debug)]
struct EvalReq {
    pub raw: bool,
    pub is_channel: bool,
    pub sender: String,
    pub target: String,
    pub code: String
}

fn parse_msg(message: &Message) -> Option<EvalReq> {
    let sender = message.get_source_nickname().unwrap_or("");
    if let Ok(Command::PRIVMSG(target, message)) = message.into() {
        let in_channel = target.starts_with('#');
        if !in_channel && message.contains('\x01') {
            // we don't accept code via CTCP
            return None;
        }

        let tok: Vec<&str> = message.trim().splitn(2, '>').collect();
        // in channel: rust[raw]>code...
        // in private message: [raw>]code...
        let raw = match (in_channel, tok[0]) {
            (true, "rust") => false,
            (true, "rustraw") => true,
            (false, "raw") => true,
            (false, _) => false,
            _ => return None
        };
        let code = if !raw && !in_channel {
            &message as &str
        } else {
            match tok.get(1) { Some(x) => *x, None => return None }
        };
        Some(EvalReq { raw: raw, is_channel: in_channel, sender: sender.to_owned(), target: target.to_owned(), code: code.to_owned() })
    } else {
        None
    }
}

use std::sync::{Arc, Mutex, Semaphore};
use std::thread;
use std::collections::VecDeque;

#[cfg(not(unix))]
fn evaluate(code: &str, _: usize) -> String {
    if let Ok(x) = code.parse::<usize>() {
        std::iter::repeat("X").take(x).collect::<String>()
    } else {
        "not a number".to_owned()
    }
}

#[cfg(unix)]
fn playpen_exec(command: &str, args: &[&str], input: &str, timeout: usize) -> Result<(String, String), String> {
    use std::process::{Command,Stdio};
    use std::io::Write;
    let mut child = try!(Command::new("sudo")
        .arg("playpen")
        .arg("sandbox")
        .arg("--mount-proc")
        .arg("--user=rust")
        .arg(format!("--timeout={}", timeout))
        .arg("--syscalls-file=whitelist")
        .arg("--devices=/dev/urandom:r,/dev/null:w")
        .arg("--memory-limit=128")
        .arg("--")
        .arg(command)
        .args(args)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn().map_err(|x| format!("couldn't playpen_exec; {}", x)));
    if let Some(ref mut x) = child.stdin {
        try!(x.write_all(input.as_bytes())
             .map_err(|x| format!("couldn't write to stdin; {}", x)));
    } else {
        return Err("no stdin?".to_owned());
    }
    let output = try!(child.wait_with_output().
                      map_err(|x| format!("wait_with_output failed; {}", x)));
    Ok((String::from_utf8_lossy(&output.stdout).into_owned(),
     String::from_utf8_lossy(&output.stderr).into_owned()))
}

#[cfg(unix)]
fn evaluate(code: &str, timeout: usize) -> String {
    let code = format!(
r#"#![allow(dead_code, unused_variables)]
fn show<T: std::fmt::Debug>(e: T) {{ println!("{{:?}}", e) }}
fn main() {{
    show({{
        {}
    }});
}}"#, code);
    let (stdout, stderr) = match playpen_exec("/usr/local/bin/evaluate.sh",
                                        &["-C","opt-level=2"],
                                        &code,
                                        timeout) {
        Ok(x) => x,
        Err(x) => return x
    };
    let stdout = stdout.replace("\u{FF}", "");
    let mut out = String::new();
    for line in stdout.lines() {
        out.push_str(&format!("stdout: {}\n", line));
    }
    for line in stderr.lines() {
        out.push_str(&format!("stderr: {}\n", line));
    }
    out
}

fn wrap_output<'a>(input: &'a str, max_len: usize) -> Vec<&'a str> {
    let mut ret = vec![];
    for line in input.lines() {
        let line = line.trim();
        if line.len() <= max_len {
            ret.push(line);
        } else {
            let mut leftover = line;
            while let Some((idx, _)) = leftover.char_indices().nth(max_len) {
                let (part, after) = leftover.split_at(idx);
                ret.push(part);
                leftover = after;
            }
            if leftover.len() > 0 {
                ret.push(leftover);
            }
        }
    }
    ret
}

fn evaluate_loop<'a, S, T, U>(conn: Arc<S>, requests: Arc<Mutex<VecDeque<EvalReq>>>, has_work: Arc<Semaphore>, cfg: Arc<EvalbotCfg>) -> !
    where T: IrcRead, U: IrcWrite, S: ServerExt<'a, T, U> + Sized {
    macro_rules! send_msg {
        ($dest:expr, $line:expr) => {
            match conn.send_privmsg($dest, $line) {
                Err(x) => println!("failed to send message: {}", x),
                _ => ()
            }
        };
    }
    loop {
        has_work.acquire();
        if let Some(work) = requests.lock().unwrap().pop_front() {
            let result = evaluate(&work.code, cfg.playpen_timeout);
            let result = wrap_output(&result,
                                     if work.is_channel { cfg.max_channel_line_len }
                                     else { 425 });
            // TODO: gist the overflow
            let max_lines = if work.is_channel { cfg.max_channel_lines } else { usize::max_value() };
            let max_lines = std::cmp::min(max_lines, result.len());
            let dest = if work.is_channel { &work.target } else { &work.sender };
            for line in result[0..max_lines].iter() {
                let line = format!("{}{}", if work.is_channel { &cfg.chan_output_prefix as &str } else { "" }, line);
                send_msg!(dest, &line);
            }
            if max_lines < result.len() {
                send_msg!(dest, "(output truncated)");
            }
        }
    }
}

fn main() {
    let config = match read_cfg() {
        Ok(x) => x,
        Err(x) => panic!("could not read config; {}", x)
    };
    println!("read config: {:?}", config);

    let conn = Arc::new(IrcServer::from_config(config.irc_config.clone()).unwrap());
    let config = Arc::new(config);
    let evalreqs = Arc::new(Mutex::new(VecDeque::new()));
    let has_work = Arc::new(Semaphore::new(0));
    for _ in 0..config.eval_threads {
        let conn = conn.clone();
        let evalreqs = evalreqs.clone();
        let has_work = has_work.clone();
        let config = config.clone();
        thread::spawn(move || { evaluate_loop(conn, evalreqs, has_work, config.clone()); });
    }
    loop {
        conn.identify().unwrap();
        for maybe_msg in conn.iter() {
            let msg = match maybe_msg {
                Ok(x) => x,
                Err(x) => {
                    println!("{}, reconnecting", x);
                    break
                }
            };

            if let Some(x) = parse_msg(&msg) {
                println!("{} @ {} (raw: {}): {}", x.sender, x.target, x.raw, x.code);
                evalreqs.lock().unwrap().push_back(x); // if mutex is poisoned, just bail
                has_work.release();
            }
        }
        conn.reconnect().unwrap();
    }
}
<commit_msg>Replace U+FFFD not 0xFF<commit_after>#![feature(semaphore)]

extern crate irc;
extern crate toml;
extern crate rustc_serialize;

use irc::client::prelude::*;

#[derive(Clone, RustcDecodable, RustcEncodable, Default, PartialEq, Debug)]
struct EvalbotCfg {
    pub chan_output_prefix: String,
    pub max_channel_lines: usize,
    pub max_channel_line_len: usize,
    pub playpen_timeout: usize,
    pub eval_threads: usize,
    pub irc_config: Config
}

unsafe impl Send for EvalbotCfg {}

fn read_cfg() -> Result<EvalbotCfg, String> {
    use std::io::prelude::*;
    use std::fs::File;
    use rustc_serialize::Decodable;

    let mut f = try!(File::open("evalbot.toml")
                     .map_err(|x| format!("could not open evalbot.toml: {}", x)));
    let mut s = String::new();

    try!(f.read_to_string(&mut s)
         .map_err(|x| format!("could not read evalbot.toml: {}", x)));

    let value = try!(s.parse::<toml::Value>()
                     .map_err(|x| format!("could not parse evalbot.toml: {:?}", x)));

    EvalbotCfg::decode(&mut toml::Decoder::new(value))
         .map_err(|x| format!("could not decode evalbot.toml: {}", x))
}

#[derive(Debug)]
struct EvalReq {
    pub raw: bool,
    pub is_channel: bool,
    pub sender: String,
    pub target: String,
    pub code: String
}

fn parse_msg(message: &Message) -> Option<EvalReq> {
    let sender = message.get_source_nickname().unwrap_or("");
    if let Ok(Command::PRIVMSG(target, message)) = message.into() {
        let in_channel = target.starts_with('#');
        if !in_channel && message.contains('\x01') {
            // we don't accept code via CTCP
            return None;
        }

        let tok: Vec<&str> = message.trim().splitn(2, '>').collect();
        // in channel: rust[raw]>code...
        // in private message: [raw>]code...
        let raw = match (in_channel, tok[0]) {
            (true, "rust") => false,
            (true, "rustraw") => true,
            (false, "raw") => true,
            (false, _) => false,
            _ => return None
        };
        let code = if !raw && !in_channel {
            &message as &str
        } else {
            match tok.get(1) { Some(x) => *x, None => return None }
        };
        Some(EvalReq { raw: raw, is_channel: in_channel, sender: sender.to_owned(), target: target.to_owned(), code: code.to_owned() })
    } else {
        None
    }
}

use std::sync::{Arc, Mutex, Semaphore};
use std::thread;
use std::collections::VecDeque;

#[cfg(not(unix))]
fn evaluate(code: &str, _: usize) -> String {
    if let Ok(x) = code.parse::<usize>() {
        std::iter::repeat("X").take(x).collect::<String>()
    } else {
        "not a number".to_owned()
    }
}

#[cfg(unix)]
fn playpen_exec(command: &str, args: &[&str], input: &str, timeout: usize) -> Result<(String, String), String> {
    use std::process::{Command,Stdio};
    use std::io::Write;
    let mut child = try!(Command::new("sudo")
        .arg("playpen")
        .arg("sandbox")
        .arg("--mount-proc")
        .arg("--user=rust")
        .arg(format!("--timeout={}", timeout))
        .arg("--syscalls-file=whitelist")
        .arg("--devices=/dev/urandom:r,/dev/null:w")
        .arg("--memory-limit=128")
        .arg("--")
        .arg(command)
        .args(args)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn().map_err(|x| format!("couldn't playpen_exec; {}", x)));
    if let Some(ref mut x) = child.stdin {
        try!(x.write_all(input.as_bytes())
             .map_err(|x| format!("couldn't write to stdin; {}", x)));
    } else {
        return Err("no stdin?".to_owned());
    }
    let output = try!(child.wait_with_output().
                      map_err(|x| format!("wait_with_output failed; {}", x)));
    Ok((String::from_utf8_lossy(&output.stdout).into_owned(),
     String::from_utf8_lossy(&output.stderr).into_owned()))
}

#[cfg(unix)]
fn evaluate(code: &str, timeout: usize) -> String {
    let code = format!(
r#"#![allow(dead_code, unused_variables)]
fn show<T: std::fmt::Debug>(e: T) {{ println!("{{:?}}", e) }}
fn main() {{
    show({{
        {}
    }});
}}"#, code);
    let (stdout, stderr) = match playpen_exec("/usr/local/bin/evaluate.sh",
                                        &["-C","opt-level=2"],
                                        &code,
                                        timeout) {
        Ok(x) => x,
        Err(x) => return x
    };
    let stdout = stdout.replace("\u{FFFD}", "");
    let mut out = String::new();
    for line in stdout.lines() {
        out.push_str(&format!("stdout: {}\n", line));
    }
    for line in stderr.lines() {
        out.push_str(&format!("stderr: {}\n", line));
    }
    out
}

fn wrap_output<'a>(input: &'a str, max_len: usize) -> Vec<&'a str> {
    let mut ret = vec![];
    for line in input.lines() {
        let line = line.trim();
        if line.len() <= max_len {
            ret.push(line);
        } else {
            let mut leftover = line;
            while let Some((idx, _)) = leftover.char_indices().nth(max_len) {
                let (part, after) = leftover.split_at(idx);
                ret.push(part);
                leftover = after;
            }
            if leftover.len() > 0 {
                ret.push(leftover);
            }
        }
    }
    ret
}

fn evaluate_loop<'a, S, T, U>(conn: Arc<S>, requests: Arc<Mutex<VecDeque<EvalReq>>>, has_work: Arc<Semaphore>, cfg: Arc<EvalbotCfg>) -> !
    where T: IrcRead, U: IrcWrite, S: ServerExt<'a, T, U> + Sized {
    macro_rules! send_msg {
        ($dest:expr, $line:expr) => {
            match conn.send_privmsg($dest, $line) {
                Err(x) => println!("failed to send message: {}", x),
                _ => ()
            }
        };
    }
    loop {
        has_work.acquire();
        if let Some(work) = requests.lock().unwrap().pop_front() {
            let result = evaluate(&work.code, cfg.playpen_timeout);
            let result = wrap_output(&result,
                                     if work.is_channel { cfg.max_channel_line_len }
                                     else { 425 });
            // TODO: gist the overflow
            let max_lines = if work.is_channel { cfg.max_channel_lines } else { usize::max_value() };
            let max_lines = std::cmp::min(max_lines, result.len());
            let dest = if work.is_channel { &work.target } else { &work.sender };
            for line in result[0..max_lines].iter() {
                let line = format!("{}{}", if work.is_channel { &cfg.chan_output_prefix as &str } else { "" }, line);
                send_msg!(dest, &line);
            }
            if max_lines < result.len() {
                send_msg!(dest, "(output truncated)");
            }
        }
    }
}

fn main() {
    let config = match read_cfg() {
        Ok(x) => x,
        Err(x) => panic!("could not read config; {}", x)
    };
    println!("read config: {:?}", config);

    let conn = Arc::new(IrcServer::from_config(config.irc_config.clone()).unwrap());
    let config = Arc::new(config);
    let evalreqs = Arc::new(Mutex::new(VecDeque::new()));
    let has_work = Arc::new(Semaphore::new(0));
    for _ in 0..config.eval_threads {
        let conn = conn.clone();
        let evalreqs = evalreqs.clone();
        let has_work = has_work.clone();
        let config = config.clone();
        thread::spawn(move || { evaluate_loop(conn, evalreqs, has_work, config.clone()); });
    }
    loop {
        conn.identify().unwrap();
        for maybe_msg in conn.iter() {
            let msg = match maybe_msg {
                Ok(x) => x,
                Err(x) => {
                    println!("{}, reconnecting", x);
                    break
                }
            };

            if let Some(x) = parse_msg(&msg) {
                println!("{} @ {} (raw: {}): {}", x.sender, x.target, x.raw, x.code);
                evalreqs.lock().unwrap().push_back(x); // if mutex is poisoned, just bail
                has_work.release();
            }
        }
        conn.reconnect().unwrap();
    }
}
<|endoftext|>


<commit_before>
#[macro_use]
extern crate nom;

use nom::*;

fn c_always_true(_c: char) -> bool { true }
fn c_is_alphanumeric(c: char) -> bool { c.is_alphanumeric() }
fn c_is_alphabetic(c: char) -> bool { c.is_alphabetic() }
fn c_is_path_element(c: char) -> bool {
    c.is_alphanumeric() || c == ' ' || c == '/' || c == '-' || c == '_' || c == '.'
}

#[derive(PartialEq, Eq, Clone, Debug)]
enum SystemdItem {
    Comment(String),
    Category(String),
    Directive(String, String),
}

named!(take_whole_line<&str, &str>, take_while_s!(c_always_true));

#[test]
fn take_whole_line_returns_whole_line() {
    let input = " yo 👋!";
    let res = take_whole_line(input);

    assert!(res.is_done());
    assert_eq!(input, res.unwrap().1)
}

named!(
    parse_comment<&str, SystemdItem>,
    do_parse!(
        tag_s!("#")                >>
        comment: take_whole_line   >>
        (SystemdItem::Comment(String::from(comment.trim())))
    )
);

#[test]
fn parse_comment_should_fail_when_not_starting_with_hash_char() {
    let res = parse_comment("yo");
    assert_eq!(true, res.is_err())
}

#[test]
fn parse_comment_should_be_done_when_starting_with_hash_char() {
    let res = parse_comment("# yo");
    assert_eq!(true, res.is_done())
}

#[test]
fn parse_comment_should_trim_whitespaces() {
    let res = parse_comment("# yo ");
    let expected = SystemdItem::Comment(String::from("yo"));
    assert_eq!(expected, res.unwrap().1)
}

named!(
    parse_category<&str, SystemdItem>,
    do_parse!(
        tag!("[") >>
        eat_separator!(" ") >>
        category: take_while1_s!(c_is_alphabetic) >>
        eat_separator!(" ") >>
        tag!("]") >>
        (SystemdItem::Category(String::from(category)))
    )
);

#[test]
fn parse_category_should_be_done() {
    let input = "[Category]";
    let res = parse_category(input);
    assert!(res.is_done())
}

#[test]
fn parse_category_should_consume_the_category() {
    let input = "[ Category ]";
    let res = parse_category(input);
    let expected = SystemdItem::Category(String::from("Category"));
    assert_eq!(expected, res.unwrap().1);
}

#[test]
fn parse_category_should_reject_more_than_one_word() {
    let input = "[ Category wrong ]";
    let res = parse_category(input);
    assert!(res.is_err())
}

named!(
    parse_directive<&str, SystemdItem>,
    do_parse!(
        key: take_while1_s!(c_is_alphabetic) >>
        eat_separator!(" ") >>
        tag!("=") >>
        eat_separator!(" ") >>
        value: take_while1_s!(c_is_path_element) >>
        (SystemdItem::Directive(String::from(key), String::from(value)))
    )
);

#[test]
fn parse_directive_should_be_done() {
    let input = "ExecStart=42";
    let res = parse_directive(input);

    assert!(res.is_done());
}

#[test]
fn parse_directive_should_consume_the_directive_key_and_value() {
    let input = "ExecStart = 42";
    let res = parse_directive(input);
    let expected = SystemdItem::Directive(String::from("ExecStart"), String::from("42"));

    assert_eq!(expected, res.unwrap().1);
}

#[test]
fn parse_directive_should_reject_the_directive_with_no_key() {
    let input = " = 42";
    let res = parse_directive(input);

    assert!(res.is_err());
}

#[test]
fn parse_directive_should_reject_the_directive_with_no_value() {
    let input = "Yo =";
    let res = parse_directive(input);

    assert!(res.is_err());
}

#[test]
fn parse_directive_should_reject_the_directive_with_invalid_characters() {
    let inputs = vec!["Yo == 42", "Yo =! 42", "Yo = !42", "Yo = @42"];
    for input in inputs {
        let res = parse_directive(input);
        assert!(res.is_err(), "expected {} to be rejected", input);
    }
}

#[test]
fn parse_directive_should_consume_path_in_values() {
    let input = "ExecStart=/usr/sbin/some-fancy-httpd-server -p 3000 -h localhost -l server.log";
    let res = parse_directive(input);
    let expected = SystemdItem::Directive(
        String::from("ExecStart"),
        String::from("/usr/sbin/some-fancy-httpd-server -p 3000 -h localhost -l server.log")
    );

    assert_eq!(expected, res.unwrap().1);
}

#[test]
fn parse_directive_doesnt_consume_comment_at_end_of_line() {
    let input = "ExecStart=/usr/sbin/some-fancy-httpd-server # I like this one";
    let res = parse_directive(input);

    assert_eq!("# I like this one", res.unwrap().0)
}

pub fn main() {
    println!("yo")
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
    }
}
<commit_msg> better support for directives<commit_after>
#[macro_use]
extern crate nom;

use nom::*;

fn c_always_true(_c: char) -> bool { true }
fn c_is_alphabetic(c: char) -> bool { c.is_alphabetic() }
fn c_is_value_element(c: char) -> bool {
    match c {
        ' '|'/'|'-'|'_'|'.'|'@'|'+' => true,
        c if c.is_alphanumeric() => true,
        _ => false
    }
}
fn c_is_key_element(c: char) -> bool {
    match c {
        '!'|'|'|'@' => true,
        c if c.is_alphabetic() => true,
        _ => false
    }
}

#[derive(PartialEq, Eq, Clone, Debug)]
enum SystemdItem {
    Comment(String),
    Category(String),
    Directive(String, String),
}

named!(take_whole_line<&str, &str>, take_while_s!(c_always_true));

#[test]
fn take_whole_line_returns_whole_line() {
    let input = " yo 👋!";
    let res = take_whole_line(input);

    assert!(res.is_done());
    assert_eq!(input, res.unwrap().1)
}

named!(
    parse_comment<&str, SystemdItem>,
    do_parse!(
        tag_s!("#")                >>
        comment: take_whole_line   >>
        (SystemdItem::Comment(String::from(comment.trim())))
    )
);

#[test]
fn parse_comment_should_fail_when_not_starting_with_hash_char() {
    let res = parse_comment("yo");
    assert_eq!(true, res.is_err())
}

#[test]
fn parse_comment_should_be_done_when_starting_with_hash_char() {
    let res = parse_comment("# yo");
    assert_eq!(true, res.is_done())
}

#[test]
fn parse_comment_should_trim_whitespaces() {
    let res = parse_comment("# yo ");
    let expected = SystemdItem::Comment(String::from("yo"));
    assert_eq!(expected, res.unwrap().1)
}

named!(
    parse_category<&str, SystemdItem>,
    do_parse!(
        tag!("[") >>
        eat_separator!(" ") >>
        category: take_while1_s!(c_is_alphabetic) >>
        eat_separator!(" ") >>
        tag!("]") >>
        (SystemdItem::Category(String::from(category)))
    )
);

#[test]
fn parse_category_should_be_done() {
    let input = "[Category]";
    let res = parse_category(input);
    assert!(res.is_done())
}

#[test]
fn parse_category_should_consume_the_category() {
    let input = "[ Category ]";
    let res = parse_category(input);
    let expected = SystemdItem::Category(String::from("Category"));
    assert_eq!(expected, res.unwrap().1);
}

#[test]
fn parse_category_should_reject_more_than_one_word() {
    let input = "[ Category wrong ]";
    let res = parse_category(input);
    assert!(res.is_err())
}

named!(
    parse_directive<&str, SystemdItem>,
    do_parse!(
        key: take_while1_s!(c_is_key_element) >>
        eat_separator!(" ") >>
        tag!("=") >>
        eat_separator!(" ") >>
        value: take_while1_s!(c_is_value_element) >>
        (SystemdItem::Directive(String::from(key), String::from(value)))
    )
);

#[test]
fn parse_directive_should_be_done() {
    let input = "ExecStart=42";
    let res = parse_directive(input);

    assert!(res.is_done());
}

#[test]
fn parse_directive_should_consume_the_directive_key_and_value() {
    let input = "ExecStart = 42";
    let res = parse_directive(input);
    let expected = SystemdItem::Directive(String::from("ExecStart"), String::from("42"));

    assert_eq!(expected, res.unwrap().1);
}

#[test]
fn parse_directive_should_reject_the_directive_with_no_key() {
    let input = " = 42";
    let res = parse_directive(input);

    assert!(res.is_err());
}

#[test]
fn parse_directive_should_reject_the_directive_with_no_value() {
    let input = "Yo =";
    let res = parse_directive(input);

    assert!(res.is_err());
}

#[test]
fn parse_directive_should_reject_the_directive_with_invalid_characters() {
    let inputs = vec!["Yo == 42", "Yo =! 42", "Yo = !42"];
    for input in inputs {
        let res = parse_directive(input);
        assert!(res.is_err(), "expected {} to be rejected", input);
    }
}

#[test]
fn parse_directive_should_consume_path_in_values() {
    let input = "ExecStart=/usr/sbin/some-fancy-httpd-server -p 3000 -h localhost -l server.log";
    let res = parse_directive(input);
    let expected = SystemdItem::Directive(
        String::from("ExecStart"),
        String::from("/usr/sbin/some-fancy-httpd-server -p 3000 -h localhost -l server.log")
    );

    assert_eq!(expected, res.unwrap().1);
}

#[test]
fn parse_directive_doesnt_consume_comment_at_end_of_line() {
    let input = "ExecStart=/usr/sbin/some-fancy-httpd-server # I like this one";
    let res = parse_directive(input);

    assert_eq!("# I like this one", res.unwrap().0)
}

#[test]
fn parse_directive_should_accept_exotic_output() {
    let inputs = vec![
        ("!ConditionPathIsMountPoint=/mnt/plop", "bang in keys"),
        ("|ConditionPathIsMountPoint=/mnt/plop", "pipe in keys"),
        ("Alias=foo.service.wants/bar.service", "Alias=foo.service.wants/bar.service"),
        ("ExecStart=-/bin/false", "- in value"),
        ("ExecStart=@/bin/echo", "@ in value"),
        ("ExecStart=+/bin/true", "+ in value"),
        ("ExecStart=+@-/bin/true", "+@- in value"),
        ("ExecStart=/bin/echo $TERM", "$ in value"),
    ];

    for (input, msg) in inputs {
        let res = parse_directive(input);
        assert!(res.is_done(), "it should accept {}", msg)
    }
}

pub fn main() {
    println!("yo")
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
    }
}
<|endoftext|>


<commit_before>extern crate piston;
extern crate graphics;
extern crate glutin_window;
extern crate opengl_graphics;
extern crate box2d;

use piston::window::WindowSettings;
use piston::event_loop::*;
use piston::input::*;
use piston::input::Input::*;
use glutin_window::GlutinWindow as Window;
use opengl_graphics::{GlGraphics, OpenGL};
use box2d::b2;

pub struct Viewport {
    width: u32,
    height: u32,
    scale: f32,
}

pub struct InputState {
    mouse_position: b2::Vec2,
}

pub struct App {
    gl: GlGraphics,
    input_state: InputState,
    viewport: Viewport,
    world: b2::World,
}

impl App {
    fn onClick(&mut self, btn: MouseButton, pos: b2::Vec2) {

    }

    fn input(&mut self, i: &Input) {
        match *i {
            Input::Press(Button::Mouse(b)) => {
            	let pos = self.input_state.mouse_position;
                self.onClick(b, pos);
            }
            Move(Motion::MouseCursor(x, y)) => {
                let ref viewport = self.viewport;
                let tx = (x as f32 - (viewport.width as f32 * 0.5)) / viewport.scale;
                let ty = ((viewport.height as f32 * 0.5) - y as f32)  / viewport.scale;
                self.input_state.mouse_position = b2::Vec2 { x: tx, y: ty };
            }
            Resize(w, h) => {
                self.viewport.width = w;
                self.viewport.height = h;
                self.viewport.scale = (w as f32) / 100.0;
            }
            _ => (),
        }
    }

    fn render(&mut self, args: &RenderArgs) {
        use graphics::*;

        const WHITE: [f32; 4] = [1.0; 4];
        const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0];
        const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0];
        const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0];

        let ref world = self.world;
        let ref viewport = self.viewport;

        self.gl.draw(args.viewport(), |c, g| {
            clear(WHITE, g);

            for (_, b) in world.bodies() {
                let body = b.borrow();
                let position = (*body).position();
                let angle = (*body).angle();

                let transform = c.transform // transform compose right to left
                                 .trans((viewport.width as f64 * 0.5), (viewport.height as f64 * 0.5))
                                 .scale(viewport.scale as f64, -viewport.scale as f64)
                                 .trans(position.x as f64, position.y as f64)
                                 .rot_deg(angle as f64);

                for (_, f) in body.fixtures() {
                    let fixture = f.borrow();
                    let shape = (*fixture).shape();

                    match *shape {
                        b2::UnknownShape::Circle(ref s) => {
                            let p = s.position();
                            let r = s.radius() as f64;
                            let extent = rectangle::square(p.x as f64 - r, p.y as f64 - r, r * 2.0);
                            Ellipse::new(RED).draw(extent, default_draw_state(), transform, g);
                        }
                        b2::UnknownShape::Polygon(ref s) => {
                            let n = s.vertex_count();
                            let mut v = Vec::with_capacity(n as usize);
                            for i in 0..n {
                                let vertex = s.vertex(i);
                                v.push([vertex.x as f64, vertex.y as f64]);
                            }
                            Polygon::new(BLACK)
                                .draw(v.as_slice(), default_draw_state(), transform, g);
                        }
                        _ => (),
                    }
                }
            }
        });
    }

    fn update(&mut self, args: &UpdateArgs) {
        // Rotate 2 radians per second.
        self.world.step(args.dt as f32, 8, 3);
    }
}

fn new_world() -> b2::World {
    let mut world = b2::World::new(&b2::Vec2 { x: 0.0, y: -9.8 });

    let mut b_def = b2::BodyDef::new();
    b_def.body_type = b2::BodyType::Static;
    b_def.position = b2::Vec2 { x: 0., y: -20. };

    let mut ground_box = b2::PolygonShape::new();
    ground_box.set_as_box(20., 1.);

    let ground_handle = world.create_body(&b_def);
    world.get_body_mut(ground_handle)
         .create_fast_fixture(&ground_box, 0.);

    let mut b_def = b2::BodyDef::new();
    b_def.body_type = b2::BodyType::Dynamic;
    b_def.position = b2::Vec2 { x: 0., y: 0. };

    let mut cube_shape = b2::PolygonShape::new();
    cube_shape.set_as_box(1., 1.);

    let mut circle_shape = b2::CircleShape::new();
    circle_shape.set_radius(1.);

    let mut f_def = b2::FixtureDef::new();
    f_def.density = 1.;
    f_def.restitution = 0.2;
    f_def.friction = 0.3;

    b_def.position.x += 0.5;
    if b_def.position.x > 20. {
        b_def.position.x = -20.;
    }
    let handle = world.create_body(&b_def);
    world.get_body_mut(handle)
         .create_fixture(&circle_shape, &mut f_def);

    return world;
}

fn main() {
	const WIDTH: u32 = 1920;
	const HEIGHT: u32 = 1080;
    // Change this to OpenGL::V2_1 if not working.
    let opengl = OpenGL::V3_2;
    // Create an Glutin window.
    let mut window: Window = WindowSettings::new("box2d",
                                                 [WIDTH, HEIGHT])
                                 .opengl(opengl)
                                 .exit_on_esc(true)
                                 .build()
                                 .unwrap();

    // Create a new game and run it.
    let mut app = App {
        gl: GlGraphics::new(opengl),
        input_state: InputState { mouse_position: b2::Vec2 { x: 0.0, y: 0.0 } },
        viewport: Viewport {
            width: WIDTH,
            height: HEIGHT,
            scale: (WIDTH as f32) / 100.0,
        },
        world: new_world(),
    };

    let mut events = window.events();
    while let Some(e) = events.next(&mut window) {
        match e {
            Event::Render(args) => app.render(&args),
            Event::Update(args) => app.update(&args),
            Event::Input(input) => app.input(&input),
            _ => (),
        }
    }
}
<commit_msg>Multiple fixture static objects.<commit_after>extern crate piston;
extern crate graphics;
extern crate glutin_window;
extern crate opengl_graphics;
extern crate box2d;

use piston::window::WindowSettings;
use piston::event_loop::*;
use piston::input::*;
use piston::input::Input::*;
use glutin_window::GlutinWindow as Window;
use opengl_graphics::{GlGraphics, OpenGL};
use box2d::b2;

pub struct Viewport {
    width: u32,
    height: u32,
    scale: f32,
}

pub struct InputState {
    left_button_pressed: bool,
    mouse_position: b2::Vec2,
}

pub struct App {
    gl: GlGraphics,
    input_state: InputState,
    viewport: Viewport,
    world: b2::World,
}

fn new_ball(world: &mut b2::World, pos: b2::Vec2) {
    let mut circle_shape = b2::CircleShape::new();
    circle_shape.set_radius(1.);

    let mut f_def = b2::FixtureDef::new();
    f_def.density = 1.;
    f_def.restitution = 0.2;
    f_def.friction = 0.3;

    let mut b_def = b2::BodyDef::new();
    b_def.body_type = b2::BodyType::Dynamic;
    b_def.position = pos;
    let handle = world.create_body(&b_def);
    world.get_body_mut(handle)
         .create_fixture(&circle_shape, &mut f_def);
}

impl App {
    fn on_click(&mut self, btn: MouseButton, pos: b2::Vec2) {
        match btn {
            MouseButton::Left => {
                self.input_state.left_button_pressed = true;
                new_ball(&mut self.world, pos);
            }
            _ => (),
        }
    }

    fn on_drag(&mut self, pos: b2::Vec2) {
        new_ball(&mut self.world, pos);
    }

    fn on_release(&mut self, btn: MouseButton, _: b2::Vec2) {
        match btn {
            MouseButton::Left => {
                self.input_state.left_button_pressed = false;
            }
            _ => (),
        }
    }

    fn input(&mut self, i: &Input) {
        match *i {
            Release(Button::Mouse(b)) => {
                let pos = self.input_state.mouse_position;
                self.on_release(b, pos);
            }
            Press(Button::Mouse(b)) => {
                let pos = self.input_state.mouse_position;
                self.on_click(b, pos);
            }
            Move(Motion::MouseCursor(x, y)) => {
                fn transform_pos(viewport: &Viewport, x: f64, y: f64) -> b2::Vec2 {
                    let viewport = &viewport;
                    let tx = (x as f32 - (viewport.width as f32 * 0.5)) / viewport.scale;
                    let ty = ((viewport.height as f32 * 0.5) - y as f32) / viewport.scale;
                    return b2::Vec2 { x: tx, y: ty };
                }
                let pos = transform_pos(&self.viewport, x, y);
                self.input_state.mouse_position = pos;
                if self.input_state.left_button_pressed {
                    self.on_drag(pos);
                }
            }
            Resize(w, h) => {
                self.viewport.width = w;
                self.viewport.height = h;
                self.viewport.scale = (w as f32) / 100.0;
            }
            _ => (),
        }
    }

    fn render(&mut self, args: &RenderArgs) {
        use graphics::*;

        const WHITE: [f32; 4] = [1.0; 4];
        const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0];
        const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0];

        let ref world = self.world;
        let ref viewport = self.viewport;

        self.gl.draw(args.viewport(), |c, g| {
            clear(WHITE, g);

            for (_, b) in world.bodies() {
                let body = b.borrow();
                let position = (*body).position();
                let angle = (*body).angle();

                let transform = c.transform // transform compose right to left
                                 .trans((viewport.width as f64 * 0.5), (viewport.height as f64 * 0.5))
                                 .scale(viewport.scale as f64, -viewport.scale as f64)
                                 .trans(position.x as f64, position.y as f64)
                                 .rot_deg(angle as f64);

                for (_, f) in body.fixtures() {
                    let fixture = f.borrow();
                    let shape = (*fixture).shape();

                    match *shape {
                        b2::UnknownShape::Circle(ref s) => {
                            let p = s.position();
                            let r = s.radius() as f64;
                            let extent = rectangle::square(p.x as f64 - r, p.y as f64 - r, r * 2.0);
                            Ellipse::new(RED).draw(extent, default_draw_state(), transform, g);
                        }
                        b2::UnknownShape::Polygon(ref s) => {
                            let n = s.vertex_count();
                            let mut v = Vec::with_capacity(n as usize);
                            for i in 0..n {
                                let vertex = s.vertex(i);
                                v.push([vertex.x as f64, vertex.y as f64]);
                            }
                            Polygon::new(BLACK)
                                .draw(v.as_slice(), default_draw_state(), transform, g);
                        }
                        _ => (),
                    }
                }
            }
        });
    }

    fn update(&mut self, args: &UpdateArgs) {
        // Rotate 2 radians per second.
        self.world.step(args.dt as f32, 8, 3);
    }
}

fn new_world() -> b2::World {
    let mut world = b2::World::new(&b2::Vec2 { x: 0.0, y: -9.8 });

    let mut b_def = b2::BodyDef::new();
    b_def.body_type = b2::BodyType::Static;
    b_def.position = b2::Vec2 { x: 0.0, y: -20.0 };

    let mut ground_box = b2::PolygonShape::new();
    {
        ground_box.set_as_box(20.0, 1.0);
        let ground_handle = world.create_body(&b_def);
        let ground = &mut world.get_body_mut(ground_handle);
        ground.create_fast_fixture(&ground_box, 0.);

        ground_box.set_as_oriented_box(1.0, 5.0, &b2::Vec2 { x: 20.0, y: 5.0 }, 0.0);
        ground.create_fast_fixture(&ground_box, 0.);

        ground_box.set_as_oriented_box(1.0, 5.0, &b2::Vec2 { x: -20.0, y: 5.0 }, 0.0);
        ground.create_fast_fixture(&ground_box, 0.);
    }
    return world;
}

fn main() {
    const WIDTH: u32 = 1920;
    const HEIGHT: u32 = 1080;
    // Change this to OpenGL::V2_1 if not working.
    let opengl = OpenGL::V3_2;
    // Create an Glutin window.
    let mut window: Window = WindowSettings::new("box2d", [WIDTH, HEIGHT])
                                 .opengl(opengl)
                                 .exit_on_esc(true)
                                 .build()
                                 .unwrap();

    // Create a new game and run it.
    let mut app = App {
        gl: GlGraphics::new(opengl),
        input_state: InputState {
            left_button_pressed: false,
            mouse_position: b2::Vec2 { x: 0.0, y: 0.0 },
        },
        viewport: Viewport {
            width: WIDTH,
            height: HEIGHT,
            scale: (WIDTH as f32) / 100.0,
        },
        world: new_world(),
    };

    let mut events = window.events();
    while let Some(e) = events.next(&mut window) {
        match e {
            Event::Render(args) => app.render(&args),
            Event::Update(args) => app.update(&args),
            Event::Input(input) => app.input(&input),
            _ => (),
        }
    }
}
<|endoftext|>


<commit_before>extern crate obj;
extern crate genmesh;
extern crate sdl2;
extern crate sdl2_image;
extern crate time;
extern crate cgmath;
extern crate libc;
extern crate sdl2_sys;

mod mesh;
mod utils;
mod scene;
mod tests;
mod device;
mod memory;
mod shader;
mod texture;
mod material;
mod importobj;
mod dll_import;
// mod generator;
mod rasterization;

use cgmath::*;
use scene::Scene;
use shader::Shader;
// use generator::{generate_plane, generate_sphere};
use importobj::ModelObj;

pub fn main() {
    let eye;
    let center;
    let model;
    let ind = 7;
    // let mut material = Material::gold();

    let mut add_angle = rad(2.0_f32 * std::f32::consts::PI / 180.0_f32);
    // let add_angle = rad(0.0_f32);
    let light = Vector3::new(1.0_f32, -1.0_f32, 1.0_f32);
    match ind {
        // 0 => {
        //     eye = Point3::new(0.0_f32, 0.0_f32, -0.5_f32);
        //     center = Point3::new(0.0_f32, 0.0_f32, 0.0_f32);
        //     add_angle = rad(0.0_f32);
        //     init_matrix = Matrix4::from(Matrix3::from_angle_x(rad(std::f32::consts::PI * 0.25_f32)));
        //     model = generate_plane().unwrap();
        // },
        // 1 => {
        //     eye = Point3::new(0.0_f32, 0.0_f32, -2.0_f32);
        //     center = Point3::new(0.0_f32, 0.0_f32, 0.0_f32);
        //     model = generate_sphere(50).unwrap();
        // },
        // 2 => {
        //     eye = Point3::new(0.0_f32, 0.7_f32, -1.1_f32);
        //     center = Point3::new(0.0_f32, 0.0_f32, 0.0_f32);
        //     // material = Material::silver();
        //     add_angle = rad(0.0_f32);
        //     model = Model3ds::load("ring.3ds").unwrap();
        // },
        // 3 => {
        //     eye = Point3::new(0.0_f32, 0.0_f32, -10.1_f32);
        //     center = Point3::new(0.0_f32, 0.0_f32, 0.0_f32);
        //     model = Model3ds::load("tux.3ds").unwrap();
        // },
        // 4 => {
        //     eye = Point3::new(0.0_f32, -2.0_f32, -4.1_f32);
        //     center = Point3::new(0.0_f32, -2.0_f32, 0.0_f32);
        //     // material = Material::monster_skin();
        //     init_matrix = Matrix4::from(Matrix3::from_angle_x(rad(-1.8_f32)));
        //     model = Model3ds::load("monster.3ds").unwrap();
        // },
        // 5 => {
        //     eye = Point3::new(0.0_f32, 0.0_f32, -1.1_f32);
        //     center = Point3::new(0.0_f32, 0.0_f32, 0.0_f32);
        //     model = Model3ds::load("yoda/yoda2.3ds").unwrap();
        // },
        // 6 => {
        //     eye = Point3::new(0.0_f32, 0.0_f32, -1.1_f32);
        //     center = Point3::new(0.0_f32, 0.0_f32, 0.0_f32);
        //     model = Model3ds::load("nokia/nokia-n82-highres.3DS").unwrap();
        // },
        7 => {
            eye = Point3::new(0.0_f32, 1.0_f32, -0.8_f32);
            center = Point3::new(0.0_f32, 0.0_f32, 0.0_f32);
            // model = ModelObj::load("cube.obj").unwrap();
            // model = ModelObj::load("monster1/monster.obj").unwrap();
            model = ModelObj::load("nokia/nokia.obj").unwrap();
            // model = ModelObj::load("droid/attack_droid.obj").unwrap();
        },

        _ => return
    };
    let init_matrix = model.to_center_matrix();
    let up = Vector3::new(0.0_f32, 1.0_f32, 0.0_f32);

    let mut angle = rad(std::f32::consts::PI * 0.5_f32);

    let mut scene = Scene::new(800, 600);
    scene.proj(deg(100.0_f32), 0.1_f32, 100.0_f32)
        .view(eye, center, up)
        .light(light);

    // let mut texture = Texture::new();
    // texture.load_from_def("gamma_dalai_lama_gray.jpg").unwrap();
    // texture.load_from_def("green_monster.png").unwrap();
    // texture.load_from_def("chess.png").unwrap();

    let mut shader = Shader::new();
    shader.set_lambert();
    // shader.set_shaders(Shader::vertex_cook_torrance, Shader::pixel_cook_torrance);
    // shader.set_shaders(Shader::vertex_phong_blinn, Shader::pixel_phong_blinn);
    // shader.set_shaders(Shader::vertex_normals, Shader::pixel_normals);
    while scene.start(0xAAAAAA) {
        angle = angle + add_angle;
        scene.draw(&model, Matrix4::from(Matrix3::from_angle_y(angle)) * init_matrix, &mut shader).present();
    }
}
<commit_msg>fix warnins<commit_after>extern crate obj;
extern crate genmesh;
extern crate sdl2;
extern crate sdl2_image;
extern crate time;
extern crate cgmath;
extern crate libc;
extern crate sdl2_sys;

mod mesh;
mod utils;
mod scene;
mod tests;
mod device;
mod memory;
mod shader;
mod texture;
mod material;
mod importobj;
mod dll_import;
// mod generator;
mod rasterization;

use cgmath::*;
use scene::Scene;
use shader::Shader;
// use generator::{generate_plane, generate_sphere};
use importobj::ModelObj;

pub fn main() {
    let eye;
    let center;
    let model;
    let ind = 3;
    // let mut material = Material::gold();

    let add_angle = rad(2.0_f32 * std::f32::consts::PI / 180.0_f32);
    // let add_angle = rad(0.0_f32);
    let light = Vector3::new(1.0_f32, -1.0_f32, 1.0_f32);
    match ind {
        // 0 => {
        //     eye = Point3::new(0.0_f32, 0.0_f32, -0.5_f32);
        //     center = Point3::new(0.0_f32, 0.0_f32, 0.0_f32);
        //     add_angle = rad(0.0_f32);
        //     init_matrix = Matrix4::from(Matrix3::from_angle_x(rad(std::f32::consts::PI * 0.25_f32)));
        //     model = generate_plane().unwrap();
        // },
        // 1 => {
        //     eye = Point3::new(0.0_f32, 0.0_f32, -2.0_f32);
        //     center = Point3::new(0.0_f32, 0.0_f32, 0.0_f32);
        //     model = generate_sphere(50).unwrap();
        // },
        3 => {
            eye = Point3::new(0.0_f32, 1.0_f32, -0.8_f32);
            center = Point3::new(0.0_f32, 0.0_f32, 0.0_f32);
            // model = ModelObj::load("cube.obj").unwrap();
            model = ModelObj::load("monster1/monster.obj").unwrap();
            // model = ModelObj::load("nokia/nokia.obj").unwrap();
            // model = ModelObj::load("droid/attack_droid.obj").unwrap();
        },

        _ => return
    };
    let init_matrix = model.to_center_matrix();
    let up = Vector3::new(0.0_f32, 1.0_f32, 0.0_f32);

    let mut angle = rad(std::f32::consts::PI * 0.5_f32);

    let mut scene = Scene::new(800, 600);
    scene.proj(deg(100.0_f32), 0.1_f32, 100.0_f32)
        .view(eye, center, up)
        .light(light);

    // let mut texture = Texture::new();
    // texture.load_from_def("gamma_dalai_lama_gray.jpg").unwrap();
    // texture.load_from_def("green_monster.png").unwrap();
    // texture.load_from_def("chess.png").unwrap();

    let mut shader = Shader::new();
    shader.set_lambert();
    // shader.set_shaders(Shader::vertex_cook_torrance, Shader::pixel_cook_torrance);
    // shader.set_shaders(Shader::vertex_phong_blinn, Shader::pixel_phong_blinn);
    // shader.set_shaders(Shader::vertex_normals, Shader::pixel_normals);
    while scene.start(0xAAAAAA) {
        angle = angle + add_angle;
        scene.draw(&model, Matrix4::from(Matrix3::from_angle_y(angle)) * init_matrix, &mut shader).present();
    }
}
<|endoftext|>


<commit_before>use std::env;
use std::io::{self, Write};
use std::process::{self, Command};

#[cfg(unix)]
use std::process::{Child, Stdio};

extern crate isatty;
use isatty::{stdout_isatty, stderr_isatty};

fn main() {
    let result = cargo_expand();
    process::exit(match result {
        Ok(code) => code,
        Err(err) => {
            let _ = writeln!(&mut io::stderr(), "{}", err);
            1
        }
    });
}

#[cfg(windows)]
fn cargo_expand() -> io::Result<i32> {
    // Build cargo command
    let mut cmd = Command::new("cargo");
    cmd.args(&wrap_args(env::args()));
    run(cmd)
}

#[cfg(unix)]
fn cargo_expand() -> io::Result<i32> {
    if env::args().last().unwrap() == "--filter-rustfmt" {
        filter_rustfmt();
    }

    // Build cargo command
    let mut cmd = Command::new("cargo");
    cmd.args(&wrap_args(env::args()));

    // Pipe to rustfmt
    let _wait = match which(&["rustfmt"]) {
        Some(ref fmt) => {
            let args: Vec<_> = env::args().collect();
            let mut filter_args = Vec::new();
            for i in 0..args.len() {
                filter_args.push(args[i].as_str());
            }
            filter_args.push("--filter-rustfmt");

            Some((
                // Work around $crate issue https://github.com/rust-lang/rust/issues/38016
                try!(cmd.pipe_to(&["sed", "s/$crate/XCRATE/g"], None)),
                try!(cmd.pipe_to(&[fmt], None)),
                try!(cmd.pipe_to(&["sed", "s/XCRATE/$crate/g"], Some(&filter_args))),
            ))
        }
        None => None,
    };

    // Pipe to pygmentize
    let _wait = if stdout_isatty() {
        match which(&["pygmentize", "-l", "rust"]) {
            Some(pyg) => Some(try!(cmd.pipe_to(&[&pyg, "-l", "rust"], None))),
            None => None,
        }
    } else {
        None
    };

    run(cmd)
}

fn run(mut cmd: Command) -> io::Result<i32> {
    cmd.status().map(|status| status.code().unwrap_or(1))
}

#[cfg(unix)]
struct Wait(Vec<Child>);

#[cfg(unix)]
impl Drop for Wait {
    fn drop(&mut self) {
        for child in &mut self.0 {
            if let Err(err) = child.wait() {
                let _ = writeln!(&mut io::stderr(), "{}", err);
            }
        }
    }
}

#[cfg(unix)]
trait PipeTo {
    fn pipe_to(&mut self, out: &[&str], err: Option<&[&str]>) -> io::Result<Wait>;
}

#[cfg(unix)]
impl PipeTo for Command {
    fn pipe_to(&mut self, out: &[&str], err: Option<&[&str]>) -> io::Result<Wait> {
        use std::os::unix::io::{AsRawFd, FromRawFd};

        self.stdout(Stdio::piped());
        if err.is_some() {
            self.stderr(Stdio::piped());
        }

        let child = try!(self.spawn());

        *self = Command::new(out[0]);
        self.args(&out[1..]);
        self.stdin(unsafe {
            Stdio::from_raw_fd(child.stdout.as_ref().map(AsRawFd::as_raw_fd).unwrap())
        });

        match err {
            None => {
                Ok(Wait(vec![child]))
            }
            Some(err) => {
                let mut errcmd = Command::new(err[0]);
                errcmd.args(&err[1..]);
                errcmd.stdin(unsafe {
                    Stdio::from_raw_fd(child.stderr.as_ref().map(AsRawFd::as_raw_fd).unwrap())
                });
                errcmd.stdout(Stdio::null());
                errcmd.stderr(Stdio::inherit());
                let spawn = try!(errcmd.spawn());
                Ok(Wait(vec![spawn, child]))
            }
        }
    }
}

// Based on https://github.com/rsolomo/cargo-check
fn wrap_args<T, I>(it: I) -> Vec<String>
    where T: AsRef<str>,
          I: IntoIterator<Item=T>
{
    let mut args = vec!["rustc".to_string()];
    let mut has_color = false;
    let mut has_double_hyphen = false;
    let mut ends_with_test = false;

    for arg in it.into_iter().skip(2) {
        let arg = arg.as_ref().to_string();
        has_color |= arg.starts_with("--color");
        has_double_hyphen |= arg == "--";
        ends_with_test = arg == "--test";
        args.push(arg);
    }

    if !has_double_hyphen && ends_with_test {
        // Expand the `test.rs` test by default.
        args.push("test".to_string());
    }

    if !has_color {
        let color = stdout_isatty() && stderr_isatty();
        let setting = if color { "always" } else { "never" };
        args.push(format!("--color={}", setting));
    }

    if !has_double_hyphen {
        args.push("--".to_string());
    }

    args.push("-Zunstable-options".to_string());
    args.push("--pretty=expanded".to_string());

    args
}

#[cfg(unix)]
fn which(cmd: &[&str]) -> Option<String> {
    if env::args().find(|arg| arg == "--help").is_some() {
        None
    } else {
        match env::var(&cmd[0].to_uppercase()) {
            Ok(which) => {
                if which.is_empty() {
                    None
                } else {
                    Some(which)
                }
            }
            Err(_) => {
                let in_path = Command::new(cmd[0])
                    .args(&cmd[1..])
                    .stdin(Stdio::null())
                    .stdout(Stdio::null())
                    .stderr(Stdio::null())
                    .spawn()
                    .is_ok();
                if in_path {
                    Some(cmd[0].to_string())
                } else {
                    None
                }
            }
        }
    }
}

#[cfg(unix)]
fn filter_rustfmt() -> ! {
    let mut line = String::new();
    while let Ok(n) = io::stdin().read_line(&mut line) {
        if n == 0 {
            break;
        }
        if !ignore_rustfmt_err(&line) {
            let _ = write!(&mut io::stderr(), "{}", line);
        }
        line.clear();
    }
    process::exit(0);
}

#[cfg(unix)]
fn ignore_rustfmt_err(line: &str) -> bool {
    line.trim().is_empty()
        || line.trim_right().ends_with("line exceeded maximum length (sorry)")
        || line.trim_right().ends_with("left behind trailing whitespace (sorry)")
}
<commit_msg>Expand the example.rs example by default<commit_after>use std::env;
use std::io::{self, Write};
use std::process::{self, Command};

#[cfg(unix)]
use std::process::{Child, Stdio};

extern crate isatty;
use isatty::{stdout_isatty, stderr_isatty};

fn main() {
    let result = cargo_expand();
    process::exit(match result {
        Ok(code) => code,
        Err(err) => {
            let _ = writeln!(&mut io::stderr(), "{}", err);
            1
        }
    });
}

#[cfg(windows)]
fn cargo_expand() -> io::Result<i32> {
    // Build cargo command
    let mut cmd = Command::new("cargo");
    cmd.args(&wrap_args(env::args()));
    run(cmd)
}

#[cfg(unix)]
fn cargo_expand() -> io::Result<i32> {
    if env::args().last().unwrap() == "--filter-rustfmt" {
        filter_rustfmt();
    }

    // Build cargo command
    let mut cmd = Command::new("cargo");
    cmd.args(&wrap_args(env::args()));

    // Pipe to rustfmt
    let _wait = match which(&["rustfmt"]) {
        Some(ref fmt) => {
            let args: Vec<_> = env::args().collect();
            let mut filter_args = Vec::new();
            for i in 0..args.len() {
                filter_args.push(args[i].as_str());
            }
            filter_args.push("--filter-rustfmt");

            Some((
                // Work around $crate issue https://github.com/rust-lang/rust/issues/38016
                try!(cmd.pipe_to(&["sed", "s/$crate/XCRATE/g"], None)),
                try!(cmd.pipe_to(&[fmt], None)),
                try!(cmd.pipe_to(&["sed", "s/XCRATE/$crate/g"], Some(&filter_args))),
            ))
        }
        None => None,
    };

    // Pipe to pygmentize
    let _wait = if stdout_isatty() {
        match which(&["pygmentize", "-l", "rust"]) {
            Some(pyg) => Some(try!(cmd.pipe_to(&[&pyg, "-l", "rust"], None))),
            None => None,
        }
    } else {
        None
    };

    run(cmd)
}

fn run(mut cmd: Command) -> io::Result<i32> {
    cmd.status().map(|status| status.code().unwrap_or(1))
}

#[cfg(unix)]
struct Wait(Vec<Child>);

#[cfg(unix)]
impl Drop for Wait {
    fn drop(&mut self) {
        for child in &mut self.0 {
            if let Err(err) = child.wait() {
                let _ = writeln!(&mut io::stderr(), "{}", err);
            }
        }
    }
}

#[cfg(unix)]
trait PipeTo {
    fn pipe_to(&mut self, out: &[&str], err: Option<&[&str]>) -> io::Result<Wait>;
}

#[cfg(unix)]
impl PipeTo for Command {
    fn pipe_to(&mut self, out: &[&str], err: Option<&[&str]>) -> io::Result<Wait> {
        use std::os::unix::io::{AsRawFd, FromRawFd};

        self.stdout(Stdio::piped());
        if err.is_some() {
            self.stderr(Stdio::piped());
        }

        let child = try!(self.spawn());

        *self = Command::new(out[0]);
        self.args(&out[1..]);
        self.stdin(unsafe {
            Stdio::from_raw_fd(child.stdout.as_ref().map(AsRawFd::as_raw_fd).unwrap())
        });

        match err {
            None => {
                Ok(Wait(vec![child]))
            }
            Some(err) => {
                let mut errcmd = Command::new(err[0]);
                errcmd.args(&err[1..]);
                errcmd.stdin(unsafe {
                    Stdio::from_raw_fd(child.stderr.as_ref().map(AsRawFd::as_raw_fd).unwrap())
                });
                errcmd.stdout(Stdio::null());
                errcmd.stderr(Stdio::inherit());
                let spawn = try!(errcmd.spawn());
                Ok(Wait(vec![spawn, child]))
            }
        }
    }
}

// Based on https://github.com/rsolomo/cargo-check
fn wrap_args<T, I>(it: I) -> Vec<String>
    where T: AsRef<str>,
          I: IntoIterator<Item=T>
{
    let mut args = vec!["rustc".to_string()];
    let mut has_color = false;
    let mut has_double_hyphen = false;
    let mut ends_with_test = false;
    let mut ends_with_example = false;

    for arg in it.into_iter().skip(2) {
        let arg = arg.as_ref().to_string();
        has_color |= arg.starts_with("--color");
        has_double_hyphen |= arg == "--";
        ends_with_test = arg == "--test";
        ends_with_example = arg == "--example";
        args.push(arg);
    }

    if !has_double_hyphen && ends_with_test {
        // Expand the `test.rs` test by default.
        args.push("test".to_string());
    }

    if !has_double_hyphen && ends_with_example {
        // Expand the `example.rs` example by default.
        args.push("example".to_string());
    }

    if !has_color {
        let color = stdout_isatty() && stderr_isatty();
        let setting = if color { "always" } else { "never" };
        args.push(format!("--color={}", setting));
    }

    if !has_double_hyphen {
        args.push("--".to_string());
    }

    args.push("-Zunstable-options".to_string());
    args.push("--pretty=expanded".to_string());

    args
}

#[cfg(unix)]
fn which(cmd: &[&str]) -> Option<String> {
    if env::args().find(|arg| arg == "--help").is_some() {
        None
    } else {
        match env::var(&cmd[0].to_uppercase()) {
            Ok(which) => {
                if which.is_empty() {
                    None
                } else {
                    Some(which)
                }
            }
            Err(_) => {
                let in_path = Command::new(cmd[0])
                    .args(&cmd[1..])
                    .stdin(Stdio::null())
                    .stdout(Stdio::null())
                    .stderr(Stdio::null())
                    .spawn()
                    .is_ok();
                if in_path {
                    Some(cmd[0].to_string())
                } else {
                    None
                }
            }
        }
    }
}

#[cfg(unix)]
fn filter_rustfmt() -> ! {
    let mut line = String::new();
    while let Ok(n) = io::stdin().read_line(&mut line) {
        if n == 0 {
            break;
        }
        if !ignore_rustfmt_err(&line) {
            let _ = write!(&mut io::stderr(), "{}", line);
        }
        line.clear();
    }
    process::exit(0);
}

#[cfg(unix)]
fn ignore_rustfmt_err(line: &str) -> bool {
    line.trim().is_empty()
        || line.trim_right().ends_with("line exceeded maximum length (sorry)")
        || line.trim_right().ends_with("left behind trailing whitespace (sorry)")
}
<|endoftext|>


<commit_before>extern crate image;

use std::env;
use std::process;

use image::open;
use display::Display;
use parse_args::ArgParser;
use parse_args::Error as ParseError;

mod display;
mod braille;
mod parse_args;

const USAGE_TEXT: &'static str = "\
braillify image [size]
    image: Any image (ex: image.png)
    size: The desired output size in characters. (ex: 50x25)
        If a size isn't given, it'll be guessed from the image's dimensions.";

fn main() {
    let args = match ArgParser::new(env::args().skip(1).collect()) {
        Err(ParseError::TooFewArgs) =>
            complain("Too few arguments!"),
        Err(ParseError::CantParseSize) =>
            complain("Couldn't parse size!"),
        Err(ParseError::BadArgs) =>
            complain("Bad arguments!"),
        Ok(args) => args
    };

    let img = match image::open(args.path()) {
        Ok(image) => image.to_luma(),
        Err(_) => complain("Couldn't open image!")
    };

    let (width, height) = args.size().unwrap_or({
        let (width, height) = img.dimensions();
        (width/10, height/20)
    });

    let display = Display::new(img, width, height);

    println!("{}", display.render());
}

fn complain(error: &str) -> ! {
    println!("{}\n\n{}", error, USAGE_TEXT);
    process::exit(1);
}
<commit_msg>Got rid of stray newline after braille output<commit_after>extern crate image;

use std::env;
use std::process;

use image::open;
use display::Display;
use parse_args::ArgParser;
use parse_args::Error as ParseError;

mod display;
mod braille;
mod parse_args;

const USAGE_TEXT: &'static str = "\
braillify image [size]
    image: Any image (ex: image.png)
    size: The desired output size in characters. (ex: 50x25)
        If a size isn't given, it'll be guessed from the image's dimensions.";

fn main() {
    let args = match ArgParser::new(env::args().skip(1).collect()) {
        Err(ParseError::TooFewArgs) =>
            complain("Too few arguments!"),
        Err(ParseError::CantParseSize) =>
            complain("Couldn't parse size!"),
        Err(ParseError::BadArgs) =>
            complain("Bad arguments!"),
        Ok(args) => args
    };

    let img = match image::open(args.path()) {
        Ok(image) => image.to_luma(),
        Err(_) => complain("Couldn't open image!")
    };

    let (width, height) = args.size().unwrap_or({
        let (width, height) = img.dimensions();
        (width/10, height/20)
    });

    let display = Display::new(img, width, height);

    print!("{}", display.render());
}

fn complain(error: &str) -> ! {
    println!("{}\n\n{}", error, USAGE_TEXT);
    process::exit(1);
}
<|endoftext|>