/
mod.rs
334 lines (295 loc) · 8.47 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{
helpers::{
app_paths::tauri_dir,
config::{
get as get_config, reload as reload_config, AppUrl, Config as TauriConfig, WindowUrl,
},
},
interface::{AppInterface, AppSettings, DevProcess, Interface, Options as InterfaceOptions},
};
use anyhow::{bail, Result};
use jsonrpsee::core::client::{Client, ClientBuilder, ClientT};
use jsonrpsee::server::{RpcModule, ServerBuilder, ServerHandle};
use jsonrpsee_client_transport::ws::WsTransportClientBuilder;
use jsonrpsee_core::rpc_params;
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
env::{set_var, temp_dir},
ffi::OsString,
fmt::Write,
fs::{create_dir_all, read_to_string, write},
net::SocketAddr,
path::PathBuf,
process::{exit, ExitStatus},
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
};
use tauri_mobile::{
config::app::{App, Raw as RawAppConfig},
env::Error as EnvError,
opts::{NoiseLevel, Profile},
ChildHandle,
};
use tokio::runtime::Runtime;
#[cfg(not(windows))]
use tauri_mobile::env::Env;
#[cfg(windows)]
use tauri_mobile::os::Env;
pub mod android;
mod init;
#[cfg(target_os = "macos")]
pub mod ios;
const MIN_DEVICE_MATCH_SCORE: isize = 0;
#[derive(Clone)]
pub struct DevChild {
child: Arc<ChildHandle>,
manually_killed_process: Arc<AtomicBool>,
}
impl DevChild {
fn new(handle: ChildHandle) -> Self {
Self {
child: Arc::new(handle),
manually_killed_process: Default::default(),
}
}
}
impl DevProcess for DevChild {
fn kill(&self) -> std::io::Result<()> {
self.child.kill()?;
self.manually_killed_process.store(true, Ordering::Relaxed);
Ok(())
}
fn try_wait(&self) -> std::io::Result<Option<ExitStatus>> {
self.child.try_wait().map(|res| res.map(|o| o.status))
}
fn wait(&self) -> std::io::Result<ExitStatus> {
self.child.wait().map(|o| o.status)
}
fn manually_killed_process(&self) -> bool {
self.manually_killed_process.load(Ordering::Relaxed)
}
fn is_building_app(&self) -> bool {
false
}
}
#[derive(PartialEq, Eq, Copy, Clone)]
pub enum Target {
Android,
#[cfg(target_os = "macos")]
Ios,
}
impl Target {
fn ide_name(&self) -> &'static str {
match self {
Self::Android => "Android Studio",
#[cfg(target_os = "macos")]
Self::Ios => "Xcode",
}
}
fn command_name(&self) -> &'static str {
match self {
Self::Android => "android",
#[cfg(target_os = "macos")]
Self::Ios => "ios",
}
}
fn ide_build_script_name(&self) -> &'static str {
match self {
Self::Android => "android-studio-script",
#[cfg(target_os = "macos")]
Self::Ios => "xcode-script",
}
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CliOptions {
pub features: Option<Vec<String>>,
pub args: Vec<String>,
pub noise_level: NoiseLevel,
pub vars: HashMap<String, OsString>,
}
fn setup_dev_config(
config_extension: &mut Option<String>,
force_ip_prompt: bool,
) -> crate::Result<()> {
let config = get_config(config_extension.as_deref())?;
let mut dev_path = config
.lock()
.unwrap()
.as_ref()
.unwrap()
.build
.dev_path
.clone();
if let AppUrl::Url(WindowUrl::External(url)) = &mut dev_path {
let localhost = match url.host() {
Some(url::Host::Domain(d)) => d == "localhost",
Some(url::Host::Ipv4(i)) => {
i == std::net::Ipv4Addr::LOCALHOST || i == std::net::Ipv4Addr::UNSPECIFIED
}
_ => false,
};
if localhost {
let ip = crate::dev::local_ip_address(force_ip_prompt);
url.set_host(Some(&ip.to_string())).unwrap();
if let Some(c) = config_extension {
let mut c: tauri_utils::config::Config = serde_json::from_str(c)?;
c.build.dev_path = dev_path.clone();
config_extension.replace(serde_json::to_string(&c).unwrap());
} else {
config_extension.replace(format!(r#"{{ "build": {{ "devPath": "{url}" }} }}"#));
}
reload_config(config_extension.as_deref())?;
}
}
Ok(())
}
fn env_vars() -> HashMap<String, OsString> {
let mut vars = HashMap::new();
vars.insert("RUST_LOG_STYLE".into(), "always".into());
for (k, v) in std::env::vars_os() {
let k = k.to_string_lossy();
if (k.starts_with("TAURI") && k != "TAURI_PRIVATE_KEY" && k != "TAURI_KEY_PASSWORD")
|| k.starts_with("WRY")
|| k.starts_with("CARGO_")
|| k == "TMPDIR"
|| k == "PATH"
{
vars.insert(k.into_owned(), v);
}
}
vars
}
fn env() -> Result<Env, EnvError> {
let env = Env::new()?.explicit_env_vars(env_vars());
Ok(env)
}
/// Writes CLI options to be used later on the Xcode and Android Studio build commands
pub fn write_options(
identifier: &str,
mut options: CliOptions,
) -> crate::Result<(Runtime, ServerHandle)> {
options.vars.extend(env_vars());
let runtime = Runtime::new().unwrap();
let r: anyhow::Result<(ServerHandle, SocketAddr)> = runtime.block_on(async move {
let server = ServerBuilder::default().build("127.0.0.1:0").await?;
let addr = server.local_addr()?;
let mut module = RpcModule::new(());
module.register_method("options", move |_, _| Ok(options.clone()))?;
let handle = server.start(module)?;
Ok((handle, addr))
});
let (handle, addr) = r?;
write(
temp_dir().join(format!("{identifier}-server-addr")),
addr.to_string(),
)?;
Ok((runtime, handle))
}
fn read_options(identifier: &str) -> CliOptions {
let runtime = tokio::runtime::Runtime::new().unwrap();
let options = runtime
.block_on(async move {
let (tx, rx) = WsTransportClientBuilder::default()
.build(
format!(
"ws://{}",
read_to_string(temp_dir().join(format!("{identifier}-server-addr")))
.expect("missing addr file")
)
.parse()
.unwrap(),
)
.await?;
let client: Client = ClientBuilder::default().build_with_tokio(tx, rx);
let options: CliOptions = client.request("options", rpc_params![]).await?;
Ok::<CliOptions, anyhow::Error>(options)
})
.expect("failed to read CLI options");
for (k, v) in &options.vars {
set_var(k, v);
}
options
}
fn get_app(config: &TauriConfig) -> App {
let mut s = config.tauri.bundle.identifier.rsplit('.');
let app_name = s.next().unwrap_or("app").to_string();
let mut domain = String::new();
for w in s {
domain.push_str(w);
domain.push('.');
}
if domain.is_empty() {
domain = config.tauri.bundle.identifier.clone();
if domain.is_empty() {
log::error!(
"Bundle identifier set in `tauri.conf.json > tauri > bundle > identifier` cannot be empty"
);
exit(1);
}
} else {
domain.pop();
}
let interface = AppInterface::new(
config,
// the target triple is not relevant
Some("".into()),
)
.expect("failed to load interface");
let app_name = interface.app_settings().app_name().unwrap_or(app_name);
let lib_name = interface
.app_settings()
.lib_name()
.unwrap_or(app_name.clone());
let raw = RawAppConfig {
name: app_name,
lib_name: Some(lib_name),
stylized_name: config.package.product_name.clone(),
domain,
asset_dir: None,
template_pack: None,
};
App::from_raw(tauri_dir(), raw)
.unwrap()
.with_target_dir_resolver(move |target, profile| {
let bin_path = interface
.app_settings()
.app_binary_path(&InterfaceOptions {
debug: matches!(profile, Profile::Debug),
target: Some(target.into()),
..Default::default()
})
.expect("failed to resolve target directory");
bin_path.parent().unwrap().to_path_buf()
})
}
fn ensure_init(project_dir: PathBuf, target: Target) -> Result<()> {
if !project_dir.exists() {
bail!(
"{} project directory {} doesn't exist. Please run `tauri {} init` and try again.",
target.ide_name(),
project_dir.display(),
target.command_name(),
)
} else {
if target == Target::Android {
create_dir_all(project_dir.join(".tauri"))?;
}
Ok(())
}
}
fn log_finished(outputs: Vec<PathBuf>, kind: &str) {
if !outputs.is_empty() {
let mut printable_paths = String::new();
for path in &outputs {
writeln!(printable_paths, " {}", path.display()).unwrap();
}
log::info!(action = "Finished"; "{} {}{} at:\n{}", outputs.len(), kind, if outputs.len() == 1 { "" } else { "s" }, printable_paths);
}
}