<commit_before>extern crate bindgen;

fn osx_version() -> Result<String, std::io::Error> {
    use std::process::Command;

    let output = Command::new("defaults")
        .arg("read")
        .arg("loginwindow")
        .arg("SystemVersionStampAsString")
        .output()?
        .stdout;
    let version_str = std::str::from_utf8(&output).expect("invalid output from `defaults`");
    let version = version_str.trim_right();

    Ok(version.to_owned())
}

fn parse_version(version: &str) -> Option<i32> {
    version
        .split(".")
        .skip(1)
        .next()
        .and_then(|m| m.parse::<i32>().ok())
}

fn frameworks_path() -> Result<String, std::io::Error> {
    // For 10.13 and higher:
    //
    // While macOS has its system frameworks located at "/System/Library/Frameworks"
    // for actually linking against them (especially for cross-compilation) once
    // has to refer to the frameworks as found within "Xcode.app/Contents/Developer/…".

    if osx_version()
        .and_then(|version| Ok(parse_version(&version).map(|v| v >= 13).unwrap_or(false)))
        .unwrap_or(false)
    {
        use std::process::Command;

        let output = Command::new("xcode-select").arg("-p").output()?.stdout;
        let prefix_str = std::str::from_utf8(&output).expect("invalid output from `xcode-select`");
        let prefix = prefix_str.trim_right();

        let platform = if cfg!(target_os = "macos") {
            "MacOSX"
        } else if cfg!(target_os = "ios") {
            "iPhoneOS"
        } else {
            unreachable!();
        };

        let infix = if prefix == "/Library/Developer/CommandLineTools" {
            format!("SDKs/{}.sdk", platform)
        } else {
            format!(
                "Platforms/{}.platform/Developer/SDKs/{}.sdk",
                platform, platform
            )
        };

        let suffix = "System/Library/Frameworks";
        let directory = format!("{}/{}/{}", prefix, infix, suffix);

        Ok(directory)
    } else {
        Ok("/System/Library/Frameworks".to_string())
    }
}

fn build(frameworks_path: &str) {
    // Generate one large set of bindings for all frameworks.
    //
    // We do this rather than generating a module per framework as some frameworks depend on other
    // frameworks and in turn share types. To ensure all types are compatible across each
    // framework, we feed all headers to bindgen at once.
    //
    // Only link to each framework and include their headers if their features are enabled and they
    // are available on the target os.

    use std::env;
    use std::path::PathBuf;

    let mut frameworks = vec![];
    let mut headers = vec![];

    #[cfg(feature = "audio_toolbox")]
    {
        println!("cargo:rustc-link-lib=framework=AudioToolbox");
        frameworks.push("AudioToolbox");
        headers.push("AudioToolbox.framework/Headers/AudioToolbox.h");
    }

    #[cfg(feature = "audio_unit")]
    {
        println!("cargo:rustc-link-lib=framework=AudioUnit");
        frameworks.push("AudioUnit");
        headers.push("AudioUnit.framework/Headers/AudioUnit.h");
    }

    #[cfg(feature = "core_audio")]
    {
        println!("cargo:rustc-link-lib=framework=CoreAudio");
        frameworks.push("CoreAudio");
        headers.push("CoreAudio.framework/Headers/CoreAudio.h");
    }

    #[cfg(feature = "open_al")]
    {
        println!("cargo:rustc-link-lib=framework=OpenAL");
        frameworks.push("OpenAL");
        headers.push("OpenAL.framework/Headers/al.h");
        headers.push("OpenAL.framework/Headers/alc.h");
    }

    #[cfg(all(feature = "core_midi", target_os = "macos"))]
    {
        println!("cargo:rustc-link-lib=framework=CoreMIDI");
        frameworks.push("CoreMIDI");
        headers.push("CoreMIDI.framework/Headers/CoreMIDI.h");
    }

    // Get the cargo out directory.
    let out_dir = PathBuf::from(env::var("OUT_DIR").expect("env variable OUT_DIR not found"));

    // Begin building the bindgen params.
    let mut builder = bindgen::Builder::default();

    builder = builder.clang_arg(format!("-F/{}", frameworks_path));

    // Add all headers.
    for relative_path in headers {
        let absolute_path = format!("{}/{}", frameworks_path, relative_path);
        builder = builder.header(absolute_path);
    }

    // Link to all frameworks.
    for relative_path in frameworks {
        let link_instruction = format!("#[link = \"{}/{}\"]", frameworks_path, relative_path);
        builder = builder.raw_line(link_instruction);
    }

    // Generate the bindings.
    let bindings = builder
        .trust_clang_mangling(false)
        .derive_default(true)
        .rustfmt_bindings(false)
        .generate()
        .expect("unable to generate bindings");

    // Write them to the crate root.
    bindings
        .write_to_file(out_dir.join("coreaudio.rs"))
        .expect("could not write bindings");
}

#[cfg(any(target_os = "macos", target_os = "ios"))]
fn main() {
    if let Ok(directory) = frameworks_path() {
        build(&directory);
    } else {
        eprintln!("coreaudio-sys could not find frameworks path");
    }
}

#[cfg(not(any(target_os = "macos", target_os = "ios")))]
fn main() {
    eprintln!("coreaudio-sys requires macos or ios target");
}
<commit_msg>Support Linux Cross Compiling<commit_after>extern crate bindgen;

fn osx_version() -> Result<String, std::io::Error> {
    use std::process::Command;

    let output = Command::new("defaults")
        .arg("read")
        .arg("loginwindow")
        .arg("SystemVersionStampAsString")
        .output()?
        .stdout;
    let version_str = std::str::from_utf8(&output).expect("invalid output from `defaults`");
    let version = version_str.trim_right();

    Ok(version.to_owned())
}

fn parse_version(version: &str) -> Option<i32> {
    version
        .split(".")
        .skip(1)
        .next()
        .and_then(|m| m.parse::<i32>().ok())
}

fn frameworks_path() -> Result<String, std::io::Error> {
    // For 10.13 and higher:
    //
    // While macOS has its system frameworks located at "/System/Library/Frameworks"
    // for actually linking against them (especially for cross-compilation) once
    // has to refer to the frameworks as found within "Xcode.app/Contents/Developer/…".

    // Use environment variable if set
    if let Ok(path) = std::env::var("COREAUDIO_FRAMEWORKS_PATH") {
        return Ok(path)
    }

    if osx_version()
        .and_then(|version| Ok(parse_version(&version).map(|v| v >= 13).unwrap_or(false)))
        .unwrap_or(false)
    {
        use std::process::Command;

        let output = Command::new("xcode-select").arg("-p").output()?.stdout;
        let prefix_str = std::str::from_utf8(&output).expect("invalid output from `xcode-select`");
        let prefix = prefix_str.trim_right();

        let target = std::env::var("TARGET").unwrap();
        let platform = if target.contains("apple-darwin") {
            "MacOSX"
        } else if target.contains("apple-ios") {
            "iPhoneOS"
        } else {
            unreachable!();
        };

        let infix = if prefix == "/Library/Developer/CommandLineTools" {
            format!("SDKs/{}.sdk", platform)
        } else {
            format!(
                "Platforms/{}.platform/Developer/SDKs/{}.sdk",
                platform, platform
            )
        };

        let suffix = "System/Library/Frameworks";
        let directory = format!("{}/{}/{}", prefix, infix, suffix);

        Ok(directory)
    } else {
        Ok("/System/Library/Frameworks".to_string())
    }
}

fn build(frameworks_path: &str) {
    // Generate one large set of bindings for all frameworks.
    //
    // We do this rather than generating a module per framework as some frameworks depend on other
    // frameworks and in turn share types. To ensure all types are compatible across each
    // framework, we feed all headers to bindgen at once.
    //
    // Only link to each framework and include their headers if their features are enabled and they
    // are available on the target os.

    use std::env;
    use std::path::PathBuf;

    let mut frameworks = vec![];
    let mut headers = vec![];

    #[cfg(feature = "audio_toolbox")]
    {
        println!("cargo:rustc-link-lib=framework=AudioToolbox");
        frameworks.push("AudioToolbox");
        headers.push("AudioToolbox.framework/Headers/AudioToolbox.h");
    }

    #[cfg(feature = "audio_unit")]
    {
        println!("cargo:rustc-link-lib=framework=AudioUnit");
        frameworks.push("AudioUnit");
        headers.push("AudioUnit.framework/Headers/AudioUnit.h");
    }

    #[cfg(feature = "core_audio")]
    {
        println!("cargo:rustc-link-lib=framework=CoreAudio");
        frameworks.push("CoreAudio");
        headers.push("CoreAudio.framework/Headers/CoreAudio.h");
    }

    #[cfg(feature = "open_al")]
    {
        println!("cargo:rustc-link-lib=framework=OpenAL");
        frameworks.push("OpenAL");
        headers.push("OpenAL.framework/Headers/al.h");
        headers.push("OpenAL.framework/Headers/alc.h");
    }

    #[cfg(all(feature = "core_midi"))]
    {
        if std::env::var("TARGET").unwrap().contains("apple-darwin") {
            println!("cargo:rustc-link-lib=framework=CoreMIDI");
            frameworks.push("CoreMIDI");
            headers.push("CoreMIDI.framework/Headers/CoreMIDI.h");
        }
    }

    // Get the cargo out directory.
    let out_dir = PathBuf::from(env::var("OUT_DIR").expect("env variable OUT_DIR not found"));

    // Begin building the bindgen params.
    let mut builder = bindgen::Builder::default();

    builder = builder.clang_arg(format!("-F/{}", frameworks_path));

    // Add all headers.
    for relative_path in headers {
        let absolute_path = format!("{}/{}", frameworks_path, relative_path);
        builder = builder.header(absolute_path);
    }

    // Link to all frameworks.
    for relative_path in frameworks {
        let link_instruction = format!("#[link = \"{}/{}\"]", frameworks_path, relative_path);
        builder = builder.raw_line(link_instruction);
    }

    // Generate the bindings.
    builder = builder
        .trust_clang_mangling(false)
        .derive_default(true)
        .rustfmt_bindings(false);

    if let Ok(cflags) = std::env::var("COREAUDIO_CFLAGS") {
        builder = builder.clang_args(cflags.split(" "));
    }

    let bindings = builder
        .generate()
        .expect("unable to generate bindings");

    // Write them to the crate root.
    bindings
        .write_to_file(out_dir.join("coreaudio.rs"))
        .expect("could not write bindings");
}

fn main() {
    let target = std::env::var("TARGET").unwrap();
    if ! (target.contains("apple-darwin") || target.contains("apple-ios")) {
        eprintln!("coreaudio-sys requires macos or ios target");
    }

    if let Ok(directory) = frameworks_path() {
        build(&directory);
    } else {
        eprintln!("coreaudio-sys could not find frameworks path");
    }
}

<|endoftext|>


<commit_before>extern crate gcc;

use std::env;

fn compile_chipmunk() {
    let input = [
        "chipmunk/src/chipmunk.c",
        "chipmunk/src/cpArbiter.c",
        "chipmunk/src/cpArray.c",
        "chipmunk/src/cpBBTree.c",
        "chipmunk/src/cpBody.c",
        "chipmunk/src/cpCollision.c",
        "chipmunk/src/cpConstraint.c",
        "chipmunk/src/cpDampedRotarySpring.c",
        "chipmunk/src/cpDampedSpring.c",
        "chipmunk/src/cpGearJoint.c",
        "chipmunk/src/cpGrooveJoint.c",
        "chipmunk/src/cpHashSet.c",
        "chipmunk/src/cpHastySpace.c",
        "chipmunk/src/cpMarch.c",
        "chipmunk/src/cpPinJoint.c",
        "chipmunk/src/cpPivotJoint.c",
        "chipmunk/src/cpPolyShape.c",
        "chipmunk/src/cpPolyline.c",
        "chipmunk/src/cpRatchetJoint.c",
        "chipmunk/src/cpRotaryLimitJoint.c",
        "chipmunk/src/cpShape.c",
        "chipmunk/src/cpSimpleMotor.c",
        "chipmunk/src/cpSlideJoint.c",
        "chipmunk/src/cpSpace.c",
        "chipmunk/src/cpSpaceComponent.c",
        "chipmunk/src/cpSpaceDebug.c",
        "chipmunk/src/cpSpaceHash.c",
        "chipmunk/src/cpSpaceQuery.c",
        "chipmunk/src/cpSpaceStep.c",
        "chipmunk/src/cpSpatialIndex.c",
        "chipmunk/src/cpSweep1D.c",
    ];

      let mut conf = gcc::Config::new();

      conf.include("chipmunk/include/");
      conf.flag("-g");
      conf.flag("-std=c99");

      if let Ok(profile) = env::var("PROFILE") {
          if "release" == profile {
              conf.flag("-DNDEBUG");
          }
      }

      for src in &input {
          conf.file(src);
      }

      conf.compile("libchipmunk.a");
}

