Use anyhow more idiomatically (#31052)

https://github.com/zed-industries/zed/issues/30972 brought up another
case where our context is not enough to track the actual source of the
issue: we get a general top-level error without inner error.

The reason for this was `.ok_or_else(|| anyhow!("failed to read HEAD
SHA"))?; ` on the top level.

The PR finally reworks the way we use anyhow to reduce such issues (or
at least make it simpler to bubble them up later in a fix).
On top of that, uses a few more anyhow methods for better readability.

* `.ok_or_else(|| anyhow!("..."))`, `map_err` and other similar error
conversion/option reporting cases are replaced with `context` and
`with_context` calls
* in addition to that, various `anyhow!("failed to do ...")` are
stripped with `.context("Doing ...")` messages instead to remove the
parasitic `failed to` text
* `anyhow::ensure!` is used instead of `if ... { return Err(...); }`
calls
* `anyhow::bail!` is used instead of `return Err(anyhow!(...));`

Release Notes:

- N/A
This commit is contained in:
Kirill Bulatov 2025-05-21 02:06:07 +03:00 committed by GitHub
parent 1e51a7ac44
commit 16366cf9f2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
294 changed files with 2037 additions and 2610 deletions

View file

@ -7,7 +7,7 @@ use crate::{
ShowStackTrace, StepBack, StepInto, StepOut, StepOver, Stop, ToggleIgnoreBreakpoints,
persistence,
};
use anyhow::{Result, anyhow};
use anyhow::{Context as _, Result, anyhow};
use command_palette_hooks::CommandPaletteFilter;
use dap::StartDebuggingRequestArguments;
use dap::adapters::DebugAdapterName;
@ -1021,17 +1021,13 @@ impl DebugPanel {
}
workspace.update(cx, |workspace, cx| {
if let Some(project_path) = workspace
workspace
.project()
.read(cx)
.project_path_for_absolute_path(&path, cx)
{
Ok(project_path)
} else {
Err(anyhow!(
"Couldn't get project path for .zed/debug.json in active worktree"
))
}
.context(
"Couldn't get project path for .zed/debug.json in active worktree",
)
})?
})
})

View file

@ -9,7 +9,6 @@ use std::{
usize,
};
use anyhow::Result;
use dap::{
DapRegistry, DebugRequest,
adapters::{DebugAdapterName, DebugTaskDefinition},
@ -253,7 +252,7 @@ impl NewSessionModal {
cx.emit(DismissEvent);
})
.ok();
Result::<_, anyhow::Error>::Ok(())
anyhow::Ok(())
})
.detach_and_log_err(cx);
}

View file

@ -1,3 +1,4 @@
use anyhow::Context as _;
use collections::HashMap;
use dap::{Capabilities, adapters::DebugAdapterName};
use db::kvp::KEY_VALUE_STORE;
@ -96,18 +97,14 @@ pub(crate) async fn serialize_pane_layout(
adapter_name: DebugAdapterName,
pane_group: SerializedLayout,
) -> anyhow::Result<()> {
if let Ok(serialized_pane_group) = serde_json::to_string(&pane_group) {
KEY_VALUE_STORE
.write_kvp(
format!("{DEBUGGER_PANEL_PREFIX}-{adapter_name}"),
serialized_pane_group,
)
.await
} else {
Err(anyhow::anyhow!(
"Failed to serialize pane group with serde_json as a string"
))
}
let serialized_pane_group = serde_json::to_string(&pane_group)
.context("Serializing pane group with serde_json as a string")?;
KEY_VALUE_STORE
.write_kvp(
format!("{DEBUGGER_PANEL_PREFIX}-{adapter_name}"),
serialized_pane_group,
)
.await
}
pub(crate) fn build_serialized_layout(

View file

@ -196,7 +196,7 @@ impl FollowableItem for DebugSession {
_state: &mut Option<proto::view::Variant>,
_window: &mut Window,
_cx: &mut App,
) -> Option<gpui::Task<gpui::Result<Entity<Self>>>> {
) -> Option<gpui::Task<anyhow::Result<Entity<Self>>>> {
None
}
@ -218,7 +218,7 @@ impl FollowableItem for DebugSession {
_message: proto::update_view::Variant,
_window: &mut Window,
_cx: &mut Context<Self>,
) -> gpui::Task<gpui::Result<()>> {
) -> gpui::Task<anyhow::Result<()>> {
Task::ready(Ok(()))
}

View file

@ -10,7 +10,7 @@ use std::{any::Any, ops::ControlFlow, path::PathBuf, sync::Arc, time::Duration};
use crate::persistence::{self, DebuggerPaneItem, SerializedLayout};
use super::DebugPanelItemEvent;
use anyhow::{Result, anyhow};
use anyhow::{Context as _, Result, anyhow};
use breakpoint_list::BreakpointList;
use collections::{HashMap, IndexMap};
use console::Console;
@ -817,7 +817,7 @@ impl RunningState {
let exit_status = terminal
.read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))?
.await
.ok_or_else(|| anyhow!("Failed to wait for completed task"))?;
.context("Failed to wait for completed task")?;
if !exit_status.success() {
anyhow::bail!("Build failed");
@ -829,22 +829,22 @@ impl RunningState {
let request = if let Some(request) = request {
request
} else if let Some((task, locator_name)) = build_output {
let locator_name = locator_name
.ok_or_else(|| anyhow!("Could not find a valid locator for a build task"))?;
let locator_name =
locator_name.context("Could not find a valid locator for a build task")?;
dap_store
.update(cx, |this, cx| {
this.run_debug_locator(&locator_name, task, cx)
})?
.await?
} else {
return Err(anyhow!("No request or build provided"));
anyhow::bail!("No request or build provided");
};
let request = match request {
dap::DebugRequest::Launch(launch_request) => {
let cwd = match launch_request.cwd.as_deref().and_then(|path| path.to_str()) {
Some(cwd) => {
let substituted_cwd = substitute_variables_in_str(&cwd, &task_context)
.ok_or_else(|| anyhow!("Failed to substitute variables in cwd"))?;
.context("substituting variables in cwd")?;
Some(PathBuf::from(substituted_cwd))
}
None => None,
@ -854,7 +854,7 @@ impl RunningState {
&launch_request.env.into_iter().collect(),
&task_context,
)
.ok_or_else(|| anyhow!("Failed to substitute variables in env"))?
.context("substituting variables in env")?
.into_iter()
.collect();
let new_launch_request = LaunchRequest {
@ -862,13 +862,13 @@ impl RunningState {
&launch_request.program,
&task_context,
)
.ok_or_else(|| anyhow!("Failed to substitute variables in program"))?,
.context("substituting variables in program")?,
args: launch_request
.args
.into_iter()
.map(|arg| substitute_variables_in_str(&arg, &task_context))
.collect::<Option<Vec<_>>>()
.ok_or_else(|| anyhow!("Failed to substitute variables in args"))?,
.context("substituting variables in args")?,
cwd,
env,
};
@ -994,7 +994,7 @@ impl RunningState {
.pty_info
.pid()
.map(|pid| pid.as_u32())
.ok_or_else(|| anyhow!("Terminal was spawned but PID was not available"))
.context("Terminal was spawned but PID was not available")
})?
});

View file

@ -377,7 +377,7 @@ impl LineBreakpoint {
})
.ok();
}
Result::<_, anyhow::Error>::Ok(())
anyhow::Ok(())
})
.detach();

