Skip to content

Commit

Permalink
feat: major error improvement
Browse files Browse the repository at this point in the history
  • Loading branch information
DmitryTravyan committed Dec 21, 2022
1 parent 3f79813 commit 67ffb27
Show file tree
Hide file tree
Showing 18 changed files with 1,242 additions and 66 deletions.
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,8 @@ node_modules
/deploy/.terraform.tfstate.lock.info
/deploy/terraform.tfstate
/deploy/terraform.tfstate.backup
*.genin.yml
*.genin.yaml
inventory.yml
inventory.yaml

2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "genin"
version = "0.4.11"
version = "0.4.12"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
Expand Down
20 changes: 10 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ Download and unzip the archive for the desired architecture.

Universal executable:
```shell
curl -sLO https://binary.picodata.io/repository/raw/genin/bin/genin-0.4.11-x86_64-musl.tar.gz
tar -xvf genin-0.4.11-x86_64-musl.tar.gz ; sudo install genin /usr/local/bin/
curl -sLO https://binary.picodata.io/repository/raw/genin/bin/genin-0.4.12-x86_64-musl.tar.gz
tar -xvf genin-0.4.12-x86_64-musl.tar.gz ; sudo install genin /usr/local/bin/
```

---
Expand Down Expand Up @@ -85,11 +85,11 @@ sudo yum install -y genin
2. If you want to install `rpm` packages directly without
adding our repository.
```shell
sudo rpm -i https://binary.picodata.io/repository/yum/el/8/x86_64/os/genin-0.4.11-1.el8.x86_64.rpm
sudo rpm -i https://binary.picodata.io/repository/yum/el/8/x86_64/os/genin-0.4.12-1.el8.x86_64.rpm
```
RHEL 7.x, CentOS 7.x
```shell
sudo rpm -i https://binary.picodata.io/repository/yum/el/7/x86_64/os/genin-0.4.11-1.el7.x86_64.rpm
sudo rpm -i https://binary.picodata.io/repository/yum/el/7/x86_64/os/genin-0.4.12-1.el7.x86_64.rpm
```

---
Expand Down Expand Up @@ -117,7 +117,7 @@ sudo apt install -y genin
2. Downloading and installing the package directly:
```shell
curl -sLO https://binary.picodata.io/repository/raw/genin/deb/genin-0.4.11.amd64.deb && sudo dpkg -i genin-0.4.11.amd64.deb
curl -sLO https://binary.picodata.io/repository/raw/genin/deb/genin-0.4.12.amd64.deb && sudo dpkg -i genin-0.4.12.amd64.deb
```
---
Expand All @@ -143,7 +143,7 @@ sudo apt install -y genin
2. Downloading and installing the package directly:
```shell
curl -sLO https://binary.picodata.io/repository/raw/genin/deb/genin-0.4.11.amd64.deb && sudo dpkg -i genin-0.4.11.amd64.deb
curl -sLO https://binary.picodata.io/repository/raw/genin/deb/genin-0.4.12.amd64.deb && sudo dpkg -i genin-0.4.12.amd64.deb
```
---
Expand All @@ -163,8 +163,8 @@ brew install genin
Use the following command to grab and install Genin in macOS (10.10+) wihtout
homebrew:
```shell
curl -L https://binary.picodata.io/repository/raw/genin/apple/genin-0.4.11-darwin-amd64.zip -o genin-0.4.11-darwin-amd64.zip
unzip genin-0.4.11-darwin-amd64.zip -d ~/bin/
curl -L https://binary.picodata.io/repository/raw/genin/apple/genin-0.4.12-darwin-amd64.zip -o genin-0.4.12-darwin-amd64.zip
unzip genin-0.4.12-darwin-amd64.zip -d ~/bin/
```
> **Note:** The application can then be found under the `~/bin` directory.
> Make sure the directory is in your `$PATH`.
Expand All @@ -182,8 +182,8 @@ brew install [email protected]
#### Windows
Use the following command to grab and install Genin in Windows 7 64 bit or newer:
```shell
curl.exe -L https://binary.picodata.io/repository/raw/genin/windows/genin-0.4.11-darwin-amd64.zip -o genin-0.4.11-windows-amd64.zip
unzip.exe genin-0.4.11-windows-amd64.zip -d %HOME%/.cargo/bin/
curl.exe -L https://binary.picodata.io/repository/raw/genin/windows/genin-0.4.12-darwin-amd64.zip -o genin-0.4.12-windows-amd64.zip
unzip.exe genin-0.4.12-windows-amd64.zip -d %HOME%/.cargo/bin/
```
> **Note:** The application can then be found under the `.cargo/bin` folder inside
> your user profile folder. Make sure it is in your `%PATH%`.
Expand Down
22 changes: 11 additions & 11 deletions README.ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ Genin уже заранее скомпилирован под разные ар

Универсальный исполняемый файл:
```shell
curl -sLO https://binary.picodata.io/repository/raw/genin/bin/genin-0.4.11-x86_64-musl.tar.gz
tar -xvf genin-0.4.11-x86_64-musl.tar.gz ; sudo install genin /usr/local/bin/
curl -sLO https://binary.picodata.io/repository/raw/genin/bin/genin-0.4.12-x86_64-musl.tar.gz
tar -xvf genin-0.4.12-x86_64-musl.tar.gz ; sudo install genin /usr/local/bin/
```

