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

extern crate rustc_serialize;
extern crate docopt;
#[macro_use] extern crate quick_error;

use std::path::{Path, PathBuf};
use std::io;
use std::io::BufReader;
use std::io::BufRead;
use std::fs::File;

// use quick_error::ResultExt;

docopt!(Args derive Debug, "
Create SSH bookmarks from known_hosts and ssh_config files.

Usage:
  ssh_bookmarker create [-v...] [-c FILE...] [-k FILE...] <output>

Options:
  -h --help              Show this screen.
  --version              Show version.
  -v --verbose           Log verbosely.
  -c --config FILE       ssh_config(5) file to read.
  -k --known-hosts FILE  known_hosts file to read.
");

#[derive(Debug, PartialEq)]
struct Host {
    name: String,
}

quick_error! {
    #[derive(Debug)]
    pub enum Error {
        KnownHostFormat(path: PathBuf, lineno: usize, line: String) {
            // context(path: &'a Path, lineno: usize, line: &'a str)
            //     -> (path.to_path_buf(), lineno, line.to_string())
            display("{} line {}: {:?}", path.to_str().unwrap_or("(unprintable path)"), lineno, line)
        }
        IO(err: io::Error) {
            from()
                cause(err)
                description("Couldn't read from file")
        }
    }
}

fn create_config_entries<'a>(pathname: &Path) -> Result<Vec<Host>, Error>{
    Ok(vec!())
}

fn process_entry(pathname: &Path, lineno: usize, line: &str) -> Result<Vec<Host>, Error> {
    let mut hosts: Vec<Host> = vec!();
    let line = line.trim();
    // Skip comments or blank lines:
    if line.len() == 0 || line.starts_with('#') {
        return Ok(vec![]);
    }

    let mut items = line.split_whitespace();
    let mut host_item = try!(items.next().ok_or(Error::KnownHostFormat(pathname.to_path_buf(), lineno, line.to_string())));
    if host_item.starts_with('@') {
        // the hosts list is the next item if the first is a marker
        host_item = try!(items.next().ok_or(Error::KnownHostFormat(pathname.to_path_buf(), lineno, line.to_string())));
    }
    if host_item.starts_with('|') {
        // hashed hosts can't be processed meaningfully, so don't do anything:
        return Ok(vec![]);
    }
    for host in host_item.split(',') {
        hosts.push(Host{name: host.to_string()});
    }
    Ok(hosts)
}

fn create_known_hosts_entries<'a>(pathname: &Path) -> Result<Vec<Host>, Error>{
    let f = try!(File::open(pathname));
    let file = BufReader::new(&f);

    let mut hosts: Vec<Host> = vec!();
    for (lineno, maybe_line) in file.lines().enumerate() {
        let line = try!(maybe_line);
        hosts.extend(try!(process_entry(pathname, lineno, &line)));
    }
    Ok(hosts)
}

fn main() {
    let args: Args = Args::docopt().decode().unwrap_or_else(|e| e.exit());
    if args.cmd_create {
        let known_hosts: Vec<Host> = args.flag_known_hosts.iter().flat_map (|kh| {
            create_known_hosts_entries(Path::new(kh)).unwrap()
        }).collect();
        let config_hosts = args.flag_config.iter().flat_map (|conf| {
            create_config_entries(Path::new(conf)).unwrap()
        });
        println!("known hosts: {:?}", known_hosts);
        println!("ssh config: {:?}", config_hosts);
    } else {
        panic!("I don't understand what {:?} should do", args)
    }
}

#[test]
fn test_known_hosts_entry() {
    let no_hosts: Vec<Host> = vec![];
    let comment: Vec<Host> = process_entry(Path::new("/dev/null"), 0, "# Comments allowed at start of line").unwrap();
    assert_eq!(no_hosts, comment);

    let empty: Vec<Host> = process_entry(Path::new("/dev/null"), 0, "    ").unwrap();
    assert_eq!(no_hosts, empty);

    let multiple: Vec<Host> = process_entry(Path::new("/dev/null"), 0, "closenet,closenet.example.net,192.0.2.53 1024 37 159...93 closenet.example.net ").unwrap();
    let expected_multiple: Vec<Host> = vec![Host{name: "closenet".to_string()}, Host{name: "closenet.example.net".to_string()}, Host{name: "192.0.2.53".to_string()}];
    assert_eq!(multiple, expected_multiple);

    let annotated: Vec<Host> = process_entry(Path::new("/dev/null"), 0, "@revoked something ssh-rsa AAAAB5W...").unwrap();
    let expected_annotated: Vec<Host> = vec![Host{name: "something".to_string()}];
    assert_eq!(annotated, expected_annotated);

    let hashed: Vec<Host> = process_entry(Path::new("/dev/null"), 0, "|1|JfKTdBh7rNbXkVAQCRp4OQoPfmI=|USECr3SWf1JUPsms5AqfD5QfxkM= ssh-rsa AAAAB5W...").unwrap();
    let expected_hashed: Vec<Host> = vec![];
    assert_eq!(hashed, expected_hashed);
}
<commit_msg>First stab at a rewrite in rust: Can parse ~/.ssh/config<commit_after>#![feature(plugin)]
#![plugin(docopt_macros)]
#![feature(advanced_slice_patterns, slice_patterns)]

extern crate rustc_serialize;
extern crate docopt;
#[macro_use] extern crate quick_error;

use std::path::{Path, PathBuf};
use std::io;
use std::io::BufReader;
use std::io::BufRead;
use std::fs::File;

// use quick_error::ResultExt;

docopt!(Args derive Debug, "
Create SSH bookmarks from known_hosts and ssh_config files.

Usage:
  ssh_bookmarker create [-v...] [-c FILE...] [-k FILE...] <output>

Options:
  -h --help              Show this screen.
  --version              Show version.
  -v --verbose           Log verbosely.
  -c --config FILE       ssh_config(5) file to read.
  -k --known-hosts FILE  known_hosts file to read.
");

#[derive(Debug, PartialEq)]
struct Host {
    name: String,
    protocol: String,
}

impl Host {
    fn new(name: &str, protocol: &str) -> Host {
        Host{
            name: name.to_string(),
            protocol: protocol.to_string(),
        }
    }

    fn named(name: &str) -> Host {
        Host{
            name: name.to_string(),
            protocol: "ssh".to_string(),
        }
    }
}

quick_error! {
    #[derive(Debug)]
    pub enum Error {
        KnownHostFormat(path: PathBuf, lineno: usize, line: String) {
            // context(path: &'a Path, lineno: usize, line: &'a str)
            //     -> (path.to_path_buf(), lineno, line.to_string())
            display("{} line {}: {:?}", path.to_str().unwrap_or("(unprintable path)"), lineno, line)
        }
        IO(err: io::Error) {
            from()
                cause(err)
                description("Couldn't read from file")
        }
    }
}

fn create_config_entries<'a>(pathname: &Path) -> Result<Vec<Host>, Error>{
    let f = try!(File::open(pathname));
    let file = BufReader::new(&f);

    let mut hosts: Vec<Host> = vec!();
    for maybe_line in file.lines() {
        let line = try!(maybe_line);

        let line = line.trim();
        // Skip comments or blank lines:
        if line.len() == 0 || line.starts_with('#') {
            continue;
        }

        let mut protocols: Vec<&str> = vec!["ssh"];
        let annotated: Vec<&str> = line.split("#:").collect();
        if annotated.len() > 1 {
            protocols = annotated[1].split(",").collect();
        }

        let items: Vec<String> = annotated[0].split_whitespace().map(|s| s.to_lowercase()).collect();
        let matchable_items: Vec<&str> = items.iter().map(|s| s.as_str()).collect();
        match matchable_items.as_slice() {
            &["host", ref host_entries..] => {
                for proto in protocols.iter() {
                    hosts.extend(host_entries.into_iter().map(|name| Host::new(name, proto)))
                }
            },
            _ => {}
        }
    }
    Ok(hosts)
}

fn process_entry(pathname: &Path, lineno: usize, line: &str) -> Result<Vec<Host>, Error> {
    let mut hosts: Vec<Host> = vec!();
    let line = line.trim();
    // Skip comments or blank lines:
    if line.len() == 0 || line.starts_with('#') {
        return Ok(vec![]);
    }

    let mut items = line.split_whitespace();
    let mut host_item = try!(items.next().ok_or(Error::KnownHostFormat(pathname.to_path_buf(), lineno, line.to_string())));
    if host_item.starts_with('@') {
        // the hosts list is the next item if the first is a marker
        host_item = try!(items.next().ok_or(Error::KnownHostFormat(pathname.to_path_buf(), lineno, line.to_string())));
    }
    if host_item.starts_with('|') {
        // hashed hosts can't be processed meaningfully, so don't do anything:
        return Ok(vec![]);
    }
    for host in host_item.split(',') {
        hosts.push(Host::named(host));
    }
    Ok(hosts)
}

fn create_known_hosts_entries<'a>(pathname: &Path) -> Result<Vec<Host>, Error>{
    let f = try!(File::open(pathname));
    let file = BufReader::new(&f);

    let mut hosts: Vec<Host> = vec!();
    for (lineno, maybe_line) in file.lines().enumerate() {
        let line = try!(maybe_line);
        hosts.extend(try!(process_entry(pathname, lineno, &line)));
    }
    Ok(hosts)
}

fn main() {
    let args: Args = Args::docopt().decode().unwrap_or_else(|e| e.exit());
    if args.cmd_create {
        let known_hosts: Vec<Host> = args.flag_known_hosts.iter().flat_map (|kh| {
            create_known_hosts_entries(Path::new(kh)).unwrap()
        }).collect();
        let config_hosts: Vec<Host> = args.flag_config.iter().flat_map (|conf| {
            create_config_entries(Path::new(conf)).unwrap()
        }).collect();
        println!("known hosts: {:?}", known_hosts);
        println!("ssh config: {:?}", config_hosts);
    } else {
        panic!("I don't understand what {:?} should do", args)
    }
}

#[test]
fn test_known_hosts_entry() {
    let no_hosts: Vec<Host> = vec![];
    let comment: Vec<Host> = process_entry(Path::new("/dev/null"), 0, "# Comments allowed at start of line").unwrap();
    assert_eq!(no_hosts, comment);

    let empty: Vec<Host> = process_entry(Path::new("/dev/null"), 0, "    ").unwrap();
    assert_eq!(no_hosts, empty);

    let multiple: Vec<Host> = process_entry(Path::new("/dev/null"), 0, "closenet,closenet.example.net,192.0.2.53 1024 37 159...93 closenet.example.net ").unwrap();
    let expected_multiple: Vec<Host> = vec![Host::named("closenet"), Host::named("closenet.example.net"), Host::named("192.0.2.53")];
    assert_eq!(multiple, expected_multiple);

    let annotated: Vec<Host> = process_entry(Path::new("/dev/null"), 0, "@revoked something ssh-rsa AAAAB5W...").unwrap();
    let expected_annotated: Vec<Host> = vec![Host::named("something")];
    assert_eq!(annotated, expected_annotated);

    let hashed: Vec<Host> = process_entry(Path::new("/dev/null"), 0, "|1|JfKTdBh7rNbXkVAQCRp4OQoPfmI=|USECr3SWf1JUPsms5AqfD5QfxkM= ssh-rsa AAAAB5W...").unwrap();
    let expected_hashed: Vec<Host> = vec![];
    assert_eq!(hashed, expected_hashed);
}
<|endoftext|>


