Skip to content

Commit 7bb7dda

Browse files
authored
refactor(core): resolve resource_dir using the package info (#1762)
1 parent b6b4128 commit 7bb7dda

File tree

16 files changed

+198
-96
lines changed

16 files changed

+198
-96
lines changed

.changes/app-dir-refactor.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,5 @@
22
"tauri": patch
33
---
44

5-
**Breaking:** `api::path::resolve_path()` and `api::path::app_dir()` now takes the config as first argument.
5+
**Breaking:** `api::path::resolve_path()` and `api::path::app_dir()` now takes the config as first argument and the `PackageInfo` as second argument.
66
**Breaking:** `api::path::app_dir()` now resolves to `${configDir}/${config.tauri.bundle.identifier}`.

.changes/resources-dir-refactor.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"tauri-utils": patch
3+
---
4+
5+
The `platform::resource_dir` API now takes the `PackageInfo`.

core/tauri-codegen/src/context.rs

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,23 @@ pub fn context_codegen(data: ContextData) -> Result<TokenStream, EmbeddedAssetsE
6262
quote!(None)
6363
};
6464

65+
let package_name = if let Some(product_name) = &config.package.product_name {
66+
quote!(#product_name.to_string())
67+
} else {
68+
quote!(env!("CARGO_PKG_NAME").to_string())
69+
};
70+
let package_version = if let Some(version) = &config.package.version {
71+
quote!(#version.to_string())
72+
} else {
73+
quote!(env!("CARGO_PKG_VERSION").to_string())
74+
};
75+
let package_info = quote!(
76+
#root::api::PackageInfo {
77+
name: #package_name,
78+
version: #package_version,
79+
}
80+
);
81+
6582
#[cfg(target_os = "linux")]
6683
let system_tray_icon = if let Some(tray) = &config.tauri.system_tray {
6784
let mut system_tray_icon_path = tray.icon_path.clone();
@@ -73,7 +90,7 @@ pub fn context_codegen(data: ContextData) -> Result<TokenStream, EmbeddedAssetsE
7390
.to_string_lossy()
7491
.to_string();
7592
quote!(Some(
76-
::tauri::platform::resource_dir()
93+
::tauri::platform::resource_dir(&#package_info)
7794
.expect("failed to read resource dir")
7895
.join(
7996
#system_tray_icon_file_name
@@ -103,26 +120,12 @@ pub fn context_codegen(data: ContextData) -> Result<TokenStream, EmbeddedAssetsE
103120
quote!(None)
104121
};
105122

106-
let package_name = if let Some(product_name) = &config.package.product_name {
107-
quote!(#product_name.to_string())
108-
} else {
109-
quote!(env!("CARGO_PKG_NAME").to_string())
110-
};
111-
let package_version = if let Some(version) = &config.package.version {
112-
quote!(#version.to_string())
113-
} else {
114-
quote!(env!("CARGO_PKG_VERSION").to_string())
115-
};
116-
117123
// double braces are purposeful to force the code into a block expression
118124
Ok(quote!(#root::Context {
119125
config: #config,
120126
assets: ::std::sync::Arc::new(#assets),
121127
default_window_icon: #default_window_icon,
122128
system_tray_icon: #system_tray_icon,
123-
package_info: #root::api::PackageInfo {
124-
name: #package_name,
125-
version: #package_version,
126-
},
129+
package_info: #package_info,
127130
}))
128131
}

core/tauri-utils/Cargo.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,5 +20,8 @@ html5ever = "0.25"
2020
proc-macro2 = { version = "1.0", optional = true }
2121
quote = { version = "1.0", optional = true }
2222

23+
[target."cfg(target_os = \"linux\")".dependencies]
24+
heck = "0.3"
25+
2326
[features]
2427
build = [ "proc-macro2", "quote" ]

core/tauri-utils/src/lib.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,29 @@ pub mod html;
1414
/// Platform helpers
1515
pub mod platform;
1616

17+
/// `App` package information.
18+
#[derive(Debug, Clone)]
19+
pub struct PackageInfo {
20+
/// App name.
21+
pub name: String,
22+
/// App version.
23+
pub version: String,
24+
}
25+
26+
impl PackageInfo {
27+
/// Returns the application package name.
28+
/// On macOS and Windows it's the `name` field, and on Linux it's the `name` in `kebab-case`.
29+
pub fn package_name(&self) -> String {
30+
#[cfg(target_os = "linux")]
31+
{
32+
use heck::KebabCase;
33+
self.name.to_kebab_case()
34+
}
35+
#[cfg(not(target_os = "linux"))]
36+
return self.name.clone();
37+
}
38+
}
39+
1740
/// Result type alias using the crate's error type.
1841
pub type Result<T> = std::result::Result<T, Error>;
1942

core/tauri-utils/src/platform.rs

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ use std::{
77
path::{PathBuf, MAIN_SEPARATOR},
88
};
99

10+
use crate::PackageInfo;
11+
1012
/// Try to determine the current target triple.
1113
///
1214
/// Returns a target triple (e.g. `x86_64-unknown-linux-gnu` or `i686-pc-windows-msvc`) or an
@@ -70,13 +72,9 @@ pub fn target_triple() -> crate::Result<String> {
7072
/// `${exe_dir}/../lib/${exe_name}`.
7173
///
7274
/// On MacOS, it's `${exe_dir}../Resources` (inside .app).
73-
pub fn resource_dir() -> crate::Result<PathBuf> {
75+
pub fn resource_dir(package_info: &PackageInfo) -> crate::Result<PathBuf> {
7476
let exe = std::env::current_exe()?;
7577
let exe_dir = exe.parent().expect("failed to get exe directory");
76-
let app_name = exe
77-
.file_name()
78-
.expect("failed to get exe filename")
79-
.to_string_lossy();
8078
let curr_dir = exe_dir.display().to_string();
8179

8280
if curr_dir.ends_with(format!("{S}target{S}debug", S = MAIN_SEPARATOR).as_str())
@@ -90,12 +88,19 @@ pub fn resource_dir() -> crate::Result<PathBuf> {
9088
if cfg!(target_os = "linux") {
9189
if curr_dir.ends_with("/data/usr/bin") {
9290
// running from the deb bundle dir
93-
Ok(exe_dir.join(format!("../lib/{}", app_name)))
91+
Ok(exe_dir.join(format!("../lib/{}", package_info.package_name())))
9492
} else if let Ok(appdir) = env::var("APPDIR") {
95-
Ok(PathBuf::from(format!("{}/usr/lib/{}", appdir, app_name)))
93+
Ok(PathBuf::from(format!(
94+
"{}/usr/lib/{}",
95+
appdir,
96+
package_info.package_name()
97+
)))
9698
} else {
9799
// running bundle
98-
Ok(PathBuf::from(format!("/usr/lib/{}", app_name)))
100+
Ok(PathBuf::from(format!(
101+
"/usr/lib/{}",
102+
package_info.package_name()
103+
)))
99104
}
100105
} else if cfg!(target_os = "macos") {
101106
Ok(exe_dir.join("../Resources"))

core/tauri/src/api/mod.rs

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -52,15 +52,6 @@ pub use error::Error;
5252
/// Tauri API result type.
5353
pub type Result<T> = std::result::Result<T, Error>;
5454

55-
/// `App` package information.
56-
#[derive(Debug, Clone)]
57-
pub struct PackageInfo {
58-
/// App name.
59-
pub name: String,
60-
/// App version.
61-
pub version: String,
62-
}
63-
6455
// Not public API
6556
#[doc(hidden)]
6657
pub mod private {

core/tauri/src/api/path.rs

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use std::{
77
path::{Path, PathBuf},
88
};
99

10-
use crate::Config;
10+
use crate::{Config, PackageInfo};
1111

1212
use serde_repr::{Deserialize_repr, Serialize_repr};
1313

@@ -65,14 +65,22 @@ pub enum BaseDirectory {
6565
///
6666
/// # Example
6767
/// ```
68-
/// use tauri::api::path::{resolve_path, BaseDirectory};
69-
/// // we use the default config, but in an actual app you should get the Config created from tauri.conf.json
70-
/// let path = resolve_path(&Default::default(), "path/to/something", Some(BaseDirectory::Config))
71-
/// .expect("failed to resolve path");
68+
/// use tauri::api::{path::{resolve_path, BaseDirectory}, PackageInfo};
69+
/// // we use the default config and a mock PackageInfo, but in an actual app you should get the Config created from tauri.conf.json and the app's PackageInfo instance
70+
/// let path = resolve_path(
71+
/// &Default::default(),
72+
/// &PackageInfo {
73+
/// name: "app".into(),
74+
/// version: "1.0.0".into(),
75+
/// },
76+
/// "path/to/something",
77+
/// Some(BaseDirectory::Config)
78+
/// ).expect("failed to resolve path");
7279
/// // path is equal to "/home/${whoami}/.config/path/to/something" on Linux
7380
/// ```
7481
pub fn resolve_path<P: AsRef<Path>>(
7582
config: &Config,
83+
package_info: &PackageInfo,
7684
path: P,
7785
dir: Option<BaseDirectory>,
7886
) -> crate::api::Result<PathBuf> {
@@ -94,7 +102,7 @@ pub fn resolve_path<P: AsRef<Path>>(
94102
BaseDirectory::Runtime => runtime_dir(),
95103
BaseDirectory::Template => template_dir(),
96104
BaseDirectory::Video => video_dir(),
97-
BaseDirectory::Resource => resource_dir(),
105+
BaseDirectory::Resource => resource_dir(package_info),
98106
BaseDirectory::App => app_dir(config),
99107
BaseDirectory::Current => Some(env::current_dir()?),
100108
};
@@ -194,8 +202,8 @@ pub fn video_dir() -> Option<PathBuf> {
194202
}
195203

196204
/// Returns the path to the resource directory of this app.
197-
pub fn resource_dir() -> Option<PathBuf> {
198-
crate::api::platform::resource_dir().ok()
205+
pub fn resource_dir(package_info: &PackageInfo) -> Option<PathBuf> {
206+
crate::api::platform::resource_dir(package_info).ok()
199207
}
200208

201209
/// Returns the path to the suggested directory for your app config files.

core/tauri/src/endpoints.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ impl Module {
7575
.respond_async(async move { cmd.run().and_then(|r| r.json).map_err(InvokeError::from) }),
7676
Self::Fs(cmd) => resolver.respond_async(async move {
7777
cmd
78-
.run(config)
78+
.run(config, &package_info)
7979
.and_then(|r| r.json)
8080
.map_err(InvokeError::from)
8181
}),
@@ -122,7 +122,7 @@ impl Module {
122122
}
123123
Self::Notification(cmd) => resolver.respond_closure(move || {
124124
cmd
125-
.run(config)
125+
.run(config, &package_info)
126126
.and_then(|r| r.json)
127127
.map_err(InvokeError::from)
128128
}),

0 commit comments

Comments
 (0)