feat: add error and fs utils

This commit is contained in:
Dmitriy Pleshevskiy 2021-05-23 23:28:29 +03:00
parent 2a2ce85381
commit 5a4a3c8eb0
3 changed files with 97 additions and 0 deletions

32
migra/src/error.rs Normal file
View File

@ -0,0 +1,32 @@
use std::fmt;
use std::io;
pub type MigraResult<T> = Result<T, Error>;
#[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<io::Error> for Error {
#[inline]
fn from(err: io::Error) -> Error {
Error::Io(err)
}
}

33
migra/src/fs.rs Normal file
View File

@ -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<migration::List> {
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::<Vec<_>>(),
};
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::<Vec<_>>();
Ok(migration::List::from(file_names))
}

View File

@ -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
*/