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

@ -1,4 +1,4 @@
use anyhow::{Context, Result, anyhow, bail};
use anyhow::{Context as _, Result, bail};
use dap_types::{
ErrorResponse,
messages::{Message, Response},
@ -226,12 +226,9 @@ impl TransportDelegate {
pub(crate) async fn send_message(&self, message: Message) -> Result<()> {
if let Some(server_tx) = self.server_tx.lock().await.as_ref() {
server_tx
.send(message)
.await
.map_err(|e| anyhow!("Failed to send message: {}", e))
server_tx.send(message).await.context("sending message")
} else {
Err(anyhow!("Server tx already dropped"))
anyhow::bail!("Server tx already dropped")
}
}
@ -254,7 +251,7 @@ impl TransportDelegate {
};
if bytes_read == 0 {
break Err(anyhow!("Debugger log stream closed"));
anyhow::bail!("Debugger log stream closed");
}
if let Some(log_handlers) = log_handlers.as_ref() {
@ -379,7 +376,7 @@ impl TransportDelegate {
let result = loop {
match reader.read_line(&mut buffer).await {
Ok(0) => break Err(anyhow!("debugger error stream closed")),
Ok(0) => anyhow::bail!("debugger error stream closed"),
Ok(_) => {
for (kind, log_handler) in log_handlers.lock().iter_mut() {
if matches!(kind, LogKind::Adapter) {
@ -409,13 +406,13 @@ impl TransportDelegate {
.and_then(|response| response.error.map(|msg| msg.format))
.or_else(|| response.message.clone())
{
return Err(anyhow!(error_message));
anyhow::bail!(error_message);
};
Err(anyhow!(
anyhow::bail!(
"Received error response from adapter. Response: {:?}",
response.clone()
))
response
);
}
}
@ -437,7 +434,7 @@ impl TransportDelegate {
.with_context(|| "reading a message from server")?
== 0
{
return Err(anyhow!("debugger reader stream closed"));
anyhow::bail!("debugger reader stream closed");
};
if buffer == "\r\n" {
@ -540,9 +537,10 @@ impl TcpTransport {
}
async fn start(binary: &DebugAdapterBinary, cx: AsyncApp) -> Result<(TransportPipe, Self)> {
let Some(connection_args) = binary.connection.as_ref() else {
return Err(anyhow!("No connection arguments provided"));
};
let connection_args = binary
.connection
.as_ref()
.context("No connection arguments provided")?;
let host = connection_args.host;
let port = connection_args.port;
@ -577,7 +575,7 @@ impl TcpTransport {
let (mut process, (rx, tx)) = select! {
_ = cx.background_executor().timer(Duration::from_millis(timeout)).fuse() => {
return Err(anyhow!(format!("Connection to TCP DAP timeout {}:{}", host, port)))
anyhow::bail!("Connection to TCP DAP timeout {host}:{port}");
},
result = cx.spawn(async move |cx| {
loop {
@ -591,7 +589,7 @@ impl TcpTransport {
} else {
String::from_utf8_lossy(&output.stderr).to_string()
};
return Err(anyhow!("{}\nerror: process exited before debugger attached.", output));
anyhow::bail!("{output}\nerror: process exited before debugger attached.");
}
cx.background_executor().timer(Duration::from_millis(100)).await;
}
@ -664,14 +662,8 @@ impl StdioTransport {
.spawn()
.with_context(|| "failed to spawn command.")?;
let stdin = process
.stdin
.take()
.ok_or_else(|| anyhow!("Failed to open stdin"))?;
let stdout = process
.stdout
.take()
.ok_or_else(|| anyhow!("Failed to open stdout"))?;
let stdin = process.stdin.take().context("Failed to open stdin")?;
let stdout = process.stdout.take().context("Failed to open stdout")?;
let stderr = process
.stderr
.take()
@ -793,7 +785,7 @@ impl FakeTransport {
match message {
Err(error) => {
break anyhow!(error);
break anyhow::anyhow!(error);
}
Ok(message) => {
match message {