lints: A bunch of extra style lint fixes (#36568)

- **lints: Fix 'doc_lazy_continuation'**
- **lints: Fix 'doc_overindented_list_items'**
- **inherent_to_string and io_other_error**
- **Some more lint fixes**
- **lints: enable bool_assert_comparison, match_like_matches_macro and
wrong_self_convention**


Release Notes:

- N/A
This commit is contained in:
Piotr Osiewicz 2025-08-20 12:05:58 +02:00 committed by GitHub
parent a32a264508
commit cf7c64d77f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
92 changed files with 277 additions and 345 deletions

View file

@ -822,15 +822,21 @@ single_range_in_vec_init = "allow"
style = { level = "allow", priority = -1 }
# Temporary list of style lints that we've fixed so far.
bool_assert_comparison = "warn"
comparison_to_empty = "warn"
doc_lazy_continuation = "warn"
doc_overindented_list_items = "warn"
inherent_to_string = "warn"
for_kv_map = "warn"
into_iter_on_ref = "warn"
io_other_error = "warn"
iter_cloned_collect = "warn"
iter_next_slice = "warn"
iter_nth = "warn"
iter_nth_zero = "warn"
iter_skip_next = "warn"
let_and_return = "warn"
match_like_matches_macro = "warn"
module_inception = { level = "deny" }
question_mark = { level = "deny" }
single_match = "warn"
@ -846,6 +852,7 @@ needless_return = { level = "warn" }
unnecessary_mut_passed = {level = "warn"}
unnecessary_map_or = { level = "warn" }
unused_unit = "warn"
wrong_self_convention = "warn"
# Individual rules that have violations in the codebase:
type_complexity = "allow"

View file

@ -254,10 +254,9 @@ impl HistoryStore {
}
pub fn remove_recently_opened_thread(&mut self, id: ThreadId, cx: &mut Context<Self>) {
self.recently_opened_entries.retain(|entry| match entry {
HistoryEntryId::Thread(thread_id) if thread_id == &id => false,
_ => true,
});
self.recently_opened_entries.retain(
|entry| !matches!(entry, HistoryEntryId::Thread(thread_id) if thread_id == &id),
);
self.save_recently_opened_entries(cx);
}

View file

@ -181,7 +181,7 @@ impl Message {
}
}
pub fn to_string(&self) -> String {
pub fn to_message_content(&self) -> String {
let mut result = String::new();
if !self.loaded_context.text.is_empty() {
@ -2823,7 +2823,7 @@ impl Thread {
let message_content = self
.message(message_id)
.map(|msg| msg.to_string())
.map(|msg| msg.to_message_content())
.unwrap_or_default();
cx.background_spawn(async move {

View file

@ -312,10 +312,9 @@ impl HistoryStore {
}
pub fn remove_recently_opened_thread(&mut self, id: acp::SessionId, cx: &mut Context<Self>) {
self.recently_opened_entries.retain(|entry| match entry {
HistoryEntryId::AcpThread(thread_id) if thread_id == &id => false,
_ => true,
});
self.recently_opened_entries.retain(
|entry| !matches!(entry, HistoryEntryId::AcpThread(thread_id) if thread_id == &id),
);
self.save_recently_opened_entries(cx);
}

View file

@ -505,9 +505,8 @@ impl Settings for AgentSettings {
}
}
debug_assert_eq!(
sources.default.always_allow_tool_actions.unwrap_or(false),
false,
debug_assert!(
!sources.default.always_allow_tool_actions.unwrap_or(false),
"For security, agent.always_allow_tool_actions should always be false in default.json. If it's true, that is a bug that should be fixed!"
);

View file

@ -1765,7 +1765,7 @@ impl ActiveThread {
.thread
.read(cx)
.message(message_id)
.map(|msg| msg.to_string())
.map(|msg| msg.to_message_content())
.unwrap_or_default();
telemetry::event!(

View file

@ -668,10 +668,10 @@ mod tests {
);
let parsed_model = model_input.parse(cx).unwrap();
assert_eq!(parsed_model.capabilities.tools, true);
assert_eq!(parsed_model.capabilities.images, false);
assert_eq!(parsed_model.capabilities.parallel_tool_calls, false);
assert_eq!(parsed_model.capabilities.prompt_cache_key, false);
assert!(parsed_model.capabilities.tools);
assert!(!parsed_model.capabilities.images);
assert!(!parsed_model.capabilities.parallel_tool_calls);
assert!(!parsed_model.capabilities.prompt_cache_key);
});
}
@ -693,10 +693,10 @@ mod tests {
model_input.capabilities.supports_prompt_cache_key = ToggleState::Unselected;
let parsed_model = model_input.parse(cx).unwrap();
assert_eq!(parsed_model.capabilities.tools, false);
assert_eq!(parsed_model.capabilities.images, false);
assert_eq!(parsed_model.capabilities.parallel_tool_calls, false);
assert_eq!(parsed_model.capabilities.prompt_cache_key, false);
assert!(!parsed_model.capabilities.tools);
assert!(!parsed_model.capabilities.images);
assert!(!parsed_model.capabilities.parallel_tool_calls);
assert!(!parsed_model.capabilities.prompt_cache_key);
});
}
@ -719,10 +719,10 @@ mod tests {
let parsed_model = model_input.parse(cx).unwrap();
assert_eq!(parsed_model.name, "somemodel");
assert_eq!(parsed_model.capabilities.tools, true);
assert_eq!(parsed_model.capabilities.images, false);
assert_eq!(parsed_model.capabilities.parallel_tool_calls, true);
assert_eq!(parsed_model.capabilities.prompt_cache_key, false);
assert!(parsed_model.capabilities.tools);
assert!(!parsed_model.capabilities.images);
assert!(parsed_model.capabilities.parallel_tool_calls);
assert!(!parsed_model.capabilities.prompt_cache_key);
});
}

View file

@ -1436,6 +1436,6 @@ impl SlashCommand for FakeSlashCommand {
sections: vec![],
run_commands_in_text: false,
}
.to_event_stream()))
.into_event_stream()))
}
}

View file

@ -161,7 +161,7 @@ impl SlashCommandOutput {
}
/// Returns this [`SlashCommandOutput`] as a stream of [`SlashCommandEvent`]s.
pub fn to_event_stream(mut self) -> BoxStream<'static, Result<SlashCommandEvent>> {
pub fn into_event_stream(mut self) -> BoxStream<'static, Result<SlashCommandEvent>> {
self.ensure_valid_section_ranges();
let mut events = Vec::new();
@ -363,7 +363,7 @@ mod tests {
run_commands_in_text: false,
};
let events = output.clone().to_event_stream().collect::<Vec<_>>().await;
let events = output.clone().into_event_stream().collect::<Vec<_>>().await;
let events = events
.into_iter()
.filter_map(|event| event.ok())
@ -386,7 +386,7 @@ mod tests {
);
let new_output =
SlashCommandOutput::from_event_stream(output.clone().to_event_stream())
SlashCommandOutput::from_event_stream(output.clone().into_event_stream())
.await
.unwrap();
@ -415,7 +415,7 @@ mod tests {
run_commands_in_text: false,
};
let events = output.clone().to_event_stream().collect::<Vec<_>>().await;
let events = output.clone().into_event_stream().collect::<Vec<_>>().await;
let events = events
.into_iter()
.filter_map(|event| event.ok())
@ -452,7 +452,7 @@ mod tests {
);
let new_output =
SlashCommandOutput::from_event_stream(output.clone().to_event_stream())
SlashCommandOutput::from_event_stream(output.clone().into_event_stream())
.await
.unwrap();
@ -493,7 +493,7 @@ mod tests {
run_commands_in_text: false,
};
let events = output.clone().to_event_stream().collect::<Vec<_>>().await;
let events = output.clone().into_event_stream().collect::<Vec<_>>().await;
let events = events
.into_iter()
.filter_map(|event| event.ok())
@ -562,7 +562,7 @@ mod tests {
);
let new_output =
SlashCommandOutput::from_event_stream(output.clone().to_event_stream())
SlashCommandOutput::from_event_stream(output.clone().into_event_stream())
.await
.unwrap();

View file

@ -166,7 +166,7 @@ impl SlashCommand for ExtensionSlashCommand {
.collect(),
run_commands_in_text: false,
}
.to_event_stream())
.into_event_stream())
})
}
}

View file

@ -150,7 +150,7 @@ impl SlashCommand for CargoWorkspaceSlashCommand {
}],
run_commands_in_text: false,
}
.to_event_stream())
.into_event_stream())
})
});
output.unwrap_or_else(|error| Task::ready(Err(error)))

View file

