cargo +nightly fmt --all

Rustfmt all the things!
This commit is contained in:
Alex Crichton
2018-09-26 08:26:00 -07:00
parent a3e160744e
commit 7ecf4aae87
163 changed files with 2975 additions and 1998 deletions

View File

@ -1,14 +1,14 @@
use std::env;
use std::io::{self, Read};
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::path::{PathBuf, Path};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::thread;
use std::time::{Instant, Duration};
use std::time::{Duration, Instant};
use curl::easy::Easy;
use failure::{ResultExt, Error};
use serde::{Serialize, Deserialize};
use failure::{Error, ResultExt};
use serde::{Deserialize, Serialize};
use serde_json;
use shell::Shell;
@ -22,9 +22,11 @@ use shell::Shell;
/// will return an error if some tests failed.
pub fn run(server: &SocketAddr, shell: &Shell) -> Result<(), Error> {
let (driver, args) = Driver::find()?;
println!("Running headless tests in {} with `{}`",
driver.browser(),
driver.path().display());
println!(
"Running headless tests in {} with `{}`",
driver.browser(),
driver.path().display()
);
// Allow tests to run in parallel (in theory) by finding any open port
// available for our driver. We can't bind the port for the driver, but
@ -47,7 +49,7 @@ pub fn run(server: &SocketAddr, shell: &Shell) -> Result<(), Error> {
while start.elapsed() < max {
if TcpStream::connect(&driver_addr).is_ok() {
bound = true;
break
break;
}
thread::sleep(Duration::from_millis(100));
}
@ -94,7 +96,7 @@ pub fn run(server: &SocketAddr, shell: &Shell) -> Result<(), Error> {
let max = Duration::new(20, 0);
while start.elapsed() < max {
if client.text(&id, &output)?.contains("test result: ") {
break
break;
}
thread::sleep(Duration::from_millis(100));
}
@ -174,30 +176,29 @@ impl Driver {
Some(path) => path,
None => continue,
};
return Ok((ctor(path.into()), env_args(driver)))
return Ok((ctor(path.into()), env_args(driver)));
}
// Next, check PATH. If we can find any supported driver, use that by
// default.
for path in env::split_paths(&env::var_os("PATH").unwrap_or_default()) {
let found = drivers
.iter()
.find(|(name, _)| {
path.join(name)
.with_extension(env::consts::EXE_EXTENSION)
.exists()
});
let found = drivers.iter().find(|(name, _)| {
path.join(name)
.with_extension(env::consts::EXE_EXTENSION)
.exists()
});
let (name, ctor) = match found {
Some(p) => p,
None => continue,
};
return Ok((ctor(name.into()), env_args(name)))
return Ok((ctor(name.into()), env_args(name)));
}
// TODO: download an appropriate driver? How to know which one to
// download?
bail!("\
bail!(
"\
failed to find a suitable WebDriver binary to drive headless testing; to
configure the location of the webdriver binary you can use environment
variables like `GECKODRIVER=/path/to/geckodriver` or make sure that the binary
@ -217,7 +218,8 @@ visit in a web browser, and headless testing should not be used.
If you're still having difficulty resolving this error, please feel free to open
an issue against rustwasm/wasm-bindgen!
")
"
)
}
fn path(&self) -> &Path {
@ -320,8 +322,7 @@ impl Client {
fn close_window(&mut self, id: &str) -> Result<(), Error> {
#[derive(Deserialize)]
struct Response {
}
struct Response {}
let x: Response = self.delete(&format!("/session/{}/window", id))?;
drop(x);
Ok(())
@ -333,8 +334,7 @@ impl Client {
url: String,
}
#[derive(Deserialize)]
struct Response {
}
struct Response {}
let request = Request {
url: url.to_string(),
@ -367,10 +367,10 @@ impl Client {
value: selector.to_string(),
};
let x: Response = self.post(&format!("/session/{}/element", id), &request)?;
Ok(x.value.gecko_reference
.or(x.value.safari_reference)
.ok_or(format_err!("failed to find element reference in response"))?)
Ok(x.value
.gecko_reference
.or(x.value.safari_reference)
.ok_or(format_err!("failed to find element reference in response"))?)
}
fn text(&mut self, id: &str, element: &str) -> Result<String, Error> {
@ -383,7 +383,8 @@ impl Client {
}
fn get<U>(&mut self, path: &str) -> Result<U, Error>
where U: for<'a> Deserialize<'a>,
where
U: for<'a> Deserialize<'a>,
{
debug!("GET {}", path);
let result = self.doit(path, Method::Get)?;
@ -391,8 +392,9 @@ impl Client {
}
fn post<T, U>(&mut self, path: &str, data: &T) -> Result<U, Error>
where T: Serialize,
U: for<'a> Deserialize<'a>,
where
T: Serialize,
U: for<'a> Deserialize<'a>,
{
let input = serde_json::to_string(data)?;
debug!("POST {} {}", path, input);
@ -401,7 +403,8 @@ impl Client {
}
fn delete<U>(&mut self, path: &str) -> Result<U, Error>
where U: for<'a> Deserialize<'a>,
where
U: for<'a> Deserialize<'a>,
{
debug!("DELETE {}", path);
let result = self.doit(path, Method::Delete)?;
@ -431,7 +434,11 @@ impl Client {
}
let result = String::from_utf8_lossy(&result);
if self.handle.response_code()? != 200 {
bail!("non-200 response code: {}\n{}", self.handle.response_code()?, result);
bail!(
"non-200 response code: {}\n{}",
self.handle.response_code()?,
result
);
}
debug!("got: {}", result);
Ok(result.into_owned())
@ -475,14 +482,16 @@ struct BackgroundChild<'a> {
}
impl<'a> BackgroundChild<'a> {
fn spawn(path: &Path, cmd: &mut Command, shell: &'a Shell)
-> Result<BackgroundChild<'a>, Error>
{
cmd
.stdout(Stdio::piped())
fn spawn(
path: &Path,
cmd: &mut Command,
shell: &'a Shell,
) -> Result<BackgroundChild<'a>, Error> {
cmd.stdout(Stdio::piped())
.stderr(Stdio::piped())
.stdin(Stdio::null());
let mut child = cmd.spawn()
let mut child = cmd
.spawn()
.context(format!("failed to spawn {:?} binary", path))?;
let mut stdout = child.stdout.take().unwrap();
let mut stderr = child.stderr.take().unwrap();
@ -503,7 +512,7 @@ impl<'a> Drop for BackgroundChild<'a> {
self.child.kill().unwrap();
let status = self.child.wait().unwrap();
if !self.print_stdio_on_drop {
return
return;
}
self.shell.clear();

View File

@ -32,8 +32,8 @@ use std::path::PathBuf;
use std::process;
use std::thread;
use failure::{ResultExt, Error};
use parity_wasm::elements::{Module, Deserialize, Section};
use failure::{Error, ResultExt};
use parity_wasm::elements::{Deserialize, Module, Section};
use wasm_bindgen_cli_support::Bindgen;
mod headless;
@ -67,33 +67,29 @@ fn rmain() -> Result<(), Error> {
// Assume a cargo-like directory layout and generate output at
// `target/wasm32-unknown-unknown/wbg-tmp/...`
let tmpdir = wasm_file_to_test.parent() // chop off file name
.and_then(|p| p.parent()) // chop off `deps`
.and_then(|p| p.parent()) // chop off `debug`
let tmpdir = wasm_file_to_test
.parent() // chop off file name
.and_then(|p| p.parent()) // chop off `deps`
.and_then(|p| p.parent()) // chop off `debug`
.map(|p| p.join("wbg-tmp"))
.ok_or_else(|| {
format_err!("file to test doesn't follow the expected Cargo conventions")
})?;
.ok_or_else(|| format_err!("file to test doesn't follow the expected Cargo conventions"))?;
// Make sure there's no stale state from before
drop(fs::remove_dir_all(&tmpdir));
fs::create_dir(&tmpdir)
.context("creating temporary directory")?;
fs::create_dir(&tmpdir).context("creating temporary directory")?;
let module = "wasm-bindgen-test";
// Collect all tests that the test harness is supposed to run. We assume
// that any exported function with the prefix `__wbg_test` is a test we need
// to execute.
let wasm = fs::read(&wasm_file_to_test)
.context("failed to read wasm file")?;
let wasm = Module::deserialize(&mut &wasm[..])
.context("failed to deserialize wasm module")?;
let wasm = fs::read(&wasm_file_to_test).context("failed to read wasm file")?;
let wasm = Module::deserialize(&mut &wasm[..]).context("failed to deserialize wasm module")?;
let mut tests = Vec::new();
if let Some(exports) = wasm.export_section() {
for export in exports.entries() {
if !export.field().starts_with("__wbg_test") {
continue
continue;
}
tests.push(export.field().to_string());
}
@ -104,7 +100,7 @@ fn rmain() -> Result<(), Error> {
// early saying everything is ok.
if tests.len() == 0 {
println!("no tests to run!");
return Ok(())
return Ok(());
}
// Figure out if this tests is supposed to execute in node.js or a browser.
@ -118,7 +114,7 @@ fn rmain() -> Result<(), Error> {
_ => continue,
};
if custom.name() != "__wasm_bindgen_test_unstable" {
continue
continue;
}
node = !custom.payload().contains(&0x01);
}
@ -138,7 +134,7 @@ fn rmain() -> Result<(), Error> {
// If we're executing in node.js, that module will take it from here.
if node {
return node::execute(&module, &tmpdir, &args.collect::<Vec<_>>(), &tests)
return node::execute(&module, &tmpdir, &args.collect::<Vec<_>>(), &tests);
}
// Otherwise we're executing in a browser. Spawn a server which serves up
@ -160,13 +156,16 @@ fn rmain() -> Result<(), Error> {
// TODO: eventually we should provide the ability to exit at some point
// (gracefully) here, but for now this just runs forever.
if !headless {
println!("Interactive browsers tests are now available at http://{}", addr);
println!(
"Interactive browsers tests are now available at http://{}",
addr
);
println!("");
println!("Note that interactive mode is enabled because `NO_HEADLESS`");
println!("is specified in the environment of this process. Once you're");
println!("done with testing you'll need to kill this server with");
println!("Ctrl-C.");
return Ok(srv.run())
return Ok(srv.run());
}
thread::spawn(|| srv.run());

View File

@ -4,12 +4,16 @@ use std::fs;
use std::path::Path;
use std::process::Command;
use failure::{ResultExt, Error};
use failure::{Error, ResultExt};
pub fn execute(module: &str, tmpdir: &Path, args: &[OsString], tests: &[String])
-> Result<(), Error>
{
let mut js_to_execute = format!(r#"
pub fn execute(
module: &str,
tmpdir: &Path,
args: &[OsString],
tests: &[String],
) -> Result<(), Error> {
let mut js_to_execute = format!(
r#"
const {{ exit }} = require('process');
let console_log_redirect = null;
@ -68,17 +72,18 @@ pub fn execute(module: &str, tmpdir: &Path, args: &[OsString], tests: &[String])
js_to_execute.push_str(&format!("tests.push('{}')\n", test));
}
// And as a final addendum, exit with a nonzero code if any tests fail.
js_to_execute.push_str("
js_to_execute.push_str(
"
main(tests)
.catch(e => {
console.error(e);
exit(1);
});
");
",
);
let js_path = tmpdir.join("run.js");
fs::write(&js_path, js_to_execute)
.context("failed to write JS file")?;
fs::write(&js_path, js_to_execute).context("failed to write JS file")?;
// Augment `NODE_PATH` so things like `require("tests/my-custom.js")` work
// and Rust code can import from custom JS shims. This is a bit of a hack
@ -91,14 +96,16 @@ pub fn execute(module: &str, tmpdir: &Path, args: &[OsString], tests: &[String])
Command::new("node")
.env("NODE_PATH", env::join_paths(&path).unwrap())
.arg(&js_path)
.args(args)
.args(args),
)
}
#[cfg(unix)]
fn exec(cmd: &mut Command) -> Result<(), Error> {
use std::os::unix::prelude::*;
Err(Error::from(cmd.exec()).context("failed to execute `node`").into())
Err(Error::from(cmd.exec())
.context("failed to execute `node`")
.into())
}
#[cfg(windows)]

View File

@ -1,10 +1,10 @@
use std::ffi::OsString;
use std::path::Path;
use std::fs;
use std::net::SocketAddr;
use std::path::Path;
use failure::{ResultExt, Error};
use rouille::{self, Response, Request, Server};
use failure::{Error, ResultExt};
use rouille::{self, Request, Response, Server};
use wasm_bindgen_cli_support::wasm2es6js::Config;
pub fn spawn(
@ -15,7 +15,8 @@ pub fn spawn(
args: &[OsString],
tests: &[String],
) -> Result<Server<impl Fn(&Request) -> Response + Send + Sync>, Error> {
let mut js_to_execute = format!(r#"
let mut js_to_execute = format!(
r#"
import {{ Context, __wbgtest_console_log, __wbgtest_console_error }} from './{0}';
import * as wasm from './{0}_bg';
@ -52,8 +53,7 @@ pub fn spawn(
js_to_execute.push_str("main(tests);\n");
let js_path = tmpdir.join("run.js");
fs::write(&js_path, js_to_execute)
.context("failed to write JS file")?;
fs::write(&js_path, js_to_execute).context("failed to write JS file")?;
// No browser today supports a wasm file as ES modules natively, so we need
// to shim it. Use `wasm2es6js` here to fetch an appropriate URL and look
@ -69,8 +69,7 @@ pub fn spawn(
.fetch(Some(format!("/{}", wasm_name)))
.generate(&wasm)?;
let js = output.js()?;
fs::write(tmpdir.join(format!("{}_bg.js", module)), js)
.context("failed to write JS file")?;
fs::write(tmpdir.join(format!("{}_bg.js", module)), js).context("failed to write JS file")?;
// For now, always run forever on this port. We may update this later!
let tmpdir = tmpdir.to_path_buf();
@ -85,7 +84,7 @@ pub fn spawn(
} else {
include_str!("index.html")
};
return Response::from_data("text/html", s)
return Response::from_data("text/html", s);
}
// Otherwise we need to find the asset here. It may either be in our
@ -98,14 +97,14 @@ pub fn spawn(
// Make sure browsers don't cache anything (Chrome appeared to with this
// header?)
response.headers.retain(|(k, _)| k != "Cache-Control");
return response
return response;
}).map_err(|e| format_err!("{}", e))?;
return Ok(srv);
fn try_asset(request: &Request, dir: &Path) -> Response {
let response = rouille::match_assets(request, dir);
if response.is_success() {
return response
return response;
}
// When a browser is doing ES imports it's using the directives we
@ -117,14 +116,15 @@ pub fn spawn(
let new_request = Request::fake_http(
request.method(),
format!("{}.js", request.url()),
request.headers()
request
.headers()
.map(|(a, b)| (a.to_string(), b.to_string()))
.collect(),
Vec::new(),
);
let response = rouille::match_assets(&new_request, dir);
if response.is_success() {
return response
return response;
}
}
}

View File

@ -2,8 +2,7 @@ const WIDTH: usize = 50;
use std::io::{self, Write};
pub struct Shell {
}
pub struct Shell {}
impl Shell {
pub fn new() -> Shell {
@ -11,11 +10,7 @@ impl Shell {
}
pub fn status(&self, s: &str) {
let s = if s.len() > WIDTH {
&s[..WIDTH]
} else {
s
};
let s = if s.len() > WIDTH { &s[..WIDTH] } else { s };
print!("{:<1$}\r", s, WIDTH);
io::stdout().flush().unwrap();
}

View File

@ -67,8 +67,7 @@ fn rmain(args: &Args) -> Result<(), Error> {
if let Some(ref p) = args.flag_output {
let dst = p.with_extension("d.ts");
let ts = object.typescript();
fs::write(&dst, ts)
.with_context(|_| format!("failed to write `{}`", dst.display()))?;
fs::write(&dst, ts).with_context(|_| format!("failed to write `{}`", dst.display()))?;
}
}
@ -76,8 +75,7 @@ fn rmain(args: &Args) -> Result<(), Error> {
match args.flag_output {
Some(ref p) => {
fs::write(p, js)
.with_context(|_| format!("failed to write `{}`", p.display()))?;
fs::write(p, js).with_context(|_| format!("failed to write `{}`", p.display()))?;
}
None => {
println!("{}", js);