<commit_before>#![deny(
    missing_debug_implementations,
    trivial_numeric_casts,
    unstable_features,
    unused_import_braces,
    unused_qualifications
)]

extern crate clap;
extern crate notify;
extern crate rouille;
extern crate tempdir;
extern crate reqwest;
extern crate pbr;
extern crate app_dirs;
extern crate libflate;
extern crate tar;
extern crate sha1;
extern crate sha2;
extern crate digest;
extern crate toml;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate cargo_shim;
extern crate handlebars;
extern crate unicode_categories;
extern crate ordermap;

extern crate parity_wasm;
#[macro_use]
extern crate log;
extern crate rustc_demangle;

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

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

use cargo_shim::*;

#[macro_use]
mod utils;
mod config;
mod package;
mod build;
mod error;
mod wasm;
mod wasm_gc;
mod wasm_inline_js;
mod wasm_export_main;
mod wasm_export_table;
mod wasm_hook_grow;
mod wasm_runtime;
mod wasm_context;
mod wasm_intrinsics;
mod emscripten;
mod cmd_build;
mod cmd_start;
mod cmd_test;

fn main() {
    let args = {
        // To allow running both as 'cargo-web' and as 'cargo web'.
        let mut args = env::args();
        let mut filtered_args = Vec::new();
        filtered_args.push( args.next().unwrap() );

        match args.next() {
            None => {},
            #[cfg(any(unix))]
            Some( ref arg ) if filtered_args[ 0 ].ends_with( "cargo-web" ) && arg == "web" => {},
            #[cfg(any(windows))]
            Some( ref arg ) if filtered_args[ 0 ].ends_with( "cargo-web.exe" ) && arg == "web" => {},
            Some( arg ) => filtered_args.push( arg )
        }

        filtered_args.extend( args );
        filtered_args
    };

    let matches = App::new( "cargo-web" )
        .version( env!( "CARGO_PKG_VERSION" ) )
        .setting( AppSettings::SubcommandRequiredElseHelp )
        .setting( AppSettings::VersionlessSubcommands )
        .subcommand(
            SubCommand::with_name( "build" )
                .about( "Compile a local package and all of its dependencies" )
                .arg(
                    Arg::with_name( "use-system-emscripten" )
                        .long( "use-system-emscripten" )
                        .help( "Won't try to download Emscripten; will always use the system one" )
                )
                .arg(
                    Arg::with_name( "release" )
                        .long( "release" )
                        .help( "Build artifacts in release mode, with optimizations" )
                )
                .arg(
                    Arg::with_name( "target-asmjs-emscripten" )
                        .long( "target-asmjs-emscripten" )
                        .help( "Generate asmjs through Emscripten (default)" )
                        .overrides_with_all( &["target-webasm-emscripten", "target-webasm"] )
                )
                .arg(
                    Arg::with_name( "target-webasm-emscripten" )
                        .long( "target-webasm-emscripten" )
                        .help( "Generate webasm through Emscripten" )
                        .overrides_with_all( &["target-asmjs-emscripten", "target-webasm"] )
                )
                .arg(
                    Arg::with_name( "target-webasm" )
                        .long( "target-webasm" )
                        .help( "Generates webasm through Rust's native backend (HIGHLY EXPERIMENTAL!)" )
                        .overrides_with_all( &["target-asmjs-emscripten", "target-webasm-emscripten"] )
                )
                .arg(
                    Arg::with_name( "package" )
                        .short( "p" )
                        .long( "package" )
                        .help( "Package to build" )
                        .value_name( "NAME" )
                        .takes_value( true )
                )
                .arg(
                    Arg::with_name( "lib" )
                        .long( "lib" )
                        .help( "Build only this package's library" )
                )
                .arg(
                    Arg::with_name( "bin" )
                        .long( "bin" )
                        .help( "Build only the specified binary" )
                        .value_name( "NAME" )
                        .takes_value( true )
                )
                .arg(
                    Arg::with_name( "example" )
                        .long( "example" )
                        .help( "Build only the specified example" )
                        .value_name( "NAME" )
                        .takes_value( true )
                )
                .arg(
                    Arg::with_name( "test" )
                        .long( "test" )
                        .help( "Build only the specified test target" )
                        .value_name( "NAME" )
                        .takes_value( true )
                )
                .arg(
                    Arg::with_name( "bench" )
                        .long( "bench" )
                        .help( "Build only the specified benchmark target" )
                        .value_name( "NAME" )
                        .takes_value( true )
                )
        )
        .subcommand(
            SubCommand::with_name( "test" )
                .about( "Compiles and runs tests" )
                .arg(
                    Arg::with_name( "use-system-emscripten" )
                        .long( "use-system-emscripten" )
                        .help( "Won't try to download Emscripten; will always use the system one" )
                )
                .arg(
                    Arg::with_name( "no-run" )
                        .long( "no-run" )
                        .help( "Compile, but don't run tests" )
                )
                .arg(
                    Arg::with_name( "target-asmjs-emscripten" )
                        .long( "target-asmjs-emscripten" )
                        .help( "Generate asmjs through Emscripten (default)" )
                        .overrides_with_all( &["target-webasm-emscripten", "target-webasm"] )
                )
                .arg(
                    Arg::with_name( "target-webasm-emscripten" )
                        .long( "target-webasm-emscripten" )
                        .help( "Generate webasm through Emscripten" )
                        .overrides_with_all( &["target-asmjs-emscripten", "target-webasm"] )
                )
                .arg(
                    Arg::with_name( "target-webasm" )
                        .long( "target-webasm" )
                        .help( "Generates webasm through Rust's native backend (HIGHLY EXPERIMENTAL!)" )
                        .overrides_with_all( &["target-asmjs-emscripten", "target-webasm-emscripten"] )
                )
                .arg(
                    Arg::with_name( "package" )
                        .short( "p" )
                        .long( "package" )
                        .help( "Package to build" )
                        .value_name( "NAME" )
                        .takes_value( true )
                )
                .arg(
                    Arg::with_name( "release" )
                        .long( "release" )
                        .help( "Build artifacts in release mode, with optimizations" )
                )
                .arg(
                    Arg::with_name( "nodejs" )
                        .long( "nodejs" )
                        .help( "Uses Node.js to run the tests" )
                )
                .arg(
                    Arg::with_name( "passthrough" )
                        .help( "-- followed by anything will pass the arguments to the test runner")
                        .multiple( true )
                        .takes_value( true )
                        .last( true )
                )
        )
        .subcommand(
            SubCommand::with_name( "start" )
                .about( "Runs an embedded web server serving the built project" )
                .arg(
                    Arg::with_name( "use-system-emscripten" )
                        .long( "use-system-emscripten" )
                        .help( "Won't try to download Emscripten; will always use the system one" )
                )
                .arg(
                    Arg::with_name( "release" )
                        .long( "release" )
                        .help( "Build artifacts in release mode, with optimizations" )
                )
                .arg(
                    Arg::with_name( "target-asmjs-emscripten" )
                        .long( "target-asmjs-emscripten" )
                        .help( "Generate asmjs through Emscripten (default)" )
                        .overrides_with_all( &["target-webasm-emscripten", "target-webasm"] )
                )
                .arg(
                    Arg::with_name( "target-webasm-emscripten" )
                        .long( "target-webasm-emscripten" )
                        .help( "Generate webasm through Emscripten" )
                        .overrides_with_all( &["target-asmjs-emscripten", "target-webasm"] )
                )
                .arg(
                    Arg::with_name( "target-webasm" )
                        .long( "target-webasm" )
                        .help( "Generates webasm through Rust's native backend (HIGHLY EXPERIMENTAL!)" )
                        .overrides_with_all( &["target-asmjs-emscripten", "target-webasm-emscripten"] )
                )
                .arg(
                    Arg::with_name( "package" )
                        .short( "p" )
                        .long( "package" )
                        .help( "Package to build" )
                        .value_name( "NAME" )
                        .takes_value( true )
                )
                .arg(
                    Arg::with_name( "bin" )
                        .long( "bin" )
                        .help( "Build only the specified binary" )
                        .value_name( "NAME" )
                        .takes_value( true )
                )
                .arg(
                    Arg::with_name( "example" )
                        .long( "example" )
                        .help( "Serves the specified example" )
                        .value_name( "NAME" )
                        .takes_value( true )
                )
                .arg(
                    Arg::with_name( "test" )
                        .long( "test" )
                        .help( "Build only the specified test target" )
                        .value_name( "NAME" )
                        .takes_value( true )
                )
                .arg(
                    Arg::with_name( "bench" )
                        .long( "bench" )
                        .help( "Build only the specified benchmark target" )
                        .value_name( "NAME" )
                        .takes_value( true )
                ).arg(
                    Arg::with_name( "host" )
                        .long( "host" )
                        .help( "Bind the server to this address, default `localhost`")
                        .value_name( "HOST" )
                        .takes_value( true )
                ).arg(
                    Arg::with_name( "port" )
                        .long( "port" )
                        .help( "Bind the server to this port, default 8000" )
                        .value_name( "PORT" )
                        .takes_value( true )
                )
        )
        .get_matches_from( args );

    let project = CargoProject::new( None );
    let result = if let Some( matches ) = matches.subcommand_matches( "build" ) {
        cmd_build::command_build( matches, &project )
    } else if let Some( matches ) = matches.subcommand_matches( "test" ) {
        cmd_test::command_test( matches, &project )
    } else if let Some( matches ) = matches.subcommand_matches( "start" ) {
        cmd_start::command_start( matches, &project )
    } else {
        return;
    };

    match result {
        Ok( _ ) => {},
        Err( error ) => {
            println_err!( "error: {}", error );
            exit( 101 );
        }
    }
}
<commit_msg>Deduplicate shared build arguments<commit_after>#![deny(
    missing_debug_implementations,
    trivial_numeric_casts,
    unstable_features,
    unused_import_braces,
    unused_qualifications
)]

extern crate clap;
extern crate notify;
extern crate rouille;
extern crate tempdir;
extern crate reqwest;
extern crate pbr;
extern crate app_dirs;
extern crate libflate;
extern crate tar;
extern crate sha1;
extern crate sha2;
extern crate digest;
extern crate toml;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate cargo_shim;
extern crate handlebars;
extern crate unicode_categories;
extern crate ordermap;

extern crate parity_wasm;
#[macro_use]
extern crate log;
extern crate rustc_demangle;

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

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

use cargo_shim::*;