View file

@ -278,7 +278,7 @@ impl CompletionProvider for ConsoleQueryBarCompletionProvider {
_completion_indices: Vec<usize>,
_completions: Rc<RefCell<Box<[Completion]>>>,
_cx: &mut Context<Editor>,
) -> gpui::Task<gpui::Result<bool>> {
) -> gpui::Task<anyhow::Result<bool>> {
Task::ready(Ok(false))
}
@ -289,7 +289,7 @@ impl CompletionProvider for ConsoleQueryBarCompletionProvider {
_completion_index: usize,
_push_to_history: bool,
_cx: &mut Context<Editor>,
) -> gpui::Task<gpui::Result<Option<language::Transaction>>> {
) -> gpui::Task<anyhow::Result<Option<language::Transaction>>> {
Task::ready(Ok(None))
}

View file

@ -2,7 +2,7 @@ use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
use anyhow::{Result, anyhow};
use anyhow::{Context as _, Result, anyhow};
use dap::StackFrameId;
use gpui::{
AnyElement, Entity, EventEmitter, FocusHandle, Focusable, MouseButton, ScrollStrategy,
@ -285,9 +285,10 @@ impl StackFrameList {
})?;
this.update_in(cx, |this, window, cx| {
this.workspace.update(cx, |workspace, cx| {
let project_path = buffer.read(cx).project_path(cx).ok_or_else(|| {
anyhow!("Could not select a stack frame for unnamed buffer")
})?;
let project_path = buffer
.read(cx)
.project_path(cx)
.context("Could not select a stack frame for unnamed buffer")?;
let open_preview = !workspace
.item_of_type::<StackTraceView>(cx)
@ -312,9 +313,9 @@ impl StackFrameList {
.await?;
this.update(cx, |this, cx| {
let Some(thread_id) = this.state.read_with(cx, |state, _| state.thread_id)? else {
return Err(anyhow!("No selected thread ID found"));
};
let thread_id = this.state.read_with(cx, |state, _| {
state.thread_id.context("No selected thread ID found")
})??;
this.workspace.update(cx, |workspace, cx| {
let breakpoint_store = workspace.project().read(cx).breakpoint_store();

View file

@ -1,6 +1,6 @@
use std::sync::Arc;
use anyhow::{Result, anyhow};
use anyhow::{Context as _, Result};
use dap::adapters::DebugTaskDefinition;
use dap::{DebugRequest, client::DebugAdapterClient};
use gpui::{Entity, TestAppContext, WindowHandle};
@ -125,7 +125,7 @@ pub fn start_debug_session_with<T: Fn(&Arc<DebugAdapterClient>) + 'static>(
.and_then(|panel| panel.read(cx).active_session())
.map(|session| session.read(cx).running_state().read(cx).session())
.cloned()
.ok_or_else(|| anyhow!("Failed to get active session"))
.context("Failed to get active session")
})??;
Ok(session)