Remove if-not-else patterns (#10402)

Joseph T. Lyons created

Change summary

crates/assistant/src/assistant_panel.rs              |  6 +-
crates/call/src/call.rs                              |  6 +-
crates/collab_ui/src/collab_panel.rs                 |  6 +-
crates/editor/src/display_map/fold_map.rs            |  6 +-
crates/editor/src/display_map/wrap_map.rs            |  6 +-
crates/editor/src/editor.rs                          | 10 ++--
crates/editor/src/hover_popover.rs                   |  6 +-
crates/editor/src/scroll.rs                          |  6 +-
crates/extension/src/extension_lsp_adapter.rs        |  6 +-
crates/gpui/src/key_dispatch.rs                      |  6 +-
crates/language/src/buffer.rs                        | 16 +++---
crates/markdown_preview/src/markdown_preview_view.rs |  6 +-
crates/multi_buffer/src/multi_buffer.rs              |  6 +-
crates/project/src/project.rs                        |  6 +-
crates/recent_projects/src/recent_projects.rs        |  6 +-
crates/rich_text/src/rich_text.rs                    | 10 ++--
crates/search/src/project_search.rs                  |  6 +-
crates/settings/src/settings_file.rs                 | 10 ++--
crates/sqlez/src/migrations.rs                       |  8 +-
crates/terminal/src/terminal.rs                      |  6 +-
crates/terminal_view/src/terminal_element.rs         |  8 +-
crates/terminal_view/src/terminal_view.rs            |  6 +-
crates/vim/src/normal/change.rs                      |  6 +-
crates/worktree/src/worktree.rs                      | 30 +++++++-------
24 files changed, 97 insertions(+), 97 deletions(-)

Detailed changes

crates/assistant/src/assistant_panel.rs 🔗

@@ -625,10 +625,10 @@ impl AssistantPanel {
         // If Markdown or No Language is Known, increase the randomness for more creative output
         // If Code, decrease temperature to get more deterministic outputs
         let temperature = if let Some(language) = language_name.clone() {
-            if language.as_ref() != "Markdown" {
-                0.5
-            } else {
+            if language.as_ref() == "Markdown" {
                 1.0
+            } else {
+                0.5
             }
         } else {
             1.0

crates/call/src/call.rs 🔗

@@ -432,7 +432,9 @@ impl ActiveCall {
         room: Option<Model<Room>>,
         cx: &mut ModelContext<Self>,
     ) -> Task<Result<()>> {
-        if room.as_ref() != self.room.as_ref().map(|room| &room.0) {
+        if room.as_ref() == self.room.as_ref().map(|room| &room.0) {
+            Task::ready(Ok(()))
+        } else {
             cx.notify();
             if let Some(room) = room {
                 if room.read(cx).status().is_offline() {
@@ -462,8 +464,6 @@ impl ActiveCall {
                 self.room = None;
                 Task::ready(Ok(()))
             }
-        } else {
-            Task::ready(Ok(()))
         }
     }
 

crates/collab_ui/src/collab_panel.rs 🔗

@@ -2519,7 +2519,9 @@ impl CollabPanel {
         const FACEPILE_LIMIT: usize = 3;
         let participants = self.channel_store.read(cx).channel_participants(channel_id);
 
-        let face_pile = if !participants.is_empty() {
+        let face_pile = if participants.is_empty() {
+            None
+        } else {
             let extra_count = participants.len().saturating_sub(FACEPILE_LIMIT);
             let result = FacePile::new(
                 participants
@@ -2540,8 +2542,6 @@ impl CollabPanel {
             );
 
             Some(result)
-        } else {
-            None
         };
 
         let width = self.width.unwrap_or(px(240.));

crates/editor/src/display_map/fold_map.rs 🔗

@@ -233,11 +233,11 @@ impl FoldMap {
     }
 
     pub fn set_ellipses_color(&mut self, color: Hsla) -> bool {
-        if self.ellipses_color != Some(color) {
+        if self.ellipses_color == Some(color) {
+            false
+        } else {
             self.ellipses_color = Some(color);
             true
-        } else {
-            false
         }
     }
 

crates/editor/src/display_map/wrap_map.rs 🔗

@@ -126,12 +126,12 @@ impl WrapMap {
     ) -> bool {
         let font_with_size = (font, font_size);
 
-        if font_with_size != self.font_with_size {
+        if font_with_size == self.font_with_size {
+            false
+        } else {
             self.font_with_size = font_with_size;
             self.rewrap(cx);
             true
-        } else {
-            false
         }
     }
 

crates/editor/src/editor.rs 🔗

@@ -8833,16 +8833,16 @@ impl Editor {
     }
 
     pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
-        if !self.show_git_blame {
+        if self.show_git_blame {
+            self.blame_subscription.take();
+            self.blame.take();
+            self.show_git_blame = false
+        } else {
             if let Err(error) = self.show_git_blame_internal(cx) {
                 log::error!("failed to toggle on 'git blame': {}", error);
                 return;
             }
             self.show_git_blame = true
-        } else {
-            self.blame_subscription.take();
-            self.blame.take();
-            self.show_git_blame = false
         }
 
         cx.notify();

crates/editor/src/hover_popover.rs 🔗

@@ -238,7 +238,9 @@ fn show_hover(
     let task = cx.spawn(|this, mut cx| {
         async move {
             // If we need to delay, delay a set amount initially before making the lsp request
-            let delay = if !ignore_timeout {
+            let delay = if ignore_timeout {
+                None
+            } else {
                 // Construct delay task to wait for later
                 let total_delay = Some(
                     cx.background_executor()
@@ -249,8 +251,6 @@ fn show_hover(
                     .timer(Duration::from_millis(HOVER_REQUEST_DELAY_MILLIS))
                     .await;
                 total_delay
-            } else {
-                None
             };
 
             // query the LSP for hover info

crates/editor/src/scroll.rs 🔗

@@ -45,11 +45,11 @@ impl ScrollAnchor {
 
     pub fn scroll_position(&self, snapshot: &DisplaySnapshot) -> gpui::Point<f32> {
         let mut scroll_position = self.offset;
-        if self.anchor != Anchor::min() {
+        if self.anchor == Anchor::min() {
+            scroll_position.y = 0.;
+        } else {
             let scroll_top = self.anchor.to_display_point(snapshot).row() as f32;
             scroll_position.y = scroll_top + scroll_position.y;
-        } else {
-            scroll_position.y = 0.;
         }
         scroll_position
     }

crates/extension/src/extension_lsp_adapter.rs 🔗

@@ -295,10 +295,10 @@ fn labels_from_wit(
         .into_iter()
         .map(|label| {
             let label = label?;
-            let runs = if !label.code.is_empty() {
-                language.highlight_text(&label.code.as_str().into(), 0..label.code.len())
-            } else {
+            let runs = if label.code.is_empty() {
                 Vec::new()
+            } else {
+                language.highlight_text(&label.code.as_str().into(), 0..label.code.len())
             };
             build_code_label(&label, &runs, &language)
         })

crates/gpui/src/key_dispatch.rs 🔗

@@ -260,11 +260,11 @@ impl DispatchTree {
         {
             let source_node_id = DispatchNodeId(source_node_id);
             while let Some(source_ancestor) = source_stack.last() {
-                if source_node.parent != Some(*source_ancestor) {
+                if source_node.parent == Some(*source_ancestor) {
+                    break;
+                } else {
                     source_stack.pop();
                     self.pop_node();
-                } else {
-                    break;
                 }
             }
 

crates/language/src/buffer.rs 🔗

@@ -1326,14 +1326,7 @@ impl Buffer {
         current_size: IndentSize,
         new_size: IndentSize,
     ) -> Option<(Range<Point>, String)> {
-        if new_size.kind != current_size.kind {
-            Some((
-                Point::new(row, 0)..Point::new(row, current_size.len),
-                iter::repeat(new_size.char())
-                    .take(new_size.len as usize)
-                    .collect::<String>(),
-            ))
-        } else {
+        if new_size.kind == current_size.kind {
             match new_size.len.cmp(&current_size.len) {
                 Ordering::Greater => {
                     let point = Point::new(row, 0);
@@ -1352,6 +1345,13 @@ impl Buffer {
 
                 Ordering::Equal => None,
             }
+        } else {
+            Some((
+                Point::new(row, 0)..Point::new(row, current_size.len),
+                iter::repeat(new_size.char())
+                    .take(new_size.len as usize)
+                    .collect::<String>(),
+            ))
         }
     }
 

crates/markdown_preview/src/markdown_preview_view.rs 🔗

@@ -175,10 +175,10 @@ impl MarkdownPreviewView {
                                             this.bg(cx.theme().colors().border)
                                         })
                                         .group_hover("markdown-block", |s| {
-                                            if ix != view.selected_block {
-                                                s.bg(cx.theme().colors().border_variant)
-                                            } else {
+                                            if ix == view.selected_block {
                                                 s
+                                            } else {
+                                                s.bg(cx.theme().colors().border_variant)
                                             }
                                         })
                                         .rounded_sm();

crates/multi_buffer/src/multi_buffer.rs 🔗

@@ -3393,10 +3393,10 @@ impl MultiBufferSnapshot {
         cursor.seek(&range.end, Bias::Right, &());
         let end_excerpt = cursor.item()?;
 
-        if start_excerpt.id != end_excerpt.id {
-            None
-        } else {
+        if start_excerpt.id == end_excerpt.id {
             Some(MultiBufferExcerpt::new(start_excerpt, *cursor.start()))
+        } else {
+            None
         }
     }
 

crates/project/src/project.rs 🔗

@@ -2737,15 +2737,15 @@ impl Project {
             futures::future::join_all(tasks).await;
 
             this.update(&mut cx, |this, cx| {
-                if !this.buffers_needing_diff.is_empty() {
-                    this.recalculate_buffer_diffs(cx).detach();
-                } else {
+                if this.buffers_needing_diff.is_empty() {
                     // TODO: Would a `ModelContext<Project>.notify()` suffice here?
                     for buffer in buffers {
                         if let Some(buffer) = buffer.upgrade() {
                             buffer.update(cx, |_, cx| cx.notify());
                         }
                     }
+                } else {
+                    this.recalculate_buffer_diffs(cx).detach();
                 }
             })
             .ok();

crates/recent_projects/src/recent_projects.rs 🔗

@@ -258,7 +258,9 @@ impl PickerDelegate for RecentProjectsDelegate {
             };
             workspace
                 .update(cx, |workspace, cx| {
-                    if workspace.database_id() != *candidate_workspace_id {
+                    if workspace.database_id() == *candidate_workspace_id {
+                        Task::ready(Ok(()))
+                    } else {
                         let candidate_paths = candidate_workspace_location.paths().as_ref().clone();
                         if replace_current_window {
                             cx.spawn(move |workspace, mut cx| async move {
@@ -284,8 +286,6 @@ impl PickerDelegate for RecentProjectsDelegate {
                         } else {
                             workspace.open_workspace_for_paths(false, candidate_paths, cx)
                         }
-                    } else {
-                        Task::ready(Ok(()))
                     }
                 })
                 .detach_and_log_err(cx);

crates/rich_text/src/rich_text.rs 🔗

@@ -69,18 +69,18 @@ impl RichText {
                                 ..id.style(theme.syntax()).unwrap_or_default()
                             },
                             Highlight::InlineCode(link) => {
-                                if !*link {
+                                if *link {
                                     HighlightStyle {
                                         background_color: Some(code_background),
+                                        underline: Some(UnderlineStyle {
+                                            thickness: 1.0.into(),
+                                            ..Default::default()
+                                        }),
                                         ..Default::default()
                                     }
                                 } else {
                                     HighlightStyle {
                                         background_color: Some(code_background),
-                                        underline: Some(UnderlineStyle {
-                                            thickness: 1.0.into(),
-                                            ..Default::default()
-                                        }),
                                         ..Default::default()
                                     }
                                 }

crates/search/src/project_search.rs 🔗

@@ -1244,10 +1244,10 @@ impl ProjectSearchBar {
         if let Some(search) = &self.active_project_search {
             search.update(cx, |this, cx| {
                 this.replace_enabled = !this.replace_enabled;
-                let editor_to_focus = if !this.replace_enabled {
-                    this.query_editor.focus_handle(cx)
-                } else {
+                let editor_to_focus = if this.replace_enabled {
                     this.replacement_editor.focus_handle(cx)
+                } else {
+                    this.query_editor.focus_handle(cx)
                 };
                 cx.focus(&editor_to_focus);
                 cx.notify();

crates/settings/src/settings_file.rs 🔗

@@ -116,11 +116,7 @@ pub fn update_settings_file<T: Settings>(
             store.new_text_for_update::<T>(old_text, update)
         })?;
         let initial_path = paths::SETTINGS.as_path();
-        if !fs.is_file(initial_path).await {
-            fs.atomic_write(initial_path.to_path_buf(), new_text)
-                .await
-                .with_context(|| format!("Failed to write settings to file {:?}", initial_path))?;
-        } else {
+        if fs.is_file(initial_path).await {
             let resolved_path = fs.canonicalize(initial_path).await.with_context(|| {
                 format!("Failed to canonicalize settings path {:?}", initial_path)
             })?;
@@ -128,6 +124,10 @@ pub fn update_settings_file<T: Settings>(
             fs.atomic_write(resolved_path.clone(), new_text)
                 .await
                 .with_context(|| format!("Failed to write settings to file {:?}", resolved_path))?;
+        } else {
+            fs.atomic_write(initial_path.to_path_buf(), new_text)
+                .await
+                .with_context(|| format!("Failed to write settings to file {:?}", initial_path))?;
         }
 
         anyhow::Ok(())

crates/sqlez/src/migrations.rs 🔗

@@ -56,7 +56,10 @@ impl Connection {
 
             for (index, migration) in migrations.iter().enumerate() {
                 if let Some((_, _, completed_migration)) = completed_migrations.get(index) {
-                    if completed_migration != migration {
+                    if completed_migration == migration {
+                        // Migration already run. Continue
+                        continue;
+                    } else {
                         return Err(anyhow!(formatdoc! {"
                             Migration changed for {} at step {}
 
@@ -65,9 +68,6 @@ impl Connection {
 
                             Proposed migration:
                             {}", domain, index, completed_migration, migration}));
-                    } else {
-                        // Migration already run. Continue
-                        continue;
                     }
                 }
 

crates/terminal/src/terminal.rs 🔗

@@ -846,11 +846,11 @@ impl Terminal {
                         Some(url_match) => {
                             // `]` is a valid symbol in the `file://` URL, so the regex match will include it
                             // consider that when ensuring that the URL match is the same as the original word
-                            if sanitized_match != original_match {
+                            if sanitized_match == original_match {
+                                url_match == sanitized_match
+                            } else {
                                 url_match.start() == sanitized_match.start()
                                     && url_match.end() == original_match.end()
-                            } else {
-                                url_match == sanitized_match
                             }
                         }
                         None => false,

crates/terminal_view/src/terminal_element.rs 🔗

@@ -447,14 +447,14 @@ impl TerminalElement {
                 if e.pressed_button.is_some() && !cx.has_active_drag() {
                     let hovered = hitbox.is_hovered(cx);
                     terminal.update(cx, |terminal, cx| {
-                        if !terminal.selection_started() {
+                        if terminal.selection_started() {
+                            terminal.mouse_drag(e, origin, hitbox.bounds);
+                            cx.notify();
+                        } else {
                             if hovered {
                                 terminal.mouse_drag(e, origin, hitbox.bounds);
                                 cx.notify();
                             }
-                        } else {
-                            terminal.mouse_drag(e, origin, hitbox.bounds);
-                            cx.notify();
                         }
                     })
                 }

crates/terminal_view/src/terminal_view.rs 🔗

@@ -222,21 +222,21 @@ impl TerminalView {
     }
 
     fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
-        if !self
+        if self
             .terminal
             .read(cx)
             .last_content
             .mode
             .contains(TermMode::ALT_SCREEN)
         {
-            cx.show_character_palette();
-        } else {
             self.terminal.update(cx, |term, cx| {
                 term.try_keystroke(
                     &Keystroke::parse("ctrl-cmd-space").unwrap(),
                     TerminalSettings::get_global(cx).option_as_meta,
                 )
             });
+        } else {
+            cx.show_character_palette();
         }
     }
 

crates/vim/src/normal/change.rs 🔗

@@ -137,12 +137,12 @@ fn expand_changed_word_selection(
             .unwrap_or_default();
 
         if in_word {
-            if !use_subword {
+            if use_subword {
                 selection.end =
-                    motion::next_word_end(map, selection.end, ignore_punctuation, 1, false);
+                    motion::next_subword_end(map, selection.end, ignore_punctuation, 1, false);
             } else {
                 selection.end =
-                    motion::next_subword_end(map, selection.end, ignore_punctuation, 1, false);
+                    motion::next_word_end(map, selection.end, ignore_punctuation, 1, false);
             }
             selection.end = motion::next_char(map, selection.end, false);
             true

crates/worktree/src/worktree.rs 🔗

@@ -1999,10 +1999,10 @@ impl Snapshot {
         let mut repositories = self.repositories().peekable();
         entries.map(move |entry| {
             while let Some((repo_path, _)) = containing_repos.last() {
-                if !entry.path.starts_with(repo_path) {
-                    containing_repos.pop();
-                } else {
+                if entry.path.starts_with(repo_path) {
                     break;
+                } else {
+                    containing_repos.pop();
                 }
             }
             while let Some((repo_path, _)) = repositories.peek() {
@@ -2033,10 +2033,10 @@ impl Snapshot {
             let entry_to_finish = match (containing_entry, next_entry) {
                 (Some(_), None) => entry_stack.pop(),
                 (Some(containing_entry), Some(next_path)) => {
-                    if !next_path.path.starts_with(&containing_entry.path) {
-                        entry_stack.pop()
-                    } else {
+                    if next_path.path.starts_with(&containing_entry.path) {
                         None
+                    } else {
+                        entry_stack.pop()
                     }
                 }
                 (None, Some(_)) => None,
@@ -3930,7 +3930,9 @@ impl BackgroundScanner {
                 child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, true);
 
                 // Avoid recursing until crash in the case of a recursive symlink
-                if !job.ancestor_inodes.contains(&child_entry.inode) {
+                if job.ancestor_inodes.contains(&child_entry.inode) {
+                    new_jobs.push(None);
+                } else {
                     let mut ancestor_inodes = job.ancestor_inodes.clone();
                     ancestor_inodes.insert(child_entry.inode);
 
@@ -3947,8 +3949,6 @@ impl BackgroundScanner {
                         scan_queue: job.scan_queue.clone(),
                         containing_repository: job.containing_repository.clone(),
                     }));
-                } else {
-                    new_jobs.push(None);
                 }
             } else {
                 child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, false);
@@ -4686,10 +4686,10 @@ impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTa
         match self {
             TraversalTarget::Path(path) => path.cmp(&cursor_location.max_path),
             TraversalTarget::PathSuccessor(path) => {
-                if !cursor_location.max_path.starts_with(path) {
-                    Ordering::Equal
-                } else {
+                if cursor_location.max_path.starts_with(path) {
                     Ordering::Greater
+                } else {
+                    Ordering::Equal
                 }
             }
             TraversalTarget::Count {
@@ -4799,10 +4799,10 @@ fn combine_git_statuses(
 ) -> Option<GitFileStatus> {
     if let Some(staged) = staged {
         if let Some(unstaged) = unstaged {
-            if unstaged != staged {
-                Some(GitFileStatus::Modified)
-            } else {
+            if unstaged == staged {
                 Some(staged)
+            } else {
+                Some(GitFileStatus::Modified)
             }
         } else {
             Some(staged)