<commit_before>extern crate rustbox;
extern crate rustc_serialize;
extern crate gag;
extern crate toml;
extern crate itertools;
extern crate docopt;
#[macro_use] extern crate rex_utils;

use std::path::Path;
use std::error::Error;
use std::io;
use std::io::Write;
use std::process;
use docopt::Docopt;
use rustbox::{RustBox, Event, InputMode, InitOptions};
use rustbox::keyboard::Key;
use gag::Hold;

mod config;
mod ui;

use ui::view::HexEdit;
use config::Config;

static USAGE: &'static str = "
Usage: rex [options] [-C CONF... FILE]
       rex --help
       rex --help-config

Options:
    -h, --help                  Show this help message
    -c FILE, --config FILE      Use FILE as the config file
    -C CONF                     Set a configuration option, for example: -C line_width=16
";

#[derive(RustcDecodable, Debug)]
struct Args {
    flag_help_config: bool,
    arg_FILE: Option<String>,
    flag_config: Option<String>,
    flag_C: Vec<String>,
}

fn exit_err<E: Error>(msg: &str, error: E) -> ! {
    write!(&mut io::stderr(), "{}: {}", msg, error).unwrap();
    process::exit(1);
}

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

    if args.flag_help_config {
        println!("{}", Config::get_config_usage());
        process::exit(0);
    }

    let config_res = if let Some(config_filename) = args.flag_config {
        Config::from_file(config_filename)
    } else {
        Config::open_default()
    };
    let mut config = config_res.unwrap_or_else(
        |e| exit_err("Couldn't open config file", e)
    );

    for config_line in &args.flag_C {
        config.set_from_string(config_line).unwrap_or_else(
            |e| exit_err("Couldn't parse command line config option", e)
        );
    }

    let mut edit = HexEdit::new(config);

    if let Some(ref filename) = args.arg_FILE {
        edit.open(&Path::new(filename));
    }

    let hold = (Hold::stdout().unwrap(), Hold::stderr().unwrap());

    let rb = RustBox::init(InitOptions{
        buffer_stderr: false,
        input_mode: InputMode::Esc,
    }).unwrap();

    edit.resize(rb.width() as i32, rb.height() as i32);
    edit.draw(&rb);
    rb.present();
    loop {
        let event = rb.poll_event(false).unwrap();
        match event {
            // This case is here, since we want to have a 'way ouy' till we fixed bugs
            Event::KeyEvent(Some(Key::Ctrl('q'))) => break,
            Event::KeyEvent(Some(key)) => edit.input(key),
            Event::ResizeEvent(w, h) => { edit.resize(w, h) }
            _ => ()
        };
        rb.clear();
        edit.draw(&rb);
        rb.present();
    }
    drop(rb);
    drop(hold);
}
<commit_msg>Remove some warnings<commit_after>extern crate rustbox;
extern crate rustc_serialize;
extern crate gag;
extern crate toml;
extern crate itertools;
extern crate docopt;
#[macro_use] extern crate rex_utils;

use std::path::Path;
use std::error::Error;
use std::io;
use std::io::Write;
use std::process;
use docopt::Docopt;
use rustbox::{RustBox, Event, InputMode, InitOptions};
use rustbox::keyboard::Key;
use gag::Hold;

mod config;
mod ui;

use ui::view::HexEdit;
use config::Config;

static USAGE: &'static str = "
Usage: rex [options] [-C CONF... FILE]
       rex --help
       rex --help-config

Options:
    -h, --help                  Show this help message
    -c FILE, --config FILE      Use FILE as the config file
    -C CONF                     Set a configuration option, for example: -C line_width=16
";

#[derive(RustcDecodable, Debug)]
#[allow(non_snake_case)]
struct Args {
    flag_help_config: bool,
    arg_FILE: Option<String>,
    flag_config: Option<String>,
    flag_C: Vec<String>,
}

fn exit_err<E: Error>(msg: &str, error: E) -> ! {
    write!(&mut io::stderr(), "{}: {}", msg, error).unwrap();
    process::exit(1);
}

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

    if args.flag_help_config {
        println!("{}", Config::get_config_usage());
        process::exit(0);
    }

    let config_res = if let Some(config_filename) = args.flag_config {
        Config::from_file(config_filename)
    } else {
        Config::open_default()
    };
    let mut config = config_res.unwrap_or_else(
        |e| exit_err("Couldn't open config file", e)
    );

    for config_line in &args.flag_C {
        config.set_from_string(config_line).unwrap_or_else(
            |e| exit_err("Couldn't parse command line config option", e)
        );
    }

    let mut edit = HexEdit::new(config);

    if let Some(ref filename) = args.arg_FILE {
        edit.open(&Path::new(filename));
    }

    let hold = (Hold::stdout().unwrap(), Hold::stderr().unwrap());

    let rb = RustBox::init(InitOptions{
        buffer_stderr: false,
        input_mode: InputMode::Esc,
    }).unwrap();

    edit.resize(rb.width() as i32, rb.height() as i32);
    edit.draw(&rb);
    rb.present();
    loop {
        let event = rb.poll_event(false).unwrap();
        match event {
            // This case is here, since we want to have a 'way ouy' till we fixed bugs
            Event::KeyEvent(Some(Key::Ctrl('q'))) => break,
            Event::KeyEvent(Some(key)) => edit.input(key),
            Event::ResizeEvent(w, h) => { edit.resize(w, h) }
            _ => ()
        };
        rb.clear();
        edit.draw(&rb);
        rb.present();
    }
    drop(rb);
    drop(hold);
}
<|endoftext|>


<commit_before>#![feature(slice_patterns, vec_resize)]
#[macro_use]
extern crate nom;

use nom::{IResult, eof};
use std::collections::BTreeMap;
use std::fs;
use std::io;
use std::io::{Read, Write};
use std::path::Path;
use std::thread;

#[derive(Debug)]
#[derive(PartialEq)]
#[derive(Eq)]
enum Op {
    Add(u8),
    Mov(isize),
    In,
    Out,
    Loop(OpStream),

    // extra optimized ops
    Transfer(u8, Vec<(isize, u8)>),
}

use Op::*;

#[derive(Debug)]
#[derive(PartialEq)]
#[derive(Eq)]
struct OpStream {
    ops: Vec<Op>,
}

impl OpStream {
    fn optimize(&mut self) {
        let mut i = 0;
        while i < self.ops.len() {
            match &self.ops[i..] {
                [Add(a), Add(b), ..] => {
                    self.ops[i] = Add(a.wrapping_add(b));
                    self.ops.remove(i + 1);
                }
                [Mov(a), Mov(b), ..] => {
                    self.ops[i] = Mov(a + b);
                    self.ops.remove(i + 1);
                }
                [Add(0), ..] | [Mov(0), ..] => {
                    self.ops.remove(i);
                    if i > 0 {
                        i -= 1;
                    }
                }
                [Loop(_), ..] => {
                    let mut maybe_new_op = None;

                    if let &mut Loop(ref mut stream) = &mut self.ops[i] {
                        stream.optimize();
                        maybe_new_op = stream.find_alternative();
                    }

                    if let Some(new_op) = maybe_new_op {
                        self.ops[i] = new_op;
                    }

                    i += 1
                }
                _ => i += 1,
            }
        }
    }

    fn find_alternative(&self) -> Option<Op> {
        let mut map: BTreeMap<isize, u8> = BTreeMap::new();
        let mut rel_index = 0;

        for op in &self.ops[..] {
            match op {
                &Add(x) => {
                    let new_val = map.get(&rel_index).unwrap_or(&0).wrapping_add(x);
                    map.insert(rel_index, new_val);
                }
                &Mov(x) => {
                    rel_index += x;
                }
                _ => {
                    return None;
                }
            }
        }

        if rel_index != 0 {
            return None;
        }

        Some(Transfer(map.remove(&0).unwrap_or(0), map.into_iter().collect()))
    }

    fn get(&self) -> &[Op] {
        &self.ops[..]
    }
}

static ZERO: u8 = 0;

struct State {
    index: usize,
    memory: Vec<u8>,
}

impl State {
    fn new() -> State {
        State {
            index: 0,
            memory: vec![],
        }
    }

    fn rel_index(&self, relative: isize) -> usize {
        (self.index as isize + relative) as usize
    }

    fn step(&mut self, op: &Op) -> bool {
        match *op {
            Add(i) => {
                self[0] = self[0].wrapping_add(i);
            }
            Mov(n) => {
                self.index = self.rel_index(n);
            }
            In => {
                let mut c = [0u8];
                if io::stdin().read(&mut c).unwrap() == 0 {
                    return false;
                }
                self[0] = c[0];
            }
            Out => {
                io::stdout().write(&[self[0]]).unwrap();
            }
            Loop(ref ops) => {
                while self[0] != 0 {
                    if !self.run(ops.get()) {
                        return false;
                    }
                }
            }
            Transfer(d, ref map) => {
                if self[0] == 0 {
                    return true
                }

                let mut _v = self[0];
                let mut _n = 0;

                while _v != 0 {
                    _v = _v.wrapping_add(d);
                    if _v == self[0] {
                        // stalled: the current transfer will never complete
                        loop {
                            thread::park()
                        }
                    }
                    _n += 1
                }

                self[0] = 0;
                for &(k, v) in &map[..] {
                    self[k] = self[k].wrapping_add(v.wrapping_mul(_n));
                }
            }
        }
        return true;
    }

    fn run(&mut self, ops: &[Op]) -> bool {
        for op in ops {
            if !self.step(op) {
                return false;
            }
        }
        return true;
    }
}

impl std::ops::Index<isize> for State {
    type Output = u8;
    fn index(&self, _index: isize) -> &u8 {
        let idx = self.rel_index(_index);
        if idx >= self.memory.len() {
            &ZERO
        } else {
            &self.memory[idx]
        }
    }
}

impl std::ops::IndexMut<isize> for State {
    fn index_mut(&mut self, _index: isize) -> &mut u8 {
        let idx = self.rel_index(_index);
        if idx >= self.memory.len() {
            self.memory.resize(idx * 2 + 1, 0);
        }
        &mut self.memory[idx]
    }
}

fn main() {
    let filenames: Vec<String> = std::iter::FromIterator::from_iter(std::env::args());

    for filename in &filenames[1..] {
        match reader(&Path::new(filename))
                  .and_then(|mut reader| {
                      let mut buffer = Vec::new();
                      reader.read_to_end(&mut buffer).map(|_| buffer)
                  })
                  .map_err(|e| format!("{}", e))
                  .and_then(|buffer| {
                      match bf_parse_file(&buffer[..]) {
                          IResult::Done(_, o) => Ok(o),
                          IResult::Error(e) => Err(format!("Parsing error: {:?}", e)),
                          IResult::Incomplete(m) => Err(format!("Incomplete file: {:?}", m)),
                      }
                  }) {
            Ok(ops) => {
                let mut opstream = OpStream { ops: ops };
                opstream.optimize();
                State::new().run(opstream.get());
            }
            Err(e) => {
                writeln!(&mut io::stderr(),
                         "Error while processing {}: {}",
                         filename,
                         e)
                    .unwrap();
            }
        };
    }
}