fn main() {
    compile_chipmunk();
}
<commit_msg>Only compile library with -g for debug bulids.<commit_after>extern crate gcc;

use std::env;

fn compile_chipmunk() {
    let input = [
        "chipmunk/src/chipmunk.c",
        "chipmunk/src/cpArbiter.c",
        "chipmunk/src/cpArray.c",
        "chipmunk/src/cpBBTree.c",
        "chipmunk/src/cpBody.c",
        "chipmunk/src/cpCollision.c",
        "chipmunk/src/cpConstraint.c",
        "chipmunk/src/cpDampedRotarySpring.c",
        "chipmunk/src/cpDampedSpring.c",
        "chipmunk/src/cpGearJoint.c",
        "chipmunk/src/cpGrooveJoint.c",
        "chipmunk/src/cpHashSet.c",
        "chipmunk/src/cpHastySpace.c",
        "chipmunk/src/cpMarch.c",
        "chipmunk/src/cpPinJoint.c",
        "chipmunk/src/cpPivotJoint.c",
        "chipmunk/src/cpPolyShape.c",
        "chipmunk/src/cpPolyline.c",
        "chipmunk/src/cpRatchetJoint.c",
        "chipmunk/src/cpRotaryLimitJoint.c",
        "chipmunk/src/cpShape.c",
        "chipmunk/src/cpSimpleMotor.c",
        "chipmunk/src/cpSlideJoint.c",
        "chipmunk/src/cpSpace.c",
        "chipmunk/src/cpSpaceComponent.c",
        "chipmunk/src/cpSpaceDebug.c",
        "chipmunk/src/cpSpaceHash.c",
        "chipmunk/src/cpSpaceQuery.c",
        "chipmunk/src/cpSpaceStep.c",
        "chipmunk/src/cpSpatialIndex.c",
        "chipmunk/src/cpSweep1D.c",
    ];

      let mut conf = gcc::Config::new();

      conf.include("chipmunk/include/");
      conf.flag("-std=c99");

      if let Ok(profile) = env::var("PROFILE") {
          if "debug" == profile {
            conf.flag("-g");
          }
          if "release" == profile {
              conf.flag("-DNDEBUG");
          }
      }

      for src in &input {
          conf.file(src);
      }

      conf.compile("libchipmunk.a");
}

fn main() {
    compile_chipmunk();
}
<|endoftext|>


<commit_before>use std::old_io::Command;
use std::os;

fn main() {
    let curr_dir = Path::new(os::getenv("CARGO_MANIFEST_DIR").unwrap());
    Command::new("git").arg("submodule").arg("update").arg("--init").cwd(&curr_dir).status().unwrap();

    let nvim_dir = curr_dir.join("neovim");
    Command::new("make").arg("libnvim").cwd(&nvim_dir).status().unwrap();

    let nvim_lib_dir = nvim_dir.join_many(&["build", "lib"]);
    let deps_lib_dir = nvim_dir.join_many(&[".deps", "usr", "lib"]);
    println!("cargo:rustc-flags=-L {} -L {} -l nvim:static",
        nvim_lib_dir.as_str().unwrap(),
        deps_lib_dir.as_str().unwrap());
}
<commit_msg>Build deps before libnvim<commit_after>use std::old_io::Command;
use std::os;

fn main() {
    let curr_dir = Path::new(os::getenv("CARGO_MANIFEST_DIR").unwrap());
    Command::new("git").arg("submodule").arg("update").arg("--init").cwd(&curr_dir).status().unwrap();

    let nvim_dir = curr_dir.join("neovim");
    Command::new("make").arg("deps").cwd(&nvim_dir).status().unwrap();
    Command::new("make").arg("libnvim").cwd(&nvim_dir).status().unwrap();

    let nvim_lib_dir = nvim_dir.join_many(&["build", "lib"]);
    let deps_lib_dir = nvim_dir.join_many(&[".deps", "usr", "lib"]);
    println!("cargo:rustc-flags=-L {} -L {} -l nvim:static",
        nvim_lib_dir.as_str().unwrap(),
        deps_lib_dir.as_str().unwrap());
}
<|endoftext|>


<commit_before>extern crate git2;

use git2::{Repository, DescribeOptions, DescribeFormatOptions};

use std::env;
use std::path::Path;
use std::fs::File;
use std::io::Write;

fn main() {
  let profile = env::var("PROFILE").unwrap();
  if profile == "release" {
    return;
  }
  let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
  let repo = match Repository::open(&manifest_dir) {
    Ok(r) => r,
    Err(e) => panic!("Could not read git repository in {}: {}", manifest_dir, e)
  };
  let version = repo
  .describe(
    DescribeOptions::new().describe_tags().show_commit_oid_as_fallback(true)
  )
  .unwrap()
  .format(
    Some(DescribeFormatOptions::new().dirty_suffix("-dirty"))
  )
  .unwrap();

  let out_dir = env::var("OUT_DIR").unwrap();
  let dest_path = Path::new(&out_dir).join("git_short_tag.rs");
  let mut f = File::create(&dest_path).unwrap();
  f.write_all(format!("
      fn git_short_tag() -> &'static str {{
          \"-{}\"
      }}
  ", version).as_bytes()).unwrap();
}
<commit_msg>fix(build): make build script generate included function on release profile<commit_after>extern crate git2;

use git2::{Repository, DescribeOptions, DescribeFormatOptions};

use std::env;
use std::path::Path;
use std::fs::File;
use std::io::Write;

fn main() {
  let profile = env::var("PROFILE").unwrap();
  let version = if profile == "release" {
    String::from("")
  } else {
    let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
    let repo = match Repository::open(&manifest_dir) {
      Ok(r) => r,
      Err(e) => panic!("Could not read git repository in {}: {}", manifest_dir, e)
    };
    let version = repo
    .describe(
      DescribeOptions::new().describe_tags().show_commit_oid_as_fallback(true)
    )
    .unwrap()
    .format(
      Some(DescribeFormatOptions::new().dirty_suffix("-dirty"))
    )
    .unwrap();
    String::from("-") + &version
  };

  let out_dir = env::var("OUT_DIR").unwrap();
  let dest_path = Path::new(&out_dir).join("git_short_tag.rs");
  let mut f = File::create(&dest_path).unwrap();
  f.write_all(format!("
      fn git_short_tag() -> &'static str {{
          \"{}\"
      }}
  ", version).as_bytes()).unwrap();
}
<|endoftext|>


<commit_before>use std::env;
use std::error::Error;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
use std::process::Command;

struct Ignore;

impl<E> From<E> for Ignore where E: Error
{
    fn from(_: E) -> Ignore { Ignore }
}

fn main() -> Result<(), std::io::Error> {
    let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap());
    File::create(out_dir.join("commit-info.txt"))?.write_all(commit_info().as_bytes())?;
    let log_level = env::var("LOG_LEVEL").unwrap_or_else(|_| "OFF".to_string());
    File::create(out_dir.join("log-level.txt"))?.write_all(log_level.as_bytes())?;
    Ok(println!("cargo:rerun-if-changed=build.rs"))
}

fn commit_info() -> String {
    match (commit_date(), commit_hash()) {
        (Ok(date), Ok(hash)) => format!(" {} {}", date.trim_end(), hash.trim_end(),),
        _ => String::new(),
    }
}

fn commit_hash() -> Result<String, Ignore> {
    let args = &["rev-parse", "--short=10", "HEAD"];
    Ok(String::from_utf8(Command::new("git").args(args).output()?.stdout)?)
}

fn commit_date() -> Result<String, Ignore> {
    let args = &["log", "-1", "--date=short", "--pretty=format:%cd"];
    Ok(String::from_utf8(Command::new("git").args(args).output()?.stdout)?)
}
<commit_msg>Avoid unit args<commit_after>use std::env;
use std::error::Error;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
use std::process::Command;

struct Ignore;

impl<E> From<E> for Ignore where E: Error
{
    fn from(_: E) -> Ignore { Ignore }
}

fn main() -> Result<(), std::io::Error> {
    let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap());
    File::create(out_dir.join("commit-info.txt"))?.write_all(commit_info().as_bytes())?;
    let log_level = env::var("LOG_LEVEL").unwrap_or_else(|_| "OFF".to_string());
    File::create(out_dir.join("log-level.txt"))?.write_all(log_level.as_bytes())?;
    println!("cargo:rerun-if-changed=build.rs");
    Ok(())
}

fn commit_info() -> String {
    match (commit_date(), commit_hash()) {
        (Ok(date), Ok(hash)) => format!(" {} {}", date.trim_end(), hash.trim_end(),),
        _ => String::new(),
    }
}

fn commit_hash() -> Result<String, Ignore> {
    let args = &["rev-parse", "--short=10", "HEAD"];
    Ok(String::from_utf8(Command::new("git").args(args).output()?.stdout)?)
}

fn commit_date() -> Result<String, Ignore> {
    let args = &["log", "-1", "--date=short", "--pretty=format:%cd"];
    Ok(String::from_utf8(Command::new("git").args(args).output()?.stdout)?)
}
<|endoftext|>


<commit_before>use std::env;
use std::fs::{File, OpenOptions};
use std::path::Path;
use std::process::Command;

trait CheckedCommand {
    fn check(&mut self);
}

impl CheckedCommand for Command {
    fn check(&mut self) {
        if !self.status().unwrap().success() {
            panic!("command {:?} failed", self)
        }
    }
}

