Skip to content

Commit 2d28e31

Browse files
authored
Cleanups (#14632)
* refactor(tauri-utils): current_dest and current_pattern always change in-sync, group them to one Option * refactor(tauri-utils): pass path as explicit argument instead of implicitly through self * refactor(tauri-utils): remove struct field that is never set to Some * refactor(tauri-cli): use OsString, OsStr where possible * refactor(tauri-cli): Deref Arc early * refactor(tauri-cli): lock config before passing to build::setup() * refactor(tauri-build, tauri-utils): bettern pattern matching and borrowing * refactor(tauri-cli): dont need Arc if already have static * fix(tauri-cli): race condition initializing static flag, remove unnecessary OnceLock * refactor(tauri-cli): use expect * refactor(tauri-cli): remove unnecessary OnceLock * refactor(tauri-cli): better use of dunce api * refactor(tauri-cli): rename
1 parent 18c69df commit 2d28e31

File tree

14 files changed

+89
-124
lines changed

14 files changed

+89
-124
lines changed

.changes/change-pr-14632.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
"tauri-utils": patch:enhance
3+
"tauri-build": patch:enhance
4+
"tauri-cli": patch:enhance
5+
---
6+
7+
Small code refactors for improved code readability. No user facing changes.

crates/tauri-build/src/lib.rs

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -165,21 +165,21 @@ fn copy_frameworks(dest_dir: &Path, frameworks: &[String]) -> Result<()> {
165165
.with_context(|| format!("Failed to create frameworks output directory at {dest_dir:?}"))?;
166166
for framework in frameworks.iter() {
167167
if framework.ends_with(".framework") {
168-
let src_path = PathBuf::from(framework);
168+
let src_path = Path::new(framework);
169169
let src_name = src_path
170170
.file_name()
171171
.expect("Couldn't get framework filename");
172172
let dest_path = dest_dir.join(src_name);
173-
copy_dir(&src_path, &dest_path)?;
173+
copy_dir(src_path, &dest_path)?;
174174
continue;
175175
} else if framework.ends_with(".dylib") {
176-
let src_path = PathBuf::from(framework);
176+
let src_path = Path::new(framework);
177177
if !src_path.exists() {
178178
return Err(anyhow::anyhow!("Library not found: {}", framework));
179179
}
180180
let src_name = src_path.file_name().expect("Couldn't get library filename");
181181
let dest_path = dest_dir.join(src_name);
182-
copy_file(&src_path, &dest_path)?;
182+
copy_file(src_path, &dest_path)?;
183183
continue;
184184
} else if framework.contains('/') {
185185
return Err(anyhow::anyhow!(
@@ -192,12 +192,8 @@ fn copy_frameworks(dest_dir: &Path, frameworks: &[String]) -> Result<()> {
192192
continue;
193193
}
194194
}
195-
if copy_framework_from(&PathBuf::from("/Library/Frameworks/"), framework, dest_dir)?
196-
|| copy_framework_from(
197-
&PathBuf::from("/Network/Library/Frameworks/"),
198-
framework,
199-
dest_dir,
200-
)?
195+
if copy_framework_from("/Library/Frameworks/".as_ref(), framework, dest_dir)?
196+
|| copy_framework_from("/Network/Library/Frameworks/".as_ref(), framework, dest_dir)?
201197
{
202198
continue;
203199
}

crates/tauri-bundler/src/bundle/windows/sign.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -266,8 +266,7 @@ pub fn try_sign<P: AsRef<Path>>(file_path: P, settings: &Settings) -> crate::Res
266266
pub fn should_sign(file_path: &Path) -> crate::Result<bool> {
267267
let is_binary = file_path
268268
.extension()
269-
.and_then(|extension| extension.to_str())
270-
.is_some_and(|extension| matches!(extension, "exe" | "dll"));
269+
.is_some_and(|ext| ext == "exe" || ext == "dll");
271270
if !is_binary {
272271
return Ok(false);
273272
}

crates/tauri-cli/src/build.rs

Lines changed: 17 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use crate::{
88
helpers::{
99
self,
1010
app_paths::{frontend_dir, tauri_dir},
11-
config::{get as get_config, ConfigHandle, FrontendDist},
11+
config::{get as get_config, ConfigMetadata, FrontendDist},
1212
},
1313
info::plugins::check_mismatched_packages,
1414
interface::{rust::get_cargo_target_dir, AppInterface, Interface},
@@ -106,11 +106,11 @@ pub fn command(mut options: Options, verbosity: u8) -> Result<()> {
106106
options.target.clone(),
107107
)?;
108108

109-
setup(&interface, &mut options, config.clone(), false)?;
110-
111109
let config_guard = config.lock().unwrap();
112110
let config_ = config_guard.as_ref().unwrap();
113111

112+
setup(&interface, &mut options, config_, false)?;
113+
114114
if let Some(minimum_system_version) = &config_.bundle.macos.minimum_system_version {
115115
std::env::set_var("MACOSX_DEPLOYMENT_TARGET", minimum_system_version);
116116
}
@@ -132,7 +132,7 @@ pub fn command(mut options: Options, verbosity: u8) -> Result<()> {
132132
verbosity,
133133
ci,
134134
&interface,
135-
&app_settings,
135+
&*app_settings,
136136
config_,
137137
&out_dir,
138138
)?;
@@ -144,7 +144,7 @@ pub fn command(mut options: Options, verbosity: u8) -> Result<()> {
144144
pub fn setup(
145145
interface: &AppInterface,
146146
options: &mut Options,
147-
config: ConfigHandle,
147+
config: &ConfigMetadata,
148148
mobile: bool,
149149
) -> Result<()> {
150150
let tauri_path = tauri_dir();
@@ -162,44 +162,39 @@ pub fn setup(
162162

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

165-
let config_guard = config.lock().unwrap();
166-
let config_ = config_guard.as_ref().unwrap();
167-
168-
let bundle_identifier_source = config_
165+
let bundle_identifier_source = config
169166
.find_bundle_identifier_overwriter()
170167
.unwrap_or_else(|| "tauri.conf.json".into());
171168

172-
if config_.identifier == "com.tauri.dev" {
169+
if config.identifier == "com.tauri.dev" {
173170
crate::error::bail!(
174171
"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.",
175172
);
176173
}
177174

178-
if config_
175+
if config
179176
.identifier
180177
.chars()
181178
.any(|ch| !(ch.is_alphanumeric() || ch == '-' || ch == '.'))
182179
{
183180
crate::error::bail!(
184-
"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 (.).",
185-
config_.identifier,
186-
bundle_identifier_source
181+
"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 (.).",
182+
config.identifier,
187183
);
188184
}
189185

190-
if config_.identifier.ends_with(".app") {
186+
if config.identifier.ends_with(".app") {
191187
log::warn!(
192-
"The bundle identifier \"{}\" set in `{} identifier` ends with `.app`. This is not recommended because it conflicts with the application bundle extension on macOS.",
193-
config_.identifier,
194-
bundle_identifier_source
188+
"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.",
189+
config.identifier,
195190
);
196191
}
197192

198-
if let Some(before_build) = config_.build.before_build_command.clone() {
193+
if let Some(before_build) = config.build.before_build_command.clone() {
199194
helpers::run_hook("beforeBuildCommand", before_build, interface, options.debug)?;
200195
}
201196

202-
if let Some(FrontendDist::Directory(web_asset_path)) = &config_.build.frontend_dist {
197+
if let Some(FrontendDist::Directory(web_asset_path)) = &config.build.frontend_dist {
203198
if !web_asset_path.exists() {
204199
let absolute_path = web_asset_path
205200
.parent()
@@ -252,13 +247,13 @@ pub fn setup(
252247
}
253248

254249
if options.runner.is_none() {
255-
options.runner = config_.build.runner.clone();
250+
options.runner = config.build.runner.clone();
256251
}
257252

258253
options
259254
.features
260255
.get_or_insert(Vec::new())
261-
.extend(config_.build.features.clone().unwrap_or_default());
256+
.extend(config.build.features.clone().unwrap_or_default());
262257
interface.build_options(&mut options.args, &mut options.features, mobile);
263258

264259
Ok(())

crates/tauri-cli/src/bundle.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ pub fn command(options: Options, verbosity: u8) -> crate::Result<()> {
158158
verbosity,
159159
ci,
160160
&interface,
161-
&app_settings,
161+
&*app_settings,
162162
config_,
163163
&out_dir,
164164
)
@@ -170,7 +170,7 @@ pub fn bundle<A: AppSettings>(
170170
verbosity: u8,
171171
ci: bool,
172172
interface: &AppInterface,
173-
app_settings: &std::sync::Arc<A>,
173+
app_settings: &A,
174174
config: &ConfigMetadata,
175175
out_dir: &Path,
176176
) -> crate::Result<()> {

crates/tauri-cli/src/dev.rs

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ use std::{
3434
mod builtin_dev_server;
3535

3636
static BEFORE_DEV: OnceLock<Mutex<Arc<SharedChild>>> = OnceLock::new();
37-
static KILL_BEFORE_DEV_FLAG: OnceLock<AtomicBool> = OnceLock::new();
37+
static KILL_BEFORE_DEV_FLAG: AtomicBool = AtomicBool::new(false);
3838

3939
#[cfg(unix)]
4040
const KILL_CHILDREN_SCRIPT: &[u8] = include_bytes!("../scripts/kill-children.sh");
@@ -218,14 +218,13 @@ pub fn setup(interface: &AppInterface, options: &mut Options, config: ConfigHand
218218
let status = child_
219219
.wait()
220220
.expect("failed to wait on \"beforeDevCommand\"");
221-
if !(status.success() || KILL_BEFORE_DEV_FLAG.get().unwrap().load(Ordering::Relaxed)) {
221+
if !(status.success() || KILL_BEFORE_DEV_FLAG.load(Ordering::Relaxed)) {
222222
log::error!("The \"beforeDevCommand\" terminated with a non-zero status code.");
223223
exit(status.code().unwrap_or(1));
224224
}
225225
});
226226

227227
BEFORE_DEV.set(Mutex::new(child)).unwrap();
228-
KILL_BEFORE_DEV_FLAG.set(AtomicBool::default()).unwrap();
229228

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

305304
if !options.no_dev_server_wait {
306305
if let Some(url) = dev_url {
307-
let host = url
308-
.host()
309-
.unwrap_or_else(|| panic!("No host name in the URL"));
306+
let host = url.host().expect("No host name in the URL");
310307
let port = url
311308
.port_or_known_default()
312-
.unwrap_or_else(|| panic!("No port number in the URL"));
309+
.expect("No port number in the URL");
313310
let addrs;
314311
let addr;
315312
let addrs = match host {
@@ -380,11 +377,10 @@ pub fn on_app_exit(code: Option<i32>, reason: ExitReason, exit_on_panic: bool, n
380377
pub fn kill_before_dev_process() {
381378
if let Some(child) = BEFORE_DEV.get() {
382379
let child = child.lock().unwrap();
383-
let kill_before_dev_flag = KILL_BEFORE_DEV_FLAG.get().unwrap();
384-
if kill_before_dev_flag.load(Ordering::Relaxed) {
380+
if KILL_BEFORE_DEV_FLAG.load(Ordering::Relaxed) {
385381
return;
386382
}
387-
kill_before_dev_flag.store(true, Ordering::Relaxed);
383+
KILL_BEFORE_DEV_FLAG.store(true, Ordering::Relaxed);
388384
#[cfg(windows)]
389385
{
390386
let powershell_path = std::env::var("SYSTEMROOT").map_or_else(

crates/tauri-cli/src/helpers/app_paths.rs

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -75,21 +75,13 @@ fn lookup<F: Fn(&PathBuf) -> bool>(dir: &Path, checker: F) -> Option<PathBuf> {
7575
}
7676

7777
fn env_tauri_app_path() -> Option<PathBuf> {
78-
std::env::var(ENV_TAURI_APP_PATH)
79-
.map(PathBuf::from)
80-
.ok()?
81-
.canonicalize()
82-
.ok()
83-
.map(|p| dunce::simplified(&p).to_path_buf())
78+
let p = PathBuf::from(std::env::var_os(ENV_TAURI_APP_PATH)?);
79+
dunce::canonicalize(p).ok()
8480
}
8581

8682
fn env_tauri_frontend_path() -> Option<PathBuf> {
87-
std::env::var(ENV_TAURI_FRONTEND_PATH)
88-
.map(PathBuf::from)
89-
.ok()?
90-
.canonicalize()
91-
.ok()
92-
.map(|p| dunce::simplified(&p).to_path_buf())
83+
let p = PathBuf::from(std::env::var_os(ENV_TAURI_FRONTEND_PATH)?);
84+
dunce::canonicalize(p).ok()
9385
}
9486

9587
pub fn resolve_tauri_dir() -> Option<PathBuf> {

crates/tauri-cli/src/helpers/config.rs

Lines changed: 16 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,9 @@ pub use tauri_utils::{config::*, platform::Target};
1212
use std::{
1313
collections::HashMap,
1414
env::{current_dir, set_current_dir, set_var},
15-
ffi::OsStr,
15+
ffi::{OsStr, OsString},
1616
process::exit,
17-
sync::{Arc, Mutex, OnceLock},
17+
sync::Mutex,
1818
};
1919

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

3636
impl std::ops::Deref for ConfigMetadata {
@@ -50,7 +50,7 @@ impl ConfigMetadata {
5050
}
5151

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

69-
pub type ConfigHandle = Arc<Mutex<Option<ConfigMetadata>>>;
69+
pub type ConfigHandle = &'static Mutex<Option<ConfigMetadata>>;
7070

7171
pub fn wix_settings(config: WixConfig) -> tauri_bundler::WixSettings {
7272
tauri_bundler::WixSettings {
@@ -141,9 +141,9 @@ pub fn custom_sign_settings(
141141
}
142142
}
143143

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

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

159159
let tauri_dir = super::app_paths::tauri_dir();
160160
let (mut config, config_path) =
161161
tauri_utils::config::parse::parse_value(target, tauri_dir.join("tauri.conf.json"))
162162
.context("failed to parse config")?;
163-
let config_file_name = config_path.file_name().unwrap().to_string_lossy();
163+
let config_file_name = config_path.file_name().unwrap();
164164
let mut extensions = HashMap::new();
165165

166166
let original_identifier = config
@@ -174,10 +174,7 @@ fn get_internal(
174174
.context("failed to parse platform config")?
175175
{
176176
merge(&mut config, &platform_config);
177-
extensions.insert(
178-
config_path.file_name().unwrap().to_str().unwrap().into(),
179-
platform_config,
180-
);
177+
extensions.insert(config_path.file_name().unwrap().into(), platform_config);
181178
}
182179

183180
if !merge_configs.is_empty() {
@@ -203,9 +200,9 @@ fn get_internal(
203200
for error in errors {
204201
let path = error.instance_path.into_iter().join(" > ");
205202
if path.is_empty() {
206-
log::error!("`{}` error: {}", config_file_name, error);
203+
log::error!("`{config_file_name:?}` error: {}", error);
207204
} else {
208-
log::error!("`{}` error on `{}`: {}", config_file_name, path, error);
205+
log::error!("`{config_file_name:?}` error on `{}`: {}", path, error);
209206
}
210207
}
211208
if !reload {
@@ -243,7 +240,7 @@ fn get_internal(
243240
extensions,
244241
});
245242

246-
Ok(config_handle().clone())
243+
Ok(config_handle())
247244
}
248245

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

270267
if merge_configs.is_empty() {
271-
return Ok(handle.clone());
268+
return Ok(handle);
272269
}
273270

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

288-
Ok(handle.clone())
285+
Ok(handle)
289286
} else {
290287
crate::error::bail!("config not loaded");
291288
}

0 commit comments

Comments
 (0)