named!(bf_parse_file<&[u8], Vec<Op> >, chain!(ops: bf_parse ~ eof, || ops));
named!(bf_parse<&[u8], Vec<Op> >,
    many0!(
        chain!(
            opt!(is_not!("+-<>.,[]")) ~
            op: alt!(
                chain!(tag!("+"), || Add(0x01)) |
                chain!(tag!("-"), || Add(0xff)) |
                chain!(tag!(">"), || Mov(1)) |
                chain!(tag!("<"), || Mov(-1)) |
                chain!(tag!("."), || Out) |
                chain!(tag!(","), || In) |
                chain!(subops: delimited!(tag!("["), bf_parse, tag!("]")), || Loop(OpStream { ops: subops }))
            ) ~
            opt!(is_not!("+-<>.,[]")), || op)
        )
    );

fn reader(path: &Path) -> Result<io::BufReader<fs::File>, io::Error> {
    fs::File::open(path).map(|f| io::BufReader::new(f))
}

#[cfg(test)]
mod tests {
    use nom::IResult::Done;
    use super::{bf_parse_file, State, OpStream};
    use super::Op::*;

    #[test]
    fn test_state_index() {
        let mut state = State {
            index: 0,
            memory: vec![23, 0, 0, 0, 0, 42],
        };
        assert_eq!(23, state[0]);
        state.index = 5;
        assert_eq!(42, state[0]);
    }

    #[test]
    fn test_state_index_mut() {
        let mut state = State::new();
        state[0] = 23;
        assert_eq!(23, state.memory[state.index]);
        state.index = 5;
        state[0] = 42;
        assert_eq!(42, state.memory[state.index]);
    }

    #[test]
    fn test_state_step_add() {
        let mut state = State::new();
        state.step(&Add(23));
        assert_eq!(23, state[0]);
        state.step(&Add(42));
        assert_eq!(65, state[0]);
        state.step(&Add(190));
        assert_eq!(255, state[0]);
    }

    #[test]
    fn test_state_step_mov() {
        let mut state = State::new();
        state.step(&Mov(1));
        assert_eq!(1, state.index);
        state.step(&Mov(42));
        assert_eq!(43, state.index);
        state.step(&Mov(-1));
        assert_eq!(42, state.index);
    }

    #[test]
    fn test_state_step_loop() {
        let mut state = State::new();
        state[0] = 23;
        state.step(&Loop(OpStream { ops: vec![Add(1)] }));
        assert_eq!(0, state[0]);
    }

    #[test]
    fn test_state_step_transfer() {
        let mut state = State::new();
        state[0] = 15;
        state[1] = 7;
        state.step(&Transfer(5, vec![(1, 2)]));
        assert_eq!(0, state[0]);
        assert_eq!(1, state[1]);
    }

    #[test]
    fn test_opstream_optimize() {
        let mut opstream = OpStream {
            ops: vec![Mov(1),
                      Mov(1),
                      Add(0x01),
                      Add(0x0ff),
                      Add(0x0ff),
                      Mov(1),
                      Mov(-1),
                      Loop(OpStream { ops: vec![Mov(2), Mov(3)] })],
        };
        opstream.optimize();

        assert_eq!(opstream,
                   OpStream { ops: vec![Mov(2), Add(0xff), Loop(OpStream { ops: vec![Mov(5)] })] });
    }

    #[test]
    fn test_opstream_optimize_transfer() {
        let mut opstream = OpStream {
            ops: vec![Loop(OpStream { ops: vec![Add(0x01), Mov(3), Add(0xff), Mov(-3)] })],
        };
        opstream.optimize();

        assert_eq!(opstream,
                   OpStream { ops: vec![Transfer(1, vec![(3, 255)])] });
    }

    #[test]
    fn test_parse() {
        let input = b"+-[+.,]+";
        assert_eq!(bf_parse_file(&input[..]),
                   Done(&b""[..],
                        vec![Add(0x01),
                             Add(0xff),
                             Loop(OpStream { ops: vec![Add(1), Out, In] }),
                             Add(0x01)]));
    }
}
<commit_msg>chore: adjust to latest rust changes<commit_after>#![feature(slice_patterns)]
#[macro_use]
extern crate nom;

use nom::{IResult, eof};
use std::collections::BTreeMap;
use std::fs;
use std::io;
use std::io::{Read, Write};
use std::path::Path;
use std::thread;

#[derive(Debug)]
#[derive(PartialEq)]
#[derive(Eq)]
enum Op {
    Add(u8),
    Mov(isize),
    In,
    Out,
    Loop(OpStream),

    // extra optimized ops
    Transfer(u8, Vec<(isize, u8)>),
}

use Op::*;

#[derive(Debug)]
#[derive(PartialEq)]
#[derive(Eq)]
struct OpStream {
    ops: Vec<Op>,
}

impl OpStream {
    fn optimize(&mut self) {
        let mut i = 0;
        while i < self.ops.len() {
            match &self.ops[i..] {
                [Add(a), Add(b), ..] => {
                    self.ops[i] = Add(a.wrapping_add(b));
                    self.ops.remove(i + 1);
                }
                [Mov(a), Mov(b), ..] => {
                    self.ops[i] = Mov(a + b);
                    self.ops.remove(i + 1);
                }
                [Add(0), ..] | [Mov(0), ..] => {
                    self.ops.remove(i);
                    if i > 0 {
                        i -= 1;
                    }
                }
                [Loop(_), ..] => {
                    let mut maybe_new_op = None;

                    if let &mut Loop(ref mut stream) = &mut self.ops[i] {
                        stream.optimize();
                        maybe_new_op = stream.find_alternative();
                    }

                    if let Some(new_op) = maybe_new_op {
                        self.ops[i] = new_op;
                    }

                    i += 1
                }
                _ => i += 1,
            }
        }
    }

    fn find_alternative(&self) -> Option<Op> {
        let mut map: BTreeMap<isize, u8> = BTreeMap::new();
        let mut rel_index = 0;

        for op in &self.ops[..] {
            match op {
                &Add(x) => {
                    let new_val = map.get(&rel_index).unwrap_or(&0).wrapping_add(x);
                    map.insert(rel_index, new_val);
                }
                &Mov(x) => {
                    rel_index += x;
                }
                _ => {
                    return None;
                }
            }
        }

        if rel_index != 0 {
            return None;
        }

        Some(Transfer(map.remove(&0).unwrap_or(0), map.into_iter().collect()))
    }

    fn get(&self) -> &[Op] {
        &self.ops[..]
    }
}

static ZERO: u8 = 0;

struct State {
    index: usize,
    memory: Vec<u8>,
}

impl State {
    fn new() -> State {
        State {
            index: 0,
            memory: vec![],
        }
    }

    fn rel_index(&self, relative: isize) -> usize {
        (self.index as isize + relative) as usize
    }

    fn step(&mut self, op: &Op) -> bool {
        match *op {
            Add(i) => {
                self[0] = self[0].wrapping_add(i);
            }
            Mov(n) => {
                self.index = self.rel_index(n);
            }
            In => {
                let mut c = [0u8];
                if io::stdin().read(&mut c).unwrap() == 0 {
                    return false;
                }
                self[0] = c[0];
            }
            Out => {
                io::stdout().write(&[self[0]]).unwrap();
            }
            Loop(ref ops) => {
                while self[0] != 0 {
                    if !self.run(ops.get()) {
                        return false;
                    }
                }
            }
            Transfer(d, ref map) => {
                if self[0] == 0 {
                    return true
                }

                let mut _v = self[0];
                let mut _n = 0;

                while _v != 0 {
                    _v = _v.wrapping_add(d);
                    if _v == self[0] {
                        // stalled: the current transfer will never complete
                        loop {
                            thread::park()
                        }
                    }
                    _n += 1
                }

                self[0] = 0;
                for &(k, v) in &map[..] {
                    self[k] = self[k].wrapping_add(v.wrapping_mul(_n));
                }
            }
        }
        return true;
    }

    fn run(&mut self, ops: &[Op]) -> bool {
        for op in ops {
            if !self.step(op) {
                return false;
            }
        }
        return true;
    }
}

impl std::ops::Index<isize> for State {
    type Output = u8;
    fn index(&self, _index: isize) -> &u8 {
        let idx = self.rel_index(_index);
        if idx >= self.memory.len() {
            &ZERO
        } else {
            &self.memory[idx]
        }
    }
}

impl std::ops::IndexMut<isize> for State {
    fn index_mut(&mut self, _index: isize) -> &mut u8 {
        let idx = self.rel_index(_index);
        if idx >= self.memory.len() {
            self.memory.resize(idx * 2 + 1, 0);
        }
        &mut self.memory[idx]
    }
}

fn main() {
    let filenames: Vec<String> = std::iter::FromIterator::from_iter(std::env::args());

    for filename in &filenames[1..] {
        match reader(&Path::new(filename))
                  .and_then(|mut reader| {
                      let mut buffer = Vec::new();
                      reader.read_to_end(&mut buffer).map(|_| buffer)
                  })
                  .map_err(|e| format!("{}", e))
                  .and_then(|buffer| {
                      match bf_parse_file(&buffer[..]) {
                          IResult::Done(_, o) => Ok(o),
                          IResult::Error(e) => Err(format!("Parsing error: {:?}", e)),
                          IResult::Incomplete(m) => Err(format!("Incomplete file: {:?}", m)),
                      }
                  }) {
            Ok(ops) => {
                let mut opstream = OpStream { ops: ops };
                opstream.optimize();
                State::new().run(opstream.get());
            }
            Err(e) => {
                writeln!(&mut io::stderr(),
                         "Error while processing {}: {}",
                         filename,
                         e)
                    .unwrap();
            }
        };
    }
}

named!(bf_parse_file<&[u8], Vec<Op> >, chain!(ops: bf_parse ~ eof, || ops));
named!(bf_parse<&[u8], Vec<Op> >,
    many0!(
        chain!(
            opt!(is_not!("+-<>.,[]")) ~
            op: alt!(
                chain!(tag!("+"), || Add(0x01)) |
                chain!(tag!("-"), || Add(0xff)) |
                chain!(tag!(">"), || Mov(1)) |
                chain!(tag!("<"), || Mov(-1)) |
                chain!(tag!("."), || Out) |
                chain!(tag!(","), || In) |
                chain!(subops: delimited!(tag!("["), bf_parse, tag!("]")), || Loop(OpStream { ops: subops }))
            ) ~
            opt!(is_not!("+-<>.,[]")), || op)
        )
    );

fn reader(path: &Path) -> Result<io::BufReader<fs::File>, io::Error> {
    fs::File::open(path).map(|f| io::BufReader::new(f))
}

#[cfg(test)]
mod tests {
    use nom::IResult::Done;
    use super::{bf_parse_file, State, OpStream};
    use super::Op::*;

    #[test]
    fn test_state_index() {
        let mut state = State {
            index: 0,
            memory: vec![23, 0, 0, 0, 0, 42],
        };
        assert_eq!(23, state[0]);
        state.index = 5;
        assert_eq!(42, state[0]);
    }

    #[test]
    fn test_state_index_mut() {
        let mut state = State::new();
        state[0] = 23;
        assert_eq!(23, state.memory[state.index]);
        state.index = 5;
        state[0] = 42;
        assert_eq!(42, state.memory[state.index]);
    }

