<commit_before>/// An example of a client/server agnostic WebSocket that takes input from stdin and sends that
/// input to all other peers.
///
/// For example, to create a network like this:
///
/// 3013 ---- 3012 ---- 3014
///   \        |
///    \       |
///     \      |
///      \     |
///       \    |
///        \   |
///         \  |
///          3015
///
/// Run these commands in separate processes
/// ./peer2peer
/// ./peer2peer --server localhost:3013 ws://localhost:3012
/// ./peer2peer --server localhost:3014 ws://localhost:3012
/// ./peer2peer --server localhost:3015 ws://localhost:3012 ws://localhost:3013
///
/// Stdin on 3012 will be sent to all other peers
/// Stdin on 3013 will be sent to 3012 and 3015
/// Stdin on 3014 will be sent to 3012 only
/// Stdin on 3015 will be sent to 3012 and 2013

extern crate ws;
extern crate url;
extern crate clap;
extern crate env_logger;
extern crate rustc_serialize;
extern crate bincode;
#[macro_use]
extern crate log;

pub mod handler;
pub mod message;

use message::PeerMessage;
use handler::MessageFactory;

use std::collections::hash_map::HashMap;
use std::clone::Clone;
use std::io;
use std::io::prelude::*;
use std::thread;
use std::sync::{Arc, Mutex};

use bincode::rustc_serialize::encode;

use clap::{App, Arg};

fn main() {
    // Setup logging
    env_logger::init().unwrap();

    // Parse command line arguments
    let matches = App::new("Simple Peer 2 Peer")
                      .version("1.0")
                      .author("Jonathan Almeida <hello@jonalmeida.com>")
                      .about("Connect to other peers and listen for incoming connections.")
                      .arg(Arg::with_name("server")
                               .short("s")
                               .long("server")
                               .value_name("SERVER")
                               .help("Set the address to listen for new connections. (default: \
                                      localhost:3012"))
                      .arg(Arg::with_name("PEER")
                               .help("A WebSocket URL to attempt to connect to at start.")
                               .multiple(true))
                      .arg(Arg::with_name("demo")
                               .short("d")
                               .long("demo")
                               .value_name("DEMO_SERVER")
                               .help("Sleeps for 4 seconds before receiving messages from this \
                                      peer."))
                      .get_matches();

    // Get address of this peer
    let my_addr = String::from(matches.value_of("server").unwrap_or("localhost:3012"));
    let demo_addr = matches.value_of("demo");
    let my_addr_clone = my_addr.clone();

    let mut init_clock = HashMap::new();
    init_clock.insert(my_addr.clone(), 0u32);
    let clock = Arc::new(Mutex::new(init_clock));
    let connecting_clocks = clock.clone();
    let mut factory = MessageFactory::build(connecting_clocks.clone()).me(my_addr.clone().as_str());

    if let Some(demo) = demo_addr {
        factory.demo(demo);
    }

    // Create simple websocket that just prints out messages
    let mut me = ws::WebSocket::new(factory).unwrap();

    // Get a sender for ALL connections to the websocket
    let broacaster = me.broadcaster();

    // Setup thread for listening to stdin and sending messages to connections
    let input = thread::spawn(move || {
        let stdin = io::stdin();
        for line in stdin.lock().lines() {

            // Incrementing clock before sending
            let mut clock = clock.lock().unwrap();
            if let Some(clock) = clock.get_mut(&my_addr_clone) {
                *clock += 1;
            }

            // Constructing new message
            let message = PeerMessage {
                sender: my_addr_clone.clone(),
                clocks: clock.clone(),
                message: line.unwrap_or(String::from("n/a")),
            };

            // Encoding into bytes
            if let Ok(encoded_msg) = encode(&message, bincode::SizeLimit::Infinite) {
                // Sending bytes to all connected clients
                broacaster.send(&*encoded_msg.into_boxed_slice()).unwrap();
            }
        }
    });

    // Connect to any existing peers specified on the cli
    if let Some(peers) = matches.values_of("PEER") {
        for peer in peers {
            if let Ok(peer) = url::Url::parse(peer) {
                me.connect(peer).unwrap();
            }
        }
    }

    // Run the websocket
    me.listen(my_addr.clone().as_str()).unwrap();
    input.join().unwrap();

}
<commit_msg>Fewer named bindings<commit_after>/// An example of a client/server agnostic WebSocket that takes input from stdin and sends that
/// input to all other peers.
///
/// For example, to create a network like this:
///
/// 3013 ---- 3012 ---- 3014
///   \        |
///    \       |
///     \      |
///      \     |
///       \    |
///        \   |
///         \  |
///          3015
///
/// Run these commands in separate processes
/// ./peer2peer
/// ./peer2peer --server localhost:3013 ws://localhost:3012
/// ./peer2peer --server localhost:3014 ws://localhost:3012
/// ./peer2peer --server localhost:3015 ws://localhost:3012 ws://localhost:3013
///
/// Stdin on 3012 will be sent to all other peers
/// Stdin on 3013 will be sent to 3012 and 3015
/// Stdin on 3014 will be sent to 3012 only
/// Stdin on 3015 will be sent to 3012 and 2013

extern crate ws;
extern crate url;
extern crate clap;
extern crate env_logger;
extern crate rustc_serialize;
extern crate bincode;
#[macro_use]
extern crate log;

pub mod handler;
pub mod message;

use message::PeerMessage;
use handler::MessageFactory;

use std::collections::hash_map::HashMap;
use std::clone::Clone;
use std::io;
use std::io::prelude::*;
use std::thread;
use std::sync::{Arc, Mutex};

use bincode::rustc_serialize::encode;

use clap::{App, Arg};

fn main() {
    // Setup logging
    env_logger::init().unwrap();

    // Parse command line arguments
    let matches = App::new("Simple Peer 2 Peer")
                      .version("1.0")
                      .author("Jonathan Almeida <hello@jonalmeida.com>")
                      .about("Connect to other peers and listen for incoming connections.")
                      .arg(Arg::with_name("server")
                               .short("s")
                               .long("server")
                               .value_name("SERVER")
                               .help("Set the address to listen for new connections. (default: \
                                      localhost:3012"))
                      .arg(Arg::with_name("PEER")
                               .help("A WebSocket URL to attempt to connect to at start.")
                               .multiple(true))
                      .arg(Arg::with_name("demo")
                               .short("d")
                               .long("demo")
                               .value_name("DEMO_SERVER")
                               .help("Sleeps for 4 seconds before receiving messages from this \
                                      peer."))
                      .get_matches();

    // Get address of this peer
    let my_addr = String::from(matches.value_of("server").unwrap_or("localhost:3012"));
    let demo_addr = matches.value_of("demo");
    let my_addr_clone = my_addr.clone();

    let mut clock = HashMap::new();
    clock.insert(my_addr.clone(), 0u32);
    let clock = Arc::new(Mutex::new(clock));

    // Creating a Factory for the WebSocket
    let mut factory = MessageFactory::build(clock.clone()).me(my_addr.clone().as_str());
    if let Some(demo) = demo_addr {
        factory.demo(demo);
    }

    // Create simple websocket that just prints out messages
    let mut me = ws::WebSocket::new(factory).unwrap();

    // Get a sender for ALL connections to the websocket
    let broacaster = me.broadcaster();

    // Setup thread for listening to stdin and sending messages to connections
    let input = thread::spawn(move || {
        let stdin = io::stdin();
        for line in stdin.lock().lines() {

            // Incrementing clock before sending
            let mut clock = clock.lock().unwrap();
            if let Some(clock) = clock.get_mut(&my_addr_clone) {
                *clock += 1;
            }

            // Constructing new message
            let message = PeerMessage {
                sender: my_addr_clone.clone(),
                clocks: clock.clone(),
                message: line.unwrap_or(String::from("n/a")),
            };

            // Encoding into bytes
            if let Ok(encoded_msg) = encode(&message, bincode::SizeLimit::Infinite) {
                // Sending bytes to all connected clients
                broacaster.send(&*encoded_msg.into_boxed_slice()).unwrap();
            }
        }
    });

    // Connect to any existing peers specified on the cli
    if let Some(peers) = matches.values_of("PEER") {
        for peer in peers {
            if let Ok(peer) = url::Url::parse(peer) {
                me.connect(peer).unwrap();
            }
        }
    }

    // Run the websocket
    me.listen(my_addr.clone().as_str()).unwrap();
    input.join().unwrap();

}
<|endoftext|>


<commit_before>#[macro_use]
extern crate conrod;
extern crate find_folder;
extern crate piston_window;
extern crate websocket;

use std::borrow::Cow;
use std::str::from_utf8;
use std::thread;
use std::io::stdin;
use std::sync::mpsc::channel;
use websocket::{Message, Sender, Receiver};
use websocket::message::Type;
use websocket::client::request::Url;
use websocket::Client;
use websocket::stream::WebSocketStream;
use std::sync::mpsc::{Sender as TrueSender, Receiver as TrueReceiver, RecvError as TrueRecvError,
                      TryRecvError};

use conrod::{color, Scalar, Button, Canvas, Circle, Color, Colorable, DropDownList,
             EnvelopeEditor, Frameable, Labelable, NumberDialer, Point, Positionable, Slider,
             Sizeable, Text, TextBox, Theme, Toggle, Widget, WidgetMatrix, XYPad};

use piston_window::{EventLoop, Glyphs, PistonWindow, UpdateEvent, WindowSettings};

