Skip to content
Open
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
5 changes: 5 additions & 0 deletions .changes/external-bin-dir.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
tauri-utils: minor:feat
---

Added `platform::external_bin_dir` to resolve the directory where the sidecars configured in `bundle > externalBin` are located.
6 changes: 6 additions & 0 deletions .changes/sidecar-path.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
tauri: minor:feat
"@tauri-apps/api": minor:feat
---

Added `PathResolver::sidecar_path` and the `resolveExternalBin` path API to resolve the path to a sidecar binary configured in `bundle > externalBin`.
81 changes: 67 additions & 14 deletions crates/tauri-utils/src/platform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,46 @@ fn is_cargo_output_directory(path: &std::path::Path) -> bool {
.any(|dirname| &last_component.as_os_str() == dirname)
}

/// Checks if the given directory is a Cargo output directory, which means it's an executable in a development machine.
///
/// We check if the directory is inside a `target` folder which can be either `target/$profile` or `target/$triple/$profile`
/// and see if there's a .cargo-lock file along the executable.
/// This ensures the check is safer so it doesn't affect apps in production.
#[cfg(not(target_os = "android"))]
fn is_cargo_target_directory(dir: &std::path::Path) -> bool {
let mut parents = dir.components().rev().skip(1).take(2);
parents.any(|c| c.as_os_str() == "target") && is_cargo_output_directory(dir)
}

/// Computes the directory where the sidecars configured in `bundle > externalBin` are located.
///
/// The bundler places sidecars next to the main executable, so this is usually the directory of the current executable.
/// When running tests from the Cargo output directory (`target/$profile/deps`), the sidecars are located in `target/$profile` instead.
///
/// # Security
///
/// See [`current_exe`] for possible security implications.
pub fn external_bin_dir() -> std::io::Result<PathBuf> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Why does this return io::Result instead of crate:Result?

let exe = current_exe()?;
let exe_dir = exe.parent().ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::NotFound,
"current executable has no parent directory",
)
})?;
Ok(external_bin_dir_from(exe_dir).to_path_buf())
}

fn external_bin_dir_from(exe_dir: &std::path::Path) -> &std::path::Path {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

we should comment about this was split up for the unit tests

#[cfg(not(target_os = "android"))]
if exe_dir.ends_with("deps") {
if let Some(parent) = exe_dir.parent().filter(|p| is_cargo_target_directory(p)) {
return parent;
}
}
exe_dir
}

