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

@ -252,13 +252,7 @@ impl WorkDirectory {
match self {
WorkDirectory::InProject { relative_path } => Ok(path
.strip_prefix(relative_path)
.map_err(|_| {
anyhow!(
"could not relativize {:?} against {:?}",
path,
relative_path
)
})?
.map_err(|_| anyhow!("could not relativize {path:?} against {relative_path:?}"))?
.into()),
WorkDirectory::AboveProject {
location_in_repo, ..
@ -1093,7 +1087,7 @@ impl Worktree {
),
)
})?;
task.ok_or_else(|| anyhow!("invalid entry"))?.await?;
task.context("invalid entry")?.await?;
Ok(proto::ProjectEntryResponse {
entry: None,
worktree_scan_id: scan_id as u64,
@ -1108,7 +1102,7 @@ impl Worktree {
let task = this.update(&mut cx, |this, cx| {
this.expand_entry(ProjectEntryId::from_proto(request.entry_id), cx)
})?;
task.ok_or_else(|| anyhow!("no such entry"))?.await?;
task.context("no such entry")?.await?;
let scan_id = this.read_with(&cx, |this, _| this.scan_id())?;
Ok(proto::ExpandProjectEntryResponse {
worktree_scan_id: scan_id as u64,
@ -1123,7 +1117,7 @@ impl Worktree {
let task = this.update(&mut cx, |this, cx| {
this.expand_all_for_entry(ProjectEntryId::from_proto(request.entry_id), cx)
})?;
task.ok_or_else(|| anyhow!("no such entry"))?.await?;
task.context("no such entry")?.await?;
let scan_id = this.read_with(&cx, |this, _| this.scan_id())?;
Ok(proto::ExpandAllForProjectEntryResponse {
worktree_scan_id: scan_id as u64,
@ -1487,9 +1481,7 @@ impl LocalWorktree {
let abs_path = abs_path?;
let content = fs.load_bytes(&abs_path).await?;
let worktree = worktree
.upgrade()
.ok_or_else(|| anyhow!("worktree was dropped"))?;
let worktree = worktree.upgrade().context("worktree was dropped")?;
let file = match entry.await? {
Some(entry) => File::for_entry(entry, worktree),
None => {
@ -1544,9 +1536,7 @@ impl LocalWorktree {
}
let text = fs.load(&abs_path).await?;
let worktree = this
.upgrade()
.ok_or_else(|| anyhow!("worktree was dropped"))?;
let worktree = this.upgrade().context("worktree was dropped")?;
let file = match entry.await? {
Some(entry) => File::for_entry(entry, worktree),
None => {
@ -1683,7 +1673,7 @@ impl LocalWorktree {
.refresh_entry(path.clone(), None, cx)
})?
.await?;
let worktree = this.upgrade().ok_or_else(|| anyhow!("worktree dropped"))?;
let worktree = this.upgrade().context("worktree dropped")?;
if let Some(entry) = entry {
Ok(File::for_entry(entry, worktree))
} else {
@ -1930,17 +1920,17 @@ impl LocalWorktree {
)
.await
.with_context(|| {
anyhow!("Failed to copy file from {source:?} to {target:?}")
format!("Failed to copy file from {source:?} to {target:?}")
})?;
}
Ok::<(), anyhow::Error>(())
anyhow::Ok(())
})
.await
.log_err();
let mut refresh = cx.read_entity(
&this.upgrade().with_context(|| "Dropped worktree")?,
|this, _| {
Ok::<postage::barrier::Receiver, anyhow::Error>(
anyhow::Ok::<postage::barrier::Receiver>(
this.as_local()
.with_context(|| "Worktree is not local")?
.refresh_entries_for_paths(paths_to_refresh.clone()),
@ -1950,7 +1940,7 @@ impl LocalWorktree {
cx.background_spawn(async move {
refresh.next().await;
Ok::<(), anyhow::Error>(())
anyhow::Ok(())
})
.await
.log_err();
@ -2040,7 +2030,7 @@ impl LocalWorktree {
let new_entry = this.update(cx, |this, _| {
this.entry_for_path(path)
.cloned()
.ok_or_else(|| anyhow!("failed to read path after update"))
.context("reading path after update")
})??;
Ok(Some(new_entry))
})
@ -2301,7 +2291,7 @@ impl RemoteWorktree {
paths_to_copy: Vec<Arc<Path>>,
local_fs: Arc<dyn Fs>,
cx: &Context<Worktree>,
) -> Task<Result<Vec<ProjectEntryId>, anyhow::Error>> {
) -> Task<anyhow::Result<Vec<ProjectEntryId>>> {
let client = self.client.clone();
let worktree_id = self.id().to_proto();
let project_id = self.project_id;
@ -2424,7 +2414,7 @@ impl Snapshot {
.components()
.any(|component| !matches!(component, std::path::Component::Normal(_)))
{
return Err(anyhow!("invalid path"));
anyhow::bail!("invalid path");
}
if path.file_name().is_some() {
Ok(self.abs_path.as_path().join(path))
@ -3402,15 +3392,12 @@ impl File {
worktree: Entity<Worktree>,
cx: &App,
) -> Result<Self> {
let worktree_id = worktree
.read(cx)
.as_remote()
.ok_or_else(|| anyhow!("not remote"))?
.id();
let worktree_id = worktree.read(cx).as_remote().context("not remote")?.id();
if worktree_id.to_proto() != proto.worktree_id {
return Err(anyhow!("worktree id does not match file"));
}
anyhow::ensure!(
worktree_id.to_proto() == proto.worktree_id,
"worktree id does not match file"
);
let disk_state = if proto.is_deleted {
DiskState::Deleted
@ -5559,7 +5546,7 @@ impl CreatedEntry {
fn parse_gitfile(content: &str) -> anyhow::Result<&Path> {
let path = content
.strip_prefix("gitdir:")
.ok_or_else(|| anyhow!("failed to parse gitfile content {content:?}"))?;
.with_context(|| format!("parsing gitfile content {content:?}"))?;
Ok(Path::new(path.trim()))
}