repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-bundler/src/bundle/windows/nsis/mod.rs | crates/tauri-bundler/src/bundle/windows/nsis/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{
bundle::{
settings::Arch,
windows::{
sign::{should_sign, sign_command, try_sign},
util::{
download_webview2_bootstrapper, download_webview2_offline_installer,
NSIS_OUTPUT_FOLDER_NAME, NSIS_UPDATER_OUTPUT_FOLDER_NAME,
},
},
},
error::ErrorExt,
utils::{
http_utils::{download_and_verify, verify_file_hash, HashAlgorithm},
CommandExt,
},
Error, Settings,
};
use tauri_utils::display_path;
use crate::error::Context;
use handlebars::{to_json, Handlebars};
use tauri_utils::config::{NSISInstallerMode, NsisCompression, WebviewInstallMode};
use std::{
collections::BTreeMap,
fs,
path::{Path, PathBuf},
process::Command,
};
// URLS for the NSIS toolchain.
#[cfg(target_os = "windows")]
const NSIS_URL: &str =
"https://github.com/tauri-apps/binary-releases/releases/download/nsis-3.11/nsis-3.11.zip";
#[cfg(target_os = "windows")]
const NSIS_SHA1: &str = "EF7FF767E5CBD9EDD22ADD3A32C9B8F4500BB10D";
const NSIS_TAURI_UTILS_URL: &str =
"https://github.com/tauri-apps/nsis-tauri-utils/releases/download/nsis_tauri_utils-v0.5.2/nsis_tauri_utils.dll";
const NSIS_TAURI_UTILS_SHA1: &str = "D0C502F45DF55C0465C9406088FF016C2E7E6817";
#[cfg(target_os = "windows")]
const NSIS_REQUIRED_FILES: &[&str] = &[
"makensis.exe",
"Bin/makensis.exe",
"Stubs/lzma-x86-unicode",
"Stubs/lzma_solid-x86-unicode",
"Plugins/x86-unicode/additional/nsis_tauri_utils.dll",
"Include/MUI2.nsh",
"Include/FileFunc.nsh",
"Include/x64.nsh",
"Include/nsDialogs.nsh",
"Include/WinMessages.nsh",
"Include/Win/COM.nsh",
"Include/Win/Propkey.nsh",
"Include/Win/RestartManager.nsh",
];
const NSIS_PLUGIN_FILES: &[&str] = &[
"NSISdl.dll",
"StartMenu.dll",
"System.dll",
"nsDialogs.dll",
"additional/nsis_tauri_utils.dll",
];
#[cfg(not(target_os = "windows"))]
const NSIS_REQUIRED_FILES: &[&str] = &["Plugins/x86-unicode/additional/nsis_tauri_utils.dll"];
const NSIS_REQUIRED_FILES_HASH: &[(&str, &str, &str, HashAlgorithm)] = &[(
"Plugins/x86-unicode/additional/nsis_tauri_utils.dll",
NSIS_TAURI_UTILS_URL,
NSIS_TAURI_UTILS_SHA1,
HashAlgorithm::Sha1,
)];
/// Runs all of the commands to build the NSIS installer.
/// Returns a vector of PathBuf that shows where the NSIS installer was created.
pub fn bundle_project(settings: &Settings, updater: bool) -> crate::Result<Vec<PathBuf>> {
let tauri_tools_path = settings
.local_tools_directory()
.map(|d| d.join(".tauri"))
.unwrap_or_else(|| dirs::cache_dir().unwrap().join("tauri"));
let nsis_toolset_path = tauri_tools_path.join("NSIS");
if !nsis_toolset_path.exists() {
get_and_extract_nsis(&nsis_toolset_path, &tauri_tools_path)?;
} else if NSIS_REQUIRED_FILES
.iter()
.any(|p| !nsis_toolset_path.join(p).exists())
{
log::warn!("NSIS directory is missing some files. Recreating it.");
std::fs::remove_dir_all(&nsis_toolset_path)?;
get_and_extract_nsis(&nsis_toolset_path, &tauri_tools_path)?;
} else {
let mismatched = NSIS_REQUIRED_FILES_HASH
.iter()
.filter(|(p, _, hash, hash_algorithm)| {
verify_file_hash(nsis_toolset_path.join(p), hash, *hash_algorithm).is_err()
})
.collect::<Vec<_>>();
if !mismatched.is_empty() {
log::warn!("NSIS directory contains mis-hashed files. Redownloading them.");
for (path, url, hash, hash_algorithm) in mismatched {
let data = download_and_verify(url, hash, *hash_algorithm)?;
let out_path = nsis_toolset_path.join(path);
std::fs::create_dir_all(out_path.parent().context("output path has no parent")?)
.fs_context("failed to create file output directory", out_path.clone())?;
fs::write(&out_path, data)
.fs_context("failed to save NSIS downloaded file", out_path.clone())?;
}
}
}
build_nsis_app_installer(settings, &nsis_toolset_path, &tauri_tools_path, updater)
}
// Gets NSIS and verifies the download via Sha1
fn get_and_extract_nsis(nsis_toolset_path: &Path, _tauri_tools_path: &Path) -> crate::Result<()> {
log::info!("Verifying NSIS package");
#[cfg(target_os = "windows")]
{
let data = download_and_verify(NSIS_URL, NSIS_SHA1, HashAlgorithm::Sha1)?;
log::info!("extracting NSIS");
crate::utils::http_utils::extract_zip(&data, _tauri_tools_path)?;
fs::rename(_tauri_tools_path.join("nsis-3.11"), nsis_toolset_path)?;
}
// download additional plugins
let nsis_plugins = nsis_toolset_path.join("Plugins");
let data = download_and_verify(
NSIS_TAURI_UTILS_URL,
NSIS_TAURI_UTILS_SHA1,
HashAlgorithm::Sha1,
)?;
let target_folder = nsis_plugins.join("x86-unicode").join("additional");
fs::create_dir_all(&target_folder)?;
fs::write(target_folder.join("nsis_tauri_utils.dll"), data)?;
Ok(())
}
fn try_add_numeric_build_number(version_str: &str) -> crate::Result<String> {
let version = semver::Version::parse(version_str)
.map_err(|error| Error::GenericError(format!("invalid app version: {error}")))?;
if !version.build.is_empty() {
let build = version.build.parse::<u64>();
if build.is_ok() {
return Ok(format!(
"{}.{}.{}.{}",
version.major, version.minor, version.patch, version.build
));
} else {
log::warn!(
"Unable to parse version build metadata. Numeric value expected, received: `{}`. This will be replaced with `0` in `VIProductVersion` because Windows requires this field to be numeric.",
version.build
);
}
}
Ok(format!(
"{}.{}.{}.0",
version.major, version.minor, version.patch,
))
}
fn build_nsis_app_installer(
settings: &Settings,
#[allow(unused_variables)] nsis_toolset_path: &Path,
tauri_tools_path: &Path,
updater: bool,
) -> crate::Result<Vec<PathBuf>> {
let arch = match settings.binary_arch() {
Arch::X86_64 => "x64",
Arch::X86 => "x86",
Arch::AArch64 => "arm64",
target => {
return Err(crate::Error::ArchError(format!(
"unsupported architecture: {target:?}"
)))
}
};
log::info!("Target: {}", arch);
let output_path = settings.project_out_directory().join("nsis").join(arch);
if output_path.exists() {
fs::remove_dir_all(&output_path)?;
}
fs::create_dir_all(&output_path)?;
// we make a copy of the NSIS directory if we're going to sign its DLLs
// because we don't want to change the DLL hashes so the cache can reuse it
let maybe_plugin_copy_path = if settings.windows().can_sign() {
// find nsis path
#[cfg(target_os = "linux")]
let system_nsis_toolset_path = std::env::var_os("NSIS_PATH")
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("/usr/share/nsis"));
#[cfg(target_os = "macos")]
let system_nsis_toolset_path = std::env::var_os("NSIS_PATH")
.map(PathBuf::from)
.context("failed to resolve NSIS path")
.or_else(|_| {
let mut makensis_path = which::which("makensis").map_err(|error| Error::CommandFailed {
command: "makensis".to_string(),
error: std::io::Error::other(format!("failed to find makensis: {error}")),
})?;
// homebrew installs it as a symlink
if makensis_path.is_symlink() {
// read_link might return a path relative to makensis_path so we must use join() and canonicalize
makensis_path = makensis_path
.parent()
.context("missing makensis parent")?
.join(
std::fs::read_link(&makensis_path)
.fs_context("failed to resolve makensis symlink", makensis_path.clone())?,
)
.canonicalize()
.fs_context(
"failed to canonicalize makensis path",
makensis_path.clone(),
)?;
}
// file structure:
// ├── bin
// │ ├── makensis
// ├── share
// │ ├── nsis
let bin_folder = makensis_path.parent().context("missing makensis parent")?;
let root_folder = bin_folder.parent().context("missing makensis root")?;
crate::Result::Ok(root_folder.join("share").join("nsis"))
})?;
#[cfg(windows)]
let system_nsis_toolset_path = nsis_toolset_path.to_path_buf();
let plugins_path = output_path.join("Plugins");
// copy system plugins (we don't want to modify system installed DLLs, and on some systems there will even be permission errors if we try)
crate::utils::fs_utils::copy_dir(
&system_nsis_toolset_path.join("Plugins").join("x86-unicode"),
&plugins_path.join("x86-unicode"),
)
.context("failed to copy system NSIS Plugins folder to local copy")?;
// copy our downloaded DLLs
crate::utils::fs_utils::copy_dir(
&nsis_toolset_path
.join("Plugins")
.join("x86-unicode")
.join("additional"),
&plugins_path.join("x86-unicode").join("additional"),
)
.context("failed to copy additional NSIS Plugins folder to local copy")?;
Some(plugins_path)
} else {
// in this case plugin_copy_path can be None, we'll use the system default path
None
};
let mut data = BTreeMap::new();
let bundle_id = settings.bundle_identifier();
let manufacturer = settings
.publisher()
.unwrap_or_else(|| bundle_id.split('.').nth(1).unwrap_or(bundle_id));
let additional_plugins_path = maybe_plugin_copy_path
.clone()
.unwrap_or_else(|| nsis_toolset_path.join("Plugins"))
.join("x86-unicode")
.join("additional");
data.insert(
"additional_plugins_path",
// either our Plugins copy (when signing) or the cache/Plugins/x86-unicode path
to_json(&additional_plugins_path),
);
data.insert("arch", to_json(arch));
data.insert("bundle_id", to_json(bundle_id));
data.insert("manufacturer", to_json(manufacturer));
data.insert("product_name", to_json(settings.product_name()));
data.insert("short_description", to_json(settings.short_description()));
data.insert(
"homepage",
to_json(settings.homepage_url().unwrap_or_default()),
);
data.insert(
"long_description",
to_json(settings.long_description().unwrap_or_default()),
);
data.insert("copyright", to_json(settings.copyright_string()));
if settings.windows().can_sign() {
if settings.no_sign() {
log::warn!("Skipping signing for NSIS uninstaller due to --no-sign flag.");
} else {
let sign_cmd = format!("{:?}", sign_command("%1", &settings.sign_params())?);
data.insert("uninstaller_sign_cmd", to_json(sign_cmd));
}
}
let version = settings.version_string();
data.insert("version", to_json(version));
data.insert(
"version_with_build",
to_json(try_add_numeric_build_number(version)?),
);
data.insert(
"allow_downgrades",
to_json(settings.windows().allow_downgrades),
);
if let Some(license_file) = settings.license_file() {
let license_file = dunce::canonicalize(license_file)?;
let license_file_with_bom = output_path.join("license_file");
let content = std::fs::read(license_file)?;
write_utf8_with_bom(&license_file_with_bom, content)?;
data.insert("license", to_json(license_file_with_bom));
}
let nsis = settings.windows().nsis.as_ref();
let custom_template_path = nsis.as_ref().and_then(|n| n.template.clone());
let install_mode = nsis
.as_ref()
.map(|n| n.install_mode)
.unwrap_or(NSISInstallerMode::CurrentUser);
if let Some(nsis) = nsis {
if let Some(installer_icon) = &nsis.installer_icon {
data.insert(
"installer_icon",
to_json(dunce::canonicalize(installer_icon)?),
);
}
if let Some(header_image) = &nsis.header_image {
data.insert("header_image", to_json(dunce::canonicalize(header_image)?));
}
if let Some(sidebar_image) = &nsis.sidebar_image {
data.insert(
"sidebar_image",
to_json(dunce::canonicalize(sidebar_image)?),
);
}
if let Some(installer_hooks) = &nsis.installer_hooks {
let installer_hooks = dunce::canonicalize(installer_hooks)?;
data.insert("installer_hooks", to_json(installer_hooks));
}
if let Some(start_menu_folder) = &nsis.start_menu_folder {
data.insert("start_menu_folder", to_json(start_menu_folder));
}
if let Some(minimum_webview2_version) = &nsis.minimum_webview2_version {
data.insert(
"minimum_webview2_version",
to_json(minimum_webview2_version),
);
}
}
let compression = settings
.windows()
.nsis
.as_ref()
.map(|n| n.compression)
.unwrap_or_default();
data.insert(
"compression",
to_json(match compression {
NsisCompression::Zlib => "zlib",
NsisCompression::Bzip2 => "bzip2",
NsisCompression::Lzma => "lzma",
NsisCompression::None => "none",
}),
);
data.insert(
"install_mode",
to_json(match install_mode {
NSISInstallerMode::CurrentUser => "currentUser",
NSISInstallerMode::PerMachine => "perMachine",
NSISInstallerMode::Both => "both",
}),
);
let languages = nsis
.and_then(|nsis| nsis.languages.clone())
.unwrap_or_else(|| vec!["English".into()]);
data.insert("languages", to_json(languages.clone()));
data.insert(
"display_language_selector",
to_json(
nsis
.map(|nsis| nsis.display_language_selector && languages.len() > 1)
.unwrap_or(false),
),
);
let custom_language_files = nsis.and_then(|nsis| nsis.custom_language_files.clone());
let mut language_files_paths = Vec::new();
for lang in &languages {
// if user provided a custom lang file, we rewrite it with BOM
if let Some(path) = custom_language_files.as_ref().and_then(|h| h.get(lang)) {
let path = dunce::canonicalize(path)?;
let path_with_bom = path
.file_name()
.map(|f| output_path.join(f))
.unwrap_or_else(|| output_path.join(format!("{lang}_custom.nsh")));
let content = std::fs::read(path)?;
write_utf8_with_bom(&path_with_bom, content)?;
language_files_paths.push(path_with_bom);
} else {
// if user has not provided a custom lang file,
// we check our translated languages
if let Some((file_name, content)) = get_lang_data(lang) {
let path = output_path.join(file_name);
write_utf8_with_bom(&path, content)?;
language_files_paths.push(path);
} else {
log::warn!("Custom tauri messages for {lang} are not translated.\nIf it is a valid language listed on <https://github.com/kichik/nsis/tree/9465c08046f00ccb6eda985abbdbf52c275c6c4d/Contrib/Language%20files>, please open a Tauri feature request\n or you can provide a custom language file for it in `tauri.conf.json > bundle > windows > nsis > custom_language_files`");
}
}
}
data.insert("language_files", to_json(language_files_paths));
let main_binary = settings.main_binary()?;
let main_binary_path = settings.binary_path(main_binary);
data.insert("main_binary_name", to_json(main_binary.name()));
data.insert("main_binary_path", to_json(&main_binary_path));
let out_file = "nsis-output.exe";
data.insert("out_file", to_json(out_file));
let resources = generate_resource_data(settings)?;
let resources_dirs =
std::collections::HashSet::<PathBuf>::from_iter(resources.values().map(|r| r.0.to_owned()));
let mut resources_ancestors = resources_dirs
.iter()
.flat_map(|p| p.ancestors())
.collect::<Vec<_>>();
resources_ancestors.sort_unstable();
resources_ancestors.dedup();
resources_ancestors.sort_by_key(|p| std::cmp::Reverse(p.components().count()));
resources_ancestors.pop(); // Last one is always ""
// We need to convert / to \ for nsis to move the files into the correct dirs
#[cfg(not(target_os = "windows"))]
let resources: ResourcesMap = resources
.into_iter()
.map(|(r, p)| {
(
r,
(
p.0.display().to_string().replace('/', "\\").into(),
p.1.display().to_string().replace('/', "\\").into(),
),
)
})
.collect();
#[cfg(not(target_os = "windows"))]
let resources_ancestors: Vec<PathBuf> = resources_ancestors
.into_iter()
.map(|p| p.display().to_string().replace('/', "\\").into())
.collect();
#[cfg(not(target_os = "windows"))]
let resources_dirs: Vec<PathBuf> = resources_dirs
.into_iter()
.map(|p| p.display().to_string().replace('/', "\\").into())
.collect();
data.insert("resources_ancestors", to_json(resources_ancestors));
data.insert("resources_dirs", to_json(resources_dirs));
data.insert("resources", to_json(&resources));
let binaries = generate_binaries_data(settings)?;
data.insert("binaries", to_json(&binaries));
let estimated_size = generate_estimated_size(&main_binary_path, &binaries, &resources)?;
data.insert("estimated_size", to_json(estimated_size));
if let Some(file_associations) = settings.file_associations() {
data.insert("file_associations", to_json(file_associations));
}
if let Some(protocols) = settings.deep_link_protocols() {
let schemes = protocols
.iter()
.flat_map(|p| &p.schemes)
.collect::<Vec<_>>();
if !schemes.is_empty() {
data.insert("deep_link_protocols", to_json(schemes));
}
}
let silent_webview2_install = if let WebviewInstallMode::DownloadBootstrapper { silent }
| WebviewInstallMode::EmbedBootstrapper { silent }
| WebviewInstallMode::OfflineInstaller { silent } =
settings.windows().webview_install_mode
{
silent
} else {
true
};
let webview2_install_mode = if updater {
WebviewInstallMode::DownloadBootstrapper {
silent: silent_webview2_install,
}
} else {
settings.windows().webview_install_mode.clone()
};
let webview2_installer_args = to_json(if silent_webview2_install {
"/silent"
} else {
""
});
data.insert("webview2_installer_args", to_json(webview2_installer_args));
data.insert(
"install_webview2_mode",
to_json(match webview2_install_mode {
WebviewInstallMode::DownloadBootstrapper { silent: _ } => "downloadBootstrapper",
WebviewInstallMode::EmbedBootstrapper { silent: _ } => "embedBootstrapper",
WebviewInstallMode::OfflineInstaller { silent: _ } => "offlineInstaller",
_ => "",
}),
);
match webview2_install_mode {
WebviewInstallMode::EmbedBootstrapper { silent: _ } => {
let webview2_bootstrapper_path = download_webview2_bootstrapper(tauri_tools_path)?;
data.insert(
"webview2_bootstrapper_path",
to_json(webview2_bootstrapper_path),
);
}
WebviewInstallMode::OfflineInstaller { silent: _ } => {
let webview2_installer_path =
download_webview2_offline_installer(&tauri_tools_path.join(arch), arch)?;
data.insert("webview2_installer_path", to_json(webview2_installer_path));
}
_ => {}
}
let mut handlebars = Handlebars::new();
handlebars.register_helper("or", Box::new(handlebars_or));
handlebars.register_helper("association-description", Box::new(association_description));
handlebars.register_helper("no-escape", Box::new(handlebars_no_escape));
handlebars.register_escape_fn(|s| {
let mut output = String::new();
for c in s.chars() {
match c {
'\"' => output.push_str("$\\\""),
'$' => output.push_str("$$"),
'`' => output.push_str("$\\`"),
'\n' => output.push_str("$\\n"),
'\t' => output.push_str("$\\t"),
'\r' => output.push_str("$\\r"),
_ => output.push(c),
}
}
output
});
if let Some(path) = custom_template_path {
handlebars
.register_template_string("installer.nsi", std::fs::read_to_string(path)?)
.map_err(|e| e.to_string())
.expect("Failed to setup custom handlebar template");
} else {
handlebars
.register_template_string("installer.nsi", include_str!("./installer.nsi"))
.map_err(|e| e.to_string())
.expect("Failed to setup handlebar template");
}
write_utf8_with_bom(
output_path.join("FileAssociation.nsh"),
include_bytes!("./FileAssociation.nsh"),
)?;
write_utf8_with_bom(output_path.join("utils.nsh"), include_bytes!("./utils.nsh"))?;
let installer_nsi_path = output_path.join("installer.nsi");
write_utf8_with_bom(
&installer_nsi_path,
handlebars.render("installer.nsi", &data)?,
)?;
let package_base_name = format!(
"{}_{}_{}-setup",
settings.product_name(),
settings.version_string(),
arch,
);
let nsis_output_path = output_path.join(out_file);
let nsis_installer_path = settings.project_out_directory().to_path_buf().join(format!(
"bundle/{}/{}.exe",
if updater {
NSIS_UPDATER_OUTPUT_FOLDER_NAME
} else {
NSIS_OUTPUT_FOLDER_NAME
},
package_base_name
));
fs::create_dir_all(nsis_installer_path.parent().unwrap())?;
if settings.windows().can_sign() {
if let Some(plugin_copy_path) = &maybe_plugin_copy_path {
let plugin_copy_path = plugin_copy_path.join("x86-unicode");
log::info!("Signing NSIS plugins");
for dll in NSIS_PLUGIN_FILES {
let path = plugin_copy_path.join(dll);
if path.exists() {
try_sign(&path, settings)?;
} else {
log::warn!("Could not find {}, skipping signing", path.display());
}
}
}
}
log::info!(action = "Running"; "makensis to produce {}", display_path(&nsis_installer_path));
#[cfg(target_os = "windows")]
let mut nsis_cmd = Command::new(nsis_toolset_path.join("makensis.exe"));
#[cfg(not(target_os = "windows"))]
let mut nsis_cmd = Command::new("makensis");
if let Some(plugins_path) = &maybe_plugin_copy_path {
nsis_cmd.env("NSISPLUGINS", plugins_path);
}
nsis_cmd
.args(["-INPUTCHARSET", "UTF8", "-OUTPUTCHARSET", "UTF8"])
.arg(match settings.log_level() {
log::Level::Error => "-V1",
log::Level::Warn => "-V2",
log::Level::Info => "-V3",
_ => "-V4",
})
.arg(installer_nsi_path)
.env_remove("NSISDIR")
.env_remove("NSISCONFDIR")
.current_dir(output_path)
.piped()
.map_err(|error| Error::CommandFailed {
command: "makensis.exe".to_string(),
error,
})?;
fs::rename(nsis_output_path, &nsis_installer_path)?;
if settings.windows().can_sign() {
try_sign(&nsis_installer_path, settings)?;
} else {
#[cfg(not(target_os = "windows"))]
log::warn!("Signing, by default, is only supported on Windows hosts, but you can specify a custom signing command in `bundler > windows > sign_command`, for now, skipping signing the installer...");
}
Ok(vec![nsis_installer_path])
}
fn handlebars_or(
h: &handlebars::Helper<'_>,
_: &Handlebars<'_>,
_: &handlebars::Context,
_: &mut handlebars::RenderContext<'_, '_>,
out: &mut dyn handlebars::Output,
) -> handlebars::HelperResult {
let param1 = h.param(0).unwrap().render();
let param2 = h.param(1).unwrap();
out.write(&if param1.is_empty() {
param2.render()
} else {
param1
})?;
Ok(())
}
fn association_description(
h: &handlebars::Helper<'_>,
_: &Handlebars<'_>,
_: &handlebars::Context,
_: &mut handlebars::RenderContext<'_, '_>,
out: &mut dyn handlebars::Output,
) -> handlebars::HelperResult {
let description = h.param(0).unwrap().render();
let ext = h.param(1).unwrap();
out.write(&if description.is_empty() {
format!("{} File", ext.render().to_uppercase())
} else {
description
})?;
Ok(())
}
fn handlebars_no_escape(
h: &handlebars::Helper<'_>,
_: &Handlebars<'_>,
_: &handlebars::Context,
_: &mut handlebars::RenderContext<'_, '_>,
out: &mut dyn handlebars::Output,
) -> handlebars::HelperResult {
// get parameter from helper or throw an error
let param = h
.param(0)
.ok_or(handlebars::RenderErrorReason::ParamNotFoundForIndex(
"no-escape",
0,
))?;
write!(out, "{}", param.render())?;
Ok(())
}
/// BTreeMap<OriginalPath, (ParentOfTargetPath, TargetPath)>
type ResourcesMap = BTreeMap<PathBuf, (PathBuf, PathBuf)>;
fn generate_resource_data(settings: &Settings) -> crate::Result<ResourcesMap> {
let mut resources = ResourcesMap::new();
let cwd = std::env::current_dir()?;
let mut added_resources = Vec::new();
// Adding WebViewer2Loader.dll in case windows-gnu toolchain is used
if settings.target().ends_with("-gnu") {
let loader_path =
dunce::simplified(&settings.project_out_directory().join("WebView2Loader.dll")).to_path_buf();
if loader_path.exists() {
if settings.windows().can_sign() {
try_sign(&loader_path, settings)?;
}
added_resources.push(loader_path.clone());
resources.insert(
loader_path,
(PathBuf::new(), PathBuf::from("WebView2Loader.dll")),
);
}
}
for resource in settings.resource_files().iter() {
let resource = resource?;
let src = cwd.join(resource.path());
let resource_path = dunce::simplified(&src).to_path_buf();
// In some glob resource paths like `assets/**/*` a file might appear twice
// because the `tauri_utils::resources::ResourcePaths` iterator also reads a directory
// when it finds one. So we must check it before processing the file.
if added_resources.contains(&resource_path) {
continue;
}
added_resources.push(resource_path.clone());
if settings.windows().can_sign() && should_sign(&resource_path)? {
try_sign(&resource_path, settings)?;
}
let target_path = resource.target();
resources.insert(
resource_path,
(
target_path
.parent()
.expect("Couldn't get parent of target path")
.to_path_buf(),
target_path.to_path_buf(),
),
);
}
Ok(resources)
}
/// BTreeMap<OriginalPath, TargetFileName>
type BinariesMap = BTreeMap<PathBuf, String>;
fn generate_binaries_data(settings: &Settings) -> crate::Result<BinariesMap> {
let mut binaries = BinariesMap::new();
let cwd = std::env::current_dir()?;
for src in settings.external_binaries() {
let src = src?;
let binary_path = dunce::canonicalize(cwd.join(&src))?;
let dest_filename = src
.file_name()
.expect("failed to extract external binary filename")
.to_string_lossy()
.replace(&format!("-{}", settings.target()), "");
binaries.insert(binary_path, dest_filename);
}
for bin in settings.binaries() {
if !bin.main() {
let bin_path = settings.binary_path(bin);
binaries.insert(
bin_path.clone(),
bin_path
.file_name()
.expect("failed to extract external binary filename")
.to_string_lossy()
.to_string(),
);
}
}
Ok(binaries)
}
fn generate_estimated_size(
main: &PathBuf,
binaries: &BinariesMap,
resources: &ResourcesMap,
) -> crate::Result<u64> {
let mut size = 0;
for k in std::iter::once(main)
.chain(binaries.keys())
.chain(resources.keys())
{
size += std::fs::metadata(k)
.map_err(|error| Error::Fs {
context: "when getting size of",
path: k.to_path_buf(),
error,
})?
.len();
}
Ok(size / 1024)
}
fn get_lang_data(lang: &str) -> Option<(String, &[u8])> {
let path = format!("{lang}.nsh");
let content: &[u8] = match lang.to_lowercase().as_str() {
"arabic" => include_bytes!("./languages/Arabic.nsh"),
"bulgarian" => include_bytes!("./languages/Bulgarian.nsh"),
"dutch" => include_bytes!("./languages/Dutch.nsh"),
"english" => include_bytes!("./languages/English.nsh"),
"german" => include_bytes!("./languages/German.nsh"),
"italian" => include_bytes!("./languages/Italian.nsh"),
"japanese" => include_bytes!("./languages/Japanese.nsh"),
"korean" => include_bytes!("./languages/Korean.nsh"),
"portuguesebr" => include_bytes!("./languages/PortugueseBR.nsh"),
"russian" => include_bytes!("./languages/Russian.nsh"),
"tradchinese" => include_bytes!("./languages/TradChinese.nsh"),
"simpchinese" => include_bytes!("./languages/SimpChinese.nsh"),
"french" => include_bytes!("./languages/French.nsh"),
"spanish" => include_bytes!("./languages/Spanish.nsh"),
"spanishinternational" => include_bytes!("./languages/SpanishInternational.nsh"),
"persian" => include_bytes!("./languages/Persian.nsh"),
"turkish" => include_bytes!("./languages/Turkish.nsh"),
"swedish" => include_bytes!("./languages/Swedish.nsh"),
"portuguese" => include_bytes!("./languages/Portuguese.nsh"),
"ukrainian" => include_bytes!("./languages/Ukrainian.nsh"),
_ => return None,
};
Some((path, content))
}
fn write_utf8_with_bom<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, content: C) -> crate::Result<()> {
use std::fs::File;
use std::io::{BufWriter, Write};
let file = File::create(path)?;
let mut output = BufWriter::new(file);
output.write_all(&[0xEF, 0xBB, 0xBF])?; // UTF-8 BOM
output.write_all(content.as_ref())?;
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-bundler/src/bundle/windows/msi/mod.rs | crates/tauri-bundler/src/bundle/windows/msi/mod.rs | // Copyright 2016-2019 Cargo-Bundle developers <https://github.com/burtonageo/cargo-bundle>
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{
bundle::{
settings::{Arch, Settings},
windows::{
sign::{should_sign, try_sign},
util::{
download_webview2_bootstrapper, download_webview2_offline_installer,
WIX_OUTPUT_FOLDER_NAME, WIX_UPDATER_OUTPUT_FOLDER_NAME,
},
},
},
error::Context,
utils::{
fs_utils::copy_file,
http_utils::{download_and_verify, extract_zip, HashAlgorithm},
CommandExt,
},
};
use handlebars::{html_escape, to_json, Handlebars};
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::{
collections::{BTreeMap, HashMap, HashSet},
ffi::OsStr,
fs::{self, File},
io::Write,
path::{Path, PathBuf},
process::Command,
};
use tauri_utils::{config::WebviewInstallMode, display_path};
use uuid::Uuid;
// URLS for the WIX toolchain. Can be used for cross-platform compilation.
pub const WIX_URL: &str =
"https://github.com/wixtoolset/wix3/releases/download/wix3141rtm/wix314-binaries.zip";
pub const WIX_SHA256: &str = "6ac824e1642d6f7277d0ed7ea09411a508f6116ba6fae0aa5f2c7daa2ff43d31";
const WIX_REQUIRED_FILES: &[&str] = &[
"candle.exe",
"candle.exe.config",
"darice.cub",
"light.exe",
"light.exe.config",
"wconsole.dll",
"winterop.dll",
"wix.dll",
"WixUIExtension.dll",
"WixUtilExtension.dll",
];
/// Runs all of the commands to build the MSI installer.
/// Returns a vector of PathBuf that shows where the MSI was created.
pub fn bundle_project(settings: &Settings, updater: bool) -> crate::Result<Vec<PathBuf>> {
let tauri_tools_path = settings
.local_tools_directory()
.map(|d| d.join(".tauri"))
.unwrap_or_else(|| dirs::cache_dir().unwrap().join("tauri"));
let wix_path = tauri_tools_path.join("WixTools314");
if !wix_path.exists() {
get_and_extract_wix(&wix_path)?;
} else if WIX_REQUIRED_FILES
.iter()
.any(|p| !wix_path.join(p).exists())
{
log::warn!("WixTools directory is missing some files. Recreating it.");
std::fs::remove_dir_all(&wix_path)?;
get_and_extract_wix(&wix_path)?;
}
build_wix_app_installer(settings, &wix_path, updater)
}
// For Cross Platform Compilation.
// const VC_REDIST_X86_URL: &str =
// "https://download.visualstudio.microsoft.com/download/pr/c8edbb87-c7ec-4500-a461-71e8912d25e9/99ba493d660597490cbb8b3211d2cae4/vc_redist.x86.exe";
// const VC_REDIST_X86_SHA256: &str =
// "3a43e8a55a3f3e4b73d01872c16d47a19dd825756784f4580187309e7d1fcb74";
// const VC_REDIST_X64_URL: &str =
// "https://download.visualstudio.microsoft.com/download/pr/9e04d214-5a9d-4515-9960-3d71398d98c3/1e1e62ab57bbb4bf5199e8ce88f040be/vc_redist.x64.exe";
// const VC_REDIST_X64_SHA256: &str =
// "d6cd2445f68815fe02489fafe0127819e44851e26dfbe702612bc0d223cbbc2b";
// A v4 UUID that was generated specifically for tauri-bundler, to be used as a
// namespace for generating v5 UUIDs from bundle identifier strings.
const UUID_NAMESPACE: [u8; 16] = [
0xfd, 0x85, 0x95, 0xa8, 0x17, 0xa3, 0x47, 0x4e, 0xa6, 0x16, 0x76, 0x14, 0x8d, 0xfa, 0x0c, 0x7b,
];
/// Mapper between a resource directory name and its ResourceDirectory descriptor.
type ResourceMap = BTreeMap<String, ResourceDirectory>;
#[derive(Debug, Deserialize)]
struct LanguageMetadata {
#[serde(rename = "asciiCode")]
ascii_code: usize,
#[serde(rename = "langId")]
lang_id: usize,
}
/// A binary to bundle with WIX.
/// External binaries or additional project binaries are represented with this data structure.
/// This data structure is needed because WIX requires each path to have its own `id` and `guid`.
#[derive(Serialize)]
struct Binary {
/// the GUID to use on the WIX XML.
guid: String,
/// the id to use on the WIX XML.
id: String,
/// the binary path.
path: String,
}
/// A Resource file to bundle with WIX.
/// This data structure is needed because WIX requires each path to have its own `id` and `guid`.
#[derive(Serialize, Clone)]
struct ResourceFile {
/// the GUID to use on the WIX XML.
guid: String,
/// the id to use on the WIX XML.
id: String,
/// the file path.
path: PathBuf,
}
/// A resource directory to bundle with WIX.
/// This data structure is needed because WIX requires each path to have its own `id` and `guid`.
#[derive(Serialize)]
struct ResourceDirectory {
/// the directory path.
path: String,
/// the directory name of the described resource.
name: String,
/// the files of the described resource directory.
files: Vec<ResourceFile>,
/// the directories that are children of the described resource directory.
directories: Vec<ResourceDirectory>,
}
impl ResourceDirectory {
/// Adds a file to this directory descriptor.
fn add_file(&mut self, file: ResourceFile) {
self.files.push(file);
}
/// Generates the wix XML string to bundle this directory resources recursively
fn get_wix_data(self) -> crate::Result<(String, Vec<String>)> {
let mut files = String::from("");
let mut file_ids = Vec::new();
for file in self.files {
file_ids.push(file.id.clone());
files.push_str(
format!(
r#"<Component Id="{id}" Guid="{guid}" Win64="$(var.Win64)" KeyPath="yes"><File Id="PathFile_{id}" Source="{path}" /></Component>"#,
id = file.id,
guid = file.guid,
path = html_escape(&file.path.display().to_string())
).as_str()
);
}
let mut directories = String::from("");
for directory in self.directories {
let (wix_string, ids) = directory.get_wix_data()?;
for id in ids {
file_ids.push(id)
}
directories.push_str(wix_string.as_str());
}
let wix_string = if self.name.is_empty() {
format!("{files}{directories}")
} else {
format!(
r#"<Directory Id="I{id}" Name="{name}">{files}{directories}</Directory>"#,
id = Uuid::new_v4().as_simple(),
name = html_escape(&self.name),
files = files,
directories = directories,
)
};
Ok((wix_string, file_ids))
}
}
/// Copies the icon to the binary path, under the `resources` folder,
/// and returns the path to the file.
fn copy_icon(settings: &Settings, filename: &str, path: &Path) -> crate::Result<PathBuf> {
let base_dir = settings.project_out_directory();
let resource_dir = base_dir.join("resources");
fs::create_dir_all(&resource_dir)?;
let icon_target_path = resource_dir.join(filename);
let icon_path = std::env::current_dir()?.join(path);
copy_file(&icon_path, &icon_target_path)?;
Ok(icon_target_path)
}
/// The app installer output path.
fn app_installer_output_path(
settings: &Settings,
language: &str,
version: &str,
updater: bool,
) -> crate::Result<PathBuf> {
let arch = match settings.binary_arch() {
Arch::X86_64 => "x64",
Arch::X86 => "x86",
Arch::AArch64 => "arm64",
target => {
return Err(crate::Error::ArchError(format!(
"Unsupported architecture: {target:?}"
)))
}
};
let package_base_name = format!(
"{}_{}_{}_{}",
settings.product_name(),
version,
arch,
language,
);
Ok(settings.project_out_directory().to_path_buf().join(format!(
"bundle/{}/{}.msi",
if updater {
WIX_UPDATER_OUTPUT_FOLDER_NAME
} else {
WIX_OUTPUT_FOLDER_NAME
},
package_base_name
)))
}
/// Generates the UUID for the Wix template.
fn generate_package_guid(settings: &Settings) -> Uuid {
generate_guid(settings.bundle_identifier().as_bytes())
}
/// Generates a GUID.
fn generate_guid(key: &[u8]) -> Uuid {
let namespace = Uuid::from_bytes(UUID_NAMESPACE);
Uuid::new_v5(&namespace, key)
}
// Specifically goes and gets Wix and verifies the download via Sha256
pub fn get_and_extract_wix(path: &Path) -> crate::Result<()> {
log::info!("Verifying wix package");
let data = download_and_verify(WIX_URL, WIX_SHA256, HashAlgorithm::Sha256)?;
log::info!("extracting WIX");
extract_zip(&data, path)
}
fn clear_env_for_wix(cmd: &mut Command) {
cmd.env_clear();
let required_vars: Vec<std::ffi::OsString> =
vec!["SYSTEMROOT".into(), "TMP".into(), "TEMP".into()];
for (k, v) in std::env::vars_os() {
let k = k.to_ascii_uppercase();
if required_vars.contains(&k) || k.to_string_lossy().starts_with("TAURI") {
cmd.env(k, v);
}
}
}
fn validate_wix_version(version_str: &str) -> crate::Result<()> {
let components = version_str
.split('.')
.flat_map(|c| c.parse::<u64>().ok())
.collect::<Vec<_>>();
if components.len() < 3 {
crate::error::bail!(
"app wix version should be in the format major.minor.patch.build (build is optional)"
);
}
if components[0] > 255 {
crate::error::bail!("app version major number cannot be greater than 255");
}
if components[1] > 255 {
crate::error::bail!("app version minor number cannot be greater than 255");
}
if components[2] > 65535 {
crate::error::bail!("app version patch number cannot be greater than 65535");
}
if components.len() == 4 && components[3] > 65535 {
crate::error::bail!("app version build number cannot be greater than 65535");
}
Ok(())
}
// WiX requires versions to be numeric only in a `major.minor.patch.build` format
fn convert_version(version_str: &str) -> crate::Result<String> {
let version = semver::Version::parse(version_str)
.map_err(Into::into)
.context("invalid app version")?;
if !version.build.is_empty() {
let build = version.build.parse::<u64>();
if build.map(|b| b <= 65535).unwrap_or_default() {
return Ok(format!(
"{}.{}.{}.{}",
version.major, version.minor, version.patch, version.build
));
} else {
crate::error::bail!("optional build metadata in app version must be numeric-only and cannot be greater than 65535 for msi target");
}
}
if !version.pre.is_empty() {
let pre = version.pre.parse::<u64>();
if pre.is_ok() && pre.unwrap() <= 65535 {
return Ok(format!(
"{}.{}.{}.{}",
version.major, version.minor, version.patch, version.pre
));
} else {
crate::error::bail!("optional pre-release identifier in app version must be numeric-only and cannot be greater than 65535 for msi target");
}
}
Ok(version_str.to_string())
}
/// Runs the Candle.exe executable for Wix. Candle parses the wxs file and generates the code for building the installer.
fn run_candle(
settings: &Settings,
wix_toolset_path: &Path,
cwd: &Path,
wxs_file_path: PathBuf,
extensions: Vec<PathBuf>,
) -> crate::Result<()> {
let arch = match settings.binary_arch() {
Arch::X86_64 => "x64",
Arch::X86 => "x86",
Arch::AArch64 => "arm64",
target => {
return Err(crate::Error::ArchError(format!(
"unsupported architecture: {target:?}"
)))
}
};
let main_binary = settings.main_binary()?;
let mut args = vec![
"-arch".to_string(),
arch.to_string(),
wxs_file_path.to_string_lossy().to_string(),
format!(
"-dSourceDir={}",
display_path(settings.binary_path(main_binary))
),
];
if settings
.windows()
.wix
.as_ref()
.map(|w| w.fips_compliant)
.unwrap_or_default()
{
args.push("-fips".into());
}
let candle_exe = wix_toolset_path.join("candle.exe");
log::info!(action = "Running"; "candle for {:?}", wxs_file_path);
let mut cmd = Command::new(candle_exe);
for ext in extensions {
cmd.arg("-ext");
cmd.arg(ext);
}
clear_env_for_wix(&mut cmd);
cmd.args(&args).current_dir(cwd).output_ok()?;
Ok(())
}
/// Runs the Light.exe file. Light takes the generated code from Candle and produces an MSI Installer.
fn run_light(
wix_toolset_path: &Path,
build_path: &Path,
arguments: Vec<String>,
extensions: &Vec<PathBuf>,
output_path: &Path,
) -> crate::Result<()> {
let light_exe = wix_toolset_path.join("light.exe");
let mut args: Vec<String> = vec!["-o".to_string(), display_path(output_path)];
args.extend(arguments);
let mut cmd = Command::new(light_exe);
for ext in extensions {
cmd.arg("-ext");
cmd.arg(ext);
}
clear_env_for_wix(&mut cmd);
cmd.args(&args).current_dir(build_path).output_ok()?;
Ok(())
}
// fn get_icon_data() -> crate::Result<()> {
// Ok(())
// }
// Entry point for bundling and creating the MSI installer. For now the only supported platform is Windows x64.
pub fn build_wix_app_installer(
settings: &Settings,
wix_toolset_path: &Path,
updater: bool,
) -> crate::Result<Vec<PathBuf>> {
let arch = match settings.binary_arch() {
Arch::X86_64 => "x64",
Arch::X86 => "x86",
Arch::AArch64 => "arm64",
target => {
return Err(crate::Error::ArchError(format!(
"unsupported architecture: {target:?}"
)))
}
};
let app_version = if let Some(version) = settings
.windows()
.wix
.as_ref()
.and_then(|wix| wix.version.clone())
{
version
} else {
convert_version(settings.version_string())?
};
validate_wix_version(&app_version)?;
// target only supports x64.
log::info!("Target: {}", arch);
let output_path = settings.project_out_directory().join("wix").join(arch);
if output_path.exists() {
fs::remove_dir_all(&output_path)?;
}
fs::create_dir_all(&output_path)?;
// when we're performing code signing, we'll sign some WiX DLLs, so we make a local copy
let wix_toolset_path = if settings.windows().can_sign() {
let wix_path = output_path.join("wix");
crate::utils::fs_utils::copy_dir(wix_toolset_path, &wix_path)?;
wix_path
} else {
wix_toolset_path.to_path_buf()
};
let mut data = BTreeMap::new();
let silent_webview_install = if let WebviewInstallMode::DownloadBootstrapper { silent }
| WebviewInstallMode::EmbedBootstrapper { silent }
| WebviewInstallMode::OfflineInstaller { silent } =
settings.windows().webview_install_mode
{
silent
} else {
true
};
let webview_install_mode = if updater {
WebviewInstallMode::DownloadBootstrapper {
silent: silent_webview_install,
}
} else {
settings.windows().webview_install_mode.clone()
};
data.insert("install_webview", to_json(true));
data.insert(
"webview_installer_args",
to_json(if silent_webview_install {
"/silent"
} else {
""
}),
);
match webview_install_mode {
WebviewInstallMode::Skip | WebviewInstallMode::FixedRuntime { .. } => {
data.insert("install_webview", to_json(false));
}
WebviewInstallMode::DownloadBootstrapper { silent: _ } => {
data.insert("download_bootstrapper", to_json(true));
data.insert(
"webview_installer_args",
to_json(if silent_webview_install {
"'/silent',"
} else {
""
}),
);
}
WebviewInstallMode::EmbedBootstrapper { silent: _ } => {
let webview2_bootstrapper_path = download_webview2_bootstrapper(&output_path)?;
data.insert(
"webview2_bootstrapper_path",
to_json(webview2_bootstrapper_path),
);
}
WebviewInstallMode::OfflineInstaller { silent: _ } => {
let webview2_installer_path =
download_webview2_offline_installer(&output_path.join(arch), arch)?;
data.insert("webview2_installer_path", to_json(webview2_installer_path));
}
}
if let Some(license) = settings.license_file() {
if license.ends_with(".rtf") {
data.insert("license", to_json(license));
} else {
let license_contents = fs::read_to_string(license)?;
let license_rtf = format!(
r#"{{\rtf1\ansi\ansicpg1252\deff0\nouicompat\deflang1033{{\fonttbl{{\f0\fnil\fcharset0 Calibri;}}}}
{{\*\generator Riched20 10.0.18362}}\viewkind4\uc1
\pard\sa200\sl276\slmult1\f0\fs22\lang9 {}\par
}}
"#,
license_contents.replace('\n', "\\par ")
);
let rtf_output_path = settings
.project_out_directory()
.join("wix")
.join("LICENSE.rtf");
std::fs::write(&rtf_output_path, license_rtf)?;
data.insert("license", to_json(rtf_output_path));
}
}
let language_map: HashMap<String, LanguageMetadata> =
serde_json::from_str(include_str!("./languages.json")).unwrap();
let configured_languages = settings
.windows()
.wix
.as_ref()
.map(|w| w.language.clone())
.unwrap_or_default();
data.insert("product_name", to_json(settings.product_name()));
data.insert("version", to_json(app_version));
data.insert(
"long_description",
to_json(settings.long_description().unwrap_or_default()),
);
data.insert("homepage", to_json(settings.homepage_url()));
let bundle_id = settings.bundle_identifier();
let manufacturer = settings
.publisher()
.unwrap_or_else(|| bundle_id.split('.').nth(1).unwrap_or(bundle_id));
data.insert("bundle_id", to_json(bundle_id));
data.insert("manufacturer", to_json(manufacturer));
// NOTE: if this is ever changed, make sure to also update `tauri inspect wix-upgrade-code` subcommand
let upgrade_code = settings
.windows()
.wix
.as_ref()
.and_then(|w| w.upgrade_code)
.unwrap_or_else(|| {
Uuid::new_v5(
&Uuid::NAMESPACE_DNS,
format!("{}.exe.app.x64", &settings.product_name()).as_bytes(),
)
});
data.insert("upgrade_code", to_json(upgrade_code.to_string()));
data.insert(
"allow_downgrades",
to_json(settings.windows().allow_downgrades),
);
let path_guid = generate_package_guid(settings).to_string();
data.insert("path_component_guid", to_json(path_guid.as_str()));
let shortcut_guid = generate_package_guid(settings).to_string();
data.insert("shortcut_guid", to_json(shortcut_guid.as_str()));
let binaries = generate_binaries_data(settings)?;
let binaries_json = to_json(binaries);
data.insert("binaries", binaries_json);
let resources = generate_resource_data(settings)?;
let mut resources_wix_string = String::from("");
let mut files_ids = Vec::new();
for (_, dir) in resources {
let (wix_string, ids) = dir.get_wix_data()?;
resources_wix_string.push_str(wix_string.as_str());
for id in ids {
files_ids.push(id);
}
}
data.insert("resources", to_json(resources_wix_string));
data.insert("resource_file_ids", to_json(files_ids));
let merge_modules = get_merge_modules(settings)?;
data.insert("merge_modules", to_json(merge_modules));
// Note: `main_binary_name` is not used in our template but we keep it as it is potentially useful for custom temples
let main_binary_name = settings.main_binary_name()?;
data.insert("main_binary_name", to_json(main_binary_name));
let main_binary = settings.main_binary()?;
let main_binary_path = settings.binary_path(main_binary);
data.insert("main_binary_path", to_json(main_binary_path));
// copy icon from `settings.windows().icon_path` folder to resource folder near msi
#[allow(deprecated)]
let icon_path = if !settings.windows().icon_path.as_os_str().is_empty() {
settings.windows().icon_path.clone()
} else {
settings
.icon_files()
.flatten()
.find(|i| i.extension() == Some(OsStr::new("ico")))
.context("Couldn't find a .ico icon")?
};
let icon_path = copy_icon(settings, "icon.ico", &icon_path)?;
data.insert("icon_path", to_json(icon_path));
let mut fragment_paths = Vec::new();
let mut handlebars = Handlebars::new();
handlebars.register_escape_fn(handlebars::no_escape);
let mut custom_template_path = None;
let mut enable_elevated_update_task = false;
if let Some(wix) = &settings.windows().wix {
data.insert("component_group_refs", to_json(&wix.component_group_refs));
data.insert("component_refs", to_json(&wix.component_refs));
data.insert("feature_group_refs", to_json(&wix.feature_group_refs));
data.insert("feature_refs", to_json(&wix.feature_refs));
data.insert("merge_refs", to_json(&wix.merge_refs));
fragment_paths.clone_from(&wix.fragment_paths);
enable_elevated_update_task = wix.enable_elevated_update_task;
custom_template_path.clone_from(&wix.template);
if let Some(banner_path) = &wix.banner_path {
let filename = banner_path
.file_name()
.unwrap()
.to_string_lossy()
.into_owned();
data.insert(
"banner_path",
to_json(copy_icon(settings, &filename, banner_path)?),
);
}
if let Some(dialog_image_path) = &wix.dialog_image_path {
let filename = dialog_image_path
.file_name()
.unwrap()
.to_string_lossy()
.into_owned();
data.insert(
"dialog_image_path",
to_json(copy_icon(settings, &filename, dialog_image_path)?),
);
}
}
if let Some(file_associations) = settings.file_associations() {
data.insert("file_associations", to_json(file_associations));
}
if let Some(protocols) = settings.deep_link_protocols() {
let schemes = protocols
.iter()
.flat_map(|p| &p.schemes)
.collect::<Vec<_>>();
if !schemes.is_empty() {
data.insert("deep_link_protocols", to_json(schemes));
}
}
if let Some(path) = custom_template_path {
handlebars
.register_template_string("main.wxs", fs::read_to_string(path)?)
.map_err(|e| e.to_string())
.expect("Failed to setup custom handlebar template");
} else {
handlebars
.register_template_string("main.wxs", include_str!("./main.wxs"))
.map_err(|e| e.to_string())
.expect("Failed to setup handlebar template");
}
if enable_elevated_update_task {
data.insert(
"msiexec_args",
to_json(
settings
.updater()
.map(|updater| updater.msiexec_args)
.map(|args| args.join(" "))
.unwrap_or_else(|| "/passive".to_string()),
),
);
// Create the update task XML
let skip_uac_task = Handlebars::new();
let xml = include_str!("./update-task.xml");
let update_content = skip_uac_task.render_template(xml, &data)?;
let temp_xml_path = output_path.join("update.xml");
fs::write(temp_xml_path, update_content)?;
// Create the Powershell script to install the task
let mut skip_uac_task_installer = Handlebars::new();
skip_uac_task_installer.register_escape_fn(handlebars::no_escape);
let xml = include_str!("./install-task.ps1");
let install_script_content = skip_uac_task_installer.render_template(xml, &data)?;
let temp_ps1_path = output_path.join("install-task.ps1");
fs::write(temp_ps1_path, install_script_content)?;
// Create the Powershell script to uninstall the task
let mut skip_uac_task_uninstaller = Handlebars::new();
skip_uac_task_uninstaller.register_escape_fn(handlebars::no_escape);
let xml = include_str!("./uninstall-task.ps1");
let install_script_content = skip_uac_task_uninstaller.render_template(xml, &data)?;
let temp_ps1_path = output_path.join("uninstall-task.ps1");
fs::write(temp_ps1_path, install_script_content)?;
data.insert("enable_elevated_update_task", to_json(true));
}
let main_wxs_path = output_path.join("main.wxs");
fs::write(&main_wxs_path, handlebars.render("main.wxs", &data)?)?;
let mut candle_inputs = vec![];
let current_dir = std::env::current_dir()?;
let extension_regex = Regex::new("\"http://schemas.microsoft.com/wix/(\\w+)\"")?;
let input_paths =
std::iter::once(main_wxs_path).chain(fragment_paths.iter().map(|p| current_dir.join(p)));
for input_path in input_paths {
let input_content = fs::read_to_string(&input_path)?;
let input_handlebars = Handlebars::new();
let input = input_handlebars.render_template(&input_content, &data)?;
let mut extensions = Vec::new();
for cap in extension_regex.captures_iter(&input) {
let path = wix_toolset_path.join(format!("Wix{}.dll", &cap[1]));
if settings.windows().can_sign() {
try_sign(&path, settings)?;
}
extensions.push(path);
}
candle_inputs.push((input_path, extensions));
}
let mut fragment_extensions = HashSet::new();
//Default extensions
fragment_extensions.insert(wix_toolset_path.join("WixUIExtension.dll"));
fragment_extensions.insert(wix_toolset_path.join("WixUtilExtension.dll"));
// sign default extensions
if settings.windows().can_sign() {
for path in &fragment_extensions {
try_sign(path, settings)?;
}
}
for (path, extensions) in candle_inputs {
for ext in &extensions {
fragment_extensions.insert(ext.clone());
}
run_candle(settings, &wix_toolset_path, &output_path, path, extensions)?;
}
let mut output_paths = Vec::new();
for (language, language_config) in configured_languages.0 {
let language_metadata = language_map.get(&language).unwrap_or_else(|| {
panic!(
"Language {} not found. It must be one of {}",
language,
language_map
.keys()
.cloned()
.collect::<Vec<String>>()
.join(", ")
)
});
let locale_contents = match language_config.locale_path {
Some(p) => fs::read_to_string(p)?,
None => format!(
r#"<WixLocalization Culture="{}" xmlns="http://schemas.microsoft.com/wix/2006/localization"></WixLocalization>"#,
language.to_lowercase(),
),
};
let locale_strings = include_str!("./default-locale-strings.xml")
.replace("__language__", &language_metadata.lang_id.to_string())
.replace("__codepage__", &language_metadata.ascii_code.to_string())
.replace("__productName__", settings.product_name());
let mut unset_locale_strings = String::new();
let prefix_len = "<String ".len();
for locale_string in locale_strings.split('\n').filter(|s| !s.is_empty()) {
// strip `<String ` prefix and `>{value}</String` suffix.
let id = locale_string
.chars()
.skip(prefix_len)
.take(locale_string.find('>').unwrap() - prefix_len)
.collect::<String>();
if !locale_contents.contains(&id) {
unset_locale_strings.push_str(locale_string);
}
}
let locale_contents = locale_contents.replace(
"</WixLocalization>",
&format!("{unset_locale_strings}</WixLocalization>"),
);
let locale_path = output_path.join("locale.wxl");
{
let mut fileout = File::create(&locale_path).expect("Failed to create locale file");
fileout.write_all(locale_contents.as_bytes())?;
}
let arguments = vec![
format!(
"-cultures:{}",
if language == "en-US" {
language.to_lowercase()
} else {
format!("{};en-US", language.to_lowercase())
}
),
"-loc".into(),
display_path(&locale_path),
"*.wixobj".into(),
];
let msi_output_path = output_path.join("output.msi");
let msi_path =
app_installer_output_path(settings, &language, settings.version_string(), updater)?;
fs::create_dir_all(msi_path.parent().unwrap())?;
log::info!(action = "Running"; "light to produce {}", display_path(&msi_path));
run_light(
&wix_toolset_path,
&output_path,
arguments,
&(fragment_extensions.clone().into_iter().collect()),
&msi_output_path,
)?;
fs::rename(&msi_output_path, &msi_path)?;
if settings.windows().can_sign() {
try_sign(&msi_path, settings)?;
}
output_paths.push(msi_path);
}
Ok(output_paths)
}
/// Generates the data required for the external binaries and extra binaries bundling.
fn generate_binaries_data(settings: &Settings) -> crate::Result<Vec<Binary>> {
let mut binaries = Vec::new();
let cwd = std::env::current_dir()?;
let tmp_dir = std::env::temp_dir();
let regex = Regex::new(r"[^\w\d\.]")?;
for src in settings.external_binaries() {
let src = src?;
let binary_path = cwd.join(&src);
let dest_filename = src
.file_name()
.expect("failed to extract external binary filename")
.to_string_lossy()
.replace(&format!("-{}", settings.target()), "");
let dest = tmp_dir.join(&dest_filename);
std::fs::copy(binary_path, &dest)?;
binaries.push(Binary {
guid: Uuid::new_v4().to_string(),
path: dest
.into_os_string()
.into_string()
.expect("failed to read external binary path"),
id: regex
.replace_all(&dest_filename.replace('-', "_"), "")
.to_string(),
});
}
for bin in settings.binaries() {
if !bin.main() {
binaries.push(Binary {
guid: Uuid::new_v4().to_string(),
path: settings
.binary_path(bin)
.into_os_string()
.into_string()
.expect("failed to read binary path"),
id: regex
.replace_all(&bin.name().replace('-', "_"), "")
.to_string(),
})
}
}
Ok(binaries)
}
#[derive(Serialize)]
struct MergeModule {
name: String,
path: String,
}
fn get_merge_modules(settings: &Settings) -> crate::Result<Vec<MergeModule>> {
let mut merge_modules = Vec::new();
let regex = Regex::new(r"[^\w\d\.]")?;
for msm in glob::glob(
&PathBuf::from(glob::Pattern::escape(
&settings.project_out_directory().to_string_lossy(),
))
.join("*.msm")
.to_string_lossy(),
)? {
let path = msm?;
let filename = path
.file_name()
.expect("failed to extract merge module filename")
.to_os_string()
.into_string()
.expect("failed to convert merge module filename to string");
merge_modules.push(MergeModule {
name: regex.replace_all(&filename, "").to_string(),
path: path.to_string_lossy().to_string(),
});
}
Ok(merge_modules)
}
/// Generates the data required for the resource bundling on wix
fn generate_resource_data(settings: &Settings) -> crate::Result<ResourceMap> {
let mut resources = ResourceMap::new();
let cwd = std::env::current_dir()?;
let mut added_resources = Vec::new();
for resource in settings.resource_files().iter() {
let resource = resource?;
let src = cwd.join(resource.path());
let resource_path = dunce::simplified(&src).to_path_buf();
// In some glob resource paths like `assets/**/*` a file might appear twice
// because the `tauri_utils::resources::ResourcePaths` iterator also reads a directory
// when it finds one. So we must check it before processing the file.
if added_resources.contains(&resource_path) {
continue;
}
added_resources.push(resource_path.clone());
if settings.windows().can_sign() && should_sign(&resource_path)? {
try_sign(&resource_path, settings)?;
}
let resource_entry = ResourceFile {
id: format!("I{}", Uuid::new_v4().as_simple()),
guid: Uuid::new_v4().to_string(),
path: resource_path.clone(),
};
// split the resource path directories
let target_path = resource.target();
let components_count = target_path.components().count();
let directories = target_path
.components()
.take(components_count - 1) // the last component is the file
.collect::<Vec<_>>();
// transform the directory structure to a chained vec structure
let first_directory = directories
.first()
.map(|d| d.as_os_str().to_string_lossy().into_owned())
.unwrap_or_else(String::new);
if !resources.contains_key(&first_directory) {
resources.insert(
first_directory.clone(),
ResourceDirectory {
path: first_directory.clone(),
name: first_directory.clone(),
directories: vec![],
files: vec![],
},
);
}
let mut directory_entry = resources
.get_mut(&first_directory)
.expect("Unable to handle resources");
let mut path = String::new();
// the first component is already parsed on `first_directory` so we skip(1)
for directory in directories.into_iter().skip(1) {
let directory_name = directory
.as_os_str()
.to_os_string()
.into_string()
.expect("failed to read resource folder name");
path.push_str(directory_name.as_str());
path.push(std::path::MAIN_SEPARATOR);
let index = directory_entry
.directories
.iter()
.position(|f| f.path == path);
match index {
Some(i) => directory_entry = directory_entry.directories.get_mut(i).unwrap(),
None => {
directory_entry.directories.push(ResourceDirectory {
path: path.clone(),
name: directory_name,
directories: vec![],
files: vec![],
});
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | true |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-bundler/src/bundle/macos/ios.rs | crates/tauri-bundler/src/bundle/macos/ios.rs | // Copyright 2016-2019 Cargo-Bundle developers <https://github.com/burtonageo/cargo-bundle>
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
// An iOS package is laid out like:
//
// Foobar.app # Actually a directory
// Foobar # The main binary executable of the app
// Info.plist # An XML file containing the app's metadata
// ... # Icons and other resource files
//
// See https://developer.apple.com/go/?id=bundle-structure for a full
// explanation.
use crate::{
error::{Context, ErrorExt},
utils::{self, fs_utils},
Settings,
};
use image::{codecs::png::PngDecoder, GenericImageView, ImageDecoder};
use std::{
collections::BTreeSet,
ffi::OsStr,
fs::{self, File},
io::{BufReader, Write},
path::{Path, PathBuf},
};
/// Bundles the project.
/// Returns a vector of PathBuf that shows where the .app was created.
pub fn bundle_project(settings: &Settings) -> crate::Result<Vec<PathBuf>> {
log::warn!("iOS bundle support is still experimental.");
let app_product_name = format!("{}.app", settings.product_name());
let app_bundle_path = settings
.project_out_directory()
.join("bundle/ios")
.join(&app_product_name);
log::info!(action = "Bundling"; "{} ({})", app_product_name, app_bundle_path.display());
if app_bundle_path.exists() {
fs::remove_dir_all(&app_bundle_path)
.fs_context("failed to remove old app bundle", &app_bundle_path)?;
}
fs::create_dir_all(&app_bundle_path)
.fs_context("failed to create bundle directory", &app_bundle_path)?;
for src in settings.resource_files() {
let src = src?;
let dest = app_bundle_path.join(tauri_utils::resources::resource_relpath(&src));
fs_utils::copy_file(&src, &dest)
.with_context(|| format!("Failed to copy resource file {src:?}"))?;
}
let icon_filenames = generate_icon_files(&app_bundle_path, settings)
.with_context(|| "Failed to create app icons")?;
generate_info_plist(&app_bundle_path, settings, &icon_filenames)
.with_context(|| "Failed to create Info.plist")?;
for bin in settings.binaries() {
let bin_path = settings.binary_path(bin);
fs_utils::copy_file(&bin_path, &app_bundle_path.join(bin.name()))
.with_context(|| format!("Failed to copy binary from {bin_path:?}"))?;
}
Ok(vec![app_bundle_path])
}
/// Generate the icon files and store them under the `bundle_dir`.
fn generate_icon_files(bundle_dir: &Path, settings: &Settings) -> crate::Result<Vec<String>> {
let mut filenames = Vec::new();
{
let mut get_dest_path = |width: u32, height: u32, is_retina: bool| {
let filename = format!(
"icon_{}x{}{}.png",
width,
height,
if is_retina { "@2x" } else { "" }
);
let path = bundle_dir.join(&filename);
filenames.push(filename);
path
};
let mut sizes = BTreeSet::new();
// Prefer PNG files.
for icon_path in settings.icon_files() {
let icon_path = icon_path?;
if icon_path.extension() != Some(OsStr::new("png")) {
continue;
}
let decoder = PngDecoder::new(BufReader::new(File::open(&icon_path)?))?;
let width = decoder.dimensions().0;
let height = decoder.dimensions().1;
let is_retina = utils::is_retina(&icon_path);
if !sizes.contains(&(width, height, is_retina)) {
sizes.insert((width, height, is_retina));
let dest_path = get_dest_path(width, height, is_retina);
fs_utils::copy_file(&icon_path, &dest_path)?;
}
}
// Fall back to non-PNG files for any missing sizes.
for icon_path in settings.icon_files() {
let icon_path = icon_path?;
if icon_path.extension() == Some(OsStr::new("png")) {
continue;
} else if icon_path.extension() == Some(OsStr::new("icns")) {
let icon_family = icns::IconFamily::read(File::open(&icon_path)?)?;
for icon_type in icon_family.available_icons() {
let width = icon_type.screen_width();
let height = icon_type.screen_height();
let is_retina = icon_type.pixel_density() > 1;
if !sizes.contains(&(width, height, is_retina)) {
sizes.insert((width, height, is_retina));
let dest_path = get_dest_path(width, height, is_retina);
let icon = icon_family.get_icon_with_type(icon_type)?;
icon.write_png(File::create(dest_path)?)?;
}
}
} else {
let icon = image::open(&icon_path)?;
let (width, height) = icon.dimensions();
let is_retina = utils::is_retina(&icon_path);
if !sizes.contains(&(width, height, is_retina)) {
sizes.insert((width, height, is_retina));
let dest_path = get_dest_path(width, height, is_retina);
icon.write_to(
&mut fs_utils::create_file(&dest_path)?,
image::ImageFormat::Png,
)?;
}
}
}
}
Ok(filenames)
}
/// Generates the Info.plist file
fn generate_info_plist(
bundle_dir: &Path,
settings: &Settings,
icon_filenames: &[String],
) -> crate::Result<()> {
let file = &mut fs_utils::create_file(&bundle_dir.join("Info.plist"))?;
writeln!(
file,
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \
\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n\
<plist version=\"1.0\">\n\
<dict>"
)?;
writeln!(
file,
" <key>CFBundleIdentifier</key>\n <string>{}</string>",
settings.bundle_identifier()
)?;
writeln!(
file,
" <key>CFBundleDisplayName</key>\n <string>{}</string>",
settings.product_name()
)?;
writeln!(
file,
" <key>CFBundleName</key>\n <string>{}</string>",
settings.product_name()
)?;
writeln!(
file,
" <key>CFBundleExecutable</key>\n <string>{}</string>",
settings.main_binary_name()?
)?;
writeln!(
file,
" <key>CFBundleVersion</key>\n <string>{}</string>",
settings
.ios()
.bundle_version
.as_deref()
.unwrap_or_else(|| settings.version_string())
)?;
writeln!(
file,
" <key>CFBundleShortVersionString</key>\n <string>{}</string>",
settings.version_string()
)?;
writeln!(
file,
" <key>CFBundleDevelopmentRegion</key>\n <string>en_US</string>"
)?;
if !icon_filenames.is_empty() {
writeln!(file, " <key>CFBundleIconFiles</key>\n <array>")?;
for filename in icon_filenames {
writeln!(file, " <string>{filename}</string>")?;
}
writeln!(file, " </array>")?;
}
writeln!(file, " <key>LSRequiresIPhoneOS</key>\n <true/>")?;
writeln!(file, "</dict>\n</plist>")?;
file.flush()?;
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-bundler/src/bundle/macos/icon.rs | crates/tauri-bundler/src/bundle/macos/icon.rs | // Copyright 2016-2019 Cargo-Bundle developers <https://github.com/burtonageo/cargo-bundle>
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::bundle::Settings;
use crate::utils::{self, fs_utils};
use std::{
cmp::min,
ffi::OsStr,
fs::{self, File},
io::{self, BufWriter},
path::{Path, PathBuf},
};
use image::GenericImageView;
// Given a list of icon files, try to produce an ICNS file in the out_dir
// and return the path to it. Returns `Ok(None)` if no usable icons
// were provided.
pub fn create_icns_file(out_dir: &Path, settings: &Settings) -> crate::Result<Option<PathBuf>> {
if settings.icon_files().count() == 0 {
return Ok(None);
}
// If one of the icon files is already an ICNS file, just use that.
for icon_path in settings.icon_files() {
let icon_path = icon_path?;
if icon_path.extension() == Some(OsStr::new("icns")) {
let mut dest_path = out_dir.to_path_buf();
dest_path.push(icon_path.file_name().expect("Could not get icon filename"));
fs_utils::copy_file(&icon_path, &dest_path)?;
return Ok(Some(dest_path));
}
}
// Otherwise, read available images and pack them into a new ICNS file.
let mut family = icns::IconFamily::new();
fn add_icon_to_family(
icon: image::DynamicImage,
density: u32,
family: &mut icns::IconFamily,
) -> io::Result<()> {
// Try to add this image to the icon family. Ignore images whose sizes
// don't map to any ICNS icon type; print warnings and skip images that
// fail to encode.
match icns::IconType::from_pixel_size_and_density(icon.width(), icon.height(), density) {
Some(icon_type) => {
if !family.has_icon_with_type(icon_type) {
let icon = make_icns_image(icon)?;
family.add_icon_with_type(&icon, icon_type)?;
}
Ok(())
}
None => Err(io::Error::new(
io::ErrorKind::InvalidData,
"No matching IconType",
)),
}
}
let mut images_to_resize: Vec<(image::DynamicImage, u32, u32)> = vec![];
for icon_path in settings.icon_files() {
let icon_path = icon_path?;
let icon = image::open(&icon_path)?;
let density = if utils::is_retina(&icon_path) { 2 } else { 1 };
let (w, h) = icon.dimensions();
let orig_size = min(w, h);
let next_size_down = 2f32.powf((orig_size as f32).log2().floor()) as u32;
if orig_size > next_size_down {
images_to_resize.push((icon, next_size_down, density));
} else {
add_icon_to_family(icon, density, &mut family)?;
}
}
for (icon, next_size_down, density) in images_to_resize {
let icon = icon.resize_exact(
next_size_down,
next_size_down,
image::imageops::FilterType::Lanczos3,
);
add_icon_to_family(icon, density, &mut family)?;
}
if !family.is_empty() {
fs::create_dir_all(out_dir)?;
let mut dest_path = out_dir.to_path_buf();
dest_path.push(settings.product_name());
dest_path.set_extension("icns");
let icns_file = BufWriter::new(File::create(&dest_path)?);
family.write(icns_file)?;
Ok(Some(dest_path))
} else {
Err(crate::Error::GenericError(
"No usable Icon files found".to_owned(),
))
}
}
// Converts an image::DynamicImage into an icns::Image.
fn make_icns_image(img: image::DynamicImage) -> io::Result<icns::Image> {
let pixel_format = match img.color() {
image::ColorType::Rgba8 => icns::PixelFormat::RGBA,
image::ColorType::Rgb8 => icns::PixelFormat::RGB,
image::ColorType::La8 => icns::PixelFormat::GrayAlpha,
image::ColorType::L8 => icns::PixelFormat::Gray,
_ => {
let msg = format!("unsupported ColorType: {:?}", img.color());
return Err(io::Error::new(io::ErrorKind::InvalidData, msg));
}
};
icns::Image::from_data(pixel_format, img.width(), img.height(), img.into_bytes())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-bundler/src/bundle/macos/app.rs | crates/tauri-bundler/src/bundle/macos/app.rs | // Copyright 2016-2019 Cargo-Bundle developers <https://github.com/burtonageo/cargo-bundle>
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
// A macOS application bundle package is laid out like:
//
// foobar.app # Actually a directory
// Contents # A further subdirectory
// Info.plist # An xml file containing the app's metadata
// MacOS # A directory to hold executable binary files
// foobar # The main binary executable of the app
// foobar_helper # A helper application, possibly providing a CLI
// Resources # Data files such as images, sounds, translations and nib files
// en.lproj # Folder containing english translation strings/data
// Frameworks # A directory containing private frameworks (shared libraries)
// ... # Any other optional files the developer wants to place here
//
// See https://developer.apple.com/go/?id=bundle-structure for a full
// explanation.
//
// Currently, cargo-bundle does not support Frameworks, nor does it support placing arbitrary
// files into the `Contents` directory of the bundle.
use super::{
icon::create_icns_file,
sign::{notarize, notarize_auth, notarize_without_stapling, sign, SignTarget},
};
use crate::{
bundle::settings::PlistKind,
error::{Context, ErrorExt, NotarizeAuthError},
utils::{fs_utils, CommandExt},
Error::GenericError,
Settings,
};
use std::{
ffi::OsStr,
fs,
path::{Path, PathBuf},
process::Command,
};
const NESTED_CODE_FOLDER: [&str; 6] = [
"MacOS",
"Frameworks",
"Plugins",
"Helpers",
"XPCServices",
"Libraries",
];
/// Bundles the project.
/// Returns a vector of PathBuf that shows where the .app was created.
pub fn bundle_project(settings: &Settings) -> crate::Result<Vec<PathBuf>> {
// we should use the bundle name (App name) as a MacOS standard.
// version or platform shouldn't be included in the App name.
let app_product_name = format!("{}.app", settings.product_name());
let app_bundle_path = settings
.project_out_directory()
.join("bundle/macos")
.join(&app_product_name);
log::info!(action = "Bundling"; "{} ({})", app_product_name, app_bundle_path.display());
if app_bundle_path.exists() {
fs::remove_dir_all(&app_bundle_path)
.fs_context("failed to remove old app bundle", &app_bundle_path)?;
}
let bundle_directory = app_bundle_path.join("Contents");
fs::create_dir_all(&bundle_directory)
.fs_context("failed to create bundle directory", &bundle_directory)?;
let resources_dir = bundle_directory.join("Resources");
let bin_dir = bundle_directory.join("MacOS");
let mut sign_paths = Vec::new();
let bundle_icon_file: Option<PathBuf> =
{ create_icns_file(&resources_dir, settings).with_context(|| "Failed to create app icon")? };
create_info_plist(&bundle_directory, bundle_icon_file, settings)
.with_context(|| "Failed to create Info.plist")?;
let framework_paths = copy_frameworks_to_bundle(&bundle_directory, settings)
.with_context(|| "Failed to bundle frameworks")?;
sign_paths.extend(framework_paths);
settings.copy_resources(&resources_dir)?;
let bin_paths = settings
.copy_binaries(&bin_dir)
.with_context(|| "Failed to copy external binaries")?;
sign_paths.extend(bin_paths.into_iter().map(|path| SignTarget {
path,
is_an_executable: true,
}));
let bin_paths = copy_binaries_to_bundle(&bundle_directory, settings)?;
sign_paths.extend(bin_paths.into_iter().map(|path| SignTarget {
path,
is_an_executable: true,
}));
copy_custom_files_to_bundle(&bundle_directory, settings)?;
if settings.no_sign() {
log::warn!("Skipping signing due to --no-sign flag.",);
} else if let Some(keychain) =
super::sign::keychain(settings.macos().signing_identity.as_deref())?
{
// Sign frameworks and sidecar binaries first, per apple, signing must be done inside out
// https://developer.apple.com/forums/thread/701514
sign_paths.push(SignTarget {
path: app_bundle_path.clone(),
is_an_executable: true,
});
// Remove extra attributes, which could cause codesign to fail
// https://developer.apple.com/library/archive/qa/qa1940/_index.html
remove_extra_attr(&app_bundle_path)?;
// sign application
sign(&keychain, sign_paths, settings)?;
// notarization is required for distribution
match notarize_auth() {
Ok(auth) => {
if settings.macos().skip_stapling {
notarize_without_stapling(&keychain, app_bundle_path.clone(), &auth)?;
} else {
notarize(&keychain, app_bundle_path.clone(), &auth)?;
}
}
Err(e) => {
if matches!(e, NotarizeAuthError::MissingTeamId) {
return Err(e.into());
} else {
log::warn!("skipping app notarization, {}", e.to_string());
}
}
}
}
Ok(vec![app_bundle_path])
}
fn remove_extra_attr(app_bundle_path: &Path) -> crate::Result<()> {
Command::new("xattr")
.arg("-crs")
.arg(app_bundle_path)
.output_ok()
.context("failed to remove extra attributes from app bundle")?;
Ok(())
}
// Copies the app's binaries to the bundle.
fn copy_binaries_to_bundle(
bundle_directory: &Path,
settings: &Settings,
) -> crate::Result<Vec<PathBuf>> {
let mut paths = Vec::new();
let dest_dir = bundle_directory.join("MacOS");
for bin in settings.binaries() {
let bin_path = settings.binary_path(bin);
let dest_path = dest_dir.join(bin.name());
fs_utils::copy_file(&bin_path, &dest_path)
.with_context(|| format!("Failed to copy binary from {bin_path:?}"))?;
paths.push(dest_path);
}
Ok(paths)
}
/// Copies user-defined files to the app under Contents.
fn copy_custom_files_to_bundle(bundle_directory: &Path, settings: &Settings) -> crate::Result<()> {
for (contents_path, path) in settings.macos().files.iter() {
if !path.try_exists()? {
return Err(GenericError(format!(
"Failed to copy {path:?} to {contents_path:?}. {path:?} does not exist."
)));
}
let contents_path = if contents_path.is_absolute() {
contents_path.strip_prefix("/").unwrap()
} else {
contents_path
};
if path.is_file() {
fs_utils::copy_file(path, &bundle_directory.join(contents_path))
.with_context(|| format!("Failed to copy file {path:?} to {contents_path:?}"))?;
} else if path.is_dir() {
fs_utils::copy_dir(path, &bundle_directory.join(contents_path))
.with_context(|| format!("Failed to copy directory {path:?} to {contents_path:?}"))?;
} else {
return Err(GenericError(format!(
"{path:?} is not a file or directory."
)));
}
}
Ok(())
}
// Creates the Info.plist file.
fn create_info_plist(
bundle_dir: &Path,
bundle_icon_file: Option<PathBuf>,
settings: &Settings,
) -> crate::Result<()> {
let mut plist = plist::Dictionary::new();
plist.insert("CFBundleDevelopmentRegion".into(), "English".into());
plist.insert("CFBundleDisplayName".into(), settings.product_name().into());
plist.insert(
"CFBundleExecutable".into(),
settings.main_binary_name()?.into(),
);
if let Some(path) = bundle_icon_file {
plist.insert(
"CFBundleIconFile".into(),
path
.file_name()
.expect("No file name")
.to_string_lossy()
.into_owned()
.into(),
);
}
plist.insert(
"CFBundleIdentifier".into(),
settings.bundle_identifier().into(),
);
plist.insert("CFBundleInfoDictionaryVersion".into(), "6.0".into());
if let Some(bundle_name) = settings
.macos()
.bundle_name
.as_deref()
.unwrap_or_else(|| settings.product_name())
.into()
{
plist.insert("CFBundleName".into(), bundle_name.into());
}
plist.insert("CFBundlePackageType".into(), "APPL".into());
plist.insert(
"CFBundleShortVersionString".into(),
settings.version_string().into(),
);
plist.insert(
"CFBundleVersion".into(),
settings
.macos()
.bundle_version
.as_deref()
.unwrap_or_else(|| settings.version_string())
.into(),
);
plist.insert("CSResourcesFileMapped".into(), true.into());
if let Some(category) = settings.app_category() {
plist.insert(
"LSApplicationCategoryType".into(),
category.macos_application_category_type().into(),
);
}
if let Some(version) = settings.macos().minimum_system_version.clone() {
plist.insert("LSMinimumSystemVersion".into(), version.into());
}
if let Some(associations) = settings.file_associations() {
let exported_associations = associations
.iter()
.filter_map(|association| {
association.exported_type.as_ref().map(|exported_type| {
let mut dict = plist::Dictionary::new();
dict.insert(
"UTTypeIdentifier".into(),
exported_type.identifier.clone().into(),
);
if let Some(description) = &association.description {
dict.insert("UTTypeDescription".into(), description.clone().into());
}
if let Some(conforms_to) = &exported_type.conforms_to {
dict.insert(
"UTTypeConformsTo".into(),
plist::Value::Array(conforms_to.iter().map(|s| s.clone().into()).collect()),
);
}
let mut specification = plist::Dictionary::new();
specification.insert(
"public.filename-extension".into(),
plist::Value::Array(
association
.ext
.iter()
.map(|s| s.to_string().into())
.collect(),
),
);
if let Some(mime_type) = &association.mime_type {
specification.insert("public.mime-type".into(), mime_type.clone().into());
}
dict.insert("UTTypeTagSpecification".into(), specification.into());
plist::Value::Dictionary(dict)
})
})
.collect::<Vec<_>>();
if !exported_associations.is_empty() {
plist.insert(
"UTExportedTypeDeclarations".into(),
plist::Value::Array(exported_associations),
);
}
plist.insert(
"CFBundleDocumentTypes".into(),
plist::Value::Array(
associations
.iter()
.map(|association| {
let mut dict = plist::Dictionary::new();
if !association.ext.is_empty() {
dict.insert(
"CFBundleTypeExtensions".into(),
plist::Value::Array(
association
.ext
.iter()
.map(|ext| ext.to_string().into())
.collect(),
),
);
}
if let Some(content_types) = &association.content_types {
dict.insert(
"LSItemContentTypes".into(),
plist::Value::Array(content_types.iter().map(|s| s.to_string().into()).collect()),
);
}
dict.insert(
"CFBundleTypeName".into(),
association
.name
.as_ref()
.unwrap_or(&association.ext[0].0)
.to_string()
.into(),
);
dict.insert(
"CFBundleTypeRole".into(),
association.role.to_string().into(),
);
dict.insert("LSHandlerRank".into(), association.rank.to_string().into());
plist::Value::Dictionary(dict)
})
.collect(),
),
);
}
if let Some(protocols) = settings.deep_link_protocols() {
plist.insert(
"CFBundleURLTypes".into(),
plist::Value::Array(
protocols
.iter()
.filter(|p| !p.schemes.is_empty())
.map(|protocol| {
let mut dict = plist::Dictionary::new();
dict.insert(
"CFBundleURLSchemes".into(),
plist::Value::Array(
protocol
.schemes
.iter()
.map(|s| s.to_string().into())
.collect(),
),
);
dict.insert(
"CFBundleURLName".into(),
protocol
.name
.clone()
.unwrap_or(format!(
"{} {}",
settings.bundle_identifier(),
protocol.schemes[0]
))
.into(),
);
dict.insert("CFBundleTypeRole".into(), protocol.role.to_string().into());
plist::Value::Dictionary(dict)
})
.collect(),
),
);
}
plist.insert("LSRequiresCarbon".into(), true.into());
plist.insert("NSHighResolutionCapable".into(), true.into());
if let Some(copyright) = settings.copyright_string() {
plist.insert("NSHumanReadableCopyright".into(), copyright.into());
}
if let Some(exception_domain) = settings.macos().exception_domain.clone() {
let mut security = plist::Dictionary::new();
let mut domain = plist::Dictionary::new();
domain.insert("NSExceptionAllowsInsecureHTTPLoads".into(), true.into());
domain.insert("NSIncludesSubdomains".into(), true.into());
let mut exception_domains = plist::Dictionary::new();
exception_domains.insert(exception_domain, domain.into());
security.insert("NSExceptionDomains".into(), exception_domains.into());
plist.insert("NSAppTransportSecurity".into(), security.into());
}
if let Some(user_plist) = &settings.macos().info_plist {
let user_plist = match user_plist {
PlistKind::Path(path) => plist::Value::from_file(path)?,
PlistKind::Plist(value) => value.clone(),
};
if let Some(dict) = user_plist.into_dictionary() {
for (key, value) in dict {
plist.insert(key, value);
}
}
}
plist::Value::Dictionary(plist).to_file_xml(bundle_dir.join("Info.plist"))?;
Ok(())
}
// Copies the framework under `{src_dir}/{framework}.framework` to `{dest_dir}/{framework}.framework`.
fn copy_framework_from(dest_dir: &Path, framework: &str, src_dir: &Path) -> crate::Result<bool> {
let src_name = format!("{framework}.framework");
let src_path = src_dir.join(&src_name);
if src_path.exists() {
fs_utils::copy_dir(&src_path, &dest_dir.join(&src_name))?;
Ok(true)
} else {
Ok(false)
}
}
// Copies the macOS application bundle frameworks to the .app
fn copy_frameworks_to_bundle(
bundle_directory: &Path,
settings: &Settings,
) -> crate::Result<Vec<SignTarget>> {
let mut paths = Vec::new();
let frameworks = settings.macos().frameworks.clone().unwrap_or_default();
if frameworks.is_empty() {
return Ok(paths);
}
let dest_dir = bundle_directory.join("Frameworks");
fs::create_dir_all(&dest_dir).fs_context("failed to create Frameworks directory", &dest_dir)?;
for framework in frameworks.iter() {
if framework.ends_with(".framework") {
let src_path = PathBuf::from(framework);
let src_name = src_path
.file_name()
.expect("Couldn't get framework filename");
let dest_path = dest_dir.join(src_name);
fs_utils::copy_dir(&src_path, &dest_path)?;
add_framework_sign_path(&src_path, &dest_path, &mut paths);
continue;
} else if framework.ends_with(".dylib") {
let src_path = PathBuf::from(framework);
if !src_path.exists() {
return Err(GenericError(format!("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);
fs_utils::copy_file(&src_path, &dest_path)?;
paths.push(SignTarget {
path: dest_path,
is_an_executable: false,
});
continue;
} else if framework.contains('/') {
return Err(GenericError(format!(
"Framework path should have .framework extension: {framework}"
)));
}
if let Some(home_dir) = dirs::home_dir() {
if copy_framework_from(&dest_dir, framework, &home_dir.join("Library/Frameworks/"))? {
continue;
}
}
if copy_framework_from(&dest_dir, framework, &PathBuf::from("/Library/Frameworks/"))?
|| copy_framework_from(
&dest_dir,
framework,
&PathBuf::from("/Network/Library/Frameworks/"),
)?
{
continue;
}
return Err(GenericError(format!(
"Could not locate framework: {framework}"
)));
}
Ok(paths)
}
/// Recursively add framework's sign paths.
/// If the framework has multiple versions, it will sign "Current" version by default.
fn add_framework_sign_path(
framework_root: &Path,
dest_path: &Path,
sign_paths: &mut Vec<SignTarget>,
) {
if framework_root.join("Versions/Current").exists() {
add_nested_code_sign_path(
&framework_root.join("Versions/Current"),
&dest_path.join("Versions/Current"),
sign_paths,
);
} else {
add_nested_code_sign_path(framework_root, dest_path, sign_paths);
}
sign_paths.push(SignTarget {
path: dest_path.into(),
is_an_executable: false,
});
}
/// Recursively add executable bundle's sign path (.xpc, .app).
fn add_executable_bundle_sign_path(
bundle_root: &Path,
dest_path: &Path,
sign_paths: &mut Vec<SignTarget>,
) {
if bundle_root.join("Contents").exists() {
add_nested_code_sign_path(
&bundle_root.join("Contents"),
&dest_path.join("Contents"),
sign_paths,
);
} else {
add_nested_code_sign_path(bundle_root, dest_path, sign_paths);
}
sign_paths.push(SignTarget {
path: dest_path.into(),
is_an_executable: true,
});
}
fn add_nested_code_sign_path(src_path: &Path, dest_path: &Path, sign_paths: &mut Vec<SignTarget>) {
for folder_name in NESTED_CODE_FOLDER.iter() {
let src_folder_path = src_path.join(folder_name);
let dest_folder_path = dest_path.join(folder_name);
if src_folder_path.exists() {
for entry in walkdir::WalkDir::new(src_folder_path)
.min_depth(1)
.max_depth(1)
.into_iter()
.filter_map(|e| e.ok())
{
if entry.path_is_symlink() || entry.file_name().to_string_lossy().starts_with('.') {
continue;
}
let dest_path = dest_folder_path.join(entry.file_name());
let ext = entry.path().extension();
if entry.path().is_dir() {
// Bundles, like .app, .framework, .xpc
if ext == Some(OsStr::new("framework")) {
add_framework_sign_path(&entry.clone().into_path(), &dest_path, sign_paths);
} else if ext == Some(OsStr::new("xpc")) || ext == Some(OsStr::new("app")) {
add_executable_bundle_sign_path(&entry.clone().into_path(), &dest_path, sign_paths);
}
} else if entry.path().is_file() {
// Binaries, like .dylib, Mach-O executables
if ext == Some(OsStr::new("dylib")) {
sign_paths.push(SignTarget {
path: dest_path,
is_an_executable: false,
});
} else if ext.is_none() {
sign_paths.push(SignTarget {
path: dest_path,
is_an_executable: true,
});
}
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::bundle::{BundleSettings, MacOsSettings, PackageSettings, SettingsBuilder};
use std::{
collections::HashMap,
fs,
path::{Path, PathBuf},
};
/// Helper that builds a `Settings` instance and bundle directory for tests.
/// It receives a mapping of bundle-relative paths to source paths and
/// returns the generated bundle directory and settings.
fn create_test_bundle(
project_dir: &Path,
files: HashMap<PathBuf, PathBuf>,
) -> (PathBuf, crate::bundle::Settings) {
let macos_settings = MacOsSettings {
files,
..Default::default()
};
let settings = SettingsBuilder::new()
.project_out_directory(project_dir)
.package_settings(PackageSettings {
product_name: "TestApp".into(),
version: "0.1.0".into(),
description: "test".into(),
homepage: None,
authors: None,
default_run: None,
})
.bundle_settings(BundleSettings {
macos: macos_settings,
..Default::default()
})
.target("x86_64-apple-darwin".into())
.build()
.expect("failed to build settings");
let bundle_dir = project_dir.join("TestApp.app/Contents");
fs::create_dir_all(&bundle_dir).expect("failed to create bundle dir");
(bundle_dir, settings)
}
#[test]
fn test_copy_custom_file_to_bundle_file() {
let tmp_dir = tempfile::tempdir().expect("failed to create temp dir");
// Prepare a single file to copy.
let src_file = tmp_dir.path().join("sample.txt");
fs::write(&src_file, b"hello tauri").expect("failed to write sample file");
let files_map = HashMap::from([(PathBuf::from("Resources/sample.txt"), src_file.clone())]);
let (bundle_dir, settings) = create_test_bundle(tmp_dir.path(), files_map);
copy_custom_files_to_bundle(&bundle_dir, &settings)
.expect("copy_custom_files_to_bundle failed");
let dest_file = bundle_dir.join("Resources/sample.txt");
assert!(dest_file.exists() && dest_file.is_file());
assert_eq!(fs::read_to_string(dest_file).unwrap(), "hello tauri");
}
#[test]
fn test_copy_custom_file_to_bundle_dir() {
let tmp_dir = tempfile::tempdir().expect("failed to create temp dir");
// Create a source directory with a nested file.
let src_dir = tmp_dir.path().join("assets");
fs::create_dir_all(&src_dir).expect("failed to create assets directory");
let nested_file = src_dir.join("nested.txt");
fs::write(&nested_file, b"nested").expect("failed to write nested file");
let files_map = HashMap::from([(PathBuf::from("MyAssets"), src_dir.clone())]);
let (bundle_dir, settings) = create_test_bundle(tmp_dir.path(), files_map);
copy_custom_files_to_bundle(&bundle_dir, &settings)
.expect("copy_custom_files_to_bundle failed");
let dest_nested_file = bundle_dir.join("MyAssets/nested.txt");
assert!(
dest_nested_file.exists(),
"{dest_nested_file:?} does not exist"
);
assert!(
dest_nested_file.is_file(),
"{dest_nested_file:?} is not a file"
);
assert_eq!(
fs::read_to_string(dest_nested_file).unwrap().trim(),
"nested"
);
}
#[test]
fn test_copy_custom_files_to_bundle_missing_source() {
let tmp_dir = tempfile::tempdir().expect("failed to create temp dir");
// Intentionally reference a non-existent path.
let missing_path = tmp_dir.path().join("does_not_exist.txt");
let files_map = HashMap::from([(PathBuf::from("Missing.txt"), missing_path)]);
let (bundle_dir, settings) = create_test_bundle(tmp_dir.path(), files_map);
let result = copy_custom_files_to_bundle(&bundle_dir, &settings);
assert!(result.is_err());
assert!(result.err().unwrap().to_string().contains("does not exist"));
}
#[test]
fn test_copy_custom_files_to_bundle_invalid_source() {
let tmp_dir = tempfile::tempdir().expect("failed to create temp dir");
let files_map = HashMap::from([(PathBuf::from("Invalid.txt"), PathBuf::from("///"))]);
let (bundle_dir, settings) = create_test_bundle(tmp_dir.path(), files_map);
let result = copy_custom_files_to_bundle(&bundle_dir, &settings);
assert!(result.is_err());
assert!(result
.err()
.unwrap()
.to_string()
.contains("Failed to copy directory"));
}
#[test]
fn test_copy_custom_files_to_bundle_dev_null() {
let tmp_dir = tempfile::tempdir().expect("failed to create temp dir");
let files_map = HashMap::from([(PathBuf::from("Invalid.txt"), PathBuf::from("/dev/null"))]);
let (bundle_dir, settings) = create_test_bundle(tmp_dir.path(), files_map);
let result = copy_custom_files_to_bundle(&bundle_dir, &settings);
assert!(result.is_err());
assert!(result
.err()
.unwrap()
.to_string()
.contains("is not a file or directory."));
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-bundler/src/bundle/macos/sign.rs | crates/tauri-bundler/src/bundle/macos/sign.rs | // Copyright 2016-2019 Cargo-Bundle developers <https://github.com/burtonageo/cargo-bundle>
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{
env::{var, var_os},
ffi::OsString,
path::PathBuf,
};
use crate::{error::NotarizeAuthError, Entitlements, Settings};
pub struct SignTarget {
pub path: PathBuf,
pub is_an_executable: bool,
}
pub fn keychain(identity: Option<&str>) -> crate::Result<Option<tauri_macos_sign::Keychain>> {
if let (Some(certificate_encoded), Some(certificate_password)) = (
var_os("APPLE_CERTIFICATE"),
var_os("APPLE_CERTIFICATE_PASSWORD"),
) {
// import user certificate - useful for for CI build
let keychain =
tauri_macos_sign::Keychain::with_certificate(&certificate_encoded, &certificate_password)
.map_err(Box::new)?;
if let Some(identity) = identity {
let certificate_identity = keychain.signing_identity();
if !certificate_identity.contains(identity) {
return Err(crate::Error::GenericError(format!(
"certificate from APPLE_CERTIFICATE \"{certificate_identity}\" environment variable does not match provided identity \"{identity}\""
)));
}
}
Ok(Some(keychain))
} else if let Some(identity) = identity {
Ok(Some(tauri_macos_sign::Keychain::with_signing_identity(
identity,
)))
} else {
Ok(None)
}
}
pub fn sign(
keychain: &tauri_macos_sign::Keychain,
targets: Vec<SignTarget>,
settings: &Settings,
) -> crate::Result<()> {
log::info!(action = "Signing"; "with identity \"{}\"", keychain.signing_identity());
for target in targets {
let (entitlements_path, _temp_file) = match settings.macos().entitlements.as_ref() {
Some(Entitlements::Path(path)) => (Some(path.to_owned()), None),
Some(Entitlements::Plist(plist)) => {
let mut temp_file = tempfile::NamedTempFile::new()?;
plist::to_writer_xml(temp_file.as_file_mut(), &plist)?;
(Some(temp_file.path().to_path_buf()), Some(temp_file))
}
None => (None, None),
};
keychain
.sign(
&target.path,
entitlements_path.as_deref(),
target.is_an_executable && settings.macos().hardened_runtime,
)
.map_err(Box::new)?;
}
Ok(())
}
pub fn notarize(
keychain: &tauri_macos_sign::Keychain,
app_bundle_path: PathBuf,
credentials: &tauri_macos_sign::AppleNotarizationCredentials,
) -> crate::Result<()> {
tauri_macos_sign::notarize(keychain, &app_bundle_path, credentials)
.map_err(Box::new)
.map_err(Into::into)
}
pub fn notarize_without_stapling(
keychain: &tauri_macos_sign::Keychain,
app_bundle_path: PathBuf,
credentials: &tauri_macos_sign::AppleNotarizationCredentials,
) -> crate::Result<()> {
tauri_macos_sign::notarize_without_stapling(keychain, &app_bundle_path, credentials)
.map_err(Box::new)
.map_err(Into::into)
}
pub fn notarize_auth() -> Result<tauri_macos_sign::AppleNotarizationCredentials, NotarizeAuthError>
{
match (
var_os("APPLE_ID"),
var_os("APPLE_PASSWORD"),
var_os("APPLE_TEAM_ID"),
) {
(Some(apple_id), Some(password), Some(team_id)) => {
Ok(tauri_macos_sign::AppleNotarizationCredentials::AppleId {
apple_id,
password,
team_id,
})
}
(Some(_apple_id), Some(_password), None) => Err(NotarizeAuthError::MissingTeamId),
_ => {
match (
var_os("APPLE_API_KEY"),
var_os("APPLE_API_ISSUER"),
var("APPLE_API_KEY_PATH"),
) {
(Some(key_id), Some(issuer), Ok(key_path)) => {
Ok(tauri_macos_sign::AppleNotarizationCredentials::ApiKey {
key_id,
key: tauri_macos_sign::ApiKey::Path(key_path.into()),
issuer,
})
}
(Some(key_id), Some(issuer), Err(_)) => {
let mut api_key_file_name = OsString::from("AuthKey_");
api_key_file_name.push(&key_id);
api_key_file_name.push(".p8");
let mut key_path = None;
let mut search_paths = vec!["./private_keys".into()];
if let Some(home_dir) = dirs::home_dir() {
search_paths.push(home_dir.join("private_keys"));
search_paths.push(home_dir.join(".private_keys"));
search_paths.push(home_dir.join(".appstoreconnect").join("private_keys"));
}
for folder in search_paths {
if let Some(path) = find_api_key(folder, &api_key_file_name) {
key_path = Some(path);
break;
}
}
if let Some(key_path) = key_path {
Ok(tauri_macos_sign::AppleNotarizationCredentials::ApiKey {
key_id,
key: tauri_macos_sign::ApiKey::Path(key_path),
issuer,
})
} else {
Err(NotarizeAuthError::MissingApiKey {
file_name: api_key_file_name.to_string_lossy().into_owned(),
})
}
}
_ => Err(NotarizeAuthError::MissingCredentials),
}
}
}
}
fn find_api_key(folder: PathBuf, file_name: &OsString) -> Option<PathBuf> {
let path = folder.join(file_name);
if path.exists() {
Some(path)
} else {
None
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-bundler/src/bundle/macos/mod.rs | crates/tauri-bundler/src/bundle/macos/mod.rs | // Copyright 2016-2019 Cargo-Bundle developers <https://github.com/burtonageo/cargo-bundle>
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
pub mod app;
pub mod dmg;
pub mod icon;
pub mod ios;
pub mod sign;
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-bundler/src/bundle/macos/dmg/mod.rs | crates/tauri-bundler/src/bundle/macos/dmg/mod.rs | // Copyright 2016-2019 Cargo-Bundle developers <https://github.com/burtonageo/cargo-bundle>
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use super::{app, icon::create_icns_file};
use crate::{
bundle::{settings::Arch, Bundle},
error::{Context, ErrorExt},
utils::CommandExt,
PackageType, Settings,
};
use std::{
env,
fs::{self, write},
path::PathBuf,
process::{Command, Stdio},
};
pub struct Bundled {
pub dmg: Vec<PathBuf>,
pub app: Vec<PathBuf>,
}
/// Bundles the project.
/// Returns a vector of PathBuf that shows where the DMG was created.
pub fn bundle_project(settings: &Settings, bundles: &[Bundle]) -> crate::Result<Bundled> {
// generate the .app bundle if needed
let app_bundle_paths = if !bundles
.iter()
.any(|bundle| bundle.package_type == PackageType::MacOsBundle)
{
app::bundle_project(settings)?
} else {
Vec::new()
};
// get the target path
let output_path = settings.project_out_directory().join("bundle/dmg");
let package_base_name = format!(
"{}_{}_{}",
settings.product_name(),
settings.version_string(),
match settings.binary_arch() {
Arch::X86_64 => "x64",
Arch::AArch64 => "aarch64",
Arch::Universal => "universal",
target => {
return Err(crate::Error::ArchError(format!(
"Unsupported architecture: {target:?}"
)));
}
}
);
let dmg_name = format!("{}.dmg", &package_base_name);
let dmg_path = output_path.join(&dmg_name);
let product_name = settings.product_name();
let bundle_file_name = format!("{product_name}.app");
let bundle_dir = settings.project_out_directory().join("bundle/macos");
let support_directory_path = output_path
.parent()
.unwrap()
.join("share/create-dmg/support");
for path in &[&support_directory_path, &output_path] {
if path.exists() {
fs::remove_dir_all(path).fs_context("failed to remove old dmg", path.to_path_buf())?;
}
fs::create_dir_all(path).fs_context("failed to create output directory", path.to_path_buf())?;
}
// create paths for script
let bundle_script_path = output_path.join("bundle_dmg.sh");
log::info!(action = "Bundling"; "{} ({})", dmg_name, dmg_path.display());
// write the scripts
write(&bundle_script_path, include_str!("./bundle_dmg"))?;
write(
support_directory_path.join("template.applescript"),
include_str!("./template.applescript"),
)?;
write(
support_directory_path.join("eula-resources-template.xml"),
include_str!("./eula-resources-template.xml"),
)?;
// chmod script for execution
Command::new("chmod")
.arg("777")
.arg(&bundle_script_path)
.current_dir(&output_path)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output()
.expect("Failed to chmod script");
let dmg_settings = settings.dmg();
let app_position = &dmg_settings.app_position;
let application_folder_position = &dmg_settings.application_folder_position;
let window_size = &dmg_settings.window_size;
let app_position_x = app_position.x.to_string();
let app_position_y = app_position.y.to_string();
let application_folder_position_x = application_folder_position.x.to_string();
let application_folder_position_y = application_folder_position.y.to_string();
let window_size_width = window_size.width.to_string();
let window_size_height = window_size.height.to_string();
let mut bundle_dmg_cmd = Command::new(&bundle_script_path);
bundle_dmg_cmd.args([
"--volname",
product_name,
"--icon",
&bundle_file_name,
&app_position_x,
&app_position_y,
"--app-drop-link",
&application_folder_position_x,
&application_folder_position_y,
"--window-size",
&window_size_width,
&window_size_height,
"--hide-extension",
&bundle_file_name,
]);
let window_position = dmg_settings
.window_position
.as_ref()
.map(|position| (position.x.to_string(), position.y.to_string()));
if let Some(window_position) = &window_position {
bundle_dmg_cmd.arg("--window-pos");
bundle_dmg_cmd.arg(&window_position.0);
bundle_dmg_cmd.arg(&window_position.1);
}
let background_path = if let Some(background_path) = &dmg_settings.background {
Some(env::current_dir()?.join(background_path))
} else {
None
};
if let Some(background_path) = &background_path {
bundle_dmg_cmd.arg("--background");
bundle_dmg_cmd.arg(background_path);
}
let icns_icon_path = create_icns_file(&output_path, settings)?;
if let Some(icon) = &icns_icon_path {
bundle_dmg_cmd.arg("--volicon");
bundle_dmg_cmd.arg(icon);
}
let license_path = if let Some(license_path) = settings.license_file() {
Some(env::current_dir()?.join(license_path))
} else {
None
};
if let Some(license_path) = &license_path {
bundle_dmg_cmd.arg("--eula");
bundle_dmg_cmd.arg(license_path);
}
// Issue #592 - Building MacOS dmg files on CI
// https://github.com/tauri-apps/tauri/issues/592
if env::var_os("TAURI_BUNDLER_DMG_IGNORE_CI").unwrap_or_default() != "true" {
if let Some(value) = env::var_os("CI") {
if value == "true" {
bundle_dmg_cmd.arg("--skip-jenkins");
}
}
}
log::info!(action = "Running"; "bundle_dmg.sh");
// execute the bundle script
bundle_dmg_cmd
.current_dir(bundle_dir.clone())
.args(vec![dmg_name.as_str(), bundle_file_name.as_str()])
.output_ok()
.context("error running bundle_dmg.sh")?;
fs::rename(bundle_dir.join(dmg_name), dmg_path.clone())?;
// Sign DMG if needed
// skipping self-signing DMGs https://github.com/tauri-apps/tauri/issues/12288
let identity = settings.macos().signing_identity.as_deref();
if !settings.no_sign() && identity != Some("-") {
if let Some(keychain) = super::sign::keychain(identity)? {
super::sign::sign(
&keychain,
vec![super::sign::SignTarget {
path: dmg_path.clone(),
is_an_executable: false,
}],
settings,
)?;
}
}
Ok(Bundled {
dmg: vec![dmg_path],
app: app_bundle_paths,
})
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-macos-sign/src/keychain.rs | crates/tauri-macos-sign/src/keychain.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{
ffi::OsString,
path::{Path, PathBuf},
process::Command,
};
use crate::{assert_command, CommandExt, Error, Result};
use rand::distr::{Alphanumeric, SampleString};
mod identity;
pub use identity::Team;
pub enum SigningIdentity {
Team(Team),
Identifier(String),
}
pub struct Keychain {
// none means the default keychain must be used
path: Option<PathBuf>,
signing_identity: SigningIdentity,
}
impl Drop for Keychain {
fn drop(&mut self) {
if let Some(path) = &self.path {
let _ = Command::new("security")
.arg("delete-keychain")
.arg(path)
.piped();
}
}
}
impl Keychain {
/// Use a certificate in the default keychain.
pub fn with_signing_identity(identity: impl Into<String>) -> Self {
Self {
path: None,
signing_identity: SigningIdentity::Identifier(identity.into()),
}
}
/// Import certificate from base64 string.
/// certificate_encoded is the p12 certificate base64 encoded.
/// By example you can use; openssl base64 -in MyCertificate.p12 -out MyCertificate-base64.txt
/// Then use the value of the base64 as `certificate_encoded`.
/// You need to set certificate_password to the password you set when you exported your certificate.
/// <https://help.apple.com/xcode/mac/current/#/dev154b28f09> see: `Export a signing certificate`
pub fn with_certificate(
certificate_encoded: &OsString,
certificate_password: &OsString,
) -> Result<Self> {
let tmp_dir = tempfile::tempdir().map_err(Error::TempDir)?;
let cert_path = tmp_dir.path().join("cert.p12");
super::decode_base64(certificate_encoded, &cert_path)?;
Self::with_certificate_file(&cert_path, certificate_password)
}
pub fn with_certificate_file(cert_path: &Path, certificate_password: &OsString) -> Result<Self> {
let home_dir = dirs::home_dir().ok_or(Error::ResolveHomeDir)?;
let keychain_path = home_dir.join("Library").join("Keychains").join(format!(
"{}.keychain-db",
Alphanumeric.sample_string(&mut rand::rng(), 16)
));
let keychain_password = Alphanumeric.sample_string(&mut rand::rng(), 16);
let keychain_list_output = Command::new("security")
.args(["list-keychain", "-d", "user"])
.output()
.map_err(|e| Error::CommandFailed {
command: "security list-keychain -d user".to_string(),
error: e,
})?;
assert_command(
Command::new("security")
.args(["create-keychain", "-p", &keychain_password])
.arg(&keychain_path)
.piped(),
"failed to create keychain",
)
.map_err(|error| Error::CommandFailed {
command: "security create-Keychain".to_string(),
error,
})?;
assert_command(
Command::new("security")
.args(["unlock-keychain", "-p", &keychain_password])
.arg(&keychain_path)
.piped(),
"failed to set unlock keychain",
)
.map_err(|error| Error::CommandFailed {
command: "security unlock-keychain".to_string(),
error,
})?;
assert_command(
Command::new("security")
.arg("import")
.arg(cert_path)
.arg("-P")
.arg(certificate_password)
.args([
"-T",
"/usr/bin/codesign",
"-T",
"/usr/bin/pkgbuild",
"-T",
"/usr/bin/productbuild",
])
.arg("-k")
.arg(&keychain_path)
.piped(),
"failed to import keychain certificate",
)
.map_err(|error| Error::CommandFailed {
command: "security import".to_string(),
error,
})?;
assert_command(
Command::new("security")
.args(["set-keychain-settings", "-t", "3600", "-u"])
.arg(&keychain_path)
.piped(),
"failed to set keychain settings",
)
.map_err(|error| Error::CommandFailed {
command: "security set-keychain-settings".to_string(),
error,
})?;
assert_command(
Command::new("security")
.args([
"set-key-partition-list",
"-S",
"apple-tool:,apple:,codesign:",
"-s",
"-k",
&keychain_password,
])
.arg(&keychain_path)
.piped(),
"failed to set keychain settings",
)
.map_err(|error| Error::CommandFailed {
command: "security set-key-partition-list".to_string(),
error,
})?;
let current_keychains = String::from_utf8_lossy(&keychain_list_output.stdout)
.split('\n')
.map(|line| {
line
.trim_matches(|c: char| c.is_whitespace() || c == '"')
.to_string()
})
.filter(|l| !l.is_empty())
.collect::<Vec<String>>();
assert_command(
Command::new("security")
.args(["list-keychain", "-d", "user", "-s"])
.args(current_keychains)
.arg(&keychain_path)
.piped(),
"failed to list keychain",
)
.map_err(|error| Error::CommandFailed {
command: "security list-keychain".to_string(),
error,
})?;
let signing_identity = identity::list(&keychain_path)
.map(|l| l.first().cloned())?
.ok_or(Error::ResolveSigningIdentity)?;
Ok(Self {
path: Some(keychain_path),
signing_identity: SigningIdentity::Team(signing_identity),
})
}
pub fn signing_identity(&self) -> String {
match &self.signing_identity {
SigningIdentity::Team(t) => t.certificate_name(),
SigningIdentity::Identifier(i) => i.to_string(),
}
}
pub fn team_id(&self) -> Option<&str> {
match &self.signing_identity {
SigningIdentity::Team(t) => Some(&t.id),
SigningIdentity::Identifier(_) => None,
}
}
pub fn sign(
&self,
path: &Path,
entitlements_path: Option<&Path>,
hardened_runtime: bool,
) -> Result<()> {
let identity = match &self.signing_identity {
SigningIdentity::Team(t) => t.certificate_name(),
SigningIdentity::Identifier(i) => i.clone(),
};
println!("Signing with identity \"{identity}\"");
println!("Signing {}", path.display());
let mut args = vec!["--force", "-s", &identity];
if hardened_runtime {
args.push("--options");
args.push("runtime");
}
let mut codesign = Command::new("codesign");
codesign.args(args);
if let Some(p) = &self.path {
codesign.arg("--keychain").arg(p);
}
if let Some(entitlements_path) = entitlements_path {
codesign.arg("--entitlements");
codesign.arg(entitlements_path);
}
codesign.arg(path);
assert_command(codesign.piped(), "failed to sign app").map_err(|error| {
Error::CommandFailed {
command: "codesign".to_string(),
error,
}
})?;
Ok(())
}
pub fn path(&self) -> Option<&Path> {
self.path.as_deref()
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-macos-sign/src/lib.rs | crates/tauri-macos-sign/src/lib.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{
ffi::{OsStr, OsString},
path::{Path, PathBuf},
process::{Command, ExitStatus},
};
use serde::Deserialize;
pub mod certificate;
mod keychain;
mod provisioning_profile;
pub use keychain::{Keychain, Team};
pub use provisioning_profile::ProvisioningProfile;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("failed to create temp directory: {0}")]
TempDir(std::io::Error),
#[error("failed to resolve home dir")]
ResolveHomeDir,
#[error("failed to resolve signing identity")]
ResolveSigningIdentity,
#[error("failed to decode provisioning profile")]
FailedToDecodeProvisioningProfile,
#[error("could not find provisioning profile UUID")]
FailedToFindProvisioningProfileUuid,
#[error("{context} {path}: {error}")]
Plist {
context: &'static str,
path: PathBuf,
error: plist::Error,
},
#[error("failed to upload app to Apple's notarization servers: {error}")]
FailedToUploadApp { error: std::io::Error },
#[error("failed to notarize app: {0}")]
Notarize(String),
#[error("failed to parse notarytool output as JSON: {output}")]
ParseNotarytoolOutput { output: String },
#[error("failed to run command {command}: {error}")]
CommandFailed {
command: String,
error: std::io::Error,
},
#[error("{context} {path}: {error}")]
Fs {
context: &'static str,
path: PathBuf,
error: std::io::Error,
},
#[error("failed to parse X509 certificate: {error}")]
X509Certificate {
error: x509_certificate::X509CertificateError,
},
#[error("failed to create PFX from self signed certificate")]
FailedToCreatePFX,
#[error("failed to create self signed certificate: {error}")]
FailedToCreateSelfSignedCertificate {
error: Box<apple_codesign::AppleCodesignError>,
},
#[error("failed to encode DER: {error}")]
FailedToEncodeDER { error: std::io::Error },
#[error("certificate missing common name")]
CertificateMissingCommonName,
#[error("certificate missing organization unit for common name {common_name}")]
CertificateMissingOrganizationUnit { common_name: String },
}
pub type Result<T> = std::result::Result<T, Error>;
trait CommandExt {
// The `pipe` function sets the stdout and stderr to properly
// show the command output in the Node.js wrapper.
fn piped(&mut self) -> std::io::Result<ExitStatus>;
}
impl CommandExt for Command {
fn piped(&mut self) -> std::io::Result<ExitStatus> {
self.stdin(os_pipe::dup_stdin()?);
self.stdout(os_pipe::dup_stdout()?);
self.stderr(os_pipe::dup_stderr()?);
let program = self.get_program().to_string_lossy().into_owned();
log::debug!(action = "Running"; "Command `{} {}`", program, self.get_args().map(|arg| arg.to_string_lossy()).fold(String::new(), |acc, arg| format!("{acc} {arg}")));
self.status()
}
}
pub enum ApiKey {
Path(PathBuf),
Raw(Vec<u8>),
}
pub enum AppleNotarizationCredentials {
AppleId {
apple_id: OsString,
password: OsString,
team_id: OsString,
},
ApiKey {
issuer: OsString,
key_id: OsString,
key: ApiKey,
},
}
#[derive(Deserialize)]
struct NotarytoolSubmitOutput {
id: String,
#[serde(default)]
status: Option<String>,
message: String,
}
pub fn notarize(
keychain: &Keychain,
app_bundle_path: &Path,
auth: &AppleNotarizationCredentials,
) -> Result<()> {
notarize_inner(keychain, app_bundle_path, auth, true)
}
pub fn notarize_without_stapling(
keychain: &Keychain,
app_bundle_path: &Path,
auth: &AppleNotarizationCredentials,
) -> Result<()> {
notarize_inner(keychain, app_bundle_path, auth, false)
}
fn notarize_inner(
keychain: &Keychain,
app_bundle_path: &Path,
auth: &AppleNotarizationCredentials,
wait: bool,
) -> Result<()> {
let bundle_stem = app_bundle_path
.file_stem()
.expect("failed to get bundle filename");
let tmp_dir = tempfile::tempdir().map_err(Error::TempDir)?;
let zip_path = tmp_dir
.path()
.join(format!("{}.zip", bundle_stem.to_string_lossy()));
let zip_args = vec![
"-c",
"-k",
"--keepParent",
"--sequesterRsrc",
app_bundle_path
.to_str()
.expect("failed to convert bundle_path to string"),
zip_path
.to_str()
.expect("failed to convert zip_path to string"),
];
// use ditto to create a PKZip almost identical to Finder
// this remove almost 99% of false alarm in notarization
assert_command(
Command::new("ditto").args(zip_args).piped(),
"failed to zip app with ditto",
)
.map_err(|error| Error::CommandFailed {
command: "ditto".to_string(),
error,
})?;
// sign the zip file
keychain.sign(&zip_path, None, false)?;
let mut notarize_args = vec![
"notarytool",
"submit",
zip_path
.to_str()
.expect("failed to convert zip_path to string"),
"--output-format",
"json",
];
if wait {
notarize_args.push("--wait");
}
let notarize_args = notarize_args;
println!("Notarizing {}", app_bundle_path.display());
let output = Command::new("xcrun")
.args(notarize_args)
.notarytool_args(auth, tmp_dir.path())?
.output()
.map_err(|error| Error::FailedToUploadApp { error })?;
if !output.status.success() {
return Err(Error::Notarize(
String::from_utf8_lossy(&output.stderr).into_owned(),
));
}
let output_str = String::from_utf8_lossy(&output.stdout);
if let Ok(submit_output) = serde_json::from_str::<NotarytoolSubmitOutput>(&output_str) {
let log_message = format!(
"{} with status {} for id {} ({})",
if wait { "Finished" } else { "Submitted" },
submit_output.status.as_deref().unwrap_or("Pending"),
submit_output.id,
submit_output.message
);
// status is empty when not waiting for the notarization to finish
if submit_output.status.map_or(!wait, |s| s == "Accepted") {
println!("Notarizing {log_message}");
if wait {
println!("Stapling app...");
staple_app(app_bundle_path.to_path_buf())?;
} else {
println!("Not waiting for notarization to finish.");
println!("You can use `xcrun notarytool log` to check the notarization progress.");
println!(
"When it's done you can optionally staple your app via `xcrun stapler staple {}`",
app_bundle_path.display()
);
}
Ok(())
} else if let Ok(output) = Command::new("xcrun")
.args(["notarytool", "log"])
.arg(&submit_output.id)
.notarytool_args(auth, tmp_dir.path())?
.output()
{
Err(Error::Notarize(format!(
"{log_message}\nLog:\n{}",
String::from_utf8_lossy(&output.stdout)
)))
} else {
Err(Error::Notarize(log_message))
}
} else {
Err(Error::ParseNotarytoolOutput {
output: output_str.into_owned(),
})
}
}
fn staple_app(mut app_bundle_path: PathBuf) -> Result<()> {
let app_bundle_path_clone = app_bundle_path.clone();
let filename = app_bundle_path_clone
.file_name()
.expect("failed to get bundle filename")
.to_str()
.expect("failed to convert bundle filename to string");
app_bundle_path.pop();
Command::new("xcrun")
.args(vec!["stapler", "staple", "-v", filename])
.current_dir(app_bundle_path)
.output()
.map_err(|error| Error::CommandFailed {
command: "xcrun stapler staple".to_string(),
error,
})?;
Ok(())
}
pub trait NotarytoolCmdExt {
fn notarytool_args(
&mut self,
auth: &AppleNotarizationCredentials,
temp_dir: &Path,
) -> Result<&mut Self>;
}
impl NotarytoolCmdExt for Command {
fn notarytool_args(
&mut self,
auth: &AppleNotarizationCredentials,
temp_dir: &Path,
) -> Result<&mut Self> {
match auth {
AppleNotarizationCredentials::AppleId {
apple_id,
password,
team_id,
} => Ok(
self
.arg("--apple-id")
.arg(apple_id)
.arg("--password")
.arg(password)
.arg("--team-id")
.arg(team_id),
),
AppleNotarizationCredentials::ApiKey {
key,
key_id,
issuer,
} => {
let key_path = match key {
ApiKey::Raw(k) => {
let key_path = temp_dir.join("AuthKey.p8");
std::fs::write(&key_path, k).map_err(|error| Error::Fs {
context: "failed to write notarization API key to temp file",
path: key_path.clone(),
error,
})?;
key_path
}
ApiKey::Path(p) => p.to_owned(),
};
Ok(
self
.arg("--key-id")
.arg(key_id)
.arg("--key")
.arg(key_path)
.arg("--issuer")
.arg(issuer),
)
}
}
}
}
fn decode_base64(base64: &OsStr, out_path: &Path) -> Result<()> {
let tmp_dir = tempfile::tempdir().map_err(Error::TempDir)?;
let src_path = tmp_dir.path().join("src");
let base64 = base64
.to_str()
.expect("failed to convert base64 to string")
.as_bytes();
// as base64 contain whitespace decoding may be broken
// https://github.com/marshallpierce/rust-base64/issues/105
// we'll use builtin base64 command from the OS
std::fs::write(&src_path, base64).map_err(|error| Error::Fs {
context: "failed to write base64 to temp file",
path: src_path.clone(),
error,
})?;
assert_command(
std::process::Command::new("base64")
.arg("--decode")
.arg("-i")
.arg(&src_path)
.arg("-o")
.arg(out_path)
.piped(),
"failed to decode certificate",
)
.map_err(|error| Error::CommandFailed {
command: "base64 --decode".to_string(),
error,
})?;
Ok(())
}
fn assert_command(
response: std::result::Result<std::process::ExitStatus, std::io::Error>,
error_message: &str,
) -> std::io::Result<()> {
let status =
response.map_err(|e| std::io::Error::new(e.kind(), format!("{error_message}: {e}")))?;
if !status.success() {
Err(std::io::Error::other(error_message))
} else {
Ok(())
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-macos-sign/src/provisioning_profile.rs | crates/tauri-macos-sign/src/provisioning_profile.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{ffi::OsStr, path::PathBuf, process::Command};
use crate::{Error, Result};
use rand::distr::{Alphanumeric, SampleString};
pub struct ProvisioningProfile {
path: PathBuf,
}
impl ProvisioningProfile {
pub fn from_base64(base64: &OsStr) -> Result<Self> {
let home_dir = dirs::home_dir().ok_or(Error::ResolveHomeDir)?;
let provisioning_profiles_folder = home_dir
.join("Library")
.join("MobileDevice")
.join("Provisioning Profiles");
std::fs::create_dir_all(&provisioning_profiles_folder).map_err(|error| Error::Fs {
context: "failed to create provisioning profiles folder",
path: provisioning_profiles_folder.clone(),
error,
})?;
let provisioning_profile_path = provisioning_profiles_folder.join(format!(
"{}.mobileprovision",
Alphanumeric.sample_string(&mut rand::rng(), 16)
));
super::decode_base64(base64, &provisioning_profile_path)?;
Ok(Self {
path: provisioning_profile_path,
})
}
pub fn uuid(&self) -> Result<String> {
let output = Command::new("security")
.args(["cms", "-D", "-i"])
.arg(&self.path)
.output()
.map_err(|error| Error::CommandFailed {
command: "security cms -D -i".to_string(),
error,
})?;
if !output.status.success() {
return Err(Error::FailedToDecodeProvisioningProfile);
}
let plist =
plist::from_bytes::<plist::Dictionary>(&output.stdout).map_err(|error| Error::Plist {
context: "failed to parse provisioning profile as plist",
path: self.path.clone(),
error,
})?;
plist
.get("UUID")
.and_then(|v| v.as_string().map(ToString::to_string))
.ok_or(Error::FailedToFindProvisioningProfileUuid)
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-macos-sign/src/certificate.rs | crates/tauri-macos-sign/src/certificate.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use apple_codesign::create_self_signed_code_signing_certificate;
use x509_certificate::{EcdsaCurve, KeyAlgorithm};
pub use apple_codesign::CertificateProfile;
use crate::{Error, Result};
/// Self signed certificate options.
pub struct SelfSignedCertificateRequest {
/// Which key type to use
pub algorithm: String,
/// Profile
pub profile: CertificateProfile,
/// Team ID (this is a short string attached to your Apple Developer account)
pub team_id: String,
/// The name of the person this certificate is for
pub person_name: String,
/// Country Name (C) value for certificate identifier
pub country_name: String,
/// How many days the certificate should be valid for
pub validity_days: i64,
/// Certificate password.
pub password: String,
}
pub fn generate_self_signed(request: SelfSignedCertificateRequest) -> Result<Vec<u8>> {
let algorithm = match request.algorithm.as_str() {
"ecdsa" => KeyAlgorithm::Ecdsa(EcdsaCurve::Secp256r1),
"ed25519" => KeyAlgorithm::Ed25519,
"rsa" => KeyAlgorithm::Rsa,
value => panic!("algorithm values should have been validated by arg parser: {value}"),
};
let validity_duration = chrono::Duration::days(request.validity_days);
let (cert, key_pair) = create_self_signed_code_signing_certificate(
algorithm,
request.profile,
&request.team_id,
&request.person_name,
&request.country_name,
validity_duration,
)
.map_err(|error| Error::FailedToCreateSelfSignedCertificate {
error: Box::new(error),
})?;
let pfx = p12::PFX::new(
&cert
.encode_der()
.map_err(|error| Error::FailedToEncodeDER { error })?,
&key_pair.to_pkcs8_one_asymmetric_key_der(),
None,
&request.password,
"code-signing",
)
.ok_or(Error::FailedToCreatePFX)?;
let der = pfx.to_der();
Ok(der)
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-macos-sign/src/keychain/identity.rs | crates/tauri-macos-sign/src/keychain/identity.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use once_cell_regex::regex;
use std::{collections::BTreeSet, path::Path, process::Command};
use x509_certificate::certificate::X509Certificate;
use crate::{Error, Result};
fn get_pem_list(keychain_path: &Path, name_substr: &str) -> Result<std::process::Output> {
Command::new("security")
.arg("find-certificate")
.args(["-p", "-a"])
.arg("-c")
.arg(name_substr)
.arg(keychain_path)
.stdin(os_pipe::dup_stdin().unwrap())
.stderr(os_pipe::dup_stderr().unwrap())
.output()
.map_err(|error| Error::CommandFailed {
command: "security find-certificate".to_string(),
error,
})
}
#[derive(Debug, Clone, Eq, Ord, PartialEq, PartialOrd)]
pub struct Team {
pub name: String,
pub certificate_name: String,
pub id: String,
pub cert_prefix: &'static str,
}
impl Team {
fn from_x509(cert_prefix: &'static str, cert: X509Certificate) -> Result<Self> {
let common_name = cert
.subject_common_name()
.ok_or(Error::CertificateMissingCommonName)?;
let organization = cert
.subject_name()
.iter_organization()
.next()
.and_then(|v| v.to_string().ok());
let name = if let Some(organization) = organization {
println!("found cert {common_name:?} with organization {organization:?}");
organization
} else {
println!(
"found cert {common_name:?} but failed to get organization; falling back to displaying common name"
);
regex!(r"Apple Develop\w+: (.*) \(.+\)")
.captures(&common_name)
.map(|caps| caps[1].to_owned())
.unwrap_or_else(|| {
println!("regex failed to capture nice part of name in cert {common_name:?}; falling back to displaying full name");
common_name.clone()
})
};
let id = cert
.subject_name()
.iter_organizational_unit()
.next()
.and_then(|v| v.to_string().ok())
.ok_or_else(|| Error::CertificateMissingOrganizationUnit {
common_name: common_name.clone(),
})?;
Ok(Self {
name,
certificate_name: common_name,
id,
cert_prefix,
})
}
pub fn certificate_name(&self) -> String {
self.certificate_name.clone()
}
}
pub fn list(keychain_path: &Path) -> Result<Vec<Team>> {
let certs = {
let mut certs = Vec::new();
for cert_prefix in [
"iOS Distribution:",
"Apple Distribution:",
"Developer ID Application:",
"Mac App Distribution:",
"Apple Development:",
"iOS App Development:",
"Mac Development:",
] {
let pem_list_out = get_pem_list(keychain_path, cert_prefix)?;
let cert_list = X509Certificate::from_pem_multiple(pem_list_out.stdout)
.map_err(|error| Error::X509Certificate { error })?;
certs.extend(cert_list.into_iter().map(|cert| (cert_prefix, cert)));
}
certs
};
Ok(
certs
.into_iter()
.flat_map(|(cert_prefix, cert)| {
Team::from_x509(cert_prefix, cert).map_err(|err| {
log::error!("{err}");
err
})
})
// Silly way to sort this and ensure no dupes
.collect::<BTreeSet<_>>()
.into_iter()
.collect(),
)
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-runtime/build.rs | crates/tauri-runtime/build.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
// creates a cfg alias if `has_feature` is true.
// `alias` must be a snake case string.
fn alias(alias: &str, has_feature: bool) {
println!("cargo:rustc-check-cfg=cfg({alias})");
if has_feature {
println!("cargo:rustc-cfg={alias}");
}
}
fn main() {
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap();
let mobile = target_os == "ios" || target_os == "android";
alias("desktop", !mobile);
alias("mobile", mobile);
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-runtime/src/lib.rs | crates/tauri-runtime/src/lib.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! Internal runtime between Tauri and the underlying webview runtime.
//!
//! None of the exposed API of this crate is stable, and it may break semver
//! compatibility in the future. The major version only signifies the intended Tauri version.
#![doc(
html_logo_url = "https://github.com/tauri-apps/tauri/raw/dev/.github/icon.png",
html_favicon_url = "https://github.com/tauri-apps/tauri/raw/dev/.github/icon.png"
)]
#![cfg_attr(docsrs, feature(doc_cfg))]
use raw_window_handle::DisplayHandle;
use serde::Deserialize;
use std::{borrow::Cow, fmt::Debug, sync::mpsc::Sender};
use tauri_utils::config::Color;
use tauri_utils::Theme;
use url::Url;
use webview::{DetachedWebview, PendingWebview};
/// UI scaling utilities.
pub mod dpi;
/// Types useful for interacting with a user's monitors.
pub mod monitor;
pub mod webview;
pub mod window;
use dpi::{PhysicalPosition, PhysicalSize, Position, Rect, Size};
use monitor::Monitor;
use window::{
CursorIcon, DetachedWindow, PendingWindow, RawWindow, WebviewEvent, WindowEvent,
WindowSizeConstraints,
};
use window::{WindowBuilder, WindowId};
use http::{
header::{InvalidHeaderName, InvalidHeaderValue},
method::InvalidMethod,
status::InvalidStatusCode,
};
/// Cookie extraction
pub use cookie::Cookie;
pub type WindowEventId = u32;
pub type WebviewEventId = u32;
/// Progress bar status.
#[derive(Debug, Clone, Copy, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ProgressBarStatus {
/// Hide progress bar.
None,
/// Normal state.
Normal,
/// Indeterminate state. **Treated as Normal on Linux and macOS**
Indeterminate,
/// Paused state. **Treated as Normal on Linux**
Paused,
/// Error state. **Treated as Normal on Linux**
Error,
}
/// Progress Bar State
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProgressBarState {
/// The progress bar status.
pub status: Option<ProgressBarStatus>,
/// The progress bar progress. This can be a value ranging from `0` to `100`
pub progress: Option<u64>,
/// The `.desktop` filename with the Unity desktop window manager, for example `myapp.desktop` **Linux Only**
pub desktop_filename: Option<String>,
}
/// Type of user attention requested on a window.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(tag = "type")]
pub enum UserAttentionType {
/// ## Platform-specific
/// - **macOS:** Bounces the dock icon until the application is in focus.
/// - **Windows:** Flashes both the window and the taskbar button until the application is in focus.
Critical,
/// ## Platform-specific
/// - **macOS:** Bounces the dock icon once.
/// - **Windows:** Flashes the taskbar button until the application is in focus.
Informational,
}
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(tag = "type")]
pub enum DeviceEventFilter {
/// Always filter out device events.
Always,
/// Filter out device events while the window is not focused.
#[default]
Unfocused,
/// Report all device events regardless of window focus.
Never,
}
/// Defines the orientation that a window resize will be performed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
pub enum ResizeDirection {
East,
North,
NorthEast,
NorthWest,
South,
SouthEast,
SouthWest,
West,
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
/// Failed to create webview.
#[error("failed to create webview: {0}")]
CreateWebview(Box<dyn std::error::Error + Send + Sync>),
// TODO: Make it take an error like `CreateWebview` in v3
/// Failed to create window.
#[error("failed to create window")]
CreateWindow,
/// The given window label is invalid.
#[error("Window labels must only include alphanumeric characters, `-`, `/`, `:` and `_`.")]
InvalidWindowLabel,
/// Failed to send message to webview.
#[error("failed to send message to the webview")]
FailedToSendMessage,
/// Failed to receive message from webview.
#[error("failed to receive message from webview")]
FailedToReceiveMessage,
/// Failed to serialize/deserialize.
#[error("JSON error: {0}")]
Json(#[from] serde_json::Error),
/// Failed to load window icon.
#[error("invalid icon: {0}")]
InvalidIcon(Box<dyn std::error::Error + Send + Sync>),
/// Failed to get monitor on window operation.
#[error("failed to get monitor")]
FailedToGetMonitor,
/// Failed to get cursor position.
#[error("failed to get cursor position")]
FailedToGetCursorPosition,
#[error("Invalid header name: {0}")]
InvalidHeaderName(#[from] InvalidHeaderName),
#[error("Invalid header value: {0}")]
InvalidHeaderValue(#[from] InvalidHeaderValue),
#[error("Invalid status code: {0}")]
InvalidStatusCode(#[from] InvalidStatusCode),
#[error("Invalid method: {0}")]
InvalidMethod(#[from] InvalidMethod),
#[error("Infallible error, something went really wrong: {0}")]
Infallible(#[from] std::convert::Infallible),
#[error("the event loop has been closed")]
EventLoopClosed,
#[error("Invalid proxy url")]
InvalidProxyUrl,
#[error("window not found")]
WindowNotFound,
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[error("failed to remove data store")]
FailedToRemoveDataStore,
#[error("Could not find the webview runtime, make sure it is installed")]
WebviewRuntimeNotInstalled,
}
/// Result type.
pub type Result<T> = std::result::Result<T, Error>;
/// Window icon.
#[derive(Debug, Clone)]
pub struct Icon<'a> {
/// RGBA bytes of the icon.
pub rgba: Cow<'a, [u8]>,
/// Icon width.
pub width: u32,
/// Icon height.
pub height: u32,
}
/// A type that can be used as an user event.
pub trait UserEvent: Debug + Clone + Send + 'static {}
impl<T: Debug + Clone + Send + 'static> UserEvent for T {}
/// Event triggered on the event loop run.
#[derive(Debug)]
#[non_exhaustive]
pub enum RunEvent<T: UserEvent> {
/// Event loop is exiting.
Exit,
/// Event loop is about to exit
ExitRequested {
/// The exit code.
code: Option<i32>,
tx: Sender<ExitRequestedEventAction>,
},
/// An event associated with a window.
WindowEvent {
/// The window label.
label: String,
/// The detailed event.
event: WindowEvent,
},
/// An event associated with a webview.
WebviewEvent {
/// The webview label.
label: String,
/// The detailed event.
event: WebviewEvent,
},
/// Application ready.
Ready,
/// Sent if the event loop is being resumed.
Resumed,
/// Emitted when all of the event loop's input events have been processed and redraw processing is about to begin.
///
/// This event is useful as a place to put your code that should be run after all state-changing events have been handled and you want to do stuff (updating state, performing calculations, etc) that happens as the "main body" of your event loop.
MainEventsCleared,
/// Emitted when the user wants to open the specified resource with the app.
#[cfg(any(target_os = "macos", target_os = "ios"))]
Opened { urls: Vec<url::Url> },
/// Emitted when the NSApplicationDelegate's applicationShouldHandleReopen gets called
#[cfg(target_os = "macos")]
Reopen {
/// Indicates whether the NSApplication object found any visible windows in your application.
has_visible_windows: bool,
},
/// A custom event defined by the user.
UserEvent(T),
}
/// Action to take when the event loop is about to exit
#[derive(Debug)]
pub enum ExitRequestedEventAction {
/// Prevent the event loop from exiting
Prevent,
}
/// Application's activation policy. Corresponds to NSApplicationActivationPolicy.
#[cfg(target_os = "macos")]
#[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
#[non_exhaustive]
pub enum ActivationPolicy {
/// Corresponds to NSApplicationActivationPolicyRegular.
Regular,
/// Corresponds to NSApplicationActivationPolicyAccessory.
Accessory,
/// Corresponds to NSApplicationActivationPolicyProhibited.
Prohibited,
}
/// A [`Send`] handle to the runtime.
pub trait RuntimeHandle<T: UserEvent>: Debug + Clone + Send + Sync + Sized + 'static {
type Runtime: Runtime<T, Handle = Self>;
/// Creates an `EventLoopProxy` that can be used to dispatch user events to the main event loop.
fn create_proxy(&self) -> <Self::Runtime as Runtime<T>>::EventLoopProxy;
/// Sets the activation policy for the application.
#[cfg(target_os = "macos")]
#[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
fn set_activation_policy(&self, activation_policy: ActivationPolicy) -> Result<()>;
/// Sets the dock visibility for the application.
#[cfg(target_os = "macos")]
#[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
fn set_dock_visibility(&self, visible: bool) -> Result<()>;
/// Requests an exit of the event loop.
fn request_exit(&self, code: i32) -> Result<()>;
/// Create a new window.
fn create_window<F: Fn(RawWindow) + Send + 'static>(
&self,
pending: PendingWindow<T, Self::Runtime>,
after_window_creation: Option<F>,
) -> Result<DetachedWindow<T, Self::Runtime>>;
/// Create a new webview.
fn create_webview(
&self,
window_id: WindowId,
pending: PendingWebview<T, Self::Runtime>,
) -> Result<DetachedWebview<T, Self::Runtime>>;
/// Run a task on the main thread.
fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> Result<()>;
/// Get a handle to the display controller of the windowing system.
fn display_handle(
&self,
) -> std::result::Result<DisplayHandle<'_>, raw_window_handle::HandleError>;
/// Returns the primary monitor of the system.
///
/// Returns None if it can't identify any monitor as a primary one.
fn primary_monitor(&self) -> Option<Monitor>;
/// Returns the monitor that contains the given point.
fn monitor_from_point(&self, x: f64, y: f64) -> Option<Monitor>;
/// Returns the list of all the monitors available on the system.
fn available_monitors(&self) -> Vec<Monitor>;
/// Get the cursor position relative to the top-left hand corner of the desktop.
fn cursor_position(&self) -> Result<PhysicalPosition<f64>>;
/// Sets the app theme.
fn set_theme(&self, theme: Option<Theme>);
/// Shows the application, but does not automatically focus it.
#[cfg(target_os = "macos")]
#[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
fn show(&self) -> Result<()>;
/// Hides the application.
#[cfg(target_os = "macos")]
#[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
fn hide(&self) -> Result<()>;
/// Change the device event filter mode.
///
/// See [Runtime::set_device_event_filter] for details.
///
/// ## Platform-specific
///
/// See [Runtime::set_device_event_filter] for details.
fn set_device_event_filter(&self, filter: DeviceEventFilter);
/// Finds an Android class in the project scope.
#[cfg(target_os = "android")]
fn find_class<'a>(
&self,
env: &mut jni::JNIEnv<'a>,
activity: &jni::objects::JObject<'_>,
name: impl Into<String>,
) -> std::result::Result<jni::objects::JClass<'a>, jni::errors::Error>;
/// Dispatch a closure to run on the Android context.
///
/// The closure takes the JNI env, the Android activity instance and the possibly null webview.
#[cfg(target_os = "android")]
fn run_on_android_context<F>(&self, f: F)
where
F: FnOnce(&mut jni::JNIEnv, &jni::objects::JObject, &jni::objects::JObject) + Send + 'static;
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[cfg_attr(docsrs, doc(cfg(any(target_os = "macos", target_os = "ios"))))]
fn fetch_data_store_identifiers<F: FnOnce(Vec<[u8; 16]>) + Send + 'static>(
&self,
cb: F,
) -> Result<()>;
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[cfg_attr(docsrs, doc(cfg(any(target_os = "macos", target_os = "ios"))))]
fn remove_data_store<F: FnOnce(Result<()>) + Send + 'static>(
&self,
uuid: [u8; 16],
cb: F,
) -> Result<()>;
}
pub trait EventLoopProxy<T: UserEvent>: Debug + Clone + Send + Sync {
fn send_event(&self, event: T) -> Result<()>;
}
#[derive(Default)]
pub struct RuntimeInitArgs {
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
pub app_id: Option<String>,
#[cfg(windows)]
pub msg_hook: Option<Box<dyn FnMut(*const std::ffi::c_void) -> bool + 'static>>,
}
/// The webview runtime interface.
pub trait Runtime<T: UserEvent>: Debug + Sized + 'static {
/// The window message dispatcher.
type WindowDispatcher: WindowDispatch<T, Runtime = Self>;
/// The webview message dispatcher.
type WebviewDispatcher: WebviewDispatch<T, Runtime = Self>;
/// The runtime handle type.
type Handle: RuntimeHandle<T, Runtime = Self>;
/// The proxy type.
type EventLoopProxy: EventLoopProxy<T>;
/// Creates a new webview runtime. Must be used on the main thread.
fn new(args: RuntimeInitArgs) -> Result<Self>;
/// Creates a new webview runtime on any thread.
#[cfg(any(
windows,
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
#[cfg_attr(
docsrs,
doc(cfg(any(
windows,
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
)))
)]
fn new_any_thread(args: RuntimeInitArgs) -> Result<Self>;
/// Creates an `EventLoopProxy` that can be used to dispatch user events to the main event loop.
fn create_proxy(&self) -> Self::EventLoopProxy;
/// Gets a runtime handle.
fn handle(&self) -> Self::Handle;
/// Create a new window.
fn create_window<F: Fn(RawWindow) + Send + 'static>(
&self,
pending: PendingWindow<T, Self>,
after_window_creation: Option<F>,
) -> Result<DetachedWindow<T, Self>>;
/// Create a new webview.
fn create_webview(
&self,
window_id: WindowId,
pending: PendingWebview<T, Self>,
) -> Result<DetachedWebview<T, Self>>;
/// Returns the primary monitor of the system.
///
/// Returns None if it can't identify any monitor as a primary one.
fn primary_monitor(&self) -> Option<Monitor>;
/// Returns the monitor that contains the given point.
fn monitor_from_point(&self, x: f64, y: f64) -> Option<Monitor>;
/// Returns the list of all the monitors available on the system.
fn available_monitors(&self) -> Vec<Monitor>;
/// Get the cursor position relative to the top-left hand corner of the desktop.
fn cursor_position(&self) -> Result<PhysicalPosition<f64>>;
/// Sets the app theme.
fn set_theme(&self, theme: Option<Theme>);
/// Sets the activation policy for the application.
#[cfg(target_os = "macos")]
#[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
fn set_activation_policy(&mut self, activation_policy: ActivationPolicy);
/// Sets the dock visibility for the application.
#[cfg(target_os = "macos")]
#[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
fn set_dock_visibility(&mut self, visible: bool);
/// Shows the application, but does not automatically focus it.
#[cfg(target_os = "macos")]
#[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
fn show(&self);
/// Hides the application.
#[cfg(target_os = "macos")]
#[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
fn hide(&self);
/// Change the device event filter mode.
///
/// Since the DeviceEvent capture can lead to high CPU usage for unfocused windows, [`tao`]
/// will ignore them by default for unfocused windows on Windows. This method allows changing
/// the filter to explicitly capture them again.
///
/// ## Platform-specific
///
/// - ** Linux / macOS / iOS / Android**: Unsupported.
///
/// [`tao`]: https://crates.io/crates/tao
fn set_device_event_filter(&mut self, filter: DeviceEventFilter);
/// Runs an iteration of the runtime event loop and returns control flow to the caller.
#[cfg(desktop)]
fn run_iteration<F: FnMut(RunEvent<T>) + 'static>(&mut self, callback: F);
/// Equivalent to [`Runtime::run`] but returns the exit code instead of exiting the process.
fn run_return<F: FnMut(RunEvent<T>) + 'static>(self, callback: F) -> i32;
/// Run the webview runtime.
fn run<F: FnMut(RunEvent<T>) + 'static>(self, callback: F);
}
/// Webview dispatcher. A thread-safe handle to the webview APIs.
pub trait WebviewDispatch<T: UserEvent>: Debug + Clone + Send + Sync + Sized + 'static {
/// The runtime this [`WebviewDispatch`] runs under.
type Runtime: Runtime<T>;
/// Run a task on the main thread.
fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> Result<()>;
/// Registers a webview event handler.
fn on_webview_event<F: Fn(&WebviewEvent) + Send + 'static>(&self, f: F) -> WebviewEventId;
/// Runs a closure with the platform webview object as argument.
fn with_webview<F: FnOnce(Box<dyn std::any::Any>) + Send + 'static>(&self, f: F) -> Result<()>;
/// Open the web inspector which is usually called devtools.
#[cfg(any(debug_assertions, feature = "devtools"))]
fn open_devtools(&self);
/// Close the web inspector which is usually called devtools.
#[cfg(any(debug_assertions, feature = "devtools"))]
fn close_devtools(&self);
/// Gets the devtools window's current open state.
#[cfg(any(debug_assertions, feature = "devtools"))]
fn is_devtools_open(&self) -> Result<bool>;
// GETTERS
/// Returns the webview's current URL.
fn url(&self) -> Result<String>;
/// Returns the webview's bounds.
fn bounds(&self) -> Result<Rect>;
/// Returns the position of the top-left hand corner of the webviews's client area relative to the top-left hand corner of the window.
fn position(&self) -> Result<PhysicalPosition<i32>>;
/// Returns the physical size of the webviews's client area.
fn size(&self) -> Result<PhysicalSize<u32>>;
// SETTER
/// Navigate to the given URL.
fn navigate(&self, url: Url) -> Result<()>;
/// Reloads the current page.
fn reload(&self) -> Result<()>;
/// Opens the dialog to prints the contents of the webview.
fn print(&self) -> Result<()>;
/// Closes the webview.
fn close(&self) -> Result<()>;
/// Sets the webview's bounds.
fn set_bounds(&self, bounds: Rect) -> Result<()>;
/// Resizes the webview.
fn set_size(&self, size: Size) -> Result<()>;
/// Updates the webview position.
fn set_position(&self, position: Position) -> Result<()>;
/// Bring the window to front and focus the webview.
fn set_focus(&self) -> Result<()>;
/// Hide the webview
fn hide(&self) -> Result<()>;
/// Show the webview
fn show(&self) -> Result<()>;
/// Executes javascript on the window this [`WindowDispatch`] represents.
fn eval_script<S: Into<String>>(&self, script: S) -> Result<()>;
/// Moves the webview to the given window.
fn reparent(&self, window_id: WindowId) -> Result<()>;
/// Get cookies for a particular url.
///
/// # Stability
///
/// See [WebviewDispatch::cookies].
fn cookies_for_url(&self, url: Url) -> Result<Vec<Cookie<'static>>>;
/// Return all cookies in the cookie store.
///
/// # Stability
///
/// The return value of this function leverages [`cookie::Cookie`] which re-exports the cookie crate.
/// This dependency might receive updates in minor Tauri releases.
fn cookies(&self) -> Result<Vec<Cookie<'static>>>;
/// Set a cookie for the webview.
///
/// # Stability
///
/// See [WebviewDispatch::cookies].
fn set_cookie(&self, cookie: cookie::Cookie<'_>) -> Result<()>;
/// Delete a cookie for the webview.
///
/// # Stability
///
/// See [WebviewDispatch::cookies].
fn delete_cookie(&self, cookie: cookie::Cookie<'_>) -> Result<()>;
/// Sets whether the webview should automatically grow and shrink its size and position when the parent window resizes.
fn set_auto_resize(&self, auto_resize: bool) -> Result<()>;
/// Set the webview zoom level
fn set_zoom(&self, scale_factor: f64) -> Result<()>;
/// Set the webview background.
fn set_background_color(&self, color: Option<Color>) -> Result<()>;
/// Clear all browsing data for this webview.
fn clear_all_browsing_data(&self) -> Result<()>;
}
/// Window dispatcher. A thread-safe handle to the window APIs.
pub trait WindowDispatch<T: UserEvent>: Debug + Clone + Send + Sync + Sized + 'static {
/// The runtime this [`WindowDispatch`] runs under.
type Runtime: Runtime<T>;
/// The window builder type.
type WindowBuilder: WindowBuilder;
/// Run a task on the main thread.
fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> Result<()>;
/// Registers a window event handler.
fn on_window_event<F: Fn(&WindowEvent) + Send + 'static>(&self, f: F) -> WindowEventId;
// GETTERS
/// Returns the scale factor that can be used to map logical pixels to physical pixels, and vice versa.
fn scale_factor(&self) -> Result<f64>;
/// Returns the position of the top-left hand corner of the window's client area relative to the top-left hand corner of the desktop.
fn inner_position(&self) -> Result<PhysicalPosition<i32>>;
/// Returns the position of the top-left hand corner of the window relative to the top-left hand corner of the desktop.
fn outer_position(&self) -> Result<PhysicalPosition<i32>>;
/// Returns the physical size of the window's client area.
///
/// The client area is the content of the window, excluding the title bar and borders.
fn inner_size(&self) -> Result<PhysicalSize<u32>>;
/// Returns the physical size of the entire window.
///
/// These dimensions include the title bar and borders. If you don't want that (and you usually don't), use inner_size instead.
fn outer_size(&self) -> Result<PhysicalSize<u32>>;
/// Gets the window's current fullscreen state.
fn is_fullscreen(&self) -> Result<bool>;
/// Gets the window's current minimized state.
fn is_minimized(&self) -> Result<bool>;
/// Gets the window's current maximized state.
fn is_maximized(&self) -> Result<bool>;
/// Gets the window's current focus state.
fn is_focused(&self) -> Result<bool>;
/// Gets the window's current decoration state.
fn is_decorated(&self) -> Result<bool>;
/// Gets the window's current resizable state.
fn is_resizable(&self) -> Result<bool>;
/// Gets the window's native maximize button state.
///
/// ## Platform-specific
///
/// - **Linux / iOS / Android:** Unsupported.
fn is_maximizable(&self) -> Result<bool>;
/// Gets the window's native minimize button state.
///
/// ## Platform-specific
///
/// - **Linux / iOS / Android:** Unsupported.
fn is_minimizable(&self) -> Result<bool>;
/// Gets the window's native close button state.
///
/// ## Platform-specific
///
/// - **iOS / Android:** Unsupported.
fn is_closable(&self) -> Result<bool>;
/// Gets the window's current visibility state.
fn is_visible(&self) -> Result<bool>;
/// Whether the window is enabled or disable.
fn is_enabled(&self) -> Result<bool>;
/// Gets the window alwaysOnTop flag state.
///
/// ## Platform-specific
///
/// - **iOS / Android:** Unsupported.
fn is_always_on_top(&self) -> Result<bool>;
/// Gets the window's current title.
fn title(&self) -> Result<String>;
/// Returns the monitor on which the window currently resides.
///
/// Returns None if current monitor can't be detected.
fn current_monitor(&self) -> Result<Option<Monitor>>;
/// Returns the primary monitor of the system.
///
/// Returns None if it can't identify any monitor as a primary one.
fn primary_monitor(&self) -> Result<Option<Monitor>>;
/// Returns the monitor that contains the given point.
fn monitor_from_point(&self, x: f64, y: f64) -> Result<Option<Monitor>>;
/// Returns the list of all the monitors available on the system.
fn available_monitors(&self) -> Result<Vec<Monitor>>;
/// Returns the `ApplicationWindow` from gtk crate that is used by this window.
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
fn gtk_window(&self) -> Result<gtk::ApplicationWindow>;
/// Returns the vertical [`gtk::Box`] that is added by default as the sole child of this window.
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
fn default_vbox(&self) -> Result<gtk::Box>;
/// Raw window handle.
fn window_handle(
&self,
) -> std::result::Result<raw_window_handle::WindowHandle<'_>, raw_window_handle::HandleError>;
/// Returns the current window theme.
fn theme(&self) -> Result<Theme>;
// SETTERS
/// Centers the window.
fn center(&self) -> Result<()>;
/// Requests user attention to the window.
///
/// Providing `None` will unset the request for user attention.
fn request_user_attention(&self, request_type: Option<UserAttentionType>) -> Result<()>;
/// Create a new window.
fn create_window<F: Fn(RawWindow) + Send + 'static>(
&mut self,
pending: PendingWindow<T, Self::Runtime>,
after_window_creation: Option<F>,
) -> Result<DetachedWindow<T, Self::Runtime>>;
/// Create a new webview.
fn create_webview(
&mut self,
pending: PendingWebview<T, Self::Runtime>,
) -> Result<DetachedWebview<T, Self::Runtime>>;
/// Updates the window resizable flag.
fn set_resizable(&self, resizable: bool) -> Result<()>;
/// Enable or disable the window.
///
/// ## Platform-specific
///
/// - **Android / iOS**: Unsupported.
fn set_enabled(&self, enabled: bool) -> Result<()>;
/// Updates the window's native maximize button state.
///
/// ## Platform-specific
///
/// - **macOS:** Disables the "zoom" button in the window titlebar, which is also used to enter fullscreen mode.
/// - **Linux / iOS / Android:** Unsupported.
fn set_maximizable(&self, maximizable: bool) -> Result<()>;
/// Updates the window's native minimize button state.
///
/// ## Platform-specific
///
/// - **Linux / iOS / Android:** Unsupported.
fn set_minimizable(&self, minimizable: bool) -> Result<()>;
/// Updates the window's native close button state.
///
/// ## Platform-specific
///
/// - **Linux:** "GTK+ will do its best to convince the window manager not to show a close button.
/// Depending on the system, this function may not have any effect when called on a window that is already visible"
/// - **iOS / Android:** Unsupported.
fn set_closable(&self, closable: bool) -> Result<()>;
/// Updates the window title.
fn set_title<S: Into<String>>(&self, title: S) -> Result<()>;
/// Maximizes the window.
fn maximize(&self) -> Result<()>;
/// Unmaximizes the window.
fn unmaximize(&self) -> Result<()>;
/// Minimizes the window.
fn minimize(&self) -> Result<()>;
/// Unminimizes the window.
fn unminimize(&self) -> Result<()>;
/// Shows the window.
fn show(&self) -> Result<()>;
/// Hides the window.
fn hide(&self) -> Result<()>;
/// Closes the window.
fn close(&self) -> Result<()>;
/// Destroys the window.
fn destroy(&self) -> Result<()>;
/// Updates the decorations flag.
fn set_decorations(&self, decorations: bool) -> Result<()>;
/// Updates the shadow flag.
fn set_shadow(&self, enable: bool) -> Result<()>;
/// Updates the window alwaysOnBottom flag.
fn set_always_on_bottom(&self, always_on_bottom: bool) -> Result<()>;
/// Updates the window alwaysOnTop flag.
fn set_always_on_top(&self, always_on_top: bool) -> Result<()>;
/// Updates the window visibleOnAllWorkspaces flag.
fn set_visible_on_all_workspaces(&self, visible_on_all_workspaces: bool) -> Result<()>;
/// Set the window background.
fn set_background_color(&self, color: Option<Color>) -> Result<()>;
/// Prevents the window contents from being captured by other apps.
fn set_content_protected(&self, protected: bool) -> Result<()>;
/// Resizes the window.
fn set_size(&self, size: Size) -> Result<()>;
/// Updates the window min inner size.
fn set_min_size(&self, size: Option<Size>) -> Result<()>;
/// Updates the window max inner size.
fn set_max_size(&self, size: Option<Size>) -> Result<()>;
/// Sets this window's minimum inner width.
fn set_size_constraints(&self, constraints: WindowSizeConstraints) -> Result<()>;
/// Updates the window position.
fn set_position(&self, position: Position) -> Result<()>;
/// Updates the window fullscreen state.
fn set_fullscreen(&self, fullscreen: bool) -> Result<()>;
#[cfg(target_os = "macos")]
fn set_simple_fullscreen(&self, enable: bool) -> Result<()>;
/// Bring the window to front and focus.
fn set_focus(&self) -> Result<()>;
/// Sets whether the window can be focused.
fn set_focusable(&self, focusable: bool) -> Result<()>;
/// Updates the window icon.
fn set_icon(&self, icon: Icon) -> Result<()>;
/// Whether to hide the window icon from the taskbar or not.
fn set_skip_taskbar(&self, skip: bool) -> Result<()>;
/// Grabs the cursor, preventing it from leaving the window.
///
/// There's no guarantee that the cursor will be hidden. You should
/// hide it by yourself if you want so.
fn set_cursor_grab(&self, grab: bool) -> Result<()>;
/// Modifies the cursor's visibility.
///
/// If `false`, this will hide the cursor. If `true`, this will show the cursor.
fn set_cursor_visible(&self, visible: bool) -> Result<()>;
// Modifies the cursor icon of the window.
fn set_cursor_icon(&self, icon: CursorIcon) -> Result<()>;
/// Changes the position of the cursor in window coordinates.
fn set_cursor_position<Pos: Into<Position>>(&self, position: Pos) -> Result<()>;
/// Ignores the window cursor events.
fn set_ignore_cursor_events(&self, ignore: bool) -> Result<()>;
/// Starts dragging the window.
fn start_dragging(&self) -> Result<()>;
/// Starts resize-dragging the window.
fn start_resize_dragging(&self, direction: ResizeDirection) -> Result<()>;
/// Sets the badge count on the taskbar
/// The badge count appears as a whole for the application
/// Using `0` or using `None` will remove the badge
///
/// ## Platform-specific
/// - **Windows:** Unsupported, use [`WindowDispatch::set_overlay_icon`] instead.
/// - **Android:** Unsupported.
/// - **iOS:** iOS expects i32, if the value is larger than i32::MAX, it will be clamped to i32::MAX.
fn set_badge_count(&self, count: Option<i64>, desktop_filename: Option<String>) -> Result<()>;
/// Sets the badge count on the taskbar **macOS only**. Using `None` will remove the badge
fn set_badge_label(&self, label: Option<String>) -> Result<()>;
/// Sets the overlay icon on the taskbar **Windows only**. Using `None` will remove the icon
///
/// The overlay icon can be unique for each window.
fn set_overlay_icon(&self, icon: Option<Icon>) -> Result<()>;
/// Sets the taskbar progress state.
///
/// ## Platform-specific
///
/// - **Linux / macOS**: Progress bar is app-wide and not specific to this window. Only supported desktop environments with `libunity` (e.g. GNOME).
/// - **iOS / Android:** Unsupported.
fn set_progress_bar(&self, progress_state: ProgressBarState) -> Result<()>;
/// Sets the title bar style. Available on macOS only.
///
/// ## Platform-specific
///
/// - **Linux / Windows / iOS / Android:** Unsupported.
fn set_title_bar_style(&self, style: tauri_utils::TitleBarStyle) -> Result<()>;
/// Change the position of the window controls. Available on macOS only.
///
/// Requires titleBarStyle: Overlay and decorations: true.
///
/// ## Platform-specific
///
/// - **Linux / Windows / iOS / Android:** Unsupported.
fn set_traffic_light_position(&self, position: Position) -> Result<()>;
/// Sets the theme for this window.
///
/// ## Platform-specific
///
/// - **Linux / macOS**: Theme is app-wide and not specific to this window.
/// - **iOS / Android:** Unsupported.
fn set_theme(&self, theme: Option<Theme>) -> Result<()>;
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-runtime/src/dpi.rs | crates/tauri-runtime/src/dpi.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
pub use dpi::*;
use serde::Serialize;
/// A rectangular region.
#[derive(Clone, Copy, Debug, Serialize)]
pub struct Rect {
/// Rect position.
pub position: dpi::Position,
/// Rect size.
pub size: dpi::Size,
}
impl Default for Rect {
fn default() -> Self {
Self {
position: Position::Logical((0, 0).into()),
size: Size::Logical((0, 0).into()),
}
}
}
/// A rectangular region in physical pixels.
#[derive(Clone, Copy, Debug, Serialize)]
pub struct PhysicalRect<P: dpi::Pixel, S: dpi::Pixel> {
/// Rect position.
pub position: dpi::PhysicalPosition<P>,
/// Rect size.
pub size: dpi::PhysicalSize<S>,
}
impl<P: dpi::Pixel, S: dpi::Pixel> Default for PhysicalRect<P, S> {
fn default() -> Self {
Self {
position: (0, 0).into(),
size: (0, 0).into(),
}
}
}
/// A rectangular region in logical pixels.
#[derive(Clone, Copy, Debug, Serialize)]
pub struct LogicalRect<P: dpi::Pixel, S: dpi::Pixel> {
/// Rect position.
pub position: dpi::LogicalPosition<P>,
/// Rect size.
pub size: dpi::LogicalSize<S>,
}
impl<P: dpi::Pixel, S: dpi::Pixel> Default for LogicalRect<P, S> {
fn default() -> Self {
Self {
position: (0, 0).into(),
size: (0, 0).into(),
}
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-runtime/src/window.rs | crates/tauri-runtime/src/window.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! A layer between raw [`Runtime`] windows and Tauri.
use crate::{
webview::{DetachedWebview, PendingWebview},
Icon, Runtime, UserEvent, WindowDispatch,
};
use dpi::PixelUnit;
use serde::{Deserialize, Deserializer, Serialize};
use tauri_utils::{
config::{Color, WindowConfig},
Theme,
};
#[cfg(windows)]
use windows::Win32::Foundation::HWND;
use std::{
hash::{Hash, Hasher},
marker::PhantomData,
path::PathBuf,
sync::mpsc::Sender,
};
/// An event from a window.
#[derive(Debug, Clone)]
pub enum WindowEvent {
/// The size of the window has changed. Contains the client area's new dimensions.
Resized(dpi::PhysicalSize<u32>),
/// The position of the window has changed. Contains the window's new position.
Moved(dpi::PhysicalPosition<i32>),
/// The window has been requested to close.
CloseRequested {
/// A signal sender. If a `true` value is emitted, the window won't be closed.
signal_tx: Sender<bool>,
},
/// The window has been destroyed.
Destroyed,
/// The window gained or lost focus.
///
/// The parameter is true if the window has gained focus, and false if it has lost focus.
Focused(bool),
/// The window's scale factor has changed.
///
/// The following user actions can cause DPI changes:
///
/// - Changing the display's resolution.
/// - Changing the display's scale factor (e.g. in Control Panel on Windows).
/// - Moving the window to a display with a different scale factor.
ScaleFactorChanged {
/// The new scale factor.
scale_factor: f64,
/// The window inner size.
new_inner_size: dpi::PhysicalSize<u32>,
},
/// An event associated with the drag and drop action.
DragDrop(DragDropEvent),
/// The system window theme has changed.
///
/// Applications might wish to react to this to change the theme of the content of the window when the system changes the window theme.
ThemeChanged(Theme),
}
/// An event from a window.
#[derive(Debug, Clone)]
pub enum WebviewEvent {
/// An event associated with the drag and drop action.
DragDrop(DragDropEvent),
}
/// The drag drop event payload.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum DragDropEvent {
/// A drag operation has entered the webview.
Enter {
/// List of paths that are being dragged onto the webview.
paths: Vec<PathBuf>,
/// The position of the mouse cursor.
position: dpi::PhysicalPosition<f64>,
},
/// A drag operation is moving over the webview.
Over {
/// The position of the mouse cursor.
position: dpi::PhysicalPosition<f64>,
},
/// The file(s) have been dropped onto the webview.
Drop {
/// List of paths that are being dropped onto the window.
paths: Vec<PathBuf>,
/// The position of the mouse cursor.
position: dpi::PhysicalPosition<f64>,
},
/// The drag operation has been cancelled or left the window.
Leave,
}
/// Describes the appearance of the mouse cursor.
#[non_exhaustive]
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash)]
pub enum CursorIcon {
/// The platform-dependent default cursor.
#[default]
Default,
/// A simple crosshair.
Crosshair,
/// A hand (often used to indicate links in web browsers).
Hand,
/// Self explanatory.
Arrow,
/// Indicates something is to be moved.
Move,
/// Indicates text that may be selected or edited.
Text,
/// Program busy indicator.
Wait,
/// Help indicator (often rendered as a "?")
Help,
/// Progress indicator. Shows that processing is being done. But in contrast
/// with "Wait" the user may still interact with the program. Often rendered
/// as a spinning beach ball, or an arrow with a watch or hourglass.
Progress,
/// Cursor showing that something cannot be done.
NotAllowed,
ContextMenu,
Cell,
VerticalText,
Alias,
Copy,
NoDrop,
/// Indicates something can be grabbed.
Grab,
/// Indicates something is grabbed.
Grabbing,
AllScroll,
ZoomIn,
ZoomOut,
/// Indicate that some edge is to be moved. For example, the 'SeResize' cursor
/// is used when the movement starts from the south-east corner of the box.
EResize,
NResize,
NeResize,
NwResize,
SResize,
SeResize,
SwResize,
WResize,
EwResize,
NsResize,
NeswResize,
NwseResize,
ColResize,
RowResize,
}
impl<'de> Deserialize<'de> for CursorIcon {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
Ok(match s.to_lowercase().as_str() {
"default" => CursorIcon::Default,
"crosshair" => CursorIcon::Crosshair,
"hand" => CursorIcon::Hand,
"arrow" => CursorIcon::Arrow,
"move" => CursorIcon::Move,
"text" => CursorIcon::Text,
"wait" => CursorIcon::Wait,
"help" => CursorIcon::Help,
"progress" => CursorIcon::Progress,
"notallowed" => CursorIcon::NotAllowed,
"contextmenu" => CursorIcon::ContextMenu,
"cell" => CursorIcon::Cell,
"verticaltext" => CursorIcon::VerticalText,
"alias" => CursorIcon::Alias,
"copy" => CursorIcon::Copy,
"nodrop" => CursorIcon::NoDrop,
"grab" => CursorIcon::Grab,
"grabbing" => CursorIcon::Grabbing,
"allscroll" => CursorIcon::AllScroll,
"zoomin" => CursorIcon::ZoomIn,
"zoomout" => CursorIcon::ZoomOut,
"eresize" => CursorIcon::EResize,
"nresize" => CursorIcon::NResize,
"neresize" => CursorIcon::NeResize,
"nwresize" => CursorIcon::NwResize,
"sresize" => CursorIcon::SResize,
"seresize" => CursorIcon::SeResize,
"swresize" => CursorIcon::SwResize,
"wresize" => CursorIcon::WResize,
"ewresize" => CursorIcon::EwResize,
"nsresize" => CursorIcon::NsResize,
"neswresize" => CursorIcon::NeswResize,
"nwseresize" => CursorIcon::NwseResize,
"colresize" => CursorIcon::ColResize,
"rowresize" => CursorIcon::RowResize,
_ => CursorIcon::Default,
})
}
}
/// Window size constraints
#[derive(Clone, Copy, PartialEq, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WindowSizeConstraints {
/// The minimum width a window can be, If this is `None`, the window will have no minimum width.
///
/// The default is `None`.
pub min_width: Option<PixelUnit>,
/// The minimum height a window can be, If this is `None`, the window will have no minimum height.
///
/// The default is `None`.
pub min_height: Option<PixelUnit>,
/// The maximum width a window can be, If this is `None`, the window will have no maximum width.
///
/// The default is `None`.
pub max_width: Option<PixelUnit>,
/// The maximum height a window can be, If this is `None`, the window will have no maximum height.
///
/// The default is `None`.
pub max_height: Option<PixelUnit>,
}
/// Do **NOT** implement this trait except for use in a custom [`Runtime`]
///
/// This trait is separate from [`WindowBuilder`] to prevent "accidental" implementation.
pub trait WindowBuilderBase: std::fmt::Debug + Clone + Sized {}
/// A builder for all attributes related to a single window.
///
/// This trait is only meant to be implemented by a custom [`Runtime`]
/// and not by applications.
pub trait WindowBuilder: WindowBuilderBase {
/// Initializes a new window attributes builder.
fn new() -> Self;
/// Initializes a new window builder from a [`WindowConfig`]
fn with_config(config: &WindowConfig) -> Self;
/// Show window in the center of the screen.
#[must_use]
fn center(self) -> Self;
/// The initial position of the window in logical pixels.
#[must_use]
fn position(self, x: f64, y: f64) -> Self;
/// Window size in logical pixels.
#[must_use]
fn inner_size(self, width: f64, height: f64) -> Self;
/// Window min inner size in logical pixels.
#[must_use]
fn min_inner_size(self, min_width: f64, min_height: f64) -> Self;
/// Window max inner size in logical pixels.
#[must_use]
fn max_inner_size(self, max_width: f64, max_height: f64) -> Self;
/// Window inner size constraints.
#[must_use]
fn inner_size_constraints(self, constraints: WindowSizeConstraints) -> Self;
/// Prevent the window from overflowing the working area (e.g. monitor size - taskbar size) on creation
///
/// ## Platform-specific
///
/// - **iOS / Android:** Unsupported.
#[must_use]
fn prevent_overflow(self) -> Self;
/// Prevent the window from overflowing the working area (e.g. monitor size - taskbar size)
/// on creation with a margin
///
/// ## Platform-specific
///
/// - **iOS / Android:** Unsupported.
#[must_use]
fn prevent_overflow_with_margin(self, margin: dpi::Size) -> Self;
/// Whether the window is resizable or not.
/// When resizable is set to false, native window's maximize button is automatically disabled.
#[must_use]
fn resizable(self, resizable: bool) -> Self;
/// Whether the window's native maximize button is enabled or not.
/// If resizable is set to false, this setting is ignored.
///
/// ## Platform-specific
///
/// - **macOS:** Disables the "zoom" button in the window titlebar, which is also used to enter fullscreen mode.
/// - **Linux / iOS / Android:** Unsupported.
#[must_use]
fn maximizable(self, maximizable: bool) -> Self;
/// Whether the window's native minimize button is enabled or not.
///
/// ## Platform-specific
///
/// - **Linux / iOS / Android:** Unsupported.
#[must_use]
fn minimizable(self, minimizable: bool) -> Self;
/// Whether the window's native close button is enabled or not.
///
/// ## Platform-specific
///
/// - **Linux:** "GTK+ will do its best to convince the window manager not to show a close button.
/// Depending on the system, this function may not have any effect when called on a window that is already visible"
/// - **iOS / Android:** Unsupported.
#[must_use]
fn closable(self, closable: bool) -> Self;
/// The title of the window in the title bar.
#[must_use]
fn title<S: Into<String>>(self, title: S) -> Self;
/// Whether to start the window in fullscreen or not.
#[must_use]
fn fullscreen(self, fullscreen: bool) -> Self;
/// Whether the window will be initially focused or not.
#[must_use]
fn focused(self, focused: bool) -> Self;
/// Whether the window will be focusable or not.
#[must_use]
fn focusable(self, focusable: bool) -> Self;
/// Whether the window should be maximized upon creation.
#[must_use]
fn maximized(self, maximized: bool) -> Self;
/// Whether the window should be immediately visible upon creation.
#[must_use]
fn visible(self, visible: bool) -> Self;
/// Whether the window should be transparent. If this is true, writing colors
/// with alpha values different than `1.0` will produce a transparent window.
#[cfg(any(not(target_os = "macos"), feature = "macos-private-api"))]
#[cfg_attr(
docsrs,
doc(cfg(any(not(target_os = "macos"), feature = "macos-private-api")))
)]
#[must_use]
fn transparent(self, transparent: bool) -> Self;
/// Whether the window should have borders and bars.
#[must_use]
fn decorations(self, decorations: bool) -> Self;
/// Whether the window should always be below other windows.
#[must_use]
fn always_on_bottom(self, always_on_bottom: bool) -> Self;
/// Whether the window should always be on top of other windows.
#[must_use]
fn always_on_top(self, always_on_top: bool) -> Self;
/// Whether the window should be visible on all workspaces or virtual desktops.
#[must_use]
fn visible_on_all_workspaces(self, visible_on_all_workspaces: bool) -> Self;
/// Prevents the window contents from being captured by other apps.
#[must_use]
fn content_protected(self, protected: bool) -> Self;
/// Sets the window icon.
fn icon(self, icon: Icon) -> crate::Result<Self>;
/// Sets whether or not the window icon should be added to the taskbar.
#[must_use]
fn skip_taskbar(self, skip: bool) -> Self;
/// Set the window background color.
#[must_use]
fn background_color(self, color: Color) -> Self;
/// Sets whether or not the window has shadow.
///
/// ## Platform-specific
///
/// - **Windows:**
/// - `false` has no effect on decorated window, shadows are always ON.
/// - `true` will make undecorated window have a 1px white border,
/// and on Windows 11, it will have a rounded corners.
/// - **Linux:** Unsupported.
#[must_use]
fn shadow(self, enable: bool) -> Self;
/// Set an owner to the window to be created.
///
/// From MSDN:
/// - An owned window is always above its owner in the z-order.
/// - The system automatically destroys an owned window when its owner is destroyed.
/// - An owned window is hidden when its owner is minimized.
///
/// For more information, see <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#owned-windows>
#[cfg(windows)]
#[must_use]
fn owner(self, owner: HWND) -> Self;
/// Sets a parent to the window to be created.
///
/// A child window has the WS_CHILD style and is confined to the client area of its parent window.
///
/// For more information, see <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#child-windows>
#[cfg(windows)]
#[must_use]
fn parent(self, parent: HWND) -> Self;
/// Sets a parent to the window to be created.
///
/// See <https://developer.apple.com/documentation/appkit/nswindow/1419152-addchildwindow?language=objc>
#[cfg(target_os = "macos")]
#[must_use]
fn parent(self, parent: *mut std::ffi::c_void) -> Self;
/// Sets the window to be created transient for parent.
///
/// See <https://docs.gtk.org/gtk3/method.Window.set_transient_for.html>
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
fn transient_for(self, parent: &impl gtk::glib::IsA<gtk::Window>) -> Self;
/// Enables or disables drag and drop support.
#[cfg(windows)]
#[must_use]
fn drag_and_drop(self, enabled: bool) -> Self;
/// Hide the titlebar. Titlebar buttons will still be visible.
#[cfg(target_os = "macos")]
#[must_use]
fn title_bar_style(self, style: tauri_utils::TitleBarStyle) -> Self;
/// Change the position of the window controls on macOS.
///
/// Requires titleBarStyle: Overlay and decorations: true.
#[cfg(target_os = "macos")]
#[must_use]
fn traffic_light_position<P: Into<dpi::Position>>(self, position: P) -> Self;
/// Hide the window title.
#[cfg(target_os = "macos")]
#[must_use]
fn hidden_title(self, hidden: bool) -> Self;
/// Defines the window [tabbing identifier] for macOS.
///
/// Windows with matching tabbing identifiers will be grouped together.
/// If the tabbing identifier is not set, automatic tabbing will be disabled.
///
/// [tabbing identifier]: <https://developer.apple.com/documentation/appkit/nswindow/1644704-tabbingidentifier>
#[cfg(target_os = "macos")]
#[must_use]
fn tabbing_identifier(self, identifier: &str) -> Self;
/// Forces a theme or uses the system settings if None was provided.
fn theme(self, theme: Option<Theme>) -> Self;
/// Whether the icon was set or not.
fn has_icon(&self) -> bool;
fn get_theme(&self) -> Option<Theme>;
/// Sets custom name for Windows' window class. **Windows only**.
#[must_use]
fn window_classname<S: Into<String>>(self, window_classname: S) -> Self;
}
/// A window that has yet to be built.
pub struct PendingWindow<T: UserEvent, R: Runtime<T>> {
/// The label that the window will be named.
pub label: String,
/// The [`WindowBuilder`] that the window will be created with.
pub window_builder: <R::WindowDispatcher as WindowDispatch<T>>::WindowBuilder,
/// The webview that gets added to the window. Optional in case you want to use child webviews or other window content instead.
pub webview: Option<PendingWebview<T, R>>,
}
pub fn is_label_valid(label: &str) -> bool {
label
.chars()
.all(|c| char::is_alphanumeric(c) || c == '-' || c == '/' || c == ':' || c == '_')
}
pub fn assert_label_is_valid(label: &str) {
assert!(
is_label_valid(label),
"Window label must include only alphanumeric characters, `-`, `/`, `:` and `_`."
);
}
impl<T: UserEvent, R: Runtime<T>> PendingWindow<T, R> {
/// Create a new [`PendingWindow`] with a label from the given [`WindowBuilder`].
pub fn new(
window_builder: <R::WindowDispatcher as WindowDispatch<T>>::WindowBuilder,
label: impl Into<String>,
) -> crate::Result<Self> {
let label = label.into();
if !is_label_valid(&label) {
Err(crate::Error::InvalidWindowLabel)
} else {
Ok(Self {
window_builder,
label,
webview: None,
})
}
}
/// Sets a webview to be created on the window.
pub fn set_webview(&mut self, webview: PendingWebview<T, R>) -> &mut Self {
self.webview.replace(webview);
self
}
}
/// Identifier of a window.
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct WindowId(u32);
impl From<u32> for WindowId {
fn from(value: u32) -> Self {
Self(value)
}
}
/// A window that is not yet managed by Tauri.
#[derive(Debug)]
pub struct DetachedWindow<T: UserEvent, R: Runtime<T>> {
/// The identifier of the window.
pub id: WindowId,
/// Name of the window
pub label: String,
/// The [`WindowDispatch`] associated with the window.
pub dispatcher: R::WindowDispatcher,
/// The webview dispatcher in case this window has an attached webview.
pub webview: Option<DetachedWindowWebview<T, R>>,
}
/// A detached webview associated with a window.
#[derive(Debug)]
pub struct DetachedWindowWebview<T: UserEvent, R: Runtime<T>> {
pub webview: DetachedWebview<T, R>,
pub use_https_scheme: bool,
}
impl<T: UserEvent, R: Runtime<T>> Clone for DetachedWindowWebview<T, R> {
fn clone(&self) -> Self {
Self {
webview: self.webview.clone(),
use_https_scheme: self.use_https_scheme,
}
}
}
impl<T: UserEvent, R: Runtime<T>> Clone for DetachedWindow<T, R> {
fn clone(&self) -> Self {
Self {
id: self.id,
label: self.label.clone(),
dispatcher: self.dispatcher.clone(),
webview: self.webview.clone(),
}
}
}
impl<T: UserEvent, R: Runtime<T>> Hash for DetachedWindow<T, R> {
/// Only use the [`DetachedWindow`]'s label to represent its hash.
fn hash<H: Hasher>(&self, state: &mut H) {
self.label.hash(state)
}
}
impl<T: UserEvent, R: Runtime<T>> Eq for DetachedWindow<T, R> {}
impl<T: UserEvent, R: Runtime<T>> PartialEq for DetachedWindow<T, R> {
/// Only use the [`DetachedWindow`]'s label to compare equality.
fn eq(&self, other: &Self) -> bool {
self.label.eq(&other.label)
}
}
/// A raw window type that contains fields to access
/// the HWND on Windows, gtk::ApplicationWindow on Linux
pub struct RawWindow<'a> {
#[cfg(windows)]
pub hwnd: isize,
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
pub gtk_window: &'a gtk::ApplicationWindow,
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
pub default_vbox: Option<&'a gtk::Box>,
pub _marker: &'a PhantomData<()>,
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-runtime/src/monitor.rs | crates/tauri-runtime/src/monitor.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::dpi::{PhysicalPosition, PhysicalRect, PhysicalSize};
/// Monitor descriptor.
#[derive(Debug, Clone)]
pub struct Monitor {
/// A human-readable name of the monitor.
/// `None` if the monitor doesn't exist anymore.
pub name: Option<String>,
/// The monitor's resolution.
pub size: PhysicalSize<u32>,
/// The top-left corner position of the monitor relative to the larger full screen area.
pub position: PhysicalPosition<i32>,
/// The monitor's work_area.
pub work_area: PhysicalRect<i32, u32>,
/// Returns the scale factor that can be used to map logical pixels to physical pixels, and vice versa.
pub scale_factor: f64,
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-runtime/src/webview.rs | crates/tauri-runtime/src/webview.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! A layer between raw [`Runtime`] webviews and Tauri.
//!
#[cfg(not(any(target_os = "android", target_os = "ios")))]
use crate::window::WindowId;
use crate::{window::is_label_valid, Rect, Runtime, UserEvent};
use http::Request;
use tauri_utils::config::{
BackgroundThrottlingPolicy, Color, ScrollBarStyle as ConfigScrollBarStyle, WebviewUrl,
WindowConfig, WindowEffectsConfig,
};
use url::Url;
use std::{
borrow::Cow,
collections::HashMap,
hash::{Hash, Hasher},
path::PathBuf,
sync::Arc,
};
type UriSchemeProtocolHandler = dyn Fn(&str, http::Request<Vec<u8>>, Box<dyn FnOnce(http::Response<Cow<'static, [u8]>>) + Send>)
+ Send
+ Sync
+ 'static;
type WebResourceRequestHandler =
dyn Fn(http::Request<Vec<u8>>, &mut http::Response<Cow<'static, [u8]>>) + Send + Sync;
type NavigationHandler = dyn Fn(&Url) -> bool + Send;
type NewWindowHandler = dyn Fn(Url, NewWindowFeatures) -> NewWindowResponse + Send + Sync;
type OnPageLoadHandler = dyn Fn(Url, PageLoadEvent) + Send;
type DocumentTitleChangedHandler = dyn Fn(String) + Send + 'static;
type DownloadHandler = dyn Fn(DownloadEvent) -> bool + Send + Sync;
#[cfg(target_os = "ios")]
type InputAccessoryViewBuilderFn = dyn Fn(&objc2_ui_kit::UIView) -> Option<objc2::rc::Retained<objc2_ui_kit::UIView>>
+ Send
+ Sync
+ 'static;
/// Download event.
pub enum DownloadEvent<'a> {
/// Download requested.
Requested {
/// The url being downloaded.
url: Url,
/// Represents where the file will be downloaded to.
/// Can be used to set the download location by assigning a new path to it.
/// The assigned path _must_ be absolute.
destination: &'a mut PathBuf,
},
/// Download finished.
Finished {
/// The URL of the original download request.
url: Url,
/// Potentially representing the filesystem path the file was downloaded to.
path: Option<PathBuf>,
/// Indicates if the download succeeded or not.
success: bool,
},
}
#[cfg(target_os = "android")]
pub struct CreationContext<'a, 'b> {
pub env: &'a mut jni::JNIEnv<'b>,
pub activity: &'a jni::objects::JObject<'b>,
pub webview: &'a jni::objects::JObject<'b>,
}
/// Kind of event for the page load handler.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PageLoadEvent {
/// Page started to load.
Started,
/// Page finished loading.
Finished,
}
/// Information about the webview that initiated a new window request.
#[derive(Debug)]
pub struct NewWindowOpener {
/// The instance of the webview that initiated the new window request.
///
/// This must be set as the related view of the new webview. See [`WebviewAttributes::related_view`].
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
))]
pub webview: webkit2gtk::WebView,
/// The instance of the webview that initiated the new window request.
///
/// The target webview environment **MUST** match the environment of the opener webview. See [`WebviewAttributes::environment`].
#[cfg(windows)]
pub webview: webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2,
#[cfg(windows)]
pub environment: webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2Environment,
/// The instance of the webview that initiated the new window request.
#[cfg(target_os = "macos")]
pub webview: objc2::rc::Retained<objc2_web_kit::WKWebView>,
/// Configuration of the target webview.
///
/// This **MUST** be used when creating the target webview. See [`WebviewAttributes::webview_configuration`].
#[cfg(target_os = "macos")]
pub target_configuration: objc2::rc::Retained<objc2_web_kit::WKWebViewConfiguration>,
}
/// Window features of a window requested to open.
#[derive(Debug)]
pub struct NewWindowFeatures {
pub(crate) size: Option<crate::dpi::LogicalSize<f64>>,
pub(crate) position: Option<crate::dpi::LogicalPosition<f64>>,
pub(crate) opener: NewWindowOpener,
}
impl NewWindowFeatures {
pub fn new(
size: Option<crate::dpi::LogicalSize<f64>>,
position: Option<crate::dpi::LogicalPosition<f64>>,
opener: NewWindowOpener,
) -> Self {
Self {
size,
position,
opener,
}
}
/// Specifies the size of the content area
/// as defined by the user's operating system where the new window will be generated.
pub fn size(&self) -> Option<crate::dpi::LogicalSize<f64>> {
self.size
}
/// Specifies the position of the window relative to the work area
/// as defined by the user's operating system where the new window will be generated.
pub fn position(&self) -> Option<crate::dpi::LogicalPosition<f64>> {
self.position
}
/// Returns information about the webview that initiated a new window request.
pub fn opener(&self) -> &NewWindowOpener {
&self.opener
}
}
/// Response for the new window request handler.
pub enum NewWindowResponse {
/// Allow the window to be opened with the default implementation.
Allow,
/// Allow the window to be opened, with the given window.
///
/// ## Platform-specific:
///
/// **Linux**: The webview must be related to the caller webview. See [`WebviewAttributes::related_view`].
/// **Windows**: The webview must use the same environment as the caller webview. See [`WebviewAttributes::environment`].
#[cfg(not(any(target_os = "android", target_os = "ios")))]
Create { window_id: WindowId },
/// Deny the window from being opened.
Deny,
}
/// The scrollbar style to use in the webview.
///
/// ## Platform-specific
///
/// - **Windows**: This option must be given the same value for all webviews that target the same data directory.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Default)]
pub enum ScrollBarStyle {
#[default]
/// The default scrollbar style for the webview.
Default,
#[cfg(windows)]
/// Fluent UI style overlay scrollbars. **Windows Only**
///
/// Requires WebView2 Runtime version 125.0.2535.41 or higher, does nothing on older versions,
/// see https://learn.microsoft.com/en-us/microsoft-edge/webview2/release-notes/?tabs=dotnetcsharp#10253541
FluentOverlay,
}
/// A webview that has yet to be built.
pub struct PendingWebview<T: UserEvent, R: Runtime<T>> {
/// The label that the webview will be named.
pub label: String,
/// The [`WebviewAttributes`] that the webview will be created with.
pub webview_attributes: WebviewAttributes,
/// Custom protocols to register on the webview
pub uri_scheme_protocols: HashMap<String, Box<UriSchemeProtocolHandler>>,
/// How to handle IPC calls on the webview.
pub ipc_handler: Option<WebviewIpcHandler<T, R>>,
/// A handler to decide if incoming url is allowed to navigate.
pub navigation_handler: Option<Box<NavigationHandler>>,
pub new_window_handler: Option<Box<NewWindowHandler>>,
pub document_title_changed_handler: Option<Box<DocumentTitleChangedHandler>>,
/// The resolved URL to load on the webview.
pub url: String,
#[cfg(target_os = "android")]
#[allow(clippy::type_complexity)]
pub on_webview_created:
Option<Box<dyn Fn(CreationContext<'_, '_>) -> Result<(), jni::errors::Error> + Send>>,
pub web_resource_request_handler: Option<Box<WebResourceRequestHandler>>,
pub on_page_load_handler: Option<Box<OnPageLoadHandler>>,
pub download_handler: Option<Arc<DownloadHandler>>,
}
impl<T: UserEvent, R: Runtime<T>> PendingWebview<T, R> {
/// Create a new [`PendingWebview`] with a label from the given [`WebviewAttributes`].
pub fn new(
webview_attributes: WebviewAttributes,
label: impl Into<String>,
) -> crate::Result<Self> {
let label = label.into();
if !is_label_valid(&label) {
Err(crate::Error::InvalidWindowLabel)
} else {
Ok(Self {
webview_attributes,
uri_scheme_protocols: Default::default(),
label,
ipc_handler: None,
navigation_handler: None,
new_window_handler: None,
document_title_changed_handler: None,
url: "tauri://localhost".to_string(),
#[cfg(target_os = "android")]
on_webview_created: None,
web_resource_request_handler: None,
on_page_load_handler: None,
download_handler: None,
})
}
}
pub fn register_uri_scheme_protocol<
N: Into<String>,
H: Fn(&str, http::Request<Vec<u8>>, Box<dyn FnOnce(http::Response<Cow<'static, [u8]>>) + Send>)
+ Send
+ Sync
+ 'static,
>(
&mut self,
uri_scheme: N,
protocol_handler: H,
) {
let uri_scheme = uri_scheme.into();
self
.uri_scheme_protocols
.insert(uri_scheme, Box::new(protocol_handler));
}
#[cfg(target_os = "android")]
pub fn on_webview_created<
F: Fn(CreationContext<'_, '_>) -> Result<(), jni::errors::Error> + Send + 'static,
>(
mut self,
f: F,
) -> Self {
self.on_webview_created.replace(Box::new(f));
self
}
}
/// A webview that is not yet managed by Tauri.
#[derive(Debug)]
pub struct DetachedWebview<T: UserEvent, R: Runtime<T>> {
/// Name of the window
pub label: String,
/// The [`crate::WebviewDispatch`] associated with the window.
pub dispatcher: R::WebviewDispatcher,
}
impl<T: UserEvent, R: Runtime<T>> Clone for DetachedWebview<T, R> {
fn clone(&self) -> Self {
Self {
label: self.label.clone(),
dispatcher: self.dispatcher.clone(),
}
}
}
impl<T: UserEvent, R: Runtime<T>> Hash for DetachedWebview<T, R> {
/// Only use the [`DetachedWebview`]'s label to represent its hash.
fn hash<H: Hasher>(&self, state: &mut H) {
self.label.hash(state)
}
}
impl<T: UserEvent, R: Runtime<T>> Eq for DetachedWebview<T, R> {}
impl<T: UserEvent, R: Runtime<T>> PartialEq for DetachedWebview<T, R> {
/// Only use the [`DetachedWebview`]'s label to compare equality.
fn eq(&self, other: &Self) -> bool {
self.label.eq(&other.label)
}
}
/// The attributes used to create an webview.
#[derive(Debug)]
pub struct WebviewAttributes {
pub url: WebviewUrl,
pub user_agent: Option<String>,
/// A list of initialization javascript scripts to run when loading new pages.
/// When webview load a new page, this initialization code will be executed.
/// It is guaranteed that code is executed before `window.onload`.
///
/// ## Platform-specific
///
/// - **Windows:** scripts are always added to subframes.
/// - **Android:** When [addDocumentStartJavaScript] is not supported,
/// we prepend initialization scripts to each HTML head (implementation only supported on custom protocol URLs).
/// For remote URLs, we use [onPageStarted] which is not guaranteed to run before other scripts.
///
/// [addDocumentStartJavaScript]: https://developer.android.com/reference/androidx/webkit/WebViewCompat#addDocumentStartJavaScript(android.webkit.WebView,java.lang.String,java.util.Set%3Cjava.lang.String%3E)
/// [onPageStarted]: https://developer.android.com/reference/android/webkit/WebViewClient#onPageStarted(android.webkit.WebView,%20java.lang.String,%20android.graphics.Bitmap)
pub initialization_scripts: Vec<InitializationScript>,
pub data_directory: Option<PathBuf>,
pub drag_drop_handler_enabled: bool,
pub clipboard: bool,
pub accept_first_mouse: bool,
pub additional_browser_args: Option<String>,
pub window_effects: Option<WindowEffectsConfig>,
pub incognito: bool,
pub transparent: bool,
pub focus: bool,
pub bounds: Option<Rect>,
pub auto_resize: bool,
pub proxy_url: Option<Url>,
pub zoom_hotkeys_enabled: bool,
pub browser_extensions_enabled: bool,
pub extensions_path: Option<PathBuf>,
pub data_store_identifier: Option<[u8; 16]>,
pub use_https_scheme: bool,
pub devtools: Option<bool>,
pub background_color: Option<Color>,
pub traffic_light_position: Option<dpi::Position>,
pub background_throttling: Option<BackgroundThrottlingPolicy>,
pub javascript_disabled: bool,
/// on macOS and iOS there is a link preview on long pressing links, this is enabled by default.
/// see https://docs.rs/objc2-web-kit/latest/objc2_web_kit/struct.WKWebView.html#method.allowsLinkPreview
pub allow_link_preview: bool,
pub scroll_bar_style: ScrollBarStyle,
/// Allows overriding the the keyboard accessory view on iOS.
/// Returning `None` effectively removes the view.
///
/// The closure parameter is the webview instance.
///
/// The accessory view is the view that appears above the keyboard when a text input element is focused.
/// It usually displays a view with "Done", "Next" buttons.
///
/// # Stability
///
/// This relies on [`objc2_ui_kit`] which does not provide a stable API yet, so it can receive breaking changes in minor releases.
#[cfg(target_os = "ios")]
pub input_accessory_view_builder: Option<InputAccessoryViewBuilder>,
/// Set the environment for the webview.
/// Useful if you need to share the same environment, for instance when using the [`PendingWebview::new_window_handler`].
#[cfg(windows)]
pub environment: Option<webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2Environment>,
/// Creates a new webview sharing the same web process with the provided webview.
/// Useful if you need to link a webview to another, for instance when using the [`PendingWebview::new_window_handler`].
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
))]
pub related_view: Option<webkit2gtk::WebView>,
#[cfg(target_os = "macos")]
pub webview_configuration: Option<objc2::rc::Retained<objc2_web_kit::WKWebViewConfiguration>>,
}
unsafe impl Send for WebviewAttributes {}
unsafe impl Sync for WebviewAttributes {}
#[cfg(target_os = "ios")]
#[non_exhaustive]
pub struct InputAccessoryViewBuilder(pub Box<InputAccessoryViewBuilderFn>);
#[cfg(target_os = "ios")]
impl std::fmt::Debug for InputAccessoryViewBuilder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
f.debug_struct("InputAccessoryViewBuilder").finish()
}
}
#[cfg(target_os = "ios")]
impl InputAccessoryViewBuilder {
pub fn new(builder: Box<InputAccessoryViewBuilderFn>) -> Self {
Self(builder)
}
}
impl From<&WindowConfig> for WebviewAttributes {
fn from(config: &WindowConfig) -> Self {
let mut builder = Self::new(config.url.clone())
.incognito(config.incognito)
.focused(config.focus)
.zoom_hotkeys_enabled(config.zoom_hotkeys_enabled)
.use_https_scheme(config.use_https_scheme)
.browser_extensions_enabled(config.browser_extensions_enabled)
.background_throttling(config.background_throttling.clone())
.devtools(config.devtools)
.scroll_bar_style(match config.scroll_bar_style {
ConfigScrollBarStyle::Default => ScrollBarStyle::Default,
#[cfg(windows)]
ConfigScrollBarStyle::FluentOverlay => ScrollBarStyle::FluentOverlay,
_ => ScrollBarStyle::Default,
});
#[cfg(any(not(target_os = "macos"), feature = "macos-private-api"))]
{
builder = builder.transparent(config.transparent);
}
#[cfg(target_os = "macos")]
{
if let Some(position) = &config.traffic_light_position {
builder =
builder.traffic_light_position(dpi::LogicalPosition::new(position.x, position.y).into());
}
}
builder = builder.accept_first_mouse(config.accept_first_mouse);
if !config.drag_drop_enabled {
builder = builder.disable_drag_drop_handler();
}
if let Some(user_agent) = &config.user_agent {
builder = builder.user_agent(user_agent);
}
if let Some(additional_browser_args) = &config.additional_browser_args {
builder = builder.additional_browser_args(additional_browser_args);
}
if let Some(effects) = &config.window_effects {
builder = builder.window_effects(effects.clone());
}
if let Some(url) = &config.proxy_url {
builder = builder.proxy_url(url.to_owned());
}
if let Some(color) = config.background_color {
builder = builder.background_color(color);
}
builder.javascript_disabled = config.javascript_disabled;
builder.allow_link_preview = config.allow_link_preview;
#[cfg(target_os = "ios")]
if config.disable_input_accessory_view {
builder
.input_accessory_view_builder
.replace(InputAccessoryViewBuilder::new(Box::new(|_webview| None)));
}
builder
}
}
impl WebviewAttributes {
/// Initializes the default attributes for a webview.
pub fn new(url: WebviewUrl) -> Self {
Self {
url,
user_agent: None,
initialization_scripts: Vec::new(),
data_directory: None,
drag_drop_handler_enabled: true,
clipboard: false,
accept_first_mouse: false,
additional_browser_args: None,
window_effects: None,
incognito: false,
transparent: false,
focus: true,
bounds: None,
auto_resize: false,
proxy_url: None,
zoom_hotkeys_enabled: false,
browser_extensions_enabled: false,
data_store_identifier: None,
extensions_path: None,
use_https_scheme: false,
devtools: None,
background_color: None,
traffic_light_position: None,
background_throttling: None,
javascript_disabled: false,
allow_link_preview: true,
scroll_bar_style: ScrollBarStyle::Default,
#[cfg(target_os = "ios")]
input_accessory_view_builder: None,
#[cfg(windows)]
environment: None,
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
))]
related_view: None,
#[cfg(target_os = "macos")]
webview_configuration: None,
}
}
/// Sets the user agent
#[must_use]
pub fn user_agent(mut self, user_agent: &str) -> Self {
self.user_agent = Some(user_agent.to_string());
self
}
/// Adds an init script for the main frame.
///
/// When webview load a new page, this initialization code will be executed.
/// It is guaranteed that code is executed before `window.onload`.
///
/// This is executed only on the main frame.
/// If you only want to run it in all frames, use [`Self::initialization_script_on_all_frames`] instead.
///
/// ## Platform-specific
///
/// - **Windows:** scripts are always added to subframes.
/// - **Android:** When [addDocumentStartJavaScript] is not supported,
/// we prepend initialization scripts to each HTML head (implementation only supported on custom protocol URLs).
/// For remote URLs, we use [onPageStarted] which is not guaranteed to run before other scripts.
///
/// [addDocumentStartJavaScript]: https://developer.android.com/reference/androidx/webkit/WebViewCompat#addDocumentStartJavaScript(android.webkit.WebView,java.lang.String,java.util.Set%3Cjava.lang.String%3E)
/// [onPageStarted]: https://developer.android.com/reference/android/webkit/WebViewClient#onPageStarted(android.webkit.WebView,%20java.lang.String,%20android.graphics.Bitmap)
#[must_use]
pub fn initialization_script(mut self, script: impl Into<String>) -> Self {
self.initialization_scripts.push(InitializationScript {
script: script.into(),
for_main_frame_only: true,
});
self
}
/// Adds an init script for all frames.
///
/// When webview load a new page, this initialization code will be executed.
/// It is guaranteed that code is executed before `window.onload`.
///
/// This is executed on all frames, main frame and also sub frames.
/// If you only want to run it in the main frame, use [`Self::initialization_script`] instead.
///
/// ## Platform-specific
///
/// - **Windows:** scripts are always added to subframes.
/// - **Android:** When [addDocumentStartJavaScript] is not supported,
/// we prepend initialization scripts to each HTML head (implementation only supported on custom protocol URLs).
/// For remote URLs, we use [onPageStarted] which is not guaranteed to run before other scripts.
///
/// [addDocumentStartJavaScript]: https://developer.android.com/reference/androidx/webkit/WebViewCompat#addDocumentStartJavaScript(android.webkit.WebView,java.lang.String,java.util.Set%3Cjava.lang.String%3E)
/// [onPageStarted]: https://developer.android.com/reference/android/webkit/WebViewClient#onPageStarted(android.webkit.WebView,%20java.lang.String,%20android.graphics.Bitmap)
#[must_use]
pub fn initialization_script_on_all_frames(mut self, script: impl Into<String>) -> Self {
self.initialization_scripts.push(InitializationScript {
script: script.into(),
for_main_frame_only: false,
});
self
}
/// Data directory for the webview.
#[must_use]
pub fn data_directory(mut self, data_directory: PathBuf) -> Self {
self.data_directory.replace(data_directory);
self
}
/// Disables the drag and drop handler. This is required to use HTML5 drag and drop APIs on the frontend on Windows.
#[must_use]
pub fn disable_drag_drop_handler(mut self) -> Self {
self.drag_drop_handler_enabled = false;
self
}
/// Enables clipboard access for the page rendered on **Linux** and **Windows**.
///
/// **macOS** doesn't provide such method and is always enabled by default,
/// but you still need to add menu item accelerators to use shortcuts.
#[must_use]
pub fn enable_clipboard_access(mut self) -> Self {
self.clipboard = true;
self
}
/// Sets whether clicking an inactive window also clicks through to the webview.
#[must_use]
pub fn accept_first_mouse(mut self, accept: bool) -> Self {
self.accept_first_mouse = accept;
self
}
/// Sets additional browser arguments. **Windows Only**
#[must_use]
pub fn additional_browser_args(mut self, additional_args: &str) -> Self {
self.additional_browser_args = Some(additional_args.to_string());
self
}
/// Sets window effects
#[must_use]
pub fn window_effects(mut self, effects: WindowEffectsConfig) -> Self {
self.window_effects = Some(effects);
self
}
/// Enable or disable incognito mode for the WebView.
#[must_use]
pub fn incognito(mut self, incognito: bool) -> Self {
self.incognito = incognito;
self
}
/// Enable or disable transparency for the WebView.
#[cfg(any(not(target_os = "macos"), feature = "macos-private-api"))]
#[must_use]
pub fn transparent(mut self, transparent: bool) -> Self {
self.transparent = transparent;
self
}
/// Whether the webview should be focused or not.
#[must_use]
pub fn focused(mut self, focus: bool) -> Self {
self.focus = focus;
self
}
/// Sets the webview to automatically grow and shrink its size and position when the parent window resizes.
#[must_use]
pub fn auto_resize(mut self) -> Self {
self.auto_resize = true;
self
}
/// Enable proxy for the WebView
#[must_use]
pub fn proxy_url(mut self, url: Url) -> Self {
self.proxy_url = Some(url);
self
}
/// Whether page zooming by hotkeys is enabled
///
/// ## Platform-specific:
///
/// - **Windows**: Controls WebView2's [`IsZoomControlEnabled`](https://learn.microsoft.com/en-us/microsoft-edge/webview2/reference/winrt/microsoft_web_webview2_core/corewebview2settings?view=webview2-winrt-1.0.2420.47#iszoomcontrolenabled) setting.
/// - **MacOS / Linux**: Injects a polyfill that zooms in and out with `ctrl/command` + `-/=`,
/// 20% in each step, ranging from 20% to 1000%. Requires `webview:allow-set-webview-zoom` permission
///
/// - **Android / iOS**: Unsupported.
#[must_use]
pub fn zoom_hotkeys_enabled(mut self, enabled: bool) -> Self {
self.zoom_hotkeys_enabled = enabled;
self
}
/// Whether browser extensions can be installed for the webview process
///
/// ## Platform-specific:
///
/// - **Windows**: Enables the WebView2 environment's [`AreBrowserExtensionsEnabled`](https://learn.microsoft.com/en-us/microsoft-edge/webview2/reference/winrt/microsoft_web_webview2_core/corewebview2environmentoptions?view=webview2-winrt-1.0.2739.15#arebrowserextensionsenabled)
/// - **MacOS / Linux / iOS / Android** - Unsupported.
#[must_use]
pub fn browser_extensions_enabled(mut self, enabled: bool) -> Self {
self.browser_extensions_enabled = enabled;
self
}
/// Sets whether the custom protocols should use `https://<scheme>.localhost` instead of the default `http://<scheme>.localhost` on Windows and Android. Defaults to `false`.
///
/// ## Note
///
/// Using a `https` scheme will NOT allow mixed content when trying to fetch `http` endpoints and therefore will not match the behavior of the `<scheme>://localhost` protocols used on macOS and Linux.
///
/// ## Warning
///
/// Changing this value between releases will change the IndexedDB, cookies and localstorage location and your app will not be able to access the old data.
#[must_use]
pub fn use_https_scheme(mut self, enabled: bool) -> Self {
self.use_https_scheme = enabled;
self
}
/// Whether web inspector, which is usually called browser devtools, is enabled or not. Enabled by default.
///
/// This API works in **debug** builds, but requires `devtools` feature flag to enable it in **release** builds.
///
/// ## Platform-specific
///
/// - macOS: This will call private functions on **macOS**.
/// - Android: Open `chrome://inspect/#devices` in Chrome to get the devtools window. Wry's `WebView` devtools API isn't supported on Android.
/// - iOS: Open Safari > Develop > [Your Device Name] > [Your WebView] to get the devtools window.
#[must_use]
pub fn devtools(mut self, enabled: Option<bool>) -> Self {
self.devtools = enabled;
self
}
/// Set the window and webview background color.
/// ## Platform-specific:
///
/// - **Windows**: On Windows 7, alpha channel is ignored for the webview layer.
/// - **Windows**: On Windows 8 and newer, if alpha channel is not `0`, it will be ignored.
#[must_use]
pub fn background_color(mut self, color: Color) -> Self {
self.background_color = Some(color);
self
}
/// Change the position of the window controls. Available on macOS only.
///
/// Requires titleBarStyle: Overlay and decorations: true.
///
/// ## Platform-specific
///
/// - **Linux / Windows / iOS / Android:** Unsupported.
#[must_use]
pub fn traffic_light_position(mut self, position: dpi::Position) -> Self {
self.traffic_light_position = Some(position);
self
}
/// Whether to show a link preview when long pressing on links. Available on macOS and iOS only.
///
/// Default is true.
///
/// See https://docs.rs/objc2-web-kit/latest/objc2_web_kit/struct.WKWebView.html#method.allowsLinkPreview
///
/// ## Platform-specific
///
/// - **Linux / Windows / Android:** Unsupported.
#[must_use]
pub fn allow_link_preview(mut self, allow_link_preview: bool) -> Self {
self.allow_link_preview = allow_link_preview;
self
}
/// Change the default background throttling behavior.
///
/// By default, browsers use a suspend policy that will throttle timers and even unload
/// the whole tab (view) to free resources after roughly 5 minutes when a view became
/// minimized or hidden. This will pause all tasks until the documents visibility state
/// changes back from hidden to visible by bringing the view back to the foreground.
///
/// ## Platform-specific
///
/// - **Linux / Windows / Android**: Unsupported. Workarounds like a pending WebLock transaction might suffice.
/// - **iOS**: Supported since version 17.0+.
/// - **macOS**: Supported since version 14.0+.
///
/// see https://github.com/tauri-apps/tauri/issues/5250#issuecomment-2569380578
#[must_use]
pub fn background_throttling(mut self, policy: Option<BackgroundThrottlingPolicy>) -> Self {
self.background_throttling = policy;
self
}
/// Specifies the native scrollbar style to use with the webview.
/// CSS styles that modify the scrollbar are applied on top of the native appearance configured here.
///
/// Defaults to [`ScrollBarStyle::Default`], which is the browser default.
///
/// ## Platform-specific
///
/// - **Windows**:
/// - [`ScrollBarStyle::FluentOverlay`] requires WebView2 Runtime version 125.0.2535.41 or higher,
/// and does nothing on older versions.
/// - This option must be given the same value for all webviews that target the same data directory. Use
/// [`WebviewAttributes::data_directory`] to change data directories if needed.
/// - **Linux / Android / iOS / macOS**: Unsupported. Only supports `Default` and performs no operation.
#[must_use]
pub fn scroll_bar_style(mut self, style: ScrollBarStyle) -> Self {
self.scroll_bar_style = style;
self
}
}
/// IPC handler.
pub type WebviewIpcHandler<T, R> = Box<dyn Fn(DetachedWebview<T, R>, Request<String>) + Send>;
/// An initialization script
#[derive(Debug, Clone)]
pub struct InitializationScript {
/// The script to run
pub script: String,
/// Whether the script should be injected to main frame only
pub for_main_frame_only: bool,
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/build.rs | crates/tauri-cli/build.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
fn main() {
println!("cargo:rerun-if-changed=templates/");
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/icon.rs | crates/tauri-cli/src/icon.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{
error::{Context, Error, ErrorExt},
helpers::app_paths::tauri_dir,
Result,
};
use std::{
borrow::Cow,
collections::HashMap,
fs::{create_dir_all, File},
io::{BufWriter, Write},
path::{Path, PathBuf},
str::FromStr,
sync::Arc,
};
use clap::Parser;
use icns::{IconFamily, IconType};
use image::{
codecs::{
ico::{IcoEncoder, IcoFrame},
png::{CompressionType, FilterType as PngFilterType, PngEncoder},
},
imageops::FilterType,
open, DynamicImage, ExtendedColorType, GenericImageView, ImageBuffer, ImageEncoder, Pixel, Rgba,
};
use rayon::iter::ParallelIterator;
use resvg::{tiny_skia, usvg};
use serde::Deserialize;
#[derive(Debug, Deserialize)]
struct IcnsEntry {
size: u32,
ostype: String,
}
#[derive(Debug)]
struct PngEntry {
name: String,
size: u32,
out_path: PathBuf,
}
enum AndroidIconKind {
Regular,
Rounded,
}
struct AndroidEntries {
icon: Vec<(PngEntry, AndroidIconKind)>,
foreground: Vec<PngEntry>,
background: Vec<PngEntry>,
monochrome: Vec<PngEntry>,
}
#[derive(Deserialize)]
struct Manifest {
default: String,
bg_color: Option<String>,
android_bg: Option<String>,
android_fg: Option<String>,
android_monochrome: Option<String>,
android_fg_scale: Option<f32>,
}
#[derive(Debug, Parser)]
#[clap(about = "Generate various icons for all major platforms")]
pub struct Options {
/// Path to the source icon (squared PNG or SVG file with transparency) or a manifest file.
///
/// The manifest file is a JSON file with the following structure:
/// {
/// "default": "app-icon.png",
/// "bg_color": "#fff",
/// "android_bg": "app-icon-bg.png",
/// "android_fg": "app-icon-fg.png",
/// "android_fg_scale": 85,
/// "android_monochrome": "app-icon-monochrome.png"
/// }
///
/// All file paths defined in the manifest JSON are relative to the manifest file path.
///
/// Only the `default` manifest property is required.
///
/// The `bg_color` manifest value overwrites the `--ios-color` option if set.
#[clap(default_value = "./app-icon.png")]
input: PathBuf,
/// Output directory.
/// Default: 'icons' directory next to the tauri.conf.json file.
#[clap(short, long)]
output: Option<PathBuf>,
/// Custom PNG icon sizes to generate. When set, the default icons are not generated.
#[clap(short, long, use_value_delimiter = true)]
png: Option<Vec<u32>>,
/// The background color of the iOS icon - string as defined in the W3C's CSS Color Module Level 4 <https://www.w3.org/TR/css-color-4/>.
#[clap(long, default_value = "#fff")]
ios_color: String,
}
#[derive(Clone)]
#[allow(clippy::large_enum_variant)]
enum Source {
Svg(resvg::usvg::Tree),
DynamicImage(DynamicImage),
}
impl Source {
fn width(&self) -> u32 {
match self {
Self::Svg(svg) => svg.size().width() as u32,
Self::DynamicImage(i) => i.width(),
}
}
fn height(&self) -> u32 {
match self {
Self::Svg(svg) => svg.size().height() as u32,
Self::DynamicImage(i) => i.height(),
}
}
fn resize_exact(&self, size: u32) -> DynamicImage {
match self {
Self::Svg(svg) => {
let mut pixmap = tiny_skia::Pixmap::new(size, size).unwrap();
let scale = size as f32 / svg.size().height();
resvg::render(
svg,
tiny_skia::Transform::from_scale(scale, scale),
&mut pixmap.as_mut(),
);
// Switch to use `Pixmap::take_demultiplied` in the future when it's published
// https://github.com/linebender/tiny-skia/blob/624257c0feb394bf6c4d0d688f8ea8030aae320f/src/pixmap.rs#L266
let img_buffer = ImageBuffer::from_par_fn(size, size, |x, y| {
let pixel = pixmap.pixel(x, y).unwrap().demultiply();
Rgba([pixel.red(), pixel.green(), pixel.blue(), pixel.alpha()])
});
DynamicImage::ImageRgba8(img_buffer)
}
Self::DynamicImage(image) => {
// image.resize_exact(size, size, FilterType::Lanczos3)
resize_image(image, size, size)
}
}
}
}
// `image` does not use premultiplied alpha in resize, so we do it manually here,
// see https://github.com/image-rs/image/issues/1655
fn resize_image(image: &DynamicImage, new_width: u32, new_height: u32) -> DynamicImage {
// Premultiply alpha
let premultiplied_image = ImageBuffer::from_par_fn(image.width(), image.height(), |x, y| {
let mut pixel = image.get_pixel(x, y);
let alpha = pixel.0[3] as f32 / u8::MAX as f32;
pixel.apply_without_alpha(|channel_value| (channel_value as f32 * alpha) as u8);
pixel
});
let mut resized = image::imageops::resize(
&premultiplied_image,
new_width,
new_height,
FilterType::Lanczos3,
);
// Demultiply alpha
resized.par_pixels_mut().for_each(|pixel| {
let alpha = pixel.0[3] as f32 / u8::MAX as f32;
pixel.apply_without_alpha(|channel_value| (channel_value as f32 / alpha) as u8);
});
DynamicImage::ImageRgba8(resized)
}
fn read_source(path: PathBuf) -> Result<Source> {
if let Some(extension) = path.extension() {
if extension == "svg" {
let rtree = {
let mut fontdb = usvg::fontdb::Database::new();
fontdb.load_system_fonts();
let opt = usvg::Options {
// Get file's absolute directory.
resources_dir: std::fs::canonicalize(&path)
.ok()
.and_then(|p| p.parent().map(|p| p.to_path_buf())),
fontdb: Arc::new(fontdb),
..Default::default()
};
let svg_data = std::fs::read(&path).fs_context("Failed to read source icon", &path)?;
usvg::Tree::from_data(&svg_data, &opt).unwrap()
};
Ok(Source::Svg(rtree))
} else {
Ok(Source::DynamicImage(DynamicImage::ImageRgba8(
open(&path)
.context(format!(
"failed to read and decode source image {}",
path.display()
))?
.into_rgba8(),
)))
}
} else {
crate::error::bail!("Error loading image");
}
}
fn parse_bg_color(bg_color_string: &String) -> Result<Rgba<u8>> {
let bg_color = css_color::Srgb::from_str(bg_color_string)
.map(|color| {
Rgba([
(color.red * 255.) as u8,
(color.green * 255.) as u8,
(color.blue * 255.) as u8,
(color.alpha * 255.) as u8,
])
})
.map_err(|_e| {
Error::Context(
format!("failed to parse color {bg_color_string}"),
"invalid RGBA color".into(),
)
})?;
Ok(bg_color)
}
pub fn command(options: Options) -> Result<()> {
let input = options.input;
let out_dir = options.output.unwrap_or_else(|| {
crate::helpers::app_paths::resolve();
tauri_dir().join("icons")
});
let png_icon_sizes = options.png.unwrap_or_default();
create_dir_all(&out_dir).fs_context("Can't create output directory", &out_dir)?;
let manifest = if input.extension().is_some_and(|ext| ext == "json") {
parse_manifest(&input).map(Some)?
} else {
None
};
let bg_color_string = match manifest {
Some(ref manifest) => manifest
.bg_color
.as_ref()
.unwrap_or(&options.ios_color)
.clone(),
None => options.ios_color,
};
let bg_color = parse_bg_color(&bg_color_string)?;
let default_icon = match manifest {
Some(ref manifest) => input.parent().unwrap().join(manifest.default.clone()),
None => input.clone(),
};
let source = read_source(default_icon)?;
if source.height() != source.width() {
crate::error::bail!("Source image must be square");
}
if png_icon_sizes.is_empty() {
appx(&source, &out_dir).context("Failed to generate appx icons")?;
icns(&source, &out_dir).context("Failed to generate .icns file")?;
ico(&source, &out_dir).context("Failed to generate .ico file")?;
png(&source, &out_dir, bg_color).context("Failed to generate png icons")?;
android(&source, &input, manifest, &bg_color_string, &out_dir)
.context("Failed to generate android icons")?;
} else {
for target in png_icon_sizes.into_iter().map(|size| {
let name = format!("{size}x{size}.png");
let out_path = out_dir.join(&name);
PngEntry {
name,
out_path,
size,
}
}) {
log::info!(action = "PNG"; "Creating {}", target.name);
resize_and_save_png(&source, target.size, &target.out_path, None, None)?;
}
}
Ok(())
}
fn parse_manifest(manifest_path: &Path) -> Result<Manifest> {
let manifest: Manifest = serde_json::from_str(
&std::fs::read_to_string(manifest_path)
.fs_context("cannot read manifest file", manifest_path)?,
)
.context(format!(
"failed to parse manifest file {}",
manifest_path.display()
))?;
log::debug!("Read manifest file from {}", manifest_path.display());
Ok(manifest)
}
fn appx(source: &Source, out_dir: &Path) -> Result<()> {
log::info!(action = "Appx"; "Creating StoreLogo.png");
resize_and_save_png(source, 50, &out_dir.join("StoreLogo.png"), None, None)?;
for size in [30, 44, 71, 89, 107, 142, 150, 284, 310] {
let file_name = format!("Square{size}x{size}Logo.png");
log::info!(action = "Appx"; "Creating {}", file_name);
resize_and_save_png(source, size, &out_dir.join(&file_name), None, None)?;
}
Ok(())
}
// Main target: macOS
fn icns(source: &Source, out_dir: &Path) -> Result<()> {
log::info!(action = "ICNS"; "Creating icon.icns");
let entries: HashMap<String, IcnsEntry> =
serde_json::from_slice(include_bytes!("helpers/icns.json")).unwrap();
let mut family = IconFamily::new();
for (_name, entry) in entries {
let size = entry.size;
let mut buf = Vec::new();
let image = source.resize_exact(size);
write_png(image.as_bytes(), &mut buf, size).context("failed to write output file")?;
let image = icns::Image::read_png(&buf[..]).context("failed to read output file")?;
family
.add_icon_with_type(
&image,
IconType::from_ostype(entry.ostype.parse().unwrap()).unwrap(),
)
.context("failed to add icon to Icns Family")?;
}
let icns_path = out_dir.join("icon.icns");
let mut out_file = BufWriter::new(
File::create(&icns_path).fs_context("failed to create output file", &icns_path)?,
);
family
.write(&mut out_file)
.fs_context("failed to write output file", &icns_path)?;
out_file
.flush()
.fs_context("failed to flush output file", &icns_path)?;
Ok(())
}
// Generate .ico file with layers for the most common sizes.
// Main target: Windows
fn ico(source: &Source, out_dir: &Path) -> Result<()> {
log::info!(action = "ICO"; "Creating icon.ico");
let mut frames = Vec::new();
for size in [32, 16, 24, 48, 64, 256] {
let image = source.resize_exact(size);
// Only the 256px layer can be compressed according to the ico specs.
if size == 256 {
let mut buf = Vec::new();
write_png(image.as_bytes(), &mut buf, size).context("failed to write output file")?;
frames.push(
IcoFrame::with_encoded(buf, size, size, ExtendedColorType::Rgba8)
.context("failed to create ico frame")?,
);
} else {
frames.push(
IcoFrame::as_png(image.as_bytes(), size, size, ExtendedColorType::Rgba8)
.context("failed to create PNG frame")?,
);
}
}
let ico_path = out_dir.join("icon.ico");
let mut out_file =
BufWriter::new(File::create(&ico_path).fs_context("failed to create output file", &ico_path)?);
let encoder = IcoEncoder::new(&mut out_file);
encoder
.encode_images(&frames)
.context("failed to encode images")?;
out_file
.flush()
.fs_context("failed to flush output file", &ico_path)?;
Ok(())
}
fn android(
source: &Source,
input: &Path,
manifest: Option<Manifest>,
bg_color: &String,
out_dir: &Path,
) -> Result<()> {
fn android_entries(out_dir: &Path) -> Result<AndroidEntries> {
struct AndroidEntry {
name: &'static str,
size: u32,
foreground_size: u32,
}
let targets = vec![
AndroidEntry {
name: "hdpi",
size: 49,
foreground_size: 162,
},
AndroidEntry {
name: "mdpi",
size: 48,
foreground_size: 108,
},
AndroidEntry {
name: "xhdpi",
size: 96,
foreground_size: 216,
},
AndroidEntry {
name: "xxhdpi",
size: 144,
foreground_size: 324,
},
AndroidEntry {
name: "xxxhdpi",
size: 192,
foreground_size: 432,
},
];
let mut icon_entries = Vec::new();
let mut fg_entries = Vec::new();
let mut bg_entries = Vec::new();
let mut monochrome_entries = Vec::new();
for target in targets {
let folder_name = format!("mipmap-{}", target.name);
let out_folder = out_dir.join(&folder_name);
create_dir_all(&out_folder).fs_context(
"failed to create Android mipmap output directory",
&out_folder,
)?;
fg_entries.push(PngEntry {
name: format!("{}/{}", folder_name, "ic_launcher_foreground.png"),
out_path: out_folder.join("ic_launcher_foreground.png"),
size: target.foreground_size,
});
icon_entries.push((
PngEntry {
name: format!("{}/{}", folder_name, "ic_launcher_round.png"),
out_path: out_folder.join("ic_launcher_round.png"),
size: target.size,
},
AndroidIconKind::Rounded,
));
icon_entries.push((
PngEntry {
name: format!("{}/{}", folder_name, "ic_launcher.png"),
out_path: out_folder.join("ic_launcher.png"),
size: target.size,
},
AndroidIconKind::Regular,
));
bg_entries.push(PngEntry {
name: format!("{}/{}", folder_name, "ic_launcher_background.png"),
out_path: out_folder.join("ic_launcher_background.png"),
size: target.foreground_size,
});
monochrome_entries.push(PngEntry {
name: format!("{}/{}", folder_name, "ic_launcher_monochrome.png"),
out_path: out_folder.join("ic_launcher_monochrome.png"),
size: target.foreground_size,
});
}
Ok(AndroidEntries {
icon: icon_entries,
foreground: fg_entries,
background: bg_entries,
monochrome: monochrome_entries,
})
}
fn create_color_file(out_dir: &Path, color: &String) -> Result<()> {
let values_folder = out_dir.join("values");
create_dir_all(&values_folder).fs_context(
"Can't create Android values output directory",
&values_folder,
)?;
let launcher_background_xml_path = values_folder.join("ic_launcher_background.xml");
let mut color_file = File::create(&launcher_background_xml_path).fs_context(
"failed to create Android color file",
&launcher_background_xml_path,
)?;
color_file
.write_all(
format!(
r#"<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">{color}</color>
</resources>"#,
)
.as_bytes(),
)
.fs_context(
"failed to write Android color file",
&launcher_background_xml_path,
)?;
Ok(())
}
let android_out = out_dir
.parent()
.unwrap()
.join("gen/android/app/src/main/res/");
let out = if android_out.exists() {
android_out
} else {
let out = out_dir.join("android");
create_dir_all(&out).fs_context("Can't create Android output directory", &out)?;
out
};
let entries = android_entries(&out)?;
let fg_source = match manifest {
Some(ref manifest) => {
Some(read_source(input.parent().unwrap().join(
manifest.android_fg.as_ref().unwrap_or(&manifest.default),
))?)
}
None => None,
};
for entry in entries.foreground {
log::info!(action = "Android"; "Creating {}", entry.name);
resize_and_save_png(
fg_source.as_ref().unwrap_or(source),
entry.size,
&entry.out_path,
None,
None,
)?;
}
let mut bg_source = None;
let mut has_monochrome_image = false;
if let Some(ref manifest) = manifest {
if let Some(ref background_path) = manifest.android_bg {
let bg = read_source(input.parent().unwrap().join(background_path))?;
for entry in entries.background {
log::info!(action = "Android"; "Creating {}", entry.name);
resize_and_save_png(&bg, entry.size, &entry.out_path, None, None)?;
}
bg_source.replace(bg);
}
if let Some(ref monochrome_path) = manifest.android_monochrome {
has_monochrome_image = true;
let mc = read_source(input.parent().unwrap().join(monochrome_path))?;
for entry in entries.monochrome {
log::info!(action = "Android"; "Creating {}", entry.name);
resize_and_save_png(&mc, entry.size, &entry.out_path, None, None)?;
}
}
}
for (entry, kind) in entries.icon {
log::info!(action = "Android"; "Creating {}", entry.name);
let (margin, radius) = match kind {
AndroidIconKind::Regular => {
let radius = ((entry.size as f32) * 0.0833).round() as u32;
(radius, radius)
}
AndroidIconKind::Rounded => {
let margin = ((entry.size as f32) * 0.04).round() as u32;
let radius = ((entry.size as f32) * 0.5).round() as u32;
(margin, radius)
}
};
let image = if let (Some(bg_source), Some(fg_source)) = (bg_source.as_ref(), fg_source.as_ref())
{
resize_png(
fg_source,
entry.size,
Some(Background::Image(bg_source)),
manifest
.as_ref()
.and_then(|manifest| manifest.android_fg_scale),
)?
} else {
resize_png(source, entry.size, None, None)?
};
let image = apply_round_mask(&image, entry.size, margin, radius);
let mut out_file = BufWriter::new(
File::create(&entry.out_path).fs_context("failed to create output file", &entry.out_path)?,
);
write_png(image.as_bytes(), &mut out_file, entry.size)
.context("failed to write output file")?;
out_file
.flush()
.fs_context("failed to flush output file", &entry.out_path)?;
}
let mut launcher_content = r#"<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>"#
.to_owned();
if bg_source.is_some() {
launcher_content
.push_str("\n <background android:drawable=\"@mipmap/ic_launcher_background\"/>");
} else {
create_color_file(&out, bg_color)?;
launcher_content
.push_str("\n <background android:drawable=\"@color/ic_launcher_background\"/>");
}
if has_monochrome_image {
launcher_content
.push_str("\n <monochrome android:drawable=\"@mipmap/ic_launcher_monochrome\"/>");
}
launcher_content.push_str("\n</adaptive-icon>");
let any_dpi_folder = out.join("mipmap-anydpi-v26");
create_dir_all(&any_dpi_folder).fs_context(
"Can't create Android mipmap-anydpi-v26 output directory",
&any_dpi_folder,
)?;
let launcher_xml_path = any_dpi_folder.join("ic_launcher.xml");
let mut launcher_file = File::create(&launcher_xml_path)
.fs_context("failed to create Android launcher file", &launcher_xml_path)?;
launcher_file
.write_all(launcher_content.as_bytes())
.fs_context("failed to write Android launcher file", &launcher_xml_path)?;
Ok(())
}
// Generate .png files in 32x32, 64x64, 128x128, 256x256, 512x512 (icon.png)
// Main target: Linux
fn png(source: &Source, out_dir: &Path, ios_color: Rgba<u8>) -> Result<()> {
fn desktop_entries(out_dir: &Path) -> Vec<PngEntry> {
let mut entries = Vec::new();
for size in [32, 64, 128, 256, 512] {
let file_name = match size {
256 => "128x128@2x.png".to_string(),
512 => "icon.png".to_string(),
_ => format!("{size}x{size}.png"),
};
entries.push(PngEntry {
out_path: out_dir.join(&file_name),
name: file_name,
size,
});
}
entries
}
fn ios_entries(out_dir: &Path) -> Result<Vec<PngEntry>> {
struct IosEntry {
size: f32,
multipliers: Vec<u8>,
has_extra: bool,
}
let mut entries = Vec::new();
let targets = vec![
IosEntry {
size: 20.,
multipliers: vec![1, 2, 3],
has_extra: true,
},
IosEntry {
size: 29.,
multipliers: vec![1, 2, 3],
has_extra: true,
},
IosEntry {
size: 40.,
multipliers: vec![1, 2, 3],
has_extra: true,
},
IosEntry {
size: 60.,
multipliers: vec![2, 3],
has_extra: false,
},
IosEntry {
size: 76.,
multipliers: vec![1, 2],
has_extra: false,
},
IosEntry {
size: 83.5,
multipliers: vec![2],
has_extra: false,
},
IosEntry {
size: 512.,
multipliers: vec![2],
has_extra: false,
},
];
for target in targets {
let size_str = if target.size == 512. {
"512".to_string()
} else {
format!("{size}x{size}", size = target.size)
};
if target.has_extra {
let name = format!("AppIcon-{size_str}@2x-1.png");
entries.push(PngEntry {
out_path: out_dir.join(&name),
name,
size: (target.size * 2.) as u32,
});
}
for multiplier in target.multipliers {
let name = format!("AppIcon-{size_str}@{multiplier}x.png");
entries.push(PngEntry {
out_path: out_dir.join(&name),
name,
size: (target.size * multiplier as f32) as u32,
});
}
}
Ok(entries)
}
let entries = desktop_entries(out_dir);
let ios_out = out_dir
.parent()
.unwrap()
.join("gen/apple/Assets.xcassets/AppIcon.appiconset");
let out = if ios_out.exists() {
ios_out
} else {
let out = out_dir.join("ios");
create_dir_all(&out).fs_context("failed to create iOS output directory", &out)?;
out
};
for entry in entries {
log::info!(action = "PNG"; "Creating {}", entry.name);
resize_and_save_png(source, entry.size, &entry.out_path, None, None)?;
}
for entry in ios_entries(&out)? {
log::info!(action = "iOS"; "Creating {}", entry.name);
resize_and_save_png(
source,
entry.size,
&entry.out_path,
Some(Background::Color(ios_color)),
None,
)?;
}
Ok(())
}
enum Background<'a> {
Color(Rgba<u8>),
Image(&'a Source),
}
// Resize image.
fn resize_png(
source: &Source,
size: u32,
bg: Option<Background>,
scale_percent: Option<f32>,
) -> Result<DynamicImage> {
let mut image = source.resize_exact(size);
match bg {
Some(Background::Color(bg_color)) => {
let mut bg_img = ImageBuffer::from_fn(size, size, |_, _| bg_color);
let fg = scale_percent
.map(|scale| resize_asset(&image, size, scale))
.unwrap_or(image);
image::imageops::overlay(&mut bg_img, &fg, 0, 0);
image = bg_img.into();
}
Some(Background::Image(bg_source)) => {
let mut bg = bg_source.resize_exact(size);
let fg = scale_percent
.map(|scale| resize_asset(&image, size, scale))
.unwrap_or(image);
image::imageops::overlay(&mut bg, &fg, 0, 0);
image = bg;
}
None => {}
}
Ok(image)
}
// Resize image and save it to disk.
fn resize_and_save_png(
source: &Source,
size: u32,
file_path: &Path,
bg: Option<Background>,
scale_percent: Option<f32>,
) -> Result<()> {
let image = resize_png(source, size, bg, scale_percent)?;
let mut out_file =
BufWriter::new(File::create(file_path).fs_context("failed to create output file", file_path)?);
write_png(image.as_bytes(), &mut out_file, size).context("failed to write output file")?;
out_file
.flush()
.fs_context("failed to save output file", file_path)
}
// Encode image data as png with compression.
fn write_png<W: Write>(image_data: &[u8], w: W, size: u32) -> image::ImageResult<()> {
let encoder = PngEncoder::new_with_quality(w, CompressionType::Best, PngFilterType::Adaptive);
encoder.write_image(image_data, size, size, ExtendedColorType::Rgba8)?;
Ok(())
}
// finds the bounding box of non-transparent pixels in an RGBA image.
fn content_bounds(img: &DynamicImage) -> Option<(u32, u32, u32, u32)> {
let rgba = img.to_rgba8();
let (width, height) = img.dimensions();
let mut min_x = width;
let mut min_y = height;
let mut max_x = 0;
let mut max_y = 0;
let mut found = false;
for y in 0..height {
for x in 0..width {
let a = rgba.get_pixel(x, y)[3];
if a > 0 {
found = true;
if x < min_x {
min_x = x;
}
if y < min_y {
min_y = y;
}
if x > max_x {
max_x = x;
}
if y > max_y {
max_y = y;
}
}
}
}
if found {
Some((min_x, min_y, max_x - min_x + 1, max_y - min_y + 1))
} else {
None
}
}
fn resize_asset(img: &DynamicImage, target_size: u32, scale_percent: f32) -> DynamicImage {
let cropped = if let Some((x, y, cw, ch)) = content_bounds(img) {
// TODO: Use `&` here instead when we raise MSRV to above 1.79
Cow::Owned(img.crop_imm(x, y, cw, ch))
} else {
Cow::Borrowed(img)
};
let (cw, ch) = cropped.dimensions();
let max_dim = cw.max(ch) as f32;
let scale = (target_size as f32 * (scale_percent / 100.0)) / max_dim;
let new_w = (cw as f32 * scale).round() as u32;
let new_h = (ch as f32 * scale).round() as u32;
let resized = resize_image(&cropped, new_w, new_h);
// Place on transparent square canvas
let mut canvas = ImageBuffer::from_pixel(target_size, target_size, Rgba([0, 0, 0, 0]));
let offset_x = if new_w > target_size {
// Image wider than canvas → start at negative offset
-((new_w - target_size) as i32 / 2)
} else {
(target_size - new_w) as i32 / 2
};
let offset_y = if new_h > target_size {
-((new_h - target_size) as i32 / 2)
} else {
(target_size - new_h) as i32 / 2
};
image::imageops::overlay(&mut canvas, &resized, offset_x.into(), offset_y.into());
DynamicImage::ImageRgba8(canvas)
}
fn apply_round_mask(
img: &DynamicImage,
target_size: u32,
margin: u32,
radius: u32,
) -> DynamicImage {
// Clamp radius to half of inner size
let inner_size = target_size.saturating_sub(2 * margin);
let radius = radius.min(inner_size / 2);
// Resize inner image to fit inside margins
let resized = img.resize_exact(inner_size, inner_size, image::imageops::Lanczos3);
// Prepare output canvas
let mut out = ImageBuffer::from_pixel(target_size, target_size, Rgba([0, 0, 0, 0]));
// Draw the resized image at (margin, margin)
image::imageops::overlay(&mut out, &resized, margin as i64, margin as i64);
// Apply rounded corners
for y in 0..target_size {
for x in 0..target_size {
let inside = if x >= margin + radius
&& x < target_size - margin - radius
&& y >= margin + radius
&& y < target_size - margin - radius
{
true // inside central rectangle
} else {
// Determine corner centers
let (cx, cy) = if x < margin + radius && y < margin + radius {
(margin + radius, margin + radius) // top-left
} else if x >= target_size - margin - radius && y < margin + radius {
(target_size - margin - radius, margin + radius) // top-right
} else if x < margin + radius && y >= target_size - margin - radius {
(margin + radius, target_size - margin - radius) // bottom-left
} else if x >= target_size - margin - radius && y >= target_size - margin - radius {
(target_size - margin - radius, target_size - margin - radius) // bottom-right
} else {
continue; // edges that are not corners are inside
};
let dx = x as i32 - cx as i32;
let dy = y as i32 - cy as i32;
dx * dx + dy * dy <= (radius as i32 * radius as i32)
};
if !inside {
out.put_pixel(x, y, Rgba([0, 0, 0, 0]));
}
}
}
DynamicImage::ImageRgba8(out)
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/dev.rs | crates/tauri-cli/src/dev.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{
error::{Context, ErrorExt},
helpers::{
app_paths::{frontend_dir, tauri_dir},
command_env,
config::{
get as get_config, reload as reload_config, BeforeDevCommand, ConfigHandle, FrontendDist,
},
},
info::plugins::check_mismatched_packages,
interface::{AppInterface, ExitReason, Interface},
CommandExt, ConfigValue, Error, Result,
};
use clap::{ArgAction, Parser};
use shared_child::SharedChild;
use tauri_utils::{config::RunnerConfig, platform::Target};
use std::{
env::set_current_dir,
net::{IpAddr, Ipv4Addr},
path::PathBuf,
process::{exit, Command, Stdio},
sync::{
atomic::{AtomicBool, Ordering},
Arc, Mutex, OnceLock,
},
};
mod builtin_dev_server;
static BEFORE_DEV: OnceLock<Mutex<Arc<SharedChild>>> = OnceLock::new();
static KILL_BEFORE_DEV_FLAG: AtomicBool = AtomicBool::new(false);
#[cfg(unix)]
const KILL_CHILDREN_SCRIPT: &[u8] = include_bytes!("../scripts/kill-children.sh");
pub const TAURI_CLI_BUILTIN_WATCHER_IGNORE_FILE: &[u8] =
include_bytes!("../tauri-dev-watcher.gitignore");
#[derive(Debug, Clone, Parser)]
#[clap(
about = "Run your app in development mode",
long_about = "Run your app in development mode with hot-reloading for the Rust code. It makes use of the `build.devUrl` property from your `tauri.conf.json` file. It also runs your `build.beforeDevCommand` which usually starts your frontend devServer.",
trailing_var_arg(true)
)]
pub struct Options {
/// Binary to use to run the application
#[clap(short, long)]
pub runner: Option<RunnerConfig>,
/// Target triple to build against
#[clap(short, long)]
pub target: Option<String>,
/// List of cargo features to activate
#[clap(short, long, action = ArgAction::Append, num_args(0..))]
pub features: Vec<String>,
/// Exit on panic
#[clap(short, long)]
pub exit_on_panic: bool,
/// JSON strings or paths to JSON, JSON5 or TOML files to merge with the default configuration file
///
/// Configurations are merged in the order they are provided, which means a particular value overwrites previous values when a config key-value pair conflicts.
///
/// Note that a platform-specific file is looked up and merged with the default file by default
/// (tauri.macos.conf.json, tauri.linux.conf.json, tauri.windows.conf.json, tauri.android.conf.json and tauri.ios.conf.json)
/// but you can use this for more specific use cases such as different build flavors.
#[clap(short, long)]
pub config: Vec<ConfigValue>,
/// Run the code in release mode
#[clap(long = "release")]
pub release_mode: bool,
/// Command line arguments passed to the runner.
/// Use `--` to explicitly mark the start of the arguments. Arguments after a second `--` are passed to the application
/// e.g. `tauri dev -- [runnerArgs] -- [appArgs]`.
pub args: Vec<String>,
/// Skip waiting for the frontend dev server to start before building the tauri application.
#[clap(long, env = "TAURI_CLI_NO_DEV_SERVER_WAIT")]
pub no_dev_server_wait: bool,
/// Disable the file watcher.
#[clap(long)]
pub no_watch: bool,
/// Additional paths to watch for changes.
#[clap(long)]
pub additional_watch_folders: Vec<PathBuf>,
/// Disable the built-in dev server for static files.
#[clap(long)]
pub no_dev_server: bool,
/// Specify port for the built-in dev server for static files. Defaults to 1430.
#[clap(long, env = "TAURI_CLI_PORT")]
pub port: Option<u16>,
#[clap(skip)]
pub host: Option<IpAddr>,
}
pub fn command(options: Options) -> Result<()> {
crate::helpers::app_paths::resolve();
let r = command_internal(options);
if r.is_err() {
kill_before_dev_process();
}
r
}
fn command_internal(mut options: Options) -> Result<()> {
let target = options
.target
.as_deref()
.map(Target::from_triple)
.unwrap_or_else(Target::current);
let config = get_config(
target,
&options.config.iter().map(|c| &c.0).collect::<Vec<_>>(),
)?;
let mut interface = AppInterface::new(
config.lock().unwrap().as_ref().unwrap(),
options.target.clone(),
)?;
setup(&interface, &mut options, config)?;
let exit_on_panic = options.exit_on_panic;
let no_watch = options.no_watch;
interface.dev(options.into(), move |status, reason| {
on_app_exit(status, reason, exit_on_panic, no_watch)
})
}
pub fn setup(interface: &AppInterface, options: &mut Options, config: ConfigHandle) -> Result<()> {
let tauri_path = tauri_dir();
std::thread::spawn(|| {
if let Err(error) = check_mismatched_packages(frontend_dir(), tauri_path) {
log::error!("{error}");
}
});
set_current_dir(tauri_path).context("failed to set current directory")?;
if let Some(before_dev) = config
.lock()
.unwrap()
.as_ref()
.unwrap()
.build
.before_dev_command
.clone()
{
let (script, script_cwd, wait) = match before_dev {
BeforeDevCommand::Script(s) if s.is_empty() => (None, None, false),
BeforeDevCommand::Script(s) => (Some(s), None, false),
BeforeDevCommand::ScriptWithOptions { script, cwd, wait } => {
(Some(script), cwd.map(Into::into), wait)
}
};
let cwd = script_cwd.unwrap_or_else(|| frontend_dir().clone());
if let Some(before_dev) = script {
log::info!(action = "Running"; "BeforeDevCommand (`{}`)", before_dev);
let mut env = command_env(true);
env.extend(interface.env());
#[cfg(windows)]
let mut command = {
let mut command = Command::new("cmd");
command
.arg("/S")
.arg("/C")
.arg(&before_dev)
.current_dir(cwd)
.envs(env);
command
};
#[cfg(not(windows))]
let mut command = {
let mut command = Command::new("sh");
command
.arg("-c")
.arg(&before_dev)
.current_dir(cwd)
.envs(env);
command
};
if wait {
let status = command.piped().map_err(|error| Error::CommandFailed {
command: format!(
"`{before_dev}` with `{}`",
if cfg!(windows) { "cmd /S /C" } else { "sh -c" }
),
error,
})?;
if !status.success() {
crate::error::bail!(
"beforeDevCommand `{}` failed with exit code {}",
before_dev,
status.code().unwrap_or_default()
);
}
} else {
command.stdin(Stdio::piped());
command.stdout(os_pipe::dup_stdout().unwrap());
command.stderr(os_pipe::dup_stderr().unwrap());
let child = SharedChild::spawn(&mut command)
.unwrap_or_else(|_| panic!("failed to run `{before_dev}`"));
let child = Arc::new(child);
let child_ = child.clone();
std::thread::spawn(move || {
let status = child_
.wait()
.expect("failed to wait on \"beforeDevCommand\"");
if !(status.success() || KILL_BEFORE_DEV_FLAG.load(Ordering::Relaxed)) {
log::error!("The \"beforeDevCommand\" terminated with a non-zero status code.");
exit(status.code().unwrap_or(1));
}
});
BEFORE_DEV.set(Mutex::new(child)).unwrap();
let _ = ctrlc::set_handler(move || {
kill_before_dev_process();
exit(130);
});
}
}
}
if options.runner.is_none() {
options.runner = config
.lock()
.unwrap()
.as_ref()
.unwrap()
.build
.runner
.clone();
}
let mut cargo_features = config
.lock()
.unwrap()
.as_ref()
.unwrap()
.build
.features
.clone()
.unwrap_or_default();
cargo_features.extend(options.features.clone());
let mut dev_url = config
.lock()
.unwrap()
.as_ref()
.unwrap()
.build
.dev_url
.clone();
let frontend_dist = config
.lock()
.unwrap()
.as_ref()
.unwrap()
.build
.frontend_dist
.clone();
if !options.no_dev_server && dev_url.is_none() {
if let Some(FrontendDist::Directory(path)) = &frontend_dist {
if path.exists() {
let path = path
.canonicalize()
.fs_context("failed to canonicalize path", path.to_path_buf())?;
let ip = options
.host
.unwrap_or_else(|| Ipv4Addr::new(127, 0, 0, 1).into());
let server_url = builtin_dev_server::start(path, ip, options.port)
.context("failed to start builtin dev server")?;
let server_url = format!("http://{server_url}");
dev_url = Some(server_url.parse().unwrap());
options.config.push(crate::ConfigValue(serde_json::json!({
"build": {
"devUrl": server_url
}
})));
reload_config(&options.config.iter().map(|c| &c.0).collect::<Vec<_>>())?;
}
}
}
if !options.no_dev_server_wait {
if let Some(url) = dev_url {
let host = url.host().expect("No host name in the URL");
let port = url
.port_or_known_default()
.expect("No port number in the URL");
let addrs;
let addr;
let addrs = match host {
url::Host::Domain(domain) => {
use std::net::ToSocketAddrs;
addrs = (domain, port).to_socket_addrs().unwrap();
addrs.as_slice()
}
url::Host::Ipv4(ip) => {
addr = (ip, port).into();
std::slice::from_ref(&addr)
}
url::Host::Ipv6(ip) => {
addr = (ip, port).into();
std::slice::from_ref(&addr)
}
};
let mut i = 0;
let sleep_interval = std::time::Duration::from_secs(2);
let timeout_duration = std::time::Duration::from_secs(1);
let max_attempts = 90;
'waiting: loop {
for addr in addrs.iter() {
if std::net::TcpStream::connect_timeout(addr, timeout_duration).is_ok() {
break 'waiting;
}
}
if i % 3 == 1 {
log::warn!("Waiting for your frontend dev server to start on {url}...",);
}
i += 1;
if i == max_attempts {
log::error!("Could not connect to `{url}` after {}s. Please make sure that is the URL to your dev server.", i * sleep_interval.as_secs());
exit(1);
}
std::thread::sleep(sleep_interval);
}
}
}
if options.additional_watch_folders.is_empty() {
options.additional_watch_folders.extend(
config
.lock()
.unwrap()
.as_ref()
.unwrap()
.build
.additional_watch_folders
.clone(),
);
}
Ok(())
}
pub fn on_app_exit(code: Option<i32>, reason: ExitReason, exit_on_panic: bool, no_watch: bool) {
if no_watch
|| (!matches!(reason, ExitReason::TriggeredKill)
&& (exit_on_panic || matches!(reason, ExitReason::NormalExit)))
{
kill_before_dev_process();
exit(code.unwrap_or(0));
}
}
pub fn kill_before_dev_process() {
if let Some(child) = BEFORE_DEV.get() {
let child = child.lock().unwrap();
if KILL_BEFORE_DEV_FLAG.load(Ordering::Relaxed) {
return;
}
KILL_BEFORE_DEV_FLAG.store(true, Ordering::Relaxed);
#[cfg(windows)]
{
let powershell_path = std::env::var("SYSTEMROOT").map_or_else(
|_| "powershell.exe".to_string(),
|p| format!("{p}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"),
);
let _ = Command::new(powershell_path)
.arg("-NoProfile")
.arg("-Command")
.arg(format!("function Kill-Tree {{ Param([int]$ppid); Get-CimInstance Win32_Process | Where-Object {{ $_.ParentProcessId -eq $ppid }} | ForEach-Object {{ Kill-Tree $_.ProcessId }}; Stop-Process -Id $ppid -ErrorAction SilentlyContinue }}; Kill-Tree {}", child.id()))
.status();
}
#[cfg(unix)]
{
use std::io::Write;
let mut kill_children_script_path = std::env::temp_dir();
kill_children_script_path.push("tauri-stop-dev-processes.sh");
if !kill_children_script_path.exists() {
if let Ok(mut file) = std::fs::File::create(&kill_children_script_path) {
use std::os::unix::fs::PermissionsExt;
let _ = file.write_all(KILL_CHILDREN_SCRIPT);
let mut permissions = file.metadata().unwrap().permissions();
permissions.set_mode(0o770);
let _ = file.set_permissions(permissions);
}
}
let _ = Command::new(&kill_children_script_path)
.arg(child.id().to_string())
.output();
}
let _ = child.kill();
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/lib.rs | crates/tauri-cli/src/lib.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! This Rust executable provides the full interface to all of the required activities for which the CLI is required. It will run on macOS, Windows, and Linux.
#![doc(
html_logo_url = "https://github.com/tauri-apps/tauri/raw/dev/.github/icon.png",
html_favicon_url = "https://github.com/tauri-apps/tauri/raw/dev/.github/icon.png"
)]
#![cfg(any(target_os = "macos", target_os = "linux", windows))]
mod acl;
mod add;
mod build;
mod bundle;
mod completions;
mod dev;
mod error;
mod helpers;
mod icon;
mod info;
mod init;
mod inspect;
mod interface;
mod migrate;
mod mobile;
mod plugin;
mod remove;
mod signer;
use clap::{ArgAction, CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum};
use env_logger::fmt::style::{AnsiColor, Style};
use env_logger::Builder;
pub use error::{Error, ErrorExt, Result};
use log::Level;
use serde::{Deserialize, Serialize};
use std::io::{BufReader, Write};
use std::process::{exit, Command, ExitStatus, Output, Stdio};
use std::{
ffi::OsString,
fmt::Display,
fs::read_to_string,
io::BufRead,
path::PathBuf,
str::FromStr,
sync::{Arc, Mutex},
};
use crate::error::Context;
/// Tauri configuration argument option.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConfigValue(pub(crate) serde_json::Value);
impl FromStr for ConfigValue {
type Err = Error;
fn from_str(config: &str) -> std::result::Result<Self, Self::Err> {
if config.starts_with('{') {
Ok(Self(serde_json::from_str(config).with_context(|| {
format!("failed to parse config `{config}` as JSON")
})?))
} else {
let path = PathBuf::from(config);
let raw =
read_to_string(&path).fs_context("failed to read configuration file", path.clone())?;
match path.extension().and_then(|ext| ext.to_str()) {
Some("toml") => Ok(Self(::toml::from_str(&raw).with_context(|| {
format!("failed to parse config at {} as TOML", path.display())
})?)),
Some("json5") => Ok(Self(::json5::from_str(&raw).with_context(|| {
format!("failed to parse config at {} as JSON5", path.display())
})?)),
// treat all other extensions as json
_ => Ok(Self(
// from tauri-utils/src/config/parse.rs:
// we also want to support **valid** json5 in the .json extension
// if the json5 is not valid the serde_json error for regular json will be returned.
match ::json5::from_str(&raw) {
Ok(json5) => json5,
Err(_) => serde_json::from_str(&raw)
.with_context(|| format!("failed to parse config at {} as JSON", path.display()))?,
},
)),
}
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
pub enum RunMode {
Desktop,
#[cfg(target_os = "macos")]
Ios,
Android,
}
impl Display for RunMode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
Self::Desktop => "desktop",
#[cfg(target_os = "macos")]
Self::Ios => "iOS",
Self::Android => "android",
}
)
}
}
#[derive(Deserialize)]
pub struct VersionMetadata {
tauri: String,
#[serde(rename = "tauri-build")]
tauri_build: String,
#[serde(rename = "tauri-plugin")]
tauri_plugin: String,
}
#[derive(Deserialize)]
pub struct PackageJson {
name: Option<String>,
version: Option<String>,
product_name: Option<String>,
}
#[derive(Parser)]
#[clap(
author,
version,
about,
bin_name("cargo-tauri"),
subcommand_required(true),
arg_required_else_help(true),
propagate_version(true),
no_binary_name(true)
)]
pub(crate) struct Cli {
/// Enables verbose logging
#[clap(short, long, global = true, action = ArgAction::Count)]
verbose: u8,
#[clap(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
Init(init::Options),
Dev(dev::Options),
Build(build::Options),
Bundle(bundle::Options),
Android(mobile::android::Cli),
#[cfg(target_os = "macos")]
Ios(mobile::ios::Cli),
/// Migrate from v1 to v2
Migrate,
Info(info::Options),
Add(add::Options),
Remove(remove::Options),
Plugin(plugin::Cli),
Icon(icon::Options),
Signer(signer::Cli),
Completions(completions::Options),
Permission(acl::permission::Cli),
Capability(acl::capability::Cli),
Inspect(inspect::Cli),
}
fn format_error<I: CommandFactory>(err: clap::Error) -> clap::Error {
let mut app = I::command();
err.format(&mut app)
}
fn get_verbosity(cli_verbose: u8) -> u8 {
std::env::var("TAURI_CLI_VERBOSITY")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(cli_verbose)
}
/// Run the Tauri CLI with the passed arguments, exiting if an error occurs.
///
/// The passed arguments should have the binary argument(s) stripped out before being passed.
///
/// e.g.
/// 1. `tauri-cli 1 2 3` -> `1 2 3`
/// 2. `cargo tauri 1 2 3` -> `1 2 3`
/// 3. `node tauri.js 1 2 3` -> `1 2 3`
///
/// The passed `bin_name` parameter should be how you want the help messages to display the command.
/// This defaults to `cargo-tauri`, but should be set to how the program was called, such as
/// `cargo tauri`.
pub fn run<I, A>(args: I, bin_name: Option<String>)
where
I: IntoIterator<Item = A>,
A: Into<OsString> + Clone,
{
if let Err(e) = try_run(args, bin_name) {
log::error!("{e}");
exit(1);
}
}
/// Run the Tauri CLI with the passed arguments.
///
/// It is similar to [`run`], but instead of exiting on an error, it returns a result.
pub fn try_run<I, A>(args: I, bin_name: Option<String>) -> Result<()>
where
I: IntoIterator<Item = A>,
A: Into<OsString> + Clone,
{
let cli = match bin_name {
Some(bin_name) => Cli::command().bin_name(bin_name),
None => Cli::command(),
};
let cli_ = cli.clone();
let matches = cli.get_matches_from(args);
let res = Cli::from_arg_matches(&matches).map_err(format_error::<Cli>);
let cli = match res {
Ok(s) => s,
Err(e) => e.exit(),
};
// set the verbosity level so subsequent CLI calls (xcode-script, android-studio-script) refer to it
let verbosity_number = get_verbosity(cli.verbose);
std::env::set_var("TAURI_CLI_VERBOSITY", verbosity_number.to_string());
let mut builder = Builder::from_default_env();
if let Err(err) = builder
.format_indent(Some(12))
.filter(None, verbosity_level(verbosity_number).to_level_filter())
// golbin spams an insane amount of really technical logs on the debug level so we're reducing one level
.filter(
Some("goblin"),
verbosity_level(verbosity_number.saturating_sub(1)).to_level_filter(),
)
// handlebars is not that spammy but its debug logs are typically far from being helpful
.filter(
Some("handlebars"),
verbosity_level(verbosity_number.saturating_sub(1)).to_level_filter(),
)
.format(|f, record| {
let mut is_command_output = false;
if let Some(action) = record.key_values().get("action".into()) {
let action = action.to_cow_str().unwrap();
is_command_output = action == "stdout" || action == "stderr";
if !is_command_output {
let style = Style::new().fg_color(Some(AnsiColor::Green.into())).bold();
write!(f, "{style}{action:>12}{style:#} ")?;
}
} else {
let style = f.default_level_style(record.level()).bold();
write!(
f,
"{style}{:>12}{style:#} ",
prettyprint_level(record.level())
)?;
}
if !is_command_output && log::log_enabled!(Level::Debug) {
let style = Style::new().fg_color(Some(AnsiColor::Black.into()));
write!(f, "[{style}{}{style:#}] ", record.target())?;
}
writeln!(f, "{}", record.args())
})
.try_init()
{
eprintln!("Failed to attach logger: {err}");
}
match cli.command {
Commands::Build(options) => build::command(options, cli.verbose)?,
Commands::Bundle(options) => bundle::command(options, cli.verbose)?,
Commands::Dev(options) => dev::command(options)?,
Commands::Add(options) => add::command(options)?,
Commands::Remove(options) => remove::command(options)?,
Commands::Icon(options) => icon::command(options)?,
Commands::Info(options) => info::command(options)?,
Commands::Init(options) => init::command(options)?,
Commands::Plugin(cli) => plugin::command(cli)?,
Commands::Signer(cli) => signer::command(cli)?,
Commands::Completions(options) => completions::command(options, cli_)?,
Commands::Permission(options) => acl::permission::command(options)?,
Commands::Capability(options) => acl::capability::command(options)?,
Commands::Android(c) => mobile::android::command(c, cli.verbose)?,
#[cfg(target_os = "macos")]
Commands::Ios(c) => mobile::ios::command(c, cli.verbose)?,
Commands::Migrate => migrate::command()?,
Commands::Inspect(cli) => inspect::command(cli)?,
}
Ok(())
}
/// This maps the occurrence of `--verbose` flags to the correct log level
fn verbosity_level(num: u8) -> Level {
match num {
0 => Level::Info,
1 => Level::Debug,
_ => Level::Trace,
}
}
/// The default string representation for `Level` is all uppercaps which doesn't mix well with the other printed actions.
fn prettyprint_level(lvl: Level) -> &'static str {
match lvl {
Level::Error => "Error",
Level::Warn => "Warn",
Level::Info => "Info",
Level::Debug => "Debug",
Level::Trace => "Trace",
}
}
pub trait CommandExt {
// The `pipe` function sets the stdout and stderr to properly
// show the command output in the Node.js wrapper.
fn piped(&mut self) -> std::io::Result<ExitStatus>;
fn output_ok(&mut self) -> crate::Result<Output>;
}
impl CommandExt for Command {
fn piped(&mut self) -> std::io::Result<ExitStatus> {
self.stdin(os_pipe::dup_stdin()?);
self.stdout(os_pipe::dup_stdout()?);
self.stderr(os_pipe::dup_stderr()?);
let program = self.get_program().to_string_lossy().into_owned();
let args = self
.get_args()
.map(|a| a.to_string_lossy())
.collect::<Vec<_>>()
.join(" ");
log::debug!(action = "Running"; "Command `{program} {args}`");
self.status()
}
fn output_ok(&mut self) -> crate::Result<Output> {
let program = self.get_program().to_string_lossy().into_owned();
let args = self
.get_args()
.map(|a| a.to_string_lossy())
.collect::<Vec<_>>()
.join(" ");
let cmdline = format!("{program} {args}");
log::debug!(action = "Running"; "Command `{cmdline}`");
self.stdout(Stdio::piped());
self.stderr(Stdio::piped());
let mut child = self
.spawn()
.with_context(|| format!("failed to run command `{cmdline}`"))?;
let mut stdout = child.stdout.take().map(BufReader::new).unwrap();
let stdout_lines = Arc::new(Mutex::new(Vec::new()));
let stdout_lines_ = stdout_lines.clone();
std::thread::spawn(move || {
let mut line = String::new();
if let Ok(mut lines) = stdout_lines_.lock() {
loop {
line.clear();
match stdout.read_line(&mut line) {
Ok(0) => break,
Ok(_) => {
log::debug!(action = "stdout"; "{}", line.trim_end());
lines.extend(line.as_bytes());
}
Err(_) => (),
}
}
}
});
let mut stderr = child.stderr.take().map(BufReader::new).unwrap();
let stderr_lines = Arc::new(Mutex::new(Vec::new()));
let stderr_lines_ = stderr_lines.clone();
std::thread::spawn(move || {
let mut line = String::new();
if let Ok(mut lines) = stderr_lines_.lock() {
loop {
line.clear();
match stderr.read_line(&mut line) {
Ok(0) => break,
Ok(_) => {
log::debug!(action = "stderr"; "{}", line.trim_end());
lines.extend(line.as_bytes());
}
Err(_) => (),
}
}
}
});
let status = child
.wait()
.with_context(|| format!("failed to run command `{cmdline}`"))?;
let output = Output {
status,
stdout: std::mem::take(&mut *stdout_lines.lock().unwrap()),
stderr: std::mem::take(&mut *stderr_lines.lock().unwrap()),
};
if output.status.success() {
Ok(output)
} else {
crate::error::bail!(
"failed to run command `{cmdline}`: command exited with status code {}",
output.status.code().unwrap_or(-1)
);
}
}
}
#[cfg(test)]
mod tests {
use clap::CommandFactory;
use crate::Cli;
#[test]
fn verify_cli() {
Cli::command().debug_assert();
}
#[test]
fn help_output_includes_build() {
let help = Cli::command().render_help().to_string();
assert!(help.contains("Build"));
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/bundle.rs | crates/tauri-cli/src/bundle.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{
path::{Path, PathBuf},
str::FromStr,
sync::OnceLock,
};
use clap::{builder::PossibleValue, ArgAction, Parser, ValueEnum};
use tauri_bundler::PackageType;
use tauri_utils::platform::Target;
use crate::{
error::{Context, ErrorExt},
helpers::{
self,
app_paths::tauri_dir,
config::{get as get_config, ConfigMetadata},
updater_signature,
},
interface::{AppInterface, AppSettings, Interface},
ConfigValue,
};
#[derive(Debug, Clone)]
pub struct BundleFormat(PackageType);
impl FromStr for BundleFormat {
type Err = crate::Error;
fn from_str(s: &str) -> crate::Result<Self> {
PackageType::from_short_name(s)
.map(Self)
.with_context(|| format!("unknown bundle format {s}"))
}
}
impl ValueEnum for BundleFormat {
fn value_variants<'a>() -> &'a [Self] {
static VARIANTS: OnceLock<Vec<BundleFormat>> = OnceLock::new();
VARIANTS.get_or_init(|| PackageType::all().iter().map(|t| Self(*t)).collect())
}
fn to_possible_value(&self) -> Option<PossibleValue> {
let hide = self.0 == PackageType::Updater;
Some(PossibleValue::new(self.0.short_name()).hide(hide))
}
}
#[derive(Debug, Parser, Clone)]
#[clap(
about = "Generate bundles and installers for your app (already built by `tauri build`)",
long_about = "Generate bundles and installers for your app (already built by `tauri build`). This run `build.beforeBundleCommand` before generating the bundles and installers of your app."
)]
pub struct Options {
/// Builds with the debug flag
#[clap(short, long)]
pub debug: bool,
/// Space or comma separated list of bundles to package.
#[clap(short, long, action = ArgAction::Append, num_args(0..), value_delimiter = ',')]
pub bundles: Option<Vec<BundleFormat>>,
/// JSON strings or paths to JSON, JSON5 or TOML files to merge with the default configuration file
///
/// Configurations are merged in the order they are provided, which means a particular value overwrites previous values when a config key-value pair conflicts.
///
/// Note that a platform-specific file is looked up and merged with the default file by default
/// (tauri.macos.conf.json, tauri.linux.conf.json, tauri.windows.conf.json, tauri.android.conf.json and tauri.ios.conf.json)
/// but you can use this for more specific use cases such as different build flavors.
#[clap(short, long)]
pub config: Vec<ConfigValue>,
/// Space or comma separated list of features, should be the same features passed to `tauri build` if any.
#[clap(short, long, action = ArgAction::Append, num_args(0..))]
pub features: Vec<String>,
/// Target triple to build against.
///
/// It must be one of the values outputted by `$rustc --print target-list` or `universal-apple-darwin` for an universal macOS application.
///
/// Note that compiling an universal macOS application requires both `aarch64-apple-darwin` and `x86_64-apple-darwin` targets to be installed.
#[clap(short, long)]
pub target: Option<String>,
/// Skip prompting for values
#[clap(long, env = "CI")]
pub ci: bool,
/// Whether to wait for notarization to finish and `staple` the ticket onto the app.
///
/// Gatekeeper will look for stapled tickets to tell whether your app was notarized without
/// reaching out to Apple's servers which is helpful in offline environments.
///
/// Enabling this option will also result in `tauri build` not waiting for notarization to finish
/// which is helpful for the very first time your app is notarized as this can take multiple hours.
/// On subsequent runs, it's recommended to disable this setting again.
#[clap(long)]
pub skip_stapling: bool,
/// Skip code signing during the build or bundling process.
///
/// Useful for local development and CI environments
/// where signing certificates or environment variables
/// are not available or not needed.
#[clap(long)]
pub no_sign: bool,
}
impl From<crate::build::Options> for Options {
fn from(value: crate::build::Options) -> Self {
Self {
bundles: value.bundles,
target: value.target,
features: value.features,
debug: value.debug,
ci: value.ci,
config: value.config,
skip_stapling: value.skip_stapling,
no_sign: value.no_sign,
}
}
}
pub fn command(options: Options, verbosity: u8) -> crate::Result<()> {
crate::helpers::app_paths::resolve();
let ci = options.ci;
let target = options
.target
.as_deref()
.map(Target::from_triple)
.unwrap_or_else(Target::current);
let config = get_config(
target,
&options.config.iter().map(|c| &c.0).collect::<Vec<_>>(),
)?;
let interface = AppInterface::new(
config.lock().unwrap().as_ref().unwrap(),
options.target.clone(),
)?;
let tauri_path = tauri_dir();
std::env::set_current_dir(tauri_path).context("failed to set current directory")?;
let config_guard = config.lock().unwrap();
let config_ = config_guard.as_ref().unwrap();
if let Some(minimum_system_version) = &config_.bundle.macos.minimum_system_version {
std::env::set_var("MACOSX_DEPLOYMENT_TARGET", minimum_system_version);
}
let app_settings = interface.app_settings();
let interface_options = options.clone().into();
let out_dir = app_settings.out_dir(&interface_options)?;
bundle(
&options,
verbosity,
ci,
&interface,
&*app_settings,
config_,
&out_dir,
)
}
#[allow(clippy::too_many_arguments)]
pub fn bundle<A: AppSettings>(
options: &Options,
verbosity: u8,
ci: bool,
interface: &AppInterface,
app_settings: &A,
config: &ConfigMetadata,
out_dir: &Path,
) -> crate::Result<()> {
let package_types: Vec<PackageType> = if let Some(bundles) = &options.bundles {
bundles.iter().map(|bundle| bundle.0).collect::<Vec<_>>()
} else {
config
.bundle
.targets
.to_vec()
.into_iter()
.map(Into::into)
.collect()
};
if package_types.is_empty() {
return Ok(());
}
// if we have a package to bundle, let's run the `before_bundle_command`.
if !package_types.is_empty() {
if let Some(before_bundle) = config.build.before_bundle_command.clone() {
helpers::run_hook(
"beforeBundleCommand",
before_bundle,
interface,
options.debug,
)?;
}
}
let mut settings = app_settings
.get_bundler_settings(options.clone().into(), config, out_dir, package_types)
.with_context(|| "failed to build bundler settings")?;
settings.set_no_sign(options.no_sign);
settings.set_log_level(match verbosity {
0 => log::Level::Error,
1 => log::Level::Info,
_ => log::Level::Trace,
});
let bundles = tauri_bundler::bundle_project(&settings).map_err(Box::new)?;
sign_updaters(settings, bundles, ci)?;
Ok(())
}
fn sign_updaters(
settings: tauri_bundler::Settings,
bundles: Vec<tauri_bundler::Bundle>,
ci: bool,
) -> crate::Result<()> {
let Some(update_settings) = settings.updater() else {
// Updater not enabled
return Ok(());
};
let update_enabled_bundles: Vec<&tauri_bundler::Bundle> = bundles
.iter()
.filter(|bundle| {
matches!(
bundle.package_type,
PackageType::Updater
| PackageType::Nsis
| PackageType::WindowsMsi
| PackageType::AppImage
| PackageType::Deb
| PackageType::Rpm
)
})
.collect();
if update_enabled_bundles.is_empty() {
return Ok(());
}
if settings.no_sign() {
log::warn!("Updater signing is skipped due to --no-sign flag.");
return Ok(());
}
// get the public key
let pubkey = &update_settings.pubkey;
// check if pubkey points to a file...
let maybe_path = Path::new(pubkey);
let pubkey = if maybe_path.exists() {
std::fs::read_to_string(maybe_path)
.fs_context("failed to read pubkey from file", maybe_path.to_path_buf())?
} else {
pubkey.to_string()
};
// if no password provided we use an empty string
let password = std::env::var("TAURI_SIGNING_PRIVATE_KEY_PASSWORD")
.ok()
.or_else(|| if ci { Some("".into()) } else { None });
// get the private key
let private_key = std::env::var("TAURI_SIGNING_PRIVATE_KEY")
.ok()
.context("A public key has been found, but no private key. Make sure to set `TAURI_SIGNING_PRIVATE_KEY` environment variable.")?;
// check if private_key points to a file...
let maybe_path = Path::new(&private_key);
let private_key = if maybe_path.exists() {
std::fs::read_to_string(maybe_path).fs_context(
"failed to read private key from file",
maybe_path.to_path_buf(),
)?
} else {
private_key
};
let secret_key =
updater_signature::secret_key(private_key, password).context("failed to decode secret key")?;
let public_key = updater_signature::pub_key(pubkey).context("failed to decode pubkey")?;
let mut signed_paths = Vec::new();
for bundle in update_enabled_bundles {
// we expect to have only one path in the vec but we iter if we add
// another type of updater package who require multiple file signature
for path in &bundle.bundle_paths {
// sign our path from environment variables
let (signature_path, signature) = updater_signature::sign_file(&secret_key, path)?;
if signature.keynum() != public_key.keynum() {
log::warn!("The updater secret key from `TAURI_SIGNING_PRIVATE_KEY` does not match the public key from `plugins > updater > pubkey`. If you are not rotating keys, this means your configuration is wrong and won't be accepted at runtime when performing update.");
}
signed_paths.push(signature_path);
}
}
print_signed_updater_archive(&signed_paths)?;
Ok(())
}
fn print_signed_updater_archive(output_paths: &[PathBuf]) -> crate::Result<()> {
use std::fmt::Write;
if !output_paths.is_empty() {
let finished_bundles = output_paths.len();
let pluralised = if finished_bundles == 1 {
"updater signature"
} else {
"updater signatures"
};
let mut printable_paths = String::new();
for path in output_paths {
let _ = writeln!(
printable_paths,
" {}",
tauri_utils::display_path(path)
);
}
log::info!( action = "Finished"; "{finished_bundles} {pluralised} at:\n{printable_paths}");
}
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/error.rs | crates/tauri-cli/src/error.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{fmt::Display, path::PathBuf};
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("{0}: {1}")]
Context(String, Box<dyn std::error::Error + Send + Sync + 'static>),
#[error("{0}")]
GenericError(String),
#[error("failed to bundle project {0}")]
Bundler(#[from] Box<tauri_bundler::Error>),
#[error("{context} {path}: {error}")]
Fs {
context: &'static str,
path: PathBuf,
error: std::io::Error,
},
#[error("failed to run command {command}: {error}")]
CommandFailed {
command: String,
error: std::io::Error,
},
#[cfg(target_os = "macos")]
#[error(transparent)]
MacosSign(#[from] Box<tauri_macos_sign::Error>),
}
/// Convenient type alias of Result type.
pub type Result<T> = std::result::Result<T, Error>;
pub trait Context<T> {
// Required methods
fn context<C>(self, context: C) -> Result<T>
where
C: Display + Send + Sync + 'static;
fn with_context<C, F>(self, f: F) -> Result<T>
where
C: Display + Send + Sync + 'static,
F: FnOnce() -> C;
}
impl<T, E: std::error::Error + Send + Sync + 'static> Context<T> for std::result::Result<T, E> {
fn context<C>(self, context: C) -> Result<T>
where
C: Display + Send + Sync + 'static,
{
self.map_err(|e| Error::Context(context.to_string(), Box::new(e)))
}
fn with_context<C, F>(self, f: F) -> Result<T>
where
C: Display + Send + Sync + 'static,
F: FnOnce() -> C,
{
self.map_err(|e| Error::Context(f().to_string(), Box::new(e)))
}
}
impl<T> Context<T> for Option<T> {
fn context<C>(self, context: C) -> Result<T>
where
C: Display + Send + Sync + 'static,
{
self.ok_or_else(|| Error::GenericError(context.to_string()))
}
fn with_context<C, F>(self, f: F) -> Result<T>
where
C: Display + Send + Sync + 'static,
F: FnOnce() -> C,
{
self.ok_or_else(|| Error::GenericError(f().to_string()))
}
}
pub trait ErrorExt<T> {
fn fs_context(self, context: &'static str, path: impl Into<PathBuf>) -> Result<T>;
}
impl<T> ErrorExt<T> for std::result::Result<T, std::io::Error> {
fn fs_context(self, context: &'static str, path: impl Into<PathBuf>) -> Result<T> {
self.map_err(|error| Error::Fs {
context,
path: path.into(),
error,
})
}
}
macro_rules! bail {
($msg:literal $(,)?) => {
return Err(crate::Error::GenericError($msg.into()))
};
($err:expr $(,)?) => {
return Err(crate::Error::GenericError($err))
};
($fmt:expr, $($arg:tt)*) => {
return Err(crate::Error::GenericError(format!($fmt, $($arg)*)))
};
}
pub(crate) use bail;
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/build.rs | crates/tauri-cli/src/build.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{
bundle::BundleFormat,
error::{Context, ErrorExt},
helpers::{
self,
app_paths::{frontend_dir, tauri_dir},
config::{get as get_config, ConfigMetadata, FrontendDist},
},
info::plugins::check_mismatched_packages,
interface::{rust::get_cargo_target_dir, AppInterface, Interface},
ConfigValue, Result,
};
use clap::{ArgAction, Parser};
use std::env::set_current_dir;
use tauri_utils::config::RunnerConfig;
use tauri_utils::platform::Target;
#[derive(Debug, Clone, Parser)]
#[clap(
about = "Build your app in release mode and generate bundles and installers",
long_about = "Build your app in release mode and generate bundles and installers. It makes use of the `build.frontendDist` property from your `tauri.conf.json` file. It also runs your `build.beforeBuildCommand` which usually builds your frontend into `build.frontendDist`. This will also run `build.beforeBundleCommand` before generating the bundles and installers of your app."
)]
pub struct Options {
/// Binary to use to build the application, defaults to `cargo`
#[clap(short, long)]
pub runner: Option<RunnerConfig>,
/// Builds with the debug flag
#[clap(short, long)]
pub debug: bool,
/// Target triple to build against.
///
/// It must be one of the values outputted by `$rustc --print target-list` or `universal-apple-darwin` for an universal macOS application.
///
/// Note that compiling an universal macOS application requires both `aarch64-apple-darwin` and `x86_64-apple-darwin` targets to be installed.
#[clap(short, long)]
pub target: Option<String>,
/// Space or comma separated list of features to activate
#[clap(short, long, action = ArgAction::Append, num_args(0..))]
pub features: Vec<String>,
/// Space or comma separated list of bundles to package.
#[clap(short, long, action = ArgAction::Append, num_args(0..), value_delimiter = ',')]
pub bundles: Option<Vec<BundleFormat>>,
/// Skip the bundling step even if `bundle > active` is `true` in tauri config.
#[clap(long)]
pub no_bundle: bool,
/// JSON strings or paths to JSON, JSON5 or TOML files to merge with the default configuration file
///
/// Configurations are merged in the order they are provided, which means a particular value overwrites previous values when a config key-value pair conflicts.
///
/// Note that a platform-specific file is looked up and merged with the default file by default
/// (tauri.macos.conf.json, tauri.linux.conf.json, tauri.windows.conf.json, tauri.android.conf.json and tauri.ios.conf.json)
/// but you can use this for more specific use cases such as different build flavors.
#[clap(short, long)]
pub config: Vec<ConfigValue>,
/// Command line arguments passed to the runner. Use `--` to explicitly mark the start of the arguments.
pub args: Vec<String>,
/// Skip prompting for values
#[clap(long, env = "CI")]
pub ci: bool,
/// Whether to wait for notarization to finish and `staple` the ticket onto the app.
///
/// Gatekeeper will look for stapled tickets to tell whether your app was notarized without
/// reaching out to Apple's servers which is helpful in offline environments.
///
/// Enabling this option will also result in `tauri build` not waiting for notarization to finish
/// which is helpful for the very first time your app is notarized as this can take multiple hours.
/// On subsequent runs, it's recommended to disable this setting again.
#[clap(long)]
pub skip_stapling: bool,
/// Do not error out if a version mismatch is detected on a Tauri package.
///
/// Only use this when you are sure the mismatch is incorrectly detected as version mismatched Tauri packages can lead to unknown behavior.
#[clap(long)]
pub ignore_version_mismatches: bool,
/// Skip code signing when bundling the app
#[clap(long)]
pub no_sign: bool,
}
pub fn command(mut options: Options, verbosity: u8) -> Result<()> {
crate::helpers::app_paths::resolve();
if options.no_sign {
log::warn!("--no-sign flag detected: Signing will be skipped.");
}
let ci = options.ci;
let target = options
.target
.as_deref()
.map(Target::from_triple)
.unwrap_or_else(Target::current);
let config = get_config(
target,
&options.config.iter().map(|c| &c.0).collect::<Vec<_>>(),
)?;
let mut interface = AppInterface::new(
config.lock().unwrap().as_ref().unwrap(),
options.target.clone(),
)?;
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);
}
let app_settings = interface.app_settings();
let interface_options = options.clone().into();
let out_dir = app_settings.out_dir(&interface_options)?;
let bin_path = interface.build(interface_options)?;
log::info!(action ="Built"; "application at: {}", tauri_utils::display_path(bin_path));
let app_settings = interface.app_settings();
if !options.no_bundle && (config_.bundle.active || options.bundles.is_some()) {
crate::bundle::bundle(
&options.into(),
verbosity,
ci,
&interface,
&*app_settings,
config_,
&out_dir,
)?;
}
Ok(())
}
pub fn setup(
interface: &AppInterface,
options: &mut Options,
config: &ConfigMetadata,
mobile: bool,
) -> Result<()> {
let tauri_path = tauri_dir();
// TODO: Maybe optimize this to run in parallel in the future
// see https://github.com/tauri-apps/tauri/pull/13993#discussion_r2280697117
log::info!("Looking up installed tauri packages to check mismatched versions...");
if let Err(error) = check_mismatched_packages(frontend_dir(), tauri_path) {
if options.ignore_version_mismatches {
log::error!("{error}");
} else {
return Err(error);
}
}
set_current_dir(tauri_path).context("failed to set current directory")?;
let bundle_identifier_source = config
.find_bundle_identifier_overwriter()
.unwrap_or_else(|| "tauri.conf.json".into());
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
.identifier
.chars()
.any(|ch| !(ch.is_alphanumeric() || ch == '-' || ch == '.'))
{
crate::error::bail!(
"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") {
log::warn!(
"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() {
helpers::run_hook("beforeBuildCommand", before_build, interface, options.debug)?;
}
if let Some(FrontendDist::Directory(web_asset_path)) = &config.build.frontend_dist {
if !web_asset_path.exists() {
let absolute_path = web_asset_path
.parent()
.and_then(|p| p.canonicalize().ok())
.map(|p| p.join(web_asset_path.file_name().unwrap()))
.unwrap_or_else(|| std::env::current_dir().unwrap().join(web_asset_path));
crate::error::bail!(
"Unable to find your web assets, did you forget to build your web app? Your frontendDist is set to \"{}\" (which is `{}`).",
web_asset_path.display(), absolute_path.display(),
);
}
if web_asset_path
.canonicalize()
.fs_context("failed to canonicalize path", web_asset_path.to_path_buf())?
.file_name()
== Some(std::ffi::OsStr::new("src-tauri"))
{
crate::error::bail!(
"The configured frontendDist is the `src-tauri` folder. Please isolate your web assets on a separate folder and update `tauri.conf.json > build > frontendDist`.",
);
}
// Issue #13287 - Allow the use of target dir inside frontendDist/distDir
// https://github.com/tauri-apps/tauri/issues/13287
let target_path = get_cargo_target_dir(&options.args)?;
let mut out_folders = Vec::new();
if let Ok(web_asset_canonical) = dunce::canonicalize(web_asset_path) {
if let Ok(relative_path) = target_path.strip_prefix(&web_asset_canonical) {
let relative_str = relative_path.to_string_lossy();
if !relative_str.is_empty() {
out_folders.push(relative_str.to_string());
}
}
for folder in &["node_modules", "src-tauri"] {
let sub_path = web_asset_canonical.join(folder);
if sub_path.is_dir() {
out_folders.push(folder.to_string());
}
}
}
if !out_folders.is_empty() {
crate::error::bail!(
"The configured frontendDist includes the `{:?}` {}. Please isolate your web assets on a separate folder and update `tauri.conf.json > build > frontendDist`.",
out_folders,
if out_folders.len() == 1 { "folder" } else { "folders" }
);
}
}
if options.runner.is_none() {
options.runner = config.build.runner.clone();
}
options
.features
.extend_from_slice(config.build.features.as_deref().unwrap_or_default());
interface.build_options(&mut options.args, &mut options.features, mobile);
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/init.rs | crates/tauri-cli/src/init.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{
helpers::{
framework::{infer_from_package_json as infer_framework, Framework},
npm::PackageManager,
prompts, resolve_tauri_path, template,
},
VersionMetadata,
};
use std::{
collections::BTreeMap,
env::current_dir,
fs::{read_to_string, remove_dir_all},
path::PathBuf,
};
use crate::{
error::{Context, ErrorExt},
Result,
};
use clap::Parser;
use handlebars::{to_json, Handlebars};
use include_dir::{include_dir, Dir};
const TEMPLATE_DIR: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/templates/app");
const TAURI_CONF_TEMPLATE: &str = include_str!("../templates/tauri.conf.json");
#[derive(Debug, Parser)]
#[clap(about = "Initialize a Tauri project in an existing directory")]
pub struct Options {
/// Skip prompting for values
#[clap(long, env = "CI")]
ci: bool,
/// Force init to overwrite the src-tauri folder
#[clap(short, long)]
force: bool,
/// Enables logging
#[clap(short, long)]
log: bool,
/// Set target directory for init
#[clap(short, long)]
#[clap(default_value_t = current_dir().expect("failed to read cwd").display().to_string())]
directory: String,
/// Path of the Tauri project to use (relative to the cwd)
#[clap(short, long)]
tauri_path: Option<PathBuf>,
/// Name of your Tauri application
#[clap(short = 'A', long)]
app_name: Option<String>,
/// Window title of your Tauri application
#[clap(short = 'W', long)]
window_title: Option<String>,
/// Web assets location, relative to <project-dir>/src-tauri
#[clap(short = 'D', long)]
frontend_dist: Option<String>,
/// Url of your dev server
#[clap(short = 'P', long)]
dev_url: Option<String>,
/// A shell command to run before `tauri dev` kicks in.
#[clap(long)]
before_dev_command: Option<String>,
/// A shell command to run before `tauri build` kicks in.
#[clap(long)]
before_build_command: Option<String>,
}
#[derive(Default)]
struct InitDefaults {
app_name: Option<String>,
framework: Option<Framework>,
}
impl Options {
fn load(mut self) -> Result<Self> {
let package_json_path = PathBuf::from(&self.directory).join("package.json");
let init_defaults = if package_json_path.exists() {
let package_json_text =
read_to_string(&package_json_path).fs_context("failed to read", &package_json_path)?;
let package_json: crate::PackageJson =
serde_json::from_str(&package_json_text).context("failed to parse JSON")?;
let (framework, _) = infer_framework(&package_json_text);
InitDefaults {
app_name: package_json.product_name.or(package_json.name),
framework,
}
} else {
Default::default()
};
self.app_name = self.app_name.map(|s| Ok(Some(s))).unwrap_or_else(|| {
prompts::input(
"What is your app name?",
Some(
init_defaults
.app_name
.clone()
.unwrap_or_else(|| "Tauri App".to_string()),
),
self.ci,
true,
)
})?;
self.window_title = self.window_title.map(|s| Ok(Some(s))).unwrap_or_else(|| {
prompts::input(
"What should the window title be?",
Some(
init_defaults
.app_name
.clone()
.unwrap_or_else(|| "Tauri".to_string()),
),
self.ci,
true,
)
})?;
self.frontend_dist = self.frontend_dist.map(|s| Ok(Some(s))).unwrap_or_else(|| prompts::input(
r#"Where are your web assets (HTML/CSS/JS) located, relative to the "<current dir>/src-tauri/tauri.conf.json" file that will be created?"#,
init_defaults.framework.as_ref().map(|f| f.frontend_dist()),
self.ci,
false,
))?;
self.dev_url = self.dev_url.map(|s| Ok(Some(s))).unwrap_or_else(|| {
prompts::input(
"What is the url of your dev server?",
init_defaults.framework.map(|f| f.dev_url()),
self.ci,
true,
)
})?;
let detected_package_manager = PackageManager::from_project(&self.directory);
self.before_dev_command = self
.before_dev_command
.map(|s| Ok(Some(s)))
.unwrap_or_else(|| {
prompts::input(
"What is your frontend dev command?",
Some(default_dev_command(detected_package_manager).into()),
self.ci,
true,
)
})?;
self.before_build_command = self
.before_build_command
.map(|s| Ok(Some(s)))
.unwrap_or_else(|| {
prompts::input(
"What is your frontend build command?",
Some(default_build_command(detected_package_manager).into()),
self.ci,
true,
)
})?;
Ok(self)
}
}
fn default_dev_command(pm: PackageManager) -> &'static str {
match pm {
PackageManager::Yarn => "yarn dev",
PackageManager::YarnBerry => "yarn dev",
PackageManager::Npm => "npm run dev",
PackageManager::Pnpm => "pnpm dev",
PackageManager::Bun => "bun dev",
PackageManager::Deno => "deno task dev",
}
}
fn default_build_command(pm: PackageManager) -> &'static str {
match pm {
PackageManager::Yarn => "yarn build",
PackageManager::YarnBerry => "yarn build",
PackageManager::Npm => "npm run build",
PackageManager::Pnpm => "pnpm build",
PackageManager::Bun => "bun build",
PackageManager::Deno => "deno task build",
}
}
pub fn command(mut options: Options) -> Result<()> {
options = options.load()?;
let template_target_path = PathBuf::from(&options.directory).join("src-tauri");
let metadata = serde_json::from_str::<VersionMetadata>(include_str!("../metadata-v2.json"))
.context("failed to parse version metadata")?;
if template_target_path.exists() && !options.force {
log::warn!(
"Tauri dir ({:?}) not empty. Run `init --force` to overwrite.",
template_target_path
);
} else {
let (tauri_dep, tauri_build_dep, tauri_utils_dep, tauri_plugin_dep) =
if let Some(tauri_path) = &options.tauri_path {
(
format!(
r#"{{ path = {:?} }}"#,
resolve_tauri_path(tauri_path, "crates/tauri")
),
format!(
"{{ path = {:?} }}",
resolve_tauri_path(tauri_path, "crates/tauri-build")
),
format!(
"{{ path = {:?} }}",
resolve_tauri_path(tauri_path, "crates/tauri-utils")
),
format!(
"{{ path = {:?} }}",
resolve_tauri_path(tauri_path, "crates/tauri-plugin")
),
)
} else {
(
format!(r#"{{ version = "{}" }}"#, metadata.tauri),
format!(r#"{{ version = "{}" }}"#, metadata.tauri_build),
r#"{{ version = "2" }}"#.to_string(),
r#"{{ version = "2" }}"#.to_string(),
)
};
let _ = remove_dir_all(&template_target_path);
let mut handlebars = Handlebars::new();
handlebars.register_escape_fn(handlebars::no_escape);
let mut data = BTreeMap::new();
data.insert("tauri_dep", to_json(tauri_dep));
if options.tauri_path.is_some() {
data.insert("patch_tauri_dep", to_json(true));
}
data.insert("tauri_build_dep", to_json(tauri_build_dep));
data.insert("tauri_utils_dep", to_json(tauri_utils_dep));
data.insert("tauri_plugin_dep", to_json(tauri_plugin_dep));
data.insert(
"frontend_dist",
to_json(options.frontend_dist.as_deref().unwrap_or("../dist")),
);
data.insert("dev_url", to_json(options.dev_url));
data.insert(
"app_name",
to_json(options.app_name.as_deref().unwrap_or("Tauri App")),
);
data.insert(
"window_title",
to_json(options.window_title.as_deref().unwrap_or("Tauri")),
);
data.insert("before_dev_command", to_json(options.before_dev_command));
data.insert(
"before_build_command",
to_json(options.before_build_command),
);
let mut config = serde_json::from_str(
&handlebars
.render_template(TAURI_CONF_TEMPLATE, &data)
.expect("Failed to render tauri.conf.json template"),
)
.unwrap();
if option_env!("TARGET") == Some("node") {
let mut dir = current_dir().expect("failed to read cwd");
let mut count = 0;
let mut cli_node_module_path = None;
let cli_path = "node_modules/@tauri-apps/cli";
// only go up three folders max
while count <= 2 {
let test_path = dir.join(cli_path);
if test_path.exists() {
let mut node_module_path = PathBuf::from("..");
for _ in 0..count {
node_module_path.push("..");
}
node_module_path.push(cli_path);
node_module_path.push("config.schema.json");
cli_node_module_path.replace(node_module_path);
break;
}
count += 1;
match dir.parent() {
Some(parent) => {
dir = parent.to_path_buf();
}
None => break,
}
}
if let Some(cli_node_module_path) = cli_node_module_path {
let mut map = serde_json::Map::default();
map.insert(
"$schema".into(),
serde_json::Value::String(
cli_node_module_path
.display()
.to_string()
.replace('\\', "/"),
),
);
let merge_config = serde_json::Value::Object(map);
json_patch::merge(&mut config, &merge_config);
}
}
data.insert(
"tauri_config",
to_json(serde_json::to_string_pretty(&config).unwrap()),
);
template::render(&handlebars, &data, &TEMPLATE_DIR, &options.directory)
.with_context(|| "failed to render Tauri template")?;
}
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/completions.rs | crates/tauri-cli/src/completions.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{error::ErrorExt, Result};
use clap::{Command, Parser};
use clap_complete::{generate, Shell};
use std::{fs::write, path::PathBuf};
const PKG_MANAGERS: &[&str] = &["cargo", "pnpm", "npm", "yarn", "bun", "deno"];
#[derive(Debug, Clone, Parser)]
#[clap(about = "Generate Tauri CLI shell completions for Bash, Zsh, PowerShell or Fish")]
pub struct Options {
/// Shell to generate a completion script for.
#[clap(short, long, verbatim_doc_comment)]
shell: Shell,
/// Output file for the shell completions. By default the completions are printed to stdout.
#[clap(short, long)]
output: Option<PathBuf>,
}
fn completions_for(shell: Shell, manager: &'static str, cmd: Command) -> Vec<u8> {
let tauri = cmd.name("tauri");
let mut command = if manager == "npm" || manager == "bun" {
Command::new(manager)
.bin_name(manager)
.subcommand(Command::new("run").subcommand(tauri))
} else if manager == "deno" {
Command::new(manager)
.bin_name(manager)
.subcommand(Command::new("task").subcommand(tauri))
} else {
Command::new(manager).bin_name(manager).subcommand(tauri)
};
let mut buf = Vec::new();
generate(shell, &mut command, manager, &mut buf);
buf
}
fn get_completions(shell: Shell, cmd: Command) -> Result<String> {
let completions = if shell == Shell::Bash {
let mut completions =
String::from_utf8_lossy(&completions_for(shell, "cargo", cmd)).into_owned();
for &manager in PKG_MANAGERS {
completions.push_str(&format!(
"complete -F _cargo -o bashdefault -o default {} tauri\n",
if manager == "npm" {
"npm run"
} else if manager == "bun" {
"bun run"
} else if manager == "deno" {
"deno task"
} else {
manager
}
));
}
completions
} else {
let mut buffer = String::new();
for (i, manager) in PKG_MANAGERS.iter().enumerate() {
let buf = String::from_utf8_lossy(&completions_for(shell, manager, cmd.clone())).into_owned();
let completions = match shell {
Shell::PowerShell => {
if i != 0 {
// namespaces have already been imported
buf
.replace("using namespace System.Management.Automation.Language", "")
.replace("using namespace System.Management.Automation", "")
} else {
buf
}
}
_ => buf,
};
buffer.push_str(&completions);
buffer.push('\n');
}
buffer
};
Ok(completions)
}
pub fn command(options: Options, cmd: Command) -> Result<()> {
log::info!("Generating completion file for {}...", options.shell);
let completions = get_completions(options.shell, cmd)?;
if let Some(output) = options.output {
write(&output, completions).fs_context("failed to write to completions", output)?;
} else {
print!("{completions}");
}
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/main.rs | crates/tauri-cli/src/main.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
#[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]
fn main() {
println!("The Tauri CLI is not supported on this platform");
std::process::exit(1);
}
#[cfg(any(target_os = "macos", target_os = "linux", windows))]
fn main() {
use std::env::args_os;
use std::ffi::OsStr;
use std::path::Path;
use std::process::exit;
let mut args = args_os().peekable();
let bin_name = match args
.next()
.as_deref()
.map(Path::new)
.and_then(Path::file_stem)
.and_then(OsStr::to_str)
{
Some("cargo-tauri") => {
if args.peek().and_then(|s| s.to_str()) == Some("tauri") {
// remove the extra cargo subcommand
args.next();
Some("cargo tauri".into())
} else {
Some("cargo-tauri".into())
}
}
Some(stem) => Some(stem.to_string()),
None => {
eprintln!("cargo-tauri wrapper unable to read first argument");
exit(1);
}
};
tauri_cli::run(args, bin_name)
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/add.rs | crates/tauri-cli/src/add.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use clap::Parser;
use colored::Colorize;
use regex::Regex;
use crate::{
acl,
error::ErrorExt,
helpers::{
app_paths::{resolve_frontend_dir, tauri_dir},
cargo,
npm::PackageManager,
},
Result,
};
use std::process::Command;
#[derive(Debug, Parser)]
#[clap(about = "Add a tauri plugin to the project")]
pub struct Options {
/// The plugin to add.
pub plugin: String,
/// Git tag to use.
#[clap(short, long)]
pub tag: Option<String>,
/// Git rev to use.
#[clap(short, long)]
pub rev: Option<String>,
/// Git branch to use.
#[clap(short, long)]
pub branch: Option<String>,
/// Don't format code with rustfmt
#[clap(long)]
pub no_fmt: bool,
}
pub fn command(options: Options) -> Result<()> {
crate::helpers::app_paths::resolve();
run(options)
}
pub fn run(options: Options) -> Result<()> {
let (plugin, version) = options
.plugin
.split_once('@')
.map(|(p, v)| (p, Some(v)))
.unwrap_or((&options.plugin, None));
let mut plugins = crate::helpers::plugins::known_plugins();
let (metadata, is_known) = plugins
.remove(plugin)
.map(|metadata| (metadata, true))
.unwrap_or_default();
let plugin_snake_case = plugin.replace('-', "_");
let crate_name = format!("tauri-plugin-{plugin}");
let npm_name = if is_known {
format!("@tauri-apps/plugin-{plugin}")
} else {
format!("tauri-plugin-{plugin}-api")
};
if !is_known && (options.tag.is_some() || options.rev.is_some() || options.branch.is_some()) {
crate::error::bail!(
"Git options --tag, --rev and --branch can only be used with official Tauri plugins"
);
}
let frontend_dir = resolve_frontend_dir();
let tauri_dir = tauri_dir();
let target_str = metadata
.desktop_only
.then_some(r#"cfg(not(any(target_os = "android", target_os = "ios")))"#)
.or_else(|| {
metadata
.mobile_only
.then_some(r#"cfg(any(target_os = "android", target_os = "ios"))"#)
});
let cargo_version_req = version.or(metadata.version_req.as_deref());
cargo::install_one(cargo::CargoInstallOptions {
name: &crate_name,
version: cargo_version_req,
branch: options.branch.as_deref(),
rev: options.rev.as_deref(),
tag: options.tag.as_deref(),
cwd: Some(tauri_dir),
target: target_str,
})?;
if !metadata.rust_only {
if let Some(manager) = frontend_dir.map(PackageManager::from_project) {
let npm_version_req = version
.map(ToString::to_string)
.or(metadata.version_req.as_ref().map(|v| match manager {
PackageManager::Npm => format!(">={v}"),
_ => format!("~{v}"),
}));
let npm_spec = match (npm_version_req, options.tag, options.rev, options.branch) {
(Some(version_req), _, _, _) => format!("{npm_name}@{version_req}"),
(None, Some(tag), None, None) => {
format!("tauri-apps/tauri-plugin-{plugin}#{tag}")
}
(None, None, Some(rev), None) => {
format!("tauri-apps/tauri-plugin-{plugin}#{rev}")
}
(None, None, None, Some(branch)) => {
format!("tauri-apps/tauri-plugin-{plugin}#{branch}")
}
(None, None, None, None) => npm_name,
_ => crate::error::bail!("Only one of --tag, --rev and --branch can be specified"),
};
manager.install(&[npm_spec], tauri_dir)?;
}
let _ = acl::permission::add::command(acl::permission::add::Options {
identifier: format!("{plugin}:default"),
capability: None,
});
}
// add plugin init code to main.rs or lib.rs
let plugin_init_fn = if plugin == "stronghold" {
"Builder::new(|pass| todo!()).build()"
} else if plugin == "localhost" {
"Builder::new(todo!()).build()"
} else if plugin == "single-instance" {
"init(|app, args, cwd| {})"
} else if plugin == "log" {
"Builder::new().level(tauri_plugin_log::log::LevelFilter::Info).build()"
} else if metadata.builder {
"Builder::new().build()"
} else {
"init()"
};
let plugin_init = format!(".plugin(tauri_plugin_{plugin_snake_case}::{plugin_init_fn})");
let re = Regex::new(r"(tauri\s*::\s*Builder\s*::\s*default\(\))(\s*)").unwrap();
for file in [tauri_dir.join("src/main.rs"), tauri_dir.join("src/lib.rs")] {
let contents =
std::fs::read_to_string(&file).fs_context("failed to read Rust entry point", file.clone())?;
if contents.contains(&plugin_init) {
log::info!(
"Plugin initialization code already found on {}",
file.display()
);
return Ok(());
}
if re.is_match(&contents) {
let out = re.replace(&contents, format!("$1$2{plugin_init}$2"));
log::info!("Adding plugin to {}", file.display());
std::fs::write(&file, out.as_bytes()).fs_context("failed to write plugin init code", file)?;
if !options.no_fmt {
// reformat code with rustfmt
log::info!("Running `cargo fmt`...");
let _ = Command::new("cargo")
.arg("fmt")
.current_dir(tauri_dir)
.status();
}
return Ok(());
}
}
let builder_code = if metadata.builder {
format!(r#"+ .plugin(tauri_plugin_{plugin_snake_case}::Builder::new().build())"#,)
} else {
format!(r#"+ .plugin(tauri_plugin_{plugin_snake_case}::init())"#)
};
let rust_code = format!(
r#" {}
{}
{}"#,
"tauri::Builder::default()".dimmed(),
builder_code.normal().green(),
r#".invoke_handler(tauri::generate_handler![])
.run(tauri::generate_context!())
.expect("error while running tauri application");"#
.dimmed(),
);
log::warn!(
"Couldn't find `{}` in `{}` or `{}`, you must enable the plugin in your Rust code manually:\n\n{}",
"tauri::Builder".cyan(),
"main.rs".cyan(),
"lib.rs".cyan(),
rust_code
);
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/remove.rs | crates/tauri-cli/src/remove.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use clap::Parser;
use crate::{
acl,
helpers::{
app_paths::{resolve_frontend_dir, tauri_dir},
cargo,
npm::PackageManager,
},
Result,
};
#[derive(Debug, Parser)]
#[clap(about = "Remove a tauri plugin from the project")]
pub struct Options {
/// The plugin to remove.
pub plugin: String,
}
pub fn command(options: Options) -> Result<()> {
crate::helpers::app_paths::resolve();
run(options)
}
pub fn run(options: Options) -> Result<()> {
let plugin = options.plugin;
let crate_name = format!("tauri-plugin-{plugin}");
let mut plugins = crate::helpers::plugins::known_plugins();
let metadata = plugins.remove(plugin.as_str()).unwrap_or_default();
let frontend_dir = resolve_frontend_dir();
let tauri_dir = tauri_dir();
let target_str = metadata
.desktop_only
.then_some(r#"cfg(not(any(target_os = "android", target_os = "ios")))"#)
.or_else(|| {
metadata
.mobile_only
.then_some(r#"cfg(any(target_os = "android", target_os = "ios"))"#)
});
cargo::uninstall_one(cargo::CargoUninstallOptions {
name: &crate_name,
cwd: Some(tauri_dir),
target: target_str,
})?;
if !metadata.rust_only {
if let Some(manager) = frontend_dir.map(PackageManager::from_project) {
let npm_name = format!("@tauri-apps/plugin-{plugin}");
manager.remove(&[npm_name], tauri_dir)?;
}
acl::permission::rm::command(acl::permission::rm::Options {
identifier: format!("{plugin}:*"),
})?;
}
log::info!("Now, you must manually remove the plugin from your Rust code.",);
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/inspect.rs | crates/tauri-cli/src/inspect.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::Result;
use clap::{Parser, Subcommand};
use crate::interface::{AppInterface, AppSettings, Interface};
#[derive(Debug, Parser)]
#[clap(about = "Manage or create permissions for your app or plugin")]
pub struct Cli {
#[clap(subcommand)]
command: Commands,
}
#[derive(Subcommand, Debug)]
enum Commands {
/// Print the default Upgrade Code used by MSI installer derived from productName.
WixUpgradeCode,
}
pub fn command(cli: Cli) -> Result<()> {
match cli.command {
Commands::WixUpgradeCode => wix_upgrade_code(),
}
}
// NOTE: if this is ever changed, make sure to also update Wix upgrade code generation in tauri-bundler
fn wix_upgrade_code() -> Result<()> {
crate::helpers::app_paths::resolve();
let target = tauri_utils::platform::Target::Windows;
let config = crate::helpers::config::get(target, &[])?;
let interface = AppInterface::new(config.lock().unwrap().as_ref().unwrap(), None)?;
let product_name = interface.app_settings().get_package_settings().product_name;
let upgrade_code = uuid::Uuid::new_v5(
&uuid::Uuid::NAMESPACE_DNS,
format!("{product_name}.exe.app.x64").as_bytes(),
)
.to_string();
log::info!("Default WiX Upgrade Code, derived from {product_name}: {upgrade_code}");
if let Some(code) = config.lock().unwrap().as_ref().and_then(|c| {
c.bundle
.windows
.wix
.as_ref()
.and_then(|wix| wix.upgrade_code)
}) {
log::info!("Application Upgrade Code override: {code}");
}
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/plugin/ios.rs | crates/tauri-cli/src/plugin/ios.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use super::PluginIosFramework;
use crate::{error::Context, helpers::template, Result};
use clap::{Parser, Subcommand};
use handlebars::Handlebars;
use std::{
collections::BTreeMap,
env::current_dir,
ffi::{OsStr, OsString},
fs::{create_dir_all, File},
path::{Component, PathBuf},
};
#[derive(Parser)]
#[clap(
author,
version,
about = "Manage the iOS project for a Tauri plugin",
subcommand_required(true),
arg_required_else_help(true)
)]
pub struct Cli {
#[clap(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
Init(InitOptions),
}
#[derive(Debug, Parser)]
#[clap(about = "Initializes the iOS project for an existing Tauri plugin")]
pub struct InitOptions {
/// Name of your Tauri plugin. Must match the current plugin's name.
/// If not specified, it will be inferred from the current directory.
plugin_name: Option<String>,
/// The output directory.
#[clap(short, long)]
#[clap(default_value_t = current_dir().expect("failed to read cwd").to_string_lossy().into_owned())]
out_dir: String,
/// Type of framework to use for the iOS project.
#[clap(long)]
#[clap(default_value_t = PluginIosFramework::default())]
ios_framework: PluginIosFramework,
}
pub fn command(cli: Cli) -> Result<()> {
match cli.command {
Commands::Init(options) => {
let plugin_name = match options.plugin_name {
None => super::infer_plugin_name(
std::env::current_dir().context("failed to get current directory")?,
)?,
Some(name) => name,
};
let out_dir = PathBuf::from(options.out_dir);
if out_dir.join("ios").exists() {
crate::error::bail!("iOS folder already exists");
}
let handlebars = Handlebars::new();
let mut data = BTreeMap::new();
super::init::plugin_name_data(&mut data, &plugin_name);
let ios_folder_name = match options.ios_framework {
PluginIosFramework::Spm => OsStr::new("ios-spm"),
PluginIosFramework::Xcode => OsStr::new("ios-xcode"),
};
let mut created_dirs = Vec::new();
template::render_with_generator(
&handlebars,
&data,
&super::init::TEMPLATE_DIR,
&out_dir,
&mut |path| {
let mut components = path.components();
let root = components.next().unwrap();
if let Component::Normal(component) = root {
if component == ios_folder_name {
let folder_name = components.next().unwrap().as_os_str().to_string_lossy();
let new_folder_name = folder_name.replace("{{ plugin_name }}", &plugin_name);
let new_folder_name = OsString::from(&new_folder_name);
let path = [
Component::Normal(OsStr::new("ios")),
Component::Normal(&new_folder_name),
]
.into_iter()
.chain(components)
.collect::<PathBuf>();
let path = out_dir.join(path);
let parent = path.parent().unwrap().to_path_buf();
if !created_dirs.contains(&parent) {
create_dir_all(&parent)?;
created_dirs.push(parent);
}
return File::create(path).map(Some);
}
}
Ok(None)
},
)?;
let metadata = super::init::crates_metadata()?;
let cargo_toml_addition = format!(
r#"
[build-dependencies]
tauri-build = "{}"
"#,
metadata.tauri_build
);
let build_file = super::init::TEMPLATE_DIR
.get_file("build.rs")
.unwrap()
.contents_utf8()
.unwrap();
let init_fn = format!(
r#"
#[cfg(target_os = "ios")]
tauri::ios_plugin_binding!(init_plugin_{plugin_name});
pub fn init<R: Runtime>() -> TauriPlugin<R> {{
Builder::new("{plugin_name}")
.setup(|app| {{
#[cfg(target_os = "ios")]
app.register_ios_plugin(init_plugin_{plugin_name})?;
Ok(())
}})
.build()
}}
"#,
);
log::info!("iOS project added");
println!("You must add the following to the Cargo.toml file:\n{cargo_toml_addition}",);
println!("You must add the following code to the build.rs file:\n\n{build_file}",);
println!(
"Your plugin's init function under src/lib.rs must initialize the iOS plugin:\n{init_fn}"
);
}
}
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/plugin/android.rs | crates/tauri-cli/src/plugin/android.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{
error::Context,
helpers::{prompts, template},
Result,
};
use clap::{Parser, Subcommand};
use handlebars::Handlebars;
use std::{
collections::BTreeMap,
env::current_dir,
ffi::OsStr,
path::{Component, PathBuf},
};
#[derive(Parser)]
#[clap(
author,
version,
about = "Manage the Android project for a Tauri plugin",
subcommand_required(true),
arg_required_else_help(true)
)]
pub struct Cli {
#[clap(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
Init(InitOptions),
}
#[derive(Debug, Parser)]
#[clap(about = "Initializes the Android project for an existing Tauri plugin")]
pub struct InitOptions {
/// Name of your Tauri plugin. Must match the current plugin's name.
/// If not specified, it will be inferred from the current directory.
plugin_name: Option<String>,
/// The output directory.
#[clap(short, long)]
#[clap(default_value_t = current_dir().expect("failed to read cwd").to_string_lossy().into_owned())]
out_dir: String,
}
pub fn command(cli: Cli) -> Result<()> {
match cli.command {
Commands::Init(options) => {
let plugin_name = match options.plugin_name {
None => super::infer_plugin_name(
std::env::current_dir().context("failed to get current directory")?,
)?,
Some(name) => name,
};
let out_dir = PathBuf::from(options.out_dir);
if out_dir.join("android").exists() {
crate::error::bail!("Android folder already exists");
}
let plugin_id = prompts::input(
"What should be the Android Package ID for your plugin?",
Some(format!("com.plugin.{plugin_name}")),
false,
false,
)?
.unwrap();
let handlebars = Handlebars::new();
let mut data = BTreeMap::new();
super::init::plugin_name_data(&mut data, &plugin_name);
data.insert("android_package_id", handlebars::to_json(&plugin_id));
let mut created_dirs = Vec::new();
template::render_with_generator(
&handlebars,
&data,
&super::init::TEMPLATE_DIR,
&out_dir,
&mut |path| {
let mut components = path.components();
let root = components.next().unwrap();
if let Component::Normal(component) = root {
if component == OsStr::new("android") {
return super::init::generate_android_out_file(
&path,
&out_dir,
&plugin_id.replace('.', "/"),
&mut created_dirs,
);
}
}
Ok(None)
},
)?;
let metadata = super::init::crates_metadata()?;
let cargo_toml_addition = format!(
r#"
[build-dependencies]
tauri-build = "{}"
"#,
metadata.tauri_build
);
let build_file = super::init::TEMPLATE_DIR
.get_file("build.rs")
.unwrap()
.contents_utf8()
.unwrap();
let init_fn = format!(
r#"
pub fn init<R: Runtime>() -> TauriPlugin<R> {{
Builder::new("{plugin_name}")
.setup(|app, api| {{
#[cfg(target_os = "android")]
let handle = api.register_android_plugin("{plugin_id}", "ExamplePlugin")?;
Ok(())
}})
.build()
}}
"#
);
log::info!("Android project added");
println!("You must add the following to the Cargo.toml file:\n{cargo_toml_addition}",);
println!("You must add the following code to the build.rs file:\n\n{build_file}",);
println!("Your plugin's init function under src/lib.rs must initialize the Android plugin:\n{init_fn}");
}
}
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/plugin/mod.rs | crates/tauri-cli/src/plugin/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{fmt::Display, path::Path};
use clap::{Parser, Subcommand, ValueEnum};
use crate::{
error::{Context, ErrorExt},
Result,
};
mod android;
mod init;
mod ios;
mod new;
#[derive(Debug, Clone, ValueEnum, Default)]
pub enum PluginIosFramework {
/// Swift Package Manager project
#[default]
Spm,
/// Xcode project
Xcode,
}
impl Display for PluginIosFramework {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Spm => write!(f, "spm"),
Self::Xcode => write!(f, "xcode"),
}
}
}
#[derive(Parser)]
#[clap(
author,
version,
about = "Manage or create Tauri plugins",
subcommand_required(true),
arg_required_else_help(true)
)]
pub struct Cli {
#[clap(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
New(new::Options),
Init(init::Options),
Android(android::Cli),
Ios(ios::Cli),
}
pub fn command(cli: Cli) -> Result<()> {
match cli.command {
Commands::New(options) => new::command(options)?,
Commands::Init(options) => init::command(options)?,
Commands::Android(cli) => android::command(cli)?,
Commands::Ios(cli) => ios::command(cli)?,
}
Ok(())
}
fn infer_plugin_name<P: AsRef<Path>>(directory: P) -> Result<String> {
let dir = directory.as_ref();
let cargo_toml_path = dir.join("Cargo.toml");
let name = if cargo_toml_path.exists() {
let contents = std::fs::read_to_string(&cargo_toml_path)
.fs_context("failed to read Cargo manifest", cargo_toml_path)?;
let cargo_toml: toml::Value =
toml::from_str(&contents).context("failed to parse Cargo.toml")?;
cargo_toml
.get("package")
.and_then(|v| v.get("name"))
.map(|v| v.as_str().unwrap_or_default())
.unwrap_or_default()
.to_string()
} else {
dir
.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string()
};
Ok(
name
.strip_prefix("tauri-plugin-")
.unwrap_or(&name)
.to_string(),
)
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/plugin/init.rs | crates/tauri-cli/src/plugin/init.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use super::PluginIosFramework;
use crate::Result;
use crate::{
error::{Context, ErrorExt},
helpers::{prompts, resolve_tauri_path, template},
VersionMetadata,
};
use clap::Parser;
use handlebars::{to_json, Handlebars};
use heck::{ToKebabCase, ToPascalCase, ToSnakeCase};
use include_dir::{include_dir, Dir};
use std::ffi::{OsStr, OsString};
use std::{
collections::BTreeMap,
env::current_dir,
fs::{create_dir_all, remove_dir_all, File, OpenOptions},
path::{Component, Path, PathBuf},
};
pub const TEMPLATE_DIR: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/templates/plugin");
#[derive(Debug, Parser)]
#[clap(about = "Initialize a Tauri plugin project on an existing directory")]
pub struct Options {
/// Name of your Tauri plugin.
/// If not specified, it will be inferred from the current directory.
pub(crate) plugin_name: Option<String>,
/// Initializes a Tauri plugin without the TypeScript API
#[clap(long)]
pub(crate) no_api: bool,
/// Initialize without an example project.
#[clap(long)]
pub(crate) no_example: bool,
/// Set target directory for init
#[clap(short, long)]
#[clap(default_value_t = current_dir().expect("failed to read cwd").display().to_string())]
pub(crate) directory: String,
/// Author name
#[clap(short, long)]
pub(crate) author: Option<String>,
/// Whether to initialize an Android project for the plugin.
#[clap(long)]
pub(crate) android: bool,
/// Whether to initialize an iOS project for the plugin.
#[clap(long)]
pub(crate) ios: bool,
/// Whether to initialize Android and iOS projects for the plugin.
#[clap(long)]
pub(crate) mobile: bool,
/// Type of framework to use for the iOS project.
#[clap(long)]
#[clap(default_value_t = PluginIosFramework::default())]
pub(crate) ios_framework: PluginIosFramework,
/// Generate github workflows
#[clap(long)]
pub(crate) github_workflows: bool,
/// Initializes a Tauri core plugin (internal usage)
#[clap(long, hide(true))]
pub(crate) tauri: bool,
/// Path of the Tauri project to use (relative to the cwd)
#[clap(short, long)]
pub(crate) tauri_path: Option<PathBuf>,
}
impl Options {
fn load(&mut self) {
if self.author.is_none() {
self.author.replace(if self.tauri {
"Tauri Programme within The Commons Conservancy".into()
} else {
"You".into()
});
}
}
}
pub fn command(mut options: Options) -> Result<()> {
options.load();
let plugin_name = match options.plugin_name {
None => super::infer_plugin_name(&options.directory)?,
Some(name) => name,
};
let template_target_path = PathBuf::from(options.directory);
let metadata = crates_metadata()?;
if std::fs::read_dir(&template_target_path)
.fs_context(
"failed to read target directory",
template_target_path.clone(),
)?
.count()
> 0
{
log::warn!("Plugin dir ({:?}) not empty.", template_target_path);
} else {
let (tauri_dep, tauri_example_dep, tauri_build_dep, tauri_plugin_dep) =
if let Some(tauri_path) = options.tauri_path {
(
format!(
r#"{{ path = {:?} }}"#,
resolve_tauri_path(&tauri_path, "crates/tauri")
),
format!(
r#"{{ path = {:?} }}"#,
resolve_tauri_path(&tauri_path, "crates/tauri")
),
format!(
"{{ path = {:?}, default-features = false }}",
resolve_tauri_path(&tauri_path, "crates/tauri-build")
),
format!(
r#"{{ path = {:?}, features = ["build"] }}"#,
resolve_tauri_path(&tauri_path, "crates/tauri-plugin")
),
)
} else {
(
format!(r#"{{ version = "{}" }}"#, metadata.tauri),
format!(r#"{{ version = "{}" }}"#, metadata.tauri),
format!(
r#"{{ version = "{}", default-features = false }}"#,
metadata.tauri_build
),
format!(
r#"{{ version = "{}", features = ["build"] }}"#,
metadata.tauri_plugin
),
)
};
let _ = remove_dir_all(&template_target_path);
let mut handlebars = Handlebars::new();
handlebars.register_escape_fn(handlebars::no_escape);
let mut data = BTreeMap::new();
plugin_name_data(&mut data, &plugin_name);
data.insert("tauri_dep", to_json(tauri_dep));
data.insert("tauri_example_dep", to_json(tauri_example_dep));
data.insert("tauri_build_dep", to_json(tauri_build_dep));
data.insert("tauri_plugin_dep", to_json(tauri_plugin_dep));
data.insert("author", to_json(options.author));
if options.tauri {
data.insert(
"license_header",
to_json(
"// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT\n\n"
.replace(" ", "")
.replace(" //", "//"),
),
);
}
let plugin_id = if options.android || options.mobile {
let plugin_id = prompts::input(
"What should be the Android Package ID for your plugin?",
Some(format!("com.plugin.{plugin_name}")),
false,
false,
)?
.unwrap();
data.insert("android_package_id", to_json(&plugin_id));
Some(plugin_id)
} else {
None
};
let ios_framework = options.ios_framework;
let mut created_dirs = Vec::new();
template::render_with_generator(
&handlebars,
&data,
&TEMPLATE_DIR,
&template_target_path,
&mut |mut path| {
let mut components = path.components();
let root = components.next().unwrap();
if let Component::Normal(component) = root {
match component.to_str().unwrap() {
"__example-api" => {
if options.no_api || options.no_example {
return Ok(None);
} else {
path = Path::new("examples").join(components.collect::<PathBuf>());
}
}
"__example-basic" => {
if options.no_api && !options.no_example {
path = Path::new("examples").join(components.collect::<PathBuf>());
} else {
return Ok(None);
}
}
".github" if !options.github_workflows => return Ok(None),
"android" => {
if options.android || options.mobile {
return generate_android_out_file(
&path,
&template_target_path,
&plugin_id.as_ref().unwrap().replace('.', "/"),
&mut created_dirs,
);
} else {
return Ok(None);
}
}
"ios-spm" | "ios-xcode" if !(options.ios || options.mobile) => return Ok(None),
"ios-spm" if !matches!(ios_framework, PluginIosFramework::Spm) => return Ok(None),
"ios-xcode" if !matches!(ios_framework, PluginIosFramework::Xcode) => return Ok(None),
"ios-spm" | "ios-xcode" => {
let folder_name = components.next().unwrap().as_os_str().to_string_lossy();
let new_folder_name = folder_name.replace("{{ plugin_name }}", &plugin_name);
let new_folder_name = OsString::from(&new_folder_name);
path = [
Component::Normal(OsStr::new("ios")),
Component::Normal(&new_folder_name),
]
.into_iter()
.chain(components)
.collect::<PathBuf>();
}
"guest-js" | "rollup.config.js" | "tsconfig.json" | "package.json"
if options.no_api =>
{
return Ok(None);
}
_ => (),
}
}
let path = template_target_path.join(path);
let parent = path.parent().unwrap().to_path_buf();
if !created_dirs.contains(&parent) {
create_dir_all(&parent)?;
created_dirs.push(parent);
}
File::create(path).map(Some)
},
)
.with_context(|| "failed to render plugin template")?;
}
let permissions_dir = template_target_path.join("permissions");
std::fs::create_dir(&permissions_dir).fs_context(
"failed to create `permissions` directory",
permissions_dir.clone(),
)?;
let default_permissions = r#"[default]
description = "Default permissions for the plugin"
permissions = ["allow-ping"]
"#;
std::fs::write(permissions_dir.join("default.toml"), default_permissions).fs_context(
"failed to write default permissions file",
permissions_dir.join("default.toml"),
)?;
Ok(())
}
pub fn plugin_name_data(data: &mut BTreeMap<&'static str, serde_json::Value>, plugin_name: &str) {
data.insert("plugin_name_original", to_json(plugin_name));
data.insert("plugin_name", to_json(plugin_name.to_kebab_case()));
data.insert(
"plugin_name_snake_case",
to_json(plugin_name.to_snake_case()),
);
data.insert(
"plugin_name_pascal_case",
to_json(plugin_name.to_pascal_case()),
);
}
pub fn crates_metadata() -> Result<VersionMetadata> {
serde_json::from_str::<VersionMetadata>(include_str!("../../metadata-v2.json"))
.context("failed to parse Tauri version metadata")
}
pub fn generate_android_out_file(
path: &Path,
dest: &Path,
package_path: &str,
created_dirs: &mut Vec<PathBuf>,
) -> std::io::Result<Option<File>> {
let mut iter = path.iter();
let root = iter.next().unwrap().to_str().unwrap();
let path = match (root, path.extension().and_then(|o| o.to_str())) {
("src", Some("kt")) => {
let parent = path.parent().unwrap();
let file_name = path.file_name().unwrap();
let out_dir = dest.join(parent).join(package_path);
out_dir.join(file_name)
}
_ => dest.join(path),
};
let parent = path.parent().unwrap().to_path_buf();
if !created_dirs.contains(&parent) {
create_dir_all(&parent)?;
created_dirs.push(parent);
}
let mut options = OpenOptions::new();
options.write(true);
#[cfg(unix)]
if path.file_name().unwrap() == std::ffi::OsStr::new("gradlew") {
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o755);
}
if !path.exists() {
options.create(true).open(path).map(Some)
} else {
Ok(None)
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/plugin/new.rs | crates/tauri-cli/src/plugin/new.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use super::PluginIosFramework;
use crate::{
error::{Context, ErrorExt},
Result,
};
use clap::Parser;
use std::path::PathBuf;
#[derive(Debug, Parser)]
#[clap(about = "Initializes a new Tauri plugin project")]
pub struct Options {
/// Name of your Tauri plugin
plugin_name: String,
/// Initializes a Tauri plugin without the TypeScript API
#[clap(long)]
no_api: bool,
/// Initialize without an example project.
#[clap(long)]
no_example: bool,
/// Set target directory for init
#[clap(short, long)]
directory: Option<String>,
/// Author name
#[clap(short, long)]
author: Option<String>,
/// Whether to initialize an Android project for the plugin.
#[clap(long)]
android: bool,
/// Whether to initialize an iOS project for the plugin.
#[clap(long)]
ios: bool,
/// Whether to initialize Android and iOS projects for the plugin.
#[clap(long)]
mobile: bool,
/// Type of framework to use for the iOS project.
#[clap(long)]
#[clap(default_value_t = PluginIosFramework::default())]
pub(crate) ios_framework: PluginIosFramework,
/// Generate github workflows
#[clap(long)]
github_workflows: bool,
/// Initializes a Tauri core plugin (internal usage)
#[clap(long, hide(true))]
tauri: bool,
/// Path of the Tauri project to use (relative to the cwd)
#[clap(short, long)]
tauri_path: Option<PathBuf>,
}
impl From<Options> for super::init::Options {
fn from(o: Options) -> Self {
Self {
plugin_name: Some(o.plugin_name),
no_api: o.no_api,
no_example: o.no_example,
directory: o.directory.unwrap(),
author: o.author,
android: o.android,
ios: o.ios,
mobile: o.mobile,
ios_framework: o.ios_framework,
github_workflows: o.github_workflows,
tauri: o.tauri,
tauri_path: o.tauri_path,
}
}
}
pub fn command(mut options: Options) -> Result<()> {
let cwd = std::env::current_dir().context("failed to get current directory")?;
if let Some(dir) = &options.directory {
std::fs::create_dir_all(cwd.join(dir))
.fs_context("failed to create crate directory", cwd.join(dir))?;
} else {
let target = cwd.join(format!("tauri-plugin-{}", options.plugin_name));
std::fs::create_dir_all(&target)
.fs_context("failed to create crate directory", target.clone())?;
options.directory.replace(target.display().to_string());
}
super::init::command(options.into())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/dev/builtin_dev_server.rs | crates/tauri-cli/src/dev/builtin_dev_server.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use axum::{
extract::{ws, State, WebSocketUpgrade},
http::{header, StatusCode, Uri},
response::{IntoResponse, Response},
};
use html5ever::{namespace_url, ns, LocalName, QualName};
use kuchiki::{traits::TendrilSink, NodeRef};
use std::{
net::{IpAddr, SocketAddr},
path::{Path, PathBuf},
thread,
time::Duration,
};
use tauri_utils::mime_type::MimeType;
use tokio::sync::broadcast::{channel, Sender};
use crate::error::ErrorExt;
const RELOAD_SCRIPT: &str = include_str!("./auto-reload.js");
#[derive(Clone)]
struct ServerState {
dir: PathBuf,
address: SocketAddr,
tx: Sender<()>,
}
pub fn start<P: AsRef<Path>>(dir: P, ip: IpAddr, port: Option<u16>) -> crate::Result<SocketAddr> {
let dir = dir.as_ref();
let dir =
dunce::canonicalize(dir).fs_context("failed to canonicalize path", dir.to_path_buf())?;
// bind port and tcp listener
let auto_port = port.is_none();
let mut port = port.unwrap_or(1430);
let (tcp_listener, address) = loop {
let address = SocketAddr::new(ip, port);
if let Ok(tcp) = std::net::TcpListener::bind(address) {
tcp.set_nonblocking(true).unwrap();
break (tcp, address);
}
if !auto_port {
crate::error::bail!("Couldn't bind to {port} on {ip}");
}
port += 1;
};
let (tx, _) = channel(1);
// watch dir for changes
let tx_c = tx.clone();
watch(dir.clone(), move || {
let _ = tx_c.send(());
});
let state = ServerState { dir, tx, address };
// start router thread
std::thread::spawn(move || {
tokio::runtime::Builder::new_current_thread()
.enable_io()
.build()
.expect("failed to start tokio runtime for builtin dev server")
.block_on(async move {
let router = axum::Router::new()
.fallback(handler)
.route("/__tauri_cli", axum::routing::get(ws_handler))
.with_state(state);
axum::serve(tokio::net::TcpListener::from_std(tcp_listener)?, router).await
})
.expect("builtin server errored");
});
Ok(address)
}
async fn handler(uri: Uri, state: State<ServerState>) -> impl IntoResponse {
// Frontend files should not contain query parameters. This seems to be how Vite handles it.
let uri = uri.path();
let uri = if uri == "/" {
uri
} else {
uri.strip_prefix('/').unwrap_or(uri)
};
let bytes = fs_read_scoped(state.dir.join(uri), &state.dir)
.or_else(|_| fs_read_scoped(state.dir.join(format!("{}.html", &uri)), &state.dir))
.or_else(|_| fs_read_scoped(state.dir.join(format!("{}/index.html", &uri)), &state.dir))
.or_else(|_| std::fs::read(state.dir.join("index.html")));
match bytes {
Ok(mut bytes) => {
let mime_type = MimeType::parse_with_fallback(&bytes, uri, MimeType::OctetStream);
if mime_type == MimeType::Html.to_string() {
bytes = inject_address(bytes, &state.address);
}
(StatusCode::OK, [(header::CONTENT_TYPE, mime_type)], bytes)
}
Err(_) => (
StatusCode::NOT_FOUND,
[(header::CONTENT_TYPE, "text/plain".into())],
vec![],
),
}
}
async fn ws_handler(ws: WebSocketUpgrade, state: State<ServerState>) -> Response {
ws.on_upgrade(move |mut ws| async move {
let mut rx = state.tx.subscribe();
while tokio::select! {
_ = ws.recv() => return,
fs_reload_event = rx.recv() => fs_reload_event.is_ok(),
} {
let msg = ws::Message::Text(r#"{"reload": true}"#.into());
if ws.send(msg).await.is_err() {
break;
}
}
})
}
fn inject_address(html_bytes: Vec<u8>, address: &SocketAddr) -> Vec<u8> {
fn with_html_head<F: FnOnce(&NodeRef)>(document: &mut NodeRef, f: F) {
if let Ok(ref node) = document.select_first("head") {
f(node.as_node())
} else {
let node = NodeRef::new_element(
QualName::new(None, ns!(html), LocalName::from("head")),
None,
);
f(&node);
document.prepend(node)
}
}
let mut document = kuchiki::parse_html()
.one(String::from_utf8_lossy(&html_bytes).into_owned())
.document_node;
with_html_head(&mut document, |head| {
let script = RELOAD_SCRIPT.replace("{{reload_url}}", &format!("ws://{address}/__tauri_cli"));
let script_el = NodeRef::new_element(QualName::new(None, ns!(html), "script".into()), None);
script_el.append(NodeRef::new_text(script));
head.prepend(script_el);
});
tauri_utils::html::serialize_node(&document)
}
fn fs_read_scoped(path: PathBuf, scope: &Path) -> crate::Result<Vec<u8>> {
let path = dunce::canonicalize(&path).fs_context("failed to canonicalize path", path)?;
if path.starts_with(scope) {
std::fs::read(&path).fs_context("failed to read file", &path)
} else {
crate::error::bail!("forbidden path")
}
}
fn watch<F: Fn() + Send + 'static>(dir: PathBuf, handler: F) {
thread::spawn(move || {
let (tx, rx) = std::sync::mpsc::channel();
let mut watcher = notify_debouncer_full::new_debouncer(Duration::from_secs(1), None, tx)
.expect("failed to start builtin server fs watcher");
watcher
.watch(&dir, notify::RecursiveMode::Recursive)
.expect("builtin server failed to watch dir");
loop {
if let Ok(Ok(event)) = rx.recv() {
if let Some(event) = event.first() {
if !event.kind.is_access() {
handler();
}
}
}
}
});
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/helpers/config.rs | crates/tauri-cli/src/helpers/config.rs | // Copyright 2019-2025 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use itertools::Itertools;
use json_patch::merge;
use serde_json::Value as JsonValue;
use tauri_utils::acl::REMOVE_UNUSED_COMMANDS_ENV_VAR;
pub use tauri_utils::{config::*, platform::Target};
use std::{
collections::HashMap,
env::{current_dir, set_current_dir, set_var},
ffi::{OsStr, OsString},
process::exit,
sync::{Mutex, OnceLock},
};
use crate::error::Context;
pub const MERGE_CONFIG_EXTENSION_NAME: &str = "--config";
pub struct ConfigMetadata {
/// The current target.
target: Target,
original_identifier: Option<String>,
/// The actual configuration, merged with any extension.
inner: Config,
/// The config extensions (platform-specific config files or the config CLI argument).
/// Maps the extension name to its value.
extensions: HashMap<OsString, JsonValue>,
}
impl std::ops::Deref for ConfigMetadata {
type Target = Config;
#[inline(always)]
fn deref(&self) -> &Config {
&self.inner
}
}
impl ConfigMetadata {
/// The original bundle identifier from the config file.
/// This does not take any extensions into account.
pub fn original_identifier(&self) -> Option<&str> {
self.original_identifier.as_deref()
}
/// Checks which config is overwriting the bundle identifier.
pub fn find_bundle_identifier_overwriter(&self) -> Option<OsString> {
for (ext, config) in &self.extensions {
if let Some(identifier) = config
.as_object()
.and_then(|bundle_config| bundle_config.get("identifier"))
.and_then(|id| id.as_str())
{
if identifier == self.inner.identifier {
return Some(ext.clone());
}
}
}
None
}
}
pub type ConfigHandle = &'static Mutex<Option<ConfigMetadata>>;
pub fn wix_settings(config: WixConfig) -> tauri_bundler::WixSettings {
tauri_bundler::WixSettings {
version: config.version,
upgrade_code: config.upgrade_code,
fips_compliant: std::env::var("TAURI_BUNDLER_WIX_FIPS_COMPLIANT")
.ok()
.map(|v| v == "true")
.unwrap_or(config.fips_compliant),
language: tauri_bundler::WixLanguage(match config.language {
WixLanguage::One(lang) => vec![(lang, Default::default())],
WixLanguage::List(languages) => languages
.into_iter()
.map(|lang| (lang, Default::default()))
.collect(),
WixLanguage::Localized(languages) => languages
.into_iter()
.map(|(lang, config)| {
(
lang,
tauri_bundler::WixLanguageConfig {
locale_path: config.locale_path.map(Into::into),
},
)
})
.collect(),
}),
template: config.template,
fragment_paths: config.fragment_paths,
component_group_refs: config.component_group_refs,
component_refs: config.component_refs,
feature_group_refs: config.feature_group_refs,
feature_refs: config.feature_refs,
merge_refs: config.merge_refs,
enable_elevated_update_task: config.enable_elevated_update_task,
banner_path: config.banner_path,
dialog_image_path: config.dialog_image_path,
}
}
pub fn nsis_settings(config: NsisConfig) -> tauri_bundler::NsisSettings {
tauri_bundler::NsisSettings {
template: config.template,
header_image: config.header_image,
sidebar_image: config.sidebar_image,
installer_icon: config.installer_icon,
install_mode: config.install_mode,
languages: config.languages,
custom_language_files: config.custom_language_files,
display_language_selector: config.display_language_selector,
compression: config.compression,
start_menu_folder: config.start_menu_folder,
installer_hooks: config.installer_hooks,
minimum_webview2_version: config.minimum_webview2_version,
}
}
pub fn custom_sign_settings(
config: CustomSignCommandConfig,
) -> tauri_bundler::CustomSignCommandSettings {
match config {
CustomSignCommandConfig::Command(command) => {
let mut tokens = command.split(' ');
tauri_bundler::CustomSignCommandSettings {
cmd: tokens.next().unwrap().to_string(), // split always has at least one element
args: tokens.map(String::from).collect(),
}
}
CustomSignCommandConfig::CommandWithOptions { cmd, args } => {
tauri_bundler::CustomSignCommandSettings { cmd, args }
}
}
}
fn config_handle() -> ConfigHandle {
static CONFIG_HANDLE: Mutex<Option<ConfigMetadata>> = Mutex::new(None);
&CONFIG_HANDLE
}
fn config_schema_validator() -> &'static jsonschema::Validator {
// TODO: Switch to `LazyLock` when we bump MSRV to above 1.80
static CONFIG_SCHEMA_VALIDATOR: OnceLock<jsonschema::Validator> = OnceLock::new();
CONFIG_SCHEMA_VALIDATOR.get_or_init(|| {
let schema: JsonValue = serde_json::from_str(include_str!("../../config.schema.json"))
.expect("Failed to parse config schema bundled in the tauri-cli");
jsonschema::validator_for(&schema).expect("Config schema bundled in the tauri-cli is invalid")
})
}
/// Gets the static parsed config from `tauri.conf.json`.
fn get_internal(
merge_configs: &[&serde_json::Value],
reload: bool,
target: Target,
) -> crate::Result<ConfigHandle> {
if !reload && config_handle().lock().unwrap().is_some() {
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();
let mut extensions = HashMap::new();
let original_identifier = config
.as_object()
.and_then(|config| config.get("identifier"))
.and_then(|id| id.as_str())
.map(ToString::to_string);
if let Some((platform_config, config_path)) =
tauri_utils::config::parse::read_platform(target, tauri_dir)
.context("failed to parse platform config")?
{
merge(&mut config, &platform_config);
extensions.insert(config_path.file_name().unwrap().into(), platform_config);
}
if !merge_configs.is_empty() {
let mut merge_config = serde_json::Value::Object(Default::default());
for conf in merge_configs {
merge_patches(&mut merge_config, conf);
}
let merge_config_str = serde_json::to_string(&merge_config).unwrap();
set_var("TAURI_CONFIG", merge_config_str);
merge(&mut config, &merge_config);
extensions.insert(MERGE_CONFIG_EXTENSION_NAME.into(), merge_config);
}
if config_path.extension() == Some(OsStr::new("json"))
|| config_path.extension() == Some(OsStr::new("json5"))
{
let mut errors = config_schema_validator().iter_errors(&config).peekable();
if errors.peek().is_some() {
for error in errors {
let path = error.instance_path.into_iter().join(" > ");
if path.is_empty() {
log::error!("`{config_file_name:?}` error: {error}");
} else {
log::error!("`{config_file_name:?}` error on `{path}`: {error}");
}
}
if !reload {
exit(1);
}
}
}
// the `Config` deserializer for `package > version` can resolve the version from a path relative to the config path
// so we actually need to change the current working directory here
let current_dir = current_dir().context("failed to resolve current directory")?;
set_current_dir(config_path.parent().unwrap()).context("failed to set current directory")?;
let config: Config = serde_json::from_value(config).context("failed to parse config")?;
// revert to previous working directory
set_current_dir(current_dir).context("failed to set current directory")?;
for (plugin, conf) in &config.plugins.0 {
set_var(
format!(
"TAURI_{}_PLUGIN_CONFIG",
plugin.to_uppercase().replace('-', "_")
),
serde_json::to_string(&conf).context("failed to serialize config")?,
);
}
if config.build.remove_unused_commands {
std::env::set_var(REMOVE_UNUSED_COMMANDS_ENV_VAR, tauri_dir);
}
*config_handle().lock().unwrap() = Some(ConfigMetadata {
target,
original_identifier,
inner: config,
extensions,
});
Ok(config_handle())
}
pub fn get(target: Target, merge_configs: &[&serde_json::Value]) -> crate::Result<ConfigHandle> {
get_internal(merge_configs, false, target)
}
pub fn reload(merge_configs: &[&serde_json::Value]) -> crate::Result<ConfigHandle> {
let target = config_handle()
.lock()
.unwrap()
.as_ref()
.map(|conf| conf.target);
if let Some(target) = target {
get_internal(merge_configs, true, target)
} else {
crate::error::bail!("config not loaded");
}
}
/// merges the loaded config with the given value
pub fn merge_with(merge_configs: &[&serde_json::Value]) -> crate::Result<ConfigHandle> {
let handle = config_handle();
if merge_configs.is_empty() {
return Ok(handle);
}
if let Some(config_metadata) = &mut *handle.lock().unwrap() {
let mut merge_config = serde_json::Value::Object(Default::default());
for conf in merge_configs {
merge_patches(&mut merge_config, conf);
}
let merge_config_str = serde_json::to_string(&merge_config).unwrap();
set_var("TAURI_CONFIG", merge_config_str);
let mut value =
serde_json::to_value(config_metadata.inner.clone()).context("failed to serialize config")?;
merge(&mut value, &merge_config);
config_metadata.inner = serde_json::from_value(value).context("failed to parse config")?;
Ok(handle)
} else {
crate::error::bail!("config not loaded");
}
}
/// Same as [`json_patch::merge`] but doesn't delete the key when the patch's value is `null`
fn merge_patches(doc: &mut serde_json::Value, patch: &serde_json::Value) {
use serde_json::{Map, Value};
if !patch.is_object() {
*doc = patch.clone();
return;
}
if !doc.is_object() {
*doc = Value::Object(Map::new());
}
let map = doc.as_object_mut().unwrap();
for (key, value) in patch.as_object().unwrap() {
merge_patches(map.entry(key.as_str()).or_insert(Value::Null), value);
}
}
#[cfg(test)]
mod tests {
#[test]
fn merge_patches() {
let mut json = serde_json::Value::Object(Default::default());
super::merge_patches(
&mut json,
&serde_json::json!({
"app": {
"withGlobalTauri": true,
"windows": []
},
"plugins": {
"test": "tauri"
},
"build": {
"devUrl": "http://localhost:8080"
}
}),
);
super::merge_patches(
&mut json,
&serde_json::json!({
"app": { "withGlobalTauri": null }
}),
);
super::merge_patches(
&mut json,
&serde_json::json!({
"app": { "windows": null }
}),
);
super::merge_patches(
&mut json,
&serde_json::json!({
"plugins": { "updater": {
"endpoints": ["https://tauri.app"]
} }
}),
);
assert_eq!(
json,
serde_json::json!({
"app": {
"withGlobalTauri": null,
"windows": null
},
"plugins": {
"test": "tauri",
"updater": {
"endpoints": ["https://tauri.app"]
}
},
"build": {
"devUrl": "http://localhost:8080"
}
})
)
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/helpers/http.rs | crates/tauri-cli/src/helpers/http.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use ureq::{http::Response, Agent, Body};
const CLI_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"),);
pub fn get(url: &str) -> Result<Response<Body>, ureq::Error> {
#[allow(unused_mut)]
let mut config_builder = ureq::Agent::config_builder()
.user_agent(CLI_USER_AGENT)
.proxy(ureq::Proxy::try_from_env());
#[cfg(feature = "platform-certs")]
{
config_builder = config_builder.tls_config(
ureq::tls::TlsConfig::builder()
.root_certs(ureq::tls::RootCerts::PlatformVerifier)
.build(),
);
}
let agent: Agent = config_builder.build().into();
agent.get(url).call()
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/helpers/cargo_manifest.rs | crates/tauri-cli/src/helpers/cargo_manifest.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use serde::Deserialize;
use std::{
collections::HashMap,
fs,
path::{Path, PathBuf},
};
use crate::interface::rust::get_workspace_dir;
#[derive(Clone, Deserialize)]
pub struct CargoLockPackage {
pub name: String,
pub version: String,
pub source: Option<String>,
}
#[derive(Deserialize)]
pub struct CargoLock {
pub package: Vec<CargoLockPackage>,
}
#[derive(Clone, Deserialize)]
pub struct CargoManifestDependencyPackage {
pub version: Option<String>,
pub git: Option<String>,
pub branch: Option<String>,
pub rev: Option<String>,
pub path: Option<PathBuf>,
}
#[derive(Clone, Deserialize)]
#[serde(untagged)]
pub enum CargoManifestDependency {
Version(String),
Package(CargoManifestDependencyPackage),
}
#[derive(Deserialize)]
pub struct CargoManifestPackage {
pub version: String,
}
#[derive(Deserialize)]
pub struct CargoManifest {
pub package: CargoManifestPackage,
pub dependencies: HashMap<String, CargoManifestDependency>,
}
pub fn cargo_manifest_and_lock(tauri_dir: &Path) -> (Option<CargoManifest>, Option<CargoLock>) {
let manifest: Option<CargoManifest> = fs::read_to_string(tauri_dir.join("Cargo.toml"))
.ok()
.and_then(|manifest_contents| toml::from_str(&manifest_contents).ok());
let lock: Option<CargoLock> = get_workspace_dir()
.ok()
.and_then(|p| fs::read_to_string(p.join("Cargo.lock")).ok())
.and_then(|s| toml::from_str(&s).ok());
(manifest, lock)
}
#[derive(Default)]
pub struct CrateVersion {
pub version: Option<String>,
pub git: Option<String>,
pub git_branch: Option<String>,
pub git_rev: Option<String>,
pub path: Option<PathBuf>,
pub lock_version: Option<String>,
}
impl CrateVersion {
pub fn has_version(&self) -> bool {
self.version.is_some() || self.git.is_some() || self.path.is_some()
}
}
impl std::fmt::Display for CrateVersion {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(g) = &self.git {
if let Some(version) = &self.version {
write!(f, "{g} ({version})")?;
} else {
write!(f, "git:{g}")?;
if let Some(branch) = &self.git_branch {
write!(f, "&branch={branch}")?;
} else if let Some(rev) = &self.git_rev {
write!(f, "#rev={rev}")?;
}
}
} else if let Some(p) = &self.path {
write!(f, "path:{}", p.display())?;
if let Some(version) = &self.version {
write!(f, " ({version})")?;
}
} else if let Some(version) = &self.version {
write!(f, "{version}")?;
} else {
return write!(f, "No version detected");
}
if let Some(lock_version) = &self.lock_version {
write!(f, " ({lock_version})")?;
}
Ok(())
}
}
// Reference: https://github.com/rust-lang/crates.io/blob/98c83c8231cbcd15d6b8f06d80a00ad462f71585/src/views.rs#L274
#[derive(serde::Deserialize)]
struct CrateMetadata {
/// The "default" version of this crate.
///
/// This version will be displayed by default on the crate's page.
pub default_version: Option<String>,
}
// Reference: https://github.com/rust-lang/crates.io/blob/98c83c8231cbcd15d6b8f06d80a00ad462f71585/src/controllers/krate/metadata.rs#L44
#[derive(serde::Deserialize)]
struct CrateIoGetResponse {
/// The crate metadata.
#[serde(rename = "crate")]
krate: CrateMetadata,
}
pub fn crate_latest_version(name: &str) -> Option<String> {
// Reference: https://github.com/rust-lang/crates.io/blob/98c83c8231cbcd15d6b8f06d80a00ad462f71585/src/controllers/krate/metadata.rs#L88
let url = format!("https://crates.io/api/v1/crates/{name}?include");
let mut response = super::http::get(&url).ok()?;
let metadata: CrateIoGetResponse =
serde_json::from_reader(response.body_mut().as_reader()).unwrap();
metadata.krate.default_version
}
pub fn crate_version(
tauri_dir: &Path,
manifest: Option<&CargoManifest>,
lock: Option<&CargoLock>,
name: &str,
) -> CrateVersion {
let mut version = CrateVersion::default();
let crate_lock_packages: Vec<CargoLockPackage> = lock
.as_ref()
.map(|lock| {
lock
.package
.iter()
.filter(|p| p.name == name)
.cloned()
.collect()
})
.unwrap_or_default();
if crate_lock_packages.len() == 1 {
let crate_lock_package = crate_lock_packages.first().unwrap();
if let Some(s) = crate_lock_package
.source
.as_ref()
.filter(|s| s.starts_with("git"))
{
version.git = Some(s.clone());
}
version.version = Some(crate_lock_package.version.clone());
} else {
if let Some(dep) = manifest.and_then(|m| m.dependencies.get(name).cloned()) {
match dep {
CargoManifestDependency::Version(v) => version.version = Some(v),
CargoManifestDependency::Package(p) => {
if let Some(v) = p.version {
version.version = Some(v);
} else if let Some(p) = p.path {
let manifest_path = tauri_dir.join(&p).join("Cargo.toml");
let v = fs::read_to_string(manifest_path)
.ok()
.and_then(|m| toml::from_str::<CargoManifest>(&m).ok())
.map(|m| m.package.version);
version.version = v;
version.path = Some(p);
} else if let Some(g) = p.git {
version.git = Some(g);
version.git_branch = p.branch;
version.git_rev = p.rev;
}
}
}
}
if lock.is_some() && crate_lock_packages.is_empty() {
let lock_version = crate_lock_packages
.iter()
.map(|p| p.version.clone())
.collect::<Vec<String>>()
.join(", ");
if !lock_version.is_empty() {
version.lock_version = Some(lock_version);
}
}
}
version
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/helpers/updater_signature.rs | crates/tauri-cli/src/helpers/updater_signature.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use base64::Engine;
use minisign::{
sign, KeyPair as KP, PublicKey, PublicKeyBox, SecretKey, SecretKeyBox, SignatureBox,
};
use std::{
fs::{self, File, OpenOptions},
io::{BufReader, BufWriter, Write},
path::{Path, PathBuf},
str,
time::{SystemTime, UNIX_EPOCH},
};
use crate::error::{Context, ErrorExt};
/// A key pair (`PublicKey` and `SecretKey`).
#[derive(Clone, Debug)]
pub struct KeyPair {
pub pk: String,
pub sk: String,
}
fn create_file(path: &Path) -> crate::Result<BufWriter<File>> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).fs_context("failed to create directory", parent.to_path_buf())?;
}
let file = File::create(path).fs_context("failed to create file", path.to_path_buf())?;
Ok(BufWriter::new(file))
}
/// Generate base64 encoded keypair
pub fn generate_key(password: Option<String>) -> crate::Result<KeyPair> {
let KP { pk, sk } = KP::generate_encrypted_keypair(password).unwrap();
let pk_box_str = pk.to_box().unwrap().to_string();
let sk_box_str = sk.to_box(None).unwrap().to_string();
let encoded_pk = base64::engine::general_purpose::STANDARD.encode(pk_box_str);
let encoded_sk = base64::engine::general_purpose::STANDARD.encode(sk_box_str);
Ok(KeyPair {
pk: encoded_pk,
sk: encoded_sk,
})
}
/// Transform a base64 String to readable string for the main signer
pub fn decode_key<S: AsRef<[u8]>>(base64_key: S) -> crate::Result<String> {
let decoded_str = &base64::engine::general_purpose::STANDARD
.decode(base64_key)
.context("failed to decode base64 key")?[..];
Ok(String::from(
str::from_utf8(decoded_str).context("failed to convert base64 to utf8")?,
))
}
/// Save KeyPair to disk
pub fn save_keypair<P>(
force: bool,
sk_path: P,
key: &str,
pubkey: &str,
) -> crate::Result<(PathBuf, PathBuf)>
where
P: AsRef<Path>,
{
let sk_path = sk_path.as_ref();
let pubkey_path = format!("{}.pub", sk_path.display());
let pk_path = Path::new(&pubkey_path);
if sk_path.exists() {
if !force {
crate::error::bail!(
"Key generation aborted:\n{} already exists\nIf you really want to overwrite the existing key pair, add the --force switch to force this operation.",
sk_path.display()
);
} else {
std::fs::remove_file(sk_path)
.fs_context("failed to remove secret key file", sk_path.to_path_buf())?;
}
}
if pk_path.exists() {
std::fs::remove_file(pk_path)
.fs_context("failed to remove public key file", pk_path.to_path_buf())?;
}
let write_file = |mut writer: BufWriter<File>, contents: &str| -> std::io::Result<()> {
write!(writer, "{contents:}")?;
writer.flush()?;
Ok(())
};
write_file(create_file(sk_path)?, key)
.fs_context("failed to write secret key", sk_path.to_path_buf())?;
write_file(create_file(pk_path)?, pubkey)
.fs_context("failed to write public key", pk_path.to_path_buf())?;
Ok((
fs::canonicalize(sk_path).fs_context(
"failed to canonicalize secret key path",
sk_path.to_path_buf(),
)?,
fs::canonicalize(pk_path).fs_context(
"failed to canonicalize public key path",
pk_path.to_path_buf(),
)?,
))
}
/// Sign files
pub fn sign_file<P>(secret_key: &SecretKey, bin_path: P) -> crate::Result<(PathBuf, SignatureBox)>
where
P: AsRef<Path>,
{
let bin_path = bin_path.as_ref();
// We need to append .sig at the end it's where the signature will be stored
let mut extension = bin_path.extension().unwrap().to_os_string();
extension.push(".sig");
let signature_path = bin_path.with_extension(extension);
let trusted_comment = format!(
"timestamp:{}\tfile:{}",
unix_timestamp(),
bin_path.file_name().unwrap().to_string_lossy()
);
let data_reader = open_data_file(bin_path)?;
let signature_box = sign(
None,
secret_key,
data_reader,
Some(trusted_comment.as_str()),
Some("signature from tauri secret key"),
)
.context("failed to sign file")?;
let encoded_signature =
base64::engine::general_purpose::STANDARD.encode(signature_box.to_string());
std::fs::write(&signature_path, encoded_signature.as_bytes())
.fs_context("failed to write signature file", signature_path.clone())?;
Ok((
fs::canonicalize(&signature_path)
.fs_context("failed to canonicalize signature file", &signature_path)?,
signature_box,
))
}
/// Gets the updater secret key from the given private key and password.
pub fn secret_key<S: AsRef<[u8]>>(
private_key: S,
password: Option<String>,
) -> crate::Result<SecretKey> {
let decoded_secret = decode_key(private_key).context("failed to decode base64 secret key")?;
let sk_box =
SecretKeyBox::from_string(&decoded_secret).context("failed to load updater private key")?;
let sk = sk_box
.into_secret_key(password)
.context("incorrect updater private key password")?;
Ok(sk)
}
/// Gets the updater secret key from the given private key and password.
pub fn pub_key<S: AsRef<[u8]>>(public_key: S) -> crate::Result<PublicKey> {
let decoded_publick = decode_key(public_key).context("failed to decode base64 pubkey")?;
let pk_box =
PublicKeyBox::from_string(&decoded_publick).context("failed to load updater pubkey")?;
let pk = pk_box
.into_public_key()
.context("failed to convert updater pubkey")?;
Ok(pk)
}
fn unix_timestamp() -> u64 {
let start = SystemTime::now();
let since_the_epoch = start
.duration_since(UNIX_EPOCH)
.expect("system clock is incorrect");
since_the_epoch.as_secs()
}
fn open_data_file<P>(data_path: P) -> crate::Result<BufReader<File>>
where
P: AsRef<Path>,
{
let data_path = data_path.as_ref();
let file = OpenOptions::new()
.read(true)
.open(data_path)
.fs_context("failed to open data file", data_path.to_path_buf())?;
Ok(BufReader::new(file))
}
#[cfg(test)]
mod tests {
const PRIVATE_KEY: &str = "dW50cnVzdGVkIGNvbW1lbnQ6IHJzaWduIGVuY3J5cHRlZCBzZWNyZXQga2V5ClJXUlRZMEl5dkpDN09RZm5GeVAzc2RuYlNzWVVJelJRQnNIV2JUcGVXZUplWXZXYXpqUUFBQkFBQUFBQUFBQUFBQUlBQUFBQTZrN2RnWGh5dURxSzZiL1ZQSDdNcktiaHRxczQwMXdQelRHbjRNcGVlY1BLMTBxR2dpa3I3dDE1UTVDRDE4MXR4WlQwa1BQaXdxKy9UU2J2QmVSNXhOQWFDeG1GSVllbUNpTGJQRkhhTnROR3I5RmdUZi90OGtvaGhJS1ZTcjdZU0NyYzhQWlQ5cGM9Cg==";
// minisign >=0.7.4,<0.8.0 couldn't handle empty passwords.
#[test]
fn empty_password_is_valid() {
let path = std::env::temp_dir().join("minisign-password-text.txt");
std::fs::write(&path, b"TAURI").expect("failed to write test file");
let secret_key =
super::secret_key(PRIVATE_KEY, Some("".into())).expect("failed to resolve secret key");
super::sign_file(&secret_key, &path).expect("failed to sign file");
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/helpers/fs.rs | crates/tauri-cli/src/helpers/fs.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{
error::{Context, ErrorExt},
Error,
};
use std::path::{Path, PathBuf};
pub fn copy_file(from: impl AsRef<Path>, to: impl AsRef<Path>) -> crate::Result<()> {
let from = from.as_ref();
let to = to.as_ref();
if !from.exists() {
Err(Error::Fs {
context: "failed to copy file",
path: from.to_path_buf(),
error: std::io::Error::new(std::io::ErrorKind::NotFound, "source does not exist"),
})?;
}
if !from.is_file() {
Err(Error::Fs {
context: "failed to copy file",
path: from.to_path_buf(),
error: std::io::Error::other("not a file"),
})?;
}
let dest_dir = to.parent().expect("No data in parent");
std::fs::create_dir_all(dest_dir)
.fs_context("failed to create directory", dest_dir.to_path_buf())?;
std::fs::copy(from, to).fs_context("failed to copy file", from.to_path_buf())?;
Ok(())
}
/// Find an entry in a directory matching a glob pattern.
/// Currently does not traverse subdirectories.
// currently only used on macOS
#[allow(dead_code)]
pub fn find_in_directory(path: &Path, glob_pattern: &str) -> crate::Result<PathBuf> {
let pattern = glob::Pattern::new(glob_pattern)
.with_context(|| format!("failed to parse glob pattern {glob_pattern}"))?;
for entry in std::fs::read_dir(path)
.with_context(|| format!("failed to read directory {}", path.display()))?
{
let entry = entry.context("failed to read directory entry")?;
if pattern.matches_path(&entry.path()) {
return Ok(entry.path());
}
}
crate::error::bail!(
"No file found in {} matching {}",
path.display(),
glob_pattern
)
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/helpers/pbxproj.rs | crates/tauri-cli/src/helpers/pbxproj.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{
collections::BTreeMap,
fmt,
path::{Path, PathBuf},
};
use crate::error::ErrorExt;
pub fn parse<P: AsRef<Path>>(path: P) -> crate::Result<Pbxproj> {
let path = path.as_ref();
let pbxproj =
std::fs::read_to_string(path).fs_context("failed to read pbxproj file", path.to_path_buf())?;
let mut proj = Pbxproj {
path: path.to_owned(),
raw_lines: pbxproj.split('\n').map(ToOwned::to_owned).collect(),
xc_build_configuration: BTreeMap::new(),
xc_configuration_list: BTreeMap::new(),
additions: BTreeMap::new(),
has_changes: false,
};
let mut state = State::Idle;
let mut iter = proj.raw_lines.iter().enumerate();
while let Some((line_number, line)) = iter.next() {
match &state {
State::Idle => {
if line == "/* Begin XCBuildConfiguration section */" {
state = State::XCBuildConfiguration;
} else if line == "/* Begin XCConfigurationList section */" {
state = State::XCConfigurationList;
}
}
// XCBuildConfiguration
State::XCBuildConfiguration => {
if line == "/* End XCBuildConfiguration section */" {
state = State::Idle;
} else if let Some((_identation, token)) = split_at_identation(line) {
let id: String = token.chars().take_while(|c| !c.is_whitespace()).collect();
proj.xc_build_configuration.insert(
id.clone(),
XCBuildConfiguration {
build_settings: Vec::new(),
},
);
state = State::XCBuildConfigurationObject { id };
}
}
State::XCBuildConfigurationObject { id } => {
if line.contains("buildSettings") {
state = State::XCBuildConfigurationObjectBuildSettings { id: id.clone() };
} else if split_at_identation(line).is_some_and(|(_ident, token)| token == "};") {
state = State::XCBuildConfiguration;
}
}
State::XCBuildConfigurationObjectBuildSettings { id } => {
if let Some((identation, token)) = split_at_identation(line) {
if token == "};" {
state = State::XCBuildConfigurationObject { id: id.clone() };
} else {
let assignment = token.trim_end_matches(';');
if let Some((key, value)) = assignment.split_once(" = ") {
// multiline value
let value = if value == "(" {
let mut value = value.to_string();
loop {
let Some((_next_line_number, next_line)) = iter.next() else {
break;
};
value.push_str(next_line);
value.push('\n');
if let Some((_, token)) = split_at_identation(next_line) {
if token == ");" {
break;
}
}
}
value
} else {
value.trim().to_string()
};
proj
.xc_build_configuration
.get_mut(id)
.unwrap()
.build_settings
.push(BuildSettings {
identation: identation.into(),
line_number,
key: key.trim().into(),
value,
});
}
}
}
}
// XCConfigurationList
State::XCConfigurationList => {
if line == "/* End XCConfigurationList section */" {
state = State::Idle;
} else if let Some((_identation, token)) = split_at_identation(line) {
let Some((id, comment)) = token.split_once(' ') else {
continue;
};
proj.xc_configuration_list.insert(
id.to_string(),
XCConfigurationList {
comment: comment.trim_end_matches(" = {").to_string(),
build_configurations: Vec::new(),
},
);
state = State::XCConfigurationListObject { id: id.to_string() };
}
}
State::XCConfigurationListObject { id } => {
if line.contains("buildConfigurations") {
state = State::XCConfigurationListObjectBuildConfigurations { id: id.clone() };
} else if split_at_identation(line).is_some_and(|(_ident, token)| token == "};") {
state = State::XCConfigurationList;
}
}
State::XCConfigurationListObjectBuildConfigurations { id } => {
if let Some((_identation, token)) = split_at_identation(line) {
if token == ");" {
state = State::XCConfigurationListObject { id: id.clone() };
} else {
let Some((build_configuration_id, comments)) = token.split_once(' ') else {
continue;
};
proj
.xc_configuration_list
.get_mut(id)
.unwrap()
.build_configurations
.push(BuildConfigurationRef {
id: build_configuration_id.to_string(),
comments: comments.trim_end_matches(',').to_string(),
});
}
}
}
}
}
Ok(proj)
}
fn split_at_identation(s: &str) -> Option<(&str, &str)> {
s.chars()
.position(|c| !c.is_ascii_whitespace())
.map(|pos| s.split_at(pos))
}
enum State {
Idle,
// XCBuildConfiguration
XCBuildConfiguration,
XCBuildConfigurationObject { id: String },
XCBuildConfigurationObjectBuildSettings { id: String },
// XCConfigurationList
XCConfigurationList,
XCConfigurationListObject { id: String },
XCConfigurationListObjectBuildConfigurations { id: String },
}
pub struct Pbxproj {
pub path: PathBuf,
raw_lines: Vec<String>,
pub xc_build_configuration: BTreeMap<String, XCBuildConfiguration>,
pub xc_configuration_list: BTreeMap<String, XCConfigurationList>,
// maps the line number to the line to add
additions: BTreeMap<usize, String>,
has_changes: bool,
}
impl fmt::Debug for Pbxproj {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Pbxproj")
.field("xc_build_configuration", &self.xc_build_configuration)
.field("xc_configuration_list", &self.xc_configuration_list)
.finish()
}
}
impl Pbxproj {
pub fn has_changes(&self) -> bool {
!self.additions.is_empty() || self.has_changes
}
fn serialize(&self) -> String {
let mut proj = String::new();
let last_line_number = self.raw_lines.len() - 1;
for (number, line) in self.raw_lines.iter().enumerate() {
if let Some(new) = self.additions.get(&number) {
proj.push_str(new);
proj.push('\n');
}
proj.push_str(line);
if number != last_line_number {
proj.push('\n');
}
}
proj
}
pub fn save(&self) -> std::io::Result<()> {
std::fs::write(&self.path, self.serialize())
}
pub fn set_build_settings(&mut self, build_configuration_id: &str, key: &str, value: &str) {
let Some(build_configuration) = self.xc_build_configuration.get_mut(build_configuration_id)
else {
return;
};
if let Some(build_setting) = build_configuration
.build_settings
.iter_mut()
.find(|s| s.key == key)
{
if build_setting.value != value {
let Some(line) = self.raw_lines.get_mut(build_setting.line_number) else {
return;
};
*line = format!("{}{key} = {value};", build_setting.identation);
self.has_changes = true;
}
} else {
let Some(last_build_setting) = build_configuration.build_settings.last().cloned() else {
return;
};
build_configuration.build_settings.push(BuildSettings {
identation: last_build_setting.identation.clone(),
line_number: last_build_setting.line_number + 1,
key: key.to_string(),
value: value.to_string(),
});
self.additions.insert(
last_build_setting.line_number + 1,
format!("{}{key} = {value};", last_build_setting.identation),
);
}
}
}
#[derive(Debug)]
pub struct XCBuildConfiguration {
build_settings: Vec<BuildSettings>,
}
impl XCBuildConfiguration {
pub fn get_build_setting(&self, key: &str) -> Option<&BuildSettings> {
self.build_settings.iter().find(|s| s.key == key)
}
}
#[derive(Debug, Clone)]
pub struct BuildSettings {
identation: String,
line_number: usize,
pub key: String,
pub value: String,
}
#[derive(Debug, Clone)]
pub struct XCConfigurationList {
pub comment: String,
pub build_configurations: Vec<BuildConfigurationRef>,
}
#[derive(Debug, Clone)]
pub struct BuildConfigurationRef {
pub id: String,
pub comments: String,
}
#[cfg(test)]
mod tests {
#[test]
fn parse() {
let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
let fixtures_path = manifest_dir.join("tests").join("fixtures").join("pbxproj");
let mut settings = insta::Settings::clone_current();
settings.set_snapshot_path(fixtures_path.join("snapshots"));
let _guard = settings.bind_to_scope();
insta::assert_debug_snapshot!(
"project.pbxproj",
super::parse(fixtures_path.join("project.pbxproj")).expect("failed to parse pbxproj")
);
}
#[test]
fn modify() {
let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
let fixtures_path = manifest_dir.join("tests").join("fixtures").join("pbxproj");
let mut settings = insta::Settings::clone_current();
settings.set_snapshot_path(fixtures_path.join("snapshots"));
let _guard = settings.bind_to_scope();
let mut pbxproj =
super::parse(fixtures_path.join("project.pbxproj")).expect("failed to parse pbxproj");
pbxproj.set_build_settings(
"DB_0E254D0FD84970B57F6410",
"PRODUCT_NAME",
"\"Tauri Test\"",
);
pbxproj.set_build_settings("DB_0E254D0FD84970B57F6410", "UNKNOWN", "9283j49238h");
insta::assert_snapshot!("project-modified.pbxproj", pbxproj.serialize());
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/helpers/template.rs | crates/tauri-cli/src/helpers/template.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{
fs::{create_dir_all, File},
io::Write,
path::{Path, PathBuf},
};
use handlebars::{to_json, Handlebars};
use include_dir::Dir;
use serde::Serialize;
use serde_json::value::{Map, Value as JsonValue};
use crate::error::ErrorExt;
/// Map of template variable names and values.
#[derive(Clone, Debug)]
#[repr(transparent)]
pub struct JsonMap(Map<String, JsonValue>);
impl Default for JsonMap {
fn default() -> Self {
Self(Map::new())
}
}
impl JsonMap {
pub fn insert(&mut self, name: &str, value: impl Serialize) {
self.0.insert(name.to_owned(), to_json(value));
}
pub fn inner(&self) -> &Map<String, JsonValue> {
&self.0
}
}
pub fn render<P: AsRef<Path>, D: Serialize>(
handlebars: &Handlebars<'_>,
data: &D,
dir: &Dir<'_>,
out_dir: P,
) -> crate::Result<()> {
let out_dir = out_dir.as_ref();
let mut created_dirs = Vec::new();
render_with_generator(handlebars, data, dir, out_dir, &mut |file_path: PathBuf| {
let path = out_dir.join(file_path);
let parent = path.parent().unwrap().to_path_buf();
if !created_dirs.contains(&parent) {
create_dir_all(&parent)?;
created_dirs.push(parent);
}
File::create(path).map(Some)
})
}
pub fn render_with_generator<
P: AsRef<Path>,
D: Serialize,
F: FnMut(PathBuf) -> std::io::Result<Option<File>>,
>(
handlebars: &Handlebars<'_>,
data: &D,
dir: &Dir<'_>,
out_dir: P,
out_file_generator: &mut F,
) -> crate::Result<()> {
let out_dir = out_dir.as_ref();
for file in dir.files() {
let mut file_path = file.path().to_path_buf();
// cargo for some reason ignores the /templates folder packaging when it has a Cargo.toml file inside
// so we rename the extension to `.crate-manifest`
if let Some(extension) = file_path.extension() {
if extension == "crate-manifest" {
file_path.set_extension("toml");
}
}
if let Some(mut output_file) = out_file_generator(file_path.clone())
.fs_context("failed to generate output file", file_path.clone())?
{
if let Some(utf8) = file.contents_utf8() {
handlebars
.render_template_to_write(utf8, &data, &mut output_file)
.expect("Failed to render template");
} else {
output_file
.write_all(file.contents())
.fs_context("failed to write template", file_path.clone())?;
}
}
}
for dir in dir.dirs() {
render_with_generator(handlebars, data, dir, out_dir, out_file_generator)?;
}
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/helpers/flock.rs | crates/tauri-cli/src/helpers/flock.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
// taken from https://github.com/rust-lang/cargo/blob/b0c9586f4cbf426914df47c65de38ea323772c74/src/cargo/util/flock.rs
#![allow(dead_code)]
use std::fs::{create_dir_all, File, OpenOptions};
use std::io;
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use crate::{error::ErrorExt, Error, Result};
use sys::*;
#[derive(Debug)]
pub struct FileLock {
f: Option<File>,
path: PathBuf,
state: State,
}
#[derive(PartialEq, Debug)]
enum State {
Unlocked,
Shared,
Exclusive,
}
impl FileLock {
/// Returns the underlying file handle of this lock.
pub fn file(&self) -> &File {
self.f.as_ref().unwrap()
}
/// Returns the underlying path that this lock points to.
///
/// Note that special care must be taken to ensure that the path is not
/// referenced outside the lifetime of this lock.
pub fn path(&self) -> &Path {
assert_ne!(self.state, State::Unlocked);
&self.path
}
/// Returns the parent path containing this file
pub fn parent(&self) -> &Path {
assert_ne!(self.state, State::Unlocked);
self.path.parent().unwrap()
}
}
impl Read for FileLock {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.file().read(buf)
}
}
impl Seek for FileLock {
fn seek(&mut self, to: SeekFrom) -> io::Result<u64> {
self.file().seek(to)
}
}
impl Write for FileLock {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.file().write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.file().flush()
}
}
impl Drop for FileLock {
fn drop(&mut self) {
if self.state != State::Unlocked {
if let Some(f) = self.f.take() {
let _ = unlock(&f);
}
}
}
}
/// Opens exclusive access to a file, returning the locked version of a
/// file.
///
/// This function will create a file at `path` if it doesn't already exist
/// (including intermediate directories), and then it will acquire an
/// exclusive lock on `path`. If the process must block waiting for the
/// lock, the `msg` is logged.
///
/// The returned file can be accessed to look at the path and also has
/// read/write access to the underlying file.
pub fn open_rw<P>(path: P, msg: &str) -> Result<FileLock>
where
P: AsRef<Path>,
{
open(
path.as_ref(),
OpenOptions::new().read(true).write(true).create(true),
State::Exclusive,
msg,
)
}
/// Opens shared access to a file, returning the locked version of a file.
///
/// This function will fail if `path` doesn't already exist, but if it does
/// then it will acquire a shared lock on `path`. If the process must block
/// waiting for the lock, the `msg` is logged.
///
/// The returned file can be accessed to look at the path and also has read
/// access to the underlying file. Any writes to the file will return an
/// error.
pub fn open_ro<P>(path: P, msg: &str) -> Result<FileLock>
where
P: AsRef<Path>,
{
open(
path.as_ref(),
OpenOptions::new().read(true),
State::Shared,
msg,
)
}
fn open(path: &Path, opts: &OpenOptions, state: State, msg: &str) -> Result<FileLock> {
// If we want an exclusive lock then if we fail because of NotFound it's
// likely because an intermediate directory didn't exist, so try to
// create the directory and then continue.
let f = opts.open(path).or_else(|e| {
if e.kind() == io::ErrorKind::NotFound && state == State::Exclusive {
create_dir_all(path.parent().unwrap()).fs_context(
"failed to create directory",
path.parent().unwrap().to_path_buf(),
)?;
Ok(
opts
.open(path)
.fs_context("failed to open file", path.to_path_buf())?,
)
} else {
Err(Error::Fs {
context: "failed to open file",
path: path.to_path_buf(),
error: e,
})
}
})?;
match state {
State::Exclusive => {
acquire(msg, path, &|| try_lock_exclusive(&f), &|| {
lock_exclusive(&f)
})?;
}
State::Shared => {
acquire(msg, path, &|| try_lock_shared(&f), &|| lock_shared(&f))?;
}
State::Unlocked => {}
}
Ok(FileLock {
f: Some(f),
path: path.to_path_buf(),
state,
})
}
/// Acquires a lock on a file in a "nice" manner.
///
/// Almost all long-running blocking actions in Cargo have a status message
/// associated with them as we're not sure how long they'll take. Whenever a
/// conflicted file lock happens, this is the case (we're not sure when the lock
/// will be released).
///
/// This function will acquire the lock on a `path`, printing out a nice message
/// to the console if we have to wait for it. It will first attempt to use `try`
/// to acquire a lock on the crate, and in the case of contention it will emit a
/// status message based on `msg` to `config`'s shell, and then use `block` to
/// block waiting to acquire a lock.
///
/// Returns an error if the lock could not be acquired or if any error other
/// than a contention error happens.
fn acquire(
msg: &str,
path: &Path,
lock_try: &dyn Fn() -> io::Result<()>,
lock_block: &dyn Fn() -> io::Result<()>,
) -> Result<()> {
// File locking on Unix is currently implemented via `flock`, which is known
// to be broken on NFS. We could in theory just ignore errors that happen on
// NFS, but apparently the failure mode [1] for `flock` on NFS is **blocking
// forever**, even if the "non-blocking" flag is passed!
//
// As a result, we just skip all file locks entirely on NFS mounts. That
// should avoid calling any `flock` functions at all, and it wouldn't work
// there anyway.
//
// [1]: https://github.com/rust-lang/cargo/issues/2615
if is_on_nfs_mount(path) {
return Ok(());
}
match lock_try() {
Ok(()) => return Ok(()),
// In addition to ignoring NFS which is commonly not working we also
// just ignore locking on filesystems that look like they don't
// implement file locking.
Err(e) if error_unsupported(&e) => return Ok(()),
Err(e) => {
if !error_contended(&e) {
return Err(Error::Fs {
context: "failed to lock file",
path: path.to_path_buf(),
error: e,
});
}
}
}
let msg = format!("waiting for file lock on {msg}");
log::info!(action = "Blocking"; "{}", &msg);
lock_block().fs_context("failed to lock file", path.to_path_buf())?;
return Ok(());
#[cfg(all(target_os = "linux", not(target_env = "musl")))]
fn is_on_nfs_mount(path: &Path) -> bool {
use std::ffi::CString;
use std::mem;
use std::os::unix::prelude::*;
let path = match CString::new(path.as_os_str().as_bytes()) {
Ok(path) => path,
Err(_) => return false,
};
unsafe {
let mut buf: libc::statfs = mem::zeroed();
let r = libc::statfs(path.as_ptr(), &mut buf);
r == 0 && buf.f_type as u32 == libc::NFS_SUPER_MAGIC as u32
}
}
#[cfg(any(not(target_os = "linux"), target_env = "musl"))]
fn is_on_nfs_mount(_path: &Path) -> bool {
false
}
}
#[cfg(unix)]
mod sys {
use std::fs::File;
use std::io::{Error, Result};
use std::os::unix::io::AsRawFd;
pub(super) fn lock_shared(file: &File) -> Result<()> {
flock(file, libc::LOCK_SH)
}
pub(super) fn lock_exclusive(file: &File) -> Result<()> {
flock(file, libc::LOCK_EX)
}
pub(super) fn try_lock_shared(file: &File) -> Result<()> {
flock(file, libc::LOCK_SH | libc::LOCK_NB)
}
pub(super) fn try_lock_exclusive(file: &File) -> Result<()> {
flock(file, libc::LOCK_EX | libc::LOCK_NB)
}
pub(super) fn unlock(file: &File) -> Result<()> {
flock(file, libc::LOCK_UN)
}
pub(super) fn error_contended(err: &Error) -> bool {
err.raw_os_error() == Some(libc::EWOULDBLOCK)
}
pub(super) fn error_unsupported(err: &Error) -> bool {
match err.raw_os_error() {
// Unfortunately, depending on the target, these may or may not be the same.
// For targets in which they are the same, the duplicate pattern causes a warning.
#[allow(unreachable_patterns)]
Some(libc::ENOTSUP | libc::EOPNOTSUPP) => true,
Some(libc::ENOSYS) => true,
_ => false,
}
}
#[cfg(not(target_os = "solaris"))]
fn flock(file: &File, flag: libc::c_int) -> Result<()> {
let ret = unsafe { libc::flock(file.as_raw_fd(), flag) };
if ret < 0 {
Err(Error::last_os_error())
} else {
Ok(())
}
}
#[cfg(target_os = "solaris")]
fn flock(file: &File, flag: libc::c_int) -> Result<()> {
// Solaris lacks flock(), so simply succeed with a no-op
Ok(())
}
}
#[cfg(windows)]
mod sys {
use std::fs::File;
use std::io::{Error, Result};
use std::mem;
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Foundation::{ERROR_INVALID_FUNCTION, ERROR_LOCK_VIOLATION, HANDLE};
use windows_sys::Win32::Storage::FileSystem::{
LockFileEx, UnlockFile, LOCKFILE_EXCLUSIVE_LOCK, LOCKFILE_FAIL_IMMEDIATELY, LOCK_FILE_FLAGS,
};
pub(super) fn lock_shared(file: &File) -> Result<()> {
lock_file(file, 0)
}
pub(super) fn lock_exclusive(file: &File) -> Result<()> {
lock_file(file, LOCKFILE_EXCLUSIVE_LOCK)
}
pub(super) fn try_lock_shared(file: &File) -> Result<()> {
lock_file(file, LOCKFILE_FAIL_IMMEDIATELY)
}
pub(super) fn try_lock_exclusive(file: &File) -> Result<()> {
lock_file(file, LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY)
}
pub(super) fn error_contended(err: &Error) -> bool {
err.raw_os_error() == Some(ERROR_LOCK_VIOLATION as i32)
}
pub(super) fn error_unsupported(err: &Error) -> bool {
err.raw_os_error() == Some(ERROR_INVALID_FUNCTION as i32)
}
pub(super) fn unlock(file: &File) -> Result<()> {
let ret = unsafe { UnlockFile(file.as_raw_handle() as HANDLE, 0, 0, !0, !0) };
if ret == 0 {
Err(Error::last_os_error())
} else {
Ok(())
}
}
fn lock_file(file: &File, flags: LOCK_FILE_FLAGS) -> Result<()> {
let ret = unsafe {
let mut overlapped = mem::zeroed();
LockFileEx(
file.as_raw_handle() as HANDLE,
flags,
0,
!0,
!0,
&mut overlapped,
)
};
if ret == 0 {
Err(Error::last_os_error())
} else {
Ok(())
}
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/helpers/app_paths.rs | crates/tauri-cli/src/helpers/app_paths.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{
cmp::Ordering,
env::current_dir,
ffi::OsStr,
path::{Path, PathBuf},
sync::OnceLock,
};
use ignore::WalkBuilder;
use tauri_utils::{
config::parse::{folder_has_configuration_file, is_configuration_file, ConfigFormat},
platform::Target,
};
const TAURI_GITIGNORE: &[u8] = include_bytes!("../../tauri.gitignore");
// path to the Tauri app (Rust crate) directory, usually `<project>/src-tauri/`
const ENV_TAURI_APP_PATH: &str = "TAURI_APP_PATH";
// path to the frontend app directory, usually `<project>/`
const ENV_TAURI_FRONTEND_PATH: &str = "TAURI_FRONTEND_PATH";
static FRONTEND_DIR: OnceLock<PathBuf> = OnceLock::new();
static TAURI_DIR: OnceLock<PathBuf> = OnceLock::new();
pub fn walk_builder(path: &Path) -> WalkBuilder {
let mut default_gitignore = std::env::temp_dir();
default_gitignore.push(".gitignore");
if !default_gitignore.exists() {
if let Ok(mut file) = std::fs::File::create(default_gitignore.clone()) {
use std::io::Write;
let _ = file.write_all(TAURI_GITIGNORE);
}
}
let mut builder = WalkBuilder::new(path);
builder.add_custom_ignore_filename(".taurignore");
builder.git_global(false);
builder.parents(false);
let _ = builder.add_ignore(default_gitignore);
builder
}
fn lookup<F: Fn(&PathBuf) -> bool>(dir: &Path, checker: F) -> Option<PathBuf> {
let mut builder = walk_builder(dir);
builder
.require_git(false)
.ignore(false)
.max_depth(Some(
std::env::var("TAURI_CLI_CONFIG_DEPTH")
.map(|d| {
d.parse()
.expect("`TAURI_CLI_CONFIG_DEPTH` environment variable must be a positive integer")
})
.unwrap_or(3),
))
.sort_by_file_path(|a, _| {
if a.extension().is_some() {
Ordering::Less
} else {
Ordering::Greater
}
});
for entry in builder.build().flatten() {
let path = dir.join(entry.path());
if checker(&path) {
return Some(path);
}
}
None
}
fn env_tauri_app_path() -> Option<PathBuf> {
let p = PathBuf::from(std::env::var_os(ENV_TAURI_APP_PATH)?);
dunce::canonicalize(p).ok()
}
fn env_tauri_frontend_path() -> Option<PathBuf> {
let p = PathBuf::from(std::env::var_os(ENV_TAURI_FRONTEND_PATH)?);
dunce::canonicalize(p).ok()
}
pub fn resolve_tauri_dir() -> Option<PathBuf> {
let src_dir = env_tauri_app_path().or_else(|| current_dir().ok())?;
for standard_tauri_path in [src_dir.clone(), src_dir.join("src-tauri")] {
if standard_tauri_path
.join(ConfigFormat::Json.into_file_name())
.exists()
|| standard_tauri_path
.join(ConfigFormat::Json5.into_file_name())
.exists()
|| standard_tauri_path
.join(ConfigFormat::Toml.into_file_name())
.exists()
{
log::debug!(
"Found Tauri project inside {} on early lookup",
standard_tauri_path.display()
);
return Some(standard_tauri_path);
}
}
log::debug!("resolving Tauri directory from {}", src_dir.display());
lookup(&src_dir, |path| {
folder_has_configuration_file(Target::Linux, path) || is_configuration_file(Target::Linux, path)
})
.map(|p| {
if p.is_dir() {
log::debug!("Found Tauri project directory {}", p.display());
p
} else {
log::debug!("Found Tauri project configuration file {}", p.display());
p.parent().unwrap().to_path_buf()
}
})
}
pub fn resolve() {
TAURI_DIR.set(resolve_tauri_dir().unwrap_or_else(|| {
let env_var_name = env_tauri_app_path().is_some().then(|| format!("`{ENV_TAURI_APP_PATH}`"));
panic!("Couldn't recognize the {} folder as a Tauri project. It must contain a `{}`, `{}` or `{}` file in any subfolder.",
env_var_name.as_deref().unwrap_or("current"),
ConfigFormat::Json.into_file_name(),
ConfigFormat::Json5.into_file_name(),
ConfigFormat::Toml.into_file_name()
)
})).expect("tauri dir already resolved");
FRONTEND_DIR
.set(resolve_frontend_dir().unwrap_or_else(|| tauri_dir().parent().unwrap().to_path_buf()))
.expect("app dir already resolved");
}
pub fn tauri_dir() -> &'static PathBuf {
TAURI_DIR
.get()
.expect("app paths not initialized, this is a Tauri CLI bug")
}
pub fn resolve_frontend_dir() -> Option<PathBuf> {
let frontend_dir =
env_tauri_frontend_path().unwrap_or_else(|| current_dir().expect("failed to read cwd"));
if frontend_dir.join("package.json").exists() {
return Some(frontend_dir);
}
log::debug!(
"resolving frontend directory from {}",
frontend_dir.display()
);
lookup(&frontend_dir, |path| {
if let Some(file_name) = path.file_name() {
file_name == OsStr::new("package.json")
} else {
false
}
})
.map(|p| p.parent().unwrap().to_path_buf())
}
pub fn frontend_dir() -> &'static PathBuf {
FRONTEND_DIR
.get()
.expect("app paths not initialized, this is a Tauri CLI bug")
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/helpers/prompts.rs | crates/tauri-cli/src/helpers/prompts.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{fmt::Display, str::FromStr};
use crate::{error::Context, Result};
pub fn input<T>(
prompt: &str,
initial: Option<T>,
skip: bool,
allow_empty: bool,
) -> Result<Option<T>>
where
T: Clone + FromStr + Display + ToString,
T::Err: Display + std::fmt::Debug,
T: PartialEq<str>,
{
if skip {
Ok(initial)
} else {
let theme = dialoguer::theme::ColorfulTheme::default();
let mut builder = dialoguer::Input::with_theme(&theme)
.with_prompt(prompt)
.allow_empty(allow_empty);
if let Some(v) = initial {
builder = builder.with_initial_text(v.to_string());
}
builder
.interact_text()
.map(|t: T| if t.ne("") { Some(t) } else { None })
.context("failed to prompt input")
}
}
pub fn confirm(prompt: &str, default: Option<bool>) -> Result<bool> {
let theme = dialoguer::theme::ColorfulTheme::default();
let mut builder = dialoguer::Confirm::with_theme(&theme).with_prompt(prompt);
if let Some(default) = default {
builder = builder.default(default);
}
builder.interact().context("failed to prompt confirm")
}
pub fn multiselect<T: ToString>(
prompt: &str,
items: &[T],
defaults: Option<&[bool]>,
) -> Result<Vec<usize>> {
let theme = dialoguer::theme::ColorfulTheme::default();
let mut builder = dialoguer::MultiSelect::with_theme(&theme)
.with_prompt(prompt)
.items(items);
if let Some(defaults) = defaults {
builder = builder.defaults(defaults);
}
builder.interact().context("failed to prompt multi-select")
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/helpers/framework.rs | crates/tauri-cli/src/helpers/framework.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::fmt;
#[derive(Debug, Clone)]
pub enum Framework {
SolidJS,
SolidStart,
Svelte,
SvelteKit,
Angular,
React,
Nextjs,
Gatsby,
Nuxt,
Quasar,
VueCli,
Vue,
}
impl Framework {
pub fn dev_url(&self) -> String {
match self {
Self::SolidJS => "http://localhost:3000",
Self::SolidStart => "http://localhost:3000",
Self::Svelte => "http://localhost:8080",
Self::SvelteKit => "http://localhost:5173",
Self::Angular => "http://localhost:4200",
Self::React => "http://localhost:3000",
Self::Nextjs => "http://localhost:3000",
Self::Gatsby => "http://localhost:8000",
Self::Nuxt => "http://localhost:3000",
Self::Quasar => "http://localhost:8080",
Self::VueCli => "http://localhost:8080",
Self::Vue => "http://localhost:8080",
}
.into()
}
pub fn frontend_dist(&self) -> String {
match self {
Self::SolidJS => "../dist",
Self::SolidStart => "../dist/public",
Self::Svelte => "../public",
Self::SvelteKit => "../build",
Self::Angular => "../dist",
Self::React => "../build",
Self::Nextjs => "../out",
Self::Gatsby => "../public",
Self::Nuxt => "../dist",
Self::Quasar => "../dist/spa",
Self::VueCli => "../dist",
Self::Vue => "../dist",
}
.into()
}
}
impl fmt::Display for Framework {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::SolidJS => write!(f, "SolidJS"),
Self::SolidStart => write!(f, "SolidStart"),
Self::Svelte => write!(f, "Svelte"),
Self::SvelteKit => write!(f, "SvelteKit"),
Self::Angular => write!(f, "Angular"),
Self::React => write!(f, "React"),
Self::Nextjs => write!(f, "React (Next.js)"),
Self::Gatsby => write!(f, "React (Gatsby)"),
Self::Nuxt => write!(f, "Vue.js (Nuxt)"),
Self::Quasar => write!(f, "Vue.js (Quasar)"),
Self::VueCli => write!(f, "Vue.js (Vue CLI)"),
Self::Vue => write!(f, "Vue.js"),
}
}
}
#[derive(Debug, Clone)]
pub enum Bundler {
Webpack,
Rollup,
Vite,
}
impl fmt::Display for Bundler {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Webpack => write!(f, "Webpack"),
Self::Rollup => write!(f, "Rollup"),
Self::Vite => write!(f, "Vite"),
}
}
}
pub fn infer_from_package_json(package_json: &str) -> (Option<Framework>, Option<Bundler>) {
let framework_map = [
("solid-start", Framework::SolidStart, Some(Bundler::Vite)),
("solid-js", Framework::SolidJS, Some(Bundler::Vite)),
("svelte", Framework::Svelte, Some(Bundler::Rollup)),
("@sveltejs/kit", Framework::SvelteKit, Some(Bundler::Vite)),
("@angular", Framework::Angular, Some(Bundler::Webpack)),
(r#""next""#, Framework::Nextjs, Some(Bundler::Webpack)),
("gatsby", Framework::Gatsby, Some(Bundler::Webpack)),
("react", Framework::React, None),
("nuxt", Framework::Nuxt, Some(Bundler::Webpack)),
("quasar", Framework::Quasar, Some(Bundler::Webpack)),
("@vue/cli", Framework::VueCli, Some(Bundler::Webpack)),
("vue", Framework::Vue, Some(Bundler::Vite)),
];
let bundler_map = [
("webpack", Bundler::Webpack),
("rollup", Bundler::Rollup),
("vite", Bundler::Vite),
];
let (framework, framework_bundler) = framework_map
.iter()
.find(|(keyword, _, _)| package_json.contains(keyword))
.map(|(_, framework, bundler)| (Some(framework.clone()), bundler.clone()))
.unwrap_or((None, None));
let bundler = bundler_map
.iter()
.find(|(keyword, _)| package_json.contains(keyword))
.map(|(_, bundler)| bundler.clone())
.or(framework_bundler);
(framework, bundler)
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/helpers/mod.rs | crates/tauri-cli/src/helpers/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
pub mod app_paths;
pub mod cargo;
pub mod cargo_manifest;
pub mod config;
pub mod flock;
pub mod framework;
pub mod fs;
pub mod http;
pub mod npm;
#[cfg(target_os = "macos")]
pub mod pbxproj;
#[cfg(target_os = "macos")]
pub mod plist;
pub mod plugins;
pub mod prompts;
pub mod template;
pub mod updater_signature;
use std::{
collections::HashMap,
path::{Path, PathBuf},
process::Command,
};
use tauri_utils::config::HookCommand;
#[cfg(not(target_os = "windows"))]
use crate::Error;
use crate::{
interface::{AppInterface, Interface},
CommandExt,
};
use self::app_paths::frontend_dir;
pub fn command_env(debug: bool) -> HashMap<&'static str, String> {
let mut map = HashMap::new();
map.insert(
"TAURI_ENV_PLATFORM_VERSION",
os_info::get().version().to_string(),
);
if debug {
map.insert("TAURI_ENV_DEBUG", "true".into());
}
map
}
pub fn resolve_tauri_path<P: AsRef<Path>>(path: P, crate_name: &str) -> PathBuf {
let path = path.as_ref();
if path.is_absolute() {
path.join(crate_name)
} else {
PathBuf::from("..").join(path).join(crate_name)
}
}
pub fn cross_command(bin: &str) -> Command {
#[cfg(target_os = "windows")]
let cmd = {
let mut cmd = Command::new("cmd");
cmd.arg("/c").arg(bin);
cmd
};
#[cfg(not(target_os = "windows"))]
let cmd = Command::new(bin);
cmd
}
pub fn run_hook(
name: &str,
hook: HookCommand,
interface: &AppInterface,
debug: bool,
) -> crate::Result<()> {
let (script, script_cwd) = match hook {
HookCommand::Script(s) if s.is_empty() => (None, None),
HookCommand::Script(s) => (Some(s), None),
HookCommand::ScriptWithOptions { script, cwd } => (Some(script), cwd.map(Into::into)),
};
let cwd = script_cwd.unwrap_or_else(|| frontend_dir().clone());
if let Some(script) = script {
log::info!(action = "Running"; "{} `{}`", name, script);
let mut env = command_env(debug);
env.extend(interface.env());
log::debug!("Setting environment for hook {:?}", env);
#[cfg(target_os = "windows")]
let status = Command::new("cmd")
.arg("/S")
.arg("/C")
.arg(&script)
.current_dir(cwd)
.envs(env)
.piped()
.map_err(|error| crate::error::Error::CommandFailed {
command: script.clone(),
error,
})?;
#[cfg(not(target_os = "windows"))]
let status = Command::new("sh")
.arg("-c")
.arg(&script)
.current_dir(cwd)
.envs(env)
.piped()
.map_err(|error| Error::CommandFailed {
command: script.clone(),
error,
})?;
if !status.success() {
crate::error::bail!(
"{} `{}` failed with exit code {}",
name,
script,
status.code().unwrap_or_default()
);
}
}
Ok(())
}
#[cfg(target_os = "macos")]
pub fn strip_semver_prerelease_tag(version: &mut semver::Version) -> crate::Result<()> {
use crate::error::Context;
if !version.pre.is_empty() {
if let Some((_prerelease_tag, number)) = version.pre.as_str().to_string().split_once('.') {
version.pre = semver::Prerelease::EMPTY;
version.build = semver::BuildMetadata::new(&format!(
"{prefix}{number}",
prefix = if version.build.is_empty() {
"".to_string()
} else {
format!(".{}", version.build.as_str())
}
))
.with_context(|| {
format!(
"failed to parse {version} as semver: bundle version {number:?} prerelease is invalid"
)
})?;
}
}
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/helpers/cargo.rs | crates/tauri-cli/src/helpers/cargo.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::process::Command;
use crate::Error;
#[derive(Debug, Default, Clone, Copy)]
pub struct CargoInstallOptions<'a> {
pub name: &'a str,
pub version: Option<&'a str>,
pub rev: Option<&'a str>,
pub tag: Option<&'a str>,
pub branch: Option<&'a str>,
pub cwd: Option<&'a std::path::Path>,
pub target: Option<&'a str>,
}
pub fn install_one(options: CargoInstallOptions) -> crate::Result<()> {
let mut cargo = Command::new("cargo");
cargo.arg("add");
if let Some(version) = options.version {
cargo.arg(format!("{}@{}", options.name, version));
} else {
cargo.arg(options.name);
if options.tag.is_some() || options.rev.is_some() || options.branch.is_some() {
cargo.args(["--git", "https://github.com/tauri-apps/plugins-workspace"]);
}
match (options.tag, options.rev, options.branch) {
(Some(tag), None, None) => {
cargo.args(["--tag", tag]);
}
(None, Some(rev), None) => {
cargo.args(["--rev", rev]);
}
(None, None, Some(branch)) => {
cargo.args(["--branch", branch]);
}
(None, None, None) => {}
_ => crate::error::bail!("Only one of --tag, --rev and --branch can be specified"),
};
}
if let Some(target) = options.target {
cargo.args(["--target", target]);
}
if let Some(cwd) = options.cwd {
cargo.current_dir(cwd);
}
log::info!("Installing Cargo dependency \"{}\"...", options.name);
let status = cargo.status().map_err(|error| Error::CommandFailed {
command: "cargo add".to_string(),
error,
})?;
if !status.success() {
crate::error::bail!("Failed to install Cargo dependency");
}
Ok(())
}
#[derive(Debug, Default, Clone, Copy)]
pub struct CargoUninstallOptions<'a> {
pub name: &'a str,
pub cwd: Option<&'a std::path::Path>,
pub target: Option<&'a str>,
}
pub fn uninstall_one(options: CargoUninstallOptions) -> crate::Result<()> {
let mut cargo = Command::new("cargo");
cargo.arg("remove");
cargo.arg(options.name);
if let Some(target) = options.target {
cargo.args(["--target", target]);
}
if let Some(cwd) = options.cwd {
cargo.current_dir(cwd);
}
log::info!("Uninstalling Cargo dependency \"{}\"...", options.name);
let status = cargo.status().map_err(|error| Error::CommandFailed {
command: "cargo remove".to_string(),
error,
})?;
if !status.success() {
crate::error::bail!("Failed to remove Cargo dependency");
}
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/helpers/plugins.rs | crates/tauri-cli/src/helpers/plugins.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::collections::HashMap;
#[derive(Default)]
pub struct PluginMetadata {
pub desktop_only: bool,
pub mobile_only: bool,
pub rust_only: bool,
pub builder: bool,
pub version_req: Option<String>,
}
// known plugins with particular cases
pub fn known_plugins() -> HashMap<&'static str, PluginMetadata> {
let mut plugins: HashMap<&'static str, PluginMetadata> = HashMap::new();
// desktop-only
for p in [
"authenticator",
"autostart",
"cli",
"global-shortcut",
"positioner",
"single-instance",
"updater",
"window-state",
] {
plugins.entry(p).or_default().desktop_only = true;
}
// mobile-only
for p in ["barcode-scanner", "biometric", "nfc", "haptics"] {
plugins.entry(p).or_default().mobile_only = true;
}
// uses builder pattern
for p in [
"autostart",
"global-shortcut",
"localhost",
"log",
"sql",
"store",
"stronghold",
"updater",
"window-state",
] {
plugins.entry(p).or_default().builder = true;
}
// rust-only
#[allow(clippy::single_element_loop)]
for p in ["localhost", "persisted-scope", "single-instance"] {
plugins.entry(p).or_default().rust_only = true;
}
// known, but no particular config
for p in [
"geolocation",
"deep-link",
"dialog",
"fs",
"http",
"notification",
"os",
"process",
"shell",
"upload",
"websocket",
"opener",
"clipboard-manager",
] {
plugins.entry(p).or_default();
}
let version_req = version_req();
for plugin in plugins.values_mut() {
plugin.version_req.replace(version_req.clone());
}
plugins
}
fn version_req() -> String {
let pre = env!("CARGO_PKG_VERSION_PRE");
if pre.is_empty() {
env!("CARGO_PKG_VERSION_MAJOR").to_string()
} else {
format!(
"{}.0.0-{}",
env!("CARGO_PKG_VERSION_MAJOR"),
pre.split('.').next().unwrap()
)
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/helpers/plist.rs | crates/tauri-cli/src/helpers/plist.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::path::PathBuf;
use crate::error::Context;
pub enum PlistKind {
Path(PathBuf),
Plist(plist::Value),
}
impl From<PathBuf> for PlistKind {
fn from(p: PathBuf) -> Self {
Self::Path(p)
}
}
impl From<plist::Value> for PlistKind {
fn from(p: plist::Value) -> Self {
Self::Plist(p)
}
}
pub fn merge_plist(src: Vec<PlistKind>) -> crate::Result<plist::Value> {
let mut merged_plist = plist::Dictionary::new();
for plist_kind in src {
let src_plist = match plist_kind {
PlistKind::Path(p) => plist::Value::from_file(&p)
.with_context(|| format!("failed to parse plist from {}", p.display()))?,
PlistKind::Plist(v) => v,
};
if let Some(dict) = src_plist.into_dictionary() {
for (key, value) in dict {
merged_plist.insert(key, value);
}
}
}
Ok(plist::Value::Dictionary(merged_plist))
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/helpers/npm.rs | crates/tauri-cli/src/helpers/npm.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use serde::Deserialize;
use crate::{
error::{Context, Error},
helpers::cross_command,
};
use std::{collections::HashMap, fmt::Display, path::Path, process::Command};
pub fn manager_version(package_manager: &str) -> Option<String> {
cross_command(package_manager)
.arg("-v")
.output()
.map(|o| {
if o.status.success() {
let v = String::from_utf8_lossy(o.stdout.as_slice()).to_string();
Some(v.split('\n').next().unwrap().to_string())
} else {
None
}
})
.ok()
.unwrap_or_default()
}
fn detect_yarn_or_berry() -> PackageManager {
if manager_version("yarn")
.map(|v| v.chars().next().map(|c| c > '1').unwrap_or_default())
.unwrap_or(false)
{
PackageManager::YarnBerry
} else {
PackageManager::Yarn
}
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum PackageManager {
Npm,
Pnpm,
Yarn,
YarnBerry,
Bun,
Deno,
}
impl Display for PackageManager {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
PackageManager::Npm => "npm",
PackageManager::Pnpm => "pnpm",
PackageManager::Yarn => "yarn",
PackageManager::YarnBerry => "yarn berry",
PackageManager::Bun => "bun",
PackageManager::Deno => "deno",
}
)
}
}
impl PackageManager {
/// Detects package manager from the given directory, falls back to [`PackageManager::Npm`].
pub fn from_project<P: AsRef<Path>>(path: P) -> Self {
Self::all_from_project(path)
.first()
.copied()
.unwrap_or(Self::Npm)
}
/// Detects package manager from the `npm_config_user_agent` environment variable
fn from_environment_variable() -> Option<Self> {
let npm_config_user_agent = std::env::var("npm_config_user_agent").ok()?;
match npm_config_user_agent {
user_agent if user_agent.starts_with("pnpm/") => Some(Self::Pnpm),
user_agent if user_agent.starts_with("deno/") => Some(Self::Deno),
user_agent if user_agent.starts_with("bun/") => Some(Self::Bun),
user_agent if user_agent.starts_with("yarn/") => Some(detect_yarn_or_berry()),
user_agent if user_agent.starts_with("npm/") => Some(Self::Npm),
_ => None,
}
}
/// Detects all possible package managers from the given directory.
pub fn all_from_project<P: AsRef<Path>>(path: P) -> Vec<Self> {
if let Some(from_env) = Self::from_environment_variable() {
return vec![from_env];
}
let mut found = Vec::new();
if let Ok(entries) = std::fs::read_dir(path) {
for entry in entries.flatten() {
let path = entry.path();
let name = path.file_name().unwrap().to_string_lossy();
match name.as_ref() {
"package-lock.json" => found.push(PackageManager::Npm),
"pnpm-lock.yaml" => found.push(PackageManager::Pnpm),
"yarn.lock" => found.push(detect_yarn_or_berry()),
"bun.lock" | "bun.lockb" => found.push(PackageManager::Bun),
"deno.lock" => found.push(PackageManager::Deno),
_ => (),
}
}
}
found
}
fn cross_command(&self) -> Command {
match self {
PackageManager::Yarn => cross_command("yarn"),
PackageManager::YarnBerry => cross_command("yarn"),
PackageManager::Npm => cross_command("npm"),
PackageManager::Pnpm => cross_command("pnpm"),
PackageManager::Bun => cross_command("bun"),
PackageManager::Deno => cross_command("deno"),
}
}
pub fn install<P: AsRef<Path>>(
&self,
dependencies: &[String],
frontend_dir: P,
) -> crate::Result<()> {
let dependencies_str = if dependencies.len() > 1 {
"dependencies"
} else {
"dependency"
};
log::info!(
"Installing NPM {dependencies_str} {}...",
dependencies
.iter()
.map(|d| format!("\"{d}\""))
.collect::<Vec<_>>()
.join(", ")
);
let mut command = self.cross_command();
command.arg("add");
match self {
PackageManager::Deno => command.args(dependencies.iter().map(|d| format!("npm:{d}"))),
_ => command.args(dependencies),
};
let status = command
.current_dir(frontend_dir)
.status()
.map_err(|error| Error::CommandFailed {
command: format!("failed to run {self}"),
error,
})?;
if !status.success() {
crate::error::bail!("Failed to install NPM {dependencies_str}");
}
Ok(())
}
pub fn remove<P: AsRef<Path>>(
&self,
dependencies: &[String],
frontend_dir: P,
) -> crate::Result<()> {
let dependencies_str = if dependencies.len() > 1 {
"dependencies"
} else {
"dependency"
};
log::info!(
"Removing NPM {dependencies_str} {}...",
dependencies
.iter()
.map(|d| format!("\"{d}\""))
.collect::<Vec<_>>()
.join(", ")
);
let status = self
.cross_command()
.arg(if *self == Self::Npm {
"uninstall"
} else {
"remove"
})
.args(dependencies)
.current_dir(frontend_dir)
.status()
.map_err(|error| Error::CommandFailed {
command: format!("failed to run {self}"),
error,
})?;
if !status.success() {
crate::error::bail!("Failed to remove NPM {dependencies_str}");
}
Ok(())
}
// TODO: Use `current_package_versions` as much as possible for better speed
pub fn current_package_version<P: AsRef<Path>>(
&self,
name: &str,
frontend_dir: P,
) -> crate::Result<Option<String>> {
let (output, regex) = match self {
PackageManager::Yarn => (
cross_command("yarn")
.args(["list", "--pattern"])
.arg(name)
.args(["--depth", "0"])
.current_dir(frontend_dir)
.output()
.map_err(|error| Error::CommandFailed {
command: "yarn list --pattern".to_string(),
error,
})?,
None,
),
PackageManager::YarnBerry => (
cross_command("yarn")
.arg("info")
.arg(name)
.arg("--json")
.current_dir(frontend_dir)
.output()
.map_err(|error| Error::CommandFailed {
command: "yarn info --json".to_string(),
error,
})?,
Some(regex::Regex::new("\"Version\":\"([\\da-zA-Z\\-\\.]+)\"").unwrap()),
),
PackageManager::Pnpm => (
cross_command("pnpm")
.arg("list")
.arg(name)
.args(["--parseable", "--depth", "0"])
.current_dir(frontend_dir)
.output()
.map_err(|error| Error::CommandFailed {
command: "pnpm list --parseable --depth 0".to_string(),
error,
})?,
None,
),
// Bun and Deno don't support `list` command
PackageManager::Npm | PackageManager::Bun | PackageManager::Deno => (
cross_command("npm")
.arg("list")
.arg(name)
.args(["version", "--depth", "0"])
.current_dir(frontend_dir)
.output()
.map_err(|error| Error::CommandFailed {
command: "npm list --version --depth 0".to_string(),
error,
})?,
None,
),
};
if output.status.success() {
let stdout = String::from_utf8_lossy(&output.stdout);
let regex = regex.unwrap_or_else(|| regex::Regex::new("@(\\d[\\da-zA-Z\\-\\.]+)").unwrap());
Ok(
regex
.captures_iter(&stdout)
.last()
.and_then(|cap| cap.get(1).map(|v| v.as_str().to_string())),
)
} else {
Ok(None)
}
}
pub fn current_package_versions(
&self,
packages: &[String],
frontend_dir: &Path,
) -> crate::Result<HashMap<String, semver::Version>> {
let output = match self {
PackageManager::Yarn => return yarn_package_versions(packages, frontend_dir),
PackageManager::YarnBerry => return yarn_berry_package_versions(packages, frontend_dir),
PackageManager::Pnpm => cross_command("pnpm")
.arg("list")
.args(packages)
.args(["--json", "--depth", "0"])
.current_dir(frontend_dir)
.output()
.map_err(|error| Error::CommandFailed {
command: "pnpm list --json --depth 0".to_string(),
error,
})?,
// Bun and Deno don't support `list` command
PackageManager::Npm | PackageManager::Bun | PackageManager::Deno => cross_command("npm")
.arg("list")
.args(packages)
.args(["--json", "--depth", "0"])
.current_dir(frontend_dir)
.output()
.map_err(|error| Error::CommandFailed {
command: "npm list --json --depth 0".to_string(),
error,
})?,
};
let mut versions = HashMap::new();
let stdout = String::from_utf8_lossy(&output.stdout);
if !output.status.success() {
return Ok(versions);
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct ListOutput {
#[serde(default)]
dependencies: HashMap<String, ListDependency>,
#[serde(default)]
dev_dependencies: HashMap<String, ListDependency>,
}
#[derive(Deserialize)]
struct ListDependency {
version: String,
}
let json = if matches!(self, PackageManager::Pnpm) {
serde_json::from_str::<Vec<ListOutput>>(&stdout)
.ok()
.and_then(|out| out.into_iter().next())
.context("failed to parse pnpm list")?
} else {
serde_json::from_str::<ListOutput>(&stdout).context("failed to parse npm list")?
};
for (package, dependency) in json.dependencies.into_iter().chain(json.dev_dependencies) {
let version = dependency.version;
if let Ok(version) = semver::Version::parse(&version) {
versions.insert(package, version);
} else {
log::debug!("Failed to parse version `{version}` for NPM package `{package}`");
}
}
Ok(versions)
}
}
fn yarn_package_versions(
packages: &[String],
frontend_dir: &Path,
) -> crate::Result<HashMap<String, semver::Version>> {
let output = cross_command("yarn")
.arg("list")
.args(packages)
.args(["--json", "--depth", "0"])
.current_dir(frontend_dir)
.output()
.map_err(|error| Error::CommandFailed {
command: "yarn list --json --depth 0".to_string(),
error,
})?;
let mut versions = HashMap::new();
let stdout = String::from_utf8_lossy(&output.stdout);
if !output.status.success() {
return Ok(versions);
}
#[derive(Deserialize)]
struct YarnListOutput {
data: YarnListOutputData,
}
#[derive(Deserialize)]
struct YarnListOutputData {
trees: Vec<YarnListOutputDataTree>,
}
#[derive(Deserialize)]
struct YarnListOutputDataTree {
name: String,
}
for line in stdout.lines() {
if let Ok(tree) = serde_json::from_str::<YarnListOutput>(line) {
for tree in tree.data.trees {
let Some((name, version)) = tree.name.rsplit_once('@') else {
continue;
};
if let Ok(version) = semver::Version::parse(version) {
versions.insert(name.to_owned(), version);
} else {
log::debug!("Failed to parse version `{version}` for NPM package `{name}`");
}
}
return Ok(versions);
}
}
Ok(versions)
}
fn yarn_berry_package_versions(
packages: &[String],
frontend_dir: &Path,
) -> crate::Result<HashMap<String, semver::Version>> {
let output = cross_command("yarn")
.args(["info", "--json"])
.current_dir(frontend_dir)
.output()
.map_err(|error| Error::CommandFailed {
command: "yarn info --json".to_string(),
error,
})?;
let mut versions = HashMap::new();
let stdout = String::from_utf8_lossy(&output.stdout);
if !output.status.success() {
return Ok(versions);
}
#[derive(Deserialize)]
struct YarnBerryInfoOutput {
value: String,
children: YarnBerryInfoOutputChildren,
}
#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
struct YarnBerryInfoOutputChildren {
version: String,
}
for line in stdout.lines() {
if let Ok(info) = serde_json::from_str::<YarnBerryInfoOutput>(line) {
let Some((name, _)) = info.value.rsplit_once('@') else {
continue;
};
if !packages.iter().any(|package| package == name) {
continue;
}
let version = info.children.version;
if let Ok(version) = semver::Version::parse(&version) {
versions.insert(name.to_owned(), version);
} else {
log::debug!("Failed to parse version `{version}` for NPM package `{name}`");
}
}
}
Ok(versions)
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/interface/rust.rs | crates/tauri-cli/src/interface/rust.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{
collections::HashMap,
ffi::OsStr,
fs::FileType,
io::{BufRead, Write},
path::{Path, PathBuf},
process::Command,
str::FromStr,
sync::{mpsc::sync_channel, Arc, Mutex},
time::Duration,
};
use dunce::canonicalize;
use glob::glob;
use ignore::gitignore::{Gitignore, GitignoreBuilder};
use notify::RecursiveMode;
use notify_debouncer_full::new_debouncer;
use serde::{Deserialize, Deserializer};
use tauri_bundler::{
AppCategory, AppImageSettings, BundleBinary, BundleSettings, DebianSettings, DmgSettings,
IosSettings, MacOsSettings, PackageSettings, Position, RpmSettings, Size, UpdaterSettings,
WindowsSettings,
};
use tauri_utils::config::{parse::is_configuration_file, DeepLinkProtocol, RunnerConfig, Updater};
use super::{AppSettings, DevProcess, ExitReason, Interface};
use crate::{
error::{Context, Error, ErrorExt},
helpers::{
app_paths::{frontend_dir, tauri_dir},
config::{nsis_settings, reload as reload_config, wix_settings, BundleResources, Config},
},
ConfigValue,
};
use tauri_utils::{display_path, platform::Target as TargetPlatform};
mod cargo_config;
mod desktop;
pub mod installation;
pub mod manifest;
use crate::helpers::config::custom_sign_settings;
use cargo_config::Config as CargoConfig;
use manifest::{rewrite_manifest, Manifest};
#[derive(Debug, Default, Clone)]
pub struct Options {
pub runner: Option<RunnerConfig>,
pub debug: bool,
pub target: Option<String>,
pub features: Vec<String>,
pub args: Vec<String>,
pub config: Vec<ConfigValue>,
pub no_watch: bool,
pub skip_stapling: bool,
pub additional_watch_folders: Vec<PathBuf>,
}
impl From<crate::build::Options> for Options {
fn from(options: crate::build::Options) -> Self {
Self {
runner: options.runner,
debug: options.debug,
target: options.target,
features: options.features,
args: options.args,
config: options.config,
no_watch: true,
skip_stapling: options.skip_stapling,
additional_watch_folders: Vec::new(),
}
}
}
impl From<crate::bundle::Options> for Options {
fn from(options: crate::bundle::Options) -> Self {
Self {
debug: options.debug,
config: options.config,
target: options.target,
features: options.features,
no_watch: true,
skip_stapling: options.skip_stapling,
..Default::default()
}
}
}
impl From<crate::dev::Options> for Options {
fn from(options: crate::dev::Options) -> Self {
Self {
runner: options.runner,
debug: !options.release_mode,
target: options.target,
features: options.features,
args: options.args,
config: options.config,
no_watch: options.no_watch,
skip_stapling: false,
additional_watch_folders: options.additional_watch_folders,
}
}
}
#[derive(Debug, Clone)]
pub struct MobileOptions {
pub debug: bool,
pub features: Vec<String>,
pub args: Vec<String>,
pub config: Vec<ConfigValue>,
pub no_watch: bool,
pub additional_watch_folders: Vec<PathBuf>,
}
#[derive(Debug, Clone)]
pub struct WatcherOptions {
pub config: Vec<ConfigValue>,
pub additional_watch_folders: Vec<PathBuf>,
}
#[derive(Debug)]
pub struct RustupTarget {
name: String,
installed: bool,
}
pub struct Rust {
app_settings: Arc<RustAppSettings>,
config_features: Vec<String>,
available_targets: Option<Vec<RustupTarget>>,
main_binary_name: Option<String>,
}
impl Interface for Rust {
type AppSettings = RustAppSettings;
fn new(config: &Config, target: Option<String>) -> crate::Result<Self> {
let manifest = {
let (tx, rx) = sync_channel(1);
let mut watcher = new_debouncer(Duration::from_secs(1), None, move |r| {
if let Ok(_events) = r {
let _ = tx.send(());
}
})
.unwrap();
watcher
.watch(tauri_dir().join("Cargo.toml"), RecursiveMode::NonRecursive)
.with_context(|| {
format!(
"failed to watch {}",
tauri_dir().join("Cargo.toml").display()
)
})?;
let (manifest, modified) = rewrite_manifest(config)?;
if modified {
// Wait for the modified event so we don't trigger a re-build later on
let _ = rx.recv_timeout(Duration::from_secs(2));
}
manifest
};
let target_ios = target
.as_ref()
.is_some_and(|target| target.ends_with("ios") || target.ends_with("ios-sim"));
if target_ios {
std::env::set_var(
"IPHONEOS_DEPLOYMENT_TARGET",
&config.bundle.ios.minimum_system_version,
);
}
let app_settings = RustAppSettings::new(config, manifest, target)?;
Ok(Self {
app_settings: Arc::new(app_settings),
config_features: config.build.features.clone().unwrap_or_default(),
main_binary_name: config.main_binary_name.clone(),
available_targets: None,
})
}
fn app_settings(&self) -> Arc<Self::AppSettings> {
self.app_settings.clone()
}
fn build(&mut self, options: Options) -> crate::Result<PathBuf> {
desktop::build(
options,
&self.app_settings,
&mut self.available_targets,
self.config_features.clone(),
self.main_binary_name.as_deref(),
)
}
fn dev<F: Fn(Option<i32>, ExitReason) + Send + Sync + 'static>(
&mut self,
mut options: Options,
on_exit: F,
) -> crate::Result<()> {
let on_exit = Arc::new(on_exit);
let mut run_args = Vec::new();
dev_options(
false,
&mut options.args,
&mut run_args,
&mut options.features,
&self.app_settings,
);
if options.no_watch {
let (tx, rx) = sync_channel(1);
self.run_dev(options, run_args, move |status, reason| {
on_exit(status, reason);
tx.send(()).unwrap();
})?;
rx.recv().unwrap();
Ok(())
} else {
let merge_configs = options.config.iter().map(|c| &c.0).collect::<Vec<_>>();
let run = Arc::new(|rust: &mut Rust| {
let on_exit = on_exit.clone();
rust.run_dev(options.clone(), run_args.clone(), move |status, reason| {
on_exit(status, reason)
})
});
self.run_dev_watcher(&options.additional_watch_folders, &merge_configs, run)
}
}
fn mobile_dev<R: Fn(MobileOptions) -> crate::Result<Box<dyn DevProcess + Send>>>(
&mut self,
mut options: MobileOptions,
runner: R,
) -> crate::Result<()> {
let mut run_args = Vec::new();
dev_options(
true,
&mut options.args,
&mut run_args,
&mut options.features,
&self.app_settings,
);
if options.no_watch {
runner(options)?;
Ok(())
} else {
self.watch(
WatcherOptions {
config: options.config.clone(),
additional_watch_folders: options.additional_watch_folders.clone(),
},
move || runner(options.clone()),
)
}
}
fn watch<R: Fn() -> crate::Result<Box<dyn DevProcess + Send>>>(
&mut self,
options: WatcherOptions,
runner: R,
) -> crate::Result<()> {
let merge_configs = options.config.iter().map(|c| &c.0).collect::<Vec<_>>();
let run = Arc::new(|_rust: &mut Rust| runner());
self.run_dev_watcher(&options.additional_watch_folders, &merge_configs, run)
}
fn env(&self) -> HashMap<&str, String> {
let mut env = HashMap::new();
env.insert(
"TAURI_ENV_TARGET_TRIPLE",
self.app_settings.target_triple.clone(),
);
let target_triple = &self.app_settings.target_triple;
let target_components: Vec<&str> = target_triple.split('-').collect();
let (arch, host, _host_env) = match target_components.as_slice() {
// 3 components like aarch64-apple-darwin
[arch, _, host] => (*arch, *host, None),
// 4 components like x86_64-pc-windows-msvc and aarch64-apple-ios-sim
[arch, _, host, host_env] => (*arch, *host, Some(*host_env)),
_ => {
log::warn!("Invalid target triple: {}", target_triple);
return env;
}
};
env.insert("TAURI_ENV_ARCH", arch.into());
env.insert("TAURI_ENV_PLATFORM", host.into());
env.insert(
"TAURI_ENV_FAMILY",
match host {
"windows" => "windows".into(),
_ => "unix".into(),
},
);
env
}
}
struct IgnoreMatcher(Vec<Gitignore>);
impl IgnoreMatcher {
fn is_ignore(&self, path: &Path, is_dir: bool) -> bool {
for gitignore in &self.0 {
if path.starts_with(gitignore.path())
&& gitignore
.matched_path_or_any_parents(path, is_dir)
.is_ignore()
{
return true;
}
}
false
}
}
fn build_ignore_matcher(dir: &Path) -> IgnoreMatcher {
let mut matchers = Vec::new();
// ignore crate doesn't expose an API to build `ignore::gitignore::GitIgnore`
// with custom ignore file names so we have to walk the directory and collect
// our custom ignore files and add it using `ignore::gitignore::GitIgnoreBuilder::add`
for entry in ignore::WalkBuilder::new(dir)
.require_git(false)
.ignore(false)
.overrides(
ignore::overrides::OverrideBuilder::new(dir)
.add(".taurignore")
.unwrap()
.build()
.unwrap(),
)
.build()
.flatten()
{
let path = entry.path();
if path.file_name() == Some(OsStr::new(".taurignore")) {
let mut ignore_builder = GitignoreBuilder::new(path.parent().unwrap());
ignore_builder.add(path);
if let Ok(ignore_file) = std::env::var("TAURI_CLI_WATCHER_IGNORE_FILENAME") {
ignore_builder.add(dir.join(ignore_file));
}
for line in crate::dev::TAURI_CLI_BUILTIN_WATCHER_IGNORE_FILE
.lines()
.map_while(Result::ok)
{
let _ = ignore_builder.add_line(None, &line);
}
matchers.push(ignore_builder.build().unwrap());
}
}
IgnoreMatcher(matchers)
}
fn lookup<F: FnMut(FileType, PathBuf)>(dir: &Path, mut f: F) {
let mut default_gitignore = std::env::temp_dir();
default_gitignore.push(".tauri");
let _ = std::fs::create_dir_all(&default_gitignore);
default_gitignore.push(".gitignore");
if !default_gitignore.exists() {
if let Ok(mut file) = std::fs::File::create(default_gitignore.clone()) {
let _ = file.write_all(crate::dev::TAURI_CLI_BUILTIN_WATCHER_IGNORE_FILE);
}
}
let mut builder = ignore::WalkBuilder::new(dir);
builder.add_custom_ignore_filename(".taurignore");
let _ = builder.add_ignore(default_gitignore);
if let Ok(ignore_file) = std::env::var("TAURI_CLI_WATCHER_IGNORE_FILENAME") {
builder.add_ignore(ignore_file);
}
builder.require_git(false).ignore(false).max_depth(Some(1));
for entry in builder.build().flatten() {
f(entry.file_type().unwrap(), dir.join(entry.path()));
}
}
fn dev_options(
mobile: bool,
args: &mut Vec<String>,
run_args: &mut Vec<String>,
features: &mut Vec<String>,
app_settings: &RustAppSettings,
) {
let mut dev_args = Vec::new();
let mut reached_run_args = false;
for arg in args.clone() {
if reached_run_args {
run_args.push(arg);
} else if arg == "--" {
reached_run_args = true;
} else {
dev_args.push(arg);
}
}
*args = dev_args;
if mobile {
args.push("--lib".into());
}
if !args.contains(&"--no-default-features".into()) {
let manifest_features = app_settings.manifest.lock().unwrap().features();
let enable_features: Vec<String> = manifest_features
.get("default")
.cloned()
.unwrap_or_default()
.into_iter()
.filter(|feature| {
if let Some(manifest_feature) = manifest_features.get(feature) {
!manifest_feature.contains(&"tauri/custom-protocol".into())
} else {
feature != "tauri/custom-protocol"
}
})
.collect();
args.push("--no-default-features".into());
features.extend(enable_features);
}
}
// Copied from https://github.com/rust-lang/cargo/blob/69255bb10de7f74511b5cef900a9d102247b6029/src/cargo/core/workspace.rs#L665
fn expand_member_path(path: &Path) -> crate::Result<Vec<PathBuf>> {
let path = path.to_str().context("path is not UTF-8 compatible")?;
let res = glob(path).with_context(|| format!("failed to expand glob pattern for {path}"))?;
let res = res
.map(|p| p.with_context(|| format!("failed to expand glob pattern for {path}")))
.collect::<Result<Vec<_>, _>>()?;
Ok(res)
}
fn get_watch_folders(additional_watch_folders: &[PathBuf]) -> crate::Result<Vec<PathBuf>> {
let tauri_path = tauri_dir();
let workspace_path = get_workspace_dir()?;
// We always want to watch the main tauri folder.
let mut watch_folders = vec![tauri_path.to_path_buf()];
// Add the additional watch folders, resolving the path from the tauri path if it is relative
watch_folders.extend(additional_watch_folders.iter().filter_map(|dir| {
let path = if dir.is_absolute() {
dir.to_owned()
} else {
tauri_path.join(dir)
};
let canonicalized = canonicalize(&path).ok();
if canonicalized.is_none() {
log::warn!(
"Additional watch folder '{}' not found, ignoring",
path.display()
);
}
canonicalized
}));
// We also try to watch workspace members, no matter if the tauri cargo project is the workspace root or a workspace member
let cargo_settings = CargoSettings::load(&workspace_path)?;
if let Some(members) = cargo_settings.workspace.and_then(|w| w.members) {
for p in members {
let p = workspace_path.join(p);
match expand_member_path(&p) {
// Sometimes expand_member_path returns an empty vec, for example if the path contains `[]` as in `C:/[abc]/project/`.
// Cargo won't complain unless theres a workspace.members config with glob patterns so we should support it too.
Ok(expanded_paths) => {
if expanded_paths.is_empty() {
watch_folders.push(p);
} else {
watch_folders.extend(expanded_paths);
}
}
Err(err) => {
// If this fails cargo itself should fail too. But we still try to keep going with the unexpanded path.
log::error!("Error watching {}: {}", p.display(), err);
watch_folders.push(p);
}
};
}
}
Ok(watch_folders)
}
impl Rust {
pub fn build_options(&self, args: &mut Vec<String>, features: &mut Vec<String>, mobile: bool) {
features.push("tauri/custom-protocol".into());
if mobile {
args.push("--lib".into());
} else {
args.push("--bins".into());
}
}
fn run_dev<F: Fn(Option<i32>, ExitReason) + Send + Sync + 'static>(
&mut self,
options: Options,
run_args: Vec<String>,
on_exit: F,
) -> crate::Result<Box<dyn DevProcess + Send>> {
desktop::run_dev(
options,
run_args,
&mut self.available_targets,
self.config_features.clone(),
on_exit,
)
.map(|c| Box::new(c) as Box<dyn DevProcess + Send>)
}
fn run_dev_watcher<F: Fn(&mut Rust) -> crate::Result<Box<dyn DevProcess + Send>>>(
&mut self,
additional_watch_folders: &[PathBuf],
merge_configs: &[&serde_json::Value],
run: Arc<F>,
) -> crate::Result<()> {
let child = run(self)?;
let process = Arc::new(Mutex::new(child));
let (tx, rx) = sync_channel(1);
let frontend_path = frontend_dir();
let watch_folders = get_watch_folders(additional_watch_folders)?;
let common_ancestor = common_path::common_path_all(watch_folders.iter().map(Path::new))
.expect("watch_folders should not be empty");
let ignore_matcher = build_ignore_matcher(&common_ancestor);
let mut watcher = new_debouncer(Duration::from_secs(1), None, move |r| {
if let Ok(events) = r {
tx.send(events).unwrap()
}
})
.unwrap();
for path in watch_folders {
if !ignore_matcher.is_ignore(&path, true) {
log::info!("Watching {} for changes...", display_path(&path));
lookup(&path, |file_type, p| {
if p != path {
log::debug!("Watching {} for changes...", display_path(&p));
let _ = watcher.watch(
&p,
if file_type.is_dir() {
RecursiveMode::Recursive
} else {
RecursiveMode::NonRecursive
},
);
}
});
}
}
loop {
if let Ok(events) = rx.recv() {
for event in events {
if event.kind.is_access() {
continue;
}
if let Some(event_path) = event.paths.first() {
if !ignore_matcher.is_ignore(event_path, event_path.is_dir()) {
if is_configuration_file(self.app_settings.target_platform, event_path) {
if let Ok(config) = reload_config(merge_configs) {
let (manifest, modified) =
rewrite_manifest(config.lock().unwrap().as_ref().unwrap())?;
if modified {
*self.app_settings.manifest.lock().unwrap() = manifest;
// no need to run the watcher logic, the manifest was modified
// and it will trigger the watcher again
continue;
}
}
}
log::info!(
"File {} changed. Rebuilding application...",
display_path(event_path.strip_prefix(frontend_path).unwrap_or(event_path))
);
let mut p = process.lock().unwrap();
p.kill().context("failed to kill app process")?;
// wait for the process to exit
// note that on mobile, kill() already waits for the process to exit (duct implementation)
loop {
if !matches!(p.try_wait(), Ok(None)) {
break;
}
}
*p = run(self)?;
}
}
}
}
}
}
}
// Taken from https://github.com/rust-lang/cargo/blob/70898e522116f6c23971e2a554b2dc85fd4c84cd/src/cargo/util/toml/mod.rs#L1008-L1065
/// Enum that allows for the parsing of `field.workspace = true` in a Cargo.toml
///
/// It allows for things to be inherited from a workspace or defined as needed
#[derive(Clone, Debug)]
pub enum MaybeWorkspace<T> {
Workspace(TomlWorkspaceField),
Defined(T),
}
impl<'de, T: Deserialize<'de>> serde::de::Deserialize<'de> for MaybeWorkspace<T> {
fn deserialize<D>(deserializer: D) -> Result<MaybeWorkspace<T>, D::Error>
where
D: serde::de::Deserializer<'de>,
{
let value = serde_value::Value::deserialize(deserializer)?;
if let Ok(workspace) = TomlWorkspaceField::deserialize(
serde_value::ValueDeserializer::<D::Error>::new(value.clone()),
) {
return Ok(MaybeWorkspace::Workspace(workspace));
}
T::deserialize(serde_value::ValueDeserializer::<D::Error>::new(value))
.map(MaybeWorkspace::Defined)
}
}
impl<T> MaybeWorkspace<T> {
fn resolve(
self,
label: &str,
get_ws_field: impl FnOnce() -> crate::Result<T>,
) -> crate::Result<T> {
match self {
MaybeWorkspace::Defined(value) => Ok(value),
MaybeWorkspace::Workspace(TomlWorkspaceField { workspace: true }) => get_ws_field()
.with_context(|| {
format!(
"error inheriting `{label}` from workspace root manifest's `workspace.package.{label}`"
)
}),
MaybeWorkspace::Workspace(TomlWorkspaceField { workspace: false }) => Err(
crate::Error::GenericError("`workspace=false` is unsupported for `package.{label}`".into()),
),
}
}
fn _as_defined(&self) -> Option<&T> {
match self {
MaybeWorkspace::Workspace(_) => None,
MaybeWorkspace::Defined(defined) => Some(defined),
}
}
}
#[derive(Deserialize, Clone, Debug)]
pub struct TomlWorkspaceField {
workspace: bool,
}
/// The `workspace` section of the app configuration (read from Cargo.toml).
#[derive(Clone, Debug, Deserialize)]
struct WorkspaceSettings {
/// the workspace members.
members: Option<Vec<String>>,
package: Option<WorkspacePackageSettings>,
}
#[derive(Clone, Debug, Deserialize)]
struct WorkspacePackageSettings {
authors: Option<Vec<String>>,
description: Option<String>,
homepage: Option<String>,
version: Option<String>,
license: Option<String>,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "kebab-case")]
struct BinarySettings {
name: String,
/// This is from nightly: https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#different-binary-name
filename: Option<String>,
path: Option<String>,
required_features: Option<Vec<String>>,
}
impl BinarySettings {
/// The file name without the binary extension (e.g. `.exe`)
pub fn file_name(&self) -> &str {
self.filename.as_ref().unwrap_or(&self.name)
}
}
/// The package settings.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct CargoPackageSettings {
/// the package's name.
pub name: String,
/// the package's version.
pub version: Option<MaybeWorkspace<String>>,
/// the package's description.
pub description: Option<MaybeWorkspace<String>>,
/// the package's homepage.
pub homepage: Option<MaybeWorkspace<String>>,
/// the package's authors.
pub authors: Option<MaybeWorkspace<Vec<String>>>,
/// the package's license.
pub license: Option<MaybeWorkspace<String>>,
/// the default binary to run.
pub default_run: Option<String>,
}
/// The Cargo settings (Cargo.toml root descriptor).
#[derive(Clone, Debug, Deserialize)]
struct CargoSettings {
/// the package settings.
///
/// it's optional because ancestor workspace Cargo.toml files may not have package info.
package: Option<CargoPackageSettings>,
/// the workspace settings.
///
/// it's present if the read Cargo.toml belongs to a workspace root.
workspace: Option<WorkspaceSettings>,
/// the binary targets configuration.
bin: Option<Vec<BinarySettings>>,
}
impl CargoSettings {
/// Try to load a set of CargoSettings from a "Cargo.toml" file in the specified directory.
fn load(dir: &Path) -> crate::Result<Self> {
let toml_path = dir.join("Cargo.toml");
let toml_str = std::fs::read_to_string(&toml_path)
.fs_context("Failed to read Cargo manifest", toml_path.clone())?;
toml::from_str(&toml_str).context(format!(
"failed to parse Cargo manifest at {}",
toml_path.display()
))
}
}
pub struct RustAppSettings {
manifest: Mutex<Manifest>,
cargo_settings: CargoSettings,
cargo_package_settings: CargoPackageSettings,
cargo_ws_package_settings: Option<WorkspacePackageSettings>,
package_settings: PackageSettings,
cargo_config: CargoConfig,
target_triple: String,
target_platform: TargetPlatform,
}
#[derive(Deserialize)]
#[serde(untagged)]
enum DesktopDeepLinks {
One(DeepLinkProtocol),
List(Vec<DeepLinkProtocol>),
}
#[derive(Deserialize)]
pub struct UpdaterConfig {
/// Signature public key.
pub pubkey: String,
/// The Windows configuration for the updater.
#[serde(default)]
pub windows: UpdaterWindowsConfig,
}
/// Install modes for the Windows update.
#[derive(Default, Debug, PartialEq, Eq, Clone)]
pub enum WindowsUpdateInstallMode {
/// Specifies there's a basic UI during the installation process, including a final dialog box at the end.
BasicUi,
/// The quiet mode means there's no user interaction required.
/// Requires admin privileges if the installer does.
Quiet,
/// Specifies unattended mode, which means the installation only shows a progress bar.
#[default]
Passive,
// to add more modes, we need to check if the updater relaunch makes sense
// i.e. for a full UI mode, the user can also mark the installer to start the app
}
impl<'de> Deserialize<'de> for WindowsUpdateInstallMode {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
match s.to_lowercase().as_str() {
"basicui" => Ok(Self::BasicUi),
"quiet" => Ok(Self::Quiet),
"passive" => Ok(Self::Passive),
_ => Err(serde::de::Error::custom(format!(
"unknown update install mode '{s}'"
))),
}
}
}
impl WindowsUpdateInstallMode {
/// Returns the associated `msiexec.exe` arguments.
pub fn msiexec_args(&self) -> &'static [&'static str] {
match self {
Self::BasicUi => &["/qb+"],
Self::Quiet => &["/quiet"],
Self::Passive => &["/passive"],
}
}
}
#[derive(Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdaterWindowsConfig {
#[serde(default, alias = "install-mode")]
pub install_mode: WindowsUpdateInstallMode,
}
impl AppSettings for RustAppSettings {
fn get_package_settings(&self) -> PackageSettings {
self.package_settings.clone()
}
fn get_bundle_settings(
&self,
options: &Options,
config: &Config,
features: &[String],
) -> crate::Result<BundleSettings> {
let arch64bits = self.target_triple.starts_with("x86_64")
|| self.target_triple.starts_with("aarch64")
|| self.target_triple.starts_with("riscv64");
let updater_enabled = config.bundle.create_updater_artifacts != Updater::Bool(false);
let v1_compatible = matches!(config.bundle.create_updater_artifacts, Updater::String(_));
let updater_settings = if updater_enabled {
let updater: UpdaterConfig = serde_json::from_value(
config
.plugins
.0
.get("updater")
.context("failed to get updater configuration: plugins > updater doesn't exist")?
.clone(),
)
.context("failed to parse updater plugin configuration")?;
Some(UpdaterSettings {
v1_compatible,
pubkey: updater.pubkey,
msiexec_args: updater.windows.install_mode.msiexec_args(),
})
} else {
None
};
let mut settings = tauri_config_to_bundle_settings(
self,
features,
config,
config.bundle.clone(),
updater_settings,
arch64bits,
)?;
settings.macos.skip_stapling = options.skip_stapling;
if let Some(plugin_config) = config
.plugins
.0
.get("deep-link")
.and_then(|c| c.get("desktop").cloned())
{
let protocols: DesktopDeepLinks =
serde_json::from_value(plugin_config).context("failed to parse desktop deep links from Tauri configuration > plugins > deep-link > desktop")?;
settings.deep_link_protocols = Some(match protocols {
DesktopDeepLinks::One(p) => vec![p],
DesktopDeepLinks::List(p) => p,
});
}
if let Some(open) = config.plugins.0.get("shell").and_then(|v| v.get("open")) {
if open.as_bool().is_some_and(|x| x) || open.is_string() {
settings.appimage.bundle_xdg_open = true;
}
}
if let Some(deps) = self
.manifest
.lock()
.unwrap()
.inner
.as_table()
.get("dependencies")
.and_then(|f| f.as_table())
{
if deps.contains_key("tauri-plugin-opener") {
settings.appimage.bundle_xdg_open = true;
};
}
Ok(settings)
}
fn app_binary_path(&self, options: &Options) -> crate::Result<PathBuf> {
let binaries = self.get_binaries(options)?;
let bin_name = binaries
.iter()
.find(|x| x.main())
.context("failed to find main binary, make sure you have a `package > default-run` in the Cargo.toml file")?
.name();
let out_dir = self
.out_dir(options)
.context("failed to get project out directory")?;
let mut path = out_dir.join(bin_name);
if matches!(self.target_platform, TargetPlatform::Windows) {
// Append the `.exe` extension without overriding the existing extensions
let extension = if let Some(extension) = path.extension() {
let mut extension = extension.to_os_string();
extension.push(".exe");
extension
} else {
"exe".into()
};
path.set_extension(extension);
};
Ok(path)
}
fn get_binaries(&self, options: &Options) -> crate::Result<Vec<BundleBinary>> {
let mut binaries = Vec::new();
if let Some(bins) = &self.cargo_settings.bin {
let default_run = self
.package_settings
.default_run
.clone()
.unwrap_or_default();
for bin in bins {
if let Some(req_features) = &bin.required_features {
// Check if all required features are enabled.
if !req_features
.iter()
.all(|feat| options.features.contains(feat))
{
continue;
}
}
let file_name = bin.file_name();
let is_main = file_name == self.cargo_package_settings.name || file_name == default_run;
binaries.push(BundleBinary::with_path(
file_name.to_owned(),
is_main,
bin.path.clone(),
))
}
}
let tauri_dir = tauri_dir();
let mut binaries_paths = std::fs::read_dir(tauri_dir.join("src/bin"))
.map(|dir| {
dir
.into_iter()
.flatten()
.map(|entry| {
(
entry
.path()
.file_stem()
.unwrap_or_default()
.to_string_lossy()
.into_owned(),
entry.path(),
)
})
.collect::<Vec<_>>()
})
.unwrap_or_default();
if !binaries_paths
.iter()
.any(|(_name, path)| path == Path::new("src/main.rs"))
&& tauri_dir.join("src/main.rs").exists()
{
binaries_paths.push((
self.cargo_package_settings.name.clone(),
tauri_dir.join("src/main.rs"),
));
}
for (name, path) in binaries_paths {
// see https://github.com/tauri-apps/tauri/pull/10977#discussion_r1759742414
let bin_exists = binaries
.iter()
.any(|bin| bin.name() == name || path.ends_with(bin.src_path().unwrap_or(&"".to_string())));
if !bin_exists {
binaries.push(BundleBinary::new(name, false))
}
}
if let Some(default_run) = self.package_settings.default_run.as_ref() {
if let Some(binary) = binaries.iter_mut().find(|bin| bin.name() == default_run) {
binary.set_main(true);
} else {
binaries.push(BundleBinary::new(default_run.clone(), true));
}
}
match binaries.len() {
0 => binaries.push(BundleBinary::new(
self.cargo_package_settings.name.clone(),
true,
)),
1 => binaries.get_mut(0).unwrap().set_main(true),
_ => {}
}
Ok(binaries)
}
fn app_name(&self) -> Option<String> {
self
.manifest
.lock()
.unwrap()
.inner
.as_table()
.get("package")?
.as_table()?
.get("name")?
.as_str()
.map(|n| n.to_string())
}
fn lib_name(&self) -> Option<String> {
self
.manifest
.lock()
.unwrap()
.inner
.as_table()
.get("lib")?
.as_table()?
.get("name")?
.as_str()
.map(|n| n.to_string())
}
}
impl RustAppSettings {
pub fn new(config: &Config, manifest: Manifest, target: Option<String>) -> crate::Result<Self> {
let tauri_dir = tauri_dir();
let cargo_settings = CargoSettings::load(tauri_dir).context("failed to load Cargo settings")?;
let cargo_package_settings = match &cargo_settings.package {
Some(package_info) => package_info.clone(),
None => {
return Err(crate::Error::GenericError(
"No package info in the config file".to_owned(),
))
}
};
let ws_package_settings = CargoSettings::load(&get_workspace_dir()?)
.context("failed to load Cargo settings from workspace root")?
.workspace
.and_then(|v| v.package);
let version = config.version.clone().unwrap_or_else(|| {
cargo_package_settings
.version
.clone()
.expect("Cargo manifest must have the `package.version` field")
.resolve("version", || {
ws_package_settings
.as_ref()
.and_then(|p| p.version.clone())
.context("Couldn't inherit value for `version` from workspace")
})
.expect("Cargo project does not have a version")
});
let package_settings = PackageSettings {
product_name: config
.product_name
.clone()
.unwrap_or_else(|| cargo_package_settings.name.clone()),
version,
description: cargo_package_settings
.description
.clone()
.map(|description| {
description
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | true |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/interface/mod.rs | crates/tauri-cli/src/interface/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
pub mod rust;
use std::{
collections::HashMap,
path::{Path, PathBuf},
process::ExitStatus,
sync::Arc,
};
use crate::{error::Context, helpers::config::Config};
use tauri_bundler::bundle::{PackageType, Settings, SettingsBuilder};
pub use rust::{MobileOptions, Options, Rust as AppInterface, WatcherOptions};
pub trait DevProcess {
fn kill(&self) -> std::io::Result<()>;
fn try_wait(&self) -> std::io::Result<Option<ExitStatus>>;
#[allow(unused)]
fn wait(&self) -> std::io::Result<ExitStatus>;
#[allow(unused)]
fn manually_killed_process(&self) -> bool;
}
pub trait AppSettings {
fn get_package_settings(&self) -> tauri_bundler::PackageSettings;
fn get_bundle_settings(
&self,
options: &Options,
config: &Config,
features: &[String],
) -> crate::Result<tauri_bundler::BundleSettings>;
fn app_binary_path(&self, options: &Options) -> crate::Result<PathBuf>;
fn get_binaries(&self, options: &Options) -> crate::Result<Vec<tauri_bundler::BundleBinary>>;
fn app_name(&self) -> Option<String>;
fn lib_name(&self) -> Option<String>;
fn get_bundler_settings(
&self,
options: Options,
config: &Config,
out_dir: &Path,
package_types: Vec<PackageType>,
) -> crate::Result<Settings> {
let no_default_features = options.args.contains(&"--no-default-features".into());
let mut enabled_features = options.features.clone();
if !no_default_features {
enabled_features.push("default".into());
}
let target: String = if let Some(target) = options.target.clone() {
target
} else {
tauri_utils::platform::target_triple().context("failed to get target triple")?
};
let mut bins = self.get_binaries(&options)?;
if let Some(main_binary_name) = &config.main_binary_name {
let main = bins.iter_mut().find(|b| b.main()).context("no main bin?")?;
main.set_name(main_binary_name.to_owned());
}
let mut settings_builder = SettingsBuilder::new()
.package_settings(self.get_package_settings())
.bundle_settings(self.get_bundle_settings(&options, config, &enabled_features)?)
.binaries(bins)
.project_out_directory(out_dir)
.target(target)
.package_types(package_types);
if config.bundle.use_local_tools_dir {
settings_builder = settings_builder.local_tools_directory(
rust::get_cargo_metadata()
.context("failed to get cargo metadata")?
.target_directory,
)
}
settings_builder
.build()
.map_err(Box::new)
.map_err(Into::into)
}
}
#[derive(Debug)]
pub enum ExitReason {
/// Killed manually.
TriggeredKill,
/// App compilation failed.
CompilationFailed,
/// Regular exit.
NormalExit,
}
pub trait Interface: Sized {
type AppSettings: AppSettings;
fn new(config: &Config, target: Option<String>) -> crate::Result<Self>;
fn app_settings(&self) -> Arc<Self::AppSettings>;
fn env(&self) -> HashMap<&str, String>;
fn build(&mut self, options: Options) -> crate::Result<PathBuf>;
fn dev<F: Fn(Option<i32>, ExitReason) + Send + Sync + 'static>(
&mut self,
options: Options,
on_exit: F,
) -> crate::Result<()>;
fn mobile_dev<R: Fn(MobileOptions) -> crate::Result<Box<dyn DevProcess + Send>>>(
&mut self,
options: MobileOptions,
runner: R,
) -> crate::Result<()>;
fn watch<R: Fn() -> crate::Result<Box<dyn DevProcess + Send>>>(
&mut self,
options: WatcherOptions,
runner: R,
) -> crate::Result<()>;
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/interface/rust/manifest.rs | crates/tauri-cli/src/interface/rust/manifest.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{
error::{Context, ErrorExt},
helpers::{
app_paths::tauri_dir,
config::{Config, PatternKind},
},
};
use itertools::Itertools;
use toml_edit::{Array, DocumentMut, InlineTable, Item, TableLike, Value};
use std::{
collections::{HashMap, HashSet},
path::Path,
};
#[derive(Default)]
pub struct Manifest {
pub inner: DocumentMut,
pub tauri_features: HashSet<String>,
}
impl Manifest {
pub fn features(&self) -> HashMap<String, Vec<String>> {
let mut f = HashMap::new();
if let Some(features) = self
.inner
.as_table()
.get("features")
.and_then(|f| f.as_table())
{
for (feature, enabled_features) in features.into_iter() {
if let Item::Value(Value::Array(enabled_features)) = enabled_features {
let mut enabled = Vec::new();
for value in enabled_features {
if let Value::String(s) = value {
enabled.push(s.value().clone());
}
}
f.insert(feature.to_string(), enabled);
}
}
}
f
}
pub fn all_enabled_features(&self, enabled_features: &[String]) -> Vec<String> {
let mut all_enabled_features: Vec<String> = self
.tauri_features
.iter()
.map(|f| format!("tauri/{f}"))
.collect();
let manifest_features = self.features();
for f in enabled_features {
all_enabled_features.extend(get_enabled_features(&manifest_features, f));
}
all_enabled_features
}
}
fn get_enabled_features(list: &HashMap<String, Vec<String>>, feature: &str) -> Vec<String> {
let mut f = Vec::new();
if let Some(enabled_features) = list.get(feature) {
for enabled in enabled_features {
if list.contains_key(enabled) {
f.extend(get_enabled_features(list, enabled));
} else {
f.push(enabled.clone());
}
}
}
f
}
pub fn read_manifest(manifest_path: &Path) -> crate::Result<(DocumentMut, String)> {
let manifest_str = std::fs::read_to_string(manifest_path)
.fs_context("failed to read Cargo.toml", manifest_path.to_path_buf())?;
let manifest: DocumentMut = manifest_str
.parse::<DocumentMut>()
.context("failed to parse Cargo.toml")?;
Ok((manifest, manifest_str))
}
pub fn serialize_manifest(manifest: &DocumentMut) -> String {
manifest
.to_string()
// apply some formatting fixes
.replace(r#"" ,features =["#, r#"", features = ["#)
.replace(r#"" , features"#, r#"", features"#)
.replace("]}", "] }")
.replace("={", "= {")
.replace("=[", "= [")
.replace(r#"",""#, r#"", ""#)
}
pub fn toml_array(features: &HashSet<String>) -> Array {
let mut f = Array::default();
let mut features: Vec<String> = features.iter().map(|f| f.to_string()).collect();
features.sort();
for feature in features {
f.push(feature.as_str());
}
f
}
fn find_dependency<'a>(
manifest: &'a mut DocumentMut,
name: &'a str,
kind: DependencyKind,
) -> Vec<&'a mut Item> {
let table = match kind {
DependencyKind::Build => "build-dependencies",
DependencyKind::Normal => "dependencies",
};
let m = manifest.as_table_mut();
for (k, v) in m.iter_mut() {
if let Some(t) = v.as_table_mut() {
if k == table {
if let Some(item) = t.get_mut(name) {
return vec![item];
}
} else if k == "target" {
let mut matching_deps = Vec::new();
for (_, target_value) in t.iter_mut() {
if let Some(target_table) = target_value.as_table_mut() {
if let Some(deps) = target_table.get_mut(table) {
if let Some(item) = deps.as_table_mut().and_then(|t| t.get_mut(name)) {
matching_deps.push(item);
}
}
}
}
return matching_deps;
}
}
}
Vec::new()
}
fn write_features<F: Fn(&str) -> bool>(
dependency_name: &str,
item: &mut Item,
is_managed_feature: F,
features: &mut HashSet<String>,
) -> crate::Result<bool> {
if let Some(dep) = item.as_table_mut() {
inject_features_table(dep, is_managed_feature, features);
Ok(true)
} else if let Some(dep) = item.as_value_mut() {
match dep {
Value::InlineTable(table) => {
inject_features_table(table, is_managed_feature, features);
}
Value::String(version) => {
let mut def = InlineTable::default();
def.get_or_insert("version", version.to_string().replace(['\"', ' '], ""));
def.get_or_insert("features", Value::Array(toml_array(features)));
*dep = Value::InlineTable(def);
}
_ => {
crate::error::bail!(
"Unsupported {} dependency format on Cargo.toml",
dependency_name
);
}
}
Ok(true)
} else {
Ok(false)
}
}
#[derive(Debug, Clone, Copy)]
enum DependencyKind {
Build,
Normal,
}
#[derive(Debug)]
struct DependencyAllowlist {
name: String,
kind: DependencyKind,
all_cli_managed_features: Vec<&'static str>,
features: HashSet<String>,
}
fn inject_features_table<D: TableLike, F: Fn(&str) -> bool>(
dep: &mut D,
is_managed_feature: F,
features: &mut HashSet<String>,
) {
let manifest_features = dep.entry("features").or_insert(Item::None);
if let Item::Value(Value::Array(f)) = &manifest_features {
for feat in f.iter() {
if let Value::String(feature) = feat {
if !is_managed_feature(feature.value().as_str()) {
features.insert(feature.value().to_string());
}
}
}
}
if let Some(features_array) = manifest_features.as_array_mut() {
// add features that aren't in the manifest
for feature in features.iter() {
if !features_array.iter().any(|f| f.as_str() == Some(feature)) {
features_array.insert(0, feature.as_str());
}
}
// remove features that shouldn't be in the manifest anymore
let mut i = features_array.len();
while i != 0 {
let index = i - 1;
if let Some(f) = features_array.get(index).and_then(|f| f.as_str()) {
if !features.contains(f) {
features_array.remove(index);
}
}
i -= 1;
}
} else {
*manifest_features = Item::Value(Value::Array(toml_array(features)));
}
}
fn inject_features(
manifest: &mut DocumentMut,
dependencies: &mut Vec<DependencyAllowlist>,
) -> crate::Result<bool> {
let mut persist = false;
for dependency in dependencies {
let name = dependency.name.clone();
let items = find_dependency(manifest, &dependency.name, dependency.kind);
for item in items {
// do not rewrite if dependency uses workspace inheritance
if item
.get("workspace")
.and_then(|v| v.as_bool())
.unwrap_or_default()
{
log::info!("`{name}` dependency has workspace inheritance enabled. The features array won't be automatically rewritten. Expected features: [{}]", dependency.features.iter().join(", "));
} else {
let all_cli_managed_features = dependency.all_cli_managed_features.clone();
let is_managed_feature: Box<dyn Fn(&str) -> bool> =
Box::new(move |feature| all_cli_managed_features.contains(&feature));
let should_write =
write_features(&name, item, is_managed_feature, &mut dependency.features)?;
if !persist {
persist = should_write;
}
}
}
}
Ok(persist)
}
pub fn rewrite_manifest(config: &Config) -> crate::Result<(Manifest, bool)> {
let manifest_path = tauri_dir().join("Cargo.toml");
let (mut manifest, original_manifest_str) = read_manifest(&manifest_path)?;
let mut dependencies = Vec::new();
// tauri-build
let mut tauri_build_features = HashSet::new();
if let PatternKind::Isolation { .. } = config.app.security.pattern {
tauri_build_features.insert("isolation".to_string());
}
dependencies.push(DependencyAllowlist {
name: "tauri-build".into(),
kind: DependencyKind::Build,
all_cli_managed_features: vec!["isolation"],
features: tauri_build_features,
});
// tauri
let tauri_features = HashSet::from_iter(config.app.features().into_iter().map(|f| f.to_string()));
dependencies.push(DependencyAllowlist {
name: "tauri".into(),
kind: DependencyKind::Normal,
all_cli_managed_features: crate::helpers::config::AppConfig::all_features()
.into_iter()
.filter(|f| f != &"tray-icon")
.collect(),
features: tauri_features,
});
let persist = inject_features(&mut manifest, &mut dependencies)?;
let tauri_features = dependencies
.into_iter()
.find(|d| d.name == "tauri")
.unwrap()
.features;
let new_manifest_str = serialize_manifest(&manifest);
if persist && original_manifest_str != new_manifest_str {
std::fs::write(&manifest_path, new_manifest_str)
.fs_context("failed to rewrite Cargo manifest", &manifest_path)?;
Ok((
Manifest {
inner: manifest,
tauri_features,
},
true,
))
} else {
Ok((
Manifest {
inner: manifest,
tauri_features,
},
false,
))
}
}
#[cfg(test)]
mod tests {
use super::{DependencyAllowlist, DependencyKind};
use std::collections::{HashMap, HashSet};
fn inject_features(toml: &str, mut dependencies: Vec<DependencyAllowlist>) {
let mut manifest = toml
.parse::<toml_edit::DocumentMut>()
.expect("invalid toml");
let mut expected = HashMap::new();
for dep in &dependencies {
let mut features = dep.features.clone();
for item in super::find_dependency(&mut manifest, &dep.name, dep.kind) {
let item_table = if let Some(table) = item.as_table() {
Some(table.clone())
} else if let Some(toml_edit::Value::InlineTable(table)) = item.as_value() {
Some(table.clone().into_table())
} else {
None
};
if let Some(f) = item_table
.and_then(|t| t.get("features").cloned())
.and_then(|f| f.as_array().cloned())
{
for feature in f.iter() {
let feature = feature.as_str().expect("feature is not a string");
if !dep.all_cli_managed_features.contains(&feature) {
features.insert(feature.into());
}
}
}
}
expected.insert(dep.name.clone(), features);
}
super::inject_features(&mut manifest, &mut dependencies).expect("failed to migrate manifest");
for dep in dependencies {
let expected_features = expected.get(&dep.name).unwrap();
for item in super::find_dependency(&mut manifest, &dep.name, dep.kind) {
let item_table = if let Some(table) = item.as_table() {
table.clone()
} else if let Some(toml_edit::Value::InlineTable(table)) = item.as_value() {
table.clone().into_table()
} else {
panic!("unexpected TOML item kind for {}", dep.name);
};
let features_array = item_table
.get("features")
.expect("missing features")
.as_array()
.expect("features must be an array")
.clone();
let mut features = Vec::new();
for feature in features_array.iter() {
let feature = feature.as_str().expect("feature must be a string");
features.push(feature);
}
for expected in expected_features {
assert!(
features.contains(&expected.as_str()),
"feature {expected} should have been injected"
);
}
}
}
}
fn tauri_dependency(features: HashSet<String>) -> DependencyAllowlist {
DependencyAllowlist {
name: "tauri".into(),
kind: DependencyKind::Normal,
all_cli_managed_features: vec!["isolation"],
features,
}
}
fn tauri_build_dependency(features: HashSet<String>) -> DependencyAllowlist {
DependencyAllowlist {
name: "tauri-build".into(),
kind: DependencyKind::Build,
all_cli_managed_features: crate::helpers::config::AppConfig::all_features(),
features,
}
}
#[test]
fn inject_features_table() {
inject_features(
r#"
[dependencies]
tauri = { version = "1", features = ["dummy"] }
[build-dependencies]
tauri-build = { version = "1" }
"#,
vec![
tauri_dependency(HashSet::from_iter(
crate::helpers::config::AppConfig::all_features()
.iter()
.map(|f| f.to_string()),
)),
tauri_build_dependency(HashSet::from_iter(vec!["isolation".into()])),
],
);
}
#[test]
fn inject_features_target() {
inject_features(
r#"
[target."cfg(windows)".dependencies]
tauri = { version = "1", features = ["dummy"] }
[target."cfg(target_os = \"macos\")".build-dependencies]
tauri-build = { version = "1" }
[target."cfg(target_os = \"linux\")".dependencies]
tauri = { version = "1", features = ["isolation"] }
[target."cfg(windows)".build-dependencies]
tauri-build = { version = "1" }
"#,
vec![
tauri_dependency(Default::default()),
tauri_build_dependency(HashSet::from_iter(vec!["isolation".into()])),
],
);
}
#[test]
fn inject_features_inline_table() {
inject_features(
r#"
[dependencies.tauri]
version = "1"
features = ["test"]
[build-dependencies.tauri-build]
version = "1"
features = ["config-toml", "codegen", "isolation"]
"#,
vec![
tauri_dependency(HashSet::from_iter(vec![
"isolation".into(),
"native-tls-vendored".into(),
])),
tauri_build_dependency(HashSet::from_iter(vec!["isolation".into()])),
],
);
}
#[test]
fn inject_features_string() {
inject_features(
r#"
[dependencies]
tauri = "1"
[build-dependencies]
tauri-build = "1"
"#,
vec![
tauri_dependency(HashSet::from_iter(vec![
"isolation".into(),
"native-tls-vendored".into(),
])),
tauri_build_dependency(HashSet::from_iter(vec!["isolation".into()])),
],
);
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/interface/rust/installation.rs | crates/tauri-cli/src/interface/rust/installation.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{
error::{Error, ErrorExt},
Result,
};
use std::{fs::read_dir, path::PathBuf, process::Command};
pub fn installed_targets() -> Result<Vec<String>> {
let output = Command::new("rustc")
.args(["--print", "sysroot"])
.output()
.map_err(|error| Error::CommandFailed {
command: "rustc --print sysroot".to_string(),
error,
})?;
let sysroot_path = PathBuf::from(String::from_utf8_lossy(&output.stdout).trim().to_string());
let mut targets = Vec::new();
for entry in read_dir(sysroot_path.join("lib").join("rustlib"))
.fs_context(
"failed to read Rust sysroot",
sysroot_path.join("lib").join("rustlib"),
)?
.flatten()
{
if entry.file_type().map(|t| t.is_dir()).unwrap_or_default() {
let name = entry.file_name();
if name != "etc" && name != "src" {
targets.push(name.to_string_lossy().into_owned());
}
}
}
Ok(targets)
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/interface/rust/desktop.rs | crates/tauri-cli/src/interface/rust/desktop.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use super::{AppSettings, DevProcess, ExitReason, Options, RustAppSettings, RustupTarget};
use crate::{
error::{Context, ErrorExt},
CommandExt, Error,
};
use shared_child::SharedChild;
use std::{
fs,
io::{BufReader, ErrorKind, Write},
path::PathBuf,
process::{Command, ExitStatus, Stdio},
sync::{
atomic::{AtomicBool, Ordering},
Arc, Mutex,
},
};
use tauri_utils::platform::Target as TargetPlatform;
pub struct DevChild {
manually_killed_app: Arc<AtomicBool>,
dev_child: Arc<SharedChild>,
}
impl DevProcess for DevChild {
fn kill(&self) -> std::io::Result<()> {
self.dev_child.kill()?;
self.manually_killed_app.store(true, Ordering::Relaxed);
Ok(())
}
fn try_wait(&self) -> std::io::Result<Option<ExitStatus>> {
self.dev_child.try_wait()
}
fn wait(&self) -> std::io::Result<ExitStatus> {
self.dev_child.wait()
}
fn manually_killed_process(&self) -> bool {
self.manually_killed_app.load(Ordering::Relaxed)
}
}
pub fn run_dev<F: Fn(Option<i32>, ExitReason) + Send + Sync + 'static>(
options: Options,
run_args: Vec<String>,
available_targets: &mut Option<Vec<RustupTarget>>,
config_features: Vec<String>,
on_exit: F,
) -> crate::Result<impl DevProcess> {
let mut dev_cmd = cargo_command(true, options, available_targets, config_features)?;
let runner = dev_cmd.get_program().to_string_lossy().into_owned();
dev_cmd
.env(
"CARGO_TERM_PROGRESS_WIDTH",
terminal::stderr_width()
.map(|width| {
if cfg!(windows) {
std::cmp::min(60, width)
} else {
width
}
})
.unwrap_or(if cfg!(windows) { 60 } else { 80 })
.to_string(),
)
.env("CARGO_TERM_PROGRESS_WHEN", "always");
dev_cmd.arg("--color");
dev_cmd.arg("always");
dev_cmd.stdout(os_pipe::dup_stdout().unwrap());
dev_cmd.stderr(Stdio::piped());
dev_cmd.arg("--");
dev_cmd.args(run_args);
let manually_killed_app = Arc::new(AtomicBool::default());
let manually_killed_app_ = manually_killed_app.clone();
log::info!(action = "Running"; "DevCommand (`{} {}`)", &dev_cmd.get_program().to_string_lossy(), dev_cmd.get_args().map(|arg| arg.to_string_lossy()).fold(String::new(), |acc, arg| format!("{acc} {arg}")));
let dev_child = match SharedChild::spawn(&mut dev_cmd) {
Ok(c) => Ok(c),
Err(e) if e.kind() == ErrorKind::NotFound => crate::error::bail!(
"`{runner}` command not found.{}",
if runner == "cargo" {
" Please follow the Tauri setup guide: https://v2.tauri.app/start/prerequisites/"
} else {
""
}
),
Err(e) => Err(Error::CommandFailed {
command: runner,
error: e,
}),
}?;
let dev_child = Arc::new(dev_child);
let dev_child_stderr = dev_child.take_stderr().unwrap();
let mut stderr = BufReader::new(dev_child_stderr);
let stderr_lines = Arc::new(Mutex::new(Vec::new()));
let stderr_lines_ = stderr_lines.clone();
std::thread::spawn(move || {
let mut buf = Vec::new();
let mut lines = stderr_lines_.lock().unwrap();
let mut io_stderr = std::io::stderr();
loop {
buf.clear();
if let Ok(0) = tauri_utils::io::read_line(&mut stderr, &mut buf) {
break;
}
let _ = io_stderr.write_all(&buf);
lines.push(String::from_utf8_lossy(&buf).into_owned());
}
});
let dev_child_ = dev_child.clone();
std::thread::spawn(move || {
let status = dev_child_.wait().expect("failed to build app");
if status.success() {
on_exit(status.code(), ExitReason::NormalExit);
} else {
let is_cargo_compile_error = stderr_lines
.lock()
.unwrap()
.last()
.map(|l| l.contains("could not compile"))
.unwrap_or_default();
stderr_lines.lock().unwrap().clear();
on_exit(
status.code(),
if status.code() == Some(101) && is_cargo_compile_error {
ExitReason::CompilationFailed
} else if manually_killed_app_.load(Ordering::Relaxed) {
ExitReason::TriggeredKill
} else {
ExitReason::NormalExit
},
);
}
});
Ok(DevChild {
manually_killed_app,
dev_child,
})
}
pub fn build(
options: Options,
app_settings: &RustAppSettings,
available_targets: &mut Option<Vec<RustupTarget>>,
config_features: Vec<String>,
main_binary_name: Option<&str>,
) -> crate::Result<PathBuf> {
let out_dir = app_settings.out_dir(&options)?;
let bin_path = app_settings.app_binary_path(&options)?;
if !std::env::var("STATIC_VCRUNTIME").is_ok_and(|v| v == "false") {
std::env::set_var("STATIC_VCRUNTIME", "true");
}
if options.target == Some("universal-apple-darwin".into()) {
std::fs::create_dir_all(&out_dir)
.fs_context("failed to create project out directory", out_dir.clone())?;
let bin_name = bin_path.file_stem().unwrap();
let mut lipo_cmd = Command::new("lipo");
lipo_cmd
.arg("-create")
.arg("-output")
.arg(out_dir.join(bin_name));
for triple in ["aarch64-apple-darwin", "x86_64-apple-darwin"] {
let mut options = options.clone();
options.target.replace(triple.into());
let triple_out_dir = app_settings
.out_dir(&options)
.with_context(|| format!("failed to get {triple} out dir"))?;
build_production_app(options, available_targets, config_features.clone())
.with_context(|| format!("failed to build {triple} binary"))?;
lipo_cmd.arg(triple_out_dir.join(bin_name));
}
let lipo_status = lipo_cmd.output_ok()?.status;
if !lipo_status.success() {
crate::error::bail!(
"Result of `lipo` command was unsuccessful: {lipo_status}. (Is `lipo` installed?)"
);
}
} else {
build_production_app(options, available_targets, config_features)
.with_context(|| "failed to build app")?;
}
rename_app(bin_path, main_binary_name, &app_settings.target_platform)
}
fn build_production_app(
options: Options,
available_targets: &mut Option<Vec<RustupTarget>>,
config_features: Vec<String>,
) -> crate::Result<()> {
let mut build_cmd = cargo_command(false, options, available_targets, config_features)?;
let runner = build_cmd.get_program().to_string_lossy().into_owned();
match build_cmd.piped() {
Ok(status) if status.success() => Ok(()),
Ok(_) => crate::error::bail!("failed to build app"),
Err(e) if e.kind() == ErrorKind::NotFound => crate::error::bail!(
"`{}` command not found.{}",
runner,
if runner == "cargo" {
" Please follow the Tauri setup guide: https://v2.tauri.app/start/prerequisites/"
} else {
""
}
),
Err(e) => Err(Error::CommandFailed {
command: runner,
error: e,
}),
}
}
fn cargo_command(
dev: bool,
options: Options,
available_targets: &mut Option<Vec<RustupTarget>>,
config_features: Vec<String>,
) -> crate::Result<Command> {
let runner_config = options.runner.unwrap_or_else(|| "cargo".into());
let mut build_cmd = Command::new(runner_config.cmd());
build_cmd.arg(if dev { "run" } else { "build" });
// Set working directory if specified
if let Some(cwd) = runner_config.cwd() {
build_cmd.current_dir(cwd);
}
// Add runner-specific arguments first
if let Some(runner_args) = runner_config.args() {
build_cmd.args(runner_args);
}
if let Some(target) = &options.target {
if available_targets.is_none() {
*available_targets = fetch_available_targets();
}
validate_target(available_targets, target)?;
}
build_cmd.args(&options.args);
let mut features = config_features;
features.extend(options.features);
if !features.is_empty() {
build_cmd.arg("--features");
build_cmd.arg(features.join(","));
}
if !options.debug && !options.args.contains(&"--profile".to_string()) {
build_cmd.arg("--release");
}
if let Some(target) = options.target {
build_cmd.arg("--target");
build_cmd.arg(target);
}
Ok(build_cmd)
}
fn fetch_available_targets() -> Option<Vec<RustupTarget>> {
if let Ok(output) = Command::new("rustup").args(["target", "list"]).output() {
let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
Some(
stdout
.split('\n')
.map(|t| {
let mut s = t.split(' ');
let name = s.next().unwrap().to_string();
let installed = s.next().map(|v| v == "(installed)").unwrap_or_default();
RustupTarget { name, installed }
})
.filter(|t| !t.name.is_empty())
.collect(),
)
} else {
None
}
}
fn validate_target(
available_targets: &Option<Vec<RustupTarget>>,
target: &str,
) -> crate::Result<()> {
if let Some(available_targets) = available_targets {
if let Some(target) = available_targets.iter().find(|t| t.name == target) {
if !target.installed {
crate::error::bail!(
"Target {target} is not installed (installed targets: {installed}). Please run `rustup target add {target}`.",
target = target.name,
installed = available_targets.iter().filter(|t| t.installed).map(|t| t.name.as_str()).collect::<Vec<&str>>().join(", ")
);
}
}
if !available_targets.iter().any(|t| t.name == target) {
crate::error::bail!("Target {target} does not exist. Please run `rustup target list` to see the available targets.", target = target);
}
}
Ok(())
}
fn rename_app(
bin_path: PathBuf,
main_binary_name: Option<&str>,
target_platform: &TargetPlatform,
) -> crate::Result<PathBuf> {
if let Some(main_binary_name) = main_binary_name {
let extension = if matches!(target_platform, TargetPlatform::Windows) {
".exe"
} else {
""
};
let new_path = bin_path.with_file_name(format!("{main_binary_name}{extension}"));
fs::rename(&bin_path, &new_path).fs_context("failed to rename app binary", bin_path)?;
Ok(new_path)
} else {
Ok(bin_path)
}
}
// taken from https://github.com/rust-lang/cargo/blob/78b10d4e611ab0721fc3aeaf0edd5dd8f4fdc372/src/cargo/core/shell.rs#L514
#[cfg(unix)]
mod terminal {
use std::mem;
pub fn stderr_width() -> Option<usize> {
unsafe {
let mut winsize: libc::winsize = mem::zeroed();
// The .into() here is needed for FreeBSD which defines TIOCGWINSZ
// as c_uint but ioctl wants c_ulong.
#[allow(clippy::useless_conversion)]
if libc::ioctl(libc::STDERR_FILENO, libc::TIOCGWINSZ.into(), &mut winsize) < 0 {
return None;
}
if winsize.ws_col > 0 {
Some(winsize.ws_col as usize)
} else {
None
}
}
}
}
// taken from https://github.com/rust-lang/cargo/blob/78b10d4e611ab0721fc3aeaf0edd5dd8f4fdc372/src/cargo/core/shell.rs#L543
#[cfg(windows)]
mod terminal {
use std::{cmp, mem, ptr};
use windows_sys::{
core::PCSTR,
Win32::{
Foundation::{CloseHandle, GENERIC_READ, GENERIC_WRITE, INVALID_HANDLE_VALUE},
Storage::FileSystem::{CreateFileA, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING},
System::Console::{
GetConsoleScreenBufferInfo, GetStdHandle, CONSOLE_SCREEN_BUFFER_INFO, STD_ERROR_HANDLE,
},
},
};
pub fn stderr_width() -> Option<usize> {
unsafe {
let stdout = GetStdHandle(STD_ERROR_HANDLE);
let mut csbi: CONSOLE_SCREEN_BUFFER_INFO = mem::zeroed();
if GetConsoleScreenBufferInfo(stdout, &mut csbi) != 0 {
return Some((csbi.srWindow.Right - csbi.srWindow.Left) as usize);
}
// On mintty/msys/cygwin based terminals, the above fails with
// INVALID_HANDLE_VALUE. Use an alternate method which works
// in that case as well.
let h = CreateFileA(
c"CONOUT$".as_ptr() as PCSTR,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
ptr::null_mut(),
OPEN_EXISTING,
0,
std::ptr::null_mut(),
);
if h == INVALID_HANDLE_VALUE {
return None;
}
let mut csbi: CONSOLE_SCREEN_BUFFER_INFO = mem::zeroed();
let rc = GetConsoleScreenBufferInfo(h, &mut csbi);
CloseHandle(h);
if rc != 0 {
let width = (csbi.srWindow.Right - csbi.srWindow.Left) as usize;
// Unfortunately cygwin/mintty does not set the size of the
// backing console to match the actual window size. This
// always reports a size of 80 or 120 (not sure what
// determines that). Use a conservative max of 60 which should
// work in most circumstances. ConEmu does some magic to
// resize the console correctly, but there's no reasonable way
// to detect which kind of terminal we are running in, or if
// GetConsoleScreenBufferInfo returns accurate information.
return Some(cmp::min(60, width));
}
None
}
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/interface/rust/cargo_config.rs | crates/tauri-cli/src/interface/rust/cargo_config.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use serde::Deserialize;
use std::{
fs,
path::{Path, PathBuf},
};
use tauri_utils::display_path;
use crate::{
error::{Context, ErrorExt},
Result,
};
struct PathAncestors<'a> {
current: Option<&'a Path>,
}
impl<'a> PathAncestors<'a> {
fn new(path: &'a Path) -> PathAncestors<'a> {
PathAncestors {
current: Some(path),
}
}
}
impl<'a> Iterator for PathAncestors<'a> {
type Item = &'a Path;
fn next(&mut self) -> Option<&'a Path> {
if let Some(path) = self.current {
self.current = path.parent();
Some(path)
} else {
None
}
}
}
#[derive(Default, Deserialize)]
pub struct BuildConfig {
target: Option<String>,
}
#[derive(Deserialize)]
pub struct ConfigSchema {
build: Option<BuildConfig>,
}
#[derive(Default)]
pub struct Config {
build: BuildConfig,
}
impl Config {
pub fn load(path: &Path) -> Result<Self> {
let mut config = Self::default();
let get_config = |path: PathBuf| -> Result<ConfigSchema> {
let contents =
fs::read_to_string(&path).fs_context("failed to read configuration file", path.clone())?;
toml::from_str(&contents).context(format!(
"could not parse TOML configuration in `{}`",
display_path(&path)
))
};
for current in PathAncestors::new(path) {
if let Some(path) = get_file_path(¤t.join(".cargo"), "config", true)? {
let toml = get_config(path)?;
if let Some(target) = toml.build.and_then(|b| b.target) {
config.build.target = Some(target);
break;
}
}
}
if config.build.target.is_none() {
if let Ok(cargo_home) = std::env::var("CARGO_HOME") {
if let Some(path) = get_file_path(&PathBuf::from(cargo_home), "config", true)? {
let toml = get_config(path)?;
if let Some(target) = toml.build.and_then(|b| b.target) {
config.build.target = Some(target);
}
}
}
}
Ok(config)
}
pub fn build(&self) -> &BuildConfig {
&self.build
}
}
impl BuildConfig {
pub fn target(&self) -> Option<&str> {
self.target.as_deref()
}
}
/// The purpose of this function is to aid in the transition to using
/// .toml extensions on Cargo's config files, which were historically not used.
/// Both 'config.toml' and 'credentials.toml' should be valid with or without extension.
/// When both exist, we want to prefer the one without an extension for
/// backwards compatibility, but warn the user appropriately.
fn get_file_path(
dir: &Path,
filename_without_extension: &str,
warn: bool,
) -> Result<Option<PathBuf>> {
let possible = dir.join(filename_without_extension);
let possible_with_extension = dir.join(format!("{filename_without_extension}.toml"));
if possible.exists() {
if warn && possible_with_extension.exists() {
// We don't want to print a warning if the version
// without the extension is just a symlink to the version
// WITH an extension, which people may want to do to
// support multiple Cargo versions at once and not
// get a warning.
let skip_warning = if let Ok(target_path) = fs::read_link(&possible) {
target_path == possible_with_extension
} else {
false
};
if !skip_warning {
log::warn!(
"Both `{}` and `{}` exist. Using `{}`",
display_path(&possible),
display_path(&possible_with_extension),
display_path(&possible)
);
}
}
Ok(Some(possible))
} else if possible_with_extension.exists() {
Ok(Some(possible_with_extension))
} else {
Ok(None)
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/mobile/mod.rs | crates/tauri-cli/src/mobile/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{
error::{Context, ErrorExt},
helpers::{
app_paths::tauri_dir,
config::{reload as reload_config, Config as TauriConfig, ConfigHandle, ConfigMetadata},
},
interface::{AppInterface, AppSettings, DevProcess, Interface, Options as InterfaceOptions},
ConfigValue, Error, Result,
};
use heck::ToSnekCase;
use jsonrpsee::core::client::{Client, ClientBuilder, ClientT};
use jsonrpsee::server::{RpcModule, ServerBuilder, ServerHandle};
use jsonrpsee_client_transport::ws::WsTransportClientBuilder;
use jsonrpsee_core::rpc_params;
use serde::{Deserialize, Serialize};
use cargo_mobile2::{
config::app::{App, Raw as RawAppConfig},
env::Error as EnvError,
opts::{NoiseLevel, Profile},
ChildHandle,
};
use std::{
collections::HashMap,
env::{set_var, temp_dir},
ffi::OsString,
fmt::{Display, Write},
fs::{read_to_string, write},
net::{AddrParseError, IpAddr, Ipv4Addr, SocketAddr},
path::PathBuf,
process::{exit, ExitStatus},
str::FromStr,
sync::{
atomic::{AtomicBool, Ordering},
Arc, OnceLock,
},
};
use tokio::runtime::Runtime;
#[cfg(not(windows))]
use cargo_mobile2::env::Env;
#[cfg(windows)]
use cargo_mobile2::os::Env;
pub mod android;
mod init;
#[cfg(target_os = "macos")]
pub mod ios;
const MIN_DEVICE_MATCH_SCORE: isize = 0;
#[derive(Clone)]
pub struct DevChild {
child: Arc<ChildHandle>,
manually_killed_process: Arc<AtomicBool>,
}
impl DevChild {
fn new(handle: ChildHandle) -> Self {
Self {
child: Arc::new(handle),
manually_killed_process: Default::default(),
}
}
}
impl DevProcess for DevChild {
fn kill(&self) -> std::io::Result<()> {
self.manually_killed_process.store(true, Ordering::Relaxed);
match self.child.kill() {
Ok(_) => Ok(()),
Err(e) => {
self.manually_killed_process.store(false, Ordering::Relaxed);
Err(e)
}
}
}
fn try_wait(&self) -> std::io::Result<Option<ExitStatus>> {
self.child.try_wait().map(|res| res.map(|o| o.status))
}
fn wait(&self) -> std::io::Result<ExitStatus> {
self.child.wait().map(|o| o.status)
}
fn manually_killed_process(&self) -> bool {
self.manually_killed_process.load(Ordering::Relaxed)
}
}
#[derive(PartialEq, Eq, Copy, Clone)]
pub enum Target {
Android,
#[cfg(target_os = "macos")]
Ios,
}
impl Target {
fn ide_name(&self) -> &'static str {
match self {
Self::Android => "Android Studio",
#[cfg(target_os = "macos")]
Self::Ios => "Xcode",
}
}
fn command_name(&self) -> &'static str {
match self {
Self::Android => "android",
#[cfg(target_os = "macos")]
Self::Ios => "ios",
}
}
fn ide_build_script_name(&self) -> &'static str {
match self {
Self::Android => "android-studio-script",
#[cfg(target_os = "macos")]
Self::Ios => "xcode-script",
}
}
fn platform_target(&self) -> tauri_utils::platform::Target {
match self {
Self::Android => tauri_utils::platform::Target::Android,
#[cfg(target_os = "macos")]
Self::Ios => tauri_utils::platform::Target::Ios,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TargetDevice {
id: String,
name: String,
}
#[derive(Debug, Clone)]
pub struct DevHost(Option<Option<IpAddr>>);
impl FromStr for DevHost {
type Err = AddrParseError;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
if s.is_empty() || s == "<public network address>" {
Ok(Self(Some(None)))
} else if s == "<none>" {
Ok(Self(None))
} else {
IpAddr::from_str(s).map(|addr| Self(Some(Some(addr))))
}
}
}
impl Display for DevHost {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.0 {
Some(None) => write!(f, "<public network address>"),
Some(Some(addr)) => write!(f, "{addr}"),
None => write!(f, "<none>"),
}
}
}
impl Default for DevHost {
fn default() -> Self {
// on Windows we want to force using the public network address for the development server
// because the adb port forwarding does not work well
if cfg!(windows) {
Self(Some(None))
} else {
Self(None)
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CliOptions {
pub dev: bool,
pub features: Vec<String>,
pub args: Vec<String>,
pub noise_level: NoiseLevel,
pub vars: HashMap<String, OsString>,
pub config: Vec<ConfigValue>,
pub target_device: Option<TargetDevice>,
}
impl Default for CliOptions {
fn default() -> Self {
Self {
dev: false,
features: Vec::new(),
args: vec!["--lib".into()],
noise_level: Default::default(),
vars: Default::default(),
config: Vec::new(),
target_device: None,
}
}
}
fn local_ip_address(force: bool) -> &'static IpAddr {
static LOCAL_IP: OnceLock<IpAddr> = OnceLock::new();
LOCAL_IP.get_or_init(|| {
let prompt_for_ip = || {
let addresses: Vec<IpAddr> = local_ip_address::list_afinet_netifas()
.expect("failed to list networks")
.into_iter()
.map(|(_, ipaddr)| ipaddr)
.filter(|ipaddr| match ipaddr {
IpAddr::V4(i) => i != &Ipv4Addr::LOCALHOST,
IpAddr::V6(i) => i.to_string().ends_with("::2"),
})
.collect();
match addresses.len() {
0 => panic!("No external IP detected."),
1 => {
let ipaddr = addresses.first().unwrap();
*ipaddr
}
_ => {
let selected = dialoguer::Select::with_theme(&dialoguer::theme::ColorfulTheme::default())
.with_prompt(
"Failed to detect external IP, What IP should we use to access your development server?",
)
.items(&addresses)
.default(0)
.interact()
.expect("failed to select external IP");
*addresses.get(selected).unwrap()
}
}
};
let ip = if force {
prompt_for_ip()
} else {
local_ip_address::local_ip().unwrap_or_else(|_| prompt_for_ip())
};
log::info!("Using {ip} to access the development server.");
ip
})
}
struct DevUrlConfig {
no_dev_server_wait: bool,
}
fn use_network_address_for_dev_url(
config: &ConfigHandle,
dev_options: &mut crate::dev::Options,
force_ip_prompt: bool,
) -> crate::Result<DevUrlConfig> {
let mut dev_url = config
.lock()
.unwrap()
.as_ref()
.unwrap()
.build
.dev_url
.clone();
let ip = if let Some(url) = &mut dev_url {
let localhost = match url.host() {
Some(url::Host::Domain(d)) => d == "localhost",
Some(url::Host::Ipv4(i)) => i == Ipv4Addr::LOCALHOST || i == Ipv4Addr::UNSPECIFIED,
_ => false,
};
if localhost {
let ip = dev_options
.host
.unwrap_or_else(|| *local_ip_address(force_ip_prompt));
log::info!(
"Replacing devUrl host with {ip}. {}.",
"If your frontend is not listening on that address, try configuring your development server to use the `TAURI_DEV_HOST` environment variable or 0.0.0.0 as host"
);
let url_str = format!(
"{}://{}{}",
url.scheme(),
SocketAddr::new(ip, url.port_or_known_default().unwrap()),
url.path()
);
*url =
url::Url::parse(&url_str).with_context(|| format!("failed to parse URL: {url_str}"))?;
dev_options
.config
.push(crate::ConfigValue(serde_json::json!({
"build": {
"devUrl": url
}
})));
reload_config(
&dev_options
.config
.iter()
.map(|conf| &conf.0)
.collect::<Vec<_>>(),
)?;
Some(ip)
} else {
None
}
} else if !dev_options.no_dev_server {
let ip = dev_options
.host
.unwrap_or_else(|| *local_ip_address(force_ip_prompt));
dev_options.host.replace(ip);
Some(ip)
} else {
None
};
let mut dev_url_config = DevUrlConfig {
no_dev_server_wait: false,
};
if let Some(ip) = ip {
std::env::set_var("TAURI_DEV_HOST", ip.to_string());
std::env::set_var("TRUNK_SERVE_ADDRESS", ip.to_string());
if ip.is_ipv6() {
// in this case we can't ping the server for some reason
dev_url_config.no_dev_server_wait = true;
}
}
Ok(dev_url_config)
}
fn env_vars() -> HashMap<String, OsString> {
let mut vars = HashMap::new();
vars.insert("RUST_LOG_STYLE".into(), "always".into());
for (k, v) in std::env::vars_os() {
let k = k.to_string_lossy();
if (k.starts_with("TAURI")
&& k != "TAURI_SIGNING_PRIVATE_KEY"
&& k != "TAURI_SIGNING_PRIVATE_KEY_PASSWORD")
|| k.starts_with("WRY")
|| k.starts_with("CARGO_")
|| k.starts_with("RUST_")
|| k == "TMPDIR"
|| k == "PATH"
{
vars.insert(k.into_owned(), v);
}
}
vars
}
fn env() -> std::result::Result<Env, EnvError> {
let env = Env::new()?.explicit_env_vars(env_vars());
Ok(env)
}
pub struct OptionsHandle(#[allow(unused)] Runtime, #[allow(unused)] ServerHandle);
/// Writes CLI options to be used later on the Xcode and Android Studio build commands
pub fn write_options(
config: &ConfigMetadata,
mut options: CliOptions,
) -> crate::Result<OptionsHandle> {
options.vars.extend(env_vars());
let runtime = Runtime::new().unwrap();
let r: crate::Result<(ServerHandle, SocketAddr)> = runtime.block_on(async move {
let server = ServerBuilder::default()
.build("127.0.0.1:0")
.await
.context("failed to build WebSocket server")?;
let addr = server.local_addr().context("failed to get local address")?;
let mut module = RpcModule::new(());
module
.register_method("options", move |_, _, _| Some(options.clone()))
.context("failed to register options method")?;
let handle = server.start(module);
Ok((handle, addr))
});
let (handle, addr) = r?;
let server_addr_path = temp_dir().join(format!(
"{}-server-addr",
config
.original_identifier()
.context("app configuration is missing an identifier")?
));
write(&server_addr_path, addr.to_string())
.fs_context("failed to write server address file", server_addr_path)?;
Ok(OptionsHandle(runtime, handle))
}
fn read_options(config: &ConfigMetadata) -> CliOptions {
let runtime = tokio::runtime::Runtime::new().unwrap();
let options = runtime
.block_on(async move {
let addr_path = temp_dir().join(format!(
"{}-server-addr",
config
.original_identifier()
.context("app configuration is missing an identifier")?
));
let (tx, rx) = WsTransportClientBuilder::default()
.build(
format!(
"ws://{}",
read_to_string(&addr_path).unwrap_or_else(|e| panic!(
"failed to read missing addr file {}: {e}",
addr_path.display()
))
)
.parse()
.unwrap(),
)
.await
.context("failed to build WebSocket client")?;
let client: Client = ClientBuilder::default().build_with_tokio(tx, rx);
let options: CliOptions = client
.request("options", rpc_params![])
.await
.context("failed to request options")?;
Ok::<CliOptions, Error>(options)
})
.expect("failed to read CLI options");
for (k, v) in &options.vars {
set_var(k, v);
}
options
}
pub fn get_app(target: Target, config: &TauriConfig, interface: &AppInterface) -> App {
let identifier = match target {
Target::Android => config.identifier.replace('-', "_"),
#[cfg(target_os = "macos")]
Target::Ios => config.identifier.replace('_', "-"),
};
if identifier.is_empty() {
log::error!("Bundle identifier set in `tauri.conf.json > identifier` cannot be empty");
exit(1);
}
let app_name = interface
.app_settings()
.app_name()
.unwrap_or_else(|| "app".into());
let lib_name = interface
.app_settings()
.lib_name()
.unwrap_or_else(|| app_name.to_snek_case());
if config.product_name.is_none() {
log::warn!(
"`productName` is not set in the Tauri configuration. Using `{app_name}` as the app name."
);
}
let raw = RawAppConfig {
name: app_name,
lib_name: Some(lib_name),
stylized_name: config.product_name.clone(),
identifier,
asset_dir: None,
template_pack: None,
};
let app_settings = interface.app_settings();
App::from_raw(tauri_dir().to_path_buf(), raw)
.unwrap()
.with_target_dir_resolver(move |target, profile| {
app_settings
.out_dir(&InterfaceOptions {
debug: matches!(profile, Profile::Debug),
target: Some(target.into()),
..Default::default()
})
.expect("failed to resolve target directory")
})
}
#[allow(unused_variables)]
fn ensure_init(
tauri_config: &ConfigHandle,
app: &App,
project_dir: PathBuf,
target: Target,
noninteractive: bool,
) -> Result<()> {
if !project_dir.exists() {
crate::error::bail!(
"{} project directory {} doesn't exist. Please run `tauri {} init` and try again.",
target.ide_name(),
project_dir.display(),
target.command_name(),
)
}
let tauri_config_guard = tauri_config.lock().unwrap();
let tauri_config_ = tauri_config_guard.as_ref().unwrap();
let mut project_outdated_reasons = Vec::new();
match target {
Target::Android => {
let java_folder = project_dir
.join("app/src/main/java")
.join(tauri_config_.identifier.replace('.', "/").replace('-', "_"));
if java_folder.exists() {
#[cfg(unix)]
ensure_gradlew(&project_dir)?;
} else {
project_outdated_reasons
.push("you have modified your \"identifier\" in the Tauri configuration");
}
}
#[cfg(target_os = "macos")]
Target::Ios => {
let xcodeproj_path = crate::helpers::fs::find_in_directory(&project_dir, "*.xcodeproj")
.with_context(|| format!("failed to locate xcodeproj in {}", project_dir.display()))?;
let xcodeproj_name = xcodeproj_path.file_stem().unwrap().to_str().unwrap();
if xcodeproj_name != app.name() {
let rename_targets = vec![
// first rename the entitlements
(
format!("{xcodeproj_name}_iOS/{xcodeproj_name}_iOS.entitlements"),
format!("{xcodeproj_name}_iOS/{}_iOS.entitlements", app.name()),
),
// then the scheme folder
(
format!("{xcodeproj_name}_iOS"),
format!("{}_iOS", app.name()),
),
(
format!("{xcodeproj_name}.xcodeproj"),
format!("{}.xcodeproj", app.name()),
),
];
let rename_info = rename_targets
.iter()
.map(|(from, to)| format!("- {from} to {to}"))
.collect::<Vec<_>>()
.join("\n");
log::error!(
"you have modified your package name from {current_project_name} to {new_project_name}\nWe need to apply the name change to the Xcode project, renaming:\n{rename_info}",
new_project_name = app.name(),
current_project_name = xcodeproj_name,
);
if noninteractive {
project_outdated_reasons
.push("you have modified your [lib.name] or [package.name] in the Cargo.toml file");
} else {
let confirm = crate::helpers::prompts::confirm(
"Do you want to apply the name change to the Xcode project?",
Some(true),
)
.unwrap_or_default();
if confirm {
for (from, to) in rename_targets {
std::fs::rename(project_dir.join(&from), project_dir.join(&to))
.with_context(|| format!("failed to rename {from} to {to}"))?;
}
// update scheme name in pbxproj
// identifier / product name are synchronized by the dev/build commands
let pbxproj_path =
project_dir.join(format!("{}.xcodeproj/project.pbxproj", app.name()));
let pbxproj_contents = std::fs::read_to_string(&pbxproj_path)
.with_context(|| format!("failed to read {}", pbxproj_path.display()))?;
std::fs::write(
&pbxproj_path,
pbxproj_contents.replace(
&format!("{xcodeproj_name}_iOS"),
&format!("{}_iOS", app.name()),
),
)
.with_context(|| format!("failed to write {}", pbxproj_path.display()))?;
} else {
project_outdated_reasons
.push("you have modified your [lib.name] or [package.name] in the Cargo.toml file");
}
}
}
// note: pbxproj is synchronied by the dev/build commands
}
}
if !project_outdated_reasons.is_empty() {
let reason = project_outdated_reasons.join(" and ");
crate::error::bail!(
"{} project directory is outdated because {reason}. Please delete {}, run `tauri {} init` and try again.",
target.ide_name(),
project_dir.display(),
target.command_name(),
)
}
Ok(())
}
#[cfg(unix)]
fn ensure_gradlew(project_dir: &std::path::Path) -> Result<()> {
use std::os::unix::fs::PermissionsExt;
let gradlew_path = project_dir.join("gradlew");
if let Ok(metadata) = gradlew_path.metadata() {
let mut permissions = metadata.permissions();
let is_executable = permissions.mode() & 0o111 != 0;
if !is_executable {
permissions.set_mode(permissions.mode() | 0o111);
std::fs::set_permissions(&gradlew_path, permissions)
.fs_context("failed to mark gradlew as executable", gradlew_path.clone())?;
}
std::fs::write(
&gradlew_path,
std::fs::read_to_string(&gradlew_path)
.fs_context("failed to read gradlew", gradlew_path.clone())?
.replace("\r\n", "\n"),
)
.fs_context("failed to replace gradlew CRLF with LF", gradlew_path)?;
}
Ok(())
}
fn log_finished(outputs: Vec<PathBuf>, kind: &str) {
if !outputs.is_empty() {
let mut printable_paths = String::new();
for path in &outputs {
writeln!(printable_paths, " {}", path.display()).unwrap();
}
log::info!(action = "Finished"; "{} {}{} at:\n{}", outputs.len(), kind, if outputs.len() == 1 { "" } else { "s" }, printable_paths);
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/mobile/init.rs | crates/tauri-cli/src/mobile/init.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use super::{get_app, Target};
use crate::{
helpers::{config::get as get_tauri_config, template::JsonMap},
interface::{AppInterface, Interface},
ConfigValue, Result,
};
use cargo_mobile2::{
config::app::App,
reserved_names::KOTLIN_ONLY_KEYWORDS,
util::{
self,
cli::{Report, TextWrapper},
},
};
use handlebars::{
Context, Handlebars, Helper, HelperResult, Output, RenderContext, RenderError, RenderErrorReason,
};
use std::{env::var_os, path::PathBuf};
pub fn command(
target: Target,
ci: bool,
reinstall_deps: bool,
skip_targets_install: bool,
config: Vec<ConfigValue>,
) -> Result<()> {
let wrapper = TextWrapper::default();
exec(
target,
&wrapper,
ci,
reinstall_deps,
skip_targets_install,
config,
)?;
Ok(())
}
pub fn exec(
target: Target,
wrapper: &TextWrapper,
#[allow(unused_variables)] non_interactive: bool,
#[allow(unused_variables)] reinstall_deps: bool,
skip_targets_install: bool,
config: Vec<ConfigValue>,
) -> Result<App> {
let tauri_config = get_tauri_config(
target.platform_target(),
&config.iter().map(|conf| &conf.0).collect::<Vec<_>>(),
)?;
let tauri_config_guard = tauri_config.lock().unwrap();
let tauri_config_ = tauri_config_guard.as_ref().unwrap();
let app = get_app(
target,
tauri_config_,
&AppInterface::new(tauri_config_, None)?,
);
let (handlebars, mut map) = handlebars(&app);
let mut args = std::env::args_os();
let (binary, mut build_args) = args
.next()
.map(|bin| {
let bin_path = PathBuf::from(&bin);
let mut build_args = vec!["tauri"];
if let Some(bin_stem) = bin_path.file_stem() {
let r = regex::Regex::new("(nodejs|node)\\-?([1-9]*)*$").unwrap();
if r.is_match(&bin_stem.to_string_lossy()) {
if var_os("PNPM_PACKAGE_NAME").is_some() {
return ("pnpm".into(), build_args);
} else if is_pnpm_dlx() {
return ("pnpm".into(), vec!["dlx", "@tauri-apps/cli"]);
} else if let Some(npm_execpath) = var_os("npm_execpath") {
let manager_stem = PathBuf::from(&npm_execpath)
.file_stem()
.unwrap()
.to_os_string();
let is_npm = manager_stem == "npm-cli";
let binary = if is_npm {
"npm".into()
} else if manager_stem == "npx-cli" {
"npx".into()
} else {
manager_stem
};
if is_npm {
build_args.insert(0, "run");
build_args.insert(1, "--");
}
return (binary, build_args);
}
} else if bin_stem == "deno" {
build_args.insert(0, "task");
return (std::ffi::OsString::from("deno"), build_args);
} else if !cfg!(debug_assertions) && bin_stem == "cargo-tauri" {
return (std::ffi::OsString::from("cargo"), build_args);
}
}
(bin, build_args)
})
.unwrap_or_else(|| (std::ffi::OsString::from("cargo"), vec!["tauri"]));
build_args.push(target.command_name());
build_args.push(target.ide_build_script_name());
let mut binary = binary.to_string_lossy().to_string();
if binary.ends_with(".exe") || binary.ends_with(".cmd") || binary.ends_with(".bat") {
// remove Windows-only extension
binary.pop();
binary.pop();
binary.pop();
binary.pop();
}
map.insert("tauri-binary", binary);
map.insert("tauri-binary-args", &build_args);
map.insert("tauri-binary-args-str", build_args.join(" "));
let app = match target {
// Generate Android Studio project
Target::Android => {
let _env = super::android::env(non_interactive)?;
let (config, metadata) =
super::android::get_config(&app, tauri_config_, &[], &Default::default());
map.insert("android", &config);
super::android::project::gen(
&config,
&metadata,
(handlebars, map),
wrapper,
skip_targets_install,
)?;
app
}
#[cfg(target_os = "macos")]
// Generate Xcode project
Target::Ios => {
let (config, metadata) =
super::ios::get_config(&app, tauri_config_, &[], &Default::default())?;
map.insert("apple", &config);
super::ios::project::gen(
tauri_config_,
&config,
&metadata,
(handlebars, map),
wrapper,
non_interactive,
reinstall_deps,
skip_targets_install,
)?;
app
}
};
Report::victory(
"Project generated successfully!",
"Make cool apps! 🌻 🐕 🎉",
)
.print(wrapper);
Ok(app)
}
fn handlebars(app: &App) -> (Handlebars<'static>, JsonMap) {
let mut h = Handlebars::new();
h.register_escape_fn(handlebars::no_escape);
h.register_helper("html-escape", Box::new(html_escape));
h.register_helper("join", Box::new(join));
h.register_helper("quote-and-join", Box::new(quote_and_join));
h.register_helper(
"quote-and-join-colon-prefix",
Box::new(quote_and_join_colon_prefix),
);
h.register_helper("snake-case", Box::new(snake_case));
h.register_helper("escape-kotlin-keyword", Box::new(escape_kotlin_keyword));
// don't mix these up or very bad things will happen to all of us
h.register_helper("prefix-path", Box::new(prefix_path));
h.register_helper("unprefix-path", Box::new(unprefix_path));
let mut map = JsonMap::default();
map.insert("app", app);
(h, map)
}
fn get_str<'a>(helper: &'a Helper) -> &'a str {
helper
.param(0)
.and_then(|v| v.value().as_str())
.unwrap_or("")
}
fn get_str_array(helper: &Helper, formatter: impl Fn(&str) -> String) -> Option<Vec<String>> {
helper.param(0).and_then(|v| {
v.value()
.as_array()
.and_then(|arr| arr.iter().map(|val| val.as_str().map(&formatter)).collect())
})
}
fn html_escape(
helper: &Helper,
_: &Handlebars,
_ctx: &Context,
_: &mut RenderContext,
out: &mut dyn Output,
) -> HelperResult {
out
.write(&handlebars::html_escape(get_str(helper)))
.map_err(Into::into)
}
fn join(
helper: &Helper,
_: &Handlebars,
_: &Context,
_: &mut RenderContext,
out: &mut dyn Output,
) -> HelperResult {
out
.write(
&get_str_array(helper, |s| s.to_string())
.ok_or_else(|| {
RenderErrorReason::ParamTypeMismatchForName("join", "0".to_owned(), "array".to_owned())
})?
.join(", "),
)
.map_err(Into::into)
}
fn quote_and_join(
helper: &Helper,
_: &Handlebars,
_: &Context,
_: &mut RenderContext,
out: &mut dyn Output,
) -> HelperResult {
out
.write(
&get_str_array(helper, |s| format!("{s:?}"))
.ok_or_else(|| {
RenderErrorReason::ParamTypeMismatchForName(
"quote-and-join",
"0".to_owned(),
"array".to_owned(),
)
})?
.join(", "),
)
.map_err(Into::into)
}
fn quote_and_join_colon_prefix(
helper: &Helper,
_: &Handlebars,
_: &Context,
_: &mut RenderContext,
out: &mut dyn Output,
) -> HelperResult {
out
.write(
&get_str_array(helper, |s| format!("{:?}", format!(":{s}")))
.ok_or_else(|| {
RenderErrorReason::ParamTypeMismatchForName(
"quote-and-join-colon-prefix",
"0".to_owned(),
"array".to_owned(),
)
})?
.join(", "),
)
.map_err(Into::into)
}
fn snake_case(
helper: &Helper,
_: &Handlebars,
_: &Context,
_: &mut RenderContext,
out: &mut dyn Output,
) -> HelperResult {
use heck::ToSnekCase as _;
out
.write(&get_str(helper).to_snek_case())
.map_err(Into::into)
}
fn escape_kotlin_keyword(
helper: &Helper,
_: &Handlebars,
_: &Context,
_: &mut RenderContext,
out: &mut dyn Output,
) -> HelperResult {
let escaped_result = get_str(helper)
.split('.')
.map(|s| {
if KOTLIN_ONLY_KEYWORDS.contains(&s) {
format!("`{s}`")
} else {
s.to_string()
}
})
.collect::<Vec<_>>()
.join(".");
out.write(&escaped_result).map_err(Into::into)
}
fn app_root(ctx: &Context) -> std::result::Result<&str, RenderError> {
let app_root = ctx
.data()
.get("app")
.ok_or_else(|| RenderErrorReason::Other("`app` missing from template data.".to_owned()))?
.get("root-dir")
.ok_or_else(|| {
RenderErrorReason::Other("`app.root-dir` missing from template data.".to_owned())
})?;
app_root.as_str().ok_or_else(|| {
RenderErrorReason::Other("`app.root-dir` contained invalid UTF-8.".to_owned()).into()
})
}
fn prefix_path(
helper: &Helper,
_: &Handlebars,
ctx: &Context,
_: &mut RenderContext,
out: &mut dyn Output,
) -> HelperResult {
out
.write(
util::prefix_path(app_root(ctx)?, get_str(helper))
.to_str()
.ok_or_else(|| {
RenderErrorReason::Other(
"Either the `app.root-dir` or the specified path contained invalid UTF-8.".to_owned(),
)
})?,
)
.map_err(Into::into)
}
fn unprefix_path(
helper: &Helper,
_: &Handlebars,
ctx: &Context,
_: &mut RenderContext,
out: &mut dyn Output,
) -> HelperResult {
out
.write(
util::unprefix_path(app_root(ctx)?, get_str(helper))
.map_err(|_| {
RenderErrorReason::Other(
"Attempted to unprefix a path that wasn't in the app root dir.".to_owned(),
)
})?
.to_str()
.ok_or_else(|| {
RenderErrorReason::Other(
"Either the `app.root-dir` or the specified path contained invalid UTF-8.".to_owned(),
)
})?,
)
.map_err(Into::into)
}
fn is_pnpm_dlx() -> bool {
var_os("NODE_PATH")
.map(PathBuf::from)
.is_some_and(|node_path| {
let mut iter = node_path.components().peekable();
while let Some(c) = iter.next() {
if c.as_os_str() == "pnpm" && iter.peek().is_some_and(|c| c.as_os_str() == "dlx") {
return true;
}
}
false
})
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/mobile/android/dev.rs | crates/tauri-cli/src/mobile/android/dev.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use super::{
configure_cargo, delete_codegen_vars, device_prompt, ensure_init, env, get_app, get_config,
inject_resources, open_and_wait, MobileTarget,
};
use crate::{
dev::Options as DevOptions,
error::{Context, ErrorExt},
helpers::{
app_paths::tauri_dir,
config::{get as get_tauri_config, ConfigHandle},
flock,
},
interface::{AppInterface, Interface, MobileOptions, Options as InterfaceOptions},
mobile::{
android::generate_tauri_properties, use_network_address_for_dev_url, write_options, CliOptions,
DevChild, DevHost, DevProcess, TargetDevice,
},
ConfigValue, Error, Result,
};
use clap::{ArgAction, Parser};
use cargo_mobile2::{
android::{
config::{Config as AndroidConfig, Metadata as AndroidMetadata},
device::Device,
env::Env,
target::Target,
},
opts::{FilterLevel, NoiseLevel, Profile},
target::TargetTrait,
};
use url::Host;
use std::{env::set_current_dir, net::Ipv4Addr, path::PathBuf};
#[derive(Debug, Clone, Parser)]
#[clap(
about = "Run your app in development mode on Android",
long_about = "Run your app in development mode on Android with hot-reloading for the Rust code. It makes use of the `build.devUrl` property from your `tauri.conf.json` file. It also runs your `build.beforeDevCommand` which usually starts your frontend devServer."
)]
pub struct Options {
/// List of cargo features to activate
#[clap(short, long, action = ArgAction::Append, num_args(0..))]
pub features: Vec<String>,
/// Exit on panic
#[clap(short, long)]
exit_on_panic: bool,
/// JSON strings or paths to JSON, JSON5 or TOML files to merge with the default configuration file
///
/// Configurations are merged in the order they are provided, which means a particular value overwrites previous values when a config key-value pair conflicts.
///
/// Note that a platform-specific file is looked up and merged with the default file by default
/// (tauri.macos.conf.json, tauri.linux.conf.json, tauri.windows.conf.json, tauri.android.conf.json and tauri.ios.conf.json)
/// but you can use this for more specific use cases such as different build flavors.
#[clap(short, long)]
pub config: Vec<ConfigValue>,
/// Run the code in release mode
#[clap(long = "release")]
pub release_mode: bool,
/// Skip waiting for the frontend dev server to start before building the tauri application.
#[clap(long, env = "TAURI_CLI_NO_DEV_SERVER_WAIT")]
pub no_dev_server_wait: bool,
/// Disable the file watcher
#[clap(long)]
pub no_watch: bool,
/// Additional paths to watch for changes.
#[clap(long)]
pub additional_watch_folders: Vec<PathBuf>,
/// Open Android Studio instead of trying to run on a connected device
#[clap(short, long)]
pub open: bool,
/// Runs on the given device name
pub device: Option<String>,
/// Force prompting for an IP to use to connect to the dev server on mobile.
#[clap(long)]
pub force_ip_prompt: bool,
/// Use the public network address for the development server.
/// If an actual address it provided, it is used instead of prompting to pick one.
///
/// On Windows we use the public network address by default.
///
/// This option is particularly useful along the `--open` flag when you intend on running on a physical device.
///
/// This replaces the devUrl configuration value to match the public network address host,
/// it is your responsibility to set up your development server to listen on this address
/// by using 0.0.0.0 as host for instance.
///
/// When this is set or when running on an iOS device the CLI sets the `TAURI_DEV_HOST`
/// environment variable so you can check this on your framework's configuration to expose the development server
/// on the public network address.
#[clap(long, default_value_t, default_missing_value(""), num_args(0..=1))]
pub host: DevHost,
/// Disable the built-in dev server for static files.
#[clap(long)]
pub no_dev_server: bool,
/// Specify port for the built-in dev server for static files. Defaults to 1430.
#[clap(long, env = "TAURI_CLI_PORT")]
pub port: Option<u16>,
/// Command line arguments passed to the runner.
/// Use `--` to explicitly mark the start of the arguments.
/// e.g. `tauri android dev -- [runnerArgs]`.
#[clap(last(true))]
pub args: Vec<String>,
/// Path to the certificate file used by your dev server. Required for mobile dev when using HTTPS.
#[clap(long, env = "TAURI_DEV_ROOT_CERTIFICATE_PATH")]
pub root_certificate_path: Option<PathBuf>,
}
impl From<Options> for DevOptions {
fn from(options: Options) -> Self {
Self {
runner: None,
target: None,
features: options.features,
exit_on_panic: options.exit_on_panic,
config: options.config,
args: options.args,
no_watch: options.no_watch,
additional_watch_folders: options.additional_watch_folders,
no_dev_server_wait: options.no_dev_server_wait,
no_dev_server: options.no_dev_server,
port: options.port,
release_mode: options.release_mode,
host: options.host.0.unwrap_or_default(),
}
}
}
pub fn command(options: Options, noise_level: NoiseLevel) -> Result<()> {
crate::helpers::app_paths::resolve();
let result = run_command(options, noise_level);
if result.is_err() {
crate::dev::kill_before_dev_process();
}
result
}
fn run_command(options: Options, noise_level: NoiseLevel) -> Result<()> {
delete_codegen_vars();
// setup env additions before calling env()
if let Some(root_certificate_path) = &options.root_certificate_path {
std::env::set_var(
"TAURI_DEV_ROOT_CERTIFICATE",
std::fs::read_to_string(root_certificate_path).fs_context(
"failed to read certificate file",
root_certificate_path.clone(),
)?,
);
}
let tauri_config = get_tauri_config(
tauri_utils::platform::Target::Android,
&options
.config
.iter()
.map(|conf| &conf.0)
.collect::<Vec<_>>(),
)?;
let env = env(false)?;
let device = if options.open {
None
} else {
match device_prompt(&env, options.device.as_deref()) {
Ok(d) => Some(d),
Err(e) => {
log::error!("{e}");
None
}
}
};
let mut dev_options: DevOptions = options.clone().into();
let target_triple = device
.as_ref()
.map(|d| d.target().triple.to_string())
.unwrap_or_else(|| Target::all().values().next().unwrap().triple.into());
dev_options.target = Some(target_triple);
let (interface, config, metadata) = {
let tauri_config_guard = tauri_config.lock().unwrap();
let tauri_config_ = tauri_config_guard.as_ref().unwrap();
let interface = AppInterface::new(tauri_config_, dev_options.target.clone())?;
let app = get_app(MobileTarget::Android, tauri_config_, &interface);
let (config, metadata) = get_config(
&app,
tauri_config_,
dev_options.features.as_ref(),
&Default::default(),
);
(interface, config, metadata)
};
let tauri_path = tauri_dir();
set_current_dir(tauri_path).context("failed to set current directory to Tauri directory")?;
ensure_init(
&tauri_config,
config.app(),
config.project_dir(),
MobileTarget::Android,
false,
)?;
run_dev(
interface,
options,
dev_options,
tauri_config,
device,
env,
&config,
&metadata,
noise_level,
)
}
#[allow(clippy::too_many_arguments)]
fn run_dev(
mut interface: AppInterface,
options: Options,
mut dev_options: DevOptions,
tauri_config: ConfigHandle,
device: Option<Device>,
mut env: Env,
config: &AndroidConfig,
metadata: &AndroidMetadata,
noise_level: NoiseLevel,
) -> Result<()> {
// when --host is provided or running on a physical device or resolving 0.0.0.0 we must use the network IP
if options.host.0.is_some()
|| device
.as_ref()
.map(|device| !device.serial_no().starts_with("emulator"))
.unwrap_or(false)
|| tauri_config
.lock()
.unwrap()
.as_ref()
.unwrap()
.build
.dev_url
.as_ref()
.is_some_and(|url| {
matches!(
url.host(),
Some(Host::Ipv4(i)) if i == Ipv4Addr::UNSPECIFIED
)
})
{
use_network_address_for_dev_url(&tauri_config, &mut dev_options, options.force_ip_prompt)?;
}
crate::dev::setup(&interface, &mut dev_options, tauri_config)?;
let interface_options = InterfaceOptions {
debug: !dev_options.release_mode,
target: dev_options.target.clone(),
..Default::default()
};
let app_settings = interface.app_settings();
let out_dir = app_settings.out_dir(&interface_options)?;
let _lock = flock::open_rw(out_dir.join("lock").with_extension("android"), "Android")?;
configure_cargo(&mut env, config)?;
generate_tauri_properties(config, tauri_config.lock().unwrap().as_ref().unwrap(), true)?;
let installed_targets =
crate::interface::rust::installation::installed_targets().unwrap_or_default();
// run an initial build to initialize plugins
let target_triple = dev_options.target.as_ref().unwrap();
let target = Target::all()
.values()
.find(|t| t.triple == target_triple)
.unwrap_or_else(|| Target::all().values().next().unwrap());
if !installed_targets.contains(&target.triple().into()) {
log::info!("Installing target {}", target.triple());
target.install().map_err(|error| Error::CommandFailed {
command: "rustup target add".to_string(),
error,
})?;
}
target
.build(
config,
metadata,
&env,
noise_level,
true,
if options.release_mode {
Profile::Release
} else {
Profile::Debug
},
)
.context("failed to build Android app")?;
let open = options.open;
interface.mobile_dev(
MobileOptions {
debug: !options.release_mode,
features: options.features,
args: options.args,
config: dev_options.config.clone(),
no_watch: options.no_watch,
additional_watch_folders: options.additional_watch_folders,
},
|options| {
let cli_options = CliOptions {
dev: true,
features: options.features.clone(),
args: options.args.clone(),
noise_level,
vars: Default::default(),
config: dev_options.config.clone(),
target_device: device.as_ref().map(|d| TargetDevice {
id: d.serial_no().to_string(),
name: d.name().to_string(),
}),
};
let _handle = write_options(tauri_config.lock().unwrap().as_ref().unwrap(), cli_options)?;
inject_resources(config, tauri_config.lock().unwrap().as_ref().unwrap())?;
if open {
open_and_wait(config, &env)
} else if let Some(device) = &device {
match run(device, options, config, &env, metadata, noise_level) {
Ok(c) => Ok(Box::new(c) as Box<dyn DevProcess + Send>),
Err(e) => {
crate::dev::kill_before_dev_process();
Err(e)
}
}
} else {
open_and_wait(config, &env)
}
},
)
}
fn run(
device: &Device<'_>,
options: MobileOptions,
config: &AndroidConfig,
env: &Env,
metadata: &AndroidMetadata,
noise_level: NoiseLevel,
) -> crate::Result<DevChild> {
let profile = if options.debug {
Profile::Debug
} else {
Profile::Release
};
let build_app_bundle = metadata.asset_packs().is_some();
device
.run(
config,
env,
noise_level,
profile,
Some(match noise_level {
NoiseLevel::Polite => FilterLevel::Info,
NoiseLevel::LoudAndProud => FilterLevel::Debug,
NoiseLevel::FranklyQuitePedantic => FilterLevel::Verbose,
}),
build_app_bundle,
false,
".MainActivity".into(),
)
.map(DevChild::new)
.context("failed to run Android app")
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/mobile/android/android_studio_script.rs | crates/tauri-cli/src/mobile/android/android_studio_script.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use super::{detect_target_ok, ensure_init, env, get_app, get_config, read_options, MobileTarget};
use crate::{
error::{Context, ErrorExt},
helpers::config::{get as get_tauri_config, reload as reload_tauri_config},
interface::{AppInterface, Interface},
mobile::CliOptions,
Error, Result,
};
use clap::{ArgAction, Parser};
use cargo_mobile2::{
android::{adb, target::Target},
opts::Profile,
target::{call_for_targets_with_fallback, TargetTrait},
};
use std::path::Path;
#[derive(Debug, Parser)]
pub struct Options {
/// Targets to build.
#[clap(
short,
long = "target",
action = ArgAction::Append,
num_args(0..),
default_value = Target::DEFAULT_KEY,
value_parser(clap::builder::PossibleValuesParser::new(Target::name_list()))
)]
targets: Option<Vec<String>>,
/// Builds with the release flag
#[clap(short, long)]
release: bool,
}
pub fn command(options: Options) -> Result<()> {
crate::helpers::app_paths::resolve();
let profile = if options.release {
Profile::Release
} else {
Profile::Debug
};
let (tauri_config, cli_options) = {
let tauri_config = get_tauri_config(tauri_utils::platform::Target::Android, &[])?;
let cli_options = {
let tauri_config_guard = tauri_config.lock().unwrap();
let tauri_config_ = tauri_config_guard.as_ref().unwrap();
read_options(tauri_config_)
};
let tauri_config = if cli_options.config.is_empty() {
tauri_config
} else {
// reload config with merges from the android dev|build script
reload_tauri_config(
&cli_options
.config
.iter()
.map(|conf| &conf.0)
.collect::<Vec<_>>(),
)?
};
(tauri_config, cli_options)
};
let (config, metadata) = {
let tauri_config_guard = tauri_config.lock().unwrap();
let tauri_config_ = tauri_config_guard.as_ref().unwrap();
let (config, metadata) = get_config(
&get_app(
MobileTarget::Android,
tauri_config_,
&AppInterface::new(tauri_config_, None)?,
),
tauri_config_,
&[],
&cli_options,
);
(config, metadata)
};
ensure_init(
&tauri_config,
config.app(),
config.project_dir(),
MobileTarget::Android,
std::env::var("CI").is_ok(),
)?;
if !cli_options.config.is_empty() {
crate::helpers::config::merge_with(
&cli_options
.config
.iter()
.map(|conf| &conf.0)
.collect::<Vec<_>>(),
)?;
}
let env = env(std::env::var("CI").is_ok())?;
if cli_options.dev {
let dev_url = tauri_config
.lock()
.unwrap()
.as_ref()
.unwrap()
.build
.dev_url
.clone();
if let Some(url) = dev_url {
let localhost = match url.host() {
Some(url::Host::Domain(d)) => d == "localhost",
Some(url::Host::Ipv4(i)) => i == std::net::Ipv4Addr::LOCALHOST,
_ => false,
};
if localhost {
if let Some(port) = url.port_or_known_default() {
adb_forward_port(port, &env, &cli_options)?;
}
}
}
}
let mut validated_lib = false;
let installed_targets =
crate::interface::rust::installation::installed_targets().unwrap_or_default();
call_for_targets_with_fallback(
options.targets.unwrap_or_default().iter(),
&detect_target_ok,
&env,
|target: &Target| {
if !installed_targets.contains(&target.triple().into()) {
log::info!("Installing target {}", target.triple());
target
.install()
.map_err(|error| Error::CommandFailed {
command: "rustup target add".to_string(),
error,
})
.context("failed to install target")?;
}
target
.build(
&config,
&metadata,
&env,
cli_options.noise_level,
true,
profile,
)
.context("failed to build Android app")?;
if !validated_lib {
validated_lib = true;
let lib_path = config
.app()
.target_dir(target.triple, profile)
.join(config.so_name());
validate_lib(&lib_path).context("failed to validate library")?;
}
Ok(())
},
)
.map_err(|e| Error::GenericError(e.to_string()))?
}
fn validate_lib(path: &Path) -> Result<()> {
let so_bytes = std::fs::read(path).fs_context("failed to read library", path.to_path_buf())?;
let elf = elf::ElfBytes::<elf::endian::AnyEndian>::minimal_parse(&so_bytes)
.context("failed to parse ELF")?;
let (symbol_table, string_table) = elf
.dynamic_symbol_table()
.context("failed to read dynsym section")?
.context("missing dynsym tables")?;
let mut symbols = Vec::new();
for s in symbol_table.iter() {
if let Ok(symbol) = string_table.get(s.st_name as usize) {
symbols.push(symbol);
}
}
if !symbols.contains(&"Java_app_tauri_plugin_PluginManager_handlePluginResponse") {
crate::error::bail!(
"Library from {} does not include required runtime symbols. This means you are likely missing the tauri::mobile_entry_point macro usage, see the documentation for more information: https://v2.tauri.app/start/migrate/from-tauri-1",
path.display()
);
}
Ok(())
}
fn adb_forward_port(
port: u16,
env: &cargo_mobile2::android::env::Env,
cli_options: &CliOptions,
) -> Result<()> {
let forward = format!("tcp:{port}");
log::info!("Forwarding port {port} with adb");
let mut devices = adb::device_list(env).unwrap_or_default();
// if we could not detect any running device, let's wait a few seconds, it might be booting up
if devices.is_empty() {
log::warn!(
"ADB device list is empty, waiting a few seconds to see if there's any booting device..."
);
let max = 5;
let mut count = 0;
loop {
std::thread::sleep(std::time::Duration::from_secs(1));
devices = adb::device_list(env).unwrap_or_default();
if !devices.is_empty() {
break;
}
count += 1;
if count == max {
break;
}
}
}
let target_device = if let Some(target_device) = &cli_options.target_device {
Some((target_device.id.clone(), target_device.name.clone()))
} else if devices.len() == 1 {
let device = devices.first().unwrap();
Some((device.serial_no().to_string(), device.name().to_string()))
} else if devices.len() > 1 {
crate::error::bail!("Multiple Android devices are connected ({}), please disconnect devices you do not intend to use so Tauri can determine which to use",
devices.iter().map(|d| d.name()).collect::<Vec<_>>().join(", "));
} else {
// when building the app without running to a device, we might have an empty devices list
None
};
if let Some((target_device_serial_no, target_device_name)) = target_device {
let mut already_forwarded = false;
// clear port forwarding for all devices
for device in &devices {
let reverse_list_output =
adb_reverse_list(env, device.serial_no()).map_err(|error| Error::CommandFailed {
command: "adb reverse --list".to_string(),
error,
})?;
// check if the device has the port forwarded
if String::from_utf8_lossy(&reverse_list_output.stdout).contains(&forward) {
// device matches our target, we can skip forwarding
if device.serial_no() == target_device_serial_no {
log::debug!(
"device {} already has the forward for {}",
device.name(),
forward
);
already_forwarded = true;
}
break;
}
}
// if there's a known target, we should forward the port to it
if already_forwarded {
log::info!("{forward} already forwarded to {target_device_name}");
} else {
loop {
run_adb_reverse(env, &target_device_serial_no, &forward, &forward).map_err(|error| {
Error::CommandFailed {
command: format!("adb reverse {forward} {forward}"),
error,
}
})?;
let reverse_list_output =
adb_reverse_list(env, &target_device_serial_no).map_err(|error| {
Error::CommandFailed {
command: "adb reverse --list".to_string(),
error,
}
})?;
// wait and retry until the port has actually been forwarded
if String::from_utf8_lossy(&reverse_list_output.stdout).contains(&forward) {
break;
} else {
log::warn!(
"waiting for the port to be forwarded to {}...",
target_device_name
);
std::thread::sleep(std::time::Duration::from_secs(1));
}
}
}
} else {
log::warn!("no running devices detected with ADB; skipping port forwarding");
}
Ok(())
}
fn run_adb_reverse(
env: &cargo_mobile2::android::env::Env,
device_serial_no: &str,
remote: &str,
local: &str,
) -> std::io::Result<std::process::Output> {
adb::adb(env, ["-s", device_serial_no, "reverse", remote, local])
.stdin_file(os_pipe::dup_stdin().unwrap())
.stdout_file(os_pipe::dup_stdout().unwrap())
.stderr_file(os_pipe::dup_stdout().unwrap())
.run()
}
fn adb_reverse_list(
env: &cargo_mobile2::android::env::Env,
device_serial_no: &str,
) -> std::io::Result<std::process::Output> {
adb::adb(env, ["-s", device_serial_no, "reverse", "--list"])
.stdin_file(os_pipe::dup_stdin().unwrap())
.stdout_capture()
.stderr_capture()
.run()
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/mobile/android/build.rs | crates/tauri-cli/src/mobile/android/build.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use super::{
configure_cargo, delete_codegen_vars, ensure_init, env, get_app, get_config, inject_resources,
log_finished, open_and_wait, MobileTarget, OptionsHandle,
};
use crate::{
build::Options as BuildOptions,
error::Context,
helpers::{
app_paths::tauri_dir,
config::{get as get_tauri_config, ConfigHandle},
flock,
},
interface::{AppInterface, Interface, Options as InterfaceOptions},
mobile::{android::generate_tauri_properties, write_options, CliOptions, TargetDevice},
ConfigValue, Error, Result,
};
use clap::{ArgAction, Parser};
use cargo_mobile2::{
android::{aab, apk, config::Config as AndroidConfig, env::Env, target::Target},
opts::{NoiseLevel, Profile},
target::TargetTrait,
};
use std::env::set_current_dir;
#[derive(Debug, Clone, Parser)]
#[clap(
about = "Build your app in release mode for Android and generate APKs and AABs",
long_about = "Build your app in release mode for Android and generate APKs and AABs. It makes use of the `build.frontendDist` property from your `tauri.conf.json` file. It also runs your `build.beforeBuildCommand` which usually builds your frontend into `build.frontendDist`."
)]
pub struct Options {
/// Builds with the debug flag
#[clap(short, long)]
pub debug: bool,
/// Which targets to build (all by default).
#[clap(
short,
long = "target",
action = ArgAction::Append,
num_args(0..),
value_parser(clap::builder::PossibleValuesParser::new(Target::name_list()))
)]
pub targets: Option<Vec<String>>,
/// List of cargo features to activate
#[clap(short, long, action = ArgAction::Append, num_args(0..))]
pub features: Vec<String>,
/// JSON strings or paths to JSON, JSON5 or TOML files to merge with the default configuration file
///
/// Configurations are merged in the order they are provided, which means a particular value overwrites previous values when a config key-value pair conflicts.
///
/// Note that a platform-specific file is looked up and merged with the default file by default
/// (tauri.macos.conf.json, tauri.linux.conf.json, tauri.windows.conf.json, tauri.android.conf.json and tauri.ios.conf.json)
/// but you can use this for more specific use cases such as different build flavors.
#[clap(short, long)]
pub config: Vec<ConfigValue>,
/// Whether to split the APKs and AABs per ABIs.
#[clap(long)]
pub split_per_abi: bool,
/// Build APKs.
#[clap(long)]
pub apk: Option<bool>,
/// Build AABs.
#[clap(long)]
pub aab: Option<bool>,
/// Open Android Studio
#[clap(short, long)]
pub open: bool,
/// Skip prompting for values
#[clap(long, env = "CI")]
pub ci: bool,
/// Command line arguments passed to the runner.
/// Use `--` to explicitly mark the start of the arguments.
/// e.g. `tauri android build -- [runnerArgs]`.
#[clap(last(true))]
pub args: Vec<String>,
/// Do not error out if a version mismatch is detected on a Tauri package.
///
/// Only use this when you are sure the mismatch is incorrectly detected as version mismatched Tauri packages can lead to unknown behavior.
#[clap(long)]
pub ignore_version_mismatches: bool,
/// Target device of this build
#[clap(skip)]
pub target_device: Option<TargetDevice>,
}
impl From<Options> for BuildOptions {
fn from(options: Options) -> Self {
Self {
runner: None,
debug: options.debug,
target: None,
features: options.features,
bundles: None,
no_bundle: false,
config: options.config,
args: options.args,
ci: options.ci,
skip_stapling: false,
ignore_version_mismatches: options.ignore_version_mismatches,
no_sign: false,
}
}
}
pub struct BuiltApplication {
pub config: AndroidConfig,
pub interface: AppInterface,
// prevent drop
#[allow(dead_code)]
options_handle: OptionsHandle,
}
pub fn command(options: Options, noise_level: NoiseLevel) -> Result<BuiltApplication> {
crate::helpers::app_paths::resolve();
delete_codegen_vars();
let mut build_options: BuildOptions = options.clone().into();
let first_target = Target::all()
.get(
options
.targets
.as_ref()
.and_then(|l| l.first().map(|t| t.as_str()))
.unwrap_or(Target::DEFAULT_KEY),
)
.unwrap();
build_options.target = Some(first_target.triple.into());
let tauri_config = get_tauri_config(
tauri_utils::platform::Target::Android,
&options
.config
.iter()
.map(|conf| &conf.0)
.collect::<Vec<_>>(),
)?;
let (interface, config, metadata) = {
let tauri_config_guard = tauri_config.lock().unwrap();
let tauri_config_ = tauri_config_guard.as_ref().unwrap();
let interface = AppInterface::new(tauri_config_, build_options.target.clone())?;
interface.build_options(&mut Vec::new(), &mut build_options.features, true);
let app = get_app(MobileTarget::Android, tauri_config_, &interface);
let (config, metadata) = get_config(
&app,
tauri_config_,
&build_options.features,
&Default::default(),
);
(interface, config, metadata)
};
let profile = if options.debug {
Profile::Debug
} else {
Profile::Release
};
let tauri_path = tauri_dir();
set_current_dir(tauri_path).context("failed to set current directory to Tauri directory")?;
ensure_init(
&tauri_config,
config.app(),
config.project_dir(),
MobileTarget::Android,
options.ci,
)?;
let mut env = env(options.ci)?;
configure_cargo(&mut env, &config)?;
generate_tauri_properties(
&config,
tauri_config.lock().unwrap().as_ref().unwrap(),
false,
)?;
{
let config_guard = tauri_config.lock().unwrap();
let config_ = config_guard.as_ref().unwrap();
crate::build::setup(&interface, &mut build_options, config_, true)?;
}
let installed_targets =
crate::interface::rust::installation::installed_targets().unwrap_or_default();
if !installed_targets.contains(&first_target.triple().into()) {
log::info!("Installing target {}", first_target.triple());
first_target
.install()
.map_err(|error| Error::CommandFailed {
command: "rustup target add".to_string(),
error,
})
.context("failed to install target")?;
}
// run an initial build to initialize plugins
first_target
.build(&config, &metadata, &env, noise_level, true, profile)
.context("failed to build Android app")?;
let open = options.open;
let options_handle = run_build(
&interface,
options,
build_options,
tauri_config,
profile,
&config,
&mut env,
noise_level,
)?;
if open {
open_and_wait(&config, &env);
}
Ok(BuiltApplication {
config,
interface,
options_handle,
})
}
#[allow(clippy::too_many_arguments)]
fn run_build(
interface: &AppInterface,
mut options: Options,
build_options: BuildOptions,
tauri_config: ConfigHandle,
profile: Profile,
config: &AndroidConfig,
env: &mut Env,
noise_level: NoiseLevel,
) -> Result<OptionsHandle> {
if !(options.apk.is_some() || options.aab.is_some()) {
// if the user didn't specify the format to build, we'll do both
options.apk = Some(true);
options.aab = Some(true);
}
let interface_options = InterfaceOptions {
debug: build_options.debug,
target: build_options.target.clone(),
args: build_options.args.clone(),
..Default::default()
};
let app_settings = interface.app_settings();
let out_dir = app_settings.out_dir(&interface_options)?;
let _lock = flock::open_rw(out_dir.join("lock").with_extension("android"), "Android")?;
let cli_options = CliOptions {
dev: false,
features: build_options.features.clone(),
args: build_options.args.clone(),
noise_level,
vars: Default::default(),
config: build_options.config,
target_device: options.target_device.clone(),
};
let handle = write_options(tauri_config.lock().unwrap().as_ref().unwrap(), cli_options)?;
inject_resources(config, tauri_config.lock().unwrap().as_ref().unwrap())?;
let apk_outputs = if options.apk.unwrap_or_default() {
apk::build(
config,
env,
noise_level,
profile,
get_targets_or_all(options.targets.clone().unwrap_or_default())?,
options.split_per_abi,
)
.context("failed to build APK")?
} else {
Vec::new()
};
let aab_outputs = if options.aab.unwrap_or_default() {
aab::build(
config,
env,
noise_level,
profile,
get_targets_or_all(options.targets.unwrap_or_default())?,
options.split_per_abi,
)
.context("failed to build AAB")?
} else {
Vec::new()
};
if !apk_outputs.is_empty() {
log_finished(apk_outputs, "APK");
}
if !aab_outputs.is_empty() {
log_finished(aab_outputs, "AAB");
}
Ok(handle)
}
fn get_targets_or_all<'a>(targets: Vec<String>) -> Result<Vec<&'a Target<'a>>> {
if targets.is_empty() {
Ok(Target::all().iter().map(|t| t.1).collect())
} else {
let mut outs = Vec::new();
let possible_targets = Target::all()
.keys()
.map(|key| key.to_string())
.collect::<Vec<String>>()
.join(",");
for t in targets {
let target = Target::for_name(&t).with_context(|| {
format!("Target {t} is invalid; the possible targets are {possible_targets}",)
})?;
outs.push(target);
}
Ok(outs)
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/mobile/android/mod.rs | crates/tauri-cli/src/mobile/android/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use cargo_mobile2::{
android::{
adb,
config::{Config as AndroidConfig, Metadata as AndroidMetadata, Raw as RawAndroidConfig},
device::Device,
emulator,
env::Env,
target::Target,
},
config::app::{App, DEFAULT_ASSET_DIR},
opts::{FilterLevel, NoiseLevel},
os,
target::TargetTrait,
util::prompt,
};
use clap::{Parser, Subcommand};
use semver::Version;
use std::{
env::set_var,
fs::{create_dir, create_dir_all, read_dir, write},
io::Cursor,
path::{Path, PathBuf},
process::{exit, Command},
thread::sleep,
time::Duration,
};
use sublime_fuzzy::best_match;
use tauri_utils::resources::ResourcePaths;
use super::{
ensure_init, get_app, init::command as init_command, log_finished, read_options, CliOptions,
OptionsHandle, Target as MobileTarget, MIN_DEVICE_MATCH_SCORE,
};
use crate::{
error::Context,
helpers::config::{BundleResources, Config as TauriConfig},
ConfigValue, Error, ErrorExt, Result,
};
mod android_studio_script;
mod build;
mod dev;
pub(crate) mod project;
mod run;
const NDK_VERSION: &str = "29.0.13846066";
const SDK_VERSION: u8 = 36;
#[cfg(target_os = "macos")]
const CMDLINE_TOOLS_URL: &str =
"https://dl.google.com/android/repository/commandlinetools-mac-13114758_latest.zip";
#[cfg(target_os = "linux")]
const CMDLINE_TOOLS_URL: &str =
"https://dl.google.com/android/repository/commandlinetools-linux-13114758_latest.zip";
#[cfg(windows)]
const CMDLINE_TOOLS_URL: &str =
"https://dl.google.com/android/repository/commandlinetools-win-13114758_latest.zip";
#[derive(Parser)]
#[clap(
author,
version,
about = "Android commands",
subcommand_required(true),
arg_required_else_help(true)
)]
pub struct Cli {
#[clap(subcommand)]
command: Commands,
}
#[derive(Debug, Parser)]
#[clap(about = "Initialize Android target in the project")]
pub struct InitOptions {
/// Skip prompting for values
#[clap(long, env = "CI")]
ci: bool,
/// Skips installing rust toolchains via rustup
#[clap(long)]
skip_targets_install: bool,
/// JSON strings or paths to JSON, JSON5 or TOML files to merge with the default configuration file
///
/// Configurations are merged in the order they are provided, which means a particular value overwrites previous values when a config key-value pair conflicts.
///
/// Note that a platform-specific file is looked up and merged with the default file by default
/// (tauri.macos.conf.json, tauri.linux.conf.json, tauri.windows.conf.json, tauri.android.conf.json and tauri.ios.conf.json)
/// but you can use this for more specific use cases such as different build flavors.
#[clap(short, long)]
pub config: Vec<ConfigValue>,
}
#[derive(Subcommand)]
enum Commands {
Init(InitOptions),
Dev(dev::Options),
Build(build::Options),
Run(run::Options),
#[clap(hide(true))]
AndroidStudioScript(android_studio_script::Options),
}
pub fn command(cli: Cli, verbosity: u8) -> Result<()> {
let noise_level = NoiseLevel::from_occurrences(verbosity as u64);
match cli.command {
Commands::Init(options) => {
crate::helpers::app_paths::resolve();
init_command(
MobileTarget::Android,
options.ci,
false,
options.skip_targets_install,
options.config,
)?
}
Commands::Dev(options) => dev::command(options, noise_level)?,
Commands::Build(options) => build::command(options, noise_level).map(|_| ())?,
Commands::Run(options) => run::command(options, noise_level)?,
Commands::AndroidStudioScript(options) => android_studio_script::command(options)?,
}
Ok(())
}
pub fn get_config(
app: &App,
config: &TauriConfig,
features: &[String],
cli_options: &CliOptions,
) -> (AndroidConfig, AndroidMetadata) {
let mut android_options = cli_options.clone();
android_options.features.extend_from_slice(features);
let raw = RawAndroidConfig {
features: Some(android_options.features.clone()),
logcat_filter_specs: vec![
"RustStdoutStderr".into(),
format!(
"*:{}",
match cli_options.noise_level {
NoiseLevel::Polite => FilterLevel::Info,
NoiseLevel::LoudAndProud => FilterLevel::Debug,
NoiseLevel::FranklyQuitePedantic => FilterLevel::Verbose,
}
.logcat()
),
],
min_sdk_version: Some(config.bundle.android.min_sdk_version),
..Default::default()
};
let config = AndroidConfig::from_raw(app.clone(), Some(raw)).unwrap();
let metadata = AndroidMetadata {
supported: true,
cargo_args: Some(android_options.args),
features: Some(android_options.features),
..Default::default()
};
set_var(
"WRY_ANDROID_PACKAGE",
app.android_identifier_escape_kotlin_keyword(),
);
set_var("TAURI_ANDROID_PACKAGE_UNESCAPED", app.identifier());
set_var("WRY_ANDROID_LIBRARY", app.lib_name());
set_var("TAURI_ANDROID_PROJECT_PATH", config.project_dir());
let src_main_dir = config
.project_dir()
.join("app/src/main")
.join(format!("java/{}", app.identifier().replace('.', "/"),));
if config.project_dir().exists() {
if src_main_dir.exists() {
let _ = create_dir(src_main_dir.join("generated"));
} else {
log::error!(
"Project directory {} does not exist. Did you update the package name in `Cargo.toml` or the bundle identifier in `tauri.conf.json > identifier`? Save your changes, delete the `gen/android` folder and run `tauri android init` to recreate the Android project.",
src_main_dir.display()
);
exit(1);
}
}
set_var(
"WRY_ANDROID_KOTLIN_FILES_OUT_DIR",
src_main_dir.join("generated"),
);
(config, metadata)
}
pub fn env(non_interactive: bool) -> Result<Env> {
let env = super::env().context("failed to setup Android environment")?;
ensure_env(non_interactive).context("failed to ensure Android environment")?;
cargo_mobile2::android::env::Env::from_env(env).context("failed to load Android environment")
}
fn download_cmdline_tools(extract_path: &Path) -> Result<()> {
log::info!("Downloading Android command line tools...");
let mut response = crate::helpers::http::get(CMDLINE_TOOLS_URL)
.context("failed to download Android command line tools")?;
let body = response
.body_mut()
.with_config()
.limit(200 * 1024 * 1024 /* 200MB */)
.read_to_vec()
.context("failed to read Android command line tools download response")?;
let mut zip = zip::ZipArchive::new(Cursor::new(body))
.context("failed to create zip archive from Android command line tools download response")?;
log::info!(
"Extracting Android command line tools to {}",
extract_path.display()
);
zip
.extract(extract_path)
.context("failed to extract Android command line tools")?;
Ok(())
}
fn ensure_env(non_interactive: bool) -> Result<()> {
ensure_java()?;
ensure_sdk(non_interactive)?;
ensure_ndk(non_interactive)?;
Ok(())
}
fn ensure_java() -> Result<()> {
if std::env::var_os("JAVA_HOME").is_none() {
#[cfg(windows)]
let default_java_home = "C:\\Program Files\\Android\\Android Studio\\jbr";
#[cfg(target_os = "macos")]
let default_java_home = "/Applications/Android Studio.app/Contents/jbr/Contents/Home";
#[cfg(target_os = "linux")]
let default_java_home = "/opt/android-studio/jbr";
if Path::new(default_java_home).exists() {
log::info!("Using Android Studio's default Java installation: {default_java_home}");
std::env::set_var("JAVA_HOME", default_java_home);
} else if which::which("java").is_err() {
crate::error::bail!("Java not found in PATH, default Android Studio Java installation not found at {default_java_home} and JAVA_HOME environment variable not set. Please install Java before proceeding");
}
}
Ok(())
}
fn ensure_sdk(non_interactive: bool) -> Result<()> {
let android_home = std::env::var_os("ANDROID_HOME")
.or_else(|| std::env::var_os("ANDROID_SDK_ROOT"))
.map(PathBuf::from);
if !android_home.as_ref().is_some_and(|v| v.exists()) {
log::info!(
"ANDROID_HOME {}, trying to locate Android SDK...",
if let Some(v) = &android_home {
format!("not found at {}", v.display())
} else {
"not set".into()
}
);
#[cfg(target_os = "macos")]
let default_android_home = dirs::home_dir().unwrap().join("Library/Android/sdk");
#[cfg(target_os = "linux")]
let default_android_home = dirs::home_dir().unwrap().join("Android/Sdk");
#[cfg(windows)]
let default_android_home = dirs::data_local_dir().unwrap().join("Android/Sdk");
if default_android_home.exists() {
log::info!(
"Using installed Android SDK: {}",
default_android_home.display()
);
} else if non_interactive {
crate::error::bail!("Android SDK not found. Make sure the SDK and NDK are installed and the ANDROID_HOME and NDK_HOME environment variables are set.");
} else {
log::error!(
"Android SDK not found at {}",
default_android_home.display()
);
let extract_path = if create_dir_all(&default_android_home).is_ok() {
default_android_home.clone()
} else {
std::env::current_dir().context("failed to get current directory")?
};
let sdk_manager_path = extract_path
.join("cmdline-tools/bin/sdkmanager")
.with_extension(if cfg!(windows) { "bat" } else { "" });
let mut granted_permission_to_install = false;
if !sdk_manager_path.exists() {
granted_permission_to_install = crate::helpers::prompts::confirm(
"Do you want to install the Android Studio command line tools to setup the Android SDK?",
Some(false),
)
.unwrap_or_default();
if !granted_permission_to_install {
crate::error::bail!("Skipping Android Studio command line tools installation. Please go through the manual setup process described in the documentation: https://tauri.app/start/prerequisites/#android");
}
download_cmdline_tools(&extract_path)?;
}
if !granted_permission_to_install {
granted_permission_to_install = crate::helpers::prompts::confirm(
"Do you want to install the Android SDK using the command line tools?",
Some(false),
)
.unwrap_or_default();
if !granted_permission_to_install {
crate::error::bail!("Skipping Android Studio SDK installation. Please go through the manual setup process described in the documentation: https://tauri.app/start/prerequisites/#android");
}
}
log::info!("Running sdkmanager to install platform-tools, android-{SDK_VERSION} and ndk-{NDK_VERSION} on {}...", default_android_home.display());
let status = Command::new(&sdk_manager_path)
.arg(format!("--sdk_root={}", default_android_home.display()))
.arg("--install")
.arg("platform-tools")
.arg(format!("platforms;android-{SDK_VERSION}"))
.arg(format!("ndk;{NDK_VERSION}"))
.status()
.map_err(|error| Error::CommandFailed {
command: format!("{} --sdk_root={} --install platform-tools platforms;android-{SDK_VERSION} ndk;{NDK_VERSION}", sdk_manager_path.display(), default_android_home.display()),
error,
})?;
if !status.success() {
crate::error::bail!("Failed to install Android SDK");
}
}
std::env::set_var("ANDROID_HOME", default_android_home);
}
Ok(())
}
fn ensure_ndk(non_interactive: bool) -> Result<()> {
// re-evaluate ANDROID_HOME
let android_home = std::env::var_os("ANDROID_HOME")
.or_else(|| std::env::var_os("ANDROID_SDK_ROOT"))
.map(PathBuf::from)
.context("Failed to locate Android SDK")?;
let mut installed_ndks = read_dir(android_home.join("ndk"))
.map(|dir| {
dir
.into_iter()
.flat_map(|e| e.ok().map(|e| e.path()))
.collect::<Vec<_>>()
})
.unwrap_or_default();
installed_ndks.sort();
if let Some(ndk) = installed_ndks.last() {
log::info!("Using installed NDK: {}", ndk.display());
std::env::set_var("NDK_HOME", ndk);
} else if non_interactive {
crate::error::bail!("Android NDK not found. Make sure the NDK is installed and the NDK_HOME environment variable is set.");
} else {
let sdk_manager_path = android_home
.join("cmdline-tools/bin/sdkmanager")
.with_extension(if cfg!(windows) { "bat" } else { "" });
let mut granted_permission_to_install = false;
if !sdk_manager_path.exists() {
granted_permission_to_install = crate::helpers::prompts::confirm(
"Do you want to install the Android Studio command line tools to setup the Android NDK?",
Some(false),
)
.unwrap_or_default();
if !granted_permission_to_install {
crate::error::bail!("Skipping Android Studio command line tools installation. Please go through the manual setup process described in the documentation: https://tauri.app/start/prerequisites/#android");
}
download_cmdline_tools(&android_home)?;
}
if !granted_permission_to_install {
granted_permission_to_install = crate::helpers::prompts::confirm(
"Do you want to install the Android NDK using the command line tools?",
Some(false),
)
.unwrap_or_default();
if !granted_permission_to_install {
crate::error::bail!("Skipping Android Studio NDK installation. Please go through the manual setup process described in the documentation: https://tauri.app/start/prerequisites/#android");
}
}
log::info!(
"Running sdkmanager to install ndk-{NDK_VERSION} on {}...",
android_home.display()
);
let status = Command::new(&sdk_manager_path)
.arg(format!("--sdk_root={}", android_home.display()))
.arg("--install")
.arg(format!("ndk;{NDK_VERSION}"))
.status()
.map_err(|error| Error::CommandFailed {
command: format!(
"{} --sdk_root={} --install ndk;{NDK_VERSION}",
sdk_manager_path.display(),
android_home.display()
),
error,
})?;
if !status.success() {
crate::error::bail!("Failed to install Android NDK");
}
let ndk_path = android_home.join("ndk").join(NDK_VERSION);
log::info!("Installed NDK: {}", ndk_path.display());
std::env::set_var("NDK_HOME", ndk_path);
}
Ok(())
}
fn delete_codegen_vars() {
for (k, _) in std::env::vars() {
if k.starts_with("WRY_") && (k.ends_with("CLASS_EXTENSION") || k.ends_with("CLASS_INIT")) {
std::env::remove_var(k);
}
}
}
fn adb_device_prompt<'a>(env: &'_ Env, target: Option<&str>) -> Result<Device<'a>> {
let device_list = adb::device_list(env).context("failed to detect connected Android devices")?;
if !device_list.is_empty() {
let device = if let Some(t) = target {
let (device, score) = device_list
.into_iter()
.rev()
.map(|d| {
let score = best_match(t, d.name()).map_or(0, |m| m.score());
(d, score)
})
.max_by_key(|(_, score)| *score)
// we already checked the list is not empty
.unwrap();
if score > MIN_DEVICE_MATCH_SCORE {
device
} else {
crate::error::bail!("Could not find an Android device matching {t}")
}
} else if device_list.len() > 1 {
let index = prompt::list(
concat!("Detected ", "Android", " devices"),
device_list.iter(),
"device",
None,
"Device",
)
.context("failed to prompt for device")?;
device_list.into_iter().nth(index).unwrap()
} else {
device_list.into_iter().next().unwrap()
};
log::info!(
"Detected connected device: {} with target {:?}",
device,
device.target().triple,
);
Ok(device)
} else {
Err(Error::GenericError(
"No connected Android devices detected".to_string(),
))
}
}
fn emulator_prompt(env: &'_ Env, target: Option<&str>) -> Result<emulator::Emulator> {
let emulator_list = emulator::avd_list(env).unwrap_or_default();
if !emulator_list.is_empty() {
let emulator = if let Some(t) = target {
let (device, score) = emulator_list
.into_iter()
.rev()
.map(|d| {
let score = best_match(t, d.name()).map_or(0, |m| m.score());
(d, score)
})
.max_by_key(|(_, score)| *score)
// we already checked the list is not empty
.unwrap();
if score > MIN_DEVICE_MATCH_SCORE {
device
} else {
crate::error::bail!("Could not find an Android Emulator matching {t}")
}
} else if emulator_list.len() > 1 {
let index = prompt::list(
concat!("Detected ", "Android", " emulators"),
emulator_list.iter(),
"emulator",
None,
"Emulator",
)
.context("failed to prompt for emulator")?;
emulator_list.into_iter().nth(index).unwrap()
} else {
emulator_list.into_iter().next().unwrap()
};
Ok(emulator)
} else {
Err(Error::GenericError(
"No available Android Emulator detected".to_string(),
))
}
}
fn device_prompt<'a>(env: &'_ Env, target: Option<&str>) -> Result<Device<'a>> {
if let Ok(device) = adb_device_prompt(env, target) {
Ok(device)
} else {
let emulator = emulator_prompt(env, target)?;
log::info!("Starting emulator {}", emulator.name());
emulator
.start_detached(env)
.context("failed to start emulator")?;
let mut tries = 0;
loop {
sleep(Duration::from_secs(2));
if let Ok(device) = adb_device_prompt(env, Some(emulator.name())) {
return Ok(device);
}
if tries >= 3 {
log::info!("Waiting for emulator to start... (maybe the emulator is unauthorized or offline, run `adb devices` to check)");
} else {
log::info!("Waiting for emulator to start...");
}
tries += 1;
}
}
}
fn detect_target_ok<'a>(env: &Env) -> Option<&'a Target<'a>> {
device_prompt(env, None).map(|device| device.target()).ok()
}
fn open_and_wait(config: &AndroidConfig, env: &Env) -> ! {
log::info!("Opening Android Studio");
if let Err(e) = os::open_file_with("Android Studio", config.project_dir(), &env.base) {
log::error!("{e}");
}
loop {
sleep(Duration::from_secs(24 * 60 * 60));
}
}
fn inject_resources(config: &AndroidConfig, tauri_config: &TauriConfig) -> Result<()> {
let asset_dir = config
.project_dir()
.join("app/src/main")
.join(DEFAULT_ASSET_DIR);
create_dir_all(&asset_dir).fs_context("failed to create asset directory", asset_dir.clone())?;
write(
asset_dir.join("tauri.conf.json"),
serde_json::to_string(&tauri_config).with_context(|| "failed to serialize tauri config")?,
)
.fs_context(
"failed to write tauri config",
asset_dir.join("tauri.conf.json"),
)?;
let resources = match &tauri_config.bundle.resources {
Some(BundleResources::List(paths)) => Some(ResourcePaths::new(paths.as_slice(), true)),
Some(BundleResources::Map(map)) => Some(ResourcePaths::from_map(map, true)),
None => None,
};
if let Some(resources) = resources {
for resource in resources.iter() {
let resource = resource.context("failed to get resource")?;
let dest = asset_dir.join(resource.target());
crate::helpers::fs::copy_file(resource.path(), dest).context("failed to copy resource")?;
}
}
Ok(())
}
fn configure_cargo(env: &mut Env, config: &AndroidConfig) -> Result<()> {
for target in Target::all().values() {
let config = target
.generate_cargo_config(config, env)
.context("failed to find Android tool")?;
let target_var_name = target.triple.replace('-', "_").to_uppercase();
if let Some(linker) = config.linker {
env.base.insert_env_var(
format!("CARGO_TARGET_{target_var_name}_LINKER"),
linker.into(),
);
}
env.base.insert_env_var(
format!("CARGO_TARGET_{target_var_name}_RUSTFLAGS"),
config.rustflags.join(" ").into(),
);
}
Ok(())
}
fn generate_tauri_properties(
config: &AndroidConfig,
tauri_config: &TauriConfig,
dev: bool,
) -> Result<()> {
let app_tauri_properties_path = config.project_dir().join("app").join("tauri.properties");
let mut app_tauri_properties = Vec::new();
if let Some(version) = tauri_config.version.as_ref() {
app_tauri_properties.push(format!("tauri.android.versionName={version}"));
if tauri_config.bundle.android.auto_increment_version_code && !dev {
let last_version_code = std::fs::read_to_string(&app_tauri_properties_path)
.ok()
.and_then(|content| {
content
.lines()
.find(|line| line.starts_with("tauri.android.versionCode="))
.and_then(|line| line.split('=').nth(1))
.and_then(|s| s.trim().parse::<u32>().ok())
});
let new_version_code = last_version_code.map(|v| v.saturating_add(1)).unwrap_or(1);
app_tauri_properties.push(format!("tauri.android.versionCode={new_version_code}"));
} else if let Some(version_code) = tauri_config.bundle.android.version_code.as_ref() {
app_tauri_properties.push(format!("tauri.android.versionCode={version_code}"));
} else if let Ok(version) = Version::parse(version) {
let mut version_code = version.major * 1000000 + version.minor * 1000 + version.patch;
if dev {
version_code = version_code.clamp(1, 2100000000);
}
if version_code == 0 {
crate::error::bail!(
"You must change the `version` in `tauri.conf.json`. The default value `0.0.0` is not allowed for Android package and must be at least `0.0.1`."
);
} else if version_code > 2100000000 {
crate::error::bail!(
"Invalid version code {}. Version code must be between 1 and 2100000000. You must change the `version` in `tauri.conf.json`.",
version_code
);
}
app_tauri_properties.push(format!("tauri.android.versionCode={version_code}"));
}
}
if !app_tauri_properties.is_empty() {
let app_tauri_properties_content = format!(
"// THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.\n{}",
app_tauri_properties.join("\n")
);
if std::fs::read_to_string(&app_tauri_properties_path)
.map(|o| o != app_tauri_properties_content)
.unwrap_or(true)
{
write(&app_tauri_properties_path, app_tauri_properties_content)
.context("failed to write tauri.properties")?;
}
}
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/mobile/android/run.rs | crates/tauri-cli/src/mobile/android/run.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use cargo_mobile2::{
android::target::Target,
opts::{FilterLevel, NoiseLevel, Profile},
target::TargetTrait,
};
use clap::{ArgAction, Parser};
use std::path::PathBuf;
use super::{configure_cargo, device_prompt, env};
use crate::{
error::Context,
interface::{DevProcess, Interface, WatcherOptions},
mobile::{DevChild, TargetDevice},
ConfigValue, Result,
};
#[derive(Debug, Clone, Parser)]
#[clap(
about = "Run your app in production mode on Android",
long_about = "Run your app in production mode on Android. It makes use of the `build.frontendDist` property from your `tauri.conf.json` file. It also runs your `build.beforeBuildCommand` which usually builds your frontend into `build.frontendDist`."
)]
pub struct Options {
/// Run the app in release mode
#[clap(short, long)]
pub release: bool,
/// List of cargo features to activate
#[clap(short, long, action = ArgAction::Append, num_args(0..))]
pub features: Vec<String>,
/// JSON strings or paths to JSON, JSON5 or TOML files to merge with the default configuration file
///
/// Configurations are merged in the order they are provided, which means a particular value overwrites previous values when a config key-value pair conflicts.
///
/// Note that a platform-specific file is looked up and merged with the default file by default
/// (tauri.macos.conf.json, tauri.linux.conf.json, tauri.windows.conf.json, tauri.android.conf.json and tauri.ios.conf.json)
/// but you can use this for more specific use cases such as different build flavors.
#[clap(short, long)]
pub config: Vec<ConfigValue>,
/// Disable the file watcher
#[clap(long)]
pub no_watch: bool,
/// Additional paths to watch for changes.
#[clap(long)]
pub additional_watch_folders: Vec<PathBuf>,
/// Open Android Studio
#[clap(short, long)]
pub open: bool,
/// Runs on the given device name
pub device: Option<String>,
/// Command line arguments passed to the runner.
/// Use `--` to explicitly mark the start of the arguments.
/// e.g. `tauri android build -- [runnerArgs]`.
#[clap(last(true))]
pub args: Vec<String>,
/// Do not error out if a version mismatch is detected on a Tauri package.
///
/// Only use this when you are sure the mismatch is incorrectly detected as version mismatched Tauri packages can lead to unknown behavior.
#[clap(long)]
pub ignore_version_mismatches: bool,
}
pub fn command(options: Options, noise_level: NoiseLevel) -> Result<()> {
let mut env = env(false)?;
let device = if options.open {
None
} else {
match device_prompt(&env, options.device.as_deref()) {
Ok(d) => Some(d),
Err(e) => {
log::error!("{e}");
None
}
}
};
let mut built_application = super::build::command(
super::build::Options {
debug: !options.release,
targets: device.as_ref().map(|d| {
vec![Target::all()
.iter()
.find(|(_key, t)| t.arch == d.target().arch)
.map(|(key, _t)| key.to_string())
.expect("Target not found")]
}),
features: options.features,
config: options.config.clone(),
split_per_abi: true,
apk: Some(false),
aab: Some(false),
open: options.open,
ci: false,
args: options.args,
ignore_version_mismatches: options.ignore_version_mismatches,
target_device: device.as_ref().map(|d| TargetDevice {
id: d.serial_no().to_string(),
name: d.name().to_string(),
}),
},
noise_level,
)?;
configure_cargo(&mut env, &built_application.config)?;
// options.open is handled by the build command
// so all we need to do here is run the app on the selected device
if let Some(device) = device {
let config = built_application.config.clone();
let release = options.release;
let runner = move || {
device
.run(
&config,
&env,
noise_level,
if !release {
Profile::Debug
} else {
Profile::Release
},
Some(match noise_level {
NoiseLevel::Polite => FilterLevel::Info,
NoiseLevel::LoudAndProud => FilterLevel::Debug,
NoiseLevel::FranklyQuitePedantic => FilterLevel::Verbose,
}),
false,
false,
".MainActivity".into(),
)
.map(|c| Box::new(DevChild::new(c)) as Box<dyn DevProcess + Send>)
.context("failed to run Android app")
};
if options.no_watch {
runner()?;
} else {
built_application.interface.watch(
WatcherOptions {
config: options.config,
additional_watch_folders: options.additional_watch_folders,
},
runner,
)?;
}
}
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/mobile/android/project.rs | crates/tauri-cli/src/mobile/android/project.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{
error::{Context, ErrorExt},
helpers::template,
Error, Result,
};
use cargo_mobile2::{
android::{
config::{Config, Metadata},
target::Target,
},
config::app::DEFAULT_ASSET_DIR,
os,
target::TargetTrait as _,
util::{
self,
cli::{Report, TextWrapper},
prefix_path,
},
};
use handlebars::Handlebars;
use include_dir::{include_dir, Dir};
use std::{
ffi::OsStr,
fs,
path::{Path, PathBuf},
};
const TEMPLATE_DIR: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/templates/mobile/android");
pub fn gen(
config: &Config,
metadata: &Metadata,
(handlebars, mut map): (Handlebars, template::JsonMap),
wrapper: &TextWrapper,
skip_targets_install: bool,
) -> Result<()> {
if !skip_targets_install {
let installed_targets =
crate::interface::rust::installation::installed_targets().unwrap_or_default();
let missing_targets = Target::all()
.values()
.filter(|t| !installed_targets.contains(&t.triple().into()))
.collect::<Vec<&Target>>();
if !missing_targets.is_empty() {
log::info!("Installing Android Rust targets...");
for target in missing_targets {
log::info!("Installing target {}", target.triple());
target.install().map_err(|error| Error::CommandFailed {
command: "rustup target add".to_string(),
error,
})?;
}
}
}
println!("Generating Android Studio project...");
let dest = config.project_dir();
let asset_packs = metadata.asset_packs().unwrap_or_default();
map.insert(
"root-dir-rel",
Path::new(&os::replace_path_separator(
util::relativize_path(
config.app().root_dir(),
config.project_dir().join(config.app().name_snake()),
)
.into_os_string(),
)),
);
map.insert("root-dir", config.app().root_dir());
map.insert(
"abi-list",
Target::all()
.values()
.map(|target| target.abi)
.collect::<Vec<_>>(),
);
map.insert("target-list", Target::all().keys().collect::<Vec<_>>());
map.insert(
"arch-list",
Target::all()
.values()
.map(|target| target.arch)
.collect::<Vec<_>>(),
);
map.insert("android-app-plugins", metadata.app_plugins());
map.insert(
"android-project-dependencies",
metadata.project_dependencies(),
);
map.insert("android-app-dependencies", metadata.app_dependencies());
map.insert(
"android-app-dependencies-platform",
metadata.app_dependencies_platform(),
);
map.insert(
"has-code",
metadata.project_dependencies().is_some()
|| metadata.app_dependencies().is_some()
|| metadata.app_dependencies_platform().is_some(),
);
map.insert("has-asset-packs", !asset_packs.is_empty());
map.insert(
"asset-packs",
asset_packs
.iter()
.map(|p| p.name.as_str())
.collect::<Vec<_>>(),
);
map.insert("windows", cfg!(windows));
let identifier = config.app().identifier().replace('.', "/");
let package_path = format!("java/{identifier}");
map.insert("package-path", &package_path);
let mut created_dirs = Vec::new();
template::render_with_generator(
&handlebars,
map.inner(),
&TEMPLATE_DIR,
&dest,
&mut |path| generate_out_file(&path, &dest, &package_path, &mut created_dirs),
)
.with_context(|| "failed to process template")?;
if !asset_packs.is_empty() {
Report::action_request(
"When running from Android Studio, you must first set your deployment option to \"APK from app bundle\".",
"Android Studio will not be able to find your asset packs otherwise. The option can be found under \"Run > Edit Configurations > Deploy\"."
).print(wrapper);
}
let source_dest = dest.join("app");
for source in metadata.app_sources() {
let source_src = config.app().root_dir().join(source);
let source_file = source_src
.file_name()
.with_context(|| format!("asset source {} is invalid", source_src.display()))?;
fs::copy(&source_src, source_dest.join(source_file))
.fs_context("failed to copy asset", source_src)?;
}
let dest = prefix_path(dest, "app/src/main/");
fs::create_dir_all(&dest).fs_context("failed to create directory", dest.clone())?;
let asset_dir = dest.join(DEFAULT_ASSET_DIR);
if !asset_dir.is_dir() {
fs::create_dir_all(&asset_dir).fs_context("failed to create asset dir", asset_dir)?;
}
Ok(())
}
fn generate_out_file(
path: &Path,
dest: &Path,
package_path: &str,
created_dirs: &mut Vec<PathBuf>,
) -> std::io::Result<Option<fs::File>> {
let mut iter = path.iter();
let root = iter.next().unwrap().to_str().unwrap();
let path_without_root: std::path::PathBuf = iter.collect();
let path = match (
root,
path.extension().and_then(|o| o.to_str()),
path_without_root.strip_prefix("src/main"),
) {
("app" | "buildSrc", Some("kt"), Ok(path)) => {
let parent = path.parent().unwrap();
let file_name = path.file_name().unwrap();
let out_dir = dest
.join(root)
.join("src/main")
.join(package_path)
.join(parent);
out_dir.join(file_name)
}
_ => dest.join(path),
};
let parent = path.parent().unwrap().to_path_buf();
if !created_dirs.contains(&parent) {
fs::create_dir_all(&parent)?;
created_dirs.push(parent);
}
let mut options = fs::OpenOptions::new();
options.write(true);
#[cfg(unix)]
if path.file_name().unwrap() == OsStr::new("gradlew") {
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o755);
}
if path.file_name().unwrap() == OsStr::new("BuildTask.kt") {
options.truncate(true).create(true).open(path).map(Some)
} else if !path.exists() {
options.create(true).open(path).map(Some)
} else {
Ok(None)
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/mobile/ios/dev.rs | crates/tauri-cli/src/mobile/ios/dev.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use super::{
device_prompt, ensure_init, env, get_app, get_config, inject_resources, load_pbxproj,
open_and_wait, synchronize_project_config, MobileTarget, ProjectConfig,
};
use crate::{
dev::Options as DevOptions,
error::{Context, ErrorExt},
helpers::{
app_paths::tauri_dir,
config::{get as get_tauri_config, ConfigHandle},
flock,
plist::merge_plist,
},
interface::{AppInterface, Interface, MobileOptions, Options as InterfaceOptions},
mobile::{
ios::ensure_ios_runtime_installed, use_network_address_for_dev_url, write_options, CliOptions,
DevChild, DevHost, DevProcess,
},
ConfigValue, Result,
};
use clap::{ArgAction, Parser};
use cargo_mobile2::{
apple::{
config::Config as AppleConfig,
device::{Device, DeviceKind, RunError},
target::BuildError,
},
env::Env,
opts::{NoiseLevel, Profile},
};
use url::Host;
use std::{env::set_current_dir, net::Ipv4Addr, path::PathBuf};
const PHYSICAL_IPHONE_DEV_WARNING: &str = "To develop on physical phones you need the `--host` option (not required for Simulators). See the documentation for more information: https://v2.tauri.app/develop/#development-server";
#[derive(Debug, Clone, Parser)]
#[clap(
about = "Run your app in development mode on iOS",
long_about = "Run your app in development mode on iOS with hot-reloading for the Rust code.
It makes use of the `build.devUrl` property from your `tauri.conf.json` file.
It also runs your `build.beforeDevCommand` which usually starts your frontend devServer.
When connected to a physical iOS device, the public network address must be used instead of `localhost`
for the devUrl property. Tauri makes that change automatically, but your dev server might need
a different configuration to listen on the public address. You can check the `TAURI_DEV_HOST`
environment variable to determine whether the public network should be used or not."
)]
pub struct Options {
/// List of cargo features to activate
#[clap(short, long, action = ArgAction::Append, num_args(0..))]
pub features: Vec<String>,
/// Exit on panic
#[clap(short, long)]
exit_on_panic: bool,
/// JSON strings or paths to JSON, JSON5 or TOML files to merge with the default configuration file
///
/// Configurations are merged in the order they are provided, which means a particular value overwrites previous values when a config key-value pair conflicts.
///
/// Note that a platform-specific file is looked up and merged with the default file by default
/// (tauri.macos.conf.json, tauri.linux.conf.json, tauri.windows.conf.json, tauri.android.conf.json and tauri.ios.conf.json)
/// but you can use this for more specific use cases such as different build flavors.
#[clap(short, long)]
pub config: Vec<ConfigValue>,
/// Run the code in release mode
#[clap(long = "release")]
pub release_mode: bool,
/// Skip waiting for the frontend dev server to start before building the tauri application.
#[clap(long, env = "TAURI_CLI_NO_DEV_SERVER_WAIT")]
pub no_dev_server_wait: bool,
/// Disable the file watcher
#[clap(long)]
pub no_watch: bool,
/// Additional paths to watch for changes.
#[clap(long)]
pub additional_watch_folders: Vec<PathBuf>,
/// Open Xcode instead of trying to run on a connected device
#[clap(short, long)]
pub open: bool,
/// Runs on the given device name
pub device: Option<String>,
/// Force prompting for an IP to use to connect to the dev server on mobile.
#[clap(long)]
pub force_ip_prompt: bool,
/// Use the public network address for the development server.
/// If an actual address it provided, it is used instead of prompting to pick one.
///
/// This option is particularly useful along the `--open` flag when you intend on running on a physical device.
///
/// This replaces the devUrl configuration value to match the public network address host,
/// it is your responsibility to set up your development server to listen on this address
/// by using 0.0.0.0 as host for instance.
///
/// When this is set or when running on an iOS device the CLI sets the `TAURI_DEV_HOST`
/// environment variable so you can check this on your framework's configuration to expose the development server
/// on the public network address.
#[clap(long, default_value_t, default_missing_value(""), num_args(0..=1))]
pub host: DevHost,
/// Disable the built-in dev server for static files.
#[clap(long)]
pub no_dev_server: bool,
/// Specify port for the built-in dev server for static files. Defaults to 1430.
#[clap(long, env = "TAURI_CLI_PORT")]
pub port: Option<u16>,
/// Command line arguments passed to the runner.
/// Use `--` to explicitly mark the start of the arguments.
/// e.g. `tauri ios dev -- [runnerArgs]`.
#[clap(last(true))]
pub args: Vec<String>,
/// Path to the certificate file used by your dev server. Required for mobile dev when using HTTPS.
#[clap(long, env = "TAURI_DEV_ROOT_CERTIFICATE_PATH")]
pub root_certificate_path: Option<PathBuf>,
}
impl From<Options> for DevOptions {
fn from(options: Options) -> Self {
Self {
runner: None,
target: None,
features: options.features,
exit_on_panic: options.exit_on_panic,
config: options.config,
release_mode: options.release_mode,
args: options.args,
no_watch: options.no_watch,
additional_watch_folders: options.additional_watch_folders,
no_dev_server: options.no_dev_server,
no_dev_server_wait: options.no_dev_server_wait,
port: options.port,
host: options.host.0.unwrap_or_default(),
}
}
}
pub fn command(options: Options, noise_level: NoiseLevel) -> Result<()> {
crate::helpers::app_paths::resolve();
let result = run_command(options, noise_level);
if result.is_err() {
crate::dev::kill_before_dev_process();
}
result
}
fn run_command(options: Options, noise_level: NoiseLevel) -> Result<()> {
// setup env additions before calling env()
if let Some(root_certificate_path) = &options.root_certificate_path {
std::env::set_var(
"TAURI_DEV_ROOT_CERTIFICATE",
std::fs::read_to_string(root_certificate_path).fs_context(
"failed to read root certificate file",
root_certificate_path.clone(),
)?,
);
}
let env = env().context("failed to load iOS environment")?;
let device = if options.open {
None
} else {
match device_prompt(&env, options.device.as_deref()) {
Ok(d) => Some(d),
Err(e) => {
log::error!("{e}");
None
}
}
};
if device.is_some() {
ensure_ios_runtime_installed()?;
}
let mut dev_options: DevOptions = options.clone().into();
let target_triple = device
.as_ref()
.map(|d| d.target().triple.to_string())
.unwrap_or_else(|| "aarch64-apple-ios".into());
dev_options.target = Some(target_triple.clone());
let tauri_config = get_tauri_config(
tauri_utils::platform::Target::Ios,
&options.config.iter().map(|c| &c.0).collect::<Vec<_>>(),
)?;
let (interface, config) = {
let tauri_config_guard = tauri_config.lock().unwrap();
let tauri_config_ = tauri_config_guard.as_ref().unwrap();
let interface = AppInterface::new(tauri_config_, Some(target_triple))?;
let app = get_app(MobileTarget::Ios, tauri_config_, &interface);
let (config, _metadata) = get_config(
&app,
tauri_config_,
&dev_options.features,
&Default::default(),
)?;
(interface, config)
};
let tauri_path = tauri_dir();
set_current_dir(tauri_path).context("failed to set current directory to Tauri directory")?;
ensure_init(
&tauri_config,
config.app(),
config.project_dir(),
MobileTarget::Ios,
false,
)?;
inject_resources(&config, tauri_config.lock().unwrap().as_ref().unwrap())?;
let info_plist_path = config
.project_dir()
.join(config.scheme())
.join("Info.plist");
let mut src_plists = vec![info_plist_path.clone().into()];
if tauri_path.join("Info.plist").exists() {
src_plists.push(tauri_path.join("Info.plist").into());
}
if tauri_path.join("Info.ios.plist").exists() {
src_plists.push(tauri_path.join("Info.ios.plist").into());
}
if let Some(info_plist) = &tauri_config
.lock()
.unwrap()
.as_ref()
.unwrap()
.bundle
.ios
.info_plist
{
src_plists.push(info_plist.clone().into());
}
let merged_info_plist = merge_plist(src_plists)?;
merged_info_plist
.to_file_xml(&info_plist_path)
.map_err(std::io::Error::other)
.fs_context("failed to save merged Info.plist file", info_plist_path)?;
let mut pbxproj = load_pbxproj(&config)?;
// synchronize pbxproj
synchronize_project_config(
&config,
&tauri_config,
&mut pbxproj,
&mut plist::Dictionary::new(),
&ProjectConfig {
code_sign_identity: None,
team_id: None,
provisioning_profile_uuid: None,
},
!options.release_mode,
)?;
if pbxproj.has_changes() {
pbxproj
.save()
.fs_context("failed to save pbxproj file", pbxproj.path)?;
}
run_dev(
interface,
options,
dev_options,
tauri_config,
device,
env,
&config,
noise_level,
)
}
#[allow(clippy::too_many_arguments)]
fn run_dev(
mut interface: AppInterface,
options: Options,
mut dev_options: DevOptions,
tauri_config: ConfigHandle,
device: Option<Device>,
env: Env,
config: &AppleConfig,
noise_level: NoiseLevel,
) -> Result<()> {
// when --host is provided or running on a physical device or resolving 0.0.0.0 we must use the network IP
if options.host.0.is_some()
|| device
.as_ref()
.map(|device| !matches!(device.kind(), DeviceKind::Simulator))
.unwrap_or(false)
|| tauri_config
.lock()
.unwrap()
.as_ref()
.unwrap()
.build
.dev_url
.as_ref()
.is_some_and(|url| {
matches!(
url.host(),
Some(Host::Ipv4(i)) if i == Ipv4Addr::UNSPECIFIED
)
})
{
use_network_address_for_dev_url(&tauri_config, &mut dev_options, options.force_ip_prompt)?;
}
crate::dev::setup(&interface, &mut dev_options, tauri_config.clone())?;
let app_settings = interface.app_settings();
let out_dir = app_settings.out_dir(&InterfaceOptions {
debug: !dev_options.release_mode,
target: dev_options.target.clone(),
..Default::default()
})?;
let _lock = flock::open_rw(out_dir.join("lock").with_extension("ios"), "iOS")?;
let set_host = options.host.0.is_some();
let open = options.open;
interface.mobile_dev(
MobileOptions {
debug: true,
features: options.features,
args: options.args,
config: dev_options.config.clone(),
no_watch: options.no_watch,
additional_watch_folders: options.additional_watch_folders,
},
|options| {
let cli_options = CliOptions {
dev: true,
features: options.features.clone(),
args: options.args.clone(),
noise_level,
vars: Default::default(),
config: dev_options.config.clone(),
target_device: None,
};
let _handle = write_options(tauri_config.lock().unwrap().as_ref().unwrap(), cli_options)?;
let open_xcode = || {
if !set_host {
log::warn!("{PHYSICAL_IPHONE_DEV_WARNING}");
}
open_and_wait(config, &env)
};
if open {
open_xcode()
} else if let Some(device) = &device {
match run(device, options, config, noise_level, &env) {
Ok(c) => Ok(Box::new(c) as Box<dyn DevProcess + Send>),
Err(RunError::BuildFailed(BuildError::Sdk(sdk_err))) => {
log::warn!("{sdk_err}");
open_xcode()
}
Err(e) => {
crate::dev::kill_before_dev_process();
crate::error::bail!("failed to run iOS app: {}", e)
}
}
} else {
open_xcode()
}
},
)
}
fn run(
device: &Device<'_>,
options: MobileOptions,
config: &AppleConfig,
noise_level: NoiseLevel,
env: &Env,
) -> std::result::Result<DevChild, RunError> {
let profile = if options.debug {
Profile::Debug
} else {
Profile::Release
};
device
.run(
config,
env,
noise_level,
false, // do not quit on app exit
profile,
)
.map(DevChild::new)
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/mobile/ios/build.rs | crates/tauri-cli/src/mobile/ios/build.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use super::{
detect_target_ok, ensure_init, env, get_app, get_config, inject_resources, load_pbxproj,
log_finished, open_and_wait, project_config, synchronize_project_config, MobileTarget,
OptionsHandle,
};
use crate::{
build::Options as BuildOptions,
error::{Context, ErrorExt},
helpers::{
app_paths::tauri_dir,
config::{get as get_tauri_config, ConfigHandle},
flock,
plist::merge_plist,
},
interface::{AppInterface, Interface, Options as InterfaceOptions},
mobile::{ios::ensure_ios_runtime_installed, write_options, CliOptions, TargetDevice},
ConfigValue, Error, Result,
};
use clap::{ArgAction, Parser, ValueEnum};
use cargo_mobile2::{
apple::{
config::Config as AppleConfig,
target::{ArchiveConfig, BuildConfig, ExportConfig, Target},
},
env::Env,
opts::{NoiseLevel, Profile},
target::{call_for_targets_with_fallback, TargetInvalid, TargetTrait},
};
use rand::distr::{Alphanumeric, SampleString};
use std::{
env::{set_current_dir, var, var_os},
fs,
path::PathBuf,
};
#[derive(Debug, Clone, Parser)]
#[clap(
about = "Build your app in release mode for iOS and generate IPAs",
long_about = "Build your app in release mode for iOS and generate IPAs. It makes use of the `build.frontendDist` property from your `tauri.conf.json` file. It also runs your `build.beforeBuildCommand` which usually builds your frontend into `build.frontendDist`."
)]
pub struct Options {
/// Builds with the debug flag
#[clap(short, long)]
pub debug: bool,
/// Which targets to build.
#[clap(
short,
long = "target",
action = ArgAction::Append,
num_args(0..),
default_value = Target::DEFAULT_KEY,
value_parser(clap::builder::PossibleValuesParser::new(Target::name_list()))
)]
pub targets: Option<Vec<String>>,
/// List of cargo features to activate
#[clap(short, long, action = ArgAction::Append, num_args(0..))]
pub features: Vec<String>,
/// JSON strings or paths to JSON, JSON5 or TOML files to merge with the default configuration file
///
/// Configurations are merged in the order they are provided, which means a particular value overwrites previous values when a config key-value pair conflicts.
///
/// Note that a platform-specific file is looked up and merged with the default file by default
/// (tauri.macos.conf.json, tauri.linux.conf.json, tauri.windows.conf.json, tauri.android.conf.json and tauri.ios.conf.json)
/// but you can use this for more specific use cases such as different build flavors.
#[clap(short, long)]
pub config: Vec<ConfigValue>,
/// Build number to append to the app version.
#[clap(long)]
pub build_number: Option<u32>,
/// Open Xcode
#[clap(short, long)]
pub open: bool,
/// Skip prompting for values
#[clap(long, env = "CI")]
pub ci: bool,
/// Describes how Xcode should export the archive.
///
/// Use this to create a package ready for the App Store (app-store-connect option) or TestFlight (release-testing option).
#[clap(long, value_enum)]
pub export_method: Option<ExportMethod>,
/// Command line arguments passed to the runner.
/// Use `--` to explicitly mark the start of the arguments.
/// e.g. `tauri ios build -- [runnerArgs]`.
#[clap(last(true))]
pub args: Vec<String>,
/// Do not error out if a version mismatch is detected on a Tauri package.
///
/// Only use this when you are sure the mismatch is incorrectly detected as version mismatched Tauri packages can lead to unknown behavior.
#[clap(long)]
pub ignore_version_mismatches: bool,
/// Target device of this build
#[clap(skip)]
pub target_device: Option<TargetDevice>,
}
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum ExportMethod {
AppStoreConnect,
ReleaseTesting,
Debugging,
}
impl ExportMethod {
/// Xcode 15.4 deprecated these names (in this case we should use the Display impl).
pub fn pre_xcode_15_4_name(&self) -> String {
match self {
Self::AppStoreConnect => "app-store".to_string(),
Self::ReleaseTesting => "ad-hoc".to_string(),
Self::Debugging => "development".to_string(),
}
}
}
impl std::fmt::Display for ExportMethod {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::AppStoreConnect => write!(f, "app-store-connect"),
Self::ReleaseTesting => write!(f, "release-testing"),
Self::Debugging => write!(f, "debugging"),
}
}
}
impl std::str::FromStr for ExportMethod {
type Err = &'static str;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
match s {
"app-store-connect" => Ok(Self::AppStoreConnect),
"release-testing" => Ok(Self::ReleaseTesting),
"debugging" => Ok(Self::Debugging),
_ => Err("unknown ios target"),
}
}
}
impl From<Options> for BuildOptions {
fn from(options: Options) -> Self {
Self {
runner: None,
debug: options.debug,
target: None,
features: options.features,
bundles: None,
no_bundle: false,
config: options.config,
args: options.args,
ci: options.ci,
skip_stapling: false,
ignore_version_mismatches: options.ignore_version_mismatches,
no_sign: false,
}
}
}
pub struct BuiltApplication {
pub config: AppleConfig,
pub interface: AppInterface,
// prevent drop
#[allow(dead_code)]
options_handle: OptionsHandle,
}
pub fn command(options: Options, noise_level: NoiseLevel) -> Result<BuiltApplication> {
crate::helpers::app_paths::resolve();
let mut build_options: BuildOptions = options.clone().into();
build_options.target = Some(
Target::all()
.get(
options
.targets
.as_ref()
.and_then(|t| t.first())
.map(|t| t.as_str())
.unwrap_or(Target::DEFAULT_KEY),
)
.unwrap()
.triple
.into(),
);
let tauri_config = get_tauri_config(
tauri_utils::platform::Target::Ios,
&options.config.iter().map(|c| &c.0).collect::<Vec<_>>(),
)?;
let (interface, mut config) = {
let tauri_config_guard = tauri_config.lock().unwrap();
let tauri_config_ = tauri_config_guard.as_ref().unwrap();
let interface = AppInterface::new(tauri_config_, build_options.target.clone())?;
interface.build_options(&mut Vec::new(), &mut build_options.features, true);
let app = get_app(MobileTarget::Ios, tauri_config_, &interface);
let (config, _metadata) = get_config(
&app,
tauri_config_,
&build_options.features,
&Default::default(),
)?;
(interface, config)
};
let tauri_path = tauri_dir();
set_current_dir(tauri_path).context("failed to set current directory")?;
ensure_init(
&tauri_config,
config.app(),
config.project_dir(),
MobileTarget::Ios,
options.ci,
)?;
inject_resources(&config, tauri_config.lock().unwrap().as_ref().unwrap())?;
let mut plist = plist::Dictionary::new();
plist.insert(
"CFBundleShortVersionString".into(),
config.bundle_version_short().into(),
);
let info_plist_path = config
.project_dir()
.join(config.scheme())
.join("Info.plist");
let mut src_plists = vec![info_plist_path.clone().into()];
src_plists.push(plist::Value::Dictionary(plist).into());
if tauri_path.join("Info.plist").exists() {
src_plists.push(tauri_path.join("Info.plist").into());
}
if tauri_path.join("Info.ios.plist").exists() {
src_plists.push(tauri_path.join("Info.ios.plist").into());
}
if let Some(info_plist) = &tauri_config
.lock()
.unwrap()
.as_ref()
.unwrap()
.bundle
.ios
.info_plist
{
src_plists.push(info_plist.clone().into());
}
let merged_info_plist = merge_plist(src_plists)?;
merged_info_plist
.to_file_xml(&info_plist_path)
.map_err(std::io::Error::other)
.fs_context("failed to save merged Info.plist file", info_plist_path)?;
let mut env = env().context("failed to load iOS environment")?;
if !options.open {
ensure_ios_runtime_installed()?;
}
let mut export_options_plist = plist::Dictionary::new();
if let Some(method) = options.export_method {
let xcode_version =
crate::info::env_system::xcode_version().context("failed to determine Xcode version")?;
let mut iter = xcode_version.split('.');
let major = iter.next().context(format!(
"failed to parse Xcode version `{xcode_version}` as semver"
))?;
let minor = iter.next().context(format!(
"failed to parse Xcode version `{xcode_version}` as semver"
))?;
let major = major.parse::<u64>().ok().context(format!(
"failed to parse Xcode version `{xcode_version}` as semver: major is not a number"
))?;
let minor = minor.parse::<u64>().ok().context(format!(
"failed to parse Xcode version `{xcode_version}` as semver: minor is not a number"
))?;
if major < 15 || (major == 15 && minor < 4) {
export_options_plist.insert("method".to_string(), method.pre_xcode_15_4_name().into());
} else {
export_options_plist.insert("method".to_string(), method.to_string().into());
}
}
let (keychain, provisioning_profile) = super::signing_from_env()?;
let project_config = project_config(keychain.as_ref(), provisioning_profile.as_ref())?;
let mut pbxproj = load_pbxproj(&config)?;
// synchronize pbxproj and exportoptions
synchronize_project_config(
&config,
&tauri_config,
&mut pbxproj,
&mut export_options_plist,
&project_config,
options.debug,
)?;
if pbxproj.has_changes() {
pbxproj
.save()
.fs_context("failed to save pbxproj file", pbxproj.path)?;
}
// merge export options and write to temp file
let _export_options_tmp = if !export_options_plist.is_empty() {
let export_options_plist_path = config.project_dir().join("ExportOptions.plist");
let export_options =
tempfile::NamedTempFile::new().context("failed to create temporary file")?;
let merged_plist = merge_plist(vec![
export_options_plist_path.into(),
plist::Value::from(export_options_plist).into(),
])?;
merged_plist
.to_file_xml(export_options.path())
.map_err(std::io::Error::other)
.fs_context(
"failed to save export options plist file",
export_options.path().to_path_buf(),
)?;
config.set_export_options_plist_path(export_options.path());
Some(export_options)
} else {
None
};
let open = options.open;
let options_handle = run_build(
&interface,
options,
build_options,
tauri_config,
&mut config,
&mut env,
noise_level,
)?;
if open {
open_and_wait(&config, &env);
}
Ok(BuiltApplication {
config,
interface,
options_handle,
})
}
#[allow(clippy::too_many_arguments)]
fn run_build(
interface: &AppInterface,
options: Options,
mut build_options: BuildOptions,
tauri_config: ConfigHandle,
config: &mut AppleConfig,
env: &mut Env,
noise_level: NoiseLevel,
) -> Result<OptionsHandle> {
let profile = if options.debug {
Profile::Debug
} else {
Profile::Release
};
crate::build::setup(
interface,
&mut build_options,
tauri_config.lock().unwrap().as_ref().unwrap(),
true,
)?;
let app_settings = interface.app_settings();
let out_dir = app_settings.out_dir(&InterfaceOptions {
debug: build_options.debug,
target: build_options.target.clone(),
args: build_options.args.clone(),
..Default::default()
})?;
let _lock = flock::open_rw(out_dir.join("lock").with_extension("ios"), "iOS")?;
let cli_options = CliOptions {
dev: false,
features: build_options.features.clone(),
args: build_options.args.clone(),
noise_level,
vars: Default::default(),
config: build_options.config.clone(),
target_device: options.target_device.clone(),
};
let handle = write_options(tauri_config.lock().unwrap().as_ref().unwrap(), cli_options)?;
if options.open {
return Ok(handle);
}
let mut out_files = Vec::new();
let force_skip_target_fallback = options.targets.as_ref().is_some_and(|t| t.is_empty());
call_for_targets_with_fallback(
options.targets.unwrap_or_default().iter(),
if force_skip_target_fallback {
&|_| None
} else {
&detect_target_ok
},
env,
|target: &Target| -> Result<()> {
let mut app_version = config.bundle_version().to_string();
if let Some(build_number) = options.build_number {
app_version.push('.');
app_version.push_str(&build_number.to_string());
}
let credentials = auth_credentials_from_env()?;
let skip_signing = credentials.is_some();
let mut build_config = BuildConfig::new().allow_provisioning_updates();
if let Some(credentials) = &credentials {
build_config = build_config
.authentication_credentials(credentials.clone())
.skip_codesign();
}
target
.build(None, config, env, noise_level, profile, build_config)
.context("failed to build iOS app")?;
let mut archive_config = ArchiveConfig::new();
if skip_signing {
archive_config = archive_config.skip_codesign();
}
target
.archive(
config,
env,
noise_level,
profile,
Some(app_version),
archive_config,
)
.context("failed to archive iOS app")?;
let out_dir = config.export_dir().join(target.arch);
if target.sdk == "iphonesimulator" {
fs::create_dir_all(&out_dir)
.fs_context("failed to create Xcode output directory", out_dir.clone())?;
let app_path = config
.archive_dir()
.join(format!("{}.xcarchive", config.scheme()))
.join("Products")
.join("Applications")
.join(config.app().stylized_name())
.with_extension("app");
let path = out_dir.join(app_path.file_name().unwrap());
fs::rename(&app_path, &path).fs_context("failed to rename app", app_path)?;
out_files.push(path);
} else {
// if we skipped code signing, we do not have the entitlements applied to our exported IPA
// we must force sign the app binary with a dummy certificate just to preserve the entitlements
// target.export() will sign it with an actual certificate for us
if skip_signing {
let password = Alphanumeric.sample_string(&mut rand::rng(), 16);
let certificate = tauri_macos_sign::certificate::generate_self_signed(
tauri_macos_sign::certificate::SelfSignedCertificateRequest {
algorithm: "rsa".to_string(),
profile: tauri_macos_sign::certificate::CertificateProfile::AppleDistribution,
team_id: "unset".to_string(),
person_name: "Tauri".to_string(),
country_name: "NL".to_string(),
validity_days: 365,
password: password.clone(),
},
)
.map_err(Box::new)?;
let tmp_dir = tempfile::tempdir().context("failed to create temporary directory")?;
let cert_path = tmp_dir.path().join("cert.p12");
std::fs::write(&cert_path, certificate)
.fs_context("failed to write certificate", cert_path.clone())?;
let self_signed_cert_keychain =
tauri_macos_sign::Keychain::with_certificate_file(&cert_path, &password.into())
.map_err(Box::new)?;
let app_dir = config
.export_dir()
.join(format!("{}.xcarchive", config.scheme()))
.join("Products/Applications")
.join(format!("{}.app", config.app().stylized_name()));
self_signed_cert_keychain
.sign(
&app_dir.join(config.app().stylized_name()),
Some(
&config
.project_dir()
.join(config.scheme())
.join(format!("{}.entitlements", config.scheme())),
),
false,
)
.map_err(Box::new)?;
}
let mut export_config = ExportConfig::new().allow_provisioning_updates();
if let Some(credentials) = &credentials {
export_config = export_config.authentication_credentials(credentials.clone());
}
target
.export(config, env, noise_level, export_config)
.context("failed to export iOS app")?;
if let Ok(ipa_path) = config.ipa_path() {
fs::create_dir_all(&out_dir)
.fs_context("failed to create Xcode output directory", out_dir.clone())?;
let path = out_dir.join(ipa_path.file_name().unwrap());
fs::rename(&ipa_path, &path).fs_context("failed to rename IPA", ipa_path)?;
out_files.push(path);
}
}
Ok(())
},
)
.map_err(|e: TargetInvalid| Error::GenericError(e.to_string()))??;
if !out_files.is_empty() {
log_finished(out_files, "iOS Bundle");
}
Ok(handle)
}
fn auth_credentials_from_env() -> Result<Option<cargo_mobile2::apple::AuthCredentials>> {
match (
var("APPLE_API_KEY"),
var("APPLE_API_ISSUER"),
var_os("APPLE_API_KEY_PATH").map(PathBuf::from),
) {
(Ok(key_id), Ok(key_issuer_id), Some(key_path)) => {
Ok(Some(cargo_mobile2::apple::AuthCredentials {
key_path,
key_id,
key_issuer_id,
}))
}
(Err(_), Err(_), None) => Ok(None),
_ => crate::error::bail!(
"APPLE_API_KEY, APPLE_API_ISSUER and APPLE_API_KEY_PATH must be provided for code signing"
),
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/mobile/ios/xcode_script.rs | crates/tauri-cli/src/mobile/ios/xcode_script.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use super::{ensure_init, env, get_app, get_config, read_options, MobileTarget};
use crate::{
error::{Context, ErrorExt},
helpers::config::{get as get_tauri_config, reload as reload_tauri_config},
interface::{AppInterface, Interface, Options as InterfaceOptions},
mobile::ios::LIB_OUTPUT_FILE_NAME,
Error, Result,
};
use cargo_mobile2::{apple::target::Target, opts::Profile, target::TargetTrait};
use clap::{ArgAction, Parser};
use object::{Object, ObjectSymbol};
use std::{
collections::HashMap,
env::{current_dir, set_current_dir, var, var_os},
ffi::OsStr,
fs::read_to_string,
io::Read,
path::{Path, PathBuf},
};
#[derive(Debug, Parser)]
pub struct Options {
/// Value of `PLATFORM_DISPLAY_NAME` env var
#[clap(long)]
platform: String,
/// Value of `SDKROOT` env var
#[clap(long)]
sdk_root: PathBuf,
/// Value of `FRAMEWORK_SEARCH_PATHS` env var
#[clap(long, action = ArgAction::Append, num_args(0..))]
framework_search_paths: Vec<String>,
/// Value of `GCC_PREPROCESSOR_DEFINITIONS` env var
#[clap(long, action = ArgAction::Append, num_args(0..))]
gcc_preprocessor_definitions: Vec<String>,
/// Value of `HEADER_SEARCH_PATHS` env var
#[clap(long, action = ArgAction::Append, num_args(0..))]
header_search_paths: Vec<String>,
/// Value of `CONFIGURATION` env var
#[clap(long)]
configuration: String,
/// Value of `FORCE_COLOR` env var
#[clap(long)]
force_color: bool,
/// Value of `ARCHS` env var
#[clap(index = 1, required = true)]
arches: Vec<String>,
}
pub fn command(options: Options) -> Result<()> {
fn macos_from_platform(platform: &str) -> bool {
platform == "macOS"
}
fn profile_from_configuration(configuration: &str) -> Profile {
if configuration == "release" {
Profile::Release
} else {
Profile::Debug
}
}
let process_path = std::env::current_exe().unwrap_or_default();
// `xcode-script` is ran from the `gen/apple` folder when not using NPM/yarn/pnpm/deno.
// so we must change working directory to the src-tauri folder to resolve the tauri dir
// additionally, bun@<1.2 does not modify the current working directory, so it is also runs this script from `gen/apple`
// bun@>1.2 now actually moves the CWD to the package root so we shouldn't modify CWD in that case
// see https://bun.sh/blog/bun-v1.2#bun-run-uses-the-correct-directory
if (var_os("npm_lifecycle_event").is_none()
&& var_os("PNPM_PACKAGE_NAME").is_none()
&& process_path.file_stem().unwrap_or_default() != "deno")
|| var("npm_config_user_agent")
.is_ok_and(|agent| agent.starts_with("bun/1.0") || agent.starts_with("bun/1.1"))
{
set_current_dir(
current_dir()
.context("failed to resolve current directory")?
.parent()
.unwrap()
.parent()
.unwrap(),
)
.unwrap();
}
crate::helpers::app_paths::resolve();
let profile = profile_from_configuration(&options.configuration);
let macos = macos_from_platform(&options.platform);
let (tauri_config, cli_options) = {
let tauri_config = get_tauri_config(tauri_utils::platform::Target::Ios, &[])?;
let cli_options = {
let tauri_config_guard = tauri_config.lock().unwrap();
let tauri_config_ = tauri_config_guard.as_ref().unwrap();
read_options(tauri_config_)
};
let tauri_config = if cli_options.config.is_empty() {
tauri_config
} else {
// reload config with merges from the ios dev|build script
reload_tauri_config(
&cli_options
.config
.iter()
.map(|conf| &conf.0)
.collect::<Vec<_>>(),
)?
};
(tauri_config, cli_options)
};
let (config, metadata) = {
let tauri_config_guard = tauri_config.lock().unwrap();
let tauri_config_ = tauri_config_guard.as_ref().unwrap();
let cli_options = read_options(tauri_config_);
let (config, metadata) = get_config(
&get_app(
MobileTarget::Ios,
tauri_config_,
&AppInterface::new(tauri_config_, None)?,
),
tauri_config_,
&[],
&cli_options,
)?;
(config, metadata)
};
ensure_init(
&tauri_config,
config.app(),
config.project_dir(),
MobileTarget::Ios,
std::env::var("CI").is_ok(),
)?;
if !cli_options.config.is_empty() {
crate::helpers::config::merge_with(
&cli_options
.config
.iter()
.map(|conf| &conf.0)
.collect::<Vec<_>>(),
)?;
}
let env = env()
.context("failed to load iOS environment")?
.explicit_env_vars(cli_options.vars);
if !options.sdk_root.is_dir() {
crate::error::bail!(
"SDK root provided by Xcode was invalid. {} doesn't exist or isn't a directory",
options.sdk_root.display(),
);
}
let include_dir = options.sdk_root.join("usr/include");
if !include_dir.is_dir() {
crate::error::bail!(
"Include dir was invalid. {} doesn't exist or isn't a directory",
include_dir.display()
);
}
// Host flags that are used by build scripts
let macos_isysroot = {
let macos_sdk_root = options
.sdk_root
.join("../../../../MacOSX.platform/Developer/SDKs/MacOSX.sdk");
if !macos_sdk_root.is_dir() {
crate::error::bail!("Invalid SDK root {}", macos_sdk_root.display());
}
format!("-isysroot {}", macos_sdk_root.display())
};
let mut host_env = HashMap::<&str, &OsStr>::new();
host_env.insert("RUST_BACKTRACE", "1".as_ref());
host_env.insert("CFLAGS_x86_64_apple_darwin", macos_isysroot.as_ref());
host_env.insert("CXXFLAGS_x86_64_apple_darwin", macos_isysroot.as_ref());
host_env.insert(
"OBJC_INCLUDE_PATH_x86_64_apple_darwin",
include_dir.as_os_str(),
);
let framework_search_paths = options.framework_search_paths.join(" ");
host_env.insert("FRAMEWORK_SEARCH_PATHS", framework_search_paths.as_ref());
let gcc_preprocessor_definitions = options.gcc_preprocessor_definitions.join(" ");
host_env.insert(
"GCC_PREPROCESSOR_DEFINITIONS",
gcc_preprocessor_definitions.as_ref(),
);
let header_search_paths = options.header_search_paths.join(" ");
host_env.insert("HEADER_SEARCH_PATHS", header_search_paths.as_ref());
let macos_target = Target::macos();
let isysroot = format!("-isysroot {}", options.sdk_root.display());
let simulator =
options.platform == "iOS Simulator" || options.arches.contains(&"Simulator".to_string());
let arches = if simulator {
// when compiling for the simulator, we don't need to build other targets
vec![if cfg!(target_arch = "aarch64") {
"arm64"
} else {
"x86_64"
}
.to_string()]
} else {
options.arches
};
let installed_targets =
crate::interface::rust::installation::installed_targets().unwrap_or_default();
for arch in arches {
// Set target-specific flags
let (env_triple, rust_triple) = match arch.as_str() {
"arm64" if !simulator => ("aarch64_apple_ios", "aarch64-apple-ios"),
"arm64" if simulator => ("aarch64_apple_ios_sim", "aarch64-apple-ios-sim"),
"x86_64" => ("x86_64_apple_ios", "x86_64-apple-ios"),
_ => {
crate::error::bail!("Arch specified by Xcode was invalid. {arch} isn't a known arch")
}
};
let interface = AppInterface::new(
tauri_config.lock().unwrap().as_ref().unwrap(),
Some(rust_triple.into()),
)?;
let cflags = format!("CFLAGS_{env_triple}");
let cxxflags = format!("CFLAGS_{env_triple}");
let objc_include_path = format!("OBJC_INCLUDE_PATH_{env_triple}");
let mut target_env = host_env.clone();
target_env.insert(cflags.as_ref(), isysroot.as_ref());
target_env.insert(cxxflags.as_ref(), isysroot.as_ref());
target_env.insert(objc_include_path.as_ref(), include_dir.as_ref());
let target = if macos {
&macos_target
} else {
Target::for_arch(if arch == "arm64" && simulator {
"arm64-sim"
} else {
&arch
})
.with_context(|| format!("Arch specified by Xcode was invalid. {arch} isn't a known arch"))?
};
if !installed_targets.contains(&rust_triple.into()) {
log::info!("Installing target {}", target.triple());
target.install().map_err(|error| Error::CommandFailed {
command: "rustup target add".to_string(),
error,
})?;
}
target
.compile_lib(
&config,
&metadata,
cli_options.noise_level,
true,
profile,
&env,
target_env,
)
.context("failed to compile iOS app")?;
let out_dir = interface.app_settings().out_dir(&InterfaceOptions {
debug: matches!(profile, Profile::Debug),
target: Some(rust_triple.into()),
..Default::default()
})?;
let lib_path = out_dir.join(format!("lib{}.a", config.app().lib_name()));
if !lib_path.exists() {
crate::error::bail!("Library not found at {}. Make sure your Cargo.toml file has a [lib] block with `crate-type = [\"staticlib\", \"cdylib\", \"lib\"]`", lib_path.display());
}
validate_lib(&lib_path)?;
let project_dir = config.project_dir();
let externals_lib_dir = project_dir.join(format!("Externals/{arch}/{}", profile.as_str()));
std::fs::create_dir_all(&externals_lib_dir).fs_context(
"failed to create externals lib directory",
externals_lib_dir.clone(),
)?;
// backwards compatible lib output file name
let uses_new_lib_output_file_name = {
let pbxproj_path = project_dir
.join(format!("{}.xcodeproj", config.app().name()))
.join("project.pbxproj");
let pbxproj_contents = read_to_string(&pbxproj_path)
.fs_context("failed to read project.pbxproj file", pbxproj_path)?;
pbxproj_contents.contains(LIB_OUTPUT_FILE_NAME)
};
let lib_output_file_name = if uses_new_lib_output_file_name {
LIB_OUTPUT_FILE_NAME.to_string()
} else {
format!("lib{}.a", config.app().lib_name())
};
std::fs::copy(&lib_path, externals_lib_dir.join(lib_output_file_name)).fs_context(
"failed to copy mobile lib file to Externals directory",
lib_path.to_path_buf(),
)?;
}
Ok(())
}
fn validate_lib(path: &Path) -> Result<()> {
let mut archive = ar::Archive::new(
std::fs::File::open(path).fs_context("failed to open mobile lib file", path.to_path_buf())?,
);
// Iterate over all entries in the archive:
while let Some(entry) = archive.next_entry() {
let Ok(mut entry) = entry else {
continue;
};
let mut obj_bytes = Vec::new();
entry
.read_to_end(&mut obj_bytes)
.fs_context("failed to read mobile lib entry", path.to_path_buf())?;
let file = object::File::parse(&*obj_bytes)
.map_err(std::io::Error::other)
.fs_context("failed to parse mobile lib entry", path.to_path_buf())?;
for symbol in file.symbols() {
let Ok(name) = symbol.name() else {
continue;
};
if name.contains("start_app") {
return Ok(());
}
}
}
crate::error::bail!(
"Library from {} does not include required runtime symbols. This means you are likely missing the tauri::mobile_entry_point macro usage, see the documentation for more information: https://v2.tauri.app/start/migrate/from-tauri-1",
path.display()
)
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/mobile/ios/mod.rs | crates/tauri-cli/src/mobile/ios/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use cargo_mobile2::{
apple::{
config::{
Config as AppleConfig, Metadata as AppleMetadata, Platform as ApplePlatform,
Raw as RawAppleConfig,
},
device::{self, Device},
target::Target,
teams::find_development_teams,
},
config::app::{App, DEFAULT_ASSET_DIR},
env::Env,
opts::NoiseLevel,
os,
util::{prompt, relativize_path},
};
use clap::{Parser, Subcommand};
use serde::Deserialize;
use sublime_fuzzy::best_match;
use tauri_utils::resources::ResourcePaths;
use super::{
ensure_init, env, get_app, init::command as init_command, log_finished, read_options, CliOptions,
OptionsHandle, Target as MobileTarget, MIN_DEVICE_MATCH_SCORE,
};
use crate::{
error::{Context, ErrorExt},
helpers::{
app_paths::tauri_dir,
config::{BundleResources, Config as TauriConfig, ConfigHandle},
pbxproj, strip_semver_prerelease_tag,
},
ConfigValue, Error, Result,
};
use std::{
env::{set_var, var_os},
fs::create_dir_all,
path::Path,
str::FromStr,
thread::sleep,
time::Duration,
};
mod build;
mod dev;
pub(crate) mod project;
mod run;
mod xcode_script;
pub const APPLE_DEVELOPMENT_TEAM_ENV_VAR_NAME: &str = "APPLE_DEVELOPMENT_TEAM";
pub const LIB_OUTPUT_FILE_NAME: &str = "libapp.a";
#[derive(Parser)]
#[clap(
author,
version,
about = "iOS commands",
subcommand_required(true),
arg_required_else_help(true)
)]
pub struct Cli {
#[clap(subcommand)]
command: Commands,
}
#[derive(Debug, Parser)]
#[clap(about = "Initialize iOS target in the project")]
pub struct InitOptions {
/// Skip prompting for values
#[clap(long, env = "CI")]
ci: bool,
/// Reinstall dependencies
#[clap(short, long)]
reinstall_deps: bool,
/// Skips installing rust toolchains via rustup
#[clap(long)]
skip_targets_install: bool,
/// JSON strings or paths to JSON, JSON5 or TOML files to merge with the default configuration file
///
/// Configurations are merged in the order they are provided, which means a particular value overwrites previous values when a config key-value pair conflicts.
///
/// Note that a platform-specific file is looked up and merged with the default file by default
/// (tauri.macos.conf.json, tauri.linux.conf.json, tauri.windows.conf.json, tauri.android.conf.json and tauri.ios.conf.json)
/// but you can use this for more specific use cases such as different build flavors.
#[clap(short, long)]
pub config: Vec<ConfigValue>,
}
#[derive(Subcommand)]
enum Commands {
Init(InitOptions),
Dev(dev::Options),
Build(build::Options),
Run(run::Options),
#[clap(hide(true))]
XcodeScript(xcode_script::Options),
}
pub fn command(cli: Cli, verbosity: u8) -> Result<()> {
let noise_level = NoiseLevel::from_occurrences(verbosity as u64);
match cli.command {
Commands::Init(options) => {
crate::helpers::app_paths::resolve();
init_command(
MobileTarget::Ios,
options.ci,
options.reinstall_deps,
options.skip_targets_install,
options.config,
)?
}
Commands::Dev(options) => dev::command(options, noise_level)?,
Commands::Build(options) => build::command(options, noise_level).map(|_| ())?,
Commands::Run(options) => run::command(options, noise_level)?,
Commands::XcodeScript(options) => xcode_script::command(options)?,
}
Ok(())
}
pub fn get_config(
app: &App,
tauri_config: &TauriConfig,
features: &[String],
cli_options: &CliOptions,
) -> Result<(AppleConfig, AppleMetadata)> {
let mut ios_options = cli_options.clone();
ios_options.features.extend_from_slice(features);
let bundle_version = if let Some(bundle_version) = tauri_config
.bundle
.ios
.bundle_version
.clone()
.or_else(|| tauri_config.version.clone())
{
// if it's a semver string, we must strip the prerelease tag
if let Ok(mut version) = semver::Version::from_str(&bundle_version) {
if !version.pre.is_empty() {
log::warn!("CFBundleVersion cannot have prerelease tag; stripping from {bundle_version}");
strip_semver_prerelease_tag(&mut version)?;
}
// correctly serialize version - cannot contain `+` as build metadata separator
Some(format!(
"{}.{}.{}{}",
version.major,
version.minor,
version.patch,
if version.build.is_empty() {
"".to_string()
} else {
format!(".{}", version.build.as_str())
}
))
} else {
// let it go as is - cargo-mobile2 will validate it
Some(bundle_version)
}
} else {
None
};
let full_bundle_version_short = if let Some(app_version) = &tauri_config.version {
if let Ok(mut version) = semver::Version::from_str(app_version) {
if !version.pre.is_empty() {
log::warn!(
"CFBundleShortVersionString cannot have prerelease tag; stripping from {app_version}"
);
strip_semver_prerelease_tag(&mut version)?;
}
// correctly serialize version - cannot contain `+` as build metadata separator
Some(format!(
"{}.{}.{}{}",
version.major,
version.minor,
version.patch,
if version.build.is_empty() {
"".to_string()
} else {
format!(".{}", version.build.as_str())
}
))
} else {
// let it go as is - cargo-mobile2 will validate it
Some(app_version.clone())
}
} else {
bundle_version.clone()
};
let bundle_version_short = if let Some(full_version) = full_bundle_version_short.as_deref() {
let mut s = full_version.split('.');
let short_version = format!(
"{}.{}.{}",
s.next().unwrap_or("0"),
s.next().unwrap_or("0"),
s.next().unwrap_or("0")
);
if short_version != full_version {
log::warn!("{full_version:?} is not a valid CFBundleShortVersionString since it must contain exactly three dot separated integers; setting it to {short_version} instead");
}
Some(short_version)
} else {
None
};
let raw = RawAppleConfig {
development_team: std::env::var(APPLE_DEVELOPMENT_TEAM_ENV_VAR_NAME)
.ok()
.or_else(|| tauri_config.bundle.ios.development_team.clone())
.or_else(|| {
let teams = find_development_teams().unwrap_or_default();
match teams.len() {
0 => {
log::warn!("No code signing certificates found. You must add one and set the certificate development team ID on the `bundle > iOS > developmentTeam` config value or the `{APPLE_DEVELOPMENT_TEAM_ENV_VAR_NAME}` environment variable. To list the available certificates, run `tauri info`.");
None
}
1 => None,
_ => {
log::warn!("You must set the code signing certificate development team ID on the `bundle > iOS > developmentTeam` config value or the `{APPLE_DEVELOPMENT_TEAM_ENV_VAR_NAME}` environment variable. Available certificates: {}", teams.iter().map(|t| format!("{} (ID: {})", t.name, t.id)).collect::<Vec<String>>().join(", "));
None
}
}
}),
ios_features: Some(ios_options.features.clone()),
bundle_version,
bundle_version_short,
ios_version: Some(tauri_config.bundle.ios.minimum_system_version.clone()),
..Default::default()
};
let config = AppleConfig::from_raw(app.clone(), Some(raw))
.context("failed to create Apple configuration")?;
let tauri_dir = tauri_dir();
let mut vendor_frameworks = Vec::new();
let mut frameworks = Vec::new();
for framework in tauri_config
.bundle
.ios
.frameworks
.clone()
.unwrap_or_default()
{
let framework_path = Path::new(&framework);
let ext = framework_path.extension().unwrap_or_default();
if ext.is_empty() {
frameworks.push(framework);
} else if ext == "framework" {
frameworks.push(
framework_path
.file_stem()
.unwrap()
.to_string_lossy()
.to_string(),
);
} else {
vendor_frameworks.push(
relativize_path(tauri_dir.join(framework_path), config.project_dir())
.to_string_lossy()
.to_string(),
);
}
}
let metadata = AppleMetadata {
supported: true,
ios: ApplePlatform {
cargo_args: Some(ios_options.args),
features: if ios_options.features.is_empty() {
None
} else {
Some(ios_options.features)
},
frameworks: Some(frameworks),
vendor_frameworks: Some(vendor_frameworks),
..Default::default()
},
macos: Default::default(),
};
set_var("TAURI_IOS_PROJECT_PATH", config.project_dir());
set_var("TAURI_IOS_APP_NAME", config.app().name());
Ok((config, metadata))
}
fn connected_device_prompt<'a>(env: &'_ Env, target: Option<&str>) -> Result<Device<'a>> {
let device_list = device::list_devices(env).map_err(|cause| {
Error::GenericError(format!("Failed to detect connected iOS devices: {cause}"))
})?;
if !device_list.is_empty() {
let device = if let Some(t) = target {
let (device, score) = device_list
.into_iter()
.rev()
.map(|d| {
let score = best_match(t, d.name()).map_or(0, |m| m.score());
(d, score)
})
.max_by_key(|(_, score)| *score)
// we already checked the list is not empty
.unwrap();
if score > MIN_DEVICE_MATCH_SCORE {
device
} else {
crate::error::bail!("Could not find an iOS device matching {t}")
}
} else {
let index = if device_list.len() > 1 {
prompt::list(
concat!("Detected ", "iOS", " devices"),
device_list.iter(),
"device",
None,
"Device",
)
.context("failed to prompt for device")?
} else {
0
};
device_list.into_iter().nth(index).unwrap()
};
println!(
"Detected connected device: {} with target {:?}",
device,
device.target().triple,
);
Ok(device)
} else {
crate::error::bail!("No connected iOS devices detected")
}
}
#[derive(Default, Deserialize)]
struct InstalledRuntimesList {
runtimes: Vec<InstalledRuntime>,
}
#[derive(Deserialize)]
struct InstalledRuntime {
name: String,
}
fn simulator_prompt(env: &'_ Env, target: Option<&str>) -> Result<device::Simulator> {
let simulator_list = device::list_simulators(env).map_err(|cause| {
Error::GenericError(format!(
"Failed to detect connected iOS Simulator devices: {cause}"
))
})?;
if !simulator_list.is_empty() {
let device = if let Some(t) = target {
let (device, score) = simulator_list
.into_iter()
.rev()
.map(|d| {
let score = best_match(t, d.name()).map_or(0, |m| m.score());
(d, score)
})
.max_by_key(|(_, score)| *score)
// we already checked the list is not empty
.unwrap();
if score > MIN_DEVICE_MATCH_SCORE {
device
} else {
crate::error::bail!("Could not find an iOS Simulator matching {t}")
}
} else if simulator_list.len() > 1 {
let index = prompt::list(
concat!("Detected ", "iOS", " simulators"),
simulator_list.iter(),
"simulator",
None,
"Simulator",
)
.context("failed to prompt for simulator")?;
simulator_list.into_iter().nth(index).unwrap()
} else {
simulator_list.into_iter().next().unwrap()
};
Ok(device)
} else {
log::warn!("No available iOS Simulator detected");
let install_ios = crate::helpers::prompts::confirm(
"Would you like to install the latest iOS runtime?",
Some(false),
)
.unwrap_or_default();
if install_ios {
duct::cmd("xcodebuild", ["-downloadPlatform", "iOS"])
.stdout_file(os_pipe::dup_stdout().unwrap())
.stderr_file(os_pipe::dup_stderr().unwrap())
.run()
.map_err(|e| Error::CommandFailed {
command: "xcodebuild -downloadPlatform iOS".to_string(),
error: e,
})?;
return simulator_prompt(env, target);
}
crate::error::bail!("No available iOS Simulator detected")
}
}
fn device_prompt<'a>(env: &'_ Env, target: Option<&str>) -> Result<Device<'a>> {
if let Ok(device) = connected_device_prompt(env, target) {
Ok(device)
} else {
let simulator = simulator_prompt(env, target)?;
log::info!("Starting simulator {}", simulator.name());
simulator
.start_detached(env)
.context("failed to start simulator")?;
Ok(simulator.into())
}
}
fn ensure_ios_runtime_installed() -> Result<()> {
let installed_platforms_json = duct::cmd("xcrun", ["simctl", "list", "runtimes", "--json"])
.read()
.map_err(|e| Error::CommandFailed {
command: "xcrun simctl list runtimes --json".to_string(),
error: e,
})?;
let installed_platforms: InstalledRuntimesList =
serde_json::from_str(&installed_platforms_json).unwrap_or_default();
if !installed_platforms
.runtimes
.iter()
.any(|r| r.name.starts_with("iOS"))
{
log::warn!("iOS platform not installed");
let install_ios = crate::helpers::prompts::confirm(
"Would you like to install the latest iOS runtime?",
Some(false),
)
.unwrap_or_default();
if install_ios {
duct::cmd("xcodebuild", ["-downloadPlatform", "iOS"])
.stdout_file(os_pipe::dup_stdout().unwrap())
.stderr_file(os_pipe::dup_stderr().unwrap())
.run()
.map_err(|e| Error::CommandFailed {
command: "xcodebuild -downloadPlatform iOS".to_string(),
error: e,
})?;
} else {
crate::error::bail!("iOS platform not installed");
}
}
Ok(())
}
fn detect_target_ok<'a>(env: &Env) -> Option<&'a Target<'a>> {
device_prompt(env, None).map(|device| device.target()).ok()
}
fn open_and_wait(config: &AppleConfig, env: &Env) -> ! {
log::info!("Opening Xcode");
if let Err(e) = os::open_file_with("Xcode", config.project_dir(), env) {
log::error!("{e}");
}
loop {
sleep(Duration::from_secs(24 * 60 * 60));
}
}
fn inject_resources(config: &AppleConfig, tauri_config: &TauriConfig) -> Result<()> {
let asset_dir = config.project_dir().join(DEFAULT_ASSET_DIR);
create_dir_all(&asset_dir).fs_context("failed to create asset directory", asset_dir.clone())?;
let resources = match &tauri_config.bundle.resources {
Some(BundleResources::List(paths)) => Some(ResourcePaths::new(paths.as_slice(), true)),
Some(BundleResources::Map(map)) => Some(ResourcePaths::from_map(map, true)),
None => None,
};
if let Some(resources) = resources {
for resource in resources.iter() {
let resource = resource.context("failed to get resource")?;
let dest = asset_dir.join(resource.target());
crate::helpers::fs::copy_file(resource.path(), dest)?;
}
}
Ok(())
}
pub fn signing_from_env() -> Result<(
Option<tauri_macos_sign::Keychain>,
Option<tauri_macos_sign::ProvisioningProfile>,
)> {
let keychain = match (
var_os("IOS_CERTIFICATE"),
var_os("IOS_CERTIFICATE_PASSWORD"),
) {
(Some(certificate), Some(certificate_password)) => {
log::info!("Reading iOS certificates from ");
tauri_macos_sign::Keychain::with_certificate(&certificate, &certificate_password)
.map(Some)
.map_err(Box::new)?
}
(Some(_), None) => {
log::warn!("The IOS_CERTIFICATE environment variable is set but not IOS_CERTIFICATE_PASSWORD. Ignoring the certificate...");
None
}
_ => None,
};
let provisioning_profile = if let Some(provisioning_profile) = var_os("IOS_MOBILE_PROVISION") {
tauri_macos_sign::ProvisioningProfile::from_base64(&provisioning_profile)
.map(Some)
.map_err(Box::new)?
} else {
if keychain.is_some() {
log::warn!("You have provided an iOS certificate via environment variables but the IOS_MOBILE_PROVISION environment variable is not set. This will fail when signing unless the profile is set in your Xcode project.");
}
None
};
Ok((keychain, provisioning_profile))
}
pub struct ProjectConfig {
pub code_sign_identity: Option<String>,
pub team_id: Option<String>,
pub provisioning_profile_uuid: Option<String>,
}
pub fn project_config(
keychain: Option<&tauri_macos_sign::Keychain>,
provisioning_profile: Option<&tauri_macos_sign::ProvisioningProfile>,
) -> Result<ProjectConfig> {
Ok(ProjectConfig {
code_sign_identity: keychain.map(|k| k.signing_identity()),
team_id: keychain.and_then(|k| k.team_id().map(ToString::to_string)),
provisioning_profile_uuid: provisioning_profile.and_then(|p| p.uuid().ok()),
})
}
pub fn load_pbxproj(config: &AppleConfig) -> Result<pbxproj::Pbxproj> {
pbxproj::parse(
config
.project_dir()
.join(format!("{}.xcodeproj", config.app().name()))
.join("project.pbxproj"),
)
}
pub fn synchronize_project_config(
config: &AppleConfig,
tauri_config: &ConfigHandle,
pbxproj: &mut pbxproj::Pbxproj,
export_options_plist: &mut plist::Dictionary,
project_config: &ProjectConfig,
debug: bool,
) -> Result<()> {
let identifier = tauri_config
.lock()
.unwrap()
.as_ref()
.unwrap()
.identifier
.clone();
let product_name = tauri_config
.lock()
.unwrap()
.as_ref()
.unwrap()
.product_name
.clone();
let manual_signing = project_config.code_sign_identity.is_some()
|| project_config.provisioning_profile_uuid.is_some();
if let Some(xc_configuration_list) = pbxproj
.xc_configuration_list
.clone()
.into_values()
.find(|l| l.comment.contains("_iOS"))
{
for build_configuration_ref in xc_configuration_list.build_configurations {
if manual_signing {
pbxproj.set_build_settings(&build_configuration_ref.id, "CODE_SIGN_STYLE", "Manual");
}
if let Some(team) = config.development_team() {
let team = format!("\"{team}\"");
pbxproj.set_build_settings(&build_configuration_ref.id, "DEVELOPMENT_TEAM", &team);
}
pbxproj.set_build_settings(
&build_configuration_ref.id,
"PRODUCT_BUNDLE_IDENTIFIER",
&identifier,
);
if let Some(product_name) = &product_name {
pbxproj.set_build_settings(
&build_configuration_ref.id,
"PRODUCT_NAME",
&format!("\"{product_name}\""),
);
}
if let Some(identity) = &project_config.code_sign_identity {
let identity = format!("\"{identity}\"");
pbxproj.set_build_settings(&build_configuration_ref.id, "CODE_SIGN_IDENTITY", &identity);
pbxproj.set_build_settings(
&build_configuration_ref.id,
"\"CODE_SIGN_IDENTITY[sdk=iphoneos*]\"",
&identity,
);
}
if let Some(id) = &project_config.team_id {
let id = format!("\"{id}\"");
pbxproj.set_build_settings(&build_configuration_ref.id, "DEVELOPMENT_TEAM", &id);
pbxproj.set_build_settings(
&build_configuration_ref.id,
"\"DEVELOPMENT_TEAM[sdk=iphoneos*]\"",
&id,
);
}
if let Some(profile_uuid) = &project_config.provisioning_profile_uuid {
let profile_uuid = format!("\"{profile_uuid}\"");
pbxproj.set_build_settings(
&build_configuration_ref.id,
"PROVISIONING_PROFILE_SPECIFIER",
&profile_uuid,
);
pbxproj.set_build_settings(
&build_configuration_ref.id,
"\"PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]\"",
&profile_uuid,
);
}
}
}
let build_configuration = {
if let Some(xc_configuration_list) = pbxproj
.xc_configuration_list
.clone()
.into_values()
.find(|l| l.comment.contains("_iOS"))
{
let mut configuration = None;
let target = if debug { "debug" } else { "release" };
for build_configuration_ref in xc_configuration_list.build_configurations {
if build_configuration_ref.comments.contains(target) {
configuration = pbxproj
.xc_build_configuration
.get(&build_configuration_ref.id);
break;
}
}
configuration
} else {
None
}
};
if let Some(build_configuration) = build_configuration {
if let Some(style) = build_configuration.get_build_setting("CODE_SIGN_STYLE") {
export_options_plist.insert(
"signingStyle".to_string(),
style.value.to_lowercase().into(),
);
} else {
export_options_plist.insert("signingStyle".to_string(), "automatic".into());
}
if manual_signing {
if let Some(identity) = build_configuration
.get_build_setting("\"CODE_SIGN_IDENTITY[sdk=iphoneos*]\"")
.or_else(|| build_configuration.get_build_setting("CODE_SIGN_IDENTITY"))
{
export_options_plist.insert(
"signingCertificate".to_string(),
identity.value.trim_matches('"').into(),
);
}
let profile_uuid = project_config
.provisioning_profile_uuid
.clone()
.or_else(|| {
build_configuration
.get_build_setting("\"PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]\"")
.or_else(|| build_configuration.get_build_setting("PROVISIONING_PROFILE_SPECIFIER"))
.map(|setting| setting.value.trim_matches('"').to_string())
});
if let Some(profile_uuid) = profile_uuid {
let mut provisioning_profiles = plist::Dictionary::new();
provisioning_profiles.insert(config.app().identifier().to_string(), profile_uuid.into());
export_options_plist.insert(
"provisioningProfiles".to_string(),
provisioning_profiles.into(),
);
}
}
if let Some(id) = build_configuration
.get_build_setting("\"DEVELOPMENT_TEAM[sdk=iphoneos*]\"")
.or_else(|| build_configuration.get_build_setting("DEVELOPMENT_TEAM"))
{
export_options_plist.insert("teamID".to_string(), id.value.trim_matches('"').into());
}
}
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/mobile/ios/run.rs | crates/tauri-cli/src/mobile/ios/run.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::path::PathBuf;
use cargo_mobile2::opts::{NoiseLevel, Profile};
use clap::{ArgAction, Parser};
use super::{device_prompt, env};
use crate::{
error::Context,
interface::{DevProcess, Interface, WatcherOptions},
mobile::{DevChild, TargetDevice},
ConfigValue, Result,
};
#[derive(Debug, Clone, Parser)]
#[clap(
about = "Run your app in production mode on iOS",
long_about = "Run your app in production mode on iOS. It makes use of the `build.frontendDist` property from your `tauri.conf.json` file. It also runs your `build.beforeBuildCommand` which usually builds your frontend into `build.frontendDist`."
)]
pub struct Options {
/// Run the app in release mode
#[clap(short, long)]
pub release: bool,
/// List of cargo features to activate
#[clap(short, long, action = ArgAction::Append, num_args(0..))]
pub features: Vec<String>,
/// JSON strings or paths to JSON, JSON5 or TOML files to merge with the default configuration file
///
/// Configurations are merged in the order they are provided, which means a particular value overwrites previous values when a config key-value pair conflicts.
///
/// Note that a platform-specific file is looked up and merged with the default file by default
/// (tauri.macos.conf.json, tauri.linux.conf.json, tauri.windows.conf.json, tauri.android.conf.json and tauri.ios.conf.json)
/// but you can use this for more specific use cases such as different build flavors.
#[clap(short, long)]
pub config: Vec<ConfigValue>,
/// Disable the file watcher
#[clap(long)]
pub no_watch: bool,
/// Additional paths to watch for changes.
#[clap(long)]
pub additional_watch_folders: Vec<PathBuf>,
/// Open Xcode
#[clap(short, long)]
pub open: bool,
/// Runs on the given device name
pub device: Option<String>,
/// Command line arguments passed to the runner.
/// Use `--` to explicitly mark the start of the arguments.
/// e.g. `tauri android build -- [runnerArgs]`.
#[clap(last(true))]
pub args: Vec<String>,
/// Do not error out if a version mismatch is detected on a Tauri package.
///
/// Only use this when you are sure the mismatch is incorrectly detected as version mismatched Tauri packages can lead to unknown behavior.
#[clap(long)]
pub ignore_version_mismatches: bool,
}
pub fn command(options: Options, noise_level: NoiseLevel) -> Result<()> {
let env = env().context("failed to load iOS environment")?;
let device = if options.open {
None
} else {
match device_prompt(&env, options.device.as_deref()) {
Ok(d) => Some(d),
Err(e) => {
log::error!("{e}");
None
}
}
};
let mut built_application = super::build::command(
super::build::Options {
debug: !options.release,
targets: Some(vec![]), /* skips IPA build since there's no target */
features: Vec::new(),
config: options.config.clone(),
build_number: None,
open: options.open,
ci: false,
export_method: None,
args: options.args,
ignore_version_mismatches: options.ignore_version_mismatches,
target_device: device.as_ref().map(|d| TargetDevice {
id: d.id().to_string(),
name: d.name().to_string(),
}),
},
noise_level,
)?;
// options.open is handled by the build command
// so all we need to do here is run the app on the selected device
if let Some(device) = device {
let runner = move || {
device
.run(
&built_application.config,
&env,
noise_level,
false, // do not quit on app exit
if !options.release {
Profile::Debug
} else {
Profile::Release
},
)
.map(|c| Box::new(DevChild::new(c)) as Box<dyn DevProcess + Send>)
.context("failed to run iOS app")
};
if options.no_watch {
runner()?;
} else {
built_application.interface.watch(
WatcherOptions {
config: options.config,
additional_watch_folders: options.additional_watch_folders,
},
runner,
)?;
}
}
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/mobile/ios/project.rs | crates/tauri-cli/src/mobile/ios/project.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{
error::Context,
helpers::{config::Config as TauriConfig, template},
mobile::ios::LIB_OUTPUT_FILE_NAME,
Error, ErrorExt, Result,
};
use cargo_mobile2::{
apple::{
config::{Config, Metadata},
deps,
target::Target,
},
config::app::DEFAULT_ASSET_DIR,
target::TargetTrait as _,
util::{self, cli::TextWrapper},
};
use handlebars::Handlebars;
use include_dir::{include_dir, Dir};
use std::{
ffi::OsString,
fs::{create_dir_all, OpenOptions},
path::{Component, PathBuf},
};
const TEMPLATE_DIR: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/templates/mobile/ios");
// unprefixed app_root seems pretty dangerous!!
// TODO: figure out what cargo-mobile meant by that
#[allow(clippy::too_many_arguments)]
pub fn gen(
tauri_config: &TauriConfig,
config: &Config,
metadata: &Metadata,
(handlebars, mut map): (Handlebars, template::JsonMap),
wrapper: &TextWrapper,
non_interactive: bool,
reinstall_deps: bool,
skip_targets_install: bool,
) -> Result<()> {
if !skip_targets_install {
let installed_targets =
crate::interface::rust::installation::installed_targets().unwrap_or_default();
let missing_targets = Target::all()
.values()
.filter(|t| !installed_targets.contains(&t.triple().into()))
.collect::<Vec<&Target>>();
if !missing_targets.is_empty() {
log::info!("Installing iOS Rust targets...");
for target in missing_targets {
log::info!("Installing target {}", target.triple());
target.install().map_err(|error| Error::CommandFailed {
command: "rustup target add".to_string(),
error,
})?;
}
}
}
deps::install_all(wrapper, non_interactive, true, reinstall_deps).map_err(|error| {
Error::CommandFailed {
command: "pod install".to_string(),
error: std::io::Error::other(error),
}
})?;
let dest = config.project_dir();
let rel_prefix = util::relativize_path(config.app().root_dir(), &dest);
let source_dirs = vec![rel_prefix.join("src")];
let asset_catalogs = metadata.ios().asset_catalogs().unwrap_or_default();
let ios_pods = metadata.ios().pods().unwrap_or_default();
let macos_pods = metadata.macos().pods().unwrap_or_default();
#[cfg(target_arch = "aarch64")]
let default_archs = ["arm64"];
#[cfg(not(target_arch = "aarch64"))]
let default_archs = ["arm64", "x86_64"];
map.insert("lib-output-file-name", LIB_OUTPUT_FILE_NAME);
map.insert("file-groups", &source_dirs);
map.insert("ios-frameworks", metadata.ios().frameworks());
map.insert("ios-valid-archs", default_archs);
map.insert("ios-vendor-frameworks", metadata.ios().vendor_frameworks());
map.insert("ios-vendor-sdks", metadata.ios().vendor_sdks());
map.insert("macos-frameworks", metadata.macos().frameworks());
map.insert(
"macos-vendor-frameworks",
metadata.macos().vendor_frameworks(),
);
map.insert("macos-vendor-sdks", metadata.macos().vendor_frameworks());
map.insert("asset-catalogs", asset_catalogs);
map.insert("ios-pods", ios_pods);
map.insert("macos-pods", macos_pods);
map.insert(
"ios-additional-targets",
metadata.ios().additional_targets(),
);
map.insert(
"macos-additional-targets",
metadata.macos().additional_targets(),
);
map.insert("ios-pre-build-scripts", metadata.ios().pre_build_scripts());
map.insert(
"ios-post-compile-scripts",
metadata.ios().post_compile_scripts(),
);
map.insert(
"ios-post-build-scripts",
metadata.ios().post_build_scripts(),
);
map.insert(
"macos-pre-build-scripts",
metadata.macos().pre_build_scripts(),
);
map.insert(
"macos-post-compile-scripts",
metadata.macos().post_compile_scripts(),
);
map.insert(
"macos-post-build-scripts",
metadata.macos().post_build_scripts(),
);
map.insert(
"ios-command-line-arguments",
metadata.ios().command_line_arguments(),
);
map.insert(
"macos-command-line-arguments",
metadata.macos().command_line_arguments(),
);
let mut created_dirs = Vec::new();
template::render_with_generator(
&handlebars,
map.inner(),
&TEMPLATE_DIR,
&dest,
&mut |path| {
let mut components: Vec<_> = path.components().collect();
let mut new_component = None;
for component in &mut components {
if let Component::Normal(c) = component {
let c = c.to_string_lossy();
if c.contains("{{app.name}}") {
new_component.replace(OsString::from(
&c.replace("{{app.name}}", config.app().name()),
));
*component = Component::Normal(new_component.as_ref().unwrap());
break;
}
}
}
let path = dest.join(components.iter().collect::<PathBuf>());
let parent = path.parent().unwrap().to_path_buf();
if !created_dirs.contains(&parent) {
create_dir_all(&parent)?;
created_dirs.push(parent);
}
let mut options = OpenOptions::new();
options.write(true);
if !path.exists() {
options.create(true).open(path).map(Some)
} else {
Ok(None)
}
},
)
.with_context(|| "failed to process template")?;
if let Some(template_path) = tauri_config.bundle.ios.template.as_ref() {
let template = std::fs::read_to_string(template_path).fs_context(
"failed to read custom Xcode project template",
template_path.to_path_buf(),
)?;
let mut output_file = std::fs::File::create(dest.join("project.yml")).fs_context(
"failed to create project.yml file",
dest.join("project.yml"),
)?;
handlebars
.render_template_to_write(&template, map.inner(), &mut output_file)
.expect("Failed to render template");
}
let mut dirs_to_create = asset_catalogs.to_vec();
dirs_to_create.push(dest.join(DEFAULT_ASSET_DIR));
dirs_to_create.push(dest.join("Externals"));
dirs_to_create.push(dest.join(format!("{}_iOS", config.app().name())));
// Create all required project directories if they don't already exist
for dir in &dirs_to_create {
std::fs::create_dir_all(dir).fs_context("failed to create directory", dir.to_path_buf())?;
}
// Note that Xcode doesn't always reload the project nicely; reopening is
// often necessary.
println!("Generating Xcode project...");
duct::cmd(
"xcodegen",
[
"generate",
"--spec",
&dest.join("project.yml").to_string_lossy(),
],
)
.stdout_file(os_pipe::dup_stdout().unwrap())
.stderr_file(os_pipe::dup_stderr().unwrap())
.run()
.map_err(|error| Error::CommandFailed {
command: "xcodegen".to_string(),
error,
})?;
if !ios_pods.is_empty() || !macos_pods.is_empty() {
duct::cmd(
"pod",
[
"install",
&format!("--project-directory={}", dest.display()),
],
)
.stdout_file(os_pipe::dup_stdout().unwrap())
.stderr_file(os_pipe::dup_stderr().unwrap())
.run()
.map_err(|error| Error::CommandFailed {
command: "pod install".to_string(),
error,
})?;
}
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/acl/mod.rs | crates/tauri-cli/src/acl/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::error::Context;
use serde::Serialize;
use std::fmt::Display;
pub mod capability;
pub mod permission;
#[derive(Debug, clap::ValueEnum, Clone)]
enum FileFormat {
Json,
Toml,
}
impl Display for FileFormat {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Json => write!(f, "json"),
Self::Toml => write!(f, "toml"),
}
}
}
impl FileFormat {
pub fn extension(&self) -> &'static str {
match self {
Self::Json => "json",
Self::Toml => "toml",
}
}
pub fn serialize<S: Serialize>(&self, s: &S) -> crate::Result<String> {
let contents = match self {
Self::Json => serde_json::to_string_pretty(s).context("failed to serialize JSON")?,
Self::Toml => toml_edit::ser::to_string_pretty(s).context("failed to serialize TOML")?,
};
Ok(contents)
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/acl/capability/mod.rs | crates/tauri-cli/src/acl/capability/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use clap::{Parser, Subcommand};
use crate::Result;
mod new;
#[derive(Debug, Parser)]
#[clap(about = "Manage or create capabilities for your app")]
pub struct Cli {
#[clap(subcommand)]
command: Commands,
}
#[derive(Subcommand, Debug)]
enum Commands {
#[clap(alias = "create")]
New(new::Options),
}
pub fn command(cli: Cli) -> Result<()> {
match cli.command {
Commands::New(options) => new::command(options),
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/acl/capability/new.rs | crates/tauri-cli/src/acl/capability/new.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{collections::HashSet, path::PathBuf};
use clap::Parser;
use tauri_utils::acl::capability::{Capability, PermissionEntry};
use crate::{
acl::FileFormat,
error::ErrorExt,
helpers::{app_paths::tauri_dir, prompts},
Result,
};
#[derive(Debug, Parser)]
#[clap(about = "Create a new permission file")]
pub struct Options {
/// Capability identifier.
identifier: Option<String>,
/// Capability description
#[clap(long)]
description: Option<String>,
/// Capability windows
#[clap(long)]
windows: Option<Vec<String>>,
/// Capability permissions
#[clap(long)]
permission: Option<Vec<String>>,
/// Output file format.
#[clap(long, default_value_t = FileFormat::Json)]
format: FileFormat,
/// The output file.
#[clap(short, long)]
out: Option<PathBuf>,
}
pub fn command(options: Options) -> Result<()> {
crate::helpers::app_paths::resolve();
let identifier = match options.identifier {
Some(i) => i,
None => prompts::input("What's the capability identifier?", None, false, false)?.unwrap(),
};
let description = match options.description {
Some(d) => Some(d),
None => prompts::input::<String>("What's the capability description?", None, false, true)?
.and_then(|d| if d.is_empty() { None } else { Some(d) }),
};
let windows = match options.windows.map(FromIterator::from_iter) {
Some(w) => w,
None => prompts::input::<String>(
"Which windows should be affected by this? (comma separated)",
Some("main".into()),
false,
false,
)?
.and_then(|d| {
if d.is_empty() {
None
} else {
Some(d.split(',').map(ToString::to_string).collect())
}
})
.unwrap_or_default(),
};
let permissions: HashSet<String> = match options.permission.map(FromIterator::from_iter) {
Some(p) => p,
None => prompts::input::<String>(
"What permissions to enable? (comma separated)",
None,
false,
true,
)?
.and_then(|p| {
if p.is_empty() {
None
} else {
Some(p.split(',').map(ToString::to_string).collect())
}
})
.unwrap_or_default(),
};
let capability = Capability {
identifier,
description: description.unwrap_or_default(),
remote: None,
local: true,
windows,
webviews: Vec::new(),
permissions: permissions
.into_iter()
.map(|p| {
PermissionEntry::PermissionRef(
p.clone()
.try_into()
.unwrap_or_else(|_| panic!("invalid permission {p}")),
)
})
.collect(),
platforms: None,
};
let path = match options.out {
Some(o) => o
.canonicalize()
.fs_context("failed to canonicalize capability file path", o.clone())?,
None => {
let dir = tauri_dir();
let capabilities_dir = dir.join("capabilities");
capabilities_dir.join(format!(
"{}.{}",
capability.identifier,
options.format.extension()
))
}
};
if path.exists() {
let msg = format!(
"Capability already exists at {}",
dunce::simplified(&path).display()
);
let overwrite = prompts::confirm(&format!("{msg}, overwrite?"), Some(false))?;
if overwrite {
std::fs::remove_file(&path).fs_context("failed to remove capability file", path.clone())?;
} else {
crate::error::bail!(msg);
}
}
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).fs_context(
"failed to create capability directory",
parent.to_path_buf(),
)?;
}
std::fs::write(&path, options.format.serialize(&capability)?)
.fs_context("failed to write capability file", path.clone())?;
log::info!(action = "Created"; "capability at {}", dunce::simplified(&path).display());
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/acl/permission/ls.rs | crates/tauri-cli/src/acl/permission/ls.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use clap::Parser;
use crate::{
error::{Context, ErrorExt},
helpers::app_paths::tauri_dir,
Result,
};
use colored::Colorize;
use tauri_utils::acl::{manifest::Manifest, APP_ACL_KEY};
use std::{collections::BTreeMap, fs::read_to_string};
#[derive(Debug, Parser)]
#[clap(about = "List permissions available to your application")]
pub struct Options {
/// Name of the plugin to list permissions.
plugin: Option<String>,
/// Permission identifier filter.
#[clap(short, long)]
filter: Option<String>,
}
pub fn command(options: Options) -> Result<()> {
crate::helpers::app_paths::resolve();
let acl_manifests_path = tauri_dir()
.join("gen")
.join("schemas")
.join("acl-manifests.json");
if acl_manifests_path.exists() {
let plugin_manifest_json = read_to_string(&acl_manifests_path)
.fs_context("failed to read plugin manifest", acl_manifests_path)?;
let acl = serde_json::from_str::<BTreeMap<String, Manifest>>(&plugin_manifest_json)
.context("failed to parse plugin manifest as JSON")?;
for (key, manifest) in acl {
if options
.plugin
.as_ref()
.map(|p| p != &key)
.unwrap_or_default()
{
continue;
}
let mut permissions = Vec::new();
let prefix = if key == APP_ACL_KEY {
"".to_string()
} else {
format!("{}:", key.magenta())
};
if let Some(default) = manifest.default_permission {
if options
.filter
.as_ref()
.map(|f| "default".contains(f))
.unwrap_or(true)
{
permissions.push(format!(
"{prefix}{}\n{}\nPermissions: {}",
"default".cyan(),
default.description,
default
.permissions
.iter()
.map(|c| c.cyan().to_string())
.collect::<Vec<_>>()
.join(", ")
));
}
}
for set in manifest.permission_sets.values() {
if options
.filter
.as_ref()
.map(|f| set.identifier.contains(f))
.unwrap_or(true)
{
permissions.push(format!(
"{prefix}{}\n{}\nPermissions: {}",
set.identifier.cyan(),
set.description,
set
.permissions
.iter()
.map(|c| c.cyan().to_string())
.collect::<Vec<_>>()
.join(", ")
));
}
}
for permission in manifest.permissions.into_values() {
if options
.filter
.as_ref()
.map(|f| permission.identifier.contains(f))
.unwrap_or(true)
{
permissions.push(format!(
"{prefix}{}{}{}{}",
permission.identifier.cyan(),
permission
.description
.map(|d| format!("\n{d}"))
.unwrap_or_default(),
if permission.commands.allow.is_empty() {
"".to_string()
} else {
format!(
"\n{}: {}",
"Allow commands".bold(),
permission
.commands
.allow
.iter()
.map(|c| c.green().to_string())
.collect::<Vec<_>>()
.join(", ")
)
},
if permission.commands.deny.is_empty() {
"".to_string()
} else {
format!(
"\n{}: {}",
"Deny commands".bold(),
permission
.commands
.deny
.iter()
.map(|c| c.red().to_string())
.collect::<Vec<_>>()
.join(", ")
)
},
));
}
}
if !permissions.is_empty() {
println!("{}\n", permissions.join("\n\n"));
}
}
Ok(())
} else {
crate::error::bail!("permission file not found, please build your application once first")
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/acl/permission/rm.rs | crates/tauri-cli/src/acl/permission/rm.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::path::Path;
use clap::Parser;
use tauri_utils::acl::{manifest::PermissionFile, PERMISSION_SCHEMA_FILE_NAME};
use crate::{
acl::FileFormat,
error::{Context, ErrorExt},
helpers::app_paths::resolve_tauri_dir,
Result,
};
fn rm_permission_files(identifier: &str, dir: &Path) -> Result<()> {
for entry in std::fs::read_dir(dir)
.fs_context("failed to read permissions directory", dir.to_path_buf())?
.flatten()
{
let file_type = entry
.file_type()
.fs_context("failed to get permission file type", entry.path())?;
let path = entry.path();
if file_type.is_dir() {
rm_permission_files(identifier, &path)?;
} else {
if path
.file_name()
.map(|name| name == PERMISSION_SCHEMA_FILE_NAME)
.unwrap_or_default()
{
continue;
}
let (mut permission_file, format): (PermissionFile, FileFormat) =
match path.extension().and_then(|o| o.to_str()) {
Some("toml") => {
let content = std::fs::read_to_string(&path)
.fs_context("failed to read permission file", path.clone())?;
(
toml::from_str(&content).context("failed to deserialize permission file")?,
FileFormat::Toml,
)
}
Some("json") => {
let content =
std::fs::read(&path).fs_context("failed to read permission file", path.clone())?;
(
serde_json::from_slice(&content)
.context("failed to parse permission file as JSON")?,
FileFormat::Json,
)
}
_ => {
continue;
}
};
let mut updated;
if identifier == "default" {
updated = permission_file.default.is_some();
permission_file.default = None;
} else {
let set_len = permission_file.set.len();
permission_file
.set
.retain(|s| !identifier_match(identifier, &s.identifier));
updated = permission_file.set.len() != set_len;
let permission_len = permission_file.permission.len();
permission_file
.permission
.retain(|s| !identifier_match(identifier, &s.identifier));
updated = updated || permission_file.permission.len() != permission_len;
}
// if the file is empty, let's remove it
if permission_file.default.is_none()
&& permission_file.set.is_empty()
&& permission_file.permission.is_empty()
{
std::fs::remove_file(&path).fs_context("failed to remove permission file", path.clone())?;
log::info!(action = "Removed"; "file {}", dunce::simplified(&path).display());
} else if updated {
std::fs::write(
&path,
format
.serialize(&permission_file)
.context("failed to serialize permission")?,
)
.fs_context("failed to write permission file", path.clone())?;
log::info!(action = "Removed"; "permission {identifier} from {}", dunce::simplified(&path).display());
}
}
}
Ok(())
}
fn rm_permission_from_capabilities(identifier: &str, dir: &Path) -> Result<()> {
for entry in std::fs::read_dir(dir)
.fs_context("failed to read capabilities directory", dir.to_path_buf())?
.flatten()
{
let file_type = entry
.file_type()
.fs_context("failed to get capability file type", entry.path())?;
if file_type.is_file() {
let path = entry.path();
match path.extension().and_then(|o| o.to_str()) {
Some("toml") => {
let content = std::fs::read_to_string(&path)
.fs_context("failed to read capability file", path.clone())?;
if let Ok(mut value) = content.parse::<toml_edit::DocumentMut>() {
if let Some(permissions) = value.get_mut("permissions").and_then(|p| p.as_array_mut()) {
let prev_len = permissions.len();
permissions.retain(|p| match p {
toml_edit::Value::String(s) => !identifier_match(identifier, s.value()),
toml_edit::Value::InlineTable(o) => {
if let Some(toml_edit::Value::String(permission_name)) = o.get("identifier") {
return !identifier_match(identifier, permission_name.value());
}
true
}
_ => false,
});
if prev_len != permissions.len() {
std::fs::write(&path, value.to_string())
.fs_context("failed to write capability file", path.clone())?;
log::info!(action = "Removed"; "permission from capability at {}", dunce::simplified(&path).display());
}
}
}
}
Some("json") => {
let content =
std::fs::read(&path).fs_context("failed to read capability file", path.clone())?;
if let Ok(mut value) = serde_json::from_slice::<serde_json::Value>(&content) {
if let Some(permissions) = value.get_mut("permissions").and_then(|p| p.as_array_mut()) {
let prev_len = permissions.len();
permissions.retain(|p| match p {
serde_json::Value::String(s) => !identifier_match(identifier, s),
serde_json::Value::Object(o) => {
if let Some(serde_json::Value::String(permission_name)) = o.get("identifier") {
return !identifier_match(identifier, permission_name);
}
true
}
_ => false,
});
if prev_len != permissions.len() {
std::fs::write(
&path,
serde_json::to_vec_pretty(&value)
.context("failed to serialize capability JSON")?,
)
.fs_context("failed to write capability file", path.clone())?;
log::info!(action = "Removed"; "permission from capability at {}", dunce::simplified(&path).display());
}
}
}
}
_ => {}
}
}
}
Ok(())
}
fn identifier_match(identifier: &str, permission: &str) -> bool {
match identifier.split_once(':') {
Some((plugin_name, "*")) => permission.contains(plugin_name),
_ => permission == identifier,
}
}
#[derive(Debug, Parser)]
#[clap(about = "Remove a permission file, and its reference from any capability")]
pub struct Options {
/// Permission to remove.
///
/// To remove all permissions for a given plugin, provide `<plugin-name>:*`
pub identifier: String,
}
pub fn command(options: Options) -> Result<()> {
let permissions_dir = std::env::current_dir()
.context("failed to resolve current directory")?
.join("permissions");
if permissions_dir.exists() {
rm_permission_files(&options.identifier, &permissions_dir)?;
}
if let Some(tauri_dir) = resolve_tauri_dir() {
let capabilities_dir = tauri_dir.join("capabilities");
if capabilities_dir.exists() {
rm_permission_from_capabilities(&options.identifier, &capabilities_dir)?;
}
}
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/acl/permission/mod.rs | crates/tauri-cli/src/acl/permission/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use clap::{Parser, Subcommand};
use crate::Result;
pub mod add;
mod ls;
mod new;
pub mod rm;
#[derive(Debug, Parser)]
#[clap(about = "Manage or create permissions for your app or plugin")]
pub struct Cli {
#[clap(subcommand)]
command: Commands,
}
#[derive(Subcommand, Debug)]
enum Commands {
#[clap(alias = "create")]
New(new::Options),
Add(add::Options),
#[clap(alias = "remove")]
Rm(rm::Options),
#[clap(alias = "list")]
Ls(ls::Options),
}
pub fn command(cli: Cli) -> Result<()> {
match cli.command {
Commands::New(options) => new::command(options),
Commands::Add(options) => add::command(options),
Commands::Rm(options) => rm::command(options),
Commands::Ls(options) => ls::command(options),
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/acl/permission/add.rs | crates/tauri-cli/src/acl/permission/add.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::path::Path;
use clap::Parser;
use crate::{
error::{Context, ErrorExt},
helpers::{app_paths::resolve_tauri_dir, prompts},
Result,
};
#[derive(Clone)]
enum TomlOrJson {
Toml(toml_edit::DocumentMut),
Json(serde_json::Value),
}
impl TomlOrJson {
fn identifier(&self) -> &str {
match self {
TomlOrJson::Toml(t) => t
.get("identifier")
.and_then(|k| k.as_str())
.unwrap_or_default(),
TomlOrJson::Json(j) => j
.get("identifier")
.and_then(|k| k.as_str())
.unwrap_or_default(),
}
}
fn platforms(&self) -> Option<Vec<&str>> {
match self {
TomlOrJson::Toml(t) => t.get("platforms").and_then(|k| {
k.as_array()
.and_then(|array| array.iter().map(|v| v.as_str()).collect())
}),
TomlOrJson::Json(j) => j.get("platforms").and_then(|k| {
if let Some(array) = k.as_array() {
let mut items = Vec::new();
for item in array {
if let Some(s) = item.as_str() {
items.push(s);
}
}
Some(items)
} else {
None
}
}),
}
}
fn insert_permission(&mut self, identifier: String) {
match self {
TomlOrJson::Toml(t) => {
let permissions = t.entry("permissions").or_insert_with(|| {
toml_edit::Item::Value(toml_edit::Value::Array(toml_edit::Array::new()))
});
if let Some(permissions) = permissions.as_array_mut() {
permissions.push(identifier)
};
}
TomlOrJson::Json(j) => {
if let Some(o) = j.as_object_mut() {
let permissions = o
.entry("permissions")
.or_insert_with(|| serde_json::Value::Array(Vec::new()));
if let Some(permissions) = permissions.as_array_mut() {
permissions.push(serde_json::Value::String(identifier))
};
}
}
};
}
fn has_permission(&self, identifier: &str) -> bool {
(|| {
Some(match self {
TomlOrJson::Toml(t) => t
.get("permissions")?
.as_array()?
.iter()
.any(|value| value.as_str() == Some(identifier)),
TomlOrJson::Json(j) => j
.as_object()?
.get("permissions")?
.as_array()?
.iter()
.any(|value| value.as_str() == Some(identifier)),
})
})()
.unwrap_or_default()
}
fn to_string(&self) -> Result<String> {
Ok(match self {
TomlOrJson::Toml(t) => t.to_string(),
TomlOrJson::Json(j) => {
serde_json::to_string_pretty(&j).context("failed to serialize JSON")?
}
})
}
}
fn capability_from_path<P: AsRef<Path>>(path: P) -> Option<TomlOrJson> {
match path.as_ref().extension().and_then(|o| o.to_str()) {
Some("toml") => std::fs::read_to_string(&path)
.ok()
.and_then(|c| c.parse::<toml_edit::DocumentMut>().ok())
.map(TomlOrJson::Toml),
Some("json") => std::fs::read(&path)
.ok()
.and_then(|c| serde_json::from_slice::<serde_json::Value>(&c).ok())
.map(TomlOrJson::Json),
_ => None,
}
}
#[derive(Debug, Parser)]
#[clap(about = "Add a permission to capabilities")]
pub struct Options {
/// Permission to add.
pub identifier: String,
/// Capability to add the permission to.
pub capability: Option<String>,
}
pub fn command(options: Options) -> Result<()> {
let dir = match resolve_tauri_dir() {
Some(t) => t,
None => std::env::current_dir().context("failed to resolve current directory")?,
};
let capabilities_dir = dir.join("capabilities");
if !capabilities_dir.exists() {
crate::error::bail!(
"Couldn't find capabilities directory at {}",
dunce::simplified(&capabilities_dir).display()
);
}
let known_plugins = crate::helpers::plugins::known_plugins();
let known_plugin = options
.identifier
.split_once(':')
.and_then(|(plugin, _permission)| known_plugins.get(&plugin));
let capabilities_iter = std::fs::read_dir(&capabilities_dir)
.fs_context(
"failed to read capabilities directory",
capabilities_dir.clone(),
)?
.flatten()
.filter(|e| e.file_type().map(|e| e.is_file()).unwrap_or_default())
.filter_map(|e| {
let path = e.path();
capability_from_path(&path).and_then(|capability| match &options.capability {
Some(c) => (c == capability.identifier()).then_some((capability, path)),
None => Some((capability, path)),
})
});
let (desktop_only, mobile_only) = known_plugin
.map(|p| (p.desktop_only, p.mobile_only))
.unwrap_or_default();
let expected_capability_config = if desktop_only {
Some((
vec![
tauri_utils::platform::Target::MacOS.to_string(),
tauri_utils::platform::Target::Windows.to_string(),
tauri_utils::platform::Target::Linux.to_string(),
],
"desktop",
))
} else if mobile_only {
Some((
vec![
tauri_utils::platform::Target::Android.to_string(),
tauri_utils::platform::Target::Ios.to_string(),
],
"mobile",
))
} else {
None
};
let capabilities = if let Some((expected_platforms, target_name)) = expected_capability_config {
let mut capabilities = capabilities_iter
.filter(|(capability, _path)| {
capability.platforms().is_some_and(|platforms| {
// all platforms must be in the expected platforms list
platforms
.iter()
.all(|p| expected_platforms.contains(&p.to_string()))
})
})
.collect::<Vec<_>>();
if capabilities.is_empty() {
let identifier = format!("{target_name}-capability");
let capability_path = capabilities_dir.join(target_name).with_extension("json");
log::info!(
"Capability matching platforms {expected_platforms:?} not found, creating {}",
capability_path.display()
);
capabilities.push((
TomlOrJson::Json(serde_json::json!({
"identifier": identifier,
"platforms": expected_platforms,
"windows": ["main"]
})),
capability_path,
));
}
capabilities
} else {
capabilities_iter.collect::<Vec<_>>()
};
let mut capabilities = if capabilities.len() > 1 {
let selections = prompts::multiselect(
&format!(
"Choose which capabilities to add the permission `{}` to:",
options.identifier
),
capabilities
.iter()
.map(|(c, p)| {
let id = c.identifier();
if id.is_empty() {
dunce::simplified(p).to_str().unwrap_or_default()
} else {
id
}
})
.collect::<Vec<_>>()
.as_slice(),
None,
)?;
if selections.is_empty() {
crate::error::bail!("You did not select any capabilities to update");
}
selections
.into_iter()
.map(|idx| capabilities[idx].clone())
.collect()
} else {
capabilities
};
if capabilities.is_empty() {
crate::error::bail!("Could not find a capability to update");
}
for (capability, path) in &mut capabilities {
if capability.has_permission(&options.identifier) {
log::info!(
"Permission `{}` already found in `{}` at {}",
options.identifier,
capability.identifier(),
dunce::simplified(path).display()
);
} else {
capability.insert_permission(options.identifier.clone());
std::fs::write(&*path, capability.to_string()?)
.fs_context("failed to write capability file", path.clone())?;
log::info!(action = "Added"; "permission `{}` to `{}` at {}", options.identifier, capability.identifier(), dunce::simplified(path).display());
}
}
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/acl/permission/new.rs | crates/tauri-cli/src/acl/permission/new.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::path::PathBuf;
use clap::Parser;
use crate::{
acl::FileFormat,
error::{Context, ErrorExt},
helpers::{app_paths::resolve_tauri_dir, prompts},
Result,
};
use tauri_utils::acl::{manifest::PermissionFile, Commands, Permission};
#[derive(Debug, Parser)]
#[clap(about = "Create a new permission file")]
pub struct Options {
/// Permission identifier.
identifier: Option<String>,
/// Permission description
#[clap(long)]
description: Option<String>,
/// List of commands to allow
#[clap(short, long, use_value_delimiter = true)]
allow: Option<Vec<String>>,
/// List of commands to deny
#[clap(short, long, use_value_delimiter = true)]
deny: Option<Vec<String>>,
/// Output file format.
#[clap(long, default_value_t = FileFormat::Json)]
format: FileFormat,
/// The output file.
#[clap(short, long)]
out: Option<PathBuf>,
}
pub fn command(options: Options) -> Result<()> {
let identifier = match options.identifier {
Some(i) => i,
None => prompts::input("What's the permission identifier?", None, false, false)?.unwrap(),
};
let description = match options.description {
Some(d) => Some(d),
None => prompts::input::<String>("What's the permission description?", None, false, true)?
.and_then(|d| if d.is_empty() { None } else { Some(d) }),
};
let allow: Vec<String> = options
.allow
.map(FromIterator::from_iter)
.unwrap_or_default();
let deny: Vec<String> = options
.deny
.map(FromIterator::from_iter)
.unwrap_or_default();
let permission = Permission {
version: None,
identifier,
description,
commands: Commands { allow, deny },
scope: Default::default(),
platforms: Default::default(),
};
let path = match options.out {
Some(o) => o
.canonicalize()
.fs_context("failed to canonicalize permission file path", o.clone())?,
None => {
let dir = match resolve_tauri_dir() {
Some(t) => t,
None => std::env::current_dir().context("failed to resolve current directory")?,
};
let permissions_dir = dir.join("permissions");
permissions_dir.join(format!(
"{}.{}",
permission.identifier,
options.format.extension()
))
}
};
if path.exists() {
let msg = format!(
"Permission already exists at {}",
dunce::simplified(&path).display()
);
let overwrite = prompts::confirm(&format!("{msg}, overwrite?"), Some(false))?;
if overwrite {
std::fs::remove_file(&path).fs_context("failed to remove permission file", path.clone())?;
} else {
crate::error::bail!(msg);
}
}
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).fs_context(
"failed to create permission directory",
parent.to_path_buf(),
)?;
}
std::fs::write(
&path,
options
.format
.serialize(&PermissionFile {
default: None,
set: Vec::new(),
permission: vec![permission],
})
.context("failed to serialize permission")?,
)
.fs_context("failed to write permission file", path.clone())?;
log::info!(action = "Created"; "permission at {}", dunce::simplified(&path).display());
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/migrate/mod.rs | crates/tauri-cli/src/migrate/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{
error::{bail, Context, ErrorExt},
helpers::{
app_paths::tauri_dir,
cargo_manifest::{crate_version, CargoLock, CargoManifest},
},
interface::rust::get_workspace_dir,
Result,
};
use std::{fs::read_to_string, str::FromStr};
mod migrations;
pub fn command() -> Result<()> {
crate::helpers::app_paths::resolve();
let tauri_dir = tauri_dir();
let manifest_contents = read_to_string(tauri_dir.join("Cargo.toml")).fs_context(
"failed to read Cargo manifest",
tauri_dir.join("Cargo.toml"),
)?;
let manifest = toml::from_str::<CargoManifest>(&manifest_contents).with_context(|| {
format!(
"failed to parse Cargo manifest {}",
tauri_dir.join("Cargo.toml").display()
)
})?;
let workspace_dir = get_workspace_dir()?;
let lock_path = workspace_dir.join("Cargo.lock");
let lock = if lock_path.exists() {
let lockfile_contents =
read_to_string(&lock_path).fs_context("failed to read Cargo lockfile", &lock_path)?;
let lock = toml::from_str::<CargoLock>(&lockfile_contents)
.with_context(|| format!("failed to parse Cargo lockfile {}", lock_path.display()))?;
Some(lock)
} else {
None
};
let tauri_version = crate_version(tauri_dir, Some(&manifest), lock.as_ref(), "tauri")
.version
.context("failed to get tauri version")?;
let tauri_version = semver::Version::from_str(&tauri_version)
.with_context(|| format!("failed to parse tauri version {tauri_version}"))?;
if tauri_version.major == 1 {
migrations::v1::run().context("failed to migrate from v1")?;
} else if tauri_version.major == 2 {
if let Some((pre, _number)) = tauri_version.pre.as_str().split_once('.') {
match pre {
"beta" => {
migrations::v2_beta::run().context("failed to migrate from v2 beta")?;
}
"alpha" => {
bail!(
"Migrating from v2 alpha ({tauri_version}) to v2 stable is not supported yet, \
if your project started early, try downgrading to v1 and then try again"
)
}
_ => {
bail!("Migrating from {tauri_version} to v2 stable is not supported yet")
}
}
} else {
log::info!("Nothing to do, the tauri version is already at v2 stable");
}
}
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/migrate/migrations/mod.rs | crates/tauri-cli/src/migrate/migrations/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
pub mod v1;
pub mod v2_beta;
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/migrate/migrations/v2_beta.rs | crates/tauri-cli/src/migrate/migrations/v2_beta.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{
error::{Context, ErrorExt},
helpers::{
app_paths::{frontend_dir, tauri_dir},
npm::PackageManager,
},
interface::rust::manifest::{read_manifest, serialize_manifest},
Result,
};
use std::{fs::read_to_string, path::Path};
use toml_edit::{DocumentMut, Item, Table, TableLike, Value};
pub fn run() -> Result<()> {
let frontend_dir = frontend_dir();
let tauri_dir = tauri_dir();
let manifest_path = tauri_dir.join("Cargo.toml");
let (mut manifest, _) = read_manifest(&manifest_path)?;
migrate_manifest(&mut manifest)?;
migrate_permissions(tauri_dir)?;
migrate_npm_dependencies(frontend_dir)?;
std::fs::write(&manifest_path, serialize_manifest(&manifest))
.fs_context("failed to rewrite Cargo manifest", &manifest_path)?;
Ok(())
}
fn migrate_npm_dependencies(frontend_dir: &Path) -> Result<()> {
let pm = PackageManager::from_project(frontend_dir);
let mut install_deps = Vec::new();
for pkg in [
"@tauri-apps/cli",
"@tauri-apps/api",
"@tauri-apps/plugin-authenticator",
"@tauri-apps/plugin-autostart",
"@tauri-apps/plugin-barcode-scanner",
"@tauri-apps/plugin-biometric",
"@tauri-apps/plugin-cli",
"@tauri-apps/plugin-clipboard-manager",
"@tauri-apps/plugin-deep-link",
"@tauri-apps/plugin-dialog",
"@tauri-apps/plugin-fs",
"@tauri-apps/plugin-global-shortcut",
"@tauri-apps/plugin-http",
"@tauri-apps/plugin-log",
"@tauri-apps/plugin-nfc",
"@tauri-apps/plugin-notification",
"@tauri-apps/plugin-os",
"@tauri-apps/plugin-positioner",
"@tauri-apps/plugin-process",
"@tauri-apps/plugin-shell",
"@tauri-apps/plugin-sql",
"@tauri-apps/plugin-store",
"@tauri-apps/plugin-stronghold",
"@tauri-apps/plugin-updater",
"@tauri-apps/plugin-upload",
"@tauri-apps/plugin-websocket",
"@tauri-apps/plugin-window-state",
] {
let version = pm
.current_package_version(pkg, frontend_dir)
.unwrap_or_default()
.unwrap_or_default();
if version.starts_with('1') {
install_deps.push(format!("{pkg}@^2.0.0"));
}
}
if !install_deps.is_empty() {
pm.install(&install_deps, frontend_dir)?;
}
Ok(())
}
fn migrate_permissions(tauri_dir: &Path) -> Result<()> {
let core_plugins = [
"app",
"event",
"image",
"menu",
"path",
"resources",
"tray",
"webview",
"window",
];
for entry in walkdir::WalkDir::new(tauri_dir.join("capabilities")) {
let entry = entry.map_err(std::io::Error::other).fs_context(
"failed to walk capabilities directory",
tauri_dir.join("capabilities"),
)?;
let path = entry.path();
if path.extension().is_some_and(|ext| ext == "json") {
let mut capability =
read_to_string(path).fs_context("failed to read capability", path.to_path_buf())?;
for plugin in core_plugins {
capability = capability.replace(&format!("\"{plugin}:"), &format!("\"core:{plugin}:"));
}
std::fs::write(path, capability)
.fs_context("failed to rewrite capability", path.to_path_buf())?;
}
}
Ok(())
}
fn migrate_manifest(manifest: &mut DocumentMut) -> Result<()> {
let version = "2.0.0";
let dependencies = manifest
.as_table_mut()
.entry("dependencies")
.or_insert(Item::Table(Table::new()))
.as_table_mut()
.context("manifest dependencies isn't a table")?;
for dep in [
"tauri",
"tauri-plugin-authenticator",
"tauri-plugin-autostart",
"tauri-plugin-barcode-scanner",
"tauri-plugin-biometric",
"tauri-plugin-cli",
"tauri-plugin-clipboard-manager",
"tauri-plugin-deep-link",
"tauri-plugin-dialog",
"tauri-plugin-fs",
"tauri-plugin-global-shortcut",
"tauri-plugin-http",
"tauri-plugin-localhost",
"tauri-plugin-log",
"tauri-plugin-nfc",
"tauri-plugin-notification",
"tauri-plugin-os",
"tauri-plugin-persisted-scope",
"tauri-plugin-positioner",
"tauri-plugin-process",
"tauri-plugin-shell",
"tauri-plugin-single-instance",
"tauri-plugin-sql",
"tauri-plugin-store",
"tauri-plugin-stronghold",
"tauri-plugin-updater",
"tauri-plugin-upload",
"tauri-plugin-websocket",
"tauri-plugin-window-state",
] {
migrate_dependency(dependencies, dep, version);
}
let build_dependencies = manifest
.as_table_mut()
.entry("build-dependencies")
.or_insert(Item::Table(Table::new()))
.as_table_mut()
.context("manifest build-dependencies isn't a table")?;
migrate_dependency(build_dependencies, "tauri-build", version);
Ok(())
}
fn migrate_dependency(dependencies: &mut Table, name: &str, version: &str) {
let item = dependencies.entry(name).or_insert(Item::None);
// do not rewrite if dependency uses workspace inheritance
if item
.get("workspace")
.and_then(|v| v.as_bool())
.unwrap_or_default()
{
log::info!("`{name}` dependency has workspace inheritance enabled. The features array won't be automatically rewritten.");
return;
}
if let Some(dep) = item.as_table_mut() {
migrate_dependency_table(dep, version);
} else if let Some(Value::InlineTable(table)) = item.as_value_mut() {
migrate_dependency_table(table, version);
} else if item.as_str().is_some() {
*item = Item::Value(version.into());
}
}
fn migrate_dependency_table<D: TableLike>(dep: &mut D, version: &str) {
*dep.entry("version").or_insert(Item::None) = Item::Value(version.into());
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/migrate/migrations/v1/config.rs | crates/tauri-cli/src/migrate/migrations/v1/config.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{error::Context, ErrorExt, Result};
use serde_json::{Map, Value};
use tauri_utils::acl::{
capability::{Capability, PermissionEntry},
Scopes, Value as AclValue,
};
use std::{
collections::{BTreeMap, HashSet},
fs,
path::Path,
};
pub fn migrate(tauri_dir: &Path) -> Result<MigratedConfig> {
if let Ok((mut config, config_path)) =
tauri_utils::config_v1::parse::parse_value(tauri_dir.join("tauri.conf.json"))
{
let migrated = migrate_config(&mut config)?;
if config_path.extension().is_some_and(|ext| ext == "toml") {
fs::write(
&config_path,
toml::to_string_pretty(&config).context("failed to serialize config")?,
)
.fs_context("failed to write config", config_path.clone())?;
} else {
fs::write(
&config_path,
serde_json::to_string_pretty(&config).context("failed to serialize config")?,
)
.fs_context("failed to write config", config_path.clone())?;
}
let mut permissions: Vec<PermissionEntry> = vec!["core:default"]
.into_iter()
.map(|p| PermissionEntry::PermissionRef(p.to_string().try_into().unwrap()))
.collect();
permissions.extend(migrated.permissions.clone());
let capabilities_path = config_path.parent().unwrap().join("capabilities");
fs::create_dir_all(&capabilities_path).fs_context(
"failed to create capabilities directory",
capabilities_path.clone(),
)?;
fs::write(
capabilities_path.join("migrated.json"),
serde_json::to_string_pretty(&Capability {
identifier: "migrated".to_string(),
description: "permissions that were migrated from v1".into(),
local: true,
remote: None,
windows: vec!["main".into()],
webviews: vec![],
permissions,
platforms: None,
})
.context("failed to serialize capabilities")?,
)
.fs_context(
"failed to write capabilities",
capabilities_path.join("migrated.json"),
)?;
return Ok(migrated);
}
Ok(Default::default())
}
#[derive(Default)]
pub struct MigratedConfig {
pub permissions: Vec<PermissionEntry>,
pub plugins: HashSet<String>,
}
fn migrate_config(config: &mut Value) -> Result<MigratedConfig> {
let mut migrated = MigratedConfig {
permissions: Vec::new(),
plugins: HashSet::new(),
};
if let Some(config) = config.as_object_mut() {
process_package_metadata(config);
process_build(config);
let mut plugins = config
.entry("plugins")
.or_insert_with(|| Value::Object(Default::default()))
.as_object_mut()
.unwrap()
.clone();
if let Some(tauri_config) = config.get_mut("tauri").and_then(|c| c.as_object_mut()) {
// allowlist
if let Some(allowlist) = tauri_config.remove("allowlist") {
let allowlist = process_allowlist(tauri_config, allowlist)?;
let permissions = allowlist_to_permissions(allowlist);
migrated.plugins = plugins_from_permissions(&permissions);
migrated.permissions = permissions;
}
// dangerousUseHttpScheme/useHttpsScheme
let dangerous_use_http = tauri_config
.get("security")
.and_then(|w| w.as_object())
.and_then(|w| {
w.get("dangerousUseHttpScheme")
.or_else(|| w.get("dangerous-use-http-scheme"))
})
.and_then(|v| v.as_bool())
.unwrap_or_default();
if let Some(windows) = tauri_config
.get_mut("windows")
.and_then(|w| w.as_array_mut())
{
for window in windows {
if let Some(window) = window.as_object_mut() {
window.insert("useHttpsScheme".to_string(), (!dangerous_use_http).into());
}
}
}
// security
if let Some(security) = tauri_config
.get_mut("security")
.and_then(|c| c.as_object_mut())
{
process_security(security)?;
}
// tauri > pattern
if let Some(pattern) = tauri_config.remove("pattern") {
tauri_config
.entry("security")
.or_insert_with(|| Value::Object(Default::default()))
.as_object_mut()
.map(|s| s.insert("pattern".into(), pattern));
}
// system tray
if let Some((tray, key)) = tauri_config
.remove("systemTray")
.map(|v| (v, "trayIcon"))
.or_else(|| tauri_config.remove("system-tray").map(|v| (v, "tray-icon")))
{
tauri_config.insert(key.into(), tray);
}
// cli
if let Some(cli) = tauri_config.remove("cli") {
process_cli(&mut plugins, cli)?;
}
// updater
process_updater(tauri_config, &mut plugins, &mut migrated)?;
}
process_bundle(config, &migrated);
// if we have migrated the updater config, let's ensure createUpdaterArtifacts is set
if plugins.contains_key("updater") {
let bundle_config = config
.entry("bundle")
.or_insert_with(|| Value::Object(Default::default()))
.as_object_mut()
.unwrap();
if !bundle_config.contains_key("createUpdaterArtifacts") {
bundle_config.insert("createUpdaterArtifacts".to_owned(), "v1Compatible".into());
}
}
config.insert("plugins".into(), plugins.into());
if let Some(tauri_config) = config.remove("tauri") {
config.insert("app".into(), tauri_config);
}
}
Ok(migrated)
}
fn process_package_metadata(config: &mut Map<String, Value>) {
if let Some(mut package_config) = config.remove("package") {
if let Some(package_config) = package_config.as_object_mut() {
if let Some((product_name, key)) = package_config
.remove("productName")
.map(|v| (v, "productName"))
.or_else(|| {
package_config
.remove("product-name")
.map(|v| (v, "product-name"))
})
{
config.insert(key.into(), product_name.clone());
// keep main binary name unchanged
config.insert("mainBinaryName".into(), product_name);
}
if let Some(version) = package_config.remove("version") {
config.insert("version".into(), version);
}
}
}
if let Some(bundle_config) = config
.get_mut("tauri")
.and_then(|t| t.get_mut("bundle"))
.and_then(|b| b.as_object_mut())
{
if let Some(identifier) = bundle_config.remove("identifier") {
config.insert("identifier".into(), identifier);
}
}
}
fn process_build(config: &mut Map<String, Value>) {
if let Some(build_config) = config.get_mut("build").and_then(|b| b.as_object_mut()) {
if let Some((dist_dir, key)) = build_config
.remove("distDir")
.map(|v| (v, "frontendDist"))
.or_else(|| {
build_config
.remove("dist-dir")
.map(|v| (v, "frontend-dist"))
})
{
build_config.insert(key.into(), dist_dir);
}
if let Some((dev_path, key)) = build_config
.remove("devPath")
.map(|v| (v, "devUrl"))
.or_else(|| build_config.remove("dev-path").map(|v| (v, "dev-url")))
{
let is_url = url::Url::parse(dev_path.as_str().unwrap_or_default()).is_ok();
if is_url {
build_config.insert(key.into(), dev_path);
}
}
if let Some((with_global_tauri, key)) = build_config
.remove("withGlobalTauri")
.map(|v| (v, "withGlobalTauri"))
.or_else(|| {
build_config
.remove("with-global-tauri")
.map(|v| (v, "with-global-tauri"))
})
{
config
.get_mut("tauri")
.and_then(|t| t.as_object_mut())
.map(|t| t.insert(key.into(), with_global_tauri));
}
}
}
fn process_bundle(config: &mut Map<String, Value>, migrated: &MigratedConfig) {
let mut license_file = None;
if let Some(mut bundle_config) = config
.get_mut("tauri")
.and_then(|b| b.as_object_mut())
.and_then(|t| t.remove("bundle"))
{
if let Some(bundle_config) = bundle_config.as_object_mut() {
if let Some(deb) = bundle_config.remove("deb") {
bundle_config
.entry("linux")
.or_insert_with(|| Value::Object(Default::default()))
.as_object_mut()
.map(|l| l.insert("deb".into(), deb));
}
if let Some(appimage) = bundle_config.remove("appimage") {
bundle_config
.entry("linux")
.or_insert_with(|| Value::Object(Default::default()))
.as_object_mut()
.map(|l| l.insert("appimage".into(), appimage));
}
if let Some(rpm) = bundle_config.remove("rpm") {
bundle_config
.entry("linux")
.or_insert_with(|| Value::Object(Default::default()))
.as_object_mut()
.map(|l| l.insert("rpm".into(), rpm));
}
if let Some(dmg) = bundle_config.remove("dmg") {
bundle_config
.entry("macOS")
.or_insert_with(|| Value::Object(Default::default()))
.as_object_mut()
.map(|l| l.insert("dmg".into(), dmg));
}
// license file
if let Some(macos) = bundle_config
.get_mut("macOS")
.and_then(|v| v.as_object_mut())
{
if let Some(license) = macos.remove("license") {
license_file = Some(license);
}
}
// Windows
if let Some(windows) = bundle_config.get_mut("windows") {
if let Some(windows) = windows.as_object_mut() {
if let Some(wix) = windows.get_mut("wix").and_then(|v| v.as_object_mut()) {
if let Some(license_path) = wix.remove("license") {
license_file = Some(license_path);
}
}
if let Some(nsis) = windows.get_mut("nsis").and_then(|v| v.as_object_mut()) {
if let Some(license_path) = nsis.remove("license") {
license_file = Some(license_path);
}
}
if let Some((fixed_runtime_path, key)) = windows
.remove("webviewFixedRuntimePath")
.map(|v| (v, "webviewInstallMode"))
.or_else(|| {
windows
.remove("webview-fixed-runtime-path")
.map(|v| (v, "webview-install-mode"))
})
{
if !fixed_runtime_path.is_null() {
windows.insert(
key.into(),
serde_json::json!({
"type": "fixedRuntime",
"path": fixed_runtime_path
}),
);
}
}
}
}
if let Some(license_file) = license_file {
bundle_config.insert("licenseFile".into(), license_file);
}
// Migrate updater from targets to update field
if let Some(targets) = bundle_config.get_mut("targets") {
let should_migrate = if let Some(targets) = targets.as_array_mut() {
// targets: ["updater", ...]
if let Some(index) = targets
.iter()
.position(|target| *target == serde_json::Value::String("updater".to_owned()))
{
targets.remove(index);
true
} else {
false
}
} else if let Some(target) = targets.as_str() {
// targets: "updater"
if target == "updater" {
bundle_config.remove("targets");
true
} else {
// note that target == "all" is the default from the v1 tauri CLI
// so we shouldn't bindly force updater bundles to be created
// instead we only migrate if the updater has been migrated
target == "all" && migrated.plugins.contains("updater")
}
} else {
false
};
if should_migrate {
bundle_config.insert("createUpdaterArtifacts".to_owned(), "v1Compatible".into());
}
}
}
config.insert("bundle".into(), bundle_config);
}
}
fn process_security(security: &mut Map<String, Value>) -> Result<()> {
// migrate CSP: add `ipc:` to `connect-src`
if let Some(csp_value) = security.remove("csp") {
let csp = if csp_value.is_null() {
csp_value
} else {
let mut csp: tauri_utils::config_v1::Csp =
serde_json::from_value(csp_value).context("failed to deserialize CSP")?;
match &mut csp {
tauri_utils::config_v1::Csp::Policy(csp) => {
if csp.contains("connect-src") {
*csp = csp.replace("connect-src", "connect-src ipc: http://ipc.localhost");
} else {
*csp = format!("{csp}; connect-src ipc: http://ipc.localhost");
}
}
tauri_utils::config_v1::Csp::DirectiveMap(csp) => {
if let Some(connect_src) = csp.get_mut("connect-src") {
if !connect_src.contains("ipc: http://ipc.localhost") {
connect_src.push("ipc: http://ipc.localhost");
}
} else {
csp.insert(
"connect-src".into(),
tauri_utils::config_v1::CspDirectiveSources::List(vec![
"ipc: http://ipc.localhost".to_string()
]),
);
}
}
}
serde_json::to_value(csp).context("failed to serialize CSP")?
};
security.insert("csp".into(), csp);
}
// dangerous_remote_domain_ipc_access no longer exists
if let Some(dangerous_remote_domain_ipc_access) = security
.remove("dangerousRemoteDomainIpcAccess")
.or_else(|| security.remove("dangerous-remote-domain-ipc-access"))
{
println!("dangerous remote domain IPC access config ({dangerous_remote_domain_ipc_access:?}) no longer exists, see documentation for capabilities and remote access: https://v2.tauri.app/security/capabilities/#remote-api-access")
}
security
.remove("dangerousUseHttpScheme")
.or_else(|| security.remove("dangerous-use-http-scheme"));
Ok(())
}
fn process_allowlist(
tauri_config: &mut Map<String, Value>,
allowlist: Value,
) -> Result<tauri_utils::config_v1::AllowlistConfig> {
let allowlist: tauri_utils::config_v1::AllowlistConfig =
serde_json::from_value(allowlist).context("failed to deserialize allowlist")?;
if allowlist.protocol.asset_scope != Default::default() {
let security = tauri_config
.entry("security")
.or_insert_with(|| Value::Object(Default::default()))
.as_object_mut()
.unwrap();
let mut asset_protocol = Map::new();
asset_protocol.insert(
"scope".into(),
serde_json::to_value(allowlist.protocol.asset_scope.clone())
.context("failed to serialize asset scope")?,
);
if allowlist.protocol.asset {
asset_protocol.insert("enable".into(), true.into());
}
security.insert("assetProtocol".into(), asset_protocol.into());
}
Ok(allowlist)
}
fn allowlist_to_permissions(
allowlist: tauri_utils::config_v1::AllowlistConfig,
) -> Vec<PermissionEntry> {
macro_rules! permissions {
($allowlist: ident, $permissions_list: ident, $object: ident, $field: ident => $associated_permission: expr) => {{
if $allowlist.all || $allowlist.$object.all || $allowlist.$object.$field {
$permissions_list.push(PermissionEntry::PermissionRef(
$associated_permission.to_string().try_into().unwrap(),
));
true
} else {
false
}
}};
}
let mut permissions = Vec::new();
// fs
permissions!(allowlist, permissions, fs, read_file => "fs:allow-read-file");
permissions!(allowlist, permissions, fs, write_file => "fs:allow-write-file");
permissions!(allowlist, permissions, fs, read_dir => "fs:allow-read-dir");
permissions!(allowlist, permissions, fs, copy_file => "fs:allow-copy-file");
permissions!(allowlist, permissions, fs, create_dir => "fs:allow-mkdir");
permissions!(allowlist, permissions, fs, remove_dir => "fs:allow-remove");
permissions!(allowlist, permissions, fs, remove_file => "fs:allow-remove");
permissions!(allowlist, permissions, fs, rename_file => "fs:allow-rename");
permissions!(allowlist, permissions, fs, exists => "fs:allow-exists");
let (fs_allowed, fs_denied) = match allowlist.fs.scope {
tauri_utils::config_v1::FsAllowlistScope::AllowedPaths(paths) => (paths, Vec::new()),
tauri_utils::config_v1::FsAllowlistScope::Scope { allow, deny, .. } => (allow, deny),
};
if !(fs_allowed.is_empty() && fs_denied.is_empty()) {
let fs_allowed = fs_allowed
.into_iter()
.map(|p| AclValue::String(p.to_string_lossy().into()))
.collect::<Vec<_>>();
let fs_denied = fs_denied
.into_iter()
.map(|p| AclValue::String(p.to_string_lossy().into()))
.collect::<Vec<_>>();
permissions.push(PermissionEntry::ExtendedPermission {
identifier: "fs:scope".to_string().try_into().unwrap(),
scope: Scopes {
allow: if fs_allowed.is_empty() {
None
} else {
Some(fs_allowed)
},
deny: if fs_denied.is_empty() {
None
} else {
Some(fs_denied)
},
},
});
}
// window
permissions!(allowlist, permissions, window, create => "core:window:allow-create");
permissions!(allowlist, permissions, window, center => "core:window:allow-center");
permissions!(allowlist, permissions, window, request_user_attention => "core:window:allow-request-user-attention");
permissions!(allowlist, permissions, window, set_resizable => "core:window:allow-set-resizable");
permissions!(allowlist, permissions, window, set_maximizable => "core:window:allow-set-maximizable");
permissions!(allowlist, permissions, window, set_minimizable => "core:window:allow-set-minimizable");
permissions!(allowlist, permissions, window, set_closable => "core:window:allow-set-closable");
permissions!(allowlist, permissions, window, set_title => "core:window:allow-set-title");
permissions!(allowlist, permissions, window, maximize => "core:window:allow-maximize");
permissions!(allowlist, permissions, window, unmaximize => "core:window:allow-unmaximize");
permissions!(allowlist, permissions, window, minimize => "core:window:allow-minimize");
permissions!(allowlist, permissions, window, unminimize => "core:window:allow-unminimize");
permissions!(allowlist, permissions, window, show => "core:window:allow-show");
permissions!(allowlist, permissions, window, hide => "core:window:allow-hide");
permissions!(allowlist, permissions, window, close => "core:window:allow-close");
permissions!(allowlist, permissions, window, set_decorations => "core:window:allow-set-decorations");
permissions!(allowlist, permissions, window, set_always_on_top => "core:window:allow-set-always-on-top");
permissions!(allowlist, permissions, window, set_content_protected => "core:window:allow-set-content-protected");
permissions!(allowlist, permissions, window, set_size => "core:window:allow-set-size");
permissions!(allowlist, permissions, window, set_min_size => "core:window:allow-set-min-size");
permissions!(allowlist, permissions, window, set_max_size => "core:window:allow-set-max-size");
permissions!(allowlist, permissions, window, set_position => "core:window:allow-set-position");
permissions!(allowlist, permissions, window, set_fullscreen => "core:window:allow-set-fullscreen");
permissions!(allowlist, permissions, window, set_focus => "core:window:allow-set-focus");
permissions!(allowlist, permissions, window, set_icon => "core:window:allow-set-icon");
permissions!(allowlist, permissions, window, set_skip_taskbar => "core:window:allow-set-skip-taskbar");
permissions!(allowlist, permissions, window, set_cursor_grab => "core:window:allow-set-cursor-grab");
permissions!(allowlist, permissions, window, set_cursor_visible => "core:window:allow-set-cursor-visible");
permissions!(allowlist, permissions, window, set_cursor_icon => "core:window:allow-set-cursor-icon");
permissions!(allowlist, permissions, window, set_cursor_position => "core:window:allow-set-cursor-position");
permissions!(allowlist, permissions, window, set_ignore_cursor_events => "core:window:allow-set-ignore-cursor-events");
permissions!(allowlist, permissions, window, start_dragging => "core:window:allow-start-dragging");
permissions!(allowlist, permissions, window, print => "core:webview:allow-print");
// shell
if allowlist.shell.scope.0.is_empty() {
let added = permissions!(allowlist, permissions, shell, execute => "shell:allow-execute");
// prevent duplicated permission
if !added {
permissions!(allowlist, permissions, shell, sidecar => "shell:allow-execute");
}
} else {
let allowed = allowlist
.shell
.scope
.0
.into_iter()
.map(|p| serde_json::to_value(p).unwrap().into())
.collect::<Vec<_>>();
permissions.push(PermissionEntry::ExtendedPermission {
identifier: "shell:allow-execute".to_string().try_into().unwrap(),
scope: Scopes {
allow: Some(allowed),
deny: None,
},
});
}
if allowlist.all
|| allowlist.shell.all
|| !matches!(
allowlist.shell.open,
tauri_utils::config_v1::ShellAllowlistOpen::Flag(false)
)
{
permissions.push(PermissionEntry::PermissionRef(
"shell:allow-open".to_string().try_into().unwrap(),
));
}
// dialog
permissions!(allowlist, permissions, dialog, open => "dialog:allow-open");
permissions!(allowlist, permissions, dialog, save => "dialog:allow-save");
permissions!(allowlist, permissions, dialog, message => "dialog:allow-message");
permissions!(allowlist, permissions, dialog, ask => "dialog:allow-ask");
permissions!(allowlist, permissions, dialog, confirm => "dialog:allow-confirm");
// http
if allowlist.http.scope.0.is_empty() {
permissions!(allowlist, permissions, http, request => "http:default");
} else {
let allowed = allowlist
.http
.scope
.0
.into_iter()
.map(|p| {
let mut map = BTreeMap::new();
map.insert("url".to_string(), AclValue::String(p.to_string()));
AclValue::Map(map)
})
.collect::<Vec<_>>();
permissions.push(PermissionEntry::ExtendedPermission {
identifier: "http:default".to_string().try_into().unwrap(),
scope: Scopes {
allow: Some(allowed),
deny: None,
},
});
}
// notification
permissions!(allowlist, permissions, notification, all => "notification:default");
// global-shortcut
permissions!(allowlist, permissions, global_shortcut, all => "global-shortcut:allow-is-registered");
permissions!(allowlist, permissions, global_shortcut, all => "global-shortcut:allow-register");
permissions!(allowlist, permissions, global_shortcut, all => "global-shortcut:allow-register-all");
permissions!(allowlist, permissions, global_shortcut, all => "global-shortcut:allow-unregister");
permissions!(allowlist, permissions, global_shortcut, all => "global-shortcut:allow-unregister-all");
// os
permissions!(allowlist, permissions, os, all => "os:allow-platform");
permissions!(allowlist, permissions, os, all => "os:allow-version");
permissions!(allowlist, permissions, os, all => "os:allow-os-type");
permissions!(allowlist, permissions, os, all => "os:allow-family");
permissions!(allowlist, permissions, os, all => "os:allow-arch");
permissions!(allowlist, permissions, os, all => "os:allow-exe-extension");
permissions!(allowlist, permissions, os, all => "os:allow-locale");
permissions!(allowlist, permissions, os, all => "os:allow-hostname");
// process
permissions!(allowlist, permissions, process, relaunch => "process:allow-restart");
permissions!(allowlist, permissions, process, exit => "process:allow-exit");
// clipboard
permissions!(allowlist, permissions, clipboard, read_text => "clipboard-manager:allow-read-text");
permissions!(allowlist, permissions, clipboard, write_text => "clipboard-manager:allow-write-text");
// app
permissions!(allowlist, permissions, app, show => "core:app:allow-app-show");
permissions!(allowlist, permissions, app, hide => "core:app:allow-app-hide");
permissions
}
fn process_cli(plugins: &mut Map<String, Value>, cli: Value) -> Result<()> {
if let Some(cli) = cli.as_object() {
plugins.insert(
"cli".into(),
serde_json::to_value(cli).context("failed to serialize CLI")?,
);
}
Ok(())
}
fn process_updater(
tauri_config: &mut Map<String, Value>,
plugins: &mut Map<String, Value>,
migrated: &mut MigratedConfig,
) -> Result<()> {
if let Some(mut updater) = tauri_config.remove("updater") {
if let Some(updater) = updater.as_object_mut() {
updater.remove("dialog");
// we only migrate the updater config if it's active
// since we now assume it's always active if the config object is set
// we also migrate if pubkey is set so we do not lose that information on the migration
// in this case, the user need to deal with the updater being inactive on their own
if updater
.remove("active")
.and_then(|a| a.as_bool())
.unwrap_or_default()
|| updater.get("pubkey").is_some()
{
plugins.insert(
"updater".into(),
serde_json::to_value(updater).context("failed to serialize updater")?,
);
migrated.plugins.insert("updater".to_string());
}
}
}
Ok(())
}
const KNOWN_PLUGINS: &[&str] = &[
"fs",
"shell",
"dialog",
"http",
"notification",
"global-shortcut",
"os",
"process",
"clipboard-manager",
];
fn plugins_from_permissions(permissions: &Vec<PermissionEntry>) -> HashSet<String> {
let mut plugins = HashSet::new();
for permission in permissions {
let permission = permission.identifier().get();
for plugin in KNOWN_PLUGINS {
if permission.starts_with(plugin) {
plugins.insert(plugin.to_string());
break;
}
}
}
plugins
}
#[cfg(test)]
mod test {
fn migrate(original: &serde_json::Value) -> serde_json::Value {
let mut migrated = original.clone();
super::migrate_config(&mut migrated).expect("failed to migrate config");
if original.get("$schema").is_some() {
if let Some(map) = migrated.as_object_mut() {
map.insert(
"$schema".to_string(),
serde_json::Value::String("https://schema.tauri.app/config/2".to_string()),
);
}
}
if original
.get("tauri")
.and_then(|v| v.get("bundle"))
.and_then(|v| v.get("identifier"))
.is_none()
{
if let Some(map) = migrated.as_object_mut() {
map.insert(
"identifier".to_string(),
serde_json::Value::String("com.tauri.test-injected".to_string()),
);
}
}
if let Err(e) = serde_json::from_value::<tauri_utils::config::Config>(migrated.clone()) {
panic!("migrated config is not valid: {e}");
}
migrated
}
#[test]
fn migrate_full() {
let original = serde_json::json!({
"$schema": "../node_modules/@tauri-apps/cli/schema.json",
"build": {
"distDir": "../dist",
"devPath": "http://localhost:1240",
"withGlobalTauri": true
},
"package": {
"productName": "Tauri app",
"version": "0.0.0"
},
"tauri": {
"bundle": {
"identifier": "com.tauri.test",
"deb": {
"depends": ["dep1"]
},
"appimage": {
"bundleMediaFramework": true
},
"macOS": {
"license": "license-file.txt"
},
"windows": {
"wix": {
"license": "license-file.txt"
},
"nsis": {
"license": "license-file.txt"
},
},
},
"cli": {
"description": "Tauri TEST"
},
"updater": {
"active": true,
"dialog": false,
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDE5QzMxNjYwNTM5OEUwNTgKUldSWTRKaFRZQmJER1h4d1ZMYVA3dnluSjdpN2RmMldJR09hUFFlZDY0SlFqckkvRUJhZDJVZXAK",
"endpoints": [
"https://tauri-update-server.vercel.app/update/{{target}}/{{current_version}}"
],
"windows": {
"installerArgs": ["arg1"],
"installMode": "passive"
}
},
"allowlist": {
"all": true,
"fs": {
"scope": {
"allow": ["$APPDATA/db/**", "$DOWNLOAD/**", "$RESOURCE/**"],
"deny": ["$APPDATA/db/*.stronghold"]
}
},
"shell": {
"open": true,
"scope": [
{
"name": "sh",
"cmd": "sh",
"args": ["-c", { "validator": "\\S+" }],
"sidecar": false
},
{
"name": "cmd",
"cmd": "cmd",
"args": ["/C", { "validator": "\\S+" }],
"sidecar": false
}
]
},
"protocol": {
"asset": true,
"assetScope": {
"allow": ["$APPDATA/db/**", "$RESOURCE/**"],
"deny": ["$APPDATA/db/*.stronghold"]
}
},
"http": {
"scope": ["http://localhost:3003/"]
}
},
"pattern": { "use": "brownfield" },
"security": {
"csp": "default-src 'self' tauri:"
},
"windows": [{}]
}
});
let migrated = migrate(&original);
// $schema
assert_eq!(migrated["$schema"], "https://schema.tauri.app/config/2");
// plugins > updater
assert_eq!(
migrated["plugins"]["updater"]["endpoints"],
original["tauri"]["updater"]["endpoints"]
);
assert_eq!(
migrated["plugins"]["updater"]["pubkey"],
original["tauri"]["updater"]["pubkey"]
);
assert_eq!(
migrated["plugins"]["updater"]["windows"]["installMode"],
original["tauri"]["updater"]["windows"]["installMode"]
);
assert_eq!(
migrated["plugins"]["updater"]["windows"]["installerArgs"],
original["tauri"]["updater"]["windows"]["installerArgs"]
);
// cli
assert_eq!(migrated["plugins"]["cli"], original["tauri"]["cli"]);
// asset scope
assert_eq!(
migrated["app"]["security"]["assetProtocol"]["enable"],
original["tauri"]["allowlist"]["protocol"]["asset"]
);
assert_eq!(
migrated["app"]["security"]["assetProtocol"]["scope"]["allow"],
original["tauri"]["allowlist"]["protocol"]["assetScope"]["allow"]
);
assert_eq!(
migrated["app"]["security"]["assetProtocol"]["scope"]["deny"],
original["tauri"]["allowlist"]["protocol"]["assetScope"]["deny"]
);
// security CSP
assert_eq!(
migrated["app"]["security"]["csp"],
format!(
"{}; connect-src ipc: http://ipc.localhost",
original["tauri"]["security"]["csp"].as_str().unwrap()
)
);
// security pattern
assert_eq!(
migrated["app"]["security"]["pattern"],
original["tauri"]["pattern"]
);
// license files
assert_eq!(
migrated["bundle"]["licenseFile"],
original["tauri"]["bundle"]["macOS"]["license"]
);
assert_eq!(
migrated["bundle"]["licenseFile"],
original["tauri"]["bundle"]["windows"]["wix"]["license"]
);
assert_eq!(
migrated["bundle"]["licenseFile"],
original["tauri"]["bundle"]["windows"]["nsis"]["license"]
);
// bundle appimage and deb
assert_eq!(
migrated["bundle"]["linux"]["deb"],
original["tauri"]["bundle"]["deb"]
);
assert_eq!(
migrated["bundle"]["linux"]["appimage"],
original["tauri"]["bundle"]["appimage"]
);
// app information
assert_eq!(migrated["productName"], original["package"]["productName"]);
assert_eq!(
migrated["mainBinaryName"],
original["package"]["productName"]
);
assert_eq!(migrated["version"], original["package"]["version"]);
assert_eq!(
migrated["identifier"],
original["tauri"]["bundle"]["identifier"]
);
// build object
assert_eq!(
migrated["build"]["frontendDist"],
original["build"]["distDir"]
);
assert_eq!(migrated["build"]["devUrl"], original["build"]["devPath"]);
assert_eq!(
migrated["app"]["withGlobalTauri"],
original["build"]["withGlobalTauri"]
);
assert_eq!(migrated["app"]["windows"][0]["useHttpsScheme"], true);
}
#[test]
fn skips_migrating_updater() {
let original = serde_json::json!({
"tauri": {
"updater": {
"active": false
}
}
});
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | true |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/migrate/migrations/v1/manifest.rs | crates/tauri-cli/src/migrate/migrations/v1/manifest.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{
error::ErrorExt,
interface::rust::manifest::{read_manifest, serialize_manifest},
Result,
};
use tauri_utils::config_v1::Allowlist;
use toml_edit::{DocumentMut, Entry, Item, TableLike, Value};
use std::path::Path;
const CRATE_TYPES: [&str; 3] = ["lib", "staticlib", "cdylib"];
pub fn migrate(tauri_dir: &Path) -> Result<()> {
let manifest_path = tauri_dir.join("Cargo.toml");
let (mut manifest, _) = read_manifest(&manifest_path)?;
migrate_manifest(&mut manifest)?;
std::fs::write(&manifest_path, serialize_manifest(&manifest))
.fs_context("failed to rewrite Cargo manifest", &manifest_path)?;
Ok(())
}
fn migrate_manifest(manifest: &mut DocumentMut) -> Result<()> {
let version = dependency_version();
let remove_features = features_to_remove();
let rename_features = features_to_rename();
let rename_message = rename_features
.iter()
.map(|(from, to)| format!("{from} to {to}"))
.collect::<Vec<_>>()
.join(", ");
for (dependency, table) in [
// normal deps
("tauri", "dependencies"),
("tauri-utils", "dependencies"),
("tauri-runtime", "dependencies"),
("tauri-codegen", "dependencies"),
("tauri-macros", "dependencies"),
("tauri-runtime-wry", "dependencies"),
// normal deps - plugins
("tauri-plugin-authenticator", "dependencies"),
("tauri-plugin-autostart", "dependencies"),
("tauri-plugin-fs-extra", "dependencies"),
("tauri-plugin-fs-watch", "dependencies"),
("tauri-plugin-localhost", "dependencies"),
("tauri-plugin-log", "dependencies"),
("tauri-plugin-persisted-scope", "dependencies"),
("tauri-plugin-positioner", "dependencies"),
("tauri-plugin-single-instance", "dependencies"),
("tauri-plugin-sql", "dependencies"),
("tauri-plugin-store", "dependencies"),
("tauri-plugin-stronghold", "dependencies"),
("tauri-plugin-upload", "dependencies"),
("tauri-plugin-websocket", "dependencies"),
("tauri-plugin-window-state", "dependencies"),
// dev
("tauri", "dev-dependencies"),
("tauri-utils", "dev-dependencies"),
("tauri-runtime", "dev-dependencies"),
("tauri-codegen", "dev-dependencies"),
("tauri-macros", "dev-dependencies"),
("tauri-runtime-wry", "dev-dependencies"),
// build
("tauri-build", "build-dependencies"),
] {
let items = find_dependency(manifest, dependency, table);
for item in items {
// do not rewrite if dependency uses workspace inheritance
if item
.get("workspace")
.and_then(|v| v.as_bool())
.unwrap_or_default()
{
log::warn!("`{dependency}` dependency has workspace inheritance enabled. This migration must be manually migrated to v2 by changing its version to {version}, removing any of the {remove_features:?} and renaming [{}] Cargo features.", rename_message);
} else {
migrate_dependency(item, &version, &remove_features, &rename_features);
}
}
}
if let Some(lib) = manifest
.as_table_mut()
.get_mut("lib")
.and_then(|l| l.as_table_mut())
{
match lib.entry("crate-type") {
Entry::Occupied(mut e) => {
if let Item::Value(Value::Array(types)) = e.get_mut() {
let mut crate_types_to_add = CRATE_TYPES.to_vec();
for t in types.iter() {
// type is already in the manifest, skip adding it
if let Some(i) = crate_types_to_add
.iter()
.position(|ty| Some(ty) == t.as_str().as_ref())
{
crate_types_to_add.remove(i);
}
}
for t in crate_types_to_add {
types.push(t);
}
}
}
Entry::Vacant(e) => {
let mut arr = toml_edit::Array::new();
arr.extend(CRATE_TYPES.to_vec());
e.insert(Item::Value(arr.into()));
}
}
}
Ok(())
}
fn find_dependency<'a>(
manifest: &'a mut DocumentMut,
name: &'a str,
table: &'a str,
) -> Vec<&'a mut Item> {
let m = manifest.as_table_mut();
for (k, v) in m.iter_mut() {
if let Some(t) = v.as_table_mut() {
if k == table {
if let Some(item) = t.get_mut(name) {
return vec![item];
}
} else if k == "target" {
let mut matching_deps = Vec::new();
for (_, target_value) in t.iter_mut() {
if let Some(target_table) = target_value.as_table_mut() {
if let Some(deps) = target_table.get_mut(table) {
if let Some(item) = deps.as_table_mut().and_then(|t| t.get_mut(name)) {
matching_deps.push(item);
}
}
}
}
return matching_deps;
}
}
}
Vec::new()
}
fn features_to_rename() -> Vec<(&'static str, &'static str)> {
vec![
("window-data-url", "webview-data-url"),
("reqwest-native-tls-vendored", "native-tls-vendored"),
("system-tray", "tray-icon"),
("icon-ico", "image-ico"),
("icon-png", "image-png"),
]
}
fn features_to_remove() -> Vec<&'static str> {
let mut features_to_remove = tauri_utils::config_v1::AllowlistConfig::all_features();
features_to_remove.extend(&[
"reqwest-client",
"http-multipart",
"process-command-api",
"shell-open-api",
"os-api",
"global-shortcut",
"clipboard",
"dialog",
"notification",
"fs-extract-api",
"windows7-compat",
"updater",
"cli",
"linux-protocol-headers",
"dox",
]);
// this allowlist feature was not removed
let index = features_to_remove
.iter()
.position(|x| x == &"protocol-asset")
.unwrap();
features_to_remove.remove(index);
features_to_remove
}
fn dependency_version() -> String {
let pre = env!("CARGO_PKG_VERSION_PRE");
if pre.is_empty() {
env!("CARGO_PKG_VERSION_MAJOR").to_string()
} else {
format!(
"{}.0.0-{}",
env!("CARGO_PKG_VERSION_MAJOR"),
pre.split('.').next().unwrap()
)
}
}
fn migrate_dependency(item: &mut Item, version: &str, remove: &[&str], rename: &[(&str, &str)]) {
if let Some(dep) = item.as_table_mut() {
migrate_dependency_table(dep, version, remove, rename);
} else if let Some(Value::InlineTable(table)) = item.as_value_mut() {
migrate_dependency_table(table, version, remove, rename);
} else if item.as_str().is_some() {
*item = Item::Value(version.into());
}
}
fn migrate_dependency_table<D: TableLike>(
dep: &mut D,
version: &str,
remove: &[&str],
rename: &[(&str, &str)],
) {
dep.remove("rev");
dep.remove("git");
dep.remove("branch");
dep.remove("tag");
*dep.entry("version").or_insert(Item::None) = Item::Value(version.into());
let manifest_features = dep.entry("features").or_insert(Item::None);
if let Some(features_array) = manifest_features.as_array_mut() {
// remove features that shouldn't be in the manifest anymore
let mut i = features_array.len();
let mut add_features = Vec::new();
while i != 0 {
let index = i - 1;
if let Some(f) = features_array.get(index).and_then(|f| f.as_str()) {
if remove.contains(&f) {
features_array.remove(index);
} else if let Some((_from, rename_to)) = rename.iter().find(|(from, _to)| *from == f) {
features_array.remove(index);
add_features.push(rename_to);
}
}
i -= 1;
}
for f in add_features {
features_array.push(f.to_string());
}
}
}
#[cfg(test)]
mod tests {
use itertools::Itertools;
fn migrate_deps<F: FnOnce(&[&str]) -> String>(get_toml: F) {
let keep_features = vec!["isolation", "protocol-asset"];
let mut features = super::features_to_remove();
features.extend(keep_features.clone());
let toml = get_toml(&features);
let mut manifest = toml
.parse::<toml_edit::DocumentMut>()
.expect("invalid toml");
super::migrate_manifest(&mut manifest).expect("failed to migrate manifest");
let dependencies = manifest
.as_table()
.get("dependencies")
.expect("missing manifest dependencies")
.as_table()
.expect("manifest dependencies isn't a table");
let tauri = dependencies
.get("tauri")
.expect("missing tauri dependency in manifest");
let tauri_table = if let Some(table) = tauri.as_table() {
table.clone()
} else if let Some(toml_edit::Value::InlineTable(table)) = tauri.as_value() {
table.clone().into_table()
} else if let Some(version) = tauri.as_str() {
// convert the value to a table for the assert logic below
let mut table = toml_edit::Table::new();
table.insert(
"version",
toml_edit::Item::Value(version.to_string().into()),
);
table.insert(
"features",
toml_edit::Item::Value(toml_edit::Value::Array(Default::default())),
);
table
} else {
panic!("unexpected tauri dependency format");
};
// assert version matches
let version = tauri_table
.get("version")
.expect("missing version")
.as_str()
.expect("version must be a string");
assert_eq!(version, super::dependency_version());
// assert features matches
let features = tauri_table
.get("features")
.expect("missing features")
.as_array()
.expect("features must be an array")
.clone();
if toml.contains("reqwest-native-tls-vendored") {
assert!(
features
.iter()
.any(|f| f.as_str().expect("feature must be a string") == "native-tls-vendored"),
"reqwest-native-tls-vendored was not replaced with native-tls-vendored"
);
}
if toml.contains("system-tray") {
assert!(
features
.iter()
.any(|f| f.as_str().expect("feature must be a string") == "tray-icon"),
"system-tray was not replaced with tray-icon"
);
}
for feature in features.iter() {
let feature = feature.as_str().expect("feature must be a string");
assert!(
keep_features.contains(&feature)
|| feature == "native-tls-vendored"
|| feature == "tray-icon",
"feature {feature} should have been removed"
);
}
}
#[test]
fn migrate_table() {
migrate_deps(|features| {
format!(
r#"
[dependencies]
tauri = {{ version = "1.0.0", features = [{}] }}
"#,
features.iter().map(|f| format!("{f:?}")).join(", ")
)
});
}
#[test]
fn migrate_inline_table() {
migrate_deps(|features| {
format!(
r#"
[dependencies.tauri]
version = "1.0.0"
features = [{}]
"#,
features.iter().map(|f| format!("{f:?}")).join(", ")
)
});
}
#[test]
fn migrate_str() {
migrate_deps(|_features| {
r#"
[dependencies]
tauri = "1.0.0"
"#
.into()
})
}
#[test]
fn migrate_add_crate_types() {
let toml = r#"
[lib]
crate-type = ["something"]"#;
let mut manifest = toml
.parse::<toml_edit::DocumentMut>()
.expect("invalid toml");
super::migrate_manifest(&mut manifest).expect("failed to migrate manifest");
if let Some(crate_types) = manifest
.as_table()
.get("lib")
.and_then(|l| l.get("crate-type"))
.and_then(|c| c.as_array())
{
let mut not_added_crate_types = super::CRATE_TYPES.to_vec();
for t in crate_types {
let t = t.as_str().expect("crate-type must be a string");
if let Some(i) = not_added_crate_types.iter().position(|ty| ty == &t) {
not_added_crate_types.remove(i);
}
}
assert!(
not_added_crate_types.is_empty(),
"missing crate-type: {not_added_crate_types:?}"
);
}
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/migrate/migrations/v1/mod.rs | crates/tauri-cli/src/migrate/migrations/v1/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{
error::Context,
helpers::app_paths::{frontend_dir, tauri_dir},
Result,
};
mod config;
mod frontend;
mod manifest;
pub fn run() -> Result<()> {
let tauri_dir = tauri_dir();
let frontend_dir = frontend_dir();
let mut migrated = config::migrate(tauri_dir).context("Could not migrate config")?;
manifest::migrate(tauri_dir).context("Could not migrate manifest")?;
let plugins = frontend::migrate(frontend_dir)?;
migrated.plugins.extend(plugins);
// Add plugins
for plugin in migrated.plugins {
crate::add::run(crate::add::Options {
plugin: plugin.clone(),
branch: None,
tag: None,
rev: None,
no_fmt: false,
})
.with_context(|| format!("Could not migrate plugin '{plugin}'"))?;
}
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/migrate/migrations/v1/frontend.rs | crates/tauri-cli/src/migrate/migrations/v1/frontend.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{
error::Context,
helpers::{app_paths::walk_builder, npm::PackageManager},
Error, ErrorExt, Result,
};
use itertools::Itertools;
use magic_string::MagicString;
use oxc_allocator::Allocator;
use oxc_ast::ast::*;
use oxc_parser::Parser;
use oxc_span::SourceType;
use std::{fs, path::Path};
mod partial_loader;
const RENAMED_MODULES: phf::Map<&str, &str> = phf::phf_map! {
"tauri" => "core",
"window" => "webviewWindow"
};
const PLUGINIFIED_MODULES: [&str; 11] = [
"cli",
"clipboard",
"dialog",
"fs",
"globalShortcut",
"http",
"notification",
"os",
"process",
"shell",
"updater",
];
// (from, to)
const MODULES_MAP: phf::Map<&str, &str> = phf::phf_map! {
// renamed
"@tauri-apps/api/tauri" => "@tauri-apps/api/core",
"@tauri-apps/api/window" => "@tauri-apps/api/webviewWindow",
// pluginified
"@tauri-apps/api/cli" => "@tauri-apps/plugin-cli",
"@tauri-apps/api/clipboard" => "@tauri-apps/plugin-clipboard-manager",
"@tauri-apps/api/dialog" => "@tauri-apps/plugin-dialog",
"@tauri-apps/api/fs" => "@tauri-apps/plugin-fs",
"@tauri-apps/api/globalShortcut" => "@tauri-apps/plugin-global-shortcut",
"@tauri-apps/api/http" => "@tauri-apps/plugin-http",
"@tauri-apps/api/notification" => "@tauri-apps/plugin-notification",
"@tauri-apps/api/os" => "@tauri-apps/plugin-os",
"@tauri-apps/api/process" => "@tauri-apps/plugin-process",
"@tauri-apps/api/shell" => "@tauri-apps/plugin-shell",
"@tauri-apps/api/updater" => "@tauri-apps/plugin-updater",
// v1 plugins to v2
"tauri-plugin-sql-api" => "@tauri-apps/plugin-sql",
"tauri-plugin-store-api" => "@tauri-apps/plugin-store",
"tauri-plugin-upload-api" => "@tauri-apps/plugin-upload",
"tauri-plugin-fs-extra-api" => "@tauri-apps/plugin-fs",
"tauri-plugin-fs-watch-api" => "@tauri-apps/plugin-fs",
"tauri-plugin-autostart-api" => "@tauri-apps/plugin-autostart",
"tauri-plugin-websocket-api" => "@tauri-apps/plugin-websocket",
"tauri-plugin-positioner-api" => "@tauri-apps/plugin-positioner",
"tauri-plugin-stronghold-api" => "@tauri-apps/plugin-stronghold",
"tauri-plugin-window-state-api" => "@tauri-apps/plugin-window-state",
"tauri-plugin-authenticator-api" => "@tauri-apps/plugin-authenticator",
};
const JS_EXTENSIONS: &[&str] = &["js", "mjs", "jsx", "ts", "mts", "tsx", "svelte", "vue"];
/// Returns a list of migrated plugins
pub fn migrate(frontend_dir: &Path) -> Result<Vec<String>> {
let mut new_npm_packages = Vec::new();
let mut new_plugins = Vec::new();
let mut npm_packages_to_remove = Vec::new();
let pre = env!("CARGO_PKG_VERSION_PRE");
let npm_version = if pre.is_empty() {
format!("{}.0.0", env!("CARGO_PKG_VERSION_MAJOR"))
} else {
format!(
"{}.0.0-{}.0",
env!("CARGO_PKG_VERSION_MAJOR"),
pre.split('.').next().unwrap()
)
};
let pm = PackageManager::from_project(frontend_dir);
for pkg in ["@tauri-apps/cli", "@tauri-apps/api"] {
let version = pm
.current_package_version(pkg, frontend_dir)
.unwrap_or_default()
.unwrap_or_default();
if version.starts_with('1') {
new_npm_packages.push(format!("{pkg}@^{npm_version}"));
}
}
for entry in walk_builder(frontend_dir).build().flatten() {
if entry.file_type().map(|t| t.is_file()).unwrap_or_default() {
let path = entry.path();
let ext = path.extension().unwrap_or_default();
if JS_EXTENSIONS.iter().any(|e| e == &ext) {
let js_contents =
std::fs::read_to_string(path).fs_context("failed to read JS file", path.to_path_buf())?;
let new_contents = migrate_imports(
path,
&js_contents,
&mut new_plugins,
&mut npm_packages_to_remove,
)?;
if new_contents != js_contents {
fs::write(path, new_contents)
.fs_context("failed to write JS file", path.to_path_buf())?;
}
}
}
}
if !npm_packages_to_remove.is_empty() {
npm_packages_to_remove.sort();
npm_packages_to_remove.dedup();
pm.remove(&npm_packages_to_remove, frontend_dir)
.context("Error removing npm packages")?;
}
if !new_npm_packages.is_empty() {
new_npm_packages.sort();
new_npm_packages.dedup();
pm.install(&new_npm_packages, frontend_dir)
.context("Error installing new npm packages")?;
}
Ok(new_plugins)
}
fn migrate_imports<'a>(
path: &'a Path,
js_source: &'a str,
new_plugins: &mut Vec<String>,
npm_packages_to_remove: &mut Vec<String>,
) -> crate::Result<String> {
let mut magic_js_source = MagicString::new(js_source);
let has_partial_js = path
.extension()
.is_some_and(|ext| ext == "vue" || ext == "svelte");
let sources = if !has_partial_js {
vec![(SourceType::from_path(path).unwrap(), js_source, 0i64)]
} else {
partial_loader::PartialLoader::parse(
path
.extension()
.unwrap_or_default()
.to_str()
.unwrap_or_default(),
js_source,
)
.unwrap()
.into_iter()
.map(|s| (s.source_type, s.source_text, s.start as i64))
.collect()
};
for (source_type, js_source, script_start) in sources {
let allocator = Allocator::default();
let ret = Parser::new(&allocator, js_source, source_type).parse();
if !ret.errors.is_empty() {
crate::error::bail!(
"failed to parse {} as valid Javascript/Typescript file",
path.display()
)
}
let mut program = ret.program;
let mut stmts_to_add = Vec::new();
let mut imports_to_add = Vec::new();
for import in program.body.iter_mut() {
if let Statement::ImportDeclaration(stmt) = import {
let module = stmt.source.value.as_str();
// convert module to its pluginfied module or renamed one
// import { ... } from "@tauri-apps/api/window" -> import { ... } from "@tauri-apps/api/webviewWindow"
// import { ... } from "@tauri-apps/api/cli" -> import { ... } from "@tauri-apps/plugin-cli"
if let Some(&new_module) = MODULES_MAP.get(module) {
// +1 and -1, to skip modifying the import quotes
magic_js_source
.overwrite(
script_start + stmt.source.span.start as i64 + 1,
script_start + stmt.source.span.end as i64 - 1,
new_module,
Default::default(),
)
.map_err(|e| {
Error::Context(
"failed to replace import source".to_string(),
e.to_string().into(),
)
})?;
// if module was pluginified, add to packages
if let Some(plugin_name) = new_module.strip_prefix("@tauri-apps/plugin-") {
new_plugins.push(plugin_name.to_string());
}
// if the module is a v1 plugin, we should remove it
if module.starts_with("tauri-plugin-") {
npm_packages_to_remove.push(module.to_string());
}
}
// skip parsing non @tauri-apps/api imports
if !module.starts_with("@tauri-apps/api") {
continue;
}
let Some(specifiers) = &mut stmt.specifiers else {
continue;
};
for specifier in specifiers.iter() {
if let ImportDeclarationSpecifier::ImportSpecifier(specifier) = specifier {
let new_identifier = match specifier.imported.name().as_str() {
// migrate appWindow from:
// ```
// import { appWindow } from "@tauri-apps/api/window"
// ```
// to:
// ```
// import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow"
// const appWindow = getCurrentWebviewWindow()
// ```
"appWindow" if module == "@tauri-apps/api/window" => {
stmts_to_add.push("\nconst appWindow = getCurrentWebviewWindow()");
Some("getCurrentWebviewWindow")
}
// migrate pluginified modules from:
// ```
// import { dialog, cli as superCli } from "@tauri-apps/api"
// ```
// to:
// ```
// import * as dialog from "@tauri-apps/plugin-dialog"
// import * as cli as superCli from "@tauri-apps/plugin-cli"
// ```
import if PLUGINIFIED_MODULES.contains(&import) && module == "@tauri-apps/api" => {
let js_plugin: &str = MODULES_MAP[&format!("@tauri-apps/api/{import}")];
let (_, plugin_name) = js_plugin.split_once("plugin-").unwrap();
new_plugins.push(plugin_name.to_string());
if specifier.local.name.as_str() != import {
let local = &specifier.local.name;
imports_to_add.push(format!(
"\nimport * as {import} as {local} from \"{js_plugin}\""
));
} else {
imports_to_add.push(format!("\nimport * as {import} from \"{js_plugin}\""));
};
None
}
import if module == "@tauri-apps/api" => match RENAMED_MODULES.get(import) {
Some(m) => Some(*m),
None => continue,
},
// nothing to do, go to next specifier
_ => continue,
};
// if identifier was renamed, it will be Some()
// and so we convert the import
// import { appWindow } from "@tauri-apps/api/window" -> import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow"
if let Some(new_identifier) = new_identifier {
magic_js_source
.overwrite(
script_start + specifier.span.start as i64,
script_start + specifier.span.end as i64,
new_identifier,
Default::default(),
)
.map_err(|e| {
Error::Context(
"failed to rename identifier".to_string(),
e.to_string().into(),
)
})?;
} else {
// if None, we need to remove this specifier,
// it will also be replaced with an import from its new plugin below
// find the next comma or the bracket ending the import
let start = specifier.span.start as usize;
let sliced = &js_source[start..];
let comma_or_bracket = sliced.chars().find_position(|&c| c == ',' || c == '}');
let end = match comma_or_bracket {
Some((n, ',')) => n + start + 1,
Some((_, '}')) => specifier.span.end as _,
_ => continue,
};
magic_js_source
.remove(script_start + start as i64, script_start + end as i64)
.map_err(|e| {
Error::Context(
"failed to remove identifier".to_string(),
e.to_string().into(),
)
})?;
}
}
}
}
}
// find the end of import list
// fallback to the program start
let start = program
.body
.iter()
.rev()
.find(|s| matches!(s, Statement::ImportDeclaration(_)))
.map(|s| match s {
Statement::ImportDeclaration(s) => s.span.end,
_ => unreachable!(),
})
.unwrap_or(program.span.start);
if !imports_to_add.is_empty() {
for import in imports_to_add {
magic_js_source
.append_right(script_start as u32 + start, &import)
.map_err(|e| Error::Context("failed to add import".to_string(), e.to_string().into()))?;
}
}
if !stmts_to_add.is_empty() {
for stmt in stmts_to_add {
magic_js_source
.append_right(script_start as u32 + start, stmt)
.map_err(|e| {
Error::Context("failed to add statement".to_string(), e.to_string().into())
})?;
}
}
}
Ok(magic_js_source.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn migrates_vue() {
let input = r#"
<template>
<div>Tauri!</div>
</template>
<script setup>
import { useState } from "react";
import reactLogo from "./assets/react.svg";
import { invoke, dialog, cli as superCli } from "@tauri-apps/api";
import { appWindow } from "@tauri-apps/api/window";
import { convertFileSrc } from "@tauri-apps/api/tauri";
import { open } from "@tauri-apps/api/dialog";
import { register } from "@tauri-apps/api/globalShortcut";
import clipboard from "@tauri-apps/api/clipboard";
import * as fs from "@tauri-apps/api/fs";
import "./App.css";
</script>
<style>
.greeting {
color: red;
font-weight: bold;
}
</style>
"#;
let expected = r#"
<template>
<div>Tauri!</div>
</template>
<script setup>
import { useState } from "react";
import reactLogo from "./assets/react.svg";
import { invoke, } from "@tauri-apps/api";
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
import { convertFileSrc } from "@tauri-apps/api/core";
import { open } from "@tauri-apps/plugin-dialog";
import { register } from "@tauri-apps/plugin-global-shortcut";
import clipboard from "@tauri-apps/plugin-clipboard-manager";
import * as fs from "@tauri-apps/plugin-fs";
import "./App.css";
import * as dialog from "@tauri-apps/plugin-dialog"
import * as cli as superCli from "@tauri-apps/plugin-cli"
const appWindow = getCurrentWebviewWindow()
</script>
<style>
.greeting {
color: red;
font-weight: bold;
}
</style>
"#;
let mut new_plugins = Vec::new();
let mut npm_packages_to_remove = Vec::new();
let migrated = migrate_imports(
Path::new("file.vue"),
input,
&mut new_plugins,
&mut npm_packages_to_remove,
)
.unwrap();
assert_eq!(migrated, expected);
assert_eq!(
new_plugins,
vec![
"dialog",
"cli",
"dialog",
"global-shortcut",
"clipboard-manager",
"fs"
]
);
assert_eq!(npm_packages_to_remove, Vec::<String>::new());
}
#[test]
fn migrates_svelte() {
let input = r#"
<form>
</form>
<script>
import { useState } from "react";
import reactLogo from "./assets/react.svg";
import { invoke, dialog, cli as superCli } from "@tauri-apps/api";
import { appWindow } from "@tauri-apps/api/window";
import { convertFileSrc } from "@tauri-apps/api/tauri";
import { open } from "@tauri-apps/api/dialog";
import { register } from "@tauri-apps/api/globalShortcut";
import clipboard from "@tauri-apps/api/clipboard";
import * as fs from "@tauri-apps/api/fs";
import "./App.css";
</script>
"#;
let expected = r#"
<form>
</form>
<script>
import { useState } from "react";
import reactLogo from "./assets/react.svg";
import { invoke, } from "@tauri-apps/api";
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
import { convertFileSrc } from "@tauri-apps/api/core";
import { open } from "@tauri-apps/plugin-dialog";
import { register } from "@tauri-apps/plugin-global-shortcut";
import clipboard from "@tauri-apps/plugin-clipboard-manager";
import * as fs from "@tauri-apps/plugin-fs";
import "./App.css";
import * as dialog from "@tauri-apps/plugin-dialog"
import * as cli as superCli from "@tauri-apps/plugin-cli"
const appWindow = getCurrentWebviewWindow()
</script>
"#;
let mut new_plugins = Vec::new();
let mut npm_packages_to_remove = Vec::new();
let migrated = migrate_imports(
Path::new("file.svelte"),
input,
&mut new_plugins,
&mut npm_packages_to_remove,
)
.unwrap();
assert_eq!(migrated, expected);
assert_eq!(
new_plugins,
vec![
"dialog",
"cli",
"dialog",
"global-shortcut",
"clipboard-manager",
"fs"
]
);
assert_eq!(npm_packages_to_remove, Vec::<String>::new());
}
#[test]
fn migrates_js() {
let input = r#"
import { useState } from "react";
import reactLogo from "./assets/react.svg";
import { invoke, dialog, cli as superCli } from "@tauri-apps/api";
import { appWindow } from "@tauri-apps/api/window";
import { convertFileSrc } from "@tauri-apps/api/tauri";
import { open } from "@tauri-apps/api/dialog";
import { register } from "@tauri-apps/api/globalShortcut";
import clipboard from "@tauri-apps/api/clipboard";
import * as fs from "@tauri-apps/api/fs";
import { Store } from "tauri-plugin-store-api";
import Database from "tauri-plugin-sql-api";
import "./App.css";
function App() {
const [greetMsg, setGreetMsg] = useState("");
const [name, setName] = useState("");
async function greet() {
// Learn more about Tauri commands at https://v2.tauri.app/develop/calling-rust/#commands
setGreetMsg(await invoke("greet", { name }));
await open();
await dialog.save();
await convertFileSrc("");
const a = appWindow.label;
superCli.getMatches();
clipboard.readText();
fs.exists("");
}
return (
<div className="container">
<h1>Welcome to Tauri!</h1>
<div className="row">
<a href="https://vite.dev" target="_blank">
<img src="/vite.svg" className="logo vite" alt="Vite logo" />
</a>
<a href="https://tauri.app" target="_blank">
<img src="/tauri.svg" className="logo tauri" alt="Tauri logo" />
</a>
<a href="https://react.dev" target="_blank">
<img src={reactLogo} className="logo react" alt="React logo" />
</a>
</div>
<p>Click on the Tauri, Vite, and React logos to learn more.</p>
<form
className="row"
onSubmit={(e) => {
e.preventDefault();
greet();
}}
>
<input
id="greet-input"
onChange={(e) => setName(e.currentTarget.value)}
placeholder="Enter a name..."
/>
<button type="submit">Greet</button>
</form>
<p>{greetMsg}</p>
</div>
);
}
export default App;
"#;
let expected = r#"
import { useState } from "react";
import reactLogo from "./assets/react.svg";
import { invoke, } from "@tauri-apps/api";
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
import { convertFileSrc } from "@tauri-apps/api/core";
import { open } from "@tauri-apps/plugin-dialog";
import { register } from "@tauri-apps/plugin-global-shortcut";
import clipboard from "@tauri-apps/plugin-clipboard-manager";
import * as fs from "@tauri-apps/plugin-fs";
import { Store } from "@tauri-apps/plugin-store";
import Database from "@tauri-apps/plugin-sql";
import "./App.css";
import * as dialog from "@tauri-apps/plugin-dialog"
import * as cli as superCli from "@tauri-apps/plugin-cli"
const appWindow = getCurrentWebviewWindow()
function App() {
const [greetMsg, setGreetMsg] = useState("");
const [name, setName] = useState("");
async function greet() {
// Learn more about Tauri commands at https://v2.tauri.app/develop/calling-rust/#commands
setGreetMsg(await invoke("greet", { name }));
await open();
await dialog.save();
await convertFileSrc("");
const a = appWindow.label;
superCli.getMatches();
clipboard.readText();
fs.exists("");
}
return (
<div className="container">
<h1>Welcome to Tauri!</h1>
<div className="row">
<a href="https://vite.dev" target="_blank">
<img src="/vite.svg" className="logo vite" alt="Vite logo" />
</a>
<a href="https://tauri.app" target="_blank">
<img src="/tauri.svg" className="logo tauri" alt="Tauri logo" />
</a>
<a href="https://react.dev" target="_blank">
<img src={reactLogo} className="logo react" alt="React logo" />
</a>
</div>
<p>Click on the Tauri, Vite, and React logos to learn more.</p>
<form
className="row"
onSubmit={(e) => {
e.preventDefault();
greet();
}}
>
<input
id="greet-input"
onChange={(e) => setName(e.currentTarget.value)}
placeholder="Enter a name..."
/>
<button type="submit">Greet</button>
</form>
<p>{greetMsg}</p>
</div>
);
}
export default App;
"#;
let mut new_plugins = Vec::new();
let mut npm_packages_to_remove = Vec::new();
let migrated = migrate_imports(
Path::new("file.js"),
input,
&mut new_plugins,
&mut npm_packages_to_remove,
)
.unwrap();
assert_eq!(migrated, expected);
assert_eq!(
new_plugins,
vec![
"dialog",
"cli",
"dialog",
"global-shortcut",
"clipboard-manager",
"fs",
"store",
"sql"
]
);
assert_eq!(
npm_packages_to_remove,
vec!["tauri-plugin-store-api", "tauri-plugin-sql-api"]
);
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/migrate/migrations/v1/frontend/partial_loader/svelte.rs | crates/tauri-cli/src/migrate/migrations/v1/frontend/partial_loader/svelte.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
// taken from https://github.com/oxc-project/oxc/blob/main/crates/oxc_linter/src/partial_loader/svelte.rs
use memchr::memmem::Finder;
use oxc_span::SourceType;
use super::{find_script_closing_angle, JavaScriptSource, SCRIPT_END, SCRIPT_START};
pub struct SveltePartialLoader<'a> {
source_text: &'a str,
}
impl<'a> SveltePartialLoader<'a> {
pub fn new(source_text: &'a str) -> Self {
Self { source_text }
}
pub fn parse(self) -> Vec<JavaScriptSource<'a>> {
self
.parse_script()
.map_or_else(Vec::new, |source| vec![source])
}
fn parse_script(&self) -> Option<JavaScriptSource<'a>> {
let script_start_finder = Finder::new(SCRIPT_START);
let script_end_finder = Finder::new(SCRIPT_END);
let mut pointer = 0;
// find opening "<script"
let offset = script_start_finder.find(&self.source_text.as_bytes()[pointer..])?;
pointer += offset + SCRIPT_START.len();
// find closing ">"
let offset = find_script_closing_angle(self.source_text, pointer)?;
// get lang="ts" attribute
let content = &self.source_text[pointer..pointer + offset];
let is_ts = content.contains("ts");
pointer += offset + 1;
let js_start = pointer;
// find "</script>"
let offset = script_end_finder.find(&self.source_text.as_bytes()[pointer..])?;
let js_end = pointer + offset;
let source_text = &self.source_text[js_start..js_end];
let source_type = SourceType::default()
.with_module(true)
.with_typescript(is_ts);
Some(JavaScriptSource::new(source_text, source_type, js_start))
}
}
#[cfg(test)]
mod test {
use super::{JavaScriptSource, SveltePartialLoader};
fn parse_svelte(source_text: &str) -> JavaScriptSource<'_> {
let sources = SveltePartialLoader::new(source_text).parse();
*sources.first().unwrap()
}
#[test]
fn test_parse_svelte() {
let source_text = r#"
<script>
console.log("hi");
</script>
<h1>Hello World</h1>
"#;
let result = parse_svelte(source_text);
assert_eq!(result.source_text.trim(), r#"console.log("hi");"#);
}
#[test]
fn test_parse_svelte_ts_with_generic() {
let source_text = r#"
<script lang="ts" generics="T extends Record<string, unknown>">
console.log("hi");
</script>
<h1>Hello World</h1>
"#;
let result = parse_svelte(source_text);
assert_eq!(result.source_text.trim(), r#"console.log("hi");"#);
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/migrate/migrations/v1/frontend/partial_loader/mod.rs | crates/tauri-cli/src/migrate/migrations/v1/frontend/partial_loader/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
// taken from https://github.com/oxc-project/oxc/blob/main/crates/oxc_linter/src/partial_loader/mod.rs
mod svelte;
mod vue;
use oxc_span::SourceType;
pub use self::{svelte::SveltePartialLoader, vue::VuePartialLoader};
const SCRIPT_START: &str = "<script";
const SCRIPT_END: &str = "</script>";
#[derive(Debug, Clone, Copy)]
pub struct JavaScriptSource<'a> {
pub source_text: &'a str,
pub source_type: SourceType,
/// The javascript source could be embedded in some file,
/// use `start` to record start offset of js block in the original file.
pub start: usize,
}
impl<'a> JavaScriptSource<'a> {
pub fn new(source_text: &'a str, source_type: SourceType, start: usize) -> Self {
Self {
source_text,
source_type,
start,
}
}
}
pub struct PartialLoader;
impl PartialLoader {
/// Extract js section of specifial files.
/// Returns `None` if the specifial file does not have a js section.
pub fn parse<'a>(ext: &str, source_text: &'a str) -> Option<Vec<JavaScriptSource<'a>>> {
match ext {
"vue" => Some(VuePartialLoader::new(source_text).parse()),
"svelte" => Some(SveltePartialLoader::new(source_text).parse()),
_ => None,
}
}
}
/// Find closing angle for situations where there is another `>` in between.
/// e.g. `<script generic="T extends Record<string, string>">`
fn find_script_closing_angle(source_text: &str, pointer: usize) -> Option<usize> {
let mut numbers_of_open_angle = 0;
for (offset, c) in source_text[pointer..].char_indices() {
match c {
'>' => {
if numbers_of_open_angle == 0 {
return Some(offset);
}
numbers_of_open_angle -= 1;
}
'<' => {
numbers_of_open_angle += 1;
}
_ => {}
}
}
None
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/migrate/migrations/v1/frontend/partial_loader/vue.rs | crates/tauri-cli/src/migrate/migrations/v1/frontend/partial_loader/vue.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
// taken from https://github.com/oxc-project/oxc/blob/main/crates/oxc_linter/src/partial_loader/vue.rs
use memchr::memmem::Finder;
use oxc_span::SourceType;
use super::{find_script_closing_angle, JavaScriptSource, SCRIPT_END, SCRIPT_START};
pub struct VuePartialLoader<'a> {
source_text: &'a str,
}
impl<'a> VuePartialLoader<'a> {
pub fn new(source_text: &'a str) -> Self {
Self { source_text }
}
pub fn parse(self) -> Vec<JavaScriptSource<'a>> {
self.parse_scripts()
}
/// Each *.vue file can contain at most
/// * one `<script>` block (excluding `<script setup>`).
/// * one `<script setup>` block (excluding normal `<script>`).
/// <https://vuejs.org/api/sfc-spec.html#script>
fn parse_scripts(&self) -> Vec<JavaScriptSource<'a>> {
let mut pointer = 0;
let Some(result1) = self.parse_script(&mut pointer) else {
return vec![];
};
let Some(result2) = self.parse_script(&mut pointer) else {
return vec![result1];
};
vec![result1, result2]
}
fn parse_script(&self, pointer: &mut usize) -> Option<JavaScriptSource<'a>> {
let script_start_finder = Finder::new(SCRIPT_START);
let script_end_finder = Finder::new(SCRIPT_END);
// find opening "<script"
let offset = script_start_finder.find(&self.source_text.as_bytes()[*pointer..])?;
*pointer += offset + SCRIPT_START.len();
// find closing ">"
let offset = find_script_closing_angle(self.source_text, *pointer)?;
// get ts and jsx attribute
let content = &self.source_text[*pointer..*pointer + offset];
let is_ts = content.contains("ts");
let is_jsx = content.contains("tsx") || content.contains("jsx");
*pointer += offset + 1;
let js_start = *pointer;
// find "</script>"
let offset = script_end_finder.find(&self.source_text.as_bytes()[*pointer..])?;
let js_end = *pointer + offset;
*pointer += offset + SCRIPT_END.len();
let source_text = &self.source_text[js_start..js_end];
let source_type = SourceType::default()
.with_module(true)
.with_typescript(is_ts)
.with_jsx(is_jsx);
Some(JavaScriptSource::new(source_text, source_type, js_start))
}
}
#[cfg(test)]
mod test {
use super::{JavaScriptSource, VuePartialLoader};
fn parse_vue(source_text: &str) -> JavaScriptSource<'_> {
let sources = VuePartialLoader::new(source_text).parse();
*sources.first().unwrap()
}
#[test]
fn test_parse_vue_one_line() {
let source_text = r#"
<template>
<h1>hello world</h1>
</template>
<script> console.log("hi") </script>
"#;
let result = parse_vue(source_text);
assert_eq!(result.source_text, r#" console.log("hi") "#);
}
#[test]
fn test_build_vue_with_ts_flag_1() {
let source_text = r#"
<script lang="ts" setup generic="T extends Record<string, string>">
1/1
</script>
"#;
let result = parse_vue(source_text);
assert!(result.source_type.is_typescript());
assert_eq!(result.source_text.trim(), "1/1");
}
#[test]
fn test_build_vue_with_ts_flag_2() {
let source_text = r"
<script lang=ts setup>
1/1
</script>
";
let result = parse_vue(source_text);
assert!(result.source_type.is_typescript());
assert_eq!(result.source_text.trim(), "1/1");
}
#[test]
fn test_build_vue_with_ts_flag_3() {
let source_text = r"
<script lang='ts' setup>
1/1
</script>
";
let result = parse_vue(source_text);
assert!(result.source_type.is_typescript());
assert_eq!(result.source_text.trim(), "1/1");
}
#[test]
fn test_build_vue_with_tsx_flag() {
let source_text = r"
<script lang=tsx setup>
1/1
</script>
";
let result = parse_vue(source_text);
assert!(result.source_type.is_jsx());
assert!(result.source_type.is_typescript());
assert_eq!(result.source_text.trim(), "1/1");
}
#[test]
fn test_build_vue_with_escape_string() {
let source_text = r"
<script setup>
a.replace(/'/g, '\''))
</script>
<template> </template>
";
let result = parse_vue(source_text);
assert!(!result.source_type.is_typescript());
assert_eq!(result.source_text.trim(), r"a.replace(/'/g, '\''))");
}
#[test]
fn test_multi_level_template_literal() {
let source_text = r"
<script setup>
`a${b( `c \`${d}\``)}`
</script>
";
let result = parse_vue(source_text);
assert_eq!(result.source_text.trim(), r"`a${b( `c \`${d}\``)}`");
}
#[test]
fn test_brace_with_regex_in_template_literal() {
let source_text = r"
<script setup>
`${/{/}`
</script>
";
let result = parse_vue(source_text);
assert_eq!(result.source_text.trim(), r"`${/{/}`");
}
#[test]
fn test_no_script() {
let source_text = r"
<template></template>
";
let sources = VuePartialLoader::new(source_text).parse();
assert!(sources.is_empty());
}
#[test]
fn test_syntax_error() {
let source_text = r"
<script>
console.log('error')
";
let sources = VuePartialLoader::new(source_text).parse();
assert!(sources.is_empty());
}
#[test]
fn test_multiple_scripts() {
let source_text = r"
<template></template>
<script>a</script>
<script setup>b</script>
";
let sources = VuePartialLoader::new(source_text).parse();
assert_eq!(sources.len(), 2);
assert_eq!(sources[0].source_text, "a");
assert_eq!(sources[1].source_text, "b");
}
#[test]
fn test_unicode() {
let source_text = r"
<script setup>
let 日历 = '2000年';
const t = useTranslate({
'zh-CN': {
calendar: '日历',
tiledDisplay: '平铺展示',
},
});
</script>
";
let result = parse_vue(source_text);
assert_eq!(
result.source_text.trim(),
"let 日历 = '2000年';
const t = useTranslate({
'zh-CN': {
calendar: '日历',
tiledDisplay: '平铺展示',
},
});"
.trim()
);
}
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/signer/sign.rs | crates/tauri-cli/src/signer/sign.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::path::{Path, PathBuf};
use crate::{
error::Context,
helpers::updater_signature::{secret_key, sign_file},
Result,
};
use base64::Engine;
use clap::Parser;
use tauri_utils::display_path;
#[derive(Debug, Parser)]
#[clap(about = "Sign a file")]
pub struct Options {
/// Load the private key from a string
#[clap(
short = 'k',
long,
conflicts_with("private_key_path"),
env = "TAURI_PRIVATE_KEY"
)]
private_key: Option<String>,
/// Load the private key from a file
#[clap(
short = 'f',
long,
conflicts_with("private_key"),
env = "TAURI_PRIVATE_KEY_PATH"
)]
private_key_path: Option<PathBuf>,
/// Set private key password when signing
#[clap(short, long, env = "TAURI_PRIVATE_KEY_PASSWORD")]
password: Option<String>,
/// Sign the specified file
file: PathBuf,
}
pub fn command(mut options: Options) -> Result<()> {
options.private_key = if let Some(private_key) = options.private_key_path {
Some(std::fs::read_to_string(Path::new(&private_key)).expect("Unable to extract private key"))
} else {
options.private_key
};
let private_key = if let Some(pk) = options.private_key {
pk
} else {
crate::error::bail!("Key generation aborted: Unable to find the private key");
};
if options.password.is_none() {
println!("Signing without password.");
}
let (manifest_dir, signature) =
sign_file(&secret_key(private_key, options.password)?, options.file)
.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.",
display_path(manifest_dir),
base64::engine::general_purpose::STANDARD.encode(signature.to_string())
);
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/signer/mod.rs | crates/tauri-cli/src/signer/mod.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::Result;
use clap::{Parser, Subcommand};
mod generate;
mod sign;
#[derive(Parser)]
#[clap(
author,
version,
about = "Generate signing keys for Tauri updater or sign files",
subcommand_required(true),
arg_required_else_help(true)
)]
pub struct Cli {
#[clap(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
Sign(sign::Options),
Generate(generate::Options),
}
pub fn command(cli: Cli) -> Result<()> {
match cli.command {
Commands::Sign(options) => sign::command(options)?,
Commands::Generate(options) => generate::command(options)?,
}
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/signer/generate.rs | crates/tauri-cli/src/signer/generate.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{
helpers::updater_signature::{generate_key, save_keypair},
Result,
};
use clap::Parser;
use std::path::PathBuf;
use tauri_utils::display_path;
#[derive(Debug, Parser)]
#[clap(about = "Generate a new signing key to sign files")]
pub struct Options {
/// Set private key password when signing
#[clap(short, long)]
password: Option<String>,
/// Write private key to a file
#[clap(short, long)]
write_keys: Option<PathBuf>,
/// Overwrite private key even if it exists on the specified path
#[clap(short, long)]
force: bool,
/// Skip prompting for values
#[clap(long, env = "CI")]
ci: bool,
}
pub fn command(mut options: Options) -> Result<()> {
if options.ci && options.password.is_none() {
log::warn!("Generating new private key without password. For security reasons, we recommend setting a password instead.");
options.password.replace("".into());
}
let keypair = generate_key(options.password).expect("Failed to generate key");
if let Some(output_path) = options.write_keys {
let (secret_path, public_path) =
save_keypair(options.force, output_path, &keypair.sk, &keypair.pk)
.expect("Unable to write keypair");
println!(
"\nYour keypair was generated successfully\nPrivate: {} (Keep it secret!)\nPublic: {}\n---------------------------",
display_path(secret_path),
display_path(public_path)
)
} else {
println!(
"\nYour secret key was generated successfully - Keep it secret!\n{}\n\n",
keypair.sk
);
println!(
"Your public key was generated successfully:\n{}\n\nAdd the public key in your tauri.conf.json\n---------------------------\n",
keypair.pk
);
}
println!("\nEnvironment variables used to sign:");
println!("`TAURI_SIGNING_PRIVATE_KEY` Path or String of your private key");
println!("`TAURI_SIGNING_PRIVATE_KEY_PASSWORD` Your private key password (optional)");
println!("\nATTENTION: If you lose your private key OR password, you'll not be able to sign your update package and updates will not work.\n---------------------------\n");
Ok(())
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/info/ios.rs | crates/tauri-cli/src/info/ios.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use super::SectionItem;
use colored::Colorize;
pub fn items() -> Vec<SectionItem> {
vec![SectionItem::new().action(|| {
let teams = cargo_mobile2::apple::teams::find_development_teams().unwrap_or_default();
if teams.is_empty() {
"Developer Teams: None".red().to_string().into()
} else {
format!(
"Developer Teams: {}",
teams
.iter()
.map(|t| format!("{} (ID: {})", t.name, t.id))
.collect::<Vec<String>>()
.join(", ")
)
.into()
}
})]
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/info/app.rs | crates/tauri-cli/src/info/app.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use super::SectionItem;
use crate::helpers::framework;
use std::{
fs::read_to_string,
path::{Path, PathBuf},
};
use tauri_utils::platform::Target;
pub fn items(frontend_dir: Option<&PathBuf>, tauri_dir: Option<&Path>) -> Vec<SectionItem> {
let mut items = Vec::new();
if tauri_dir.is_some() {
if let Ok(config) = crate::helpers::config::get(Target::current(), &[]) {
let config_guard = config.lock().unwrap();
let config = config_guard.as_ref().unwrap();
let bundle_or_build = if config.bundle.active {
"bundle"
} else {
"build"
};
items.push(SectionItem::new().description(format!("build-type: {bundle_or_build}")));
let csp = config
.app
.security
.csp
.clone()
.map(|c| c.to_string())
.unwrap_or_else(|| "unset".to_string());
items.push(SectionItem::new().description(format!("CSP: {csp}")));
if let Some(frontend_dist) = &config.build.frontend_dist {
items.push(SectionItem::new().description(format!("frontendDist: {frontend_dist}")));
}
if let Some(dev_url) = &config.build.dev_url {
items.push(SectionItem::new().description(format!("devUrl: {dev_url}")));
}
if let Some(frontend_dir) = frontend_dir {
if let Ok(package_json) = read_to_string(frontend_dir.join("package.json")) {
let (framework, bundler) = framework::infer_from_package_json(&package_json);
if let Some(framework) = framework {
items.push(SectionItem::new().description(format!("framework: {framework}")));
}
if let Some(bundler) = bundler {
items.push(SectionItem::new().description(format!("bundler: {bundler}")));
}
}
}
}
}
items
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/info/env_rust.rs | crates/tauri-cli/src/info/env_rust.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use super::SectionItem;
use super::Status;
use colored::Colorize;
use std::process::Command;
fn component_version(component: &str) -> Option<(String, Status)> {
Command::new(component)
.arg("-V")
.output()
.map(|o| String::from_utf8_lossy(o.stdout.as_slice()).to_string())
.map(|v| {
format!(
"{component}: {}",
v.split('\n')
.next()
.unwrap()
.strip_prefix(&format!("{component} "))
.unwrap_or_default()
)
})
.map(|desc| (desc, Status::Success))
.ok()
}
pub fn items() -> Vec<SectionItem> {
vec![
SectionItem::new().action(|| {
component_version("rustc")
.unwrap_or_else(|| {
(
format!(
"rustc: {}\nMaybe you don't have rust installed! Visit {}",
"not installed!".red(),
"https://rustup.rs/".cyan()
),
Status::Error,
)
}).into()
}),
SectionItem::new().action(|| {
component_version("cargo")
.unwrap_or_else(|| {
(
format!(
"Cargo: {}\nMaybe you don't have rust installed! Visit {}",
"not installed!".red(),
"https://rustup.rs/".cyan()
),
Status::Error,
)
}).into()
}),
SectionItem::new().action(|| {
component_version("rustup")
.unwrap_or_else(|| {
(
format!(
"rustup: {}\nIf you have rust installed some other way, we recommend uninstalling it\nthen use rustup instead. Visit {}",
"not installed!".red(),
"https://rustup.rs/".cyan()
),
Status::Warning,
)
}).into()
}),
SectionItem::new().action(|| {
Command::new("rustup")
.args(["show", "active-toolchain"])
.output()
.map(|o| String::from_utf8_lossy(o.stdout.as_slice()).to_string())
.map(|v| {
format!(
"Rust toolchain: {}",
v.split('\n')
.next()
.unwrap()
)
})
.map(|desc| (desc, Status::Success))
.ok()
.unwrap_or_else(|| {
(
format!(
"Rust toolchain: couldn't be detected!\nMaybe you don't have rustup installed? if so, Visit {}", "https://rustup.rs/".cyan()
),
Status::Warning,
)
}).into()
}),
]
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/info/env_nodejs.rs | crates/tauri-cli/src/info/env_nodejs.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use super::{ActionResult, SectionItem, VersionMetadata};
use colored::Colorize;
use crate::helpers::{cross_command, npm::manager_version};
pub fn items(metadata: &VersionMetadata) -> Vec<SectionItem> {
let node_target_ver = metadata.js_cli.node.replace(">= ", "");
vec![
SectionItem::new().action(move || {
cross_command("node")
.arg("-v")
.output()
.map(|o| {
if o.status.success() {
let v = String::from_utf8_lossy(o.stdout.as_slice()).to_string();
let v = v
.split('\n')
.next()
.unwrap()
.strip_prefix('v')
.unwrap_or_default()
.trim();
ActionResult::Description(format!("node: {}{}", v, {
let version = semver::Version::parse(v);
let target_version = semver::Version::parse(node_target_ver.as_str());
match (version, target_version) {
(Ok(version), Ok(target_version)) if version < target_version => {
format!(
" ({}, latest: {})",
"outdated".red(),
target_version.to_string().green()
)
}
_ => "".into(),
}
}))
} else {
ActionResult::None
}
})
.ok()
.unwrap_or_default()
}),
SectionItem::new().action(|| manager_version("pnpm").map(|v| format!("pnpm: {v}")).into()),
SectionItem::new().action(|| manager_version("yarn").map(|v| format!("yarn: {v}")).into()),
SectionItem::new().action(|| manager_version("npm").map(|v| format!("npm: {v}")).into()),
SectionItem::new().action(|| manager_version("bun").map(|v| format!("bun: {v}")).into()),
SectionItem::new().action(|| manager_version("deno").map(|v| format!("deno: {v}")).into()),
]
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
tauri-apps/tauri | https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/info/packages_rust.rs | crates/tauri-cli/src/info/packages_rust.rs | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use super::{ActionResult, SectionItem};
use crate::helpers::cargo_manifest::{
cargo_manifest_and_lock, crate_latest_version, crate_version, CrateVersion,
};
use colored::Colorize;
use std::path::{Path, PathBuf};
pub fn items(frontend_dir: Option<&PathBuf>, tauri_dir: Option<&Path>) -> Vec<SectionItem> {
let mut items = Vec::new();
if tauri_dir.is_some() || frontend_dir.is_some() {
if let Some(tauri_dir) = tauri_dir {
let (manifest, lock) = cargo_manifest_and_lock(tauri_dir);
for dep in ["tauri", "tauri-build", "wry", "tao"] {
let crate_version = crate_version(tauri_dir, manifest.as_ref(), lock.as_ref(), dep);
let item = rust_section_item(dep, crate_version);
items.push(item);
}
}
}
let tauri_cli_rust_item = SectionItem::new().action(|| {
std::process::Command::new("cargo")
.arg("tauri")
.arg("-V")
.output()
.ok()
.map(|o| {
if o.status.success() {
let out = String::from_utf8_lossy(o.stdout.as_slice());
let (package, version) = out.split_once(' ').unwrap_or_default();
let version = version.strip_suffix('\n').unwrap_or(version);
let latest_version = crate_latest_version(package).unwrap_or_default();
format!(
"{package} 🦀: {version}{}",
if !(version.is_empty() || latest_version.is_empty()) {
let current_version = semver::Version::parse(version).unwrap();
let target_version = semver::Version::parse(latest_version.as_str()).unwrap();
if current_version < target_version {
format!(
" ({}, latest: {})",
"outdated".yellow(),
latest_version.green()
)
} else {
"".into()
}
} else {
"".into()
}
)
.into()
} else {
ActionResult::None
}
})
.unwrap_or_default()
});
items.push(tauri_cli_rust_item);
items
}
pub fn rust_section_item(dep: &str, crate_version: CrateVersion) -> SectionItem {
let version = crate_version
.version
.as_ref()
.and_then(|v| semver::Version::parse(v).ok());
let version_suffix = match (version, crate_latest_version(dep)) {
(Some(version), Some(target_version)) => {
let target_version = semver::Version::parse(&target_version).unwrap();
if version < target_version {
Some(format!(
" ({}, latest: {})",
"outdated".yellow(),
target_version.to_string().green()
))
} else {
None
}
}
_ => None,
};
SectionItem::new().description(format!(
"{} {}: {}{}",
dep,
"🦀",
crate_version,
version_suffix
.map(|s| format!(",{s}"))
.unwrap_or_else(|| "".into())
))
}
| rust | Apache-2.0 | a03219ca196372fca542633900a5ad26d805fcf7 | 2026-01-04T15:31:58.627796Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.