Skip to content

Commit a4aec9f

Browse files
feat(cli): expose TAURI_TARGET_TRIPLE to before*Commands, closes #5091 (#5101)
Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
1 parent 39bf895 commit a4aec9f

9 files changed

Lines changed: 121 additions & 35 deletions

File tree

.changes/cli-target-triple-env.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"cli.rs": "patch"
3+
---
4+
5+
Expose `TAURI_TARGET_TRIPLE` to `beforeDevCommand`, `beforeBuildCommand` and `beforeBundleCommand`

.changes/fix-cli-envs.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"cli.rs": "patch"
3+
---
4+
5+
Set `TAURI_PLATFORM_TYPE`, `TAURI_FAMILY`, `TAURI_ARCH` and `TAURI_PLATFORM` env vars for hook commands to based on the app not the cli.

tooling/bundler/src/bundle/windows/msi/wix.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -283,8 +283,10 @@ pub fn get_and_extract_wix(path: &Path) -> crate::Result<()> {
283283

284284
fn clear_env_for_wix(cmd: &mut Command) {
285285
cmd.env_clear();
286+
let required_vars: Vec<std::ffi::OsString> =
287+
vec!["SYSTEMROOT".into(), "TMP".into(), "TEMP".into()];
286288
for (k, v) in std::env::vars_os() {
287-
if ["SYSTEMROOT", "TMP", "TEMP"].contains(k) || k.to_string_lossy().starts_with("TAURI") {
289+
if required_vars.contains(&k) || k.to_string_lossy().starts_with("TAURI") {
288290
cmd.env(k, v);
289291
}
290292
}

tooling/cli/src/build.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ pub fn command(mut options: Options) -> Result<()> {
154154
list.extend(config_.build.features.clone().unwrap_or_default());
155155
}
156156

157-
let mut interface = AppInterface::new(config_)?;
157+
let mut interface = AppInterface::new(config_, options.target.clone())?;
158158
let app_settings = interface.app_settings();
159159
let interface_options = options.clone().into();
160160

tooling/cli/src/dev.rs

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,11 @@ fn command_internal(mut options: Options) -> Result<()> {
8989

9090
let config = get_config(options.config.as_deref())?;
9191

92+
let mut interface = AppInterface::new(
93+
config.lock().unwrap().as_ref().unwrap(),
94+
options.target.clone(),
95+
)?;
96+
9297
if let Some(before_dev) = config
9398
.lock()
9499
.unwrap()
@@ -108,6 +113,9 @@ fn command_internal(mut options: Options) -> Result<()> {
108113
let cwd = script_cwd.unwrap_or_else(|| app_dir().clone());
109114
if let Some(before_dev) = script {
110115
info!(action = "Running"; "BeforeDevCommand (`{}`)", before_dev);
116+
let mut env = command_env(true);
117+
env.extend(interface.env());
118+
111119
#[cfg(windows)]
112120
let mut command = {
113121
let mut command = Command::new("cmd");
@@ -116,7 +124,7 @@ fn command_internal(mut options: Options) -> Result<()> {
116124
.arg("/C")
117125
.arg(&before_dev)
118126
.current_dir(cwd)
119-
.envs(command_env(true));
127+
.envs(env);
120128
command
121129
};
122130
#[cfg(not(windows))]
@@ -126,7 +134,7 @@ fn command_internal(mut options: Options) -> Result<()> {
126134
.arg("-c")
127135
.arg(&before_dev)
128136
.current_dir(cwd)
129-
.envs(command_env(true));
137+
.envs(env);
130138
command
131139
};
132140

@@ -234,7 +242,7 @@ fn command_internal(mut options: Options) -> Result<()> {
234242
}
235243
}
236244

237-
let config = reload_config(options.config.as_deref())?;
245+
reload_config(options.config.as_deref())?;
238246

239247
if std::env::var_os("TAURI_SKIP_DEVSERVER_CHECK") != Some("true".into()) {
240248
if let AppUrl::Url(WindowUrl::External(dev_server_url)) = dev_path {
@@ -287,8 +295,6 @@ fn command_internal(mut options: Options) -> Result<()> {
287295
}
288296
}
289297

290-
let mut interface = AppInterface::new(config.lock().unwrap().as_ref().unwrap())?;
291-
292298
let exit_on_panic = options.exit_on_panic;
293299
let no_watch = options.no_watch;
294300
interface.dev(options.into(), move |status, reason| {

tooling/cli/src/helpers/mod.rs

Lines changed: 3 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -14,26 +14,16 @@ use std::{
1414
path::{Path, PathBuf},
1515
};
1616

17-
pub fn command_env(debug: bool) -> HashMap<String, String> {
17+
pub fn command_env(debug: bool) -> HashMap<&'static str, String> {
1818
let mut map = HashMap::new();
1919

20-
map.insert("TAURI_PLATFORM".into(), std::env::consts::OS.into());
21-
map.insert("TAURI_ARCH".into(), std::env::consts::ARCH.into());
22-
map.insert("TAURI_FAMILY".into(), std::env::consts::FAMILY.into());
2320
map.insert(
24-
"TAURI_PLATFORM_VERSION".into(),
21+
"TAURI_PLATFORM_VERSION",
2522
os_info::get().version().to_string(),
2623
);
2724

28-
#[cfg(target_os = "linux")]
29-
map.insert("TAURI_PLATFORM_TYPE".into(), "Linux".into());
30-
#[cfg(target_os = "windows")]
31-
map.insert("TAURI_PLATFORM_TYPE".into(), "Windows_NT".into());
32-
#[cfg(target_os = "macos")]
33-
map.insert("TAURI_PLATFORM_TYPE".into(), "Darwin".into());
34-
3525
if debug {
36-
map.insert("TAURI_DEBUG".into(), "true".to_string());
26+
map.insert("TAURI_DEBUG", "true".into());
3727
}
3828

3929
map

tooling/cli/src/interface/mod.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
pub mod rust;
66

77
use std::{
8+
collections::HashMap,
89
path::{Path, PathBuf},
910
process::ExitStatus,
1011
};
@@ -75,8 +76,9 @@ pub enum ExitReason {
7576
pub trait Interface: Sized {
7677
type AppSettings: AppSettings;
7778

78-
fn new(config: &Config) -> crate::Result<Self>;
79+
fn new(config: &Config, target: Option<String>) -> crate::Result<Self>;
7980
fn app_settings(&self) -> &Self::AppSettings;
81+
fn env(&self) -> HashMap<&str, String>;
8082
fn build(&mut self, options: Options) -> crate::Result<()>;
8183
fn dev<F: Fn(ExitStatus, ExitReason) + Send + Sync + 'static>(
8284
&mut self,

tooling/cli/src/interface/rust.rs

Lines changed: 71 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
// SPDX-License-Identifier: MIT
44

55
use std::{
6+
collections::HashMap,
67
ffi::OsStr,
78
fs::{File, FileType},
89
io::{Read, Write},
@@ -123,7 +124,7 @@ pub struct Rust {
123124
impl Interface for Rust {
124125
type AppSettings = RustAppSettings;
125126

126-
fn new(config: &Config) -> crate::Result<Self> {
127+
fn new(config: &Config, target: Option<String>) -> crate::Result<Self> {
127128
let manifest = {
128129
let (tx, rx) = sync_channel(1);
129130
let mut watcher = new_debouncer(Duration::from_secs(1), None, move |r| {
@@ -154,7 +155,7 @@ impl Interface for Rust {
154155
}
155156

156157
Ok(Self {
157-
app_settings: RustAppSettings::new(config, manifest)?,
158+
app_settings: RustAppSettings::new(config, manifest, target)?,
158159
config_features: config.build.features.clone().unwrap_or_default(),
159160
product_name: config.package.product_name.clone(),
160161
available_targets: None,
@@ -206,6 +207,52 @@ impl Interface for Rust {
206207
self.run_dev_watcher(child, options, on_exit)
207208
}
208209
}
210+
211+
fn env(&self) -> HashMap<&str, String> {
212+
let mut env = HashMap::new();
213+
env.insert(
214+
"TAURI_TARGET_TRIPLE",
215+
self.app_settings.target_triple.clone(),
216+
);
217+
218+
let mut s = self.app_settings.target_triple.split('-');
219+
let (arch, _, host) = (s.next().unwrap(), s.next().unwrap(), s.next().unwrap());
220+
env.insert(
221+
"TAURI_ARCH",
222+
match arch {
223+
// keeps compatibility with old `std::env::consts::ARCH` implementation
224+
"i686" | "i586" => "x86".into(),
225+
a => a.into(),
226+
},
227+
);
228+
env.insert(
229+
"TAURI_PLATFORM",
230+
match host {
231+
// keeps compatibility with old `std::env::consts::OS` implementation
232+
"darwin" => "macos".into(),
233+
"ios-sim" => "ios".into(),
234+
"androideabi" => "android".into(),
235+
h => h.into(),
236+
},
237+
);
238+
239+
env.insert(
240+
"TAURI_FAMILY",
241+
match host {
242+
"windows" => "windows".into(),
243+
_ => "unix".into(),
244+
},
245+
);
246+
247+
match host {
248+
"linux" => env.insert("TAURI_PLATFORM_TYPE", "Linux".into()),
249+
"windows" => env.insert("TAURI_PLATFORM_TYPE", "Windows_NT".into()),
250+
"darwin" => env.insert("TAURI_PLATFORM_TYPE", "Darwin".into()),
251+
_ => None,
252+
};
253+
254+
env
255+
}
209256
}
210257

211258
fn lookup<F: FnMut(FileType, PathBuf)>(dir: &Path, mut f: F) {
@@ -437,6 +484,7 @@ pub struct RustAppSettings {
437484
cargo_package_settings: CargoPackageSettings,
438485
package_settings: PackageSettings,
439486
cargo_config: CargoConfig,
487+
target_triple: String,
440488
}
441489

442490
impl AppSettings for RustAppSettings {
@@ -468,13 +516,8 @@ impl AppSettings for RustAppSettings {
468516
let out_dir = self
469517
.out_dir(options.target.clone(), options.debug)
470518
.with_context(|| "failed to get project out directory")?;
471-
let target: String = if let Some(target) = options.target.clone() {
472-
target
473-
} else {
474-
tauri_utils::platform::target_triple()?
475-
};
476519

477-
let binary_extension: String = if target.contains("windows") {
520+
let binary_extension: String = if self.target_triple.contains("windows") {
478521
"exe"
479522
} else {
480523
""
@@ -590,7 +633,7 @@ impl AppSettings for RustAppSettings {
590633
}
591634

592635
impl RustAppSettings {
593-
pub fn new(config: &Config, manifest: Manifest) -> crate::Result<Self> {
636+
pub fn new(config: &Config, manifest: Manifest, target: Option<String>) -> crate::Result<Self> {
594637
let cargo_settings =
595638
CargoSettings::load(&tauri_dir()).with_context(|| "failed to load cargo settings")?;
596639
let cargo_package_settings = match &cargo_settings.package {
@@ -626,12 +669,31 @@ impl RustAppSettings {
626669

627670
let cargo_config = CargoConfig::load(&tauri_dir())?;
628671

672+
let target_triple = target.unwrap_or_else(|| {
673+
cargo_config
674+
.build()
675+
.target()
676+
.map(|t| t.to_string())
677+
.unwrap_or_else(|| {
678+
let output = Command::new("rustc").args(&["-vV"]).output().unwrap();
679+
let stdout = String::from_utf8_lossy(&output.stdout);
680+
stdout
681+
.split('\n')
682+
.find(|l| l.starts_with("host:"))
683+
.unwrap()
684+
.replace("host:", "")
685+
.trim()
686+
.to_string()
687+
})
688+
});
689+
629690
Ok(Self {
630691
manifest,
631692
cargo_settings,
632693
cargo_package_settings,
633694
package_settings,
634695
cargo_config,
696+
target_triple,
635697
})
636698
}
637699

tooling/cli/src/interface/rust/cargo_config.rs

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -50,20 +50,34 @@ impl Config {
5050
pub fn load(path: &Path) -> Result<Self> {
5151
let mut config = Self::default();
5252

53+
let get_config = |path: PathBuf| -> Result<ConfigSchema> {
54+
let contents = fs::read_to_string(&path)
55+
.with_context(|| format!("failed to read configuration file `{}`", path.display()))?;
56+
toml::from_str(&contents)
57+
.with_context(|| format!("could not parse TOML configuration in `{}`", path.display()))
58+
};
59+
5360
for current in PathAncestors::new(path) {
5461
if let Some(path) = get_file_path(&current.join(".cargo"), "config", true)? {
55-
let contents = fs::read_to_string(&path)
56-
.with_context(|| format!("failed to read configuration file `{}`", path.display()))?;
57-
let toml: ConfigSchema = toml::from_str(&contents)
58-
.with_context(|| format!("could not parse TOML configuration in `{}`", path.display()))?;
59-
62+
let toml = get_config(path)?;
6063
if let Some(target) = toml.build.and_then(|b| b.target) {
6164
config.build.target = Some(target);
6265
break;
6366
}
6467
}
6568
}
6669

70+
if config.build.target.is_none() {
71+
if let Ok(cargo_home) = std::env::var("CARGO_HOME") {
72+
if let Some(path) = get_file_path(&PathBuf::from(cargo_home), "config", true)? {
73+
let toml = get_config(path)?;
74+
if let Some(target) = toml.build.and_then(|b| b.target) {
75+
config.build.target = Some(target);
76+
}
77+
}
78+
}
79+
}
80+
6781
Ok(config)
6882
}
6983

0 commit comments

Comments
 (0)