Adds massive amount of refactor

This commit is contained in:
beffroi 2023-05-20 19:18:39 +02:00
parent 95d7ec95ba
commit 700ea029fe
5 changed files with 106 additions and 14 deletions

17
TODO.md
View File

@ -16,8 +16,19 @@
[ ] Better modes
[ ] Test populate_actions
[ ] Coverage
[ ] Remake all methods
[ ]
### Currently working on
[ ] Make custom errors
[ ] Transform all panic in errors
[ ] Remake all helper functions
[ ] edit_snippet
[ ] edit_whole_snippet
[ ] locate_snippet
[ ] print_snippet
[ ] create_snippet
## Finished
[*] Make custom errors
[*] Transform all panic in errors

View File

@ -15,6 +15,8 @@ pub enum SnippetError {
IOError(std::io::Error),
/// Yaml error, generated during serialisation of snippets
YAMLError(serde_yaml::Error),
/// The file already exists and no creation flag was set
ExistsError(std::io::Error),
}
#[derive(Debug)]
@ -28,6 +30,10 @@ impl fmt::Display for SnippetError {
SnippetError::YAMLError(..) => {
write!(f, "Couldn't convert the given arguments into a yaml")
}
SnippetError::ExistsError(..) => write!(
f,
"The file already exists. Use -c or -f to create it or force overwrite."
),
}
}
}
@ -42,6 +48,7 @@ impl error::Error for SnippetError {
SnippetError::ClapError(ref e) => Some(e),
SnippetError::IOError(ref e) => Some(e),
SnippetError::YAMLError(ref e) => Some(e),
SnippetError::ExistsError(ref e) => Some(e),
}
}
}
@ -64,6 +71,12 @@ impl From<serde_yaml::Error> for SnippetError {
}
}
// impl From<serde_yaml::Error> for SnippetError {
// fn from(err: serde_yaml::Error) -> SnippetError {
// SnippetError::YAMLError(err)
// }
// }
// impl From<()> for SnippetError {
// fn from(_: ()) -> SnippetError {
// SnippetError::Unknown

View File

