dev.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. // Copyright 2019-2021 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, ConfigHandle, WindowUrl},
  9. manifest::{rewrite_manifest, Manifest},
  10. Logger,
  11. },
  12. CommandExt, Result,
  13. };
  14. use clap::Parser;
  15. use anyhow::Context;
  16. use notify::{watcher, DebouncedEvent, RecursiveMode, Watcher};
  17. use once_cell::sync::OnceCell;
  18. use shared_child::SharedChild;
  19. use std::{
  20. env::set_current_dir,
  21. ffi::OsStr,
  22. fs::FileType,
  23. io::{BufReader, Write},
  24. path::{Path, PathBuf},
  25. process::{exit, Command, Stdio},
  26. sync::{
  27. atomic::{AtomicBool, Ordering},
  28. mpsc::channel,
  29. Arc, Mutex,
  30. },
  31. time::Duration,
  32. };
  33. static BEFORE_DEV: OnceCell<Mutex<Arc<SharedChild>>> = OnceCell::new();
  34. static KILL_BEFORE_DEV_FLAG: OnceCell<AtomicBool> = OnceCell::new();
  35. #[cfg(unix)]
  36. const KILL_CHILDREN_SCRIPT: &[u8] = include_bytes!("../scripts/kill-children.sh");
  37. const TAURI_DEV_WATCHER_GITIGNORE: &[u8] = include_bytes!("../tauri-dev-watcher.gitignore");
  38. #[derive(Debug, Parser)]
  39. #[clap(about = "Tauri dev", trailing_var_arg(true))]
  40. pub struct Options {
  41. /// Binary to use to run the application
  42. #[clap(short, long)]
  43. runner: Option<String>,
  44. /// Target triple to build against
  45. #[clap(short, long)]
  46. target: Option<String>,
  47. /// List of cargo features to activate
  48. #[clap(short, long)]
  49. features: Option<Vec<String>>,
  50. /// Exit on panic
  51. #[clap(short, long)]
  52. exit_on_panic: bool,
  53. /// JSON string or path to JSON file to merge with tauri.conf.json
  54. #[clap(short, long)]
  55. config: Option<String>,
  56. /// Run the code in release mode
  57. #[clap(long = "release")]
  58. release_mode: bool,
  59. /// Command line arguments passed to the runner
  60. args: Vec<String>,
  61. }
  62. pub fn command(options: Options) -> Result<()> {
  63. let r = command_internal(options);
  64. if r.is_err() {
  65. kill_before_dev_process();
  66. #[cfg(not(debug_assertions))]
  67. let _ = check_for_updates();
  68. }
  69. r
  70. }
  71. fn command_internal(options: Options) -> Result<()> {
  72. let logger = Logger::new("tauri:dev");
  73. let tauri_path = tauri_dir();
  74. set_current_dir(&tauri_path).with_context(|| "failed to change current working directory")?;
  75. let merge_config = if let Some(config) = &options.config {
  76. Some(if config.starts_with('{') {
  77. config.to_string()
  78. } else {
  79. std::fs::read_to_string(&config)?
  80. })
  81. } else {
  82. None
  83. };
  84. let config = get_config(merge_config.as_deref())?;
  85. if let Some(before_dev) = &config
  86. .lock()
  87. .unwrap()
  88. .as_ref()
  89. .unwrap()
  90. .build
  91. .before_dev_command
  92. {
  93. if !before_dev.is_empty() {
  94. logger.log(format!("Running `{}`", before_dev));
  95. #[cfg(target_os = "windows")]
  96. let mut command = {
  97. let mut command = Command::new("cmd");
  98. command
  99. .arg("/S")
  100. .arg("/C")
  101. .arg(before_dev)
  102. .current_dir(app_dir())
  103. .envs(command_env(true))
  104. .pipe()?; // development build always includes debug information
  105. command
  106. };
  107. #[cfg(not(target_os = "windows"))]
  108. let mut command = {
  109. let mut command = Command::new("sh");
  110. command
  111. .arg("-c")
  112. .arg(before_dev)
  113. .current_dir(app_dir())
  114. .envs(command_env(true))
  115. .pipe()?; // development build always includes debug information
  116. command
  117. };
  118. command.stdin(Stdio::piped());
  119. let child = SharedChild::spawn(&mut command)
  120. .unwrap_or_else(|_| panic!("failed to run `{}`", before_dev));
  121. let child = Arc::new(child);
  122. let child_ = child.clone();
  123. let logger_ = logger.clone();
  124. std::thread::spawn(move || {
  125. let status = child_
  126. .wait()
  127. .expect("failed to wait on \"beforeDevCommand\"");
  128. if !(status.success() || KILL_BEFORE_DEV_FLAG.get().unwrap().load(Ordering::Relaxed)) {
  129. logger_.error("The \"beforeDevCommand\" terminated with a non-zero status code.");
  130. exit(status.code().unwrap_or(1));
  131. }
  132. });
  133. BEFORE_DEV.set(Mutex::new(child)).unwrap();
  134. KILL_BEFORE_DEV_FLAG.set(AtomicBool::default()).unwrap();
  135. let _ = ctrlc::set_handler(move || {
  136. kill_before_dev_process();
  137. #[cfg(not(debug_assertions))]
  138. let _ = check_for_updates();
  139. exit(130);
  140. });
  141. }
  142. }
  143. let runner_from_config = config
  144. .lock()
  145. .unwrap()
  146. .as_ref()
  147. .unwrap()
  148. .build
  149. .runner
  150. .clone();
  151. let runner = options
  152. .runner
  153. .clone()
  154. .or(runner_from_config)
  155. .unwrap_or_else(|| "cargo".to_string());
  156. let manifest = {
  157. let (tx, rx) = channel();
  158. let mut watcher = watcher(tx, Duration::from_secs(1)).unwrap();
  159. watcher.watch(tauri_path.join("Cargo.toml"), RecursiveMode::Recursive)?;
  160. let manifest = rewrite_manifest(config.clone())?;
  161. loop {
  162. if let Ok(DebouncedEvent::NoticeWrite(_)) = rx.recv() {
  163. break;
  164. }
  165. }
  166. manifest
  167. };
  168. let mut cargo_features = config
  169. .lock()
  170. .unwrap()
  171. .as_ref()
  172. .unwrap()
  173. .build
  174. .features
  175. .clone()
  176. .unwrap_or_default();
  177. if let Some(features) = &options.features {
  178. cargo_features.extend(features.clone());
  179. }
  180. let manually_killed_app = Arc::new(AtomicBool::default());
  181. if std::env::var_os("TAURI_SKIP_DEVSERVER_CHECK") != Some("true".into()) {
  182. if let AppUrl::Url(WindowUrl::External(dev_server_url)) = config
  183. .lock()
  184. .unwrap()
  185. .as_ref()
  186. .unwrap()
  187. .build
  188. .dev_path
  189. .clone()
  190. {
  191. let host = dev_server_url
  192. .host()
  193. .unwrap_or_else(|| panic!("No host name in the URL"));
  194. let port = dev_server_url
  195. .port_or_known_default()
  196. .unwrap_or_else(|| panic!("No port number in the URL"));
  197. let addrs;
  198. let addr;
  199. let addrs = match host {
  200. url::Host::Domain(domain) => {
  201. use std::net::ToSocketAddrs;
  202. addrs = (domain, port).to_socket_addrs()?;
  203. addrs.as_slice()
  204. }
  205. url::Host::Ipv4(ip) => {
  206. addr = (ip, port).into();
  207. std::slice::from_ref(&addr)
  208. }
  209. url::Host::Ipv6(ip) => {
  210. addr = (ip, port).into();
  211. std::slice::from_ref(&addr)
  212. }
  213. };
  214. let mut i = 0;
  215. let sleep_interval = std::time::Duration::from_secs(2);
  216. let max_attempts = 90;
  217. loop {
  218. if std::net::TcpStream::connect(addrs).is_ok() {
  219. break;
  220. }
  221. if i % 3 == 0 {
  222. logger.warn(format!(
  223. "Waiting for your frontend dev server to start on {}...",
  224. dev_server_url
  225. ));
  226. }
  227. i += 1;
  228. if i == max_attempts {
  229. logger.error(format!(
  230. "Could not connect to `{}` after {}s. Please make sure that is the URL to your dev server.",
  231. dev_server_url, i * sleep_interval.as_secs()
  232. ));
  233. exit(1);
  234. }
  235. std::thread::sleep(sleep_interval);
  236. }
  237. }
  238. }
  239. let process = start_app(
  240. &options,
  241. &runner,
  242. &manifest,
  243. &cargo_features,
  244. manually_killed_app.clone(),
  245. )?;
  246. let shared_process = Arc::new(Mutex::new(process));
  247. if let Err(e) = watch(
  248. shared_process.clone(),
  249. manually_killed_app,
  250. tauri_path,
  251. merge_config,
  252. config,
  253. options,
  254. runner,
  255. manifest,
  256. cargo_features,
  257. ) {
  258. shared_process
  259. .lock()
  260. .unwrap()
  261. .kill()
  262. .with_context(|| "failed to kill app process")?;
  263. Err(e)
  264. } else {
  265. Ok(())
  266. }
  267. }
  268. #[cfg(not(debug_assertions))]
  269. fn check_for_updates() -> Result<()> {
  270. if std::env::var_os("TAURI_SKIP_UPDATE_CHECK") != Some("true".into()) {
  271. let current_version = crate::info::cli_current_version()?;
  272. let current = semver::Version::parse(&current_version)?;
  273. let upstream_version = crate::info::cli_upstream_version()?;
  274. let upstream = semver::Version::parse(&upstream_version)?;
  275. if current < upstream {
  276. println!(
  277. "🚀 A new version of Tauri CLI is avaliable! [{}]",
  278. upstream.to_string()
  279. );
  280. };
  281. }
  282. Ok(())
  283. }
  284. fn lookup<F: FnMut(FileType, PathBuf)>(dir: &Path, mut f: F) {
  285. let mut default_gitignore = std::env::temp_dir();
  286. default_gitignore.push(".tauri-dev");
  287. let _ = std::fs::create_dir_all(&default_gitignore);
  288. default_gitignore.push(".gitignore");
  289. if !default_gitignore.exists() {
  290. if let Ok(mut file) = std::fs::File::create(default_gitignore.clone()) {
  291. let _ = file.write_all(TAURI_DEV_WATCHER_GITIGNORE);
  292. }
  293. }
  294. let mut builder = ignore::WalkBuilder::new(dir);
  295. let _ = builder.add_ignore(default_gitignore);
  296. builder.require_git(false).ignore(false).max_depth(Some(1));
  297. for entry in builder.build().flatten() {
  298. f(entry.file_type().unwrap(), dir.join(entry.path()));
  299. }
  300. }
  301. #[allow(clippy::too_many_arguments)]
  302. fn watch(
  303. process: Arc<Mutex<Arc<SharedChild>>>,
  304. manually_killed_app: Arc<AtomicBool>,
  305. tauri_path: PathBuf,
  306. merge_config: Option<String>,
  307. config: ConfigHandle,
  308. options: Options,
  309. runner: String,
  310. mut manifest: Manifest,
  311. cargo_features: Vec<String>,
  312. ) -> Result<()> {
  313. let (tx, rx) = channel();
  314. let mut watcher = watcher(tx, Duration::from_secs(1)).unwrap();
  315. lookup(&tauri_path, |file_type, path| {
  316. if path != tauri_path {
  317. let _ = watcher.watch(
  318. path,
  319. if file_type.is_dir() {
  320. RecursiveMode::Recursive
  321. } else {
  322. RecursiveMode::NonRecursive
  323. },
  324. );
  325. }
  326. });
  327. loop {
  328. if let Ok(event) = rx.recv() {
  329. let event_path = match event {
  330. DebouncedEvent::Create(path) => Some(path),
  331. DebouncedEvent::Remove(path) => Some(path),
  332. DebouncedEvent::Rename(_, dest) => Some(dest),
  333. DebouncedEvent::Write(path) => Some(path),
  334. _ => None,
  335. };
  336. if let Some(event_path) = event_path {
  337. if event_path.file_name() == Some(OsStr::new("tauri.conf.json")) {
  338. reload_config(merge_config.as_deref())?;
  339. manifest = rewrite_manifest(config.clone())?;
  340. } else {
  341. // When tauri.conf.json is changed, rewrite_manifest will be called
  342. // which will trigger the watcher again
  343. // So the app should only be started when a file other than tauri.conf.json is changed
  344. manually_killed_app.store(true, Ordering::Relaxed);
  345. let mut p = process.lock().unwrap();
  346. p.kill().with_context(|| "failed to kill app process")?;
  347. // wait for the process to exit
  348. loop {
  349. if let Ok(Some(_)) = p.try_wait() {
  350. break;
  351. }
  352. }
  353. *p = start_app(
  354. &options,
  355. &runner,
  356. &manifest,
  357. &cargo_features,
  358. manually_killed_app.clone(),
  359. )?;
  360. }
  361. }
  362. }
  363. }
  364. }
  365. fn kill_before_dev_process() {
  366. if let Some(child) = BEFORE_DEV.get() {
  367. let child = child.lock().unwrap();
  368. KILL_BEFORE_DEV_FLAG
  369. .get()
  370. .unwrap()
  371. .store(true, Ordering::Relaxed);
  372. #[cfg(windows)]
  373. let _ = Command::new("powershell")
  374. .arg("-NoProfile")
  375. .arg("-Command")
  376. .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()))
  377. .status();
  378. #[cfg(unix)]
  379. {
  380. let mut kill_children_script_path = std::env::temp_dir();
  381. kill_children_script_path.push("kill-children.sh");
  382. if !kill_children_script_path.exists() {
  383. if let Ok(mut file) = std::fs::File::create(&kill_children_script_path) {
  384. use std::os::unix::fs::PermissionsExt;
  385. let _ = file.write_all(KILL_CHILDREN_SCRIPT);
  386. let mut permissions = file.metadata().unwrap().permissions();
  387. permissions.set_mode(0o770);
  388. let _ = file.set_permissions(permissions);
  389. }
  390. }
  391. let _ = Command::new(&kill_children_script_path)
  392. .arg(child.id().to_string())
  393. .output();
  394. }
  395. let _ = child.kill();
  396. }
  397. }
  398. fn start_app(
  399. options: &Options,
  400. runner: &str,
  401. manifest: &Manifest,
  402. features: &[String],
  403. manually_killed_app: Arc<AtomicBool>,
  404. ) -> Result<Arc<SharedChild>> {
  405. let mut command = Command::new(runner);
  406. command
  407. .env(
  408. "CARGO_TERM_PROGRESS_WIDTH",
  409. terminal::stderr_width()
  410. .map(|width| {
  411. if cfg!(windows) {
  412. std::cmp::min(60, width)
  413. } else {
  414. width
  415. }
  416. })
  417. .unwrap_or(if cfg!(windows) { 60 } else { 80 })
  418. .to_string(),
  419. )
  420. .env("CARGO_TERM_PROGRESS_WHEN", "always");
  421. command.arg("run").arg("--color").arg("always");
  422. if !options.args.contains(&"--no-default-features".into()) {
  423. let manifest_features = manifest.features();
  424. let enable_features: Vec<String> = manifest_features
  425. .get("default")
  426. .cloned()
  427. .unwrap_or_default()
  428. .into_iter()
  429. .filter(|feature| {
  430. if let Some(manifest_feature) = manifest_features.get(feature) {
  431. !manifest_feature.contains(&"tauri/custom-protocol".into())
  432. } else {
  433. feature != "tauri/custom-protocol"
  434. }
  435. })
  436. .collect();
  437. command.arg("--no-default-features");
  438. if !enable_features.is_empty() {
  439. command.args(&["--features", &enable_features.join(",")]);
  440. }
  441. }
  442. if options.release_mode {
  443. command.args(&["--release"]);
  444. }
  445. if let Some(target) = &options.target {
  446. command.args(&["--target", target]);
  447. }
  448. if !features.is_empty() {
  449. command.args(&["--features", &features.join(",")]);
  450. }
  451. if !options.args.is_empty() {
  452. command.args(&options.args);
  453. }
  454. command.stdout(os_pipe::dup_stdout().unwrap());
  455. command.stderr(Stdio::piped());
  456. let child =
  457. SharedChild::spawn(&mut command).with_context(|| format!("failed to run {}", runner))?;
  458. let child_arc = Arc::new(child);
  459. let child_stderr = child_arc.take_stderr().unwrap();
  460. let mut stderr = BufReader::new(child_stderr);
  461. let stderr_lines = Arc::new(Mutex::new(Vec::new()));
  462. let stderr_lines_ = stderr_lines.clone();
  463. std::thread::spawn(move || {
  464. let mut buf = Vec::new();
  465. let mut lines = stderr_lines_.lock().unwrap();
  466. let mut io_stderr = std::io::stderr();
  467. loop {
  468. buf.clear();
  469. match tauri_utils::io::read_line(&mut stderr, &mut buf) {
  470. Ok(s) if s == 0 => break,
  471. _ => (),
  472. }
  473. let _ = io_stderr.write_all(&buf);
  474. if !buf.ends_with(&[b'\r']) {
  475. let _ = io_stderr.write_all(b"\n");
  476. }
  477. lines.push(String::from_utf8_lossy(&buf).into_owned());
  478. }
  479. });
  480. let child_clone = child_arc.clone();
  481. let exit_on_panic = options.exit_on_panic;
  482. std::thread::spawn(move || {
  483. let status = child_clone.wait().expect("failed to wait on child");
  484. if exit_on_panic {
  485. if !manually_killed_app.load(Ordering::Relaxed) {
  486. kill_before_dev_process();
  487. #[cfg(not(debug_assertions))]
  488. let _ = check_for_updates();
  489. exit(status.code().unwrap_or(0));
  490. }
  491. } else {
  492. let is_cargo_compile_error = stderr_lines
  493. .lock()
  494. .unwrap()
  495. .last()
  496. .map(|l| l.contains("could not compile"))
  497. .unwrap_or_default();
  498. stderr_lines.lock().unwrap().clear();
  499. // if we're no exiting on panic, we only exit if:
  500. // - the status is a success code (app closed)
  501. // - status code is the Cargo error code
  502. // - and error is not a cargo compilation error (using stderr heuristics)
  503. if status.success() || (status.code() == Some(101) && !is_cargo_compile_error) {
  504. kill_before_dev_process();
  505. #[cfg(not(debug_assertions))]
  506. let _ = check_for_updates();
  507. exit(status.code().unwrap_or(1));
  508. }
  509. }
  510. });
  511. Ok(child_arc)
  512. }
  513. // taken from https://github.com/rust-lang/cargo/blob/78b10d4e611ab0721fc3aeaf0edd5dd8f4fdc372/src/cargo/core/shell.rs#L514
  514. #[cfg(unix)]
  515. mod terminal {
  516. use std::mem;
  517. pub fn stderr_width() -> Option<usize> {
  518. unsafe {
  519. let mut winsize: libc::winsize = mem::zeroed();
  520. // The .into() here is needed for FreeBSD which defines TIOCGWINSZ
  521. // as c_uint but ioctl wants c_ulong.
  522. #[allow(clippy::useless_conversion)]
  523. if libc::ioctl(libc::STDERR_FILENO, libc::TIOCGWINSZ.into(), &mut winsize) < 0 {
  524. return None;
  525. }
  526. if winsize.ws_col > 0 {
  527. Some(winsize.ws_col as usize)
  528. } else {
  529. None
  530. }
  531. }
  532. }
  533. }
  534. // taken from https://github.com/rust-lang/cargo/blob/78b10d4e611ab0721fc3aeaf0edd5dd8f4fdc372/src/cargo/core/shell.rs#L543
  535. #[cfg(windows)]
  536. mod terminal {
  537. use std::{cmp, mem, ptr};
  538. use winapi::um::fileapi::*;
  539. use winapi::um::handleapi::*;
  540. use winapi::um::processenv::*;
  541. use winapi::um::winbase::*;
  542. use winapi::um::wincon::*;
  543. use winapi::um::winnt::*;
  544. pub fn stderr_width() -> Option<usize> {
  545. unsafe {
  546. let stdout = GetStdHandle(STD_ERROR_HANDLE);
  547. let mut csbi: CONSOLE_SCREEN_BUFFER_INFO = mem::zeroed();
  548. if GetConsoleScreenBufferInfo(stdout, &mut csbi) != 0 {
  549. return Some((csbi.srWindow.Right - csbi.srWindow.Left) as usize);
  550. }
  551. // On mintty/msys/cygwin based terminals, the above fails with
  552. // INVALID_HANDLE_VALUE. Use an alternate method which works
  553. // in that case as well.
  554. let h = CreateFileA(
  555. "CONOUT$\0".as_ptr() as *const CHAR,
  556. GENERIC_READ | GENERIC_WRITE,
  557. FILE_SHARE_READ | FILE_SHARE_WRITE,
  558. ptr::null_mut(),
  559. OPEN_EXISTING,
  560. 0,
  561. ptr::null_mut(),
  562. );
  563. if h == INVALID_HANDLE_VALUE {
  564. return None;
  565. }
  566. let mut csbi: CONSOLE_SCREEN_BUFFER_INFO = mem::zeroed();
  567. let rc = GetConsoleScreenBufferInfo(h, &mut csbi);
  568. CloseHandle(h);
  569. if rc != 0 {
  570. let width = (csbi.srWindow.Right - csbi.srWindow.Left) as usize;
  571. // Unfortunately cygwin/mintty does not set the size of the
  572. // backing console to match the actual window size. This
  573. // always reports a size of 80 or 120 (not sure what
  574. // determines that). Use a conservative max of 60 which should
  575. // work in most circumstances. ConEmu does some magic to
  576. // resize the console correctly, but there's no reasonable way
  577. // to detect which kind of terminal we are running in, or if
  578. // GetConsoleScreenBufferInfo returns accurate information.
  579. return Some(cmp::min(60, width));
  580. }
  581. None
  582. }
  583. }
  584. }