[Refactor] Remove unwraps from tauri (#234)

* remove unwraps from tauri code

* refactor bundler and remove unwraps

* remove errors

* cleaup and add distinctions

* reword panic
This commit is contained in:
Tensor-Programming
2019-12-26 16:09:04 -05:00
committed by GitHub
parent a4e229ca10
commit b92eee019c
17 changed files with 128 additions and 87 deletions

View File

@@ -19,7 +19,7 @@ lazy_static! {
handlebars
.register_template_string("appimage", include_str!("templates/appimage"))
.unwrap();
.expect("Failed to register template for handlebars");
handlebars
};
}

View File

@@ -60,7 +60,7 @@ pub fn copy_file(from: &Path, to: &Path) -> crate::Result<()> {
if !from.is_file() {
bail!("{:?} is not a file", from);
}
let dest_dir = to.parent().unwrap();
let dest_dir = to.parent().expect("No data in parent");
fs::create_dir_all(dest_dir).chain_err(|| format!("Failed to create {:?}", dest_dir))?;
fs::copy(from, to).chain_err(|| format!("Failed to copy {:?} to {:?}", from, to))?;
Ok(())
@@ -80,12 +80,12 @@ pub fn copy_dir(from: &Path, to: &Path) -> crate::Result<()> {
if to.exists() {
bail!("{:?} already exists", to);
}
let parent = to.parent().unwrap();
let parent = to.parent().expect("No data in parent");
fs::create_dir_all(parent).chain_err(|| format!("Failed to create {:?}", parent))?;
for entry in walkdir::WalkDir::new(from) {
let entry = entry?;
debug_assert!(entry.path().starts_with(from));
let rel_path = entry.path().strip_prefix(from).unwrap();
let rel_path = entry.path().strip_prefix(from)?;
let dest_path = to.join(rel_path);
if entry.file_type().is_symlink() {
let target = fs::read_link(entry.path())?;
@@ -251,11 +251,12 @@ mod tests {
#[test]
fn create_file_with_parent_dirs() {
let tmp = tempfile::tempdir().unwrap();
let tmp = tempfile::tempdir().expect("Unable to create temp dir");
assert!(!tmp.path().join("parent").exists());
{
let mut file = create_file(&tmp.path().join("parent/file.txt")).unwrap();
write!(file, "Hello, world!\n").unwrap();
let mut file =
create_file(&tmp.path().join("parent/file.txt")).expect("Failed to create file");
write!(file, "Hello, world!\n").expect("unable to write file");
}
assert!(tmp.path().join("parent").is_dir());
assert!(tmp.path().join("parent/file.txt").is_file());
@@ -268,42 +269,44 @@ mod tests {
// sub/
// file.txt
// link -> sub/file.txt
let tmp = tempfile::tempdir().unwrap();
let tmp = tempfile::tempdir().expect("unable to create tempdir");
{
let mut file = create_file(&tmp.path().join("orig/sub/file.txt")).unwrap();
write!(file, "Hello, world!\n").unwrap();
let mut file =
create_file(&tmp.path().join("orig/sub/file.txt")).expect("Unable to create file");
write!(file, "Hello, world!\n").expect("Unable to write to file");
}
symlink_file(
&PathBuf::from("sub/file.txt"),
&tmp.path().join("orig/link"),
)
.unwrap();
.expect("Failed to create symlink");
assert_eq!(
std::fs::read(tmp.path().join("orig/link"))
.unwrap()
.expect("Failed to read file")
.as_slice(),
b"Hello, world!\n"
);
// Copy ${TMP}/orig to ${TMP}/parent/copy, and make sure that the
// directory structure, file, and symlink got copied correctly.
copy_dir(&tmp.path().join("orig"), &tmp.path().join("parent/copy")).unwrap();
copy_dir(&tmp.path().join("orig"), &tmp.path().join("parent/copy"))
.expect("Failed to copy dir");
assert!(tmp.path().join("parent/copy").is_dir());
assert!(tmp.path().join("parent/copy/sub").is_dir());
assert!(tmp.path().join("parent/copy/sub/file.txt").is_file());
assert_eq!(
std::fs::read(tmp.path().join("parent/copy/sub/file.txt"))
.unwrap()
.expect("Failed to read file")
.as_slice(),
b"Hello, world!\n"
);
assert!(tmp.path().join("parent/copy/link").exists());
assert_eq!(
std::fs::read_link(tmp.path().join("parent/copy/link")).unwrap(),
std::fs::read_link(tmp.path().join("parent/copy/link")).expect("Failed to read from symlink"),
PathBuf::from("sub/file.txt")
);
assert_eq!(
std::fs::read(tmp.path().join("parent/copy/link"))
.unwrap()
.expect("Failed to read from file")
.as_slice(),
b"Hello, world!\n"
);

View File

@@ -189,7 +189,7 @@ fn generate_md5sums(control_dir: &Path, data_dir: &Path) -> crate::Result<()> {
for byte in hash.compute().iter() {
write!(md5sums_file, "{:02x}", byte)?;
}
let rel_path = path.strip_prefix(data_dir).unwrap();
let rel_path = path.strip_prefix(data_dir)?;
let path_str = rel_path.to_str().ok_or_else(|| {
let msg = format!("Non-UTF-8 path: {:?}", rel_path);
io::Error::new(io::ErrorKind::InvalidData, msg)
@@ -232,8 +232,8 @@ fn generate_icon_files(settings: &Settings, data_dir: &PathBuf) -> crate::Result
continue;
}
let decoder = PNGDecoder::new(File::open(&icon_path)?)?;
let width = decoder.dimensions().0.try_into().unwrap();
let height = decoder.dimensions().1.try_into().unwrap();
let width = decoder.dimensions().0.try_into()?;
let height = decoder.dimensions().1.try_into()?;
let is_high_density = common::is_retina(&icon_path);
if !sizes.contains(&(width, height, is_high_density)) {
sizes.insert((width, height, is_high_density));
@@ -303,7 +303,7 @@ fn create_tar_from_dir<P: AsRef<Path>, W: Write>(src_dir: P, dest_file: W) -> cr
if src_path == src_dir {
continue;
}
let dest_path = src_path.strip_prefix(&src_dir).unwrap();
let dest_path = src_path.strip_prefix(&src_dir)?;
if entry.file_type().is_dir() {
tar_builder.append_dir(dest_path, src_path)?;
} else {

View File

@@ -17,7 +17,7 @@ lazy_static! {
handlebars
.register_template_string("bundle_dmg", include_str!("templates/bundle_dmg"))
.unwrap();
.expect("Failed to setup handlebars template");
handlebars
};
}

View File

@@ -76,8 +76,8 @@ fn generate_icon_files(bundle_dir: &Path, settings: &Settings) -> crate::Result<
continue;
}
let decoder = PNGDecoder::new(File::open(&icon_path)?)?;
let width = decoder.dimensions().0.try_into().unwrap();
let height = decoder.dimensions().1.try_into().unwrap();
let width = decoder.dimensions().0.try_into()?;
let height = decoder.dimensions().1.try_into()?;
let is_retina = common::is_retina(&icon_path);
if !sizes.contains(&(width, height, is_retina)) {
sizes.insert((width, height, is_retina));

View File

@@ -115,7 +115,7 @@ fn create_info_plist(
write!(
file,
" <key>CFBundleIconFile</key>\n <string>{}</string>\n",
path.file_name().unwrap().to_string_lossy()
path.file_name().expect("No file name").to_string_lossy()
)?;
}
write!(
@@ -201,7 +201,9 @@ fn copy_frameworks_to_bundle(bundle_directory: &Path, settings: &Settings) -> cr
for framework in frameworks.iter() {
if framework.ends_with(".framework") {
let src_path = PathBuf::from(framework);
let src_name = src_path.file_name().unwrap();
let src_name = src_path
.file_name()
.expect("Couldn't get framework filename");
common::copy_dir(&src_path, &dest_dir.join(&src_name))?;
continue;
} else if framework.contains("/") {
@@ -245,7 +247,7 @@ fn create_icns_file(
let icon_path = icon_path?;
if icon_path.extension() == Some(OsStr::new("icns")) {
let mut dest_path = resources_dir.to_path_buf();
dest_path.push(icon_path.file_name().unwrap());
dest_path.push(icon_path.file_name().expect("Could not get icon filename"));
common::copy_file(&icon_path, &dest_path)?;
return Ok(Some(dest_path));
}

View File

@@ -224,7 +224,7 @@ where
if item.is_none() {
return Err("Invalid path".into());
}
let item = item.unwrap().to_string();
let item = item.expect("Item had no data").to_string();
if path.as_ref().is_dir() {
directories.push(item);

View File

@@ -182,7 +182,7 @@ impl Settings {
Some(
matches
.values_of("features")
.unwrap()
.expect("Couldn't get the features")
.map(|s| s.to_string())
.collect(),
)
@@ -284,7 +284,7 @@ impl Settings {
if workspace_settings.members.is_some()
&& workspace_settings
.members
.unwrap()
.expect("Couldn't get members")
.iter()
.any(|member| member.as_str() == project_name)
{
@@ -607,16 +607,19 @@ mod tests {
[dependencies]\n\
rand = \"0.4\"\n";
let cargo_settings: CargoSettings = toml::from_str(toml_str).unwrap();
let package = cargo_settings.package.unwrap();
let package = cargo_settings.package.expect("Couldn't get package");
assert_eq!(package.name, "example");
assert_eq!(package.version, "0.1.0");
assert_eq!(package.description, "An example application.");
assert_eq!(package.homepage, None);
assert_eq!(package.authors, Some(vec!["Jane Doe".to_string()]));
assert!(package.metadata.is_some());
let metadata = package.metadata.as_ref().unwrap();
let metadata = package
.metadata
.as_ref()
.expect("Failed to get metadata ref");
assert!(metadata.bundle.is_some());
let bundle = metadata.bundle.as_ref().unwrap();
let bundle = metadata.bundle.as_ref().expect("Failed to get bundle ref");
assert_eq!(bundle.name, Some("Example Application".to_string()));
assert_eq!(bundle.identifier, Some("com.example.app".to_string()));
assert_eq!(bundle.icon, None);
@@ -661,26 +664,34 @@ mod tests {
\n\
[[example]]\n\
name = \"baz\"\n";
let cargo_settings: CargoSettings = toml::from_str(toml_str).unwrap();
let cargo_settings: CargoSettings = toml::from_str(toml_str).expect("Failed to read from toml");
assert!(cargo_settings.package.is_some());
let package = cargo_settings.package.as_ref().unwrap();
let package = cargo_settings
.package
.as_ref()
.expect("Failed to get package ref");
assert!(package.metadata.is_some());
let metadata = package.metadata.as_ref().unwrap();
let metadata = package
.metadata
.as_ref()
.expect("Failed to get metadata ref");
assert!(metadata.bundle.is_some());
let bundle = metadata.bundle.as_ref().unwrap();
let bundle = metadata.bundle.as_ref().expect("Failed to get bundle ref");
assert!(bundle.example.is_some());
let bins = bundle.bin.as_ref().unwrap();
let bins = bundle.bin.as_ref().expect("Failed to get bin ref");
assert!(bins.contains_key("foo"));
let foo: &BundleSettings = bins.get("foo").unwrap();
let foo: &BundleSettings = bins.get("foo").expect("Failed to get foo bundle settings");
assert_eq!(foo.name, Some("Foo App".to_string()));
assert!(bins.contains_key("bar"));
let bar: &BundleSettings = bins.get("bar").unwrap();
let bar: &BundleSettings = bins.get("bar").expect("Failed to get bar bundle settings");
assert_eq!(bar.name, Some("Bar App".to_string()));
let examples = bundle.example.as_ref().unwrap();
let examples = bundle.example.as_ref().expect("Failed to get example ref");
assert!(examples.contains_key("baz"));
let baz: &BundleSettings = examples.get("baz").unwrap();
let baz: &BundleSettings = examples
.get("baz")
.expect("Failed to get baz bundle settings");
assert_eq!(baz.name, Some("Baz Example".to_string()));
}
}

View File

@@ -47,7 +47,7 @@ lazy_static! {
handlebars
.register_template_string("main.wxs", include_str!("templates/main.wxs"))
.or_else(|e| Err(e.to_string()))
.unwrap();
.expect("Failed to setup handlebar template");
handlebars
};
}
@@ -133,7 +133,7 @@ fn extract_zip(data: &Vec<u8>, path: &Path) -> crate::Result<()> {
for i in 0..zipa.len() {
let mut file = zipa.by_index(i).or_else(|e| Err(e.to_string()))?;
let dest_path = path.join(file.name());
let parent = dest_path.parent().unwrap();
let parent = dest_path.parent().expect("Failed to get parent");
if !parent.exists() {
create_dir_all(parent).or_else(|e| Err(e.to_string()))?;
@@ -143,7 +143,7 @@ fn extract_zip(data: &Vec<u8>, path: &Path) -> crate::Result<()> {
file
.read_to_end(&mut buff)
.or_else(|e| Err(e.to_string()))?;
let mut fileout = File::create(dest_path).unwrap();
let mut fileout = File::create(dest_path).expect("Failed to open file");
fileout.write_all(&buff).or_else(|e| Err(e.to_string()))?;
}
@@ -256,15 +256,15 @@ fn run_candle(
.spawn()
.expect("error running candle.exe");
{
let stdout = cmd.stdout.as_mut().unwrap();
let stdout = cmd.stdout.as_mut().expect("Failed to get stdout handle");
let reader = BufReader::new(stdout);
for line in reader.lines() {
common::print_info(line.unwrap().as_str())?;
common::print_info(line.expect("Failed to get line").as_str())?;
}
}
let status = cmd.wait().unwrap();
let status = cmd.wait()?;
if status.success() {
Ok(())
} else {
@@ -296,15 +296,15 @@ fn run_light(
.spawn()
.expect("error running light.exe");
{
let stdout = cmd.stdout.as_mut().unwrap();
let stdout = cmd.stdout.as_mut().expect("Failed to get stdout handle");
let reader = BufReader::new(stdout);
for line in reader.lines() {
common::print_info(line.unwrap().as_str())?;
common::print_info(line.expect("Failed to get line").as_str())?;
}
}
let status = cmd.wait().unwrap();
let status = cmd.wait()?;
if status.success() {
Ok(output_path.to_path_buf())
} else {

View File

@@ -29,7 +29,7 @@ error_chain! {
Walkdir(::walkdir::Error);
HttpError(::attohttpc::Error) #[cfg(windows)];
StripError(std::path::StripPrefixError);
ConvertError(std::num::TryFromIntError);
}
errors {}
}
@@ -153,6 +153,6 @@ fn run() -> crate::Result<()> {
fn main() {
if let Err(error) = run() {
bundle::print_error(&error).unwrap();
bundle::print_error(&error).expect("Failed to call print error in main");
}
}

View File

@@ -179,7 +179,11 @@ impl<'a> Extract<'a> {
}
ArchiveFormat::Zip => {
let mut archive = zip::ZipArchive::new(source)?;
let mut file = archive.by_name(file_to_extract.to_str().unwrap())?;
let mut file = archive.by_name(
file_to_extract
.to_str()
.expect("Could not convert file to str"),
)?;
let mut output = fs::File::create(into_dir.join(file.name()))?;
io::copy(&mut file, &mut output)?;
}

View File

@@ -69,7 +69,7 @@ pub(crate) fn run(application: &mut crate::App) {
Vec::new(),
std::process::Stdio::inherit(),
)
.unwrap();
.expect("Failed to spawn updater thread");
});
}
@@ -95,13 +95,13 @@ pub(crate) fn run(application: &mut crate::App) {
})
.content(content)
.build()
.unwrap();
.expect("Failed to build webview builder");
#[cfg(feature = "dev-server")]
webview
.handle()
.dispatch(|_webview| _webview.eval(include_str!(concat!(env!("TAURI_DIR"), "/tauri.js"))))
.unwrap();
.expect("Failed to grab webview handle");
#[cfg(feature = "embedded-server")]
{
@@ -124,10 +124,10 @@ pub(crate) fn run(application: &mut crate::App) {
.to_string();
request
.respond(crate::server::asset_response(&url))
.unwrap();
.expect("Failed to read asset type");
}
});
}
webview.run().unwrap();
webview.run().expect("Failed to run webview");
}

View File

@@ -39,7 +39,7 @@ pub(crate) fn handle<T: 'static>(webview: &mut WebView<'_, T>, arg: &str) -> boo
fn = crate::event::emit_function_name(),
listeners = crate::event::event_listeners_object_name(),
queue = crate::event::event_queue_object_name()
)).unwrap();
)).expect("Failed to call webview.eval from init");
}
#[cfg(any(feature = "all-api", feature = "readTextFile"))]
ReadTextFile {
@@ -84,7 +84,7 @@ pub(crate) fn handle<T: 'static>(webview: &mut WebView<'_, T>, arg: &str) -> boo
}
#[cfg(any(feature = "all-api", feature = "setTitle"))]
SetTitle { title } => {
webview.set_title(&title).unwrap();
webview.set_title(&title).expect("Failed to set title");
}
#[cfg(any(feature = "all-api", feature = "execute"))]
Execute {
@@ -98,7 +98,7 @@ pub(crate) fn handle<T: 'static>(webview: &mut WebView<'_, T>, arg: &str) -> boo
#[cfg(any(feature = "all-api", feature = "open"))]
Open { uri } => {
crate::spawn(move || {
webbrowser::open(&uri).unwrap();
webbrowser::open(&uri).expect("Failed to open webbrowser with uri");
});
}
@@ -140,7 +140,7 @@ pub(crate) fn handle<T: 'static>(webview: &mut WebView<'_, T>, arg: &str) -> boo
handler = handler,
once_flag = if once { "true" } else { "false" }
))
.unwrap();
.expect("failed to call webview.eval from listen");
}
#[cfg(any(feature = "all-api", feature = "answer"))]
Emit { event, payload } => {
@@ -178,13 +178,17 @@ pub(crate) fn handle<T: 'static>(webview: &mut WebView<'_, T>, arg: &str) -> boo
Ok(format!(
"`data:image/{};base64,{}`",
ext,
base64::encode(&read_asset.unwrap().into_owned())
base64::encode(&read_asset.expect("Failed to read asset type").into_owned())
))
} else {
handle
.dispatch(move |_webview| {
_webview
.eval(&std::str::from_utf8(&read_asset.unwrap().into_owned()).unwrap())
_webview.eval(
&std::str::from_utf8(
&read_asset.expect("Failed to read asset type").into_owned(),
)
.expect("failed to convert asset bytes to u8 slice"),
)
})
.map_err(|err| format!("`{}`", err))
.map(|_| r#""Asset loaded successfully""#.to_string())

View File

@@ -29,7 +29,9 @@ pub fn event_queue_object_name() -> String {
pub fn listen<F: FnMut(String) + 'static>(id: &'static str, handler: F) {
LISTENERS.with(|listeners| {
let mut l = listeners.lock().unwrap();
let mut l = listeners
.lock()
.expect("Failed to lock listeners: listen()");
l.insert(
id.to_string(),
EventHandler {
@@ -55,17 +57,19 @@ pub fn emit<T: 'static>(webview_handle: &Handle<T>, event: &'static str, mut pay
salt
))
})
.unwrap();
.expect("Failed to dispatch JS from emit");
}
pub fn on_event(event: String, data: String) {
LISTENERS.with(|listeners| {
let mut l = listeners.lock().unwrap();
let mut l = listeners
.lock()
.expect("Failed to lock listeners: on_event()");
let key = event.clone();
if l.contains_key(&key) {
let handler = l.get_mut(&key).unwrap();
let handler = l.get_mut(&key).expect("Failed to get mutable handler");
(handler.on_event)(data);
}
});

View File

@@ -5,8 +5,8 @@ extern crate serde_json;
#[macro_use]
extern crate lazy_static;
mod endpoints;
pub mod config;
mod endpoints;
pub mod event;
#[cfg(feature = "embedded-server")]
@@ -56,7 +56,7 @@ pub fn execute_promise<T: 'static, F: FnOnce() -> Result<String, String> + Send
let callback_string = api::rpc::format_callback_result(task(), callback, error);
handle
.dispatch(move |_webview| _webview.eval(callback_string.as_str()))
.unwrap()
.expect("Failed to dispatch promise callback")
});
});
}

View File

@@ -13,24 +13,30 @@ lazy_static! {
pub fn generate() -> String {
let salt = Uuid::new_v4();
SALTS.lock().unwrap().push(Salt {
value: salt.to_string(),
one_time: true,
});
SALTS
.lock()
.expect("Failed to lock Salt mutex: generate()")
.push(Salt {
value: salt.to_string(),
one_time: true,
});
return salt.to_string();
}
pub fn generate_static() -> String {
let salt = Uuid::new_v4();
SALTS.lock().unwrap().push(Salt {
value: salt.to_string(),
one_time: false,
});
SALTS
.lock()
.expect("Failed to lock SALT mutex: generate_static()")
.push(Salt {
value: salt.to_string(),
one_time: false,
});
return salt.to_string();
}
pub fn is_valid(salt: String) -> bool {
let mut salts = SALTS.lock().unwrap();
let mut salts = SALTS.lock().expect("Failed to lock Salt mutex: is_valid()");
match salts.iter().position(|s| s.value == salt) {
Some(index) => {
if salts[index].one_time {
@@ -54,5 +60,7 @@ pub fn validate<T: 'static>(
Err("'INVALID SALT'".to_string())
};
let callback_string = crate::api::rpc::format_callback_result(response, callback, error);
webview.eval(callback_string.as_str()).unwrap();
webview
.eval(callback_string.as_str())
.expect("Failed to eval JS from validate()");
}

View File

@@ -3,21 +3,26 @@ use tiny_http::{Header, Response};
pub fn asset_response(path: &str) -> Response<std::io::Cursor<Vec<u8>>> {
let asset = crate::assets::ASSETS
.get(&format!("{}{}", env!("TAURI_DIST_DIR"), path))
.unwrap()
.expect("Could not get assets")
.into_owned();
let mut response = Response::from_data(asset);
let header;
if path.ends_with(".svg") {
header = Header::from_bytes(&b"Content-Type"[..], &b"image/svg+xml"[..]).unwrap();
header = Header::from_bytes(&b"Content-Type"[..], &b"image/svg+xml"[..])
.expect("Could not add svg+xml header");
} else if path.ends_with(".css") {
header = Header::from_bytes(&b"Content-Type"[..], &b"text/css"[..]).unwrap();
header =
Header::from_bytes(&b"Content-Type"[..], &b"text/css"[..]).expect("Could not add css header");
} else if path.ends_with(".html") {
header = Header::from_bytes(&b"Content-Type"[..], &b"text/html"[..]).unwrap();
header = Header::from_bytes(&b"Content-Type"[..], &b"text/html"[..])
.expect("Could not add html header");
} else if path.ends_with(".js") {
header = Header::from_bytes(&b"Content-Type"[..], &b"text/javascript"[..]).unwrap();
header = Header::from_bytes(&b"Content-Type"[..], &b"text/javascript"[..])
.expect("Could not add Javascript header");
} else {
header = Header::from_bytes(&b"Content-Type"[..], &b"application/octet-stream"[..]).unwrap();
header = Header::from_bytes(&b"Content-Type"[..], &b"application/octet-stream"[..])
.expect("Could not add octet-stream header");
}
response.add_header(header);