#[macro_use]
mod utils;
mod config;
mod package;
mod build;
mod error;
mod wasm;
mod wasm_gc;
mod wasm_inline_js;
mod wasm_export_main;
mod wasm_export_table;
mod wasm_hook_grow;
mod wasm_runtime;
mod wasm_context;
mod wasm_intrinsics;
mod emscripten;
mod cmd_build;
mod cmd_start;
mod cmd_test;

fn add_shared_build_params< 'a, 'b >( app: App< 'a, 'b > ) -> App< 'a, 'b > {
    return app
        .arg(
            Arg::with_name( "package" )
                .short( "p" )
                .long( "package" )
                .help( "Package to build" )
                .value_name( "NAME" )
                .takes_value( true )
        )
        .arg(
            Arg::with_name( "use-system-emscripten" )
                .long( "use-system-emscripten" )
                .help( "Won't try to download Emscripten; will always use the system one" )
        )
        .arg(
            Arg::with_name( "release" )
                .long( "release" )
                .help( "Build artifacts in release mode, with optimizations" )
        )
        .arg(
            Arg::with_name( "target-asmjs-emscripten" )
                .long( "target-asmjs-emscripten" )
                .help( "Generate asmjs through Emscripten (default)" )
                .overrides_with_all( &["target-webasm-emscripten", "target-webasm"] )
        )
        .arg(
            Arg::with_name( "target-webasm-emscripten" )
                .long( "target-webasm-emscripten" )
                .help( "Generate webasm through Emscripten" )
                .overrides_with_all( &["target-asmjs-emscripten", "target-webasm"] )
        )
        .arg(
            Arg::with_name( "target-webasm" )
                .long( "target-webasm" )
                .help( "Generates webasm through Rust's native backend (HIGHLY EXPERIMENTAL!)" )
                .overrides_with_all( &["target-asmjs-emscripten", "target-webasm-emscripten"] )
        );
}

fn main() {
    let args = {
        // To allow running both as 'cargo-web' and as 'cargo web'.
        let mut args = env::args();
        let mut filtered_args = Vec::new();
        filtered_args.push( args.next().unwrap() );

        match args.next() {
            None => {},
            #[cfg(any(unix))]
            Some( ref arg ) if filtered_args[ 0 ].ends_with( "cargo-web" ) && arg == "web" => {},
            #[cfg(any(windows))]
            Some( ref arg ) if filtered_args[ 0 ].ends_with( "cargo-web.exe" ) && arg == "web" => {},
            Some( arg ) => filtered_args.push( arg )
        }

        filtered_args.extend( args );
        filtered_args
    };

    let mut build_subcommand =
        SubCommand::with_name( "build" )
            .about( "Compile a local package and all of its dependencies" )
            .arg(
                Arg::with_name( "lib" )
                    .long( "lib" )
                    .help( "Build only this package's library" )
            )
            .arg(
                Arg::with_name( "bin" )
                    .long( "bin" )
                    .help( "Build only the specified binary" )
                    .value_name( "NAME" )
                    .takes_value( true )
            )
            .arg(
                Arg::with_name( "example" )
                    .long( "example" )
                    .help( "Build only the specified example" )
                    .value_name( "NAME" )
                    .takes_value( true )
            )
            .arg(
                Arg::with_name( "test" )
                    .long( "test" )
                    .help( "Build only the specified test target" )
                    .value_name( "NAME" )
                    .takes_value( true )
            )
            .arg(
                Arg::with_name( "bench" )
                    .long( "bench" )
                    .help( "Build only the specified benchmark target" )
                    .value_name( "NAME" )
                    .takes_value( true )
            );

    let mut test_subcommand =
        SubCommand::with_name( "test" )
            .about( "Compiles and runs tests" )
            .arg(
                Arg::with_name( "no-run" )
                    .long( "no-run" )
                    .help( "Compile, but don't run tests" )
            )
            .arg(
                Arg::with_name( "nodejs" )
                    .long( "nodejs" )
                    .help( "Uses Node.js to run the tests" )
            )
            .arg(
                Arg::with_name( "passthrough" )
                    .help( "-- followed by anything will pass the arguments to the test runner")
                    .multiple( true )
                    .takes_value( true )
                    .last( true )
            );

    let mut start_subcommand =
        SubCommand::with_name( "start" )
            .about( "Runs an embedded web server serving the built project" )
            .arg(
                Arg::with_name( "bin" )
                    .long( "bin" )
                    .help( "Build only the specified binary" )
                    .value_name( "NAME" )
                    .takes_value( true )
            )
            .arg(
                Arg::with_name( "example" )
                    .long( "example" )
                    .help( "Serves the specified example" )
                    .value_name( "NAME" )
                    .takes_value( true )
            )
            .arg(
                Arg::with_name( "test" )
                    .long( "test" )
                    .help( "Build only the specified test target" )
                    .value_name( "NAME" )
                    .takes_value( true )
            )
            .arg(
                Arg::with_name( "bench" )
                    .long( "bench" )
                    .help( "Build only the specified benchmark target" )
                    .value_name( "NAME" )
                    .takes_value( true )
            ).arg(
                Arg::with_name( "host" )
                    .long( "host" )
                    .help( "Bind the server to this address, default `localhost`")
                    .value_name( "HOST" )
                    .takes_value( true )
            ).arg(
                Arg::with_name( "port" )
                    .long( "port" )
                    .help( "Bind the server to this port, default 8000" )
                    .value_name( "PORT" )
                    .takes_value( true )
            );

    build_subcommand = add_shared_build_params( build_subcommand );
    test_subcommand = add_shared_build_params( test_subcommand );
    start_subcommand = add_shared_build_params( start_subcommand );

    let matches = App::new( "cargo-web" )
        .version( env!( "CARGO_PKG_VERSION" ) )
        .setting( AppSettings::SubcommandRequiredElseHelp )
        .setting( AppSettings::VersionlessSubcommands )
        .subcommand( build_subcommand )
        .subcommand( test_subcommand )
        .subcommand( start_subcommand )
        .get_matches_from( args );

    let project = CargoProject::new( None );
    let result = if let Some( matches ) = matches.subcommand_matches( "build" ) {
        cmd_build::command_build( matches, &project )
    } else if let Some( matches ) = matches.subcommand_matches( "test" ) {
        cmd_test::command_test( matches, &project )
    } else if let Some( matches ) = matches.subcommand_matches( "start" ) {
        cmd_start::command_start( matches, &project )
    } else {
        return;
    };

    match result {
        Ok( _ ) => {},
        Err( error ) => {
            println_err!( "error: {}", error );
            exit( 101 );
        }
    }
}
<|endoftext|>


<commit_before>use std::{env, process};
use std::io::prelude::*;
use std::io::BufReader;
use std::collections::HashMap;
use std::path::PathBuf;
use std::fs::File;

static OVERRIDES_PATH : &'static str = ".multirust/overrides";

fn main() {
    let home = env::home_dir().expect("Impossible to get your home dir!");
    let mut overrides_path = home.clone();
    overrides_path.push(OVERRIDES_PATH);

    let overrides = match File::open(&overrides_path) {
        Ok(f) => f,
        Err(_) => {
            println!("default");
            process::exit(0);
        }
    };
    let overrides = BufReader::new(overrides);

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

    for line in overrides.lines() {
        let line = line.expect("No valid line found");
        let mut s = line.split(';');
        let path = s.next().expect("No path in line");
        let toolchain = s.next().expect("No toolchain in line");

        let path = PathBuf::from(path);

        overrides_map.insert(path, toolchain.into());
    }

    let cwd = env::current_dir().expect("No valid working directory");

    match overrides_map.get(&cwd) {
        Some(toolchain) => println!("{}", toolchain),
        None => println!("default"),
    }
}
<commit_msg>feat: Shorten toolchain names if possible<commit_after>use std::{env, process};
use std::io::prelude::*;
use std::io::BufReader;
use std::collections::HashMap;
use std::path::PathBuf;
use std::fs::File;

static OVERRIDES_PATH : &'static str = ".multirust/overrides";

fn clean_toolchain_name(toolchain: &str) -> &str {
    static SHORTNAMES : &'static [&'static str] = &["stable", "nightly", "beta"];

    for short in SHORTNAMES {
        if toolchain.starts_with(short) {
            return short;
        }
    }

    toolchain
}

fn main() {
    let home = env::home_dir().expect("Impossible to get your home dir!");
    let mut overrides_path = home.clone();
    overrides_path.push(OVERRIDES_PATH);

    let overrides = match File::open(&overrides_path) {
        Ok(f) => f,
        Err(_) => {
            println!("default");
            process::exit(0);
        }
    };
    let overrides = BufReader::new(overrides);

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

    for line in overrides.lines() {
        let line = line.expect("No valid line found");
        let mut s = line.split(';');
        let path = s.next().expect("No path in line");
        let toolchain = s.next().expect("No toolchain in line");

        let path = PathBuf::from(path);

        overrides_map.insert(path, toolchain.into());
    }

    let cwd = env::current_dir().expect("No valid working directory");

    match overrides_map.get(&cwd) {
        Some(toolchain) => println!("{}", clean_toolchain_name(toolchain)),
        None => println!("default"),
    }
}
<|endoftext|>


<commit_before>use std::fs;
use std::env;
use std::fs::File;
use std::io::Read;
use std::hash::Hasher;
use std::path::PathBuf;
use std::collections::HashMap;
use std::os::unix::fs::MetadataExt;
use std::collections::hash_map::DefaultHasher;

#[macro_use]
extern crate log;
extern crate env_logger;

struct FileEntry {
    inode: u64,
    dev:  u64,
    path : String,
}

fn collect_files(dir: &String, h: &mut HashMap<u64, Vec<FileEntry>>) {

    let entries = match fs::read_dir(dir) {
        Ok(x) => x,
        _ => {
            warn!("{}: invalid directory", dir);
            return
        },
    };

    for path in  entries.filter( |x| x.is_ok() ).map( |x| x.unwrap().path() )
                .collect::<Vec<PathBuf>>() {
        if let (Some(path_str), Ok(metadata)) =
                (path.to_str(), path.symlink_metadata()) {
            let ft = metadata.file_type();
            if ft.is_symlink() {
                continue;
            } else if ft.is_file() {
                match metadata.len() {
                    0 => continue,
                    i => h.entry(i).or_insert_with(Vec::new)
                          .push(
                           FileEntry{
                               inode : metadata.ino(),
                               dev   : metadata.dev(),
                               path  : String::from(path_str),
                           }),
                };
            } else if ft.is_dir() {
                collect_files(&(String::from(path_str)), h);
            }
        }
    }
}