    #[test]
    fn test_state_step_add() {
        let mut state = State::new();
        state.step(&Add(23));
        assert_eq!(23, state[0]);
        state.step(&Add(42));
        assert_eq!(65, state[0]);
        state.step(&Add(190));
        assert_eq!(255, state[0]);
    }

    #[test]
    fn test_state_step_mov() {
        let mut state = State::new();
        state.step(&Mov(1));
        assert_eq!(1, state.index);
        state.step(&Mov(42));
        assert_eq!(43, state.index);
        state.step(&Mov(-1));
        assert_eq!(42, state.index);
    }

    #[test]
    fn test_state_step_loop() {
        let mut state = State::new();
        state[0] = 23;
        state.step(&Loop(OpStream { ops: vec![Add(1)] }));
        assert_eq!(0, state[0]);
    }

    #[test]
    fn test_state_step_transfer() {
        let mut state = State::new();
        state[0] = 15;
        state[1] = 7;
        state.step(&Transfer(5, vec![(1, 2)]));
        assert_eq!(0, state[0]);
        assert_eq!(1, state[1]);
    }

    #[test]
    fn test_opstream_optimize() {
        let mut opstream = OpStream {
            ops: vec![Mov(1),
                      Mov(1),
                      Add(0x01),
                      Add(0x0ff),
                      Add(0x0ff),
                      Mov(1),
                      Mov(-1),
                      Loop(OpStream { ops: vec![Mov(2), Mov(3)] })],
        };
        opstream.optimize();

        assert_eq!(opstream,
                   OpStream { ops: vec![Mov(2), Add(0xff), Loop(OpStream { ops: vec![Mov(5)] })] });
    }

    #[test]
    fn test_opstream_optimize_transfer() {
        let mut opstream = OpStream {
            ops: vec![Loop(OpStream { ops: vec![Add(0x01), Mov(3), Add(0xff), Mov(-3)] })],
        };
        opstream.optimize();

        assert_eq!(opstream,
                   OpStream { ops: vec![Transfer(1, vec![(3, 255)])] });
    }

    #[test]
    fn test_parse() {
        let input = b"+-[+.,]+";
        assert_eq!(bf_parse_file(&input[..]),
                   Done(&b""[..],
                        vec![Add(0x01),
                             Add(0xff),
                             Loop(OpStream { ops: vec![Add(1), Out, In] }),
                             Add(0x01)]));
    }
}
<|endoftext|>


<commit_before>//! Main module of way-cooler

#[macro_use]
extern crate lazy_static;
extern crate bitflags;
extern crate dbus_macros;
extern crate getopts;
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate rlua;
extern crate rustc_serialize;
extern crate json_macro;
extern crate nix;
extern crate petgraph;
extern crate uuid;
extern crate dbus;
extern crate cairo;
extern crate cairo_sys;
extern crate gdk_pixbuf;
extern crate glib;
#[macro_use]
extern crate wayland_sys;
extern crate wayland_server;
extern crate xcb;

#[macro_use]
mod macros;
mod convert;
mod callbacks;
mod keys;
mod lua;
mod registry;
mod commands;
mod ipc;
mod layout;
mod render;
mod wayland;
mod modes;
mod awesome;

use std::env;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;

use getopts::Options;
use log::LogLevel;
use nix::sys::signal::{self, SigHandler, SigSet, SigAction, SaFlags};

use rustwlc::types::LogType;

const VERSION: &'static str = env!("CARGO_PKG_VERSION");
const GIT_VERSION: &'static str = include_str!(concat!(env!("OUT_DIR"), "/git-version.txt"));
const DRIVER_MOD_PATH: &'static str = "/proc/modules";
const DEVICE_MOD_PATH: &'static str = "/sys/firmware/devicetree/base/model";

/// Callback to route wlc logs into env_logger
fn log_handler(level: LogType, message: &str) {
    match level {
        LogType::Info => info!("wlc: {}", message),
        LogType::Warn => warn!("wlc: {}", message),
        LogType::Error => error!("wlc: {}", message),
        LogType::Wayland => info!("wayland: {}", message)
    }
}

/// Formats the log strings properly
fn log_format(record: &log::LogRecord) -> String {
    let color = match record.level() {
        LogLevel::Info => "",
        LogLevel::Trace => "\x1B[37m",
        LogLevel::Debug => "\x1B[44m",
        LogLevel::Warn =>  "\x1B[33m",
        LogLevel::Error => "\x1B[31m",
    };
    let location = record.location();
    let file = location.file();
    let line = location.line();
    let mut module_path = location.module_path();
    if let Some(index) = module_path.find("way_cooler::") {
        let index = index + "way_cooler::".len();
        module_path = &module_path[index..];
    }
    format!("{} {} [{}] \x1B[37m{}:{}\x1B[0m{0} {} \x1B[0m",
            color, record.level(), module_path, file, line, record.args())
}

/// Ensures that the environment is set up correctly. E.g:
/// * XDG_RUNTIME_DIR is set to a directory that exists.
fn ensure_good_env() {
    use std::env::VarError;
    match env::var("XDG_RUNTIME_DIR") {
        Ok(_) => {/* Do nothing, logged in `log_environment` */},
        Err(VarError::NotUnicode(string)) => {
            error!("The value set for XDG_RUNTIME_DIR ({:?}) \
                    is not valid unicode!",
                   string);
            std::process::exit(1);
        },
        Err(VarError::NotPresent) => {
            error!("XDG_RUNTIME_DIR is not set!");
            std::process::exit(1);
        }
    }
}

/// Checks the loaded modules, and reports any problematic proprietary ones
fn detect_proprietary() {
    // If DISPLAY is present, we are running embedded
    if env::var("DISPLAY").is_ok() {
        return
    }
    match File::open(Path::new(DRIVER_MOD_PATH)) {
        Ok(file) => {
            let reader = BufReader::new(&file);
            for line in reader.lines() {
                if let Ok(line) = line {
                    if line.contains("nvidia") {
                        error!("Warning: Proprietary nvidia graphics drivers are installed, \
                               but they are not compatible with Wayland. \
                               Consider using nouveau drivers for Wayland.");
                        break;
                    } else if line.contains("fglrx") {
                        error!("Warning: Proprietary AMD graphics drivers are installed, \
                                but they are not compatible with Wayland. \
                               Consider using radeon drivers for Waylad.");
                        break;
                    }
                }
            }
        },
        Err(err) => {
            warn!("Could not read proprietary modules at \"{}\", because: {:#?}",
                  DRIVER_MOD_PATH, err);
            warn!("If you are running proprietary AMD or Nvidia graphics drivers, \
                   Way Cooler may not work for you");
        }
    }
}

/// Checks the loaded modules to ensure vc4 is loaded if we are running on a raspi.
fn detect_raspi() {
    use std::fmt::Debug;
    /// Prints a debug line from the given info.
    /// This should be used to "fail open" so that we keep trying but at least
    /// warn the user that what we are about to do probably won't work.
    fn fail_open<T: Debug>(path: &str, err: T) {
        warn!("Could not read file \"{}\" because {:#?}",
              path, err)
    }
    let raspi = match File::open(Path::new(DEVICE_MOD_PATH)) {
        Ok(f) => {
            let reader = BufReader::new(&f);
            let mut raspi = false;
            for line in reader.lines() {
                if let Ok(line) = line {
                    if line.contains("Raspberry Pi") {
                        raspi = true;
                        break;
                    }
                }
            }
            raspi
        },
        Err(_) => {
            return;
        }
    };
    let vc4 = match File::open(Path::new(DRIVER_MOD_PATH)) {
        Ok(f) => {
            let reader = BufReader::new(&f);
            let mut vc4 = false;
            for line in reader.lines() {
                if let Ok(line) = line {
                    if line.contains("vc4") {
                        vc4 = true;
                        break;
                    }
                }
            }
            vc4
        },
        Err(err) => {
            fail_open(DRIVER_MOD_PATH, err);
            return;
        }
    };
    if !vc4 && raspi {
        error!("You are running on a Raspberry Pi, but the vc4 module is not loaded!");
        error!("Set 'dtoverlay=vc4-kms-v3d' in /boot/config.txt and reboot!");
    }
}

#[inline(always)]
/// Determines if we should build with debug symbols.
pub fn debug_enabled() -> bool {
    cfg!(not(disable_debug))
}

/// Initializes the logging system.
pub fn init_logs() {
    let mut builder = env_logger::LogBuilder::new();
    builder.format(log_format);
    builder.filter(None, log::LogLevelFilter::Trace);
    if env::var("WAY_COOLER_LOG").is_ok() {
        builder.parse(&env::var("WAY_COOLER_LOG")
                      .expect("WAY_COOLER_LOG not defined"));
    }
    builder.init().expect("Unable to initialize logging!");
    info!("Logger initialized, setting wlc handlers.");
}

fn log_environment() {
    for (key, value) in env::vars() {
        info!("{}: {}", key, value);
    }
}

/// Handler for signals
extern "C" fn sig_handle(_: nix::libc::c_int) {
    rustwlc::terminate();
}

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

    let mut opts = Options::new();
    opts.optflag("", "version", "show version information");
    let matches = match opts.parse(&args[1..]) {
        Ok(m) => m,
        Err(f) => {
            println!("{}", f.to_string());
            std::process::exit(1);
        }
    };
    if matches.opt_present("version") {
        if !GIT_VERSION.is_empty() {
            println!("Way Cooler {} @ {}", VERSION, GIT_VERSION);
        } else {
            println!("Way Cooler {}", VERSION);
        }
        println!("Way Cooler IPC version {}", ipc::VERSION);
        return
    }
    println!("Launching way-cooler...");

    let sig_action = SigAction::new(SigHandler::Handler(sig_handle), SaFlags::empty(),
                                    SigSet::empty());
    unsafe {signal::sigaction(signal::SIGINT, &sig_action).unwrap() };

    init_logs();
    log_environment();
    detect_proprietary();
    detect_raspi();
    ensure_good_env();
    // This prepares wlc, doesn't run main loop until run_wlc is called
    let run_wlc = rustwlc::init()
        .expect("Unable to initialize wlc!");
    wayland::init_wayland_protocols();
    rustwlc::log_set_rust_handler(log_handler);
    callbacks::init();
    commands::init();
    registry::init();
    ipc::init();

    info!("Running wlc...");
    run_wlc();
}
<commit_msg>Stripped down main and fixed up old code<commit_after>//! Main module of way-cooler

// TODO FIXME Remove
#![allow(unused_macros)]
#![allow(unused_imports)]

extern crate wlroots;
#[macro_use]
extern crate lazy_static;
extern crate bitflags;
extern crate dbus_macros;
extern crate getopts;
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate rlua;
extern crate rustc_serialize;
extern crate json_macro;
extern crate nix;
extern crate petgraph;
extern crate uuid;
extern crate dbus;
extern crate cairo;
extern crate cairo_sys;
extern crate gdk_pixbuf;
extern crate glib;
#[macro_use]
extern crate wayland_sys;
extern crate wayland_server;
extern crate xcb;

#[macro_use]
mod macros;
//mod convert;
//mod callbacks;
//mod keys;
//mod lua;
//mod registry;
//mod commands;
//mod ipc;
//mod layout;
//mod render;
//mod wayland;
//mod modes;
//mod awesome;