@ -191,7 +191,7 @@ impl SlashCommand for ContextServerSlashCommand {
text: prompt,
run_commands_in_text: false,
}
.to_event_stream())
.into_event_stream())
})
} else {
Task::ready(Err(anyhow!("Context server not found")))

View file

@ -85,7 +85,7 @@ impl SlashCommand for DefaultSlashCommand {
text,
run_commands_in_text: true,
}
.to_event_stream())
.into_event_stream())
})
}
}

View file

@ -118,7 +118,7 @@ impl SlashCommand for DeltaSlashCommand {
}
anyhow::ensure!(changes_detected, "no new changes detected");
Ok(output.to_event_stream())
Ok(output.into_event_stream())
})
}
}

View file

@ -189,7 +189,7 @@ impl SlashCommand for DiagnosticsSlashCommand {
window.spawn(cx, async move |_| {
task.await?
.map(|output| output.to_event_stream())
.map(|output| output.into_event_stream())
.context("No diagnostics found")
})
}

View file

@ -177,7 +177,7 @@ impl SlashCommand for FetchSlashCommand {
}],
run_commands_in_text: false,
}
.to_event_stream())
.into_event_stream())
})
}
}

View file

@ -371,7 +371,7 @@ fn collect_files(
&mut output,
)
.log_err();
let mut buffer_events = output.to_event_stream();
let mut buffer_events = output.into_event_stream();
while let Some(event) = buffer_events.next().await {
events_tx.unbounded_send(event)?;
}

View file

@ -66,6 +66,6 @@ impl SlashCommand for NowSlashCommand {
}],
run_commands_in_text: false,
}
.to_event_stream()))
.into_event_stream()))
}
}

View file

@ -117,7 +117,7 @@ impl SlashCommand for PromptSlashCommand {
}],
run_commands_in_text: true,
}
.to_event_stream())
.into_event_stream())
})
}
}

View file

@ -92,7 +92,7 @@ impl SlashCommand for OutlineSlashCommand {
text: outline_text,
run_commands_in_text: false,
}
.to_event_stream())
.into_event_stream())
})
});

View file

@ -157,7 +157,7 @@ impl SlashCommand for TabSlashCommand {
for (full_path, buffer, _) in tab_items_search.await? {
append_buffer_to_output(&buffer, full_path.as_deref(), &mut output).log_err();
}
Ok(output.to_event_stream())
Ok(output.into_event_stream())
})
}
}

View file

@ -128,23 +128,20 @@ mod windows_impl {
#[test]
fn test_parse_args() {
// launch can be specified via two separate arguments
assert_eq!(parse_args(["--launch".into(), "true".into()]).launch, true);
assert_eq!(
parse_args(["--launch".into(), "false".into()]).launch,
false
);
assert!(parse_args(["--launch".into(), "true".into()]).launch);
assert!(!parse_args(["--launch".into(), "false".into()]).launch);
// launch can be specified via one single argument
assert_eq!(parse_args(["--launch=true".into()]).launch, true);
assert_eq!(parse_args(["--launch=false".into()]).launch, false);
assert!(parse_args(["--launch=true".into()]).launch);
assert!(!parse_args(["--launch=false".into()]).launch);
// launch defaults to true on no arguments
assert_eq!(parse_args([]).launch, true);
assert!(parse_args([]).launch);
// launch defaults to true on invalid arguments
assert_eq!(parse_args(["--launch".into()]).launch, true);
assert_eq!(parse_args(["--launch=".into()]).launch, true);
assert_eq!(parse_args(["--launch=invalid".into()]).launch, true);
assert!(parse_args(["--launch".into()]).launch);
assert!(parse_args(["--launch=".into()]).launch);
assert!(parse_args(["--launch=invalid".into()]).launch);
}
}
}

View file