fn find_duplicates(duplicates: &mut HashMap<u64, Vec<FileEntry>>,
                   vec: &Vec<FileEntry> ) {
    for file_entry in vec {
        if let Ok(mut file) = File::open(&file_entry.path) {
            let mut buf: [u8; 1024] = [0; 1024];
            if let Ok(nbytes) = file.read(&mut buf) {
                let mut hasher = DefaultHasher::new();
                hasher.write(&buf[..nbytes as usize]);
                let k = hasher.finish();
                duplicates.entry(k).or_insert_with(Vec::new)
                    .push(
                        FileEntry{
                            inode : file_entry.inode,
                            dev   : file_entry.dev,
                            path  : file_entry.path.to_string(),
                        });
            }
        }
    }
}

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

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

    // Print out usage if no directories are given.
    if args.len() == 1 || ( args.len() == 2 && args[1] == "--thorough" ) {
        println!("Usage: {} [--thorough] <dir1> [dir2 [dir3 ...]]", args[0]);
        ::std::process::exit(0);
    }

    let mut hmap: HashMap<u64, Vec<FileEntry> > = HashMap::new();

    let mut thorough = false;
    for dir in &args[1..] {
        if dir == "--thorough" {
            thorough = true;
            continue;
        }
        collect_files(dir, &mut hmap);
    }

    // Get rid of all the single entries.
    hmap.retain(|_, v| v.len() >= 2);

    let mut cluster = 1;

    for (key, val) in hmap.iter() {
        let mut duplicates: HashMap<u64, Vec<FileEntry> > = HashMap::new();
        find_duplicates(&mut duplicates, &val);

        for (hash, vec) in duplicates {
            if vec.len() >= 2 {
                println!("{} files in cluster {} (size: {}, digest: {})",
                         vec.len(), cluster, key, hash);
                // for_each becomes stable v1.22.0 onwards. Should uncomment then.
                //vec.iter().for_each(|f| println!("{}", f.path));
                for file_entry in vec {
                    println!("{}", file_entry.path);
                }
                cluster += 1;
            }
        }
    }
}
<commit_msg>Add an implementation for thorough<commit_after>use std::fs;
use std::env;
use std::fs::File;
use std::io::Read;
use std::hash::Hasher;
use std::path::PathBuf;
use std::collections::HashMap;
use std::os::unix::fs::MetadataExt;
use std::collections::hash_map::DefaultHasher;

#[macro_use]
extern crate log;
extern crate env_logger;

struct FileEntry {
    inode: u64,
    dev:  u64,
    path : String,
}

fn collect_files(dir: &String, h: &mut HashMap<u64, Vec<FileEntry>>) {

    let entries = match fs::read_dir(dir) {
        Ok(x) => x,
        _ => {
            warn!("{}: invalid directory", dir);
            return
        },
    };

    for path in  entries.filter( |x| x.is_ok() ).map( |x| x.unwrap().path() )
                .collect::<Vec<PathBuf>>() {
        if let (Some(path_str), Ok(metadata)) =
                (path.to_str(), path.symlink_metadata()) {
            let ft = metadata.file_type();
            if ft.is_symlink() {
                continue;
            } else if ft.is_file() {
                match metadata.len() {
                    0 => continue,
                    i => h.entry(i).or_insert_with(Vec::new)
                          .push(
                           FileEntry{
                               inode : metadata.ino(),
                               dev   : metadata.dev(),
                               path  : String::from(path_str),
                           }),
                };
            } else if ft.is_dir() {
                collect_files(&(String::from(path_str)), h);
            }
        }
    }
}

fn find_duplicates(duplicates: &mut HashMap<u64, Vec<FileEntry>>,
                   vec: &Vec<FileEntry>, thorough: bool ) {
    for file_entry in vec {
        if let Ok(mut file) = File::open(&file_entry.path) {
            let mut contents: Vec<u8> = Vec::new();
            let mut buf: [u8; 1024] = [0; 1024];
            let mut hash: u64 = 0;
            let mut hasher = DefaultHasher::new();
            if thorough {
                if let Ok(_) = file.read_to_end(&mut contents) {
                    hasher.write(&contents[..]);
                    hash = hasher.finish();
                }
            } else {
                if let Ok(nbytes) = file.read(&mut buf) {
                    hasher.write(&buf[..nbytes as usize]);
                    hash = hasher.finish();
                }
            }
            if hash != 0 {
                duplicates.entry(hash).or_insert_with(Vec::new)
                    .push(
                        FileEntry{
                            inode : file_entry.inode,
                            dev   : file_entry.dev,
                            path  : file_entry.path.to_string(),
                        });
            }
        }
    }
}

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

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

    // Print out usage if no directories are given.
    if args.len() == 1 || ( args.len() == 2 && args[1] == "--thorough" ) {
        println!("Usage: {} [--thorough] <dir1> [dir2 [dir3 ...]]", args[0]);
        ::std::process::exit(0);
    }

    let mut hmap: HashMap<u64, Vec<FileEntry> > = HashMap::new();

    let mut thorough = false;
    for dir in &args[1..] {
        if dir == "--thorough" {
            thorough = true;
            continue;
        }
        collect_files(dir, &mut hmap);
    }

    // Get rid of all the single entries.
    hmap.retain(|_, v| v.len() >= 2);

    let mut cluster = 1;

    for (key, val) in hmap.iter() {
        let mut duplicates: HashMap<u64, Vec<FileEntry> > = HashMap::new();
        find_duplicates(&mut duplicates, &val, thorough);

        for (hash, vec) in duplicates {
            if vec.len() >= 2 {
                println!("{} files in cluster {} (size: {}, digest: {})",
                         vec.len(), cluster, key, hash);
                // for_each becomes stable v1.22.0 onwards. Should uncomment then.
                //vec.iter().for_each(|f| println!("{}", f.path));
                for file_entry in vec {
                    println!("{}", file_entry.path);
                }
                cluster += 1;
            }
        }
    }
}
<|endoftext|>


<commit_before>use std::cell::Cell;

struct Coordinates {
    x: Cell<i32>,
    y: Cell<i32>,
}

fn main() {
    let bike = Coordinates { x: Cell::new(0), y: Cell::new(0) };
    let mut previous_positions = vec![];

    move_up(&bike.y);
    add_positions(&mut previous_positions, &bike.y, &bike.x);
    move_down(&bike.y);
    add_positions(&mut previous_positions, &bike.y, &bike.x);
    move_right(&bike.x);
    add_positions(&mut previous_positions, &bike.y, &bike.x);
    move_left(&bike.x);
    add_positions(&mut previous_positions, &bike.y, &bike.x);

    println!("X is {:?}, Y is {:?}", bike.x, bike.y);
    println!("{:?}", previous_positions)

}

fn add_positions<'a>(v_cc: &'a mut Vec<i32>, y: &Cell<i32>, x: &Cell<i32>) -> &'a mut Vec<i32> {
    v_cc.push(x.get());
    v_cc.push(y.get());
    v_cc
}

fn move_up(y_cord: &Cell<i32>) -> &Cell<i32> {
    y_cord.set(y_cord.get() + 1);
    y_cord
}

fn move_down(y_cord: &Cell<i32>) -> &Cell<i32> {
    y_cord.set(y_cord.get() - 1);
    y_cord
}

fn move_right(x_cord: &Cell<i32>) -> &Cell<i32> {
    x_cord.set(x_cord.get() + 1);
    x_cord
}

fn move_left(x_cord: &Cell<i32>) -> &Cell<i32> {
    x_cord.set(x_cord.get() - 1);
    x_cord
}

#[test]
fn it_can_move() {
    let bike = Coordinates { x: Cell::new(0), y: Cell::new(0) };

    // test it starts at 0

    assert_eq!(0, bike.y.get());

    // test it can move up one

    move_up(&bike.y);

    assert_eq!(1, bike.y.get());

    // test it can continue to move up and theat move logic is valid

    move_up(&bike.y);
    move_up(&bike.y);
    move_up(&bike.y);

    assert_eq!(4, bike.y.get());

    for _ in 0..19 { // _ instead of x so that rust does not complain about x not being used
        move_up(&bike.y); // moves up 19 times
    }

    assert_eq!(23, bike.y.get());

    // test it can move down

    for _ in 0..19 {
        move_down(&bike.y);
    }

    assert_eq!(4, bike.y.get());

    // test it can move right

    for _ in 0..19 {
        move_right(&bike.x);
    }

    assert_eq!(19, bike.x.get());

    // test it can move left

    for _ in 0..10 {
        move_left(&bike.x);
    }

    assert_eq!(9, bike.x.get());
}
<commit_msg>small test that proves the vector pushing works<commit_after>use std::cell::Cell;

struct Coordinates {
    x: Cell<i32>,
    y: Cell<i32>,
}

fn main() {
    let bike = Coordinates { x: Cell::new(0), y: Cell::new(0) };
    let mut previous_positions = vec![];

    move_up(&bike.y);
    add_positions(&mut previous_positions, &bike.y, &bike.x);
    move_down(&bike.y);
    add_positions(&mut previous_positions, &bike.y, &bike.x);
    move_right(&bike.x);
    add_positions(&mut previous_positions, &bike.y, &bike.x);
    move_left(&bike.x);
    add_positions(&mut previous_positions, &bike.y, &bike.x);

    println!("X is {:?}, Y is {:?}", bike.x, bike.y);
    println!("{:?}", previous_positions)

}

fn add_positions<'a>(v_cc: &'a mut Vec<i32>, y: &Cell<i32>, x: &Cell<i32>) -> &'a mut Vec<i32> {
    v_cc.push(x.get());
    v_cc.push(y.get());
    v_cc
}

fn move_up(y_cord: &Cell<i32>) -> &Cell<i32> {
    y_cord.set(y_cord.get() + 1);
    y_cord
}

fn move_down(y_cord: &Cell<i32>) -> &Cell<i32> {
    y_cord.set(y_cord.get() - 1);
    y_cord
}

fn move_right(x_cord: &Cell<i32>) -> &Cell<i32> {
    x_cord.set(x_cord.get() + 1);
    x_cord
}

fn move_left(x_cord: &Cell<i32>) -> &Cell<i32> {
    x_cord.set(x_cord.get() - 1);
    x_cord
}