use std::{env, process::exit, fs::File, io::{BufRead, BufReader}, path::Path};

use log::LogLevel;
use nix::sys::signal::{self, SigHandler, SigSet, SigAction, SaFlags};

const VERSION: &'static str = env!("CARGO_PKG_VERSION");
const GIT_VERSION: &'static str = include_str!(concat!(env!("OUT_DIR"), "/git-version.txt"));
const DRIVER_MOD_PATH: &'static str = "/proc/modules";
const DEVICE_MOD_PATH: &'static str = "/sys/firmware/devicetree/base/model";

fn main() {
    let mut opts = getopts::Options::new();
    opts.optflag("", "version", "show version information");
    let matches = match opts.parse(env::args().skip(1)) {
        Ok(m) => m,
        Err(f) => {
            eprintln!("{}", f.to_string());
            exit(1);
        }
    };
    if matches.opt_present("version") {
        if !GIT_VERSION.is_empty() {
            println!("Way Cooler {} @ {}", VERSION, GIT_VERSION);
        } else {
            println!("Way Cooler {}", VERSION);
        }
        return
    }
    println!("Launching way-cooler...");

    let sig_action = SigAction::new(SigHandler::Handler(sig_handle),
                                    SaFlags::empty(),
                                    SigSet::empty());
    unsafe {
        signal::sigaction(signal::SIGINT, &sig_action)
            .expect("Could not set SIGINT catcher");
    }

    init_logs();
    log_environment();
    detect_proprietary();
    detect_raspi();
    ensure_good_env();
    // TODO Custom protocols
    //wayland::init_wayland_protocols();
}

/// Formats the log strings properly
fn log_format(record: &log::LogRecord) -> String {
    let color = match record.level() {
        LogLevel::Info => "",
        LogLevel::Trace => "\x1B[37m",
        LogLevel::Debug => "\x1B[44m",
        LogLevel::Warn =>  "\x1B[33m",
        LogLevel::Error => "\x1B[31m",
    };
    let location = record.location();
    let file = location.file();
    let line = location.line();
    let mut module_path = location.module_path();
    if let Some(index) = module_path.find("way_cooler::") {
        let index = index + "way_cooler::".len();
        module_path = &module_path[index..];
    }
    format!("{} {} [{}] \x1B[37m{}:{}\x1B[0m{0} {} \x1B[0m",
            color, record.level(), module_path, file, line, record.args())
}

/// Ensures that the environment is set up correctly. E.g:
/// * XDG_RUNTIME_DIR is set to a directory that exists.
fn ensure_good_env() {
    use std::env::VarError;
    match env::var("XDG_RUNTIME_DIR") {
        Ok(_) => {/* Do nothing, logged in `log_environment` */},
        Err(VarError::NotUnicode(string)) => {
            error!("The value set for XDG_RUNTIME_DIR ({:?}) \
                    is not valid unicode!",
                   string);
            exit(1);
        },
        Err(VarError::NotPresent) => {
            error!("Please set the XDG_RUNTIME_DIR environment variable.");
            error!("e.g export XDG_RUNTIME_DIR=/run/user/1000");
            exit(1);
        }
    }
}

/// Checks the loaded modules, and reports any problematic proprietary ones
fn detect_proprietary() {
    // If DISPLAY is present, we are running embedded
    if env::var("DISPLAY").is_ok() {
        return
    }
    match File::open(Path::new(DRIVER_MOD_PATH)) {
        Ok(file) => {
            let reader = BufReader::new(&file);
            for line in reader.lines() {
                if let Ok(line) = line {
                    if line.contains("nvidia") {
                        error!("Error: Proprietary nvidia graphics drivers are installed, \
                               but they are not compatible with Wayland. \
                               Consider using nouveau drivers for Wayland.");
                        exit(1);
                    }
                }
            }
        },
        Err(err) => {
            warn!("Could not read proprietary modules at \"{}\", because: {:#?}",
                  DRIVER_MOD_PATH, err);
            warn!("If you are running proprietary Nvidia graphics drivers, \
                   Way Cooler will not work for you");
        }
    }
}

/// Checks the loaded modules to ensure vc4 is loaded if we are running on a raspi.
fn detect_raspi() {
    let raspi = match File::open(Path::new(DEVICE_MOD_PATH)) {
        Ok(f) => {
            let reader = BufReader::new(&f);
            let mut raspi = false;
            for line in reader.lines() {
                if let Ok(line) = line {
                    if line.contains("Raspberry Pi") {
                        raspi = true;
                        break;
                    }
                }
            }
            raspi
        },
        Err(_) => {
            return;
        }
    };
    let vc4 = match File::open(Path::new(DRIVER_MOD_PATH)) {
        Ok(f) => {
            let reader = BufReader::new(&f);
            let mut vc4 = false;
            for line in reader.lines() {
                if let Ok(line) = line {
                    if line.contains("vc4") {
                        vc4 = true;
                        break;
                    }
                }
            }
            vc4
        },
        Err(err) => {
            warn!("Could not read file \"{}\", because {:#?}", DRIVER_MOD_PATH, err);
            return;
        }
    };
    if !vc4 && raspi {
        error!("You are running on a Raspberry Pi, but the vc4 module is not loaded!");
        error!("Set 'dtoverlay=vc4-kms-v3d' in /boot/config.txt and reboot!");
    }
}

/// Initializes the logging system.
pub fn init_logs() {
    let mut builder = env_logger::LogBuilder::new();
    builder.format(log_format);
    builder.filter(None, log::LogLevelFilter::Trace);
    if env::var("WAY_COOLER_LOG").is_ok() {
        builder.parse(&env::var("WAY_COOLER_LOG")
                      .expect("WAY_COOLER_LOG not defined"));
    }
    builder.init().expect("Unable to initialize logging!");
    info!("Logger initialized");
}

fn log_environment() {
    for (key, value) in env::vars() {
        info!("{}: {}", key, value);
    }
}

/// Handler for signals
extern "C" fn sig_handle(_: nix::libc::c_int) {
    // TODO FIXME Terminate
    //rustwlc::terminate();
}
<|endoftext|>


<commit_before>extern crate hyper;
extern crate serde;
extern crate serde_json;
extern crate term;
extern crate rand;
extern crate url;

use hyper::Client;
use hyper::client::Response;
use std::io::{BufReader, BufRead};
use std::sync::mpsc::channel;
use std::thread;
use std::process;

include!(concat!(env!("OUT_DIR"), "/main.rs"));

#[derive(Debug)]
struct Record {
    namespace: String,
    pod: String,
    container: String,
    color: term::color::Color,
    text: String,
}

#[derive(Default)]
pub struct Options {
    follow: bool,
    label: Option<String>
}

pub struct Logs {
    options: Options,
}

#[derive(Debug)]
pub enum Error {
    Http,
    Parse,
    Url
}

impl From<url::ParseError> for Error {
    fn from(_: url::ParseError) -> Error {
        Error::Url
    }
}

impl From<hyper::Error> for Error {
    fn from(_: hyper::Error) -> Error {
        Error::Http
    }
}

impl From<serde_json::Error> for Error {
    fn from(_: serde_json::Error) -> Error {
        Error::Parse
    }
}

impl Logs {
    pub fn new(options: Options) -> Logs {
        Logs { options: options }
    }

    pub fn fetch(&self) -> Result<(), Error> {
        let colors = vec![term::color::CYAN,
                          term::color::MAGENTA,
                          term::color::GREEN,
                          term::color::YELLOW,
                          term::color::BRIGHT_BLUE];
        let client = Client::new();
        let pods_endpoint = try!(url::Url::parse("http://127.0.0.1:8001/api/v1/pods"));
        // todo: labelSelector=name=foo
        let response = try!(client.get(pods_endpoint).send());
        let pods = try!(serde_json::from_reader::<Response, PodList>(response));
        let (tx, rx) = channel();
        let mut t = term::stdout().unwrap();
        thread::spawn(move || {
            loop {
                if let Ok(Record { namespace, pod, container, color, text }) = rx.recv() {
                    t.reset().unwrap();
                    t.fg(color).unwrap();
                    write!(t, "{}/{}/{}: ", namespace, pod, container).unwrap();
                    t.reset().unwrap();
                    writeln!(t, ": {}", text).unwrap();
                }
            }
        });
        let mut rng = rand::thread_rng();
        for pod in pods.items {
            let containers = pod.spec.containers.iter().map(|c| c.name.clone()).collect::<Vec<_>>();
            let mut logs_endpoint = try!(url::Url::parse("http://127.0.0.1:8001/api/v1/namespaces/"))
                .join(format!("{}/", pod.metadata.namespace).as_ref()).unwrap()
                .join("pods/").unwrap()
                .join(format!("{}/log", pod.metadata.name).as_ref()).unwrap();
            logs_endpoint.query_pairs_mut().extend_pairs(vec![
                ("container", containers[0].as_str()),
                ("follow", self.options.follow.to_string().as_str())]);
            println!("url {}", logs_endpoint.as_str());
            let reader = BufReader::new(try!(client.get(logs_endpoint).send()));
            let px = tx.clone();
            let color = rand::sample(&mut rng, colors.clone(), 1)[0];
            thread::spawn(move || {
                for l in reader.lines() {
                    if let Ok(text) = l {
                        let _ = px.send(Record {
                            namespace: pod.metadata.namespace.clone(),
                            pod: pod.metadata.name.clone(),
                            container: containers[0].clone(),
                            color: color,
                            text: text,
                        });
                    }
                }
            });
        }
        Ok(())
    }
}

fn main() {
    if let Err(e) = Logs::new(Default::default()).fetch() {
        println!("error fetching logs: {:?}", e);
        process::exit(1);
    }
}
<commit_msg>filter by label selector<commit_after>extern crate hyper;
extern crate serde;
extern crate serde_json;
extern crate term;
extern crate rand;
extern crate url;

use hyper::Client;
use hyper::client::Response;
use std::io::{BufReader, BufRead};
use std::sync::mpsc::channel;
use std::thread;
use std::process;

include!(concat!(env!("OUT_DIR"), "/main.rs"));

#[derive(Debug)]
struct Record {
    namespace: String,
    pod: String,
    container: String,
    color: term::color::Color,
    text: String,
}

#[derive(Default)]
pub struct Options {
    follow: bool,
    label: Option<String>
}

pub struct Logs {
    options: Options,
}

#[derive(Debug)]
pub enum Error {
    Http,
    Parse,
    Url
}

impl From<url::ParseError> for Error {
    fn from(_: url::ParseError) -> Error {
        Error::Url
    }
}

impl From<hyper::Error> for Error {
    fn from(_: hyper::Error) -> Error {
        Error::Http
    }
}

impl From<serde_json::Error> for Error {
    fn from(_: serde_json::Error) -> Error {
        Error::Parse
    }
}

impl Logs {
    pub fn new(options: Options) -> Logs {
        Logs { options: options }
    }

