diff options
author | Divy Srivastava <dj.srivastava23@gmail.com> | 2024-02-13 21:52:30 +0530 |
---|---|---|
committer | GitHub <noreply@github.com> | 2024-02-13 21:52:30 +0530 |
commit | a68eb3fcc3997fce8680f87edce46f6450e79635 (patch) | |
tree | 6839607033226fdfb2ce1be3187ef93791096507 /cli/tools | |
parent | 492a9fbb9194a24a1f9223f797b4f4df9efde2bd (diff) |
feat: denort binary for `deno compile` (#22205)
This introduces the `denort` binary - a slim version of deno without
tooling. The binary is used as the default for `deno compile`.
Improves `deno compile` final size by ~2.5x (141 MB -> 61 MB) on Linux
x86_64.
Diffstat (limited to 'cli/tools')
-rw-r--r-- | cli/tools/coverage/mod.rs | 97 | ||||
-rw-r--r-- | cli/tools/run/hmr.rs | 179 | ||||
-rw-r--r-- | cli/tools/upgrade.rs | 80 |
3 files changed, 152 insertions, 204 deletions
diff --git a/cli/tools/coverage/mod.rs b/cli/tools/coverage/mod.rs index 16c955576..aafef292f 100644 --- a/cli/tools/coverage/mod.rs +++ b/cli/tools/coverage/mod.rs @@ -46,6 +46,56 @@ pub struct CoverageCollector { session: LocalInspectorSession, } +#[async_trait::async_trait(?Send)] +impl crate::worker::CoverageCollector for CoverageCollector { + async fn start_collecting(&mut self) -> Result<(), AnyError> { + self.enable_debugger().await?; + self.enable_profiler().await?; + self + .start_precise_coverage(cdp::StartPreciseCoverageArgs { + call_count: true, + detailed: true, + allow_triggered_updates: false, + }) + .await?; + + Ok(()) + } + + async fn stop_collecting(&mut self) -> Result<(), AnyError> { + fs::create_dir_all(&self.dir)?; + + let script_coverages = self.take_precise_coverage().await?.result; + for script_coverage in script_coverages { + // Filter out internal JS files from being included in coverage reports + if script_coverage.url.starts_with("ext:") + || script_coverage.url.starts_with("[ext:") + { + continue; + } + + let filename = format!("{}.json", Uuid::new_v4()); + let filepath = self.dir.join(filename); + + let mut out = BufWriter::new(File::create(&filepath)?); + let coverage = serde_json::to_string(&script_coverage)?; + let formatted_coverage = + format_json(&filepath, &coverage, &Default::default()) + .ok() + .flatten() + .unwrap_or(coverage); + + out.write_all(formatted_coverage.as_bytes())?; + out.flush()?; + } + + self.disable_debugger().await?; + self.disable_profiler().await?; + + Ok(()) + } +} + impl CoverageCollector { pub fn new(dir: PathBuf, session: LocalInspectorSession) -> Self { Self { dir, session } @@ -109,53 +159,6 @@ impl CoverageCollector { Ok(return_object) } - - pub async fn start_collecting(&mut self) -> Result<(), AnyError> { - self.enable_debugger().await?; - self.enable_profiler().await?; - self - .start_precise_coverage(cdp::StartPreciseCoverageArgs { - call_count: true, - detailed: true, - allow_triggered_updates: false, - }) - .await?; - - Ok(()) - } - - pub async fn stop_collecting(&mut self) -> Result<(), AnyError> { - fs::create_dir_all(&self.dir)?; - - let script_coverages = self.take_precise_coverage().await?.result; - for script_coverage in script_coverages { - // Filter out internal JS files from being included in coverage reports - if script_coverage.url.starts_with("ext:") - || script_coverage.url.starts_with("[ext:") - { - continue; - } - - let filename = format!("{}.json", Uuid::new_v4()); - let filepath = self.dir.join(filename); - - let mut out = BufWriter::new(File::create(&filepath)?); - let coverage = serde_json::to_string(&script_coverage)?; - let formatted_coverage = - format_json(&filepath, &coverage, &Default::default()) - .ok() - .flatten() - .unwrap_or(coverage); - - out.write_all(formatted_coverage.as_bytes())?; - out.flush()?; - } - - self.disable_debugger().await?; - self.disable_profiler().await?; - - Ok(()) - } } #[derive(Debug, Clone)] diff --git a/cli/tools/run/hmr.rs b/cli/tools/run/hmr.rs index 88f90f680..4ca9ee8b9 100644 --- a/cli/tools/run/hmr.rs +++ b/cli/tools/run/hmr.rs @@ -61,105 +61,22 @@ pub struct HmrRunner { emitter: Arc<Emitter>, } -impl HmrRunner { - pub fn new( - emitter: Arc<Emitter>, - session: LocalInspectorSession, - watcher_communicator: Arc<WatcherCommunicator>, - ) -> Self { - Self { - session, - emitter, - watcher_communicator, - script_ids: HashMap::new(), - } - } - +#[async_trait::async_trait(?Send)] +impl crate::worker::HmrRunner for HmrRunner { // TODO(bartlomieju): this code is duplicated in `cli/tools/coverage/mod.rs` - pub async fn start(&mut self) -> Result<(), AnyError> { + async fn start(&mut self) -> Result<(), AnyError> { self.enable_debugger().await } // TODO(bartlomieju): this code is duplicated in `cli/tools/coverage/mod.rs` - pub async fn stop(&mut self) -> Result<(), AnyError> { + async fn stop(&mut self) -> Result<(), AnyError> { self .watcher_communicator .change_restart_mode(WatcherRestartMode::Automatic); self.disable_debugger().await } - // TODO(bartlomieju): this code is duplicated in `cli/tools/coverage/mod.rs` - async fn enable_debugger(&mut self) -> Result<(), AnyError> { - self - .session - .post_message::<()>("Debugger.enable", None) - .await?; - self - .session - .post_message::<()>("Runtime.enable", None) - .await?; - Ok(()) - } - - // TODO(bartlomieju): this code is duplicated in `cli/tools/coverage/mod.rs` - async fn disable_debugger(&mut self) -> Result<(), AnyError> { - self - .session - .post_message::<()>("Debugger.disable", None) - .await?; - self - .session - .post_message::<()>("Runtime.disable", None) - .await?; - Ok(()) - } - - async fn set_script_source( - &mut self, - script_id: &str, - source: &str, - ) -> Result<cdp::SetScriptSourceResponse, AnyError> { - let result = self - .session - .post_message( - "Debugger.setScriptSource", - Some(json!({ - "scriptId": script_id, - "scriptSource": source, - "allowTopFrameEditing": true, - })), - ) - .await?; - - Ok(serde_json::from_value::<cdp::SetScriptSourceResponse>( - result, - )?) - } - - async fn dispatch_hmr_event( - &mut self, - script_id: &str, - ) -> Result<(), AnyError> { - let expr = format!( - "dispatchEvent(new CustomEvent(\"hmr\", {{ detail: {{ path: \"{}\" }} }}));", - script_id - ); - - let _result = self - .session - .post_message( - "Runtime.evaluate", - Some(json!({ - "expression": expr, - "contextId": Some(1), - })), - ) - .await?; - - Ok(()) - } - - pub async fn run(&mut self) -> Result<(), AnyError> { + async fn run(&mut self) -> Result<(), AnyError> { self .watcher_communicator .change_restart_mode(WatcherRestartMode::Manual); @@ -252,3 +169,89 @@ impl HmrRunner { } } } + +impl HmrRunner { + pub fn new( + emitter: Arc<Emitter>, + session: LocalInspectorSession, + watcher_communicator: Arc<WatcherCommunicator>, + ) -> Self { + Self { + session, + emitter, + watcher_communicator, + script_ids: HashMap::new(), + } + } + + // TODO(bartlomieju): this code is duplicated in `cli/tools/coverage/mod.rs` + async fn enable_debugger(&mut self) -> Result<(), AnyError> { + self + .session + .post_message::<()>("Debugger.enable", None) + .await?; + self + .session + .post_message::<()>("Runtime.enable", None) + .await?; + Ok(()) + } + + // TODO(bartlomieju): this code is duplicated in `cli/tools/coverage/mod.rs` + async fn disable_debugger(&mut self) -> Result<(), AnyError> { + self + .session + .post_message::<()>("Debugger.disable", None) + .await?; + self + .session + .post_message::<()>("Runtime.disable", None) + .await?; + Ok(()) + } + + async fn set_script_source( + &mut self, + script_id: &str, + source: &str, + ) -> Result<cdp::SetScriptSourceResponse, AnyError> { + let result = self + .session + .post_message( + "Debugger.setScriptSource", + Some(json!({ + "scriptId": script_id, + "scriptSource": source, + "allowTopFrameEditing": true, + })), + ) + .await?; + + Ok(serde_json::from_value::<cdp::SetScriptSourceResponse>( + result, + )?) + } + + async fn dispatch_hmr_event( + &mut self, + script_id: &str, + ) -> Result<(), AnyError> { + let expr = format!( + "dispatchEvent(new CustomEvent(\"hmr\", {{ detail: {{ path: \"{}\" }} }}));", + script_id + ); + + let _result = self + .session + .post_message( + "Runtime.evaluate", + Some(json!({ + "expression": expr, + "contextId": Some(1), + })), + ) + .await?; + + Ok(()) + } +} diff --git a/cli/tools/upgrade.rs b/cli/tools/upgrade.rs index 70141f571..efe7e707e 100644 --- a/cli/tools/upgrade.rs +++ b/cli/tools/upgrade.rs @@ -7,6 +7,7 @@ use crate::args::UpgradeFlags; use crate::colors; use crate::factory::CliFactory; use crate::http_util::HttpClient; +use crate::standalone::binary::unpack_into_dir; use crate::util::progress_bar::ProgressBar; use crate::util::progress_bar::ProgressBarStyle; use crate::util::time; @@ -30,11 +31,11 @@ use std::process::Command; use std::sync::Arc; use std::time::Duration; -static ARCHIVE_NAME: Lazy<String> = - Lazy::new(|| format!("deno-{}.zip", env!("TARGET"))); - const RELEASE_URL: &str = "https://github.com/denoland/deno/releases"; +pub static ARCHIVE_NAME: Lazy<String> = + Lazy::new(|| format!("deno-{}.zip", env!("TARGET"))); + // How often query server for new version. In hours. const UPGRADE_CHECK_INTERVAL: i64 = 24; @@ -501,7 +502,13 @@ pub async fn upgrade( log::info!("Deno is upgrading to version {}", &install_version); let temp_dir = tempfile::TempDir::new()?; - let new_exe_path = unpack_into_dir(archive_data, cfg!(windows), &temp_dir)?; + let new_exe_path = unpack_into_dir( + "deno", + &ARCHIVE_NAME, + archive_data, + cfg!(windows), + &temp_dir, + )?; fs::set_permissions(&new_exe_path, permissions)?; check_exe(&new_exe_path)?; @@ -628,71 +635,6 @@ async fn download_package( } } -pub fn unpack_into_dir( - archive_data: Vec<u8>, - is_windows: bool, - temp_dir: &tempfile::TempDir, -) -> Result<PathBuf, AnyError> { - const EXE_NAME: &str = "deno"; - let temp_dir_path = temp_dir.path(); - let exe_ext = if is_windows { "exe" } else { "" }; - let archive_path = temp_dir_path.join(EXE_NAME).with_extension("zip"); - let exe_path = temp_dir_path.join(EXE_NAME).with_extension(exe_ext); - assert!(!exe_path.exists()); - - let archive_ext = Path::new(&*ARCHIVE_NAME) - .extension() - .and_then(|ext| ext.to_str()) - .unwrap(); - let unpack_status = match archive_ext { - "zip" if cfg!(windows) => { - fs::write(&archive_path, &archive_data)?; - Command::new("tar.exe") - .arg("xf") - .arg(&archive_path) - .arg("-C") - .arg(temp_dir_path) - .spawn() - .map_err(|err| { - if err.kind() == std::io::ErrorKind::NotFound { - std::io::Error::new( - std::io::ErrorKind::NotFound, - "`tar.exe` was not found in your PATH", - ) - } else { - err - } - })? - .wait()? - } - "zip" => { - fs::write(&archive_path, &archive_data)?; - Command::new("unzip") - .current_dir(temp_dir_path) - .arg(&archive_path) - .spawn() - .map_err(|err| { - if err.kind() == std::io::ErrorKind::NotFound { - std::io::Error::new( - std::io::ErrorKind::NotFound, - "`unzip` was not found in your PATH, please install `unzip`", - ) - } else { - err - } - })? - .wait()? - } - ext => bail!("Unsupported archive type: '{ext}'"), - }; - if !unpack_status.success() { - bail!("Failed to unpack archive."); - } - assert!(exe_path.exists()); - fs::remove_file(&archive_path)?; - Ok(exe_path) -} - fn replace_exe(from: &Path, to: &Path) -> Result<(), std::io::Error> { if cfg!(windows) { // On windows you cannot replace the currently running executable. |