#[test]
fn it_can_move() {
    let bike = Coordinates { x: Cell::new(0), y: Cell::new(0) };
    let mut previous_positions = vec![];

    // test it starts at 0

    assert_eq!(0, bike.y.get());

    // test it can move up one and can add positions to the vector

    move_up(&bike.y);
    add_positions(&mut previous_positions, &bike.y, &bike.x);

    assert_eq!(1, bike.y.get());
    assert_eq!(0, previous_positions[0]);
    assert_eq!(1, previous_positions[1]);

    // test it can continue to move up and theat move logic is valid

    move_up(&bike.y);
    move_up(&bike.y);
    move_up(&bike.y);

    assert_eq!(4, bike.y.get());

    for _ in 0..19 { // _ instead of x so that rust does not complain about x not being used
        move_up(&bike.y); // moves up 19 times
    }

    assert_eq!(23, bike.y.get());

    // test it can move down

    for _ in 0..19 {
        move_down(&bike.y);
    }

    assert_eq!(4, bike.y.get());

    // test it can move right

    for _ in 0..19 {
        move_right(&bike.x);
    }

    assert_eq!(19, bike.x.get());

    // test it can move left

    for _ in 0..10 {
        move_left(&bike.x);
    }

    assert_eq!(9, bike.x.get());
}
<|endoftext|>


<commit_before>extern crate clap;
extern crate aluminum;

use std::io;
use std::io::prelude::*;
use std::error::Error;
use std::fs::File;
use clap::{App, Arg, AppSettings, SubCommand};
use aluminum::commands;
use aluminum::config::Config;

const VERSION_NUMBER: &'static str = "0.1.0";

fn main() {
    let matches = App::new("Rukyll")
        .setting(AppSettings::ArgRequiredElseHelp)
        .version(VERSION_NUMBER)
        .about("Static site generator")
        .subcommand(SubCommand::with_name("new").arg(Arg::with_name("project name")
                                                         .index(1)
                                                         .required(true)))
        .subcommand(SubCommand::with_name("build"))
        .subcommand(SubCommand::with_name("clean"))
        .subcommand(SubCommand::with_name("serve"))
        .get_matches();

    if let ("new", Some(new)) = matches.subcommand() {
        let project_name = if new.is_present("project name") {
            new.value_of("project name").unwrap()
        } else {
            ""
        };

        commands::new_project(project_name).unwrap();
    } else if matches.is_present("build") {
        let mut config_file_contents = String::new();
        let mut config_file = match File::open("_config.yml") {
            Ok(file) => file,
            Err(what) => panic!("No config file present: {}", Error::description(&what))
        };

        match config_file.read_to_string(&mut config_file_contents) {
            Ok(_) => {},
            Err(what) => panic!("Unable to read config file: {}", Error::description(&what))
        }

        println!("Building project...");
        let config = Config::from_string(config_file_contents);
        match commands::build_project(&config) {
            Ok(_) => {},
            Err(what) => {
                writeln!(io::stderr(), "Error: {}", Error::description(&what)).expect("Print Error");
            }
        }
    } else if matches.is_present("clean") {
        let mut config_file_contents = String::new();
        let mut config_file = match File::open("_config.yml") {
            Ok(file) => file,
            Err(what) => panic!("No config file present: {}", Error::description(&what))
        };

        match config_file.read_to_string(&mut config_file_contents) {
            Ok(_) => {},
            Err(what) => panic!("Unable to read config file: {}", Error::description(&what))
        }

        println!("Cleaning project...");
        let config = Config::from_string(config_file_contents);
        match commands::clean_project(&config) {
            Ok(_) | Err(_) => {},
        }
    } else if matches.is_present("serve") {
        let mut config_file_contents = String::new();
        let mut config_file = match File::open("_config.yml") {
            Ok(file) => file,
            Err(what) => panic!("No config file present: {}", Error::description(&what))
        };

        match config_file.read_to_string(&mut config_file_contents) {
            Ok(_) => {},
            Err(what) => panic!("Unable to read config file: {}", Error::description(&what))
        }

        println!("Serving project");
        let config = Config::from_string(config_file_contents);
        commands::serve(&config).expect("Serve");
    }
}
<commit_msg>[#143033621] change CLI name and bump version<commit_after>extern crate clap;
extern crate aluminum;

use std::io;
use std::io::prelude::*;
use std::error::Error;
use std::fs::File;
use clap::{App, Arg, AppSettings, SubCommand};
use aluminum::commands;
use aluminum::config::Config;

const VERSION_NUMBER: &'static str = "0.3.0";

fn main() {
    let matches = App::new("Aluminum")
        .setting(AppSettings::ArgRequiredElseHelp)
        .version(VERSION_NUMBER)
        .about("Static site generator")
        .subcommand(SubCommand::with_name("new").arg(Arg::with_name("project name")
                                                         .index(1)
                                                         .required(true)))
        .subcommand(SubCommand::with_name("build"))
        .subcommand(SubCommand::with_name("clean"))
        .subcommand(SubCommand::with_name("serve"))
        .get_matches();

    if let ("new", Some(new)) = matches.subcommand() {
        let project_name = if new.is_present("project name") {
            new.value_of("project name").unwrap()
        } else {
            ""
        };

        commands::new_project(project_name).unwrap();
    } else if matches.is_present("build") {
        let mut config_file_contents = String::new();
        let mut config_file = match File::open("_config.yml") {
            Ok(file) => file,
            Err(what) => panic!("No config file present: {}", Error::description(&what))
        };

        match config_file.read_to_string(&mut config_file_contents) {
            Ok(_) => {},
            Err(what) => panic!("Unable to read config file: {}", Error::description(&what))
        }

        println!("Building project...");
        let config = Config::from_string(config_file_contents);
        match commands::build_project(&config) {
            Ok(_) => {},
            Err(what) => {
                writeln!(io::stderr(), "Error: {}", Error::description(&what)).expect("Print Error");
            }
        }
    } else if matches.is_present("clean") {
        let mut config_file_contents = String::new();
        let mut config_file = match File::open("_config.yml") {
            Ok(file) => file,
            Err(what) => panic!("No config file present: {}", Error::description(&what))
        };

        match config_file.read_to_string(&mut config_file_contents) {
            Ok(_) => {},
            Err(what) => panic!("Unable to read config file: {}", Error::description(&what))
        }

        println!("Cleaning project...");
        let config = Config::from_string(config_file_contents);
        match commands::clean_project(&config) {
            Ok(_) | Err(_) => {},
        }
    } else if matches.is_present("serve") {
        let mut config_file_contents = String::new();
        let mut config_file = match File::open("_config.yml") {
            Ok(file) => file,
            Err(what) => panic!("No config file present: {}", Error::description(&what))
        };

        match config_file.read_to_string(&mut config_file_contents) {
            Ok(_) => {},
            Err(what) => panic!("Unable to read config file: {}", Error::description(&what))
        }

        println!("Serving project");
        let config = Config::from_string(config_file_contents);
        commands::serve(&config).expect("Serve");
    }
}
<|endoftext|>


<commit_before>use gl;
use mandelbrot::Mandelbrot;
use std::io::timer;
use std::mem;
use std::time::duration::Duration;
use sdl2;
use sdl2::event::Event;
use sdl2::keycode::KeyCode;
use sdl2::mouse::Mouse;
use stopwatch::TimerSet;
use yaglw::gl_context::{GLContext, GLContextExistence};
use yaglw::shader::Shader;
use yaglw::vertex_buffer::{GLArray, GLBuffer, GLType, VertexAttribData, DrawMode};

pub const WINDOW_WIDTH: u32 = 800;
pub const WINDOW_HEIGHT: u32 = 600;

#[repr(C)]
pub struct RGB {
  pub r: f32,
  pub g: f32,
  pub b: f32,
}

pub fn main() {
  let timers = TimerSet::new();

  let window = make_window();

  let _sdl_gl_context = window.gl_create_context().unwrap();

  // Load the OpenGL function pointers.
  gl::load_with(|s| unsafe {
    mem::transmute(sdl2::video::gl_get_proc_address(s))
  });

  let (gl, mut gl_context) = unsafe {
    GLContext::new()
  };

  match gl_context.get_error() {
    gl::NO_ERROR => {},
    err => {
      println!("OpenGL error 0x{:x} in setup", err);
      return;
    },
  }

  let shader = make_shader(&gl);
  shader.use_shader(&mut gl_context);

  let mut vao = make_vao(&gl, &mut gl_context, &shader);
  vao.bind(&mut gl_context);

  let mut mdlbt =
    Mandelbrot {
      low_x: -2.0,
      low_y: -2.0,
      width: 4.0,
      height: 4.0,
      max_iter: 128,
    };

  timers.time("update", || {
    vao.push(&mut gl_context, mdlbt.render().as_slice());
  });

  while process_events(&timers, &mut gl_context, &mut mdlbt, &mut vao) {
    timers.time("draw", || {
      gl_context.clear_buffer();
      vao.draw(&mut gl_context);
      // swap buffers
      window.gl_swap_window();
    });

    timer::sleep(Duration::milliseconds(10));
  }

  timers.print();
}

fn make_shader<'a>(
  gl: &'a GLContextExistence,
) -> Shader<'a> {
  let vertex_shader: String = format!("
    #version 330 core

    const int W = {};
    const int H = {};

    in vec3 color;
    out vec4 v_color;

    void main() {{
      v_color = vec4(color, 1);
      gl_Position =
        vec4(
          float(gl_VertexID % W) / W * 2 - 1,
          float(gl_VertexID / W) / H * 2 - 1,
          0, 1
        );
    }}
  ", WINDOW_WIDTH, WINDOW_HEIGHT);

  let fragment_shader: String = "
    #version 330 core

    in vec4 v_color;

    void main() {
      gl_FragColor = v_color;
    }
  ".to_string();

  let components = vec!(
    ((vertex_shader, gl::VERTEX_SHADER)),
    ((fragment_shader, gl::FRAGMENT_SHADER)),
  );

  Shader::new(gl, components.into_iter())
}

fn make_window() -> sdl2::video::Window {
  sdl2::init(sdl2::INIT_EVERYTHING);

  sdl2::video::gl_set_attribute(sdl2::video::GLAttr::GLContextMajorVersion, 3);
  sdl2::video::gl_set_attribute(sdl2::video::GLAttr::GLContextMinorVersion, 3);
  sdl2::video::gl_set_attribute(
    sdl2::video::GLAttr::GLContextProfileMask,
    sdl2::video::GLProfile::GLCoreProfile as isize
  );

  let window = sdl2::video::Window::new(
    "OpenCL",
    sdl2::video::WindowPos::PosCentered,
    sdl2::video::WindowPos::PosCentered,
    WINDOW_WIDTH as isize,
    WINDOW_HEIGHT as isize,
    sdl2::video::OPENGL,
  ).unwrap();

  window
}