@ -90,11 +90,7 @@ pub(crate) const JOBS: [Job; 2] = [
std::thread::sleep(Duration::from_millis(1000));
if let Ok(config) = std::env::var("ZED_AUTO_UPDATE") {
match config.as_str() {
"err" => Err(std::io::Error::new(
std::io::ErrorKind::Other,
"Simulated error",
))
.context("Anyhow!"),
"err" => Err(std::io::Error::other("Simulated error")).context("Anyhow!"),
_ => panic!("Unknown ZED_AUTO_UPDATE value: {}", config),
}
} else {
@ -105,11 +101,7 @@ pub(crate) const JOBS: [Job; 2] = [
std::thread::sleep(Duration::from_millis(1000));
if let Ok(config) = std::env::var("ZED_AUTO_UPDATE") {
match config.as_str() {
"err" => Err(std::io::Error::new(
std::io::ErrorKind::Other,
"Simulated error",
))
.context("Anyhow!"),
"err" => Err(std::io::Error::other("Simulated error")).context("Anyhow!"),
_ => panic!("Unknown ZED_AUTO_UPDATE value: {}", config),
}
} else {

View file

@ -41,7 +41,7 @@ impl std::fmt::Display for ChannelId {
pub struct ProjectId(pub u64);
impl ProjectId {
pub fn to_proto(&self) -> u64 {
pub fn to_proto(self) -> u64 {
self.0
}
}

View file

@ -685,7 +685,7 @@ impl LocalSettingsKind {
}
}
pub fn to_proto(&self) -> proto::LocalSettingsKind {
pub fn to_proto(self) -> proto::LocalSettingsKind {
match self {
Self::Settings => proto::LocalSettingsKind::Settings,
Self::Tasks => proto::LocalSettingsKind::Tasks,

View file

@ -3208,7 +3208,7 @@ async fn test_fs_operations(
})
.await
.unwrap()
.to_included()
.into_included()
.unwrap();
worktree_a.read_with(cx_a, |worktree, _| {
@ -3237,7 +3237,7 @@ async fn test_fs_operations(
})
.await
.unwrap()
.to_included()
.into_included()
.unwrap();
worktree_a.read_with(cx_a, |worktree, _| {
@ -3266,7 +3266,7 @@ async fn test_fs_operations(
})
.await
.unwrap()
.to_included()
.into_included()
.unwrap();
worktree_a.read_with(cx_a, |worktree, _| {
@ -3295,7 +3295,7 @@ async fn test_fs_operations(
})
.await
.unwrap()
.to_included()
.into_included()
.unwrap();
project_b
@ -3304,7 +3304,7 @@ async fn test_fs_operations(
})
.await
.unwrap()
.to_included()
.into_included()
.unwrap();
project_b
@ -3313,7 +3313,7 @@ async fn test_fs_operations(
})
.await
.unwrap()
.to_included()
.into_included()
.unwrap();
worktree_a.read_with(cx_a, |worktree, _| {

View file

@ -897,7 +897,7 @@ impl TestClient {
let window = cx.update(|cx| cx.active_window().unwrap().downcast::<Workspace>().unwrap());
let entity = window.root(cx).unwrap();
let cx = VisualTestContext::from_window(*window.deref(), cx).as_mut();
let cx = VisualTestContext::from_window(*window.deref(), cx).into_mut();
// it might be nice to try and cleanup these at the end of each test.
(entity, cx)
}

View file

@ -1821,10 +1821,10 @@ impl CollabPanel {
}
fn select_channel_editor(&mut self) {
self.selection = self.entries.iter().position(|entry| match entry {
ListEntry::ChannelEditor { .. } => true,
_ => false,
});
self.selection = self
.entries
.iter()
.position(|entry| matches!(entry, ListEntry::ChannelEditor { .. }));
}
fn new_subchannel(

View file

@ -67,11 +67,7 @@ pub(crate) struct Client {
pub(crate) struct ContextServerId(pub Arc<str>);
fn is_null_value<T: Serialize>(value: &T) -> bool {
if let Ok(Value::Null) = serde_json::to_value(value) {
true
} else {
false
}
matches!(serde_json::to_value(value), Ok(Value::Null))
}
#[derive(Serialize, Deserialize)]

View file

@ -23,7 +23,7 @@ impl SessionId {
Self(client_id as u32)
}
pub fn to_proto(&self) -> u64 {
pub fn to_proto(self) -> u64 {
self.0 as u64
}
}

View file

@ -2868,12 +2868,7 @@ mod tests {
1,
blocks
.iter()
.filter(|(_, block)| {
match block {
Block::FoldedBuffer { .. } => true,
_ => false,
}
})
.filter(|(_, block)| { matches!(block, Block::FoldedBuffer { .. }) })
.count(),
"Should have one folded block, producing a header of the second buffer"
);

View file

@ -782,10 +782,7 @@ impl MinimapVisibility {
}
fn disabled(&self) -> bool {
match *self {
Self::Disabled => true,
_ => false,
}
matches!(*self, Self::Disabled)
}
fn settings_visibility(&self) -> bool {

View file

@ -293,7 +293,7 @@ impl FollowableItem for Editor {
EditorEvent::ExcerptsRemoved { ids, .. } => {
update
.deleted_excerpts
.extend(ids.iter().map(ExcerptId::to_proto));
.extend(ids.iter().copied().map(ExcerptId::to_proto));
true
}
EditorEvent::ScrollPositionChanged { autoscroll, .. } if !autoscroll => {

View file

@ -67,10 +67,7 @@ impl ScrollAmount {
}
pub fn is_full_page(&self) -> bool {
match self {
ScrollAmount::Page(count) if count.abs() == 1.0 => true,
_ => false,
}
matches!(self, ScrollAmount::Page(count) if count.abs() == 1.0)
}
pub fn direction(&self) -> ScrollDirection {

View file

@ -300,6 +300,7 @@ impl EditorLspTestContext {
self.to_lsp_range(ranges[0].clone())
}
#[expect(clippy::wrong_self_convention, reason = "This is test code")]
pub fn to_lsp_range(&mut self, range: Range<usize>) -> lsp::Range {
let snapshot = self.update_editor(|editor, window, cx| editor.snapshot(window, cx));
let start_point = range.start.to_point(&snapshot.buffer_snapshot);
@ -326,6 +327,7 @@ impl EditorLspTestContext {
})
}
#[expect(clippy::wrong_self_convention, reason = "This is test code")]
pub fn to_lsp(&mut self, offset: usize) -> lsp::Position {
let snapshot = self.update_editor(|editor, window, cx| editor.snapshot(window, cx));
let point = offset.to_point(&snapshot.buffer_snapshot);

View file

@ -335,7 +335,7 @@ impl ExampleContext {
for message in thread.messages().skip(message_count_before) {
messages.push(Message {
_role: message.role,
text: message.to_string(),
text: message.to_message_content(),
tool_use: thread
.tool_uses_for_message(message.id, cx)
.into_iter()

View file

@ -1192,7 +1192,7 @@ mod test {
output.analysis,
Some("The model did a good job but there were still compilations errors.".into())
);
assert_eq!(output.passed, true);
assert!(output.passed);
let response = r#"
Text around ignored
@ -1212,6 +1212,6 @@ mod test {
output.analysis,
Some("Failed to compile:\n- Error 1\n- Error 2".into())
);
assert_eq!(output.passed, false);
assert!(!output.passed);
}
}

View file

@ -232,10 +232,10 @@ pub trait Extension: Send + Sync {
///
/// To work through a real-world example, take a `cargo run` task and a hypothetical `cargo` locator:
/// 1. We may need to modify the task; in this case, it is problematic that `cargo run` spawns a binary. We should turn `cargo run` into a debug scenario with
/// `cargo build` task. This is the decision we make at `dap_locator_create_scenario` scope.
/// `cargo build` task. This is the decision we make at `dap_locator_create_scenario` scope.
/// 2. Then, after the build task finishes, we will run `run_dap_locator` of the locator that produced the build task to find the program to be debugged. This function
/// should give us a debugger-agnostic configuration for launching a debug target (that we end up resolving with [`Extension::dap_config_to_scenario`]). It's almost as if the user
/// found the artifact path by themselves.
/// should give us a debugger-agnostic configuration for launching a debug target (that we end up resolving with [`Extension::dap_config_to_scenario`]). It's almost as if the user
/// found the artifact path by themselves.
///
/// Note that you're not obliged to use build tasks with locators. Specifically, it is sufficient to provide a debug configuration directly in the return value of
/// `dap_locator_create_scenario` if you're able to do that. Make sure to not fill out `build` field in that case, as that will prevent Zed from running second phase of resolution in such case.

View file

@ -153,17 +153,11 @@ impl FileStatus {
}
pub fn is_conflicted(self) -> bool {
match self {
FileStatus::Unmerged { .. } => true,
_ => false,
}
matches!(self, FileStatus::Unmerged { .. })
}
pub fn is_ignored(self) -> bool {
match self {
FileStatus::Ignored => true,
_ => false,
}
matches!(self, FileStatus::Ignored)
}
pub fn has_changes(&self) -> bool {
@ -176,40 +170,31 @@ impl FileStatus {
pub fn is_modified(self) -> bool {
match self {
FileStatus::Tracked(tracked) => match (tracked.index_status, tracked.worktree_status) {
(StatusCode::Modified, _) | (_, StatusCode::Modified) => true,
_ => false,
},
FileStatus::Tracked(tracked) => matches!(
(tracked.index_status, tracked.worktree_status),
(StatusCode::Modified, _) | (_, StatusCode::Modified)
),
_ => false,
}
}
pub fn is_created(self) -> bool {
match self {
FileStatus::Tracked(tracked) => match (tracked.index_status, tracked.worktree_status) {
(StatusCode::Added, _) | (_, StatusCode::Added) => true,
_ => false,
},
FileStatus::Tracked(tracked) => matches!(
(tracked.index_status, tracked.worktree_status),
(StatusCode::Added, _) | (_, StatusCode::Added)
),
FileStatus::Untracked => true,
_ => false,
}
}
pub fn is_deleted(self) -> bool {
match self {
FileStatus::Tracked(tracked) => match (tracked.index_status, tracked.worktree_status) {
(StatusCode::Deleted, _) | (_, StatusCode::Deleted) => true,
_ => false,
},
_ => false,
}
matches!(self, FileStatus::Tracked(tracked) if matches!((tracked.index_status, tracked.worktree_status), (StatusCode::Deleted, _) | (_, StatusCode::Deleted)))
}
pub fn is_untracked(self) -> bool {
match self {
FileStatus::Untracked => true,
_ => false,
}
matches!(self, FileStatus::Untracked)
}
pub fn summary(self) -> GitSummary {

View file

@ -1070,8 +1070,7 @@ pub struct ProjectDiffEmptyState {
impl RenderOnce for ProjectDiffEmptyState {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let status_against_remote = |ahead_by: usize, behind_by: usize| -> bool {
match self.current_branch {
Some(Branch {
matches!(self.current_branch, Some(Branch {
upstream:
Some(Upstream {
tracking:
@ -1081,9 +1080,7 @@ impl RenderOnce for ProjectDiffEmptyState {
..
}),
..
}) if (ahead > 0) == (ahead_by > 0) && (behind > 0) == (behind_by > 0) => true,
_ => false,
}
}) if (ahead > 0) == (ahead_by > 0) && (behind > 0) == (behind_by > 0))
};
let change_count = |current_branch: &Branch| -> (usize, usize) {

View file

@ -73,18 +73,18 @@ macro_rules! actions {
/// - `name = "ActionName"` overrides the action's name. This must not contain `::`.
///
/// - `no_json` causes the `build` method to always error and `action_json_schema` to return `None`,
/// and allows actions not implement `serde::Serialize` and `schemars::JsonSchema`.
/// and allows actions not implement `serde::Serialize` and `schemars::JsonSchema`.
///
/// - `no_register` skips registering the action. This is useful for implementing the `Action` trait
/// while not supporting invocation by name or JSON deserialization.
/// while not supporting invocation by name or JSON deserialization.
///
/// - `deprecated_aliases = ["editor::SomeAction"]` specifies deprecated old names for the action.
/// These action names should *not* correspond to any actions that are registered. These old names
/// can then still be used to refer to invoke this action. In Zed, the keymap JSON schema will
/// accept these old names and provide warnings.
/// These action names should *not* correspond to any actions that are registered. These old names
/// can then still be used to refer to invoke this action. In Zed, the keymap JSON schema will
/// accept these old names and provide warnings.
///
/// - `deprecated = "Message about why this action is deprecation"` specifies a deprecation message.
/// In Zed, the keymap JSON schema will cause this to be displayed as a warning.
/// In Zed, the keymap JSON schema will cause this to be displayed as a warning.
///
/// # Manual Implementation
///

View file

@ -192,6 +192,7 @@ impl TestAppContext {
&self.foreground_executor
}
#[expect(clippy::wrong_self_convention)]
fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
let mut cx = self.app.borrow_mut();
cx.new(build_entity)
@ -244,7 +245,7 @@ impl TestAppContext {
)
.unwrap();
drop(cx);
let cx = VisualTestContext::from_window(*window.deref(), self).as_mut();
let cx = VisualTestContext::from_window(*window.deref(), self).into_mut();
cx.run_until_parked();
cx
}
@ -273,7 +274,7 @@ impl TestAppContext {
.unwrap();
drop(cx);
let view = window.root(self).unwrap();
let cx = VisualTestContext::from_window(*window.deref(), self).as_mut();
let cx = VisualTestContext::from_window(*window.deref(), self).into_mut();
cx.run_until_parked();
// it might be nice to try and cleanup these at the end of each test.
@ -882,7 +883,7 @@ impl VisualTestContext {
/// Get an &mut VisualTestContext (which is mostly what you need to pass to other methods).
/// This method internally retains the VisualTestContext until the end of the test.
pub fn as_mut(self) -> &'static mut Self {
pub fn into_mut(self) -> &'static mut Self {
let ptr = Box::into_raw(Box::new(self));
// safety: on_quit will be called after the test has finished.
// the executor will ensure that all tasks related to the test have stopped.

View file

@ -905,9 +905,9 @@ mod tests {
assert_eq!(background.solid, color);
assert_eq!(background.opacity(0.5).solid, color.opacity(0.5));
assert_eq!(background.is_transparent(), false);
assert!(!background.is_transparent());
background.solid = hsla(0.0, 0.0, 0.0, 0.0);
assert_eq!(background.is_transparent(), true);
assert!(background.is_transparent());
}
#[test]
@ -921,7 +921,7 @@ mod tests {
assert_eq!(background.opacity(0.5).colors[0], from.opacity(0.5));
assert_eq!(background.opacity(0.5).colors[1], to.opacity(0.5));
assert_eq!(background.is_transparent(), false);
assert_eq!(background.opacity(0.0).is_transparent(), true);
assert!(!background.is_transparent());
assert!(background.opacity(0.0).is_transparent());
}
}

View file

@ -1641,7 +1641,7 @@ impl Bounds<Pixels> {
}
/// Convert the bounds from logical pixels to physical pixels
pub fn to_device_pixels(&self, factor: f32) -> Bounds<DevicePixels> {
pub fn to_device_pixels(self, factor: f32) -> Bounds<DevicePixels> {
Bounds {
origin: point(
DevicePixels((self.origin.x.0 * factor).round() as i32),
@ -1957,7 +1957,7 @@ impl Edges<DefiniteLength> {
/// assert_eq!(edges_in_pixels.bottom, px(32.0)); // 2 rems
/// assert_eq!(edges_in_pixels.left, px(50.0)); // 25% of parent width
/// ```
pub fn to_pixels(&self, parent_size: Size<AbsoluteLength>, rem_size: Pixels) -> Edges<Pixels> {
pub fn to_pixels(self, parent_size: Size<AbsoluteLength>, rem_size: Pixels) -> Edges<Pixels> {
Edges {
top: self.top.to_pixels(parent_size.height, rem_size),
right: self.right.to_pixels(parent_size.width, rem_size),
@ -2027,7 +2027,7 @@ impl Edges<AbsoluteLength> {
/// assert_eq!(edges_in_pixels.bottom, px(20.0)); // Already in pixels
/// assert_eq!(edges_in_pixels.left, px(32.0)); // 2 rems converted to pixels
/// ```
pub fn to_pixels(&self, rem_size: Pixels) -> Edges<Pixels> {
pub fn to_pixels(self, rem_size: Pixels) -> Edges<Pixels> {
Edges {
top: self.top.to_pixels(rem_size),
right: self.right.to_pixels(rem_size),
@ -2272,7 +2272,7 @@ impl Corners<AbsoluteLength> {
/// assert_eq!(corners_in_pixels.bottom_right, Pixels(30.0));
/// assert_eq!(corners_in_pixels.bottom_left, Pixels(32.0)); // 2 rems converted to pixels
/// ```
pub fn to_pixels(&self, rem_size: Pixels) -> Corners<Pixels> {
pub fn to_pixels(self, rem_size: Pixels) -> Corners<Pixels> {
Corners {
top_left: self.top_left.to_pixels(rem_size),
top_right: self.top_right.to_pixels(rem_size),
@ -2858,7 +2858,7 @@ impl DevicePixels {
/// let total_bytes = pixels.to_bytes(bytes_per_pixel);
/// assert_eq!(total_bytes, 40); // 10 pixels * 4 bytes/pixel = 40 bytes
/// ```
pub fn to_bytes(&self, bytes_per_pixel: u8) -> u32 {
pub fn to_bytes(self, bytes_per_pixel: u8) -> u32 {
self.0 as u32 * bytes_per_pixel as u32
}
}
@ -3073,8 +3073,8 @@ pub struct Rems(pub f32);
impl Rems {
/// Convert this Rem value to pixels.
pub fn to_pixels(&self, rem_size: Pixels) -> Pixels {
*self * rem_size
pub fn to_pixels(self, rem_size: Pixels) -> Pixels {
self * rem_size
}
}
@ -3168,9 +3168,9 @@ impl AbsoluteLength {
/// assert_eq!(length_in_pixels.to_pixels(rem_size), Pixels(42.0));
/// assert_eq!(length_in_rems.to_pixels(rem_size), Pixels(32.0));
/// ```
pub fn to_pixels(&self, rem_size: Pixels) -> Pixels {
pub fn to_pixels(self, rem_size: Pixels) -> Pixels {
match self {
AbsoluteLength::Pixels(pixels) => *pixels,
AbsoluteLength::Pixels(pixels) => pixels,
AbsoluteLength::Rems(rems) => rems.to_pixels(rem_size),
}
}
@ -3184,10 +3184,10 @@ impl AbsoluteLength {
/// # Returns
///
/// Returns the `AbsoluteLength` as `Pixels`.
pub fn to_rems(&self, rem_size: Pixels) -> Rems {
pub fn to_rems(self, rem_size: Pixels) -> Rems {
match self {
AbsoluteLength::Pixels(pixels) => Rems(pixels.0 / rem_size.0),
AbsoluteLength::Rems(rems) => *rems,
AbsoluteLength::Rems(rems) => rems,
}
}
}
@ -3315,12 +3315,12 @@ impl DefiniteLength {
/// assert_eq!(length_in_rems.to_pixels(base_size, rem_size), Pixels(32.0));
/// assert_eq!(length_as_fraction.to_pixels(base_size, rem_size), Pixels(50.0));
/// ```
pub fn to_pixels(&self, base_size: AbsoluteLength, rem_size: Pixels) -> Pixels {
pub fn to_pixels(self, base_size: AbsoluteLength, rem_size: Pixels) -> Pixels {
match self {
DefiniteLength::Absolute(size) => size.to_pixels(rem_size),
DefiniteLength::Fraction(fraction) => match base_size {
AbsoluteLength::Pixels(px) => px * *fraction,
AbsoluteLength::Rems(rems) => rems * rem_size * *fraction,
AbsoluteLength::Pixels(px) => px * fraction,
AbsoluteLength::Rems(rems) => rems * rem_size * fraction,
},
}
}

View file

@ -172,6 +172,10 @@ pub trait AppContext {
type Result<T>;
/// Create a new entity in the app context.
#[expect(
clippy::wrong_self_convention,
reason = "`App::new` is an ubiquitous function for creating entities"
)]
fn new<T: 'static>(
&mut self,
build_entity: impl FnOnce(&mut Context<T>) -> T,

View file

@ -364,29 +364,29 @@ mod tests {
// Ensure `space` results in pending input on the workspace, but not editor
let space_workspace = keymap.bindings_for_input(&[space()], &workspace_context());
assert!(space_workspace.0.is_empty());
assert_eq!(space_workspace.1, true);
assert!(space_workspace.1);
let space_editor = keymap.bindings_for_input(&[space()], &editor_workspace_context());
assert!(space_editor.0.is_empty());
assert_eq!(space_editor.1, false);
assert!(!space_editor.1);
// Ensure `space w` results in pending input on the workspace, but not editor
let space_w_workspace = keymap.bindings_for_input(&space_w, &workspace_context());
assert!(space_w_workspace.0.is_empty());
assert_eq!(space_w_workspace.1, true);
assert!(space_w_workspace.1);
let space_w_editor = keymap.bindings_for_input(&space_w, &editor_workspace_context());
assert!(space_w_editor.0.is_empty());
assert_eq!(space_w_editor.1, false);
assert!(!space_w_editor.1);
// Ensure `space w w` results in the binding in the workspace, but not in the editor
let space_w_w_workspace = keymap.bindings_for_input(&space_w_w, &workspace_context());
assert!(!space_w_w_workspace.0.is_empty());
assert_eq!(space_w_w_workspace.1, false);
assert!(!space_w_w_workspace.1);
let space_w_w_editor = keymap.bindings_for_input(&space_w_w, &editor_workspace_context());
assert!(space_w_w_editor.0.is_empty());
assert_eq!(space_w_w_editor.1, false);
assert!(!space_w_w_editor.1);
// Now test what happens if we have another binding defined AFTER the NoAction
// that should result in pending
@ -400,7 +400,7 @@ mod tests {
let space_editor = keymap.bindings_for_input(&[space()], &editor_workspace_context());
assert!(space_editor.0.is_empty());
assert_eq!(space_editor.1, true);
assert!(space_editor.1);
// Now test what happens if we have another binding defined BEFORE the NoAction
// that should result in pending
@ -414,7 +414,7 @@ mod tests {
let space_editor = keymap.bindings_for_input(&[space()], &editor_workspace_context());
assert!(space_editor.0.is_empty());
assert_eq!(space_editor.1, true);
assert!(space_editor.1);
// Now test what happens if we have another binding defined at a higher context
// that should result in pending
@ -428,7 +428,7 @@ mod tests {
let space_editor = keymap.bindings_for_input(&[space()], &editor_workspace_context());
assert!(space_editor.0.is_empty());
assert_eq!(space_editor.1, true);
assert!(space_editor.1);
}
#[test]
@ -447,7 +447,7 @@ mod tests {
&[KeyContext::parse("editor").unwrap()],
);
assert!(result.is_empty());
assert_eq!(pending, true);
assert!(pending);
let bindings = [
KeyBinding::new("ctrl-w left", ActionAlpha {}, Some("editor")),
@ -463,7 +463,7 @@ mod tests {
&[KeyContext::parse("editor").unwrap()],
);
assert_eq!(result.len(), 1);
assert_eq!(pending, false);
assert!(!pending);
}
#[test]
@ -482,7 +482,7 @@ mod tests {
&[KeyContext::parse("editor").unwrap()],
);
assert!(result.is_empty());
assert_eq!(pending, false);
assert!(!pending);
}
#[test]
@ -505,7 +505,7 @@ mod tests {
],
);
assert_eq!(result.len(), 1);
assert_eq!(pending, false);
assert!(!pending);
}
#[test]
@ -527,7 +527,7 @@ mod tests {
],
);
assert_eq!(result.len(), 0);
assert_eq!(pending, false);
assert!(!pending);
}
#[test]

View file

@ -30,11 +30,8 @@ impl Clone for KeyBinding {
impl KeyBinding {
/// Construct a new keybinding from the given data. Panics on parse error.
pub fn new<A: Action>(keystrokes: &str, action: A, context: Option<&str>) -> Self {
let context_predicate = if let Some(context) = context {
Some(KeyBindingContextPredicate::parse(context).unwrap().into())
} else {
None
};
let context_predicate =
context.map(|context| KeyBindingContextPredicate::parse(context).unwrap().into());
Self::load(keystrokes, Box::new(action), context_predicate, None, None).unwrap()
}

View file

@ -673,7 +673,7 @@ impl PlatformTextSystem for NoopTextSystem {
}
}
let mut runs = Vec::default();
if glyphs.len() > 0 {
if !glyphs.is_empty() {
runs.push(ShapedRun {
font_id: FontId(0),
glyphs,

View file

@ -667,7 +667,7 @@ pub(super) const DEFAULT_CURSOR_ICON_NAME: &str = "left_ptr";
impl CursorStyle {
#[cfg(any(feature = "wayland", feature = "x11"))]
pub(super) fn to_icon_names(&self) -> &'static [&'static str] {
pub(super) fn to_icon_names(self) -> &'static [&'static str] {
// Based on cursor names from chromium:
// https://github.com/chromium/chromium/blob/d3069cf9c973dc3627fa75f64085c6a86c8f41bf/ui/base/cursor/cursor_factory.cc#L113
match self {
@ -990,21 +990,18 @@ mod tests {
#[test]
fn test_is_within_click_distance() {
let zero = Point::new(px(0.0), px(0.0));
assert_eq!(
is_within_click_distance(zero, Point::new(px(5.0), px(5.0))),
true
);
assert_eq!(
is_within_click_distance(zero, Point::new(px(-4.9), px(5.0))),
true
);
assert_eq!(
is_within_click_distance(Point::new(px(3.0), px(2.0)), Point::new(px(-2.0), px(-2.0))),
true
);
assert_eq!(
is_within_click_distance(zero, Point::new(px(5.0), px(5.1))),
false
);
assert!(is_within_click_distance(zero, Point::new(px(5.0), px(5.0))));
assert!(is_within_click_distance(
zero,
Point::new(px(-4.9), px(5.0))
));
assert!(is_within_click_distance(
Point::new(px(3.0), px(2.0)),
Point::new(px(-2.0), px(-2.0))
));
assert!(!is_within_click_distance(
zero,
Point::new(px(5.0), px(5.1))
),);
}
}

View file

@ -12,7 +12,7 @@ use wayland_protocols::wp::cursor_shape::v1::client::wp_cursor_shape_device_v1::
use crate::CursorStyle;
impl CursorStyle {
pub(super) fn to_shape(&self) -> Shape {
pub(super) fn to_shape(self) -> Shape {
match self {
CursorStyle::Arrow => Shape::Default,
CursorStyle::IBeam => Shape::Text,

View file

@ -1139,7 +1139,7 @@ fn update_window(mut state: RefMut<WaylandWindowState>) {
}
impl WindowDecorations {
fn to_xdg(&self) -> zxdg_toplevel_decoration_v1::Mode {
fn to_xdg(self) -> zxdg_toplevel_decoration_v1::Mode {
match self {
WindowDecorations::Client => zxdg_toplevel_decoration_v1::Mode::ClientSide,
WindowDecorations::Server => zxdg_toplevel_decoration_v1::Mode::ServerSide,
@ -1148,7 +1148,7 @@ impl WindowDecorations {
}
impl ResizeEdge {
fn to_xdg(&self) -> xdg_toplevel::ResizeEdge {
fn to_xdg(self) -> xdg_toplevel::ResizeEdge {
match self {
ResizeEdge::Top => xdg_toplevel::ResizeEdge::Top,
ResizeEdge::TopRight => xdg_toplevel::ResizeEdge::TopRight,

View file

@ -95,7 +95,7 @@ fn query_render_extent(
}
impl ResizeEdge {
fn to_moveresize(&self) -> u32 {
fn to_moveresize(self) -> u32 {
match self {
ResizeEdge::TopLeft => 0,
ResizeEdge::Top => 1,

View file

@ -1090,7 +1090,7 @@ impl PlatformWindow for MacWindow {
NSView::removeFromSuperview(blur_view);
this.blurred_view = None;
}
} else if this.blurred_view == None {
} else if this.blurred_view.is_none() {
let content_view = this.native_window.contentView();
let frame = NSView::bounds(content_view);
let mut blur_view: id = msg_send![BLURRED_VIEW_CLASS, alloc];

View file

@ -45,27 +45,18 @@ impl TabHandles {
})
.unwrap_or_default();
if let Some(next_handle) = self.handles.get(next_ix) {
Some(next_handle.clone())
} else {
None
}
self.handles.get(next_ix).cloned()
}
pub(crate) fn prev(&self, focused_id: Option<&FocusId>) -> Option<FocusHandle> {
let ix = self.current_index(focused_id).unwrap_or_default();
let prev_ix;
if ix == 0 {
prev_ix = self.handles.len().saturating_sub(1);
let prev_ix = if ix == 0 {
self.handles.len().saturating_sub(1)
} else {
prev_ix = ix.saturating_sub(1);
}
ix.saturating_sub(1)
};
if let Some(prev_handle) = self.handles.get(prev_ix) {
Some(prev_handle.clone())
} else {
None
}
self.handles.get(prev_ix).cloned()
}
}

View file

@ -172,7 +172,7 @@ pub fn box_shadow_style_methods(input: TokenStream) -> TokenStream {
/// - `#[gpui::test(iterations = 5)]` runs five times, providing as seed the values in the range `0..5`.
/// - `#[gpui::test(retries = 3)]` runs up to four times if it fails to try and make it pass.
/// - `#[gpui::test(on_failure = "crate::test::report_failure")]` will call the specified function after the
/// tests fail so that you can write out more detail about the failure.
/// tests fail so that you can write out more detail about the failure.
///
/// You can combine `iterations = ...` with `seeds(...)`:
/// - `#[gpui::test(iterations = 5, seed = 10)]` is equivalent to `#[gpui::test(seeds(0, 1, 2, 3, 4, 10))]`.

View file

@ -49,7 +49,7 @@ impl LanguageName {
pub fn from_proto(s: String) -> Self {
Self(SharedString::from(s))
}
pub fn to_proto(self) -> String {
pub fn to_proto(&self) -> String {
self.0.to_string()
}
pub fn lsp_id(&self) -> String {

View file

@ -19,7 +19,7 @@ impl Role {
}
}
pub fn to_proto(&self) -> proto::LanguageModelRole {
pub fn to_proto(self) -> proto::LanguageModelRole {
match self {
Role::User => proto::LanguageModelRole::LanguageModelUser,
Role::Assistant => proto::LanguageModelRole::LanguageModelAssistant,

View file

@ -28,7 +28,7 @@ fn migrate(text: &str, patterns: MigrationPatterns, query: &Query) -> Result<Opt
let mut parser = tree_sitter::Parser::new();
parser.set_language(&tree_sitter_json::LANGUAGE.into())?;
let syntax_tree = parser
.parse(&text, None)
.parse(text, None)
.context("failed to parse settings")?;
let mut cursor = tree_sitter::QueryCursor::new();

View file

@ -7149,7 +7149,7 @@ impl ExcerptId {
Self(usize::MAX)
}
pub fn to_proto(&self) -> u64 {
pub fn to_proto(self) -> u64 {
self.0 as _
}

View file

@ -41,7 +41,7 @@ pub fn remote_server_dir_relative() -> &'static Path {
/// # Arguments
///
/// * `dir` - The path to use as the custom data directory. This will be used as the base
/// directory for all user data, including databases, extensions, and logs.
/// directory for all user data, including databases, extensions, and logs.
///
/// # Returns
///

View file

@ -6,9 +6,9 @@
//!
//! There are few reasons for this divide:
//! - Breakpoints persist across debug sessions and they're not really specific to any particular session. Sure, we have to send protocol messages for them
//! (so they're a "thing" in the protocol), but we also want to set them before any session starts up.
//! (so they're a "thing" in the protocol), but we also want to set them before any session starts up.
//! - Debug clients are doing the heavy lifting, and this is where UI grabs all of it's data from. They also rely on breakpoint store during initialization to obtain
//! current set of breakpoints.
//! current set of breakpoints.
//! - Since DAP store knows about all of the available debug sessions, it is responsible for routing RPC requests to sessions. It also knows how to find adapters for particular kind of session.
pub mod breakpoint_store;

View file

@ -904,7 +904,7 @@ impl BreakpointState {
}
#[inline]
pub fn to_int(&self) -> i32 {
pub fn to_int(self) -> i32 {
match self {
BreakpointState::Enabled => 0,
BreakpointState::Disabled => 1,

View file

@ -3,6 +3,7 @@
//! Each byte in memory can either be mapped or unmapped. We try to mimic that twofold:
//! - We assume that the memory is divided into pages of a fixed size.
//! - We assume that each page can be either mapped or unmapped.
//!
//! These two assumptions drive the shape of the memory representation.
//! In particular, we want the unmapped pages to be represented without allocating any memory, as *most*
//! of the memory in a program space is usually unmapped.
@ -165,8 +166,8 @@ impl Memory {
/// - If it succeeds/fails wholesale, cool; we have no unknown memory regions in this page.
/// - If it succeeds partially, we know # of mapped bytes.
/// We might also know the # of unmapped bytes.
/// However, we're still unsure about what's *after* the unreadable region.
///
/// However, we're still unsure about what's *after* the unreadable region.
/// This is where this builder comes in. It lets us track the state of figuring out contents of a single page.
pub(super) struct MemoryPageBuilder {
chunks: MappedPageContents,

View file

@ -653,7 +653,7 @@ mod tests {
cx.run_until_parked();
conflict_set.update(cx, |conflict_set, _| {
assert_eq!(conflict_set.has_conflict, false);
assert!(!conflict_set.has_conflict);
assert_eq!(conflict_set.snapshot.conflicts.len(), 0);
});

View file

@ -199,7 +199,7 @@ pub struct GitEntryRef<'a> {
}
impl GitEntryRef<'_> {
pub fn to_owned(&self) -> GitEntry {
pub fn to_owned(self) -> GitEntry {
GitEntry {
entry: self.entry.clone(),
git_summary: self.git_summary,

View file

@ -5,7 +5,7 @@
//! This module is split up into three distinct parts:
//! - [`LocalLspStore`], which is ran on the host machine (either project host or SSH host), that manages the lifecycle of language servers.
//! - [`RemoteLspStore`], which is ran on the remote machine (project guests) which is mostly about passing through the requests via RPC.
//! The remote stores don't really care about which language server they're running against - they don't usually get to decide which language server is going to responsible for handling their request.
//! The remote stores don't really care about which language server they're running against - they don't usually get to decide which language server is going to responsible for handling their request.
//! - [`LspStore`], which unifies the two under one consistent interface for interacting with language servers.
//!
//! Most of the interesting work happens at the local layer, as bulk of the complexity is with managing the lifecycle of language servers. The actual implementation of the LSP protocol is handled by [`lsp`] crate.
@ -12691,7 +12691,7 @@ impl DiagnosticSummary {
}
pub fn to_proto(
&self,
self,
language_server_id: LanguageServerId,
path: &Path,
) -> proto::DiagnosticSummary {

View file

@ -22,9 +22,9 @@ pub(super) struct RootPathTrie<Label> {
/// Label presence is a marker that allows to optimize searches within [RootPathTrie]; node label can be:
/// - Present; we know there's definitely a project root at this node.
/// - Known Absent - we know there's definitely no project root at this node and none of it's ancestors are Present (descendants can be present though!).
/// The distinction is there to optimize searching; when we encounter a node with unknown status, we don't need to look at it's full path
/// to the root of the worktree; it's sufficient to explore only the path between last node with a KnownAbsent state and the directory of a path, since we run searches
/// from the leaf up to the root of the worktree.
/// The distinction is there to optimize searching; when we encounter a node with unknown status, we don't need to look at it's full path
/// to the root of the worktree; it's sufficient to explore only the path between last node with a KnownAbsent state and the directory of a path, since we run searches
/// from the leaf up to the root of the worktree.
///
/// In practical terms, it means that by storing label presence we don't need to do a project discovery on a given folder more than once
/// (unless the node is invalidated, which can happen when FS entries are renamed/removed).

View file

@ -4329,7 +4329,7 @@ impl Project {
/// # Arguments
///
/// * `path` - A full path that starts with a worktree root name, or alternatively a
/// relative path within a visible worktree.
/// relative path within a visible worktree.
/// * `cx` - A reference to the `AppContext`.
///
/// # Returns
@ -5508,7 +5508,7 @@ mod disable_ai_settings_tests {
project: &[],
};
let settings = DisableAiSettings::load(sources, cx).unwrap();
assert_eq!(settings.disable_ai, false, "Default should allow AI");
assert!(!settings.disable_ai, "Default should allow AI");
// Test 2: Global true, local false -> still disabled (local cannot re-enable)
let global_true = Some(true);
@ -5525,8 +5525,8 @@ mod disable_ai_settings_tests {
project: &[&local_false],
};
let settings = DisableAiSettings::load(sources, cx).unwrap();
assert_eq!(
settings.disable_ai, true,
assert!(
settings.disable_ai,
"Local false cannot override global true"
);
@ -5545,10 +5545,7 @@ mod disable_ai_settings_tests {
project: &[&local_true],
};
let settings = DisableAiSettings::load(sources, cx).unwrap();
assert_eq!(
settings.disable_ai, true,
"Local true can override global false"
);
assert!(settings.disable_ai, "Local true can override global false");
// Test 4: Server can only make more restrictive (set to true)
let user_false = Some(false);
@ -5565,8 +5562,8 @@ mod disable_ai_settings_tests {
project: &[],
};
let settings = DisableAiSettings::load(sources, cx).unwrap();
assert_eq!(
settings.disable_ai, true,
assert!(
settings.disable_ai,
"Server can set to true even if user is false"
);
@ -5585,8 +5582,8 @@ mod disable_ai_settings_tests {
project: &[],
};
let settings = DisableAiSettings::load(sources, cx).unwrap();
assert_eq!(
settings.disable_ai, true,
assert!(
settings.disable_ai,
"Server false cannot override user true"
);
@ -5607,10 +5604,7 @@ mod disable_ai_settings_tests {
project: &[&local_false3, &local_true2, &local_false4],
};
let settings = DisableAiSettings::load(sources, cx).unwrap();
assert_eq!(
settings.disable_ai, true,
"Any local true should disable AI"
);
assert!(settings.disable_ai, "Any local true should disable AI");
// Test 7: All three sources can independently disable AI
let user_false2 = Some(false);
@ -5628,8 +5622,8 @@ mod disable_ai_settings_tests {
project: &[&local_true3],
};
let settings = DisableAiSettings::load(sources, cx).unwrap();
assert_eq!(
settings.disable_ai, true,
assert!(
settings.disable_ai,
"Local can disable even if user and server are false"
);
});

View file

@ -4123,7 +4123,7 @@ async fn test_buffer_identity_across_renames(cx: &mut gpui::TestAppContext) {
})
.unwrap()
.await
.to_included()
.into_included()
.unwrap();
cx.executor().run_until_parked();
@ -5918,7 +5918,7 @@ async fn test_create_entry(cx: &mut gpui::TestAppContext) {
})
.await
.unwrap()
.to_included()
.into_included()
.unwrap();
// Can't create paths outside the project

View file

@ -2515,7 +2515,7 @@ impl ProjectPanel {
if clip_is_cut {
// Convert the clipboard cut entry to a copy entry after the first paste.
self.clipboard = self.clipboard.take().map(ClipboardEntry::to_copy_entry);
self.clipboard = self.clipboard.take().map(ClipboardEntry::into_copy_entry);
}
self.expand_entry(worktree_id, entry.id, cx);
@ -5709,7 +5709,7 @@ impl ClipboardEntry {
}
}
fn to_copy_entry(self) -> Self {
fn into_copy_entry(self) -> Self {
match self {
ClipboardEntry::Copied(_) => self,
ClipboardEntry::Cut(entries) => ClipboardEntry::Copied(entries),

View file

@ -1452,7 +1452,7 @@ impl RemoteConnection for SshRemoteConnection {
.arg(format!(
"{}:{}",
self.socket.connection_options.scp_url(),
dest_path.to_string()
dest_path
))
.output();
@ -1836,11 +1836,7 @@ impl SshRemoteConnection {
})??;
let tmp_path_gz = RemotePathBuf::new(
PathBuf::from(format!(
"{}-download-{}.gz",
dst_path.to_string(),
std::process::id()
)),
PathBuf::from(format!("{}-download-{}.gz", dst_path, std::process::id())),
self.ssh_path_style,
);
if !self.socket.connection_options.upload_binary_over_ssh
@ -2036,7 +2032,7 @@ impl SshRemoteConnection {
.arg(format!(
"{}:{}",
self.socket.connection_options.scp_url(),
dest_path.to_string()
dest_path
))
.output()
.await?;

View file

@ -1207,7 +1207,7 @@ async fn test_remote_rename_entry(cx: &mut TestAppContext, server_cx: &mut TestA
})
.await
.unwrap()
.to_included()
.into_included()
.unwrap();
cx.run_until_parked();

View file

@ -84,7 +84,7 @@ fn init_logging_server(log_file_path: PathBuf) -> Result<Receiver<Vec<u8>>> {
fn flush(&mut self) -> std::io::Result<()> {
self.channel
.send_blocking(self.buffer.clone())
.map_err(|error| std::io::Error::new(std::io::ErrorKind::Other, error))?;
.map_err(std::io::Error::other)?;
self.buffer.clear();
self.file.flush()
}

View file

@ -169,10 +169,7 @@ pub enum KernelStatus {
impl KernelStatus {
pub fn is_connected(&self) -> bool {
match self {
KernelStatus::Idle | KernelStatus::Busy => true,
_ => false,
}
matches!(self, KernelStatus::Idle | KernelStatus::Busy)
}
}

View file

@ -264,7 +264,7 @@ impl http_client::HttpClient for ReqwestClient {
let bytes = response
.bytes_stream()
.map_err(|e| futures::io::Error::new(futures::io::ErrorKind::Other, e))
.map_err(futures::io::Error::other)
.into_async_read();
let body = http_client::AsyncBody::from_reader(bytes);

View file

@ -92,7 +92,7 @@ impl Into<Chunk> for ChunkSlice<'_> {
impl<'a> ChunkSlice<'a> {
#[inline(always)]
pub fn is_empty(self) -> bool {
pub fn is_empty(&self) -> bool {
self.text.is_empty()
}

View file

@ -56,7 +56,7 @@ impl Connection {
) {
use anyhow::anyhow;
use futures::channel::mpsc;
use std::io::{Error, ErrorKind};
use std::io::Error;
let (tx, rx) = mpsc::unbounded::<WebSocketMessage>();
@ -71,7 +71,7 @@ impl Connection {
// Writes to a half-open TCP connection will error.
if killed.load(SeqCst) {
std::io::Result::Err(Error::new(ErrorKind::Other, "connection lost"))?;
std::io::Result::Err(Error::other("connection lost"))?;
}
Ok(msg)

View file

@ -116,8 +116,8 @@ impl SearchOption {
}
}
pub fn to_toggle_action(&self) -> &'static dyn Action {
match *self {
pub fn to_toggle_action(self) -> &'static dyn Action {
match self {
SearchOption::WholeWord => &ToggleWholeWord,
SearchOption::CaseSensitive => &ToggleCaseSensitive,
SearchOption::IncludeIgnored => &ToggleIncludeIgnored,

View file

@ -50,11 +50,11 @@ impl WorktreeId {
Self(id as usize)
}
pub fn to_proto(&self) -> u64 {
pub fn to_proto(self) -> u64 {
self.0 as u64
}
pub fn to_usize(&self) -> usize {
pub fn to_usize(self) -> usize {
self.0
}
}

View file

@ -28,7 +28,7 @@ impl ShellKind {
}
}
fn to_shell_variable(&self, input: &str) -> String {
fn to_shell_variable(self, input: &str) -> String {
match self {
Self::Powershell => Self::to_powershell_variable(input),
Self::Cmd => Self::to_cmd_variable(input),

View file

@ -104,7 +104,7 @@ impl SlashCommand for TerminalSlashCommand {
}],
run_commands_in_text: false,
}
.to_event_stream()))
.into_event_stream()))
}
}

View file

@ -2192,7 +2192,7 @@ mod tests {
})
.await
.unwrap()
.to_included()
.into_included()
.unwrap();
(wt, entry)

View file

@ -582,13 +582,9 @@ impl RenderOnce for ButtonLike {
.when_some(self.width, |this, width| {
this.w(width).justify_center().text_center()
})
.when(
match self.style {
ButtonStyle::Outlined => true,
_ => false,
},
|this| this.border_1(),
)
.when(matches!(self.style, ButtonStyle::Outlined), |this| {
this.border_1()
})
.when_some(self.rounding, |this, rounding| match rounding {
ButtonLikeRounding::All => this.rounded_sm(),
ButtonLikeRounding::Left => this.rounded_l_sm(),

View file

@ -13,9 +13,9 @@ impl DateTimeType {
///
/// If the [`DateTimeType`] is already a [`NaiveDateTime`], it will be returned as is.
/// If the [`DateTimeType`] is a [`DateTime<Local>`], it will be converted to a [`NaiveDateTime`].
pub fn to_naive(&self) -> NaiveDateTime {
pub fn to_naive(self) -> NaiveDateTime {
match self {
DateTimeType::Naive(naive) => *naive,
DateTimeType::Naive(naive) => naive,
DateTimeType::Local(local) => local.naive_local(),
}
}

View file

@ -154,7 +154,7 @@ mod tests {
let mut builder =
ZipEntryBuilder::new(filename.into(), async_zip::Compression::Deflate);
use std::os::unix::fs::PermissionsExt;
let metadata = std::fs::metadata(&path)?;
let metadata = std::fs::metadata(path)?;
let perms = metadata.permissions().mode() as u16;
builder = builder.unix_permissions(perms);
writer.write_entry_whole(builder, &data).await?;

View file

@ -23,7 +23,7 @@ impl Display for MarkdownString {
/// the other characters involved are escaped:
///
/// * `!`, `]`, `(`, and `)` are used in link syntax, but `[` is escaped so these are parsed as
/// plaintext.
/// plaintext.
///
/// * `;` is used in HTML entity syntax, but `&` is escaped, so they are parsed as plaintext.
///

View file

@ -2,6 +2,7 @@ use globset::{Glob, GlobSet, GlobSetBuilder};
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
use std::fmt::{Display, Formatter};
use std::path::StripPrefixError;
use std::sync::{Arc, OnceLock};
use std::{
@ -113,10 +114,6 @@ impl SanitizedPath {
&self.0
}
pub fn to_string(&self) -> String {
self.0.to_string_lossy().to_string()
}
pub fn to_glob_string(&self) -> String {
#[cfg(target_os = "windows")]
{
@ -137,6 +134,12 @@ impl SanitizedPath {
}
}
impl Display for SanitizedPath {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0.display())
}
}
impl From<SanitizedPath> for Arc<Path> {
fn from(sanitized_path: SanitizedPath) -> Self {
sanitized_path.0
@ -220,12 +223,8 @@ impl RemotePathBuf {
Self::new(path_buf, style)
}
pub fn to_string(&self) -> String {
self.string.clone()
}
#[cfg(target_os = "windows")]
pub fn to_proto(self) -> String {
pub fn to_proto(&self) -> String {
match self.path_style() {
PathStyle::Posix => self.to_string(),
PathStyle::Windows => self.inner.to_string_lossy().replace('\\', "/"),
@ -233,7 +232,7 @@ impl RemotePathBuf {
}
#[cfg(not(target_os = "windows"))]
pub fn to_proto(self) -> String {
pub fn to_proto(&self) -> String {
match self.path_style() {
PathStyle::Posix => self.inner.to_string_lossy().to_string(),
PathStyle::Windows => self.to_string(),
@ -255,6 +254,12 @@ impl RemotePathBuf {
}
}
impl Display for RemotePathBuf {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.string)
}
}
/// A delimiter to use in `path_query:row_number:column_number` strings parsing.
pub const FILE_ROW_COLUMN_DELIMITER: char = ':';

View file

@ -816,10 +816,7 @@ impl Motion {
}
fn skip_exclusive_special_case(&self) -> bool {
match self {
Motion::WrappingLeft | Motion::WrappingRight => true,
_ => false,
}
matches!(self, Motion::WrappingLeft | Motion::WrappingRight)
}
pub(crate) fn push_to_jump_list(&self) -> bool {
@ -4099,7 +4096,7 @@ mod test {
cx.shared_state().await.assert_eq(indoc! {"
ˇhe quick brown fox
jumped over the lazy dog"});
assert_eq!(cx.cx.forced_motion(), false);
assert!(!cx.cx.forced_motion());
cx.set_shared_state(indoc! {"
the quick bˇrown fox
@ -4109,7 +4106,7 @@ mod test {
cx.shared_state().await.assert_eq(indoc! {"
ˇown fox
jumped over the lazy dog"});
assert_eq!(cx.cx.forced_motion(), false);
assert!(!cx.cx.forced_motion());
cx.set_shared_state(indoc! {"
the quick brown foˇx
@ -4119,7 +4116,7 @@ mod test {
cx.shared_state().await.assert_eq(indoc! {"
ˇ
jumped over the lazy dog"});
assert_eq!(cx.cx.forced_motion(), false);
assert!(!cx.cx.forced_motion());
}
#[gpui::test]
@ -4134,7 +4131,7 @@ mod test {
cx.shared_state().await.assert_eq(indoc! {"
ˇbrown fox
jumped over the lazy dog"});
assert_eq!(cx.cx.forced_motion(), false);
assert!(!cx.cx.forced_motion());
cx.set_shared_state(indoc! {"
the quick bˇrown fox
@ -4144,7 +4141,7 @@ mod test {
cx.shared_state().await.assert_eq(indoc! {"
the quickˇown fox
jumped over the lazy dog"});
assert_eq!(cx.cx.forced_motion(), false);
assert!(!cx.cx.forced_motion());
cx.set_shared_state(indoc! {"
the quick brown foˇx
@ -4154,7 +4151,7 @@ mod test {
cx.shared_state().await.assert_eq(indoc! {"
the quicˇk
jumped over the lazy dog"});
assert_eq!(cx.cx.forced_motion(), false);
assert!(!cx.cx.forced_motion());
cx.set_shared_state(indoc! {"
ˇthe quick brown fox
@ -4164,7 +4161,7 @@ mod test {
cx.shared_state().await.assert_eq(indoc! {"
ˇ fox
jumped over the lazy dog"});
assert_eq!(cx.cx.forced_motion(), false);
assert!(!cx.cx.forced_motion());
cx.set_shared_state(indoc! {"
ˇthe quick brown fox
@ -4174,7 +4171,7 @@ mod test {
cx.shared_state().await.assert_eq(indoc! {"
ˇuick brown fox
jumped over the lazy dog"});
assert_eq!(cx.cx.forced_motion(), false);
assert!(!cx.cx.forced_motion());
}
#[gpui::test]
@ -4189,7 +4186,7 @@ mod test {
cx.shared_state().await.assert_eq(indoc! {"
the quick brown foˇx
jumped over the lazy dog"});
assert_eq!(cx.cx.forced_motion(), false);
assert!(!cx.cx.forced_motion());
cx.set_shared_state(indoc! {"
ˇthe quick brown fox
@ -4199,7 +4196,7 @@ mod test {
cx.shared_state().await.assert_eq(indoc! {"
ˇx
jumped over the lazy dog"});
assert_eq!(cx.cx.forced_motion(), false);
assert!(!cx.cx.forced_motion());
}
#[gpui::test]
@ -4215,7 +4212,7 @@ mod test {
the quick brown fox
ˇthe quick brown fox
jumped over the lazy dog"});
assert_eq!(cx.cx.forced_motion(), false);
assert!(!cx.cx.forced_motion());
cx.set_shared_state(indoc! {"
the quick bˇrown fox
@ -4226,7 +4223,7 @@ mod test {
the quick brˇrown fox
jumped overown fox
jumped over the lazy dog"});
assert_eq!(cx.cx.forced_motion(), false);
assert!(!cx.cx.forced_motion());
cx.set_shared_state(indoc! {"
the quick brown foˇx
@ -4237,7 +4234,7 @@ mod test {
the quick brown foxˇx
jumped over the la
jumped over the lazy dog"});
assert_eq!(cx.cx.forced_motion(), false);
assert!(!cx.cx.forced_motion());
cx.set_shared_state(indoc! {"
the quick brown fox
@ -4248,7 +4245,7 @@ mod test {
thˇhe quick brown fox
je quick brown fox
jumped over the lazy dog"});
assert_eq!(cx.cx.forced_motion(), false);
assert!(!cx.cx.forced_motion());
}
#[gpui::test]
@ -4263,7 +4260,7 @@ mod test {
cx.shared_state().await.assert_eq(indoc! {"
ˇe quick brown fox
jumped over the lazy dog"});
assert_eq!(cx.cx.forced_motion(), false);
assert!(!cx.cx.forced_motion());
cx.set_shared_state(indoc! {"
the quick bˇrown fox
@ -4273,7 +4270,7 @@ mod test {
cx.shared_state().await.assert_eq(indoc! {"
the quick bˇn fox
jumped over the lazy dog"});
assert_eq!(cx.cx.forced_motion(), false);
assert!(!cx.cx.forced_motion());
cx.set_shared_state(indoc! {"
the quick brown foˇx
@ -4282,6 +4279,6 @@ mod test {
cx.simulate_shared_keystrokes("d v e").await;
cx.shared_state().await.assert_eq(indoc! {"
the quick brown foˇd over the lazy dog"});
assert_eq!(cx.cx.forced_motion(), false);
assert!(!cx.cx.forced_motion());
}
}

View file

@ -1734,10 +1734,7 @@ impl Vim {
editor.set_autoindent(vim.should_autoindent());
editor.selections.line_mode = matches!(vim.mode, Mode::VisualLine);
let hide_edit_predictions = match vim.mode {
Mode::Insert | Mode::Replace => false,
_ => true,
};
let hide_edit_predictions = !matches!(vim.mode, Mode::Insert | Mode::Replace);
editor.set_edit_predictions_hidden_for_vim_mode(hide_edit_predictions, window, cx);
});
cx.notify()

View file

@ -5509,7 +5509,7 @@ impl ProjectEntryId {
Self(id as usize)
}
pub fn to_proto(&self) -> u64 {
pub fn to_proto(self) -> u64 {
self.0 as u64
}
@ -5517,14 +5517,14 @@ impl ProjectEntryId {
ProjectEntryId(id)
}
pub fn to_usize(&self) -> usize {
pub fn to_usize(self) -> usize {
self.0
}
}
#[cfg(any(test, feature = "test-support"))]
impl CreatedEntry {
pub fn to_included(self) -> Option<Entry> {
pub fn into_included(self) -> Option<Entry> {
match self {
CreatedEntry::Included(entry) => Some(entry),
CreatedEntry::Excluded { .. } => None,

View file

@ -1274,7 +1274,7 @@ async fn test_create_directory_during_initial_scan(cx: &mut TestAppContext) {
})
.await
.unwrap()
.to_included()
.into_included()
.unwrap();
assert!(entry.is_dir());
@ -1323,7 +1323,7 @@ async fn test_create_dir_all_on_create_entry(cx: &mut TestAppContext) {
})
.await
.unwrap()
.to_included()
.into_included()
.unwrap();
assert!(entry.is_file());
@ -1357,7 +1357,7 @@ async fn test_create_dir_all_on_create_entry(cx: &mut TestAppContext) {
})
.await
.unwrap()
.to_included()
.into_included()
.unwrap();
assert!(entry.is_file());
@ -1377,7 +1377,7 @@ async fn test_create_dir_all_on_create_entry(cx: &mut TestAppContext) {
})
.await
.unwrap()
.to_included()
.into_included()
.unwrap();
assert!(entry.is_file());
@ -1395,7 +1395,7 @@ async fn test_create_dir_all_on_create_entry(cx: &mut TestAppContext) {
})
.await
.unwrap()
.to_included()
.into_included()
.unwrap();
assert!(entry.is_file());
@ -1726,7 +1726,7 @@ fn randomly_mutate_worktree(
);
let task = worktree.rename_entry(entry.id, new_path, cx);
cx.background_spawn(async move {
task.await?.to_included().unwrap();
task.await?.into_included().unwrap();
Ok(())
})
}

View file

@ -122,9 +122,6 @@ impl Model {
}
pub fn supports_images(&self) -> bool {
match self {
Self::Grok2Vision => true,
_ => false,
}
matches!(self, Self::Grok2Vision)
}
}