fn main() {
    // Unless otherwise specified, do not re-run this script
    println!("cargo:rerun-if-changed=build.rs");

    let out_dir = env::var("OUT_DIR").unwrap();
    let out_path = Path::new(&out_dir);

    let src_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
    let src_path = Path::new(&src_dir);

    let schema_path = out_path.join("graphql-schema.json");

    eprintln!("ENV: {:?}", env::vars().collect::<Vec<_>>());

    if env::var_os("CARGO_FEATURE_GRAPHQL_SCHEMA").is_some() {
        Command::new(env::var("CARGO").unwrap())
            .args(&[
                "install",
                "-vv",
                "--path",
                src_dir.as_ref(),
                "--bin",
                "turingarena-graphql-schema",
                "--root",
                out_path.to_str().unwrap(),
                "--force",
                "--debug",
                "--offline",
                "--no-default-features",
                "--features",
                "contest",
            ])
            .env_clear()
            .envs(
                std::env::vars_os()
                    .filter(|(k, _)| !k.to_string_lossy().starts_with("CARGO_FEATURE_")),
            )
            .env(
                "CARGO_TARGET_DIR",
                out_path.join("graphql-schema-target").to_str().unwrap(),
            )
            .check();

        let schema_file = File::create(&schema_path).unwrap();

        Command::new(out_path.join("bin").join("turingarena-graphql-schema"))
            .stdout(schema_file)
            .check();
    }

    if env::var_os("CARGO_FEATURE_CLI_ADMIN").is_some() {
        let operations_path = src_path
            .join("src")
            .join("contest")
            .join("operations.graphql");
        println!(
            "cargo:rerun-if-changed={}",
            operations_path.to_str().unwrap()
        );

        Command::new(env::var("CARGO").unwrap())
            .args(&[
                "install",
                "-vv",
                "graphql_client_cli",
                "--root",
                out_path.to_str().unwrap(),
                "--force",
                // FIXME: should be offline
                // "--offline",
            ])
            .env(
                "CARGO_TARGET_DIR",
                out_path.join("graphql-client-cli-target").to_str().unwrap(),
            )
            .check();

        Command::new(out_path.join("bin").join("graphql-client"))
            .args(&[
                "generate",
                "--output-directory",
                out_path.to_str().unwrap(),
                "--schema-path",
                schema_path.to_str().unwrap(),
                operations_path.to_str().unwrap(),
            ])
            .check();
    }

    if env::var_os("CARGO_FEATURE_CONTEST").is_some() {
        extern crate ssri;
        extern crate tar;
        extern crate xz2;

        let initial_contest_path = src_path.join("initial-contest");

        let mut file = OpenOptions::new()
            .write(true)
            .create(true)
            .open(out_path.join("initial-contest.tar.xz"))
            .expect("Unable to open archive file");

        let mut builder = tar::Builder::new(xz2::write::XzEncoder::new(&mut file, 5));
        builder
            .append_dir_all(".", initial_contest_path)
            .expect("Unable to add dir to archive");
        builder
            .into_inner()
            .expect("Unable to build archive")
            .finish()
            .expect("Unable to build archive");
    }

    if env::var_os("CARGO_FEATURE_WEB").is_some() {
        println!("cargo:rerun-if-changed=web/");

        {
            let mut options = fs_extra::dir::CopyOptions::new();
            options.overwrite = true;
            fs_extra::dir::copy(src_path.join("web"), out_path, &options).unwrap();
        }

        let out_web_path = out_path.join("web");

        Command::new("npm")
            .current_dir(&out_web_path)
            .args(&["ci", "--ignore-scripts"])
            .check();

        std::fs::create_dir_all(&out_web_path.join("__generated__")).unwrap();

        std::fs::copy(
            &schema_path,
            &out_web_path
                .join("__generated__")
                .join("graphql-schema.json"),
        )
        .unwrap();

        Command::new("npm")
            .current_dir(&out_web_path)
            .args(&["run", "prepare"])
            .check();

        Command::new("npm")
            .current_dir(&out_web_path)
            .args(&["run", "build"])
            .check();
    }
}
<commit_msg>Actually rerun build script when `web/` changes<commit_after>use std::env;
use std::fs::{DirEntry, File, OpenOptions};
use std::path::Path;
use std::process::Command;

trait CheckedCommand {
    fn check(&mut self);
}

impl CheckedCommand for Command {
    fn check(&mut self) {
        if !self.status().unwrap().success() {
            panic!("command {:?} failed", self)
        }
    }
}

fn traverse_dir<P: AsRef<Path>, F: Fn(&DirEntry) -> () + Copy>(p: P, f: F) {
    for x in std::fs::read_dir(p).unwrap() {
        let x = x.unwrap();
        f(&x);
        if x.file_type().unwrap().is_dir() {
            traverse_dir(x.path(), f)
        }
    }
}

fn main() {
    // Unless otherwise specified, do not re-run this script
    println!("cargo:rerun-if-changed=build.rs");

    let out_dir = env::var("OUT_DIR").unwrap();
    let out_path = Path::new(&out_dir);

    let src_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
    let src_path = Path::new(&src_dir);

    let schema_path = out_path.join("graphql-schema.json");

    eprintln!("ENV: {:?}", env::vars().collect::<Vec<_>>());

    if env::var_os("CARGO_FEATURE_GRAPHQL_SCHEMA").is_some() {
        Command::new(env::var("CARGO").unwrap())
            .args(&[
                "install",
                "-vv",
                "--path",
                src_dir.as_ref(),
                "--bin",
                "turingarena-graphql-schema",
                "--root",
                out_path.to_str().unwrap(),
                "--force",
                "--debug",
                "--offline",
                "--no-default-features",
                "--features",
                "contest",
            ])
            .env_clear()
            .envs(
                std::env::vars_os()
                    .filter(|(k, _)| !k.to_string_lossy().starts_with("CARGO_FEATURE_")),
            )
            .env(
                "CARGO_TARGET_DIR",
                out_path.join("graphql-schema-target").to_str().unwrap(),
            )
            .check();

        let schema_file = File::create(&schema_path).unwrap();

        Command::new(out_path.join("bin").join("turingarena-graphql-schema"))
            .stdout(schema_file)
            .check();
    }

    if env::var_os("CARGO_FEATURE_CLI_ADMIN").is_some() {
        let operations_path = src_path
            .join("src")
            .join("contest")
            .join("operations.graphql");
        println!(
            "cargo:rerun-if-changed={}",
            operations_path.to_str().unwrap()
        );

        Command::new(env::var("CARGO").unwrap())
            .args(&[
                "install",
                "-vv",
                "graphql_client_cli",
                "--root",
                out_path.to_str().unwrap(),
                "--force",
                // FIXME: should be offline
                // "--offline",
            ])
            .env(
                "CARGO_TARGET_DIR",
                out_path.join("graphql-client-cli-target").to_str().unwrap(),
            )
            .check();

        Command::new(out_path.join("bin").join("graphql-client"))
            .args(&[
                "generate",
                "--output-directory",
                out_path.to_str().unwrap(),
                "--schema-path",
                schema_path.to_str().unwrap(),
                operations_path.to_str().unwrap(),
            ])
            .check();
    }

    if env::var_os("CARGO_FEATURE_CONTEST").is_some() {
        extern crate ssri;
        extern crate tar;
        extern crate xz2;

        let initial_contest_path = src_path.join("initial-contest");

        let mut file = OpenOptions::new()
            .write(true)
            .create(true)
            .open(out_path.join("initial-contest.tar.xz"))
            .expect("Unable to open archive file");

        let mut builder = tar::Builder::new(xz2::write::XzEncoder::new(&mut file, 5));
        builder
            .append_dir_all(".", initial_contest_path)
            .expect("Unable to add dir to archive");
        builder
            .into_inner()
            .expect("Unable to build archive")
            .finish()
            .expect("Unable to build archive");
    }

    if env::var_os("CARGO_FEATURE_WEB").is_some() {
        traverse_dir(src_path.join("web").join("projects"), |x| {
            println!("cargo:rerun-if-changed={}", x.path().to_str().unwrap());
        });

        {
            let mut options = fs_extra::dir::CopyOptions::new();
            options.overwrite = true;
            fs_extra::dir::copy(src_path.join("web"), out_path, &options).unwrap();
        }

        let out_web_path = out_path.join("web");

        Command::new("npm")
            .current_dir(&out_web_path)
            .args(&["ci", "--ignore-scripts"])
            .check();

        std::fs::create_dir_all(&out_web_path.join("__generated__")).unwrap();

        std::fs::copy(
            &schema_path,
            &out_web_path
                .join("__generated__")
                .join("graphql-schema.json"),
        )
        .unwrap();

        Command::new("npm")
            .current_dir(&out_web_path)
            .args(&["run", "prepare"])
            .check();

        Command::new("npm")
            .current_dir(&out_web_path)
            .args(&["run", "build"])
            .check();
    }
}
<|endoftext|>


<commit_before>//! Get the version string using `git describe --dirty` or, if it
//! fails, using the `CARGO_PKG_VERSION`.
//!
//! The `GIT` environment variable can be used to set an alternative
//! path to the git executable.
//!
//! Copied from https://github.com/simias/pockystation/blob/master/build.rs

use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use std::process::Command;

fn main() {
    let out_dir = env::var("OUT_DIR").unwrap();
    let dest_path = Path::new(&out_dir).join("version.rs");
    let mut f = File::create(&dest_path).unwrap();

    let git =
        env::var("GIT").unwrap_or("git".into());

    let description =
        Command::new(git)
        .arg("describe")
        .arg("--dirty")
        .arg("--tags")
        .output();

    let cargo_version = env!("CARGO_PKG_VERSION").to_owned();

    let mut version =
        match description {
            Ok(output) => {
                if output.status.success() {
                    format!("git-{}",
                            String::from_utf8(output.stdout).unwrap())
                } else {
                    cargo_version
                }
            }
            _ => cargo_version,
        };

    // Make sure version is on a single line
    if let Some(l) = version.find('\n') {
        version.truncate(l);
    }

    writeln!(f, "pub const VERSION: &'static str = \
                 \"{}\";", version).unwrap();
    writeln!(f, "pub const VERSION_CSTR: &'static str = \
                 \"{}\\0\";", version).unwrap();
}

<commit_msg>version string used libgerrit tags, now it uses gerrit-rust tags<commit_after>//! Get the version string using `git describe --dirty` or, if it
//! fails, using the `CARGO_PKG_VERSION`.
//!
//! The `GIT` environment variable can be used to set an alternative
//! path to the git executable.
//!
//! Copied from https://github.com/simias/pockystation/blob/master/build.rs

use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use std::process::Command;

fn main() {
    let out_dir = env::var("OUT_DIR").unwrap();
    let dest_path = Path::new(&out_dir).join("version.rs");
    let mut f = File::create(&dest_path).unwrap();

    let git =
        env::var("GIT").unwrap_or("git".into());

    let description =
        Command::new(git)
        .arg("describe")
        .arg("--dirty")
        .arg("--tags")
        .arg("--match")
        .arg("v*")
        .output();

    let cargo_version = env!("CARGO_PKG_VERSION").to_owned();

    let mut version =
        match description {
            Ok(output) => {
                if output.status.success() {
                    format!("git-{}",
                            String::from_utf8(output.stdout).unwrap())
                } else {
                    cargo_version
                }
            }
            _ => cargo_version,
        };

    // Make sure version is on a single line
    if let Some(l) = version.find('\n') {
        version.truncate(l);
    }

    writeln!(f, "pub const VERSION: &'static str = \
                 \"{}\";", version).unwrap();
    writeln!(f, "pub const VERSION_CSTR: &'static str = \
                 \"{}\\0\";", version).unwrap();
}

<|endoftext|>


<commit_before>use std::rc::Rc;
use std::vec::Vec;

#[cfg(not(target_os="linux"))]
use nix::c_int;
#[cfg(not(target_os="linux"))]
use nix::sys::signal::{SaFlags, SigHandler, SigAction, sigaction};
use nix::sys::signal::{SigSet, Signal};
use nix::sys::wait::{wait, WaitStatus};
use nix::unistd::{fork, ForkResult};

use errors::*;

pub enum Strategy {
    OneForOne,
    OneForAll,
    RestForOne,
    SimpleOneForOne,
}

#[derive(Clone)]
pub enum WorkerLifetime {
    Permanent,
    Temporary,
    Transient,
}

#[derive(Clone)]
pub enum ProcessType {
    Worker,
    Supervisor,
}

#[derive(Clone)]
pub enum ShutdownType {
    BrutalKill,
    Infinity,
    Timeout(u64),
}

pub trait Supervisable {
    fn init(&self) -> Result<()>;
    fn finalize(&self) -> Result<()>;
}

pub struct SupervisorFlags {
    strategy: Strategy,
    intensity: u64,
    period: u64,
}

impl SupervisorFlags {
    pub fn new(strategy: Strategy, intensity: u64, period: u64) -> Option<SupervisorFlags> {
        if period > 0 {
            Some(SupervisorFlags {
                strategy: strategy,
                intensity: intensity,
                period: period,
            })
        } else {
            None
        }
    }
}

#[derive(Clone)]
pub struct ChildSpecs {
    id: String,
    worker: Rc<Supervisable>,
    restart: WorkerLifetime,
    shutdown: ShutdownType,
    process_type: ProcessType,
}

