feat(cli): add error struct
This commit is contained in:
parent
db631fddd2
commit
ba73786a38
3 changed files with 151 additions and 28 deletions
|
@ -1,3 +1,4 @@
|
||||||
|
use crate::error::{Error, ErrorKind};
|
||||||
use crate::migration::Migration;
|
use crate::migration::Migration;
|
||||||
use crate::path::PathBuilder;
|
use crate::path::PathBuilder;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
@ -118,21 +119,17 @@ impl Config {
|
||||||
.build()
|
.build()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn database_connection(&self) -> String {
|
pub fn database_connection_string(&self) -> crate::error::Result<String> {
|
||||||
let connection = self
|
let connection = self
|
||||||
.database
|
.database
|
||||||
.connection
|
.connection
|
||||||
.clone()
|
.clone()
|
||||||
.unwrap_or_else(|| String::from(DEFAULT_DATABASE_CONNECTION_ENV));
|
.unwrap_or_else(|| String::from(DEFAULT_DATABASE_CONNECTION_ENV));
|
||||||
if let Some(connection_env) = connection.strip_prefix("$") {
|
if let Some(connection_env) = connection.strip_prefix("$") {
|
||||||
env::var(connection_env).unwrap_or_else(|_| {
|
env::var(connection_env)
|
||||||
panic!(
|
.map_err(|e| Error::new(ErrorKind::MissedEnvVar(connection_env.to_string()), e))
|
||||||
r#"You need to provide "{}" environment variable"#,
|
|
||||||
connection_env
|
|
||||||
)
|
|
||||||
})
|
|
||||||
} else {
|
} else {
|
||||||
connection
|
Ok(connection)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -143,11 +140,16 @@ impl Config {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn migrations(&self) -> io::Result<Vec<Migration>> {
|
pub fn migrations(&self) -> io::Result<Vec<Migration>> {
|
||||||
let mut entries = self
|
let mut entries = match self.migration_dir_path().read_dir() {
|
||||||
.migration_dir_path()
|
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
|
||||||
.read_dir()?
|
entries => entries?
|
||||||
.map(|res| res.map(|e| e.path()))
|
.map(|res| res.map(|e| e.path()))
|
||||||
.collect::<Result<Vec<_>, io::Error>>()?;
|
.collect::<Result<Vec<_>, io::Error>>()?,
|
||||||
|
};
|
||||||
|
|
||||||
|
if entries.is_empty() {
|
||||||
|
return Ok(vec![]);
|
||||||
|
}
|
||||||
|
|
||||||
entries.sort();
|
entries.sort();
|
||||||
|
|
||||||
|
|
101
migra-cli/src/error.rs
Normal file
101
migra-cli/src/error.rs
Normal file
|
@ -0,0 +1,101 @@
|
||||||
|
use std::error::Error as StdError;
|
||||||
|
use std::fmt;
|
||||||
|
use std::mem;
|
||||||
|
use std::result;
|
||||||
|
|
||||||
|
pub type Result<T> = result::Result<T, Error>;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Error {
|
||||||
|
repr: Repr,
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Repr {
|
||||||
|
Simple(ErrorKind),
|
||||||
|
Custom(Box<Custom>),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct Custom {
|
||||||
|
kind: ErrorKind,
|
||||||
|
error: Box<dyn StdError + Send + Sync>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub enum ErrorKind {
|
||||||
|
MissedEnvVar(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for ErrorKind {
|
||||||
|
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
match *self {
|
||||||
|
ErrorKind::MissedEnvVar(ref name) => {
|
||||||
|
write!(fmt, r#"Missed "{}" environment variable"#, name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PartialEq for ErrorKind {
|
||||||
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
mem::discriminant(self) == mem::discriminant(other)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<ErrorKind> for Error {
|
||||||
|
#[inline]
|
||||||
|
fn from(kind: ErrorKind) -> Error {
|
||||||
|
Error {
|
||||||
|
repr: Repr::Simple(kind),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Error {
|
||||||
|
pub fn new<E>(kind: ErrorKind, error: E) -> Error
|
||||||
|
where
|
||||||
|
E: Into<Box<dyn StdError + Send + Sync>>,
|
||||||
|
{
|
||||||
|
Self::_new(kind, error.into())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn _new(kind: ErrorKind, error: Box<dyn StdError + Send + Sync>) -> Error {
|
||||||
|
Error {
|
||||||
|
repr: Repr::Custom(Box::new(Custom { kind, error })),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn kind(&self) -> &ErrorKind {
|
||||||
|
match &self.repr {
|
||||||
|
Repr::Custom(ref c) => &c.kind,
|
||||||
|
Repr::Simple(kind) => &kind,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for Repr {
|
||||||
|
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
Repr::Custom(ref c) => fmt::Debug::fmt(&c, fmt),
|
||||||
|
Repr::Simple(kind) => fmt.debug_tuple("Kind").field(&kind).finish(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for Error {
|
||||||
|
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
match &self.repr {
|
||||||
|
Repr::Custom(ref c) => c.error.fmt(fmt),
|
||||||
|
Repr::Simple(kind) => write!(fmt, "{}", kind),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl StdError for Error {
|
||||||
|
fn source(&self) -> Option<&(dyn StdError + 'static)> {
|
||||||
|
match self.repr {
|
||||||
|
Repr::Simple(..) => None,
|
||||||
|
Repr::Custom(ref c) => c.error.source(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -2,16 +2,20 @@
|
||||||
|
|
||||||
mod config;
|
mod config;
|
||||||
mod database;
|
mod database;
|
||||||
|
mod error;
|
||||||
mod migration;
|
mod migration;
|
||||||
mod opts;
|
mod opts;
|
||||||
mod path;
|
mod path;
|
||||||
|
|
||||||
use chrono::Local;
|
use chrono::Local;
|
||||||
use config::Config;
|
use config::Config;
|
||||||
|
use error::ErrorKind;
|
||||||
use opts::{AppOpt, ApplyCommandOpt, Command, MakeCommandOpt, StructOpt};
|
use opts::{AppOpt, ApplyCommandOpt, Command, MakeCommandOpt, StructOpt};
|
||||||
use path::PathBuilder;
|
use path::PathBuilder;
|
||||||
use std::fs;
|
use std::fs;
|
||||||
|
|
||||||
|
const EM_DASH: char = '—';
|
||||||
|
|
||||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
let opt = AppOpt::from_args();
|
let opt = AppOpt::from_args();
|
||||||
|
|
||||||
|
@ -22,7 +26,8 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
Command::Apply(ApplyCommandOpt { file_name }) => {
|
Command::Apply(ApplyCommandOpt { file_name }) => {
|
||||||
let config = Config::read(opt.config)?;
|
let config = Config::read(opt.config)?;
|
||||||
|
|
||||||
let mut client = database::connect(&config.database_connection())?;
|
let database_connection_string = &config.database_connection_string()?;
|
||||||
|
let mut client = database::connect(database_connection_string)?;
|
||||||
|
|
||||||
let file_path = PathBuilder::from(config.directory_path())
|
let file_path = PathBuilder::from(config.directory_path())
|
||||||
.append(file_name)
|
.append(file_name)
|
||||||
|
@ -81,18 +86,31 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
Command::List => {
|
Command::List => {
|
||||||
let config = Config::read(opt.config)?;
|
let config = Config::read(opt.config)?;
|
||||||
|
|
||||||
let mut client = database::connect(&config.database_connection())?;
|
let applied_migrations = match config.database_connection_string() {
|
||||||
let applied_migrations = database::applied_migrations(&mut client)?;
|
Ok(ref database_connection_string) => {
|
||||||
|
let mut client = database::connect(database_connection_string)?;
|
||||||
|
let applied_migrations = database::applied_migrations(&mut client)?;
|
||||||
|
|
||||||
println!("Applied migrations:");
|
println!("Applied migrations:");
|
||||||
if applied_migrations.is_empty() {
|
if applied_migrations.is_empty() {
|
||||||
println!("–")
|
println!("{}", EM_DASH);
|
||||||
} else {
|
} else {
|
||||||
applied_migrations
|
applied_migrations
|
||||||
.iter()
|
.iter()
|
||||||
.rev()
|
.rev()
|
||||||
.for_each(|name| println!("{}", name));
|
.for_each(|name| println!("{}", name));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
applied_migrations
|
||||||
|
}
|
||||||
|
Err(e) if *e.kind() == ErrorKind::MissedEnvVar(String::new()) => {
|
||||||
|
println!("{}", e.kind());
|
||||||
|
println!("No connection to database");
|
||||||
|
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
Err(e) => panic!(e),
|
||||||
|
};
|
||||||
|
|
||||||
println!();
|
println!();
|
||||||
|
|
||||||
|
@ -103,7 +121,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
println!("Pending migrations:");
|
println!("Pending migrations:");
|
||||||
if pending_migrations.is_empty() {
|
if pending_migrations.is_empty() {
|
||||||
println!("–");
|
println!("{}", EM_DASH);
|
||||||
} else {
|
} else {
|
||||||
pending_migrations.iter().for_each(|m| {
|
pending_migrations.iter().for_each(|m| {
|
||||||
println!("{}", m.name());
|
println!("{}", m.name());
|
||||||
|
@ -113,7 +131,8 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
Command::Upgrade => {
|
Command::Upgrade => {
|
||||||
let config = Config::read(opt.config)?;
|
let config = Config::read(opt.config)?;
|
||||||
|
|
||||||
let mut client = database::connect(&config.database_connection())?;
|
let database_connection_string = &config.database_connection_string()?;
|
||||||
|
let mut client = database::connect(database_connection_string)?;
|
||||||
|
|
||||||
let applied_migrations = database::applied_migrations(&mut client)?;
|
let applied_migrations = database::applied_migrations(&mut client)?;
|
||||||
|
|
||||||
|
@ -136,7 +155,8 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
Command::Downgrade => {
|
Command::Downgrade => {
|
||||||
let config = Config::read(opt.config)?;
|
let config = Config::read(opt.config)?;
|
||||||
|
|
||||||
let mut client = database::connect(&config.database_connection())?;
|
let database_connection_string = &config.database_connection_string()?;
|
||||||
|
let mut client = database::connect(database_connection_string)?;
|
||||||
|
|
||||||
let applied_migrations = database::applied_migrations(&mut client)?;
|
let applied_migrations = database::applied_migrations(&mut client)?;
|
||||||
let migrations = config.migrations()?;
|
let migrations = config.migrations()?;
|
||||||
|
|
Reference in a new issue