rust/rhg/src/error.rs
author Antoine Cezar <antoine.cezar@octobus.net>
Tue, 21 Jul 2020 10:39:30 +0200
changeset 45360 227281e76c22
parent 45049 513b3ef277a3
child 45361 47997afadf08
permissions -rw-r--r--
rhg: Do not return error when when we really mean ok in commands Before when a command was successfull `Err(CommandErrorKind::Ok.into())` was returned which is an oxymoron. Using `Ok(())` when everything is ok seems more appropriate. Differential Revision: https://phab.mercurial-scm.org/D8864

use crate::exitcode;
use crate::ui::UiError;
use std::convert::From;

/// The kind of command error
#[derive(Debug, PartialEq)]
pub enum CommandErrorKind {
    /// The root of the repository cannot be found
    RootNotFound,
    /// The current directory cannot be found
    CurrentDirNotFound,
    /// The standard output stream cannot be written to
    StdoutError,
    /// The standard error stream cannot be written to
    StderrError,
}

impl CommandErrorKind {
    pub fn get_exit_code(&self) -> exitcode::ExitCode {
        match self {
            CommandErrorKind::RootNotFound => exitcode::ABORT,
            CommandErrorKind::CurrentDirNotFound => exitcode::ABORT,
            CommandErrorKind::StdoutError => exitcode::ABORT,
            CommandErrorKind::StderrError => exitcode::ABORT,
        }
    }
}

/// The error type for the Command trait
#[derive(Debug, PartialEq)]
pub struct CommandError {
    pub kind: CommandErrorKind,
}

impl CommandError {
    /// Exist the process with the corresponding exit code.
    pub fn exit(&self) -> () {
        std::process::exit(self.kind.get_exit_code())
    }
}

impl From<CommandErrorKind> for CommandError {
    fn from(kind: CommandErrorKind) -> Self {
        CommandError { kind }
    }
}

impl From<UiError> for CommandError {
    fn from(error: UiError) -> Self {
        CommandError {
            kind: match error {
                UiError::StdoutError(_) => CommandErrorKind::StdoutError,
                UiError::StderrError(_) => CommandErrorKind::StderrError,
            },
        }
    }
}