file_util: move PathError and its helper trait from repo module

It's generally useful in order to attach context to io::Error.
This commit is contained in:
Yuya Nishihara 2023-07-05 19:41:00 +09:00
parent cf81de0484
commit 6d6b87f4b0
3 changed files with 27 additions and 24 deletions

View file

@ -13,10 +13,32 @@
// limitations under the License.
use std::fs::File;
use std::iter;
use std::path::{Component, Path, PathBuf};
use std::{io, iter};
use tempfile::{NamedTempFile, PersistError};
use thiserror::Error;
#[derive(Debug, Error)]
#[error("Cannot access {path}")]
pub struct PathError {
pub path: PathBuf,
#[source]
pub error: io::Error,
}
pub(crate) trait IoResultExt<T> {
fn context(self, path: impl AsRef<Path>) -> Result<T, PathError>;
}
impl<T> IoResultExt<T> for io::Result<T> {
fn context(self, path: impl AsRef<Path>) -> Result<T, PathError> {
self.map_err(|error| PathError {
path: path.as_ref().to_path_buf(),
error,
})
}
}
/// Turns the given `to` path into relative path starting from the `from` path.
///

View file

@ -31,6 +31,7 @@ use crate::commit::Commit;
use crate::commit_builder::CommitBuilder;
use crate::default_index_store::DefaultIndexStore;
use crate::default_submodule_store::DefaultSubmoduleStore;
use crate::file_util::{IoResultExt as _, PathError};
use crate::git_backend::GitBackend;
use crate::index::{HexPrefix, Index, IndexStore, MutableIndex, PrefixResolution, ReadonlyIndex};
use crate::local_backend::LocalBackend;
@ -1306,27 +1307,6 @@ pub enum CheckOutCommitError {
EditCommit(#[from] EditCommitError),
}
#[derive(Debug, Error)]
#[error("Cannot access {path}")]
pub struct PathError {
pub path: PathBuf,
#[source]
pub error: io::Error,
}
pub(crate) trait IoResultExt<T> {
fn context(self, path: impl AsRef<Path>) -> Result<T, PathError>;
}
impl<T> IoResultExt<T> for io::Result<T> {
fn context(self, path: impl AsRef<Path>) -> Result<T, PathError> {
self.map_err(|error| PathError {
path: path.as_ref().to_path_buf(),
error,
})
}
}
mod dirty_cell {
use std::cell::{Cell, RefCell};

View file

@ -20,14 +20,15 @@ use std::sync::Arc;
use thiserror::Error;
use crate::backend::{Backend, BackendError};
use crate::file_util::{IoResultExt as _, PathError};
use crate::git_backend::GitBackend;
use crate::index::IndexStore;
use crate::local_backend::LocalBackend;
use crate::op_heads_store::OpHeadsStore;
use crate::op_store::{OpStore, WorkspaceId};
use crate::repo::{
CheckOutCommitError, IoResultExt, PathError, ReadonlyRepo, Repo, RepoInitError, RepoLoader,
StoreFactories, StoreLoadError,
CheckOutCommitError, ReadonlyRepo, Repo, RepoInitError, RepoLoader, StoreFactories,
StoreLoadError,
};
use crate::settings::UserSettings;
use crate::submodule_store::SubmoduleStore;