<commit_before>
#[macro_use]
extern crate clap;
extern crate regex;
extern crate chrono;
extern crate lettre;
extern crate colored;
extern crate notify_rust;

use clap::App;
use colored::*;
use regex::Regex;
use chrono::prelude::*;
// use chrono::offset::local;
// use chrono::{datetime, date};
use std::{thread, time};
use notify_rust::Notification;
use lettre::email::EmailBuilder;
use lettre::transport::EmailTransport;
use lettre::transport::smtp::{SecurityLevel, SmtpTransportBuilder};

use std::process::exit;

fn main() {
    let re = Regex::new(r"([01]?\d):(\d{2})").unwrap();
    let yml = load_yaml!("cli.yml");
    let app = App::from_yaml(yml)
        .version(crate_version!())
        .get_matches();

    match app.subcommand() {
        ("run", Some(content)) => {
            let time = content.value_of("time").unwrap();
            if re.is_match(time) {
                println!("{} Run with notifications", "[Notice]".yellow().bold());
                let captures = re.captures(time).unwrap();
                execute(None,
                        captures.get(1).unwrap().as_str(),
                        captures.get(2).unwrap().as_str());
            } else {
                exit(1);
            }
        }
        ("server", Some(sub_m)) => {
            let time = sub_m.value_of("time").unwrap();
            if re.is_match(time) {
                println!("{} Run as server", "[Notice]".yellow().bold());
                let captures = re.captures(time).unwrap();
                execute(Some(sub_m),
                        captures.get(0).unwrap().as_str(),
                        captures.get(1).unwrap().as_str())
            } else {
                exit(1);
            }
        }
        _ => println!("{}", app.usage()),
    }
}

fn execute(server_info: Option<&clap::ArgMatches>, hour: &str, minute: &str) {
    let notification = match server_info {
        Some(_) => false,
        None => true,
    };
    let mut trigger_time: DateTime<Local>;
    let mut sleep_duration;
    if Local::today()
        .and_hms(hour.parse::<u32>().unwrap(),
                 minute.parse::<u32>().unwrap(),
                 0)
        .timestamp() > Local::now().timestamp() {
        sleep_duration = time::Duration::from_secs(((Local::today()
            .and_hms(hour.parse::<u32>().unwrap(),
                     minute.parse::<u32>().unwrap(),
                     0)
            .timestamp() -
                                                     Local::now().timestamp()) as
                                                    u64));
        let now = Local::now();
        println!("{} {}\tFirst notification will be delivered in {} seconds",
                 "[Notice]".yellow().bold(),
                 now.format("%Y/%m/%d %H:%M:%S").to_string(),
                 sleep_duration.as_secs());
        thread::sleep(sleep_duration);
    }
    loop {
        trigger_time = match Local::today().succ_opt() {
            Some(date) => {
                date.and_hms(hour.parse::<u32>().unwrap(),
                             minute.parse::<u32>().unwrap(),
                             0)
            }
            None => {
                let now = Local::now();
                println!("{} {}\tThere is no tomorrow",
                         "[Error]".red().bold(),
                         now.format("%Y/%m/%d %H:%M:%S").to_string());
                exit(1);
            }
        };
        let time_delta = trigger_time.timestamp() - Local::now().timestamp();
        sleep_duration = time::Duration::from_secs((time_delta as u64));
        if notification {
            deliver_notifiaction();
        } else {
            send_mail(server_info.unwrap());
        }
        thread::sleep(sleep_duration);
    }
}

fn send_mail(args: &clap::ArgMatches) {
    let now = Local::now();
    let mail = EmailBuilder::new()
        .to(args.value_of("mail").unwrap())
        .from((args.value_of("mail").unwrap(), "Once a day"))
        .body("Be friendly and make a compliment today! :-)")
        .subject("Your compliment today")
        .build()
        .unwrap();
    let port = match args.value_of("port") {
        Some(x) => x.parse::<u16>().unwrap(),
        None => 587 as u16,
    };
    let mut sender = SmtpTransportBuilder::new((args.value_of("host").unwrap(), port))
        .unwrap()
        .credentials(args.value_of("user").unwrap(),
                     args.value_of("pass").unwrap())
        .security_level(SecurityLevel::AlwaysEncrypt)
        .smtp_utf8(true)
        .connection_reuse(true)
        .build();
    match sender.send(mail) {
        Ok(_) => {
            println!("{} {}\tMail send to {}",
                     "[Log]   ".green().bold(),
                     now.format("%Y/%m/%d %H:%M:%S").to_string(),
                     args.value_of("mail").unwrap())
        }
        Err(x) => {
            println!("{} {}\tMail could not be sent because of {}",
                     "[Error]".red().bold(),
                     now.format("%Y/%m/%d %H:%M:%S").to_string(),
                     x)
        }
    }
}

#[cfg(all(unix))]
fn deliver_notifiaction() {
    let now = Local::now();
    match Notification::new()
        .summary("Once a day")
        .body("Be friendly and make a compliment today! 😊")
        .show() {
        Ok(_) => {
            println!("{} {}\tNotification delivered",
                     "[Log]   ".green().bold(),
                     now.format("%Y/%m/%d %H:%M:%S").to_string())
        }
        Err(x) => {
            println!("{} {}\tNotification could not be delivered because of {:?}",
                     "[Error]".red().bold(),
                     now.format("%Y/%m/%d %H:%M:%S").to_string(),
                     x)
        }
    }

}

#[cfg(windows)]
fn deliver_notifiaction(now: &date::Date) {
    let now = Local::now();
    println!("{} {}\tNo notification support for Windows right now.",
             "[Error]".red().bold(),
             now.format("%Y/%m/%d %H:%M:%S").to_string());
    exit(1);
}
<commit_msg>moving time calculation<commit_after>
#[macro_use]
extern crate clap;
extern crate regex;
extern crate chrono;
extern crate lettre;
extern crate colored;
extern crate notify_rust;

use clap::App;
use colored::*;
use regex::Regex;
use chrono::prelude::*;
use std::{thread, time};
use notify_rust::Notification;
use lettre::email::EmailBuilder;
use lettre::transport::EmailTransport;
use lettre::transport::smtp::{SecurityLevel, SmtpTransportBuilder};

use std::process::exit;

fn main() {
    let re = Regex::new(r"([01]?\d):(\d{2})").unwrap();
    let yml = load_yaml!("cli.yml");
    let app = App::from_yaml(yml).version(crate_version!()).get_matches();
    match app.subcommand() {
        ("run", Some(content)) => {
            let time = content.value_of("time").unwrap();
            if re.is_match(time) {
                println!("{} Run with notifications", "[Notice]".yellow().bold());
                let captures = re.captures(time).unwrap();
                execute(None,
                        captures.get(1).unwrap().as_str(),
                        captures.get(2).unwrap().as_str());
            } else {
                exit(1);
            }
        }
        ("server", Some(sub_m)) => {
            let time = sub_m.value_of("time").unwrap();
            if re.is_match(time) {
                println!("{} Run as server", "[Notice]".yellow().bold());
                let captures = re.captures(time).unwrap();
                execute(Some(sub_m),
                        captures.get(0).unwrap().as_str(),
                        captures.get(1).unwrap().as_str())
            } else {
                exit(1);
            }
        }
        _ => println!("{}", app.usage()),
    }
}

fn execute(server_info: Option<&clap::ArgMatches>, hour: &str, minute: &str) {
    let notification = match server_info {
        Some(_) => false,
        None => true,
    };
    let mut sleep_duration;
    let delta = time_delta(hour, minute, true);
    if delta.as_secs() > 0 {
        let now = Local::now();
        println!("{} {}\tFirst notification will be delivered in {} seconds",
                 "[Notice]".yellow().bold(),
                 now.format("%Y/%m/%d %H:%M:%S").to_string(),
                 delta.as_secs());
        thread::sleep(delta);
    }
    loop {
        sleep_duration = time_delta(hour, minute, false);
        if notification {
            deliver_notifiaction();
        } else {
            send_mail(server_info.unwrap());
        }
        thread::sleep(sleep_duration);
    }
}

fn send_mail(args: &clap::ArgMatches) {
    let now = Local::now();
    let mail = EmailBuilder::new()
        .to(args.value_of("mail").unwrap())
        .from((args.value_of("mail").unwrap(), "Once a day"))
        .body("Be friendly and make a compliment today! :-)")
        .subject("Your compliment today")
        .build()
        .unwrap();
    let port = match args.value_of("port") {
        Some(x) => x.parse::<u16>().unwrap(),
        None => 587 as u16,
    };
    let mut sender = SmtpTransportBuilder::new((args.value_of("host").unwrap(), port))
        .unwrap()
        .credentials(args.value_of("user").unwrap(),
                     args.value_of("pass").unwrap())
        .security_level(SecurityLevel::AlwaysEncrypt)
        .smtp_utf8(true)
        .connection_reuse(true)
        .build();
    match sender.send(mail) {
        Ok(_) => {
            println!("{} {}\tMail send to {}",
                     "[Log]   ".green().bold(),
                     now.format("%Y/%m/%d %H:%M:%S").to_string(),
                     args.value_of("mail").unwrap())
        }
        Err(x) => {
            println!("{} {}\tMail could not be sent because of {}",
                     "[Error]".red().bold(),
                     now.format("%Y/%m/%d %H:%M:%S").to_string(),
                     x)
        }
    }
}