// Use `piston_window` for UI backend.
type Backend = (<piston_window::G2d<'static> as conrod::Graphics>::Texture, Glyphs);
type Ui = conrod::Ui<Backend>;
type UiCell<'a> = conrod::UiCell<'a, Backend>;

fn main() {
    // Reply from Odin.
    let (reply_tx, reply_rx): (TrueSender<String>, TrueReceiver<String>) = channel();

    let url = Url::parse("ws://127.0.0.1:2794").unwrap();

    println!("Connecting to {}", url);

    let request = Client::connect(url).unwrap();

    let response = request.send().unwrap(); // Send the request and retrieve a response

    println!("Validating response...");

    response.validate().unwrap(); // Validate the response

    println!("Successfully connected");

    let (mut sender, mut receiver) = response.begin().split();

    let (tx, rx) = channel();

    let tx_1 = tx.clone();

    let send_loop = thread::spawn(move || {
        loop {
            // Send loop
            let message: Message = match rx.recv() {
                Ok(m) => m,
                Err(e) => {
                    println!("Send Loop: {:?}", e);
                    return;
                }
            };
            match message.opcode {
                Type::Close => {
                    let _ = sender.send_message(&message);
                    // If it's a close message, just send it and then return.
                    return;
                }
                _ => (),
            }
            // Send the message
            match sender.send_message(&message) {
                Ok(()) => (),
                Err(e) => {
                    println!("Send Loop: {:?}", e);
                    let _ = sender.send_message(&Message::close());
                    return;
                }
            }
        }
    });

    let receive_loop = thread::spawn(move || {
        // Receive loop
        for message in receiver.incoming_messages() {
            let message: Message = match message {
                Ok(m) => m,
                Err(e) => {
                    println!("Receive Loop: {:?}", e);
                    let _ = tx_1.send(Message::close());
                    return;
                }
            };
            match message.opcode {
                Type::Close => {
                    // Got a close message, so send a close message and return
                    let _ = tx_1.send(Message::close());
                    return;
                }
                Type::Ping => {
                    match tx_1.send(Message::pong(message.payload)) {
                        // Send a pong in response
                        Ok(()) => (),
                        Err(e) => {
                            println!("Receive Loop: {:?}", e);
                            return;
                        }
                    }
                }
                // Parse message from Odin.
                _ => {
                    reply_tx.send(from_utf8(&*message.payload).unwrap().to_string());
                }
            }
        }
    });

    // Construct the window.
    let window: PistonWindow = WindowSettings::new("Thor", [1080, 720])
                                   .exit_on_esc(true)
                                   .fullscreen(true)
                                   .build()
                                   .unwrap();

    // Construct the UI.
    let mut ui = {
        // Get path for "assets".
        let assets = find_folder::Search::KidsThenParents(3, 5)
                         .for_folder("assets")
                         .unwrap();

        // Get path for the font.
        let font_path = assets.join("fonts/NotoSans/NotoSans-Regular.ttf");

        // Use the "default" theme.
        let theme = Theme::default();

        // Glyph cache.
        let glyph_cache = Glyphs::new(&font_path, window.factory.borrow().clone());

        // Finally, create the UI.
        Ui::new(glyph_cache.unwrap(), theme)
    };

    // Did the user click on the button?
    let mut clicked = false;
    // Did we press Enter in the textbox?
    let mut submitted = false;
    // Textbox input.
    let mut input: String = "".to_string();
    // Reply from Odin.
    let mut reply = String::new();

    // Poll events from the window.
    for event in window.ups(60) {

        // Listen to sockets without blocking.
        let res = reply_rx.try_recv();
        match res {
            Ok(val) => reply = val,
            Err(err) => {
                match err {
                    TryRecvError::Empty => {
                        // Channel is empty. This event fires frequently.
                    }
                    TryRecvError::Disconnected => {
                        // Channel is disconnected.
                    }
                }
            }
        }
        ui.handle_event(&event);
        event.update(|_| {
            ui.set_widgets(|mut ui| {
                set_widgets(&mut ui,
                            &mut reply,
                            &mut clicked,
                            &mut submitted,
                            &mut input)
            })
        });
        event.draw_2d(|c, g| ui.draw(c, g));
        if clicked == true {
            let message = Message::text("This drink... I like it! ANOTHER!");
            tx.send(message);
            clicked = false;
        }
        if submitted == true {
            let message = Message::text(input);
            tx.send(message);
            // Clear input.
            input = "".to_string();
            // Reset submitted state.
            submitted = false;
        }
    }
}

fn set_widgets(ui: &mut UiCell,
               text: &mut String,
               clicked: &mut bool,
               submitted: &mut bool,
               input: &mut String) {

    // Unique ID's for each widget.
    widget_ids!{
        MASTER,
        COL,
        LABEL,
        BUTTON,
        TEXTBOX,
        INSTRUCTIONS_LABEL,
    }

    // Create the canvas.
    Canvas::new()
        .flow_right(&[(COL, Canvas::new().color(color::WHITE))])
        .set(MASTER, ui);

    const PAD: Scalar = 20.0;

    Text::new(text)
        .color(color::BLUE)
        .padded_w_of(COL, PAD)
        .middle_of(COL)
        .align_text_middle()
        .line_spacing(2.5)
        .set(LABEL, ui);

    Text::new("Enter your message in the green field and press Enter to send to \
                            everyone.")
        .color(color::BLUE)
        .padded_w_of(COL, PAD)
        .mid_top_of(COL)
        .align_text_middle()
        .line_spacing(2.5)
        .set(INSTRUCTIONS_LABEL, ui);

    Button::new()
        .w_h(300.0, 50.0)
        .mid_left_of(MASTER)
        .rgb(0.4, 0.75, 0.6)
        .label("Send a message to Odin")
        .react(|| {
            *clicked = true;
        });

    TextBox::new(input)
        .w_h(300.0, 50.0)
        .font_size(20)
        .mid_bottom_of(COL)
        .rgb(0.4, 0.75, 0.6)
        .react(|_string: &mut String| {
            *submitted = true;
        })
        .set(TEXTBOX, ui);
}
<commit_msg>Fix Glutin crash when fullscreen.<commit_after>#[macro_use]
extern crate conrod;
extern crate find_folder;
extern crate piston_window;
extern crate websocket;

use std::borrow::Cow;
use std::str::from_utf8;
use std::thread;
use std::io::stdin;
use std::sync::mpsc::channel;
use websocket::{Message, Sender, Receiver};
use websocket::message::Type;
use websocket::client::request::Url;
use websocket::Client;
use websocket::stream::WebSocketStream;
use std::sync::mpsc::{Sender as TrueSender, Receiver as TrueReceiver, RecvError as TrueRecvError,
                      TryRecvError};

use conrod::{color, Scalar, Button, Canvas, Circle, Color, Colorable, DropDownList,
             EnvelopeEditor, Frameable, Labelable, NumberDialer, Point, Positionable, Slider,
             Sizeable, Text, TextBox, Theme, Toggle, Widget, WidgetMatrix, XYPad};

use piston_window::{EventLoop, Glyphs, PistonWindow, UpdateEvent, WindowSettings};

// Use `piston_window` for UI backend.
type Backend = (<piston_window::G2d<'static> as conrod::Graphics>::Texture, Glyphs);
type Ui = conrod::Ui<Backend>;
type UiCell<'a> = conrod::UiCell<'a, Backend>;

fn main() {
    // Reply from Odin.
    let (reply_tx, reply_rx): (TrueSender<String>, TrueReceiver<String>) = channel();

    let url = Url::parse("ws://127.0.0.1:2794").unwrap();

    println!("Connecting to {}", url);

    let request = Client::connect(url).unwrap();

    let response = request.send().unwrap(); // Send the request and retrieve a response

    println!("Validating response...");

    response.validate().unwrap(); // Validate the response

    println!("Successfully connected");

    let (mut sender, mut receiver) = response.begin().split();

    let (tx, rx) = channel();

    let tx_1 = tx.clone();

    let send_loop = thread::spawn(move || {
        loop {
            // Send loop
            let message: Message = match rx.recv() {
                Ok(m) => m,
                Err(e) => {
                    println!("Send Loop: {:?}", e);
                    return;
                }
            };
            match message.opcode {
                Type::Close => {
                    let _ = sender.send_message(&message);
                    // If it's a close message, just send it and then return.
                    return;
                }
                _ => (),
            }
            // Send the message
            match sender.send_message(&message) {
                Ok(()) => (),
                Err(e) => {
                    println!("Send Loop: {:?}", e);
                    let _ = sender.send_message(&Message::close());
                    return;
                }
            }
        }
    });

    let receive_loop = thread::spawn(move || {
        // Receive loop
        for message in receiver.incoming_messages() {
            let message: Message = match message {
                Ok(m) => m,
                Err(e) => {
                    println!("Receive Loop: {:?}", e);
                    let _ = tx_1.send(Message::close());
                    return;
                }
            };
            match message.opcode {
                Type::Close => {
                    // Got a close message, so send a close message and return
                    let _ = tx_1.send(Message::close());
                    return;
                }
                Type::Ping => {
                    match tx_1.send(Message::pong(message.payload)) {
                        // Send a pong in response
                        Ok(()) => (),
                        Err(e) => {
                            println!("Receive Loop: {:?}", e);
                            return;
                        }
                    }
                }
                // Parse message from Odin.
                _ => {
                    reply_tx.send(from_utf8(&*message.payload).unwrap().to_string());
                }
            }
        }
    });

    // Construct the window.
    let window: PistonWindow = WindowSettings::new("Thor", [1024, 768])
                                   .exit_on_esc(true)
                                   .fullscreen(true)
                                   .build()
                                   .unwrap();

    // Construct the UI.
    let mut ui = {
        // Get path for "assets".
        let assets = find_folder::Search::KidsThenParents(3, 5)
                         .for_folder("assets")
                         .unwrap();

        // Get path for the font.
        let font_path = assets.join("fonts/NotoSans/NotoSans-Regular.ttf");

        // Use the "default" theme.
        let theme = Theme::default();

        // Glyph cache.
        let glyph_cache = Glyphs::new(&font_path, window.factory.borrow().clone());

        // Finally, create the UI.
        Ui::new(glyph_cache.unwrap(), theme)
    };

    // Did the user click on the button?
    let mut clicked = false;
    // Did we press Enter in the textbox?
    let mut submitted = false;
    // Textbox input.
    let mut input: String = "".to_string();
    // Reply from Odin.
    let mut reply = String::new();

    // Poll events from the window.
    for event in window.ups(60) {

        // Listen to sockets without blocking.
        let res = reply_rx.try_recv();
        match res {
            Ok(val) => reply = val,
            Err(err) => {
                match err {
                    TryRecvError::Empty => {
                        // Channel is empty. This event fires frequently.
                    }
                    TryRecvError::Disconnected => {
                        // Channel is disconnected.
                    }
                }
            }
        }
        ui.handle_event(&event);
        event.update(|_| {
            ui.set_widgets(|mut ui| {
                set_widgets(&mut ui,
                            &mut reply,
                            &mut clicked,
                            &mut submitted,
                            &mut input)
            })
        });
        event.draw_2d(|c, g| ui.draw(c, g));
        if clicked == true {
            let message = Message::text("This drink... I like it! ANOTHER!");
            tx.send(message);
            clicked = false;
        }
        if submitted == true {
            let message = Message::text(input);
            tx.send(message);
            // Clear input.
            input = "".to_string();
            // Reset submitted state.
            submitted = false;
        }
    }
}

fn set_widgets(ui: &mut UiCell,
               text: &mut String,
               clicked: &mut bool,
               submitted: &mut bool,
               input: &mut String) {

    // Unique ID's for each widget.
    widget_ids!{
        MASTER,
        COL,
        LABEL,
        BUTTON,
        TEXTBOX,
        INSTRUCTIONS_LABEL,
    }

    // Create the canvas.
    Canvas::new()
        .flow_right(&[(COL, Canvas::new().color(color::WHITE))])
        .set(MASTER, ui);

    const PAD: Scalar = 20.0;

    Text::new(text)
        .color(color::BLUE)
        .padded_w_of(COL, PAD)
        .middle_of(COL)
        .align_text_middle()
        .line_spacing(2.5)
        .set(LABEL, ui);

    Text::new("Enter your message in the green field and press Enter to send to \
                            everyone.")
        .color(color::BLUE)
        .padded_w_of(COL, PAD)
        .mid_top_of(COL)
        .align_text_middle()
        .line_spacing(2.5)
        .set(INSTRUCTIONS_LABEL, ui);

    Button::new()
        .w_h(300.0, 50.0)
        .mid_left_of(MASTER)
        .rgb(0.4, 0.75, 0.6)
        .label("Send a message to Odin")
        .react(|| {
            *clicked = true;
        });

    TextBox::new(input)
        .w_h(300.0, 50.0)
        .font_size(20)
        .mid_bottom_of(COL)
        .rgb(0.4, 0.75, 0.6)
        .react(|_string: &mut String| {
            *submitted = true;
        })
        .set(TEXTBOX, ui);
}
<|endoftext|>


<commit_before>extern crate ppbert;
#[macro_use] extern crate clap;

use std::io::{self, Read, Write};
use std::fs;
use std::process::exit;
use std::time::{Duration, Instant};

use clap::{Arg, App};

use ppbert::bertterm::BertTerm;
use ppbert::error::Result;
use ppbert::parser;

const DEFAULT_INDENT_WIDTH: &str = "2";
const DEFAULT_MAX_TERMS_PER_LINE: &str = "5";
const PROG_NAME: &str = "ppbert";

fn main() {
    let matches = App::new(PROG_NAME)
        .version(crate_version!())
        .author("Vincent Foley")
        .about("Pretty print structure encoded in Erlang's External Term Format")
        .arg(Arg::with_name("input_files")
             .value_name("FILES")
             .multiple(true))
        .arg(Arg::with_name("indent_width")
             .help("Indents with <num> spaces")
             .value_name("num")
             .short("i")
             .long("indent-width")
             .default_value(DEFAULT_INDENT_WIDTH)
             .takes_value(true))
        .arg(Arg::with_name("max_per_line")
             .help("Prints at most <num> basic terms per line")
             .value_name("num")
             .short("m")
             .long("max-terms-per-line")
             .default_value(DEFAULT_MAX_TERMS_PER_LINE)
             .takes_value(true))
        .arg(Arg::with_name("verbose")
             .help("Enables verbose mode")
             .short("v")
             .long("verbose"))
        .arg(Arg::with_name("parse")
             .help("Parses the input, doesn't pretty print it")
             .short("p")
             .long("parse"))
        .arg(Arg::with_name("bert2")
             .help("Parses .bert2 files")
             .conflicts_with("disk_log")
             .short("2")
             .long("bert2"))
        .arg(Arg::with_name("disk_log")
             .help("Parses disk_log files")
             .conflicts_with("bert2")
             .short("d")
             .long("disk-log"))
        .arg(Arg::with_name("json")
             .help("Outputs in JSON")
             .short("j")
             .long("json"))
        .arg(Arg::with_name("transform-proplists")
             .help("Transforms proplists into JSON objects (only valid with --json)")
             .short("t")
             .long("transform-proplists"))
        .get_matches();

    let files: Vec<&str> = match matches.values_of("input_files") {
        Some(files) => files.collect(),
        None => vec!["-"]
    };
    let indent_level = value_t!(matches, "indent_width", usize).unwrap();
    let max_per_line = value_t!(matches, "max_per_line", usize).unwrap();
    let verbose = matches.is_present("verbose");
    let parse_only = matches.is_present("parse");
    let json = matches.is_present("json");
    let transform_proplists = matches.is_present("transform-proplists");

    let parse_fn =
        if matches.is_present("bert2") {
            parser::Parser::bert2_next
        } else if matches.is_present("disk_log") {
            parser::Parser::disk_log_next
        } else {
            parser::Parser::bert_next
        };
    let output_fn = match (json, transform_proplists) {
        (true, false)  => pp_json,
        (true, true)   => pp_json_proplist,
        (false, false) => pp_bert,
        (false, true)  => {
            eprintln!("{}: --transform-proplists is only valid with the --json flag", PROG_NAME);
            pp_bert
        }
    };

    let mut return_code = 0;
    for file in files {
        let res = handle_file(file, parse_only, verbose,
                              indent_level, max_per_line,
                              parse_fn, output_fn);
        match res {
            Ok(()) => (),
            Err(e) => {
                return_code = 1;
                eprintln!("{}: {}: {}", PROG_NAME, file, e);
            }
        }
    }
    exit(return_code);
}

fn handle_file(
    file: &str,
    parse_only: bool,
    verbose: bool,
    indent: usize,
    terms_per_line: usize,
    parse_fn: fn(&mut parser::Parser) -> Option<Result<BertTerm>>,
    pp_fn: fn(BertTerm, usize, usize) -> ()
) -> Result<()> {

    // Read file or stdin into buffer
    let now = Instant::now();
    let buf = if file == "-" {
        let stdin = io::stdin();
        let mut stdin = stdin.lock();
        let mut buf: Vec<u8> = Vec::with_capacity(4096);
        stdin.read_to_end(&mut buf)?;
        buf
    } else {
        fs::read(file)?
    };
    let read_dur = now.elapsed();

    let mut parser = parser::Parser::new(buf);
    let mut parse_dur = Duration::new(0, 0);
    let mut pp_dur = Duration::new(0, 0);

    loop {
        let now = Instant::now();
        let next_item = parse_fn(&mut parser);
        parse_dur += now.elapsed();

        match next_item {
            None => { break; }
            Some(Err(e)) => { return Err(e); }
            Some(Ok(t)) => {
                if !parse_only {
                    let now = Instant::now();
                    pp_fn(t, indent, terms_per_line);
                    pp_dur += now.elapsed();
                }
            }
        }
    }

    if verbose {
        eprintln!("{}: {} read time: {}.{:06} seconds", PROG_NAME, file, read_dur.as_secs(), read_dur.subsec_micros());
        eprintln!("{}: {} parse time: {}.{:06} seconds", PROG_NAME, file, parse_dur.as_secs(), parse_dur.subsec_micros());
        if !parse_only {
            eprintln!("{}: {} print time: {}.{:06} seconds", PROG_NAME, file, pp_dur.as_secs(), pp_dur.subsec_micros());
        }
    }

    return Ok(());
}

/// Outputs a BertTerm to stdout.
fn pp_bert(term: BertTerm, indent_width: usize, terms_per_line: usize) {
    let stdout = io::stdout();
    let mut stdout = stdout.lock();
    let _ = term.write_as_erlang(&mut stdout, indent_width, terms_per_line);
    let _ = writeln!(&mut stdout, ""); // newline, ignore SIGPIPE
}

/// Outputs a BertTerm as JSON to stdout.
fn pp_json(term: BertTerm, _: usize, _: usize) {
    let stdout = io::stdout();
    let mut stdout = stdout.lock();
    let _ = term.write_as_json(&mut stdout, false);
    let _ = writeln!(&mut stdout, "");
}

/// Outputs a BertTerm as JSON to stdout;
/// Erlang proplists are converted to JSON objects.
fn pp_json_proplist(term: BertTerm, _: usize, _: usize) {
    let stdout = io::stdout();
    let mut stdout = stdout.lock();
    let _ = term.write_as_json(&mut stdout, true);
    let _ = writeln!(&mut stdout, "");
}
<commit_msg>Remove default constants<commit_after>extern crate ppbert;
#[macro_use] extern crate clap;

use std::io::{self, Read, Write};
use std::fs;
use std::process::exit;
use std::time::{Duration, Instant};

use clap::{Arg, App};

use ppbert::bertterm::BertTerm;
use ppbert::error::Result;
use ppbert::parser;

const PROG_NAME: &str = "ppbert";

fn main() {
    let matches = App::new(PROG_NAME)
        .version(crate_version!())
        .author("Vincent Foley")
        .about("Pretty print structure encoded in Erlang's External Term Format")
        .arg(Arg::with_name("input_files")
             .value_name("FILES")
             .multiple(true))
        .arg(Arg::with_name("indent_width")
             .help("Indents with <num> spaces")
             .value_name("num")
             .short("i")
             .long("indent-width")
             .default_value("2")
             .takes_value(true))
        .arg(Arg::with_name("max_per_line")
             .help("Prints at most <num> basic terms per line")
             .value_name("num")
             .short("m")
             .long("max-terms-per-line")
             .default_value("5")
             .takes_value(true))
        .arg(Arg::with_name("verbose")
             .help("Enables verbose mode")
             .short("v")
             .long("verbose"))
        .arg(Arg::with_name("parse")
             .help("Parses the input, doesn't pretty print it")
             .short("p")
             .long("parse"))
        .arg(Arg::with_name("bert2")
             .help("Parses .bert2 files")
             .conflicts_with("disk_log")
             .short("2")
             .long("bert2"))
        .arg(Arg::with_name("disk_log")
             .help("Parses disk_log files")
             .conflicts_with("bert2")
             .short("d")
             .long("disk-log"))
        .arg(Arg::with_name("json")
             .help("Outputs in JSON")
             .short("j")
             .long("json"))
        .arg(Arg::with_name("transform-proplists")
             .help("Transforms proplists into JSON objects (only valid with --json)")
             .short("t")
             .long("transform-proplists"))
        .get_matches();

    let files: Vec<&str> = match matches.values_of("input_files") {
        Some(files) => files.collect(),
        None => vec!["-"]
    };
    let indent_level = value_t!(matches, "indent_width", usize).unwrap();
    let max_per_line = value_t!(matches, "max_per_line", usize).unwrap();
    let verbose = matches.is_present("verbose");
    let parse_only = matches.is_present("parse");
    let json = matches.is_present("json");
    let transform_proplists = matches.is_present("transform-proplists");

    let parse_fn =
        if matches.is_present("bert2") {
            parser::Parser::bert2_next
        } else if matches.is_present("disk_log") {
            parser::Parser::disk_log_next
        } else {
            parser::Parser::bert_next
        };
    let output_fn = match (json, transform_proplists) {
        (true, false)  => pp_json,
        (true, true)   => pp_json_proplist,
        (false, false) => pp_bert,
        (false, true)  => {
            eprintln!("{}: --transform-proplists is only valid with the --json flag", PROG_NAME);
            pp_bert
        }
    };

    let mut return_code = 0;
    for file in files {
        let res = handle_file(file, parse_only, verbose,
                              indent_level, max_per_line,
                              parse_fn, output_fn);
        match res {
            Ok(()) => (),
            Err(e) => {
                return_code = 1;
                eprintln!("{}: {}: {}", PROG_NAME, file, e);
            }
        }
    }
    exit(return_code);
}

fn handle_file(
    file: &str,
    parse_only: bool,
    verbose: bool,
    indent: usize,
    terms_per_line: usize,
    parse_fn: fn(&mut parser::Parser) -> Option<Result<BertTerm>>,
    pp_fn: fn(BertTerm, usize, usize) -> ()
) -> Result<()> {

    // Read file or stdin into buffer
    let now = Instant::now();
    let buf = if file == "-" {
        let stdin = io::stdin();
        let mut stdin = stdin.lock();
        let mut buf: Vec<u8> = Vec::with_capacity(4096);
        stdin.read_to_end(&mut buf)?;
        buf
    } else {
        fs::read(file)?
    };
    let read_dur = now.elapsed();

    let mut parser = parser::Parser::new(buf);
    let mut parse_dur = Duration::new(0, 0);
    let mut pp_dur = Duration::new(0, 0);

    loop {
        let now = Instant::now();
        let next_item = parse_fn(&mut parser);
        parse_dur += now.elapsed();

        match next_item {
            None => { break; }
            Some(Err(e)) => { return Err(e); }
            Some(Ok(t)) => {
                if !parse_only {
                    let now = Instant::now();
                    pp_fn(t, indent, terms_per_line);
                    pp_dur += now.elapsed();
                }
            }
        }
    }

    if verbose {
        eprintln!("{}: {} read time: {}.{:06} seconds", PROG_NAME, file, read_dur.as_secs(), read_dur.subsec_micros());
        eprintln!("{}: {} parse time: {}.{:06} seconds", PROG_NAME, file, parse_dur.as_secs(), parse_dur.subsec_micros());
        if !parse_only {
            eprintln!("{}: {} print time: {}.{:06} seconds", PROG_NAME, file, pp_dur.as_secs(), pp_dur.subsec_micros());
        }
    }

    return Ok(());
}

/// Outputs a BertTerm to stdout.
fn pp_bert(term: BertTerm, indent_width: usize, terms_per_line: usize) {
    let stdout = io::stdout();
    let mut stdout = stdout.lock();
    let _ = term.write_as_erlang(&mut stdout, indent_width, terms_per_line);
    let _ = writeln!(&mut stdout, ""); // newline, ignore SIGPIPE
}

/// Outputs a BertTerm as JSON to stdout.
fn pp_json(term: BertTerm, _: usize, _: usize) {
    let stdout = io::stdout();
    let mut stdout = stdout.lock();
    let _ = term.write_as_json(&mut stdout, false);
    let _ = writeln!(&mut stdout, "");
}

/// Outputs a BertTerm as JSON to stdout;
/// Erlang proplists are converted to JSON objects.
fn pp_json_proplist(term: BertTerm, _: usize, _: usize) {
    let stdout = io::stdout();
    let mut stdout = stdout.lock();
    let _ = term.write_as_json(&mut stdout, true);
    let _ = writeln!(&mut stdout, "");
}
<|endoftext|>


<commit_before>#![feature(iter_arith)]
#![feature(scoped)]

#![deny(warnings)]
#![allow(deprecated)] // thread::scoped needs to go, but can't do it now
#![feature(plugin)]

extern crate regex;
extern crate rustc_serialize;

use example::Example;
use std::thread;
use std::sync::mpsc;
use std::path::Path;

mod example;
mod file;
mod markdown;
mod playpen;

fn main() {
    let examples = Example::get_list();
    let (tx, rx) = mpsc::channel();

    let mut nexamples = 0;
    for (i, example) in examples.into_iter().enumerate() {
        let tx = tx.clone();
        let count = example.count();

        let _ = thread::scoped(move || {
            example.process(vec!(i + 1), tx, 0, String::new());
        });

        nexamples += count;
    }

    let mut entries = (0..nexamples).map(|_| {
        rx.recv().unwrap()
    }).collect::<Vec<(Vec<usize>, String)>>();

    entries.sort_by(|&(ref i, _), &(ref j, _)| i.cmp(j));

    let summary = entries.into_iter()
                         .map(|(_, s)| s)
                         .collect::<Vec<String>>()
                         .connect("\n");

    match file::write(&Path::new("stage/SUMMARY.md"), &summary) {
        Err(why) => panic!("{}", why),
        Ok(_) => {},
    }
}
<commit_msg>Drop thread::scoped from update<commit_after>#![feature(iter_arith)]

#![deny(warnings)]
#![allow(deprecated)]
#![feature(plugin)]

extern crate regex;
extern crate rustc_serialize;

use example::Example;
use std::thread;
use std::sync::mpsc;
use std::path::Path;

mod example;
mod file;
mod markdown;
mod playpen;

fn main() {
    let examples = Example::get_list();
    let (tx, rx) = mpsc::channel();
    let mut children = vec![];

    let mut nexamples = 0;
    for (i, example) in examples.into_iter().enumerate() {
        let tx = tx.clone();
        let count = example.count();

        children.push(thread::spawn(move || {
            example.process(vec!(i + 1), tx, 0, String::new());
        }));

        nexamples += count;
    }

    for child in children { let _ = child.join(); }

    let mut entries = (0..nexamples).map(|_| {
        rx.recv().unwrap()
    }).collect::<Vec<(Vec<usize>, String)>>();

    entries.sort_by(|&(ref i, _), &(ref j, _)| i.cmp(j));

    let summary = entries.into_iter()
                         .map(|(_, s)| s)
                         .collect::<Vec<String>>()
                         .connect("\n");

    match file::write(&Path::new("stage/SUMMARY.md"), &summary) {
        Err(why) => panic!("{}", why),
        Ok(_) => {},
    }
}
<|endoftext|>


<commit_before>
#![feature(slice_patterns)]

extern crate piston;
extern crate graphics;
extern crate sdl2_window;
extern crate opengl_graphics;
extern crate sprite;
extern crate vecmath;
extern crate uuid;

pub mod entity;

use entity::{Drawable, MobileUnit};

use std::cell::RefCell;
use std::rc::Rc;

use opengl_graphics::{
    GlGraphics,
    OpenGL,
};
use sdl2_window::Sdl2Window;
use piston::input::Button;
use piston::input::keyboard::Key;

fn main() {
    let win_size = piston::window::Size{width: 1280, height: 720};
    let window_settings = piston::window::WindowSettings::new(
        "Space Game".to_string(),
        win_size
        ).fullscreen(false).exit_on_esc(true).samples(0);
    let opengl = OpenGL::_3_2;
    let window = Sdl2Window::new(
        opengl,
        window_settings,
    );

    let ref mut gl = GlGraphics::new(opengl);
    let window = Rc::new(RefCell::new(window));
    let mut scene = sprite::Scene::new();
    let mut player = entity::Player::new(&mut scene);
    // left, up, right, down
    let mut moving = [false; 4];
    for e in piston::events(window) {
        use piston::event::*;

        scene.event(&e);
        if let Some(Button::Keyboard(key)) = e.press_args() {
            match key {
                Key::Left  => {moving[0] = true;},
                Key::Up    => {moving[1] = true;},
                Key::Right => {moving[2] = true;},
                Key::Down  => {moving[3] = true;},
                _ => {},
            }
        }
        if let Some(Button::Keyboard(key)) = e.release_args() {
            match key {
                Key::Left  => {moving[0] = false;},
                Key::Up    => {moving[1] = false;},
                Key::Right => {moving[2] = false;},
                Key::Down  => {moving[3] = false;},
                _ => {},

            }
        }
        if let Some(args) = e.update_args() {
            player.update(args.dt);
            // update movement
            match moving {
                [true , _, false, _] => {player.set_vel_x(-500.0);},
                [false, _, true , _] => {player.set_vel_x(500.0);},
                [_    , _, _    , _] => {player.set_vel_x(0.0);},
            }
            match moving {
                [_, true , _, false] => {player.set_vel_y(500.0);},
                [_, false, _, true ] => {player.set_vel_y(-500.0);},
                [_, _    , _, _    ] => {player.set_vel_y(0.0);},
            }
        }
        if let Some(args) = e.render_args() {
            use graphics::*;
            player.draw(&mut scene, args);

            gl.draw([0, 0, args.width as i32, args.height as i32], |c, gl| {
                graphics::clear([1.0, 1.0, 1.0, 1.0], gl);
                scene.draw(c.transform, gl);
            });
        }
    }
}
<commit_msg>Added clarifying comments for movement matchs<commit_after>
#![feature(slice_patterns)]

extern crate piston;
extern crate graphics;
extern crate sdl2_window;
extern crate opengl_graphics;
extern crate sprite;
extern crate vecmath;
extern crate uuid;

pub mod entity;

use entity::{Drawable, MobileUnit};

use std::cell::RefCell;
use std::rc::Rc;

use opengl_graphics::{
    GlGraphics,
    OpenGL,
};
use sdl2_window::Sdl2Window;
use piston::input::Button;
use piston::input::keyboard::Key;

fn main() {
    let win_size = piston::window::Size{width: 1280, height: 720};
    let window_settings = piston::window::WindowSettings::new(
        "Space Game".to_string(),
        win_size
        ).fullscreen(false).exit_on_esc(true).samples(0);
    let opengl = OpenGL::_3_2;
    let window = Sdl2Window::new(
        opengl,
        window_settings,
    );

    let ref mut gl = GlGraphics::new(opengl);
    let window = Rc::new(RefCell::new(window));
    let mut scene = sprite::Scene::new();
    let mut player = entity::Player::new(&mut scene);
    // left, up, right, down
    let mut moving = [false; 4];
    for e in piston::events(window) {
        use piston::event::*;

        scene.event(&e);
        if let Some(Button::Keyboard(key)) = e.press_args() {
            match key {
                Key::Left  => {moving[0] = true;},
                Key::Up    => {moving[1] = true;},
                Key::Right => {moving[2] = true;},
                Key::Down  => {moving[3] = true;},
                _ => {},
            }
        }
        if let Some(Button::Keyboard(key)) = e.release_args() {
            match key {
                Key::Left  => {moving[0] = false;},
                Key::Up    => {moving[1] = false;},
                Key::Right => {moving[2] = false;},
                Key::Down  => {moving[3] = false;},
                _ => {},

            }
        }
        if let Some(args) = e.update_args() {
            player.update(args.dt);
            // update horizontal movement
            match moving {
                [true , _, false, _] => {player.set_vel_x(-500.0);},
                [false, _, true , _] => {player.set_vel_x(500.0);},
                [_    , _, _    , _] => {player.set_vel_x(0.0);},
            }
            // update vertical movement
            match moving {
                [_, true , _, false] => {player.set_vel_y(500.0);},
                [_, false, _, true ] => {player.set_vel_y(-500.0);},
                [_, _    , _, _    ] => {player.set_vel_y(0.0);},
            }
        }
        if let Some(args) = e.render_args() {
            use graphics::*;
            player.draw(&mut scene, args);

            gl.draw([0, 0, args.width as i32, args.height as i32], |c, gl| {
                graphics::clear([1.0, 1.0, 1.0, 1.0], gl);
                scene.draw(c.transform, gl);
            });
        }
    }
}
<|endoftext|>


<commit_before>use std::ffi::OsStr;
use std::path::PathBuf;

fn home() -> PathBuf {
    std::env::home_dir().unwrap()
}

fn sbt_launch_dir() -> PathBuf {
    let mut p = PathBuf::from(home());
    p.push(".sbt/launchers");
    p
}

fn jar_file(sbt_version: &str) -> PathBuf {
    let mut p = PathBuf::from(sbt_launch_dir());
    p.push(sbt_version);
    p.push("sbt-launch.jar");
    p
}

fn sbt_version() -> String {
    "0.13.13".to_string()
}

fn sbt_jar() -> PathBuf {
    jar_file(&sbt_version())
}

fn exec_runner<S: AsRef<OsStr>>(args: &[S]) {
    use std::os::unix::process::CommandExt;
    let err = std::process::Command::new(&args[0]).args(&args[1..]).exec();
    println!("error: {}", err);
    if let Some(err) = err.raw_os_error() {
        std::process::exit(err);
    }
    std::process::exit(-1)
}

fn main() {
    let sbt_jar = sbt_jar();

    let java_cmd = "java";
    let extra_jvm_opts = ["-Xms512m", "-Xmx1536m", "-Xss2m"];
    let java_args: [&OsStr; 0] = [];
    let sbt_commands: [&OsStr; 0] = [];
    let residual_args = ["shell"];

    let mut exec_args: Vec<&OsStr> = Vec::new();
    exec_args.push(OsStr::new(java_cmd));
    exec_args.extend_from_slice(&extra_jvm_opts.iter().map(|x| OsStr::new(x)).collect::<Vec<_>>());
    exec_args.extend_from_slice(&java_args.iter().map(|x| OsStr::new(x)).collect::<Vec<_>>());
    exec_args.extend_from_slice(&[OsStr::new("-jar"), sbt_jar.as_os_str()]);
    exec_args.extend_from_slice(&sbt_commands.iter().map(|x| OsStr::new(x)).collect::<Vec<_>>());
    exec_args.extend_from_slice(&residual_args.iter().map(|x| OsStr::new(x)).collect::<Vec<_>>());
    let exec_args = exec_args;

    exec_runner(&exec_args)
}
<commit_msg>Use .as_ref() everywhere<commit_after>use std::ffi::OsStr;
use std::path::PathBuf;

fn home() -> PathBuf {
    std::env::home_dir().unwrap()
}

fn sbt_launch_dir() -> PathBuf {
    let mut p = PathBuf::from(home());
    p.push(".sbt/launchers");
    p
}

fn jar_file(sbt_version: &str) -> PathBuf {
    let mut p = PathBuf::from(sbt_launch_dir());
    p.push(sbt_version);
    p.push("sbt-launch.jar");
    p
}

fn sbt_version() -> String {
    "0.13.13".to_string()
}

fn sbt_jar() -> PathBuf {
    jar_file(&sbt_version())
}

fn exec_runner<S: AsRef<OsStr>>(args: &[S]) {
    use std::os::unix::process::CommandExt;
    let err = std::process::Command::new(&args[0]).args(&args[1..]).exec();
    println!("error: {}", err);
    if let Some(err) = err.raw_os_error() {
        std::process::exit(err);
    }
    std::process::exit(-1)
}

fn main() {
    let sbt_jar = sbt_jar();

    let java_cmd = "java";
    let extra_jvm_opts = ["-Xms512m", "-Xmx1536m", "-Xss2m"];
    let java_args: [&str; 0] = [];
    let sbt_commands: [&str; 0] = [];
    let residual_args = ["shell"];

    let mut exec_args: Vec<&OsStr> = Vec::new();
    exec_args.push(java_cmd.as_ref());
    exec_args.extend_from_slice(&extra_jvm_opts.iter().map(|x| x.as_ref()).collect::<Vec<_>>());
    exec_args.extend_from_slice(&java_args.iter().map(|x| x.as_ref()).collect::<Vec<_>>());
    exec_args.extend_from_slice(&["-jar".as_ref(), sbt_jar.as_ref()]);
    exec_args.extend_from_slice(&sbt_commands.iter().map(|x| x.as_ref()).collect::<Vec<_>>());
    exec_args.extend_from_slice(&residual_args.iter().map(|x| x.as_ref()).collect::<Vec<_>>());
    let exec_args = exec_args;

    exec_runner(&exec_args)
}
<|endoftext|>


<commit_before>
extern crate chrono;
extern crate docopt;
extern crate riemann_client;

use riemann_client::Client;
use riemann_client::proto::Event;

use std::process::Command;

use std::io::prelude::*;
use std::net::TcpStream;

use docopt::Docopt;

use std::str::FromStr;

// Write the Docopt usage string. dfrites ?
static USAGE: &'static str = "
Usage: durite -l HOSTNAME [-g GHOSTNAME [-p PORT]] [-r RHOSTNAME [-o RPORT]]
       durite (--help | -h)

Options:
    -h, --help          Show this screen.
    -l HOSTNAME         Hostname to advertise.
    -g GHOSTNAME        Graphite Hostname.
    -r RHOSTNAME        Riemann Hostname.
    -o RPORT            Riemann port [default: 5555]
    -p PORT             Graphite port [default: 2003]
";

#[cfg(not(any(target_os="macos")))]
fn disk_free() -> std::process::Output {
	Command::new("df")
		.arg("--portability").output().unwrap_or_else(|e| { panic!("failed to execute process: {}", e) })
}

#[cfg(any(target_os="macos"))]
fn disk_free() -> std::process::Output {
	Command::new("df")
		.arg("-k").output().unwrap_or_else(|e| { panic!("failed to execute process: {}", e) })
}

fn send_content(stream: &mut std::net::TcpStream, hostname: &str, probe_and_value: String, timestamp: i64) {
	let content = format!("durite.{}.{} {}\n", hostname, probe_and_value, timestamp);
	let _ = stream.write(&content.as_bytes());
}

fn main() {

	// Parse argv and exit the program with an error message if it fails.
	let args = Docopt::new(USAGE)
		.and_then(|d| d.argv(std::env::args().into_iter()).parse())
		.unwrap_or_else(|e| e.exit());

    let graphite_connect_string: Option<String> = if args.get_str("-g") != "" {
        Some(format!("{}:{}", args.get_str("-g"), args.get_str("-p")))
    } else {
        None
    };

    let mut riemann_connection: Option<Client> = if args.get_str("-r") != "" {
        match Client::connect(&(args.get_str("-r"), u16::from_str(args.get_str("-o")).unwrap())) {
            Ok(c) => Some(c),
            Err(e) => {println!("Oups: {:?}", e); None}
        }
    } else {
        None
    };

    println!("Connect string is {:?}", graphite_connect_string);
    let my_hostname = args.get_str("-l");

	while true {
	    let dt = chrono::UTC::now();
	    let timestamp = dt.timestamp();
	    let o = disk_free();
		let stdout = String::from_utf8(o.stdout).
			ok().
			unwrap();

		let lines = stdout.split("\n");

        for line in lines {
            if line.starts_with("/") {
                let values: Vec<&str> = line.split(" ").filter(|e| {
                    e.len() != 0
                }).collect();

                let disk = values[0];
                // du reports kbytes
                let all: u64 = u64::from_str(values[1]).unwrap() / 1024;
                let available: u64 = u64::from_str(values[3]).unwrap() / 1024;
                if values.len() > 8 {
                }
                // let w = values[8].to_string();
                // let mut st: StatFs = Default::default();
                // let mp = CString::new(w.into_bytes()).unwrap();
                // unsafe {
                //  let o = statfs(mp.as_ptr(), &mut st);
                //  println!("o{} {:?}", o, st.f_bfree);
                // }

                // {:6E} 6 digit, lower exponential format

                match graphite_connect_string {
                    Some(ref connect_string) => {
                        let cs: &str = connect_string.as_ref();
                        match TcpStream::connect(cs) {
                            Ok(mut stream) => {
                                send_content(&mut stream, my_hostname, format!("{}.available {:3.3}", disk, available), timestamp);
                                send_content(&mut stream, my_hostname, format!("{}.all {}", disk, all), timestamp);
                            },
                            Err(e) => println!("Unable to connect to {}: {:?}\nIgnoring this data point.", connect_string, e)
                        }
                    },
                    None => {}
                }
                match riemann_connection {
                    Some(ref mut client) => {
                        client.event({
                                let mut event = Event::new();
                                event.set_service(format!("durite {} disk {} percent free", my_hostname, disk).to_string());
                                event.set_metric_d(available as f64 / all as f64);
                                event
                            }).unwrap();
                    },
                    None => {}
                }
            }
        }
	 	std::thread::sleep_ms(10000);
	}
}
<commit_msg>Percent Used, round to nearest %<commit_after>
extern crate chrono;
extern crate docopt;
extern crate riemann_client;

use riemann_client::Client;
use riemann_client::proto::Event;

use std::process::Command;

use std::io::prelude::*;
use std::net::TcpStream;

use docopt::Docopt;

use std::str::FromStr;

// Write the Docopt usage string. dfrites ?
static USAGE: &'static str = "
Usage: durite -l HOSTNAME [-g GHOSTNAME [-p PORT]] [-r RHOSTNAME [-o RPORT]]
       durite (--help | -h)

Options:
    -h, --help          Show this screen.
    -l HOSTNAME         Hostname to advertise.
    -g GHOSTNAME        Graphite Hostname.
    -r RHOSTNAME        Riemann Hostname.
    -o RPORT            Riemann port [default: 5555]
    -p PORT             Graphite port [default: 2003]
";

#[cfg(not(any(target_os="macos")))]
fn disk_free() -> std::process::Output {
	Command::new("df")
		.arg("--portability").output().unwrap_or_else(|e| { panic!("failed to execute process: {}", e) })
}

#[cfg(any(target_os="macos"))]
fn disk_free() -> std::process::Output {
	Command::new("df")
		.arg("-k").output().unwrap_or_else(|e| { panic!("failed to execute process: {}", e) })
}

fn send_content(stream: &mut std::net::TcpStream, hostname: &str, probe_and_value: String, timestamp: i64) {
	let content = format!("durite.{}.{} {}\n", hostname, probe_and_value, timestamp);
	let _ = stream.write(&content.as_bytes());
}

fn main() {

	// Parse argv and exit the program with an error message if it fails.
	let args = Docopt::new(USAGE)
		.and_then(|d| d.argv(std::env::args().into_iter()).parse())
		.unwrap_or_else(|e| e.exit());

    let graphite_connect_string: Option<String> = if args.get_str("-g") != "" {
        Some(format!("{}:{}", args.get_str("-g"), args.get_str("-p")))
    } else {
        None
    };

    let mut riemann_connection: Option<Client> = if args.get_str("-r") != "" {
        match Client::connect(&(args.get_str("-r"), u16::from_str(args.get_str("-o")).unwrap())) {
            Ok(c) => Some(c),
            Err(e) => {println!("Oups: {:?}", e); None}
        }
    } else {
        None
    };

    println!("Connect string is {:?}", graphite_connect_string);
    let my_hostname = args.get_str("-l");

	while true {
	    let dt = chrono::UTC::now();
	    let timestamp = dt.timestamp();
	    let o = disk_free();
		let stdout = String::from_utf8(o.stdout).
			ok().
			unwrap();

		let lines = stdout.split("\n");

        for line in lines {
            if line.starts_with("/") {
                let values: Vec<&str> = line.split(" ").filter(|e| {
                    e.len() != 0
                }).collect();

                let disk = values[0];
                // du reports kbytes
                let all: u64 = u64::from_str(values[1]).unwrap() / 1024;
                let available: u64 = u64::from_str(values[3]).unwrap() / 1024;
                if values.len() > 8 {
                }
                // let w = values[8].to_string();
                // let mut st: StatFs = Default::default();
                // let mp = CString::new(w.into_bytes()).unwrap();
                // unsafe {
                //  let o = statfs(mp.as_ptr(), &mut st);
                //  println!("o{} {:?}", o, st.f_bfree);
                // }

                // {:6E} 6 digit, lower exponential format

                match graphite_connect_string {
                    Some(ref connect_string) => {
                        let cs: &str = connect_string.as_ref();
                        match TcpStream::connect(cs) {
                            Ok(mut stream) => {
                                send_content(&mut stream, my_hostname, format!("{}.available {:3.3}", disk, available), timestamp);
                                send_content(&mut stream, my_hostname, format!("{}.all {}", disk, all), timestamp);
                            },
                            Err(e) => println!("Unable to connect to {}: {:?}\nIgnoring this data point.", connect_string, e)
                        }
                    },
                    None => {}
                }
                match riemann_connection {
                    Some(ref mut client) => {
                        client.event({
                                let mut event = Event::new();
                                event.set_service(format!("durite {} disk {} percent used", my_hostname, disk).to_string());
                                let percent_used: u64 = 100 - 100*(available/all);
                                event.set_metric_d(percent_used as f64 / 100 as f64);
                                event
                            }).unwrap();
                    },
                    None => {}
                }
            }
        }
	 	std::thread::sleep_ms(10000);
	}
}
<|endoftext|>


<commit_before>extern crate bismuth;
extern crate glutin;
extern crate nalgebra;

use bismuth::cube::{Axis, Cursor, Geometry, LogWidth, Offset, Root, Spatial};
use bismuth::math::{FPoint3, FScalar, IntoSpace, Matrix4Ext, UPoint2, UPoint3, UScalar, UVector3};
use bismuth::render::{AspectRatio, Camera, Context, Mesh, Projection, Transform};
use glutin::{ElementState, Event, MouseButton, VirtualKeyCode, WindowBuilder};

fn new_root(width: LogWidth) -> Root {
    let cursor = Cursor::at_point_with_span(&UPoint3::origin(), width - 3, &UVector3::new(7, 1, 7));
    let mut root = Root::new(width);
    for mut cube in root.to_cube_mut().subdivide_to_cursor(&cursor).iter_mut() {
        for mut cube in cube.iter_mut() {
            if let Some(leaf) = cube.as_leaf_mut() {
                for axis in Axis::range() {
                    for edge in leaf.geometry.edges_mut(axis.into()) {
                        edge.set_front(Offset::from(2));
                        edge.set_back(Offset::from(14));
                    }
                }
            }
        }
    }
    root
}

fn new_camera<W, C>(window: &W, cube: &C) -> Camera
    where W: AspectRatio,
          C: Spatial
{
    let midpoint: FPoint3 = cube.partition().midpoint().into_space();
    let projection = {
        let mut projection = Projection::default();
        projection.far = cube.partition().width().exp() as FScalar * 2.0;
        projection
    };
    let mut camera = Camera::new(window, &projection);
    camera.look_at(&FPoint3::new(midpoint.x * 0.25, -midpoint.y, midpoint.z * 3.0),
                   &midpoint);
    camera
}

fn main() {
    let mut context = Context::from_glutin_window(WindowBuilder::new()
        .with_title("Bismuth")
        .with_dimensions(640, 480)
        .with_vsync()
        .build()
        .unwrap());
    let width = LogWidth::new(8);
    let mut root = new_root(width);
    let mut mesh = root.to_cube().mesh_buffer();
    let camera = new_camera(&context.window, &root);
    let mut pointer = UPoint2::origin();
    let mut transform = Transform::default();
    'main: loop {
        transform.camera = camera.transform().to_array();
        for event in context.window.poll_events() {
            match event {
                Event::KeyboardInput(_, _, Some(VirtualKeyCode::Escape)) |
                Event::Closed => {
                    break 'main;
                }
                Event::MouseInput(ElementState::Pressed, MouseButton::Left) => {
                    let ray = camera.cast_ray(&context.window, &pointer);
                    let mut edited = false;
                    if let Some((_, mut cube)) = root.to_cube_mut()
                        .at_ray_mut(&ray, LogWidth::min_value()) {
                        if let Some(leaf) = cube.as_leaf_mut() {
                            leaf.geometry = Geometry::empty();
                            edited = true;
                        }
                    }
                    if edited {
                        mesh = root.to_cube().mesh_buffer();
                    }
                }
                Event::MouseMoved(x, y) => {
                    pointer = UPoint2::new(x as UScalar, y as UScalar);
                }
                _ => {}
            }
        }
        context.clear();
        context.set_transform(&transform).unwrap();
        context.draw_mesh_buffer(&mesh);
        context.flush().unwrap();
    }
}
<commit_msg>Remove geometry deformation.<commit_after>extern crate bismuth;
extern crate glutin;
extern crate nalgebra;

use bismuth::cube::{Cursor, Geometry, LogWidth, Root, Spatial};
use bismuth::math::{FPoint3, FScalar, IntoSpace, Matrix4Ext, UPoint2, UPoint3, UScalar, UVector3};
use bismuth::render::{AspectRatio, Camera, Context, Mesh, Projection, Transform};
use glutin::{ElementState, Event, MouseButton, VirtualKeyCode, WindowBuilder};

fn new_root(width: LogWidth) -> Root {
    let cursor = Cursor::at_point_with_span(&UPoint3::origin(), width - 3, &UVector3::new(7, 1, 7));
    let mut root = Root::new(width);
    root.to_cube_mut().subdivide_to_cursor(&cursor);
    root
}

fn new_camera<W, C>(window: &W, cube: &C) -> Camera
    where W: AspectRatio,
          C: Spatial
{
    let midpoint: FPoint3 = cube.partition().midpoint().into_space();
    let projection = {
        let mut projection = Projection::default();
        projection.far = cube.partition().width().exp() as FScalar * 2.0;
        projection
    };
    let mut camera = Camera::new(window, &projection);
    camera.look_at(&FPoint3::new(midpoint.x * 0.25, -midpoint.y, midpoint.z * 3.0),
                   &midpoint);
    camera
}

fn main() {
    let mut context = Context::from_glutin_window(WindowBuilder::new()
        .with_title("Bismuth")
        .with_dimensions(1024, 576)
        .with_vsync()
        .build()
        .unwrap());
    let width = LogWidth::new(8);
    let mut root = new_root(width);
    let mut mesh = root.to_cube().mesh_buffer();
    let camera = new_camera(&context.window, &root);
    let mut pointer = UPoint2::origin();
    let mut transform = Transform::default();
    'main: loop {
        transform.camera = camera.transform().to_array();
        for event in context.window.poll_events() {
            match event {
                Event::KeyboardInput(_, _, Some(VirtualKeyCode::Escape)) |
                Event::Closed => {
                    break 'main;
                }
                Event::MouseInput(ElementState::Pressed, MouseButton::Left) => {
                    let ray = camera.cast_ray(&context.window, &pointer);
                    let mut edited = false;
                    if let Some((_, mut cube)) = root.to_cube_mut()
                        .at_ray_mut(&ray, LogWidth::min_value()) {
                        if let Some(leaf) = cube.as_leaf_mut() {
                            leaf.geometry = Geometry::empty();
                            edited = true;
                        }
                    }
                    if edited {
                        mesh = root.to_cube().mesh_buffer();
                    }
                }
                Event::MouseMoved(x, y) => {
                    pointer = UPoint2::new(x as UScalar, y as UScalar);
                }
                _ => {}
            }
        }
        context.clear();
        context.set_transform(&transform).unwrap();
        context.draw_mesh_buffer(&mesh);
        context.flush().unwrap();
    }
}
<|endoftext|>


