Skip to content

Commit

Permalink
feat(codegen): use TARGET environment variable if set (#4921)
Browse files Browse the repository at this point in the history
  • Loading branch information
lucasfernog committed Aug 12, 2022
1 parent 8958e9f commit 6ba9968
Show file tree
Hide file tree
Showing 2 changed files with 103 additions and 66 deletions.
5 changes: 5 additions & 0 deletions .changes/codegen-check-target.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"tauri-codegen": patch
---

Use `TARGET` environment variable for code generation inside build scripts.
164 changes: 98 additions & 66 deletions core/tauri-codegen/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ pub struct ContextData {

fn map_core_assets(
options: &AssetOptions,
target: Target,
) -> impl Fn(&AssetKey, &Path, &mut Vec<u8>, &mut CspHashes) -> Result<(), EmbeddedAssetsError> {
#[cfg(feature = "isolation")]
let pattern = tauri_utils::html::PatternObject::from(&options.pattern);
Expand All @@ -40,8 +41,9 @@ fn map_core_assets(

#[allow(clippy::collapsible_if)]
if csp {
#[cfg(target_os = "linux")]
::tauri_utils::html::inject_csp_token(&mut document);
if target == Target::Linux {
::tauri_utils::html::inject_csp_token(&mut document);
}

inject_nonce_token(&mut document, &dangerous_disable_asset_csp_modification);

Expand Down Expand Up @@ -106,6 +108,16 @@ fn map_isolation(
}
}

#[derive(PartialEq, Eq, Clone, Copy)]
enum Target {
Linux,
Windows,
Darwin,
Android,
// iOS.
Ios,
}

/// Build a `tauri::Context` for including in application code.
pub fn context_codegen(data: ContextData) -> Result<TokenStream, EmbeddedAssetsError> {
let ContextData {
Expand All @@ -115,6 +127,34 @@ pub fn context_codegen(data: ContextData) -> Result<TokenStream, EmbeddedAssetsE
root,
} = data;

let target = if let Ok(target) = std::env::var("TARGET") {
if target.contains("unknown-linux") {
Target::Linux
} else if target.contains("pc-windows") {
Target::Windows
} else if target.contains("apple-darwin") {
Target::Darwin
} else if target.contains("android") {
Target::Android
} else if target.contains("apple-ios") {
Target::Ios
} else {
panic!("unknown codegen target {}", target);
}
} else if cfg!(target_os = "linux") {
Target::Linux
} else if cfg!(windows) {
Target::Windows
} else if cfg!(target_os = "macos") {
Target::Darwin
} else if cfg!(target_os = "android") {
Target::Android
} else if cfg!(target_os = "ios") {
Target::Ios
} else {
panic!("unknown codegen target");
};

let mut options = AssetOptions::new(config.tauri.pattern.clone())
.freeze_prototype(config.tauri.security.freeze_prototype)
.dangerous_disable_asset_csp_modification(
Expand Down Expand Up @@ -162,7 +202,7 @@ pub fn context_codegen(data: ContextData) -> Result<TokenStream, EmbeddedAssetsE
path
)
}
EmbeddedAssets::new(assets_path, &options, map_core_assets(&options))?
EmbeddedAssets::new(assets_path, &options, map_core_assets(&options, target))?
}
_ => unimplemented!(),
},
Expand All @@ -172,7 +212,7 @@ pub fn context_codegen(data: ContextData) -> Result<TokenStream, EmbeddedAssetsE
.map(|p| config_parent.join(p))
.collect::<Vec<_>>(),
&options,
map_core_assets(&options),
map_core_assets(&options, target),
)?,
_ => unimplemented!(),
};
Expand All @@ -189,42 +229,41 @@ pub fn context_codegen(data: ContextData) -> Result<TokenStream, EmbeddedAssetsE
out_dir
};