/// Computes the resource directory of the current environment.
///
/// ## Platform-specific
Expand Down Expand Up @@ -292,20 +332,9 @@ fn resource_dir_from<P: AsRef<std::path::Path>>(
env: &Env,
) -> crate::Result<PathBuf> {
let exe_dir = exe.as_ref().parent().expect("failed to get exe directory");
let curr_dir = exe_dir.display().to_string();

let parts: Vec<&str> = curr_dir.split(std::path::MAIN_SEPARATOR).collect();
let len = parts.len();

// Check if running from the Cargo output directory, which means it's an executable in a development machine
// We check if the binary is inside a `target` folder which can be either `target/$profile` or `target/$triple/$profile`
// and see if there's a .cargo-lock file along the executable
// This ensures the check is safer so it doesn't affect apps in production
// Windows also includes the resources in the executable folder so we check that too
if cfg!(target_os = "windows")
|| ((len >= 2 && parts[len - 2] == "target") || (len >= 3 && parts[len - 3] == "target"))
&& is_cargo_output_directory(exe_dir)
{

// Windows also includes the resources in the executable folder

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggested change
// Windows also includes the resources in the executable folder
// Windows always includes the resources in the executable folder

if cfg!(target_os = "windows") || is_cargo_target_directory(exe_dir) {
return Ok(exe_dir.to_path_buf());
}

Expand Down Expand Up @@ -439,4 +468,28 @@ mod tests {
#[cfg(windows)]
assert_eq!(resource_dir.unwrap(), path.parent().unwrap());
}

#[test]
#[cfg(not(target_os = "android"))]
fn resolve_external_bin_dir() {
use std::path::Path;

let dir = Path::new("/path/to/target/debug/deps");
assert_eq!(
super::external_bin_dir_from(dir),
Path::new("/path/to/target/debug")
);

let dir = Path::new("/path/to/target/aarch64-apple-darwin/release/deps");
assert_eq!(
super::external_bin_dir_from(dir),
Path::new("/path/to/target/aarch64-apple-darwin/release")
);

let dir = Path::new("/path/to/target/debug");
assert_eq!(super::external_bin_dir_from(dir), dir);

let dir = Path::new("/usr/lib/my-app/deps");
assert_eq!(super::external_bin_dir_from(dir), dir);
}
}
1 change: 1 addition & 0 deletions crates/tauri/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const PLUGINS: &[(&str, &[(&str, bool)])] = &[
"core:path",
&[
("resolve_directory", true),
("resolve_external_bin", true),
("resolve", true),
("normalize", true),
("join", true),
Expand Down
27 changes: 27 additions & 0 deletions crates/tauri/permissions/path/autogenerated/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ Default permissions for the plugin, which enables all commands.
#### This default permission set includes the following:

- `allow-resolve-directory`
- `allow-resolve-external-bin`
- `allow-resolve`
- `allow-normalize`
- `allow-join`
Expand Down Expand Up @@ -227,6 +228,32 @@ Enables the resolve_directory command without any pre-configured scope.

Denies the resolve_directory command without any pre-configured scope.

</td>
</tr>

<tr>
<td>

`core:path:allow-resolve-external-bin`

</td>
<td>

Enables the resolve_external_bin command without any pre-configured scope.

</td>
</tr>

<tr>
<td>

`core:path:deny-resolve-external-bin`

</td>
<td>

Denies the resolve_external_bin command without any pre-configured scope.

</td>
</tr>
</table>
2 changes: 1 addition & 1 deletion crates/tauri/scripts/bundle.global.js

Large diffs are not rendered by default.

41 changes: 41 additions & 0 deletions crates/tauri/src/path/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,47 @@ impl<R: Runtime> PathResolver<R> {

Ok(p)
}

/// Resolves the path to a sidecar binary bundled with the app via
/// [`bundle > externalBin`](crate::utils::config::BundleConfig::external_bin).
///
/// The `name` is the file name of the sidecar without the target triple suffix,
/// e.g. `my-sidecar` for a sidecar configured as `binaries/my-sidecar`.
///
/// The bundler places sidecars next to the main executable, so this resolves to `${exe_dir}/${name}`,
/// with the `.exe` extension appended on Windows.
///
/// # Security
///
/// See [`tauri_utils::platform::current_exe`] for possible security implications.
///
/// # Examples
///
/// ```rust,no_run
/// use tauri::Manager;
/// tauri::Builder::default()
/// .setup(|app| {
/// let path = app.path().sidecar_path("my-sidecar")?;
/// std::process::Command::new(path).spawn()?;
/// Ok(())
/// });
/// ```
pub fn sidecar_path<P: AsRef<Path>>(&self, name: P) -> Result<PathBuf> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This is still sidecar which is not consistent with the others, we should use only one name everywhere

let mut path = tauri_utils::platform::external_bin_dir()?.join(name);

#[cfg(windows)]
if path.extension().is_none_or(|ext| ext != "exe") {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

does set_extension work here?

// do not use with_extension to retain dots in the file name
path.as_mut_os_string().push(".exe");
}

#[cfg(not(windows))]
if path.extension().is_some_and(|ext| ext == "exe") {
path.set_extension("");
}

Ok(path)
}
}

fn resolve_path<R: Runtime>(
Expand Down
12 changes: 12 additions & 0 deletions crates/tauri/src/path/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,17 @@ pub fn resolve_directory<R: Runtime>(
super::resolve_path(&resolver, directory, path).map(|p| dunce::simplified(&p).to_path_buf())
}

#[command(root = "crate")]
pub fn resolve_external_bin<R: Runtime>(
_app: AppHandle<R>,
resolver: State<'_, PathResolver<R>>,
name: PathBuf,
) -> Result<PathBuf> {
resolver
.sidecar_path(name)
.map(|p| dunce::simplified(&p).to_path_buf())
}

#[command(root = "crate")]
pub fn resolve(paths: Vec<String>) -> Result<PathBuf> {
// Start with current directory then start adding paths from the vector one by one using `PathBuf.push()` which
Expand Down Expand Up @@ -219,6 +230,7 @@ pub(crate) fn init<R: Runtime>() -> TauriPlugin<R> {
.invoke_handler(crate::generate_handler![
#![plugin(path)]
resolve_directory,
resolve_external_bin,
resolve,
normalize,
join,
Expand Down
23 changes: 23 additions & 0 deletions packages/api/src/path.ts
Original file line number Diff line number Diff line change
Expand Up @@ -573,6 +573,28 @@ async function resolveResource(resourcePath: string): Promise<string> {
})
}

/**
* Resolves the path to a sidecar binary configured in `tauri.conf.json > bundle > externalBin`.
*
* Sidecars are placed next to the main executable, so this resolves to `${exe_dir}/${name}`,
* with the `.exe` extension appended on Windows.
*
* @example
* ```typescript
* import { resolveExternalBin } from '@tauri-apps/api/path';
* const binPath = await resolveExternalBin('my-sidecar');
* ```
*
* @param name The file name of the sidecar without the target triple suffix,
* e.g. `my-sidecar` for a sidecar configured as `binaries/my-sidecar`.
* @returns The full path to the sidecar.
*
* @since 2.13.0
*/
async function resolveExternalBin(name: string): Promise<string> {
return invoke('plugin:path|resolve_external_bin', { name })
}

/**
* Returns the path to the user's runtime directory.
*
Expand Down Expand Up @@ -843,6 +865,7 @@ export {
publicDir,
resourceDir,
resolveResource,
resolveExternalBin,
runtimeDir,
templateDir,
videoDir,
Expand Down
Loading