<commit_before>extern crate libchip8;
extern crate sdl2;

use libchip8::Chip8;
use sdl2::event::Event;
use sdl2::keyboard::{Keycode, KeyboardState, Scancode};
use sdl2::pixels::PixelFormatEnum;
use sdl2::rect::Rect;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::thread::sleep;
use std::time::{Duration, Instant};

const SCALE : u32 = 8;
const WIDTH : u32 = 64 * SCALE;
const HEIGHT : u32 = 32 * SCALE;

fn check_keys(chip : &mut Chip8, kb : &KeyboardState) {
    chip.key[0x0] = if kb.is_scancode_pressed(Scancode::Num0) { 1 } else { 0 };
    chip.key[0x1] = if kb.is_scancode_pressed(Scancode::Num1) { 1 } else { 0 };
    chip.key[0x2] = if kb.is_scancode_pressed(Scancode::Num2) { 1 } else { 0 };
    chip.key[0x3] = if kb.is_scancode_pressed(Scancode::Num3) { 1 } else { 0 };
    chip.key[0x4] = if kb.is_scancode_pressed(Scancode::Num4) { 1 } else { 0 };
    chip.key[0x5] = if kb.is_scancode_pressed(Scancode::Num5) { 1 } else { 0 };
    chip.key[0x6] = if kb.is_scancode_pressed(Scancode::Num6) { 1 } else { 0 };
    chip.key[0x7] = if kb.is_scancode_pressed(Scancode::Num7) { 1 } else { 0 };
    chip.key[0x8] = if kb.is_scancode_pressed(Scancode::Num8) { 1 } else { 0 };
    chip.key[0x9] = if kb.is_scancode_pressed(Scancode::Num9) { 1 } else { 0 };
    chip.key[0xA] = if kb.is_scancode_pressed(Scancode::A) { 1 } else { 0 };
    chip.key[0xB] = if kb.is_scancode_pressed(Scancode::B) { 1 } else { 0 };
    chip.key[0xC] = if kb.is_scancode_pressed(Scancode::C) { 1 } else { 0 };
    chip.key[0xD] = if kb.is_scancode_pressed(Scancode::D) { 1 } else { 0 };
    chip.key[0xE] = if kb.is_scancode_pressed(Scancode::E) { 1 } else { 0 };
    chip.key[0xF] = if kb.is_scancode_pressed(Scancode::F) { 1 } else { 0 };
}