@ -16,7 +16,7 @@ mod wrapper_functions;
pub struct Cli {
/// The snippet name (and therefore his path)
#[arg()]
snipplet: String,
snippet: String,
/// Wether to try to load or instead create a new one
#[arg(short, long, default_value_t = false)]

View File

@ -4,11 +4,18 @@
use clap::error::Result;
use serde::{Deserialize, Serialize};
use std::io::Write;
use std::{fs::File, io::Write};
use crate::errors::{self, SnippetError};
use crate::{
errors::{self, SnippetError},
wrapper_functions::config_folder,
Cli,
};
/// A snippet ready to be Serialized/Deserialized
///
/// No conditionnal behaviour is handle by this module,
/// all calls will force, override and delete by default
#[derive(Deserialize, Serialize, Debug)]
pub struct Snippet {
/// Akin to path, the name of the snippet is where to store it
@ -32,7 +39,35 @@ impl Snippet {
}
/// Save the snippet at the default location under it's name
pub fn save(&self, mut file: std::fs::File) -> Result<(), errors::SnippetError> {
pub fn save(&self, options: &Cli) -> Result<(), errors::SnippetError> {
let mut file = self.open(&self.name, options)?;
write!(file, "{}", serde_yaml::to_string(self)?)?;
Ok(())
}
/// Open the file, will create on empty
pub fn open(&self, name: &str, options: &Cli) -> Result<File, SnippetError> {
// Find the config folder
let mut path = config_folder()?; //.expect("Coudn't open config forder");
// Add path
path.push(format!("{}.yaml", options.snippet));
// Open the file
let f = match std::fs::File::open(&path) {
Ok(f) => f,
Err(e) => {
if options.create {
File::create(path)?
} else {
return Err(SnippetError::IOError(e));
}
}
}; //.expect("Could not open snippet file.");
let snp: Snippet = serde_yaml::from_reader(&f)?; //.expect("Couldn't parse values");
Ok(f)
}
/// Save the snippet under a path, errors on existing file
pub fn save_as(&self, mut file: std::fs::File) -> Result<(), SnippetError> {
write!(file, "{}", serde_yaml::to_string(self)?)?;
Ok(())
}
@ -54,4 +89,13 @@ impl Snippet {
pub fn delete(&self) -> Result<(), SnippetError> {
Ok(())
}
pub fn from_str(taw_content: &str) -> Result<Self, SnippetError> {
// Parse the string
// Try to create
// Return the snippet
todo!();
}
}

View File

@ -6,10 +6,12 @@
use std::{
env,
fs::{create_dir_all, File},
io,
io::{self, Read},
path::{Path, PathBuf},
};
use edit::edit;
use crate::dynamic_formatter;
use crate::{dynamic_formatter::complete_vec, errors::SnippetError, snippet::Snippet, Cli};
@ -17,6 +19,18 @@ use crate::{dynamic_formatter::complete_vec, errors::SnippetError, snippet::Snip
/// Note that the snippet can be saved with another name and might trigger
/// a creation or an override
pub fn edit_whole_snippet(cli: &Cli) -> Result<(), SnippetError> {
// Find location
let path = snippet_path(&cli.snippet)?;
// Edit the whole file as str
let mut f = std::fs::File::open(&path)?; //.expect("Could not open snippet file.");
let mut raw_snippet = String::from("");
f.read_to_string(&mut raw_snippet)?;
let edited_str = edit(raw_snippet)?;
// Parse the result
let snp = Snippet::from_str(&edited_str)?;
// If no error save with snp.save()
snp.save(cli);
Ok(())
}
@ -34,7 +48,7 @@ fn print_path(path: &Path) {
pub fn print_snippet(args: &Cli) -> Result<(), SnippetError> {
// Try to load the snippet <name>
let mut path = config_folder()?; //.expect("Coudn't open config forder");
path.push(format!("{}.yaml", args.snipplet));
path.push(format!("{}.yaml", args.snippet));
let f = std::fs::File::open(&path)?; //.expect("Could not open snippet file.");
let snp: Snippet = serde_yaml::from_reader(f)?; //.expect("Couldn't parse values");
@ -68,8 +82,11 @@ pub fn print_snippet(args: &Cli) -> Result<(), SnippetError> {
/// Open and load snippet and edit it
/// If chained with create, the file will be created, closed and opened again
pub fn edit_snippet(cli: &Cli) -> Result<(), SnippetError> {
// Load snippet
// Try loading, if not existant check if create or error
// let file = File::open(snippet_path(&cli.snippet)?)?;
// Edit content
// let content =
// Write snippet
Ok(())
}
@ -80,7 +97,7 @@ fn edit_snippet_content(snp: &Snippet) -> Result<(), SnippetError> {
let snp = Snippet::new(snp.name.clone(), snp.default_values.clone(), test);
// TODO: Write snippet . Destroy original ? Return new ?
let file = open_path(&snp)?;
snp.save(file)?;
snp.save_as(file)?;
// .unwrap_or_else(|e| println!("Coudln't save to file {:?} {}", path, e));
Ok(())
}
@ -98,7 +115,7 @@ pub fn create_snippet(args: &Cli) -> Result<(), SnippetError> {
};
// Create a snippet with the given data
let snp = Snippet::new(args.snipplet.clone(), args.args.clone(), string);
let snp = Snippet::new(args.snippet.clone(), args.args.clone(), string);
let file = open_path(&snp)?;
// TODO: LOCATE
// if args.locate {
@ -106,7 +123,7 @@ pub fn create_snippet(args: &Cli) -> Result<(), SnippetError> {
// }
// Write the snippet
snp.save(file)?;
snp.save_as(file)?;
// .unwrap_or_else(|_| panic!("Couldn't write yaml to file {:?}", save_path));
Ok(())
}
@ -130,7 +147,7 @@ fn open_path(snp: &Snippet) -> Result<File, SnippetError> {
}
/// Find a configuration folder/name for the given snippet name
fn config_folder() -> Result<PathBuf, SnippetError> {
pub fn config_folder() -> Result<PathBuf, SnippetError> {
let exe = env::current_exe()?;
let dir = exe.parent().expect("Executable must be in some directory");
let mut dir = dir.join(".config");
@ -138,3 +155,10 @@ fn config_folder() -> Result<PathBuf, SnippetError> {
// dir.push(format!("{}.yaml", name));
Ok(dir)
}
/// Find the path of the given snippet
fn snippet_path(snp: &str) -> Result<PathBuf, SnippetError> {
let mut dir = config_folder()?;
dir.push(format!("{}.yaml", snp));
Ok(dir)
}