fn time_delta(hour: &str, minute: &str, first: bool) -> time::Duration {
    let trigger_base = if first {
        Local::today()
    } else {
        match Local::today().succ_opt() {
            Some(date) => date,
            None => {
                let now = Local::now();
                println!("{} {}\tThere is no tomorrow",
                         "[Error]".red().bold(),
                         now.format("%Y/%m/%d %H:%M:%S").to_string());
                exit(1);
            }
        }
    };
    let trigger_time = trigger_base.and_hms(hour.parse::<u32>().unwrap(),
                                            minute.parse::<u32>().unwrap(),
                                            0);
    let time_delta = trigger_time.timestamp() - Local::now().timestamp();
    time::Duration::from_secs(time_delta as u64)
}

#[cfg(all(unix))]
fn deliver_notifiaction() {
    let now = Local::now();
    match Notification::new()
        .summary("Once a day")
        .body("Be friendly and make a compliment today! 😊")
        .show() {
        Ok(_) => {
            println!("{} {}\tNotification delivered",
                     "[Log]   ".green().bold(),
                     now.format("%Y/%m/%d %H:%M:%S").to_string())
        }
        Err(x) => {
            println!("{} {}\tNotification could not be delivered because of {:?}",
                     "[Error]".red().bold(),
                     now.format("%Y/%m/%d %H:%M:%S").to_string(),
                     x)
        }
    }

}

#[cfg(windows)]
fn deliver_notifiaction(now: &date::Date) {
    let now = Local::now();
    println!("{} {}\tNo notification support for Windows right now.",
             "[Error]".red().bold(),
             now.format("%Y/%m/%d %H:%M:%S").to_string());
    exit(1);
}
<|endoftext|>


<commit_before>#[macro_use]
extern crate clap;

fn main() {
    let matches = clap_app!(open_depacker =>
        (version: "0.1")
        (author: "Daniel Collin. <daniel@collin.com>")
        (about: "Generic data depacter")
        (@arg input: +required "Sets the input file to use")
        (@arg debug: -d ... "Sets the level of debugging information")
    ).get_matches();

    match matches.occurrences_of("debug") {
        0 => println!("Debug mode is off"),
        1 => println!("Debug mode is kind of on"),
        2 => println!("Debug mode is on"),
        3 | _ => println!("Don't be crazy"),
    }

    if let Some(ref file) = matches.value_of("input") {
        println!("Using config file: {}", file);
    }
}
<commit_msg>Fixed typo<commit_after>#[macro_use]
extern crate clap;

fn main() {
    let matches = clap_app!(open_depacker =>
        (version: "0.1")
        (author: "Daniel Collin. <daniel@collin.com>")
        (about: "Generic data depacker")
        (@arg input: +required "Sets the input file to use")
        (@arg debug: -d ... "Sets the level of debugging information")
    ).get_matches();

    match matches.occurrences_of("debug") {
        0 => println!("Debug mode is off"),
        1 => println!("Debug mode is kind of on"),
        2 => println!("Debug mode is on"),
        3 | _ => println!("Don't be crazy"),
    }

    if let Some(ref file) = matches.value_of("input") {
        println!("Using config file: {}", file);
    }
}
<|endoftext|>


<commit_before>extern crate toml;

use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::collections::BTreeMap;

fn strip_toolchain(name: &str) -> String {
    name.split('-').nth(0).unwrap().to_string()
}

fn read_settings() -> (String, BTreeMap<String, String>) {
    let mut settings_path = env::home_dir().unwrap();
    settings_path.push(".multirust/settings.toml");

    let mut file = File::open(&settings_path).expect("file open error");

    let mut buffer = String::new();
    file.read_to_string(&mut buffer).expect("read error");

    let value = toml::Parser::new(&buffer).parse().unwrap();
    let default = value.get("default_toolchain").unwrap().as_str().unwrap();
    let overrides = value.get("overrides").unwrap().as_table().unwrap();
    let overrides = overrides.iter()
        .map(|(k, v)| (k.to_string(), v.as_str().unwrap().to_string()))
        .collect();

    (default.into(), overrides)
}

fn main() {
    let cwd = env::current_dir().unwrap();
    let (default, overrides) = read_settings();

    let toolchain = match overrides.get(cwd.to_str().unwrap()) {
        Some(toolchain) => strip_toolchain(toolchain),
        None => default,
    };

    println!("{}", toolchain);
}
<commit_msg>do not convert every toml value to String every time the config is read.<commit_after>extern crate toml;

use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::collections::BTreeMap;

fn strip_toolchain(name: &toml::Value) -> String {
    name.as_str().unwrap().split('-').nth(0).unwrap().to_string()
}

fn read_settings() -> (String, BTreeMap<String, toml::Value>) {
    let mut settings_path = env::home_dir().unwrap();
    settings_path.push(".multirust/settings.toml");

    let mut file = File::open(&settings_path).expect("file open error");

    let mut buffer = String::new();
    file.read_to_string(&mut buffer).expect("read error");

    let value = toml::Parser::new(&buffer).parse().unwrap();
    let default = value.get("default_toolchain").unwrap().as_str().unwrap();
    let overrides = value.get("overrides").unwrap().as_table().unwrap();

    (default.to_owned(), overrides.to_owned())
}

fn main() {
    let cwd = env::current_dir().unwrap();
    let (default, overrides) = read_settings();

    let toolchain = match overrides.get(cwd.to_str().unwrap()) {
        Some(toolchain) => strip_toolchain(toolchain),
        None => default,
    };

    println!("{}", toolchain);
}
<|endoftext|>


<commit_before>extern crate clap;
#[macro_use]
extern crate error_chain;
extern crate bakervm_bytecodes as bytecode;
extern crate sdl2;

mod vm;
mod error;

use clap::{Arg, App};
use sdl2::event::Event;
use sdl2::rect::Rect;
use vm::VM;
use error::*;

fn main() {
    if let Err(ref e) = run() {
        println!("error: {}", e);

        for e in e.iter().skip(1) {
            println!("caused by: {}", e);
        }

        // The backtrace is not always generated. Try to run this example
        // with `RUST_BACKTRACE=1`.
        if let Some(backtrace) = e.backtrace() {
            println!("backtrace: {:?}", backtrace);
        }

        ::std::process::exit(1);
    }
}

fn run() -> VMResult<()> {
    let matches = App::new("bakerVM")
        .version("0.0.1")
        .author("Julian Laubstein <contact@julianlaubstein.de>")
        .about("A virtual machine for classic point-and-click adventure games")
        .arg(Arg::with_name("input")
            .index(1)
            .help("Sets the image file to use. Uses a standard image if not specified."))
        .get_matches();

    let input = matches.value_of("input").unwrap_or("").to_string();

    let mut vm = VM::new();

    vm.exec(input).chain_err(|| "unable to exec file")?;

    // start sdl2 with everything
    let ctx = sdl2::init().unwrap();
    let video_ctx = ctx.video().unwrap();

    // Create a window
    let window = match video_ctx.window("bakerVM", 640, 480).position_centered().opengl().build() {
        Ok(window) => window,
        Err(err) => bail!("failed to create window: {}", err),
    };

    // Create a rendering context
    let mut renderer = match window.renderer().build() {
        Ok(renderer) => renderer,
        Err(err) => bail!("failed to create renderer: {}", err),
    };

    // Set the drawing color to a light blue.
    let _ = renderer.set_draw_color(sdl2::pixels::Color::RGB(101, 208, 246));

    // Clear the buffer, using the light blue color set above.
    let _ = renderer.clear();

    // Set the drawing color to a darker blue.
    let _ = renderer.set_draw_color(sdl2::pixels::Color::RGB(0, 153, 204));

    // Create centered Rect, draw the outline of the Rect in our dark blue color.
    let border_rect = Rect::new(320 - 64, 240 - 64, 128, 128);
    let _ = renderer.draw_rect(border_rect);

    // Create a smaller centered Rect, filling it in the same dark blue.
    let inner_rect = Rect::new(320 - 60, 240 - 60, 120, 120);
    let _ = renderer.fill_rect(inner_rect);

    // Swap our buffer for the present buffer, displaying it.
    let _ = renderer.present();

    let mut events = ctx.event_pump().unwrap();

    // loop until we receive a QuitEvent
    'event: loop {
        for event in events.poll_iter() {
            match event {
                Event::Quit { .. } => break 'event,
                _ => continue,
            }
        }
    }

    Ok(())
}
<commit_msg>Simplified error handling<commit_after>extern crate clap;
#[macro_use]
extern crate error_chain;
extern crate bakervm_bytecodes as bytecode;
extern crate sdl2;

mod vm;
mod error;

use clap::{Arg, App};
use sdl2::event::Event;
use sdl2::rect::Rect;
use vm::VM;
use error::*;