impl ChildSpecs {
    pub fn new(id: &str,
               worker: Rc<Supervisable>,
               restart: WorkerLifetime,
               shutdown: ShutdownType,
               process_type: ProcessType)
               -> ChildSpecs {
        ChildSpecs {
            id: id.to_owned(),
            worker: worker,
            restart: restart,
            shutdown: shutdown,
            process_type: process_type,
        }
    }
}

pub struct Supervisor {
    flags: SupervisorFlags,
    child_specs: Vec<ChildSpecs>,
}

impl Supervisor {
    pub fn new(flags: SupervisorFlags, child_specs: &[ChildSpecs]) -> Supervisor {
        Supervisor {
            flags: flags,
            child_specs: child_specs.to_vec(),
        }
    }

    /// Runs the supervisor for the given child tasks
    pub fn run(&self) -> Result<()> {
        info!("Supervisor start");
        self.init().chain_err(|| ErrorKind::SupervisorInitError)?;
        for idx in 0..self.child_specs.len() {
            info!("Supervisor spawning child: {}", self.child_specs[idx].id);
            match fork().chain_err(|| "Could not fork process.")? {
                ForkResult::Child => {
                    self.child_specs[idx].worker.init()?;
                    return Ok(());
                }
                ForkResult::Parent { child: _ } => {}
            }
        }
        self.supervise()?;
        Ok(())
    }

    fn init(&self) -> Result<()> {
        #[cfg(not(target_os="linux"))]
        {
            let mask = SigSet::empty();
            let flags = SaFlags::empty();
            let handler = SigHandler::Handler(null_handler);
            let action = SigAction::new(handler, flags, mask);
            unsafe {
                sigaction(Signal::SIGCHLD, &action)?;
            }
        }
        self.mask_all_signals()?;
        Ok(())
    }

    fn supervise(&self) -> Result<()> {
        let mut active_kids = self.child_specs.len();
        while active_kids > 0 {
            info!("Supervisor waiting for child processes. {} remaining.",
                  active_kids);
            match wait()? {
                WaitStatus::Exited(pid, ret) => {
                    info!("Status: {} exited with code {}", pid, ret);
                }
                _ => {
                    warn!("Unknown action");
                }
            }
            active_kids -= 1;
        }
        Ok(())
    }

    fn mask_all_signals(&self) -> Result<()> {
        Ok(SigSet::all().thread_set_mask()?)
    }
}

#[cfg(not(target_os="linux"))]
extern "C" fn null_handler(_: c_int) -> () {}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {}
}
<commit_msg>Re-adding initial wait for SIGCHLD<commit_after>use std::rc::Rc;
use std::vec::Vec;

#[cfg(not(target_os="linux"))]
use nix::c_int;
#[cfg(not(target_os="linux"))]
use nix::sys::signal::{SaFlags, SigHandler, SigAction, sigaction};
use nix::sys::signal::{SigSet, Signal};
use nix::sys::wait::{wait, WaitStatus};
use nix::unistd::{fork, ForkResult};

use errors::*;

pub enum Strategy {
    OneForOne,
    OneForAll,
    RestForOne,
    SimpleOneForOne,
}

#[derive(Clone)]
pub enum WorkerLifetime {
    Permanent,
    Temporary,
    Transient,
}

#[derive(Clone)]
pub enum ProcessType {
    Worker,
    Supervisor,
}

#[derive(Clone)]
pub enum ShutdownType {
    BrutalKill,
    Infinity,
    Timeout(u64),
}

pub trait Supervisable {
    fn init(&self) -> Result<()>;
    fn finalize(&self) -> Result<()>;
}

pub struct SupervisorFlags {
    strategy: Strategy,
    intensity: u64,
    period: u64,
}

impl SupervisorFlags {
    pub fn new(strategy: Strategy, intensity: u64, period: u64) -> Option<SupervisorFlags> {
        if period > 0 {
            Some(SupervisorFlags {
                strategy: strategy,
                intensity: intensity,
                period: period,
            })
        } else {
            None
        }
    }
}

#[derive(Clone)]
pub struct ChildSpecs {
    id: String,
    worker: Rc<Supervisable>,
    restart: WorkerLifetime,
    shutdown: ShutdownType,
    process_type: ProcessType,
}

impl ChildSpecs {
    pub fn new(id: &str,
               worker: Rc<Supervisable>,
               restart: WorkerLifetime,
               shutdown: ShutdownType,
               process_type: ProcessType)
               -> ChildSpecs {
        ChildSpecs {
            id: id.to_owned(),
            worker: worker,
            restart: restart,
            shutdown: shutdown,
            process_type: process_type,
        }
    }
}

pub struct Supervisor {
    flags: SupervisorFlags,
    child_specs: Vec<ChildSpecs>,
}

impl Supervisor {
    pub fn new(flags: SupervisorFlags, child_specs: &[ChildSpecs]) -> Supervisor {
        Supervisor {
            flags: flags,
            child_specs: child_specs.to_vec(),
        }
    }

    /// Runs the supervisor for the given child tasks
    pub fn run(&self) -> Result<()> {
        info!("Supervisor start");
        self.init().chain_err(|| ErrorKind::SupervisorInitError)?;
        for idx in 0..self.child_specs.len() {
            info!("Supervisor spawning child: {}", self.child_specs[idx].id);
            match fork().chain_err(|| "Could not fork process.")? {
                ForkResult::Child => {
                    self.child_specs[idx].worker.init()?;
                    return Ok(());
                }
                ForkResult::Parent { child: _ } => {}
            }
        }
        self.supervise()?;
        Ok(())
    }

    fn init(&self) -> Result<()> {
        #[cfg(not(target_os="linux"))]
        {
            let mask = SigSet::empty();
            let flags = SaFlags::empty();
            let handler = SigHandler::Handler(null_handler);
            let action = SigAction::new(handler, flags, mask);
            unsafe {
                sigaction(Signal::SIGCHLD, &action)?;
            }
        }
        self.mask_all_signals()?;
        Ok(())
    }

    fn supervise(&self) -> Result<()> {
        let mut sigchld = SigSet::empty();
        sigchld.add(Signal::SIGCHLD);
        sigchld.wait()?;

        let mut active_kids = self.child_specs.len();
        while active_kids > 0 {
            info!("Supervisor waiting for child processes. {} remaining.",
                  active_kids);
            match wait()? {
                WaitStatus::Exited(pid, ret) => {
                    info!("Status: {} exited with code {}", pid, ret);
                }
                _ => {
                    warn!("Unknown action");
                }
            }
            active_kids -= 1;
        }
        Ok(())
    }

    fn mask_all_signals(&self) -> Result<()> {
        Ok(SigSet::all().thread_set_mask()?)
    }
}

#[cfg(not(target_os="linux"))]
extern "C" fn null_handler(_: c_int) -> () {}

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


<commit_before>use iced::*;

//
// Run the Application.
// Call method run() which will take control of the current thread and will NOT return.
// It should be the last thing in the main function.
//
pub fn main() -> iced::Result {
    // Use logger for debug messages.
    simple_logger::init_with_level(log::Level::Warn).unwrap();

    MyApp::run(Settings::default())
}

//
// The state of our application.
//
#[derive(Default)]
struct MyApp {
    button1_state: button::State,
    button2_state: button::State,
    button3_state: button::State,
    phrase_selected: String,
}

//
// The type of messages our application will produce.
//
#[derive(Debug, Clone)]
pub enum Message {
    Phrase(String),
}

//
// Implement Application trait: the main entrypoint of Iced.
// On native platforms, it will run in its own window.
// An Application can execute asynchronous actions by returning
// a Command in some of its methods.
//
impl Application for MyApp {

    type Message = Message;
    type Executor = executor::Default;
    type Flags = ();

    //
    // Initialize the Application.
    // Return the initial state of our app.
    // Also return a Command to perform some async action in the background on startup.
    //
    fn new(_flags: ()) -> (Self, Command<Message>) {
        (
            Self {
                phrase_selected: "Hello, World!".to_string(),
                ..Self::default()
            },
            Command::none(),
        )
    }

    //
    // Return the current title of the Application.
    // This title can be dynamic! The runtime will automatically
    // update the title of the application when necessary.
    //
    fn title(&self) -> String {
        String::from("MyApp - Iced")
    }

    //
    // Process messages and update the state of the Application.
    // All the messages, produced by either user interactions or commands,
    // are be handled by this method.
    // Any Command returned will be executed immediately in the background.
    //
    fn update(&mut self, message: Message, _cb: &mut Clipboard) -> Command<Message> {
        match message {
            Message::Phrase(phrase) => {
                log::warn!("phrase = {}", phrase);
                self.phrase_selected = phrase;
            }
        }

        Command::none()
    }

    //
    // Return the widgets to display in the Application.
    // These widgets can produce messages based on user interaction.
    //
    fn view(&mut self) -> Element<Message> {
        let message = Text::new(&self.phrase_selected)
            .size(96);

        let canvas = Container::new(message)
            .width(Length::Fill)
            .height(Length::Fill)
            .padding(20)
            .center_x()
            .center_y();

        let controls = Column::new()
            .padding(10)
            .spacing(20)
            .push(Button::new(&mut self.button1_state, Text::new("Hi there!"))
                    .on_press(Message::Phrase("Hi there!".to_string())))
            .push(Button::new(&mut self.button2_state, Text::new("Hola!"))
                    .on_press(Message::Phrase("Hola!".to_string())))
            .push(Button::new(&mut self.button3_state, Text::new("Приветик!"))
                    .on_press(Message::Phrase("Приветик!".to_string())));

        let content = Row::new()
            .spacing(20)
            .push(canvas)
            .push(controls);

        content.into()
    }
}
<commit_msg>Iced demo: use explicit iced:: prefixes.<commit_after>use iced::Application;

//
// Run the Application.
// Call method run() which will take control of the current thread and will NOT return.
// It should be the last thing in the main function.
//
pub fn main() -> iced::Result {
    // Use logger for debug messages.
    simple_logger::init_with_level(log::Level::Warn).unwrap();

    MyApp::run(iced::Settings::default())
}

//
// The state of our application.
//
#[derive(Default)]
struct MyApp {
    button1_state: iced::button::State,
    button2_state: iced::button::State,
    button3_state: iced::button::State,
    phrase_selected: String,
}

//
// The type of messages our application will produce.
//
#[derive(Debug, Clone)]
pub enum Message {
    Phrase(String),
}

//
// Implement Application trait: the main entrypoint of Iced.
// On native platforms, it will run in its own window.
// An Application can execute asynchronous actions by returning
// a Command in some of its methods.
//
impl iced::Application for MyApp {

    type Message = Message;
    type Executor = iced::executor::Default;
    type Flags = ();

    //
    // Initialize the Application.
    // Return the initial state of our app.
    // Also return a Command to perform some async action in the background on startup.
    //
    fn new(_flags: ()) -> (Self, iced::Command<Message>) {
        (
            Self {
                phrase_selected: "Hello, World!".to_string(),
                ..Self::default()
            },
            iced::Command::none(),
        )
    }

    //
    // Return the current title of the Application.
    // This title can be dynamic! The runtime will automatically
    // update the title of the application when necessary.
    //
    fn title(&self) -> String {
        String::from("MyApp - Iced")
    }

    //
    // Process messages and update the state of the Application.
    // All the messages, produced by either user interactions or commands,
    // are be handled by this method.
    // Any Command returned will be executed immediately in the background.
    //
    fn update(&mut self, message: Message, _cb: &mut iced::Clipboard) -> iced::Command<Message> {
        match message {
            Message::Phrase(phrase) => {
                log::warn!("phrase = {}", phrase);
                self.phrase_selected = phrase;
            }
        }

        iced::Command::none()
    }

