From 5a4a3c8eb096fd2d37275ba9540f52f832fd1f8c Mon Sep 17 00:00:00 2001 From: Dmitriy Pleshevskiy Date: Sun, 23 May 2021 23:28:29 +0300 Subject: [PATCH] feat: add error and fs utils --- migra/src/error.rs | 32 ++++++++++++++++++++++++++++++++ migra/src/fs.rs | 33 +++++++++++++++++++++++++++++++++ migra/src/lib.rs | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 97 insertions(+) create mode 100644 migra/src/error.rs create mode 100644 migra/src/fs.rs diff --git a/migra/src/error.rs b/migra/src/error.rs new file mode 100644 index 0000000..11f86ab --- /dev/null +++ b/migra/src/error.rs @@ -0,0 +1,32 @@ +use std::fmt; +use std::io; + +pub type MigraResult = Result; + +#[derive(Debug)] +pub enum Error { + Io(io::Error), +} + +impl fmt::Display for Error { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::Io(ref error) => write!(fmt, "{}", error), + } + } +} + +impl std::error::Error for Error {} + +impl PartialEq for Error { + fn eq(&self, other: &Self) -> bool { + std::mem::discriminant(self) == std::mem::discriminant(other) + } +} + +impl From for Error { + #[inline] + fn from(err: io::Error) -> Error { + Error::Io(err) + } +} diff --git a/migra/src/fs.rs b/migra/src/fs.rs new file mode 100644 index 0000000..4787963 --- /dev/null +++ b/migra/src/fs.rs @@ -0,0 +1,33 @@ +use crate::error::MigraResult; +use crate::migration; +use std::io; +use std::path::Path; + +#[must_use] +pub fn is_migration_dir(path: &Path) -> bool { + path.join("up.sql").exists() && path.join("down.sql").exists() +} + +pub fn get_all_migrations(dir_path: &Path) -> MigraResult { + let mut entries = match dir_path.read_dir() { + Err(e) if e.kind() == io::ErrorKind::NotFound => vec![], + entries => entries? + .filter_map(|res| res.ok().map(|e| e.path())) + .filter(|path| is_migration_dir(&path)) + .collect::>(), + }; + + if entries.is_empty() { + return Ok(migration::List::new()); + } + + entries.sort(); + + let file_names = entries + .iter() + .filter_map(|path| path.file_name()) + .filter_map(std::ffi::OsStr::to_str) + .collect::>(); + + Ok(migration::List::from(file_names)) +} diff --git a/migra/src/lib.rs b/migra/src/lib.rs index 60a2864..75f3b2b 100644 --- a/migra/src/lib.rs +++ b/migra/src/lib.rs @@ -2,4 +2,36 @@ #![deny(clippy::all, clippy::pedantic)] #![allow(clippy::missing_errors_doc)] +mod error; +pub mod fs; pub mod migration; + +pub use error::{Error, MigraResult as Result}; + +/* + +# list + +fs::get_all_migrations() +db::get_applied_migrations() +utils::filter_pending_migrations(all_migrations, applied_migrations) +show_migrations(applied_migrations) +show_migrations(pending_migrations) + + +# upgrade + +fs::get_all_migrations() +db::get_applied_migrations() +utils::filter_pending_migrations(all_migrations, applied_migrations) + +db::upgrade_migration() + + + +# downgrade + + + + +*/