    pub fn fetch(&self) -> Result<(), Error> {
        let colors = vec![term::color::CYAN,
                          term::color::MAGENTA,
                          term::color::GREEN,
                          term::color::YELLOW,
                          term::color::BRIGHT_BLUE];
        let client = Client::new();
        let mut pods_endpoint = try!(url::Url::parse("http://127.0.0.1:8001/api/v1/pods"));
        if let Some(ref label) = self.options.label {
            pods_endpoint.query_pairs_mut().append_pair("labelSelector", label);
        }
        // todo: labelSelector=name=foo
        let response = try!(client.get(pods_endpoint).send());
        let pods = try!(serde_json::from_reader::<Response, PodList>(response));
        let (tx, rx) = channel();
        let mut t = term::stdout().unwrap();
        thread::spawn(move || {
            loop {
                if let Ok(Record { namespace, pod, container, color, text }) = rx.recv() {
                    t.reset().unwrap();
                    t.fg(color).unwrap();
                    write!(t, "{}/{}/{}: ", namespace, pod, container).unwrap();
                    t.reset().unwrap();
                    writeln!(t, ": {}", text).unwrap();
                }
            }
        });
        let mut rng = rand::thread_rng();
        for pod in pods.items {
            let containers = pod.spec.containers.iter().map(|c| c.name.clone()).collect::<Vec<_>>();
            let mut logs_endpoint = try!(url::Url::parse("http://127.0.0.1:8001/api/v1/namespaces/"))
                .join(format!("{}/", pod.metadata.namespace).as_ref()).unwrap()
                .join("pods/").unwrap()
                .join(format!("{}/log", pod.metadata.name).as_ref()).unwrap();
            logs_endpoint.query_pairs_mut().extend_pairs(vec![
                ("container", containers[0].as_str()),
                ("follow", self.options.follow.to_string().as_str())]);
            println!("url {}", logs_endpoint.as_str());
            let reader = BufReader::new(try!(client.get(logs_endpoint).send()));
            let px = tx.clone();
            let color = rand::sample(&mut rng, colors.clone(), 1)[0];
            thread::spawn(move || {
                for l in reader.lines() {
                    if let Ok(text) = l {
                        let _ = px.send(Record {
                            namespace: pod.metadata.namespace.clone(),
                            pod: pod.metadata.name.clone(),
                            container: containers[0].clone(),
                            color: color,
                            text: text,
                        });
                    }
                }
            });
        }
        Ok(())
    }
}

fn main() {
    if let Err(e) = Logs::new(Default::default()).fetch() {
        println!("error fetching logs: {:?}", e);
        process::exit(1);
    }
}
<|endoftext|>


<commit_before>extern crate piston;
extern crate graphics;
extern crate glutin_window;
extern crate opengl_graphics;
extern crate noise;
extern crate num;
extern crate rustc_serialize;

use std::path::Path;

use piston::window::WindowSettings;
use piston::event::{ Event, Events };
use piston::input::{ Button, Input, Key };

use glutin_window::GlutinWindow as Window;
use opengl_graphics::{OpenGL, GlGraphics, Texture};

use graphics::Image;
use graphics::rectangle::square;

// Why pub? Because that makes the docs work.
pub mod mapgen;
pub mod core;
pub mod models;
pub mod renderer;

use core::{Config, View};

use renderer::Renderer;

const TITLE: &'static str = "Open Sea";

fn main() {
  let view = core::GameView::new();

  let gl_context = OpenGL::_2_1;

  let config = Config::load().unwrap();

  let window_settings =
    WindowSettings::new(config.game_title().clone(),
                        config.window_size() ).exit_on_esc(true);
  let window = Window::new(gl_context, window_settings);

  // Create the image object and attach a square Rectangle object inside.
  let image = Image::new().rect(square(100.0, 10.0, 200.0));
  // A texture to use with the image
  let texture = Texture::from_path(Path::new("./assets/stamos.png")).unwrap();

  // This is the object used for drawing
  let mut gl = GlGraphics::new(gl_context);
  let mut renderer = Renderer::new();

  for event in window.events() {
    match event {
      Event::Input(Input::Press(Button::Keyboard(Key::Return))) =>
        println!("Return pressed!"),

      Event::Input(Input::Release(Button::Keyboard(Key::Return))) =>
        println!("Return released!"),

      Event::Render(args) => {
        use graphics::*;
        gl.draw(args.viewport(), |c, gl| {
          clear([1.0, 1.0, 1.0, 1.0], gl);

          view.render(&args, gl, &mut renderer);

          image.draw(&texture, default_draw_state(), c.transform, gl);
        });
      },

      _ => {}
    }
  }
}
<commit_msg>Remove vestigial constant<commit_after>extern crate piston;
extern crate graphics;
extern crate glutin_window;
extern crate opengl_graphics;
extern crate noise;
extern crate num;
extern crate rustc_serialize;

use std::path::Path;

use piston::window::WindowSettings;
use piston::event::{ Event, Events };
use piston::input::{ Button, Input, Key };

use glutin_window::GlutinWindow as Window;
use opengl_graphics::{OpenGL, GlGraphics, Texture};

use graphics::Image;
use graphics::rectangle::square;

// Why pub? Because that makes the docs work.
pub mod mapgen;
pub mod core;
pub mod models;
pub mod renderer;

use core::{Config, View};

use renderer::Renderer;

fn main() {
  let view = core::GameView::new();

  let gl_context = OpenGL::_2_1;

  let config = Config::load().unwrap();

  let window_settings =
    WindowSettings::new(config.game_title().clone(),
                        config.window_size() ).exit_on_esc(true);
  let window = Window::new(gl_context, window_settings);

  // Create the image object and attach a square Rectangle object inside.
  let image = Image::new().rect(square(100.0, 10.0, 200.0));
  // A texture to use with the image
  let texture = Texture::from_path(Path::new("./assets/stamos.png")).unwrap();

  // This is the object used for drawing
  let mut gl = GlGraphics::new(gl_context);
  let mut renderer = Renderer::new();

  for event in window.events() {
    match event {
      Event::Input(Input::Press(Button::Keyboard(Key::Return))) =>
        println!("Return pressed!"),

      Event::Input(Input::Release(Button::Keyboard(Key::Return))) =>
        println!("Return released!"),

      Event::Render(args) => {
        use graphics::*;
        gl.draw(args.viewport(), |c, gl| {
          clear([1.0, 1.0, 1.0, 1.0], gl);

          view.render(&args, gl, &mut renderer);

          image.draw(&texture, default_draw_state(), c.transform, gl);
        });
      },

      _ => {}
    }
  }
}
<|endoftext|>


<commit_before>extern crate gmp;
extern crate time;
use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use asm::util::*;
use std::io;
use std::io::Write;
use std::str::FromStr;
use asm::assembler::Assembler;
use asm::environment::Environment;
use std::env;
use std::collections::HashMap;

mod asm;

fn add_external_calls(asm:&mut Assembler) {
	asm.add_external_call("printnum", |v,e,_| {
		print!("{}", boolvec_to_bignum(v.get_boolvec(e).as_slice()));
		io::stdout().flush().ok().expect("Could not flush stdout");
	});
	asm.add_external_call("print", |v,e,_| {
		let mut chars:Vec<u8> = vec![];
		let boolvec = v.get_boolvec(e);
		let val = boolvec.as_slice();
		for i in 0..(val.len()/8) {
			let nums = &val[i*8..(i+1)*8];
			let c = boolvec_to_u8(nums);
			if c == 0 {
				break;
			}
			chars.push(c);
		}
		let s = String::from_utf8_lossy(chars.as_slice()).to_string();
		print!("{}", s);
		io::stdout().flush().ok().expect("Could not flush stdout");
	});
	asm.add_external_call("valid", |v,e,_a| {
		let pos = v.get_ptr_position(e);
		let num = match e.validity {
			true => gmp::mpz::Mpz::one(),
			false => gmp::mpz::Mpz::zero()
		};
		let size = v.get_size(e);
		e.set_bits_bignum(&num, pos, size);
	});
	asm.add_external_call("prompt", |_v,e,_a|{
		let mut input = String::new();
		io::stdin().read_line(&mut input).expect("Invalid Input!");
		e.input_string = "".to_string();

		for line in input.lines() {
			e.input_string.push_str(line.as_ref());
		}
	});
	asm.add_external_call("inputnumlen", |v,e,_|{
		e.validity = true;
		let num = match gmp::mpz::Mpz::from_str(e.input_string.as_ref()) {
			Ok(val) => val,
			Err(_) => {
				e.validity = false;
				gmp::mpz::Mpz::zero()
			}
		};
		let num_size = num.bit_length();
		let pos = v.get_ptr_position(e);
		let size = v.get_ptr_size(e);
		e.set_bits_usize(num_size, pos, size);
	});
	asm.add_external_call("inputlen", |v,e,_|{
		let len_bits = e.input_string.len() * 8;
		let pos = v.get_ptr_position(e);
		let size = v.get_size(e);
		e.set_bits_usize(len_bits, pos, size);
	});
	asm.add_external_call("input", |v,e,_|{
		let boolvec = str_to_boolvec(e.input_string.as_ref());
		let pos = v.get_ptr_position(e);
		let size = v.get_size(e);
		e.set_bits_boolvec(boolvec.as_slice(), pos, size);
	});
	asm.add_external_call("inputnum", |v,e,_|{
		e.validity = true;
		let num = match gmp::mpz::Mpz::from_str(e.input_string.as_ref()) {
			Ok(val) => val,
			Err(_) => {
				e.validity = false;
				gmp::mpz::Mpz::zero()
			}
		};
		let pos = v.get_ptr_position(e);
		let size = v.get_size(e);
		e.set_bits_bignum(&num, pos, size);
	});

	asm.add_external_call("random", move |v,e,_|{
		let val = v.get_bignum(e);
		let result = e.randstate.urandom(&val);
		let pos = v.get_ptr_position(e);
		let size = v.get_ptr_size(e);
		e.set_bits_bignum(&result, pos, size);
	});
}

fn load_text(asm: &mut Assembler, code: &str) {
	let mut linenum = 0;
	for line in code.lines() {
		for s in line.split(';') {
			linenum += 1;
			asm.parse_line(&s.to_string(), linenum, None);
		}
	}
}

fn load_file(asm: &mut Assembler, file_name:&str) {
	let file = File::open(file_name).unwrap();
	let buffer = BufReader::new(&file);
	let mut linenum = 0;
	for line in buffer.lines() {
		let l:String = line.unwrap();
		linenum += 1;
		asm.parse_line(&l, linenum, Some(file_name.to_string()));
	}
}

enum Req {
	Yes,
	Maybe,
	No
}

struct ArgType {
	name:String,
	short:Option<String>,
	arg:Req
}