fn main() {
    println!("Chip8 emulator in Rust");

    let path = Path::new("PONG");
    let display = path.display();

    // Initialize the emulator and load the game
    let mut chip = Chip8::new();
    let mut file = match File::open(path) {
        Err(why) => panic!("Couldn't open {}: {}", display, Error::description(&why)),
        Ok(file) => file,
    };

    let mut game = Vec::new();
    match file.read_to_end(&mut game) {
        Err(why) => panic!("Couldn't read {}: {}", display, Error::description(&why)),
        Ok(_) => (),
    };
    chip.load_hex(&game);

    let sdl_context = sdl2::init().unwrap();
    let video_subsystem = sdl_context.video().unwrap();

    let window = video_subsystem.window("Chip8 Emulator", WIDTH, HEIGHT)
        .position_centered()
        .opengl()
        .build()
        .unwrap();

    let mut renderer = window.renderer().build().unwrap();

    let mut event_pump = sdl_context.event_pump().unwrap();

    let mut texture = renderer.create_texture_streaming(
        PixelFormatEnum::RGB24, 64, 32).unwrap();

    // TODO TEST AT 60frames a second!
    // This isn't set to 60Hz because that was too slow
    let one_frame = Duration::from_millis(1);
    let mut current_time = Instant::now();

    // Emulation loop
    'running: loop {
        let last_frame = Instant::now().duration_since(current_time);
        //println!("Last frame: {:?}", last_frame);
        if last_frame < one_frame {
            let diff = one_frame - last_frame;
            //println!("Sleeping for: {:?}", diff);
            sleep(diff);
        }
        current_time = Instant::now();

        // Handle quit event
        for event in event_pump.poll_iter() {
            match event {
                Event::Quit {..} | Event::KeyDown { keycode: Some(Keycode::Escape), .. } => {
                    break 'running
                },
                _ => {}
            }
        }
        chip.emulate_cycle();

        if chip.draw_flag {
            //print!("{:?}", chip);
            chip.draw_flag = false;
            texture.with_lock(None, |buffer: &mut [u8], pitch: usize| {
                for y in 0..32 {
                    for x in 0..64 {
                        let offset = y*pitch + x*3;
                        let value = if 0 != chip.graphics[y * 64 + x] { 255 } else { 0 };
                        buffer[offset + 0] = value as u8;
                        buffer[offset + 1] = value as u8;
                        buffer[offset + 2] = 0;
                    }
                }

            }).unwrap();
            renderer.clear();
            renderer.copy(&texture, None, Some(Rect::new(0, 0, WIDTH, HEIGHT)));
            renderer.present();
        }

        // Store key press state
        let keyboard_state = KeyboardState::new(&event_pump);
        check_keys(&mut chip, &keyboard_state);

        // Make sound
        if chip.make_sound {
            unsafe {
                println!("{}", std::char::from_u32_unchecked(7));
            }
        }
    }
}
<commit_msg>Fixing up main.rs<commit_after>extern crate libchip8;
extern crate sdl2;