---
Expand Down Expand Up @@ -88,11 +88,11 @@ sudo yum install -y genin
2. Так же вы можете установить пакет `rpm` напрямую без добавления нашего репозитория.
RHEL 8.x, CentOS 8.x, Rockylinux 8.x, recent Fedora version
```shell
sudo rpm -i https://binary.picodata.io/repository/yum/el/8/x86_64/os/genin-0.4.11-1.el8.x86_64.rpm
sudo rpm -i https://binary.picodata.io/repository/yum/el/8/x86_64/os/genin-0.4.12-1.el8.x86_64.rpm
```
RHEL 7.x, CentOS 7.x
```shell
sudo rpm -i https://binary.picodata.io/repository/yum/el/7/x86_64/os/genin-0.4.11-1.el7.x86_64.rpm
sudo rpm -i https://binary.picodata.io/repository/yum/el/7/x86_64/os/genin-0.4.12-1.el7.x86_64.rpm
```
> **Note:** будьте внимательны, так как при выборе не правильной версии ос могут быть ошибки
> при установке `rpm`
Expand All @@ -119,7 +119,7 @@ sudo apt install -y genin

2. Загрузкой и установкой пакета напрямую:
```shell
curl -sLO https://binary.picodata.io/repository/raw/genin/deb/genin-0.4.11.amd64.deb && sudo dpkg -i genin-0.4.11.amd64.deb
curl -sLO https://binary.picodata.io/repository/raw/genin/deb/genin-0.4.12.amd64.deb && sudo dpkg -i genin-0.4.12.amd64.deb
```

---
Expand All @@ -144,7 +144,7 @@ sudo apt install -y genin

2. Загрузкой и установкой пакета напрямую:
```shell
curl -sLO https://binary.picodata.io/repository/raw/genin/deb/genin-0.4.11.amd64.deb && sudo dpkg -i genin-0.4.11.amd64.deb
curl -sLO https://binary.picodata.io/repository/raw/genin/deb/genin-0.4.12.amd64.deb && sudo dpkg -i genin-0.4.12.amd64.deb
```

---
Expand All @@ -164,8 +164,8 @@ brew install genin
Для установки без помощи homebrew используйте следующие команды для загрузки и установки
Genin на macOS (10.10+):
```shell
curl -sLO https://binary.picodata.io/repository/raw/genin/osx/genin-0.4.11-x86_64-macosx.tar.gz
unzip genin-0.4.11-darwin-amd64.zip -d ~/bin/
curl -sLO https://binary.picodata.io/repository/raw/genin/osx/genin-0.4.12-x86_64-macosx.tar.gz
unzip genin-0.4.12-darwin-amd64.zip -d ~/bin/
```

---
Expand All @@ -189,8 +189,8 @@ brew install [email protected]
Используйте следующие команды для скачивания и установки Genin на операционных системах
Windows 7 64 и новее.
```shell
curl.exe -sLO https://binary.picodata.io/repository/raw/genin/win/genin-0.4.11-win64.zip
unzip.exe genin-0.4.11-win64.zip -d %HOME%/.cargo/bin/
curl.exe -sLO https://binary.picodata.io/repository/raw/genin/win/genin-0.4.12-win64.zip
unzip.exe genin-0.4.12-win64.zip -d %HOME%/.cargo/bin/
```
> **Note:** Genin будет распакован в директорию `.cargo/bin` которая находится в домашнем
> каталоге важего пользователя. Перед использованием приложения пожалуйста удостоверьтесь
Expand All @@ -200,7 +200,7 @@ unzip.exe genin-0.4.11-win64.zip -d %HOME%/.cargo/bin/
```
genin --version
```
Если вы видите сообщение `genin 0.4.11` значит установка прошла успешно.
Если вы видите сообщение `genin 0.4.12` значит установка прошла успешно.

---
## Руководство по использованию
Expand Down
6 changes: 4 additions & 2 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::{error::Error, fmt::Display};
use std::fmt::Display;
use std::error::Error as StdError;

#[derive(Debug, PartialEq, Eq)]
pub enum GeninErrorKind {
Expand All @@ -24,7 +25,7 @@ impl Display for GeninError {
}
}

impl Error for GeninError {}
impl StdError for GeninError {}

impl GeninError {
pub fn new<T: Display>(err_kind: GeninErrorKind, err: T) -> Self {
Expand All @@ -34,3 +35,4 @@ impl GeninError {
}
}
}

145 changes: 145 additions & 0 deletions src/task.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@ mod args;
pub mod cluster;
mod flv;
pub mod inventory;
pub mod serde_genin;
pub mod vars;

use log::info;
use serde_yaml::{Mapping, Value};
use std::convert::TryFrom;
use std::error::Error;
use std::fmt;
use std::fs::File;
use std::io::Read;

Expand All @@ -18,6 +21,12 @@ use crate::task::{
inventory::Inventory,
};

