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

refactor: remove usages of map_or / map_or_else (#18212)

These methods are confusing because the arguments are backwards. I feel
like they should have never been added to `Option<T>` and that clippy
should suggest rewriting to
`map(...).unwrap_or(...)`/`map(...).unwrap_or_else(|| ...)`

https://github.com/rust-lang/rfcs/issues/1025
This commit is contained in:
David Sherret 2023-03-15 17:46:36 -04:00 committed by GitHub
parent ca51f4f6c0
commit fb021d7cef
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
21 changed files with 179 additions and 141 deletions

View file

@ -174,7 +174,7 @@ fn run(
println!("{output}");
assert!(
server.try_wait()?.map_or(true, |s| s.success()),
server.try_wait()?.map(|s| s.success()).unwrap_or(true),
"server ended with error"
);

32
cli/cache/mod.rs vendored
View file

@ -129,25 +129,23 @@ impl Loader for FetchCacher {
file_fetcher
.fetch(&specifier, permissions)
.await
.map_or_else(
|err| {
if let Some(err) = err.downcast_ref::<std::io::Error>() {
if err.kind() == std::io::ErrorKind::NotFound {
return Ok(None);
}
} else if get_error_class_name(&err) == "NotFound" {
.map(|file| {
Ok(Some(LoadResponse::Module {
specifier: file.specifier,
maybe_headers: file.maybe_headers,
content: file.source,
}))
})
.unwrap_or_else(|err| {
if let Some(err) = err.downcast_ref::<std::io::Error>() {
if err.kind() == std::io::ErrorKind::NotFound {
return Ok(None);
}
Err(err)
},
|file| {
Ok(Some(LoadResponse::Module {
specifier: file.specifier,
maybe_headers: file.maybe_headers,
content: file.source,
}))
},
)
} else if get_error_class_name(&err) == "NotFound" {
return Ok(None);
}
Err(err)
})
}
.boxed()
}

View file

@ -202,7 +202,8 @@ impl CacheSemantics {
&& self
.cache_control
.max_stale
.map_or(true, |val| val > self.age() - self.max_age());
.map(|val| val > self.age() - self.max_age())
.unwrap_or(true);
if !allows_stale {
return false;
}

View file

@ -19,7 +19,7 @@ fn code_action_capabilities(
.as_ref()
.and_then(|it| it.code_action.as_ref())
.and_then(|it| it.code_action_literal_support.as_ref())
.map_or(CodeActionProviderCapability::Simple(true), |_| {
.map(|_| {
let mut code_action_kinds =
vec![CodeActionKind::QUICKFIX, CodeActionKind::REFACTOR];
code_action_kinds.extend(
@ -34,6 +34,7 @@ fn code_action_capabilities(
work_done_progress_options: Default::default(),
})
})
.unwrap_or(CodeActionProviderCapability::Simple(true))
}
pub fn server_capabilities(

View file

@ -490,7 +490,8 @@ impl Document {
pub fn script_version(&self) -> String {
self
.maybe_lsp_version()
.map_or_else(|| self.fs_version().to_string(), |v| v.to_string())
.map(|v| v.to_string())
.unwrap_or_else(|| self.fs_version().to_string())
}
pub fn is_diagnosable(&self) -> bool {
@ -901,15 +902,13 @@ impl Documents {
let mut file_system_docs = self.file_system_docs.lock();
file_system_docs.docs.remove(specifier)
})
.map_or_else(
|| {
Err(custom_error(
"NotFound",
format!("The specifier \"{specifier}\" was not found."),
))
},
Ok,
)?;
.map(Ok)
.unwrap_or_else(|| {
Err(custom_error(
"NotFound",
format!("The specifier \"{specifier}\" was not found."),
))
})?;
self.dirty = true;
let doc = doc.with_change(version, changes, self.get_resolver())?;
self.open_docs.insert(doc.specifier().clone(), doc.clone());

View file

@ -509,14 +509,14 @@ impl Inner {
&self,
specifier: &ModuleSpecifier,
) -> LspResult<AssetOrDocument> {
self.get_maybe_asset_or_document(specifier).map_or_else(
|| {
self
.get_maybe_asset_or_document(specifier)
.map(Ok)
.unwrap_or_else(|| {
Err(LspError::invalid_params(format!(
"Unable to find asset or document for: {specifier}"
)))
},
Ok,
)
})
}
/// Searches assets and documents for the provided specifier.
@ -1677,16 +1677,12 @@ impl Inner {
// Refactor
let start = line_index.offset_tsc(params.range.start)?;
let length = line_index.offset_tsc(params.range.end)? - start;
let only =
params
.context
.only
.as_ref()
.map_or(String::default(), |values| {
values
.first()
.map_or(String::default(), |v| v.as_str().to_owned())
});
let only = params
.context
.only
.as_ref()
.and_then(|values| values.first().map(|v| v.as_str().to_owned()))
.unwrap_or_default();
let req = tsc::RequestMethod::GetApplicableRefactors((
specifier.clone(),
tsc::TextSpan { start, length },

View file

@ -452,14 +452,11 @@ pub fn parse(
path = String::new();
}
let name = name.map_or_else(
|| {
let default = StringOrNumber::Number(key);
key += 1;
default
},
StringOrNumber::String,
);
let name = name.map(StringOrNumber::String).unwrap_or_else(|| {
let default = StringOrNumber::Number(key);
key += 1;
default
});
let prefix = if prefix.is_empty() {
None
} else {
@ -498,8 +495,10 @@ pub fn parse(
must_consume(&TokenType::Close, &mut tokens)?;
let name = maybe_name.clone().map_or_else(
|| {
let name = maybe_name
.clone()
.map(StringOrNumber::String)
.unwrap_or_else(|| {
if maybe_pattern.is_some() {
let default = StringOrNumber::Number(key);
key += 1;
@ -507,9 +506,7 @@ pub fn parse(
} else {
StringOrNumber::String("".to_string())
}
},
StringOrNumber::String,
);
});
let pattern = if maybe_name.is_some() && maybe_pattern.is_none() {
default_pattern.clone()
} else {
@ -570,11 +567,13 @@ pub fn tokens_to_regex(
let prefix = key
.prefix
.clone()
.map_or_else(|| "".to_string(), |s| escape_string(&s));
.map(|s| escape_string(&s))
.unwrap_or_default();
let suffix = key
.suffix
.clone()
.map_or_else(|| "".to_string(), |s| escape_string(&s));
.map(|s| escape_string(&s))
.unwrap_or_default();
if !key.pattern.is_empty() {
if !prefix.is_empty() || !suffix.is_empty() {

View file

@ -295,18 +295,20 @@ fn validate_config(config: &RegistryConfigurationJson) -> Result<(), AnyError> {
}
for registry in &config.registries {
let (_, keys) = string_to_regex(&registry.schema, None)?;
let key_names: Vec<String> = keys.map_or_else(Vec::new, |keys| {
keys
.iter()
.filter_map(|k| {
if let StringOrNumber::String(s) = &k.name {
Some(s.clone())
} else {
None
}
})
.collect()
});
let key_names: Vec<String> = keys
.map(|keys| {
keys
.iter()
.filter_map(|k| {
if let StringOrNumber::String(s) = &k.name {
Some(s.clone())
} else {
None
}
})
.collect()
})
.unwrap_or_default();
for key_name in &key_names {
if !registry
@ -664,18 +666,20 @@ impl ModuleRegistry {
})
.ok()?;
let mut i = tokens.len();
let last_key_name =
StringOrNumber::String(tokens.iter().last().map_or_else(
|| "".to_string(),
|t| {
let last_key_name = StringOrNumber::String(
tokens
.iter()
.last()
.map(|t| {
if let Token::Key(key) = t {
if let StringOrNumber::String(s) = &key.name {
return s.clone();
}
}
"".to_string()
},
));
})
.unwrap_or_default(),
);
loop {
let matcher = Matcher::new(&tokens[..i], None)
.map_err(|e| {

View file

@ -1024,15 +1024,19 @@ impl NavigationTree {
) -> bool {
let mut should_include = self.should_include_entry();
if !should_include
&& self.child_items.as_ref().map_or(true, |v| v.is_empty())
&& self
.child_items
.as_ref()
.map(|v| v.is_empty())
.unwrap_or(true)
{
return false;
}
let children = self
.child_items
.as_ref()
.map_or(&[] as &[NavigationTree], |v| v.as_slice());
.as_deref()
.unwrap_or(&[] as &[NavigationTree]);
for span in self.spans.iter() {
let range = TextRange::at(span.start.into(), span.length.into());
let mut symbol_children = Vec::<lsp::DocumentSymbol>::new();
@ -1514,7 +1518,8 @@ impl RefactorActionInfo {
.iter()
.find(|action| action.matches(&self.name));
maybe_match
.map_or(lsp::CodeActionKind::REFACTOR, |action| action.kind.clone())
.map(|action| action.kind.clone())
.unwrap_or(lsp::CodeActionKind::REFACTOR)
}
}

View file

@ -148,13 +148,14 @@ impl ModuleLoader for EmbeddedModuleLoader {
}
};
self.maybe_import_map_resolver.as_ref().map_or_else(
|| {
self
.maybe_import_map_resolver
.as_ref()
.map(|r| r.resolve(specifier, &referrer))
.unwrap_or_else(|| {
deno_core::resolve_import(specifier, referrer.as_str())
.map_err(|err| err.into())
},
|r| r.resolve(specifier, &referrer),
)
})
}
fn load(
@ -268,7 +269,10 @@ pub async fn run(
cpu_count: std::thread::available_parallelism()
.map(|p| p.get())
.unwrap_or(1),
debug_flag: metadata.log_level.map_or(false, |l| l == Level::Debug),
debug_flag: metadata
.log_level
.map(|l| l == Level::Debug)
.unwrap_or(false),
enable_testing_features: false,
locale: deno_core::v8::icu::get_language_tag(),
location: metadata.location,

View file

@ -356,7 +356,11 @@ fn merge_range_tree_children<'a>(
let mut matching_trees: Vec<&'a mut RangeTree<'a>> = Vec::new();
for (_parent_index, children) in child_forests.iter_mut().enumerate() {
let next_tree: Option<&'a mut RangeTree<'a>> = {
if children.peek().map_or(false, |tree| tree.start == *event) {
if children
.peek()
.map(|tree| tree.start == *event)
.unwrap_or(false)
{
children.next()
} else {
None

View file

@ -562,7 +562,10 @@ fn collect_coverages(
) -> Result<Vec<ScriptCoverage>, AnyError> {
let mut coverages: Vec<ScriptCoverage> = Vec::new();
let file_paths = FileCollector::new(|file_path| {
file_path.extension().map_or(false, |ext| ext == "json")
file_path
.extension()
.map(|ext| ext == "json")
.unwrap_or(false)
})
.ignore_git_folder()
.ignore_node_modules()

View file

@ -167,12 +167,11 @@ fn is_word_boundary(c: char) -> bool {
}
fn get_expr_from_line_at_pos(line: &str, cursor_pos: usize) -> &str {
let start = line[..cursor_pos]
.rfind(is_word_boundary)
.map_or_else(|| 0, |i| i);
let start = line[..cursor_pos].rfind(is_word_boundary).unwrap_or(0);
let end = line[cursor_pos..]
.rfind(is_word_boundary)
.map_or_else(|| cursor_pos, |i| cursor_pos + i);
.map(|i| cursor_pos + i)
.unwrap_or(cursor_pos);
let word = &line[start..end];
let word = word.strip_prefix(is_word_boundary).unwrap_or(word);

View file

@ -732,7 +732,8 @@ mod tests {
path
.file_name()
.and_then(|f| f.to_str())
.map_or(false, |f| !f.starts_with('.'))
.map(|f| !f.starts_with('.'))
.unwrap_or(false)
})
.add_ignore_paths(&[ignore_dir_path]);
@ -847,7 +848,8 @@ mod tests {
path
.file_name()
.and_then(|f| f.to_str())
.map_or(false, |f| !f.starts_with('.'))
.map(|f| !f.starts_with('.'))
.unwrap_or(false)
};
let result = collect_specifiers(

View file

@ -4,10 +4,10 @@ pub const GIT_COMMIT_HASH: &str = env!("GIT_COMMIT_HASH");
pub const TYPESCRIPT: &str = env!("TS_VERSION");
pub fn deno() -> String {
let semver = env!("CARGO_PKG_VERSION");
option_env!("DENO_CANARY").map_or(semver.to_string(), |_| {
format!("{}+{}", semver, &GIT_COMMIT_HASH[..7])
})
let version = env!("CARGO_PKG_VERSION");
option_env!("DENO_CANARY")
.map(|_| format!("{}+{}", version, &GIT_COMMIT_HASH[..7]))
.unwrap_or_else(|| version.to_string())
}
pub fn is_canary() -> bool {

View file

@ -510,7 +510,8 @@ async fn create_main_worker_internal(
debug_flag: ps
.options
.log_level()
.map_or(false, |l| l == log::Level::Debug),
.map(|l| l == log::Level::Debug)
.unwrap_or(false),
enable_testing_features: ps.options.enable_testing_features(),
locale: deno_core::v8::icu::get_language_tag(),
location: ps.options.location_flag().clone(),
@ -677,7 +678,8 @@ fn create_web_worker_callback(
debug_flag: ps
.options
.log_level()
.map_or(false, |l| l == log::Level::Debug),
.map(|l| l == log::Level::Debug)
.unwrap_or(false),
enable_testing_features: ps.options.enable_testing_features(),
locale: deno_core::v8::icu::get_language_tag(),
location: Some(args.main_module.clone()),

View file

@ -1410,13 +1410,16 @@ where
name,
is_file: entry
.file_type()
.map_or(false, |file_type| file_type.is_file()),
.map(|file_type| file_type.is_file())
.unwrap_or(false),
is_directory: entry
.file_type()
.map_or(false, |file_type| file_type.is_dir()),
.map(|file_type| file_type.is_dir())
.unwrap_or(false),
is_symlink: entry
.file_type()
.map_or(false, |file_type| file_type.is_symlink()),
.map(|file_type| file_type.is_symlink())
.unwrap_or(false),
})
} else {
None
@ -1457,13 +1460,16 @@ where
name,
is_file: entry
.file_type()
.map_or(false, |file_type| file_type.is_file()),
.map(|file_type| file_type.is_file())
.unwrap_or(false),
is_directory: entry
.file_type()
.map_or(false, |file_type| file_type.is_dir()),
.map(|file_type| file_type.is_dir())
.unwrap_or(false),
is_symlink: entry
.file_type()
.map_or(false, |file_type| file_type.is_symlink()),
.map(|file_type| file_type.is_symlink())
.unwrap_or(false),
})
} else {
None

View file

@ -553,7 +553,11 @@ fn req_url(
.to_string(),
),
};
let path = req.uri().path_and_query().map_or("/", |p| p.as_str());
let path = req
.uri()
.path_and_query()
.map(|p| p.as_str())
.unwrap_or("/");
[scheme, "://", &host, path].concat()
}

View file

@ -252,10 +252,9 @@ pub async fn op_webgpu_request_adapter(
) -> Result<GpuAdapterDeviceOrErr, AnyError> {
let mut state = state.borrow_mut();
check_unstable(&state, "navigator.gpu.requestAdapter");
let backends = std::env::var("DENO_WEBGPU_BACKEND").map_or_else(
|_| wgpu_types::Backends::all(),
|s| wgpu_core::instance::parse_backends_from_comma_list(&s),
);
let backends = std::env::var("DENO_WEBGPU_BACKEND")
.map(|s| wgpu_core::instance::parse_backends_from_comma_list(&s))
.unwrap_or_else(|_| wgpu_types::Backends::all());
let instance = if let Some(instance) = state.try_borrow::<Instance>() {
instance
} else {

View file

@ -45,7 +45,8 @@ pub fn format_location(frame: &JsStackFrame) -> String {
let _internal = frame
.file_name
.as_ref()
.map_or(false, |f| f.starts_with("ext:"));
.map(|f| f.starts_with("ext:"))
.unwrap_or(false);
if frame.is_native {
return cyan("native").to_string();
}
@ -73,7 +74,8 @@ fn format_frame(frame: &JsStackFrame) -> String {
let _internal = frame
.file_name
.as_ref()
.map_or(false, |f| f.starts_with("ext:"));
.map(|f| f.starts_with("ext:"))
.unwrap_or(false);
let is_method_call =
!(frame.is_top_level.unwrap_or_default() || frame.is_constructor);
let mut result = String::new();
@ -252,7 +254,10 @@ fn format_js_error_inner(
if let Some(aggregated) = &js_error.aggregated {
let aggregated_message = format_aggregated_error(
aggregated,
circular.as_ref().map_or(0, |circular| circular.index),
circular
.as_ref()
.map(|circular| circular.index)
.unwrap_or(0),
);
s.push_str(&aggregated_message);
}
@ -274,9 +279,12 @@ fn format_js_error_inner(
write!(s, "\n at {}", format_frame(frame)).unwrap();
}
if let Some(cause) = &js_error.cause {
let is_caused_by_circular = circular.as_ref().map_or(false, |circular| {
errors_are_equal_without_cause(circular.reference.from, js_error)
});
let is_caused_by_circular = circular
.as_ref()
.map(|circular| {
errors_are_equal_without_cause(circular.reference.from, js_error)
})
.unwrap_or(false);
let error_string = if is_caused_by_circular {
cyan(format!("[Circular *{}]", circular.unwrap().index)).to_string()

View file

@ -70,7 +70,9 @@ impl PermissionState {
format!(
"{} access{}",
name,
info().map_or(String::new(), |info| { format!(" to {info}") }),
info()
.map(|info| { format!(" to {info}") })
.unwrap_or_default(),
)
}
@ -114,7 +116,9 @@ impl PermissionState {
let msg = format!(
"{} access{}",
name,
info().map_or(String::new(), |info| { format!(" to {info}") }),
info()
.map(|info| { format!(" to {info}") })
.unwrap_or_default(),
);
match permission_prompt(&msg, name, api_name, true) {
PromptResponse::Allow => {
@ -1569,14 +1573,14 @@ impl Permissions {
) -> Result<UnaryPermission<NetDescriptor>, AnyError> {
Ok(UnaryPermission::<NetDescriptor> {
global_state: global_state_from_option(state),
granted_list: state.as_ref().map_or_else(
|| Ok(HashSet::new()),
|v| {
granted_list: state
.as_ref()
.map(|v| {
v.iter()
.map(|x| NetDescriptor::from_str(x))
.collect::<Result<HashSet<NetDescriptor>, AnyError>>()
},
)?,
})
.unwrap_or_else(|| Ok(HashSet::new()))?,
prompt,
..Default::default()
})
@ -1588,9 +1592,9 @@ impl Permissions {
) -> Result<UnaryPermission<EnvDescriptor>, AnyError> {
Ok(UnaryPermission::<EnvDescriptor> {
global_state: global_state_from_option(state),
granted_list: state.as_ref().map_or_else(
|| Ok(HashSet::new()),
|v| {
granted_list: state
.as_ref()
.map(|v| {
v.iter()
.map(|x| {
if x.is_empty() {
@ -1600,8 +1604,8 @@ impl Permissions {
}
})
.collect()
},
)?,
})
.unwrap_or_else(|| Ok(HashSet::new()))?,
prompt,
..Default::default()
})
@ -1613,9 +1617,9 @@ impl Permissions {
) -> Result<UnaryPermission<SysDescriptor>, AnyError> {
Ok(UnaryPermission::<SysDescriptor> {
global_state: global_state_from_option(state),
granted_list: state.as_ref().map_or_else(
|| Ok(HashSet::new()),
|v| {
granted_list: state
.as_ref()
.map(|v| {
v.iter()
.map(|x| {
if x.is_empty() {
@ -1625,8 +1629,8 @@ impl Permissions {
}
})
.collect()
},
)?,
})
.unwrap_or_else(|| Ok(HashSet::new()))?,
prompt,
..Default::default()
})
@ -1638,9 +1642,9 @@ impl Permissions {
) -> Result<UnaryPermission<RunDescriptor>, AnyError> {
Ok(UnaryPermission::<RunDescriptor> {
global_state: global_state_from_option(state),
granted_list: state.as_ref().map_or_else(
|| Ok(HashSet::new()),
|v| {
granted_list: state
.as_ref()
.map(|v| {
v.iter()
.map(|x| {
if x.is_empty() {
@ -1650,8 +1654,8 @@ impl Permissions {
}
})
.collect()
},
)?,
})
.unwrap_or_else(|| Ok(HashSet::new()))?,
prompt,
..Default::default()
})