Skip to content
Merged

Cleanups #14632

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changes/change-pr-14632.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"tauri-utils": patch:enhance
"tauri-build": patch:enhance
"tauri-cli": patch:enhance
---

Small code refactors for improved code readability. No user facing changes.
16 changes: 6 additions & 10 deletions crates/tauri-build/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,21 +165,21 @@ fn copy_frameworks(dest_dir: &Path, frameworks: &[String]) -> Result<()> {
.with_context(|| format!("Failed to create frameworks output directory at {dest_dir:?}"))?;
for framework in frameworks.iter() {
if framework.ends_with(".framework") {
let src_path = PathBuf::from(framework);
let src_path = Path::new(framework);
let src_name = src_path
.file_name()
.expect("Couldn't get framework filename");
let dest_path = dest_dir.join(src_name);
copy_dir(&src_path, &dest_path)?;
copy_dir(src_path, &dest_path)?;
continue;
} else if framework.ends_with(".dylib") {
let src_path = PathBuf::from(framework);
let src_path = Path::new(framework);
if !src_path.exists() {
return Err(anyhow::anyhow!("Library not found: {}", framework));
}
let src_name = src_path.file_name().expect("Couldn't get library filename");
let dest_path = dest_dir.join(src_name);
copy_file(&src_path, &dest_path)?;
copy_file(src_path, &dest_path)?;
continue;
} else if framework.contains('/') {
return Err(anyhow::anyhow!(
Expand All @@ -192,12 +192,8 @@ fn copy_frameworks(dest_dir: &Path, frameworks: &[String]) -> Result<()> {
continue;
}
}
if copy_framework_from(&PathBuf::from("/Library/Frameworks/"), framework, dest_dir)?
|| copy_framework_from(
&PathBuf::from("/Network/Library/Frameworks/"),
framework,
dest_dir,
)?
if copy_framework_from("/Library/Frameworks/".as_ref(), framework, dest_dir)?
|| copy_framework_from("/Network/Library/Frameworks/".as_ref(), framework, dest_dir)?
{
continue;
}
Expand Down
3 changes: 1 addition & 2 deletions crates/tauri-bundler/src/bundle/windows/sign.rs
Original file line number Diff line number Diff line change
Expand Up @@ -266,8 +266,7 @@ pub fn try_sign<P: AsRef<Path>>(file_path: P, settings: &Settings) -> crate::Res
pub fn should_sign(file_path: &Path) -> crate::Result<bool> {
let is_binary = file_path
.extension()
.and_then(|extension| extension.to_str())
.is_some_and(|extension| matches!(extension, "exe" | "dll"));
.is_some_and(|ext| ext == "exe" || ext == "dll");
if !is_binary {
return Ok(false);
}
Expand Down
39 changes: 17 additions & 22 deletions crates/tauri-cli/src/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use crate::{
helpers::{
self,
app_paths::{frontend_dir, tauri_dir},
config::{get as get_config, ConfigHandle, FrontendDist},
config::{get as get_config, ConfigMetadata, FrontendDist},
},
info::plugins::check_mismatched_packages,
interface::{rust::get_cargo_target_dir, AppInterface, Interface},
Expand Down Expand Up @@ -106,11 +106,11 @@ pub fn command(mut options: Options, verbosity: u8) -> Result<()> {
options.target.clone(),
)?;

setup(&interface, &mut options, config.clone(), false)?;

let config_guard = config.lock().unwrap();
let config_ = config_guard.as_ref().unwrap();

setup(&interface, &mut options, config_, false)?;

if let Some(minimum_system_version) = &config_.bundle.macos.minimum_system_version {
std::env::set_var("MACOSX_DEPLOYMENT_TARGET", minimum_system_version);
}
Expand All @@ -132,7 +132,7 @@ pub fn command(mut options: Options, verbosity: u8) -> Result<()> {
verbosity,
ci,
&interface,
&app_settings,
&*app_settings,
config_,
&out_dir,
)?;
Expand All @@ -144,7 +144,7 @@ pub fn command(mut options: Options, verbosity: u8) -> Result<()> {
pub fn setup(
interface: &AppInterface,
options: &mut Options,
config: ConfigHandle,
config: &ConfigMetadata,
mobile: bool,
) -> Result<()> {
let tauri_path = tauri_dir();
Expand All @@ -162,44 +162,39 @@ pub fn setup(

set_current_dir(tauri_path).context("failed to set current directory")?;

let config_guard = config.lock().unwrap();
let config_ = config_guard.as_ref().unwrap();

let bundle_identifier_source = config_
let bundle_identifier_source = config
.find_bundle_identifier_overwriter()
.unwrap_or_else(|| "tauri.conf.json".into());

if config_.identifier == "com.tauri.dev" {
if config.identifier == "com.tauri.dev" {
crate::error::bail!(
"You must change the bundle identifier in `{bundle_identifier_source} identifier`. The default value `com.tauri.dev` is not allowed as it must be unique across applications.",
);
}

if config_
if config
.identifier
.chars()
.any(|ch| !(ch.is_alphanumeric() || ch == '-' || ch == '.'))
{
crate::error::bail!(
"The bundle identifier \"{}\" set in `{} identifier`. The bundle identifier string must contain only alphanumeric characters (A-Z, a-z, and 0-9), hyphens (-), and periods (.).",
config_.identifier,
bundle_identifier_source
"The bundle identifier \"{}\" set in `{bundle_identifier_source:?} identifier`. The bundle identifier string must contain only alphanumeric characters (A-Z, a-z, and 0-9), hyphens (-), and periods (.).",
config.identifier,
);
}

if config_.identifier.ends_with(".app") {
if config.identifier.ends_with(".app") {
log::warn!(
"The bundle identifier \"{}\" set in `{} identifier` ends with `.app`. This is not recommended because it conflicts with the application bundle extension on macOS.",
config_.identifier,
bundle_identifier_source
"The bundle identifier \"{}\" set in `{bundle_identifier_source:?} identifier` ends with `.app`. This is not recommended because it conflicts with the application bundle extension on macOS.",
config.identifier,
);
}

if let Some(before_build) = config_.build.before_build_command.clone() {
if let Some(before_build) = config.build.before_build_command.clone() {
helpers::run_hook("beforeBuildCommand", before_build, interface, options.debug)?;
}

if let Some(FrontendDist::Directory(web_asset_path)) = &config_.build.frontend_dist {
if let Some(FrontendDist::Directory(web_asset_path)) = &config.build.frontend_dist {
if !web_asset_path.exists() {
let absolute_path = web_asset_path
.parent()
Expand Down Expand Up @@ -252,13 +247,13 @@ pub fn setup(
}

if options.runner.is_none() {
options.runner = config_.build.runner.clone();
options.runner = config.build.runner.clone();
}

options
.features
.get_or_insert(Vec::new())
.extend(config_.build.features.clone().unwrap_or_default());
.extend(config.build.features.clone().unwrap_or_default());
interface.build_options(&mut options.args, &mut options.features, mobile);

Ok(())
Expand Down
4 changes: 2 additions & 2 deletions crates/tauri-cli/src/bundle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ pub fn command(options: Options, verbosity: u8) -> crate::Result<()> {
verbosity,
ci,
&interface,
&app_settings,
&*app_settings,
config_,
&out_dir,
)
Expand All @@ -170,7 +170,7 @@ pub fn bundle<A: AppSettings>(
verbosity: u8,
ci: bool,
interface: &AppInterface,
app_settings: &std::sync::Arc<A>,
app_settings: &A,
config: &ConfigMetadata,
out_dir: &Path,
) -> crate::Result<()> {
Expand Down
16 changes: 6 additions & 10 deletions crates/tauri-cli/src/dev.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ use std::{
mod builtin_dev_server;

static BEFORE_DEV: OnceLock<Mutex<Arc<SharedChild>>> = OnceLock::new();
static KILL_BEFORE_DEV_FLAG: OnceLock<AtomicBool> = OnceLock::new();
static KILL_BEFORE_DEV_FLAG: AtomicBool = AtomicBool::new(false);

#[cfg(unix)]
const KILL_CHILDREN_SCRIPT: &[u8] = include_bytes!("../scripts/kill-children.sh");
Expand Down Expand Up @@ -218,14 +218,13 @@ pub fn setup(interface: &AppInterface, options: &mut Options, config: ConfigHand
let status = child_
.wait()
.expect("failed to wait on \"beforeDevCommand\"");
if !(status.success() || KILL_BEFORE_DEV_FLAG.get().unwrap().load(Ordering::Relaxed)) {
if !(status.success() || KILL_BEFORE_DEV_FLAG.load(Ordering::Relaxed)) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Although implausible, there's nothing stopping the child to exit before the flag gets initialized. Because the thread is spawned, this panic might be hard to detect.

log::error!("The \"beforeDevCommand\" terminated with a non-zero status code.");
exit(status.code().unwrap_or(1));
}
});

BEFORE_DEV.set(Mutex::new(child)).unwrap();
KILL_BEFORE_DEV_FLAG.set(AtomicBool::default()).unwrap();

let _ = ctrlc::set_handler(move || {
kill_before_dev_process();
Expand Down Expand Up @@ -304,12 +303,10 @@ pub fn setup(interface: &AppInterface, options: &mut Options, config: ConfigHand

if !options.no_dev_server_wait {
if let Some(url) = dev_url {
let host = url
.host()
.unwrap_or_else(|| panic!("No host name in the URL"));
let host = url.host().expect("No host name in the URL");
let port = url
.port_or_known_default()
.unwrap_or_else(|| panic!("No port number in the URL"));
.expect("No port number in the URL");
let addrs;
let addr;
let addrs = match host {
Expand Down Expand Up @@ -380,11 +377,10 @@ pub fn on_app_exit(code: Option<i32>, reason: ExitReason, exit_on_panic: bool, n
pub fn kill_before_dev_process() {
if let Some(child) = BEFORE_DEV.get() {
let child = child.lock().unwrap();
let kill_before_dev_flag = KILL_BEFORE_DEV_FLAG.get().unwrap();
if kill_before_dev_flag.load(Ordering::Relaxed) {
if KILL_BEFORE_DEV_FLAG.load(Ordering::Relaxed) {
return;
}
kill_before_dev_flag.store(true, Ordering::Relaxed);
KILL_BEFORE_DEV_FLAG.store(true, Ordering::Relaxed);
#[cfg(windows)]
{
let powershell_path = std::env::var("SYSTEMROOT").map_or_else(
Expand Down
16 changes: 4 additions & 12 deletions crates/tauri-cli/src/helpers/app_paths.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,21 +75,13 @@ fn lookup<F: Fn(&PathBuf) -> bool>(dir: &Path, checker: F) -> Option<PathBuf> {
}

fn env_tauri_app_path() -> Option<PathBuf> {
std::env::var(ENV_TAURI_APP_PATH)
.map(PathBuf::from)
.ok()?
.canonicalize()
.ok()
.map(|p| dunce::simplified(&p).to_path_buf())
let p = PathBuf::from(std::env::var_os(ENV_TAURI_APP_PATH)?);
dunce::canonicalize(p).ok()
}

fn env_tauri_frontend_path() -> Option<PathBuf> {
std::env::var(ENV_TAURI_FRONTEND_PATH)
.map(PathBuf::from)
.ok()?
.canonicalize()
.ok()
.map(|p| dunce::simplified(&p).to_path_buf())
let p = PathBuf::from(std::env::var_os(ENV_TAURI_FRONTEND_PATH)?);
dunce::canonicalize(p).ok()
}

pub fn resolve_tauri_dir() -> Option<PathBuf> {
Expand Down
35 changes: 16 additions & 19 deletions crates/tauri-cli/src/helpers/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ pub use tauri_utils::{config::*, platform::Target};
use std::{
collections::HashMap,
env::{current_dir, set_current_dir, set_var},
ffi::OsStr,
ffi::{OsStr, OsString},
process::exit,
sync::{Arc, Mutex, OnceLock},
sync::Mutex,
};

use crate::error::Context;
Expand All @@ -30,7 +30,7 @@ pub struct ConfigMetadata {
inner: Config,
/// The config extensions (platform-specific config files or the config CLI argument).
/// Maps the extension name to its value.
extensions: HashMap<String, JsonValue>,
extensions: HashMap<OsString, JsonValue>,
}

impl std::ops::Deref for ConfigMetadata {
Expand All @@ -50,7 +50,7 @@ impl ConfigMetadata {
}

/// Checks which config is overwriting the bundle identifier.
pub fn find_bundle_identifier_overwriter(&self) -> Option<String> {
pub fn find_bundle_identifier_overwriter(&self) -> Option<OsString> {
for (ext, config) in &self.extensions {
if let Some(identifier) = config
.as_object()
Expand All @@ -66,7 +66,7 @@ impl ConfigMetadata {
}
}

pub type ConfigHandle = Arc<Mutex<Option<ConfigMetadata>>>;
pub type ConfigHandle = &'static Mutex<Option<ConfigMetadata>>;

pub fn wix_settings(config: WixConfig) -> tauri_bundler::WixSettings {
tauri_bundler::WixSettings {
Expand Down Expand Up @@ -141,9 +141,9 @@ pub fn custom_sign_settings(
}
}

fn config_handle() -> &'static ConfigHandle {
static CONFIG_HANDLE: OnceLock<ConfigHandle> = OnceLock::new();
CONFIG_HANDLE.get_or_init(Default::default)
fn config_handle() -> ConfigHandle {
static CONFIG_HANDLE: Mutex<Option<ConfigMetadata>> = Mutex::new(None);
&CONFIG_HANDLE
}

/// Gets the static parsed config from `tauri.conf.json`.
Expand All @@ -153,14 +153,14 @@ fn get_internal(
target: Target,
) -> crate::Result<ConfigHandle> {
if !reload && config_handle().lock().unwrap().is_some() {
return Ok(config_handle().clone());
return Ok(config_handle());
}

let tauri_dir = super::app_paths::tauri_dir();
let (mut config, config_path) =
tauri_utils::config::parse::parse_value(target, tauri_dir.join("tauri.conf.json"))
.context("failed to parse config")?;
let config_file_name = config_path.file_name().unwrap().to_string_lossy();
let config_file_name = config_path.file_name().unwrap();
let mut extensions = HashMap::new();

let original_identifier = config
Expand All @@ -174,10 +174,7 @@ fn get_internal(
.context("failed to parse platform config")?
{
merge(&mut config, &platform_config);
extensions.insert(
config_path.file_name().unwrap().to_str().unwrap().into(),
platform_config,
);
extensions.insert(config_path.file_name().unwrap().into(), platform_config);
}

if !merge_configs.is_empty() {
Expand All @@ -203,9 +200,9 @@ fn get_internal(
for error in errors {
let path = error.instance_path.into_iter().join(" > ");
if path.is_empty() {
log::error!("`{}` error: {}", config_file_name, error);
log::error!("`{config_file_name:?}` error: {}", error);
} else {
log::error!("`{}` error on `{}`: {}", config_file_name, path, error);
log::error!("`{config_file_name:?}` error on `{}`: {}", path, error);
}
}
if !reload {
Expand Down Expand Up @@ -243,7 +240,7 @@ fn get_internal(
extensions,
});

Ok(config_handle().clone())
Ok(config_handle())
}

pub fn get(target: Target, merge_configs: &[&serde_json::Value]) -> crate::Result<ConfigHandle> {
Expand All @@ -268,7 +265,7 @@ pub fn merge_with(merge_configs: &[&serde_json::Value]) -> crate::Result<ConfigH
let handle = config_handle();

if merge_configs.is_empty() {
return Ok(handle.clone());
return Ok(handle);
}

if let Some(config_metadata) = &mut *handle.lock().unwrap() {
Expand All @@ -285,7 +282,7 @@ pub fn merge_with(merge_configs: &[&serde_json::Value]) -> crate::Result<ConfigH
merge(&mut value, &merge_config);
config_metadata.inner = serde_json::from_value(value).context("failed to parse config")?;

Ok(handle.clone())
Ok(handle)
} else {
crate::error::bail!("config not loaded");
}
Expand Down
Loading
Loading