    //
    // Return the widgets to display in the Application.
    // These widgets can produce messages based on user interaction.
    //
    fn view(&mut self) -> iced::Element<Message> {
        let message = iced::Text::new(&self.phrase_selected)
            .size(96);

        let canvas = iced::Container::new(message)
            .width(iced::Length::Fill)
            .height(iced::Length::Fill)
            .padding(20)
            .center_x()
            .center_y();

        let controls = iced::Column::new()
            .padding(10)
            .spacing(20)
            .push(iced::Button::new(&mut self.button1_state, iced::Text::new("Hi there!"))
                    .on_press(Message::Phrase("Hi there!".to_string())))
            .push(iced::Button::new(&mut self.button2_state, iced::Text::new("Hola!"))
                    .on_press(Message::Phrase("Hola!".to_string())))
            .push(iced::Button::new(&mut self.button3_state, iced::Text::new("Приветик!"))
                    .on_press(Message::Phrase("Приветик!".to_string())));

        let content = iced::Row::new()
            .spacing(20)
            .push(canvas)
            .push(controls);

        content.into()
    }
}
<|endoftext|>


<commit_before>extern crate ansi_term;
#[macro_use(chan_select)]
extern crate chan;
extern crate rand;
extern crate rayon;
extern crate time;
extern crate rustyregisters;

use ansi_term::Colour::*;
use time::Duration;

use rustyregisters::*;

fn main() {
    println!("{} {}",
             Yellow.bold().paint("RustyRegisters"),
             Red.bold().paint("LFSR Benchmark"));

    let two = 2 as usize;
    let width = 64;
    let taps = vec![64 - 1, 63 - 1, 61 - 1, 60 - 1];

    let seeds = two.pow(16);
    let clocks = two.pow(16);

    let galois_duration = time(GaloisLFSR::new(width, taps.clone(), vec![0]), seeds, clocks);
    println!("{} took {:?}ms to perform 2^32 clockings.",
             Purple.bold().paint("GaloisLFSR"),
             galois_duration.num_milliseconds());

    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
    let pop_cnt_duration = time(PopCntLFSR::new(width, taps.clone(), vec![0]), seeds, clocks);
    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
    println!("{} took {:?}ms to perform 2^32 clockings.",
             Purple.bold().paint("PopCntLFSR"),
             pop_cnt_duration.num_milliseconds());

    let count_ones_duration = time(CountOnesLFSR::new(width, taps.clone(), vec![0]),
                                   seeds,
                                   clocks);
    println!("{} took {:?}ms to perform 2^32 clockings.",
             Purple.bold().paint("CountOnesLFSR"),
             count_ones_duration.num_milliseconds());

    let naive_duration = time(NaiveLFSR::new(width, taps.clone(), vec![0]), seeds, clocks);
    println!("{} took {:?}ms to perform 2^32 clockings.",
             Purple.bold().paint("NaiveLFSR"),
             naive_duration.num_milliseconds());
}

fn time<L: LFSRTrait>(mut lfsr: L, seeds: usize, clocks: usize) -> Duration {
    Duration::span(move || {
        for seed in 0..seeds {
            lfsr.set(vec![seed]);
            lfsr.multiclock(clocks);
        }
    })
}
<commit_msg>Fixed usage of GaloisLFSR in LFSR Benchmark.<commit_after>extern crate ansi_term;
#[macro_use(chan_select)]
extern crate chan;
extern crate rand;
extern crate rayon;
extern crate time;
extern crate rustyregisters;

use ansi_term::Colour::*;
use time::Duration;

use rustyregisters::*;

fn main() {
    println!("{} {}",
             Yellow.bold().paint("RustyRegisters"),
             Red.bold().paint("LFSR Benchmark"));

    let two = 2 as usize;
    let width = 64;
    let taps = vec![64 - 1, 63 - 1, 61 - 1, 60 - 1];

    let seeds = two.pow(16);
    let clocks = two.pow(16);

    let galois_duration = time(GaloisLFSR::fibonacci(width, taps.clone(), vec![0]), seeds, clocks);
    println!("{} took {:?}ms to perform 2^32 clockings.",
             Purple.bold().paint("GaloisLFSR"),
             galois_duration.num_milliseconds());

    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
    let pop_cnt_duration = time(PopCntLFSR::new(width, taps.clone(), vec![0]), seeds, clocks);
    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
    println!("{} took {:?}ms to perform 2^32 clockings.",
             Purple.bold().paint("PopCntLFSR"),
             pop_cnt_duration.num_milliseconds());

    let count_ones_duration = time(CountOnesLFSR::new(width, taps.clone(), vec![0]),
                                   seeds,
                                   clocks);
    println!("{} took {:?}ms to perform 2^32 clockings.",
             Purple.bold().paint("CountOnesLFSR"),
             count_ones_duration.num_milliseconds());

    let naive_duration = time(NaiveLFSR::new(width, taps.clone(), vec![0]), seeds, clocks);
    println!("{} took {:?}ms to perform 2^32 clockings.",
             Purple.bold().paint("NaiveLFSR"),
             naive_duration.num_milliseconds());
}

fn time<L: LFSRTrait>(mut lfsr: L, seeds: usize, clocks: usize) -> Duration {
    Duration::span(move || {
        for seed in 0..seeds {
            lfsr.set(vec![seed]);
            lfsr.multiclock(clocks);
        }
    })
}
<|endoftext|>


<commit_before>// Iterates over every crate versions ever uploaded and (re-)renders their
// readme using the Markdown renderer from the cargo_registry crate.
//
// Warning: this can take a lot of time.
//
// Usage:
//     cargo run --bin render-readmes [page-size: optional = 25]
// The page-size argument dictate how much versions should be queried and processed at once.

#![deny(warnings)]

#[macro_use]
extern crate serde_derive;

extern crate cargo_registry;
extern crate curl;
extern crate diesel;
extern crate flate2;
extern crate s3;
extern crate tar;
extern crate time;
extern crate toml;
extern crate url;

use curl::easy::{Easy, List};
use diesel::prelude::*;
use flate2::read::GzDecoder;
use std::env;
use std::io::{Cursor, Read};
use std::path::Path;
use std::thread;
use tar::Archive;
use url::Url;

use cargo_registry::{Config, Version};
use cargo_registry::version::EncodableVersion;
use cargo_registry::schema::*;
use cargo_registry::render::markdown_to_html;

const DEFAULT_PAGE_SIZE: i64 = 25;

fn main() {
    let config: Config = Default::default();
    let conn = cargo_registry::db::connect_now().unwrap();
    let versions_count = versions::table
        .select(versions::all_columns)
        .count()
        .get_result::<i64>(&conn)
        .expect("error counting versions");
    let page_size = match env::args().nth(1) {
        None => DEFAULT_PAGE_SIZE,
        Some(s) => s.parse::<i64>().unwrap_or(DEFAULT_PAGE_SIZE),
    };
    let pages = if versions_count % page_size == 0 {
        versions_count / page_size
    } else {
        versions_count / page_size + 1
    };
    for current_page in 0..pages {
        let versions: Vec<EncodableVersion> = versions::table
            .inner_join(crates::table)
            .select((versions::all_columns, crates::name))
            .limit(page_size)
            .offset(current_page * page_size)
            .load::<(Version, String)>(&conn)
            .expect("error loading versions")
            .into_iter()
            .map(|(version, crate_name)| version.encodable(&crate_name))
            .collect();
        let mut tasks = Vec::with_capacity(page_size as usize);
        for version in versions {
            let config = config.clone();
            let handle = thread::spawn(move || {
                println!("[{}-{}] Rendering README...", version.krate, version.num);
                let readme = get_readme(&config, &version);
                if readme.is_none() {
                    return;
                }
                let readme = readme.unwrap();
                let readme_path = format!(
                    "readmes/{}/{}-{}.html",
                    version.krate,
                    version.krate,
                    version.num
                );
                let readme_len = readme.len();
                let mut body = Cursor::new(readme.into_bytes());
                config
                    .uploader
                    .upload(
                        Easy::new(),
                        &readme_path,
                        &mut body,
                        "text/html",
                        readme_len as u64,
                    )
                    .expect(&format!(
                        "[{}-{}] Couldn't upload file to S3",
                        version.krate,
                        version.num
                    ));
            });
            tasks.push(handle);
        }
        for handle in tasks {
            if let Err(err) = handle.join() {
                println!("Thead panicked: {:?}", err);
            }
        }
    }
}

/// Renders the readme of an uploaded crate version.
fn get_readme(config: &Config, version: &EncodableVersion) -> Option<String> {
    let mut handle = Easy::new();
    let location = match config.uploader.crate_location(&version.krate, &version.num) {
        Some(l) => l,
        None => return None,
    };
    let date = time::now().rfc822z().to_string();
    let url = Url::parse(&location).expect(&format!(
        "[{}-{}] Couldn't parse crate URL",
        version.krate,
        version.num
    ));

    let mut headers = List::new();
    headers
        .append(&format!("Host: {}", url.host().unwrap()))
        .unwrap();
    headers.append(&format!("Date: {}", date)).unwrap();

    handle.url(url.as_str()).unwrap();
    handle.get(true).unwrap();
    handle.http_headers(headers).unwrap();

    let mut response = Vec::new();
    {
        let mut req = handle.transfer();
        req.write_function(|data| {
            response.extend(data);
            Ok(data.len())
        }).unwrap();
        if let Err(err) = req.perform() {
            println!(
                "[{}-{}] Unable to fetch crate: {}",
                version.krate,
                version.num,
                err
            );
            return None;
        }
    }
    if handle.response_code().unwrap() != 200 {
        let response = String::from_utf8_lossy(&response);
        println!(
            "[{}-{}] Failed to get a 200 response: {}",
            version.krate,
            version.num,
            response
        );
        return None;
    }
    let reader = Cursor::new(response);
    let reader = GzDecoder::new(reader).expect(&format!(
        "[{}-{}] Invalid gzip header",
        version.krate,
        version.num
    ));
    let mut archive = Archive::new(reader);
    let mut entries = archive.entries().expect(&format!(
        "[{}-{}] Invalid tar archive entries",
        version.krate,
        version.num
    ));
    let manifest: Manifest = {
        let path = format!("{}-{}/Cargo.toml", version.krate, version.num);
        let contents = find_file_by_path(&mut entries, Path::new(&path), &version);
        toml::from_str(&contents).expect(&format!(
            "[{}-{}] Syntax error in manifest file",
            version.krate,
            version.num
        ))
    };
    if manifest.package.readme.is_none() {
        return None;
    }
    let rendered = {
        let path = format!(
            "{}-{}/{}",
            version.krate,
            version.num,
            manifest.package.readme.unwrap()
        );
        let contents = find_file_by_path(&mut entries, Path::new(&path), &version);
        markdown_to_html(&contents).expect(&format!(
            "[{}-{}] Couldn't render README",
            version.krate,
            version.num
        ))
    };
    return Some(rendered);
    #[derive(Deserialize)]
    struct Package {
        readme: Option<String>,
    }
    #[derive(Deserialize)]
    struct Manifest {
        package: Package,
    }
}

/// Search an entry by its path in a Tar archive.
fn find_file_by_path<R: Read>(
    entries: &mut tar::Entries<R>,
    path: &Path,
    version: &EncodableVersion,
) -> String {
    let mut file = entries
        .find(|entry| match *entry {
            Err(_) => false,
            Ok(ref file) => {
                let filepath = match file.path() {
                    Ok(p) => p,
                    Err(_) => return false,
                };
                return filepath == path;
            }
        })
        .expect(&format!(
            "[{}-{}] couldn't open file: {}",
            version.krate,
            version.num,
            path.display()
        ))
        .expect(&format!(
            "[{}-{}] file is not present: {}",
            version.krate,
            version.num,
            path.display()
        ));
    let mut contents = String::new();
    file.read_to_string(&mut contents).expect(&format!(
        "[{}-{}] Couldn't read file contents",
        version.krate,
        version.num
    ));
    contents
}
<commit_msg>Rendering readmes doesn't need an encodable version<commit_after>// Iterates over every crate versions ever uploaded and (re-)renders their
// readme using the Markdown renderer from the cargo_registry crate.
//
// Warning: this can take a lot of time.
//
// Usage:
//     cargo run --bin render-readmes [page-size: optional = 25]
// The page-size argument dictate how much versions should be queried and processed at once.

