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 async_trait::async_trait;
use futures::StreamExt;
use gpui::{App, AsyncApp};
@ -54,7 +54,7 @@ impl super::LspAdapter for CLspAdapter {
.assets
.iter()
.find(|asset| asset.name == asset_name)
.ok_or_else(|| anyhow!("no asset found matching {:?}", asset_name))?;
.with_context(|| format!("no asset found matching {asset_name:?}"))?;
let version = GitHubLspBinaryVersion {
name: release.tag_name,
url: asset.browser_download_url.clone(),
@ -80,12 +80,11 @@ impl super::LspAdapter for CLspAdapter {
.await
.context("error downloading release")?;
let mut file = File::create(&zip_path).await?;
if !response.status().is_success() {
Err(anyhow!(
"download failed with status {}",
response.status().to_string()
))?;
}
anyhow::ensure!(
response.status().is_success(),
"download failed with status {}",
response.status().to_string()
);
futures::io::copy(response.body_mut(), &mut file).await?;
let unzip_status = util::command::new_smol_command("unzip")
@ -94,10 +93,7 @@ impl super::LspAdapter for CLspAdapter {
.output()
.await?
.status;
if !unzip_status.success() {
Err(anyhow!("failed to unzip clangd archive"))?;
}
anyhow::ensure!(unzip_status.success(), "failed to unzip clangd archive");
remove_matching(&container_dir, |entry| entry != version_dir).await;
}
@ -339,20 +335,17 @@ async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServ
last_clangd_dir = Some(entry.path());
}
}
let clangd_dir = last_clangd_dir.ok_or_else(|| anyhow!("no cached binary"))?;
let clangd_dir = last_clangd_dir.context("no cached binary")?;
let clangd_bin = clangd_dir.join("bin/clangd");
if clangd_bin.exists() {
Ok(LanguageServerBinary {
path: clangd_bin,
env: None,
arguments: vec![],
})
} else {
Err(anyhow!(
"missing clangd binary in directory {:?}",
clangd_dir
))
}
anyhow::ensure!(
clangd_bin.exists(),
"missing clangd binary in directory {clangd_dir:?}"
);
Ok(LanguageServerBinary {
path: clangd_bin,
env: None,
arguments: vec![],
})
})
.await
.log_err()

View file

@ -1,4 +1,4 @@
use anyhow::{Result, anyhow};
use anyhow::{Context as _, Result};
use async_trait::async_trait;
use futures::StreamExt;
use gpui::AsyncApp;
@ -149,20 +149,17 @@ async fn get_cached_server_binary(
last_version_dir = Some(entry.path());
}
}
let last_version_dir = last_version_dir.ok_or_else(|| anyhow!("no cached binary"))?;
let last_version_dir = last_version_dir.context("no cached binary")?;
let server_path = last_version_dir.join(SERVER_PATH);
if server_path.exists() {
Ok(LanguageServerBinary {
path: node.binary_path().await?,
env: None,
arguments: server_binary_arguments(&server_path),
})
} else {
Err(anyhow!(
"missing executable in directory {:?}",
last_version_dir
))
}
anyhow::ensure!(
server_path.exists(),
"missing executable in directory {last_version_dir:?}"
);
Ok(LanguageServerBinary {
path: node.binary_path().await?,
env: None,
arguments: server_binary_arguments(&server_path),
})
})
.await
.log_err()

View file

@ -1,4 +1,4 @@
use anyhow::{Context as _, Result, anyhow};
use anyhow::{Context as _, Result};
use async_trait::async_trait;
use collections::HashMap;
use futures::StreamExt;
@ -107,7 +107,7 @@ impl super::LspAdapter for GoLspAdapter {
delegate.show_notification(NOTIFICATION_MESSAGE, cx);
})?
}
return Err(anyhow!("cannot install gopls"));
anyhow::bail!("cannot install gopls");
}
Ok(())
}))
@ -167,10 +167,9 @@ impl super::LspAdapter for GoLspAdapter {
String::from_utf8_lossy(&install_output.stdout),
String::from_utf8_lossy(&install_output.stderr)
);
return Err(anyhow!(
anyhow::bail!(
"failed to install gopls with `go install`. Is `go` installed and in the PATH? Check logs for more information."
));
);
}
let installed_binary_path = gobin_dir.join(BINARY);
@ -405,15 +404,12 @@ async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServ
}
}
if let Some(path) = last_binary_path {
Ok(LanguageServerBinary {
path,
arguments: server_binary_arguments(),
env: None,
})
} else {
Err(anyhow!("no cached binary"))
}
let path = last_binary_path.context("no cached binary")?;
anyhow::Ok(LanguageServerBinary {
path,
arguments: server_binary_arguments(),
env: None,
})
})
.await
.log_err()