fn make_vao<'a>(
  gl: &'a GLContextExistence,
  gl_context: &mut GLContext,
  shader: &Shader<'a>,
) -> GLArray<'a, RGB> {
  let attribs = [
    VertexAttribData {
      name: "color",
      size: 3,
      unit: GLType::Float,
    },
  ];

  let capacity = WINDOW_WIDTH as usize * WINDOW_HEIGHT as usize * 3;
  let vbo = GLBuffer::new(gl, gl_context, capacity);

  GLArray::new(
    gl,
    gl_context,
    shader,
    &attribs,
    DrawMode::Points,
    vbo,
  )
}

fn process_events<'a>(
  timers: &TimerSet,
  gl: &mut GLContext,
  mdlbt: &mut Mandelbrot,
  vao: &mut GLArray<'a, RGB>,
) -> bool {
  loop {
    match sdl2::event::poll_event() {
      Event::None => {
        return true;
      },
      Event::Quit(_) => {
        return false;
      },
      Event::AppTerminating(_) => {
        return false;
      },
      Event::MouseButtonDown(_, _, _, btn, x, y) => {
        match btn {
          Mouse::Left => {
            let ww = WINDOW_WIDTH as f32;
            let wh = WINDOW_HEIGHT as f32;
            mdlbt.low_x = (x as f32) / ww * mdlbt.width + mdlbt.low_x;
            mdlbt.low_y = (y as f32) / wh * mdlbt.height + mdlbt.low_y;
            mdlbt.width = mdlbt.width / ww;
            mdlbt.height = mdlbt.height / wh;

            timers.time("update", || {
              vao.buffer.update(gl, 0, mdlbt.render().as_slice());
            });
          },
          _ => {},
        };
      },
      Event::KeyDown(_, _, key, _, _, repeat) => {
        if !repeat {
          match key {
            KeyCode::Up => {
              mdlbt.max_iter *= 2;

              timers.time("update", || {
                vao.buffer.update(gl, 0, mdlbt.render().as_slice());
              });
            },
            KeyCode::Down => {
              mdlbt.max_iter /= 2;

              timers.time("update", || {
                vao.buffer.update(gl, 0, mdlbt.render().as_slice());
              });
            },
            _ => {},
          }
        }
      },
      _ => {},
    }
  }
}
<commit_msg>Fix y-coordinate of mouse clicks<commit_after>use gl;
use mandelbrot::Mandelbrot;
use std::io::timer;
use std::mem;
use std::time::duration::Duration;
use sdl2;
use sdl2::event::Event;
use sdl2::keycode::KeyCode;
use sdl2::mouse::Mouse;
use stopwatch::TimerSet;
use yaglw::gl_context::{GLContext, GLContextExistence};
use yaglw::shader::Shader;
use yaglw::vertex_buffer::{GLArray, GLBuffer, GLType, VertexAttribData, DrawMode};

pub const WINDOW_WIDTH: u32 = 800;
pub const WINDOW_HEIGHT: u32 = 600;

#[repr(C)]
pub struct RGB {
  pub r: f32,
  pub g: f32,
  pub b: f32,
}

pub fn main() {
  let timers = TimerSet::new();

  let window = make_window();

  let _sdl_gl_context = window.gl_create_context().unwrap();

  // Load the OpenGL function pointers.
  gl::load_with(|s| unsafe {
    mem::transmute(sdl2::video::gl_get_proc_address(s))
  });

  let (gl, mut gl_context) = unsafe {
    GLContext::new()
  };

  match gl_context.get_error() {
    gl::NO_ERROR => {},
    err => {
      println!("OpenGL error 0x{:x} in setup", err);
      return;
    },
  }

  let shader = make_shader(&gl);
  shader.use_shader(&mut gl_context);

  let mut vao = make_vao(&gl, &mut gl_context, &shader);
  vao.bind(&mut gl_context);

  let mut mdlbt =
    Mandelbrot {
      low_x: -2.0,
      low_y: -2.0,
      width: 4.0,
      height: 4.0,
      max_iter: 128,
    };

  timers.time("update", || {
    vao.push(&mut gl_context, mdlbt.render().as_slice());
  });

  while process_events(&timers, &mut gl_context, &mut mdlbt, &mut vao) {
    timers.time("draw", || {
      gl_context.clear_buffer();
      vao.draw(&mut gl_context);
      // swap buffers
      window.gl_swap_window();
    });

    timer::sleep(Duration::milliseconds(10));
  }

  timers.print();
}

fn make_shader<'a>(
  gl: &'a GLContextExistence,
) -> Shader<'a> {
  let vertex_shader: String = format!("
    #version 330 core

    const int W = {};
    const int H = {};

    in vec3 color;
    out vec4 v_color;

    void main() {{
      v_color = vec4(color, 1);
      gl_Position =
        vec4(
          float(gl_VertexID % W) / W * 2 - 1,
          float(gl_VertexID / W) / H * 2 - 1,
          0, 1
        );
    }}
  ", WINDOW_WIDTH, WINDOW_HEIGHT);

  let fragment_shader: String = "
    #version 330 core

    in vec4 v_color;

    void main() {
      gl_FragColor = v_color;
    }
  ".to_string();

  let components = vec!(
    ((vertex_shader, gl::VERTEX_SHADER)),
    ((fragment_shader, gl::FRAGMENT_SHADER)),
  );

  Shader::new(gl, components.into_iter())
}

fn make_window() -> sdl2::video::Window {
  sdl2::init(sdl2::INIT_EVERYTHING);

  sdl2::video::gl_set_attribute(sdl2::video::GLAttr::GLContextMajorVersion, 3);
  sdl2::video::gl_set_attribute(sdl2::video::GLAttr::GLContextMinorVersion, 3);
  sdl2::video::gl_set_attribute(
    sdl2::video::GLAttr::GLContextProfileMask,
    sdl2::video::GLProfile::GLCoreProfile as isize
  );

  let window = sdl2::video::Window::new(
    "OpenCL",
    sdl2::video::WindowPos::PosCentered,
    sdl2::video::WindowPos::PosCentered,
    WINDOW_WIDTH as isize,
    WINDOW_HEIGHT as isize,
    sdl2::video::OPENGL,
  ).unwrap();

  window
}

fn make_vao<'a>(
  gl: &'a GLContextExistence,
  gl_context: &mut GLContext,
  shader: &Shader<'a>,
) -> GLArray<'a, RGB> {
  let attribs = [
    VertexAttribData {
      name: "color",
      size: 3,
      unit: GLType::Float,
    },
  ];

  let capacity = WINDOW_WIDTH as usize * WINDOW_HEIGHT as usize * 3;
  let vbo = GLBuffer::new(gl, gl_context, capacity);

  GLArray::new(
    gl,
    gl_context,
    shader,
    &attribs,
    DrawMode::Points,
    vbo,
  )
}

fn process_events<'a>(
  timers: &TimerSet,
  gl: &mut GLContext,
  mdlbt: &mut Mandelbrot,
  vao: &mut GLArray<'a, RGB>,
) -> bool {
  loop {
    match sdl2::event::poll_event() {
      Event::None => {
        return true;
      },
      Event::Quit(_) => {
        return false;
      },
      Event::AppTerminating(_) => {
        return false;
      },
      Event::MouseButtonDown(_, _, _, btn, x, y) => {
        let y = WINDOW_HEIGHT as i32 - y;
        match btn {
          Mouse::Left => {
            let ww = WINDOW_WIDTH as f32;
            let wh = WINDOW_HEIGHT as f32;
            mdlbt.low_x = (x as f32) / ww * mdlbt.width + mdlbt.low_x;
            mdlbt.low_y = (y as f32) / wh * mdlbt.height + mdlbt.low_y;
            mdlbt.width = mdlbt.width / ww;
            mdlbt.height = mdlbt.height / wh;

            timers.time("update", || {
              vao.buffer.update(gl, 0, mdlbt.render().as_slice());
            });
          },
          _ => {},
        };
      },
      Event::KeyDown(_, _, key, _, _, repeat) => {
        if !repeat {
          match key {
            KeyCode::Up => {
              mdlbt.max_iter *= 2;

              timers.time("update", || {
                vao.buffer.update(gl, 0, mdlbt.render().as_slice());
              });
            },
            KeyCode::Down => {
              mdlbt.max_iter /= 2;

              timers.time("update", || {
                vao.buffer.update(gl, 0, mdlbt.render().as_slice());
              });
            },
            _ => {},
          }
        }
      },
      _ => {},
    }
  }
}
<|endoftext|>


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

extern crate oak_runtime;
use oak_runtime::*;

