Skip to content

Commit

Permalink
formatted code
Browse files Browse the repository at this point in the history
  • Loading branch information
Kurt Lawrence committed Mar 15, 2019
1 parent aa9a520 commit e409ced
Show file tree
Hide file tree
Showing 8 changed files with 799 additions and 799 deletions.
144 changes: 72 additions & 72 deletions src/pfh/compile/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,97 +6,97 @@ use std::sync::mpsc;
use std::{error, fmt, fs};

pub fn compile<P, F>(
compile_dir: P,
linking_config: &linking::LinkingConfiguration,
stderr_line_cb: F,
compile_dir: P,
linking_config: &linking::LinkingConfiguration,
stderr_line_cb: F,
) -> Result<PathBuf, CompilationError>
where
P: AsRef<Path>,
F: Fn(&str),
P: AsRef<Path>,
F: Fn(&str),
{
let compile_dir = compile_dir.as_ref();
let lib_file = compile_dir.join("target/debug/");
let lib_file = if cfg!(windows) {
lib_file.join(format!("{}.dll", LIBRARY_NAME))
} else {
lib_file.join(format!("lib{}.so", LIBRARY_NAME))
};
let compile_dir = compile_dir.as_ref();
let lib_file = compile_dir.join("target/debug/");
let lib_file = if cfg!(windows) {
lib_file.join(format!("{}.dll", LIBRARY_NAME))
} else {
lib_file.join(format!("lib{}.so", LIBRARY_NAME))
};

let mut _s_tmp = String::new();
let mut args = vec!["rustc", "--", "-Awarnings"];
if let Some(crate_name) = linking_config.crate_name {
args.push("--extern");
_s_tmp = format!("{0}=lib{0}.rlib", crate_name);
args.push(&_s_tmp);
}
let mut _s_tmp = String::new();
let mut args = vec!["rustc", "--", "-Awarnings"];
if let Some(crate_name) = linking_config.crate_name {
args.push("--extern");
_s_tmp = format!("{0}=lib{0}.rlib", crate_name);
args.push(&_s_tmp);
}

let mut child = Command::new("cargo")
.current_dir(compile_dir)
.args(&args)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|_| CompilationError::NoBuildCommand)?;
let mut child = Command::new("cargo")
.current_dir(compile_dir)
.args(&args)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|_| CompilationError::NoBuildCommand)?;

let stderr = {
let rdr = BufReader::new(child.stderr.as_mut().expect("stderr should be piped"));
let mut s = String::new();
for line in rdr.lines() {
let line = line.unwrap();
stderr_line_cb(&line);
s.push_str(&line);
s.push('\n');
}
s
};
let stderr = {
let rdr = BufReader::new(child.stderr.as_mut().expect("stderr should be piped"));
let mut s = String::new();
for line in rdr.lines() {
let line = line.unwrap();
stderr_line_cb(&line);
s.push_str(&line);
s.push('\n');
}
s
};

match child.wait() {
Ok(ex) => {
if ex.success() {
Ok(lib_file)
} else {
Err(CompilationError::CompileError(stderr))
}
}
Err(e) => Err(CompilationError::IOError(e)),
}
match child.wait() {
Ok(ex) => {
if ex.success() {
Ok(lib_file)
} else {
Err(CompilationError::CompileError(stderr))
}
}
Err(e) => Err(CompilationError::IOError(e)),
}
}

/// Error type for compilation.
#[derive(Debug)]
pub enum CompilationError {
/// Failed to initialise `cargo build`. Usually because `cargo` is not in your `PATH` or Rust is not installed.
NoBuildCommand,
/// A compiling error occured, with the contents of the stderr.
CompileError(String),
/// Generic IO errors.
IOError(io::Error),
/// Failed to initialise `cargo build`. Usually because `cargo` is not in your `PATH` or Rust is not installed.
NoBuildCommand,
/// A compiling error occured, with the contents of the stderr.
CompileError(String),
/// Generic IO errors.
IOError(io::Error),
}

impl error::Error for CompilationError {}

impl fmt::Display for CompilationError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
CompilationError::NoBuildCommand => {
write!(f, "cargo build command failed to start, is rust installed?")
}
CompilationError::CompileError(e) => write!(f, "{}", e),
CompilationError::IOError(e) => write!(f, "io error occurred: {}", e),
}
}
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
CompilationError::NoBuildCommand => {
write!(f, "cargo build command failed to start, is rust installed?")
}
CompilationError::CompileError(e) => write!(f, "{}", e),
CompilationError::IOError(e) => write!(f, "io error occurred: {}", e),
}
}
}