fn main() {
    if let Err(ref e) = run() {
        println!("error: {}", e);

        for e in e.iter().skip(1) {
            println!("caused by: {}", e);
        }

        // The backtrace is not always generated. Try to run this example
        // with `RUST_BACKTRACE=1`.
        if let Some(backtrace) = e.backtrace() {
            println!("backtrace: {:?}", backtrace);
        }

        ::std::process::exit(1);
    }
}

fn run() -> VMResult<()> {
    let matches = App::new("bakerVM")
        .version("0.0.1")
        .author("Julian Laubstein <contact@julianlaubstein.de>")
        .about("A virtual machine for classic point-and-click adventure games")
        .arg(Arg::with_name("input")
            .index(1)
            .help("Sets the image file to use. Uses a standard image if not specified."))
        .get_matches();

    let input = matches.value_of("input").unwrap_or("").to_string();

    let mut vm = VM::new();

    vm.exec(input).chain_err(|| "unable to exec file")?;

    // start sdl2 with everything
    let ctx = sdl2::init().unwrap();
    let video_ctx = ctx.video().unwrap();

    // Create a window
    let window = video_ctx.window("bakerVM", 640, 480)
        .position_centered()
        .opengl()
        .build()
        .chain_err(|| "unable to create window")?;

    // Create a rendering context
    let mut renderer = window.renderer().build().chain_err(|| "unable to create renderer")?;

    // Set the drawing color to a light blue.
    let _ = renderer.set_draw_color(sdl2::pixels::Color::RGB(101, 208, 246));

    // Clear the buffer, using the light blue color set above.
    let _ = renderer.clear();

    // Set the drawing color to a darker blue.
    let _ = renderer.set_draw_color(sdl2::pixels::Color::RGB(0, 153, 204));

    // Create centered Rect, draw the outline of the Rect in our dark blue color.
    let border_rect = Rect::new(320 - 64, 240 - 64, 128, 128);
    let _ = renderer.draw_rect(border_rect);

    // Create a smaller centered Rect, filling it in the same dark blue.
    let inner_rect = Rect::new(320 - 60, 240 - 60, 120, 120);
    let _ = renderer.fill_rect(inner_rect);

    // Swap our buffer for the present buffer, displaying it.
    let _ = renderer.present();

    let mut events = ctx.event_pump().unwrap();

    // loop until we receive a QuitEvent
    'event: loop {
        for event in events.poll_iter() {
            match event {
                Event::Quit { .. } => break 'event,
                _ => continue,
            }
        }
    }

    Ok(())
}
<|endoftext|>


<commit_before>struct AddressSpace {
    data: [u8; 0xFFFF],
}

impl AddressSpace {

    fn new() -> AddressSpace {
        AddressSpace { data: [0; 0xFFFF] }
    }

    fn read(&self, addr: u16) -> u8 {
        self.data[addr as usize]
    }

    fn write(&mut self, addr: u16, data: u8) {
        self.data[addr as usize] = data;
    }

}

struct Instr<'a> {
    opcode: u8,
    data: Option<&'a [u8]>,
}

impl<'a> Instr<'a> {

    fn new(opcode: u8, data: Option<&[u8]>) -> Instr {
        Instr { opcode: opcode, data: data }
    }

    fn opcode(&self) -> u8 {
        self.opcode
    }

    fn param(&self, i: usize) -> u8 {
        self.data.expect("Instruction type does not carry parameters")[i]
    }

}

fn main() {
    println!("Hello, world!");
}
<commit_msg>Implement simple instruction parser<commit_after>struct AddressSpace {
    data: [u8; 0xFFFF],
}

impl AddressSpace {

    fn new() -> AddressSpace {
        AddressSpace { data: [0; 0xFFFF] }
    }

    fn read(&self, addr: u16) -> u8 {
        self.data[addr as usize]
    }

    fn read_slice(&self, addr: u16, bytes: u16) -> &[u8] {
        self.data.slice(addr as usize, (addr + bytes) as usize)
    }

    fn write(&mut self, addr: u16, data: u8) {
        self.data[addr as usize] = data;
    }

}

struct Instr<'a> {
    opcode: u8,
    data: Option<&'a [u8]>,
}

impl<'a> Instr<'a> {

    fn new(opcode: u8, data: Option<&[u8]>) -> Instr {
        Instr { opcode: opcode, data: data }
    }

    fn opcode(&self) -> u8 {
        self.opcode
    }

    fn param(&self, i: usize) -> u8 {
        self.data.expect("Instruction type does not carry parameters")[i]
    }

}

struct InstrParser<'a> {
    rom: &'a AddressSpace,
    pc: u16,
}

impl<'a> InstrParser<'a> {

    fn new(rom: &AddressSpace) -> InstrParser {
        InstrParser { rom: rom, pc: 0x100 }
    }

    fn next_instr(&mut self) -> Instr {
        let opcode = self.rom.read(self.pc);
        self.pc += 1;
        Instr {
            opcode: opcode,
            data: None,
        }
    }

    fn set_pc(&mut self, pc: u16) {
        self.pc = pc;
    }

}

fn main() {
    println!("Hello, world!");
}
<|endoftext|>


<commit_before>extern crate hyper;
extern crate itertools;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;

mod get;
mod post;
mod makeresponse;

use hyper::{Get, Post};
use hyper::header;
use hyper::server::{Handler, Server, Request, Response};
use hyper::status::StatusCode;

struct HttpTin {
    server: String,
}

impl HttpTin {
    pub fn new() -> Self {
        let server = format!("{}/{}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));
        HttpTin { server: server }
    }

    fn prepare_response(&self, response: &mut Response) {
        let server = header::Server(self.server.clone());
        response.headers_mut().set(server);
    }
}

impl Handler for HttpTin {
    fn handle(&self, request: Request, mut response: Response) {
        println!("{} {} {}", request.remote_addr, request.method, request.uri);
        self.prepare_response(&mut response);
        match request.method {
            Get => get::handler(request, response),
            Post => post::handler(request, response),
            _ => *response.status_mut() = StatusCode::MethodNotAllowed,
        }
    }
}

fn main() {
    let server = Server::http("localhost:8000").unwrap();
    if let Ok(active) = server.handle(HttpTin::new()) {
        println!("Listening on {:?}", active.socket);
    }
}
<commit_msg>Drop another debug println!()<commit_after>extern crate hyper;
extern crate itertools;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;

mod get;
mod post;
mod makeresponse;

use hyper::{Get, Post};
use hyper::header;
use hyper::server::{Handler, Server, Request, Response};
use hyper::status::StatusCode;

struct HttpTin {
    server: String,
}

impl HttpTin {
    pub fn new() -> Self {
        let server = format!("{}/{}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));
        HttpTin { server: server }
    }

    fn prepare_response(&self, response: &mut Response) {
        let server = header::Server(self.server.clone());
        response.headers_mut().set(server);
    }
}

impl Handler for HttpTin {
    fn handle(&self, request: Request, mut response: Response) {
        self.prepare_response(&mut response);
        match request.method {
            Get => get::handler(request, response),
            Post => post::handler(request, response),
            _ => *response.status_mut() = StatusCode::MethodNotAllowed,
        }
    }
}

fn main() {
    let server = Server::http("localhost:8000").unwrap();
    if let Ok(active) = server.handle(HttpTin::new()) {
        println!("Listening on {:?}", active.socket);
    }
}
<|endoftext|>


<commit_before>extern crate crypto;
extern crate regex;
extern crate rustc_serialize;

use crypto::md5::Md5;
use crypto::digest::Digest;

use rustc_serialize::{json, Decodable, Encodable};

use std::collections::HashMap;
use std::ffi::OsString;
use std::fs::{self, DirEntry, File};
use std::io::prelude::*;
use std::path::Path;
use std::process::{self, Command};

trait Stringable {
    fn to_string(self) -> String;
}

impl Stringable for DirEntry {
    fn to_string(self) -> String {
        self.path().as_path().to_str().unwrap().to_owned()
    }
}

impl Stringable for OsString {
    fn to_string(self) -> String {
        self.as_os_str().to_str().unwrap().to_owned()
    }
}

const INDEX_PATH: &'static str = ".roller_index.json";
const CONFIG_PATH: &'static str = ".roller_config.json";

// Map from path to hash
#[derive(RustcDecodable, RustcEncodable, Default)]
pub struct Index {
    files: HashMap<String, String>,
}

#[derive(RustcDecodable)]
pub struct Lint {
    name: String,
    command: String,
    args: Vec<String>,
}

impl Lint {
    fn command(&self, paths: &[String]) -> Command {
        let mut c = Command::new(&self.command);
        for arg in &self.args {
            c.arg(arg);
        }
        for path in paths {
            c.arg(path);
        }
        c
    }