use libchip8::Chip8;
use sdl2::event::Event;
use sdl2::keyboard::{Keycode, KeyboardState, Scancode};
use sdl2::pixels::PixelFormatEnum;
use sdl2::rect::Rect;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::thread::sleep;
use std::time::{Duration, Instant};

const SCALE : u32 = 8;
const WIDTH : u32 = 64 * SCALE;
const HEIGHT : u32 = 32 * SCALE;

fn check_keys(chip : &mut Chip8, kb : &KeyboardState) {
    chip.key[0x0] = kb.is_scancode_pressed(Scancode::Num0) as u8;
    chip.key[0x1] = kb.is_scancode_pressed(Scancode::Num1) as u8;
    chip.key[0x2] = kb.is_scancode_pressed(Scancode::Num2) as u8;
    chip.key[0x3] = kb.is_scancode_pressed(Scancode::Num3) as u8;
    chip.key[0x4] = kb.is_scancode_pressed(Scancode::Num4) as u8;
    chip.key[0x5] = kb.is_scancode_pressed(Scancode::Num5) as u8;
    chip.key[0x6] = kb.is_scancode_pressed(Scancode::Num6) as u8;
    chip.key[0x7] = kb.is_scancode_pressed(Scancode::Num7) as u8;
    chip.key[0x8] = kb.is_scancode_pressed(Scancode::Num8) as u8;
    chip.key[0x9] = kb.is_scancode_pressed(Scancode::Num9) as u8;
    chip.key[0xA] = kb.is_scancode_pressed(Scancode::A) as u8;
    chip.key[0xB] = kb.is_scancode_pressed(Scancode::B) as u8;
    chip.key[0xC] = kb.is_scancode_pressed(Scancode::C) as u8;
    chip.key[0xD] = kb.is_scancode_pressed(Scancode::D) as u8;
    chip.key[0xE] = kb.is_scancode_pressed(Scancode::E) as u8;
    chip.key[0xF] = kb.is_scancode_pressed(Scancode::F) as u8;
}