grammar! awesome {
  #![show_api]

  program = declaration_list /
            statement_list /
            expression_list

  declaration_list
    = declaration (terminator declaration)*

  expression_list
    = expression (terminator expression)*

  statement_list
    = statement (terminator statement)*

  declaration
    = class_declaration > to_class_declaration
    / method_declaration > to_method_declaration

  class_declaration
    = kw_class spacing identifier class_body

  class_body
    = lbracket spacing method_declaration* rbracket

  method_declaration
    = kw_def spacing identifier lparen params_list? rparen block

  block
    = lbracket spacing (statement / expression)+ spacing rbracket

  statement
    = if_statement > to_if_statement
    / while_statement > to_while_statement

  if_statement
    = kw_if expression block

  while_statement
    = kw_while expression block

  assignment_expression
    = identifier bind_op expression

  expression
    = spacing cond_expr (cond_expr_op cond_expr)* > fold_left

  cond_expr
    = spacing add_expr (add_expr_op add_expr)* > fold_left

  add_expr
    = spacing mult_expr (mult_expr_op mult_expr)* > fold_left

  mult_expr
    = primary_expr

  primary_expr
    = call > call_expr
    / number > number_expr
    / assignment_expression > assign_expr
    / identifier > variable_expr
    / lparen expression rparen

    call
      = identifier lparen arg_list? rparen

    arg_list
     = (expression ("," spacing expression)*)

    params_list
      = (identifier ("," spacing identifier)*)

    add_expr_op
        = add_op > add_bin_op
        / sub_op > sub_bin_op

    mult_expr_op
        = mul_op > mul_bin_op
        / div_op > div_bin_op

    cond_expr_op
       = lt_op > lt_bin_op /
       lte_op > lte_bin_op /
       gt_op > gt_bin_op /
       gte_op > gte_bin_op /
       ne_op > ne_bin_op /
       eq_op > eq_bin_op /
       andand_op > and_bin_op /
       oror_op > or_bin_op

  identifier = !digit !keyword ident_char+ spacing > to_string
  ident_char = ["a-zA-Z0-9_"]

  digit = ["0-9"]
  number = digit+ spacing > to_number
  spacing = [" \r\t"]* -> ()

  kw_def = "def"
  kw_class = "class"
  kw_true = "true"
  kw_false = "false"
  kw_nil = "nil"
  kw_if = "if"
  kw_while = "while"
  kw_tail = !ident_char spacing

  keyword
    = kw_def
    / kw_class
    / kw_true
    / kw_false
    / kw_nil
    / kw_tail

  bind_op = "=" spacing
  add_op = "+" spacing
  sub_op = "-" spacing
  mul_op = "*" spacing
  div_op = "/" spacing
  lt_op = "<" spacing
  lte_op = "<=" spacing
  gt_op = ">" spacing
  gte_op = ">=" spacing
  ne_op = "!=" spacing
  eq_op = "==" spacing
  andand_op  = "&&" spacing
  oror_op = "||" spacing
  lparen = "(" spacing
  rparen = ")" spacing
  lbracket = "{"
  rbracket = "}"

  terminator = ";" / "\n"

  use std::str::FromStr;
  use self::Expression::*;
  use self::BinOp::*;

  pub type PExpr = Box<Expression>;

  #[derive(Debug)]
  pub enum Expression {
    Variable(String),
    Number(u32),
    BinaryExpr(BinOp, PExpr, PExpr),
    Call(String, Option<(PExpr, Vec<PExpr>)>),
    AssingExpr(String, PExpr),
    ClassDecl(String),
    MethodDecl(String, Option<(String, Vec<String>)>, Vec<PExpr>),
    IfStatement(PExpr, Vec<PExpr>),
    WhileStatement(PExpr, Vec<PExpr>)
  }

  #[derive(Debug)]
  pub enum BinOp {
    Add, Sub, Mul, Div, Lt, Lte, Gt, Gte, Ne, Eq, And, Or
  }

  fn to_number(raw_text: Vec<char>) -> u32 {
    u32::from_str(&*to_string(raw_text)).unwrap()
  }

  fn number_expr(value: u32) -> PExpr {
    Box::new(Number(value))
  }

  fn variable_expr(ident: String) -> PExpr {
    Box::new(Variable(ident))
  }

  fn to_string(raw_text: Vec<char>) -> String {
    raw_text.into_iter().collect()
  }

  fn fold_left(head: PExpr, rest: Vec<(BinOp, PExpr)>) -> PExpr {
    rest.into_iter().fold(head,
      |accu, (op, expr)| Box::new(BinaryExpr(op, accu, expr)))
  }

  fn fold_right(front: Vec<(PExpr, BinOp)>, last: PExpr) -> PExpr {
    front.into_iter().rev().fold(last,
      |accu, (expr, op)| Box::new(BinaryExpr(op, expr, accu)))
  }

  fn add_bin_op() -> BinOp { Add }
  fn sub_bin_op() -> BinOp { Sub }
  fn mul_bin_op() -> BinOp { Mul }
  fn div_bin_op() -> BinOp { Div }
  fn lt_bin_op() -> BinOp { Lt }
  fn lte_bin_op() -> BinOp { Lte }
  fn gt_bin_op() -> BinOp { Gt }
  fn gte_bin_op() -> BinOp { Gte }
  fn ne_bin_op() -> BinOp { Ne }
  fn eq_bin_op() -> BinOp { Eq }
  fn and_bin_op() -> BinOp { And }
  fn or_bin_op() -> BinOp { Or }

  fn call_expr(method: String, args: Option<(PExpr, Vec<PExpr>)>) -> PExpr {
      Box::new(Call(method, args))
  }

  fn assign_expr(variable: String, exp: PExpr) -> PExpr {
      Box::new(AssingExpr(variable, exp))
  }

  fn to_class_declaration(foo: String, bar: Vec<(String, Option<(String, Vec<String>)>, Vec<PExpr>)>) -> PExpr {
      Box::new(ClassDecl(foo))
  }

  fn to_method_declaration(name: String, params: Option<(String, Vec<String>)>, body: Vec<PExpr>) -> PExpr {
      Box::new(MethodDecl(name, params, body))
  }

  fn to_if_statement(condition: PExpr, block: Vec<PExpr>) -> PExpr {
      Box::new(IfStatement(condition, block))
  }

  fn to_while_statement(condition: PExpr,  block: Vec<PExpr>) -> PExpr {
      Box::new(WhileStatement(condition, block))
  }
}

fn analyse_state(state: ParseState<StrStream, awesome::PExpr>) {
    match state.into_result() {
        Ok((success, error)) => {
            if success.partial_read() {
                println!("Partial match: {:?} because: {}", success.data, error);
            } else {
                println!("Full match: {:?}", success.data);
            }
        }
        Err(error) => {
            println!("Error: {}", error);
        }
    }
}

fn main() {
    let program1 = "if a > 3 { a = 1 + (2 + 2) }";
    println!("{:?}", awesome::parse_program(program1.stream()));
    // analyse_state(awesome::parse_program(program1.stream()));
}
<commit_msg>Some indentation fixes. Also renaming.<commit_after>#![feature(plugin)]
#![plugin(oak)]

extern crate oak_runtime;
use oak_runtime::*;

grammar! awesome {
    #![show_api]

    program = decl_list /
            stmt_list /
            expr_list

    decl_list
        = decl (terminator decl)*

    expr_list
        = expr (terminator expr)*

    stmt_list
        = stmt (terminator stmt)*

    decl
        = class_decl > to_class_decl
        / method_decl > to_method_decl

    class_decl
        = kw_class spacing ident class_body

    class_body
        = lbracket spacing method_decl* rbracket

    method_decl
        = kw_def spacing ident lparen params_list? rparen block

    block
        = lbracket spacing (stmt / expr)+ spacing rbracket

    stmt
        = if_stmt > to_if_stmt
        / while_stmt > to_while_stmt

    if_stmt
        = kw_if expr block

    while_stmt
        = kw_while expr block

    assign_expr
        = ident bind_op expr

    expr
        = spacing cond_expr (cond_expr_op cond_expr)* > fold_left

    cond_expr
        = spacing add_expr (add_expr_op add_expr)* > fold_left

    add_expr
        = spacing mult_expr (mult_expr_op mult_expr)* > fold_left

    mult_expr
        = primary_expr

    primary_expr
        = call > call_expr
        / number > number_expr
        / assign_expr > to_assign_expr
        / ident > variable_expr
        / lparen expr rparen

    call
        = ident lparen arg_list? rparen

    arg_list
        = (expr ("," spacing expr)*)

    params_list
        = (ident ("," spacing ident)*)

    add_expr_op
        = add_op > add_bin_op
        / sub_op > sub_bin_op

    mult_expr_op
        = mul_op > mul_bin_op
        / div_op > div_bin_op

    cond_expr_op
        = lt_op > lt_bin_op /
        lte_op > lte_bin_op /
        gt_op > gt_bin_op /
        gte_op > gte_bin_op /
        ne_op > ne_bin_op /
        eq_op > eq_bin_op /
        andand_op > and_bin_op /
        oror_op > or_bin_op

    ident = !digit !keyword ident_char+ spacing > to_string
    ident_char = ["a-zA-Z0-9_"]

    digit = ["0-9"]
    number = digit+ spacing > to_number
    spacing = [" \r\t"]* -> ()

    kw_def = "def"
    kw_class = "class"
    kw_true = "true"
    kw_false = "false"
    kw_nil = "nil"
    kw_if = "if"
    kw_while = "while"
    kw_tail = !ident_char spacing

    keyword
        = kw_def
        / kw_class
        / kw_true
        / kw_false
        / kw_nil
        / kw_tail

    bind_op = "=" spacing
    add_op = "+" spacing
    sub_op = "-" spacing
    mul_op = "*" spacing
    div_op = "/" spacing
    lt_op = "<" spacing
    lte_op = "<=" spacing
    gt_op = ">" spacing
    gte_op = ">=" spacing
    ne_op = "!=" spacing
    eq_op = "==" spacing
    andand_op  = "&&" spacing
    oror_op = "||" spacing
    lparen = "(" spacing
    rparen = ")" spacing
    lbracket = "{" spacing
    rbracket = "}" spacing

    terminator = ";" / "\n"

    use std::str::FromStr;
    use self::Expression::*;
    use self::BinOp::*;

    pub type PExpr = Box<Expression>;

    #[derive(Debug)]
    pub enum Expression {
    Variable(String),
    Number(u32),
    BinaryExpr(BinOp, PExpr, PExpr),
    Call(String, Option<(PExpr, Vec<PExpr>)>),
    AssingExpr(String, PExpr),
    ClassDecl(String),
    MethodDecl(String, Option<(String, Vec<String>)>, Vec<PExpr>),
    IfStatement(PExpr, Vec<PExpr>),
    WhileStatement(PExpr, Vec<PExpr>)
    }

    #[derive(Debug)]
    pub enum BinOp {
    Add, Sub, Mul, Div, Lt, Lte, Gt, Gte, Ne, Eq, And, Or
    }

    fn to_number(raw_text: Vec<char>) -> u32 {
    u32::from_str(&*to_string(raw_text)).unwrap()
    }

    fn number_expr(value: u32) -> PExpr {
    Box::new(Number(value))
    }

    fn variable_expr(ident: String) -> PExpr {
    Box::new(Variable(ident))
    }

    fn to_string(raw_text: Vec<char>) -> String {
    raw_text.into_iter().collect()
    }

    fn fold_left(head: PExpr, rest: Vec<(BinOp, PExpr)>) -> PExpr {
    rest.into_iter().fold(head,
      |accu, (op, expr)| Box::new(BinaryExpr(op, accu, expr)))
    }

    fn fold_right(front: Vec<(PExpr, BinOp)>, last: PExpr) -> PExpr {
    front.into_iter().rev().fold(last,
      |accu, (expr, op)| Box::new(BinaryExpr(op, expr, accu)))
    }

    fn add_bin_op() -> BinOp { Add }
    fn sub_bin_op() -> BinOp { Sub }
    fn mul_bin_op() -> BinOp { Mul }
    fn div_bin_op() -> BinOp { Div }
    fn lt_bin_op() -> BinOp { Lt }
    fn lte_bin_op() -> BinOp { Lte }
    fn gt_bin_op() -> BinOp { Gt }
    fn gte_bin_op() -> BinOp { Gte }
    fn ne_bin_op() -> BinOp { Ne }
    fn eq_bin_op() -> BinOp { Eq }
    fn and_bin_op() -> BinOp { And }
    fn or_bin_op() -> BinOp { Or }

    fn call_expr(method: String, args: Option<(PExpr, Vec<PExpr>)>) -> PExpr {
      Box::new(Call(method, args))
    }

    fn to_assign_expr(variable: String, exp: PExpr) -> PExpr {
      Box::new(AssingExpr(variable, exp))
    }

    fn to_class_decl(foo: String, bar: Vec<(String, Option<(String, Vec<String>)>, Vec<PExpr>)>) -> PExpr {
      Box::new(ClassDecl(foo))
    }

    fn to_method_decl(name: String, params: Option<(String, Vec<String>)>, body: Vec<PExpr>) -> PExpr {
      Box::new(MethodDecl(name, params, body))
    }

    fn to_if_stmt(condition: PExpr, block: Vec<PExpr>) -> PExpr {
      Box::new(IfStatement(condition, block))
    }

    fn to_while_stmt(condition: PExpr,  block: Vec<PExpr>) -> PExpr {
      Box::new(WhileStatement(condition, block))
    }
}