fn main() {
	let valid_args = vec![
		ArgType{name:"help".to_string(), short:Some("h".to_string()), arg:Req::No},
		ArgType{name:"file".to_string(), short:Some("h".to_string()), arg:Req::Yes},
		ArgType{name:"text".to_string(), short:Some("h".to_string()), arg:Req::Yes},
		ArgType{name:"print-stack".to_string(),  short:Some("s".to_string()), arg:Req::Maybe},
		ArgType{name:"print-parsed".to_string(), short:Some("p".to_string()), arg:Req::No},
	];

	let mut args:HashMap<String, String> = HashMap::new();

	let mut current_arg_name:String = "file".to_string();

	let mut is_first = true;
	for element in env::args().collect::<Vec<String>>() {
		if is_first {
			is_first = false;
			continue;
		}
		//argument
		if element.len() >= 2 && &element[0..2] == "--" {
			let element = &element[2..];
			let does_contain = valid_args.iter().filter(
				|a| a.name == element
			).count() != 0;

			if !does_contain {
				panic!("No such argument of name '{}'!", element);
			}

			current_arg_name = element.to_string();

			args.insert(current_arg_name.clone(), "".to_string());

		//shortened argument
		} else if element.len() >= 1 && &element[0..1] == "-" {
			let element = &element[1..];
			let mut arg_name = "".to_string();
			for arg in &valid_args {
				if arg.short == Some(element.to_string()) {
					arg_name = arg.name.clone();
					break;
				}
			}

			if arg_name == "" {
				panic!("No such argument of name '{}'!", element);
			} else {
				current_arg_name = arg_name;
			}

			args.insert(current_arg_name.clone(), "".to_string());

		//not an argument
		} else {
			println!("{}", element);
			let arg = args.get_mut(&current_arg_name).expect("No argument");
			arg.push_str(element.as_ref());
		}
	}

	let do_print_parsed = args.contains_key("print-parsed");
	let do_stack_print = args.contains_key("print-stack");

	let mut env = Environment::new();
	let mut asm = Assembler::new(do_print_parsed);
	add_external_calls(&mut asm);
	let mut do_run = false;

	if args.contains_key("help") {
		println!("{}",
"Welcome to Bit Assembly!
For help on how to write Bit Assembly, refer to the 'doc.md' file.

Usage:
    bit-asm --file {file name}.asm
    bit-asm --text {assembly}");

	} else if args.contains_key("file") {
		load_file(&mut asm, args.get("file").expect("This shouldnt happen"));
		do_run = true;

	} else if args.contains_key("text") {
		load_text(&mut asm, args.get("text").expect("This shouldnt happen"));
		do_run = true;

	} else {
		println!("type 'bit-asm --help' for help on how to use bit assembly");
	}
	if do_run {
		asm.run(&mut env);
		if do_stack_print {
			let bits = usize::from_str(args.get("print-stack").unwrap_or(&"64".to_string()))
				.expect("print-stack argument is not valid!");
			env.print_bytes(bits);
		}
	}
}
<commit_msg>default argument for --print-stack now works properly<commit_after>extern crate gmp;
extern crate time;
use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use asm::util::*;
use std::io;
use std::io::Write;
use std::str::FromStr;
use asm::assembler::Assembler;
use asm::environment::Environment;
use std::env;
use std::collections::HashMap;

mod asm;

fn add_external_calls(asm:&mut Assembler) {
	asm.add_external_call("printnum", |v,e,_| {
		print!("{}", boolvec_to_bignum(v.get_boolvec(e).as_slice()));
		io::stdout().flush().ok().expect("Could not flush stdout");
	});
	asm.add_external_call("print", |v,e,_| {
		let mut chars:Vec<u8> = vec![];
		let boolvec = v.get_boolvec(e);
		let val = boolvec.as_slice();
		for i in 0..(val.len()/8) {
			let nums = &val[i*8..(i+1)*8];
			let c = boolvec_to_u8(nums);
			if c == 0 {
				break;
			}
			chars.push(c);
		}
		let s = String::from_utf8_lossy(chars.as_slice()).to_string();
		print!("{}", s);
		io::stdout().flush().ok().expect("Could not flush stdout");
	});
	asm.add_external_call("valid", |v,e,_a| {
		let pos = v.get_ptr_position(e);
		let num = match e.validity {
			true => gmp::mpz::Mpz::one(),
			false => gmp::mpz::Mpz::zero()
		};
		let size = v.get_size(e);
		e.set_bits_bignum(&num, pos, size);
	});
	asm.add_external_call("prompt", |_v,e,_a|{
		let mut input = String::new();
		io::stdin().read_line(&mut input).expect("Invalid Input!");
		e.input_string = "".to_string();

		for line in input.lines() {
			e.input_string.push_str(line.as_ref());
		}
	});
	asm.add_external_call("inputnumlen", |v,e,_|{
		e.validity = true;
		let num = match gmp::mpz::Mpz::from_str(e.input_string.as_ref()) {
			Ok(val) => val,
			Err(_) => {
				e.validity = false;
				gmp::mpz::Mpz::zero()
			}
		};
		let num_size = num.bit_length();
		let pos = v.get_ptr_position(e);
		let size = v.get_ptr_size(e);
		e.set_bits_usize(num_size, pos, size);
	});
	asm.add_external_call("inputlen", |v,e,_|{
		let len_bits = e.input_string.len() * 8;
		let pos = v.get_ptr_position(e);
		let size = v.get_size(e);
		e.set_bits_usize(len_bits, pos, size);
	});
	asm.add_external_call("input", |v,e,_|{
		let boolvec = str_to_boolvec(e.input_string.as_ref());
		let pos = v.get_ptr_position(e);
		let size = v.get_size(e);
		e.set_bits_boolvec(boolvec.as_slice(), pos, size);
	});
	asm.add_external_call("inputnum", |v,e,_|{
		e.validity = true;
		let num = match gmp::mpz::Mpz::from_str(e.input_string.as_ref()) {
			Ok(val) => val,
			Err(_) => {
				e.validity = false;
				gmp::mpz::Mpz::zero()
			}
		};
		let pos = v.get_ptr_position(e);
		let size = v.get_size(e);
		e.set_bits_bignum(&num, pos, size);
	});

	asm.add_external_call("random", move |v,e,_|{
		let val = v.get_bignum(e);
		let result = e.randstate.urandom(&val);
		let pos = v.get_ptr_position(e);
		let size = v.get_ptr_size(e);
		e.set_bits_bignum(&result, pos, size);
	});
}

fn load_text(asm: &mut Assembler, code: &str) {
	let mut linenum = 0;
	for line in code.lines() {
		for s in line.split(';') {
			linenum += 1;
			asm.parse_line(&s.to_string(), linenum, None);
		}
	}
}

fn load_file(asm: &mut Assembler, file_name:&str) {
	let file = File::open(file_name).unwrap();
	let buffer = BufReader::new(&file);
	let mut linenum = 0;
	for line in buffer.lines() {
		let l:String = line.unwrap();
		linenum += 1;
		asm.parse_line(&l, linenum, Some(file_name.to_string()));
	}
}

enum Req {
	Yes,
	Maybe,
	No
}

struct ArgType {
	name:String,
	short:Option<String>,
	arg:Req
}

fn main() {
	let valid_args = vec![
		ArgType{name:"help".to_string(), short:Some("h".to_string()), arg:Req::No},
		ArgType{name:"file".to_string(), short:Some("h".to_string()), arg:Req::Yes},
		ArgType{name:"text".to_string(), short:Some("h".to_string()), arg:Req::Yes},
		ArgType{name:"print-stack".to_string(),  short:Some("s".to_string()), arg:Req::Maybe},
		ArgType{name:"print-parsed".to_string(), short:Some("p".to_string()), arg:Req::No},
	];

	let mut args:HashMap<String, String> = HashMap::new();

	let mut current_arg_name:String = "file".to_string();

	let mut is_first = true;
	for element in env::args().collect::<Vec<String>>() {
		if is_first {
			is_first = false;
			continue;
		}
		//argument
		if element.len() >= 2 && &element[0..2] == "--" {
			let element = &element[2..];
			let does_contain = valid_args.iter().filter(
				|a| a.name == element
			).count() != 0;

			if !does_contain {
				panic!("No such argument of name '{}'!", element);
			}

			current_arg_name = element.to_string();

			args.insert(current_arg_name.clone(), "".to_string());

		//shortened argument
		} else if element.len() >= 1 && &element[0..1] == "-" {
			let element = &element[1..];
			let mut arg_name = "".to_string();
			for arg in &valid_args {
				if arg.short == Some(element.to_string()) {
					arg_name = arg.name.clone();
					break;
				}
			}

			if arg_name == "" {
				panic!("No such argument of name '{}'!", element);
			} else {
				current_arg_name = arg_name;
			}

			args.insert(current_arg_name.clone(), "".to_string());

		//not an argument
		} else {
			println!("{}", element);
			let arg = args.get_mut(&current_arg_name).expect("No argument");
			arg.push_str(element.as_ref());
		}
	}

	let do_print_parsed = args.contains_key("print-parsed");
	let do_stack_print = args.contains_key("print-stack");

	let mut env = Environment::new();
	let mut asm = Assembler::new(do_print_parsed);
	add_external_calls(&mut asm);
	let mut do_run = false;

	if args.contains_key("help") {
		println!("{}",
"Welcome to Bit Assembly!
For help on how to write Bit Assembly, refer to the 'doc.md' file.

Usage:
    bit-asm --file {file name}.asm
    bit-asm --text {assembly}");

	} else if args.contains_key("file") {
		load_file(&mut asm, args.get("file").expect("This shouldnt happen"));
		do_run = true;

	} else if args.contains_key("text") {
		load_text(&mut asm, args.get("text").expect("This shouldnt happen"));
		do_run = true;

	} else {
		println!("type 'bit-asm --help' for help on how to use bit assembly");
	}
	if do_run {
		asm.run(&mut env);
		if do_stack_print {
			let bits = usize::from_str(
				match args.get("print-stack").unwrap_or(&"64".to_string()).as_ref() {
					"" => "64",
					other => other
				}
			)
				.expect("print-stack argument is not valid!");
			env.print_bytes(bits);
		}
	}
}
<|endoftext|>


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

#[macro_use]
extern crate lazy_static;

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

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

    use std::env;
    use std::path::Path;
    use std::process;

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

#[macro_use]
extern crate lazy_static;

extern crate libc;

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

macro_rules! syslog {
    ($msg:expr) => (
        unsafe {
            libc::openlog("sectora".as_ptr() as *const i8, libc::LOG_PID, libc::LOG_AUTH);
            libc::syslog(libc::LOG_NOTICE, $msg.as_ptr() as *const i8);
            libc::closelog();
        }
    )
}

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

    use std::env;
    use std::path::Path;
    use std::process;

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


<commit_before>// fs.rs
use std::env; // env::home_dir()
use std::fs; // fs::read_dir()
//use std::path::Path;
use std::path::PathBuf;

fn main() {
   //let mut idg_dir_path = PathBuf::from("~/Files/Doom/idgames");
   let mut idg_dir = PathBuf::new();
   match env::home_dir() {
      //Some(idg_dir) => println!("{}", idg_dir.display()),
      Some(home_dir) => idg_dir = home_dir,
      None => println!("Can't obtain home directory path!"),
   }

   idg_dir.push("Files");
   idg_dir.push("Doom");
   idg_dir.push("idgames");

   println!("Updated іdgames/ path: {}", idg_dir.display());
   // read the contents of idg_dir/
   match fs::read_dir(idg_dir) {
      Err(why) => println!("! {:?}", why.kind()),
      Ok(paths) => for path in paths {
         println!("> {:?}", path.unwrap().path());
      }
   }
}
<commit_msg>src/main.rs: added comments explaining what the bits are/do<commit_after>// fs.rs
use std::env; // env::home_dir()
use std::fs; // fs::read_dir()
//use std::path::Path;
use std::path::PathBuf;

fn main() {
   //let mut idg_dir_path = PathBuf::from("~/Files/Doom/idgames");
   // create an empty PathBuf
   let mut idg_dir = PathBuf::new();
   // call `home_dir()` and act on what it returns
   match env::home_dir() {
      //Some(idg_dir) => println!("{}", idg_dir.display()),
      // home_dir() returned something
      Some(home_dir) => idg_dir = home_dir,
      // home_dir() returned nothing
      None => println!("Can't obtain home directory path!"),
   }

   // append more directories on to idg_dir
   idg_dir.push("Files");
   idg_dir.push("Doom");
   idg_dir.push("idgames");

   // try and read the contents of idg_dir/
   match fs::read_dir(idg_dir) {
      // nope, can't read for some reason
      Err(why) => println!("! {:?}", why.kind()),
      // yep, can read contents of idg_dir, see what items are there
      Ok(items) => for item in items {
         println!("- {:?}", item.unwrap().path());
      }
   }
}
<|endoftext|>


<commit_before>fn main() {
    println!("Hello, world!");
}
<commit_msg>Started loading ROM's<commit_after>use std::env;
use std::fs;
use std::io::Read;
use std::path::Path;

fn main() {
    let pif_file_name = env::args().nth(1).unwrap();
    let rom_file_name = env::args().nth(2).unwrap();

    let pif = read_bin(pif_file_name);
    let rom = read_bin(rom_file_name);
}

fn read_bin<P: AsRef<Path>>(path: P) -> Vec<u8> {
    let mut file = fs::File::open(path).unwrap();
    let mut file_buf = Vec::new();
    file.read_to_end(&mut file_buf).unwrap();
    file_buf
}
<|endoftext|>


<commit_before>extern crate cairo_sys;
extern crate cairo;
extern crate chrono;
extern crate futures;
extern crate mio;
extern crate pango;
extern crate pangocairo;
extern crate tokio_core;
extern crate tokio_timer;
extern crate xcb_util;
extern crate xcb;

use std::rc::Rc;

use cairo::{Context, Surface, XCBConnection, XCBDrawable, XCBSurface, XCBVisualType};
use mio::{Events, Ready, Poll, PollOpt, Token};
use mio::unix::EventedFd;
use pango::LayoutExt;
use pangocairo::CairoContextExt;
use xcb::ffi::*;

mod text;
use text::*;
mod widgets;
use widgets::*;
mod window;
use window::*;

fn main() {
    let (conn, screen_idx) = xcb::Connection::connect_with_xlib_display().unwrap();
    let conn = Rc::new(conn);

    let w = Window::new(conn.clone(), screen_idx as usize);

    use tokio_core::reactor::{Core, Handle, PollEvented};

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

    use futures::future;
    use futures::{Async, Future, Poll, Stream};

    struct XcbEventStream<'a> {
        conn: Rc<xcb::Connection>,
        poll: PollEvented<EventedFd<'a>>,
        would_block: bool,
    };

    impl<'a> XcbEventStream<'a> {
        fn new(conn: Rc<xcb::Connection>,
               conn_fd: &'a std::os::unix::io::RawFd,
               handle: &Handle)
               -> XcbEventStream<'a> {
            // XXX Lifetime of the connection?
            XcbEventStream {
                conn: conn,
                poll: PollEvented::new(EventedFd(conn_fd), &handle).unwrap(),
                would_block: true,
            }
        }
    }

    impl<'a> Stream for XcbEventStream<'a> {
        type Item = xcb::GenericEvent;
        type Error = ();

        fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
            if self.would_block {
                match self.poll.poll_read() {
                    Async::Ready(()) => self.would_block = false,
                    Async::NotReady => return Ok(Async::NotReady),
                }
            }

            match self.conn.poll_for_event() {
                Some(event) => Ok(Async::Ready(Some(event))),
                None => {
                    self.would_block = true;
                    self.poll.need_read();
                    Ok(Async::NotReady)
                }
            }
        }
    }

    let inactive_attr = Attributes {
        font: pango::FontDescription::from_string("Envy Code R 27"),
        fg_color: Color::white(),
        bg_color: None,
        padding: Padding::new(10.0, 10.0, 5.0, 5.0),
    };
    let active_attr = inactive_attr.with_bg_color(Some(Color::blue()));

    let conn_fd = unsafe { xcb::ffi::base::xcb_get_file_descriptor(conn.get_raw_conn()) };
    let stream = XcbEventStream::new(conn.clone(), &conn_fd, &handle);

    let widgets: Vec<Box<Widget>> = vec![
        Box::new(Pager::new(active_attr, inactive_attr.clone())) as Box<Widget>,
        Box::new(ActiveWindowTitle::new(inactive_attr.clone())) as Box<Widget>,
        Box::new(Clock::new(inactive_attr.clone())) as Box<Widget>,
    ];

    use std::rc::Rc;

    let widget_list = widgets::WidgetList::new(widgets);

    struct MainLoop<'a> {
        xcb_stream: XcbEventStream<'a>,
        widget_list: WidgetList,
        window: Window,
    }

    impl<'a> Future for MainLoop<'a> {
        type Item = ();
        type Error = ();

        fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
            match self.widget_list.poll() {
                Ok(Async::Ready(texts)) => self.window.expose(self.widget_list.texts()),
                Ok(Async::NotReady) => {},
                Err(e) => return Err(e),
            }
            match self.xcb_stream.poll() {
                Ok(Async::Ready(event)) => {
                    if let Some(event) = event {
                        let r = event.response_type() & !0x80;
                        match r {
                            xcb::EXPOSE => self.window.expose(self.widget_list.texts()),
                            _ => {}
                        }
                    }
                },
                Ok(Async::NotReady) => {},
                Err(e) => return Err(e),
            }
            Ok(Async::NotReady)
        }
    }

    let fut = MainLoop {
        xcb_stream: stream,
        widget_list: widget_list,
        window: w,
    };

    core.run(fut);
}
<commit_msg>Move `use` statements to top and sort.<commit_after>extern crate cairo_sys;
extern crate cairo;
extern crate chrono;
extern crate futures;
extern crate mio;
extern crate pango;
extern crate pangocairo;
extern crate tokio_core;
extern crate tokio_timer;
extern crate xcb_util;
extern crate xcb;