#![deny(warnings)]

#[macro_use]
extern crate serde_derive;

extern crate cargo_registry;
extern crate curl;
extern crate diesel;
extern crate flate2;
extern crate s3;
extern crate tar;
extern crate time;
extern crate toml;
extern crate url;

use curl::easy::{Easy, List};
use diesel::prelude::*;
use flate2::read::GzDecoder;
use std::env;
use std::io::{Cursor, Read};
use std::path::Path;
use std::thread;
use tar::Archive;
use url::Url;

use cargo_registry::{Config, Version};
use cargo_registry::schema::*;
use cargo_registry::render::markdown_to_html;

const DEFAULT_PAGE_SIZE: i64 = 25;

fn main() {
    let config: Config = Default::default();
    let conn = cargo_registry::db::connect_now().unwrap();
    let versions_count = versions::table
        .select(versions::all_columns)
        .count()
        .get_result::<i64>(&conn)
        .expect("error counting versions");
    let page_size = match env::args().nth(1) {
        None => DEFAULT_PAGE_SIZE,
        Some(s) => s.parse::<i64>().unwrap_or(DEFAULT_PAGE_SIZE),
    };
    let pages = if versions_count % page_size == 0 {
        versions_count / page_size
    } else {
        versions_count / page_size + 1
    };
    for current_page in 0..pages {
        let versions: Vec<(Version, String)> = versions::table
            .inner_join(crates::table)
            .select((versions::all_columns, crates::name))
            .limit(page_size)
            .offset(current_page * page_size)
            .load::<(Version, String)>(&conn)
            .expect("error loading versions");
        let mut tasks = Vec::with_capacity(page_size as usize);
        for (version, krate_name) in versions {
            let config = config.clone();
            let handle = thread::spawn(move || {
                println!("[{}-{}] Rendering README...", krate_name, version.num);
                let readme = get_readme(&config, &version, &krate_name);
                if readme.is_none() {
                    return;
                }
                let readme = readme.unwrap();
                let readme_path =
                    format!("readmes/{}/{}-{}.html", krate_name, krate_name, version.num);
                let readme_len = readme.len();
                let mut body = Cursor::new(readme.into_bytes());
                config
                    .uploader
                    .upload(
                        Easy::new(),
                        &readme_path,
                        &mut body,
                        "text/html",
                        readme_len as u64,
                    )
                    .expect(&format!(
                        "[{}-{}] Couldn't upload file to S3",
                        krate_name,
                        version.num
                    ));
            });
            tasks.push(handle);
        }
        for handle in tasks {
            if let Err(err) = handle.join() {
                println!("Thread panicked: {:?}", err);
            }
        }
    }
}

/// Renders the readme of an uploaded crate version.
fn get_readme(config: &Config, version: &Version, krate_name: &str) -> Option<String> {
    let mut handle = Easy::new();
    let location = match config.uploader.crate_location(
        &krate_name,
        &version.num.to_string(),
    ) {
        Some(l) => l,
        None => return None,
    };
    let date = time::now().rfc822z().to_string();
    let url = Url::parse(&location).expect(&format!(
        "[{}-{}] Couldn't parse crate URL",
        krate_name,
        version.num
    ));

    let mut headers = List::new();
    headers
        .append(&format!("Host: {}", url.host().unwrap()))
        .unwrap();
    headers.append(&format!("Date: {}", date)).unwrap();

    handle.url(url.as_str()).unwrap();
    handle.get(true).unwrap();
    handle.http_headers(headers).unwrap();

    let mut response = Vec::new();
    {
        let mut req = handle.transfer();
        req.write_function(|data| {
            response.extend(data);
            Ok(data.len())
        }).unwrap();
        if let Err(err) = req.perform() {
            println!(
                "[{}-{}] Unable to fetch crate: {}",
                krate_name,
                version.num,
                err
            );
            return None;
        }
    }
    if handle.response_code().unwrap() != 200 {
        let response = String::from_utf8_lossy(&response);
        println!(
            "[{}-{}] Failed to get a 200 response: {}",
            krate_name,
            version.num,
            response
        );
        return None;
    }
    let reader = Cursor::new(response);
    let reader = GzDecoder::new(reader).expect(&format!(
        "[{}-{}] Invalid gzip header",
        krate_name,
        version.num
    ));
    let mut archive = Archive::new(reader);
    let mut entries = archive.entries().expect(&format!(
        "[{}-{}] Invalid tar archive entries",
        krate_name,
        version.num
    ));
    let manifest: Manifest = {
        let path = format!("{}-{}/Cargo.toml", krate_name, version.num);
        let contents = find_file_by_path(&mut entries, Path::new(&path), &version, &krate_name);
        toml::from_str(&contents).expect(&format!(
            "[{}-{}] Syntax error in manifest file",
            krate_name,
            version.num
        ))
    };
    if manifest.package.readme.is_none() {
        return None;
    }
    let rendered = {
        let path = format!(
            "{}-{}/{}",
            krate_name,
            version.num,
            manifest.package.readme.unwrap()
        );
        let contents = find_file_by_path(&mut entries, Path::new(&path), &version, &krate_name);
        markdown_to_html(&contents).expect(&format!(
            "[{}-{}] Couldn't render README",
            krate_name,
            version.num
        ))
    };
    return Some(rendered);
    #[derive(Deserialize)]
    struct Package {
        readme: Option<String>,
    }
    #[derive(Deserialize)]
    struct Manifest {
        package: Package,
    }
}

/// Search an entry by its path in a Tar archive.
fn find_file_by_path<R: Read>(
    entries: &mut tar::Entries<R>,
    path: &Path,
    version: &Version,
    krate_name: &str,
) -> String {
    let mut file = entries
        .find(|entry| match *entry {
            Err(_) => false,
            Ok(ref file) => {
                let filepath = match file.path() {
                    Ok(p) => p,
                    Err(_) => return false,
                };
                return filepath == path;
            }
        })
        .expect(&format!(
            "[{}-{}] couldn't open file: {}",
            krate_name,
            version.num,
            path.display()
        ))
        .expect(&format!(
            "[{}-{}] file is not present: {}",
            krate_name,
            version.num,
            path.display()
        ));
    let mut contents = String::new();
    file.read_to_string(&mut contents).expect(&format!(
        "[{}-{}] Couldn't read file contents",
        krate_name,
        version.num
    ));
    contents
}
<|endoftext|>


<commit_before>use std::io::prelude::*;
use std::fs::{self, File};
use std::path::PathBuf;
use std::env;
use bins::error::*;
use toml::Value;

const DEFAULT_CONFIG_FILE: &'static str =
r#"[defaults]
# If this is true, all pastes will be created as private or unlisted.
# Using the command-line option `--public` or `--private` will change this behavior.
private = true

# If this is true, all pastes will be made to accounts or with API keys defined in this file.
# Pastebin ignores this setting and the command-line argument, since Pastebin requires an API key to paste.
# Using the command-line option `--auth` or `--anon` will change this behavior.
auth = true

# Uncomment this line if you want to set a default service to use with bins. This will make the `--service` option
# optional and use the configured service if the option is not specified.
# service = ""

# If this is true, all command will copy their output to the system clipboard.
# Using the command-line option `--copy` or `--no-copy` will change this behavior.
copy = false

[gist]
# The username to use for gist.github.com. This is ignored if access_token is empty.
username = ""

# Access token to use to log in to gist.github.com. If this is empty, an anonymous gist will be made.
# Generate a token from https://github.com/settings/tokens - only the gist permission is necessary
access_token = ""

[pastebin]
# The API key for pastebin.com. Learn more: http://pastebin.com/api
# If this is empty, all paste attempts to the pastebin service will fail.
api_key = ""
"#;

pub trait BetterLookups {
  fn lookup_str<'a>(&'a self, path: &'a str) -> Option<&str>;
  fn lookup_str_or<'a>(&'a self, key: &'a str, def: &'a str) -> &'a str;
  fn lookup_bool<'a>(&'a self, path: &'a str) -> Option<bool>;
  fn lookup_bool_or<'a>(&'a self, key: &'a str, def: bool) -> bool;
}

impl BetterLookups for Value {

  fn lookup_str<'a>(&'a self, path: &'a str) -> Option<&str> {
    match self.lookup(path) {
      Some(v) => v.as_str(),
      None => None
    }
  }

  fn lookup_str_or<'a>(&'a self, key: &'a str, def: &'a str) -> &'a str {
    self.lookup_str(key).unwrap_or(def)
  }

  fn lookup_bool<'a>(&'a self, path: &'a str) -> Option<bool> {
    match self.lookup(path) {
      Some(v) => v.as_bool(),
      None => None
    }
  }

  fn lookup_bool_or<'a>(&'a self, key: &'a str, def: bool) -> bool {
    self.lookup_bool(key).unwrap_or(def)
  }
}

pub struct BinsConfiguration;

impl BinsConfiguration {
  pub fn new() -> Self {
    BinsConfiguration { }
  }
}

pub trait Configurable {
  fn parse_config(&self) -> Result<Value>;

  fn get_default_config(&self) -> Result<Value>;

  fn get_config_paths(&self) -> Vec<PathBuf> {
    let mut paths: Vec<PathBuf> = vec![];
    if let Ok(dir) = env::var("XDG_CONFIG_DIR") {
      let mut xdg = PathBuf::from(dir);
      xdg.push("bins.cfg");
      paths.push(xdg);
    }
    let mut home = match env::home_dir() {
      Some(p) => p,
      None => return paths
    };
    let mut dot_config = home.clone();
    dot_config.push(".config");
    dot_config.push("bins.cfg");
    paths.push(dot_config);
    home.push(".bins.cfg");
    paths.push(home);
    paths
  }

  fn get_config_path(&self) -> Option<PathBuf> {
    self.get_config_paths().into_iter().find(|p| p.exists())
  }
}

impl Configurable for BinsConfiguration {
  fn parse_config(&self) -> Result<Value> {
    let path = match self.get_config_path() {
      Some(p) => p,
      None => {
        let config_paths = self.get_config_paths();
        let priority = some_or_err!(config_paths.first(), "no possible config paths computed".into());
        let parent = some_or_err!(priority.parent(), "config file path had no parent".into());
        let parent_str = some_or_err!(parent.to_str(), "config file path parent could not be converted to string".into());
        try!(fs::create_dir_all(parent_str));
        priority.to_path_buf()
      }
    };
    if !&path.exists() {
      let mut file = try!(File::create(&path));
      try!(file.write_all(DEFAULT_CONFIG_FILE.as_bytes()));
    }
    if (&path).is_dir() || !&path.is_file() {
      return Err("configuration file exists, but is not a valid file".into())
    }
    let mut config = String::new();
    try!(try!(File::open(path)).read_to_string(&mut config));
    match config.parse() {
      Ok(v) => Ok(v),
      Err(e) => Err(e.into_iter().next().map_or("could not parse config".to_owned(), |e| e.to_string()).into())
    }
  }

  fn get_default_config(&self) -> Result<Value> {
    match DEFAULT_CONFIG_FILE.parse() {
      Ok(v) => Ok(v),
      Err(e) => Err(e.into_iter().next().map_or("could not parse default config".to_owned(), |e| e.to_string()).into())
    }
  }
}
<commit_msg>refactor: also remove unused method<commit_after>use std::io::prelude::*;
use std::fs::{self, File};
use std::path::PathBuf;
use std::env;
use bins::error::*;
use toml::Value;

const DEFAULT_CONFIG_FILE: &'static str =
r#"[defaults]
# If this is true, all pastes will be created as private or unlisted.
# Using the command-line option `--public` or `--private` will change this behavior.
private = true

# If this is true, all pastes will be made to accounts or with API keys defined in this file.
# Pastebin ignores this setting and the command-line argument, since Pastebin requires an API key to paste.
# Using the command-line option `--auth` or `--anon` will change this behavior.
auth = true