    // runs this lint on all given files, return all the clean files
    fn resolve(&self, files: Vec<String>) -> Vec<String> {
        let output = &self.command(&files)
                          .output()
                          .unwrap_or_else(|_| {
                              println!("{} not installed", self.name);
                              process::exit(1);
                          });
        let stdout = String::from_utf8_lossy(&output.stdout);
        if stdout != "" {
            println!("{}", stdout);
        }
        let stderr = String::from_utf8_lossy(&output.stderr);
        if stderr != "" {
            println!("{}", stderr);
        }
        files.into_iter()
             .filter(|file| {
                 let re = regex::Regex::new(&format!(".*{}.*", file)).unwrap();
                 !re.is_match(&stdout) && !re.is_match(&stderr)
             })
             .collect()
    }
}

#[derive(RustcDecodable)]
pub struct LintConfig {
    // filetypes is a map from extension to lints
    filetypes: HashMap<String, Vec<Lint>>,
    global_ignore: Vec<String>,
}

impl Default for LintConfig {
    fn default() -> Self {
        println!("No {} file was found", CONFIG_PATH);
        process::exit(1);
    }
}

fn main() {
    let lint_config: LintConfig = load(CONFIG_PATH);
    let mut new_index = Index::default();

    for (extension, lints) in &lint_config.filetypes {
        let mut files = dirty_files(extension, &lint_config.global_ignore, &mut new_index);

        for lint in lints.iter() {
            if !files.is_empty() {
                println!("Running {} on {} files", lint.name, files.len());
                files = lint.resolve(files);
            }
        }

        while let Some(file) = files.pop() {
            let file_hash = hash(&file);
            new_index.files.insert(file, file_hash);
        }
    }

    save(INDEX_PATH, &new_index);
}

fn dirty_files(extension: &str, ignore: &[String], new_index: &mut Index) -> Vec<String> {
    let old_index: Index = load(INDEX_PATH);
    let mut dirty_files = vec![];

    let mut dirs_to_visit: Vec<String> = vec![".".to_owned()];
    while let Some(dir) = dirs_to_visit.pop() {

        for entry in fs::read_dir(dir).unwrap() {
            let dir_entry = entry.unwrap();

            let file_name = dir_entry.file_name().to_string();
            let file_extension = match dir_entry.path().extension() {
                Some(ext) => ext.to_str().unwrap().to_owned(),
                None => "".to_owned(),
            };

            if ignore.contains(&file_name) {
                continue;
            }

            let path = dir_entry.to_string();

            if (fs::metadata(path.clone()).unwrap()).is_dir() {
                dirs_to_visit.push(path);
                continue;
            }

            if &file_extension != extension {
                continue;
            }

            let file_hash = hash(&path);
            if old_index.files.get(&path) != Some(&file_hash) {
                dirty_files.push(path);
            } else {
                new_index.files.insert(path, file_hash);
            }
        }

    }
    dirty_files
}

fn hash(path: &str) -> String {
    let mut file = match File::open(path) {
        Err(_) => panic!("couldn't open file to get hash: {}", path),
        Ok(file) => file,
    };
    let mut s = String::new();
    match file.read_to_string(&mut s) {
        Err(_) => panic!("couldn't read file to string: {}", path),
        Ok(_) => (),
    };

    let mut hasher = Md5::new();
    hasher.input(s.as_bytes());
    let mut output = [0; 16]; // Md5 is 16 bytes
    hasher.result(&mut output);
    let temp: &[u8] = &output;
    rustc_serialize::hex::ToHex::to_hex(temp)
}

fn save<P: AsRef<Path>, T: Encodable>(path: P, t: &T) {
    let encoded = json::encode(t).unwrap();
    let mut file = File::create(path).unwrap();
    match write!(file, "{}", encoded) {
        Err(_) => panic!(),
        Ok(_) => (),
    };
}

fn load<P: AsRef<Path>, T: Decodable + Default>(path: P) -> T {
    let mut file = match File::open(path) {
        Err(_) => return T::default(),
        Ok(file) => file,
    };
    let mut s = String::new();
    file.read_to_string(&mut s).unwrap();

    json::decode(&s).expect("Could not decode json")
}
<commit_msg>Rename to generate_command to avoid confusion<commit_after>extern crate crypto;
extern crate regex;
extern crate rustc_serialize;

use crypto::md5::Md5;
use crypto::digest::Digest;

use rustc_serialize::{json, Decodable, Encodable};

use std::collections::HashMap;
use std::ffi::OsString;
use std::fs::{self, DirEntry, File};
use std::io::prelude::*;
use std::path::Path;
use std::process::{self, Command};

trait Stringable {
    fn to_string(self) -> String;
}

impl Stringable for DirEntry {
    fn to_string(self) -> String {
        self.path().as_path().to_str().unwrap().to_owned()
    }
}

impl Stringable for OsString {
    fn to_string(self) -> String {
        self.as_os_str().to_str().unwrap().to_owned()
    }
}

const INDEX_PATH: &'static str = ".roller_index.json";
const CONFIG_PATH: &'static str = ".roller_config.json";

// Map from path to hash
#[derive(RustcDecodable, RustcEncodable, Default)]
pub struct Index {
    files: HashMap<String, String>,
}

#[derive(RustcDecodable)]
pub struct Lint {
    name: String,
    command: String,
    args: Vec<String>,
}

impl Lint {
    fn generate_command(&self, paths: &[String]) -> Command {
        let mut c = Command::new(&self.command);
        for arg in &self.args {
            c.arg(arg);
        }
        for path in paths {
            c.arg(path);
        }
        c
    }