#[test]
fn compilation_error_fmt_test() {
let e = CompilationError::NoBuildCommand;
assert_eq!(
&e.to_string(),
"cargo build command failed to start, is rust installed?"
);
let e = CompilationError::CompileError("compile err".to_string());
assert_eq!(&e.to_string(), "compile err");
let ioe = io::Error::new(io::ErrorKind::Other, "test");
let e = CompilationError::IOError(ioe);
assert_eq!(&e.to_string(), "io error occurred: test");
let e = CompilationError::NoBuildCommand;
assert_eq!(
&e.to_string(),
"cargo build command failed to start, is rust installed?"
);
let e = CompilationError::CompileError("compile err".to_string());
assert_eq!(&e.to_string(), "compile err");
let ioe = io::Error::new(io::ErrorKind::Other, "test");
let e = CompilationError::IOError(ioe);
assert_eq!(&e.to_string(), "io error occurred: test");
}
138 changes: 69 additions & 69 deletions src/pfh/compile/construct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,94 +9,94 @@ use std::{error, fmt, fs};
/// Takes a list of source files and writes the contents to file.
/// Builds `Cargo.toml` using crates found in `SourceFile`.
pub fn build_compile_dir<'a, P, I>(
compile_dir: P,
files: I,
linking_config: &linking::LinkingConfiguration,
compile_dir: P,
files: I,
linking_config: &linking::LinkingConfiguration,
) -> io::Result<()>
where
P: AsRef<Path>,
I: Iterator<Item = &'a SourceFile>,
P: AsRef<Path>,
I: Iterator<Item = &'a SourceFile>,
{
let compile_dir = compile_dir.as_ref();
let compile_dir = compile_dir.as_ref();

let mut crates = Vec::new();
let mut crates = Vec::new();

// write source files
for file in files {
// add linked crate if there is one to lib file
let mut contents = String::new();
if let Some(cname) = linking_config.crate_name {
if file.path == Path::new("lib.rs") {
contents.push_str(&format!("extern crate {};\n", cname));
}
}
contents.push_str(&file::code::construct(
&file.contents,
&file.mod_path,
linking_config,
));
// write source files
for file in files {
// add linked crate if there is one to lib file
let mut contents = String::new();
if let Some(cname) = linking_config.crate_name {
if file.path == Path::new("lib.rs") {
contents.push_str(&format!("extern crate {};\n", cname));
}
}
contents.push_str(&file::code::construct(
&file.contents,
&file.mod_path,
linking_config,
));

create_file_and_dir(compile_dir.join("src/").join(&file.path))?
.write_all(contents.as_bytes())?;
for c in file.contents.iter().flat_map(|x| &x.crates) {
crates.push(c);
}
}
create_file_and_dir(compile_dir.join("src/").join(&file.path))?
.write_all(contents.as_bytes())?;
for c in file.contents.iter().flat_map(|x| &x.crates) {
crates.push(c);
}
}

// write cargo toml contents
create_file_and_dir(compile_dir.join("Cargo.toml"))?
.write_all(cargotoml_contents(LIBRARY_NAME, crates.into_iter()).as_bytes())?;
// write cargo toml contents
create_file_and_dir(compile_dir.join("Cargo.toml"))?
.write_all(cargotoml_contents(LIBRARY_NAME, crates.into_iter()).as_bytes())?;

Ok(())
Ok(())
}

/// Run `cargo fmt` in the given directory.
pub fn fmt<P: AsRef<Path>>(compile_dir: P) -> bool {
match Command::new("cargo")
.current_dir(compile_dir)
.args(&["fmt"])
.output()
{
Ok(output) => output.status.success(),
Err(e) => {
debug!("{}", e);
false
}
}
match Command::new("cargo")
.current_dir(compile_dir)
.args(&["fmt"])
.output()
{
Ok(output) => output.status.success(),
Err(e) => {
debug!("{}", e);
false
}
}
}

/// Creates the specified file along with the directory to it if it doesn't exist.
fn create_file_and_dir<P: AsRef<Path>>(file: P) -> io::Result<fs::File> {
let file = file.as_ref();
debug!("trying to create file: {}", file.display());
if let Some(parent) = file.parent() {
fs::create_dir_all(parent)?;
}
fs::File::create(file)
let file = file.as_ref();
debug!("trying to create file: {}", file.display());
if let Some(parent) = file.parent() {
fs::create_dir_all(parent)?;
}
fs::File::create(file)
}

#[test]
fn create_file_and_dir_test() {
use std::path::Path;
use std::path::Path;

let p = Path::new("foo.txt");
assert!(!p.exists());
create_file_and_dir(&"foo.txt").unwrap();
assert!(p.exists());
fs::remove_file(p).unwrap();
assert!(!p.exists());
let p = Path::new("foo.txt");
assert!(!p.exists());
create_file_and_dir(&"foo.txt").unwrap();
assert!(p.exists());
fs::remove_file(p).unwrap();
assert!(!p.exists());

let p = Path::new("test/foo");
assert!(!p.exists());
create_file_and_dir(&p).unwrap();
assert!(p.exists());
fs::remove_file(p).unwrap();
assert!(!p.exists());
let p = Path::new("test/foo");
assert!(!p.exists());
create_file_and_dir(&p).unwrap();
assert!(p.exists());
fs::remove_file(p).unwrap();
assert!(!p.exists());
}

fn cargotoml_contents<'a, I: Iterator<Item = &'a CrateType>>(lib_name: &str, crates: I) -> String {
format!(
r#"[package]
format!(
r#"[package]
name = "{lib_name}"
version = "0.1.0"
Expand All @@ -108,10 +108,10 @@ path = "src/lib.rs"
[dependencies]
{crates}
"#,
lib_name = lib_name,
crates = crates
.map(|c| format!(r#"{} = "*""#, c.cargo_name))
.collect::<Vec<_>>()
.join("\n")
)
lib_name = lib_name,
crates = crates
.map(|c| format!(r#"{} = "*""#, c.cargo_name))
.collect::<Vec<_>>()
.join("\n")
)
}
Loading

0 comments on commit e409ced

Please sign in to comment.