View file

@ -1,4 +1,4 @@
use anyhow::{Context, Result, anyhow, bail};
use anyhow::{Context as _, Result, bail};
use async_compression::futures::bufread::GzipDecoder;
use async_tar::Archive;
use async_trait::async_trait;
@ -321,20 +321,17 @@ async fn get_cached_server_binary(
}
}
let last_version_dir = last_version_dir.ok_or_else(|| anyhow!("no cached binary"))?;
let last_version_dir = last_version_dir.context("no cached binary")?;
let server_path = last_version_dir.join(SERVER_PATH);
if server_path.exists() {
Ok(LanguageServerBinary {
path: node.binary_path().await?,
env: None,
arguments: server_binary_arguments(&server_path),
})
} else {
Err(anyhow!(
"missing executable in directory {:?}",
last_version_dir
))
}
anyhow::ensure!(
server_path.exists(),
"missing executable in directory {last_version_dir:?}"
);
Ok(LanguageServerBinary {
path: node.binary_path().await?,
env: None,
arguments: server_binary_arguments(&server_path),
})
})
.await
.log_err()
@ -430,7 +427,7 @@ impl LspAdapter for NodeVersionAdapter {
.http_client()
.get(&version.url, Default::default(), true)
.await
.map_err(|err| anyhow!("error downloading release: {}", err))?;
.context("downloading release")?;
if version.url.ends_with(".zip") {
node_runtime::extract_zip(
&destination_container_path,
@ -488,7 +485,7 @@ async fn get_cached_version_server_binary(container_dir: PathBuf) -> Option<Lang
}
anyhow::Ok(LanguageServerBinary {
path: last.ok_or_else(|| anyhow!("no cached binary"))?,
path: last.context("no cached binary")?,
env: None,
arguments: Default::default(),
})

View file

@ -1,4 +1,4 @@
use anyhow::ensure;
use anyhow::{Context as _, ensure};
use anyhow::{Result, anyhow};
use async_trait::async_trait;
use collections::HashMap;
@ -883,11 +883,11 @@ impl PyLspAdapter {
async fn ensure_venv(delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>> {
let python_path = Self::find_base_python(delegate)
.await
.ok_or_else(|| anyhow!("Could not find Python installation for PyLSP"))?;
.context("Could not find Python installation for PyLSP")?;
let work_dir = delegate
.language_server_download_dir(&Self::SERVER_NAME)
.await
.ok_or_else(|| anyhow!("Could not get working directory for PyLSP"))?;
.context("Could not get working directory for PyLSP")?;
let mut path = PathBuf::from(work_dir.as_ref());
path.push("pylsp-venv");
if !path.exists() {

View file

@ -1,4 +1,4 @@
use anyhow::{Context as _, Result, anyhow};
use anyhow::{Context as _, Result};
use async_compression::futures::bufread::GzipDecoder;
use async_trait::async_trait;
use collections::HashMap;
@ -974,7 +974,7 @@ async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServ
}
anyhow::Ok(LanguageServerBinary {
path: last.ok_or_else(|| anyhow!("no cached binary"))?,
path: last.context("no cached binary")?,
env: None,
arguments: Default::default(),
})

View file

@ -1,4 +1,4 @@
use anyhow::{Result, anyhow};
use anyhow::{Context as _, Result};
use async_trait::async_trait;
use collections::HashMap;
use futures::StreamExt;
@ -198,20 +198,17 @@ async fn get_cached_server_binary(
last_version_dir = Some(entry.path());
}
}
let last_version_dir = last_version_dir.ok_or_else(|| anyhow!("no cached binary"))?;
let last_version_dir = last_version_dir.context("no cached binary")?;
let server_path = last_version_dir.join(SERVER_PATH);
if server_path.exists() {
Ok(LanguageServerBinary {
path: node.binary_path().await?,
env: None,
arguments: server_binary_arguments(&server_path),
})
} else {
Err(anyhow!(
"missing executable in directory {:?}",
last_version_dir
))
}
anyhow::ensure!(
server_path.exists(),
"missing executable in directory {last_version_dir:?}"
);
Ok(LanguageServerBinary {
path: node.binary_path().await?,
env: None,
arguments: server_binary_arguments(&server_path),
})
})
.await
.log_err()

View file

@ -1,4 +1,4 @@
use anyhow::{Context as _, Result, anyhow};
use anyhow::{Context as _, Result};
use async_compression::futures::bufread::GzipDecoder;
use async_tar::Archive;
use async_trait::async_trait;
@ -315,10 +315,7 @@ async fn get_cached_ts_server_binary(
arguments: typescript_server_binary_arguments(&old_server_path),
})
} else {
Err(anyhow!(
"missing executable in directory {:?}",
container_dir
))
anyhow::bail!("missing executable in directory {container_dir:?}")
}
})
.await
@ -491,7 +488,7 @@ impl LspAdapter for EsLintLspAdapter {
.http_client()
.get(&version.url, Default::default(), true)
.await
.map_err(|err| anyhow!("error downloading release: {}", err))?;
.context("downloading release")?;
match Self::GITHUB_ASSET_KIND {
AssetKind::TarGz => {
let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
@ -529,7 +526,7 @@ impl LspAdapter for EsLintLspAdapter {
}
let mut dir = fs::read_dir(&destination_path).await?;
let first = dir.next().await.ok_or(anyhow!("missing first file"))??;
let first = dir.next().await.context("missing first file")??;
let repo_root = destination_path.join("vscode-eslint");
fs::rename(first.path(), &repo_root).await?;
@ -580,9 +577,10 @@ impl LspAdapter for EsLintLspAdapter {
#[cfg(target_os = "windows")]
async fn handle_symlink(src_dir: PathBuf, dest_dir: PathBuf) -> Result<()> {
if fs::metadata(&src_dir).await.is_err() {
return Err(anyhow!("Directory {} not present.", src_dir.display()));
}
anyhow::ensure!(
fs::metadata(&src_dir).await.is_ok(),
"Directory {src_dir:?} is not present"
);
if fs::metadata(&dest_dir).await.is_ok() {
fs::remove_file(&dest_dir).await?;
}

View file

@ -1,4 +1,4 @@
use anyhow::{Result, anyhow};
use anyhow::Result;
use async_trait::async_trait;
use collections::HashMap;
use gpui::AsyncApp;
@ -284,18 +284,15 @@ async fn get_cached_ts_server_binary(
) -> Option<LanguageServerBinary> {
maybe!(async {
let server_path = container_dir.join(VtslsLspAdapter::SERVER_PATH);
if server_path.exists() {
Ok(LanguageServerBinary {
path: node.binary_path().await?,
env: None,
arguments: typescript_server_binary_arguments(&server_path),
})
} else {
Err(anyhow!(
"missing executable in directory {:?}",
container_dir
))
}
anyhow::ensure!(
server_path.exists(),
"missing executable in directory {container_dir:?}"
);
Ok(LanguageServerBinary {
path: node.binary_path().await?,
env: None,
arguments: typescript_server_binary_arguments(&server_path),
})
})
.await
.log_err()

View file

@ -1,4 +1,4 @@
use anyhow::{Result, anyhow};
use anyhow::{Context as _, Result};
use async_trait::async_trait;
use futures::StreamExt;
use gpui::AsyncApp;
@ -173,20 +173,17 @@ async fn get_cached_server_binary(
last_version_dir = Some(entry.path());
}
}
let last_version_dir = last_version_dir.ok_or_else(|| anyhow!("no cached binary"))?;
let last_version_dir = last_version_dir.context("no cached binary")?;
let server_path = last_version_dir.join(SERVER_PATH);
if server_path.exists() {
Ok(LanguageServerBinary {
path: node.binary_path().await?,
env: None,
arguments: server_binary_arguments(&server_path),
})
} else {
Err(anyhow!(
"missing executable in directory {:?}",
last_version_dir
))
}
anyhow::ensure!(
server_path.exists(),
"missing executable in directory {last_version_dir:?}"
);
Ok(LanguageServerBinary {
path: node.binary_path().await?,
env: None,
arguments: server_binary_arguments(&server_path),
})
})
.await
.log_err()