fn analyse_state(state: ParseState<StrStream, awesome::PExpr>) {
    match state.into_result() {
        Ok((success, error)) => {
            if success.partial_read() {
                println!("Partial match: {:?} because: {}", success.data, error);
            } else {
                println!("Full match: {:?}", success.data);
            }
        }
        Err(error) => {
            println!("Error: {}", error);
        }
    }
}

fn main() {
    let program1 = "if a > 3 { a = 1 + (2 + 2) }";
    println!("{:?}", awesome::parse_program(program1.stream()));
    // analyse_state(awesome::parse_program(program1.stream()));
}
<|endoftext|>


<commit_before>use std::thread;
use std::sync::{Arc, Mutex, Condvar};

fn main() {
    let arc = Arc::new((Mutex::new(false), Condvar::new()));
    let arc_temp = arc.clone();

    thread::spawn(move || {

        let (ref lock, ref condvar) = *arc_temp;
        let mut state = lock.lock().unwrap();

        *state = true;

        condvar.notify_one();

        println!("thread {}", *state);
    });

    let (ref lock, ref condvar) = *arc;
    let mut state = lock.lock().unwrap();

    println!("main {}", *state);

    while !*state {
        println!("main prev {}", *state);
        state = condvar.wait(state).unwrap();
        println!("main next {}", *state);
    }
}

<commit_msg>test: condvar<commit_after>use std::thread;
use std::sync::{Arc, Mutex, Condvar};

fn main() {

    let wrapper = Arc::new((Mutex::new(false), Condvar::new()));
    let wrapper_clone = wrapper.clone();

    thread::Builder::new()
        .name("thread_1".to_string())
        .stack_size(4 * 1024 * 1024)
        .spawn(move || {
            let (ref lock, ref condition) = *wrapper_clone;
            let mut state = lock.lock().unwrap();

            *state = true;

            condition.notify_one();
        })
        .unwrap();

    let (ref lock, ref condition) = *wrapper;
    let mut state = lock.lock().unwrap();

    while !*state {

        state = condition.wait(state).unwrap();

        println!("receive {}", *state);
    }

    println!("-- main end --");
}<|endoftext|>


<commit_before>#![feature(fs_canonicalize)]

use std::path::Path;

#[cfg(not(test))]
fn main() {
    use std::{env, fs};
    use std::process::{self, Command};

    let path = env::current_exe().unwrap();
    let path = fs::canonicalize(path).unwrap();
    let path = path.parent().unwrap();
    let path = path.join("deps/");

    let args = wrap_args(env::args(), path);
    let mut command = Command::new("cargo");
    command.args(&args);
    let mut child = command.spawn().unwrap_or_else(|e| panic!("{}", e));
    let exit_status = child.wait().unwrap_or_else(|e| panic!("{}", e));

    if let Some(code) = exit_status.code() {
        process::exit(code);
    }
}

fn wrap_args<T, I, P>(it: I, clippy_path: P) -> Vec<String>
    where T: AsRef<str>,
          I: IntoIterator<Item=T>,
          P: AsRef<Path> {

    let it = it.into_iter();
    let mut args = vec!["rustc".to_owned()];
    let mut has_double_hyphen = false;

    for arg in it.skip(2) {
        let arg = arg.as_ref().to_owned();
        has_double_hyphen |= &arg == "--";
        args.push(arg);
    }

    if !has_double_hyphen {
        args.push("--".to_owned());
    }
    args.push("-L".to_owned());
    args.push(clippy_path.as_ref().to_string_lossy().into_owned());
    args.push("-lclippy".to_owned());
    args.push("-Zextra-plugins=clippy".to_owned());
    args.push("-Zno-trans".to_owned());
    args
}
<commit_msg>Remove trailing slash for the sake of Windows<commit_after>#![feature(fs_canonicalize)]

use std::path::Path;

#[cfg(not(test))]
fn main() {
    use std::{env, fs};
    use std::process::{self, Command};

    let path = env::current_exe().unwrap();
    let path = fs::canonicalize(path).unwrap();
    let path = path.parent().unwrap();
    let path = path.join("deps");

    let args = wrap_args(env::args(), path);
    let mut command = Command::new("cargo");
    command.args(&args);
    let mut child = command.spawn().unwrap_or_else(|e| panic!("{}", e));
    let exit_status = child.wait().unwrap_or_else(|e| panic!("{}", e));

    if let Some(code) = exit_status.code() {
        process::exit(code);
    }
}

fn wrap_args<T, I, P>(it: I, clippy_path: P) -> Vec<String>
    where T: AsRef<str>,
          I: IntoIterator<Item=T>,
          P: AsRef<Path> {

    let it = it.into_iter();
    let mut args = vec!["rustc".to_owned()];
    let mut has_double_hyphen = false;

    for arg in it.skip(2) {
        let arg = arg.as_ref().to_owned();
        has_double_hyphen |= &arg == "--";
        args.push(arg);
    }

    if !has_double_hyphen {
        args.push("--".to_owned());
    }
    args.push("-L".to_owned());
    args.push(clippy_path.as_ref().to_string_lossy().into_owned());
    args.push("-lclippy".to_owned());
    args.push("-Zextra-plugins=clippy".to_owned());
    args.push("-Zno-trans".to_owned());
    args
}
<|endoftext|>


<commit_before>extern crate hyper;
extern crate rustc_serialize;
extern crate chrono;
extern crate regex;

use std::ascii::AsciiExt;
use std::io::Read;
use std::env;

use chrono::naive::datetime::NaiveDateTime;
use chrono::offset::local::Local;
use chrono::offset::fixed::FixedOffset;
use chrono::datetime::DateTime;
use chrono::Datelike;

use rustc_serialize::json;
use hyper::client::Client;
use regex::Regex;

fn main() {
    let mut args      = env::args();
    let _program      = args.next().expect("program should be first arg!");
    let from_in: &str = &args.next().expect("must specify from");
    let to_in: &str   = &args.next().expect("must specify to");

    // pull in api key at *build* time from environment
    let s = Session::new(env!("WSDOT_API_KEY"));

    let now = Local::now();
    let mut from: Option<i32> = None;
    let mut to: Option<i32> = None;
    let terminals = s.terminals();
    for terminal in terminals.iter() {
        if terminal.Description.to_ascii_lowercase().starts_with(&from_in) {
            from = Some(terminal.TerminalID);
        }
        if terminal.Description.to_ascii_lowercase().starts_with(&to_in) {
            to = Some(terminal.TerminalID);
        }
    }

    let url = &s.url(format!("/schedule/{}-{}-{}/{}/{}",
                             now.year(), now.month(), now.day(), from.unwrap(), to.unwrap()));

    let mut res = s.client.get(url).send().unwrap();
    assert_eq!(res.status, hyper::Ok);

    let mut buf = String::new();
    res.read_to_string(&mut buf).unwrap();
    let schedule: ScheduleResult = json::decode(&buf).unwrap();

    assert_eq!(1, schedule.TerminalCombos.len());
    let tc = &schedule.TerminalCombos[0];
    for time in tc.Times.iter() {
        if time.depart_time() > now {
            println!("{}\t{}\t{}\t{}",
            time.depart_time().time(), tc.DepartingTerminalName, tc.ArrivingTerminalName, time.VesselName );
        }

    }
}

struct Session {
    api_key: String,
    client: Client,
}

impl Session {
    fn new(api_key: &str) -> Session {
        Session {
            api_key: api_key.to_string(),
            client: Client::new(),
        }
    }

    fn url(&self, path: String) -> String {
        format!("http://www.wsdot.wa.gov/ferries/api/schedule/rest{}?apiaccesscode={}",
                path,
                self.api_key)
    }

    fn terminals(&self) -> Vec<Terminal> {
        let now = Local::today();
        let url = &self.url(format!("/terminals/{}-{}-{}", now.year(), now.month(), now.day()));

        let mut res = self.client.get(url).send().unwrap();
        assert_eq!(res.status, hyper::Ok);

        let mut buf = String::new();
        res.read_to_string(&mut buf).unwrap();
        let routes: Vec<Terminal> = json::decode(&buf).unwrap();
        routes
    }
}

#[allow(non_snake_case)]
#[derive(RustcDecodable, RustcEncodable, Debug, Clone)]
struct Terminal {
    TerminalID: i32,
    Description: String,
}

#[allow(non_snake_case)]
#[derive(RustcDecodable, RustcEncodable, Debug)]
struct SailingTime {
    DepartingTime: String,
    ArrivingTime: Option<String>,
    VesselName: String,
}