// handle default window icons for Windows targets
#[cfg(windows)]
let default_window_icon = {
let icon_path = find_icon(
&config,
&config_parent,
|i| i.ends_with(".ico"),
"icons/icon.ico",
);
if icon_path.exists() {
ico_icon(&root, &out_dir, icon_path)?
} else {
if target == Target::Windows {
// handle default window icons for Windows targets
let icon_path = find_icon(
&config,
&config_parent,
|i| i.ends_with(".ico"),
"icons/icon.ico",
);
if icon_path.exists() {
ico_icon(&root, &out_dir, icon_path)?
} else {
let icon_path = find_icon(
&config,
&config_parent,
|i| i.ends_with(".png"),
"icons/icon.png",
);
png_icon(&root, &out_dir, icon_path)?
}
} else if target == Target::Linux {
// handle default window icons for Linux targets
let icon_path = find_icon(
&config,
&config_parent,
|i| i.ends_with(".png"),
"icons/icon.png",
);
png_icon(&root, &out_dir, icon_path)?
} else {
quote!(None)
}
};
#[cfg(target_os = "linux")]
let default_window_icon = {
let icon_path = find_icon(
&config,
&config_parent,
|i| i.ends_with(".png"),
"icons/icon.png",
);
png_icon(&root, &out_dir, icon_path)?
};
#[cfg(not(any(windows, target_os = "linux")))]
let default_window_icon = quote!(None);

#[cfg(target_os = "macos")]
let app_icon = if dev {
let app_icon = if target == Target::Darwin && dev {
let mut icon_path = find_icon(
&config,
&config_parent,
Expand All @@ -243,8 +282,6 @@ pub fn context_codegen(data: ContextData) -> Result<TokenStream, EmbeddedAssetsE
} else {
quote!(None)
};
#[cfg(not(target_os = "macos"))]
let app_icon = quote!(None);

let package_name = if let Some(product_name) = &config.package.product_name {
quote!(#product_name.to_string())
Expand Down Expand Up @@ -283,43 +320,40 @@ pub fn context_codegen(data: ContextData) -> Result<TokenStream, EmbeddedAssetsE
};

#[cfg(target_os = "macos")]
let info_plist = {
if dev {
let info_plist_path = config_parent.join("Info.plist");
let mut info_plist = if info_plist_path.exists() {
plist::Value::from_file(&info_plist_path)
.unwrap_or_else(|e| panic!("failed to read plist {}: {}", info_plist_path.display(), e))
} else {
plist::Value::Dictionary(Default::default())
};
let info_plist = if target == Target::Darwin && dev {
let info_plist_path = config_parent.join("Info.plist");
let mut info_plist = if info_plist_path.exists() {
plist::Value::from_file(&info_plist_path)
.unwrap_or_else(|e| panic!("failed to read plist {}: {}", info_plist_path.display(), e))
} else {
plist::Value::Dictionary(Default::default())
};

if let Some(plist) = info_plist.as_dictionary_mut() {
if let Some(product_name) = &config.package.product_name {
plist.insert("CFBundleName".into(), product_name.clone().into());
}
if let Some(version) = &config.package.version {
plist.insert("CFBundleShortVersionString".into(), version.clone().into());
}
let format =
time::format_description::parse("[year][month][day].[hour][minute][second]").unwrap();
if let Ok(build_number) = time::OffsetDateTime::now_utc().format(&format) {
plist.insert("CFBundleVersion".into(), build_number.into());
}
if let Some(plist) = info_plist.as_dictionary_mut() {
if let Some(product_name) = &config.package.product_name {
plist.insert("CFBundleName".into(), product_name.clone().into());
}
if let Some(version) = &config.package.version {
plist.insert("CFBundleShortVersionString".into(), version.clone().into());
}
let format =
time::format_description::parse("[year][month][day].[hour][minute][second]").unwrap();
if let Ok(build_number) = time::OffsetDateTime::now_utc().format(&format) {
plist.insert("CFBundleVersion".into(), build_number.into());
}
}

let out_path = out_dir.join("Info.plist");
info_plist
.to_file_xml(&out_path)
.expect("failed to write Info.plist");
let out_path = out_dir.join("Info.plist");
info_plist
.to_file_xml(&out_path)
.expect("failed to write Info.plist");

let info_plist_path = out_path.display().to_string();
quote!({
#[cfg(desktop)]
tauri::embed_plist::embed_info_plist!(#info_plist_path);
})
} else {
quote!(())
}
let info_plist_path = out_path.display().to_string();
quote!({
tauri::embed_plist::embed_info_plist!(#info_plist_path);
})
} else {
quote!(())
};
#[cfg(not(target_os = "macos"))]
let info_plist = quote!(());
Expand Down Expand Up @@ -443,7 +477,6 @@ fn ico_icon<P: AsRef<Path>>(
Ok(icon)
}

#[cfg(target_os = "macos")]
fn raw_icon<P: AsRef<Path>>(out_dir: &Path, path: P) -> Result<TokenStream, EmbeddedAssetsError> {
let path = path.as_ref();
let bytes = std::fs::read(&path)
Expand Down Expand Up @@ -508,7 +541,6 @@ fn write_if_changed(out_path: &Path, data: &[u8]) -> std::io::Result<()> {
out_file.write_all(data)
}

#[cfg(any(windows, target_os = "macos", target_os = "linux"))]
fn find_icon<F: Fn(&&String) -> bool>(
config: &Config,
config_parent: &Path,
Expand Down

0 comments on commit 6ba9968

Please sign in to comment.