const BOOL: &str = "Bool";
const NUMBER: &str = "Number";
const STRING: &str = "String";
const LIST: &str = "List";
const DICT: &str = "Dict";

/// А function that launches an application and walks it through the state stages.
pub fn run_v2() -> Result<(), Box<dyn Error>> {
// At first set logging level
Expand Down Expand Up @@ -72,6 +81,7 @@ pub fn run_v2() -> Result<(), Box<dyn Error>> {
args.get_flag("force"),
)?
.deserialize_input::<Cluster>()?
//.map_err(|err|ClusterError::from(err))?
.print_input()
.try_map(|IO { input, output }| {
Inventory::try_from(&input).map(|inventory| IO {
Expand Down Expand Up @@ -155,3 +165,138 @@ pub fn run_v2() -> Result<(), Box<dyn Error>> {

Ok(())
}

pub trait Validate {
type Type: fmt::Debug + Default + 'static;
type Error: fmt::Debug;

fn validate(bytes: &[u8]) -> Result<Self::Type, Self::Error>;

fn whole_block(bytes: &[u8]) -> String;
}

trait AsError {
fn as_error(&self) -> String;
}

impl<T: std::fmt::Debug> AsError for T {
fn as_error(&self) -> String {
format!("\u{1b}[93m\u{1b}4{:?}\u{1b}[0m", self)
}
}

trait TypeError {
fn type_error(&self, expected: &str) -> String;
}

impl TypeError for Value {
fn type_error(&self, expected: &str) -> String {
match self {
Value::Null => format!("Expected type {} got Null", expected),
Value::Bool(_) => format!("Expected type {} got Bool", expected),
Value::Number(_) => format!("Expected type {} got Number", expected),
Value::String(_) => format!("Expected type {} got String", expected),
Value::Sequence(_) => format!("Expected type {} got List", expected),
Value::Mapping(_) => format!("Expected type {} got Dict", expected),
}
}
}

pub struct ErrSeqMapping<'a> {
pub offset: String,
pub value: &'a Vec<Value>,
}

impl<'a> std::fmt::Debug for ErrSeqMapping<'a> {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("\n")?;
self.value.iter().try_for_each(|value| match value {
Value::String(value) => {
formatter.write_fmt(format_args!("{}- {}", &self.offset, value))?;
formatter.write_str("\n")
}
Value::Mapping(value) => {
formatter.write_fmt(format_args!(
"{}- {:?}",
&self.offset,
ErrConfMapping {
offset: self.offset.clone(),
value,
}
))?;
formatter.write_str("\n")
}
_ => {
formatter.write_fmt(format_args!(
"{}- {}",
&self.offset,
value.type_error(DICT).as_error()
))?;
formatter.write_str("\n")
}
})?;

Ok(())
}
}

pub struct ErrConfMapping<'a> {
pub offset: String,
pub value: &'a Mapping,
}

impl<'a> std::fmt::Debug for ErrConfMapping<'a> {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.value
.iter()
.try_for_each(|(key, value)| match (key, value) {
(Value::String(key), Value::String(value)) => {
formatter.write_str("\n")?;
formatter.write_fmt(format_args!("{} {}: {}", &self.offset, key, value))
}
(Value::String(key), Value::Sequence(value)) => {
formatter.write_str("\n")?;
formatter.write_fmt(format_args!(
"{} {}: {:?}",
&self.offset,
key,
ErrSeqMapping {
offset: format!("{} ", &self.offset),
value
}
))
}
(Value::String(key), Value::Mapping(value)) => {
formatter.write_str("\n")?;
formatter.write_fmt(format_args!(
"{} {}: {:?}",
&self.offset,
key,
ErrConfMapping {
offset: format!("{} ", &self.offset),
value,
}
))
}
(Value::String(key), value) => {
formatter.write_str("\n")?;
formatter.write_fmt(format_args!(
"{} - {}: {}",
&self.offset,
key,
value.type_error(DICT).as_error()
))
}
_ => {
formatter.write_str("\n")?;
formatter.write_fmt(format_args!(
"{} - {}",
&self.offset,
"Errorneous field".as_error(),
))
}
})?;

Ok(())
}
}
6 changes: 2 additions & 4 deletions src/task/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,6 @@ pub(super) fn read() -> ArgMatches {
.help("(list, optional): cluster print output option"),
]),
Command::new("inspect")
.override_help("Generate and show cluster scheme whithout saving")
.about(
"Read cluster.genin.yaml configuration or inventory.yaml \
and display cluster schema. This command is needed \
Expand Down Expand Up @@ -147,11 +146,10 @@ pub(super) fn read() -> ArgMatches {
.help("Export resulting schema as csv."),
]),
Command::new("reverse")
.override_help("Reverse parsing inventory.yaml and save the configuration.")
.about(
"In some cases, you may need to get a cluster.genin.yaml \
based on an already prepared inventory. This subcommand \
is for that.",
based on an already prepared inventory. This subcommand \
is for that.",
)
.args(&[
Arg::new("source")
Expand Down
Loading

0 comments on commit 67ffb27

Please sign in to comment.