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<&str>,
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 = Path::new(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 = Path::new(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("/Library/Frameworks/".as_ref(), framework, dest_dir)?
196 || copy_framework_from("/Network/Library/Frameworks/".as_ref(), framework, dest_dir)?
197 {
198 continue;
199 }
200 }
201 Ok(())
202}
203
204fn cfg_alias(alias: &str, has_feature: bool) {
207 println!("cargo:rustc-check-cfg=cfg({alias})");
208 if has_feature {
209 println!("cargo:rustc-cfg={alias}");
210 }
211}
212
213#[allow(dead_code)]
215#[derive(Debug)]
216pub struct WindowsAttributes {
217 window_icon_path: Option<PathBuf>,
218 #[doc = include_str!("windows-app-manifest.xml")]
223 app_manifest: Option<String>,
245}
246
247impl Default for WindowsAttributes {
248 fn default() -> Self {
249 Self::new()
250 }
251}
252
253impl WindowsAttributes {
254 pub fn new() -> Self {
256 Self {
257 window_icon_path: Default::default(),
258 app_manifest: Some(include_str!("windows-app-manifest.xml").into()),
259 }
260 }
261
262 #[must_use]
264 pub fn new_without_app_manifest() -> Self {
265 Self {
266 app_manifest: None,
267 window_icon_path: Default::default(),
268 }
269 }
270
271 #[must_use]
274 pub fn window_icon_path<P: AsRef<Path>>(mut self, window_icon_path: P) -> Self {
275 self
276 .window_icon_path
277 .replace(window_icon_path.as_ref().into());
278 self
279 }
280
281 #[doc = include_str!("windows-app-manifest.xml")]
286 #[must_use]
333 pub fn app_manifest<S: AsRef<str>>(mut self, manifest: S) -> Self {
334 self.app_manifest = Some(manifest.as_ref().to_string());
335 self
336 }
337}
338
339#[derive(Debug, Default)]
341pub struct Attributes {
342 #[allow(dead_code)]
343 windows_attributes: WindowsAttributes,
344 capabilities_path_pattern: Option<&'static str>,
345 #[cfg(feature = "codegen")]
346 codegen: Option<codegen::context::CodegenContext>,
347 inlined_plugins: HashMap<&'static str, InlinedPlugin>,
348 app_manifest: AppManifest,
349}
350
351impl Attributes {
352 pub fn new() -> Self {
354 Self::default()
355 }
356
357 #[must_use]
359 pub fn windows_attributes(mut self, windows_attributes: WindowsAttributes) -> Self {
360 self.windows_attributes = windows_attributes;
361 self
362 }
363
364 #[must_use]
372 pub fn capabilities_path_pattern(mut self, pattern: &'static str) -> Self {
373 self.capabilities_path_pattern.replace(pattern);
374 self
375 }
376
377 pub fn plugin(mut self, name: &'static str, plugin: InlinedPlugin) -> Self {
381 self.inlined_plugins.insert(name, plugin);
382 self
383 }
384
385 pub fn plugins<I>(mut self, plugins: I) -> Self
389 where
390 I: IntoIterator<Item = (&'static str, InlinedPlugin)>,
391 {
392 self.inlined_plugins.extend(plugins);
393 self
394 }
395
396 pub fn app_manifest(mut self, manifest: AppManifest) -> Self {
400 self.app_manifest = manifest;
401 self
402 }
403
404 #[cfg(feature = "codegen")]
405 #[cfg_attr(docsrs, doc(cfg(feature = "codegen")))]
406 #[must_use]
407 pub fn codegen(mut self, codegen: codegen::context::CodegenContext) -> Self {
408 self.codegen.replace(codegen);
409 self
410 }
411}
412
413pub fn is_dev() -> bool {
414 env::var("DEP_TAURI_DEV").expect("missing `cargo:dev` instruction, please update tauri to latest")
415 == "true"
416}
417
418pub fn build() {
441 if let Err(error) = try_build(Attributes::default()) {
442 let error = format!("{error:#}");
443 println!("{error}");
444 if error.starts_with("unknown field") {
445 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. ");
446 println!(
447 "Please try updating the Rust crates by running `cargo update` in the Tauri app folder."
448 );
449 }
450 std::process::exit(1);
451 }
452}
453
454#[allow(unused_variables)]
456pub fn try_build(attributes: Attributes) -> Result<()> {
457 use anyhow::anyhow;
458
459 println!("cargo:rerun-if-env-changed=TAURI_CONFIG");
460
461 let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
462 let mobile = target_os == "ios" || target_os == "android";
463 cfg_alias("desktop", !mobile);
464 cfg_alias("mobile", mobile);
465
466 let target_triple = env::var("TARGET").unwrap();
467 let target = tauri_utils::platform::Target::from_triple(&target_triple);
468
469 let (mut config, config_paths) =
470 tauri_utils::config::parse::read_from(target, &env::current_dir().unwrap())?;
471 for config_file_path in config_paths {
472 println!("cargo:rerun-if-changed={}", config_file_path.display());
473 }
474 if let Ok(env) = env::var("TAURI_CONFIG") {
475 let merge_config: serde_json::Value = serde_json::from_str(&env)?;
476 json_patch::merge(&mut config, &merge_config);
477 }
478 let config: Config = serde_json::from_value(config)?;
479
480 let s = config.identifier.split('.');
481 let last = s.clone().count() - 1;
482 let mut android_package_prefix = String::new();
483 for (i, w) in s.enumerate() {
484 if i == last {
485 println!(
486 "cargo:rustc-env=TAURI_ANDROID_PACKAGE_NAME_APP_NAME={}",
487 w.replace('-', "_")
488 );
489 } else {
490 android_package_prefix.push_str(&w.replace(['_', '-'], "_1"));
491 android_package_prefix.push('_');
492 }
493 }
494 android_package_prefix.pop();
495 println!("cargo:rustc-env=TAURI_ANDROID_PACKAGE_NAME_PREFIX={android_package_prefix}");
496
497 if let Some(project_dir) = env::var_os("TAURI_ANDROID_PROJECT_PATH").map(PathBuf::from) {
498 mobile::generate_gradle_files(project_dir)?;
499 }
500
501 cfg_alias("dev", is_dev());
502
503 let cargo_toml_path = Path::new("Cargo.toml").canonicalize()?;
504 let mut manifest = Manifest::<cargo_toml::Value>::from_path_with_metadata(cargo_toml_path)?;
505
506 let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
507
508 manifest::check(&config, &mut manifest)?;
509
510 acl::build(&out_dir, target, &attributes)?;
511
512 tauri_utils::plugin::save_global_api_scripts_paths(&out_dir, None);
513
514 println!("cargo:rustc-env=TAURI_ENV_TARGET_TRIPLE={target_triple}");
515 env::set_var("TAURI_ENV_TARGET_TRIPLE", &target_triple);
517
518 let target_dir = out_dir
520 .parent()
521 .unwrap()
522 .parent()
523 .unwrap()
524 .parent()
525 .unwrap();
526
527 if let Some(paths) = &config.bundle.external_bin {
528 copy_binaries(
529 ResourcePaths::new(&external_binaries(paths, &target_triple, &target), true),
530 &target_triple,
531 target_dir,
532 manifest.package.as_ref().map(|p| p.name.as_ref()),
533 )?;
534 }
535
536 #[allow(unused_mut, clippy::redundant_clone)]
537 let mut resources = config
538 .bundle
539 .resources
540 .clone()
541 .unwrap_or_else(|| BundleResources::List(Vec::new()));
542 if target_triple.contains("windows") {
543 if let Some(fixed_webview2_runtime_path) = match &config.bundle.windows.webview_install_mode {
544 WebviewInstallMode::FixedRuntime { path } => Some(path),
545 _ => None,
546 } {
547 resources.push(fixed_webview2_runtime_path.display().to_string());
548 }
549 }
550 match resources {
551 BundleResources::List(res) => {
552 copy_resources(ResourcePaths::new(res.as_slice(), true), target_dir)?
553 }
554 BundleResources::Map(map) => copy_resources(ResourcePaths::from_map(&map, true), target_dir)?,
555 }
556
557 if target_triple.contains("darwin") {
558 if let Some(frameworks) = &config.bundle.macos.frameworks {
559 if !frameworks.is_empty() {
560 let frameworks_dir = target_dir.parent().unwrap().join("Frameworks");
561 let _ = fs::remove_dir_all(&frameworks_dir);
562 copy_frameworks(&frameworks_dir, frameworks)?;
565
566 println!("cargo:rustc-link-arg=-Wl,-rpath,@executable_path/../Frameworks");
569 }
570 }
571
572 if !is_dev() {
573 if let Some(version) = &config.bundle.macos.minimum_system_version {
574 println!("cargo:rustc-env=MACOSX_DEPLOYMENT_TARGET={version}");
575 }
576 }
577 }
578
579 if target_triple.contains("ios") {
580 println!(
581 "cargo:rustc-env=IPHONEOS_DEPLOYMENT_TARGET={}",
582 config.bundle.ios.minimum_system_version
583 );
584 }
585
586 if target_triple.contains("windows") {
587 use semver::Version;
588 use tauri_winres::{VersionInfo, WindowsResource};
589
590 let window_icon_path = attributes
591 .windows_attributes
592 .window_icon_path
593 .unwrap_or_else(|| {
594 config
595 .bundle
596 .icon
597 .iter()
598 .find(|i| i.ends_with(".ico"))
599 .map(AsRef::as_ref)
600 .unwrap_or("icons/icon.ico")
601 .into()
602 });
603
604 let mut res = WindowsResource::new();
605
606 if let Some(manifest) = attributes.windows_attributes.app_manifest {
607 res.set_manifest(&manifest);
608 }
609
610 if let Some(version_str) = &config.version {
611 if let Ok(v) = Version::parse(version_str) {
612 let version = (v.major << 48) | (v.minor << 32) | (v.patch << 16);
613 res.set_version_info(VersionInfo::FILEVERSION, version);
614 res.set_version_info(VersionInfo::PRODUCTVERSION, version);
615 }
616 }
617
618 if let Some(product_name) = &config.product_name {
619 res.set("ProductName", product_name);
620 }
621
622 let company_name = config.bundle.publisher.unwrap_or_else(|| {
623 config
624 .identifier
625 .split('.')
626 .nth(1)
627 .unwrap_or(&config.identifier)
628 .to_string()
629 });
630
631 res.set("CompanyName", &company_name);
632
633 let file_description = config
634 .product_name
635 .or_else(|| manifest.package.as_ref().map(|p| p.name.clone()))
636 .or_else(|| std::env::var("CARGO_PKG_NAME").ok());
637
638 res.set("FileDescription", &file_description.unwrap());
639
640 if let Some(copyright) = &config.bundle.copyright {
641 res.set("LegalCopyright", copyright);
642 }
643
644 if window_icon_path.exists() {
645 res.set_icon_with_id(&window_icon_path.display().to_string(), "32512");
646 } else {
647 return Err(anyhow!(format!(
648 "`{}` not found; required for generating a Windows Resource file during tauri-build",
649 window_icon_path.display()
650 )));
651 }
652
653 res.compile().with_context(|| {
654 format!(
655 "failed to compile `{}` into a Windows Resource file during tauri-build",
656 window_icon_path.display()
657 )
658 })?;
659
660 let target_env = env::var("CARGO_CFG_TARGET_ENV").unwrap();
661 match target_env.as_str() {
662 "gnu" => {
663 let target_arch = match env::var("CARGO_CFG_TARGET_ARCH").unwrap().as_str() {
664 "x86_64" => Some("x64"),
665 "x86" => Some("x86"),
666 "aarch64" => Some("arm64"),
667 arch => None,
668 };
669 if let Some(target_arch) = target_arch {
670 for entry in fs::read_dir(target_dir.join("build"))? {
671 let path = entry?.path();
672 let webview2_loader_path = path
673 .join("out")
674 .join(target_arch)
675 .join("WebView2Loader.dll");
676 if path.to_string_lossy().contains("webview2-com-sys") && webview2_loader_path.exists()
677 {
678 fs::copy(webview2_loader_path, target_dir.join("WebView2Loader.dll"))?;
679 break;
680 }
681 }
682 }
683 }
684 "msvc" => {
685 if env::var("STATIC_VCRUNTIME").is_ok_and(|v| v == "true") {
686 static_vcruntime::build();
687 }
688 }
689 _ => (),
690 }
691 }
692
693 #[cfg(feature = "codegen")]
694 if let Some(codegen) = attributes.codegen {
695 codegen.try_build()?;
696 }
697
698 Ok(())
699}