dev.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. use crate::{
  5. helpers::{
  6. app_paths::{app_dir, tauri_dir},
  7. command_env,
  8. config::{get as get_config, reload as reload_config, AppUrl, BeforeDevCommand, WindowUrl},
  9. },
  10. interface::{AppInterface, ExitReason, Interface},
  11. CommandExt, Result,
  12. };
  13. use clap::{ArgAction, Parser};
  14. use anyhow::{bail, Context};
  15. use log::{error, info, warn};
  16. use once_cell::sync::OnceCell;
  17. use shared_child::SharedChild;
  18. use std::{
  19. env::set_current_dir,
  20. process::{exit, Command, ExitStatus, Stdio},
  21. sync::{
  22. atomic::{AtomicBool, Ordering},
  23. Arc, Mutex,
  24. },
  25. };
  26. static BEFORE_DEV: OnceCell<Mutex<Arc<SharedChild>>> = OnceCell::new();
  27. static KILL_BEFORE_DEV_FLAG: OnceCell<AtomicBool> = OnceCell::new();
  28. #[cfg(unix)]
  29. const KILL_CHILDREN_SCRIPT: &[u8] = include_bytes!("../scripts/kill-children.sh");
  30. pub const TAURI_DEV_WATCHER_GITIGNORE: &[u8] = include_bytes!("../tauri-dev-watcher.gitignore");
  31. #[derive(Debug, Clone, Parser)]
  32. #[clap(about = "Tauri dev", trailing_var_arg(true))]
  33. pub struct Options {
  34. /// Binary to use to run the application
  35. #[clap(short, long)]
  36. pub runner: Option<String>,
  37. /// Target triple to build against
  38. #[clap(short, long)]
  39. pub target: Option<String>,
  40. /// List of cargo features to activate
  41. #[clap(short, long, action = ArgAction::Append, num_args(0..))]
  42. pub features: Option<Vec<String>>,
  43. /// Exit on panic
  44. #[clap(short, long)]
  45. exit_on_panic: bool,
  46. /// JSON string or path to JSON file to merge with tauri.conf.json
  47. #[clap(short, long)]
  48. pub config: Option<String>,
  49. /// Run the code in release mode
  50. #[clap(long = "release")]
  51. pub release_mode: bool,
  52. /// Command line arguments passed to the runner. Arguments after `--` are passed to the application.
  53. pub args: Vec<String>,
  54. /// Disable the file watcher
  55. #[clap(long)]
  56. pub no_watch: bool,
  57. /// Disable the dev server for static files.
  58. #[clap(long)]
  59. pub no_dev_server: bool,
  60. /// Specify port for the dev server for static files. Defaults to 1430
  61. /// Can also be set using `TAURI_DEV_SERVER_PORT` env var.
  62. #[clap(long)]
  63. pub port: Option<u16>,
  64. }
  65. pub fn command(options: Options) -> Result<()> {
  66. let r = command_internal(options);
  67. if r.is_err() {
  68. kill_before_dev_process();
  69. }
  70. r
  71. }
  72. fn command_internal(mut options: Options) -> Result<()> {
  73. let tauri_path = tauri_dir();
  74. options.config = if let Some(config) = &options.config {
  75. Some(if config.starts_with('{') {
  76. config.to_string()
  77. } else {
  78. std::fs::read_to_string(config).with_context(|| "failed to read custom configuration")?
  79. })
  80. } else {
  81. None
  82. };
  83. set_current_dir(tauri_path).with_context(|| "failed to change current working directory")?;
  84. let config = get_config(options.config.as_deref())?;
  85. let mut interface = AppInterface::new(
  86. config.lock().unwrap().as_ref().unwrap(),
  87. options.target.clone(),
  88. )?;
  89. if let Some(before_dev) = config
  90. .lock()
  91. .unwrap()
  92. .as_ref()
  93. .unwrap()
  94. .build
  95. .before_dev_command
  96. .clone()
  97. {
  98. let (script, script_cwd, wait) = match before_dev {
  99. BeforeDevCommand::Script(s) if s.is_empty() => (None, None, false),
  100. BeforeDevCommand::Script(s) => (Some(s), None, false),
  101. BeforeDevCommand::ScriptWithOptions { script, cwd, wait } => {
  102. (Some(script), cwd.map(Into::into), wait)
  103. }
  104. };
  105. let cwd = script_cwd.unwrap_or_else(|| app_dir().clone());
  106. if let Some(before_dev) = script {
  107. info!(action = "Running"; "BeforeDevCommand (`{}`)", before_dev);
  108. let mut env = command_env(true);
  109. env.extend(interface.env());
  110. #[cfg(windows)]
  111. let mut command = {
  112. let mut command = Command::new("cmd");
  113. command
  114. .arg("/S")
  115. .arg("/C")
  116. .arg(&before_dev)
  117. .current_dir(cwd)
  118. .envs(env);
  119. command
  120. };
  121. #[cfg(not(windows))]
  122. let mut command = {
  123. let mut command = Command::new("sh");
  124. command
  125. .arg("-c")
  126. .arg(&before_dev)
  127. .current_dir(cwd)
  128. .envs(env);
  129. command
  130. };
  131. if wait {
  132. let status = command.piped().with_context(|| {
  133. format!(
  134. "failed to run `{}` with `{}`",
  135. before_dev,
  136. if cfg!(windows) { "cmd /S /C" } else { "sh -c" }
  137. )
  138. })?;
  139. if !status.success() {
  140. bail!(
  141. "beforeDevCommand `{}` failed with exit code {}",
  142. before_dev,
  143. status.code().unwrap_or_default()
  144. );
  145. }
  146. } else {
  147. command.stdin(Stdio::piped());
  148. command.stdout(os_pipe::dup_stdout()?);
  149. command.stderr(os_pipe::dup_stderr()?);
  150. let child = SharedChild::spawn(&mut command)
  151. .unwrap_or_else(|_| panic!("failed to run `{before_dev}`"));
  152. let child = Arc::new(child);
  153. let child_ = child.clone();
  154. std::thread::spawn(move || {
  155. let status = child_
  156. .wait()
  157. .expect("failed to wait on \"beforeDevCommand\"");
  158. if !(status.success() || KILL_BEFORE_DEV_FLAG.get().unwrap().load(Ordering::Relaxed)) {
  159. error!("The \"beforeDevCommand\" terminated with a non-zero status code.");
  160. exit(status.code().unwrap_or(1));
  161. }
  162. });
  163. BEFORE_DEV.set(Mutex::new(child)).unwrap();
  164. KILL_BEFORE_DEV_FLAG.set(AtomicBool::default()).unwrap();
  165. let _ = ctrlc::set_handler(move || {
  166. kill_before_dev_process();
  167. exit(130);
  168. });
  169. }
  170. }
  171. }
  172. if options.runner.is_none() {
  173. options.runner = config
  174. .lock()
  175. .unwrap()
  176. .as_ref()
  177. .unwrap()
  178. .build
  179. .runner
  180. .clone();
  181. }
  182. let mut cargo_features = config
  183. .lock()
  184. .unwrap()
  185. .as_ref()
  186. .unwrap()
  187. .build
  188. .features
  189. .clone()
  190. .unwrap_or_default();
  191. if let Some(features) = &options.features {
  192. cargo_features.extend(features.clone());
  193. }
  194. let mut dev_path = config
  195. .lock()
  196. .unwrap()
  197. .as_ref()
  198. .unwrap()
  199. .build
  200. .dev_path
  201. .clone();
  202. if !options.no_dev_server {
  203. if let AppUrl::Url(WindowUrl::App(path)) = &dev_path {
  204. use crate::helpers::web_dev_server::start_dev_server;
  205. if path.exists() {
  206. let path = path.canonicalize()?;
  207. let server_url = start_dev_server(path, options.port)?;
  208. let server_url = format!("http://{server_url}");
  209. dev_path = AppUrl::Url(WindowUrl::External(server_url.parse().unwrap()));
  210. // TODO: in v2, use an env var to pass the url to the app context
  211. // or better separate the config passed from the cli internally and
  212. // config passed by the user in `--config` into to separate env vars
  213. // and the context merges, the user first, then the internal cli config
  214. if let Some(c) = options.config {
  215. let mut c: tauri_utils::config::Config = serde_json::from_str(&c)?;
  216. c.build.dev_path = dev_path.clone();
  217. options.config = Some(serde_json::to_string(&c).unwrap());
  218. } else {
  219. options.config = Some(format!(r#"{{ "build": {{ "devPath": "{server_url}" }} }}"#))
  220. }
  221. }
  222. }
  223. reload_config(options.config.as_deref())?;
  224. }
  225. if std::env::var_os("TAURI_SKIP_DEVSERVER_CHECK") != Some("true".into()) {
  226. if let AppUrl::Url(WindowUrl::External(dev_server_url)) = dev_path {
  227. let host = dev_server_url
  228. .host()
  229. .unwrap_or_else(|| panic!("No host name in the URL"));
  230. let port = dev_server_url
  231. .port_or_known_default()
  232. .unwrap_or_else(|| panic!("No port number in the URL"));
  233. let addrs;
  234. let addr;
  235. let addrs = match host {
  236. url::Host::Domain(domain) => {
  237. use std::net::ToSocketAddrs;
  238. addrs = (domain, port).to_socket_addrs()?;
  239. addrs.as_slice()
  240. }
  241. url::Host::Ipv4(ip) => {
  242. addr = (ip, port).into();
  243. std::slice::from_ref(&addr)
  244. }
  245. url::Host::Ipv6(ip) => {
  246. addr = (ip, port).into();
  247. std::slice::from_ref(&addr)
  248. }
  249. };
  250. let mut i = 0;
  251. let sleep_interval = std::time::Duration::from_secs(2);
  252. let timeout_duration = std::time::Duration::from_secs(1);
  253. let max_attempts = 90;
  254. 'waiting: loop {
  255. for addr in addrs.iter() {
  256. if std::net::TcpStream::connect_timeout(addr, timeout_duration).is_ok() {
  257. break 'waiting;
  258. }
  259. }
  260. if i % 3 == 1 {
  261. warn!(
  262. "Waiting for your frontend dev server to start on {}...",
  263. dev_server_url
  264. );
  265. }
  266. i += 1;
  267. if i == max_attempts {
  268. error!(
  269. "Could not connect to `{}` after {}s. Please make sure that is the URL to your dev server.",
  270. dev_server_url, i * sleep_interval.as_secs()
  271. );
  272. exit(1);
  273. }
  274. std::thread::sleep(sleep_interval);
  275. }
  276. }
  277. }
  278. let exit_on_panic = options.exit_on_panic;
  279. let no_watch = options.no_watch;
  280. interface.dev(options.into(), move |status, reason| {
  281. on_dev_exit(status, reason, exit_on_panic, no_watch)
  282. })
  283. }
  284. fn on_dev_exit(status: ExitStatus, reason: ExitReason, exit_on_panic: bool, no_watch: bool) {
  285. if no_watch
  286. || (!matches!(reason, ExitReason::TriggeredKill)
  287. && (exit_on_panic || matches!(reason, ExitReason::NormalExit)))
  288. {
  289. kill_before_dev_process();
  290. exit(status.code().unwrap_or(0));
  291. }
  292. }
  293. fn kill_before_dev_process() {
  294. if let Some(child) = BEFORE_DEV.get() {
  295. let child = child.lock().unwrap();
  296. KILL_BEFORE_DEV_FLAG
  297. .get()
  298. .unwrap()
  299. .store(true, Ordering::Relaxed);
  300. #[cfg(windows)]
  301. {
  302. let powershell_path = std::env::var("SYSTEMROOT").map_or_else(
  303. |_| "powershell.exe".to_string(),
  304. |p| format!("{p}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"),
  305. );
  306. let _ = Command::new(powershell_path)
  307. .arg("-NoProfile")
  308. .arg("-Command")
  309. .arg(format!("function Kill-Tree {{ Param([int]$ppid); Get-CimInstance Win32_Process | Where-Object {{ $_.ParentProcessId -eq $ppid }} | ForEach-Object {{ Kill-Tree $_.ProcessId }}; Stop-Process -Id $ppid -ErrorAction SilentlyContinue }}; Kill-Tree {}", child.id()))
  310. .status();
  311. }
  312. #[cfg(unix)]
  313. {
  314. use std::io::Write;
  315. let mut kill_children_script_path = std::env::temp_dir();
  316. kill_children_script_path.push("kill-children.sh");
  317. if !kill_children_script_path.exists() {
  318. if let Ok(mut file) = std::fs::File::create(&kill_children_script_path) {
  319. use std::os::unix::fs::PermissionsExt;
  320. let _ = file.write_all(KILL_CHILDREN_SCRIPT);
  321. let mut permissions = file.metadata().unwrap().permissions();
  322. permissions.set_mode(0o770);
  323. let _ = file.set_permissions(permissions);
  324. }
  325. }
  326. let _ = Command::new(&kill_children_script_path)
  327. .arg(child.id().to_string())
  328. .output();
  329. }
  330. let _ = child.kill();
  331. }
  332. }