use std::rc::Rc;

use cairo::{Context, Surface, XCBConnection, XCBDrawable, XCBSurface, XCBVisualType};
use futures::{future, Async, Future, Poll, Stream};
use mio::unix::EventedFd;
use pango::LayoutExt;
use pangocairo::CairoContextExt;
use xcb::ffi::*;

mod text;
use text::*;
mod widgets;
use widgets::*;
mod window;
use window::*;

fn main() {
    let (conn, screen_idx) = xcb::Connection::connect_with_xlib_display().unwrap();
    let conn = Rc::new(conn);

    let w = Window::new(conn.clone(), screen_idx as usize);

    use tokio_core::reactor::{Core, Handle, PollEvented};

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

    struct XcbEventStream<'a> {
        conn: Rc<xcb::Connection>,
        poll: PollEvented<EventedFd<'a>>,
        would_block: bool,
    };

    impl<'a> XcbEventStream<'a> {
        fn new(conn: Rc<xcb::Connection>,
               conn_fd: &'a std::os::unix::io::RawFd,
               handle: &Handle)
               -> XcbEventStream<'a> {
            // XXX Lifetime of the connection?
            XcbEventStream {
                conn: conn,
                poll: PollEvented::new(EventedFd(conn_fd), &handle).unwrap(),
                would_block: true,
            }
        }
    }

    impl<'a> Stream for XcbEventStream<'a> {
        type Item = xcb::GenericEvent;
        type Error = ();

        fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
            if self.would_block {
                match self.poll.poll_read() {
                    Async::Ready(()) => self.would_block = false,
                    Async::NotReady => return Ok(Async::NotReady),
                }
            }

            match self.conn.poll_for_event() {
                Some(event) => Ok(Async::Ready(Some(event))),
                None => {
                    self.would_block = true;
                    self.poll.need_read();
                    Ok(Async::NotReady)
                }
            }
        }
    }

    let inactive_attr = Attributes {
        font: pango::FontDescription::from_string("Envy Code R 27"),
        fg_color: Color::white(),
        bg_color: None,
        padding: Padding::new(10.0, 10.0, 5.0, 5.0),
    };
    let active_attr = inactive_attr.with_bg_color(Some(Color::blue()));

    let conn_fd = unsafe { xcb::ffi::base::xcb_get_file_descriptor(conn.get_raw_conn()) };
    let stream = XcbEventStream::new(conn.clone(), &conn_fd, &handle);

    let widgets: Vec<Box<Widget>> = vec![
        Box::new(Pager::new(active_attr, inactive_attr.clone())) as Box<Widget>,
        Box::new(ActiveWindowTitle::new(inactive_attr.clone())) as Box<Widget>,
        Box::new(Clock::new(inactive_attr.clone())) as Box<Widget>,
    ];

    let widget_list = widgets::WidgetList::new(widgets);

    struct MainLoop<'a> {
        xcb_stream: XcbEventStream<'a>,
        widget_list: WidgetList,
        window: Window,
    }

    impl<'a> Future for MainLoop<'a> {
        type Item = ();
        type Error = ();

        fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
            match self.widget_list.poll() {
                Ok(Async::Ready(texts)) => self.window.expose(self.widget_list.texts()),
                Ok(Async::NotReady) => {},
                Err(e) => return Err(e),
            }
            match self.xcb_stream.poll() {
                Ok(Async::Ready(event)) => {
                    if let Some(event) = event {
                        let r = event.response_type() & !0x80;
                        match r {
                            xcb::EXPOSE => self.window.expose(self.widget_list.texts()),
                            _ => {}
                        }
                    }
                },
                Ok(Async::NotReady) => {},
                Err(e) => return Err(e),
            }
            Ok(Async::NotReady)
        }
    }

    let fut = MainLoop {
        xcb_stream: stream,
        widget_list: widget_list,
        window: w,
    };

    core.run(fut);
}
<|endoftext|>


<commit_before>mod state;
mod matcher;
mod util;
extern crate regex;
extern crate rand;
extern crate clap;
use clap::{App, Arg};
fn main() {
    let args = App::new("Befunge")
        .version("0.1.0")
        .author("Oreoluwa Babarinsa <oreoluwa@babarinsa.me>")
        .about("Interprets Befunge-9x programs")
        .arg(Arg::with_name("SOURCE")
             .help("the befunge source file")
             .required(true)
             .index(1))
        .get_matches();

    let fname = args.value_of("SOURCE").unwrap();
    match state::State::new_from_file(fname).as_mut() {
        Ok(state) => state.run(),
        Err(e) => eprintln!("Befunge error : {}", e),
    }

}
<commit_msg>Fixing Author Name<commit_after>mod state;
mod matcher;
mod util;
extern crate regex;
extern crate rand;
extern crate clap;
use clap::{App, Arg};
fn main() {
    let args = App::new("Befunge")
        .version("0.1.0")
        .author("Aurelia Augusta <aurelia@aeva.dev>")
        .about("Interprets Befunge-9x programs")
        .arg(Arg::with_name("SOURCE")
             .help("the befunge source file")
             .required(true)
             .index(1))
        .get_matches();

    let fname = args.value_of("SOURCE").unwrap();
    match state::State::new_from_file(fname).as_mut() {
        Ok(state) => state.run(),
        Err(e) => eprintln!("Befunge error : {}", e),
    }

}
<|endoftext|>