dev.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. // Copyright 2019-2022 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. }
  61. pub fn command(options: Options) -> Result<()> {
  62. let r = command_internal(options);
  63. if r.is_err() {
  64. kill_before_dev_process();
  65. #[cfg(not(debug_assertions))]
  66. let _ = check_for_updates();
  67. }
  68. r
  69. }
  70. fn command_internal(mut options: Options) -> Result<()> {
  71. let tauri_path = tauri_dir();
  72. options.config = if let Some(config) = &options.config {
  73. Some(if config.starts_with('{') {
  74. config.to_string()
  75. } else {
  76. std::fs::read_to_string(config).with_context(|| "failed to read custom configuration")?
  77. })
  78. } else {
  79. None
  80. };
  81. set_current_dir(tauri_path).with_context(|| "failed to change current working directory")?;
  82. let config = get_config(options.config.as_deref())?;
  83. let mut interface = AppInterface::new(
  84. config.lock().unwrap().as_ref().unwrap(),
  85. options.target.clone(),
  86. )?;
  87. if let Some(before_dev) = config
  88. .lock()
  89. .unwrap()
  90. .as_ref()
  91. .unwrap()
  92. .build
  93. .before_dev_command
  94. .clone()
  95. {
  96. let (script, script_cwd, wait) = match before_dev {
  97. BeforeDevCommand::Script(s) if s.is_empty() => (None, None, false),
  98. BeforeDevCommand::Script(s) => (Some(s), None, false),
  99. BeforeDevCommand::ScriptWithOptions { script, cwd, wait } => {
  100. (Some(script), cwd.map(Into::into), wait)
  101. }
  102. };
  103. let cwd = script_cwd.unwrap_or_else(|| app_dir().clone());
  104. if let Some(before_dev) = script {
  105. info!(action = "Running"; "BeforeDevCommand (`{}`)", before_dev);
  106. let mut env = command_env(true);
  107. env.extend(interface.env());
  108. #[cfg(windows)]
  109. let mut command = {
  110. let mut command = Command::new("cmd");
  111. command
  112. .arg("/S")
  113. .arg("/C")
  114. .arg(&before_dev)
  115. .current_dir(cwd)
  116. .envs(env);
  117. command
  118. };
  119. #[cfg(not(windows))]
  120. let mut command = {
  121. let mut command = Command::new("sh");
  122. command
  123. .arg("-c")
  124. .arg(&before_dev)
  125. .current_dir(cwd)
  126. .envs(env);
  127. command
  128. };
  129. if wait {
  130. let status = command.piped().with_context(|| {
  131. format!(
  132. "failed to run `{}` with `{}`",
  133. before_dev,
  134. if cfg!(windows) { "cmd /S /C" } else { "sh -c" }
  135. )
  136. })?;
  137. if !status.success() {
  138. bail!(
  139. "beforeDevCommand `{}` failed with exit code {}",
  140. before_dev,
  141. status.code().unwrap_or_default()
  142. );
  143. }
  144. } else {
  145. command.stdin(Stdio::piped());
  146. command.stdout(os_pipe::dup_stdout()?);
  147. command.stderr(os_pipe::dup_stderr()?);
  148. let child = SharedChild::spawn(&mut command)
  149. .unwrap_or_else(|_| panic!("failed to run `{before_dev}`"));
  150. let child = Arc::new(child);
  151. let child_ = child.clone();
  152. std::thread::spawn(move || {
  153. let status = child_
  154. .wait()
  155. .expect("failed to wait on \"beforeDevCommand\"");
  156. if !(status.success() || KILL_BEFORE_DEV_FLAG.get().unwrap().load(Ordering::Relaxed)) {
  157. error!("The \"beforeDevCommand\" terminated with a non-zero status code.");
  158. exit(status.code().unwrap_or(1));
  159. }
  160. });
  161. BEFORE_DEV.set(Mutex::new(child)).unwrap();
  162. KILL_BEFORE_DEV_FLAG.set(AtomicBool::default()).unwrap();
  163. let _ = ctrlc::set_handler(move || {
  164. kill_before_dev_process();
  165. #[cfg(not(debug_assertions))]
  166. let _ = check_for_updates();
  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, SERVER_URL};
  205. if path.exists() {
  206. let path = path.canonicalize()?;
  207. start_dev_server(path);
  208. dev_path = AppUrl::Url(WindowUrl::External(SERVER_URL.parse().unwrap()));
  209. // TODO: in v2, use an env var to pass the url to the app context
  210. // or better separate the config passed from the cli internally and
  211. // config passed by the user in `--config` into to separate env vars
  212. // and the context merges, the user first, then the internal cli config
  213. if let Some(c) = options.config {
  214. let mut c: tauri_utils::config::Config = serde_json::from_str(&c)?;
  215. c.build.dev_path = dev_path.clone();
  216. options.config = Some(serde_json::to_string(&c).unwrap());
  217. } else {
  218. options.config = Some(format!(r#"{{ "build": {{ "devPath": "{SERVER_URL}" }} }}"#))
  219. }
  220. }
  221. }
  222. reload_config(options.config.as_deref())?;
  223. }
  224. if std::env::var_os("TAURI_SKIP_DEVSERVER_CHECK") != Some("true".into()) {
  225. if let AppUrl::Url(WindowUrl::External(dev_server_url)) = dev_path {
  226. let host = dev_server_url
  227. .host()
  228. .unwrap_or_else(|| panic!("No host name in the URL"));
  229. let port = dev_server_url
  230. .port_or_known_default()
  231. .unwrap_or_else(|| panic!("No port number in the URL"));
  232. let addrs;
  233. let addr;
  234. let addrs = match host {
  235. url::Host::Domain(domain) => {
  236. use std::net::ToSocketAddrs;
  237. addrs = (domain, port).to_socket_addrs()?;
  238. addrs.as_slice()
  239. }
  240. url::Host::Ipv4(ip) => {
  241. addr = (ip, port).into();
  242. std::slice::from_ref(&addr)
  243. }
  244. url::Host::Ipv6(ip) => {
  245. addr = (ip, port).into();
  246. std::slice::from_ref(&addr)
  247. }
  248. };
  249. let mut i = 0;
  250. let sleep_interval = std::time::Duration::from_secs(2);
  251. let max_attempts = 90;
  252. loop {
  253. if std::net::TcpStream::connect(addrs).is_ok() {
  254. break;
  255. }
  256. if i % 3 == 1 {
  257. warn!(
  258. "Waiting for your frontend dev server to start on {}...",
  259. dev_server_url
  260. );
  261. }
  262. i += 1;
  263. if i == max_attempts {
  264. error!(
  265. "Could not connect to `{}` after {}s. Please make sure that is the URL to your dev server.",
  266. dev_server_url, i * sleep_interval.as_secs()
  267. );
  268. exit(1);
  269. }
  270. std::thread::sleep(sleep_interval);
  271. }
  272. }
  273. }
  274. let exit_on_panic = options.exit_on_panic;
  275. let no_watch = options.no_watch;
  276. interface.dev(options.into(), move |status, reason| {
  277. on_dev_exit(status, reason, exit_on_panic, no_watch)
  278. })
  279. }
  280. fn on_dev_exit(status: ExitStatus, reason: ExitReason, exit_on_panic: bool, no_watch: bool) {
  281. if no_watch
  282. || (!matches!(reason, ExitReason::TriggeredKill)
  283. && (exit_on_panic || matches!(reason, ExitReason::NormalExit)))
  284. {
  285. kill_before_dev_process();
  286. #[cfg(not(debug_assertions))]
  287. let _ = check_for_updates();
  288. exit(status.code().unwrap_or(0));
  289. }
  290. }
  291. #[cfg(not(debug_assertions))]
  292. fn check_for_updates() -> Result<()> {
  293. if std::env::var_os("TAURI_SKIP_UPDATE_CHECK") != Some("true".into()) {
  294. let current_version = crate::info::cli_current_version()?;
  295. let current = semver::Version::parse(&current_version)?;
  296. let upstream_version = crate::info::cli_upstream_version()?;
  297. let upstream = semver::Version::parse(&upstream_version)?;
  298. if current < upstream {
  299. println!(
  300. "🚀 A new version of Tauri CLI is available! [{}]",
  301. upstream.to_string()
  302. );
  303. };
  304. }
  305. Ok(())
  306. }
  307. fn kill_before_dev_process() {
  308. if let Some(child) = BEFORE_DEV.get() {
  309. let child = child.lock().unwrap();
  310. KILL_BEFORE_DEV_FLAG
  311. .get()
  312. .unwrap()
  313. .store(true, Ordering::Relaxed);
  314. #[cfg(windows)]
  315. {
  316. let powershell_path = std::env::var("SYSTEMROOT").map_or_else(
  317. |_| "powershell.exe".to_string(),
  318. |p| format!("{p}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"),
  319. );
  320. let _ = Command::new(powershell_path)
  321. .arg("-NoProfile")
  322. .arg("-Command")
  323. .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()))
  324. .status();
  325. }
  326. #[cfg(unix)]
  327. {
  328. use std::io::Write;
  329. let mut kill_children_script_path = std::env::temp_dir();
  330. kill_children_script_path.push("kill-children.sh");
  331. if !kill_children_script_path.exists() {
  332. if let Ok(mut file) = std::fs::File::create(&kill_children_script_path) {
  333. use std::os::unix::fs::PermissionsExt;
  334. let _ = file.write_all(KILL_CHILDREN_SCRIPT);
  335. let mut permissions = file.metadata().unwrap().permissions();
  336. permissions.set_mode(0o770);
  337. let _ = file.set_permissions(permissions);
  338. }
  339. }
  340. let _ = Command::new(&kill_children_script_path)
  341. .arg(child.id().to_string())
  342. .output();
  343. }
  344. let _ = child.kill();
  345. }
  346. }