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]
374 pub fn capabilities_path_pattern(mut self, pattern: &'static str) -> Self {
375 self.capabilities_path_pattern.replace(pattern);
376 self
377 }
378
379 pub fn plugin(mut self, name: &'static str, plugin: InlinedPlugin) -> Self {
383 self.inlined_plugins.insert(name, plugin);
384 self
385 }
386
387 pub fn plugins<I>(mut self, plugins: I) -> Self
391 where
392 I: IntoIterator<Item = (&'static str, InlinedPlugin)>,
393 {
394 self.inlined_plugins.extend(plugins);
395 self
396 }
397
398 pub fn app_manifest(mut self, manifest: AppManifest) -> Self {
402 self.app_manifest = manifest;
403 self
404 }
405
406 #[cfg(feature = "codegen")]
407 #[cfg_attr(docsrs, doc(cfg(feature = "codegen")))]
408 #[must_use]
409 pub fn codegen(mut self, codegen: codegen::context::CodegenContext) -> Self {
410 self.codegen.replace(codegen);
411 self
412 }
413}
414
415pub fn is_dev() -> bool {
416 env::var("DEP_TAURI_DEV").expect("missing `cargo:dev` instruction, please update tauri to latest")
417 == "true"
418}
419
420pub fn build() {
440 if let Err(error) = try_build(Attributes::default()) {
441 let error = format!("{error:#}");
442 println!("{error}");
443 if error.starts_with("unknown field") {
444 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. ");
445 println!(
446 "Please try updating the Rust crates by running `cargo update` in the Tauri app folder."
447 );
448 }
449 std::process::exit(1);
450 }
451}
452
453#[allow(unused_variables)]
455pub fn try_build(attributes: Attributes) -> Result<()> {
456 use anyhow::anyhow;
457
458 println!("cargo:rerun-if-env-changed=TAURI_CONFIG");
459 #[cfg(feature = "config-json")]
460 println!("cargo:rerun-if-changed=tauri.conf.json");
461 #[cfg(feature = "config-json5")]
462 println!("cargo:rerun-if-changed=tauri.conf.json5");
463 #[cfg(feature = "config-toml")]
464 println!("cargo:rerun-if-changed=Tauri.toml");
465
466 let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
467 let mobile = target_os == "ios" || target_os == "android";
468 cfg_alias("desktop", !mobile);
469 cfg_alias("mobile", mobile);
470
471 let target_triple = env::var("TARGET").unwrap();
472 let target = tauri_utils::platform::Target::from_triple(&target_triple);
473
474 let (config, merged_config_path) =
475 tauri_utils::config::parse::read_from(target, env::current_dir().unwrap())?;
476 if let Some(merged_config_path) = merged_config_path {
477 println!("cargo:rerun-if-changed={}", merged_config_path.display());
478 }
479 let mut config = serde_json::from_value(config)?;
480 if let Ok(env) = env::var("TAURI_CONFIG") {
481 let merge_config: serde_json::Value = serde_json::from_str(&env)?;
482 json_patch::merge(&mut config, &merge_config);
483 }
484 let config: Config = serde_json::from_value(config)?;
485
486 let s = config.identifier.split('.');
487 let last = s.clone().count() - 1;
488 let mut android_package_prefix = String::new();
489 for (i, w) in s.enumerate() {
490 if i == last {
491 println!(
492 "cargo:rustc-env=TAURI_ANDROID_PACKAGE_NAME_APP_NAME={}",
493 w.replace('-', "_")
494 );
495 } else {
496 android_package_prefix.push_str(&w.replace(['_', '-'], "_1"));
497 android_package_prefix.push('_');
498 }
499 }
500 android_package_prefix.pop();
501 println!("cargo:rustc-env=TAURI_ANDROID_PACKAGE_NAME_PREFIX={android_package_prefix}");
502
503 if let Some(project_dir) = env::var_os("TAURI_ANDROID_PROJECT_PATH").map(PathBuf::from) {
504 mobile::generate_gradle_files(project_dir, &config)?;
505 }
506
507 cfg_alias("dev", is_dev());
508
509 let cargo_toml_path = Path::new("Cargo.toml").canonicalize()?;
510 let mut manifest = Manifest::<cargo_toml::Value>::from_path_with_metadata(cargo_toml_path)?;
511
512 let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
513
514 manifest::check(&config, &mut manifest)?;
515
516 acl::build(&out_dir, target, &attributes)?;
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).as_slice(), 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 let Some(version) = &config.bundle.macos.minimum_system_version {
577 println!("cargo:rustc-env=MACOSX_DEPLOYMENT_TARGET={version}");
578 }
579 }
580
581 if target_triple.contains("ios") {
582 println!(
583 "cargo:rustc-env=IPHONEOS_DEPLOYMENT_TARGET={}",
584 config.bundle.ios.minimum_system_version
585 );
586 }
587
588 if target_triple.contains("windows") {
589 use semver::Version;
590 use tauri_winres::{VersionInfo, WindowsResource};
591
592 fn find_icon<F: Fn(&&String) -> bool>(config: &Config, predicate: F, default: &str) -> PathBuf {
593 let icon_path = config
594 .bundle
595 .icon
596 .iter()
597 .find(|i| predicate(i))
598 .cloned()
599 .unwrap_or_else(|| default.to_string());
600 icon_path.into()
601 }
602
603 let window_icon_path = attributes
604 .windows_attributes
605 .window_icon_path
606 .unwrap_or_else(|| find_icon(&config, |i| i.ends_with(".ico"), "icons/icon.ico"));
607
608 let mut res = WindowsResource::new();
609
610 if let Some(manifest) = attributes.windows_attributes.app_manifest {
611 res.set_manifest(&manifest);
612 }
613
614 if let Some(version_str) = &config.version {
615 if let Ok(v) = Version::parse(version_str) {
616 let version = v.major << 48 | v.minor << 32 | v.patch << 16;
617 res.set_version_info(VersionInfo::FILEVERSION, version);
618 res.set_version_info(VersionInfo::PRODUCTVERSION, version);
619 }
620 }
621
622 if let Some(product_name) = &config.product_name {
623 res.set("ProductName", product_name);
624 }
625
626 let file_description = config
627 .product_name
628 .or_else(|| manifest.package.as_ref().map(|p| p.name.clone()))
629 .or_else(|| std::env::var("CARGO_PKG_NAME").ok());
630
631 res.set("FileDescription", &file_description.unwrap());
632
633 if let Some(copyright) = &config.bundle.copyright {
634 res.set("LegalCopyright", copyright);
635 }
636
637 if window_icon_path.exists() {
638 res.set_icon_with_id(&window_icon_path.display().to_string(), "32512");
639 } else {
640 return Err(anyhow!(format!(
641 "`{}` not found; required for generating a Windows Resource file during tauri-build",
642 window_icon_path.display()
643 )));
644 }
645
646 res.compile().with_context(|| {
647 format!(
648 "failed to compile `{}` into a Windows Resource file during tauri-build",
649 window_icon_path.display()
650 )
651 })?;
652
653 let target_env = env::var("CARGO_CFG_TARGET_ENV").unwrap();
654 match target_env.as_str() {
655 "gnu" => {
656 let target_arch = match env::var("CARGO_CFG_TARGET_ARCH").unwrap().as_str() {
657 "x86_64" => Some("x64"),
658 "x86" => Some("x86"),
659 "aarch64" => Some("arm64"),
660 arch => None,
661 };
662 if let Some(target_arch) = target_arch {
663 for entry in fs::read_dir(target_dir.join("build"))? {
664 let path = entry?.path();
665 let webview2_loader_path = path
666 .join("out")
667 .join(target_arch)
668 .join("WebView2Loader.dll");
669 if path.to_string_lossy().contains("webview2-com-sys") && webview2_loader_path.exists()
670 {
671 fs::copy(webview2_loader_path, target_dir.join("WebView2Loader.dll"))?;
672 break;
673 }
674 }
675 }
676 }
677 "msvc" => {
678 if env::var("STATIC_VCRUNTIME").is_ok_and(|v| v == "true") {
679 static_vcruntime::build();
680 }
681 }
682 _ => (),
683 }
684 }
685
686 #[cfg(feature = "codegen")]
687 if let Some(codegen) = attributes.codegen {
688 codegen.try_build()?;
689 }
690
691 Ok(())
692}