Skip to content

Commit

Permalink
feat(cli.rs): add context to errors (#1674)
Browse files Browse the repository at this point in the history
  • Loading branch information
lucasfernog authored May 2, 2021
1 parent 9fadbf3 commit 5cc4b11
Show file tree
Hide file tree
Showing 8 changed files with 69 additions and 26 deletions.
5 changes: 5 additions & 0 deletions .changes/cli-error-logging.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"cli.rs": patch
---

Improve error logging.
21 changes: 14 additions & 7 deletions tooling/cli.rs/src/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

use anyhow::Context;
use tauri_bundler::bundle::{bundle_project, PackageType, SettingsBuilder};

use crate::helpers::{
Expand Down Expand Up @@ -67,7 +68,7 @@ impl Build {
let config = get_config(self.config.as_deref())?;

let tauri_path = tauri_dir();
set_current_dir(&tauri_path)?;
set_current_dir(&tauri_path).with_context(|| "failed to change current working directory")?;

rewrite_manifest(config.clone())?;

Expand All @@ -83,14 +84,16 @@ impl Build {
.arg("/C")
.arg(before_build)
.current_dir(app_dir()),
)?;
)
.with_context(|| format!("failed to run `{}` with `cmd /C`", before_build))?;
#[cfg(not(target_os = "windows"))]
execute_with_output(
&mut Command::new("sh")
.arg("-c")
.arg(before_build)
.current_dir(app_dir()),
)?;
)
.with_context(|| format!("failed to run `{}` with `sh -c`", before_build))?;
}
}