# Uncomment this line if you want to set a default service to use with bins. This will make the `--service` option
# optional and use the configured service if the option is not specified.
# service = ""

# If this is true, all command will copy their output to the system clipboard.
# Using the command-line option `--copy` or `--no-copy` will change this behavior.
copy = false

[gist]
# The username to use for gist.github.com. This is ignored if access_token is empty.
username = ""

# Access token to use to log in to gist.github.com. If this is empty, an anonymous gist will be made.
# Generate a token from https://github.com/settings/tokens - only the gist permission is necessary
access_token = ""

[pastebin]
# The API key for pastebin.com. Learn more: http://pastebin.com/api
# If this is empty, all paste attempts to the pastebin service will fail.
api_key = ""
"#;

pub trait BetterLookups {
  fn lookup_str<'a>(&'a self, path: &'a str) -> Option<&str>;
  fn lookup_str_or<'a>(&'a self, key: &'a str, def: &'a str) -> &'a str;
  fn lookup_bool<'a>(&'a self, path: &'a str) -> Option<bool>;
  fn lookup_bool_or<'a>(&'a self, key: &'a str, def: bool) -> bool;
}

impl BetterLookups for Value {

  fn lookup_str<'a>(&'a self, path: &'a str) -> Option<&str> {
    match self.lookup(path) {
      Some(v) => v.as_str(),
      None => None
    }
  }

  fn lookup_str_or<'a>(&'a self, key: &'a str, def: &'a str) -> &'a str {
    self.lookup_str(key).unwrap_or(def)
  }

  fn lookup_bool<'a>(&'a self, path: &'a str) -> Option<bool> {
    match self.lookup(path) {
      Some(v) => v.as_bool(),
      None => None
    }
  }

  fn lookup_bool_or<'a>(&'a self, key: &'a str, def: bool) -> bool {
    self.lookup_bool(key).unwrap_or(def)
  }
}

pub struct BinsConfiguration;

impl BinsConfiguration {
  pub fn new() -> Self {
    BinsConfiguration { }
  }
}

pub trait Configurable {
  fn parse_config(&self) -> Result<Value>;

  fn get_config_paths(&self) -> Vec<PathBuf> {
    let mut paths: Vec<PathBuf> = vec![];
    if let Ok(dir) = env::var("XDG_CONFIG_DIR") {
      let mut xdg = PathBuf::from(dir);
      xdg.push("bins.cfg");
      paths.push(xdg);
    }
    let mut home = match env::home_dir() {
      Some(p) => p,
      None => return paths
    };
    let mut dot_config = home.clone();
    dot_config.push(".config");
    dot_config.push("bins.cfg");
    paths.push(dot_config);
    home.push(".bins.cfg");
    paths.push(home);
    paths
  }

  fn get_config_path(&self) -> Option<PathBuf> {
    self.get_config_paths().into_iter().find(|p| p.exists())
  }
}

impl Configurable for BinsConfiguration {
  fn parse_config(&self) -> Result<Value> {
    let path = match self.get_config_path() {
      Some(p) => p,
      None => {
        let config_paths = self.get_config_paths();
        let priority = some_or_err!(config_paths.first(), "no possible config paths computed".into());
        let parent = some_or_err!(priority.parent(), "config file path had no parent".into());
        let parent_str = some_or_err!(parent.to_str(), "config file path parent could not be converted to string".into());
        try!(fs::create_dir_all(parent_str));
        priority.to_path_buf()
      }
    };
    if !&path.exists() {
      let mut file = try!(File::create(&path));
      try!(file.write_all(DEFAULT_CONFIG_FILE.as_bytes()));
    }
    if (&path).is_dir() || !&path.is_file() {
      return Err("configuration file exists, but is not a valid file".into())
    }
    let mut config = String::new();
    try!(try!(File::open(path)).read_to_string(&mut config));
    match config.parse() {
      Ok(v) => Ok(v),
      Err(e) => Err(e.into_iter().next().map_or("could not parse config".to_owned(), |e| e.to_string()).into())
    }
  }
}
<|endoftext|>


<commit_before>#![feature(old_io,old_path,os)]
extern crate gl_generator;
extern crate khronos_api;

use std::os;
use std::old_io::File;

fn main() {
    let target = os::getenv("TARGET").unwrap();
    let dest = Path::new(os::getenv("OUT_DIR").unwrap());

    if target.contains("windows") {
        let mut file = File::create(&dest.join("wgl_bindings.rs")).unwrap();
        gl_generator::generate_bindings(gl_generator::StaticGenerator,
                                        gl_generator::registry::Ns::Wgl,
                                        gl_generator::Fallbacks::All,
                                        khronos_api::WGL_XML, vec![],
                                        "1.0", "core", &mut file).unwrap();

        let mut file = File::create(&dest.join("wgl_extra_bindings.rs")).unwrap();
        gl_generator::generate_bindings(gl_generator::StructGenerator,
                                        gl_generator::registry::Ns::Wgl,
                                        gl_generator::Fallbacks::All,
                                        khronos_api::WGL_XML,
                                        vec![
                                            "WGL_ARB_create_context".to_string(),
                                            "WGL_EXT_swap_control".to_string(),
                                            "WGL_ARB_pixel_format".to_string(),
                                            "WGL_ARB_framebuffer_sRGB".to_string(),
                                        ],
                                        "1.0", "core", &mut file).unwrap();
    }

    if target.contains("linux") {
        let mut file = File::create(&dest.join("glx_bindings.rs")).unwrap();
        gl_generator::generate_bindings(gl_generator::StaticGenerator,
                                        gl_generator::registry::Ns::Glx,
                                        gl_generator::Fallbacks::All,
                                        khronos_api::GLX_XML, vec![],
                                        "1.4", "core", &mut file).unwrap();

        let mut file = File::create(&dest.join("glx_extra_bindings.rs")).unwrap();
        gl_generator::generate_bindings(gl_generator::StructGenerator,
                                        gl_generator::registry::Ns::Glx,
                                        gl_generator::Fallbacks::All,
                                        khronos_api::GLX_XML,
                                        vec![
                                            "GLX_ARB_create_context".to_string(),
                                            "GLX_EXT_swap_control".to_string(),
                                            "GLX_SGI_swap_control".to_string()
                                        ],
                                        "1.4", "core", &mut file).unwrap();
    }

    if target.contains("android") {
        let mut file = File::create(&dest.join("egl_bindings.rs")).unwrap();
        gl_generator::generate_bindings(gl_generator::StaticGenerator,
                                        gl_generator::registry::Ns::Egl,
                                        gl_generator::Fallbacks::All,
                                        khronos_api::EGL_XML, vec![],
                                        "1.5", "core", &mut file).unwrap();
    }

    if target.contains("darwin") {
        let mut file = File::create(&dest.join("gl_bindings.rs")).unwrap();
        gl_generator::generate_bindings(gl_generator::GlobalGenerator,
                                        gl_generator::registry::Ns::Gl,
                                        gl_generator::Fallbacks::All,
                                        khronos_api::GL_XML,
                                        vec!["GL_EXT_framebuffer_object".to_string()],
                                        "3.2", "core", &mut file).unwrap();
    }

    // TODO: only build the bindings below if we run tests/examples

    let mut file = File::create(&dest.join("test_gl_bindings.rs")).unwrap();
    gl_generator::generate_bindings(gl_generator::StructGenerator,
                                    gl_generator::registry::Ns::Gl,
                                    gl_generator::Fallbacks::All,
                                    khronos_api::GL_XML, vec![],
                                    "1.1", "core", &mut file).unwrap();

    let mut file = File::create(&dest.join("test_gles1_bindings.rs")).unwrap();
    gl_generator::generate_bindings(gl_generator::StructGenerator,
                                    gl_generator::registry::Ns::Gles1,
                                    gl_generator::Fallbacks::All,
                                    khronos_api::GL_XML, vec![],
                                    "1.1", "core", &mut file).unwrap();
}
<commit_msg>Stop using deprecated os::getenv function<commit_after>#![feature(old_io,old_path,os)]
extern crate gl_generator;
extern crate khronos_api;

use std::env;
use std::old_io::File;

fn main() {
    let target = env::var("TARGET").unwrap();
    let dest = Path::new(env::var("OUT_DIR").unwrap());

    if target.contains("windows") {
        let mut file = File::create(&dest.join("wgl_bindings.rs")).unwrap();
        gl_generator::generate_bindings(gl_generator::StaticGenerator,
                                        gl_generator::registry::Ns::Wgl,
                                        gl_generator::Fallbacks::All,
                                        khronos_api::WGL_XML, vec![],
                                        "1.0", "core", &mut file).unwrap();

        let mut file = File::create(&dest.join("wgl_extra_bindings.rs")).unwrap();
        gl_generator::generate_bindings(gl_generator::StructGenerator,
                                        gl_generator::registry::Ns::Wgl,
                                        gl_generator::Fallbacks::All,
                                        khronos_api::WGL_XML,
                                        vec![
                                            "WGL_ARB_create_context".to_string(),
                                            "WGL_EXT_swap_control".to_string(),
                                            "WGL_ARB_pixel_format".to_string(),
                                            "WGL_ARB_framebuffer_sRGB".to_string(),
                                        ],
                                        "1.0", "core", &mut file).unwrap();
    }

    if target.contains("linux") {
        let mut file = File::create(&dest.join("glx_bindings.rs")).unwrap();
        gl_generator::generate_bindings(gl_generator::StaticGenerator,
                                        gl_generator::registry::Ns::Glx,
                                        gl_generator::Fallbacks::All,
                                        khronos_api::GLX_XML, vec![],
                                        "1.4", "core", &mut file).unwrap();

        let mut file = File::create(&dest.join("glx_extra_bindings.rs")).unwrap();
        gl_generator::generate_bindings(gl_generator::StructGenerator,
                                        gl_generator::registry::Ns::Glx,
                                        gl_generator::Fallbacks::All,
                                        khronos_api::GLX_XML,
                                        vec![
                                            "GLX_ARB_create_context".to_string(),
                                            "GLX_EXT_swap_control".to_string(),
                                            "GLX_SGI_swap_control".to_string()
                                        ],
                                        "1.4", "core", &mut file).unwrap();
    }

    if target.contains("android") {
        let mut file = File::create(&dest.join("egl_bindings.rs")).unwrap();
        gl_generator::generate_bindings(gl_generator::StaticGenerator,
                                        gl_generator::registry::Ns::Egl,
                                        gl_generator::Fallbacks::All,
                                        khronos_api::EGL_XML, vec![],
                                        "1.5", "core", &mut file).unwrap();
    }

    if target.contains("darwin") {
        let mut file = File::create(&dest.join("gl_bindings.rs")).unwrap();
        gl_generator::generate_bindings(gl_generator::GlobalGenerator,
                                        gl_generator::registry::Ns::Gl,
                                        gl_generator::Fallbacks::All,
                                        khronos_api::GL_XML,
                                        vec!["GL_EXT_framebuffer_object".to_string()],
                                        "3.2", "core", &mut file).unwrap();
    }

    // TODO: only build the bindings below if we run tests/examples

    let mut file = File::create(&dest.join("test_gl_bindings.rs")).unwrap();
    gl_generator::generate_bindings(gl_generator::StructGenerator,
                                    gl_generator::registry::Ns::Gl,
                                    gl_generator::Fallbacks::All,
                                    khronos_api::GL_XML, vec![],
                                    "1.1", "core", &mut file).unwrap();

    let mut file = File::create(&dest.join("test_gles1_bindings.rs")).unwrap();
    gl_generator::generate_bindings(gl_generator::StructGenerator,
                                    gl_generator::registry::Ns::Gles1,
                                    gl_generator::Fallbacks::All,
                                    khronos_api::GL_XML, vec![],
                                    "1.1", "core", &mut file).unwrap();
}
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

extern crate cmake;