fn main() {
    println!("Chip8 emulator in Rust");

    // Initialize the emulator and load the game
    let path = Path::new("PONG");
    let display = path.display();

    let mut chip = Chip8::new();
    let mut file = match File::open(path) {
        Err(why) => panic!("Couldn't open {}: {}", display, Error::description(&why)),
        Ok(file) => file,
    };

    let mut game = Vec::new();
    match file.read_to_end(&mut game) {
        Err(why) => panic!("Couldn't read {}: {}", display, Error::description(&why)),
        Ok(_) => (),
    };
    chip.load_hex(&game);

    // Setup the graphics and input
    let sdl_context = sdl2::init().unwrap();
    let video_subsystem = sdl_context.video().unwrap();

    let window = video_subsystem.window("Chip8 Emulator", WIDTH, HEIGHT)
        .position_centered()
        .opengl()
        .build()
        .unwrap();

    let mut renderer = window.renderer().build().unwrap();

    let mut event_pump = sdl_context.event_pump().unwrap();

    let mut texture = renderer.create_texture_streaming(
        PixelFormatEnum::RGB24, 64, 32).unwrap();

    // TODO TEST AT 60frames a second!
    // This isn't set to 60Hz because that was too slow
    let one_frame = Duration::from_millis(1);
    let mut current_time = Instant::now();

    // Emulation loop
    'running: loop {
        let last_frame = Instant::now().duration_since(current_time);
        //println!("Last frame: {:?}", last_frame);
        if last_frame < one_frame {
            let diff = one_frame - last_frame;
            //println!("Sleeping for: {:?}", diff);
            sleep(diff);
        }
        current_time = Instant::now();

        // Handle quit event
        for event in event_pump.poll_iter() {
            match event {
                Event::Quit {..} | Event::KeyDown { keycode: Some(Keycode::Escape), .. } => {
                    break 'running
                },
                _ => {}
            }
        }
        chip.emulate_cycle();

        if chip.draw_flag {
            //print!("{:?}", chip);
            chip.draw_flag = false;
            texture.with_lock(None, |buffer: &mut [u8], pitch: usize| {
                for y in 0..32 {
                    for x in 0..64 {
                        let offset = y*pitch + x*3;
                        let value = if 0 != chip.graphics[y * 64 + x] { 255 } else { 0 };
                        buffer[offset + 0] = value as u8;
                        buffer[offset + 1] = value as u8;
                        buffer[offset + 2] = 0;
                    }
                }

            }).unwrap();
            renderer.clear();
            renderer.copy(&texture, None, Some(Rect::new(0, 0, WIDTH, HEIGHT)));
            renderer.present();
        }

        // Store key press state
        let keyboard_state = KeyboardState::new(&event_pump);
        check_keys(&mut chip, &keyboard_state);

        // Make sound
        if chip.make_sound {
            unsafe {
                println!("{}", std::char::from_u32_unchecked(7));
            }
        }
    }
}
<|endoftext|>