Expand All @@ -108,11 +111,13 @@ impl Build {
.or(runner_from_config)
.unwrap_or_else(|| "cargo".to_string());

rust::build_project(runner, &self.target, self.debug)?;
rust::build_project(runner, &self.target, self.debug).with_context(|| "failed to build app")?;

let app_settings = rust::AppSettings::new(&config_)?;

let out_dir = app_settings.get_out_dir(self.debug)?;
let out_dir = app_settings
.get_out_dir(self.debug)
.with_context(|| "failed to get project out directory")?;
if let Some(product_name) = config_.package.product_name.clone() {
let bin_name = app_settings.cargo_package_settings().name.clone();
#[cfg(windows)]
Expand Down Expand Up @@ -176,9 +181,11 @@ impl Build {
}

// Bundle the project
let settings = settings_builder.build()?;
let settings = settings_builder
.build()
.with_context(|| "failed to build bundler settings")?;

let bundles = bundle_project(settings)?;
let bundles = bundle_project(settings).with_context(|| "failed to bundle project")?;

// If updater is active and pubkey is available
if config_.tauri.updater.active && config_.tauri.updater.pubkey.is_some() {
Expand Down
29 changes: 21 additions & 8 deletions tooling/cli.rs/src/build/rust.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use std::{
str::FromStr,
};

use anyhow::Context;
use serde::Deserialize;

use crate::helpers::{app_paths::tauri_dir, config::Config};
Expand Down Expand Up @@ -70,9 +71,13 @@ impl CargoSettings {
fn load(dir: &Path) -> crate::Result<Self> {
let toml_path = dir.join("Cargo.toml");
let mut toml_str = String::new();
let mut toml_file = File::open(toml_path)?;
toml_file.read_to_string(&mut toml_str)?;
toml::from_str(&toml_str).map_err(Into::into)
let mut toml_file = File::open(toml_path).with_context(|| "failed to open Cargo.toml")?;
toml_file
.read_to_string(&mut toml_str)
.with_context(|| "failed to read Cargo.toml")?;
toml::from_str(&toml_str)
.with_context(|| "failed to parse Cargo.toml")
.map_err(Into::into)
}
}

Expand All @@ -99,7 +104,10 @@ pub fn build_project(runner: String, target: &Option<String>, debug: bool) -> cr
args.push("--release");
}

let status = Command::new(&runner).args(args).status()?;
let status = Command::new(&runner)
.args(args)
.status()
.with_context(|| format!("failed to run {}", runner))?;
if !status.success() {
return Err(anyhow::anyhow!(format!(
"Result of `{} build` operation was unsuccessful: {}",
Expand All @@ -118,7 +126,8 @@ pub struct AppSettings {

impl AppSettings {
pub fn new(config: &Config) -> crate::Result<Self> {
let cargo_settings = CargoSettings::load(&tauri_dir())?;
let cargo_settings =
CargoSettings::load(&tauri_dir()).with_context(|| "failed to load cargo settings")?;
let cargo_package_settings = match &cargo_settings.package {
Some(package_info) => package_info.clone(),
None => {
Expand Down Expand Up @@ -268,9 +277,13 @@ fn get_target_dir(
// if the path exists, parse it
if cargo_config_path.exists() {
let mut config_str = String::new();
let mut config_file = File::open(cargo_config_path)?;
config_file.read_to_string(&mut config_str)?;
let config: CargoConfig = toml::from_str(&config_str)?;
let mut config_file = File::open(&cargo_config_path)
.with_context(|| format!("failed to open {:?}", cargo_config_path))?;
config_file
.read_to_string(&mut config_str)
.with_context(|| "failed to read cargo config file")?;
let config: CargoConfig =
toml::from_str(&config_str).with_context(|| "failed to parse cargo config file")?;
if let Some(build) = config.build {
if let Some(target_dir) = build.target_dir {
break Some(target_dir.into());
Expand Down
13 changes: 9 additions & 4 deletions tooling/cli.rs/src/dev.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use crate::helpers::{
Logger,
};

use anyhow::Context;
use notify::{watcher, DebouncedEvent, RecursiveMode, Watcher};
use once_cell::sync::OnceCell;
use shared_child::SharedChild;
Expand Down Expand Up @@ -74,7 +75,7 @@ impl Dev {
pub fn run(self) -> crate::Result<()> {
let logger = Logger::new("tauri:dev");
let tauri_path = tauri_dir();
set_current_dir(&tauri_path)?;
set_current_dir(&tauri_path).with_context(|| "failed to change current working directory")?;
let merge_config = self.config.clone();
let config = get_config(merge_config.as_deref())?;
let mut process: Arc<SharedChild>;
Expand All @@ -94,13 +95,15 @@ impl Dev {
.arg("/C")
.arg(before_dev)
.current_dir(app_dir())
.spawn()?;
.spawn()
.with_context(|| format!("failed to run `{}` with `cmd /C`", before_dev))?;
#[cfg(not(target_os = "windows"))]
let child = Command::new("sh")
.arg("-c")
.arg(before_dev)
.current_dir(app_dir())
.spawn()?;
.spawn()
.with_context(|| format!("failed to run `{}` with `sh -c`", before_dev))?;
BEFORE_DEV.set(Mutex::new(child)).unwrap();
}
}
Expand Down Expand Up @@ -173,7 +176,9 @@ impl Dev {
// which will trigger the watcher again
// So the app should only be started when a file other than tauri.conf.json is changed
let _ = child_wait_tx.send(());
process.kill()?;
process
.kill()
.with_context(|| "failed to kill app process")?;
process = self.start_app(&runner, child_wait_rx.clone());
}
}
Expand Down
7 changes: 5 additions & 2 deletions tooling/cli.rs/src/helpers/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

use anyhow::Context;
#[cfg(target_os = "linux")]
use heck::KebabCase;
use json_patch::merge;
Expand Down Expand Up @@ -52,7 +53,8 @@ fn get_internal(merge_config: Option<&str>, reload: bool) -> crate::Result<Confi
let path = super::app_paths::tauri_dir().join("tauri.conf.json");
let file = File::open(path)?;
let buf = BufReader::new(file);
let mut config: JsonValue = serde_json::from_reader(buf)?;
let mut config: JsonValue =
serde_json::from_reader(buf).with_context(|| "failed to parse `tauri.conf.json`")?;

let schema: JsonValue = serde_json::from_str(include_str!("../../schema.json"))?;
let mut scope = valico::json_schema::Scope::new();
Expand All @@ -75,7 +77,8 @@ fn get_internal(merge_config: Option<&str>, reload: bool) -> crate::Result<Confi
}

if let Some(merge_config) = merge_config {
let merge_config: JsonValue = serde_json::from_str(&merge_config)?;
let merge_config: JsonValue =
serde_json::from_str(&merge_config).with_context(|| "failed to parse config to merge")?;
merge(&mut config, &merge_config);
}

Expand Down
11 changes: 8 additions & 3 deletions tooling/cli.rs/src/helpers/manifest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use super::{app_paths::tauri_dir, config::ConfigHandle};

use anyhow::Context;
use toml_edit::{Array, Document, InlineTable, Item, Value};

use std::{
Expand All @@ -14,9 +15,12 @@ use std::{
pub fn rewrite_manifest(config: ConfigHandle) -> crate::Result<()> {
let manifest_path = tauri_dir().join("Cargo.toml");
let mut manifest_str = String::new();
let mut manifest_file = File::open(&manifest_path)?;
let mut manifest_file = File::open(&manifest_path)
.with_context(|| format!("failed to open `{:?}` file", manifest_path))?;
manifest_file.read_to_string(&mut manifest_str)?;
let mut manifest: Document = manifest_str.parse::<Document>()?;
let mut manifest: Document = manifest_str
.parse::<Document>()
.with_context(|| "failed to parse Cargo.toml")?;
let dependencies = manifest
.as_table_mut()
.entry("dependencies")
Expand Down Expand Up @@ -68,7 +72,8 @@ pub fn rewrite_manifest(config: ConfigHandle) -> crate::Result<()> {
return Ok(());
}

let mut manifest_file = File::create(&manifest_path)?;
let mut manifest_file =
File::create(&manifest_path).with_context(|| "failed to open Cargo.toml for rewrite")?;
manifest_file.write_all(
manifest
.to_string_in_original_order()
Expand Down
4 changes: 3 additions & 1 deletion tooling/cli.rs/src/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use std::{
};

use crate::helpers::Logger;
use anyhow::Context;
use handlebars::{to_json, Handlebars};
use include_dir::{include_dir, Dir};
use serde::Deserialize;
Expand Down Expand Up @@ -142,7 +143,8 @@ impl Init {
to_json(self.window_title.unwrap_or_else(|| "Tauri".to_string())),
);

render_template(&handlebars, &data, &TEMPLATE_DIR, &self.directory)?;
render_template(&handlebars, &data, &TEMPLATE_DIR, &self.directory)
.with_context(|| "failed to render Tauri template")?;
}

Ok(())
Expand Down
5 changes: 4 additions & 1 deletion tooling/cli.rs/src/sign.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ use crate::helpers::updater_signature::{
};
use std::path::{Path, PathBuf};

use anyhow::Context;

#[derive(Default)]
pub struct Signer {
private_key: Option<String>,
Expand Down Expand Up @@ -63,7 +65,8 @@ impl Signer {
self.password.unwrap(),
self.file.unwrap(),
false,
)?;
)
.with_context(|| "failed to sign file")?;

println!(
"\nYour file was signed successfully, You can find the signature here:\n{}\n\nPublic signature:\n{}\n\nMake sure to include this into the signature field of your update server.",
Expand Down

0 comments on commit 5cc4b11

Please sign in to comment.