fn main() {
    let dst = cmake::Config::new(".").build();
    println!("cargo:rustc-link-search=native={}/lib", dst.display());
    println!("cargo:rustc-link-lib=static=jsglue");
}
<commit_msg>Don't rerun build script unnecessarily<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

extern crate cmake;

fn main() {
    let dst = cmake::Config::new(".").build();
    println!("cargo:rustc-link-search=native={}/lib", dst.display());
    println!("cargo:rustc-link-lib=static=jsglue");
    println!("cargo:rerun-if-changed=src/jsglue.cpp");
}
<|endoftext|>


<commit_before>extern crate gcc;

fn main() {
    // Compile the external code
    let mut conf = gcc::Config::new();

    if cfg!(debug_assertions) {
        conf.define("DEBUG", None);
    }

    conf.cpp(true)
        .file("src/solver/solver_flint/solver_flint.cpp")
        .compile("libsolver_flint.a");

    // Tell rustc to link against flint and gmp
    println!("cargo:rustc-link-lib=flint");
    println!("cargo:rustc-link-lib=gmp");
}
<commit_msg>Avoid using deprecated item in gcc<commit_after>extern crate gcc;

fn main() {
    // Compile the external code
    let mut conf = gcc::Build::new();

    if cfg!(debug_assertions) {
        conf.define("DEBUG", None);
    }

    conf.cpp(true)
        .file("src/solver/solver_flint/solver_flint.cpp")
        .compile("libsolver_flint.a");

    // Tell rustc to link against flint and gmp
    println!("cargo:rustc-link-lib=flint");
    println!("cargo:rustc-link-lib=gmp");
}
<|endoftext|>


<commit_before>/*
At this stage this build script is just a shim to get the old build script
working. At some point they'll both need to be refactored into a single
unified build.rs
*/

use std::io::Command;
use std::os;

fn main() {
    // Build nanovg
    Command::new("make").arg("-f").arg("nanovg.mk").status().unwrap();

    let out_dir = os.getenv("OUT_DIR").unwrap();
    println!("cargo:rustc-flags=-L native={} -l static=shim", out_dir);
}
<commit_msg>Finally got a working build.<commit_after>/*
At this stage this build script is just a shim to get the old build script
working. At some point they'll both need to be refactored into a single
unified build.rs
*/

use std::io::Command;
use std::os;

fn main() {
    // Build nanovg
    Command::new("make").arg("-f").arg("nanovg.mk").status().unwrap();

    let out_dir = os::getenv("OUT_DIR").unwrap();
    println!("cargo:rustc-flags=-L native={} -l static=nanovg_shim", out_dir);
}
<|endoftext|>


<commit_before>use std::env;
use std::fs;
use std::path::Path;

fn main() {
    let out_dir = env::var_os("OUT_DIR").unwrap();
    let dest_path = Path::new(&out_dir).join("words.rs");

    let mut lines: Vec<String> = vec![];

    let list_sizes = ["small", "medium", "large"];
    let list_names = ["adjectives", "adverbs", "names"];

    for list_size in list_sizes {
        lines.push(format!("pub mod {list_size} {{"));
        for list_name in list_names {
            let list_path = format!("words/{list_size}/{list_name}.txt");
            println!("cargo:rerun-if-changed={list_path}");
            let list_raw = fs::read_to_string(list_path).unwrap();
            let list = list_raw.split_whitespace().collect::<Vec<_>>();
            lines.push(format!(
                "  pub const {}: [&str; {}] = [",
                list_name.to_uppercase(),
                list.len()
            ));
            lines.extend(list.iter().map(|word| format!("    \"{word}\",")));
            lines.push(format!("  ];"));
        }
        lines.push(format!("}}"));
    }

    fs::write(&dest_path, lines.join("\n")).unwrap();
    println!("cargo:rerun-if-changed=build.rs");
}
<commit_msg>Follow Clippy's suggestions<commit_after>use std::env;
use std::fs;
use std::path::Path;

fn main() {
    let out_dir = env::var_os("OUT_DIR").unwrap();
    let dest_path = Path::new(&out_dir).join("words.rs");

    let mut lines: Vec<String> = vec![];

    let list_sizes = ["small", "medium", "large"];
    let list_names = ["adjectives", "adverbs", "names"];

    for list_size in list_sizes {
        lines.push(format!("pub mod {list_size} {{"));
        for list_name in list_names {
            let list_path = format!("words/{list_size}/{list_name}.txt");
            println!("cargo:rerun-if-changed={list_path}");
            let list_raw = fs::read_to_string(list_path).unwrap();
            let list = list_raw.split_whitespace().collect::<Vec<_>>();
            lines.push(format!(
                "  pub static {}: [&str; {}] = [",
                list_name.to_uppercase(),
                list.len()
            ));
            lines.extend(list.iter().map(|word| format!("    \"{word}\",")));
            lines.push("  ];".to_string());
        }
        lines.push("}".to_string());
    }

    fs::write(&dest_path, lines.join("\n")).unwrap();
    println!("cargo:rerun-if-changed=build.rs");
}
<|endoftext|>


<commit_before>// Copyright 2014 Johannes Köster.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.

use bindgen;
use cc;
use fs_utils::copy::copy_directory;

use std::env;
use std::fs;
use std::path::PathBuf;
use std::process::Command;

fn sed_htslib_makefile(out: &PathBuf, patterns: &Vec<&str>, feature: &str) {
    for pattern in patterns {
        if Command::new("sed")
            .current_dir(out.join("htslib"))
            .arg("-i")
            .arg("-e")
            .arg(pattern)
            .arg("Makefile")
            .status()
            .unwrap()
            .success()
            != true
        {
            panic!("failed to strip {} support", feature);
        }
    }
}

fn main() {
    let out = PathBuf::from(env::var("OUT_DIR").unwrap());
    let mut cfg = cc::Build::new();
    cfg.warnings(false).static_flag(true).pic(true);

    if let Ok(z_inc) = env::var("DEP_Z_INCLUDE") {
        cfg.include(z_inc);
    }

    if !out.join("htslib").exists() {
        copy_directory("htslib", &out).unwrap();
    }

    let use_bzip2 = env::var("CARGO_FEATURE_BZIP2").is_ok();
    if !use_bzip2 {
        let bzip2_patterns = vec!["s/ -lbz2//", "/#define HAVE_LIBBZ2/d"];
        sed_htslib_makefile(&out, &bzip2_patterns, "bzip2");
    } else if let Ok(inc) = env::var("DEP_BZIP2_ROOT")
        .map(PathBuf::from)
        .map(|path| path.join("include"))
    {
        cfg.include(inc);
    }

    let use_lzma = env::var("CARGO_FEATURE_LZMA").is_ok();
    if !use_lzma {
        let lzma_patterns = vec!["s/ -llzma//", "/#define HAVE_LIBLZMA/d"];
        sed_htslib_makefile(&out, &lzma_patterns, "lzma");
    } else if let Ok(inc) = env::var("DEP_LZMA_INCLUDE").map(PathBuf::from) {
        cfg.include(inc);
    }

    let tool = cfg.get_compiler();
    let (cc_path, cflags_env) = (tool.path(), tool.cflags_env());
    let cc_cflags = cflags_env.to_string_lossy().replace("-O0", "");
    if Command::new("make")
        .current_dir(out.join("htslib"))
        .arg(format!("CC={}", cc_path.display()))
        .arg(format!("CFLAGS={}", cc_cflags))
        .arg("lib-static")
        .arg("-B")
        .status()
        .unwrap()
        .success()
        != true
    {
        panic!("failed to build htslib");
    }

    cfg.file("wrapper.c").compile("wrapper");

    bindgen::Builder::default()
        .header("wrapper.h")
        .generate_comments(false)
        .blacklist_type("max_align_t")
        .generate()
        .expect("Unable to generate bindings.")
        .write_to_file(out.join("bindings.rs"))
        .expect("Could not write bindings.");

    let include = out.join("include");
    fs::create_dir_all(&include).unwrap();
    if include.join("htslib").exists() {
        fs::remove_dir_all(include.join("htslib")).expect("remove exist include dir");
    }
    copy_directory(out.join("htslib").join("htslib"), &include).unwrap();
    fs::copy(out.join("htslib").join("libhts.a"), out.join("libhts.a")).unwrap();

    println!("cargo:root={}", out.display());
    println!("cargo:include={}", include.display());
    println!("cargo:libdir={}", out.display());
    println!("cargo:rustc-link-lib=static=hts");
}
<commit_msg>ensure we do not pull in unstable u128 FFI (#158)<commit_after>// Copyright 2014 Johannes Köster.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.

use bindgen;
use cc;
use fs_utils::copy::copy_directory;

use std::env;
use std::fs;
use std::path::PathBuf;
use std::process::Command;

fn sed_htslib_makefile(out: &PathBuf, patterns: &Vec<&str>, feature: &str) {
    for pattern in patterns {
        if Command::new("sed")
            .current_dir(out.join("htslib"))
            .arg("-i")
            .arg("-e")
            .arg(pattern)
            .arg("Makefile")
            .status()
            .unwrap()
            .success()
            != true
        {
            panic!("failed to strip {} support", feature);
        }
    }
}

fn main() {
    let out = PathBuf::from(env::var("OUT_DIR").unwrap());
    let mut cfg = cc::Build::new();
    cfg.warnings(false).static_flag(true).pic(true);

    if let Ok(z_inc) = env::var("DEP_Z_INCLUDE") {
        cfg.include(z_inc);
    }

    if !out.join("htslib").exists() {
        copy_directory("htslib", &out).unwrap();
    }

    let use_bzip2 = env::var("CARGO_FEATURE_BZIP2").is_ok();
    if !use_bzip2 {
        let bzip2_patterns = vec!["s/ -lbz2//", "/#define HAVE_LIBBZ2/d"];
        sed_htslib_makefile(&out, &bzip2_patterns, "bzip2");
    } else if let Ok(inc) = env::var("DEP_BZIP2_ROOT")
        .map(PathBuf::from)
        .map(|path| path.join("include"))
    {
        cfg.include(inc);
    }

    let use_lzma = env::var("CARGO_FEATURE_LZMA").is_ok();
    if !use_lzma {
        let lzma_patterns = vec!["s/ -llzma//", "/#define HAVE_LIBLZMA/d"];
        sed_htslib_makefile(&out, &lzma_patterns, "lzma");
    } else if let Ok(inc) = env::var("DEP_LZMA_INCLUDE").map(PathBuf::from) {
        cfg.include(inc);
    }

    let tool = cfg.get_compiler();
    let (cc_path, cflags_env) = (tool.path(), tool.cflags_env());
    let cc_cflags = cflags_env.to_string_lossy().replace("-O0", "");
    if Command::new("make")
        .current_dir(out.join("htslib"))
        .arg(format!("CC={}", cc_path.display()))
        .arg(format!("CFLAGS={}", cc_cflags))
        .arg("lib-static")
        .arg("-B")
        .status()
        .unwrap()
        .success()
        != true
    {
        panic!("failed to build htslib");
    }

    cfg.file("wrapper.c").compile("wrapper");

    bindgen::Builder::default()
        .header("wrapper.h")
        .generate_comments(false)
        .blacklist_function("strtold")
        .blacklist_type("max_align_t")
        .generate()
        .expect("Unable to generate bindings.")
        .write_to_file(out.join("bindings.rs"))
        .expect("Could not write bindings.");

    let include = out.join("include");
    fs::create_dir_all(&include).unwrap();
    if include.join("htslib").exists() {
        fs::remove_dir_all(include.join("htslib")).expect("remove exist include dir");
    }
    copy_directory(out.join("htslib").join("htslib"), &include).unwrap();
    fs::copy(out.join("htslib").join("libhts.a"), out.join("libhts.a")).unwrap();

    println!("cargo:root={}", out.display());
    println!("cargo:include={}", include.display());
    println!("cargo:libdir={}", out.display());
    println!("cargo:rustc-link-lib=static=hts");
}
<|endoftext|>