    // runs this lint on all given files, return all the clean files
    fn resolve(&self, files: Vec<String>) -> Vec<String> {
        let output = &self.generate_command(&files)
                          .output()
                          .unwrap_or_else(|_| {
                              println!("{} not installed", self.name);
                              process::exit(1);
                          });
        let stdout = String::from_utf8_lossy(&output.stdout);
        if stdout != "" {
            println!("{}", stdout);
        }
        let stderr = String::from_utf8_lossy(&output.stderr);
        if stderr != "" {
            println!("{}", stderr);
        }
        files.into_iter()
             .filter(|file| {
                 let re = regex::Regex::new(&format!(".*{}.*", file)).unwrap();
                 !re.is_match(&stdout) && !re.is_match(&stderr)
             })
             .collect()
    }
}

#[derive(RustcDecodable)]
pub struct LintConfig {
    // filetypes is a map from extension to lints
    filetypes: HashMap<String, Vec<Lint>>,
    global_ignore: Vec<String>,
}

impl Default for LintConfig {
    fn default() -> Self {
        println!("No {} file was found", CONFIG_PATH);
        process::exit(1);
    }
}

fn main() {
    let lint_config: LintConfig = load(CONFIG_PATH);
    let mut new_index = Index::default();

    for (extension, lints) in &lint_config.filetypes {
        let mut files = dirty_files(extension, &lint_config.global_ignore, &mut new_index);

        for lint in lints.iter() {
            if !files.is_empty() {
                println!("Running {} on {} files", lint.name, files.len());
                files = lint.resolve(files);
            }
        }

        while let Some(file) = files.pop() {
            let file_hash = hash(&file);
            new_index.files.insert(file, file_hash);
        }
    }

    save(INDEX_PATH, &new_index);
}

fn dirty_files(extension: &str, ignore: &[String], new_index: &mut Index) -> Vec<String> {
    let old_index: Index = load(INDEX_PATH);
    let mut dirty_files = vec![];

    let mut dirs_to_visit: Vec<String> = vec![".".to_owned()];
    while let Some(dir) = dirs_to_visit.pop() {

        for entry in fs::read_dir(dir).unwrap() {
            let dir_entry = entry.unwrap();

            let file_name = dir_entry.file_name().to_string();
            let file_extension = match dir_entry.path().extension() {
                Some(ext) => ext.to_str().unwrap().to_owned(),
                None => "".to_owned(),
            };

            if ignore.contains(&file_name) {
                continue;
            }

            let path = dir_entry.to_string();

            if (fs::metadata(path.clone()).unwrap()).is_dir() {
                dirs_to_visit.push(path);
                continue;
            }

            if &file_extension != extension {
                continue;
            }

            let file_hash = hash(&path);
            if old_index.files.get(&path) != Some(&file_hash) {
                dirty_files.push(path);
            } else {
                new_index.files.insert(path, file_hash);
            }
        }

    }
    dirty_files
}

fn hash(path: &str) -> String {
    let mut file = match File::open(path) {
        Err(_) => panic!("couldn't open file to get hash: {}", path),
        Ok(file) => file,
    };
    let mut s = String::new();
    match file.read_to_string(&mut s) {
        Err(_) => panic!("couldn't read file to string: {}", path),
        Ok(_) => (),
    };

    let mut hasher = Md5::new();
    hasher.input(s.as_bytes());
    let mut output = [0; 16]; // Md5 is 16 bytes
    hasher.result(&mut output);
    let temp: &[u8] = &output;
    rustc_serialize::hex::ToHex::to_hex(temp)
}

fn save<P: AsRef<Path>, T: Encodable>(path: P, t: &T) {
    let encoded = json::encode(t).unwrap();
    let mut file = File::create(path).unwrap();
    match write!(file, "{}", encoded) {
        Err(_) => panic!(),
        Ok(_) => (),
    };
}

fn load<P: AsRef<Path>, T: Decodable + Default>(path: P) -> T {
    let mut file = match File::open(path) {
        Err(_) => return T::default(),
        Ok(file) => file,
    };
    let mut s = String::new();
    file.read_to_string(&mut s).unwrap();

    json::decode(&s).expect("Could not decode json")
}
<|endoftext|>


<commit_before>extern crate rand;

use rand::Rng;
use rand::distributions;
use individual::Individual;

mod individual;

fn select<R: Rng>(population: &Vec<Individual>, rng: &mut R)
                  -> Individual {
    if let Some(selected) = (0..4).map(|_| rng.choose(population)).min() {
        selected.unwrap().clone()
    } else {
        unimplemented!();
    }
}

fn main() {
    let mut rng = rand::thread_rng();
    let range = distributions::Range::new(-512.03_f64, 511.97);

    // initialize population
    let mut population: Vec<_> = (0..128).map(|_| {
        Individual::new(&range, &mut rng)
    }).collect();

    for i in 0..10000 {
        // select and mutate individuals for next population
        population = (0..128).map(|_| {
            select(&population, &mut rng).mutate(&range, &mut rng)
        }).collect();

        if let Some(x) = population.iter().min() {
            if i % 100 == 0 {
                println!("{}th fitness: {}", i, x.fitness);
            }

            if x.fitness < 1000_f64 {
                println!("{}th solution converged at {}: {:?}",
                         i, x.fitness, x.solution);
                return;
            }
        } else { unimplemented!() }
    }
    println!("Failed to converge.");
}
<commit_msg>Use recombination in algorithm<commit_after>extern crate rand;

use rand::Rng;
use rand::distributions;
use individual::Individual;

mod individual;

fn select<R: Rng>(population: &Vec<Individual>, rng: &mut R)
                  -> Individual {
    if let Some(selected) = (0..4).map(|_| rng.choose(population)).min() {
        selected.unwrap().clone()
    } else {
        unimplemented!();
    }
}

fn main() {
    let mut rng = rand::thread_rng();
    let range = distributions::Range::new(-512.03_f64, 511.97);

    // initialize population
    let mut population: Vec<_> = (0..128).map(|_| {
        Individual::new(&range, &mut rng)
    }).collect();

    for i in 0..10000 {
        // select, mutate, and recombine individuals for next population
        let mut offspring: Vec<Individual> = Vec::with_capacity(population.len());
        for _ in (0..population.len()/2) {
            let (mut x, mut y) = (select(&population, &mut rng),
                                  select(&population, &mut rng));
            x.mutate(&range, &mut rng);
            y.mutate(&range, &mut rng);
            Individual::combine(&mut x, &mut y, &mut rng);
            offspring.push(x);
            offspring.push(y);
        }
        assert!(offspring.len() == population.len());
        population = offspring;

        if let Some(x) = population.iter().min() {
            if i % 100 == 0 {
                println!("{}th fitness: {}", i, x.fitness);
            }

            if x.fitness < 1000_f64 {
                println!("{}th solution converged at {}: {:?}",
                         i, x.fitness, x.solution);
                return;
            }
        } else { unimplemented!() }
    }
    println!("Failed to converge.");
}
<|endoftext|>


<commit_before>#![cfg_attr(feature = "cargo-clippy", allow(match_same_arms))]
#![cfg_attr(feature = "cargo-clippy", allow(let_and_return))]
#![cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))]

extern crate case;
extern crate docopt;
extern crate env_logger;
#[macro_use]
extern crate error_chain;
extern crate git2;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate xml;
extern crate toml;
extern crate regex;
extern crate hprof;
extern crate stripper_lib;

use std::cell::RefCell;

use env::Env;
use library::Library;
use hprof::Profiler;

//generated by build.rs
mod gir_version;

mod analysis;
mod chunk;
mod codegen;
mod config;
mod consts;
mod env;
mod file_saver;
mod git;
mod library;
mod library_postprocessing;
mod nameutil;
mod parser;
mod traits;
mod update_version;
mod version;
mod writer;

use self::config::error::*;

#[cfg_attr(test, allow(dead_code))]
fn main() {
    if let Err(ref e) = do_main() {
        println!("{}", e);

        for e in e.iter().skip(1) {
            println!("caused by: {}", e);
        }

        ::std::process::exit(1);
    }
}

fn do_main() -> Result<()> {
    if std::env::var_os("RUST_LOG").is_none() {
        std::env::set_var("RUST_LOG", "gir=warn");
    }
    try!(env_logger::init());

    let mut cfg = match config::Config::new() {
        Ok(cfg) => cfg,
        Err(Error(ErrorKind::CommandLine(ref err), _)) => {
            // Fatal errors processed in same branch
            // to prevent repeat message in "caused by:"
            if err.fatal() {
                println!("error: {}", err);
            } else {
                println!("{}", err);
            }
            return Ok(());
        }
        Err(err) => return Err(err),
    };

    let statistics = Profiler::new("Gir");
    statistics.start_frame();

    let watcher_total = statistics.enter("Total");

    let mut library;

    {
        let _watcher = statistics.enter("Loading");

        library = Library::new(&cfg.library_name);
        try!(library.read_file(&cfg.girs_dir, &cfg.library_full_name()));
    }

    {
        let _watcher = statistics.enter("Postprocessing");
        library.postprocessing();
    }

    {
        let _watcher = statistics.enter("Resolving type ids");
        cfg.resolve_type_ids(&library);
    }

    {
        let _watcher = statistics.enter("Checking versions");
        update_version::check_function_real_version(&mut library);
    }

    let mut env;

    {
        let _watcher = statistics.enter("Namespace/symbol/class analysis");

        let namespaces = analysis::namespaces::run(&library);
        let symbols = analysis::symbols::run(&library, &namespaces);
        let class_hierarchy = analysis::class_hierarchy::run(&library);

        env = Env {
            library: library,
            config: cfg,
            namespaces: namespaces,
            symbols: RefCell::new(symbols),
            class_hierarchy: class_hierarchy,
            analysis: Default::default(),
        };
    }

    {
        let _watcher = statistics.enter("Analysing");
        analysis::run(&mut env);
    }

    {
        let _watcher = statistics.enter("Generating");

        codegen::generate(&env);
    }

    drop(watcher_total);
    statistics.end_frame();

    if env.config.show_statistics {
        statistics.print_timing();
    }

    Ok(())
}
<commit_msg>Whitespace fix<commit_after>#![cfg_attr(feature = "cargo-clippy", allow(match_same_arms))]
#![cfg_attr(feature = "cargo-clippy", allow(let_and_return))]
#![cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))]

extern crate case;
extern crate docopt;
extern crate env_logger;
#[macro_use]
extern crate error_chain;
extern crate git2;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate xml;
extern crate toml;
extern crate regex;
extern crate hprof;
extern crate stripper_lib;

use std::cell::RefCell;

use env::Env;
use library::Library;
use hprof::Profiler;

//generated by build.rs
mod gir_version;

mod analysis;
mod chunk;
mod codegen;
mod config;
mod consts;
mod env;
mod file_saver;
mod git;
mod library;
mod library_postprocessing;
mod nameutil;
mod parser;
mod traits;
mod update_version;
mod version;
mod writer;

use self::config::error::*;

#[cfg_attr(test, allow(dead_code))]
fn main() {
    if let Err(ref e) = do_main() {
        println!("{}", e);

        for e in e.iter().skip(1) {
            println!("caused by: {}", e);
        }

        ::std::process::exit(1);
    }
}

fn do_main() -> Result<()> {
    if std::env::var_os("RUST_LOG").is_none() {
        std::env::set_var("RUST_LOG", "gir=warn");
    }
    try!(env_logger::init());

    let mut cfg = match config::Config::new() {
        Ok(cfg) => cfg,
        Err(Error(ErrorKind::CommandLine(ref err), _)) => {
            // Fatal errors processed in same branch
            // to prevent repeat message in "caused by:"
            if err.fatal() {
                println!("error: {}", err);
            } else {
                println!("{}", err);
            }
            return Ok(());
        }
        Err(err) => return Err(err),
    };

    let statistics = Profiler::new("Gir");
    statistics.start_frame();

    let watcher_total = statistics.enter("Total");

    let mut library;

    {
        let _watcher = statistics.enter("Loading");

        library = Library::new(&cfg.library_name);
        try!(library.read_file(&cfg.girs_dir, &cfg.library_full_name()));
    }

    {
        let _watcher = statistics.enter("Postprocessing");
        library.postprocessing();
    }

    {
        let _watcher = statistics.enter("Resolving type ids");
        cfg.resolve_type_ids(&library);
    }

    {
        let _watcher = statistics.enter("Checking versions");
        update_version::check_function_real_version(&mut library);
    }

    let mut env;

    {
        let _watcher = statistics.enter("Namespace/symbol/class analysis");

        let namespaces = analysis::namespaces::run(&library);
        let symbols = analysis::symbols::run(&library, &namespaces);
        let class_hierarchy = analysis::class_hierarchy::run(&library);

        env = Env {
            library: library,
            config: cfg,
            namespaces: namespaces,
            symbols: RefCell::new(symbols),
            class_hierarchy: class_hierarchy,
            analysis: Default::default(),
        };
    }

    {
        let _watcher = statistics.enter("Analysing");
        analysis::run(&mut env);
    }

    {
        let _watcher = statistics.enter("Generating");
        codegen::generate(&env);
    }

    drop(watcher_total);
    statistics.end_frame();

    if env.config.show_statistics {
        statistics.print_timing();
    }

    Ok(())
}
<|endoftext|>


<commit_before>extern crate html5ever;
extern crate hyper;
extern crate hyper_native_tls;
extern crate url;

use std::default::Default;
use std::io;

use html5ever::{parse_document, serialize};
use html5ever::rcdom::RcDom;
use html5ever::tendril::TendrilSink;

use hyper::client::Client;
use hyper::header::ContentType;
use hyper::net::HttpsConnector;
use hyper_native_tls::NativeTlsClient;

use url::form_urlencoded;

fn main() {
    let ssl = NativeTlsClient::new().unwrap();
    let http_client = Client::with_connector(HttpsConnector::new(ssl));

    let body = form_urlencoded::Serializer::new(String::new())
        .append_pair("contractCode", "NRSO")
        .append_pair("parkId", "70928")
        .append_pair("siteTypeFilter", "ALL")
        .append_pair("availStatus", "ONLINE")
        .append_pair("submitSiteForm", "true")
        .append_pair("search", "site")
        .append_pair("arrivalDate", "Tue Sep 12 2017")
        .append_pair("departureDate", "Wed Sep 13 2017")
        .append_pair("flexDates", "")
        .append_pair("loop", "")
        .append_pair("siteCode", "")
        .append_pair("lookingFor", "")
        .append_pair("camping_common_218", "")
        .append_pair("camping_common_3012", "")
        .append_pair("camping_common_3013", "")
        .finish();

    let mut response = http_client.post("https://www.recreation.gov/campsiteSearch.do")
        .header(ContentType::form_url_encoded())
        .body(&body)
        .send()
        .unwrap();

    let dom: RcDom = parse_document(RcDom::default(), Default::default())
        .from_utf8()
        .read_from(&mut response)
        .unwrap();

    // TODO(John Sirois): index into the dom to check for available sites.
    serialize(&mut io::stdout(), &dom.document, Default::default())
        .ok()
        .expect("Failed to serialize post body to stdout!")
}
<commit_msg>Add some TODOs.<commit_after>extern crate html5ever;
extern crate hyper;
extern crate hyper_native_tls;
extern crate url;

use std::default::Default;
use std::io;

use html5ever::{parse_document, serialize};
use html5ever::rcdom::RcDom;
use html5ever::tendril::TendrilSink;

use hyper::client::Client;
use hyper::header::ContentType;
use hyper::net::HttpsConnector;
use hyper_native_tls::NativeTlsClient;

use url::form_urlencoded;

fn main() {
    let ssl = NativeTlsClient::new().unwrap();
    let http_client = Client::with_connector(HttpsConnector::new(ssl));

    let body = form_urlencoded::Serializer::new(String::new())
        .append_pair("contractCode", "NRSO")
        .append_pair("parkId", "70928")
        .append_pair("siteTypeFilter", "ALL")
        .append_pair("availStatus", "ONLINE")
        .append_pair("submitSiteForm", "true")
        .append_pair("search", "site")
        .append_pair("arrivalDate", "Tue Sep 12 2017")
        .append_pair("departureDate", "Wed Sep 13 2017")
        .append_pair("flexDates", "")
        .append_pair("loop", "")
        .append_pair("siteCode", "")
        .append_pair("lookingFor", "")
        .append_pair("camping_common_218", "")
        .append_pair("camping_common_3012", "")
        .append_pair("camping_common_3013", "")
        .finish();

    // TODO(John Sirois): Handle request errors instead of panicking.
    let mut response = http_client.post("https://www.recreation.gov/campsiteSearch.do")
        .header(ContentType::form_url_encoded())
        .body(&body)
        .send()
        .unwrap();

    // TODO(John Sirois): Handle request errors instead of panicking.
    let dom: RcDom = parse_document(RcDom::default(), Default::default())
        .from_utf8()
        .read_from(&mut response)
        .unwrap();

    // TODO(John Sirois): index into the dom to check for available sites.
    serialize(&mut io::stdout(), &dom.document, Default::default())
        .ok()
        .expect("Failed to serialize post body to stdout!")
}
<|endoftext|>


<commit_before>// Copyright © 2014, Peter Atashian

#![feature(phase, associated_types, slicing_syntax)]

extern crate cookie;
extern crate hyper;
extern crate image;
#[phase(plugin)]
extern crate regex_macros;
extern crate regex;
extern crate "rustc-serialize" as serialize;
extern crate url;

use image::{GenericImage, ImageBuffer, Pixel, Rgba, RgbaImage};
use image::ColorType::RGBA;
use std::borrow::ToOwned;
use std::collections::HashMap;
use std::io::{ALL_PERMISSIONS, BufferedWriter, File};
use std::io::fs::{PathExtensions, copy, mkdir, readdir};
use std::io::stdio::{flush, stdin};
use std::num::{Float, FloatMath};

pub mod tilesheets;

type FloatImage = ImageBuffer<Vec<f32>, f32, Rgba<f32>>;
pub fn save(img: &RgbaImage, path: &Path) {
    image::save_buffer(path, img.as_slice(), img.width(), img.height(), RGBA(8)).unwrap();
}

pub fn dump_descriptions() {
    let path = Path::new(r"C:\Users\retep998\Minecraft\Wiki\GT Lang\GregTech.lang");
    let mut file = File::open(&path).unwrap();
    let data = file.read_to_string().unwrap();
    let reg = regex!(r"S:TileEntity_DESCRIPTION_(\d+)_([0-9A-Za-z_]+)=(.+?)\r?\n");
    let mut descs = Vec::new();
    for cap in reg.captures_iter(data.as_slice()) {
        let index: i32 = cap.at(1).unwrap().parse().unwrap();
        let name = cap.at(2).unwrap();
        let desc = cap.at(3).unwrap();
        descs.push((index, name, desc));
    }
    descs.sort_by(|&(a, _, _), &(b, _, _)| a.cmp(&b));
    let mut file = BufferedWriter::new(File::create(&Path::new("descriptions.txt")).unwrap());
    for desc in descs.iter() {
        let &(index, name, desc) = desc;
        (write!(&mut file, "{},{},", index, name)).unwrap();
        let mut color = false;
        let mut code = false;
        for c in desc.chars() {
            match code {
                true => {
                    code = false;
                    if color { file.write_str("}}").unwrap() }
                    color = true;
                    match c {
                        '0' => file.write_str("{{Color|000000|").unwrap(),
                        '1' => file.write_str("{{Color|0000AA|").unwrap(),
                        '2' => file.write_str("{{Color|00AA00|").unwrap(),
                        '3' => file.write_str("{{Color|00AAAA|").unwrap(),
                        '4' => file.write_str("{{Color|AA0000|").unwrap(),
                        '5' => file.write_str("{{Color|AA00AA|").unwrap(),
                        '6' => file.write_str("{{Color|FFAA00|").unwrap(),
                        '7' => file.write_str("{{Color|AAAAAA|").unwrap(),
                        '8' => file.write_str("{{Color|555555|").unwrap(),
                        '9' => file.write_str("{{Color|5555FF|").unwrap(),
                        'a' => file.write_str("{{Color|55FF55|").unwrap(),
                        'b' => file.write_str("{{Color|55FFFF|").unwrap(),
                        'c' => file.write_str("{{Color|FF5555|").unwrap(),
                        'd' => file.write_str("{{Color|FF55FF|").unwrap(),
                        'e' => file.write_str("{{Color|FFFF55|").unwrap(),
                        'f' => file.write_str("{{Color|FFFFFF|").unwrap(),
                        'r' => color = false,
                        _ => println!("Unknown: {}", c),
                    }
                },
                false => {
                    match c {
                        '§' => code = true,
                        c => file.write_char(c).unwrap(),
                    }
                },
            }
        }
        if color { file.write_str("}}").unwrap() }
        file.write_line("").unwrap();
    }
}
pub fn read_gt_lang() -> HashMap<String, String> {
    let path = Path::new(r"work/GregTech.lang");
    let mut file = File::open(&path).unwrap();
    let data = file.read_to_string().unwrap();
    let reg = regex!(r"S:([\w\.]+?)=(.+?)\r?\n");
    reg.captures_iter(data.as_slice()).map(|cap|
        (cap.at(1).unwrap().to_owned(), cap.at(2).unwrap().to_owned())
    ).collect()
}
pub fn import_special_metaitems(lang: &HashMap<String, String>) {
    print!("Importing special metaitems... ");
    flush();
    let inpath = Path::new(r"work\assets\gt\gregtech\textures\items");
    let outpath = Path::new(r"work\tilesheets\GT");
    let _ = mkdir(&outpath, ALL_PERMISSIONS);
    let import = |category: &str| {
        for path in readdir(&inpath.join(category)).unwrap().iter() {
            if !path.is_file() { continue }
            if path.extension_str() != Some("png") { continue }
            let stub: u32 = path.filestem_str().unwrap().parse().unwrap();
            let rawname = format!("{}.{}.name", category, stub + 32000);
            let name = match lang.get(&rawname) {
                Some(s) => format!("{}.png", s),
                None => continue,
            };
            let out = outpath.join(name[]);
            copy(path, &out).unwrap();
        }
    };
    import("gt.metaitem.01");
    import("gt.metaitem.02");
    println!(" done!");
}
pub fn import_fluids(lang: &HashMap<String, String>) {
    print!("Importing fluids... ");
    flush();
    let inpath = Path::new(r"work\assets\gt\gregtech\textures\blocks\fluids");
    let outpath = Path::new(r"work\tilesheets\GT");
    let _ = mkdir(&outpath, ALL_PERMISSIONS);
    for path in readdir(&inpath).unwrap().iter() {
        if !path.is_file() { continue }
        if path.extension_str() != Some("png") { continue }
        let stub = path.filestem_str().unwrap();
        let name = match lang.get(stub) {
            Some(s) => s,
            None => continue,
        };
        let name = format!("{} (Fluid)", name);
        let mut out = outpath.join(name.as_slice());
        out.set_extension("png");
        let img = image::open(path).unwrap().to_rgba();
        let w = img.width();
        let mut pixels = img.into_vec();
        pixels.truncate((w * w * 4) as uint);
        let img = ImageBuffer::from_raw(w, w, pixels).unwrap();
        save(&img, &out);
    }
    println!(" done!");
}
trait Srgb {
    type Linear;
    fn decode(&self) -> <Self as Srgb>::Linear;
}
impl Srgb for Rgba<u8> {
    type Linear = Rgba<f32>;
    fn decode(&self) -> Rgba<f32> {
        fn dec(x: u8) -> f32 {
            let x = x as f32 * (1. / 255.);
            if x <= 0.04045 {
                x / 12.92
            } else {
                ((x + 0.055) / (1. + 0.055)).powf(2.4)
            }
        }
        let p = Rgba([dec(self[0]), dec(self[1]), dec(self[2]), dec(self[3])]);
        Rgba([p[0] * p[3], p[1] * p[3], p[2] * p[3], p[3]])
    }
}
fn decode_srgb(img: &RgbaImage) -> FloatImage {
    let (w, h) = img.dimensions();
    ImageBuffer::from_fn(w, h, |x, y| img[(x, y)].decode())
}
trait Linear {
    type Srgb;
    fn encode(&self) -> <Self as Linear>::Srgb;
}
impl Linear for Rgba<f32> {
    type Srgb = Rgba<u8>;
    fn encode(&self) -> Rgba<u8> {
        fn enc(x: f32) -> u8 {
            let x = if x <= 0.0031308 {
                x * 12.92
            } else {
                x.powf(1. / 2.4) * (1. + 0.055) - 0.055
            };
            (x * 255.).round().max(0.).min(255.) as u8
        }
        let p = if self[3] > 0.0001 {
            Rgba([self[0] / self[3], self[1] / self[3], self[2] / self[3], self[3]])
        } else {
            Rgba([0., 0., 0., 0.])
        };
        Rgba([enc(p[0]), enc(p[1]), enc(p[2]), enc(p[3])])
    }
}
fn encode_srgb(img: &FloatImage) -> RgbaImage {
    let (w, h) = img.dimensions();
    ImageBuffer::from_fn(w, h, |x, y| img[(x, y)].encode())
}
fn resize(img: &FloatImage, width: u32, height: u32) -> FloatImage {
    let (w, h) = img.dimensions();
    assert!(width.cmp(&w) == height.cmp(&h));
    if width < w {
        let (rw, rh) = (w as f32 / (width as f32), h as f32 / (height as f32));
        ImageBuffer::from_fn(width, height, |x, y| {
            let (x1, x2) = ((x as f32 * rw) as u32, ((x + 1) as f32 * rw) as u32);
            let (y1, y2) = ((y as f32 * rh) as u32, ((y + 1) as f32 * rh) as u32);
            let (mut r, mut g, mut b, mut a) = (0., 0., 0., 0.);
            for xx in range(x1, x2) {
                for yy in range(y1, y2) {
                    let p = img[(xx, yy)];
                    r += p[0];
                    g += p[1];
                    b += p[2];
                    a += p[3];
                }
            }
            let m = 1. / (((x2 - x1) * (y2 - y1)) as f32);
            Rgba([r * m, g * m, b * m, a * m])
        })
    } else if width == w {
        img.clone()
    } else {
        let (rw, rh) = (w as f32 / (width as f32), h as f32 / (height as f32));
        ImageBuffer::from_fn(width, height, |x, y| {
            let xx = (x as f32 * rw) as u32;
            let yy = (y as f32 * rh) as u32;
            img[(xx, yy)]
        })
    }
}

pub fn check_lang_dups(lang: &HashMap<String, String>) {
    let mut stuff = HashMap::new();
    for (key, val) in lang.iter() {
        if key.as_slice().contains(".tooltip") { continue }
        if key.as_slice().contains("fluid.") { continue }
        if key.as_slice().contains("DESCRIPTION") { continue }
        match stuff.get(val) {
            Some(other) => {
                println!("Collision for {}", val);
                println!("{} && {}", key, other);
            },
            None => (),
        }
        stuff.insert(val.clone(), key);
    }
}
pub fn check_navbox() {
    let reg = regex!(r"(\d+) (\d+) (.+?)\r?\n");
    let path = Path::new(r"work\navbox.txt");
    let mut file = File::open(&path).unwrap();
    let navbox = file.read_to_string().unwrap();
    let navbox = navbox.as_slice();
    let path = Path::new(r"work\tilesheets\Tilesheet GT.txt");
    let mut file = File::open(&path).unwrap();
    let data = file.read_to_string().unwrap();
    for cap in reg.captures_iter(data.as_slice()) {
        let name = format!("mod=GT|{}", cap.at(3));
        let name = name.as_slice();
        if !navbox.contains(name) && !name.contains("(Fluid)") {
            println!("{}", cap.at(3));
        }
    }
}
pub fn import_old_tilesheet(name: &str) {
    let path = Path::new(r"work/tilesheets/import.txt");
    if !path.is_file() { return }
    println!("Importing old tilesheet");
    let mut file = File::open(&path).unwrap();
    let data = file.read_to_string().unwrap();
    let name = format!("work/tilesheets/Tilesheet {}.txt", name);
    let path = Path::new(name[]);
    let mut out = File::create(&path).unwrap();
    let reg = regex!(r"Edit\s+[0-9]+\s+(.+?)\s+[A-Z0-9]+\s+([0-9]+)\s+([0-9]+)\s+16px, 32px\r?\n");
    for cap in reg.captures_iter(data.as_slice()) {
        let name = cap.at(1);
        let x = cap.at(2);
        let y = cap.at(3);
        (writeln!(&mut out, "{} {} {}", x, y, name)).unwrap();
    }
}
pub fn fix_lang() {
    let path = Path::new(r"work/GregTech.lang");
    let mut file = File::open(&path).unwrap();
    let data = file.read_to_string().unwrap();
    let data = regex!("\r").replace_all(data[], "");
    let data = regex!("(blockores\\.[0-9]{1,3}\\.name=.*)").replace_all(data[], "$1 (Stone)");
    let data = regex!("(blockores\\.1[0-9]{3}\\.name=.*)").replace_all(data[], "$1 (Netherrack)");
    let data = regex!("(blockores\\.2[0-9]{3}\\.name=.*)").replace_all(data[], "$1 (Endstone)");
    let data = regex!("(blockores\\.3[0-9]{3}\\.name=.*)").replace_all(data[], "$1 (Black Granite)");
    let data = regex!("(blockores\\.4[0-9]{3}\\.name=.*)").replace_all(data[], "$1 (Red Granite)");
    let data = regex!("(blockores\\.16[0-9]{3}\\.name=.*)").replace_all(data[], "$1 (Stone)");
    let data = regex!("(blockores\\.17[0-9]{3}\\.name=.*)").replace_all(data[], "$1 (Netherrack)");
    let data = regex!("(blockores\\.18[0-9]{3}\\.name=.*)").replace_all(data[], "$1 (Endstone)");
    let data = regex!("(blockores\\.19[0-9]{3}\\.name=.*)").replace_all(data[], "$1 (Black Granite)");
    let data = regex!("(blockores\\.20[0-9]{3}\\.name=.*)").replace_all(data[], "$1 (Red Granite)");
    let path = Path::new(r"work/modified.lang");
    let mut file = File::create(&path).unwrap();
    file.write_str(data[]).unwrap();
}

fn main() {
    let mut cin = stdin();
    print!("Mod name: ");
    flush();
    let blah = cin.read_line().unwrap();
    let blah = blah[].trim();
    // import_old_tilesheet(blah);
    tilesheets::update_tilesheet(blah, &[16, 32]);
    // api::api_things();
    // greg_scan_foods();
    // fix_lang();
    // let lang = read_gt_lang();
    // import_special_metaitems(&lang);
    // import_fluids(&lang);
    // check_lang_dups(&lang);
    // check_navbox();
}
<commit_msg>Clear some old code and make it take command line args<commit_after>// Copyright © 2014, Peter Atashian

#![feature(phase, associated_types, slicing_syntax)]

extern crate cookie;
extern crate hyper;
extern crate image;
#[phase(plugin)]
extern crate regex_macros;
extern crate regex;
extern crate "rustc-serialize" as serialize;
extern crate url;

use image::{GenericImage, ImageBuffer, Pixel, Rgba, RgbaImage};
use image::ColorType::RGBA;
use std::borrow::ToOwned;
use std::collections::HashMap;
use std::io::File;
use std::io::fs::PathExtensions;
use std::num::{Float, FloatMath};

pub mod tilesheets;

type FloatImage = ImageBuffer<Vec<f32>, f32, Rgba<f32>>;
pub fn save(img: &RgbaImage, path: &Path) {
    image::save_buffer(path, img.as_slice(), img.width(), img.height(), RGBA(8)).unwrap();
}

pub fn read_gt_lang() -> HashMap<String, String> {
    let path = Path::new(r"work/GregTech.lang");
    let mut file = File::open(&path).unwrap();
    let data = file.read_to_string().unwrap();
    let reg = regex!(r"S:([\w\.]+?)=(.+?)\r?\n");
    reg.captures_iter(data.as_slice()).map(|cap|
        (cap.at(1).unwrap().to_owned(), cap.at(2).unwrap().to_owned())
    ).collect()
}
trait Srgb {
    type Linear;
    fn decode(&self) -> <Self as Srgb>::Linear;
}
impl Srgb for Rgba<u8> {
    type Linear = Rgba<f32>;
    fn decode(&self) -> Rgba<f32> {
        fn dec(x: u8) -> f32 {
            let x = x as f32 * (1. / 255.);
            if x <= 0.04045 {
                x / 12.92
            } else {
                ((x + 0.055) / (1. + 0.055)).powf(2.4)
            }
        }
        let p = Rgba([dec(self[0]), dec(self[1]), dec(self[2]), dec(self[3])]);
        Rgba([p[0] * p[3], p[1] * p[3], p[2] * p[3], p[3]])
    }
}
fn decode_srgb(img: &RgbaImage) -> FloatImage {
    let (w, h) = img.dimensions();
    ImageBuffer::from_fn(w, h, |x, y| img[(x, y)].decode())
}
trait Linear {
    type Srgb;
    fn encode(&self) -> <Self as Linear>::Srgb;
}
impl Linear for Rgba<f32> {
    type Srgb = Rgba<u8>;
    fn encode(&self) -> Rgba<u8> {
        fn enc(x: f32) -> u8 {
            let x = if x <= 0.0031308 {
                x * 12.92
            } else {
                x.powf(1. / 2.4) * (1. + 0.055) - 0.055
            };
            (x * 255.).round().max(0.).min(255.) as u8
        }
        let p = if self[3] > 0.0001 {
            Rgba([self[0] / self[3], self[1] / self[3], self[2] / self[3], self[3]])
        } else {
            Rgba([0., 0., 0., 0.])
        };
        Rgba([enc(p[0]), enc(p[1]), enc(p[2]), enc(p[3])])
    }
}
fn encode_srgb(img: &FloatImage) -> RgbaImage {
    let (w, h) = img.dimensions();
    ImageBuffer::from_fn(w, h, |x, y| img[(x, y)].encode())
}
fn resize(img: &FloatImage, width: u32, height: u32) -> FloatImage {
    let (w, h) = img.dimensions();
    assert!(width.cmp(&w) == height.cmp(&h));
    if width < w {
        let (rw, rh) = (w as f32 / (width as f32), h as f32 / (height as f32));
        ImageBuffer::from_fn(width, height, |x, y| {
            let (x1, x2) = ((x as f32 * rw) as u32, ((x + 1) as f32 * rw) as u32);
            let (y1, y2) = ((y as f32 * rh) as u32, ((y + 1) as f32 * rh) as u32);
            let (mut r, mut g, mut b, mut a) = (0., 0., 0., 0.);
            for xx in range(x1, x2) {
                for yy in range(y1, y2) {
                    let p = img[(xx, yy)];
                    r += p[0];
                    g += p[1];
                    b += p[2];
                    a += p[3];
                }
            }
            let m = 1. / (((x2 - x1) * (y2 - y1)) as f32);
            Rgba([r * m, g * m, b * m, a * m])
        })
    } else if width == w {
        img.clone()
    } else {
        let (rw, rh) = (w as f32 / (width as f32), h as f32 / (height as f32));
        ImageBuffer::from_fn(width, height, |x, y| {
            let xx = (x as f32 * rw) as u32;
            let yy = (y as f32 * rh) as u32;
            img[(xx, yy)]
        })
    }
}

pub fn check_lang_dups(lang: &HashMap<String, String>) {
    let mut stuff = HashMap::new();
    for (key, val) in lang.iter() {
        if key.as_slice().contains(".tooltip") { continue }
        if key.as_slice().contains("fluid.") { continue }
        if key.as_slice().contains("DESCRIPTION") { continue }
        match stuff.get(val) {
            Some(other) => {
                println!("Collision for {}", val);
                println!("{} && {}", key, other);
            },
            None => (),
        }
        stuff.insert(val.clone(), key);
    }
}
pub fn check_navbox() {
    let reg = regex!(r"(\d+) (\d+) (.+?)\r?\n");
    let path = Path::new(r"work\navbox.txt");
    let mut file = File::open(&path).unwrap();
    let navbox = file.read_to_string().unwrap();
    let navbox = navbox.as_slice();
    let path = Path::new(r"work\tilesheets\Tilesheet GT.txt");
    let mut file = File::open(&path).unwrap();
    let data = file.read_to_string().unwrap();
    for cap in reg.captures_iter(data.as_slice()) {
        let name = format!("mod=GT|{}", cap.at(3));
        let name = name.as_slice();
        if !navbox.contains(name) && !name.contains("(Fluid)") {
            println!("{}", cap.at(3));
        }
    }
}
pub fn import_old_tilesheet(name: &str) {
    let path = Path::new(r"work/tilesheets/import.txt");
    if !path.is_file() { return }
    println!("Importing old tilesheet");
    let mut file = File::open(&path).unwrap();
    let data = file.read_to_string().unwrap();
    let name = format!("work/tilesheets/Tilesheet {}.txt", name);
    let path = Path::new(name[]);
    let mut out = File::create(&path).unwrap();
    let reg = regex!(r"Edit\s+[0-9]+\s+(.+?)\s+[A-Z0-9]+\s+([0-9]+)\s+([0-9]+)\s+16px, 32px\r?\n");
    for cap in reg.captures_iter(data.as_slice()) {
        let name = cap.at(1);
        let x = cap.at(2);
        let y = cap.at(3);
        (writeln!(&mut out, "{} {} {}", x, y, name)).unwrap();
    }
}
pub fn fix_lang() {
    let path = Path::new(r"work/GregTech.lang");
    let mut file = File::open(&path).unwrap();
    let data = file.read_to_string().unwrap();
    let data = regex!("\r").replace_all(data[], "");
    let data = regex!("(blockores\\.[0-9]{1,3}\\.name=.*)").replace_all(data[], "$1 (Stone)");
    let data = regex!("(blockores\\.1[0-9]{3}\\.name=.*)").replace_all(data[], "$1 (Netherrack)");
    let data = regex!("(blockores\\.2[0-9]{3}\\.name=.*)").replace_all(data[], "$1 (Endstone)");
    let data = regex!("(blockores\\.3[0-9]{3}\\.name=.*)").replace_all(data[], "$1 (Black Granite)");
    let data = regex!("(blockores\\.4[0-9]{3}\\.name=.*)").replace_all(data[], "$1 (Red Granite)");
    let data = regex!("(blockores\\.16[0-9]{3}\\.name=.*)").replace_all(data[], "$1 (Stone)");
    let data = regex!("(blockores\\.17[0-9]{3}\\.name=.*)").replace_all(data[], "$1 (Netherrack)");
    let data = regex!("(blockores\\.18[0-9]{3}\\.name=.*)").replace_all(data[], "$1 (Endstone)");
    let data = regex!("(blockores\\.19[0-9]{3}\\.name=.*)").replace_all(data[], "$1 (Black Granite)");
    let data = regex!("(blockores\\.20[0-9]{3}\\.name=.*)").replace_all(data[], "$1 (Red Granite)");
    let path = Path::new(r"work/modified.lang");
    let mut file = File::create(&path).unwrap();
    file.write_str(data[]).unwrap();
}

fn main() {
    let args = std::os::args();
    let args = args.iter().map(|x| x[]).collect::<Vec<_>>();
    match args[] {
        [_, "update", name] => tilesheets::update_tilesheet(name[], &[16, 32]),
        _ => println!("Invalid arguments"),
    }
}
<|endoftext|>