refactor: cleanup cli/main.rs (#13160)

This commit is contained in:
Bartek Iwańczuk 2021-12-21 15:49:27 +01:00 committed by GitHub
parent 9825c876b4
commit 907cef563e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 207 additions and 206 deletions

View file

@ -541,14 +541,7 @@ async fn install_command(
create_main_worker(&ps, main_module.clone(), permissions, None);
// First, fetch and compile the module; this step ensures that the module exists.
worker.preload_module(&main_module, true).await?;
tools::installer::install(
flags,
&install_flags.module_url,
install_flags.args,
install_flags.name,
install_flags.root,
install_flags.force,
)?;
tools::installer::install(flags, install_flags)?;
Ok(0)
}
@ -649,15 +642,9 @@ async fn eval_command(
worker.execute_side_module(&compat::GLOBAL_URL).await?;
}
worker.execute_main_module(&main_module).await?;
worker.execute_script(
&located_script_name!(),
"window.dispatchEvent(new Event('load'))",
)?;
worker.dispatch_load_event(&located_script_name!())?;
worker.run_event_loop(false).await?;
worker.execute_script(
&located_script_name!(),
"window.dispatchEvent(new Event('unload'))",
)?;
worker.dispatch_unload_event(&located_script_name!())?;
Ok(0)
}
@ -987,15 +974,9 @@ async fn run_from_stdin(flags: Flags) -> Result<i32, AnyError> {
worker.execute_side_module(&compat::GLOBAL_URL).await?;
}
worker.execute_main_module(&main_module).await?;
worker.execute_script(
&located_script_name!(),
"window.dispatchEvent(new Event('load'))",
)?;
worker.dispatch_load_event(&located_script_name!())?;
worker.run_event_loop(false).await?;
worker.execute_script(
&located_script_name!(),
"window.dispatchEvent(new Event('unload'))",
)?;
worker.dispatch_unload_event(&located_script_name!())?;
Ok(worker.get_exit_code())
}
@ -1115,10 +1096,7 @@ async fn run_with_watch(flags: Flags, script: String) -> Result<i32, AnyError> {
self.worker.execute_side_module(&compat::GLOBAL_URL).await?;
}
self.worker.execute_main_module(main_module).await?;
self.worker.execute_script(
&located_script_name!(),
"window.dispatchEvent(new Event('load'))",
)?;
self.worker.dispatch_load_event(&located_script_name!())?;
self.pending_unload = true;
let result = self.worker.run_event_loop(false).await;
@ -1128,10 +1106,7 @@ async fn run_with_watch(flags: Flags, script: String) -> Result<i32, AnyError> {
return Err(err);
}
self.worker.execute_script(
&located_script_name!(),
"window.dispatchEvent(new Event('unload'))",
)?;
self.worker.dispatch_unload_event(&located_script_name!())?;
Ok(())
}
@ -1142,10 +1117,7 @@ async fn run_with_watch(flags: Flags, script: String) -> Result<i32, AnyError> {
if self.pending_unload {
self
.worker
.execute_script(
&located_script_name!(),
"window.dispatchEvent(new Event('unload'))",
)
.dispatch_unload_event(&located_script_name!())
.unwrap();
}
}
@ -1243,17 +1215,11 @@ async fn run_command(
worker.execute_main_module(&main_module).await?;
}
worker.execute_script(
&located_script_name!(),
"window.dispatchEvent(new Event('load'))",
)?;
worker.dispatch_load_event(&located_script_name!())?;
worker
.run_event_loop(maybe_coverage_collector.is_none())
.await?;
worker.execute_script(
&located_script_name!(),
"window.dispatchEvent(new Event('unload'))",
)?;
worker.dispatch_unload_event(&located_script_name!())?;
if let Some(coverage_collector) = maybe_coverage_collector.as_mut() {
worker
@ -1296,6 +1262,28 @@ async fn test_command(
Ok(0)
}
async fn completions_command(
_flags: Flags,
completions_flags: CompletionsFlags,
) -> Result<i32, AnyError> {
write_to_stdout_ignore_sigpipe(&completions_flags.buf)?;
Ok(0)
}
async fn types_command(flags: Flags) -> Result<i32, AnyError> {
let types = get_types(flags.unstable);
write_to_stdout_ignore_sigpipe(types.as_bytes())?;
Ok(0)
}
async fn upgrade_command(
_flags: Flags,
upgrade_flags: UpgradeFlags,
) -> Result<i32, AnyError> {
tools::upgrade::upgrade(upgrade_flags).await?;
Ok(0)
}
fn init_v8_flags(v8_flags: &[String]) {
let v8_flags_includes_help = v8_flags
.iter()
@ -1367,38 +1355,12 @@ fn get_subcommand(
DenoSubcommand::Test(test_flags) => {
test_command(flags, test_flags).boxed_local()
}
DenoSubcommand::Completions(CompletionsFlags { buf }) => {
if let Err(e) = write_to_stdout_ignore_sigpipe(&buf) {
eprintln!("{}", e);
std::process::exit(1);
}
std::process::exit(0);
}
DenoSubcommand::Types => {
let types = get_types(flags.unstable);
if let Err(e) = write_to_stdout_ignore_sigpipe(types.as_bytes()) {
eprintln!("{}", e);
std::process::exit(1);
}
std::process::exit(0);
DenoSubcommand::Completions(completions_flags) => {
completions_command(flags, completions_flags).boxed_local()
}
DenoSubcommand::Types => types_command(flags).boxed_local(),
DenoSubcommand::Upgrade(upgrade_flags) => {
let UpgradeFlags {
force,
dry_run,
canary,
version,
output,
ca_file,
} = upgrade_flags;
async move {
tools::upgrade::upgrade_command(
dry_run, force, canary, version, output, ca_file,
)
.await?;
Ok(0)
}
.boxed_local()
upgrade_command(flags, upgrade_flags).boxed_local()
}
}
}
@ -1457,10 +1419,8 @@ pub fn main() {
Ok(None) => Ok(()),
Err(err) => Err(err),
};
if let Err(err) = standalone_res {
eprintln!("{}: {}", colors::red_bold("error"), err.to_string());
std::process::exit(1);
}
// TODO(bartlomieju): doesn't handle exit code set by the runtime properly
unwrap_or_exit(standalone_res);
let flags = match flags::flags_from_vec(args) {
Ok(flags) => flags,

View file

@ -284,15 +284,9 @@ pub async fn run(
js_runtime.sync_ops_cache();
}
worker.execute_main_module(&main_module).await?;
worker.execute_script(
&located_script_name!(),
"window.dispatchEvent(new Event('load'))",
)?;
worker.dispatch_load_event(&located_script_name!())?;
worker.run_event_loop(true).await?;
worker.execute_script(
&located_script_name!(),
"window.dispatchEvent(new Event('unload'))",
)?;
worker.dispatch_unload_event(&located_script_name!())?;
std::process::exit(0);
}

View file

@ -2,6 +2,7 @@
use crate::flags::CheckFlag;
use crate::flags::Flags;
use crate::flags::InstallFlags;
use crate::fs_util::canonicalize_path;
use deno_core::error::generic_error;
use deno_core::error::AnyError;
@ -192,13 +193,9 @@ pub fn uninstall(name: String, root: Option<PathBuf>) -> Result<(), AnyError> {
pub fn install(
flags: Flags,
module_url: &str,
args: Vec<String>,
name: Option<String>,
root: Option<PathBuf>,
force: bool,
install_flags: InstallFlags,
) -> Result<(), AnyError> {
let root = if let Some(root) = root {
let root = if let Some(root) = install_flags.root {
canonicalize_path(&root)?
} else {
get_installer_root()?
@ -215,9 +212,11 @@ pub fn install(
};
// Check if module_url is remote
let module_url = resolve_url_or_path(module_url)?;
let module_url = resolve_url_or_path(&install_flags.module_url)?;
let name = name.or_else(|| infer_name_from_url(&module_url));
let name = install_flags
.name
.or_else(|| infer_name_from_url(&module_url));
let name = match name {
Some(name) => name,
@ -233,7 +232,7 @@ pub fn install(
file_path = file_path.with_extension("cmd");
}
if file_path.exists() && !force {
if file_path.exists() && !install_flags.force {
return Err(generic_error(
"Existing installation found. Aborting (Use -f to overwrite).",
));
@ -331,7 +330,7 @@ pub fn install(
}
executable_args.push(module_url.to_string());
executable_args.extend_from_slice(&args);
executable_args.extend_from_slice(&install_flags.args);
generate_executable_file(file_path.to_owned(), executable_args)?;
for (path, contents) in extra_files {
@ -471,11 +470,13 @@ mod tests {
install(
Flags::default(),
"http://localhost:4545/echo_server.ts",
vec![],
Some("echo_test".to_string()),
None,
false,
InstallFlags {
module_url: "http://localhost:4545/echo_server.ts".to_string(),
args: vec![],
name: Some("echo_test".to_string()),
root: None,
force: false,
},
)
.expect("Install failed");
@ -519,11 +520,13 @@ mod tests {
unstable: true,
..Flags::default()
},
"http://localhost:4545/echo_server.ts",
vec![],
Some("echo_test".to_string()),
Some(temp_dir.path().to_path_buf()),
false,
InstallFlags {
module_url: "http://localhost:4545/echo_server.ts".to_string(),
args: vec![],
name: Some("echo_test".to_string()),
root: Some(temp_dir.path().to_path_buf()),
force: false,
},
)
.expect("Install failed");
@ -554,11 +557,13 @@ mod tests {
install(
Flags::default(),
"http://localhost:4545/echo_server.ts",
vec![],
None,
Some(temp_dir.path().to_path_buf()),
false,
InstallFlags {
module_url: "http://localhost:4545/echo_server.ts".to_string(),
args: vec![],
name: None,
root: Some(temp_dir.path().to_path_buf()),
force: false,
},
)
.expect("Install failed");
@ -586,11 +591,13 @@ mod tests {
install(
Flags::default(),
"http://localhost:4545/subdir/main.ts",
vec![],
None,
Some(temp_dir.path().to_path_buf()),
false,
InstallFlags {
module_url: "http://localhost:4545/subdir/main.ts".to_string(),
args: vec![],
name: None,
root: Some(temp_dir.path().to_path_buf()),
force: false,
},
)
.expect("Install failed");
@ -618,11 +625,13 @@ mod tests {
install(
Flags::default(),
"http://localhost:4545/echo_server.ts",
vec![],
Some("echo_test".to_string()),
Some(temp_dir.path().to_path_buf()),
false,
InstallFlags {
module_url: "http://localhost:4545/echo_server.ts".to_string(),
args: vec![],
name: Some("echo_test".to_string()),
root: Some(temp_dir.path().to_path_buf()),
force: false,
},
)
.expect("Install failed");
@ -653,11 +662,13 @@ mod tests {
install(
Flags::default(),
"http://localhost:4545/echo_server.ts",
vec![],
Some("echo_test".to_string()),
None,
false,
InstallFlags {
module_url: "http://localhost:4545/echo_server.ts".to_string(),
args: vec![],
name: Some("echo_test".to_string()),
root: None,
force: false,
},
)
.expect("Install failed");
@ -694,11 +705,13 @@ mod tests {
log_level: Some(Level::Error),
..Flags::default()
},
"http://localhost:4545/echo_server.ts",
vec!["--foobar".to_string()],
Some("echo_test".to_string()),
Some(temp_dir.path().to_path_buf()),
false,
InstallFlags {
module_url: "http://localhost:4545/echo_server.ts".to_string(),
args: vec!["--foobar".to_string()],
name: Some("echo_test".to_string()),
root: Some(temp_dir.path().to_path_buf()),
force: false,
},
)
.expect("Install failed");
@ -727,11 +740,13 @@ mod tests {
install(
Flags::default(),
&local_module_str,
vec![],
Some("echo_test".to_string()),
Some(temp_dir.path().to_path_buf()),
false,
InstallFlags {
module_url: local_module_str.to_string(),
args: vec![],
name: Some("echo_test".to_string()),
root: Some(temp_dir.path().to_path_buf()),
force: false,
},
)
.expect("Install failed");
@ -753,11 +768,13 @@ mod tests {
install(
Flags::default(),
"http://localhost:4545/echo_server.ts",
vec![],
Some("echo_test".to_string()),
Some(temp_dir.path().to_path_buf()),
false,
InstallFlags {
module_url: "http://localhost:4545/echo_server.ts".to_string(),
args: vec![],
name: Some("echo_test".to_string()),
root: Some(temp_dir.path().to_path_buf()),
force: false,
},
)
.expect("Install failed");
@ -770,11 +787,13 @@ mod tests {
// No force. Install failed.
let no_force_result = install(
Flags::default(),
"http://localhost:4545/cat.ts", // using a different URL
vec![],
Some("echo_test".to_string()),
Some(temp_dir.path().to_path_buf()),
false,
InstallFlags {
module_url: "http://localhost:4545/cat.ts".to_string(), // using a different URL
args: vec![],
name: Some("echo_test".to_string()),
root: Some(temp_dir.path().to_path_buf()),
force: false,
},
);
assert!(no_force_result.is_err());
assert!(no_force_result
@ -788,11 +807,13 @@ mod tests {
// Force. Install success.
let force_result = install(
Flags::default(),
"http://localhost:4545/cat.ts", // using a different URL
vec![],
Some("echo_test".to_string()),
Some(temp_dir.path().to_path_buf()),
true,
InstallFlags {
module_url: "http://localhost:4545/cat.ts".to_string(), // using a different URL
args: vec![],
name: Some("echo_test".to_string()),
root: Some(temp_dir.path().to_path_buf()),
force: true,
},
);
assert!(force_result.is_ok());
// Assert modified
@ -815,11 +836,13 @@ mod tests {
config_path: Some(config_file_path.to_string_lossy().to_string()),
..Flags::default()
},
"http://localhost:4545/cat.ts",
vec![],
Some("echo_test".to_string()),
Some(temp_dir.path().to_path_buf()),
true,
InstallFlags {
module_url: "http://localhost:4545/cat.ts".to_string(),
args: vec![],
name: Some("echo_test".to_string()),
root: Some(temp_dir.path().to_path_buf()),
force: true,
},
);
eprintln!("result {:?}", result);
assert!(result.is_ok());
@ -842,11 +865,13 @@ mod tests {
install(
Flags::default(),
"http://localhost:4545/echo_server.ts",
vec!["\"".to_string()],
Some("echo_test".to_string()),
Some(temp_dir.path().to_path_buf()),
false,
InstallFlags {
module_url: "http://localhost:4545/echo_server.ts".to_string(),
args: vec!["\"".to_string()],
name: Some("echo_test".to_string()),
root: Some(temp_dir.path().to_path_buf()),
force: false,
},
)
.expect("Install failed");
@ -883,11 +908,13 @@ mod tests {
install(
Flags::default(),
&local_module_str,
vec![],
Some("echo_test".to_string()),
Some(temp_dir.path().to_path_buf()),
false,
InstallFlags {
module_url: local_module_str.to_string(),
args: vec![],
name: Some("echo_test".to_string()),
root: Some(temp_dir.path().to_path_buf()),
force: false,
},
)
.expect("Install failed");
@ -917,11 +944,13 @@ mod tests {
import_map_path: Some(import_map_path.to_string_lossy().to_string()),
..Flags::default()
},
"http://localhost:4545/cat.ts",
vec![],
Some("echo_test".to_string()),
Some(temp_dir.path().to_path_buf()),
true,
InstallFlags {
module_url: "http://localhost:4545/cat.ts".to_string(),
args: vec![],
name: Some("echo_test".to_string()),
root: Some(temp_dir.path().to_path_buf()),
force: true,
},
);
assert!(result.is_ok());
@ -958,11 +987,13 @@ mod tests {
let result = install(
Flags::default(),
&file_module_string,
vec![],
Some("echo_test".to_string()),
Some(temp_dir.path().to_path_buf()),
true,
InstallFlags {
module_url: file_module_string.to_string(),
args: vec![],
name: Some("echo_test".to_string()),
root: Some(temp_dir.path().to_path_buf()),
force: true,
},
);
assert!(result.is_ok());

View file

@ -487,10 +487,7 @@ async fn test_specifier(
worker.execute_side_module(&specifier).await?;
}
worker.js_runtime.execute_script(
&located_script_name!(),
"window.dispatchEvent(new Event('load'));",
)?;
worker.dispatch_load_event(&located_script_name!())?;
let test_result = worker.js_runtime.execute_script(
&located_script_name!(),
@ -505,10 +502,7 @@ async fn test_specifier(
worker.js_runtime.resolve_value(test_result).await?;
worker.js_runtime.execute_script(
&located_script_name!(),
"window.dispatchEvent(new Event('unload'));",
)?;
worker.dispatch_unload_event(&located_script_name!())?;
if let Some(coverage_collector) = maybe_coverage_collector.as_mut() {
worker

View file

@ -2,6 +2,7 @@
//! This module provides feature to upgrade deno executable
use crate::flags::UpgradeFlags;
use deno_core::anyhow::bail;
use deno_core::error::AnyError;
use deno_core::futures::StreamExt;
@ -21,18 +22,11 @@ static ARCHIVE_NAME: Lazy<String> =
const RELEASE_URL: &str = "https://github.com/denoland/deno/releases";
pub async fn upgrade_command(
dry_run: bool,
force: bool,
canary: bool,
version: Option<String>,
output: Option<PathBuf>,
ca_file: Option<String>,
) -> Result<(), AnyError> {
pub async fn upgrade(upgrade_flags: UpgradeFlags) -> Result<(), AnyError> {
let mut client_builder = Client::builder();
// If we have been provided a CA Certificate, add it into the HTTP client
if let Some(ca_file) = ca_file {
if let Some(ca_file) = upgrade_flags.ca_file {
let buf = std::fs::read(ca_file)?;
let cert = reqwest::Certificate::from_pem(&buf)?;
client_builder = client_builder.add_root_certificate(cert);
@ -40,17 +34,18 @@ pub async fn upgrade_command(
let client = client_builder.build()?;
let install_version = match version {
let install_version = match upgrade_flags.version {
Some(passed_version) => {
if canary
if upgrade_flags.canary
&& !regex::Regex::new("^[0-9a-f]{40}$")?.is_match(&passed_version)
{
bail!("Invalid commit hash passed");
} else if !canary && semver_parse(&passed_version).is_err() {
} else if !upgrade_flags.canary && semver_parse(&passed_version).is_err()
{
bail!("Invalid semver passed");
}
let current_is_passed = if canary {
let current_is_passed = if upgrade_flags.canary {
crate::version::GIT_COMMIT_HASH == passed_version
} else if !crate::version::is_canary() {
crate::version::deno() == passed_version
@ -58,7 +53,10 @@ pub async fn upgrade_command(
false
};
if !force && output.is_none() && current_is_passed {
if !upgrade_flags.force
&& upgrade_flags.output.is_none()
&& current_is_passed
{
println!("Version {} is already installed", crate::version::deno());
return Ok(());
} else {
@ -66,13 +64,13 @@ pub async fn upgrade_command(
}
}
None => {
let latest_version = if canary {
let latest_version = if upgrade_flags.canary {
get_latest_canary_version(&client).await?
} else {
get_latest_release_version(&client).await?
};
let current_is_most_recent = if canary {
let current_is_most_recent = if upgrade_flags.canary {
let mut latest_hash = latest_version.clone();
latest_hash.truncate(7);
crate::version::GIT_COMMIT_HASH == latest_hash
@ -84,7 +82,10 @@ pub async fn upgrade_command(
false
};
if !force && output.is_none() && current_is_most_recent {
if !upgrade_flags.force
&& upgrade_flags.output.is_none()
&& current_is_most_recent
{
println!(
"Local deno version {} is the most recent release",
crate::version::deno()
@ -97,7 +98,7 @@ pub async fn upgrade_command(
}
};
let download_url = if canary {
let download_url = if upgrade_flags.canary {
format!(
"https://dl.deno.land/canary/{}/{}",
install_version, *ARCHIVE_NAME
@ -119,8 +120,8 @@ pub async fn upgrade_command(
fs::set_permissions(&new_exe_path, permissions)?;
check_exe(&new_exe_path)?;
if !dry_run {
match output {
if !upgrade_flags.dry_run {
match upgrade_flags.output {
Some(path) => {
fs::rename(&new_exe_path, &path)
.or_else(|_| fs::copy(&new_exe_path, &path).map(|_| ()))?;

View file

@ -184,10 +184,10 @@ impl MainWorker {
/// See [JsRuntime::execute_script](deno_core::JsRuntime::execute_script)
pub fn execute_script(
&mut self,
name: &str,
script_name: &str,
source_code: &str,
) -> Result<(), AnyError> {
self.js_runtime.execute_script(name, source_code)?;
self.js_runtime.execute_script(script_name, source_code)?;
Ok(())
}
@ -305,6 +305,27 @@ impl MainWorker {
let exit_code = op_state.borrow::<Arc<AtomicI32>>().load(Relaxed);
exit_code
}
/// Dispatches "load" event to the JavaScript runtime.
///
/// Does not poll event loop, and thus not await any of the "load" event handlers.
pub fn dispatch_load_event(
&mut self,
script_name: &str,
) -> Result<(), AnyError> {
self.execute_script(script_name, "window.dispatchEvent(new Event('load'))")
}
/// Dispatches "unload" event to the JavaScript runtime.
///
/// Does not poll event loop, and thus not await any of the "unload" event handlers.
pub fn dispatch_unload_event(
&mut self,
script_name: &str,
) -> Result<(), AnyError> {
self
.execute_script(script_name, "window.dispatchEvent(new Event('unload'))")
}
}
#[cfg(test)]