impl SailingTime {
    // parse date strings of form "/Date(1436318400000-0700)/"
    fn depart_time(&self) -> DateTime<Local> {
        let re = Regex::new(r"^/Date\((\d{10})000-(\d{2})(\d{2})\)/$").unwrap();
        let caps = re.captures(&self.DepartingTime).unwrap();

        let epoch: i64 = caps.at(1).unwrap().parse().unwrap();
        let tz_hours: i32 = caps.at(2).unwrap().parse().unwrap();
        let tz_minutes: i32 = caps.at(3).unwrap().parse().unwrap();

        let nd = NaiveDateTime::from_timestamp(epoch, 0);
        let tz = FixedOffset::west((tz_hours * 3600) + (tz_minutes * 60));
        let fotz: DateTime<FixedOffset> = DateTime::from_utc(nd, tz);
        fotz.with_timezone(&Local)
    }
}

#[allow(non_snake_case)]
#[derive(RustcDecodable, RustcEncodable, Debug)]
struct TerminalCombo {
    Times: Vec<SailingTime>,
    DepartingTerminalName: String,
    ArrivingTerminalName: String,
}

#[allow(non_snake_case)]
#[derive(RustcDecodable, RustcEncodable, Debug)]
struct ScheduleResult {
    TerminalCombos: Vec<TerminalCombo>,
}

#[test]
fn test_hashmap() {
    let mut h: HashMap<&str, i32> = HashMap::new();
    h.insert("bi", 3);
    h.insert("sea", 7);
    match h.get("bi") {
        Some(id) => assert_eq!(*id, 3),
        None => assert!(false)
    }
}
<commit_msg>remove stale test, fix a format thing<commit_after>extern crate hyper;
extern crate rustc_serialize;
extern crate chrono;
extern crate regex;

use std::ascii::AsciiExt;
use std::io::Read;
use std::env;

use chrono::naive::datetime::NaiveDateTime;
use chrono::offset::local::Local;
use chrono::offset::fixed::FixedOffset;
use chrono::datetime::DateTime;
use chrono::Datelike;

use rustc_serialize::json;
use hyper::client::Client;
use regex::Regex;

fn main() {
    let mut args      = env::args();
    let _program      = args.next().expect("program should be first arg!");
    let from_in: &str = &args.next().expect("must specify from");
    let to_in: &str   = &args.next().expect("must specify to");

    // pull in api key at *build* time from environment
    let s = Session::new(env!("WSDOT_API_KEY"));

    let now = Local::now();
    let mut from: Option<i32> = None;
    let mut to: Option<i32> = None;
    let terminals = s.terminals();
    for terminal in terminals.iter() {
        if terminal.Description.to_ascii_lowercase().starts_with(&from_in) {
            from = Some(terminal.TerminalID);
        }
        if terminal.Description.to_ascii_lowercase().starts_with(&to_in) {
            to = Some(terminal.TerminalID);
        }
    }

    let url = &s.url(format!("/schedule/{}-{}-{}/{}/{}",
                             now.year(), now.month(), now.day(), from.unwrap(), to.unwrap()));

    let mut res = s.client.get(url).send().unwrap();
    assert_eq!(res.status, hyper::Ok);

    let mut buf = String::new();
    res.read_to_string(&mut buf).unwrap();
    let schedule: ScheduleResult = json::decode(&buf).unwrap();

    assert_eq!(1, schedule.TerminalCombos.len());
    let tc = &schedule.TerminalCombos[0];
    for time in tc.Times.iter() {
        if time.depart_time() > now {
            println!("{}\t{}\t{}\t{}",
                     time.depart_time().time(),
                     tc.DepartingTerminalName,
                     tc.ArrivingTerminalName,
                     time.VesselName );
        }

    }
}

struct Session {
    api_key: String,
    client: Client,
}

impl Session {
    fn new(api_key: &str) -> Session {
        Session {
            api_key: api_key.to_string(),
            client: Client::new(),
        }
    }

    fn url(&self, path: String) -> String {
        format!("http://www.wsdot.wa.gov/ferries/api/schedule/rest{}?apiaccesscode={}",
                path,
                self.api_key)
    }

    fn terminals(&self) -> Vec<Terminal> {
        let now = Local::today();
        let url = &self.url(format!("/terminals/{}-{}-{}", now.year(), now.month(), now.day()));

        let mut res = self.client.get(url).send().unwrap();
        assert_eq!(res.status, hyper::Ok);

        let mut buf = String::new();
        res.read_to_string(&mut buf).unwrap();
        let routes: Vec<Terminal> = json::decode(&buf).unwrap();
        routes
    }
}

#[allow(non_snake_case)]
#[derive(RustcDecodable, RustcEncodable, Debug, Clone)]
struct Terminal {
    TerminalID: i32,
    Description: String,
}

#[allow(non_snake_case)]
#[derive(RustcDecodable, RustcEncodable, Debug)]
struct SailingTime {
    DepartingTime: String,
    ArrivingTime: Option<String>,
    VesselName: String,
}

impl SailingTime {
    // parse date strings of form "/Date(1436318400000-0700)/"
    fn depart_time(&self) -> DateTime<Local> {
        let re = Regex::new(r"^/Date\((\d{10})000-(\d{2})(\d{2})\)/$").unwrap();
        let caps = re.captures(&self.DepartingTime).unwrap();

        let epoch: i64 = caps.at(1).unwrap().parse().unwrap();
        let tz_hours: i32 = caps.at(2).unwrap().parse().unwrap();
        let tz_minutes: i32 = caps.at(3).unwrap().parse().unwrap();

        let nd = NaiveDateTime::from_timestamp(epoch, 0);
        let tz = FixedOffset::west((tz_hours * 3600) + (tz_minutes * 60));
        let fotz: DateTime<FixedOffset> = DateTime::from_utc(nd, tz);
        fotz.with_timezone(&Local)
    }
}

#[allow(non_snake_case)]
#[derive(RustcDecodable, RustcEncodable, Debug)]
struct TerminalCombo {
    Times: Vec<SailingTime>,
    DepartingTerminalName: String,
    ArrivingTerminalName: String,
}

#[allow(non_snake_case)]
#[derive(RustcDecodable, RustcEncodable, Debug)]
struct ScheduleResult {
    TerminalCombos: Vec<TerminalCombo>,
}
<|endoftext|>


<commit_before>// Copyright 2014 The Rustdown Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![feature(macro_rules)]
#![feature(phase)]
#![feature(globs)]
#![feature(import_shadowing)]
#![crate_id="rustdown#0.1"]

extern crate rustdoc;
extern crate getopts;

use std::os;
use std::path::posix::Path;
use getopts::OptGroup;

use html::ToHtml;

mod blocks;
mod mdfile;
mod html;
mod text;
mod types;
mod convert;

fn print_usage(program: &str, opts: &[OptGroup]) {
    let summary = getopts::short_usage(program, opts);
    let usage = getopts::usage(summary.as_slice(), opts);
    println!("{}", usage);
}

// Get the options.
// Print help if necessary, otherwise return Some(matches).
fn opts() -> Option<getopts::Matches> {
    let args: Vec<String> = os::args();

    let program = "rustdown";

    let opts = [
        getopts::opt("i",
                     "input",
                     "markdown file for input",
                     "INPUT",
                     getopts::Yes,
                     getopts::Req),
        getopts::opt("o",
                     "output",
                     "set output file name",
                     "OUTPUT",
                     getopts::Yes,
                     getopts::Optional),
        getopts::optflag("h", "help", "print this help menu")
    ];
    let matches = match getopts::getopts(args.tail(), opts) {
        Ok(m) => { m }
        Err(f) => {
            println!("{}\n", f.to_string());
            print_usage(program.as_slice(), opts);
            return None;
        }
    };
    if matches.opt_present("h") {
        print_usage(program.as_slice(), opts);
        return None;
    }
    return Some(matches);
}

fn main() {
    match opts() {
        Some(matches) => {
            let input = matches.opt_str("i").expect("-i argument is required!");
            let input_file = match Path::new_opt(input) {
                Some(file) => file,
                None => return,
            };
            match mdfile::open_markdown_file(&input_file) {
                Ok(file) => {
                    let blocks = blocks::blockify_file(file);
                    let markdown = convert::convert(blocks);
                    for md in markdown.iter() {
                        let html = md.to_html();
                        println!("{}", html);
                    }
                }
                Err(e) => {
                    println!("Error opening markdown file:\n{}", e);
                }
            }
        }
        _ => {
            // User asked for help
        }
    }
}
<commit_msg>Change missing input error message<commit_after>// Copyright 2014 The Rustdown Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![feature(macro_rules)]
#![feature(phase)]
#![feature(globs)]
#![feature(import_shadowing)]
#![crate_id="rustdown#0.1"]

extern crate rustdoc;
extern crate getopts;

use std::os;
use std::path::posix::Path;
use getopts::OptGroup;

use html::ToHtml;

mod blocks;
mod mdfile;
mod html;
mod text;
mod types;
mod convert;

fn print_usage(program: &str, opts: &[OptGroup]) {
    let summary = getopts::short_usage(program, opts);
    let usage = getopts::usage(summary.as_slice(), opts);
    println!("{}", usage);
}

// Get the options.
// Print help if necessary, otherwise return Some(matches).
fn opts() -> Option<getopts::Matches> {
    let args: Vec<String> = os::args();

    let program = "rustdown";

    let opts = [
        getopts::opt("i",
                     "input",
                     "markdown file for input",
                     "INPUT",
                     getopts::Yes,
                     getopts::Req),
        getopts::opt("o",
                     "output",
                     "set output file name",
                     "OUTPUT",
                     getopts::Yes,
                     getopts::Optional),
        getopts::optflag("h", "help", "print this help menu")
    ];
    let matches = match getopts::getopts(args.tail(), opts) {
        Ok(m) => { m }
        Err(f) => {
            println!("{}\n", f.to_string());
            print_usage(program.as_slice(), opts);
            return None;
        }
    };
    if matches.opt_present("h") {
        print_usage(program.as_slice(), opts);
        return None;
    }
    return Some(matches);
}

fn main() {
    match opts() {
        Some(matches) => {
            let input = matches.opt_str("i").expect("Some input argument is required!");
            let input_file = match Path::new_opt(input) {
                Some(file) => file,
                None => return,
            };
            match mdfile::open_markdown_file(&input_file) {
                Ok(file) => {
                    let blocks = blocks::blockify_file(file);
                    let markdown = convert::convert(blocks);
                    for md in markdown.iter() {
                        let html = md.to_html();
                        println!("{}", html);
                    }
                }
                Err(e) => {
                    println!("Error opening markdown file:\n{}", e);
                }
            }
        }
        _ => {
            // User asked for help
        }
    }
}
<|endoftext|>