1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-12-24 08:09:08 -05:00

refactor: clean up unwrap and clone (#17282)

Co-authored-by: Divy Srivastava <dj.srivastava23@gmail.com>
This commit is contained in:
Yiyu Lin 2023-01-15 12:06:46 +08:00 committed by GitHub
parent 05ef925eb0
commit fd85f840cd
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
15 changed files with 75 additions and 94 deletions

View file

@ -213,7 +213,7 @@ impl TsConfig {
} }
pub fn as_bytes(&self) -> Vec<u8> { pub fn as_bytes(&self) -> Vec<u8> {
let map = self.0.as_object().unwrap(); let map = self.0.as_object().expect("invalid tsconfig");
let ordered: BTreeMap<_, _> = map.iter().collect(); let ordered: BTreeMap<_, _> = map.iter().collect();
let value = json!(ordered); let value = json!(ordered);
value.to_string().as_bytes().to_owned() value.to_string().as_bytes().to_owned()

View file

@ -465,30 +465,30 @@ impl Flags {
/// If it returns None, the config file shouldn't be discovered at all. /// If it returns None, the config file shouldn't be discovered at all.
pub fn config_path_args(&self) -> Option<Vec<PathBuf>> { pub fn config_path_args(&self) -> Option<Vec<PathBuf>> {
use DenoSubcommand::*; use DenoSubcommand::*;
if let Fmt(FmtFlags { files, .. }) = &self.subcommand {
Some(files.include.clone()) match &self.subcommand {
} else if let Lint(LintFlags { files, .. }) = &self.subcommand { Fmt(FmtFlags { files, .. }) => Some(files.include.clone()),
Some(files.include.clone()) Lint(LintFlags { files, .. }) => Some(files.include.clone()),
} else if let Run(RunFlags { script }) = &self.subcommand { Run(RunFlags { script }) => {
if let Ok(module_specifier) = deno_core::resolve_url_or_path(script) { if let Ok(module_specifier) = deno_core::resolve_url_or_path(script) {
if module_specifier.scheme() == "file" if module_specifier.scheme() == "file"
|| module_specifier.scheme() == "npm" || module_specifier.scheme() == "npm"
{ {
if let Ok(p) = module_specifier.to_file_path() { if let Ok(p) = module_specifier.to_file_path() {
Some(vec![p]) Some(vec![p])
} else {
Some(vec![])
}
} else { } else {
Some(vec![]) // When the entrypoint doesn't have file: scheme (it's the remote
// script), then we don't auto discover config file.
None
} }
} else { } else {
// When the entrypoint doesn't have file: scheme (it's the remote Some(vec![])
// script), then we don't auto discover config file.
None
} }
} else {
Some(vec![])
} }
} else { _ => Some(vec![]),
Some(vec![])
} }
} }
@ -583,15 +583,15 @@ pub fn flags_from_vec(args: Vec<String>) -> clap::Result<Flags> {
if matches.is_present("unstable") { if matches.is_present("unstable") {
flags.unstable = true; flags.unstable = true;
} }
if matches.is_present("log-level") {
flags.log_level = match matches.value_of("log-level").unwrap() {
"debug" => Some(Level::Debug),
"info" => Some(Level::Info),
_ => unreachable!(),
};
}
if matches.is_present("quiet") { if matches.is_present("quiet") {
flags.log_level = Some(Level::Error); flags.log_level = Some(Level::Error);
} else {
match matches.value_of("log-level") {
Some("debug") => flags.log_level = Some(Level::Debug),
Some("info") => flags.log_level = Some(Level::Info),
_ => {}
}
} }
match matches.subcommand() { match matches.subcommand() {
@ -2556,11 +2556,9 @@ fn fmt_parse(flags: &mut Flags, matches: &clap::ArgMatches) {
} else { } else {
None None
}; };
let prose_wrap = if matches.is_present("options-prose-wrap") { let prose_wrap = matches
Some(matches.value_of("options-prose-wrap").unwrap().to_string()) .value_of("options-prose-wrap")
} else { .map(ToString::to_string);
None
};
flags.subcommand = DenoSubcommand::Fmt(FmtFlags { flags.subcommand = DenoSubcommand::Fmt(FmtFlags {
check: matches.is_present("check"), check: matches.is_present("check"),
@ -2597,12 +2595,7 @@ fn info_parse(flags: &mut Flags, matches: &clap::ArgMatches) {
fn install_parse(flags: &mut Flags, matches: &clap::ArgMatches) { fn install_parse(flags: &mut Flags, matches: &clap::ArgMatches) {
runtime_args_parse(flags, matches, true, true); runtime_args_parse(flags, matches, true, true);
let root = if matches.is_present("root") { let root = matches.value_of("root").map(PathBuf::from);
let install_root = matches.value_of("root").unwrap();
Some(PathBuf::from(install_root))
} else {
None
};
let force = matches.is_present("force"); let force = matches.is_present("force");
let name = matches.value_of("name").map(|s| s.to_string()); let name = matches.value_of("name").map(|s| s.to_string());
@ -2625,12 +2618,7 @@ fn install_parse(flags: &mut Flags, matches: &clap::ArgMatches) {
} }
fn uninstall_parse(flags: &mut Flags, matches: &clap::ArgMatches) { fn uninstall_parse(flags: &mut Flags, matches: &clap::ArgMatches) {
let root = if matches.is_present("root") { let root = matches.value_of("root").map(PathBuf::from);
let install_root = matches.value_of("root").unwrap();
Some(PathBuf::from(install_root))
} else {
None
};
let name = matches.value_of("name").unwrap().to_string(); let name = matches.value_of("name").unwrap().to_string();
flags.subcommand = DenoSubcommand::Uninstall(UninstallFlags { name, root }); flags.subcommand = DenoSubcommand::Uninstall(UninstallFlags { name, root });

View file

@ -219,7 +219,7 @@ mod ts {
// if it comes from an op crate, we were supplied with the path to the // if it comes from an op crate, we were supplied with the path to the
// file. // file.
let path = if let Some(op_crate_lib) = op_crate_libs.get(lib) { let path = if let Some(op_crate_lib) = op_crate_libs.get(lib) {
PathBuf::from(op_crate_lib).canonicalize().unwrap() PathBuf::from(op_crate_lib).canonicalize()?
// otherwise we are will generate the path ourself // otherwise we are will generate the path ourself
} else { } else {
path_dts.join(format!("lib.{}.d.ts", lib)) path_dts.join(format!("lib.{}.d.ts", lib))

View file

@ -8,4 +8,4 @@ use once_cell::sync::Lazy;
static CURRENT_STD_URL_STR: &str = "https://deno.land/std@0.172.0/"; static CURRENT_STD_URL_STR: &str = "https://deno.land/std@0.172.0/";
pub static CURRENT_STD_URL: Lazy<Url> = pub static CURRENT_STD_URL: Lazy<Url> =
Lazy::new(|| Url::parse(CURRENT_STD_URL_STR).unwrap()); Lazy::new(|| Url::parse(CURRENT_STD_URL_STR).expect("invalid std url"));

View file

@ -53,7 +53,7 @@ pub fn resolve_redirect_from_response(
) -> Result<Url, AnyError> { ) -> Result<Url, AnyError> {
debug_assert!(response.status().is_redirection()); debug_assert!(response.status().is_redirection());
if let Some(location) = response.headers().get(LOCATION) { if let Some(location) = response.headers().get(LOCATION) {
let location_string = location.to_str().unwrap(); let location_string = location.to_str()?;
log::debug!("Redirecting to {:?}...", &location_string); log::debug!("Redirecting to {:?}...", &location_string);
let new_url = resolve_url_from_location(request_url, location_string); let new_url = resolve_url_from_location(request_url, location_string);
Ok(new_url) Ok(new_url)

View file

@ -239,7 +239,7 @@ impl NpmResolution {
package_reqs: Vec<NpmPackageReq>, package_reqs: Vec<NpmPackageReq>,
) -> Result<(), AnyError> { ) -> Result<(), AnyError> {
// only allow one thread in here at a time // only allow one thread in here at a time
let _permit = self.update_semaphore.acquire().await.unwrap(); let _permit = self.update_semaphore.acquire().await?;
let snapshot = self.snapshot.read().clone(); let snapshot = self.snapshot.read().clone();
let snapshot = self let snapshot = self
@ -255,7 +255,7 @@ impl NpmResolution {
package_reqs: HashSet<NpmPackageReq>, package_reqs: HashSet<NpmPackageReq>,
) -> Result<(), AnyError> { ) -> Result<(), AnyError> {
// only allow one thread in here at a time // only allow one thread in here at a time
let _permit = self.update_semaphore.acquire().await.unwrap(); let _permit = self.update_semaphore.acquire().await?;
let snapshot = self.snapshot.read().clone(); let snapshot = self.snapshot.read().clone();
let has_removed_package = !snapshot let has_removed_package = !snapshot

View file

@ -133,7 +133,7 @@ impl ProcState {
// Add the extra files listed in the watch flag // Add the extra files listed in the watch flag
if let Some(watch_paths) = ps.options.watch_paths() { if let Some(watch_paths) = ps.options.watch_paths() {
files_to_watch_sender.send(watch_paths.clone()).unwrap(); files_to_watch_sender.send(watch_paths.clone())?;
} }
if let Ok(Some(import_map_path)) = ps if let Ok(Some(import_map_path)) = ps
@ -141,7 +141,7 @@ impl ProcState {
.resolve_import_map_specifier() .resolve_import_map_specifier()
.map(|ms| ms.and_then(|ref s| s.to_file_path().ok())) .map(|ms| ms.and_then(|ref s| s.to_file_path().ok()))
{ {
files_to_watch_sender.send(vec![import_map_path]).unwrap(); files_to_watch_sender.send(vec![import_map_path])?;
} }
Ok(ps) Ok(ps)
@ -625,9 +625,9 @@ impl ProcState {
// but sadly that's not the case due to missing APIs in V8. // but sadly that's not the case due to missing APIs in V8.
let is_repl = matches!(self.options.sub_command(), DenoSubcommand::Repl(_)); let is_repl = matches!(self.options.sub_command(), DenoSubcommand::Repl(_));
let referrer = if referrer.is_empty() && is_repl { let referrer = if referrer.is_empty() && is_repl {
deno_core::resolve_url_or_path("./$deno$repl.ts").unwrap() deno_core::resolve_url_or_path("./$deno$repl.ts")?
} else { } else {
deno_core::resolve_url_or_path(referrer).unwrap() deno_core::resolve_url_or_path(referrer)?
}; };
// FIXME(bartlomieju): this is another hack way to provide NPM specifier // FIXME(bartlomieju): this is another hack way to provide NPM specifier

View file

@ -184,14 +184,10 @@ impl CliMainWorker {
// Enable op call tracing in core to enable better debugging of op sanitizer // Enable op call tracing in core to enable better debugging of op sanitizer
// failures. // failures.
if self.ps.options.trace_ops() { if self.ps.options.trace_ops() {
self self.worker.js_runtime.execute_script(
.worker &located_script_name!(),
.js_runtime "Deno.core.enableOpCallTracing();",
.execute_script( )?;
&located_script_name!(),
"Deno.core.enableOpCallTracing();",
)
.unwrap();
} }
let mut maybe_coverage_collector = let mut maybe_coverage_collector =
@ -233,13 +229,10 @@ impl CliMainWorker {
) -> Result<(), AnyError> { ) -> Result<(), AnyError> {
self.enable_test(); self.enable_test();
self self.worker.execute_script(
.worker &located_script_name!(),
.execute_script( "Deno.core.enableOpCallTracing();",
&located_script_name!(), )?;
"Deno.core.enableOpCallTracing();",
)
.unwrap();
if mode != TestMode::Documentation { if mode != TestMode::Documentation {
// We execute the module module as a side module so that import.meta.main is not set. // We execute the module module as a side module so that import.meta.main is not set.

View file

@ -37,6 +37,8 @@ pub use sourcemap;
pub use url; pub use url;
pub use v8; pub use v8;
pub use deno_ops::op;
pub use crate::async_cancel::CancelFuture; pub use crate::async_cancel::CancelFuture;
pub use crate::async_cancel::CancelHandle; pub use crate::async_cancel::CancelHandle;
pub use crate::async_cancel::CancelTryFuture; pub use crate::async_cancel::CancelTryFuture;
@ -110,13 +112,12 @@ pub use crate::runtime::Snapshot;
pub use crate::runtime::V8_WRAPPER_OBJECT_INDEX; pub use crate::runtime::V8_WRAPPER_OBJECT_INDEX;
pub use crate::runtime::V8_WRAPPER_TYPE_INDEX; pub use crate::runtime::V8_WRAPPER_TYPE_INDEX;
pub use crate::source_map::SourceMapGetter; pub use crate::source_map::SourceMapGetter;
pub use deno_ops::op;
pub fn v8_version() -> &'static str { pub fn v8_version() -> &'static str {
v8::V8::get_version() v8::V8::get_version()
} }
/// An internal module re-exporting funcs used by the #[op] (`deno_ops`) macro /// An internal module re-exporting functions used by the #[op] (`deno_ops`) macro
#[doc(hidden)] #[doc(hidden)]
pub mod _ops { pub mod _ops {
pub use super::bindings::throw_type_error; pub use super::bindings::throw_type_error;

View file

@ -142,7 +142,7 @@ pub fn resolve_path(
.map_err(|_| ModuleResolutionError::InvalidPath(path_str.into()))? .map_err(|_| ModuleResolutionError::InvalidPath(path_str.into()))?
.join(path_str); .join(path_str);
let path = normalize_path(path); let path = normalize_path(path);
Url::from_file_path(path.clone()) Url::from_file_path(&path)
.map_err(|()| ModuleResolutionError::InvalidPath(path)) .map_err(|()| ModuleResolutionError::InvalidPath(path))
} }

View file

@ -5,6 +5,10 @@ mod in_memory_broadcast_channel;
pub use in_memory_broadcast_channel::InMemoryBroadcastChannel; pub use in_memory_broadcast_channel::InMemoryBroadcastChannel;
pub use in_memory_broadcast_channel::InMemoryBroadcastChannelResource; pub use in_memory_broadcast_channel::InMemoryBroadcastChannelResource;
use std::cell::RefCell;
use std::path::PathBuf;
use std::rc::Rc;
use async_trait::async_trait; use async_trait::async_trait;
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::include_js_files; use deno_core::include_js_files;
@ -14,9 +18,6 @@ use deno_core::OpState;
use deno_core::Resource; use deno_core::Resource;
use deno_core::ResourceId; use deno_core::ResourceId;
use deno_core::ZeroCopyBuf; use deno_core::ZeroCopyBuf;
use std::cell::RefCell;
use std::path::PathBuf;
use std::rc::Rc;
#[async_trait] #[async_trait]
pub trait BroadcastChannel: Clone { pub trait BroadcastChannel: Clone {

15
ext/cache/lib.rs vendored
View file

@ -1,8 +1,9 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
mod sqlite; use std::cell::RefCell;
use deno_core::ByteString; use std::path::PathBuf;
pub use sqlite::SqliteBackedCache; use std::rc::Rc;
use std::sync::Arc;
use async_trait::async_trait; use async_trait::async_trait;
use deno_core::error::AnyError; use deno_core::error::AnyError;
@ -10,15 +11,13 @@ use deno_core::include_js_files;
use deno_core::op; use deno_core::op;
use deno_core::serde::Deserialize; use deno_core::serde::Deserialize;
use deno_core::serde::Serialize; use deno_core::serde::Serialize;
use deno_core::ByteString;
use deno_core::Extension; use deno_core::Extension;
use deno_core::OpState; use deno_core::OpState;
use deno_core::Resource; use deno_core::Resource;
use deno_core::ResourceId; use deno_core::ResourceId;
mod sqlite;
use std::cell::RefCell; pub use sqlite::SqliteBackedCache;
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::Arc;
#[derive(Clone)] #[derive(Clone)]
pub struct CreateCache<C: Cache + 'static>(pub Arc<dyn Fn() -> C>); pub struct CreateCache<C: Cache + 'static>(pub Arc<dyn Fn() -> C>);

14
ext/cache/sqlite.rs vendored
View file

@ -1,5 +1,12 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
use std::borrow::Cow;
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::Arc;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use async_trait::async_trait; use async_trait::async_trait;
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::parking_lot::Mutex; use deno_core::parking_lot::Mutex;
@ -13,13 +20,6 @@ use rusqlite::OptionalExtension;
use tokio::io::AsyncReadExt; use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt; use tokio::io::AsyncWriteExt;
use std::borrow::Cow;
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::Arc;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use crate::deserialize_headers; use crate::deserialize_headers;
use crate::get_header; use crate::get_header;
use crate::serialize_headers; use crate::serialize_headers;

View file

@ -57,8 +57,7 @@ pub fn op_worker_sync_fetch(
let runtime = tokio::runtime::Builder::new_current_thread() let runtime = tokio::runtime::Builder::new_current_thread()
.enable_io() .enable_io()
.enable_time() .enable_time()
.build() .build()?;
.unwrap();
let handles: Vec<_> = scripts let handles: Vec<_> = scripts
.into_iter() .into_iter()

View file

@ -427,7 +427,7 @@ impl UnaryPermission<ReadDescriptor> {
self.prompt, self.prompt,
); );
if prompted { if prompted {
let resolved_path = resolve_from_cwd(path).unwrap(); let resolved_path = resolve_from_cwd(path)?;
if result.is_ok() { if result.is_ok() {
self.granted_list.insert(ReadDescriptor(resolved_path)); self.granted_list.insert(ReadDescriptor(resolved_path));
} else { } else {
@ -446,7 +446,7 @@ impl UnaryPermission<ReadDescriptor> {
display: &str, display: &str,
api_name: &str, api_name: &str,
) -> Result<(), AnyError> { ) -> Result<(), AnyError> {
let resolved_path = resolve_from_cwd(path).unwrap(); let resolved_path = resolve_from_cwd(path)?;
let (result, prompted) = self.query(Some(&resolved_path)).check( let (result, prompted) = self.query(Some(&resolved_path)).check(
self.name, self.name,
Some(api_name), Some(api_name),
@ -600,7 +600,7 @@ impl UnaryPermission<WriteDescriptor> {
self.prompt, self.prompt,
); );
if prompted { if prompted {
let resolved_path = resolve_from_cwd(path).unwrap(); let resolved_path = resolve_from_cwd(path)?;
if result.is_ok() { if result.is_ok() {
self.granted_list.insert(WriteDescriptor(resolved_path)); self.granted_list.insert(WriteDescriptor(resolved_path));
} else { } else {