<commit_before>extern crate iron;
#[macro_use]
extern crate router;
extern crate logger;
extern crate rustc_serialize;
extern crate walkdir;
#[macro_use]
extern crate horrorshow;
#[macro_use]
extern crate mopa;
extern crate docopt;

mod scripts;
mod mainpage_generator;
mod script_handlers;

use iron::prelude::*;
use iron::status;
use iron::mime::Mime;
use router::Router;
use logger::Logger;

use walkdir::WalkDir;

use docopt::Docopt;

use std::env;
use std::io;
use std::thread;
use std::time::Duration;
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use rustc_serialize::json;
use std::str::FromStr;

use scripts::Script;
use mainpage_generator::MainPageHtml;

static IMMEDIATE_RET_PATH: &'static str = "ret_immediately";
static DEFAULT_SERVER_HOSTNAME: &'static str = "localhost:3000";

#[cfg_attr(rustfmt, rustfmt_skip)]
const USAGE: &'static str = "
Articulator
A small server program that can run arbitrary scripts on the hosting server.

Usage:
    articulator.exe [<hostname>]
    articulator.exe (-h | --help)

Options:
    hostname        (Optional) An IPv4-compatible hostname string.
    -h --help       Show this screen.
";

#[derive(Debug, RustcDecodable)]
struct Args {
    flag_hostname: Option<String>,
}

fn main() {
    let args: Args = Docopt::new(USAGE)
                         .and_then(|d| d.decode())
                         .unwrap_or_else(|e| {
                             println!("Invalid input. Terminating.");
                             e.exit();
                         });

    let hostname = match args.flag_hostname {
        Some(name) => name,
        None => String::from(DEFAULT_SERVER_HOSTNAME),
    };

    let (logger_before, logger_after) = Logger::new(None);
    let router = router!(get "/" => show_mainpage_handler,
                         get "/scr" => show_scripts_handler,
                         get "/scr/:scriptName" => script_handler);

    let mut chain = Chain::new(router);

    chain.link_after(logger_after); //this seems incredibly prone to breaking for no good reason
    chain.link_before(logger_before);

    Iron::new(chain).http(hostname.as_str()).unwrap();
}

fn show_mainpage_handler(_: &mut Request) -> IronResult<Response> {
    if let Ok(scripts) = get_script_list() {
        let mainpage = MainPageHtml::new(scripts);
        let content_type = "text/html".parse::<Mime>().unwrap();
        return Ok(Response::with((content_type, status::Ok, mainpage.html_string)));
    } else {
        script_error_handler()
    }
}

fn show_scripts_handler(_: &mut Request) -> IronResult<Response> {
    println!("Getting scripts...");
    if let Ok(scripts) = get_script_list() {
        let scripts = json::encode(&scripts).unwrap();
        Ok(Response::with((status::Ok, scripts)))
    } else {
        script_error_handler()
    }
}

fn script_handler(req: &mut Request) -> IronResult<Response> {
    let ref query = req.extensions.get::<Router>().unwrap().find("scriptName").unwrap_or("/");
    let script = get_script(query);
    if script.is_err() {
        return script_error_handler();
    }
    let script = script.unwrap();
    let script_path = script.get_full_path();

    match script_path {
        Ok(path) => {
            if path.to_string_lossy().contains(IMMEDIATE_RET_PATH) {
                run_early_return_script(script)
            } else {
                script.run()
            }
        }
        Err(_) => {
            println!("Could not find script.");
            script_error_handler()
        }
    }
}

fn run_early_return_script(script: Box<Script>) -> IronResult<Response> {
    thread::spawn(move || {
        thread::sleep(Duration::from_millis(500));
        script.run().ok();
    });
    Ok(Response::with((status::Ok, "Attempted to kick off early-return script.")))
}

fn script_error_handler() -> IronResult<Response> {
    Ok(Response::with(status::InternalServerError))
}

fn get_script_folder() -> io::Result<PathBuf> {
    let current_exe = try!(env::current_exe());
    match current_exe.parent() {
        Some(parent_dir) => Ok(parent_dir.join("scripts")),
        None => Err(io::Error::new(io::ErrorKind::NotFound, "Unable to find scripts folder.")),
    }
}

// todo: fix unwrap infestation in here
fn get_script_list() -> io::Result<Vec<Box<Script>>> {
    let folder = try!(get_script_folder());
    let paths = WalkDir::new(&folder);

    let mut scripts = Vec::new();
    for p in paths {
        let p: walkdir::DirEntry = p.unwrap();
        if !p.file_type().is_file() {
            continue;
        };
        let split_str = String::from(p.file_name().to_str().unwrap());
        let split_str: Vec<&str> = split_str.split('.').collect();
        let name = *split_str.first().unwrap();

        let mut path = PathBuf::new();
        path.push(p.path());
        let path_root = Path::new(path.strip_prefix(folder.as_path().parent().unwrap())
                                      .unwrap());
        let rel_path = String::from(path_root.to_str().unwrap()).replace("\\", "/");

        let path_ext = p.path()
                        .extension()
                        .unwrap_or_else(|| OsStr::new(""))
                        .to_str()
                        .unwrap_or_else(|| "");
        if let Some(boxed_script) = scripts::construct_script(String::from_str(name).unwrap(),
                                                              String::from(rel_path),
                                                              String::from(path_ext)) {
            scripts.push(boxed_script);
        } else {
            return Err(io::Error::new(io::ErrorKind::InvalidInput,
                                      format!("Unable to determine file type for script {:?}",
                                              p.path())));
        }
    }
    return Ok(scripts);
}

fn get_script(name: &str) -> io::Result<Box<Script>> {
    let script_list: Vec<Box<Script>> = try!(get_script_list());
    if let Some(script) = script_list.into_iter().find(|s| s.get_name() == name) {
        Ok(script)
    } else {
        Err(io::Error::new(io::ErrorKind::NotFound,
                           format!("Script with name {} not found.", name)))
    }
}
<commit_msg>Fix command line parsing<commit_after>extern crate iron;
#[macro_use]
extern crate router;
extern crate logger;
extern crate rustc_serialize;
extern crate walkdir;
#[macro_use]
extern crate horrorshow;
#[macro_use]
extern crate mopa;
extern crate docopt;

mod scripts;
mod mainpage_generator;
mod script_handlers;

use iron::prelude::*;
use iron::status;
use iron::mime::Mime;
use router::Router;
use logger::Logger;

use walkdir::WalkDir;

use docopt::Docopt;

use std::env;
use std::io;
use std::thread;
use std::time::Duration;
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use rustc_serialize::json;
use std::str::FromStr;

use scripts::Script;
use mainpage_generator::MainPageHtml;

static IMMEDIATE_RET_PATH: &'static str = "ret_immediately";
static DEFAULT_SERVER_HOSTNAME: &'static str = "localhost:3000";

#[cfg_attr(rustfmt, rustfmt_skip)]
const USAGE: &'static str = "
Articulator
A small server program that can run arbitrary scripts on the hosting server.

Usage:
    articulator.exe [<hostname>]
    articulator.exe (-h | --help)

