1#![doc(
8 html_logo_url = "https://github.com/tauri-apps/tauri/raw/dev/.github/icon.png",
9 html_favicon_url = "https://github.com/tauri-apps/tauri/raw/dev/.github/icon.png"
10)]
11#![cfg_attr(docsrs, feature(doc_cfg))]
12
13use anyhow::Context;
14pub use anyhow::Result;
15use cargo_toml::Manifest;
16
17use tauri_utils::{
18 config::{BundleResources, Config, WebviewInstallMode},
19 resources::{external_binaries, ResourcePaths},
20};
21
22use std::{
23 collections::HashMap,
24 env, fs,
25 path::{Path, PathBuf},
26};
27
28mod acl;
29#[cfg(feature = "codegen")]
30mod codegen;
31mod manifest;
32mod mobile;
33mod static_vcruntime;
34
35#[cfg(feature = "codegen")]
36#[cfg_attr(docsrs, doc(cfg(feature = "codegen")))]
37pub use codegen::context::CodegenContext;
38
39pub use acl::{AppManifest, DefaultPermissionRule, InlinedPlugin};
40
41fn copy_file(from: impl AsRef<Path>, to: impl AsRef<Path>) -> Result<()> {
42 let from = from.as_ref();
43 let to = to.as_ref();
44 if !from.exists() {
45 return Err(anyhow::anyhow!("{:?} does not exist", from));
46 }
47 if !from.is_file() {
48 return Err(anyhow::anyhow!("{:?} is not a file", from));
49 }
50 let dest_dir = to.parent().expect("No data in parent");
51 fs::create_dir_all(dest_dir)?;
52 fs::copy(from, to)?;
53 Ok(())
54}
55
56fn copy_binaries(
57 binaries: ResourcePaths,
58 target_triple: &str,
59 path: &Path,
60 package_name: Option<&String>,
61) -> Result<()> {
62 for src in binaries {
63 let src = src?;
64 println!("cargo:rerun-if-changed={}", src.display());
65 let file_name = src
66 .file_name()
67 .expect("failed to extract external binary filename")
68 .to_string_lossy()
69 .replace(&format!("-{target_triple}"), "");
70
71 if package_name == Some(&file_name) {
72 return Err(anyhow::anyhow!(
73 "Cannot define a sidecar with the same name as the Cargo package name `{}`. Please change the sidecar name in the filesystem and the Tauri configuration.",
74 file_name
75 ));
76 }
77
78 let dest = path.join(file_name);
79 if dest.exists() {
80 fs::remove_file(&dest).unwrap();
81 }
82 copy_file(&src, &dest)?;
83 }
84 Ok(())
85}
86
87fn copy_resources(resources: ResourcePaths<'_>, path: &Path) -> Result<()> {
89 let path = path.canonicalize()?;
90 for resource in resources.iter() {
91 let resource = resource?;
92
93 println!("cargo:rerun-if-changed={}", resource.path().display());
94
95 let src = resource.path().canonicalize()?;
97 let target = path.join(resource.target());
98 if src != target {
99 copy_file(src, target)?;
100 }
101 }
102 Ok(())
103}
104
105#[cfg(unix)]
106fn symlink_dir(src: &Path, dst: &Path) -> std::io::Result<()> {
107 std::os::unix::fs::symlink(src, dst)
108}
109
110#[cfg(windows)]
112fn symlink_dir(src: &Path, dst: &Path) -> std::io::Result<()> {
113 std::os::windows::fs::symlink_dir(src, dst)
114}
115
116#[cfg(unix)]
118fn symlink_file(src: &Path, dst: &Path) -> std::io::Result<()> {
119 std::os::unix::fs::symlink(src, dst)
120}
121
122#[cfg(windows)]
124fn symlink_file(src: &Path, dst: &Path) -> std::io::Result<()> {
125 std::os::windows::fs::symlink_file(src, dst)
126}
127
128fn copy_dir(from: &Path, to: &Path) -> Result<()> {
129 for entry in walkdir::WalkDir::new(from) {
130 let entry = entry?;
131 debug_assert!(entry.path().starts_with(from));
132 let rel_path = entry.path().strip_prefix(from)?;
133 let dest_path = to.join(rel_path);
134 if entry.file_type().is_symlink() {
135 let target = fs::read_link(entry.path())?;
136 if entry.path().is_dir() {
137 symlink_dir(&target, &dest_path)?;
138 } else {
139 symlink_file(&target, &dest_path)?;
140 }
141 } else if entry.file_type().is_dir() {
142 fs::create_dir(dest_path)?;
143 } else {
144 fs::copy(entry.path(), dest_path)?;
145 }
146 }
147 Ok(())
148}
149
150fn copy_framework_from(src_dir: &Path, framework: &str, dest_dir: &Path) -> Result<bool> {
152 let src_name = format!("{framework}.framework");
153 let src_path = src_dir.join(&src_name);
154 if src_path.exists() {
155 copy_dir(&src_path, &dest_dir.join(&src_name))?;
156 Ok(true)
157 } else {
158 Ok(false)
159 }
160}
161
162fn copy_frameworks(dest_dir: &Path, frameworks: &[String]) -> Result<()> {
164 fs::create_dir_all(dest_dir)
165 .with_context(|| format!("Failed to create frameworks output directory at {dest_dir:?}"))?;
166 for framework in frameworks.iter() {
167 if framework.ends_with(".framework") {
168 let src_path = PathBuf::from(framework);
169 let src_name = src_path
170 .file_name()
171 .expect("Couldn't get framework filename");
172 let dest_path = dest_dir.join(src_name);
173 copy_dir(&src_path, &dest_path)?;
174 continue;
175 } else if framework.ends_with(".dylib") {
176 let src_path = PathBuf::from(framework);
177 if !src_path.exists() {
178 return Err(anyhow::anyhow!("Library not found: {}", framework));
179 }
180 let src_name = src_path.file_name().expect("Couldn't get library filename");
181 let dest_path = dest_dir.join(src_name);
182 copy_file(&src_path, &dest_path)?;
183 continue;
184 } else if framework.contains('/') {
185 return Err(anyhow::anyhow!(
186 "Framework path should have .framework extension: {}",
187 framework
188 ));
189 }
190 if let Some(home_dir) = dirs::home_dir() {
191 if copy_framework_from(&home_dir.join("Library/Frameworks/"), framework, dest_dir)? {
192 continue;
193 }
194 }
195 if copy_framework_from(&PathBuf::from("/Library/Frameworks/"), framework, dest_dir)?
196 || copy_framework_from(
197 &PathBuf::from("/Network/Library/Frameworks/"),
198 framework,
199 dest_dir,
200 )?
201 {
202 continue;
203 }
204 }
205 Ok(())
206}
207
208fn cfg_alias(alias: &str, has_feature: bool) {
211 println!("cargo:rustc-check-cfg=cfg({alias})");
212 if has_feature {
213 println!("cargo:rustc-cfg={alias}");
214 }
215}
216
217#[allow(dead_code)]
219#[derive(Debug)]
220pub struct WindowsAttributes {
221 window_icon_path: Option<PathBuf>,
222 #[doc = include_str!("windows-app-manifest.xml")]
227 app_manifest: Option<String>,
249}
250
251impl Default for WindowsAttributes {
252 fn default() -> Self {
253 Self::new()
254 }
255}
256
257impl WindowsAttributes {
258 pub fn new() -> Self {
260 Self {
261 window_icon_path: Default::default(),
262 app_manifest: Some(include_str!("windows-app-manifest.xml").into()),
263 }
264 }
265
266 #[must_use]
268 pub fn new_without_app_manifest() -> Self {
269 Self {
270 app_manifest: None,
271 window_icon_path: Default::default(),
272 }
273 }
274
275 #[must_use]
278 pub fn window_icon_path<P: AsRef<Path>>(mut self, window_icon_path: P) -> Self {
279 self
280 .window_icon_path
281 .replace(window_icon_path.as_ref().into());
282 self
283 }
284
285 #[doc = include_str!("windows-app-manifest.xml")]
290 #[must_use]
337 pub fn app_manifest<S: AsRef<str>>(mut self, manifest: S) -> Self {
338 self.app_manifest = Some(manifest.as_ref().to_string());
339 self
340 }
341}
342
343#[derive(Debug, Default)]
345pub struct Attributes {
346 #[allow(dead_code)]
347 windows_attributes: WindowsAttributes,
348 capabilities_path_pattern: Option<&'static str>,
349 #[cfg(feature = "codegen")]
350 codegen: Option<codegen::context::CodegenContext>,
351 inlined_plugins: HashMap<&'static str, InlinedPlugin>,
352 app_manifest: AppManifest,
353}
354
355impl Attributes {
356 pub fn new() -> Self {
358 Self::default()
359 }
360
361 #[must_use]
363 pub fn windows_attributes(mut self, windows_attributes: WindowsAttributes) -> Self {
364 self.windows_attributes = windows_attributes;
365 self
366 }
367
368 #[must_use]
376 pub fn capabilities_path_pattern(mut self, pattern: &'static str) -> Self {
377 self.capabilities_path_pattern.replace(pattern);
378 self
379 }
380
381 pub fn plugin(mut self, name: &'static str, plugin: InlinedPlugin) -> Self {
385 self.inlined_plugins.insert(name, plugin);
386 self
387 }
388
389 pub fn plugins<I>(mut self, plugins: I) -> Self
393 where
394 I: IntoIterator<Item = (&'static str, InlinedPlugin)>,
395 {
396 self.inlined_plugins.extend(plugins);
397 self
398 }
399
400 pub fn app_manifest(mut self, manifest: AppManifest) -> Self {
404 self.app_manifest = manifest;
405 self
406 }
407
408 #[cfg(feature = "codegen")]
409 #[cfg_attr(docsrs, doc(cfg(feature = "codegen")))]
410 #[must_use]
411 pub fn codegen(mut self, codegen: codegen::context::CodegenContext) -> Self {
412 self.codegen.replace(codegen);
413 self
414 }
415}
416
417pub fn is_dev() -> bool {
418 env::var("DEP_TAURI_DEV").expect("missing `cargo:dev` instruction, please update tauri to latest")
419 == "true"
420}
421
422pub fn build() {
445 if let Err(error) = try_build(Attributes::default()) {
446 let error = format!("{error:#}");
447 println!("{error}");
448 if error.starts_with("unknown field") {
449 print!("found an unknown configuration field. This usually means that you are using a CLI version that is newer than `tauri-build` and is incompatible. ");
450 println!(
451 "Please try updating the Rust crates by running `cargo update` in the Tauri app folder."
452 );
453 }
454 std::process::exit(1);
455 }
456}
457
458#[allow(unused_variables)]
460pub fn try_build(attributes: Attributes) -> Result<()> {
461 use anyhow::anyhow;
462
463 println!("cargo:rerun-if-env-changed=TAURI_CONFIG");
464
465 let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
466 let mobile = target_os == "ios" || target_os == "android";
467 cfg_alias("desktop", !mobile);
468 cfg_alias("mobile", mobile);
469
470 let target_triple = env::var("TARGET").unwrap();
471 let target = tauri_utils::platform::Target::from_triple(&target_triple);
472
473 let (mut config, config_paths) =
474 tauri_utils::config::parse::read_from(target, &env::current_dir().unwrap())?;
475 for config_file_path in config_paths {
476 println!("cargo:rerun-if-changed={}", config_file_path.display());
477 }
478 if let Ok(env) = env::var("TAURI_CONFIG") {
479 let merge_config: serde_json::Value = serde_json::from_str(&env)?;
480 json_patch::merge(&mut config, &merge_config);
481 }
482 let config: Config = serde_json::from_value(config)?;
483
484 let s = config.identifier.split('.');
485 let last = s.clone().count() - 1;
486 let mut android_package_prefix = String::new();
487 for (i, w) in s.enumerate() {
488 if i == last {
489 println!(
490 "cargo:rustc-env=TAURI_ANDROID_PACKAGE_NAME_APP_NAME={}",
491 w.replace('-', "_")
492 );
493 } else {
494 android_package_prefix.push_str(&w.replace(['_', '-'], "_1"));
495 android_package_prefix.push('_');
496 }
497 }
498 android_package_prefix.pop();
499 println!("cargo:rustc-env=TAURI_ANDROID_PACKAGE_NAME_PREFIX={android_package_prefix}");
500
501 if let Some(project_dir) = env::var_os("TAURI_ANDROID_PROJECT_PATH").map(PathBuf::from) {
502 mobile::generate_gradle_files(project_dir, &config)?;
503 }
504
505 cfg_alias("dev", is_dev());
506
507 let cargo_toml_path = Path::new("Cargo.toml").canonicalize()?;
508 let mut manifest = Manifest::<cargo_toml::Value>::from_path_with_metadata(cargo_toml_path)?;
509
510 let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
511
512 manifest::check(&config, &mut manifest)?;
513
514 acl::build(&out_dir, target, &attributes)?;
515
516 tauri_utils::plugin::save_global_api_scripts_paths(&out_dir, None);
517
518 println!("cargo:rustc-env=TAURI_ENV_TARGET_TRIPLE={target_triple}");
519 env::set_var("TAURI_ENV_TARGET_TRIPLE", &target_triple);
521
522 let target_dir = out_dir
524 .parent()
525 .unwrap()
526 .parent()
527 .unwrap()
528 .parent()
529 .unwrap();
530
531 if let Some(paths) = &config.bundle.external_bin {
532 copy_binaries(
533 ResourcePaths::new(&external_binaries(paths, &target_triple, &target), true),
534 &target_triple,
535 target_dir,
536 manifest.package.as_ref().map(|p| &p.name),
537 )?;
538 }
539
540 #[allow(unused_mut, clippy::redundant_clone)]
541 let mut resources = config
542 .bundle
543 .resources
544 .clone()
545 .unwrap_or_else(|| BundleResources::List(Vec::new()));
546 if target_triple.contains("windows") {
547 if let Some(fixed_webview2_runtime_path) = match &config.bundle.windows.webview_install_mode {
548 WebviewInstallMode::FixedRuntime { path } => Some(path),
549 _ => None,
550 } {
551 resources.push(fixed_webview2_runtime_path.display().to_string());
552 }
553 }
554 match resources {
555 BundleResources::List(res) => {
556 copy_resources(ResourcePaths::new(res.as_slice(), true), target_dir)?
557 }
558 BundleResources::Map(map) => copy_resources(ResourcePaths::from_map(&map, true), target_dir)?,
559 }
560
561 if target_triple.contains("darwin") {
562 if let Some(frameworks) = &config.bundle.macos.frameworks {
563 if !frameworks.is_empty() {
564 let frameworks_dir = target_dir.parent().unwrap().join("Frameworks");
565 let _ = fs::remove_dir_all(&frameworks_dir);
566 copy_frameworks(&frameworks_dir, frameworks)?;
569
570 println!("cargo:rustc-link-arg=-Wl,-rpath,@executable_path/../Frameworks");
573 }
574 }
575
576 if !is_dev() {
577 if let Some(version) = &config.bundle.macos.minimum_system_version {
578 println!("cargo:rustc-env=MACOSX_DEPLOYMENT_TARGET={version}");
579 }
580 }
581 }
582
583 if target_triple.contains("ios") {
584 println!(
585 "cargo:rustc-env=IPHONEOS_DEPLOYMENT_TARGET={}",
586 config.bundle.ios.minimum_system_version
587 );
588 }
589
590 if target_triple.contains("windows") {
591 use semver::Version;
592 use tauri_winres::{VersionInfo, WindowsResource};
593
594 fn find_icon<F: Fn(&&String) -> bool>(config: &Config, predicate: F, default: &str) -> PathBuf {
595 let icon_path = config
596 .bundle
597 .icon
598 .iter()
599 .find(|i| predicate(i))
600 .cloned()
601 .unwrap_or_else(|| default.to_string());
602 icon_path.into()
603 }
604
605 let window_icon_path = attributes
606 .windows_attributes
607 .window_icon_path
608 .unwrap_or_else(|| find_icon(&config, |i| i.ends_with(".ico"), "icons/icon.ico"));
609
610 let mut res = WindowsResource::new();
611
612 if let Some(manifest) = attributes.windows_attributes.app_manifest {
613 res.set_manifest(&manifest);
614 }
615
616 if let Some(version_str) = &config.version {
617 if let Ok(v) = Version::parse(version_str) {
618 let version = (v.major << 48) | (v.minor << 32) | (v.patch << 16);
619 res.set_version_info(VersionInfo::FILEVERSION, version);
620 res.set_version_info(VersionInfo::PRODUCTVERSION, version);
621 }
622 }
623
624 if let Some(product_name) = &config.product_name {
625 res.set("ProductName", product_name);
626 }
627
628 let company_name = config.bundle.publisher.unwrap_or_else(|| {
629 config
630 .identifier
631 .split('.')
632 .nth(1)
633 .unwrap_or(&config.identifier)
634 .to_string()
635 });
636
637 res.set("CompanyName", &company_name);
638
639 let file_description = config
640 .product_name
641 .or_else(|| manifest.package.as_ref().map(|p| p.name.clone()))
642 .or_else(|| std::env::var("CARGO_PKG_NAME").ok());
643
644 res.set("FileDescription", &file_description.unwrap());
645
646 if let Some(copyright) = &config.bundle.copyright {
647 res.set("LegalCopyright", copyright);
648 }
649
650 if window_icon_path.exists() {
651 res.set_icon_with_id(&window_icon_path.display().to_string(), "32512");
652 } else {
653 return Err(anyhow!(format!(
654 "`{}` not found; required for generating a Windows Resource file during tauri-build",
655 window_icon_path.display()
656 )));
657 }
658
659 res.compile().with_context(|| {
660 format!(
661 "failed to compile `{}` into a Windows Resource file during tauri-build",
662 window_icon_path.display()
663 )
664 })?;
665
666 let target_env = env::var("CARGO_CFG_TARGET_ENV").unwrap();
667 match target_env.as_str() {
668 "gnu" => {
669 let target_arch = match env::var("CARGO_CFG_TARGET_ARCH").unwrap().as_str() {
670 "x86_64" => Some("x64"),
671 "x86" => Some("x86"),
672 "aarch64" => Some("arm64"),
673 arch => None,
674 };
675 if let Some(target_arch) = target_arch {
676 for entry in fs::read_dir(target_dir.join("build"))? {
677 let path = entry?.path();
678 let webview2_loader_path = path
679 .join("out")
680 .join(target_arch)
681 .join("WebView2Loader.dll");
682 if path.to_string_lossy().contains("webview2-com-sys") && webview2_loader_path.exists()
683 {
684 fs::copy(webview2_loader_path, target_dir.join("WebView2Loader.dll"))?;
685 break;
686 }
687 }
688 }
689 }
690 "msvc" => {
691 if env::var("STATIC_VCRUNTIME").is_ok_and(|v| v == "true") {
692 static_vcruntime::build();
693 }
694 }
695 _ => (),
696 }
697 }
698
699 #[cfg(feature = "codegen")]
700 if let Some(codegen) = attributes.codegen {
701 codegen.try_build()?;
702 }
703
704 Ok(())
705}