Skip to content

Commit

Permalink
Cleanup errors
Browse files Browse the repository at this point in the history
Signed-off-by: simonsan <[email protected]>
  • Loading branch information
simonsan committed Oct 27, 2024
1 parent 56c45af commit b31054c
Show file tree
Hide file tree
Showing 11 changed files with 23 additions and 234 deletions.
12 changes: 2 additions & 10 deletions crates/core/src/archiver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,9 @@ use crate::{
Progress,
};

/// [`ArchiverErrorKind`] describes the errors that can be returned from the archiver
#[derive(thiserror::Error, Debug, displaydoc::Display)]
#[non_exhaustive]
pub enum ArchiverErrorKind {
/// tree stack empty
TreeStackEmpty,
/// couldn't determine size for item in Archiver
CouldNotDetermineSize,
}

pub(crate) type ArchiverResult<T> = Result<T, ArchiverErrorKind>;
/// Tree stack empty
pub struct TreeStackEmptyError;

/// The `Archiver` is responsible for archiving files and trees.
/// It will read the file, chunk it, and write the chunks to the backend.
Expand Down
8 changes: 4 additions & 4 deletions crates/core/src/archiver/parent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::{
use log::warn;

use crate::{
archiver::{tree::TreeType, ArchiverErrorKind, ArchiverResult},
archiver::{tree::TreeType, TreeStackEmptyError},
backend::{decrypt::DecryptReadBackend, node::Node},
blob::tree::{Tree, TreeId},
index::ReadGlobalIndex,
Expand Down Expand Up @@ -218,8 +218,8 @@ impl Parent {
/// # Errors
///
/// * If the tree stack is empty.
fn finish_dir(&mut self) -> ArchiverResult<()> {
let (tree, node_idx) = self.stack.pop().ok_or(ArchiverErrorKind::TreeStackEmpty)?;
fn finish_dir(&mut self) -> Result<(), TreeStackEmptyError> {
let (tree, node_idx) = self.stack.pop().ok_or(TreeStackEmptyError)?;

self.tree = tree;
self.node_idx = node_idx;
Expand Down Expand Up @@ -252,7 +252,7 @@ impl Parent {
be: &impl DecryptReadBackend,
index: &impl ReadGlobalIndex,
item: TreeType<O, OsString>,
) -> ArchiverResult<ItemWithParent<O>> {
) -> Result<ItemWithParent<O>, TreeStackEmptyError> {
let result = match item {
TreeType::NewTree((path, node, tree)) => {
let parent_result = self
Expand Down
55 changes: 1 addition & 54 deletions crates/core/src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ pub(crate) mod node;
pub(crate) mod stdin;
pub(crate) mod warm_up;

use std::{io::Read, num::TryFromIntError, ops::Deref, path::PathBuf, sync::Arc};
use std::{io::Read, ops::Deref, path::PathBuf, sync::Arc};

use bytes::Bytes;
use enum_map::Enum;
Expand All @@ -31,64 +31,11 @@ use crate::{
#[derive(thiserror::Error, Debug, displaydoc::Display)]
#[non_exhaustive]
pub enum BackendErrorKind {
/// backend `{0:?}` is not supported!
BackendNotSupported(String),
/// no suitable id found for `{0}`
NoSuitableIdFound(String),
/// id `{0}` is not unique
IdNotUnique(String),
/// creating data in backend failed
CreatingDataOnBackendFailed,
/// writing bytes to backend failed
WritingBytesToBackendFailed,
/// removing data from backend failed
RemovingDataFromBackendFailed,
/// failed to list files on Backend
ListingFilesOnBackendFailed,
/// Path is not allowed: `{0:?}`
PathNotAllowed(PathBuf),
/// Backend location not convertible: `{location}`
BackendLocationNotConvertible { location: String },
}

/// [`CryptBackendErrorKind`] describes the errors that can be returned by a Decryption action in Backends
#[derive(thiserror::Error, Debug, displaydoc::Display)]
#[non_exhaustive]
pub enum CryptBackendErrorKind {
/// decryption not supported for backend
DecryptionNotSupportedForBackend,
/// length of uncompressed data does not match!
LengthOfUncompressedDataDoesNotMatch,
/// failed to read encrypted data during full read
DecryptionInFullReadFailed,
/// failed to read encrypted data during partial read
DecryptionInPartialReadFailed,
/// decrypting from backend failed
DecryptingFromBackendFailed,
/// deserializing from bytes of JSON Text failed: `{0:?}`
DeserializingFromBytesOfJsonTextFailed(serde_json::Error),
/// failed to write data in crypt backend
WritingDataInCryptBackendFailed,
/// failed to list Ids
ListingIdsInDecryptionBackendFailed,
/// writing full hash failed in `CryptBackend`
WritingFullHashFailed,
/// decoding Zstd compressed data failed: `{0:?}`
DecodingZstdCompressedDataFailed(std::io::Error),
/// Serializing to JSON byte vector failed: `{0:?}`
SerializingToJsonByteVectorFailed(serde_json::Error),
/// encrypting data failed
EncryptingDataFailed,
/// Compressing and appending data failed: `{0:?}`
CopyEncodingDataFailed(std::io::Error),
/// conversion for integer failed: `{0:?}`
IntConversionFailed(TryFromIntError),
/// Extra verification failed: After decrypting and decompressing the data changed!
ExtraVerificationFailed,
}

pub(crate) type BackendResult<T> = Result<T, BackendErrorKind>;
pub(crate) type CryptBackendResult<T> = Result<T, CryptBackendErrorKind>;

/// All [`FileType`]s which are located in separated directories
pub const ALL_FILE_TYPES: [FileType; 4] = [
Expand Down
9 changes: 5 additions & 4 deletions crates/core/src/backend/local_destination.rs
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@ impl LocalDestination {
/// # Errors
///
/// * If the user/group could not be set.
#[allow(clippy::unused_self)]
#[allow(clippy::unused_self, clippy::unnecessary_wraps)]
pub(crate) fn set_user_group(
&self,
_item: impl AsRef<Path>,
Expand Down Expand Up @@ -355,7 +355,7 @@ impl LocalDestination {
/// # Errors
///
/// * If the uid/gid could not be set.
#[allow(clippy::unused_self)]
#[allow(clippy::unused_self, clippy::unnecessary_wraps)]
pub(crate) fn set_uid_gid(
&self,
_item: impl AsRef<Path>,
Expand Down Expand Up @@ -403,7 +403,7 @@ impl LocalDestination {
/// # Errors
///
/// * If the permissions could not be set.
#[allow(clippy::unused_self)]
#[allow(clippy::unused_self, clippy::unnecessary_wraps)]
pub(crate) fn set_permission(
&self,
_item: impl AsRef<Path>,
Expand Down Expand Up @@ -456,7 +456,7 @@ impl LocalDestination {
/// # Errors
///
/// * If the extended attributes could not be set.
#[allow(clippy::unused_self)]
#[allow(clippy::unused_self, clippy::unnecessary_wraps)]
pub(crate) fn set_extended_attributes(
&self,
_item: impl AsRef<Path>,
Expand Down Expand Up @@ -600,6 +600,7 @@ impl LocalDestination {
/// # Returns
///
/// Ok if the special file was created.
#[allow(clippy::unused_self, clippy::unnecessary_wraps)]
pub(crate) fn create_special(
&self,
_item: impl AsRef<Path>,
Expand Down
8 changes: 0 additions & 8 deletions crates/core/src/chunker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,6 @@ use crate::{
error::{ErrorKind, RusticError, RusticResult},
};

/// [`PolynomialErrorKind`] describes the errors that can happen while dealing with Polynomials
#[derive(thiserror::Error, Debug, displaydoc::Display)]
#[non_exhaustive]
pub enum PolynomialErrorKind {
/// no suitable polynomial found
NoSuitablePolynomialFound,
}

pub(super) mod constants {
/// The Splitmask is used to determine if a chunk is a chunk boundary.
pub(super) const SPLITMASK: u64 = (1u64 << 20) - 1;
Expand Down
44 changes: 0 additions & 44 deletions crates/core/src/commands.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,5 @@
//! The commands that can be run by the CLI.

use std::{num::TryFromIntError, path::PathBuf};

use chrono::OutOfRangeError;

use crate::{backend::node::NodeType, blob::BlobId, repofile::packfile::PackId, RusticError};

pub mod backup;
/// The `cat` command.
pub mod cat;
Expand All @@ -26,41 +20,3 @@ pub mod repair;
pub mod repoinfo;
pub mod restore;
pub mod snapshots;

/// [`CommandErrorKind`] describes the errors that can happen while executing a high-level command
#[derive(thiserror::Error, Debug, displaydoc::Display)]
#[non_exhaustive]
pub enum CommandErrorKind {
/// path is no dir: `{0}`
PathIsNoDir(String),
/// used blobs are missing: blob `{0}` doesn't existing
BlobsMissing(BlobId),
/// used pack `{0}`: size does not match! Expected size: `{1}`, real size: `{2}`
PackSizeNotMatching(PackId, u32, u32),
/// used pack `{0}` does not exist!
PackNotExisting(PackId),
/// pack `{0}` got no decision what to do
NoDecision(PackId),
/// Bytesize parser failed: `{0}`
FromByteSizeParser(String),
/// --repack-uncompressed makes no sense for v1 repo!
RepackUncompressedRepoV1,
/// datetime out of range: `{0}`
FromOutOfRangeError(OutOfRangeError),
/// node type `{0:?}` not supported by dump
DumpNotSupported(NodeType),
/// error creating `{0:?}`: `{1:?}`
ErrorCreating(PathBuf, Box<RusticError>),
/// error collecting information for `{0:?}`: `{1:?}`
ErrorCollecting(PathBuf, Box<RusticError>),
/// error setting length for `{0:?}`: `{1:?}`
ErrorSettingLength(PathBuf, Box<RusticError>),
/// Conversion from integer failed: `{0:?}`
ConversionFromIntFailed(TryFromIntError),
/// Specify one of the keep-* options for forget! Please use keep-none to keep no snapshot.
NoKeepOption,
/// Checking the repository failed!
CheckFailed,
}

pub(crate) type CommandResult<T> = Result<T, CommandErrorKind>;
72 changes: 0 additions & 72 deletions crates/core/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -413,76 +413,4 @@ pub enum ErrorKind {
Verification,
/// Virtual File System Error
Vfs,
// /// The repository password is incorrect. Please try again.
// IncorrectRepositoryPassword,
// /// No repository given. Please use the --repository option.
// NoRepositoryGiven,
// /// No password given. Please use one of the --password-* options.
// NoPasswordGiven,
// /// warm-up command must contain %id!
// NoIDSpecified,
// /// error opening password file `{0:?}`
// OpeningPasswordFileFailed(std::io::Error),
// /// No repository config file found. Is there a repo at `{0}`?
// NoRepositoryConfigFound(String),
// /// More than one repository config file at `{0}`. Aborting.
// MoreThanOneRepositoryConfig(String),
// /// keys from repo and repo-hot do not match for `{0}`. Aborting.
// KeysDontMatchForRepositories(String),
// /// repository is a hot repository!\nPlease use as --repo-hot in combination with the normal repo. Aborting.
// HotRepositoryFlagMissing,
// /// repo-hot is not a hot repository! Aborting.
// IsNotHotRepository,
// /// incorrect password!
// IncorrectPassword,
// /// error running the password command
// PasswordCommandExecutionFailed,
// /// error reading password from command
// ReadingPasswordFromCommandFailed,
// /// running command `{0}`:`{1}` was not successful: `{2}`
// CommandExecutionFailed(String, String, std::io::Error),
// /// running command {0}:{1} returned status: `{2}`
// CommandErrorStatus(String, String, ExitStatus),
// /// error listing the repo config file
// ListingRepositoryConfigFileFailed,
// /// error listing the repo keys
// ListingRepositoryKeysFailed,
// /// error listing the hot repo keys
// ListingHotRepositoryKeysFailed,
// /// error accessing config file
// AccessToConfigFileFailed,
// /// Thread pool build error: `{0:?}`
// FromThreadPoolbilderError(rayon::ThreadPoolBuildError),
// /// reading Password failed: `{0:?}`
// ReadingPasswordFromReaderFailed(std::io::Error),
// /// reading Password from prompt failed: `{0:?}`
// ReadingPasswordFromPromptFailed(std::io::Error),
// /// Config file already exists. Aborting.
// ConfigFileExists,
// /// did not find id `{0}` in index
// IdNotFound(BlobId),
// /// no suitable backend type found
// NoBackendTypeGiven,
// /// Hex decoding error: `{0:?}`
// HexError(hex::FromHexError),
}

// TODO: Possible more general categories for errors for RusticErrorKind (WIP):
//
// - **JSON Parsing Errors**: e.g., `serde_json::Error`
// - **Version Errors**: e.g., `VersionNotSupported`, `CannotDowngrade`
// - **Compression Errors**: e.g., `NoCompressionV1Repo`, `CompressionLevelNotSupported`
// - **Size Errors**: e.g., `SizeTooLarge`
// - **File and Path Errors**: e.g., `ErrorCreating`, `ErrorCollecting`, `ErrorSettingLength`
// - **Thread Pool Errors**: e.g., `rayon::ThreadPoolBuildError`
// - **Conversion Errors**: e.g., `ConversionFromIntFailed`
// - **Permission Errors**: e.g., `NotAllowedWithAppendOnly`
// - **Parsing Errors**: e.g., `shell_words::ParseError`
// - **Cryptographic Errors**: e.g., `DataDecryptionFailed`, `DataEncryptionFailed`, `CryptoKeyTooShort`
// - **Polynomial Errors**: e.g., `NoSuitablePolynomialFound`
// - **File Handling Errors**: e.g., `TransposingOptionResultFailed`, `ConversionFromU64ToUsizeFailed`
// - **ID Processing Errors**: e.g., `HexError`
// - **Repository Errors**: general repository-related errors
// - **Backend Access Errors**: e.g., `BackendNotSupported`, `BackendLoadError`, `NoSuitableIdFound`, `IdNotUnique`
// - **Rclone Errors**: e.g., `NoOutputForRcloneVersion`, `NoStdOutForRclone`, `RCloneExitWithBadStatus`
// - **REST API Errors**: e.g., `NotSupportedForRetry`, `UrlParsingFailed`
19 changes: 1 addition & 18 deletions crates/core/src/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use bytes::Bytes;
use derive_more::Constructor;

use crate::{
backend::{decrypt::DecryptReadBackend, CryptBackendErrorKind, FileType},
backend::{decrypt::DecryptReadBackend, FileType},
blob::{tree::TreeId, BlobId, BlobType, DataId},
error::{ErrorKind, RusticError, RusticResult},
index::binarysorted::{Index, IndexCollector, IndexType},
Expand All @@ -18,23 +18,6 @@ use crate::{
pub(crate) mod binarysorted;
pub(crate) mod indexer;

/// [`IndexErrorKind`] describes the errors that can be returned by processing Indizes
#[derive(thiserror::Error, Debug, displaydoc::Display)]
#[non_exhaustive]
pub enum IndexErrorKind {
/// blob not found in index
BlobInIndexNotFound,
/// failed to get a blob from the backend
GettingBlobIndexEntryFromBackendFailed,
/// saving `IndexFile` failed
SavingIndexFileFailed {
/// the error that occurred
source: CryptBackendErrorKind,
},
}

pub(crate) type IndexResult<T> = Result<T, IndexErrorKind>;

/// An entry in the index
#[derive(Debug, Clone, Copy, PartialEq, Eq, Constructor)]
pub struct IndexEntry {
Expand Down
2 changes: 1 addition & 1 deletion crates/core/src/repofile/snapshotfile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1249,7 +1249,7 @@ impl PathList {
/// # Errors
///
/// * no errors can occur here
/// * RusticResult is used for consistency and future compatibility
/// * [`RusticResult`] is used for consistency and future compatibility
pub fn from_string(source: &str) -> RusticResult<Self> {
Ok(Self(vec![source.into()]))
}
Expand Down
10 changes: 0 additions & 10 deletions crates/core/src/repository/warm_up.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,6 @@ use crate::{
CommandInput,
};

/// [`WarmupErrorKind`] describes the errors that can be returned from Warmup
#[derive(thiserror::Error, Debug, displaydoc::Display)]
#[non_exhaustive]
pub enum WarmupErrorKind {
/// Error in warm-up command
General,
}

pub(crate) type WarmupResult<T> = Result<T, WarmupErrorKind>;

pub(super) mod constants {
/// The maximum number of reader threads to use for warm-up.
pub(super) const MAX_READER_THREADS_NUM: usize = 20;
Expand Down
18 changes: 9 additions & 9 deletions crates/core/src/vfs/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,15 @@ use runtime_format::{FormatKey, FormatKeyError};
/// To be formatted with [`runtime_format`].
///
/// The following keys are available:
/// - `id`: the snapshot id
/// - `long_id`: the snapshot id as a string
/// - `time`: the snapshot time
/// - `username`: the snapshot username
/// - `hostname`: the snapshot hostname
/// - `label`: the snapshot label
/// - `tags`: the snapshot tags
/// - `backup_start`: the snapshot backup start time
/// - `backup_end`: the snapshot backup end time
/// * `id`: the snapshot id
/// * `long_id`: the snapshot id as a string
/// * `time`: the snapshot time
/// * `username`: the snapshot username
/// * `hostname`: the snapshot hostname
/// * `label`: the snapshot label
/// * `tags`: the snapshot tags
/// * `backup_start`: the snapshot backup start time
/// * `backup_end`: the snapshot backup end time
#[derive(Debug)]
pub(crate) struct FormattedSnapshot<'a> {
/// The snapshot file.
Expand Down

0 comments on commit b31054c

Please sign in to comment.