Options:
    hostname        (Optional) An IPv4-compatible hostname string.
    -h --help       Show this screen.
";

#[derive(Debug, RustcDecodable)]
struct Args {
    arg_hostname: Option<String>,
}

fn main() {
    let args: Args = Docopt::new(USAGE)
                         .and_then(|d| d.decode())
                         .unwrap_or_else(|e| {
                             println!("Invalid input. Terminating.");
                             e.exit();
                         });

    println!("Args: {:?}", args);
    let hostname = match args.arg_hostname {
        Some(name) => name,
        None => String::from(DEFAULT_SERVER_HOSTNAME),
    };

    let (logger_before, logger_after) = Logger::new(None);
    let router = router!(get "/" => show_mainpage_handler,
                         get "/scr" => show_scripts_handler,
                         get "/scr/:scriptName" => script_handler);

    let mut chain = Chain::new(router);

    chain.link_after(logger_after); //this seems incredibly prone to breaking for no good reason
    chain.link_before(logger_before);

    Iron::new(chain).http(hostname.as_str()).unwrap();
}

fn show_mainpage_handler(_: &mut Request) -> IronResult<Response> {
    if let Ok(scripts) = get_script_list() {
        let mainpage = MainPageHtml::new(scripts);
        let content_type = "text/html".parse::<Mime>().unwrap();
        return Ok(Response::with((content_type, status::Ok, mainpage.html_string)));
    } else {
        script_error_handler()
    }
}

fn show_scripts_handler(_: &mut Request) -> IronResult<Response> {
    println!("Getting scripts...");
    if let Ok(scripts) = get_script_list() {
        let scripts = json::encode(&scripts).unwrap();
        Ok(Response::with((status::Ok, scripts)))
    } else {
        script_error_handler()
    }
}

fn script_handler(req: &mut Request) -> IronResult<Response> {
    let ref query = req.extensions.get::<Router>().unwrap().find("scriptName").unwrap_or("/");
    let script = get_script(query);
    if script.is_err() {
        return script_error_handler();
    }
    let script = script.unwrap();
    let script_path = script.get_full_path();

    match script_path {
        Ok(path) => {
            if path.to_string_lossy().contains(IMMEDIATE_RET_PATH) {
                run_early_return_script(script)
            } else {
                script.run()
            }
        }
        Err(_) => {
            println!("Could not find script.");
            script_error_handler()
        }
    }
}

fn run_early_return_script(script: Box<Script>) -> IronResult<Response> {
    thread::spawn(move || {
        thread::sleep(Duration::from_millis(500));
        script.run().ok();
    });
    Ok(Response::with((status::Ok, "Attempted to kick off early-return script.")))
}

fn script_error_handler() -> IronResult<Response> {
    Ok(Response::with(status::InternalServerError))
}

fn get_script_folder() -> io::Result<PathBuf> {
    let current_exe = try!(env::current_exe());
    match current_exe.parent() {
        Some(parent_dir) => Ok(parent_dir.join("scripts")),
        None => Err(io::Error::new(io::ErrorKind::NotFound, "Unable to find scripts folder.")),
    }
}

// todo: fix unwrap infestation in here
fn get_script_list() -> io::Result<Vec<Box<Script>>> {
    let folder = try!(get_script_folder());
    let paths = WalkDir::new(&folder);

    let mut scripts = Vec::new();
    for p in paths {
        let p: walkdir::DirEntry = p.unwrap();
        if !p.file_type().is_file() {
            continue;
        };
        let split_str = String::from(p.file_name().to_str().unwrap());
        let split_str: Vec<&str> = split_str.split('.').collect();
        let name = *split_str.first().unwrap();

        let mut path = PathBuf::new();
        path.push(p.path());
        let path_root = Path::new(path.strip_prefix(folder.as_path().parent().unwrap())
                                      .unwrap());
        let rel_path = String::from(path_root.to_str().unwrap()).replace("\\", "/");

        let path_ext = p.path()
                        .extension()
                        .unwrap_or_else(|| OsStr::new(""))
                        .to_str()
                        .unwrap_or_else(|| "");
        if let Some(boxed_script) = scripts::construct_script(String::from_str(name).unwrap(),
                                                              String::from(rel_path),
                                                              String::from(path_ext)) {
            scripts.push(boxed_script);
        } else {
            return Err(io::Error::new(io::ErrorKind::InvalidInput,
                                      format!("Unable to determine file type for script {:?}",
                                              p.path())));
        }
    }
    return Ok(scripts);
}

fn get_script(name: &str) -> io::Result<Box<Script>> {
    let script_list: Vec<Box<Script>> = try!(get_script_list());
    if let Some(script) = script_list.into_iter().find(|s| s.get_name() == name) {
        Ok(script)
    } else {
        Err(io::Error::new(io::ErrorKind::NotFound,
                           format!("Script with name {} not found.", name)))
    }
}
<|endoftext|>


<commit_before>extern crate clap;
extern crate notify;
extern crate term;

use clap::App;
use notify::{RecommendedWatcher, Error, Watcher};
use std::io::Write;
use std::thread;
use std::string::String;
use std::path::Path;
use std::process::{Command, Stdio};
use std::convert::Into;
use std::sync::mpsc::channel;
use term::color;

fn out<S:Into<String>>(label: &str, msg: S, color: color::Color) -> std::io::Result<()> {
  let mut out = term::stdout().unwrap();
  try!(out.reset());
  try!(out.fg(color));
  try!(write!(&mut std::io::stdout(), "{:>12}", format!("Capgun {}", label)));
  try!(out.reset());
  try!(write!(&mut std::io::stdout(), " {}\n", msg.into()));
  try!(out.flush());
  Ok(())
}

fn err<S:Into<String>>(label: &str, msg: S) -> std::io::Result<()> {
  let mut out = term::stderr().unwrap();
  try!(out.reset());
  try!(out.fg(color::RED));
  try!(write!(&mut std::io::stderr(), "{:>12}", format!("Capgun {}", label)));
  try!(out.reset());
  try!(write!(&mut std::io::stderr(), " {}\n", msg.into()));
  try!(out.flush());
  Ok(())
}

fn main() {
  let matches = App::new("capgun")
    .about("fires off commands when files change")
    .args_from_usage(
      "-c, --command=<CMD> 'cmd to run when files under <INPUT> change'
       <INPUT> 'Sets the directory to watch'"
    )
    .get_matches();

  let cmd = matches.value_of("CMD").unwrap();
  let input = matches.value_of("INPUT").unwrap();

  let _ = out("Watching", input, color::BRIGHT_CYAN);

  let (tx, rx) = channel();
  let watch: Result<RecommendedWatcher, Error> = Watcher::new(tx);

  match watch {
    Ok(mut watcher) =>  {
      match watcher.watch(&Path::new(input)) {
        Ok(_) => {},
        Err(e) => {
          let _ = err("Error", format!("Failed to load gun {:?}", e));
          return
        },
      }

      loop {
        thread::sleep_ms(5000);
        match rx.recv() {
          Ok(e) => fire(e, cmd),
          Err(e) => {
            let _ = err("Missfire", &(format!("{:?}", e)[..]));
            return
          }
        }
      }
    },
    Err(_) => println!("Couldn't generate directory watcher")
  }
}

fn fire(e: notify::Event, cmd:  &str) {
  match e.op {
    Ok(_) => {
      let mut split = cmd.split(" ");
      let mut task = Command::new(split.next().unwrap());
      for s in split {
        task.arg(s);
      }
      let output = task
        .stdin(Stdio::inherit())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .output()
        .unwrap_or_else(|e| panic!("Failed to fire: {} {}", cmd, e));

      println!("{}", String::from_utf8_lossy(&output.stdout));
      match writeln!(&mut std::io::stderr(), "{}", String::from_utf8_lossy(&output.stderr)) {
        Err(x) => panic!("Unable to write to stderr: {}", x),
        Ok(_) => {}
      }
      if output.status.success() {
        let _ = out("Hit", cmd, color::BRIGHT_GREEN);
      } else {
        let _ = err("Miss", cmd);
      }
    },
    Err(e) => println!("{:?}", e),
  }
}
<commit_msg>refactor(main): simplify assignment of conditional out calls<commit_after>extern crate clap;
extern crate notify;
extern crate term;

use clap::App;
use notify::{RecommendedWatcher, Error, Watcher};
use std::io::Write;
use std::thread;
use std::string::String;
use std::path::Path;
use std::process::{Command, Stdio};
use std::convert::Into;
use std::sync::mpsc::channel;
use term::color;

fn out<S:Into<String>>(label: &str, msg: S, color: color::Color) -> std::io::Result<()> {
  let mut out = term::stdout().unwrap();
  try!(out.reset());
  try!(out.fg(color));
  try!(write!(&mut std::io::stdout(), "{:>12}", format!("Capgun {}", label)));
  try!(out.reset());
  try!(write!(&mut std::io::stdout(), " {}\n", msg.into()));
  try!(out.flush());
  Ok(())
}

fn err<S:Into<String>>(label: &str, msg: S) -> std::io::Result<()> {
  let mut out = term::stderr().unwrap();
  try!(out.reset());
  try!(out.fg(color::RED));
  try!(write!(&mut std::io::stderr(), "{:>12}", format!("Capgun {}", label)));
  try!(out.reset());
  try!(write!(&mut std::io::stderr(), " {}\n", msg.into()));
  try!(out.flush());
  Ok(())
}

fn main() {
  let matches = App::new("capgun")
    .about("fires off commands when files change")
    .args_from_usage(
      "-c, --command=<CMD> 'cmd to run when files under <INPUT> change'
       <INPUT> 'Sets the directory to watch'"
    )
    .get_matches();

  let cmd = matches.value_of("CMD").unwrap();
  let input = matches.value_of("INPUT").unwrap();

  let _ = out("Watching", input, color::BRIGHT_CYAN);

  let (tx, rx) = channel();
  let watch: Result<RecommendedWatcher, Error> = Watcher::new(tx);

  match watch {
    Ok(mut watcher) =>  {
      match watcher.watch(&Path::new(input)) {
        Ok(_) => {},
        Err(e) => {
          let _ = err("Error", format!("Failed to load gun {:?}", e));
          return
        },
      }

      loop {
        thread::sleep_ms(5000);
        match rx.recv() {
          Ok(e) => fire(e, cmd),
          Err(e) => {
            let _ = err("Missfire", &(format!("{:?}", e)[..]));
            return
          }
        }
      }
    },
    Err(_) => println!("Couldn't generate directory watcher")
  }
}

fn fire(e: notify::Event, cmd:  &str) {
  match e.op {
    Ok(_) => {
      let mut split = cmd.split(" ");
      let mut task = Command::new(split.next().unwrap());
      for s in split {
        task.arg(s);
      }
      let output = task
        .stdin(Stdio::inherit())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .output()
        .unwrap_or_else(|e| panic!("Failed to fire: {} {}", cmd, e));

      println!("{}", String::from_utf8_lossy(&output.stdout));
      match writeln!(&mut std::io::stderr(), "{}", String::from_utf8_lossy(&output.stderr)) {
        Err(x) => panic!("Unable to write to stderr: {}", x),
        Ok(_) => {}
      }

      let _ = if output.status.success() {
        out("Hit", cmd, color::BRIGHT_GREEN)
      } else {
        err("Miss", cmd)
      };
    },
    Err(e) => println!("{:?}", e),
  }
}
<|endoftext|>